text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as U from './util' import { sequenceT } from '../src/Apply' import * as RA from '../src/ReadonlyArray' import * as E from '../src/Either' import { identity, pipe, SK } from '../src/function' import * as I from '../src/IO' import * as IE from '../src/IOEither' import { monoidString } from '../src/Monoid' import { none, some } from '../src/Option' import { pipeable } from '../src/pipeable' import * as N from '../src/number' import * as T from '../src/Task' import * as TO from '../src/TaskOption' import * as _ from '../src/TaskEither' import * as S from '../src/string' import { left, right } from '../src/Separated' import { ReadonlyNonEmptyArray } from '../src/ReadonlyNonEmptyArray' describe('TaskEither', () => { // ------------------------------------------------------------------------------------- // pipeables // ------------------------------------------------------------------------------------- it('alt', async () => { U.deepStrictEqual( await pipe( _.left('a'), _.alt(() => _.right(1)) )(), E.right(1) ) }) it('map', async () => { U.deepStrictEqual(await pipe(_.right(1), _.map(U.double))(), E.right(2)) }) it('ap', async () => { U.deepStrictEqual(await pipe(_.right(U.double), _.ap(_.right(1)))(), E.right(2)) }) it('apFirst', async () => { U.deepStrictEqual(await pipe(_.right('a'), _.apFirst(_.right('b')))(), E.right('a')) }) it('apSecond', async () => { U.deepStrictEqual(await pipe(_.right('a'), _.apSecond(_.right('b')))(), E.right('b')) }) it('chain', async () => { U.deepStrictEqual( await pipe( _.right('foo'), _.chain((a) => (a.length > 2 ? _.right(a.length) : _.left('foo'))) )(), E.right(3) ) U.deepStrictEqual( await pipe( _.right('a'), _.chain((a) => (a.length > 2 ? _.right(a.length) : _.left('foo'))) )(), E.left('foo') ) }) it('chainFirst', async () => { U.deepStrictEqual( await pipe( _.right('foo'), _.chainFirst((a) => (a.length > 2 ? _.right(a.length) : _.left('foo'))) )(), E.right('foo') ) }) it('chainFirstW', async () => { U.deepStrictEqual( await pipe( _.right<number, string>('foo'), _.chainFirstW((a) => (a.length > 2 ? _.right(a.length) : _.left('foo'))) )(), E.right('foo') ) }) it('flatten', async () => { U.deepStrictEqual(await pipe(_.right(_.right('a')), _.flatten)(), E.right('a')) }) it('flattenW', async () => { U.deepStrictEqual( await pipe(_.right<'left1', _.TaskEither<'left2', 'a'>>(_.right('a')), _.flattenW)(), E.right('a') ) }) it('bimap', async () => { const f = (s: string): number => s.length const g = (n: number): boolean => n > 2 U.deepStrictEqual(await pipe(_.right(1), _.bimap(f, g))(), E.right(false)) U.deepStrictEqual(await pipe(_.left('foo'), _.bimap(f, g))(), E.left(3)) }) it('mapLeft', async () => { U.deepStrictEqual(await pipe(_.left(1), _.mapLeft(U.double))(), E.left(2)) }) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- it('getApplicativeTaskValidation', async () => { const A = _.getApplicativeTaskValidation(T.ApplicativePar, S.Semigroup) U.deepStrictEqual(await sequenceT(A)(_.left('a'), _.left('b'))(), E.left('ab')) // tslint:disable-next-line: deprecation const AV = _.getTaskValidation(S.Semigroup) U.deepStrictEqual(await sequenceT(AV)(_.left('a'), _.left('b'))(), E.left('ab')) }) it('getAltTaskValidation', async () => { const A = _.getAltTaskValidation(S.Semigroup) U.deepStrictEqual(await A.alt(_.left('a'), () => _.left('b'))(), E.left('ab')) // tslint:disable-next-line: deprecation const AV = _.getTaskValidation(S.Semigroup) U.deepStrictEqual(await AV.alt(_.left('a'), () => _.left('b'))(), E.left('ab')) }) describe('getTaskValidation', () => { // tslint:disable-next-line: deprecation const TV = _.getTaskValidation(S.Semigroup) it('ap', async () => { const fab = _.left('a') const fa = _.left('b') U.deepStrictEqual(await TV.ap(fab, fa)(), E.left('ab')) }) it('alt', async () => { U.deepStrictEqual(await TV.alt(_.right(1), () => _.right(2))(), E.right(1)) U.deepStrictEqual(await TV.alt(_.left('a'), () => _.right(2))(), E.right(2)) U.deepStrictEqual(await TV.alt(_.right(1), () => _.left('b'))(), E.right(1)) U.deepStrictEqual(await TV.alt(_.left('a'), () => _.left('b'))(), E.left('ab')) }) }) describe('getCompactable', () => { const C = _.getCompactable(S.Monoid) it('compact', async () => { U.deepStrictEqual(await C.compact(_.right(some(1)))(), E.right(1)) }) it('separate', async () => { const s1 = C.separate(_.left('a')) U.deepStrictEqual(await left(s1)(), E.left('a')) U.deepStrictEqual(await right(s1)(), E.left('a')) const s2 = C.separate(_.right(E.left('a'))) U.deepStrictEqual(await left(s2)(), E.right('a')) U.deepStrictEqual(await right(s2)(), E.left('')) const s3 = C.separate(_.right(E.right(1))) U.deepStrictEqual(await left(s3)(), E.left('')) U.deepStrictEqual(await right(s3)(), E.right(1)) }) }) describe('getFilterable', () => { const F_ = _.getFilterable(RA.getMonoid<string>()) // tslint:disable-next-line: deprecation const { filter, filterMap, partition, partitionMap } = pipeable(F_) it('filter', async () => { U.deepStrictEqual( await pipe( _.right(1), filter((n) => n > 0) )(), await _.right(1)() ) U.deepStrictEqual( await pipe( _.right(-1), filter((n) => n > 0) )(), await _.left([])() ) U.deepStrictEqual( await pipe( _.left(['a']), filter((n) => n > 0) )(), await _.left(['a'])() ) }) it('filterMap', async () => { U.deepStrictEqual( await pipe( _.right('aaa'), filterMap((s) => (s.length > 1 ? some(s.length) : none)) )(), E.right(3) ) U.deepStrictEqual( await pipe( _.right('a'), filterMap((s) => (s.length > 1 ? some(s.length) : none)) )(), E.left([]) ) U.deepStrictEqual( await pipe( _.left<ReadonlyArray<string>, string>(['e']), filterMap((s) => (s.length > 1 ? some(s.length) : none)) )(), E.left(['e']) ) }) it('partition', async () => { const s = pipe( _.right('a'), partition((s) => s.length > 2) ) U.deepStrictEqual(await left(s)(), E.right('a')) U.deepStrictEqual(await right(s)(), E.left([])) }) it('partitionMap', async () => { const s = pipe( _.right('a'), partitionMap((s) => (s.length > 2 ? E.right(s.length) : E.left(false))) ) U.deepStrictEqual(await left(s)(), E.right(false)) U.deepStrictEqual(await right(s)(), E.left([])) }) }) describe('getSemigroup', () => { it('concat', async () => { // tslint:disable-next-line: deprecation const S = _.getSemigroup<string, number>(N.SemigroupSum) U.deepStrictEqual(await S.concat(_.left('a'), _.left('b'))(), E.left('a')) U.deepStrictEqual(await S.concat(_.left('a'), _.right(2))(), E.right(2)) U.deepStrictEqual(await S.concat(_.right(1), _.left('b'))(), E.right(1)) U.deepStrictEqual(await S.concat(_.right(1), _.right(2))(), E.right(3)) }) }) describe('getApplyMonoid', () => { // tslint:disable-next-line: deprecation const M = _.getApplyMonoid(monoidString) it('concat (right)', async () => { return U.deepStrictEqual(await M.concat(_.right('a'), _.right('b'))(), E.right('ab')) }) it('concat (left)', async () => { return U.deepStrictEqual(await M.concat(_.right('a'), _.left('b'))(), E.left('b')) }) it('empty (right)', async () => { return U.deepStrictEqual(await M.concat(_.right('a'), M.empty)(), E.right('a')) }) it('empty (left)', async () => { return U.deepStrictEqual(await M.concat(M.empty, _.right('a'))(), E.right('a')) }) }) it('applicativeTaskEitherSeq', async () => { await U.assertSeq(_.ApplicativeSeq, _.FromTask, (fa) => fa()) }) it('applicativeTaskEitherPar', async () => { await U.assertPar(_.ApplicativePar, _.FromTask, (fa) => fa()) }) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- it('taskify', async () => { const api1 = (_path: string, callback: (err: Error | null | undefined, result?: string) => void): void => { callback(null, 'ok') } const api2 = (_path: string, callback: (err: Error | null | undefined, result?: string) => void): void => { callback(undefined, 'ok') } const api3 = (_path: string, callback: (err: Error | null | undefined, result?: string) => void): void => { callback(new Error('ko')) } U.deepStrictEqual(await _.taskify(api1)('foo')(), E.right('ok')) U.deepStrictEqual(await _.taskify(api2)('foo')(), E.right('ok')) U.deepStrictEqual(await _.taskify(api3)('foo')(), E.left(new Error('ko'))) }) it('composed taskify', async () => { const api = (callback: (err: Error | null | undefined, result?: string) => void): void => { callback(null, 'ok') } const taskApi = _.taskify(api)() U.deepStrictEqual(await taskApi(), E.right('ok')) U.deepStrictEqual(await taskApi(), E.right('ok')) }) describe('bracket', () => { // tslint:disable-next-line: readonly-array let log: Array<string> = [] const acquireFailure = _.left('acquire failure') const acquireSuccess = _.right({ res: 'acquire success' }) const useSuccess = () => _.right('use success') const useFailure = () => _.left('use failure') const releaseSuccess = () => _.rightIO(() => { log.push('release success') }) const releaseFailure = () => _.left('release failure') beforeEach(() => { log = [] }) it('should return the acquire error if acquire fails', async () => { U.deepStrictEqual(await _.bracket(acquireFailure, useSuccess, releaseSuccess)(), E.left('acquire failure')) }) it('body and release must not be called if acquire fails', async () => { await _.bracket(acquireFailure, useSuccess, releaseSuccess)() U.deepStrictEqual(log, []) }) it('should return the use error if use fails and release does not', async () => { U.deepStrictEqual(await _.bracket(acquireSuccess, useFailure, releaseSuccess)(), E.left('use failure')) }) it('should return the release error if both use and release fail', async () => { U.deepStrictEqual(await _.bracket(acquireSuccess, useFailure, releaseFailure)(), E.left('release failure')) }) it('release must be called if the body returns', async () => { await _.bracket(acquireSuccess, useSuccess, releaseSuccess)() U.deepStrictEqual(log, ['release success']) }) it('release must be called if the body throws', async () => { await _.bracket(acquireSuccess, useFailure, releaseSuccess)() U.deepStrictEqual(log, ['release success']) }) it('should return the release error if release fails', async () => { U.deepStrictEqual(await _.bracket(acquireSuccess, useSuccess, releaseFailure)(), E.left('release failure')) }) }) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- it('filterOrElse', async () => { U.deepStrictEqual( await pipe( _.right(12), _.filterOrElse( (n) => n > 10, () => 'a' ) )(), E.right(12) ) U.deepStrictEqual( await pipe( _.right(7), _.filterOrElse( (n) => n > 10, () => 'a' ) )(), E.left('a') ) }) it('orElse', async () => { U.deepStrictEqual( await pipe( _.left('foo'), _.orElse((l) => _.right(l.length)) )(), E.right(3) ) U.deepStrictEqual( await pipe( _.right(1), _.orElse(() => _.right(2)) )(), E.right(1) ) }) it('orElseW', async () => { U.deepStrictEqual( await pipe( _.left('foo'), _.orElseW((l) => _.right(l.length)) )(), E.right(3) ) U.deepStrictEqual( await pipe( _.right(1), _.orElseW(() => _.right(2)) )(), E.right(1) ) }) it('orElseFirst', async () => { const f = _.orElseFirst((e: string) => (e.length <= 1 ? _.right(true) : _.left(e + '!'))) U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)(), E.left('a')) U.deepStrictEqual(await pipe(_.left('aa'), f)(), E.left('aa!')) }) it('orElseFirstW', async () => { const f = _.orElseFirstW((e: string) => (e.length <= 1 ? _.right(true) : _.left(e + '!'))) U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)(), E.left('a')) U.deepStrictEqual(await pipe(_.left('aa'), f)(), E.left('aa!')) }) it('orLeft', async () => { const f = _.orLeft((e: string) => T.of(e + '!')) U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(1)) U.deepStrictEqual(await pipe(_.left('a'), f)(), E.left('a!')) }) it('swap', async () => { U.deepStrictEqual(await _.swap(_.right(1))(), E.left(1)) U.deepStrictEqual(await _.swap(_.left('a'))(), E.right('a')) }) it('chainEitherK', async () => { const f = (s: string) => E.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainEitherK(f))(), E.right(1)) }) it('chainIOEitherK', async () => { const f = (s: string) => IE.right(s.length) U.deepStrictEqual(await pipe(_.right('a'), _.chainIOEitherK(f))(), E.right(1)) }) it('tryCatchK', async () => { const f = (n: number) => { if (n > 0) { return Promise.resolve(n * 2) } return Promise.reject('negative') } const g = _.tryCatchK(f, identity) U.deepStrictEqual(await g(1)(), E.right(2)) U.deepStrictEqual(await g(-1)(), E.left('negative')) }) // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- it('rightIO', async () => { const io = () => 1 const fa = _.rightIO(io) U.deepStrictEqual(await fa(), E.right(1)) }) it('leftIO', async () => { U.deepStrictEqual(await _.leftIO(I.of(1))(), E.left(1)) }) it('tryCatch', async () => { U.deepStrictEqual( await _.tryCatch( () => Promise.resolve(1), () => 'error' )(), E.right(1) ) U.deepStrictEqual( await _.tryCatch( () => Promise.reject(undefined), () => 'error' )(), E.left('error') ) }) it('fromIOEither', async () => { U.deepStrictEqual(await _.fromIOEither(() => E.right(1))(), E.right(1)) U.deepStrictEqual(await _.fromIOEither(() => E.left('foo'))(), E.left('foo')) }) it('fromOption', async () => { U.deepStrictEqual( await pipe( none, _.fromOption(() => 'none') )(), E.left('none') ) U.deepStrictEqual( await pipe( some(1), _.fromOption(() => 'none') )(), E.right(1) ) }) it('fromTaskOption', async () => { U.deepStrictEqual( await pipe( TO.none, _.fromTaskOption(() => 'none') )(), E.left('none') ) U.deepStrictEqual( await pipe( TO.some(1), _.fromTaskOption(() => 'none') )(), E.right(1) ) }) it('fromPredicate', async () => { const gt2 = _.fromPredicate( (n: number) => n >= 2, (n) => `Invalid number ${n}` ) U.deepStrictEqual(await gt2(3)(), E.right(3)) U.deepStrictEqual(await gt2(1)(), E.left('Invalid number 1')) // refinements const isNumber = (u: string | number): u is number => typeof u === 'number' U.deepStrictEqual(await _.fromPredicate(isNumber, () => 'not a number')(4)(), E.right(4)) }) it('do notation', async () => { U.deepStrictEqual( await pipe( _.right<string, number>(1), _.bindTo('a'), _.bind('b', () => _.right('b')) )(), E.right({ a: 1, b: 'b' }) ) }) it('apS', async () => { U.deepStrictEqual( await pipe(_.right<string, number>(1), _.bindTo('a'), _.apS('b', _.right('b')))(), E.right({ a: 1, b: 'b' }) ) }) describe('array utils', () => { const input: ReadonlyNonEmptyArray<string> = ['a', 'b'] it('traverseReadonlyArrayWithIndex', async () => { const f = _.traverseReadonlyArrayWithIndex((i, a: string) => (a.length > 0 ? _.right(a + i) : _.left('e'))) U.deepStrictEqual(await pipe(RA.empty, f)(), E.right(RA.empty)) U.deepStrictEqual(await pipe(input, f)(), E.right(['a0', 'b1'])) U.deepStrictEqual(await pipe(['a', ''], f)(), E.left('e')) }) it('traverseReadonlyArrayWithIndexSeq', async () => { const f = _.traverseReadonlyArrayWithIndexSeq((i, a: string) => (a.length > 0 ? _.right(a + i) : _.left('e'))) U.deepStrictEqual(await pipe(RA.empty, f)(), E.right(RA.empty)) U.deepStrictEqual(await pipe(input, f)(), E.right(['a0', 'b1'])) U.deepStrictEqual(await pipe(['a', ''], f)(), E.left('e')) }) it('sequenceReadonlyArray', async () => { const log: Array<number | string> = [] const right = (n: number): _.TaskEither<string, number> => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.TaskEither<string, number> => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(await pipe([right(1), right(2)], _.traverseReadonlyArrayWithIndex(SK))(), E.right([1, 2])) U.deepStrictEqual(await pipe([right(3), left('a')], _.traverseReadonlyArrayWithIndex(SK))(), E.left('a')) U.deepStrictEqual(await pipe([left('b'), right(4)], _.traverseReadonlyArrayWithIndex(SK))(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) it('sequenceReadonlyArraySeq', async () => { const log: Array<number | string> = [] const right = (n: number): _.TaskEither<string, number> => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.TaskEither<string, number> => _.leftIO(() => { log.push(s) return s }) U.deepStrictEqual(await pipe([right(1), right(2)], _.traverseReadonlyArrayWithIndexSeq(SK))(), E.right([1, 2])) U.deepStrictEqual(await pipe([right(3), left('a')], _.traverseReadonlyArrayWithIndexSeq(SK))(), E.left('a')) U.deepStrictEqual(await pipe([left('b'), right(4)], _.traverseReadonlyArrayWithIndexSeq(SK))(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) // old it('sequenceArray', async () => { // tslint:disable-next-line: readonly-array const log: Array<number | string> = [] const right = (n: number): _.TaskEither<string, number> => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.TaskEither<string, number> => _.leftIO(() => { log.push(s) return s }) // tslint:disable-next-line: deprecation U.deepStrictEqual(await pipe([right(1), right(2)], _.sequenceArray)(), E.right([1, 2])) // tslint:disable-next-line: deprecation U.deepStrictEqual(await pipe([right(3), left('a')], _.sequenceArray)(), E.left('a')) // tslint:disable-next-line: deprecation U.deepStrictEqual(await pipe([left('b'), right(4)], _.sequenceArray)(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b', 4]) }) it('sequenceSeqArray', async () => { // tslint:disable-next-line: readonly-array const log: Array<number | string> = [] const right = (n: number): _.TaskEither<string, number> => _.rightIO(() => { log.push(n) return n }) const left = (s: string): _.TaskEither<string, number> => _.leftIO(() => { log.push(s) return s }) // tslint:disable-next-line: deprecation U.deepStrictEqual(await pipe([right(1), right(2)], _.sequenceSeqArray)(), E.right([1, 2])) // tslint:disable-next-line: deprecation U.deepStrictEqual(await pipe([right(3), left('a')], _.sequenceSeqArray)(), E.left('a')) // tslint:disable-next-line: deprecation U.deepStrictEqual(await pipe([left('b'), right(4)], _.sequenceSeqArray)(), E.left('b')) U.deepStrictEqual(log, [1, 2, 3, 'a', 'b']) }) }) it('match', async () => { const f = _.match( () => 'left', () => 'right' ) U.deepStrictEqual(await f(_.right(1))(), 'right') U.deepStrictEqual(await f(_.left(''))(), 'left') }) it('matchE', async () => { const f = _.matchE( () => T.of('left'), () => T.of('right') ) U.deepStrictEqual(await f(_.right(1))(), 'right') U.deepStrictEqual(await f(_.left(''))(), 'left') }) it('chainTaskOptionK', async () => { const f = _.chainTaskOptionK(() => 'a')((n: number) => (n > 0 ? TO.some(n * 2) : TO.none)) U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(2)) U.deepStrictEqual(await pipe(_.right(-1), f)(), E.left('a')) U.deepStrictEqual(await pipe(_.left('b'), f)(), E.left('b')) }) })
the_stack
import { java } from 'j4ts/j4ts'; /** * Constructor. * @param {java.io.InputStream} dstream * @param {string} encoding * @param {number} startline * @param {number} startcolumn * @param {number} buffersize * @class */ export class SimpleCharStream { /** * Whether parser is static. */ public static staticFlag: boolean = false; bufsize: number; available: number; tokenBegin: number; /** * Position in buffer. */ public bufpos: number; bufline: number[]; bufcolumn: number[]; column: number; line: number; prevCharIsCR: boolean; prevCharIsLF: boolean; inputStream: java.io.Reader; buffer: string[]; maxNextCharInd: number; inBuf: number; tabSize: number; trackLineColumn: boolean; public setTabSize(i: number) { this.tabSize = i; } public getTabSize(): number { return this.tabSize; } ExpandBuff(wrapAround: boolean) { const newbuffer: string[] = (s => { let a=[]; while(s-->0) a.push(null); return a; })(this.bufsize + 2048); const newbufline: number[] = (s => { let a=[]; while(s-->0) a.push(0); return a; })(this.bufsize + 2048); const newbufcolumn: number[] = (s => { let a=[]; while(s-->0) a.push(0); return a; })(this.bufsize + 2048); try { if (wrapAround){ java.lang.System.arraycopy(this.buffer, this.tokenBegin, newbuffer, 0, this.bufsize - this.tokenBegin); java.lang.System.arraycopy(this.buffer, 0, newbuffer, this.bufsize - this.tokenBegin, this.bufpos); this.buffer = newbuffer; java.lang.System.arraycopy(this.bufline, this.tokenBegin, newbufline, 0, this.bufsize - this.tokenBegin); java.lang.System.arraycopy(this.bufline, 0, newbufline, this.bufsize - this.tokenBegin, this.bufpos); this.bufline = newbufline; java.lang.System.arraycopy(this.bufcolumn, this.tokenBegin, newbufcolumn, 0, this.bufsize - this.tokenBegin); java.lang.System.arraycopy(this.bufcolumn, 0, newbufcolumn, this.bufsize - this.tokenBegin, this.bufpos); this.bufcolumn = newbufcolumn; this.maxNextCharInd = (this.bufpos += (this.bufsize - this.tokenBegin)); } else { java.lang.System.arraycopy(this.buffer, this.tokenBegin, newbuffer, 0, this.bufsize - this.tokenBegin); this.buffer = newbuffer; java.lang.System.arraycopy(this.bufline, this.tokenBegin, newbufline, 0, this.bufsize - this.tokenBegin); this.bufline = newbufline; java.lang.System.arraycopy(this.bufcolumn, this.tokenBegin, newbufcolumn, 0, this.bufsize - this.tokenBegin); this.bufcolumn = newbufcolumn; this.maxNextCharInd = (this.bufpos -= this.tokenBegin); } } catch(t) { throw new Error(t.message); } this.bufsize += 2048; this.available = this.bufsize; this.tokenBegin = 0; } FillBuff() { if (this.maxNextCharInd === this.available){ if (this.available === this.bufsize){ if (this.tokenBegin > 2048){ this.bufpos = this.maxNextCharInd = 0; this.available = this.tokenBegin; } else if (this.tokenBegin < 0)this.bufpos = this.maxNextCharInd = 0; else this.ExpandBuff(false); } else if (this.available > this.tokenBegin)this.available = this.bufsize; else if ((this.tokenBegin - this.available) < 2048)this.ExpandBuff(true); else this.available = this.tokenBegin; } let i: number; try { if ((i = this.inputStream.read(this.buffer, this.maxNextCharInd, this.available - this.maxNextCharInd)) === -1){ this.inputStream.close(); throw new java.io.IOException(); } else this.maxNextCharInd += i; return; } catch(e) { --this.bufpos; this.backup(0); if (this.tokenBegin === -1)this.tokenBegin = this.bufpos; throw e; } } /** * Start. * @return {string} */ public BeginToken(): string { this.tokenBegin = -1; const c: string = this.readChar(); this.tokenBegin = this.bufpos; return c; } UpdateLineColumn(c: string) { this.column++; if (this.prevCharIsLF){ this.prevCharIsLF = false; this.line += (this.column = 1); } else if (this.prevCharIsCR){ this.prevCharIsCR = false; if ((c => c.charCodeAt==null?<any>c:c.charCodeAt(0))(c) == '\n'.charCodeAt(0)){ this.prevCharIsLF = true; } else this.line += (this.column = 1); } switch((c).charCodeAt(0)) { case 13 /* '\r' */: this.prevCharIsCR = true; break; case 10 /* '\n' */: this.prevCharIsLF = true; break; case 9 /* '\t' */: this.column--; this.column += (this.tabSize - (this.column % this.tabSize)); break; default: break; } this.bufline[this.bufpos] = this.line; this.bufcolumn[this.bufpos] = this.column; } /** * Read a character. * @return {string} */ public readChar(): string { if (this.inBuf > 0){ --this.inBuf; if (++this.bufpos === this.bufsize)this.bufpos = 0; return this.buffer[this.bufpos]; } if (++this.bufpos >= this.maxNextCharInd)this.FillBuff(); const c: string = this.buffer[this.bufpos]; this.UpdateLineColumn(c); return c; } public getColumn(): number { return this.bufcolumn[this.bufpos]; } public getLine(): number { return this.bufline[this.bufpos]; } /** * Get token end column number. * @return {number} */ public getEndColumn(): number { return this.bufcolumn[this.bufpos]; } /** * Get token end line number. * @return {number} */ public getEndLine(): number { return this.bufline[this.bufpos]; } /** * Get token beginning column number. * @return {number} */ public getBeginColumn(): number { return this.bufcolumn[this.tokenBegin]; } /** * Get token beginning line number. * @return {number} */ public getBeginLine(): number { return this.bufline[this.tokenBegin]; } /** * Backup a number of characters. * @param {number} amount */ public backup(amount: number) { this.inBuf += amount; if ((this.bufpos -= amount) < 0)this.bufpos += this.bufsize; } public ReInit$java_io_Reader$int$int$int(dstream: java.io.Reader, startline: number, startcolumn: number, buffersize: number) { this.inputStream = dstream; this.line = startline; this.column = startcolumn - 1; if (this.buffer == null || buffersize !== this.buffer.length){ this.available = this.bufsize = buffersize; this.buffer = (s => { let a=[]; while(s-->0) a.push(null); return a; })(buffersize); this.bufline = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); this.bufcolumn = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); } this.prevCharIsLF = this.prevCharIsCR = false; this.tokenBegin = this.inBuf = this.maxNextCharInd = 0; this.bufpos = -1; } public ReInit$java_io_Reader$int$int(dstream: java.io.Reader, startline: number, startcolumn: number) { this.ReInit$java_io_Reader$int$int$int(dstream, startline, startcolumn, 4096); } public ReInit$java_io_Reader(dstream: java.io.Reader) { this.ReInit$java_io_Reader$int$int$int(dstream, 1, 1, 4096); } public constructor(dstream?: any, encoding?: any, startline?: any, startcolumn?: any, buffersize?: any) { if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && ((typeof encoding === 'string') || encoding === null) && ((typeof startline === 'number') || startline === null) && ((typeof startcolumn === 'number') || startcolumn === null) && ((typeof buffersize === 'number') || buffersize === null)) { let __args = arguments; { let __args = arguments; let dstream: any = encoding == null ? new java.io.InputStreamReader(__args[0]) : new java.io.InputStreamReader(__args[0], encoding); if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; this.inputStream = dstream; this.line = startline; this.column = startcolumn - 1; this.available = this.bufsize = buffersize; this.buffer = (s => { let a=[]; while(s-->0) a.push(null); return a; })(buffersize); this.bufline = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); this.bufcolumn = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } else if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && ((typeof encoding === 'string') || encoding === null) && ((typeof startline === 'number') || startline === null) && ((typeof startcolumn === 'number') || startcolumn === null) && buffersize === undefined) { let __args = arguments; { let __args = arguments; let buffersize: any = 4096; { let __args = arguments; let dstream: any = encoding == null ? new java.io.InputStreamReader(__args[0]) : new java.io.InputStreamReader(__args[0], encoding); if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; this.inputStream = dstream; this.line = startline; this.column = startcolumn - 1; this.available = this.bufsize = buffersize; this.buffer = (s => { let a=[]; while(s-->0) a.push(null); return a; })(buffersize); this.bufline = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); this.bufcolumn = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } else if (((dstream != null && dstream instanceof <any>java.io.Reader) || dstream === null) && ((typeof encoding === 'number') || encoding === null) && ((typeof startline === 'number') || startline === null) && ((typeof startcolumn === 'number') || startcolumn === null) && buffersize === undefined) { let __args = arguments; let startline: any = __args[1]; let startcolumn: any = __args[2]; let buffersize: any = __args[3]; if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; this.inputStream = dstream; this.line = startline; this.column = startcolumn - 1; this.available = this.bufsize = buffersize; this.buffer = (s => { let a=[]; while(s-->0) a.push(null); return a; })(buffersize); this.bufline = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); this.bufcolumn = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); } else if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && ((typeof encoding === 'number') || encoding === null) && ((typeof startline === 'number') || startline === null) && ((typeof startcolumn === 'number') || startcolumn === null) && buffersize === undefined) { let __args = arguments; let startline: any = __args[1]; let startcolumn: any = __args[2]; let buffersize: any = __args[3]; { let __args = arguments; let dstream: any = new java.io.InputStreamReader(__args[0]); if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; this.inputStream = dstream; this.line = startline; this.column = startcolumn - 1; this.available = this.bufsize = buffersize; this.buffer = (s => { let a=[]; while(s-->0) a.push(null); return a; })(buffersize); this.bufline = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); this.bufcolumn = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } else if (((dstream != null && dstream instanceof <any>java.io.Reader) || dstream === null) && ((typeof encoding === 'number') || encoding === null) && ((typeof startline === 'number') || startline === null) && startcolumn === undefined && buffersize === undefined) { let __args = arguments; let startline: any = __args[1]; let startcolumn: any = __args[2]; { let __args = arguments; let buffersize: any = 4096; if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; this.inputStream = dstream; this.line = startline; this.column = startcolumn - 1; this.available = this.bufsize = buffersize; this.buffer = (s => { let a=[]; while(s-->0) a.push(null); return a; })(buffersize); this.bufline = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); this.bufcolumn = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } else if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && ((typeof encoding === 'number') || encoding === null) && ((typeof startline === 'number') || startline === null) && startcolumn === undefined && buffersize === undefined) { let __args = arguments; let startline: any = __args[1]; let startcolumn: any = __args[2]; { let __args = arguments; let buffersize: any = 4096; { let __args = arguments; let dstream: any = new java.io.InputStreamReader(__args[0]); if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; this.inputStream = dstream; this.line = startline; this.column = startcolumn - 1; this.available = this.bufsize = buffersize; this.buffer = (s => { let a=[]; while(s-->0) a.push(null); return a; })(buffersize); this.bufline = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); this.bufcolumn = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } else if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && ((typeof encoding === 'string') || encoding === null) && startline === undefined && startcolumn === undefined && buffersize === undefined) { let __args = arguments; { let __args = arguments; let startline: any = 1; let startcolumn: any = 1; let buffersize: any = 4096; { let __args = arguments; let dstream: any = encoding == null ? new java.io.InputStreamReader(__args[0]) : new java.io.InputStreamReader(__args[0], encoding); if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; this.inputStream = dstream; this.line = startline; this.column = startcolumn - 1; this.available = this.bufsize = buffersize; this.buffer = (s => { let a=[]; while(s-->0) a.push(null); return a; })(buffersize); this.bufline = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); this.bufcolumn = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } else if (((dstream != null && dstream instanceof <any>java.io.Reader) || dstream === null) && encoding === undefined && startline === undefined && startcolumn === undefined && buffersize === undefined) { let __args = arguments; { let __args = arguments; let startline: any = 1; let startcolumn: any = 1; let buffersize: any = 4096; if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; this.inputStream = dstream; this.line = startline; this.column = startcolumn - 1; this.available = this.bufsize = buffersize; this.buffer = (s => { let a=[]; while(s-->0) a.push(null); return a; })(buffersize); this.bufline = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); this.bufcolumn = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } else if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && encoding === undefined && startline === undefined && startcolumn === undefined && buffersize === undefined) { let __args = arguments; { let __args = arguments; let startline: any = 1; let startcolumn: any = 1; let buffersize: any = 4096; { let __args = arguments; let dstream: any = new java.io.InputStreamReader(__args[0]); if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; this.inputStream = dstream; this.line = startline; this.column = startcolumn - 1; this.available = this.bufsize = buffersize; this.buffer = (s => { let a=[]; while(s-->0) a.push(null); return a; })(buffersize); this.bufline = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); this.bufcolumn = (s => { let a=[]; while(s-->0) a.push(0); return a; })(buffersize); } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } if (this.bufsize === undefined) { this.bufsize = 0; } if (this.available === undefined) { this.available = 0; } if (this.tokenBegin === undefined) { this.tokenBegin = 0; } if (this.bufline === undefined) { this.bufline = null; } if (this.bufcolumn === undefined) { this.bufcolumn = null; } if (this.inputStream === undefined) { this.inputStream = null; } if (this.buffer === undefined) { this.buffer = null; } this.bufpos = -1; this.column = 0; this.line = 1; this.prevCharIsCR = false; this.prevCharIsLF = false; this.maxNextCharInd = 0; this.inBuf = 0; this.tabSize = 8; this.trackLineColumn = true; } else throw new Error('invalid overload'); } public ReInit$java_io_InputStream$java_lang_String$int$int$int(dstream: java.io.InputStream, encoding: string, startline: number, startcolumn: number, buffersize: number) { this.ReInit$java_io_Reader$int$int$int(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** * Reinitialise. * @param {java.io.InputStream} dstream * @param {string} encoding * @param {number} startline * @param {number} startcolumn * @param {number} buffersize */ public ReInit(dstream?: any, encoding?: any, startline?: any, startcolumn?: any, buffersize?: any) { if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && ((typeof encoding === 'string') || encoding === null) && ((typeof startline === 'number') || startline === null) && ((typeof startcolumn === 'number') || startcolumn === null) && ((typeof buffersize === 'number') || buffersize === null)) { return <any>this.ReInit$java_io_InputStream$java_lang_String$int$int$int(dstream, encoding, startline, startcolumn, buffersize); } else if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && ((typeof encoding === 'string') || encoding === null) && ((typeof startline === 'number') || startline === null) && ((typeof startcolumn === 'number') || startcolumn === null) && buffersize === undefined) { return <any>this.ReInit$java_io_InputStream$java_lang_String$int$int(dstream, encoding, startline, startcolumn); } else if (((dstream != null && dstream instanceof <any>java.io.Reader) || dstream === null) && ((typeof encoding === 'number') || encoding === null) && ((typeof startline === 'number') || startline === null) && ((typeof startcolumn === 'number') || startcolumn === null) && buffersize === undefined) { return <any>this.ReInit$java_io_Reader$int$int$int(dstream, encoding, startline, startcolumn); } else if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && ((typeof encoding === 'number') || encoding === null) && ((typeof startline === 'number') || startline === null) && ((typeof startcolumn === 'number') || startcolumn === null) && buffersize === undefined) { return <any>this.ReInit$java_io_InputStream$int$int$int(dstream, encoding, startline, startcolumn); } else if (((dstream != null && dstream instanceof <any>java.io.Reader) || dstream === null) && ((typeof encoding === 'number') || encoding === null) && ((typeof startline === 'number') || startline === null) && startcolumn === undefined && buffersize === undefined) { return <any>this.ReInit$java_io_Reader$int$int(dstream, encoding, startline); } else if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && ((typeof encoding === 'number') || encoding === null) && ((typeof startline === 'number') || startline === null) && startcolumn === undefined && buffersize === undefined) { return <any>this.ReInit$java_io_InputStream$int$int(dstream, encoding, startline); } else if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && ((typeof encoding === 'string') || encoding === null) && startline === undefined && startcolumn === undefined && buffersize === undefined) { return <any>this.ReInit$java_io_InputStream$java_lang_String(dstream, encoding); } else if (((dstream != null && dstream instanceof <any>java.io.Reader) || dstream === null) && encoding === undefined && startline === undefined && startcolumn === undefined && buffersize === undefined) { return <any>this.ReInit$java_io_Reader(dstream); } else if (((dstream != null && dstream instanceof <any>java.io.InputStream) || dstream === null) && encoding === undefined && startline === undefined && startcolumn === undefined && buffersize === undefined) { return <any>this.ReInit$java_io_InputStream(dstream); } else throw new Error('invalid overload'); } public ReInit$java_io_InputStream$int$int$int(dstream: java.io.InputStream, startline: number, startcolumn: number, buffersize: number) { this.ReInit$java_io_Reader$int$int$int(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } public ReInit$java_io_InputStream$java_lang_String(dstream: java.io.InputStream, encoding: string) { this.ReInit$java_io_InputStream$java_lang_String$int$int$int(dstream, encoding, 1, 1, 4096); } public ReInit$java_io_InputStream(dstream: java.io.InputStream) { this.ReInit$java_io_InputStream$int$int$int(dstream, 1, 1, 4096); } public ReInit$java_io_InputStream$java_lang_String$int$int(dstream: java.io.InputStream, encoding: string, startline: number, startcolumn: number) { this.ReInit$java_io_InputStream$java_lang_String$int$int$int(dstream, encoding, startline, startcolumn, 4096); } public ReInit$java_io_InputStream$int$int(dstream: java.io.InputStream, startline: number, startcolumn: number) { this.ReInit$java_io_InputStream$int$int$int(dstream, startline, startcolumn, 4096); } /** * Get token literal value. * @return {string} */ public GetImage(): string { if (this.bufpos >= this.tokenBegin)return <string>((str, index, len) => str.substring(index, index + len))((this.buffer).join(''), this.tokenBegin, this.bufpos - this.tokenBegin + 1); else return <string>((str, index, len) => str.substring(index, index + len))((this.buffer).join(''), this.tokenBegin, this.bufsize - this.tokenBegin) + <string>((str, index, len) => str.substring(index, index + len))((this.buffer).join(''), 0, this.bufpos + 1); } /** * Get the suffix. * @param {number} len * @return {char[]} */ public GetSuffix(len: number): string[] { const ret: string[] = (s => { let a=[]; while(s-->0) a.push(null); return a; })(len); if ((this.bufpos + 1) >= len)java.lang.System.arraycopy(this.buffer, this.bufpos - len + 1, ret, 0, len); else { java.lang.System.arraycopy(this.buffer, this.bufsize - (len - this.bufpos - 1), ret, 0, len - this.bufpos - 1); java.lang.System.arraycopy(this.buffer, 0, ret, len - this.bufpos - 1, this.bufpos + 1); } return ret; } /** * Reset buffer when finished. */ public Done() { this.buffer = null; this.bufline = null; this.bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. * @param {number} newLine * @param {number} newCol */ public adjustBeginLineColumn(newLine: number, newCol: number) { let start: number = this.tokenBegin; let len: number; if (this.bufpos >= this.tokenBegin){ len = this.bufpos - this.tokenBegin + this.inBuf + 1; } else { len = this.bufsize - this.tokenBegin + this.bufpos + 1 + this.inBuf; } let i: number = 0; let j: number = 0; let k: number = 0; let nextColDiff: number = 0; let columnDiff: number = 0; while((i < len && this.bufline[j = start % this.bufsize] === this.bufline[k = ++start % this.bufsize])) {{ this.bufline[j] = newLine; nextColDiff = columnDiff + this.bufcolumn[k] - this.bufcolumn[j]; this.bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; }}; if (i < len){ this.bufline[j] = newLine++; this.bufcolumn[j] = newCol + columnDiff; while((i++ < len)) {{ if (this.bufline[j = start % this.bufsize] !== this.bufline[++start % this.bufsize])this.bufline[j] = newLine++; else this.bufline[j] = newLine; }}; } this.line = this.bufline[j]; this.column = this.bufcolumn[j]; } getTrackLineColumn(): boolean { return this.trackLineColumn; } setTrackLineColumn(tlc: boolean) { this.trackLineColumn = tlc; } } SimpleCharStream["__class"] = "org.mariuszgromada.math.mxparser.syntaxchecker.SimpleCharStream";
the_stack
import * as path from "path"; import * as fs from "fs-extra"; import { execSync } from "child_process"; import { expect as expectCdk, countResources, countResourcesLike, haveResource, notMatching, objectLike, stringLike, arrayWith, anything, ABSENT, } from "@aws-cdk/assert"; import * as cf from "@aws-cdk/aws-cloudfront"; import * as route53 from "@aws-cdk/aws-route53"; import * as acm from "@aws-cdk/aws-certificatemanager"; import { App, Api, Stack, NextjsSite } from "../src"; const sitePath = "test/nextjs-site"; const sitePathMinimalFeatures = "test/nextjs-site-minimal-features"; const buildOutputPath = path.join(".build", "nextjs-output"); beforeAll(async () => { // Instal Next.js app dependencies execSync("npm install", { cwd: sitePath, stdio: "inherit", }); execSync("npm install", { cwd: sitePathMinimalFeatures, stdio: "inherit", }); // Build Next.js app fs.removeSync(path.join(__dirname, "..", buildOutputPath)); const configBuffer = Buffer.from( JSON.stringify({ cwd: path.join(__dirname, "..", sitePath), args: ["build"], }) ); const cmd = [ "node", path.join(__dirname, "../assets/NextjsSite/build.js"), "--path", path.join(__dirname, "..", sitePath), "--output", path.join(__dirname, "..", buildOutputPath), "--config", configBuffer.toString("base64"), ].join(" "); execSync(cmd, { cwd: path.join(__dirname, "..", sitePath), stdio: "inherit", }); }); ///////////////////////////// // Test Constructor ///////////////////////////// test("constructor: no domain", async () => { const stack = new Stack(new App(), "stack"); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expect(site.url).toBeDefined(); expect(site.customDomainUrl).toBeUndefined(); expect(site.bucketArn).toBeDefined(); expect(site.bucketName).toBeDefined(); expect(site.distributionId).toBeDefined(); expect(site.distributionDomain).toBeDefined(); expect(site.acmCertificate).toBeUndefined(); expectCdk(stack).to(countResources("AWS::S3::Bucket", 1)); expectCdk(stack).to(countResources("AWS::Lambda::Function", 10)); expectCdk(stack).to(countResources("AWS::CloudFront::Distribution", 1)); expectCdk(stack).to( haveResource("AWS::CloudFront::Distribution", { DistributionConfig: { Aliases: [], CacheBehaviors: [ { AllowedMethods: [ "GET", "HEAD", "OPTIONS", "PUT", "PATCH", "POST", "DELETE", ], CachePolicyId: { Ref: "SiteImageCache3A336C80", }, CachedMethods: ["GET", "HEAD", "OPTIONS"], Compress: true, LambdaFunctionAssociations: [ { EventType: "origin-request", LambdaFunctionARN: anything(), }, ], OriginRequestPolicyId: { Ref: "SiteImageOriginRequestFA9A64F5", }, PathPattern: "_next/image*", TargetOriginId: "devmyappstackSiteDistributionOrigin1F25265FA", ViewerProtocolPolicy: "redirect-to-https", }, { AllowedMethods: ["GET", "HEAD", "OPTIONS"], CachePolicyId: { Ref: "SiteLambdaCacheD9743183", }, CachedMethods: ["GET", "HEAD", "OPTIONS"], Compress: true, LambdaFunctionAssociations: [ { EventType: "origin-request", IncludeBody: true, LambdaFunctionARN: anything(), }, { EventType: "origin-response", LambdaFunctionARN: anything(), }, ], PathPattern: "_next/data/*", TargetOriginId: "devmyappstackSiteDistributionOrigin1F25265FA", ViewerProtocolPolicy: "redirect-to-https", }, { AllowedMethods: ["GET", "HEAD", "OPTIONS"], CachePolicyId: { Ref: "SiteStaticsCache29AFAE7C", }, CachedMethods: ["GET", "HEAD", "OPTIONS"], Compress: true, PathPattern: "_next/*", TargetOriginId: "devmyappstackSiteDistributionOrigin1F25265FA", ViewerProtocolPolicy: "redirect-to-https", }, { AllowedMethods: ["GET", "HEAD", "OPTIONS"], CachePolicyId: { Ref: "SiteStaticsCache29AFAE7C", }, CachedMethods: ["GET", "HEAD", "OPTIONS"], Compress: true, PathPattern: "static/*", TargetOriginId: "devmyappstackSiteDistributionOrigin1F25265FA", ViewerProtocolPolicy: "redirect-to-https", }, { AllowedMethods: [ "GET", "HEAD", "OPTIONS", "PUT", "PATCH", "POST", "DELETE", ], CachePolicyId: { Ref: "SiteLambdaCacheD9743183", }, CachedMethods: ["GET", "HEAD", "OPTIONS"], Compress: true, LambdaFunctionAssociations: [ { EventType: "origin-request", IncludeBody: true, LambdaFunctionARN: anything(), }, ], PathPattern: "api/*", TargetOriginId: "devmyappstackSiteDistributionOrigin1F25265FA", ViewerProtocolPolicy: "redirect-to-https", }, ], DefaultCacheBehavior: { AllowedMethods: ["GET", "HEAD", "OPTIONS"], CachePolicyId: { Ref: "SiteLambdaCacheD9743183", }, CachedMethods: ["GET", "HEAD", "OPTIONS"], Compress: true, LambdaFunctionAssociations: [ { EventType: "origin-request", IncludeBody: true, LambdaFunctionARN: anything(), }, { EventType: "origin-response", LambdaFunctionARN: anything(), }, ], TargetOriginId: "devmyappstackSiteDistributionOrigin1F25265FA", ViewerProtocolPolicy: "redirect-to-https", }, DefaultRootObject: "", Enabled: true, HttpVersion: "http2", IPV6Enabled: true, Origins: [ { DomainName: { "Fn::GetAtt": ["SiteBucket978D4AEB", "RegionalDomainName"], }, Id: "devmyappstackSiteDistributionOrigin1F25265FA", OriginPath: anything(), S3OriginConfig: { OriginAccessIdentity: { "Fn::Join": [ "", [ "origin-access-identity/cloudfront/", { Ref: "SiteDistributionOrigin1S3Origin76FD4338", }, ], ], }, }, }, ], }, }) ); expectCdk(stack).to(countResources("AWS::Route53::RecordSet", 0)); expectCdk(stack).to(countResources("AWS::Route53::HostedZone", 0)); expectCdk(stack).to(countResources("Custom::SSTBucketDeployment", 1)); expectCdk(stack).to( haveResource("Custom::SSTBucketDeployment", { Sources: [ { BucketName: anything(), ObjectKey: anything(), }, ], DestinationBucketName: { Ref: "SiteBucket978D4AEB", }, DestinationBucketKeyPrefix: stringLike("deploy-*"), FileOptions: [ [ "--exclude", "*", "--include", "public/*", "--cache-control", "public,max-age=31536000,must-revalidate", ], [ "--exclude", "*", "--include", "static/*", "--cache-control", "public,max-age=31536000,must-revalidate", ], [ "--exclude", "*", "--include", "static-pages/*", "--cache-control", "public,max-age=0,s-maxage=2678400,must-revalidate", ], [ "--exclude", "*", "--include", "_next/data/*", "--cache-control", "public,max-age=0,s-maxage=2678400,must-revalidate", ], [ "--exclude", "*", "--include", "_next/static/*", "--cache-control", "public,max-age=31536000,immutable", ], ], ReplaceValues: [], }) ); expectCdk(stack).to(countResources("Custom::SSTCloudFrontInvalidation", 1)); expectCdk(stack).to( haveResource("Custom::SSTCloudFrontInvalidation", { DistributionPaths: ["/*"], }) ); }); test("constructor: with domain", async () => { const stack = new Stack(new App(), "stack"); route53.HostedZone.fromLookup = jest .fn() .mockImplementation((scope, id, { domainName }) => { return new route53.HostedZone(scope, id, { zoneName: domainName }); }); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", customDomain: "domain.com", // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expect(site.url).toBeDefined(); expect(site.customDomainUrl).toBeDefined(); expect(site.bucketArn).toBeDefined(); expect(site.bucketName).toBeDefined(); expect(site.distributionId).toBeDefined(); expect(site.distributionDomain).toBeDefined(); expect(site.acmCertificate).toBeDefined(); expectCdk(stack).to(countResources("AWS::S3::Bucket", 1)); expectCdk(stack).to(countResources("AWS::CloudFront::Distribution", 1)); expectCdk(stack).to( haveResource("AWS::CloudFront::Distribution", { DistributionConfig: objectLike({ Aliases: ["domain.com"], }), }) ); expectCdk(stack).to(countResources("AWS::Route53::RecordSet", 1)); expectCdk(stack).to( haveResource("AWS::Route53::RecordSet", { Name: "domain.com.", Type: "A", AliasTarget: { DNSName: { "Fn::GetAtt": ["SiteDistribution390DED28", "DomainName"], }, HostedZoneId: { "Fn::FindInMap": [ "AWSCloudFrontPartitionHostedZoneIdMap", { Ref: "AWS::Partition", }, "zoneId", ], }, }, HostedZoneId: { Ref: "SiteHostedZone0E1602DC", }, }) ); expectCdk(stack).to(countResources("AWS::Route53::HostedZone", 1)); expectCdk(stack).to( haveResource("AWS::Route53::HostedZone", { Name: "domain.com.", }) ); }); test("constructor: with domain with alias", async () => { const stack = new Stack(new App(), "stack"); route53.HostedZone.fromLookup = jest .fn() .mockImplementation((scope, id, { domainName }) => { return new route53.HostedZone(scope, id, { zoneName: domainName }); }); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-nextjs-site", customDomain: { domainName: "domain.com", domainAlias: "www.domain.com", }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expect(site.url).toBeDefined(); expect(site.customDomainUrl).toBeDefined(); expect(site.bucketArn).toBeDefined(); expect(site.bucketName).toBeDefined(); expect(site.distributionId).toBeDefined(); expect(site.distributionDomain).toBeDefined(); expect(site.acmCertificate).toBeDefined(); expectCdk(stack).to(countResources("AWS::S3::Bucket", 2)); expectCdk(stack).to( haveResource("AWS::S3::Bucket", { WebsiteConfiguration: { RedirectAllRequestsTo: { HostName: "domain.com", Protocol: "https", }, }, }) ); expectCdk(stack).to(countResources("AWS::CloudFront::Distribution", 2)); expectCdk(stack).to( haveResource("AWS::CloudFront::Distribution", { DistributionConfig: objectLike({ Aliases: ["www.domain.com"], }), }) ); expectCdk(stack).to(countResources("AWS::Route53::RecordSet", 3)); expectCdk(stack).to( haveResource("AWS::Route53::RecordSet", { Name: "domain.com.", Type: "A", }) ); expectCdk(stack).to( haveResource("AWS::Route53::RecordSet", { Name: "www.domain.com.", Type: "A", }) ); expectCdk(stack).to( haveResource("AWS::Route53::RecordSet", { Name: "www.domain.com.", Type: "AAAA", }) ); expectCdk(stack).to(countResources("AWS::Route53::HostedZone", 1)); }); test("customDomain: string", async () => { const stack = new Stack(new App(), "stack"); route53.HostedZone.fromLookup = jest .fn() .mockImplementation((scope, id, { domainName }) => { return new route53.HostedZone(scope, id, { zoneName: domainName }); }); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", customDomain: "domain.com", // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expect(site.customDomainUrl).toEqual("https://domain.com"); expectCdk(stack).to( haveResource("AWS::CloudFormation::CustomResource", { DomainName: "domain.com", Region: "us-east-1", }) ); expectCdk(stack).to( haveResource("AWS::Route53::RecordSet", { Name: "domain.com.", Type: "A", }) ); expectCdk(stack).to( haveResource("AWS::Route53::HostedZone", { Name: "domain.com.", }) ); }); test("customDomain: domainName string", async () => { const stack = new Stack(new App(), "stack"); route53.HostedZone.fromLookup = jest .fn() .mockImplementation((scope, id, { domainName }) => { return new route53.HostedZone(scope, id, { zoneName: domainName }); }); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", customDomain: { domainName: "domain.com", }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expect(site.customDomainUrl).toEqual("https://domain.com"); expectCdk(stack).to( haveResource("AWS::CloudFormation::CustomResource", { DomainName: "domain.com", Region: "us-east-1", }) ); expectCdk(stack).to( haveResource("AWS::Route53::RecordSet", { Name: "domain.com.", Type: "A", }) ); expectCdk(stack).to( haveResource("AWS::Route53::HostedZone", { Name: "domain.com.", }) ); }); test("customDomain: hostedZone string", async () => { const stack = new Stack(new App(), "stack"); route53.HostedZone.fromLookup = jest .fn() .mockImplementation((scope, id, { domainName }) => { return new route53.HostedZone(scope, id, { zoneName: domainName }); }); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", customDomain: { domainName: "www.domain.com", hostedZone: "domain.com", }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expect(site.customDomainUrl).toEqual("https://www.domain.com"); expectCdk(stack).to( haveResource("AWS::CloudFormation::CustomResource", { DomainName: "www.domain.com", Region: "us-east-1", }) ); expectCdk(stack).to( haveResource("AWS::Route53::RecordSet", { Name: "www.domain.com.", Type: "A", }) ); expectCdk(stack).to( haveResource("AWS::Route53::HostedZone", { Name: "domain.com.", }) ); }); test("customDomain: hostedZone construct", async () => { const stack = new Stack(new App(), "stack"); route53.HostedZone.fromLookup = jest .fn() .mockImplementation((scope, id, { domainName }) => { return new route53.HostedZone(scope, id, { zoneName: domainName }); }); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", customDomain: { domainName: "www.domain.com", hostedZone: route53.HostedZone.fromLookup(stack, "HostedZone", { domainName: "domain.com", }), }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expect(route53.HostedZone.fromLookup).toHaveBeenCalledTimes(1); expect(site.customDomainUrl).toEqual("https://www.domain.com"); expectCdk(stack).to( haveResource("AWS::CloudFormation::CustomResource", { DomainName: "www.domain.com", Region: "us-east-1", }) ); expectCdk(stack).to( haveResource("AWS::Route53::RecordSet", { Name: "www.domain.com.", Type: "A", }) ); expectCdk(stack).to( haveResource("AWS::Route53::HostedZone", { Name: "domain.com.", }) ); }); test("customDomain: certificate imported", async () => { const stack = new Stack(new App(), "stack"); route53.HostedZone.fromLookup = jest .fn() .mockImplementation((scope, id, { domainName }) => { return new route53.HostedZone(scope, id, { zoneName: domainName }); }); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", customDomain: { domainName: "www.domain.com", hostedZone: "domain.com", certificate: new acm.Certificate(stack, "Cert", { domainName: "domain.com", }), }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expect(site.customDomainUrl).toEqual("https://www.domain.com"); expectCdk(stack).to(countResources("AWS::CloudFormation::CustomResource", 0)); expectCdk(stack).to( haveResource("AWS::Route53::RecordSet", { Name: "www.domain.com.", Type: "A", }) ); expectCdk(stack).to( haveResource("AWS::Route53::HostedZone", { Name: "domain.com.", }) ); }); test("customDomain: isExternalDomain true", async () => { const stack = new Stack(new App(), "stack"); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", customDomain: { domainName: "www.domain.com", certificate: new acm.Certificate(stack, "Cert", { domainName: "domain.com", }), isExternalDomain: true, }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expect(site.customDomainUrl).toEqual("https://www.domain.com"); expectCdk(stack).to(countResources("AWS::CloudFront::Distribution", 1)); expectCdk(stack).to( haveResource("AWS::CloudFront::Distribution", { DistributionConfig: objectLike({ Aliases: ["www.domain.com"], }), }) ); expectCdk(stack).to(countResources("AWS::CloudFormation::CustomResource", 0)); expectCdk(stack).to(countResources("AWS::Route53::HostedZone", 0)); expectCdk(stack).to(countResources("AWS::Route53::RecordSet", 0)); }); test("customDomain: isExternalDomain true and no certificate", async () => { const stack = new Stack(new App(), "stack"); expect(() => { new NextjsSite(stack, "Site", { path: "test/nextjs-site", customDomain: { domainName: "www.domain.com", isExternalDomain: true, }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); }).toThrow( /A valid certificate is required when "isExternalDomain" is set to "true"./ ); }); test("customDomain: isExternalDomain true and domainAlias set", async () => { const stack = new Stack(new App(), "stack"); expect(() => { new NextjsSite(stack, "Site", { path: "test/nextjs-site", customDomain: { domainName: "domain.com", domainAlias: "www.domain.com", certificate: new acm.Certificate(stack, "Cert", { domainName: "domain.com", }), isExternalDomain: true, }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); }).toThrow( /Domain alias is only supported for domains hosted on Amazon Route 53/ ); }); test("customDomain: isExternalDomain true and hostedZone set", async () => { const stack = new Stack(new App(), "stack"); expect(() => { new NextjsSite(stack, "Site", { path: "test/nextjs-site", customDomain: { domainName: "www.domain.com", hostedZone: "domain.com", certificate: new acm.Certificate(stack, "Cert", { domainName: "domain.com", }), isExternalDomain: true, }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); }).toThrow( /Hosted zones can only be configured for domains hosted on Amazon Route 53/ ); }); test("constructor: path not exist", async () => { const stack = new Stack(new App(), "stack"); expect(() => { new NextjsSite(stack, "Site", { path: "does-not-exist", }); }).toThrow(/No path found/); }); test("constructor: skipbuild doesn't expect path", async () => { const stack = new Stack( new App({ skipBuild: true, }), "stack" ); expect(() => { new NextjsSite(stack, "Site", { path: "does-not-exist", }); }).not.toThrow(/No path found/); }); test("constructor: s3Bucket props", async () => { const stack = new Stack(new App(), "stack"); new NextjsSite(stack, "Site", { path: "test/nextjs-site", s3Bucket: { bucketName: "my-bucket", }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expectCdk(stack).to(countResources("AWS::S3::Bucket", 1)); expectCdk(stack).to( haveResource("AWS::S3::Bucket", { BucketName: "my-bucket", }) ); }); test("constructor: cfDistribution props", async () => { const stack = new Stack(new App(), "stack"); new NextjsSite(stack, "Site", { path: "test/nextjs-site", cfDistribution: { comment: "My Comment", }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expectCdk(stack).to(countResources("AWS::CloudFront::Distribution", 1)); expectCdk(stack).to( haveResource("AWS::CloudFront::Distribution", { DistributionConfig: objectLike({ Comment: "My Comment", }), }) ); }); test("constructor: cfDistribution defaultBehavior override", async () => { const stack = new Stack(new App(), "stack"); new NextjsSite(stack, "Site", { path: "test/nextjs-site", cfDistribution: { defaultBehavior: { viewerProtocolPolicy: cf.ViewerProtocolPolicy.HTTPS_ONLY, allowedMethods: cf.AllowedMethods.ALLOW_ALL, }, }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expectCdk(stack).to(countResources("AWS::CloudFront::Distribution", 1)); expectCdk(stack).to( haveResource("AWS::CloudFront::Distribution", { DistributionConfig: objectLike({ DefaultCacheBehavior: objectLike({ ViewerProtocolPolicy: "https-only", AllowedMethods: [ "GET", "HEAD", "OPTIONS", "PUT", "PATCH", "POST", "DELETE", ], }), }), }) ); }); test("constructor: cfDistribution certificate conflict", async () => { const stack = new Stack(new App(), "stack"); expect(() => { new NextjsSite(stack, "Site", { path: "test/nextjs-site", cfDistribution: { certificate: new acm.Certificate(stack, "Cert", { domainName: "domain.com", }), }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); }).toThrow(/Do not configure the "cfDistribution.certificate"/); }); test("constructor: cfDistribution domainNames conflict", async () => { const stack = new Stack(new App(), "stack"); expect(() => { new NextjsSite(stack, "Site", { path: "test/nextjs-site", cfDistribution: { domainNames: ["domain.com"], }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); }).toThrow(/Do not configure the "cfDistribution.domainNames"/); }); test("constructor: environment generates placeholders", async () => { // Note: Build for real, do not use jestBuildOutputPath const stack = new Stack(new App(), "stack"); const api = new Api(stack, "Api"); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", environment: { CONSTANT_ENV: "my-url", REFERENCE_ENV: api.url, }, }); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "site.buildOutDir" not exposed in props const buildOutDir = site.buildOutDir || ""; const buildId = fs .readFileSync(path.join(buildOutDir, "assets", "BUILD_ID")) .toString() .trim(); const html = fs.readFileSync( path.join(buildOutDir, "assets", "static-pages", buildId, "env.html") ); // test constant values are replaced with actual values expect(html.toString().indexOf("{{ CONSTANT_ENV }}") > -1).toBeFalsy(); expect(html.toString().indexOf("my-url") > -1).toBeTruthy(); // test reference values are replaced with placeholder expect(html.toString().indexOf("{{ REFERENCE_ENV }}") > -1).toBeTruthy(); expectCdk(stack).to( haveResource("Custom::SSTBucketDeployment", { ReplaceValues: [ { files: "**/*.html", search: "{{ REFERENCE_ENV }}", replace: { "Fn::GetAtt": anything() }, }, { files: "**/*.js", search: "{{ REFERENCE_ENV }}", replace: { "Fn::GetAtt": anything() }, }, { files: "**/*.json", search: "{{ REFERENCE_ENV }}", replace: { "Fn::GetAtt": anything() }, }, ], }) ); expectCdk(stack).to( countResourcesLike("Custom::SSTLambdaCodeUpdater", 4, { ReplaceValues: [ { files: "**/*.html", search: "{{ REFERENCE_ENV }}", replace: { "Fn::GetAtt": anything() }, }, { files: "**/*.js", search: "{{ REFERENCE_ENV }}", replace: { "Fn::GetAtt": anything() }, }, { files: "**/*.json", search: "{{ REFERENCE_ENV }}", replace: { "Fn::GetAtt": anything() }, }, { files: "**/*.js", search: '"{{ _SST_NEXTJS_SITE_ENVIRONMENT_ }}"', replace: { "Fn::Join": [ "", ['{"REFERENCE_ENV":"', { "Fn::GetAtt": anything() }, '"}'], ], }, }, ], }) ); }); test("constructor: minimal feature (empty api lambda)", async () => { // Note: Build for real, do not use jestBuildOutputPath const stack = new Stack(new App(), "stack"); const site = new NextjsSite(stack, "Site", { path: sitePathMinimalFeatures, }); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "site.buildOutDir" not exposed in props const buildOutDir = site.buildOutDir || ""; // Verify "image-lambda" and "api-lambda" do not exist expect( fs.pathExistsSync(path.join(buildOutDir, "default-lambda", "index.js")) ).toBeTruthy(); expect( fs.pathExistsSync(path.join(buildOutDir, "regeneration-lambda", "index.js")) ).toBeTruthy(); expect( fs.pathExistsSync(path.join(buildOutDir, "image-lambda", "index.js")) ).toBeFalsy(); expect( fs.pathExistsSync(path.join(buildOutDir, "api-lambda", "index.js")) ).toBeFalsy(); expectCdk(stack).to(countResources("AWS::Lambda::Function", 10)); }); ///////////////////////////// // Test Constructor for non-us-east-1 region ///////////////////////////// test("constructor: us-east-1", async () => { const app = new App({ region: "us-east-1" }); const stack = new Stack(app, "stack"); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expect(site.url).toBeDefined(); expect(site.customDomainUrl).toBeUndefined(); expect(site.bucketArn).toBeDefined(); expect(site.bucketName).toBeDefined(); expect(site.distributionId).toBeDefined(); expect(site.distributionDomain).toBeDefined(); expect(site.acmCertificate).toBeUndefined(); expectCdk(stack).to(countResources("AWS::S3::Bucket", 1)); expectCdk(stack).to(countResources("AWS::Lambda::Function", 10)); expectCdk(stack).to(countResources("AWS::CloudFront::Distribution", 1)); expectCdk(stack).to(countResources("Custom::SSTEdgeLambdaBucket", 0)); expectCdk(stack).to(countResources("Custom::SSTEdgeLambda", 0)); expectCdk(stack).to(countResources("Custom::SSTEdgeLambdaVersion", 0)); expectCdk(stack).to(countResources("Custom::SSTBucketDeployment", 1)); expectCdk(stack).to(countResources("Custom::SSTLambdaCodeUpdater", 4)); expectCdk(stack).to(countResources("Custom::SSTCloudFrontInvalidation", 1)); }); test("constructor: ca-central-1", async () => { const app = new App({ region: "ca-central-1" }); const stack = new Stack(app, "stack"); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); expect(site.url).toBeDefined(); expect(site.customDomainUrl).toBeUndefined(); expect(site.bucketArn).toBeDefined(); expect(site.bucketName).toBeDefined(); expect(site.distributionId).toBeDefined(); expect(site.distributionDomain).toBeDefined(); expect(site.acmCertificate).toBeUndefined(); expectCdk(stack).to(countResources("AWS::S3::Bucket", 1)); expectCdk(stack).to(countResources("AWS::Lambda::Function", 9)); expectCdk(stack).to(countResources("AWS::CloudFront::Distribution", 1)); expectCdk(stack).to(countResources("Custom::SSTEdgeLambdaBucket", 1)); expectCdk(stack).to(countResources("Custom::SSTEdgeLambda", 3)); expectCdk(stack).to(countResources("Custom::SSTEdgeLambdaVersion", 3)); expectCdk(stack).to(countResources("Custom::SSTBucketDeployment", 1)); expectCdk(stack).to(countResources("Custom::SSTLambdaCodeUpdater", 4)); expectCdk(stack).to(countResources("Custom::SSTCloudFrontInvalidation", 1)); }); ///////////////////////////// // Test Constructor for Local Debug ///////////////////////////// test("constructor: local debug", async () => { const app = new App({ debugEndpoint: "placeholder", }); const stack = new Stack(app, "stack"); new NextjsSite(stack, "Site", { path: "test/nextjs-site", }); expectCdk(stack).to(countResources("Custom::SSTBucketDeployment", 1)); expectCdk(stack).to( haveResource("Custom::SSTBucketDeployment", { Sources: [ { BucketName: anything(), ObjectKey: anything(), }, ], DestinationBucketName: { Ref: "SiteBucket978D4AEB", }, DestinationBucketKeyPrefix: "deploy-live", }) ); expectCdk(stack).to(countResources("Custom::SSTCloudFrontInvalidation", 1)); expectCdk(stack).to( haveResource("Custom::SSTCloudFrontInvalidation", { DistributionPaths: ["/*"], }) ); expectCdk(stack).to( haveResource("AWS::CloudFront::Distribution", { DistributionConfig: objectLike({ CustomErrorResponses: [ { ErrorCode: 403, ResponseCode: 200, ResponsePagePath: "/index.html", }, { ErrorCode: 404, ResponseCode: 200, ResponsePagePath: "/index.html", }, ], }), }) ); }); test("constructor: local debug with disablePlaceholder true", async () => { const app = new App({ debugEndpoint: "placeholder", }); const stack = new Stack(app, "stack"); new NextjsSite(stack, "Site", { path: "test/nextjs-site", disablePlaceholder: true, }); expectCdk(stack).to(countResources("Custom::SSTBucketDeployment", 1)); expectCdk(stack).to( haveResource("Custom::SSTBucketDeployment", { Sources: [ { BucketName: anything(), ObjectKey: anything(), }, ], DestinationBucketName: { Ref: "SiteBucket978D4AEB", }, DestinationBucketKeyPrefix: notMatching("deploy-live"), }) ); expectCdk(stack).to( haveResource("AWS::CloudFront::Distribution", { DistributionConfig: objectLike({ CustomErrorResponses: ABSENT, }), }) ); }); ///////////////////////////// // Test Constructor for skipBuild ///////////////////////////// test("constructor: skipBuild", async () => { const app = new App({ skipBuild: true, }); const stack = new Stack(app, "stack"); new NextjsSite(stack, "Site", { path: "test/nextjs-site", }); expectCdk(stack).to(countResources("Custom::SSTBucketDeployment", 1)); }); ///////////////////////////// // Test Methods ///////////////////////////// test("attachPermissions", async () => { const stack = new Stack(new App(), "stack"); const site = new NextjsSite(stack, "Site", { path: "test/nextjs-site", // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: "jestBuildOutputPath" not exposed in props jestBuildOutputPath: buildOutputPath, }); site.attachPermissions(["sns"]); expectCdk(stack).to( countResourcesLike("AWS::IAM::Policy", 1, { PolicyDocument: { Statement: arrayWith({ Action: "sns:*", Effect: "Allow", Resource: "*", }), Version: "2012-10-17", }, }) ); });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/endpointsMappers"; import * as Parameters from "../models/parameters"; import { TrafficManagerManagementClientContext } from "../trafficManagerManagementClientContext"; /** Class representing a Endpoints. */ export class Endpoints { private readonly client: TrafficManagerManagementClientContext; /** * Create a Endpoints. * @param {TrafficManagerManagementClientContext} client Reference to the service client. */ constructor(client: TrafficManagerManagementClientContext) { this.client = client; } /** * Update a Traffic Manager endpoint. * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint * to be updated. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint to be updated. * @param endpointName The name of the Traffic Manager endpoint to be updated. * @param parameters The Traffic Manager endpoint parameters supplied to the Update operation. * @param [options] The optional parameters * @returns Promise<Models.EndpointsUpdateResponse> */ update(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, parameters: Models.Endpoint, options?: msRest.RequestOptionsBase): Promise<Models.EndpointsUpdateResponse>; /** * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint * to be updated. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint to be updated. * @param endpointName The name of the Traffic Manager endpoint to be updated. * @param parameters The Traffic Manager endpoint parameters supplied to the Update operation. * @param callback The callback */ update(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, parameters: Models.Endpoint, callback: msRest.ServiceCallback<Models.Endpoint>): void; /** * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint * to be updated. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint to be updated. * @param endpointName The name of the Traffic Manager endpoint to be updated. * @param parameters The Traffic Manager endpoint parameters supplied to the Update operation. * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, parameters: Models.Endpoint, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Endpoint>): void; update(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, parameters: Models.Endpoint, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Endpoint>, callback?: msRest.ServiceCallback<Models.Endpoint>): Promise<Models.EndpointsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, profileName, endpointType, endpointName, parameters, options }, updateOperationSpec, callback) as Promise<Models.EndpointsUpdateResponse>; } /** * Gets a Traffic Manager endpoint. * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint. * @param endpointName The name of the Traffic Manager endpoint. * @param [options] The optional parameters * @returns Promise<Models.EndpointsGetResponse> */ get(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, options?: msRest.RequestOptionsBase): Promise<Models.EndpointsGetResponse>; /** * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint. * @param endpointName The name of the Traffic Manager endpoint. * @param callback The callback */ get(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, callback: msRest.ServiceCallback<Models.Endpoint>): void; /** * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint. * @param endpointName The name of the Traffic Manager endpoint. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Endpoint>): void; get(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Endpoint>, callback?: msRest.ServiceCallback<Models.Endpoint>): Promise<Models.EndpointsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, profileName, endpointType, endpointName, options }, getOperationSpec, callback) as Promise<Models.EndpointsGetResponse>; } /** * Create or update a Traffic Manager endpoint. * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint * to be created or updated. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint to be created or updated. * @param endpointName The name of the Traffic Manager endpoint to be created or updated. * @param parameters The Traffic Manager endpoint parameters supplied to the CreateOrUpdate * operation. * @param [options] The optional parameters * @returns Promise<Models.EndpointsCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, parameters: Models.Endpoint, options?: msRest.RequestOptionsBase): Promise<Models.EndpointsCreateOrUpdateResponse>; /** * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint * to be created or updated. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint to be created or updated. * @param endpointName The name of the Traffic Manager endpoint to be created or updated. * @param parameters The Traffic Manager endpoint parameters supplied to the CreateOrUpdate * operation. * @param callback The callback */ createOrUpdate(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, parameters: Models.Endpoint, callback: msRest.ServiceCallback<Models.Endpoint>): void; /** * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint * to be created or updated. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint to be created or updated. * @param endpointName The name of the Traffic Manager endpoint to be created or updated. * @param parameters The Traffic Manager endpoint parameters supplied to the CreateOrUpdate * operation. * @param options The optional parameters * @param callback The callback */ createOrUpdate(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, parameters: Models.Endpoint, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Endpoint>): void; createOrUpdate(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, parameters: Models.Endpoint, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Endpoint>, callback?: msRest.ServiceCallback<Models.Endpoint>): Promise<Models.EndpointsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, profileName, endpointType, endpointName, parameters, options }, createOrUpdateOperationSpec, callback) as Promise<Models.EndpointsCreateOrUpdateResponse>; } /** * Deletes a Traffic Manager endpoint. * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint * to be deleted. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint to be deleted. * @param endpointName The name of the Traffic Manager endpoint to be deleted. * @param [options] The optional parameters * @returns Promise<Models.EndpointsDeleteMethodResponse> */ deleteMethod(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, options?: msRest.RequestOptionsBase): Promise<Models.EndpointsDeleteMethodResponse>; /** * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint * to be deleted. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint to be deleted. * @param endpointName The name of the Traffic Manager endpoint to be deleted. * @param callback The callback */ deleteMethod(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, callback: msRest.ServiceCallback<Models.DeleteOperationResult>): void; /** * @param resourceGroupName The name of the resource group containing the Traffic Manager endpoint * to be deleted. * @param profileName The name of the Traffic Manager profile. * @param endpointType The type of the Traffic Manager endpoint to be deleted. * @param endpointName The name of the Traffic Manager endpoint to be deleted. * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DeleteOperationResult>): void; deleteMethod(resourceGroupName: string, profileName: string, endpointType: string, endpointName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DeleteOperationResult>, callback?: msRest.ServiceCallback<Models.DeleteOperationResult>): Promise<Models.EndpointsDeleteMethodResponse> { return this.client.sendOperationRequest( { resourceGroupName, profileName, endpointType, endpointName, options }, deleteMethodOperationSpec, callback) as Promise<Models.EndpointsDeleteMethodResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}", urlParameters: [ Parameters.resourceGroupName, Parameters.profileName, Parameters.endpointType, Parameters.endpointName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.Endpoint, required: true } }, responses: { 200: { bodyMapper: Mappers.Endpoint }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}", urlParameters: [ Parameters.resourceGroupName, Parameters.profileName, Parameters.endpointType, Parameters.endpointName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Endpoint }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}", urlParameters: [ Parameters.resourceGroupName, Parameters.profileName, Parameters.endpointType, Parameters.endpointName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.Endpoint, required: true } }, responses: { 200: { bodyMapper: Mappers.Endpoint }, 201: { bodyMapper: Mappers.Endpoint }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}", urlParameters: [ Parameters.resourceGroupName, Parameters.profileName, Parameters.endpointType, Parameters.endpointName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DeleteOperationResult }, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import Game from './game'; import Render from '../base/render'; import { Duck } from '../index'; import Debug from './debug/debug'; import Sprite from './gameobjects/sprite'; import Rect from './gameobjects/rect'; import Circle from './gameobjects/circle'; import RoundRect from './gameobjects/roundrect'; import Particle from './gameobjects/particles/particle'; import ParticleEmitter from './gameobjects/particles/particleEmitter'; import SoundPlayer from './sound/soundPlayer'; import Input from './input/input'; import Camera from './camera/camera'; import StaticLight from './lights/staticLight'; import Group from './group/group'; import Cutscene from './cutscene/cutscene'; import Loader from './loader/loader'; import randomInt from './math/randomInt'; import randomFloat from './math/randomFloat'; import isHex from '../helper/color/isHex'; import isHSL from '../helper/color/isHSL'; import isRGB from '../helper/color/isRGB'; import rgbToRGBA from '../helper/color/rgbToRGBA'; import rgbToHSL from '../helper/color/rgbToHSL'; import rgbaToHSLA from '../helper/color/rgbaToHSLA'; import rgbaToRGB from '../helper/color/rgbaToRGB'; import hexToRGBA from '../helper/color/hexToRGBA'; import hexToRGB from '../helper/color/hexToRGB'; import hexToHSL from '../helper/color/hexToHSL'; import randomColor from '../helper/color/randomColor'; import randomColorWithAlpha from '../helper/color/randomAlphaColor'; import rectToRectIntersect from './physics/rectToRectIntersect'; import circleToRectIntersect from './physics/circleToRectIntersect'; import TileMap from './map/tilemap'; import Once from '../base/once'; import Amount from '../base/amount'; import Button from './gameobjects/interactive/button'; import Text from './gameobjects/interactive/text'; import Effect from './effect/effect'; import ExplosionEffect from './effect/preset/explosion'; import SmokeEffect from './effect/preset/smoke'; import DisplayList from './models/displayList'; import CanvasModulate from './gameobjects/misc/canvasModulate'; import Vector2 from './math/vector2'; import clamp from './math/clamp'; import lerp from './math/lerp'; import PhysicsServer from './physics/server/physicsServer'; import PhysicsList from './models/physicsList'; import Area from './physics/models/area'; import PhysicsBody from './physics/physicsBody'; import GameObject from './gameobjects/gameObject'; import Tileset from './map/tileset'; import TileLayer from './map/tilelayer'; /** * @class Scene * @classdesc Creates a DuckEngine Scene * @description The Scene Class. Main rendering happens here * @since 1.0.0-beta */ export default class Scene extends Render { /** * @memberof Scene * @description The key of the Scene, used to identify the Scene * @type string * @since 1.0.0-beta */ public readonly key: string; /** * @memberof Scene * @description The state of the Scene being visible, determines if the Scene.displayList, physicsList, update, and __tick, is being called/used * in the game loop * @type boolean * @since 1.0.0-beta */ public visible: boolean; /** * @memberof Scene * @description Determines if the Scene is visible by default * @type boolean * @since 1.0.0-beta */ public readonly default: boolean; /** * @memberof Scene * @description The game instance the scene is added to * @type Game * @since 1.0.0-beta */ protected game: Game; /** * @memberof Scene * @description The current camera being updated * @type Camera | undefined * @since 1.0.0-beta */ public currentCamera: Camera | undefined; /** * @memberof Scene * @description The main camera of the scene * @type Camera | undefined * @since 1.0.0-beta */ public mainCamera: Camera | undefined; /** * @memberof Scene * @description An array of cameras that the scene holds * @type Camera[] * @since 1.0.0-beta */ public cameras: Camera[]; /** * @memberof Scene * @description A DisplayList instance, holds and manages Renderables * @type DisplayList * @since 2.0.0 */ public displayList: DisplayList; /** * @memberof Scene * @description A PhysicsList instance, holds and manages PhysicsBodies * @type PhysicsList * @since 2.0.0 */ public physicsList: PhysicsList; /** * @memberof Scene * @description A Loader instance, used to load assets in Scene.preload method that you override * @type Loader * @since 2.0.0 */ public loader: Loader; /** * @memberof Scene * @description A PhysicsServer instance, manages and updates all the physics for the Scene.PhysicsList. It is set to undefined if * Game.config.physics.customTick is truthy * @type PhysicsServer | undefined * @since 2.0.0 */ public physicsServer: PhysicsServer | undefined; // methods /** * @memberof Scene * @description Used to add GameObjects and more to the scene * @since 1.0.0-beta */ public add: { gameobject: { misc: { canvasModulate: ( x: number, y: number, w: number, h: number, fillColor: string ) => CanvasModulate; }; existing: <t extends Duck.Types.Texture.Type>( gameobject: GameObject<t> ) => GameObject<t>; sprite: ( x: number, y: number, w: number, h: number, textureKey: string, frameWidth?: number, frameHeight?: number, rows?: number, cols?: number, currentRow?: number, currentCol?: number ) => Sprite; rect: ( x: number, y: number, w: number, h: number, fillColor: string ) => Rect; circle: ( x: number, y: number, r: number, fillColor: string ) => Circle; roundRect: ( x: number, y: number, w: number, h: number, r: number, fillColor: string ) => RoundRect; }; misc: { area: ( x: number, y: number, w: number, h: number, collisionFilter: PhysicsBody<Duck.Types.Texture.Type>[] ) => Area; }; interactive: { text: ( text: string, config: Duck.Types.Interactive.Text.Config ) => Text; button: ( shape: Duck.Types.Interactive.Button.Shape, x: number, y: number, w: number, h: number, r: number, fillColor: string, text: Text ) => Button; }; soundPlayer: ( path: string, options?: Duck.Types.Sound.Config ) => SoundPlayer; input: () => Input; camera: () => Camera; mainCamera: () => Camera; light: { staticLight: ( x: number, y: number, r: number, fillColor: string, alpha: Duck.Types.Helper.AlphaRange ) => StaticLight; }; group: <t extends Duck.Types.Group.StackItem>( name: string, defaultValues?: t[] ) => Group<t>; particle: ( shape: Duck.Types.Collider.ShapeString, w: number, h: number, r: number, fillColor: string ) => Particle; particleEmitter: ( particle: Particle, rangeX: Duck.Types.ParticleEmitter.Range, rangeY: Duck.Types.ParticleEmitter.Range, amount: number ) => ParticleEmitter; cutscene: ( config: Duck.Types.Cutscene.Config, instructions: Duck.Types.Cutscene.Instructions ) => Cutscene; map: { tilemap: ( origin: Duck.Types.Math.Vector2Like, tilelayers: TileLayer[] ) => TileMap; tileset: ( textureKey: string, tileW: number, tileH: number, rows: number, cols: number ) => Tileset; tileLayer: ( tileset: Tileset, map: number[][], zIndex?: number, visible?: boolean ) => TileLayer; }; effect: ( rangeX: Duck.Types.ParticleEmitter.Range, rangeY: Duck.Types.ParticleEmitter.Range, particleEmitter: ParticleEmitter ) => Effect; presetEffect: { explosionEffect: ( rangeX: Duck.Types.ParticleEmitter.Range, rangeY: Duck.Types.ParticleEmitter.Range, particleAmount: number | undefined, speedRange: [1, 1] | undefined, maxAge: number | undefined, color: string | undefined ) => ExplosionEffect; smokeEffect: ( rangeX: Duck.Types.ParticleEmitter.Range, rangeY: Duck.Types.ParticleEmitter.Range, particleAmount: number | undefined, speedRangeX: [-0.1, 0.4] | undefined, speedRangeY: [-0.1, 0.4] | undefined, maxAge: number | undefined, color: '#2e2e2e' | undefined, interval: 50 | undefined ) => SmokeEffect; }; }; /** * @memberof Scene * @description Misc tools, contains color, physics, and math related tools * @since 1.0.0-beta */ public tools: { loader: typeof Loader; color: { random: () => string; randomWithAlpha: (alpha?: Duck.Types.Helper.AlphaRange) => string; is: { hex: (str: string) => boolean; hsl: (str: string) => boolean; rgb: (str: string) => boolean; }; convert: { rgb: { toHsl: (r: number, g: number, b: number) => string; toRgba: ( color: string, alpha: Duck.Types.Helper.AlphaRange ) => string; }; rgba: { toHsla: ( r: string | number, g: string | number, b: string | number, a: Duck.Types.Helper.AlphaRange ) => string; toRgb: (rgba: string) => string; }; hex: { toRgba: ( hex: string, alpha: Duck.Types.Helper.AlphaRange ) => string; toRgb: (hex: string) => string | null; toHsl: (hex: string) => string; }; }; }; physics: { rectToRectIntersect: ( rect: Rect | Sprite, rect2: Rect | Sprite ) => boolean; circleToRectIntersect: ( circle: | Circle | { position: { x: number; y: number }; w: number; h: number; r: number; }, rect: | Rect | Sprite | { position: { x: number; y: number }; w: number; h: number; } ) => boolean; }; math: { createVector: (x?: number, y?: number) => Vector2; vector: typeof Vector2; clamp: (x: number, min: number, max: number) => number; lerp: (start: number, end: number, amount: number) => number; randomInt: (min: number, max: number) => number; randomFloat: (min: number, max: number, fixed?: number) => number; }; }; /** * @constructor Scene * @description Creates a Scene instance * @param {string} key Key/Identifier or name of scene * @param {Game} game Game instance * @param {boolean} [visible=false] Is the scene visible, defaults to false * @since 1.0.0-beta */ constructor(key: string, game: Game, visible?: boolean) { super(); this.key = key; this.game = game; this.visible = visible || false; this.default = false; // set visible if key is same as defaultScene key if (this.game.stack.defaultScene === this.key) { this.default = true; this.visible = true; } // main camera this.currentCamera; this.mainCamera; this.cameras = []; this.displayList = new DisplayList(); this.physicsList = new PhysicsList(); this.loader = new Loader(this.game, this); if (this.game.config.physics?.enabled) { this.physicsServer = new PhysicsServer(this.game, this); } // methods this.add = { gameobject: { misc: { canvasModulate: ( x: number, y: number, w: number, h: number, fillColor: string ) => { const myCanvasModulate = new CanvasModulate( x, y, w, h, fillColor, this.game, this ); this.displayList.add(myCanvasModulate); this.physicsList.add(myCanvasModulate); return myCanvasModulate; }, }, existing: <t extends Duck.Types.Texture.Type>( gameobject: GameObject<t> ) => { this.displayList.add(gameobject); this.physicsList.add(gameobject); return gameobject; }, sprite: ( x: number, y: number, w: number, h: number, textureKey: string, frameWidth?: number, frameHeight?: number, rows?: number, cols?: number, currentRow?: number, currentCol?: number ) => { const sprite = new Sprite( x, y, w, h, textureKey, this.game, this, frameWidth, frameHeight, rows, cols, currentRow, currentCol ); this.displayList.add(sprite); this.physicsList.add(sprite); return sprite; }, rect: ( x: number, y: number, w: number, h: number, fillColor: string ) => { const rect = new Rect( x, y, w, h, fillColor, this.game, this ); this.displayList.add(rect); this.physicsList.add(rect); return rect; }, circle: ( x: number, y: number, r: number, fillColor: string ) => { const circle = new Circle( x, y, r, fillColor, this.game, this ); this.displayList.add(circle); this.physicsList.add(circle); return circle; }, roundRect: ( x: number, y: number, w: number, h: number, r: number, fillColor: string ) => { const roundRect = new RoundRect( x, y, w, h, r, fillColor, this.game, this ); this.displayList.add(roundRect); this.physicsList.add(roundRect); return roundRect; }, }, misc: { area: ( x: number, y: number, w: number, h: number, collisionFilter: PhysicsBody<Duck.Types.Texture.Type>[] ) => { const myArea = new Area( x, y, w, h, collisionFilter, this.game, this ); this.physicsList.add(myArea); return myArea; }, }, interactive: { text: ( text: string, config: Duck.Types.Interactive.Text.Config ) => { const myText = new Text(text, config, this.game, this); this.displayList.add(myText); this.physicsList.add(myText); return myText; }, button: ( shape: Duck.Types.Interactive.Button.Shape, x: number, y: number, w: number, h: number, r: number, fillColor: string, text: Text ) => { const myButton = new Button( shape, x, y, w, h, r, fillColor, text, this.game, this ); this.displayList.add(myButton); this.physicsList.add(myButton); return myButton; }, }, soundPlayer: (path: string, options?: Duck.Types.Sound.Config) => { return new SoundPlayer(path, options); }, input: () => { return new Input(this.game, this); }, camera: () => { const c = new Camera(this.game, this); this.cameras.push(c); return c; }, mainCamera: () => { const c = new Camera(this.game, this); this.cameras.push(c); this.mainCamera = c; this.currentCamera = c; return c; }, light: { staticLight: ( x: number, y: number, r: number, fillColor: string, alpha: Duck.Types.Helper.AlphaRange ) => { const myStaticLight = new StaticLight( x, y, r, fillColor, alpha, this.game, this ); this.displayList.add(myStaticLight); this.physicsList.add(myStaticLight); return myStaticLight; }, }, group: <t extends Duck.Types.Group.StackItem>( name: string, defaultValues?: t[] ) => { return new Group<t>(name, this.game, defaultValues); }, particle: ( shape: Duck.Types.Collider.ShapeString, w: number, h: number, r: number, fillColor: string ) => { const myParticle = new Particle( shape, w, h, r, fillColor, this.game, this ); return myParticle; }, particleEmitter: ( particle: Particle, rangeX: Duck.Types.ParticleEmitter.Range, rangeY: Duck.Types.ParticleEmitter.Range, amount: number ) => { return new ParticleEmitter( particle, rangeX, rangeY, amount, this.game, this ); }, cutscene: ( config: Duck.Types.Cutscene.Config, instructions: Duck.Types.Cutscene.Instructions ) => { return new Cutscene(config, instructions, this.game); }, map: { tilemap: ( origin: Duck.Types.Math.Vector2Like, tilelayers: TileLayer[] ) => { const myTileMap = new TileMap( origin, tilelayers, this.game, this ); this.displayList.add(myTileMap); return myTileMap; }, tileset: ( textureKey: string, tileW: number, tileH: number, rows: number, cols: number ) => { return new Tileset( textureKey, tileW, tileH, rows, cols, this.game, this ); }, tileLayer: ( tileset: Tileset, map: number[][], zIndex = 2, visible = true ) => { return new TileLayer( tileset, map, this.game, this, zIndex, visible ); }, }, effect: ( rangeX: Duck.Types.ParticleEmitter.Range, rangeY: Duck.Types.ParticleEmitter.Range, particleEmitter: ParticleEmitter ) => { const myEffect = new Effect( rangeX, rangeY, particleEmitter, this.game ); this.displayList.add(myEffect); return myEffect; }, presetEffect: { explosionEffect: ( rangeX: Duck.Types.ParticleEmitter.Range, rangeY: Duck.Types.ParticleEmitter.Range, particleAmount = 50, speedRange = [1, 1], maxAge = 3, color = '#FFA500' ) => { const myExplosionEffect = new ExplosionEffect( rangeX, rangeY, this.game, particleAmount, speedRange, maxAge, color, this ); this.displayList.add(myExplosionEffect); return myExplosionEffect; }, smokeEffect: ( rangeX: Duck.Types.ParticleEmitter.Range, rangeY: Duck.Types.ParticleEmitter.Range, particleAmount = 50, speedRangeX = [-0.1, 0.4], speedRangeY = [-0.1, 0.4], maxAge = 20, color = '#2e2e2e', interval = 50 ) => { const mySmokeEffect = new SmokeEffect( rangeX, rangeY, this.game, particleAmount, speedRangeX, speedRangeY, maxAge, color, interval, this ); this.displayList.add(mySmokeEffect); return mySmokeEffect; }, }, }; this.tools = { loader: Loader, color: { random: randomColor, randomWithAlpha: (alpha?: Duck.Types.Helper.AlphaRange) => randomColorWithAlpha(alpha), is: { hex: isHex, hsl: isHSL, rgb: isRGB, }, convert: { rgb: { toHsl: rgbToHSL, toRgba: rgbToRGBA, }, rgba: { toHsla: rgbaToHSLA, toRgb: rgbaToRGB, }, hex: { toRgba: hexToRGBA, toRgb: hexToRGB, toHsl: hexToHSL, }, }, }, physics: { rectToRectIntersect: ( rect: Rect | Sprite, rect2: Rect | Sprite ) => { return rectToRectIntersect(rect, rect2); }, circleToRectIntersect: ( circle: | Circle | { position: { x: number; y: number }; w: number; h: number; r: number; }, rect: | Rect | Sprite | { position: { x: number; y: number }; w: number; h: number; } ) => { return circleToRectIntersect(circle, rect); }, }, math: { createVector: (x?: number, y?: number) => { return Vector2.CREATE(x, y); }, vector: Vector2, clamp: clamp, lerp: lerp, randomInt: randomInt, randomFloat: randomFloat, }, }; } /** * @memberof Scene * @description Calls physics server __tick method if game.config.physics.enabled is true * and game.config.physics.customTick is false * *Do not call manually, this is called in GAME LOOP* * * @since 2.0.0 */ public __tick() { if (!this.game.config.physics?.customTick) { this.physicsServer?.__tick(); } } /** * @memberof Scene * @description Switches the active camera to a passed camera * @param {Camera} camera Camera to switch to * @memberof 1.0.0-beta */ public switchCamera(camera: Camera) { const foundCamera = this.cameras.find((_camera) => _camera === camera); if (foundCamera) { this.currentCamera = foundCamera; if (this.game.config.debug) { new Debug.Log('Switched cameras.'); } } else { new Debug.Error( 'Cannot switch camera. Camera not found in the current scene.' ); } } /** * @memberof Scene * @description Switches the active camera to the main camera * @since 1.0.0-beta */ public switchToMainCamera() { this.currentCamera = this.mainCamera; if (this.game.config.debug) { new Debug.Log('Switched to main camera.'); } } /** * @memberof Scene * @description Sets a camera as the main camera * @param {Camera} camera Camera to set the main camera as * @since 1.0.0-beta */ public setMainCamera(camera: Camera) { this.mainCamera = camera; if (this.game.config.debug) { new Debug.Log(`Set main camera to ${camera}.`); } } /** * @memberof Scene * @description Runs a function once no matter if it is in a loop or not * @param {Function} func Function to run * @param {boolean} [run] Determines if function is ran right when it is initialized * @since 1.0.0 */ public once(func: Function, run?: boolean) { const one = new Once(func, run); return one; } /** * @memberof Scene * @description Allows a function to only be ran a max amount of times * @param {(currentCount:number) => void} func Function to call * @param {number} maxAmount Max amount of times to allow the function to be called * @param {boolean} [run] Determines if function is ran right when it is initialized * @since 1.1.0 */ public runAmount( func: (currentCount: number) => void, maxAmount: number, run?: boolean ) { const amount = new Amount(func, maxAmount, this.game, run); return amount; } }
the_stack
import { Component, Element, Host, VNode, h, Prop, Listen, Event, EventEmitter, Method, Watch } from "@stencil/core"; import { guid } from "../../utils/guid"; import { getKey } from "../../utils/key"; import { parseTimeString, Time, formatTimeString, HourDisplayFormat, getMeridiem, getMeridiemHour } from "../../utils/time"; import { Scale } from "../interfaces"; import { LabelableComponent, connectLabel, disconnectLabel, getLabelText } from "../../utils/label"; @Component({ tag: "calcite-input-time-picker", styleUrl: "calcite-input-time-picker.scss", shadow: true }) export class CalciteInputTimePicker implements LabelableComponent { //-------------------------------------------------------------------------- // // Element // //-------------------------------------------------------------------------- @Element() el: HTMLCalciteInputTimePickerElement; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** The active state of the time input */ @Prop({ reflect: true, mutable: true }) active = false; /** The disabled state of the time input */ @Prop({ reflect: true }) disabled = false; /** Format of the hour value (12-hour or 24-hour) (this will be replaced by locale eventually) */ @Prop() hourDisplayFormat: HourDisplayFormat = "12"; /** aria-label for the hour input */ @Prop() intlHour?: string; /** aria-label for the hour down button */ @Prop() intlHourDown?: string; /** aria-label for the hour up button */ @Prop() intlHourUp?: string; /** aria-label for the meridiem (am/pm) input */ @Prop() intlMeridiem?: string; /** aria-label for the meridiem (am/pm) down button */ @Prop() intlMeridiemDown?: string; /** aria-label for the meridiem (am/pm) up button */ @Prop() intlMeridiemUp?: string; /** aria-label for the minute input */ @Prop() intlMinute?: string; /** aria-label for the minute down button */ @Prop() intlMinuteDown?: string; /** aria-label for the minute up button */ @Prop() intlMinuteUp?: string; /** aria-label for the second input */ @Prop() intlSecond?: string; /** aria-label for the second down button */ @Prop() intlSecondDown?: string; /** aria-label for the second up button */ @Prop() intlSecondUp?: string; /** The name of the time input */ @Prop() name?: string; /** The scale (size) of the time input */ @Prop({ reflect: true }) scale: Scale = "m"; /** number that specifies the granularity that the value must adhere to */ @Prop() step = 60; /** The selected time (always 24-hour format)*/ @Prop({ mutable: true }) value: string = null; @Watch("value") valueWatcher(newValue: string): void { if (!this.internalValueChange) { this.setValue({ value: newValue, origin: "external" }); } this.internalValueChange = false; } //-------------------------------------------------------------------------- // // Private Properties // //-------------------------------------------------------------------------- labelEl: HTMLCalciteLabelElement; private calciteInputEl: HTMLCalciteInputElement; /** whether the value of the input was changed as a result of user typing or not */ private internalValueChange = false; private previousValidValue: string = null; private referenceElementId = `input-time-picker-${guid()}`; //-------------------------------------------------------------------------- // // Events // //-------------------------------------------------------------------------- /** * Fires when the time value is changed as a result of user input. */ @Event() calciteInputTimePickerChange: EventEmitter<string>; //-------------------------------------------------------------------------- // // Event Listeners // //-------------------------------------------------------------------------- private calciteInputBlurHandler = (): void => { this.active = false; const newValue = formatTimeString(this.calciteInputEl.value) || formatTimeString(this.value); if (newValue !== this.calciteInputEl.value) { this.setInputValue(newValue); } }; private calciteInputFocusHandler = (): void => { this.active = true; }; private calciteInputInputHandler = (event: CustomEvent): void => { this.setValue({ value: event.detail.value }); }; @Listen("keyup") keyUpHandler(event: KeyboardEvent): void { if (getKey(event.key) === "Escape" && this.active) { this.active = false; } } @Listen("calciteTimePickerBlur") timePickerBlurHandler(event: CustomEvent): void { event.preventDefault(); event.stopPropagation(); this.active = false; } @Listen("calciteTimePickerChange") timePickerChangeHandler(event: CustomEvent): void { event.preventDefault(); event.stopPropagation(); if (event.detail) { const { hour, minute, second } = event.detail as Time; let value; if (hour && minute) { value = second && this.step !== 60 ? `${hour}:${minute}:${second}` : `${hour}:${minute}`; } else { value = ""; } this.setValue({ value, origin: "time-picker" }); } } @Listen("calciteTimePickerFocus") timePickerFocusHandler(event: CustomEvent): void { event.preventDefault(); event.stopPropagation(); this.active = true; } // -------------------------------------------------------------------------- // // Public Methods // // -------------------------------------------------------------------------- /** Sets focus on the component. */ @Method() async setFocus(): Promise<void> { this.calciteInputEl.setFocus(); } // -------------------------------------------------------------------------- // // Private Methods // // -------------------------------------------------------------------------- onLabelClick(): void { this.setFocus(); } private setCalciteInputEl = (el: HTMLCalciteInputElement): void => { this.calciteInputEl = el; }; private setInputValue = (newInputValue: string): void => { if (!this.calciteInputEl) { return; } if (this.hourDisplayFormat === "12") { const { hour, minute, second } = parseTimeString(newInputValue); this.calciteInputEl.value = newInputValue ? `${getMeridiemHour(hour)}:${minute}${this.step !== 60 ? ":" + second : ""} ${getMeridiem( hour )}` : null; } else { this.calciteInputEl.value = newInputValue; } }; private setValue = ({ value, origin = "input" }: { value: string; origin?: "input" | "time-picker" | "external" | "loading"; }): void => { const previousValue = this.value; const validatedNewValue = formatTimeString(value); this.internalValueChange = origin !== "external" && origin !== "loading"; const shouldEmit = origin !== "loading" && origin !== "external" && ((value !== this.previousValidValue && !value) || !!(!this.previousValidValue && validatedNewValue) || (validatedNewValue !== this.previousValidValue && validatedNewValue)); if (value) { if (shouldEmit) { this.previousValidValue = validatedNewValue; } if (validatedNewValue && validatedNewValue !== this.value) { this.value = validatedNewValue; } } else { this.value = value; } if (origin === "time-picker" || origin === "external") { this.setInputValue(validatedNewValue); } if (shouldEmit) { const changeEvent = this.calciteInputTimePickerChange.emit(); if (changeEvent.defaultPrevented) { this.internalValueChange = false; this.value = previousValue; this.setInputValue(previousValue); this.previousValidValue = previousValue; } else { this.previousValidValue = validatedNewValue; } } }; //-------------------------------------------------------------------------- // // Lifecycle // //-------------------------------------------------------------------------- connectedCallback() { if (this.value) { this.setValue({ value: this.value, origin: "loading" }); } connectLabel(this); } componentDidLoad() { if (this.calciteInputEl.value !== this.value) { this.setInputValue(this.value); } } disconnectedCallback() { disconnectLabel(this); } // -------------------------------------------------------------------------- // // Render Methods // // -------------------------------------------------------------------------- render(): VNode { const { hour, minute, second } = parseTimeString(this.value); const popoverId = `${this.referenceElementId}-popover`; return ( <Host> <div aria-controls={popoverId} aria-haspopup="dialog" aria-label={this.name} aria-owns={popoverId} id={this.referenceElementId} role="combobox" > <calcite-input disabled={this.disabled} icon="clock" label={getLabelText(this)} name={this.name} onCalciteInputBlur={this.calciteInputBlurHandler} onCalciteInputFocus={this.calciteInputFocusHandler} onCalciteInputInput={this.calciteInputInputHandler} ref={this.setCalciteInputEl} scale={this.scale} step={this.step} /> </div> <calcite-popover id={popoverId} label="Time Picker" open={this.active || false} referenceElement={this.referenceElementId} > <calcite-time-picker hour={hour} hour-display-format={this.hourDisplayFormat} intlHour={this.intlHour} intlHourDown={this.intlHourDown} intlHourUp={this.intlHourUp} intlMeridiem={this.intlMeridiem} intlMeridiemDown={this.intlMeridiemDown} intlMeridiemUp={this.intlMeridiemUp} intlMinute={this.intlMinute} intlMinuteDown={this.intlMinuteDown} intlMinuteUp={this.intlMinuteUp} intlSecond={this.intlSecond} intlSecondDown={this.intlSecondDown} intlSecondUp={this.intlSecondUp} minute={minute} scale={this.scale} second={second} step={this.step} /> </calcite-popover> </Host> ); } }
the_stack
import * as coreHttp from "@azure/core-http"; export const DetectRequest: coreHttp.CompositeMapper = { type: { name: "Composite", className: "DetectRequest", modelProperties: { series: { serializedName: "series", required: true, type: { name: "Sequence", element: { type: { name: "Composite", className: "TimeSeriesPoint" } } } }, granularity: { serializedName: "granularity", type: { name: "Enum", allowedValues: [ "yearly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", "microsecond", "none" ] } }, customInterval: { serializedName: "customInterval", type: { name: "Number" } }, period: { serializedName: "period", type: { name: "Number" } }, maxAnomalyRatio: { serializedName: "maxAnomalyRatio", type: { name: "Number" } }, sensitivity: { serializedName: "sensitivity", type: { name: "Number" } } } } }; export const TimeSeriesPoint: coreHttp.CompositeMapper = { type: { name: "Composite", className: "TimeSeriesPoint", modelProperties: { timestamp: { serializedName: "timestamp", type: { name: "DateTime" } }, value: { serializedName: "value", required: true, type: { name: "Number" } } } } }; export const DetectEntireResponse: coreHttp.CompositeMapper = { type: { name: "Composite", className: "DetectEntireResponse", modelProperties: { period: { serializedName: "period", required: true, type: { name: "Number" } }, expectedValues: { serializedName: "expectedValues", required: true, type: { name: "Sequence", element: { type: { name: "Number" } } } }, upperMargins: { serializedName: "upperMargins", required: true, type: { name: "Sequence", element: { type: { name: "Number" } } } }, lowerMargins: { serializedName: "lowerMargins", required: true, type: { name: "Sequence", element: { type: { name: "Number" } } } }, isAnomaly: { serializedName: "isAnomaly", required: true, type: { name: "Sequence", element: { type: { name: "Boolean" } } } }, isNegativeAnomaly: { serializedName: "isNegativeAnomaly", required: true, type: { name: "Sequence", element: { type: { name: "Boolean" } } } }, isPositiveAnomaly: { serializedName: "isPositiveAnomaly", required: true, type: { name: "Sequence", element: { type: { name: "Boolean" } } } } } } }; export const AnomalyDetectorError: coreHttp.CompositeMapper = { type: { name: "Composite", className: "AnomalyDetectorError", modelProperties: { code: { serializedName: "code", type: { name: "String" } }, message: { serializedName: "message", type: { name: "String" } } } } }; export const DetectLastPointResponse: coreHttp.CompositeMapper = { type: { name: "Composite", className: "DetectLastPointResponse", modelProperties: { period: { serializedName: "period", required: true, type: { name: "Number" } }, suggestedWindow: { serializedName: "suggestedWindow", required: true, type: { name: "Number" } }, expectedValue: { serializedName: "expectedValue", required: true, type: { name: "Number" } }, upperMargin: { serializedName: "upperMargin", required: true, type: { name: "Number" } }, lowerMargin: { serializedName: "lowerMargin", required: true, type: { name: "Number" } }, isAnomaly: { serializedName: "isAnomaly", required: true, type: { name: "Boolean" } }, isNegativeAnomaly: { serializedName: "isNegativeAnomaly", required: true, type: { name: "Boolean" } }, isPositiveAnomaly: { serializedName: "isPositiveAnomaly", required: true, type: { name: "Boolean" } } } } }; export const DetectChangePointRequest: coreHttp.CompositeMapper = { type: { name: "Composite", className: "DetectChangePointRequest", modelProperties: { series: { serializedName: "series", required: true, type: { name: "Sequence", element: { type: { name: "Composite", className: "TimeSeriesPoint" } } } }, granularity: { serializedName: "granularity", required: true, type: { name: "Enum", allowedValues: [ "yearly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", "microsecond", "none" ] } }, customInterval: { serializedName: "customInterval", type: { name: "Number" } }, period: { serializedName: "period", type: { name: "Number" } }, stableTrendWindow: { serializedName: "stableTrendWindow", type: { name: "Number" } }, threshold: { serializedName: "threshold", type: { name: "Number" } } } } }; export const DetectChangePointResponse: coreHttp.CompositeMapper = { type: { name: "Composite", className: "DetectChangePointResponse", modelProperties: { period: { serializedName: "period", readOnly: true, type: { name: "Number" } }, isChangePoint: { serializedName: "isChangePoint", type: { name: "Sequence", element: { type: { name: "Boolean" } } } }, confidenceScores: { serializedName: "confidenceScores", type: { name: "Sequence", element: { type: { name: "Number" } } } } } } }; export const ModelInfo: coreHttp.CompositeMapper = { type: { name: "Composite", className: "ModelInfo", modelProperties: { slidingWindow: { serializedName: "slidingWindow", type: { name: "Number" } }, alignPolicy: { serializedName: "alignPolicy", type: { name: "Composite", className: "AlignPolicy" } }, source: { serializedName: "source", required: true, type: { name: "String" } }, startTime: { serializedName: "startTime", required: true, type: { name: "DateTime" } }, endTime: { serializedName: "endTime", required: true, type: { name: "DateTime" } }, displayName: { constraints: { MaxLength: 24 }, serializedName: "displayName", type: { name: "String" } }, status: { serializedName: "status", readOnly: true, type: { name: "Enum", allowedValues: ["CREATED", "RUNNING", "READY", "FAILED"] } }, errors: { serializedName: "errors", readOnly: true, type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorResponse" } } } }, diagnosticsInfo: { serializedName: "diagnosticsInfo", type: { name: "Composite", className: "DiagnosticsInfo" } } } } }; export const AlignPolicy: coreHttp.CompositeMapper = { type: { name: "Composite", className: "AlignPolicy", modelProperties: { alignMode: { serializedName: "alignMode", type: { name: "Enum", allowedValues: ["Inner", "Outer"] } }, fillNAMethod: { serializedName: "fillNAMethod", type: { name: "Enum", allowedValues: [ "Previous", "Subsequent", "Linear", "Zero", "Pad", "NotFill" ] } }, paddingValue: { serializedName: "paddingValue", type: { name: "Number" } } } } }; export const ErrorResponse: coreHttp.CompositeMapper = { type: { name: "Composite", className: "ErrorResponse", modelProperties: { code: { serializedName: "code", required: true, type: { name: "String" } }, message: { serializedName: "message", required: true, type: { name: "String" } } } } }; export const DiagnosticsInfo: coreHttp.CompositeMapper = { type: { name: "Composite", className: "DiagnosticsInfo", modelProperties: { modelState: { serializedName: "modelState", type: { name: "Composite", className: "ModelState" } }, variableStates: { serializedName: "variableStates", type: { name: "Sequence", element: { type: { name: "Composite", className: "VariableState" } } } } } } }; export const ModelState: coreHttp.CompositeMapper = { type: { name: "Composite", className: "ModelState", modelProperties: { epochIds: { serializedName: "epochIds", type: { name: "Sequence", element: { type: { name: "Number" } } } }, trainLosses: { serializedName: "trainLosses", type: { name: "Sequence", element: { type: { name: "Number" } } } }, validationLosses: { serializedName: "validationLosses", type: { name: "Sequence", element: { type: { name: "Number" } } } }, latenciesInSeconds: { serializedName: "latenciesInSeconds", type: { name: "Sequence", element: { type: { name: "Number" } } } } } } }; export const VariableState: coreHttp.CompositeMapper = { type: { name: "Composite", className: "VariableState", modelProperties: { variable: { serializedName: "variable", type: { name: "String" } }, filledNARatio: { constraints: { InclusiveMaximum: 1, InclusiveMinimum: 0 }, serializedName: "filledNARatio", type: { name: "Number" } }, effectiveCount: { serializedName: "effectiveCount", type: { name: "Number" } }, startTime: { serializedName: "startTime", type: { name: "DateTime" } }, endTime: { serializedName: "endTime", type: { name: "DateTime" } }, errors: { serializedName: "errors", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorResponse" } } } } } } }; export const Model: coreHttp.CompositeMapper = { type: { name: "Composite", className: "Model", modelProperties: { modelId: { serializedName: "modelId", required: true, type: { name: "Uuid" } }, createdTime: { serializedName: "createdTime", required: true, type: { name: "DateTime" } }, lastUpdatedTime: { serializedName: "lastUpdatedTime", required: true, type: { name: "DateTime" } }, modelInfo: { serializedName: "modelInfo", type: { name: "Composite", className: "ModelInfo" } } } } }; export const DetectionRequest: coreHttp.CompositeMapper = { type: { name: "Composite", className: "DetectionRequest", modelProperties: { source: { serializedName: "source", required: true, type: { name: "String" } }, startTime: { serializedName: "startTime", required: true, type: { name: "DateTime" } }, endTime: { serializedName: "endTime", required: true, type: { name: "DateTime" } } } } }; export const DetectionResult: coreHttp.CompositeMapper = { type: { name: "Composite", className: "DetectionResult", modelProperties: { resultId: { serializedName: "resultId", required: true, type: { name: "Uuid" } }, summary: { serializedName: "summary", type: { name: "Composite", className: "DetectionResultSummary" } }, results: { serializedName: "results", required: true, type: { name: "Sequence", element: { type: { name: "Composite", className: "AnomalyState" } } } } } } }; export const DetectionResultSummary: coreHttp.CompositeMapper = { type: { name: "Composite", className: "DetectionResultSummary", modelProperties: { status: { serializedName: "status", required: true, type: { name: "Enum", allowedValues: ["CREATED", "RUNNING", "READY", "FAILED"] } }, errors: { serializedName: "errors", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorResponse" } } } }, variableStates: { serializedName: "variableStates", type: { name: "Sequence", element: { type: { name: "Composite", className: "VariableState" } } } }, setupInfo: { serializedName: "setupInfo", type: { name: "Composite", className: "DetectionRequest" } } } } }; export const AnomalyState: coreHttp.CompositeMapper = { type: { name: "Composite", className: "AnomalyState", modelProperties: { timestamp: { serializedName: "timestamp", required: true, type: { name: "DateTime" } }, value: { serializedName: "value", type: { name: "Composite", className: "AnomalyValue" } }, errors: { serializedName: "errors", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorResponse" } } } } } } }; export const AnomalyValue: coreHttp.CompositeMapper = { type: { name: "Composite", className: "AnomalyValue", modelProperties: { contributors: { serializedName: "contributors", type: { name: "Sequence", element: { type: { name: "Composite", className: "AnomalyContributor" } } } }, isAnomaly: { serializedName: "isAnomaly", required: true, type: { name: "Boolean" } }, severity: { constraints: { InclusiveMaximum: 1, InclusiveMinimum: 0 }, serializedName: "severity", required: true, type: { name: "Number" } }, score: { constraints: { InclusiveMaximum: 2, InclusiveMinimum: 0 }, serializedName: "score", type: { name: "Number" } } } } }; export const AnomalyContributor: coreHttp.CompositeMapper = { type: { name: "Composite", className: "AnomalyContributor", modelProperties: { contributionScore: { constraints: { InclusiveMaximum: 2, InclusiveMinimum: 0 }, serializedName: "contributionScore", type: { name: "Number" } }, variable: { serializedName: "variable", type: { name: "String" } } } } }; export const ModelList: coreHttp.CompositeMapper = { type: { name: "Composite", className: "ModelList", modelProperties: { models: { serializedName: "models", required: true, type: { name: "Sequence", element: { type: { name: "Composite", className: "ModelSnapshot" } } } }, currentCount: { serializedName: "currentCount", required: true, type: { name: "Number" } }, maxCount: { serializedName: "maxCount", required: true, type: { name: "Number" } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const ModelSnapshot: coreHttp.CompositeMapper = { type: { name: "Composite", className: "ModelSnapshot", modelProperties: { modelId: { serializedName: "modelId", required: true, type: { name: "Uuid" } }, createdTime: { serializedName: "createdTime", required: true, type: { name: "DateTime" } }, lastUpdatedTime: { serializedName: "lastUpdatedTime", required: true, type: { name: "DateTime" } }, status: { serializedName: "status", required: true, readOnly: true, type: { name: "Enum", allowedValues: ["CREATED", "RUNNING", "READY", "FAILED"] } }, displayName: { serializedName: "displayName", type: { name: "String" } }, variablesCount: { serializedName: "variablesCount", required: true, type: { name: "Number" } } } } }; export const AnomalyDetectorTrainMultivariateModelHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "AnomalyDetectorTrainMultivariateModelHeaders", modelProperties: { location: { serializedName: "location", type: { name: "String" } } } } }; export const AnomalyDetectorDetectAnomalyHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "AnomalyDetectorDetectAnomalyHeaders", modelProperties: { location: { serializedName: "location", type: { name: "String" } } } } }; export const AnomalyDetectorExportModelHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", className: "AnomalyDetectorExportModelHeaders", modelProperties: { contentType: { serializedName: "content-type", type: { name: "String" } } } } };
the_stack
import { flatMap } from '../../util'; import { ISDK } from '../aws-auth'; import { ChangeHotswapImpact, ChangeHotswapResult, establishResourcePhysicalName, HotswapOperation, HotswappableChangeCandidate } from './common'; import { EvaluateCloudFormationTemplate } from './evaluate-cloudformation-template'; /** * Returns `ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT` if the change cannot be short-circuited, * `ChangeHotswapImpact.IRRELEVANT` if the change is irrelevant from a short-circuit perspective * (like a change to CDKMetadata), * or a LambdaFunctionResource if the change can be short-circuited. */ export async function isHotswappableLambdaFunctionChange( logicalId: string, change: HotswappableChangeCandidate, evaluateCfnTemplate: EvaluateCloudFormationTemplate, ): Promise<ChangeHotswapResult> { // if the change is for a Lambda Version, // ignore it by returning an empty hotswap operation - // we will publish a new version when we get to hotswapping the actual Function this Version points to, below // (Versions can't be changed in CloudFormation anyway, they're immutable) if (change.newValue.Type === 'AWS::Lambda::Version') { return ChangeHotswapImpact.IRRELEVANT; } // we handle Aliases specially too if (change.newValue.Type === 'AWS::Lambda::Alias') { return checkAliasHasVersionOnlyChange(change); } const lambdaCodeChange = await isLambdaFunctionCodeOnlyChange(change, evaluateCfnTemplate); if (typeof lambdaCodeChange === 'string') { return lambdaCodeChange; } const functionName = await establishResourcePhysicalName(logicalId, change.newValue.Properties?.FunctionName, evaluateCfnTemplate); if (!functionName) { return ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT; } const functionArn = await evaluateCfnTemplate.evaluateCfnExpression({ 'Fn::Sub': 'arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:' + functionName, }); // find all Lambda Versions that reference this Function const versionsReferencingFunction = evaluateCfnTemplate.findReferencesTo(logicalId) .filter(r => r.Type === 'AWS::Lambda::Version'); // find all Lambda Aliases that reference the above Versions const aliasesReferencingVersions = flatMap(versionsReferencingFunction, v => evaluateCfnTemplate.findReferencesTo(v.LogicalId)); const aliasesNames = await Promise.all(aliasesReferencingVersions.map(a => evaluateCfnTemplate.evaluateCfnExpression(a.Properties?.Name))); return new LambdaFunctionHotswapOperation({ physicalName: functionName, functionArn: functionArn, resource: lambdaCodeChange, publishVersion: versionsReferencingFunction.length > 0, aliasesNames, }); } /** * Returns is a given Alias change is only in the 'FunctionVersion' property, * and `ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT` is the change is for any other property. */ function checkAliasHasVersionOnlyChange(change: HotswappableChangeCandidate): ChangeHotswapResult { for (const updatedPropName in change.propertyUpdates) { if (updatedPropName !== 'FunctionVersion') { return ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT; } } return ChangeHotswapImpact.IRRELEVANT; } /** * Returns `ChangeHotswapImpact.IRRELEVANT` if the change is not for a AWS::Lambda::Function, * but doesn't prevent short-circuiting * (like a change to CDKMetadata resource), * `ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT` if the change is to a AWS::Lambda::Function, * but not only to its Code property, * or a LambdaFunctionCode if the change is to a AWS::Lambda::Function, * and only affects its Code property. */ async function isLambdaFunctionCodeOnlyChange( change: HotswappableChangeCandidate, evaluateCfnTemplate: EvaluateCloudFormationTemplate, ): Promise<LambdaFunctionChange | ChangeHotswapImpact> { const newResourceType = change.newValue.Type; if (newResourceType !== 'AWS::Lambda::Function') { return ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT; } /* * At first glance, we would want to initialize these using the "previous" values (change.oldValue), * in case only one of them changed, like the key, and the Bucket stayed the same. * However, that actually fails for old-style synthesis, which uses CFN Parameters! * Because the names of the Parameters depend on the hash of the Asset, * the Parameters used for the "old" values no longer exist in `assetParams` at this point, * which means we don't have the correct values available to evaluate the CFN expression with. * Fortunately, the diff will always include both the s3Bucket and s3Key parts of the Lambda's Code property, * even if only one of them was actually changed, * which means we don't need the "old" values at all, and we can safely initialize these with just `''`. */ const propertyUpdates = change.propertyUpdates; let code: LambdaFunctionCode | undefined = undefined; let tags: LambdaFunctionTags | undefined = undefined; for (const updatedPropName in propertyUpdates) { const updatedProp = propertyUpdates[updatedPropName]; switch (updatedPropName) { case 'Code': let foundCodeDifference = false; let s3Bucket = '', s3Key = ''; for (const newPropName in updatedProp.newValue) { switch (newPropName) { case 'S3Bucket': foundCodeDifference = true; s3Bucket = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]); break; case 'S3Key': foundCodeDifference = true; s3Key = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue[newPropName]); break; default: return ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT; } } if (foundCodeDifference) { code = { s3Bucket, s3Key, }; } break; case 'Tags': /* * Tag updates are a bit odd; they manifest as two lists, are flagged only as * `isDifferent`, and we have to reconcile them. */ const tagUpdates: { [tag: string]: string | TagDeletion } = {}; if (updatedProp?.isDifferent) { updatedProp.newValue.forEach((tag: CfnDiffTagValue) => { tagUpdates[tag.Key] = tag.Value; }); updatedProp.oldValue.forEach((tag: CfnDiffTagValue) => { if (tagUpdates[tag.Key] === undefined) { tagUpdates[tag.Key] = TagDeletion.DELETE; } }); tags = { tagUpdates }; } break; default: return ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT; } } return code || tags ? { code, tags } : ChangeHotswapImpact.IRRELEVANT; } interface CfnDiffTagValue { readonly Key: string; readonly Value: string; } interface LambdaFunctionCode { readonly s3Bucket: string; readonly s3Key: string; } enum TagDeletion { DELETE = -1, } interface LambdaFunctionTags { readonly tagUpdates: { [tag : string] : string | TagDeletion }; } interface LambdaFunctionChange { readonly code?: LambdaFunctionCode; readonly tags?: LambdaFunctionTags; } interface LambdaFunctionResource { readonly physicalName: string; readonly functionArn: string; readonly resource: LambdaFunctionChange; readonly publishVersion: boolean; readonly aliasesNames: string[]; } class LambdaFunctionHotswapOperation implements HotswapOperation { public readonly service = 'lambda-function'; public readonly resourceNames: string[]; constructor(private readonly lambdaFunctionResource: LambdaFunctionResource) { this.resourceNames = [ `Lambda Function '${lambdaFunctionResource.physicalName}'`, // add Version here if we're publishing a new one ...(lambdaFunctionResource.publishVersion ? [`Lambda Version for Function '${lambdaFunctionResource.physicalName}'`] : []), // add any Aliases that we are hotswapping here ...lambdaFunctionResource.aliasesNames.map(alias => `Lambda Alias '${alias}' for Function '${lambdaFunctionResource.physicalName}'`), ]; } public async apply(sdk: ISDK): Promise<any> { const lambda = sdk.lambda(); const resource = this.lambdaFunctionResource.resource; const operations: Promise<any>[] = []; if (resource.code !== undefined) { const updateFunctionCodePromise = lambda.updateFunctionCode({ FunctionName: this.lambdaFunctionResource.physicalName, S3Bucket: resource.code.s3Bucket, S3Key: resource.code.s3Key, }).promise(); // only if the code changed is there any point in publishing a new Version if (this.lambdaFunctionResource.publishVersion) { // we need to wait for the code update to be done before publishing a new Version await updateFunctionCodePromise; // if we don't wait for the Function to finish updating, // we can get a "The operation cannot be performed at this time. An update is in progress for resource:" // error when publishing a new Version await lambda.waitFor('functionUpdated', { FunctionName: this.lambdaFunctionResource.physicalName, }).promise(); const publishVersionPromise = lambda.publishVersion({ FunctionName: this.lambdaFunctionResource.physicalName, }).promise(); if (this.lambdaFunctionResource.aliasesNames.length > 0) { // we need to wait for the Version to finish publishing const versionUpdate = await publishVersionPromise; for (const alias of this.lambdaFunctionResource.aliasesNames) { operations.push(lambda.updateAlias({ FunctionName: this.lambdaFunctionResource.physicalName, Name: alias, FunctionVersion: versionUpdate.Version, }).promise()); } } else { operations.push(publishVersionPromise); } } else { operations.push(updateFunctionCodePromise); } } if (resource.tags !== undefined) { const tagsToDelete: string[] = Object.entries(resource.tags.tagUpdates) .filter(([_key, val]) => val === TagDeletion.DELETE) .map(([key, _val]) => key); const tagsToSet: { [tag: string]: string } = {}; Object.entries(resource.tags!.tagUpdates) .filter(([_key, val]) => val !== TagDeletion.DELETE) .forEach(([tagName, tagValue]) => { tagsToSet[tagName] = tagValue as string; }); if (tagsToDelete.length > 0) { operations.push(lambda.untagResource({ Resource: this.lambdaFunctionResource.functionArn, TagKeys: tagsToDelete, }).promise()); } if (Object.keys(tagsToSet).length > 0) { operations.push(lambda.tagResource({ Resource: this.lambdaFunctionResource.functionArn, Tags: tagsToSet, }).promise()); } } // run all of our updates in parallel return Promise.all(operations); } }
the_stack
import System from './../util/System' import Integer from './../util/Integer' import Arrays from './../util/Arrays' import Exception from './../Exception' /** * <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p> * * @author Sean Owen */ export default class BitArray /*implements Cloneable*/ { private size: number private bits: Int32Array // public constructor() { // this.size = 0 // this.bits = new Int32Array(1) // } // public constructor(size?: number /*int*/) { // if (undefined === size) { // this.size = 0 // } else { // this.size = size // } // this.bits = this.makeArray(size) // } // For testing only public constructor(size?: number /*int*/, bits?: Int32Array) { if (undefined === size) { this.size = 0 this.bits = new Int32Array(1) } else { this.size = size if (undefined === bits || null === bits) { this.bits = BitArray.makeArray(size) } else { this.bits = bits } } } public getSize(): number /*int*/ { return this.size } public getSizeInBytes(): number /*int*/ { return Math.floor((this.size + 7) / 8) } private ensureCapacity(size: number /*int*/): void { if (size > this.bits.length * 32) { const newBits = BitArray.makeArray(size) System.arraycopy(this.bits, 0, newBits, 0, this.bits.length) this.bits = newBits } } /** * @param i bit to get * @return true iff bit i is set */ public get(i: number /*int*/): boolean { return (this.bits[Math.floor(i / 32)] & (1 << (i & 0x1F))) !== 0 } /** * Sets bit i. * * @param i bit to set */ public set(i: number /*int*/): void { this.bits[Math.floor(i / 32)] |= 1 << (i & 0x1F) } /** * Flips bit i. * * @param i bit to set */ public flip(i: number /*int*/): void { this.bits[Math.floor(i / 32)] ^= 1 << (i & 0x1F) } /** * @param from first bit to check * @return index of first bit that is set, starting from the given index, or size if none are set * at or beyond this given index * @see #getNextUnset(int) */ public getNextSet(from: number /*int*/): number /*int*/ { const size = this.size if (from >= size) { return size } const bits = this.bits let bitsOffset = Math.floor(from / 32) let currentBits = bits[bitsOffset] // mask off lesser bits first currentBits &= ~((1 << (from & 0x1F)) - 1) const length = bits.length while (currentBits === 0) { if (++bitsOffset === length) { return size } currentBits = bits[bitsOffset] } const result = (bitsOffset * 32) + Integer.numberOfTrailingZeros(currentBits) return result > size ? size : result } /** * @param from index to start looking for unset bit * @return index of next unset bit, or {@code size} if none are unset until the end * @see #getNextSet(int) */ public getNextUnset(from: number /*int*/): number /*int*/ { const size = this.size if (from >= size) { return size } const bits = this.bits let bitsOffset = Math.floor(from / 32) let currentBits = ~bits[bitsOffset] // mask off lesser bits first currentBits &= ~((1 << (from & 0x1F)) - 1) const length = bits.length while (currentBits === 0) { if (++bitsOffset === length) { return size } currentBits = ~bits[bitsOffset] } const result = (bitsOffset * 32) + Integer.numberOfTrailingZeros(currentBits) return result > size ? size : result } /** * Sets a block of 32 bits, starting at bit i. * * @param i first bit to set * @param newBits the new value of the next 32 bits. Note again that the least-significant bit * corresponds to bit i, the next-least-significant to i+1, and so on. */ public setBulk(i: number /*int*/, newBits: number /*int*/): void { this.bits[Math.floor(i / 32)] = newBits } /** * Sets a range of bits. * * @param start start of range, inclusive. * @param end end of range, exclusive */ public setRange(start: number /*int*/, end: number /*int*/): void { if (end < start || start < 0 || end > this.size) { throw new Exception(Exception.IllegalArgumentException) } if (end === start) { return } end-- // will be easier to treat this as the last actually set bit -- inclusive const firstInt = Math.floor(start / 32) const lastInt =Math.floor(end / 32) const bits = this.bits for (let i = firstInt; i <= lastInt; i++) { const firstBit = i > firstInt ? 0 : start & 0x1F const lastBit = i < lastInt ? 31 : end & 0x1F // Ones from firstBit to lastBit, inclusive const mask = (2 << lastBit) - (1 << firstBit) bits[i] |= mask } } /** * Clears all bits (sets to false). */ public clear(): void { const max = this.bits.length const bits = this.bits for (let i = 0; i < max; i++) { bits[i] = 0 } } /** * Efficient method to check if a range of bits is set, or not set. * * @param start start of range, inclusive. * @param end end of range, exclusive * @param value if true, checks that bits in range are set, otherwise checks that they are not set * @return true iff all bits are set or not set in range, according to value argument * @throws IllegalArgumentException if end is less than start or the range is not contained in the array */ public isRange(start: number /*int*/, end: number /*int*/, value: boolean): boolean { if (end < start || start < 0 || end > this.size) { throw new Exception(Exception.IllegalArgumentException) } if (end === start) { return true // empty range matches } end-- // will be easier to treat this as the last actually set bit -- inclusive const firstInt = Math.floor(start / 32) const lastInt = Math.floor(end / 32) const bits = this.bits for (let i = firstInt; i <= lastInt; i++) { const firstBit = i > firstInt ? 0 : start & 0x1F const lastBit = i < lastInt ? 31 : end & 0x1F // Ones from firstBit to lastBit, inclusive const mask = (2 << lastBit) - (1 << firstBit) & 0xFFFFFFFF // TYPESCRIPTPORT: & 0xFFFFFFFF added to discard anything after 32 bits, as ES has 53 bits // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (is: that, // equals the mask, or we're looking for 0s and the masked portion is not all 0s if ((bits[i] & mask) !== (value ? mask : 0)) { return false } } return true } public appendBit(bit: boolean): void { this.ensureCapacity(this.size + 1) if (bit) { this.bits[Math.floor(this.size / 32)] |= 1 << (this.size & 0x1F) } this.size++ } /** * Appends the least-significant bits, from value, in order from most-significant to * least-significant. For example, appending 6 bits from 0x000001E will append the bits * 0, 1, 1, 1, 1, 0 in that order. * * @param value {@code int} containing bits to append * @param numBits bits from value to append */ public appendBits(value: number /*int*/, numBits: number /*int*/): void { if (numBits < 0 || numBits > 32) { throw new Exception(Exception.IllegalArgumentException, "Num bits must be between 0 and 32") } this.ensureCapacity(this.size + numBits) const appendBit = this.appendBit for (let numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--) { this.appendBit(((value >> (numBitsLeft - 1)) & 0x01) == 1) } } public appendBitArray(other: BitArray): void { const otherSize = other.size this.ensureCapacity(this.size + otherSize) const appendBit = this.appendBit for (let i = 0; i < otherSize; i++) { this.appendBit(other.get(i)) } } public xor(other: BitArray): void { if (this.size != other.size) { throw new Exception(Exception.IllegalArgumentException, "Sizes don't match") } const bits = this.bits; for (let i = 0, length = bits.length; i < length; i++) { // The last int could be incomplete (i.e. not have 32 bits in // it) but there is no problem since 0 XOR 0 == 0. bits[i] ^= other.bits[i] } } /** * * @param bitOffset first bit to start writing * @param array array to write into. Bytes are written most-significant byte first. This is the opposite * of the internal representation, which is exposed by {@link #getBitArray()} * @param offset position in array to start writing * @param numBytes how many bytes to write */ public toBytes(bitOffset: number /*int*/, array: Uint8Array, offset: number /*int*/, numBytes: number /*int*/): void { for (let i = 0; i < numBytes; i++) { let theByte = 0 for (let j = 0; j < 8; j++) { if (this.get(bitOffset)) { theByte |= 1 << (7 - j) } bitOffset++ } array[offset + i] = /*(byte)*/ theByte } } /** * @return underlying array of ints. The first element holds the first 32 bits, and the least * significant bit is bit 0. */ public getBitArray(): Int32Array { return this.bits } /** * Reverses all bits in the array. */ public reverse(): void { const newBits = new Int32Array(this.bits.length) // reverse all int's first const len = Math.floor((this.size - 1) / 32) const oldBitsLen = len + 1 const bits = this.bits for (let i = 0; i < oldBitsLen; i++) { let x = bits[i] x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1) x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2) x = ((x >> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4) x = ((x >> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8) x = ((x >> 16) & 0x0000ffff) | ((x & 0x0000ffff) << 16) newBits[len - i] = /*(int)*/ x } // now correct the int's if the bit size isn't a multiple of 32 if (this.size !== oldBitsLen * 32) { const leftOffset = oldBitsLen * 32 - this.size; let currentInt = newBits[0] >>> leftOffset for (let i = 1; i < oldBitsLen; i++) { const nextInt = newBits[i] currentInt |= nextInt << (32 - leftOffset) newBits[i - 1] = currentInt currentInt = nextInt >>> leftOffset } newBits[oldBitsLen - 1] = currentInt } this.bits = newBits } private static makeArray(size: number /*int*/): Int32Array { return new Int32Array(Math.floor((size + 31) / 32)) } /*@Override*/ public equals(o: any): boolean { if (!(o instanceof BitArray)) { return false } const other = <BitArray> o return this.size === other.size && Arrays.equals(this.bits, other.bits) } /*@Override*/ public hashCode(): number /*int*/ { return 31 * this.size + Arrays.hashCode(this.bits); } /*@Override*/ public toString(): string { let result = "" for (let i = 0, size = this.size; i < size; i++) { if ((i & 0x07) === 0) { result += " " } result += this.get(i) ? "X" : "." } return result } /*@Override*/ public clone(): BitArray { return new BitArray(this.size, this.bits.slice()) } }
the_stack
import { WeightVectorOption, ErrorCohort, defaultModelAssessmentContext, ModelAssessmentContext } from "@responsible-ai/core-ui"; import { localization } from "@responsible-ai/localization"; import { IChoiceGroupOption, IStackItemStyles, PrimaryButton, ChoiceGroup, Stack, Text } from "office-ui-fabric-react"; import React from "react"; import { PredictionTabKeys } from "../../ErrorAnalysisEnums"; import { HelpMessageDict } from "../../Interfaces/IStringsParam"; import { InspectionView } from "../InspectionView/InspectionView"; import { DataViewKeys, TabularDataView } from "../TabularDataView/TabularDataView"; import { InstanceViewStyles } from "./InstanceView.styles"; export interface ISelectionDetails { selectedAllIndexes: number[]; selectedAllCorrectIndexes: number[]; selectedAllIncorrectIndexes: number[]; selectedIncorrectDatasetIndexes: number[]; selectedCorrectDatasetIndexes: number[]; } export interface IInstanceViewProps { messages?: HelpMessageDict; features: string[]; invokeModel?: (data: any[], abortSignal: AbortSignal) => Promise<any[]>; selectedWeightVector: WeightVectorOption; weightOptions: WeightVectorOption[]; weightLabels: any; onWeightChange: (option: WeightVectorOption) => void; activePredictionTab: PredictionTabKeys; setActivePredictionTab: (key: PredictionTabKeys) => void; customPoints: Array<{ [key: string]: any }>; selectedCohort: ErrorCohort; setWhatIfDatapoint: (index: number) => void; } export interface IInstanceViewState { selectionDetails: ISelectionDetails; } const inspectButtonStyles: IStackItemStyles = { root: { paddingRight: 20 } }; enum SelectionType { CorrectSelectionType = "CorrectSelectionType", IncorrectSelectionType = "IncorrectSelectionType", AllSelectionType = "AllSelectionType" } export class InstanceView extends React.Component< IInstanceViewProps, IInstanceViewState > { public static contextType = ModelAssessmentContext; public context: React.ContextType<typeof ModelAssessmentContext> = defaultModelAssessmentContext; private choiceItems: IChoiceGroupOption[] = []; public constructor(props: IInstanceViewProps) { super(props); this.state = { selectionDetails: { selectedAllCorrectIndexes: [], selectedAllIncorrectIndexes: [], selectedAllIndexes: [], selectedCorrectDatasetIndexes: [], selectedIncorrectDatasetIndexes: [] } }; const classNames = InstanceViewStyles(); this.choiceItems.push({ key: PredictionTabKeys.CorrectPredictionTab, onRenderLabel: this.onRenderLabel(SelectionType.CorrectSelectionType), styles: { root: classNames.choiceItemRootStyle }, text: localization.ErrorAnalysis.correctPrediction }); this.choiceItems.push({ key: PredictionTabKeys.IncorrectPredictionTab, onRenderLabel: this.onRenderLabel(SelectionType.IncorrectSelectionType), styles: { root: classNames.choiceItemRootStyle }, text: localization.ErrorAnalysis.incorrectPrediction }); this.choiceItems.push({ key: PredictionTabKeys.AllSelectedTab, onRenderLabel: this.onRenderLabel(SelectionType.AllSelectionType), styles: { root: classNames.choiceItemRootStyle }, text: localization.ErrorAnalysis.allSelected }); this.choiceItems.push({ key: PredictionTabKeys.WhatIfDatapointsTab, styles: { root: classNames.choiceItemRootStyle }, text: localization.ErrorAnalysis.whatIfDatapoints }); } public render(): React.ReactNode { const classNames = InstanceViewStyles(); if (this.props.activePredictionTab === PredictionTabKeys.InspectionTab) { return ( <div className={classNames.frame}> <InspectionView features={this.context.modelMetadata.featureNames} jointDataset={this.context.jointDataset} metadata={this.context.modelMetadata} selectedCohort={this.props.selectedCohort} messages={this.props.messages} inspectedIndexes={this.state.selectionDetails.selectedAllIndexes} selectedWeightVector={this.props.selectedWeightVector} weightOptions={this.props.weightOptions} weightLabels={this.props.weightLabels} invokeModel={this.props.invokeModel} onWeightChange={this.props.onWeightChange} /> </div> ); } return ( <div className={classNames.frame}> <Stack> <Stack horizontal horizontalAlign="space-between"> <Stack.Item align="start"> <ChoiceGroup selectedKey={this.props.activePredictionTab} onChange={this.handlePredictionTabClick.bind(this)} styles={{ flexContainer: classNames.choiceGroupContainerStyle }} options={this.choiceItems} /> </Stack.Item> <Stack.Item align="end" styles={inspectButtonStyles}> <PrimaryButton text={localization.ErrorAnalysis.InstanceView.inspect} onClick={this.inspect.bind(this)} allowDisabledFocus disabled={false} checked={false} /> </Stack.Item> </Stack> </Stack> {this.props.activePredictionTab === PredictionTabKeys.CorrectPredictionTab && ( <div className="tabularDataView"> <TabularDataView features={this.context.modelMetadata.featureNames} jointDataset={this.context.jointDataset} messages={this.props.messages} dataView={DataViewKeys.CorrectInstances} selectedIndexes={ this.state.selectionDetails.selectedCorrectDatasetIndexes } setSelectedIndexes={this.setCorrectSelectedIndexes.bind(this)} selectedCohort={this.props.selectedCohort} setWhatIfDatapoint={this.props.setWhatIfDatapoint} /> </div> )} {this.props.activePredictionTab === PredictionTabKeys.IncorrectPredictionTab && ( <div className="tabularDataView"> <TabularDataView features={this.context.modelMetadata.featureNames} jointDataset={this.context.jointDataset} messages={this.props.messages} dataView={DataViewKeys.IncorrectInstances} selectedIndexes={ this.state.selectionDetails.selectedIncorrectDatasetIndexes } setSelectedIndexes={this.setIncorrectSelectedIndexes.bind(this)} selectedCohort={this.props.selectedCohort} setWhatIfDatapoint={this.props.setWhatIfDatapoint} /> </div> )} {this.props.activePredictionTab === PredictionTabKeys.AllSelectedTab && ( <div className="tabularDataView"> <TabularDataView features={this.context.modelMetadata.featureNames} jointDataset={this.context.jointDataset} messages={this.props.messages} dataView={DataViewKeys.SelectedInstances} setSelectedIndexes={this.updateAllSelectedIndexes.bind(this)} selectedIndexes={this.state.selectionDetails.selectedAllIndexes} allSelectedIndexes={ this.state.selectionDetails.selectedAllIndexes } selectedCohort={this.props.selectedCohort} setWhatIfDatapoint={this.props.setWhatIfDatapoint} /> </div> )} {this.props.activePredictionTab === PredictionTabKeys.WhatIfDatapointsTab && ( <div className="tabularDataView"> <TabularDataView features={this.context.modelMetadata.featureNames} jointDataset={this.context.jointDataset} messages={this.props.messages} customPoints={this.props.customPoints} dataView={DataViewKeys.SelectedInstances} setSelectedIndexes={(_: number[]): void => { // do nothing. }} selectedIndexes={[]} allSelectedIndexes={[]} selectedCohort={this.props.selectedCohort} setWhatIfDatapoint={(): void => { // do nothing. }} /> </div> )} </div> ); } private handlePredictionTabClick( _?: React.FormEvent<HTMLElement | HTMLInputElement>, option?: IChoiceGroupOption ): void { if (option) { const predictionTabClickFunc = ( state: Readonly<IInstanceViewState>, props: Readonly<IInstanceViewProps> ): IInstanceViewState => { const selectionDetails = state.selectionDetails; let selectedCorrectIndexes = selectionDetails.selectedCorrectDatasetIndexes; let selectedIncorrectIndexes = selectionDetails.selectedIncorrectDatasetIndexes; const selectedAllIndexes = [...selectionDetails.selectedAllIndexes]; // If going from AllSelectedTab, need to update the other arrays if (props.activePredictionTab === PredictionTabKeys.AllSelectedTab) { selectedCorrectIndexes = selectedCorrectIndexes.filter((index) => selectedAllIndexes.includes(index) ); selectedIncorrectIndexes = selectedIncorrectIndexes.filter((index) => selectedAllIndexes.includes(index) ); } this.props.setActivePredictionTab(PredictionTabKeys[option.key]); return { selectionDetails: { selectedAllCorrectIndexes: selectedCorrectIndexes, selectedAllIncorrectIndexes: selectedIncorrectIndexes, selectedAllIndexes, selectedCorrectDatasetIndexes: selectedCorrectIndexes, selectedIncorrectDatasetIndexes: selectedIncorrectIndexes } }; }; this.setState(predictionTabClickFunc); } } private inspect(): void { this.props.setActivePredictionTab(PredictionTabKeys.InspectionTab); } private setCorrectSelectedIndexes(indexes: number[]): void { const reloadDataFunc = ( state: Readonly<IInstanceViewState> ): IInstanceViewState => { const selectionDetails = state.selectionDetails; const selectedCorrectIndexes = indexes; const selectedIncorrectIndexes = selectionDetails.selectedIncorrectDatasetIndexes; const selectedIndexes = [ ...selectedCorrectIndexes, ...selectedIncorrectIndexes ]; return { selectionDetails: { selectedAllCorrectIndexes: selectedCorrectIndexes, selectedAllIncorrectIndexes: selectedIncorrectIndexes, selectedAllIndexes: selectedIndexes, selectedCorrectDatasetIndexes: selectedCorrectIndexes, selectedIncorrectDatasetIndexes: selectedIncorrectIndexes } }; }; this.setState(reloadDataFunc); } private setIncorrectSelectedIndexes(indexes: number[]): void { const reloadDataFunc = ( state: Readonly<IInstanceViewState> ): IInstanceViewState => { const selectionDetails = state.selectionDetails; const selectedCorrectIndexes = selectionDetails.selectedCorrectDatasetIndexes; const selectedIncorrectIndexes = indexes; const selectedIndexes = [ ...selectedCorrectIndexes, ...selectedIncorrectIndexes ]; return { selectionDetails: { selectedAllCorrectIndexes: selectedCorrectIndexes, selectedAllIncorrectIndexes: selectedIncorrectIndexes, selectedAllIndexes: selectedIndexes, selectedCorrectDatasetIndexes: selectedCorrectIndexes, selectedIncorrectDatasetIndexes: selectedIncorrectIndexes } }; }; this.setState(reloadDataFunc); } private updateAllSelectedIndexes(indexes: number[]): void { const reloadDataFunc = ( state: Readonly<IInstanceViewState> ): IInstanceViewState => { const selectionDetails = state.selectionDetails; const correctDatasetIndexes = selectionDetails.selectedCorrectDatasetIndexes.filter((value) => indexes.includes(value) ); const incorrectDatasetIndexes = selectionDetails.selectedIncorrectDatasetIndexes.filter((value) => indexes.includes(value) ); return { selectionDetails: { selectedAllCorrectIndexes: correctDatasetIndexes, selectedAllIncorrectIndexes: incorrectDatasetIndexes, selectedAllIndexes: indexes, selectedCorrectDatasetIndexes: selectionDetails.selectedCorrectDatasetIndexes, selectedIncorrectDatasetIndexes: selectionDetails.selectedIncorrectDatasetIndexes } }; }; this.setState(reloadDataFunc); } private onRenderLabel = (type: SelectionType) => (p: IChoiceGroupOption | undefined): JSX.Element => { const classNames = InstanceViewStyles(); let selectionText = ""; switch (type) { case SelectionType.AllSelectionType: { selectionText = localization.formatString( localization.ErrorAnalysis.InstanceView.selection, this.state.selectionDetails.selectedAllIndexes.length ); break; } case SelectionType.CorrectSelectionType: { let countCorrect: number; if ( this.props.activePredictionTab === PredictionTabKeys.AllSelectedTab ) { countCorrect = this.state.selectionDetails.selectedAllCorrectIndexes.length; } else { countCorrect = this.state.selectionDetails.selectedCorrectDatasetIndexes.length; } selectionText = localization.formatString( localization.ErrorAnalysis.InstanceView.selection, countCorrect ); break; } case SelectionType.IncorrectSelectionType: { let countIncorrect: number; if ( this.props.activePredictionTab === PredictionTabKeys.AllSelectedTab ) { countIncorrect = this.state.selectionDetails.selectedAllIncorrectIndexes.length; } else { countIncorrect = this.state.selectionDetails.selectedIncorrectDatasetIndexes .length; } selectionText = localization.formatString( localization.ErrorAnalysis.InstanceView.selection, countIncorrect ); break; } default: break; } const stackItemStyles: IStackItemStyles = { root: classNames.stackItemsStyle }; const textStyle = { root: classNames.selectedTextStyle }; return ( <Stack> <Stack.Item align="start"> <span id={p?.labelId} className="ms-ChoiceFieldLabel"> {p?.text} </span> </Stack.Item> <Stack.Item align="start" styles={stackItemStyles}> <Text variant="small" styles={textStyle}> {selectionText} </Text> </Stack.Item> </Stack> ); }; }
the_stack
import { Inject, Injectable, Optional } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent, HttpParameterCodec } from '@angular/common/http'; import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; import { LeaveRequest } from '../model/models'; import { LeaveRequestWithRelations } from '../model/models'; import { LoopbackCount } from '../model/models'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; @Injectable({ providedIn: 'root' }) export class LeaveRequestControllerService { protected basePath = 'http://localhost:3000'; public defaultHeaders = new HttpHeaders(); public configuration = new Configuration(); public encoder: HttpParameterCodec; constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { if (typeof basePath !== 'string') { basePath = this.basePath; } this.configuration.basePath = basePath; } this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); } private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { if (typeof value === "object" && value instanceof Date === false) { httpParams = this.addToHttpParamsRecursive(httpParams, value); } else { httpParams = this.addToHttpParamsRecursive(httpParams, value, key); } return httpParams; } private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { if (value == null) { return httpParams; } if (typeof value === "object") { if (Array.isArray(value)) { (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); } else if (value instanceof Date) { if (key != null) { httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); } else { throw Error("key may not be null if value is Date"); } } else { Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( httpParams, value[k], key != null ? `${key}.${k}` : k)); } } else if (key != null) { httpParams = httpParams.append(key, value); } else { throw Error("key may not be null if value is not object or array"); } return httpParams; } /** * @param where * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerCount(where?: { [key: string]: object; }, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<LoopbackCount>; public leaveRequestControllerCount(where?: { [key: string]: object; }, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<LoopbackCount>>; public leaveRequestControllerCount(where?: { [key: string]: object; }, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<LoopbackCount>>; public leaveRequestControllerCount(where?: { [key: string]: object; }, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { let queryParameters = new HttpParams({encoder: this.encoder}); if (where !== undefined && where !== null) { queryParameters = this.addToHttpParams(queryParameters, <any>where, 'where'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.get<LoopbackCount>(`${this.configuration.basePath}/leave-requests/count`, { params: queryParameters, responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param requestBody * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerCreate(requestBody?: { [key: string]: object; }, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<LeaveRequest>; public leaveRequestControllerCreate(requestBody?: { [key: string]: object; }, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<LeaveRequest>>; public leaveRequestControllerCreate(requestBody?: { [key: string]: object; }, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<LeaveRequest>>; public leaveRequestControllerCreate(requestBody?: { [key: string]: object; }, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.post<LeaveRequest>(`${this.configuration.basePath}/leave-requests`, requestBody, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param id * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerDeleteById(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<any>; public leaveRequestControllerDeleteById(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<HttpResponse<any>>; public leaveRequestControllerDeleteById(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<HttpEvent<any>>; public leaveRequestControllerDeleteById(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling leaveRequestControllerDeleteById.'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.delete<any>(`${this.configuration.basePath}/leave-requests/${encodeURIComponent(String(id))}`, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param filter * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerFind(filter?: object, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Array<LeaveRequestWithRelations>>; public leaveRequestControllerFind(filter?: object, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Array<LeaveRequestWithRelations>>>; public leaveRequestControllerFind(filter?: object, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Array<LeaveRequestWithRelations>>>; public leaveRequestControllerFind(filter?: object, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { let queryParameters = new HttpParams({encoder: this.encoder}); if (filter !== undefined && filter !== null) { queryParameters = this.addToHttpParams(queryParameters, <any>filter, 'filter'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.get<Array<LeaveRequestWithRelations>>(`${this.configuration.basePath}/leave-requests`, { params: queryParameters, responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param patientId * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerFindAllByPatientId(patientId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<LeaveRequestWithRelations>; public leaveRequestControllerFindAllByPatientId(patientId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<LeaveRequestWithRelations>>; public leaveRequestControllerFindAllByPatientId(patientId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<LeaveRequestWithRelations>>; public leaveRequestControllerFindAllByPatientId(patientId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { if (patientId === null || patientId === undefined) { throw new Error('Required parameter patientId was null or undefined when calling leaveRequestControllerFindAllByPatientId.'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.get<LeaveRequestWithRelations>(`${this.configuration.basePath}/leave-requests/patient/${encodeURIComponent(String(patientId))}`, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param id * @param filter * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerFindById(id: string, filter?: object, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<LeaveRequestWithRelations>; public leaveRequestControllerFindById(id: string, filter?: object, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<LeaveRequestWithRelations>>; public leaveRequestControllerFindById(id: string, filter?: object, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<LeaveRequestWithRelations>>; public leaveRequestControllerFindById(id: string, filter?: object, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling leaveRequestControllerFindById.'); } let queryParameters = new HttpParams({encoder: this.encoder}); if (filter !== undefined && filter !== null) { queryParameters = this.addToHttpParams(queryParameters, <any>filter, 'filter'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.get<LeaveRequestWithRelations>(`${this.configuration.basePath}/leave-requests/${encodeURIComponent(String(id))}`, { params: queryParameters, responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param token * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerFindByToken(token: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<LeaveRequestWithRelations>; public leaveRequestControllerFindByToken(token: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<LeaveRequestWithRelations>>; public leaveRequestControllerFindByToken(token: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<LeaveRequestWithRelations>>; public leaveRequestControllerFindByToken(token: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { if (token === null || token === undefined) { throw new Error('Required parameter token was null or undefined when calling leaveRequestControllerFindByToken.'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.get<LeaveRequestWithRelations>(`${this.configuration.basePath}/leave-requests/token/${encodeURIComponent(String(token))}`, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param id * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerGetLeaveRequestsByPatientId(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<LeaveRequestWithRelations>; public leaveRequestControllerGetLeaveRequestsByPatientId(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<LeaveRequestWithRelations>>; public leaveRequestControllerGetLeaveRequestsByPatientId(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<LeaveRequestWithRelations>>; public leaveRequestControllerGetLeaveRequestsByPatientId(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling leaveRequestControllerGetLeaveRequestsByPatientId.'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.get<LeaveRequestWithRelations>(`${this.configuration.basePath}/patients/${encodeURIComponent(String(id))}/leaveRequests`, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param id * @param requestBody * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerReplaceById(id: string, requestBody?: { [key: string]: object; }, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<any>; public leaveRequestControllerReplaceById(id: string, requestBody?: { [key: string]: object; }, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<HttpResponse<any>>; public leaveRequestControllerReplaceById(id: string, requestBody?: { [key: string]: object; }, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<HttpEvent<any>>; public leaveRequestControllerReplaceById(id: string, requestBody?: { [key: string]: object; }, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling leaveRequestControllerReplaceById.'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.put<any>(`${this.configuration.basePath}/leave-requests/${encodeURIComponent(String(id))}`, requestBody, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param token * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerSetAtHome(token: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<any>; public leaveRequestControllerSetAtHome(token: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<HttpResponse<any>>; public leaveRequestControllerSetAtHome(token: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<HttpEvent<any>>; public leaveRequestControllerSetAtHome(token: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable<any> { if (token === null || token === undefined) { throw new Error('Required parameter token was null or undefined when calling leaveRequestControllerSetAtHome.'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.put<any>(`${this.configuration.basePath}/leave-requests/token/${encodeURIComponent(String(token))}/set-at-home`, null, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param token * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerSetOutOfHome(token: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<any>; public leaveRequestControllerSetOutOfHome(token: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<HttpResponse<any>>; public leaveRequestControllerSetOutOfHome(token: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<HttpEvent<any>>; public leaveRequestControllerSetOutOfHome(token: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable<any> { if (token === null || token === undefined) { throw new Error('Required parameter token was null or undefined when calling leaveRequestControllerSetOutOfHome.'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.put<any>(`${this.configuration.basePath}/leave-requests/token/${encodeURIComponent(String(token))}/set-out-home`, null, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param where * @param requestBody * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerUpdateAll(where?: { [key: string]: object; }, requestBody?: { [key: string]: object; }, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<LoopbackCount>; public leaveRequestControllerUpdateAll(where?: { [key: string]: object; }, requestBody?: { [key: string]: object; }, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<LoopbackCount>>; public leaveRequestControllerUpdateAll(where?: { [key: string]: object; }, requestBody?: { [key: string]: object; }, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<LoopbackCount>>; public leaveRequestControllerUpdateAll(where?: { [key: string]: object; }, requestBody?: { [key: string]: object; }, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> { let queryParameters = new HttpParams({encoder: this.encoder}); if (where !== undefined && where !== null) { queryParameters = this.addToHttpParams(queryParameters, <any>where, 'where'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ 'application/json' ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.patch<LoopbackCount>(`${this.configuration.basePath}/leave-requests`, requestBody, { params: queryParameters, responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * @param id * @param requestBody * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public leaveRequestControllerUpdateById(id: string, requestBody?: { [key: string]: object; }, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<any>; public leaveRequestControllerUpdateById(id: string, requestBody?: { [key: string]: object; }, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<HttpResponse<any>>; public leaveRequestControllerUpdateById(id: string, requestBody?: { [key: string]: object; }, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined}): Observable<HttpEvent<any>>; public leaveRequestControllerUpdateById(id: string, requestBody?: { [key: string]: object; }, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined}): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling leaveRequestControllerUpdateById.'); } let headers = this.defaultHeaders; let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; if (httpHeaderAcceptSelected === undefined) { // to determine the Accept header const httpHeaderAccepts: string[] = [ ]; httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); } if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } let responseType: 'text' | 'json' = 'json'; if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { responseType = 'text'; } return this.httpClient.patch<any>(`${this.configuration.basePath}/leave-requests/${encodeURIComponent(String(id))}`, requestBody, { responseType: <any>responseType, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } }
the_stack
import { combineLatest, from, Subscription } from 'rxjs' import { concatMap, filter, map, startWith, switchMap, distinctUntilChanged, debounceTime } from 'rxjs/operators' import * as sourcegraph from 'sourcegraph' import { getCommitCoverage, getTreeCoverage, Service } from './api' import { codecovToDecorations } from './decoration' import { createGraphViewProvider } from './insights' import { getCommitCoverageRatio, getFileCoverageRatios, getFileLineCoverage } from './model' import { configurationChanges, Endpoint, resolveEndpoint, resolveSettings, Settings, InsightSettings } from './settings' import { codecovParamsForRepositoryCommit, resolveDocumentURI, ResolvedRootURI, resolveRootURI } from './uri' const decorationType = sourcegraph.app.createDecorationType && sourcegraph.app.createDecorationType() // Check if the Sourcegraph instance supports status bar items (minimum Sourcegraph version 3.26) const supportsStatusBarAPI = !!sourcegraph.app.createStatusBarItemType as boolean const statusBarItemType = sourcegraph.app.createStatusBarItemType && sourcegraph.app.createStatusBarItemType() /** Entrypoint for the Codecov Sourcegraph extension. */ export function activate( context: sourcegraph.ExtensionContext = { subscriptions: new Subscription(), } ): void { /** * An Observable that emits the active window's visible view components * when the active window or its view components change. */ const editorsChanges = sourcegraph.app.activeWindowChanges ? from(sourcegraph.app.activeWindowChanges).pipe( filter( (activeWindow): activeWindow is Exclude<typeof activeWindow, undefined> => activeWindow !== undefined ), switchMap(activeWindow => from(activeWindow.activeViewComponentChanges).pipe(map(() => activeWindow.visibleViewComponents)) ) // Backcompat: rely on onDidOpenTextDocument if the extension host doesn't support activeWindowChanges / activeViewComponentChanges ) : from(sourcegraph.workspace.onDidOpenTextDocument).pipe( map(() => (sourcegraph.app.activeWindow && sourcegraph.app.activeWindow.visibleViewComponents) || []) ) // When the configuration or current file changes, publish new decorations. // // TODO: Unpublish decorations on previously (but not currently) open files when settings changes, to avoid a // brief flicker of the old state when the file is reopened. async function decorate(settings: Readonly<Settings>, editors: sourcegraph.ViewComponent[]): Promise<void> { const resolvedSettings = resolveSettings(settings) for (const editor of editors) { if (editor.type !== 'CodeEditor') { continue } const decorations = await getFileLineCoverage( resolveDocumentURI(editor.document.uri), resolvedSettings['codecov.endpoints'][0], sourcegraph ) if (!decorations) { continue } editor.setDecorations(decorationType, codecovToDecorations(settings, decorations)) } } context.subscriptions.add( combineLatest([configurationChanges, editorsChanges]) .pipe( concatMap(async ([settings, editors]) => { try { await decorate(settings, editors) } catch (err) { console.error('Codecov: decoration error', err) } }) ) .subscribe() ) // Set context values referenced in template expressions in the extension manifest (e.g., to interpolate "N" in // the "Coverage: N%" button label). // // The context only needs to be updated when the endpoints configuration changes. async function updateContext( endpoints: readonly Endpoint[] | undefined, roots: readonly sourcegraph.WorkspaceRoot[], editors: sourcegraph.ViewComponent[] ): Promise<void> { // Get the current repository. Sourcegraph 3.0-preview exposes sourcegraph.workspace.roots, but earlier // versions do not. let uri: string if (roots && roots.length > 0) { uri = roots[0].uri.toString() } else if (editors.length > 0) { const editor = editors[0] if (editor.type !== 'CodeEditor') { return } uri = editor.document.uri } else { return } const lastURI = resolveRootURI(uri) const endpoint = resolveEndpoint(endpoints) const context: { [key: string]: string | number | boolean | null } = {} const p = codecovParamsForRepositoryCommit(lastURI, sourcegraph) const repoURL = `${p.baseURL || 'https://codecov.io'}/${p.service}/${p.owner}/${p.repo}` context['codecov.repoURL'] = repoURL const baseFileURL = `${repoURL}/src/${p.sha}` context['codecov.commitURL'] = `${repoURL}/commit/${p.sha}` try { // Store overall commit coverage ratio. const commitCoverage = await getCommitCoverageRatio(lastURI, endpoint, sourcegraph) context['codecov.commitCoverage'] = commitCoverage ? commitCoverage.toFixed(1) : null // Store coverage ratio (and Codecov report URL) for each file at this commit so that // template strings in contributions can refer to these values. const fileRatios = await getFileCoverageRatios(lastURI, endpoint, sourcegraph) if (fileRatios) { for (const [path, ratio] of Object.entries(fileRatios)) { const uri = `git://${lastURI.repo}?${lastURI.rev}#${path}` context[`codecov.coverageRatio.${uri}`] = ratio.toFixed(0) context[`codecov.fileURL.${uri}`] = `${baseFileURL}/${path}` } } } catch (err) { console.error('Error loading Codecov file coverage:', err) } sourcegraph.internal.updateContext(context) } async function setStatusBars( endpoints: readonly Endpoint[] | undefined, editors: sourcegraph.ViewComponent[] ): Promise<void> { if (supportsStatusBarAPI) { /** * Keys: repo + revision separated, repo: "sourcegraph/sourcegraph" + revision: "1234" => "sourcegraph/sourcegraph1234" * Values: resolved root uri * Used to find all unique pairs of repo + revision across editors */ const resolvedRootURIs = new Map<string, ResolvedRootURI>() for (const editor of editors) { if (editor.type === 'CodeEditor') { const { repo, rev } = resolveRootURI(editor.document.uri) resolvedRootURIs.set(repo + rev, { repo, rev }) } } // Fetch data const endpoint = resolveEndpoint(endpoints) const fileRatioByURI = new Map<string, { fileRatio: string; fileURL: string }>() const results = await Promise.allSettled( [...resolvedRootURIs].map(async ([, resolvedRootURI]) => ({ resolvedRootURI, fileRatios: await getFileCoverageRatios(resolvedRootURI, endpoint, sourcegraph), })) ) for (const result of results) { if (result.status === 'fulfilled') { const { resolvedRootURI, fileRatios } = result.value const p = codecovParamsForRepositoryCommit(resolvedRootURI, sourcegraph) const repoURL = `${p.baseURL || 'https://codecov.io'}/${p.service}/${p.owner}/${p.repo}` if (fileRatios) { for (const [path, ratio] of Object.entries(fileRatios)) { // Convert relative paths to URIs const uri = `git://${resolvedRootURI.repo}?${resolvedRootURI.rev}#${path}` const baseFileURL = `${repoURL}/src/${p.sha}` fileRatioByURI.set(uri, { fileRatio: ratio.toFixed(0), fileURL: `${baseFileURL}/${path}` }) } } } } // Set status bars for (const editor of editors) { if (editor.type === 'CodeEditor') { const ratio = fileRatioByURI.get(editor.document.uri) if (ratio) { editor.setStatusBarItem(statusBarItemType, { text: `Code Coverage: ${ratio.fileRatio}%`, command: { id: 'open', args: [ratio.fileURL] }, }) } } } } } // Update the context when the configuration, workspace roots or active editors change. context.subscriptions.add( combineLatest([ configurationChanges.pipe(map(settings => settings['codecov.endpoints'])), from( // Backcompat: rely on onDidChangeRoots if the extension host doesn't support rootChanges. sourcegraph.workspace.rootChanges || sourcegraph.workspace.onDidChangeRoots ).pipe( map(() => sourcegraph.workspace.roots), startWith(sourcegraph.workspace.roots) ), editorsChanges, ]) .pipe( // Debounce to avoid doing duplicate work for intermediate states // for views with multiple editors added sequentially (e.g. commit page, PR) debounceTime(30), concatMap(async ([endpoints, roots, editors]) => { try { await setStatusBars(endpoints, editors) } catch (err) { console.error('Codecov: error setting status bars', err) } try { // The commit data used for `updateContext` should be cached if Status Bar API is supported await updateContext(endpoints, roots, editors) } catch (err) { console.error('Codecov: error updating context', err) } }) ) .subscribe() ) sourcegraph.commands.registerCommand('codecov.setupEnterprise', async () => { const endpoint = resolveEndpoint(sourcegraph.configuration.get<Settings>().get('codecov.endpoints')) if (!sourcegraph.app.activeWindow) { throw new Error('To set a Codecov Endpoint, navigate to a file and then re-run this command.') } const service = await sourcegraph.app.activeWindow.showInputBox({ prompt: 'Version control type (gh/ghe/bb/gl):', value: endpoint.service || '', }) const url = await sourcegraph.app.activeWindow.showInputBox({ prompt: 'Codecov endpoint:', value: endpoint.url || '', }) if (url !== undefined && service !== undefined) { // TODO: Only supports setting the token of the first API endpoint. return sourcegraph.configuration .get<Settings>() .update('codecov.endpoints', [{ ...endpoint, url, service: service as Service }]) } }) // Handle the "Set Codecov API token" command (show the user a prompt for their token, and save // their input to settings). sourcegraph.commands.registerCommand('codecov.setAPIToken', async () => { const endpoint = resolveEndpoint(sourcegraph.configuration.get<Settings>().get('codecov.endpoints')) if (!sourcegraph.app.activeWindow) { throw new Error('To set a Codecov API token, navigate to a file and then re-run this command.') } const token = await sourcegraph.app.activeWindow.showInputBox({ prompt: `Codecov API token (for ${endpoint.url}):`, value: endpoint.token || undefined, }) if (token !== undefined) { // TODO: Only supports setting the token of the first API endpoint. return sourcegraph.configuration.get<Settings>().update('codecov.endpoints', [{ ...endpoint, token }]) } }) // Experimental: Show graphs on repository pages if (sourcegraph.app.registerViewProvider) { const graphTypes: ['icicle', 'sunburst', 'tree', 'pie'] = ['icicle', 'sunburst', 'tree', 'pie'] for (const graphType of graphTypes) { let subscription: sourcegraph.Unsubscribable = new Subscription() context.subscriptions.add( configurationChanges .pipe( map((settings): boolean => settings[`codecov.insight.${graphType}` as keyof InsightSettings]), distinctUntilChanged() ) .subscribe(enabled => { if (enabled) { subscription = sourcegraph.app.registerViewProvider( `codecov.${graphType}`, createGraphViewProvider(graphType) ) context.subscriptions.add(subscription) } else { subscription.unsubscribe() } }) ) } } // Experimental: file decorations. Check if the Sourcegraph instance supports // file decoration providers (minimum Sourcegraph version 3.23) if (sourcegraph.app.registerFileDecorationProvider) { function createFileDecoration(uri: string, ratio: number, settings: Settings): sourcegraph.FileDecoration { const after = { contentText: `${ratio}%`, hoverMessage: `Codecov: ${ratio}% covered`, } return { uri, after, meter: { value: ratio, hoverMessage: `Codecov: ${ratio}% covered`, min: 0, max: 100, low: settings['codecov.fileDecorations.low'], high: settings['codecov.fileDecorations.high'], optimum: settings['codecov.fileDecorations.optimum'], }, } } context.subscriptions.add( sourcegraph.app.registerFileDecorationProvider({ provideFileDecorations: async ({ files, uri }) => { const settings = resolveSettings(sourcegraph.configuration.get<Partial<Settings>>().value) if (!settings['codecov.fileDecorations.show']) { return [] } const { repo, rev } = resolveDocumentURI(uri) const apiParams = codecovParamsForRepositoryCommit({ repo, rev }, sourcegraph) // Fetch commit coverage to get ratio for files, tree coverage to get ratio for directories const nonDirectoryFiles = files.filter(file => !file.isDirectory) const directories = files.filter(file => file.isDirectory) const [commitCoverage, ...treeCoverages] = await Promise.allSettled([ getCommitCoverage(apiParams), ...directories.map(async (dir, i) => { const treeCoverage = await getTreeCoverage({ ...apiParams, path: dir.path }) return { treeCoverage, directory: directories[i] } }), ]) // Iterate over files and get value from commit coverage to construct file decorations const fileDecorations: sourcegraph.FileDecoration[] = [] if (commitCoverage.status === 'fulfilled' && commitCoverage.value) { const { files: reportFiles } = commitCoverage.value.commit.report for (const file of nonDirectoryFiles) { const report = reportFiles[file.path] if (!report) { continue } const ratio = parseInt(report.t.c, 10) fileDecorations.push(createFileDecoration(file.uri, ratio, settings)) } } // Iterate over tree coverage results to construct directory decorations const directoryDecorations: sourcegraph.FileDecoration[] = [] for (const result of treeCoverages) { if (result.status === 'rejected') { continue } const { treeCoverage, directory } = result.value if (!treeCoverage) { continue } const ratio = parseInt(treeCoverage.commit.folder_totals.coverage, 10) directoryDecorations.push(createFileDecoration(directory.uri, ratio, settings)) } return [...fileDecorations, ...directoryDecorations] }, }) ) } }
the_stack
module WinJSTests { "use strict"; var ITEMS_COUNT = 5; var ListView = <typeof WinJS.UI.PrivateListView> WinJS.UI.ListView; function getDataSource(count = ITEMS_COUNT) { var rawData = []; for (var i = 0; i < count; i++) { rawData.push({ itemInfo: "Tile" + i }); } return new WinJS.Binding.List(rawData).dataSource; } function basicRenderer(itemPromise) { var element = document.createElement("div"); element.style.width = "50px"; element.style.height = "50px"; return { element: element, renderComplete: itemPromise.then(function (item) { element.textContent = item.data.itemInfo; }) }; } function verifyListLayout(listView) { var list = listView.itemDataSource.list; for (var i = 0; i < list.length; i++) { var element = listView.elementFromIndex(i), container = Helper.ListView.containerFrom(element); LiveUnit.Assert.areEqual(list.getItem(i).data.itemInfo, element.textContent); LiveUnit.Assert.areEqual(i * 50, Helper.ListView.offsetTopFromSurface(listView, container)); LiveUnit.Assert.areEqual(0, Helper.ListView.offsetLeftFromSurface(listView, container)); } } function verifyGridLayout(listView, expectedRows) { var list = listView.itemDataSource.list, row = 0, col = 0, rtl = (listView._element.style.direction === "rtl"); if (!expectedRows) { expectedRows = 3; } for (var i = 0; i < list.length; i++) { var element = listView.elementFromIndex(i), container = Helper.ListView.containerFrom(element); LiveUnit.Assert.areEqual(list.getItem(i).data.itemInfo, element.textContent); var expectedLeft = col * 50; if (rtl) { expectedLeft = listView._canvas.offsetWidth - expectedLeft - container.offsetWidth; } LiveUnit.Assert.areEqual(row * 50, Helper.ListView.offsetTopFromSurface(listView, container)); LiveUnit.Assert.areEqual(expectedLeft, Helper.ListView.offsetLeftFromSurface(listView, container)); row++; row = row % expectedRows; if (row == 0) { col++; } } } export class ListViewAnimationTest { // This is the setup function that will be called at the beginning of each test function. setUp() { LiveUnit.LoggingCore.logComment("In setup"); var newNode = document.createElement("div"); newNode.id = "AnimationTest"; newNode.style.width = "500px"; newNode.style.height = "500px"; document.body.appendChild(newNode); } tearDown() { LiveUnit.LoggingCore.logComment("In tearDown"); var element = document.getElementById("AnimationTest"); if (element) { WinJS.Utilities.disposeSubTree(element); document.body.removeChild(element); } } }; function generateDelayedEntranceAnimation(layoutName) { ListViewAnimationTest.prototype["testDelayedEntranceAnimation" + layoutName] = function (complete) { // This test is only useful on a machine that has animations enabled. if (!WinJS.UI.isAnimationEnabled()) { complete(); return; } var element = document.getElementById("AnimationTest"); element.style.height = "150px"; element.style.direction = "ltr"; var entranceAnimationCount = 0; WinJS.Utilities["_addEventListener"](element, "animationstart", function (e) { if (e.animationName.indexOf("enterContent") !== -1) { entranceAnimationCount++; } }); var countAnimationHandlerCalled = 0, delayedPromiseDone = false; var animationEventHandler = function (e) { countAnimationHandlerCalled++; LiveUnit.Assert.areEqual(1, countAnimationHandlerCalled); LiveUnit.Assert.areEqual(WinJS.UI.ListViewAnimationType.entrance, e.detail.type); var delayPromise = WinJS.Promise.timeout(1000).then(function () { LiveUnit.Assert.areEqual(0, entranceAnimationCount); delayedPromiseDone = true; }); e.detail.setPromise(delayPromise); }; var listView; var viewCompleteEventHandler = function (e) { if (listView && listView.loadingState === "complete") { LiveUnit.Assert.areEqual(1, countAnimationHandlerCalled); LiveUnit.Assert.areEqual(1, entranceAnimationCount); element.removeEventListener("contentanimating", animationEventHandler, false); element.removeEventListener("loadingstatechanged", viewCompleteEventHandler, false); complete(); } }; element.addEventListener("contentanimating", animationEventHandler, false); element.addEventListener("loadingstatechanged", viewCompleteEventHandler, false); listView = new WinJS.UI.ListView(element, { itemDataSource: getDataSource(), itemTemplate: basicRenderer, layout: new WinJS.UI[layoutName]() }); }; }; function generateSkippedEntranceAnimation(layoutName) { ListViewAnimationTest.prototype["testSkippedEntranceAnimation" + layoutName] = function (complete) { // This test is only useful on a machine that has animations enabled. if (!WinJS.UI.isAnimationEnabled()) { complete(); return; } var element = document.getElementById("AnimationTest"); element.style.height = "150px"; element.style.direction = "ltr"; var entranceAnimationCount = 0; WinJS.Utilities["_addEventListener"](element, "animationstart", function (e) { if (e.animationName.indexOf("enterContent") !== -1) { entranceAnimationCount++; } }); var countAnimationHandlerCalled = 0, delayedPromiseDone = false; var animationEventHandler = function (e) { countAnimationHandlerCalled++; LiveUnit.Assert.areEqual(1, countAnimationHandlerCalled); LiveUnit.Assert.areEqual(WinJS.UI.ListViewAnimationType.entrance, e.detail.type); e.preventDefault(); }; var listView; var viewCompleteEventHandler = function (e) { if (listView && listView.loadingState === "complete") { LiveUnit.Assert.areEqual(1, countAnimationHandlerCalled); LiveUnit.Assert.areEqual(0, entranceAnimationCount); element.removeEventListener("contentanimating", animationEventHandler, false); element.removeEventListener("loadingstatechanged", viewCompleteEventHandler, false); complete(); } }; element.addEventListener("contentanimating", animationEventHandler, false); element.addEventListener("loadingstatechanged", viewCompleteEventHandler, false); listView = new WinJS.UI.ListView(element, { itemDataSource: getDataSource(), itemTemplate: basicRenderer, layout: new WinJS.UI[layoutName]() }); }; }; function generateSkippedContentTransition(layoutName) { ListViewAnimationTest.prototype["testSkippedContentTransition" + layoutName] = function (complete) { // This test is only useful on a machine that has animations enabled. if (!WinJS.UI.isAnimationEnabled()) { complete(); return; } var element = document.getElementById("AnimationTest"); element.style.height = "150px"; element.style.direction = "ltr"; var entranceAnimationCount = 0; WinJS.Utilities["_addEventListener"](element, "animationstart", function (e) { if (e.animationName.indexOf("enterContent") !== -1) { entranceAnimationCount++; } }); var countAnimationHandlerCalled = 0, delayedPromiseDone = false; var animationEventHandler = function (e) { countAnimationHandlerCalled++; if (e.detail.type === WinJS.UI.ListViewAnimationType.entrance) { LiveUnit.Assert.areEqual(1, countAnimationHandlerCalled); } else if (e.detail.type === WinJS.UI.ListViewAnimationType.contentTransition) { LiveUnit.Assert.areEqual(2, countAnimationHandlerCalled); e.preventDefault(); } else { LiveUnit.Assert.fail("Got an animation event with an unexpected type"); } }; element.addEventListener("contentanimating", animationEventHandler, false); var listView = new WinJS.UI.ListView(element, { itemDataSource: getDataSource(), itemTemplate: basicRenderer, layout: new WinJS.UI[layoutName]() }); var tests = [ function () { LiveUnit.Assert.areEqual(1, countAnimationHandlerCalled); LiveUnit.Assert.areEqual(1, entranceAnimationCount); listView.itemDataSource = getDataSource(); return true; }, function () { LiveUnit.Assert.areEqual(2, countAnimationHandlerCalled); LiveUnit.Assert.areEqual(1, entranceAnimationCount); element.removeEventListener("contentanimating", animationEventHandler, false); complete(); } ]; Helper.ListView.runTests(listView, tests); }; }; function generateInterruptedEntranceAnimationWithContentTransitionPlayed(layoutName) { ListViewAnimationTest.prototype["testInterruptedEntranceAnimationWithContentTransitionPlayed" + layoutName] = function (complete) { // This test is only useful on a machine that has animations enabled. if (!WinJS.UI.isAnimationEnabled()) { complete(); return; } var element = document.getElementById("AnimationTest"); element.style.height = "150px"; element.style.direction = "ltr"; var entranceAnimationCount = 0; WinJS.Utilities["_addEventListener"](element, "animationstart", function (e) { if (e.animationName.indexOf("enterContent") !== -1) { entranceAnimationCount++; } }); var countAnimationHandlerCalled = 0, delayedPromiseDone = false; var animationEventHandler = function (e) { countAnimationHandlerCalled++; if (e.detail.type === WinJS.UI.ListViewAnimationType.entrance) { LiveUnit.Assert.areEqual(1, countAnimationHandlerCalled); e.detail.setPromise(WinJS.Promise.timeout(6000).then(function () { delayedPromiseDone = true; })); } else if (e.detail.type === WinJS.UI.ListViewAnimationType.contentTransition) { LiveUnit.Assert.areEqual(2, countAnimationHandlerCalled); LiveUnit.Assert.isFalse(delayedPromiseDone); } else { LiveUnit.Assert.fail("Got an animation event with an unexpected type"); } }; var listView, interruptionDone = false; var viewCompleteEventHandler = function (e) { if (listView && listView.loadingState === "complete") { LiveUnit.Assert.isTrue(interruptionDone); LiveUnit.Assert.isFalse(delayedPromiseDone); LiveUnit.Assert.areEqual(2, countAnimationHandlerCalled); LiveUnit.Assert.areEqual(1, entranceAnimationCount); element.removeEventListener("contentanimating", animationEventHandler, false); element.removeEventListener("loadingstatechanged", viewCompleteEventHandler, false); complete(); } }; element.addEventListener("contentanimating", animationEventHandler, false); element.addEventListener("loadingstatechanged", viewCompleteEventHandler, false); listView = new WinJS.UI.ListView(element, { itemDataSource: getDataSource(), itemTemplate: basicRenderer, layout: new WinJS.UI[layoutName]() }); WinJS.Promise.timeout(1000).then(function () { interruptionDone = true; listView.itemDataSource = getDataSource(); }); }; }; function generateInterruptedEntranceAnimationWithNoContentTransitionPlayed(layoutName) { ListViewAnimationTest.prototype["testInterruptedEntranceAnimationWithNoContentTransitionPlayed" + layoutName] = function (complete) { // This test is only useful on a machine that has animations enabled. if (!WinJS.UI.isAnimationEnabled()) { complete(); return; } var element = document.getElementById("AnimationTest"); element.style.height = "150px"; element.style.direction = "ltr"; var entranceAnimationCount = 0; WinJS.Utilities["_addEventListener"](element, "animationstart", function (e) { if (e.animationName.indexOf("enterContent") !== -1) { entranceAnimationCount++; } }); var countAnimationHandlerCalled = 0, delayedPromiseDone = false; var animationEventHandler = function (e) { countAnimationHandlerCalled++; if (e.detail.type === WinJS.UI.ListViewAnimationType.entrance) { LiveUnit.Assert.areEqual(1, countAnimationHandlerCalled); e.detail.setPromise(WinJS.Promise.timeout(6000).then(function () { delayedPromiseDone = true; })); } else if (e.detail.type === WinJS.UI.ListViewAnimationType.contentTransition) { LiveUnit.Assert.areEqual(2, countAnimationHandlerCalled); LiveUnit.Assert.isFalse(delayedPromiseDone); e.preventDefault(); } else { LiveUnit.Assert.fail("Got an animation event with an unexpected type"); } }; var listView, interruptionDone = false; var viewCompleteEventHandler = function (e) { if (listView && listView.loadingState === "complete") { LiveUnit.Assert.isTrue(interruptionDone); LiveUnit.Assert.isFalse(delayedPromiseDone); LiveUnit.Assert.areEqual(2, countAnimationHandlerCalled); LiveUnit.Assert.areEqual(0, entranceAnimationCount); element.removeEventListener("contentanimating", animationEventHandler, false); element.removeEventListener("loadingstatechanged", viewCompleteEventHandler, false); complete(); } }; element.addEventListener("contentanimating", animationEventHandler, false); element.addEventListener("loadingstatechanged", viewCompleteEventHandler, false); listView = new WinJS.UI.ListView(element, { itemDataSource: getDataSource(), itemTemplate: basicRenderer, layout: new WinJS.UI[layoutName]() }); WinJS.Promise.timeout(1000).then(function () { interruptionDone = true; listView.itemDataSource = getDataSource(); }); }; }; if (!WinJS.Utilities.isPhone) { generateDelayedEntranceAnimation("GridLayout"); generateSkippedEntranceAnimation("GridLayout"); generateSkippedContentTransition("GridLayout"); generateInterruptedEntranceAnimationWithContentTransitionPlayed("GridLayout"); generateInterruptedEntranceAnimationWithNoContentTransitionPlayed("GridLayout"); } function generateAnimationEventsWithAnimationsDisabled(layoutName) { ListViewAnimationTest.prototype["testAnimationEventsWithAnimationsDisabled" + layoutName] = function (complete) { var element = document.getElementById("AnimationTest"); element.style.height = "150px"; element.style.direction = "ltr"; var entranceAnimationCount = 0; WinJS.Utilities["_addEventListener"](element, "animationstart", function (e) { if (e.animationName.indexOf("enterContent") !== -1) { entranceAnimationCount++; } }); var countAnimationHandlerCalled = 0, // Since we're hacking the ListView's animations disabled function via setting _animationsDisabled below, it's possible that a synchronous listview will // complete and fire viewstatecomplete + entrance animation events before we've had a chance to override animations disabled. If that happens a couple counts // will be off by one, so this boolean is used to account for that error offByOne = false, delayedPromiseDone = false; var initializationComplete = false; var animationEventHandler = function (e) { countAnimationHandlerCalled++; if (!initializationComplete) { offByOne = true; } }; element.addEventListener("contentanimating", animationEventHandler, false); var listView = new ListView(element, { itemDataSource: getDataSource(), itemTemplate: basicRenderer, layout: new WinJS.UI[layoutName]() }); listView._animationsDisabled = function () { return true; } initializationComplete = true; var tests = [ function () { LiveUnit.Assert.areEqual((offByOne ? 1 : 0), entranceAnimationCount); LiveUnit.Assert.areEqual((offByOne ? 1 : 0), countAnimationHandlerCalled); listView.itemDataSource = getDataSource(); return true; }, function () { LiveUnit.Assert.areEqual((offByOne ? 1 : 0), entranceAnimationCount); LiveUnit.Assert.areEqual((offByOne ? 1 : 0), countAnimationHandlerCalled); complete(); } ]; Helper.ListView.runTests(listView, tests); }; }; generateAnimationEventsWithAnimationsDisabled("GridLayout"); } LiveUnit.registerTestClass("WinJSTests.ListViewAnimationTest");
the_stack
import { validateParameter } from '../../utils/utils'; import { PoEventSourcingOperation, PoEventSourcingService, PoEventSourcingSummaryItem } from '../../services/po-event-sourcing'; import { PoQueryBuilder } from './../po-query-builder/po-query-builder.model'; import { PoSchemaService, PoSchemaUtil } from '../../services/po-schema'; import { PoSyncSchema } from '../../services/po-sync/interfaces/po-sync-schema.interface'; /** * @description * * Uma instância `PoEntity` representa um *schema* e ela contém métodos que possibilitam manipular seus registros, * como por exemplo: buscar, criar e remover. * * Esta instância pode ser obtida a partir do retorno do método `PoSyncService.getModel('schema name')`. */ export class PoEntity { constructor( private eventSourcing: PoEventSourcingService, private schema: PoSyncSchema, private poSchemaService: PoSchemaService ) {} /** * Busca os registros do *schema*, podendo filtrar o resultado a partir do filtro passado e retornando apenas * os campos definidos. * * Para que esta busca seja concluída é necessário utilizar o método `PoQueryBuilder.exec()`. * Veja mais em: [PoQueryBuilder](/documentation/po-query-builder). * * @param {object} filter Objeto que contém os campos e valores a serem filtrados no *schema*. * @param {string} fields Campos que serão retornados nos registros. Este campos devem estar dentro de * uma *string* separados por espaço podendo usar o caractere `-` para excluir campos. * Por exemplo, a definição abaixo: * * ``` * PoQueryBuilder.select('name age address'); * ``` * Irá retornar apenas os campos `name`, `age` e `address`. E para não mostrar um campo ou mais basta fazer: * * ``` * PoQueryBuilder.select('-name -age'); * ``` * @returns {PoQueryBuilder} Objeto que possibilita encadear um método do `PoQueryBuilder`. */ find(filter?: object, fields?: string): PoQueryBuilder { const query = new PoQueryBuilder(this.poSchemaService, this.schema); if (filter) { query.filter(filter); } if (fields) { query.select(fields); } return query; } /** * Busca um registro pelo seu *id*. * * Para que esta busca seja concluída é necessário utilizar o método `PoQueryBuilder.exec()`. * Veja mais em: [PoQueryBuilder](/documentation/po-query-builder). * * @param {any} id Identificador do registro. * @param {string} fields Campos que serão retornados nos registros. Este campos devem estar dentro de * uma *string* separados por espaço podendo usar o caractere `-` para excluir campos. * Por exemplo, a definição abaixo: * * ``` * PoQueryBuilder.select('name age address'); * ``` * Irá retornar apenas os campos `name`, `age` e `address`. E para não mostrar um campo ou mais basta fazer: * * ``` * PoQueryBuilder.select('-name -age'); * ``` * @returns {PoQueryBuilder} Objeto que possibilita encadear um método do `PoQueryBuilder`. */ findById(id: any, fields?: string): PoQueryBuilder { return this.findOne({ [this.schema.idField]: id }, fields); } /** * Semelhante ao método `PoEntity.find()`, porém retorna apenas o primeiro registro encontrado na busca. * * Para que esta busca seja concluída é necessário utilizar o método `PoQueryBuilder.exec()`. * Veja mais em: [PoQueryBuilder](/documentation/po-query-builder). * * @param {any} filter Objeto que contém os campos e valores a serem filtrados no *schema*. * @param {string} fields Campos que serão retornados nos registros. Este campos devem estar dentro de * uma *string* separados por espaço podendo usar o caractere `-` para excluir campos. * Por exemplo, a definição abaixo: * * ``` * PoQueryBuilder.select('name age address'); * ``` * Irá retornar apenas os campos `name`, `age` e `address`. E para não mostrar um campo ou mais basta fazer: * * ``` * PoQueryBuilder.select('-name -age'); * ``` * @returns {PoQueryBuilder} Objeto que possibilita encadear um método do `PoQueryBuilder`. */ findOne(filter?: any, fields?: string): PoQueryBuilder { const query = this.find(filter, fields); query.limit(1); return query; } /** * Remove um registro. * * @param {object} record Registro que será removido. * @param {string} customRequestId Identificador customizado do comando. * @returns {Promise} Promessa que é concluída após o registro ser removido. */ async remove(record: object, customRequestId?: string): Promise<any> { validateParameter({ record }); const remove = async () => { const idField = record[this.schema.idField] ? this.schema.idField : PoSchemaUtil.syncInternalIdFieldName; const serverRecord = PoSchemaUtil.separateSchemaFields(this.schema, record)['serverRecord']; await this.poSchemaService.remove(this.schema.name, record[idField]); await this.eventSourcing.remove(this.schema.name, serverRecord, customRequestId); }; return this.poSchemaService.limitedCallWrap(remove); } /** * Altera ou inclui um registro. * * > O registro será alterado se ele possuir um *id*, caso contrário um novo registro será criado. * * @param {object} record Registro que será persistido. * @param {string} customRequestId Identificador customizado do comando. * @returns {Promise} Promessa que é concluída após o registro ser alterado ou incluído. */ async save(record: object, customRequestId?: string): Promise<any> { validateParameter({ record }); return this.poSchemaService.limitedCallWrap(this.selectSaveType.bind(this, record, true, customRequestId)); } /** * Salva uma lista de registros em lote. * * > Para cada registro da lista, será inserido um novo registro se o mesmo não tiver *id*, caso contrário * será contado como uma atualização de um registro existente. * * @param {Array<object>} records Lista de registros que serão persistidos. * @param {Array<string> | string} customRequestIds Identificador customizado do comando. * * Ao passar uma lista de identificadores, cada índice da lista de identificadores deverá * corresponder ao índice do registro na lista de registros. * @returns {Promise<any>} Promessa que é concluída após os registros serem alterados ou incluídos. */ async saveAll(records: Array<object>, customRequestIds?: Array<string> | string): Promise<any> { validateParameter({ records }); const saveAll = async () => { const batchEvents = []; for (let index = 0; index < records.length; index++) { const record = records[index]; const sendToEventSourcing = false; const isNonLocalRecordChanged = await this.isNonLocalRecordChanged(record); const updatedRecord = await this.selectSaveType(record, sendToEventSourcing); if (isNonLocalRecordChanged) { const customRequestId = customRequestIds instanceof Array ? customRequestIds[index] : customRequestIds; const eventOperation = this.createEventOperation(record, updatedRecord, customRequestId); batchEvents.push(eventOperation); } } await this.eventSourcing.createBatchEvents(this.schema.name, batchEvents); }; return this.poSchemaService.limitedCallWrap(saveAll); } private async create(newRecord: any, sendToEventSourcing: boolean, customRequestId?: string): Promise<any> { const time = new Date().getTime(); const syncProperties = { [PoSchemaUtil.syncInternalIdFieldName]: time, SyncInsertedDateTime: time, SyncUpdatedDateTime: null, SyncExclusionDateTime: null, SyncDeleted: false, SyncStatus: 0 }; const recordWithSyncProperties = { ...newRecord, ...syncProperties }; const recordedData = await this.poSchemaService.create(this.schema, recordWithSyncProperties); if (sendToEventSourcing) { await this.eventSourcing.create(this.schema.name, recordWithSyncProperties, customRequestId); } return recordedData; } private createEventOperation( record: object, updatedRecord: object, customRequestId?: string ): PoEventSourcingSummaryItem { const operation = PoSchemaUtil.getRecordId(record, this.schema) ? PoEventSourcingOperation.Update : PoEventSourcingOperation.Insert; const serverRecord = PoSchemaUtil.separateSchemaFields(this.schema, updatedRecord)['serverRecord']; return { record: serverRecord, customRequestId: customRequestId, operation: operation }; } private async isNonLocalRecordChanged(updatedRecord: object): Promise<boolean> { const nonLocalFieldNames = PoSchemaUtil.getNonLocalFieldNames(this.schema); const record = await this.poSchemaService.get(this.schema.name, updatedRecord[this.schema.idField]); return !PoSchemaUtil.isModelsEqual(nonLocalFieldNames, record, updatedRecord); } private async selectSaveType( record: object, sendToEventSourcing: boolean, customRequestId?: string ): Promise<object> { const hasId = PoSchemaUtil.getRecordId(record, this.schema); return hasId ? await this.update(record, sendToEventSourcing, customRequestId) : await this.create(record, sendToEventSourcing, customRequestId); } private async update(updatedRecord: any, sendToEventSourcing: boolean, customRequestId?: string): Promise<object> { updatedRecord.SyncUpdatedDateTime = new Date().getTime(); updatedRecord.SyncStatus = 0; const isNonLocalRecordChanged = await this.isNonLocalRecordChanged(updatedRecord); const recordedData = await this.poSchemaService.update(this.schema, updatedRecord); if (isNonLocalRecordChanged && sendToEventSourcing) { const serverRecord = PoSchemaUtil.separateSchemaFields(this.schema, updatedRecord)['serverRecord']; await this.eventSourcing.update(this.schema.name, serverRecord, customRequestId); } return recordedData; } }
the_stack
import { wikiToDomain } from '@/shared/utility-shared'; const rp = require('request-promise'); const chalk = require('chalk'); const Logger = require('heroku-logger').Logger; const pad = require('pad'); export const logger = require('heroku-logger'); export const latencyColor = function(latencyMs) { if (latencyMs >= 50000) {return 'red';} else if (latencyMs >= 5000) {return 'orange';} else if (latencyMs >= 500) {return 'yellow';} else {return 'lightgreen';} }; export const statusColor = function(statusCode) { const codeNum = parseInt(statusCode); if (codeNum >= 600) {return 'purple';} else if (codeNum >= 500) {return 'red';} else if (codeNum >= 400) {return 'orange';} else if (codeNum >= 300) {return 'yellow';} else if (codeNum >= 200) {return 'lightgreen';} else if (codeNum >= 100) {return 'lightblue';} else {return 'lightpink';} }; export const axiosLogger = new Logger({ prefix: pad('AXIOS', 8), }); export const apiLogger = new Logger({ prefix: pad('API', 8), // Defaults to `''`. }); export const perfLogger = new Logger({ prefix: pad('PERF', 8), // Defaults to `''`. }); export const cronLogger = new Logger({ prefix: pad('CRON', 8), // Defaults to `''`. }); export const feedRevisionEngineLogger = new Logger({ prefix: pad('FEED', 8), // Defaults to `''`. }); export const mwApiClientLogger = new Logger({ prefix: pad('MWAPI', 8), // Defaults to `''`. }); export const colorizeMaybe = function(logger, color, message) { if (logger.config.color) { return chalk.keyword(color)(message); } else { return message; } }; export async function isWhitelistedFor(featureName, wikiUserName) { const mongoose = require('mongoose'); const db = mongoose.connection.db; console.log('featureName', featureName, 'wikiUserName', wikiUserName); const ret = await db.collection('FeatureList').find({ featureName, whitelistedWikiUserNames: { $elemMatch: { $eq: wikiUserName } }, }).toArray(); return ret.length >= 1; } /** * @deprecated * @param oresJson * @param wiki * @param revId * @return {{badfaithScore: *, damagingScore: *, badfaith: *, damaging: *, wikiRevId: string}} */ export function computeOresField(oresJson, wiki, revId) { const damagingScore = oresJson.damagingScore || (oresJson[wiki].scores[revId].damaging.score && oresJson[wiki].scores[revId].damaging.score.probability.true); const badfaithScore = oresJson.badfaithScore || (oresJson[wiki].scores[revId].goodfaith.score && oresJson[wiki].scores[revId].goodfaith.score.probability.false); const damaging = oresJson.damaging || (oresJson[wiki].scores[revId].damaging.score && oresJson[wiki].scores[revId].damaging.score.prediction); const badfaith = oresJson.badfaith || (oresJson[wiki].scores[revId].goodfaith.score && !oresJson[wiki].scores[revId].goodfaith.score.prediction); return { wikiRevId: `${wiki}:${revId}`, damagingScore, damaging, badfaithScore, badfaith, }; } export function computeOresFieldNew(oresJson, wiki, revId) { const ret:any = {}; const damagingScore = oresJson.damagingScore || (oresJson[wiki].scores[revId].damaging.score && oresJson[wiki].scores[revId].damaging.score.probability.true); const badfaithScore = oresJson.badfaithScore || (oresJson[wiki].scores[revId].goodfaith.score && oresJson[wiki].scores[revId].goodfaith.score.probability.false); ret.wikiRevId = `${wiki}:${revId}`; ret.damaging = {}; ret.goodfaith = {}; ret.damaging.true = damagingScore; ret.damaging.false = 1 - damagingScore; ret.goodfaith.true = 1 - badfaithScore; ret.goodfaith.false = badfaithScore; return ret; } export async function fetchRevisions(wikiRevIds) { const wikiToRevIdList = wikiRevIdsGroupByWiki(wikiRevIds); const wikiToRevisionList = {}; for (const wiki in wikiToRevIdList) { const revIds = wikiToRevIdList[wiki]; const fetchUrl = new URL(`https://${wikiToDomain[wiki]}/w/api.php`); const params = { action: 'query', format: 'json', prop: 'revisions|info', indexpageids: 1, revids: revIds.join('|'), rvprop: 'ids|timestamp|flags|user|tags|size|comment', rvslots: 'main', }; Object.keys(params).forEach((key) => { fetchUrl.searchParams.set(key, params[key]); }); try { const retJson = await rp.get(fetchUrl, { json: true }); if (retJson.query.badrevids) { wikiToRevisionList[wiki] = []; // does not find } else { /** Example { "batchcomplete": "", "query": { "pageids": [ "16377", "103072" ], "pages": { "16377": { "pageid": 16377, "ns": 104, "title": "API:Query", "revisions": [ { "revid": 3319487, "parentid": 3319442, "minor": "", "user": "Shirayuki", "timestamp": "2019-07-16T22:08:58Z", "size": 15845, "comment": "", "tags": [] } ], "contentmodel": "wikitext", "pagelanguage": "en", "pagelanguagehtmlcode": "en", "pagelanguagedir": "ltr", "touched": "2019-07-17T03:10:17Z", "lastrevid": 3319487, "length": 15845 }, "103072": { "pageid": 103072, "ns": 104, "title": "API:Lists/All", "revisions": [ { "revid": 2287599, "parentid": 2287488, "user": "Wargo", "timestamp": "2016-11-17T16:49:59Z", "size": 924, "comment": "Undo revision 2287488 by [[Special:Contributions/Jkmartindale|Jkmartindale]] ([[User talk:Jkmartindale|talk]])", "tags": [] } ], "contentmodel": "wikitext", "pagelanguage": "en", "pagelanguagehtmlcode": "en", "pagelanguagedir": "ltr", "touched": "2019-07-18T04:14:03Z", "lastrevid": 2287599, "length": 924 } } } } */ const revIdToRevision = {}; for (const pageId of retJson.query.pageids) { for (const revision of retJson.query.pages[pageId].revisions) { revIdToRevision[revision.revid] = revision; revIdToRevision[revision.revid].title = retJson.query.pages[pageId].title; revIdToRevision[revision.revid].wiki = wiki; revIdToRevision[revision.revid].wikiRevId = `${wiki}:${revision.revid}`; revIdToRevision[revision.revid].pageLatestRevId = retJson.query.pages[pageId].lastrevid; revIdToRevision[revision.revid].namespace = revision.ns; } } wikiToRevisionList[wiki] = revIds.map((revId) => revIdToRevision[revId]); } } catch (err) { console.warn(err); wikiToRevisionList[wiki] = []; // does not find } } return wikiToRevisionList; } export async function getNewJudgementCounts(db, matcher = {}, offset = 0, limit = 10) { return await db.collection('Interaction').aggregate([ { $match: matcher, }, { $group: { _id: { wikiRevId: '$wikiRevId', }, wikiRevId: { $first: '$wikiRevId', }, judgements: { $push: { judgement: '$judgement', userGaId: '$userGaId', wikiUserName: '$wikiUserName', timestamp: '$timestamp', }, }, totalCounts: { $sum: 1, }, shouldRevertCounts: { $sum: { $cond: [ { $eq: [ '$judgement', 'ShouldRevert', ], }, 1, 0, ], }, }, notSureCounts: { $sum: { $cond: [ { $eq: [ '$judgement', 'NotSure', ], }, 1, 0, ], }, }, looksGoodCounts: { $sum: { $cond: [ { $eq: [ '$judgement', 'LooksGood', ], }, 1, 0, ], }, }, lastTimestamp: { $max: '$timestamp', }, wiki: { $first: '$wiki', }, }, }, { $project: { 'wikiRevId': '$_id.wikiRevId', 'judgements': '$judgements', 'wiki': 1, 'lastTimestamp': 1, 'counts.Total': '$totalCounts', 'counts.ShouldRevert': '$shouldRevertCounts', 'counts.NotSure': '$notSureCounts', 'counts.LooksGood': '$looksGoodCounts', }, }, { $match: { wiki: { $exists: true, $ne: null, }, lastTimestamp: { $exists: true, $ne: null, }, }, }, { $sort: { lastTimestamp: -1, }, }, ], { allowDiskUse: true, }) .skip(offset) .limit(limit) .toArray(); /** * Example of output schema: { "_id":{ "wikiRevId":"enwiki:905704873" }, "lastTimestamp":"1562791937", "recentChange":{ "_id":"enwiki-1169325920", "id":"1169325920", "title":"Financial endowment", "namespace":"0", "revision":{ "new":"905704873", "old":"900747399" }, "ores":{ "damagingScore":"0.8937388482947232", "damaging":"true", "badfaithScore":"0.8787846798198944", "badfaith":"true" }, "user":"<userId or IP>>", "wiki":"enwiki", "timestamp":"1562791912" }, "wikiRevId":"enwiki:905704873", "judgements":[ { "judgement":"ShouldRevert", "userGaId":"<userGaId>", "timestamp":"1562791937" } ], "counts":{ "Total":1, "ShouldRevert":1, "NotSure":0, "LooksGood":0 } } */ } export function isEmpty(value) { return typeof value === 'string' && !value.trim() || typeof value === 'undefined' || value === null; } export const useOauth = !isEmpty(process.env.MEDIAWIKI_CONSUMER_SECRET) && !isEmpty(process.env.MEDIAWIKI_CONSUMER_KEY); export function wikiRevIdsGroupByWiki(wikiRevIds) { const wikiToRevIdList = {}; wikiRevIds.forEach((wikiRevId) => { const wiki = wikiRevId.split(':')[0]; const revId = wikiRevId.split(':')[1]; if (!(wiki in wikiToRevIdList)) { wikiToRevIdList[wiki] = []; } wikiToRevIdList[wiki].push(revId); }); return wikiToRevIdList; } export const asyncHandler = (fn) => (req, res, next) => Promise .resolve(fn(req, res, next)) .catch(next); export function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } export function isAuthenticatedWithWikiUserName(req, wikiUserName:string):boolean { return req.isAuthenticated() && req.user.displayName === wikiUserName; } export function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } else { res.status(403); res.send('Login required for this endpoint'); } } export const useStiki = /mysql:\/\//.test(process.env.STIKI_MYSQL);
the_stack
import * as React from 'react'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import { mount, shallow, ReactWrapper, ShallowWrapper } from 'enzyme'; import { disable as disablePresentationMode, enable as enablePresentationMode, executeCommand, restartConversation, SharedConstants, RestartConversationStatus, } from '@bfemulator/app-shared'; import { CommandServiceImpl, CommandServiceInstance } from '@bfemulator/sdk-shared'; import { RestartConversationOptions } from '@bfemulator/app-shared'; import { Emulator } from './emulator'; import { EmulatorContainer } from './emulatorContainer'; let mockCallsMade, mockRemoteCallsMade; const replayConversationText = 'Stop Replaying Conversation'; const mockSharedConstants = SharedConstants; jest.mock('./chatPanel/chatPanel', () => ({ ChatPanel: jest.fn(() => <div />), })); jest.mock('./logPanel/logPanel', () => { return jest.fn(() => <div />); }); jest.mock('./playbackBar/playbackBar', () => { return jest.fn(() => <div />); }); jest.mock('./emulator.scss', () => ({})); jest.mock('./parts', () => ({ InspectorContainer: jest.fn(() => <div />), })); jest.mock('@bfemulator/sdk-shared/build/utils/misc', () => ({ uniqueId: () => 'someUniqueId', uniqueIdv4: () => 'newUserId', })); jest.mock('botframework-webchat', () => ({ createDirectLine: args => ({ ...args }), })); jest.mock('electron', () => ({ remote: { app: { isPackaged: false, }, }, ipcMain: new Proxy( {}, { get(): any { return () => ({}); }, has() { return true; }, } ), ipcRenderer: new Proxy( {}, { get(): any { return () => ({}); }, has() { return true; }, } ), })); describe('<EmulatorContainer/>', () => { let wrapper: ReactWrapper<any, any, any> | ShallowWrapper<any, any, any>; let node; let instance; let mockDispatch; let mockStoreState; const mockUnsubscribe = jest.fn(() => null); let commandService: CommandServiceImpl; beforeAll(() => { const decorator = CommandServiceInstance(); const descriptor = decorator({ descriptor: {} }, 'none') as any; commandService = descriptor.descriptor.get(); commandService.call = (commandName, ...args) => { mockCallsMade.push({ commandName, args }); return Promise.resolve() as any; }; commandService.remoteCall = (commandName, ...args) => { mockRemoteCallsMade.push({ commandName, args }); if (commandName === mockSharedConstants.Commands.Emulator.NewTranscript) { return Promise.resolve({ conversationId: 'someConvoId' }); } if (commandName === mockSharedConstants.Commands.Emulator.FeedTranscriptFromDisk) { return Promise.resolve({ meta: 'some file info' }); } if (commandName === mockSharedConstants.Commands.Settings.LoadAppSettings) { return Promise.resolve({ framework: { userGUID: '' } }); } return Promise.resolve() as any; }; }); beforeEach(() => { mockUnsubscribe.mockClear(); mockCallsMade = []; mockRemoteCallsMade = []; mockStoreState = { clientAwareSettings: { serverUrl: 'http://localhost', users: { usersById: {}, }, }, chat: { chats: { doc1: { conversationId: 'convo1', documentId: 'doc1', endpointId: 'endpoint1', userId: 'someUserId', subscription: { unsubscribe: mockUnsubscribe }, }, }, pendingSpeechTokenRetrieval: null, webChatStores: {}, webSpeechFactories: {}, restartStatus: {}, }, editor: { activeEditor: 'primary', editors: { primary: { activeDocumentId: 'doc1', }, }, }, presentation: { enabled: true }, }; const mockStore = createStore((_state, _action) => mockStoreState); mockDispatch = jest.spyOn(mockStore, 'dispatch').mockImplementation((action: any) => { if (action && action.payload && action.payload.resolver) { action.payload.resolver(); } return action; }); wrapper = mount( <Provider store={mockStore}> <EmulatorContainer documentId={'doc1'} url={'someUrl'} mode={'livechat'} conversationId={'convo1'} /> </Provider> ); node = wrapper.find(Emulator); instance = node.instance(); }); it('should render properly', () => { expect(instance).not.toBe(true); }); it('should render the presentation view', () => { wrapper = shallow( <Emulator createErrorNotification={jest.fn(() => null)} documentId={'doc1'} mode={'transcript'} /> ); instance = wrapper.instance(); const presentationView = instance.renderPresentationView(); expect(presentationView).not.toBeNull(); }); it('should render the default view', () => { wrapper = shallow( <Emulator createErrorNotification={jest.fn(() => null)} documentId={'doc1'} mode={'transcript'} /> ); instance = wrapper.instance(); const defaultView = instance.renderDefaultView(); expect(defaultView).not.toBeNull(); }); it('should get the veritcal splitter sizes', () => { const ui = { horizontalSplitter: [], verticalSplitter: [ { absolute: undefined, percentage: 55, }, ], }; wrapper = shallow( <Emulator createErrorNotification={jest.fn(() => null)} documentId={'doc1'} mode={'transcript'} ui={ui} /> ); instance = wrapper.instance(); const verticalSplitterSizes = instance.getVerticalSplitterSizes(); expect(verticalSplitterSizes[0]).toBe('55'); }); it('should get the veritcal splitter sizes', () => { const ui = { horizontalSplitter: [ { absolute: undefined, percentage: 46, }, ], verticalSplitter: [], }; wrapper = shallow( <Emulator createErrorNotification={jest.fn(() => null)} documentId={'doc1'} mode={'transcript'} ui={ui} /> ); instance = wrapper.instance(); const horizontalSplitterSizes = instance.getHorizontalSplitterSizes(); expect(horizontalSplitterSizes[0]).toBe('46'); }); it('should restart the conversation on Ctrl/Cmd + Shift + R', () => { wrapper = shallow( <Emulator activeDocumentId={'doc1'} createErrorNotification={jest.fn(() => null)} mode={'transcript'} documentId={'doc1'} /> ); instance = wrapper.instance(); const mockOnStartOverClick = jest.fn(() => null); instance.onStartOverClick = mockOnStartOverClick; let mockGetModifierState = jest.fn(modifier => { if (modifier === 'Control') { return true; } else if (modifier === 'Shift') { return true; } return true; }); const mockEvent = { getModifierState: mockGetModifierState, key: 'R', }; instance.keyboardEventListener(mockEvent); expect(mockOnStartOverClick).toHaveBeenCalledTimes(1); mockGetModifierState = jest.fn(modifier => { if (modifier === 'Control') { return false; } else if (modifier === 'Shift') { return true; } else { return true; // Cmd / Meta } }); instance.keyboardEventListener(mockEvent); expect(mockOnStartOverClick).toHaveBeenCalledTimes(2); }); it('should enable presentation mode', () => { instance.onPresentationClick(true); expect(mockDispatch).toHaveBeenCalledWith(enablePresentationMode()); }); it('should disable presentation mode', () => { instance.onPresentationClick(false); expect(mockDispatch).toHaveBeenCalledWith(disablePresentationMode()); }); it('should export a transcript', async () => { await instance.onExportTranscriptClick(); expect(mockDispatch).toHaveBeenCalledWith( executeCommand( true, SharedConstants.Commands.Emulator.SaveTranscriptToFile, jasmine.any(Function) as any, 32, 'convo1' ) ); }); it('should start over a conversation with a new user id on click', () => { const mockStore = createStore((_state, _action) => mockStoreState); mockDispatch = jest.spyOn(mockStore, 'dispatch').mockImplementation((action: any) => { if (action && action.payload && action.payload.resolver) { action.payload.resolver(); } return action; }); wrapper = mount( <Provider store={mockStore}> <EmulatorContainer documentId={'doc1'} url={'someUrl'} mode={'livechat'} conversationId={'convo1'} currentRestartConversationOption={RestartConversationOptions.NewUserId} /> </Provider> ); node = wrapper.find(Emulator); instance = node.instance(); instance.onStartOverClick(); expect(mockDispatch).toHaveBeenCalledWith( executeCommand(true, SharedConstants.Commands.Telemetry.TrackEvent, null, 'conversation_restart', { userId: 'new', }) ); expect(mockDispatch).toHaveBeenCalledWith(restartConversation('doc1', true, true)); }); it('should start over a conversation with the same user id on click', () => { const mockStore = createStore((_state, _action) => mockStoreState); mockDispatch = jest.spyOn(mockStore, 'dispatch').mockImplementation((action: any) => { if (action && action.payload && action.payload.resolver) { action.payload.resolver(); } return action; }); wrapper = mount( <Provider store={mockStore}> <EmulatorContainer documentId={'doc1'} url={'someUrl'} mode={'livechat'} conversationId={'convo1'} currentRestartConversationOption={RestartConversationOptions.SameUserId} /> </Provider> ); node = wrapper.find(Emulator); instance = node.instance(); instance.onStartOverClick(); expect(mockDispatch).toHaveBeenCalledWith( executeCommand(true, SharedConstants.Commands.Telemetry.TrackEvent, null, 'conversation_restart', { userId: 'same', }) ); expect(mockDispatch).toHaveBeenCalledWith(restartConversation('doc1', true, false)); }); it('should show "Stop Replaying Conversation" when in Replay mode', () => { let emulatorProps = { documentId: 'doc1', url: 'some-url', mode: 'livechat', conversationId: '123', presentationModeEnabled: false, restartStatus: RestartConversationStatus.Started, onSetRestartConversationOptionClick: jest.fn(), ui: {}, }; const mockStore = createStore((_state, _action) => mockStoreState); wrapper = mount( <Provider store={mockStore}> <Emulator {...emulatorProps} /> </Provider> ); node = wrapper.find(Emulator); expect(wrapper.text().includes(replayConversationText)).toBeTruthy(); emulatorProps = { ...emulatorProps, restartStatus: RestartConversationStatus.Stop, }; wrapper.setProps({ children: <Emulator {...emulatorProps} />, }); expect(wrapper.text().includes(replayConversationText)).toBeFalsy(); emulatorProps = { ...emulatorProps, restartStatus: undefined, }; wrapper.setProps({ children: <Emulator {...emulatorProps} />, }); expect(wrapper.text().includes(replayConversationText)).toBeFalsy(); emulatorProps = { ...emulatorProps, restartStatus: RestartConversationStatus.Rejected, }; wrapper.setProps({ children: <Emulator {...emulatorProps} />, }); expect(wrapper.text().includes(replayConversationText)).toBeFalsy(); emulatorProps = { ...emulatorProps, restartStatus: RestartConversationStatus.Started, }; wrapper.setProps({ children: <Emulator {...emulatorProps} />, }); expect(wrapper.text().includes(replayConversationText)).toBeTruthy(); }); });
the_stack
import { ActionType, OrderByDirection } from './constant' import { Db } from './index' import { Validate } from './validate' // import { Util } from './util' import { QuerySerializer } from './serializer/query' import { UpdateSerializer } from './serializer/update' import { ErrorCode } from './constant' import { GetOneRes, GetRes, CountRes, UpdateRes, RemoveRes } from './result-types' import { ProjectionType, QueryOrder, RequestInterface, QueryParam } from './interface' import { Util } from './util' import { serialize } from './serializer/datatype' interface QueryOption { /** * 查询数量 */ limit?: number /** * 偏移量 */ offset?: number /** * 指定显示或者不显示哪些字段 */ projection?: ProjectionType /** * 是否返回文档总数 */ count?: boolean } interface WithParam { /** * 子查询 */ query: Query /** * 主表联接键(关联字段) */ localField: string /** * 子表联接键(外键) */ foreignField: string, /** * 结果集字段重命名,缺省则用子表名 */ as?: string, /** * 是否是一对一查询,只在 Query.withOne() 中使用 */ one?: boolean, } /** * Db query */ export class Query { /** * Reference to db instance */ protected _db: Db /** * Collection name */ protected _coll: string /** * Query conditions */ private _fieldFilters: Object /** * Order by conditions */ private _fieldOrders: QueryOrder[] /** * Query options */ private _queryOptions: QueryOption /** * Sub queries */ private _withs: WithParam[] /** * Request instance */ private _request: RequestInterface /** * @param db - db reference * @param coll - collection name * @param fieldFilters - query condition * @param fieldOrders - order by condition * @param queryOptions - query options */ public constructor( db: Db, coll: string, fieldFilters?: Object, fieldOrders?: QueryOrder[], queryOptions?: QueryOption, withs?: WithParam[] ) { this._db = db this._coll = coll this._fieldFilters = fieldFilters this._fieldOrders = fieldOrders || [] this._queryOptions = queryOptions || {} this._withs = withs || [] this._request = this._db.request } /** * 查询条件 * * @param query */ public where(query: object) { // query校验 1. 必填对象类型 2. value 不可均为 undefiend if (Object.prototype.toString.call(query).slice(8, -1) !== 'Object') { throw Error(ErrorCode.QueryParamTypeError) } const keys = Object.keys(query) const checkFlag = keys.some(item => { return query[item] !== undefined }) if (keys.length && !checkFlag) { throw Error(ErrorCode.QueryParamValueError) } const _query = QuerySerializer.encode(query) return new Query( this._db, this._coll, _query, this._fieldOrders, this._queryOptions, this._withs ) } /** * 设置排序方式 * * @param fieldPath - 字段路径 * @param directionStr - 排序方式 */ public orderBy(fieldPath: string, directionStr: OrderByDirection): Query { Validate.isFieldPath(fieldPath) Validate.isFieldOrder(directionStr) const newOrder: QueryOrder = { field: fieldPath, direction: directionStr } const combinedOrders = this._fieldOrders.concat(newOrder) return new Query( this._db, this._coll, this._fieldFilters, combinedOrders, this._queryOptions, this._withs ) } /** * 添加 一对多 子查询条件 * @param param {WithParam} * @returns Query */ public with(param: WithParam): Query { const newWith: WithParam = { query: param.query, foreignField: param.foreignField, localField: param.localField, as: param.as ?? param.query._coll, one: param.one ?? false } const combinedWiths = this._withs.concat(newWith) return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, this._queryOptions, combinedWiths) } /** * 添加 一对一 子查询条件 * @param param {WithParam} * @returns Query */ public withOne(param: WithParam): Query { const newWith: WithParam = { query: param.query, foreignField: param.foreignField, localField: param.localField, as: param.as ?? param.query._coll, one: true } const combinedWiths = this._withs.concat(newWith) return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, this._queryOptions, combinedWiths) } /** * 指定要返回的字段 * * @param projection */ public field(projection: string[] | ProjectionType): Query { let formatted = {} as ProjectionType if (projection instanceof Array) { let result = {} as ProjectionType for (let k of projection) { result[k] = 1 } formatted = result } else { for (let k in projection) { if (projection[k]) { if (typeof projection[k] !== 'object') { formatted[k] = 1 } } else { formatted[k] = 0 } } } const option = { ...this._queryOptions } option.projection = formatted return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, option, this._withs) } /** * 设置查询条数 * * @param limit - 限制条数,当前限制一次请求获取数据条数不得大于 1000 */ public limit(limit: number): Query { Validate.isInteger('limit', limit) let option = { ...this._queryOptions } option.limit = limit return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, option, this._withs) } /** * 设置偏移量 * * @param offset - 偏移量 */ public skip(offset: number): Query { Validate.isInteger('offset', offset) let option = { ...this._queryOptions } option.offset = offset return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, option, this._withs) } /** * 设置分页查询 * @param options { current: number, size: number} `current` 是页码,默认为 `1`, `size` 是每页大小, 默认为 10 */ public page(options: { current: number, size: number }) { const current = options?.current || 1 const size = options?.size || 10 const query = this .skip((current - 1) * size) .limit(size) query._queryOptions.count = true return query } /** * 克隆 * @returns Query */ public clone(): Query { return new Query(this._db, this._coll, this._fieldFilters, this._fieldOrders, this._queryOptions, this._withs) } /** * 发起请求获取文档列表 * * - 默认 `limit` 为 100 * - 可以把通过 `orderBy()`、`where()`、`skip()`、`limit()`设置的数据添加请求参数上 */ public async get<T = any>(): Promise<GetRes<T>> { if (this._withs?.length) { return await this.internalMerge() } else { return await this.internalGet() } } /** * 发起请求获取一个文档 * @param options * @returns */ public async getOne<T = any>(): Promise<GetOneRes<T>> { const res = await this.limit(1).get<T>() if (res.error) { return res as any } if (!res.data.length) { return { ok: true, data: null, requestId: res.requestId } } return { ok: true, data: res.data[0], requestId: res.requestId } } /** * [该接口已废弃,直接使用 `get()` 代替] * 发起请求获取文档列表,当使用 with 条件时使用 * * @deprecated * * 1. 调用 get() 执行主查询 * 2. 结合主查询的结果,使用 in 执行子表查询 * 3. 合并主表 & 子表的结果,即聚合 * 4. intersection 可指定是否取两个结果集的交集,缺省则以主表结果为主 */ public async merge<T = any>(options?: { intersection?: boolean }): Promise<GetRes<T>> { const res = await this.internalMerge(options) return res } /** * 获取总数 */ public async count(): Promise<CountRes> { const param = this.buildQueryParam() const res = await this.send(ActionType.count, param) if (res.error) { return { requestId: res.requestId, ok: false, error: res.error, total: undefined, code: res.code } } return { requestId: res.requestId, total: res.data.total, ok: true } } /** * 发起请求批量更新文档 * * @param data 数据 */ public async update(data: Object, options?: { multi?: boolean, merge?: boolean, upsert?: boolean }): Promise<UpdateRes> { if (!data || typeof data !== 'object' || 0 === Object.keys(data)?.length) { throw new Error('data cannot be empty object') } if (data.hasOwnProperty('_id')) { throw new Error('can not update the `_id` field') } const param = this.buildQueryParam() param.multi = options?.multi ?? false param.merge = options?.merge ?? true param.upsert = options?.upsert ?? false if (param.merge) { param.data = UpdateSerializer.encode(data) } else { param.data = serialize(data) } const res = await this.send(ActionType.update, param) if (res.error) { return { requestId: res.requestId, error: res.error, ok: false, code: res.code, updated: undefined, matched: undefined, upsertId: undefined } } return { requestId: res.requestId, updated: res.data.updated, matched: res.data.matched, upsertId: res.data.upsert_id, ok: true } } /** * 条件删除文档 */ public async remove(options?: { multi: boolean }): Promise<RemoveRes> { if (Object.keys(this._queryOptions).length > 0) { console.warn('`offset`, `limit` and `projection` are not supported in remove() operation') } if (this._fieldOrders?.length > 0) { console.warn('`orderBy` is not supported in remove() operation') } const param = this.buildQueryParam() param.multi = options?.multi ?? false const res = await this.send(ActionType.remove, param) if (res.error) { return { requestId: res.requestId, error: res.error, ok: false, deleted: undefined, code: res.code } } return { requestId: res.requestId, deleted: res.data.deleted, ok: true } } /** * Build query param * @returns */ protected buildQueryParam() { const param: QueryParam = { collectionName: this._coll, } if (this._fieldFilters) { param.query = this._fieldFilters } if (this._fieldOrders?.length) { param.order = [...this._fieldOrders] } if (this._queryOptions.offset) { param.offset = this._queryOptions.offset } if (this._queryOptions.limit) { param.limit = this._queryOptions.limit < 1000 ? this._queryOptions.limit : 1000 } else { param.limit = 100 } if (this._queryOptions.projection) { param.projection = this._queryOptions.projection } if (this._queryOptions.count) { param.count = this._queryOptions.count } return param } /** * 发起请求获取文档列表 */ protected async internalGet<T = any>(): Promise<GetRes<T>> { const param = this.buildQueryParam() const res = await this.send(ActionType.query, param) if (res.error) { return { error: res.error, data: res.data, requestId: res.requestId, ok: false, code: res.code } } const documents: any[] = Util.formatResDocumentData(res.data.list) const result: GetRes<T> = { data: documents, requestId: res.requestId, ok: true } if (res.total) result.total = res.data?.total if (res.limit) result.limit = res.data?.limit if (res.offset) result.offset = res.data?.offset return result } /** * 发起请求获取文档列表,当使用 with 条件时使用 * * 1. 调用 internalGet() 执行主查询 * 2. 结合主查询的结果,使用 in 执行子表查询 * 3. 合并主表 & 子表的结果,即聚合 * 4. intersection 可指定是否取两个结果集的交集,缺省则以主表结果为主 */ protected async internalMerge<T = any>(options?: { intersection?: boolean }): Promise<GetRes<T>> { options = options ?? {} as any const intersection = options?.intersection ?? false // 调用 get() 执行主查询 const res = await this.internalGet() if (!res.ok) { return res as any } // 针对每一个 WithParam 做合并处理 for (let _with of this._withs) { const { query, localField, foreignField, as, one } = _with const localValues = res.data.map(localData => localData[localField]) // 处理子查询 let q = query.clone() if (!q._fieldFilters) { q._fieldFilters = {} } q._fieldFilters[foreignField] = { '$in': localValues } // 执行子查询 let r_sub: (GetRes<T>) if (q._withs.length) { r_sub = await q.merge() // 如果子查询也使用了 with/withOne,则使用 merge() 查询 } else { r_sub = await q.get() } if (!r_sub.ok) { return r_sub } // 按照 localField -> foreignField 的连接关系将子查询结果聚合: // 1. 构建 { [value of `foreignField`]: [subQueryData] } 映射表 const _map = {} for (let sub of r_sub.data) { const key = sub[foreignField] // 将子表结果的连接键的值做为映射表的 key if (one) { _map[key] = sub } else { _map[key] = _map[key] || [] _map[key].push(sub) // 将子表结果放入映射表 } } // 2. 将聚合结果合并入主表结果集中 const results = [] for (let m of res.data) { // 此处主表结果中的 [value of `localField`] 与 上面子表结果中的 [value of `foreignField`] 应该是一致的 const key = m[localField] m[as] = _map[key] // 如果取交集且子表结果无对应数据,则丢弃此条数据 if (intersection && !_map[key]) { continue } results.push(m) } res.data = results } return res as any } /** * Send query request * @param action * @param param * @returns */ public async send(action: ActionType, param: QueryParam) { return await this._request.send(action, param) } }
the_stack
import {createStore, createEvent, createEffect, Event, forward} from 'effector' const typecheck = '{global}' test('forward between events', () => { const forward_event1 = createEvent<number>() const forward_event2 = createEvent<number>() forward({ from: forward_event1, to: forward_event2, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) describe('forward between effects', () => { test('start in parallel with the same payload', () => { const forward_effect_par1 = createEffect<number, string, string>() const forward_effect_par2 = createEffect<number, string, string>() forward({ from: forward_effect_par1, to: forward_effect_par2, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('start sequentially', () => { const forward_effect_seq1 = createEffect<number, string, string>() const forward_effect_seq2 = createEffect<string, boolean, boolean>() forward({ from: forward_effect_seq1.done.map(({result}) => result), to: forward_effect_seq2, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) test('forward between stores (should pass)', () => { const e = createStore(0) const f = createStore(0) forward({from: e, to: f}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('from unknown to known type (should fail)', () => { const emitUnknown = createEvent<unknown>() const receiveNumber = createEvent<number>() forward({ //@ts-expect-error from: emitUnknown, to: receiveNumber, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. The last overload gave the following error. Type 'Event<unknown>' is not assignable to type 'Unit<number>'. Types of property '__' are incompatible. Type 'unknown' is not assignable to type 'number'. " `) }) describe('forward with subtyping', () => { const str: Event<string> = createEvent() const strOrNum: Event<string | number> = createEvent() const num: Event<number> = createEvent() it('incompatible (should fail)', () => { //@ts-expect-error forward({from: str, to: num}) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. The last overload gave the following error. Type 'Event<string>' is not assignable to type 'Unit<number>'. Types of property '__' are incompatible. Type 'string' is not assignable to type 'number'. " `) }) it('same types (should pass)', () => { forward({from: str, to: str}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('more strict -> less strict type (should pass)', () => { forward({from: str, to: strOrNum}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('less strict -> more strict type (should fail)', () => { //@ts-expect-error forward({from: strOrNum, to: str}) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. The last overload gave the following error. Type 'Event<string | number>' is not assignable to type 'Unit<string>'. Types of property '__' are incompatible. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'. " `) }) it('generic from (?)', () => { forward<string | number>({from: strOrNum, to: str}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('generic to (should fail)', () => { //@ts-expect-error forward<string>({from: strOrNum, to: str}) expect(typecheck).toMatchInlineSnapshot(` " Type 'Event<string | number>' is not assignable to type 'Unit<string & {}>'. Types of property '__' are incompatible. Type 'string | number' is not assignable to type 'string & {}'. Type 'number' is not assignable to type 'string & {}'. Type 'number' is not assignable to type 'string'. " `) }) it('generics `to` and `from` (should pass)', () => { forward<string | number, string>({to: strOrNum, from: str}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('generics `to` and `from` (should fail on providing generics)', () => { //@ts-expect-error forward<string, string | number>({to: str, from: strOrNum}) expect(typecheck).toMatchInlineSnapshot(` " Type 'string | number' does not satisfy the constraint 'string'. Type 'number' is not assignable to type 'string'. " `) }) }) describe('any to void support', () => { it('should forward from `Unit<*>` to `Unit<void>` (should pass)', () => { const from = createEvent<string>() const to = createEvent<void>() forward({from, to}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('should forward from `Unit<*>[]` to `Unit<void>[]` (should pass)', () => { const from = createEvent<string>() const to = createEvent<void>() forward({from: [from], to: [to]}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('should forward from `Unit<*>` to `Unit<void>[]` (should pass)', () => { const from = createEvent<string>() const to = createEvent<void>() forward({from, to: [to]}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('should forward from `Unit<*>` to array with mixed units (should pass)', () => { const from = createEvent<string>() const to1 = createEvent<void>() const to2 = createEvent<string>() forward({from, to: [to1, to2]}) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. The last overload gave the following error. Type 'Event<string>' is not assignable to type 'Unit<void>'. Types of property '__' are incompatible. Type 'string' is not assignable to type 'void'. Type 'Event<string>' is not assignable to type 'Unit<void>'. No overload matches this call. The last overload gave the following error. Type 'Event<string>' is not assignable to type 'Unit<void>'. Types of property '__' are incompatible. Type 'string' is not assignable to type 'void'. Type 'Event<string>' is not assignable to type 'Unit<void>'. " `) }) it('should forward from `Unit<*>[]` to `Unit<void>` (should pass)', () => { const from = createEvent<string>() const to = createEvent<void>() forward({from: [from], to}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) test('forward form event.map (should pass)', () => { const event1 = createEvent<string>() const event2 = createEvent<{value: string}>() forward({ from: event1.map(value => ({value})), to: event2, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('forward to event.prepend (should pass)', () => { const event1 = createEvent<string>() const event2 = createEvent<{value: string}>() forward({ from: event1, to: event2.prepend(value => ({value})), }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('edge case #1 (should fail)', () => { const event1 = createEvent<string>() const event2 = createEvent<{value: string}>() forward({ //@ts-expect-error from: event1, to: event2.map(value => ({value})), }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. The last overload gave the following error. Type 'Event<string>' is not assignable to type 'Unit<{ value: { value: string; }; }>'. Types of property '__' are incompatible. Type 'string' is not assignable to type '{ value: { value: string; }; }'. " `) }) describe('array support', () => { describe('forward to array', () => { test('valid (should pass)', () => { const s1 = createEvent<string>() const t1 = createEvent<string>() const t2 = createEvent<string>() forward({ from: s1, to: [t1, t2], }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) describe('invalid', () => { test('type mismatch (should fail)', () => { const s1 = createEvent<number>() const t1 = createEvent<string>() const t2 = createEvent<string>() forward({ //@ts-expect-error from: s1, to: [t1, t2], }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. The last overload gave the following error. Type 'Event<number>' is not assignable to type 'Unit<string>'. Types of property '__' are incompatible. Type 'number' is not assignable to type 'string'. " `) }) test('array mismatch (should fail)', () => { const s1 = createEvent<string>() const t1 = createEvent<string>() const t2 = createEvent<number>() forward({ //@ts-expect-error from: s1, //@ts-expect-error to: [t1, t2], }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. The last overload gave the following error. Type 'Event<string>' is not assignable to type 'Unit<number>'. Type 'Event<string>' is not assignable to type 'Unit<number>'. No overload matches this call. The last overload gave the following error. Type 'Event<string>' is not assignable to type 'Unit<number>'. Type 'Event<string>' is not assignable to type 'Unit<number>'. " `) }) }) }) describe('forward from array', () => { test('valid (should pass)', () => { const s1 = createEvent<string>() const s2 = createEvent<string>() const t1 = createEvent<string>() forward({ from: [s1, s2], to: t1, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) describe('invalid', () => { test('type mismatch (should fail)', () => { const s1 = createEvent<string>() const s2 = createEvent<string>() const t1 = createEvent<number>() forward({ //@ts-expect-error from: [s1, s2], to: t1, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. The last overload gave the following error. Type 'Event<string>[]' is missing the following properties from type 'Unit<number>': kind, __ " `) }) test('array mismatch (should fail)', () => { const s1 = createEvent<string>() const s2 = createEvent<number>() const t1 = createEvent<string>() forward({ //@ts-expect-error from: [s1, s2], to: t1, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. The last overload gave the following error. Type '(Event<number> | Event<string>)[]' is missing the following properties from type 'Unit<string>': kind, __ " `) }) }) }) })
the_stack
import { autoinject } from 'aurelia-dependency-injection' import { Entity, EntityCollection, Cartographic, ConstantPositionProperty, ConstantProperty, Cartesian3, Quaternion, Matrix3, Matrix4, CesiumMath, Transforms, JulianDate, ReferenceFrame, PerspectiveFrustum } from './cesium/cesium-imports' import { DEFAULT_NEAR_PLANE, DEFAULT_FAR_PLANE, SerializedEntityStateMap, SerializedSubviewList, SubviewType, ContextFrameState, Role, GeolocationOptions, CanvasViewport, Viewport } from './common' import { SessionService, SessionPort } from './session' import { Event, stringIdentifierFromReferenceFrame, // getReachableAncestorReferenceFrames, getSerializedEntityState, getEntityPositionInReferenceFrame, getEntityOrientationInReferenceFrame, deprecated, decomposePerspectiveProjectionMatrix } from './utils' import { EntityService, EntityServiceProvider, EntityPose } from './entity' import { DeviceService } from './device' import { eastUpSouthToFixedFrame } from './utils' import { ViewService } from './view' import { PermissionState, PermissionServiceProvider } from './permission' /** * Provides a means of querying the current state of reality. */ @autoinject() export class ContextService { constructor( protected entityService: EntityService, protected sessionService: SessionService, protected deviceService: DeviceService, protected viewService: ViewService, ) { this.sessionService.manager.on['ar.context.update'] = (state: ContextFrameState) => { const scratchFrustum = this._scratchFrustum; // backwards-compat if (typeof state.reality !== 'string') { state.reality = state.reality && state.reality['uri']; } if (!state.viewport && state['view'] && state['view'].viewport) { state.viewport = state['view'].viewport; } if (!state.subviews && state['view'] && state['view'].subviews) { state.subviews = state['view'].subviews; scratchFrustum.near = DEFAULT_NEAR_PLANE; scratchFrustum.far = DEFAULT_FAR_PLANE; for (const s of state.subviews) { const frustum = s['frustum']; scratchFrustum.xOffset = frustum.xOffset || 0; scratchFrustum.yOffset = frustum.yOffset || 0; scratchFrustum.fov = frustum.fov || CesiumMath.PI_OVER_THREE; scratchFrustum.aspectRatio = frustum.aspectRatio || 1; s.projectionMatrix = Matrix4.clone(scratchFrustum.projectionMatrix, s.projectionMatrix); } } if (!state.entities![this.user.id] && state['view'] && state['view'].pose) { state.entities![this.user.id] = state['view'].pose; } // end backwards-compat this._update(state); } this.origin.definitionChanged.addEventListener((origin, property)=>{ if (property === 'position' || property === 'orientation') { if (origin.position) { origin.position.definitionChanged.addEventListener(()=>{ this._originChanged = true; }); } if (origin.orientation) { origin.orientation.definitionChanged.addEventListener(()=>{ this._originChanged = true; }); } this._originChanged = true; } }); this._scratchFrustum.near = DEFAULT_NEAR_PLANE; this._scratchFrustum.far = DEFAULT_FAR_PLANE; this._scratchFrustum.fov = CesiumMath.PI_OVER_THREE; this._scratchFrustum.aspectRatio = 1; this._serializedFrameState = { reality: undefined, time: JulianDate.now(), entities: {}, viewport: new CanvasViewport, subviews: [{ type: SubviewType.SINGULAR, viewport: new Viewport, projectionMatrix: this._scratchFrustum.projectionMatrix }], }; } public get entities() : EntityCollection { return this.entityService.collection } /** * An event that is raised after managed entities have been updated for * the current frame. */ public updateEvent = new Event<ContextService>(); /** * An event that is raised when it is an approriate time to render graphics. * This event fires after the update event. */ public renderEvent = new Event<ContextService>(); /** * An event that is raised after the render event */ public postRenderEvent = new Event<ContextService>(); /** * An event that fires when the origin changes. */ public originChangeEvent = new Event<void>(); private _originChanged = false; /** * An event that fires when the local origin changes. */ @deprecated('originChangeEvent') public get localOriginChangeEvent() {return this.originChangeEvent}; /** * A monotonically increasing value (in milliseconds) for the current frame state. * This value is useful only for doing accurate *timing*, not for determining * the absolute time. Use [[ContextService.time]] for absolute time. * This value is -1 until the first [[ContextService.updateEvent]]. */ public timestamp = -1; /** * The time in milliseconds since the previous timestamp, * capped to [[ContextService.maxDeltaTime]] */ public deltaTime = 0; /** * This value caps the deltaTime for each frame. By default, * the value is 1/3s (333.3ms) */ public maxDeltaTime = 1 / 3 * 1000; /** * The current (absolute) time according to the current reality. * This value is arbitrary until the first [[ContextService.updateEvent]]. */ public time = new JulianDate(0,0); /** * An entity representing the local origin, which is oriented * with +Y up. The local origin changes infrequently, is platform dependent, * and is the suggested origin for a rendering scenegraph. * * Any time the local origin changes, the localOriginChange event is raised. */ public origin: Entity = this.entities.add(new Entity({ id: 'ar.origin', name: 'Origin', position: new ConstantPositionProperty(undefined, ReferenceFrame.FIXED), orientation: new ConstantProperty(undefined) })); /** alias for origin */ @deprecated('origin') public get localOrigin() { return this._localOrigin } private _localOrigin = this.entities.add(new Entity({ id: 'ar.localOrigin', name: 'Local Origin', position: new ConstantPositionProperty(Cartesian3.ZERO, this.origin), orientation: new ConstantProperty(Quaternion.IDENTITY) })); // To be removed. This is no longer useful. @deprecated() public get localOriginEastUpSouth() {return this._localOrigin;} // To be removed. This is no longer useful. @deprecated() public get localOriginEastNorthUp() { return this._localOriginEastNorthUp; } private _localOriginEastNorthUp: Entity = this.entities.add(new Entity({ id: 'ar.localOriginENU', name: 'Local Origin (ENU)', position: new ConstantPositionProperty(Cartesian3.ZERO, this.localOriginEastNorthUp), orientation: new ConstantProperty(Quaternion.fromAxisAngle(Cartesian3.UNIT_X, -Math.PI / 2)) })); /** * A coordinate system representing the physical space in which the user is free to * move around, positioned on the surface the user is standing on, * where +X is east, +Y is up, and +Z is south (East-Up-South), if geolocation is known. * If the stage is not geolocated, then the +X and +Z directions are arbitrary. */ public stage: Entity = this.entities.add(new Entity({ id: 'ar.stage', name: 'Stage', position: new ConstantPositionProperty(undefined, ReferenceFrame.FIXED), orientation: new ConstantProperty(undefined) })); /** * A coordinate system representing the floor. * While the `stage` always represents a physical surface, * the `floor` entity may represent a virtual floor. */ public floor: Entity = this.entities.add(new Entity({ id: 'ar.floor', name: 'Floor', position: new ConstantPositionProperty(Cartesian3.ZERO, this.stage), orientation: new ConstantProperty(Quaternion.IDENTITY) })); /** * An coordinate system representing the user, * where +X is right, +Y is up, and -Z is the direction the user is facing */ public user: Entity = this.entities.add(new Entity({ id: 'ar.user', name: 'User', position: new ConstantPositionProperty(undefined, this.stage), orientation: new ConstantProperty(undefined) })); /** * An coordinate system representing the rendering view, * where +X is right, +Y is up, and -Z is the direction of the view. */ public view: Entity = this.entities.add(new Entity({ id: 'ar.view', name: 'View', position: new ConstantPositionProperty(Cartesian3.ZERO, this.user), orientation: new ConstantProperty(Quaternion.IDENTITY) })); /** * The default reference frame to use when calling `getEntityPose`. * By default, this is the `origin` reference frame. */ public defaultReferenceFrame = this.origin; /** * If geopose is available, this is the accuracy of the user's heading */ public get geoposeHeadingAccuracy() : number|undefined { return this.stage['meta'].geoposeHeadingAccuracy; } /** * If geopose is available, this is the accuracy of the user's cartographic location */ public get geoposeHorizontalAccuracy() : number|undefined { return this.stage['meta'].geoposeHorizontalAccuracy; } /** * If geopose is available, this is the accuracy of the user's elevation */ public get geoposeVerticalAccuracy() : number|undefined { return this.stage['meta'].geoposeVerticalAccuracy; } /** * The serialized frame state for this frame */ public get serializedFrameState() { return this._serializedFrameState; } // the current serialized frame state private _serializedFrameState: ContextFrameState; private _entityPoseMap = new Map<string, EntityPose | undefined>(); private _updatingEntities = new Set<string>(); private _knownEntities = new Set<string>(); private _scratchCartesian = new Cartesian3; private _scratchQuaternion = new Quaternion; private _scratchFrustum = new PerspectiveFrustum(); /** * Deprecated. Use timestamp property. * @private */ @deprecated('timestamp') public get systemTime() { return this.timestamp; } /** * Deprecated. To be removed. * @private */ @deprecated('time') public getTime(): JulianDate { return this.time; } /** * Deprecated. To be removed. Use the defaultReferenceFrame property if necessary. * @private */ @deprecated() public setDefaultReferenceFrame(origin: Entity) { this.defaultReferenceFrame = origin; } /** * Deprecated. To be removed. Use the defaultReferenceFrame property. * @private */ @deprecated('defaultReferenceFrame') public getDefaultReferenceFrame(): Entity { return this.defaultReferenceFrame; } /** * Subscribe to pose updates for an entity specified by the given id * * @deprecated Use [[ContextService#subscribe]] * @param id - the id of the desired entity * @returns A new or existing entity instance matching the given id */ @deprecated('subscribe') public subscribeToEntityById(id: string): Entity { this.subscribe(id); return this.entities.getOrCreateEntity(id); } /** * Subscribe to pose updates for the given entity id * * @returns A Promise that resolves to a new or existing entity * instance matching the given id, if the subscription is successful */ public subscribe = this.entityService.subscribe.bind(this.entityService); /** * Unsubscribe to pose updates for the given entity id */ public unsubscribe = this.entityService.unsubscribe.bind(this.entityService); /** * Get the cartographic position of an Entity for the current context time */ public getEntityCartographic(entity:Entity, result?:Cartographic) : Cartographic|undefined { return this.entityService.getCartographic(entity, this.time, result); } /** * Deprecated. Use `EntityService.createFixed` (`app.entity.createFixed`); */ @deprecated('EntityService.createFixed') public createGeoEntity(cartographic:Cartographic, localToFixed:typeof Transforms.eastNorthUpToFixedFrame) { return this.entityService.createFixed(cartographic, localToFixed); } /** * Create a new EntityPose instance to represent the pose of an entity * relative to a given reference frame. If no reference frame is specified, * then the pose is based on the context's defaultReferenceFrame. * * @param entityOrId - the entity to track * @param referenceFrameOrId - The intended reference frame. Defaults to `this.defaultReferenceFrame`. */ public createEntityPose(entityOrId: Entity|string, referenceFrameOrId: string | ReferenceFrame | Entity = this.defaultReferenceFrame) : EntityPose { return this.entityService.createEntityPose(entityOrId, referenceFrameOrId); } private _stringIdentifierFromReferenceFrame = stringIdentifierFromReferenceFrame; /** * Gets the current pose of an entity, relative to a given reference frame. * * @deprecated * @param entityOrId - The entity whose state is to be queried. * @param referenceFrameOrId - The intended reference frame. Defaults to `this.defaultReferenceFrame`. */ public getEntityPose(entityOrId: Entity|string, referenceFrameOrId: string | ReferenceFrame | Entity = this.defaultReferenceFrame): EntityPose { const key = this._stringIdentifierFromReferenceFrame(entityOrId) + '@' + this._stringIdentifierFromReferenceFrame(referenceFrameOrId); let entityPose = this._entityPoseMap.get(key); if (!entityPose) { entityPose = this.entityService.createEntityPose(entityOrId, referenceFrameOrId); this._entityPoseMap.set(key, entityPose); } entityPose.update(this.time); return entityPose; } private _frameIndex = -1; /** * Process the next frame state (which should come from the current reality viewer) */ public submitFrameState(frameState: ContextFrameState) { frameState.index = ++this._frameIndex; this._update(frameState); } private _scratchFrameState:ContextFrameState = { time:<any>{}, entities: {}, viewport: <any>{}, subviews: [] } private _getSerializedEntityState = getSerializedEntityState; private _getEntityPositionInReferenceFrame = getEntityPositionInReferenceFrame; private _getEntityOrientationInReferenceFrame = getEntityOrientationInReferenceFrame; /** * Create a frame state. * * @param time * @param viewport * @param subviewList * @param user * @param entityOptions */ public createFrameState( time:JulianDate, viewport:CanvasViewport, subviewList:SerializedSubviewList, options?: {overrideStage?:boolean, overrideUser?:boolean, overrideView?:boolean, overrideSubviews?:boolean, floorOffset?:number} ) : ContextFrameState { let overrideUser = options && options.overrideUser; if (this.deviceService.strict) { if (overrideUser) { console.warn('The `overrideUser` flag is set, but the device is in strict mode'); overrideUser = false; } } const frameState:ContextFrameState = this._scratchFrameState; frameState.time = JulianDate.clone(time, frameState.time); frameState.viewport = CanvasViewport.clone(viewport, frameState.viewport)!; frameState.subviews = SerializedSubviewList.clone(subviewList, frameState.subviews)!; const entities = frameState.entities = {}; const getSerializedEntityState = this._getSerializedEntityState; // stage const stage = this.stage; if (options && options.overrideStage) { entities[stage.id] = getSerializedEntityState(stage, time, undefined); } // user const user = this.user; if (overrideUser) { entities[user.id] = getSerializedEntityState(user, time, stage); } // view const view = this.view; if (options && options.overrideView) { entities[view.id] = getSerializedEntityState(view, time, user); } // subviews for (let index=0; index < subviewList.length; index++) { // check for valid projection matrices const subview = subviewList[index]; if (!isFinite(subview.projectionMatrix[0])) throw new Error('Invalid projection matrix (contains non-finite values)'); if (options && options.overrideSubviews) { const subviewEntity = this.getSubviewEntity(index); entities[subviewEntity.id] = getSerializedEntityState(subviewEntity, time, view); } } // floor const floorOffset = options && options.floorOffset || 0; const floor = this.floor; (floor.position as ConstantPositionProperty).setValue(Cartesian3.fromElements(0,floorOffset,0, this._scratchCartesian), stage); if (floorOffset !== 0) { frameState.entities[this.floor.id] = getSerializedEntityState(floor, time, stage); } return frameState; } private _scratchMatrix3 = new Matrix3; private _scratchMatrix4 = new Matrix4; // All of the following work is only necessary when running in an old manager (version === 0) private _updateBackwardsCompatability(frameState:ContextFrameState) { this._knownEntities.clear(); // update the entities the manager knows about const entityService = this.entityService; for (const id in frameState.entities) { entityService.updateEntityFromSerializedState(id, frameState.entities[id]); this._updatingEntities.add(id); this._knownEntities.add(id); } // if the mangager didn't send us an update for a particular entity, // assume the manager no longer knows about it for (const id of <string[]><any>this._updatingEntities) { if (!this._knownEntities.has(id)) { let entity = this.entities.getById(id); if (entity) { if (entity.position) (entity.position as ConstantPositionProperty).setValue(undefined); if (entity.orientation) (entity.orientation as ConstantProperty).setValue(undefined); } this._updatingEntities.delete(id); } } // If running within an older manager, we have to set the stage based on the user pose. const userPositionFixed = this._getEntityPositionInReferenceFrame( this.user, frameState.time, ReferenceFrame.FIXED, this._scratchCartesian ); if (userPositionFixed) { const eusToFixedFrameTransform = eastUpSouthToFixedFrame(userPositionFixed, undefined, this._scratchMatrix4); const eusRotationMatrix = Matrix4.getRotation(eusToFixedFrameTransform, this._scratchMatrix3); const eusOrientation = Quaternion.fromRotationMatrix(eusRotationMatrix); (this.stage.position as ConstantPositionProperty).setValue(userPositionFixed, ReferenceFrame.FIXED); (this.stage.orientation as ConstantProperty).setValue(eusOrientation); } else { (this.stage.position as ConstantPositionProperty).setValue(Cartesian3.fromElements(0,-this.deviceService.suggestedUserHeight, 0, this._scratchCartesian), this.user.position!.referenceFrame); (this.stage.orientation as ConstantProperty).setValue(Quaternion.IDENTITY); } frameState.entities[this.stage.id] = <any>true; // assume overriden for _update } // TODO: This function is called a lot. Potential for optimization. private _update(frameState: ContextFrameState) { this._serializedFrameState = frameState; const time = frameState.time; const entities = frameState.entities; // update our time values const timestamp = performance.now(); this.deltaTime = Math.min(timestamp - this.timestamp, this.maxDeltaTime); this.timestamp = timestamp; JulianDate.clone(<JulianDate>frameState.time, this.time); // update provided entities if (this.sessionService.manager.isConnected && this.sessionService.manager.version[0] === 0) { this._updateBackwardsCompatability(frameState); } else { const entityService = this.entityService; for (const id in entities) { entityService.updateEntityFromSerializedState(id, entities[id]); } } // update stage entity const deviceStage = this.deviceService.stage; const contextStage = this.stage; if (entities[contextStage.id] === undefined) { const contextStagePosition = contextStage.position as ConstantPositionProperty; const contextStageOrientation = contextStage.orientation as ConstantProperty; contextStagePosition.setValue(Cartesian3.ZERO, deviceStage); contextStageOrientation.setValue(Quaternion.IDENTITY); } // update user entity const deviceUser = this.deviceService.user; const contextUser = this.user; if (entities[contextUser.id] === undefined) { const userPositionValue = this._getEntityPositionInReferenceFrame(deviceUser, time, deviceStage, this._scratchCartesian); const userOrientationValue = this._getEntityOrientationInReferenceFrame(deviceUser, time, deviceStage, this._scratchQuaternion); const contextUserPosition = contextUser.position as ConstantPositionProperty; const contextUserOrientation = contextUser.orientation as ConstantProperty; contextUserPosition.setValue(userPositionValue, contextStage); contextUserOrientation.setValue(userOrientationValue); } // update view entity const contextView = this.view; if (entities[contextView.id] === undefined) { const contextViewPosition = contextView.position as ConstantPositionProperty; const contextViewOrientation = contextView.orientation as ConstantProperty; contextViewPosition.setValue(Cartesian3.ZERO, contextUser); contextViewOrientation.setValue(Quaternion.IDENTITY); } // update subview entities for (let i=0; i<frameState.subviews.length; i++) { if (entities['ar.view_' + i] === undefined) { const deviceSubview = this.deviceService.getSubviewEntity(i); const contextSubview = this.getSubviewEntity(i); const subviewPositionValue = this._getEntityPositionInReferenceFrame(deviceSubview, time, deviceUser, this._scratchCartesian); const subviewOrientationValue = this._getEntityOrientationInReferenceFrame(deviceSubview, time, deviceUser, this._scratchQuaternion); const contextSubviewPosition = contextSubview.position as ConstantPositionProperty; const contextSubviewOrientation = contextSubview.orientation as ConstantProperty; contextSubviewPosition.setValue(subviewPositionValue, contextView); contextSubviewOrientation.setValue(subviewOrientationValue); } } // update floor entity if (entities[this.floor.id] === undefined) { const floorPosition = this.floor.position as ConstantPositionProperty; floorPosition.setValue(Cartesian3.ZERO, contextStage); } // update origin entity if (entities[this.origin.id] === undefined) { const deviceOrigin = this.deviceService.origin; const contextOrigin = this.origin; const deviceOriginPositionValue = this._getEntityPositionInReferenceFrame(deviceOrigin, time, deviceStage, this._scratchCartesian); const deviceOriginOrientationValue = this._getEntityOrientationInReferenceFrame(deviceOrigin, time, deviceStage, this._scratchQuaternion); const contextOriginPosition = contextOrigin.position as ConstantPositionProperty; const contextOriginOrientation = contextOrigin.orientation as ConstantProperty; contextOriginPosition.setValue(deviceOriginPositionValue, contextStage); contextOriginOrientation.setValue(deviceOriginOrientationValue); } // update view this.viewService._processContextFrameState(frameState, this); // TODO: realityService._processContextFrameState(frameState); // raise events for the user to update and render the scene if (this._originChanged) { this._originChanged = false; const originPosition = this.origin.position as ConstantPositionProperty; console.log('Updated context origin to ' + JSON.stringify(originPosition['_value']) + " at " + this._stringIdentifierFromReferenceFrame(originPosition.referenceFrame)); this.originChangeEvent.raiseEvent(undefined); } this.updateEvent.raiseEvent(this); this.renderEvent.raiseEvent(this); this.postRenderEvent.raiseEvent(this); // submit frame if necessary const vrDisplay:VRDisplay|undefined = this.deviceService.vrDisplay; if (this.deviceService.autoSubmitFrame && vrDisplay && vrDisplay.isPresenting) { vrDisplay.submitFrame(); } } getSubviewEntity(index:number) { const subviewEntity = this.entityService.collection.getOrCreateEntity('ar.view_'+index); if (!subviewEntity.position) { subviewEntity.position = new ConstantPositionProperty(Cartesian3.ZERO, this.user); } if (!subviewEntity.orientation) { subviewEntity.orientation = new ConstantProperty(Quaternion.IDENTITY); } return subviewEntity; } subscribeGeolocation(options?:GeolocationOptions) : Promise<void> { return this.entityService.subscribe(this.stage.id, options).then(()=>{}); } unsubscribeGeolocation() : void { this.entityService.unsubscribe(this.stage.id); } public get geoHeadingAccuracy() : number|undefined { return this.user['meta'] && this.user['meta'].geoHeadingAccuracy; } public get geoHorizontalAccuracy() : number|undefined { return this.user['meta'] && this.user['meta'].geoHorizontalAccuracy || this.stage['meta'] && this.stage['meta'].geoHorizontalAccuracy; } public get geoVerticalAccuracy() : number|undefined { return this.user['meta'] && this.user['meta'].geoVerticalAccuracy || this.stage['meta'] && this.stage['meta'].geoVerticalAccuracy; } } @autoinject() export class ContextServiceProvider { private _cacheTime = new JulianDate(0,0) constructor( protected sessionService:SessionService, protected contextService:ContextService, protected entityServiceProvider:EntityServiceProvider, protected permissionServiceProvider:PermissionServiceProvider ) { this.entityServiceProvider.targetReferenceFrameMap.set(this.contextService.stage.id, ReferenceFrame.FIXED); // subscribe to context geolocation if any child sessions have subscribed this.entityServiceProvider.sessionSubscribedEvent.addEventListener((evt)=>{ if (evt.id === this.contextService.stage.id && evt.session !== this.sessionService.manager) { this._setGeolocationOptions(evt.session, evt.options); this.contextService.subscribeGeolocation(this.desiredGeolocationOptions); } }) // unsubscribe from context geolocation if all child sessions are unsubscribed this.entityServiceProvider.sessionUnsubscribedEvent.addEventListener(()=>{ const subscribers = this.entityServiceProvider.subscribersByEntity.get(this.contextService.stage.id); if (subscribers && subscribers.size === 1 && subscribers.has(this.sessionService.manager)) { this.contextService.unsubscribeGeolocation(); } }) // publish updates to child sessions this.contextService.updateEvent.addEventListener(()=>{ this._publishUpdates(); }); } private _publishUpdates() { const state = this.contextService.serializedFrameState!; this._cacheTime = JulianDate.clone(state.time, this._cacheTime); for (const session of this.sessionService.managedSessions) { if (Role.isRealityAugmenter(session.info.role)) this._sendUpdateForSession(state, session); } } private _sessionEntities:SerializedEntityStateMap = {}; private _temp:any = {}; private _sendUpdateForSession(state:ContextFrameState, session: SessionPort) { const sessionEntities = this._sessionEntities; const entityServiceProvider = this.entityServiceProvider // clear session entities for (var id in sessionEntities) { delete sessionEntities[id]; } // reference all entities from the primary frame state if (state.entities) { for (var id in state.entities) { sessionEntities[id] = state.entities[id]; } } // always send the origin state sessionEntities[this.contextService.origin.id] = entityServiceProvider.getCachedSerializedEntityState(this.contextService.origin, state.time) // get subscribed entities for the session const subscriptions = entityServiceProvider.subscriptionsBySubscriber.get(session)!; // exclude the stage state unless it is explicitly subscribed const contextService = this.contextService; const contextStageId = contextService.stage.id; if (!subscriptions[contextStageId]) delete sessionEntities[contextStageId]; // add the entity states for all subscribed entities const iter = subscriptions.keys(); let item:IteratorResult<string>; while (item = iter.next(), !item.done) { // not using for-of since typescript converts this to broken es5 const id = item.value; const entity = contextService.entities.getById(id); sessionEntities[id] = entityServiceProvider.getCachedSerializedEntityState(entity, state.time); } // remove stage updates if geolocation permission is not granted if (this.permissionServiceProvider.getPermissionState(session, 'geolocation') != PermissionState.GRANTED) delete sessionEntities[contextStageId]; // recycle the frame state object, but with the session entities const parentEntities = state.entities; state.entities = sessionEntities; state.time = state.time; state.sendTime = JulianDate.now(state.sendTime); if (session.version[0] === 0) { // backwards compatability with older viewers / augmenters for (const s of state.subviews) { s['frustum'] = s['frustum'] || decomposePerspectiveProjectionMatrix(s.projectionMatrix, <any>{}); } const view = this._temp; view.viewport = state.viewport; view.subviews = state.subviews; view.pose = state.entities['ar.user']; delete state.subviews; delete state.viewport; delete state.entities['ar.user']; state['view'] = view; session.send('ar.context.update', state); delete state['view']; state.viewport = view.viewport; state.subviews = view.subviews; } else if (session.version[0] === 1 && session.version[1] === 1 && state.entities['ar.user']) { state.entities['ar.user']!.r = 'ar.stageEUS'; session.send('ar.context.update', state); state.entities['ar.user']!.r = 'ar.stage'; } else { session.send('ar.context.update', state); } // restore the parent entities state.entities = parentEntities; } public desiredGeolocationOptions:GeolocationOptions = {}; public sessionGeolocationOptions = new Map<SessionPort, GeolocationOptions|undefined>(); private _setGeolocationOptions(session:SessionPort, options?:GeolocationOptions) { this.sessionGeolocationOptions.set(session, options); session.closeEvent.addEventListener(()=>{ this.sessionGeolocationOptions.delete(session); this._updateDesiredGeolocationOptions(); }); this._updateDesiredGeolocationOptions(); } private _updateDesiredGeolocationOptions() { const reducedOptions:GeolocationOptions = {}; this.sessionGeolocationOptions.forEach((options, session)=>{ reducedOptions.enableHighAccuracy = reducedOptions.enableHighAccuracy || (options && options.enableHighAccuracy) || false; }); if (this.desiredGeolocationOptions.enableHighAccuracy !== reducedOptions.enableHighAccuracy) { this.desiredGeolocationOptions = reducedOptions; } } }
the_stack
import { NeuralNetwork } from './neural-network'; const data = [ { input: [0, 0], output: [0] }, { input: [0, 1], output: [1] }, { input: [1, 0], output: [1] }, { input: [1, 1], output: [1] }, ]; describe('NeuralNetwork.train()', () => { describe('train() options', () => { it('train until error threshold reached', () => { const net = new NeuralNetwork(); const res = net.train(data, { errorThresh: 0.2 }); expect(res.error < 0.2).toBeTruthy(); }); it('train until max iterations reached', () => { const net = new NeuralNetwork(); const res = net.train(data, { iterations: 25 }); expect(res.iterations).toBe(25); }); it('training callback called with training stats', () => { const iters = 100; const period = 20; const target = iters / period; let calls = 0; const net = new NeuralNetwork(); net.train(data, { iterations: iters, callbackPeriod: period, callback: (res) => { expect(res.iterations % period === 0).toBeTruthy(); calls++; }, }); expect(target === calls).toBeTruthy(); }); it('learningRate - higher learning rate should train faster', () => { const data = [ { input: [0, 0], output: [0] }, { input: [0, 1], output: [1] }, { input: [1, 0], output: [1] }, { input: [1, 1], output: [1] }, ]; const net = new NeuralNetwork(); const res = net.train(data, { learningRate: 0.5 }); const net2 = new NeuralNetwork(); const res2 = net2.train(data, { learningRate: 0.8 }); expect(res.iterations > res2.iterations * 1.1).toBeTruthy(); }); it('momentum - higher momentum should train faster', () => { const data = [ { input: [0, 0], output: [0] }, { input: [0, 1], output: [1] }, { input: [1, 0], output: [1] }, { input: [1, 1], output: [1] }, ]; const net = new NeuralNetwork({ momentum: 0.1 }); const res = net.train(data); const net2 = new NeuralNetwork({ momentum: 0.5 }); const res2 = net2.train(data); expect(Math.abs(res.iterations - res2.iterations)).toBeLessThan(500); }); }); describe('train() and trainAsync()', () => { let prepTrainingSpy: jest.SpyInstance; let trainingTickSpy: jest.SpyInstance; beforeEach(() => { prepTrainingSpy = jest.spyOn(NeuralNetwork.prototype, 'prepTraining'); trainingTickSpy = jest.spyOn(NeuralNetwork.prototype, 'trainingTick'); }); afterEach(() => { prepTrainingSpy.mockRestore(); trainingTickSpy.mockRestore(); }); test('both call this.prepTraining()', async () => { const syncNet = new NeuralNetwork(); const options = { iterations: 1 }; syncNet.train(data, options); expect(prepTrainingSpy).toHaveBeenCalledWith(data, options); prepTrainingSpy.mockReset(); const asyncNet = new NeuralNetwork(); asyncNet.trainAsync(data, options).then(console.log).catch(console.error); expect(prepTrainingSpy).toHaveBeenCalledWith(data, options); }); test('both call this.trainingTick()', async () => { const syncNet = new NeuralNetwork(); const options = { iterations: 1 }; const dataFormatted = data.map((datum) => { return { input: Float32Array.from(datum.input), output: Float32Array.from(datum.output), }; }); syncNet.train(data, options); expect(trainingTickSpy.mock.calls[0][0]).toEqual(dataFormatted); expect(trainingTickSpy.mock.calls[0][1].error).toBeLessThan(2); expect(trainingTickSpy.mock.calls[0][1].iterations).toEqual(1); expect(trainingTickSpy.mock.calls[0][2]).toEqual(Infinity); trainingTickSpy.mockReset(); const asyncNet = new NeuralNetwork(); asyncNet.trainAsync(data, options).then(console.log).catch(console.error); expect(trainingTickSpy.mock.calls[0][0]).toEqual(dataFormatted); expect(trainingTickSpy.mock.calls[0][1].error).toBeLessThan(2); expect(trainingTickSpy.mock.calls[0][1].iterations).toEqual(0); expect(trainingTickSpy.mock.calls[0][2]).toEqual(Infinity); }); }); describe('training options validation', () => { it('iterations validation', () => { const net = new NeuralNetwork(); expect(() => { // @ts-expect-error iterations is expected as number net.updateTrainingOptions({ iterations: 'should be a string' }); }).toThrow(); expect(() => { // @ts-expect-error iterations is expected as number net.updateTrainingOptions({ iterations: () => {} }); }).toThrow(); expect(() => { // @ts-expect-error iterations is expected as number net.updateTrainingOptions({ iterations: false }); }).toThrow(); expect(() => { net.updateTrainingOptions({ iterations: -1 }); }).toThrow(); expect(() => { net.updateTrainingOptions({ iterations: 5000 }); }).not.toThrow(); }); it('errorThresh validation', () => { const net = new NeuralNetwork(); expect(() => { // @ts-expect-error errorThresh is expected as number net.updateTrainingOptions({ errorThresh: 'no strings' }); }).toThrow(); expect(() => { // @ts-expect-error errorThresh is expected as number net.updateTrainingOptions({ errorThresh: () => {} }); }).toThrow(); expect(() => { net.updateTrainingOptions({ errorThresh: 5 }); }).toThrow(); expect(() => { net.updateTrainingOptions({ errorThresh: -1 }); }).toThrow(); expect(() => { // @ts-expect-error errorThresh is expected as number net.updateTrainingOptions({ errorThresh: false }); }).toThrow(); expect(() => { net.updateTrainingOptions({ errorThresh: 0.008 }); }).not.toThrow(); }); it('log validation', () => { const net = new NeuralNetwork(); expect(() => { // @ts-expect-error log should be boolean or function net.updateTrainingOptions({ log: 'no strings' }); }).toThrow(); expect(() => { // @ts-expect-error log should be boolean or function net.updateTrainingOptions({ log: 4 }); }).toThrow(); expect(() => { net.updateTrainingOptions({ log: false }); }).not.toThrow(); expect(() => { net.updateTrainingOptions({ log: () => {} }); }).not.toThrow(); }); it('logPeriod validation', () => { const net = new NeuralNetwork(); expect(() => { // @ts-expect-error logPeriod should be positive number net.updateTrainingOptions({ logPeriod: 'no strings' }); }).toThrow(); expect(() => { net.updateTrainingOptions({ logPeriod: -50 }); }).toThrow(); expect(() => { // @ts-expect-error logPeriod should be positive number net.updateTrainingOptions({ logPeriod: () => {} }); }).toThrow(); expect(() => { // @ts-expect-error logPeriod should be positive number net.updateTrainingOptions({ logPeriod: false }); }).toThrow(); expect(() => { net.updateTrainingOptions({ logPeriod: 40 }); }).not.toThrow(); }); it('learningRate validation', () => { const net = new NeuralNetwork(); expect(() => { // @ts-expect-error learningRate should be positive number net.updateTrainingOptions({ learningRate: 'no strings' }); }).toThrow(); expect(() => { net.updateTrainingOptions({ learningRate: -50 }); }).toThrow(); expect(() => { net.updateTrainingOptions({ learningRate: 50 }); }).toThrow(); expect(() => { // @ts-expect-error learningRate should be positive number net.updateTrainingOptions({ learningRate: () => {} }); }).toThrow(); expect(() => { // @ts-expect-error learningRate should be positive number net.updateTrainingOptions({ learningRate: false }); }).toThrow(); expect(() => { net.updateTrainingOptions({ learningRate: 0.5 }); }).not.toThrow(); }); it('momentum validation', () => { const net = new NeuralNetwork(); expect(() => { // @ts-expect-error momentum should be positive number net.updateTrainingOptions({ momentum: 'no strings' }); }).toThrow(); expect(() => { net.updateTrainingOptions({ momentum: -50 }); }).toThrow(); expect(() => { net.updateTrainingOptions({ momentum: 50 }); }).toThrow(); expect(() => { // @ts-expect-error momentum should be positive number net.updateTrainingOptions({ momentum: () => {} }); }).toThrow(); expect(() => { // @ts-expect-error momentum should be positive number net.updateTrainingOptions({ momentum: false }); }).toThrow(); expect(() => { net.updateTrainingOptions({ momentum: 0.8 }); }).not.toThrow(); }); it('callback validation', () => { const net = new NeuralNetwork(); expect(() => { // @ts-expect-error callback should be a function net.updateTrainingOptions({ callback: 'no strings' }); }).toThrow(); expect(() => { // @ts-expect-error callback should be a function net.updateTrainingOptions({ callback: 4 }); }).toThrow(); expect(() => { // @ts-expect-error callback should be a function net.updateTrainingOptions({ callback: false }); }).toThrow(); expect(() => { net.updateTrainingOptions({ callback: undefined }); }).not.toThrow(); expect(() => { net.updateTrainingOptions({ callback: () => {} }); }).not.toThrow(); }); it('callbackPeriod validation', () => { const net = new NeuralNetwork(); expect(() => { // @ts-expect-error callbackPeriod should be a number net.updateTrainingOptions({ callbackPeriod: 'no strings' }); }).toThrow(); expect(() => { net.updateTrainingOptions({ callbackPeriod: -50 }); }).toThrow(); expect(() => { // @ts-expect-error callbackPeriod should be a number net.updateTrainingOptions({ callbackPeriod: () => {} }); }).toThrow(); expect(() => { // @ts-expect-error callbackPeriod should be a number net.updateTrainingOptions({ callbackPeriod: false }); }).toThrow(); expect(() => { net.updateTrainingOptions({ callbackPeriod: 40 }); }).not.toThrow(); }); it('timeout validation', () => { const net = new NeuralNetwork(); expect(() => { // @ts-expect-error timeout should be a number net.updateTrainingOptions({ timeout: 'no strings' }); }).toThrow(); expect(() => { net.updateTrainingOptions({ timeout: -50 }); }).toThrow(); expect(() => { // @ts-expect-error timeout should be a number net.updateTrainingOptions({ timeout: () => {} }); }).toThrow(); expect(() => { // @ts-expect-error timeout should be a number net.updateTrainingOptions({ timeout: false }); }).toThrow(); expect(() => { net.updateTrainingOptions({ timeout: 40 }); }).not.toThrow(); }); it('should retain the options from instantiation as defaults', () => { const config = { iterations: 1, errorThresh: 0.0001, binaryThresh: 0.05, hiddenLayers: [1], activation: 'sigmoid', }; const net = new NeuralNetwork(config); const trainData = [ { input: [0, 0], output: [0] }, { input: [0, 1], output: [1] }, { input: [1, 0], output: [1] }, { input: [1, 1], output: [0] }, ]; const trainResult = net.train(trainData); expect(trainResult.iterations).toBe(1); }); }); });
the_stack
import { expect } from "chai"; import { ECVersion, EntityClass, PrimitiveType, Schema, SchemaContext, SchemaItemKey, SchemaKey, } from "@itwin/ecschema-metadata"; import { SchemaContextEditor } from "../../Editing/Editor"; /* eslint-disable @typescript-eslint/naming-convention */ // TODO: Add tests for cases where invalid names are passed into props objects. (to test the error message) describe("Editor tests", () => { function normalizeLineEnds(s: string): string { return s.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); } describe("SchemaEditor tests", () => { let testEditor: SchemaContextEditor; let testSchema: Schema; let testKey: SchemaKey; let context: SchemaContext; describe("should create a new schema from a context", () => { beforeEach(() => { context = new SchemaContext(); testEditor = new SchemaContextEditor(context); }); it("should create a new schema and return a SchemaEditResults", async () => { const result = await testEditor.createSchema("testSchema", "test", 1, 0, 0); expect(result).to.not.eql(undefined); }); it("upon schema creation, return a defined SchemaKey from SchemaEditResults", async () => { const result = await testEditor.createSchema("testSchema", "test", 1, 0, 0); expect(result.schemaKey?.name).to.eql("testSchema"); expect(result.schemaKey?.version).to.eql(new ECVersion(1, 0, 0)); }); }); describe("addCustomAttribute Tests", () => { it("CustomAttribute defined in same schema, instance added successfully.", async () => { const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "ValidSchema", version: "1.2.3", alias: "vs", items: { TestCustomAttribute: { schemaItemType: "CustomAttributeClass", appliesTo: "Schema", }, }, }; context = new SchemaContext(); testSchema = await Schema.fromJson(schemaJson, context); testEditor = new SchemaContextEditor(context); testKey = testSchema.schemaKey; const result = await testEditor.addCustomAttribute(testKey, { className: "TestCustomAttribute" }); expect(result).to.eql({}); expect(testSchema.customAttributes && testSchema.customAttributes.has("TestCustomAttribute")).to.be.true; }); it("CustomAttribute defined in different schema, instance added successfully.", async () => { const schemaAJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "SchemaA", version: "1.2.3", alias: "vs", references: [ { name: "SchemaB", version: "1.2.3", }, ], }; const schemaBJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "SchemaB", version: "1.2.3", alias: "vs", items: { TestCustomAttribute: { schemaItemType: "CustomAttributeClass", appliesTo: "Schema", }, }, }; context = new SchemaContext(); await Schema.fromJson(schemaBJson, context); const schemaA = await Schema.fromJson(schemaAJson, context); testEditor = new SchemaContextEditor(context); testKey = schemaA.schemaKey; const result = await testEditor.addCustomAttribute(testKey, { className: "SchemaB.TestCustomAttribute" }); expect(result).to.eql({}); expect(schemaA.customAttributes && schemaA.customAttributes.has("SchemaB.TestCustomAttribute")).to.be.true; }); it("CustomAttribute class not found, error reported successfully.", async () => { const schemaAJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "SchemaA", version: "1.2.3", alias: "vs", customAttributes: [ ], references: [ { name: "SchemaB", version: "1.2.3", }, ], }; const schemaBJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "SchemaB", version: "1.2.3", alias: "vs", }; context = new SchemaContext(); await Schema.fromJson(schemaBJson, context); const schemaA = await Schema.fromJson(schemaAJson, context); testEditor = new SchemaContextEditor(context); testKey = schemaA.schemaKey; const result = await testEditor.addCustomAttribute(testKey, { className: "SchemaB.TestCustomAttribute" }); expect(result.errorMessage).to.eql("ECObjects-502: The CustomAttribute container 'SchemaA' has a CustomAttribute with the class 'SchemaB.TestCustomAttribute' which cannot be found.\r\n"); expect(schemaA.customAttributes && schemaA.customAttributes.has("SchemaB.TestCustomAttribute")).to.be.false; }); }); describe("addSchemaReference Tests", () => { it("Schema reference is valid, reference added successfully.", async () => { const refSchemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "RefSchema", version: "1.0.0", alias: "rs", }; const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "TestSchema", version: "1.0.0", alias: "ts", }; context = new SchemaContext(); testSchema = await Schema.fromJson(schemaJson, context); testEditor = new SchemaContextEditor(context); testKey = testSchema.schemaKey; const refSchema = await Schema.fromJson(refSchemaJson, context); const result = await testEditor.addSchemaReference(testKey, refSchema); expect(result).to.eql({}); expect(testSchema.getReferenceNameByAlias("rs")).to.equal("RefSchema"); expect(await testEditor.schemaContext.getCachedSchema(refSchema.schemaKey)).to.eql(refSchema); }); it("Multiple validation errors, results formatted properly.", async () => { const schemaAJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "SchemaA", version: "1.0.0", alias: "a", references: [ { name: "SchemaB", version: "1.0.0", }, ], }; const schemaBJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "SchemaB", version: "1.0.0", alias: "b", }; const schemaCJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "SchemaC", version: "1.0.0", alias: "b", references: [ { name: "SchemaA", version: "1.0.0", }, ], }; context = new SchemaContext(); await Schema.fromJson(schemaBJson, context); const schemaA = await Schema.fromJson(schemaAJson, context); const schemaC = await Schema.fromJson(schemaCJson, context); testEditor = new SchemaContextEditor(context); testKey = schemaA.schemaKey; const result = await testEditor.addSchemaReference(schemaA.schemaKey, schemaC); expect(result.errorMessage).not.undefined; expect(normalizeLineEnds(result.errorMessage!)).to.equal(normalizeLineEnds("ECObjects-2: Schema 'SchemaA' has multiple schema references (SchemaB, SchemaC) with the same alias 'b', which is not allowed.\r\nECObjects-3: Schema 'SchemaA' has reference cycles: SchemaC --> SchemaA, SchemaA --> SchemaC\r\n")); expect(schemaA.getReferenceSync("SchemaC")).to.be.undefined; }); }); describe("Schema Version Tests", () => { it("setVersion, version updated successfully", async () => { const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "ValidSchema", version: "1.2.3", alias: "vs", }; context = new SchemaContext(); testSchema = await Schema.fromJson(schemaJson, context); testEditor = new SchemaContextEditor(context); const result = await testEditor.setVersion(testSchema.schemaKey, 2, 3, 4); expect(result).to.eql({}); expect(testSchema.readVersion).to.equal(2); expect(testSchema.writeVersion).to.equal(3); expect(testSchema.minorVersion).to.equal(4); }); it("setVersion, read version not specified, version updated successfully", async () => { const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "ValidSchema", version: "1.2.3", alias: "vs", }; context = new SchemaContext(); testSchema = await Schema.fromJson(schemaJson, context); testEditor = new SchemaContextEditor(context); const result = await testEditor.setVersion(testSchema.schemaKey, undefined, 3, 4); expect(result).to.eql({}); expect(testSchema.readVersion).to.equal(1); expect(testSchema.writeVersion).to.equal(3); expect(testSchema.minorVersion).to.equal(4); }); it("setVersion, write version not specified, version updated successfully", async () => { const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "ValidSchema", version: "1.2.3", alias: "vs", }; context = new SchemaContext(); testSchema = await Schema.fromJson(schemaJson, context); testEditor = new SchemaContextEditor(context); const result = await testEditor.setVersion(testSchema.schemaKey, 2, undefined, 4); expect(result).to.eql({}); expect(testSchema.readVersion).to.equal(2); expect(testSchema.writeVersion).to.equal(2); expect(testSchema.minorVersion).to.equal(4); }); it("setVersion, read version not specified, version updated successfully", async () => { const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "ValidSchema", version: "1.2.3", alias: "vs", }; context = new SchemaContext(); testSchema = await Schema.fromJson(schemaJson, context); testEditor = new SchemaContextEditor(context); const result = await testEditor.setVersion(testSchema.schemaKey, 2, 3, undefined); expect(result).to.eql({}); expect(testSchema.readVersion).to.equal(2); expect(testSchema.writeVersion).to.equal(3); expect(testSchema.minorVersion).to.equal(3); }); it("incrementMinorVersion, version incremented successfully", async () => { const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "ValidSchema", version: "1.2.3", alias: "vs", }; context = new SchemaContext(); testSchema = await Schema.fromJson(schemaJson, context); testEditor = new SchemaContextEditor(context); const result = await testEditor.incrementMinorVersion(testSchema.schemaKey); expect(result).to.eql({}); expect(testSchema.minorVersion).to.equal(4); }); }); describe("edits an existing schema", () => { const schemaJson = { $schema: "https://dev.bentley.com/json_schemas/ec/32/ecschema", name: "TestSchema", version: "1.2.3", alias: "ts", items: { testEnum: { schemaItemType: "Enumeration", type: "int", enumerators: [ { name: "ZeroValue", value: 0, label: "None", }, ], }, testClass: { schemaItemType: "EntityClass", label: "ExampleEntity", description: "An example entity class.", }, ExampleMixin: { schemaItemType: "Mixin", appliesTo: "TestSchema.testClass", }, ExampleStruct: { schemaItemType: "StructClass", name: "ExampleStruct", modifier: "sealed", properties: [ { type: "PrimitiveArrayProperty", name: "ExamplePrimitiveArray", typeName: "TestSchema.testEnum", minOccurs: 7, maxOccurs: 20, }, ], }, }, }; beforeEach(async () => { context = new SchemaContext(); testSchema = await Schema.fromJson(schemaJson, context); testEditor = new SchemaContextEditor(context); testKey = testSchema.schemaKey; }); it("should get the correct Schema", async () => { expect(await testEditor.schemaContext.getSchema(testKey)).to.eql(testSchema); }); it("upon manual key creation, still create a valid property to an existing entity", async () => { const schemaKey = new SchemaKey("TestSchema"); const entityKey = new SchemaItemKey("testClass", schemaKey); await testEditor.entities.createPrimitiveProperty(entityKey, "testProperty", PrimitiveType.Integer); const testEntity = await testEditor.schemaContext.getSchemaItem(entityKey) as EntityClass; expect(await testEntity.getProperty("testProperty")).to.not.eql(undefined); }); it("should get the right entity class from existing schema", async () => { const createdKey = new SchemaKey("TestSchema"); const cachedSchema = await testEditor.schemaContext.getCachedSchema(createdKey); const testEntity = await cachedSchema!.getItem("testClass"); expect(testEntity?.label).to.eql("ExampleEntity"); }); it("should add a property to existing entity", async () => { const entityKey = new SchemaItemKey("testClass", testKey); await testEditor.entities.createPrimitiveProperty(entityKey, "testProperty", PrimitiveType.Integer); const testEntity = await testSchema.getItem("testClass") as EntityClass; expect(await testEntity.getProperty("testProperty")).to.not.eql(undefined); }); }); // TODO: Add a test to compare previous SchemaContext with the SchemaContext returned when SchemaEditor.finish() is called. }); });
the_stack
import React, { useState, useEffect } from 'react'; import { AutoComplete, Modal, Form, Input, Divider, Select, Button, Tooltip, Row, Col, InputNumber, Collapse } from 'antd'; import * as actions from '../../actions'; import '../../container/agent-management/index.less'; import { connect } from "react-redux"; import { IFormProps, DataSourceItemType } from '../../interface/common'; import { flowUnitList } from '../../constants/common'; import { IAgentHostSet, IEditOpHostsParams, IOpAgent, IReceivers } from '../../interface/agent'; import { getHostDetails, getHostMachineZone, editOpHosts, getAgentDetails, editOpAgent, getReceivers, getReceiversTopic } from '../../api/agent' import MonacoEditor from '../../component/editor/monacoEditor'; import { setLimitUnit, judgeEmpty } from '../../lib/utils'; import { UpOutlined, DownOutlined } from '@ant-design/icons'; import { regString128 } from '../../constants/reg'; const { Panel } = Collapse; const { Option } = Select; const { TextArea } = Input; const mapStateToProps = (state: any) => ({ params: state.modal.params, }); interface IModifyHostParams { hostObj: IAgentHostSet; getData: any; } const ModifyHost = (props: { dispatch: any, params: IModifyHostParams }) => { // console.log('props---', props.params); const handleModifyCancel = () => { props.dispatch(actions.setModalId('')); } return ( <Modal title="编辑" visible={true} footer={null} onCancel={handleModifyCancel} > <div className="modify-agent-list"> <WrappedHostConfigurationForm dispatch={props.dispatch} params={props.params} /> <WrappedAgentConfigurationForm dispatch={props.dispatch} params={props.params} /> </div> </Modal> ) } const modifyAgentListLayout = { labelCol: { span: 7 }, wrapperCol: { span: 16 }, }; interface IDispatch { dispatch: any; params: IModifyHostParams; } const HostConfigurationForm = (props: IFormProps & IDispatch) => { const { getFieldDecorator } = props.form; let { hostObj, getData } = props.params; const [hostDetail, setHostDetail] = useState(hostObj); const [machineZones, setMachineZones] = useState([] as string[]); const getMachineZonesList = () => { const zonesList = machineZones.map((ele: string) => { return { value: ele, text: ele } }); return zonesList; } const handleHostSubmit = (e: any) => { e.preventDefault(); props.form.validateFields((err: any, values: any) => { if (err) { return false; } const params = { department: hostDetail?.department || '', id: hostDetail?.hostId, machineZone: values?.machineZone || '', } as IEditOpHostsParams; return editOpHosts(params).then((res: any) => { props.dispatch(actions.setModalId('')); Modal.success({ title: '保存成功!', okText: '确认', onOk: () => getData() }); }).catch((err: any) => { // console.log(err); }); }); }; const getMachineZones = () => { getHostMachineZone().then((res: string[]) => { const zones = res.filter(ele => !!judgeEmpty(ele)); setMachineZones(zones); }).catch((err: any) => { // console.log(err); }); } const getHostDetail = () => { getHostDetails(hostObj?.hostId).then((res: IAgentHostSet) => { setHostDetail(res); }).catch((err: any) => { // console.log(err); }); } useEffect(() => { getHostDetail(); getMachineZones(); }, []); return ( <Form className="host-configuration" {...modifyAgentListLayout} onSubmit={handleHostSubmit} > <div className="agent-list-head"> <b>主机配置</b> <Button type="primary" htmlType="submit">确认</Button> </div> <Divider /> <Form.Item label="主机名"> {getFieldDecorator('hostName', { initialValue: hostDetail?.hostName, })( <span>{hostDetail?.hostName}</span>, )} </Form.Item> <Form.Item label="主机IP"> {getFieldDecorator('ip', { initialValue: hostDetail?.ip, })( <span>{hostDetail?.ip}</span>, )} </Form.Item> {hostDetail?.container === 1 && <Form.Item label="宿主机名"> {getFieldDecorator('parentHostName', { initialValue: hostDetail?.parentHostName, })( <span>{hostDetail?.parentHostName}</span>, )} </Form.Item>} <Form.Item label="所属机房"> {getFieldDecorator('machineZone', { initialValue: hostDetail?.machineZone, rules: [{ required: false, validator: (rule: any, value: string, cb: any) => { if (!new RegExp(regString128).test(value)) { rule.message = '最大长度限制128位' cb('最大长度限制128位') } else { cb() } }, }], })( <AutoComplete placeholder="请选择或输入" dataSource={getMachineZonesList()} children={<Input />} />, )} </Form.Item> </Form> ) } const WrappedHostConfigurationForm = Form.create<IFormProps & IDispatch>()(HostConfigurationForm); const AgentConfigurationForm = (props: IFormProps & IDispatch) => { const { getFieldDecorator } = props.form; const { hostObj, getData } = props.params; const [activeKeys, setActiveKeys] = useState([] as string[]); const [agentDetail, setAgentDetail] = useState({} as IOpAgent); const [receivers, setReceivers] = useState([] as IReceivers[]); const [errorReceivers, setErrorReceivers] = useState([] as IReceivers[]); const [receiverTopic, setReceiverTopic] = useState([] as DataSourceItemType[]); const [errorTopic, setErrorTopic] = useState([] as DataSourceItemType[]); const handleAgentSubmit = (e: any) => { e.preventDefault(); props.form.validateFields((err: any, values: any) => { if (err) { collapseCallBack(['high']); return false; } const params = { metricsProducerConfiguration: values?.metricsProducerConfiguration, errorLogsProducerConfiguration: values?.errorLogsProducerConfiguration, advancedConfigurationJsonString: values?.advancedConfigurationJsonString, byteLimitThreshold: values?.byteLimitThreshold * values?.unit, cpuLimitThreshold: values?.cpuLimitThreshold, errorLogsSendReceiverId: values?.errorLogsSendReceiverId, errorLogsSendTopic: values?.errorLogsSendTopic, metricsSendReceiverId: values?.metricsSendReceiverId, metricsSendTopic: values?.metricsSendTopic, id: agentDetail.id, } as IOpAgent; return editOpAgent(params).then((res: IOpAgent) => { props.dispatch(actions.setModalId('')); Modal.success({ title: '保存成功!', okText: '确认', onOk: () => getData() }); }).catch((err: any) => { // console.log(err); }); }); }; const collapseCallBack = (key: any) => { setActiveKeys(key); } const onReceiverChange = (value: number) => { // getReceiverTopic(value); // 等对接Kafka集群时再修复 } const onErrorChange = (value: number) => { // getReceiverTopic(value, true); // 等对接Kafka集群时再修复 } const getReceiversList = () => { getReceivers().then((res: IReceivers[]) => { setReceivers(res); setErrorReceivers(res); }).catch((err: any) => { // console.log(err); }); } const getReceiverTopic = (id: number, judge?: boolean) => { getReceiversTopic(id).then((res: string[]) => { const topics = res?.map(ele => { return { text: ele, value: ele } }); judge ? setErrorTopic(topics) : setReceiverTopic(topics); }).catch((err: any) => { // console.log(err); }); } const getAgentDetail = () => { getAgentDetails(hostObj?.agentId).then((res: IOpAgent) => { setAgentDetail(res); }).catch((err: any) => { // console.log(err); }); } useEffect(() => { if (hostObj.agentId) { getAgentDetail(); getReceiversList(); } }, []); return ( <Form className="agent-configuration" {...modifyAgentListLayout} onSubmit={handleAgentSubmit} > <div className="agent-list-head"> <b>Agent配置</b> {hostObj.agentId && <Button type="primary" htmlType="submit">确认</Button>} </div> <Divider /> {hostObj.agentId ? <> <Form.Item label="CPU核数上限"> {getFieldDecorator('cpuLimitThreshold', { initialValue: agentDetail?.cpuLimitThreshold, rules: [{ required: true, message: '请输入' }], })( <InputNumber min={1} placeholder="请输入" />, )} <span>&nbsp;核</span> </Form.Item> {/* <Form.Item label="出口流量上限"> <Row> <Col span={8}> {getFieldDecorator('byteLimitThreshold', { initialValue: setLimitUnit(agentDetail?.byteLimitThreshold, 1)?.maxBytesPerLogEvent, rules: [{ required: true, message: '请输入' }], })( <InputNumber min={1} placeholder="请输入" />, )} </Col> <Col span={6}> <Form.Item> {getFieldDecorator('unit', { initialValue: setLimitUnit(agentDetail?.byteLimitThreshold, 1)?.flowunit, rules: [{ required: true, message: '请输入' }], })( <Select> {flowUnitList.map((v, index) => ( <Option key={index} value={v.value}>{v.label}</Option> ))} </Select>, )} </Form.Item> </Col> </Row> </Form.Item> */} <Collapse bordered={false} expandIconPosition="right" onChange={collapseCallBack} activeKey={activeKeys?.length ? ['high'] : []} > <Panel header={<h3>高级配置</h3>} extra={<a>{activeKeys?.length ? <>收起&nbsp;<UpOutlined /></> : <>展开&nbsp;<DownOutlined /></>}</a>} showArrow={false} key="high" > <Row> <Form.Item label="指标流接收集群"> {getFieldDecorator('metricsSendReceiverId', { initialValue: agentDetail?.metricsSendReceiverId, rules: [{ required: true, message: '请选择' }], })( <Select onChange={onReceiverChange}> {receivers.map((v: IReceivers, index: number) => ( <Option key={index} value={v.id}> {v.kafkaClusterName.length > 15 ? <Tooltip placement="bottomLeft" title={v.kafkaClusterName}>{v.kafkaClusterName}</Tooltip> : v.kafkaClusterName} </Option> ))} </Select>, )} </Form.Item> <Form.Item label="指标流接收Topic"> {getFieldDecorator('metricsSendTopic', { initialValue: agentDetail?.metricsSendTopic, rules: [{ required: true, message: '请输入' }], })( <AutoComplete placeholder="请选择或输入" dataSource={receiverTopic} children={<Input />} />, )} </Form.Item> <Form.Item label="生产端属性"> {getFieldDecorator('metricsProducerConfiguration', { initialValue: agentDetail?.metricsProducerConfiguration, rules: [{ message: '请输入', pattern: /^[-\w]{1,1024}$/, }], })( <TextArea placeholder="默认值,如修改,覆盖相应生产端配置" />, )} </Form.Item> <Form.Item label="错误日志接收集群"> {getFieldDecorator('errorLogsSendReceiverId', { initialValue: agentDetail?.errorLogsSendReceiverId, rules: [{ required: true, message: '请选择' }], })( <Select onChange={onErrorChange}> {errorReceivers.map((v: IReceivers, index: number) => ( <Option key={index} value={v.id}> {v.kafkaClusterName.length > 15 ? <Tooltip placement="bottomLeft" title={v.kafkaClusterName}>{v.kafkaClusterName}</Tooltip> : v.kafkaClusterName} </Option> ))} </Select>, )} </Form.Item> <Form.Item label="错误日志接收Topic"> {getFieldDecorator('errorLogsSendTopic', { initialValue: agentDetail?.errorLogsSendTopic, rules: [{ required: true, message: '请输入' }], })( <AutoComplete placeholder="请选择或输入" dataSource={errorTopic} children={<Input />} />, )} </Form.Item> <Form.Item label="生产端属性"> {getFieldDecorator('errorLogsProducerConfiguration', { initialValue: agentDetail?.metricsProducerConfiguration, rules: [{ message: '请输入', pattern: /^[-\w]{1,1024}$/, }], })( <TextArea placeholder="默认值,如修改,覆盖相应生产端配置" />, )} </Form.Item> <Form.Item label="配置信息"> {getFieldDecorator('advancedConfigurationJsonString', { initialValue: agentDetail?.advancedConfigurationJsonString || '', rules: [{ required: true, message: '请输入' }], })( <MonacoEditor {...props} /> )} </Form.Item> </Row> </Panel> </Collapse> </> : <p className='agent-installed'>该主机未安装Agent</p>} </Form> ) } const WrappedAgentConfigurationForm = Form.create<IFormProps & IDispatch>()(AgentConfigurationForm); export default connect(mapStateToProps)(ModifyHost);
the_stack
import { ContentView, EventData } from '@nativescript/core'; import { Camera as CameraDefinition, StatusEventData, ImageCapturedEventData, FaceDetectedEventData, QRCodeScannedEventData, } from '.'; import Validator from "./helpers/Validator"; const { ValidateProps, Required, NativeMethod, NativeAttribute, RegexNumber, RegexPX, PercentageToNumber, RegexPercentage, NumberToPixel, ParseToNsColor, RegexColor } = Validator; export abstract class CameraBase extends ContentView implements CameraDefinition { // PROPERTIES ================================================================ // =========================================================================== public set lens(value: string) { this.setCameraLens(value); } public set captureType(value: string) { this.startCapture(value); } public set imageCapture(value: boolean) { this.setImageCapture(value); } public set imageCaptureAmount(value: number) { this.setImageCaptureAmount(value); } public set imageCaptureInterval(value: number) { this.setImageCaptureInterval(value); } public set imageCaptureWidth(value: number) { this.setImageCaptureWidth(value); } public set imageCaptureHeight(value: number) { this.setImageCaptureHeight(value); } public set colorEncoding(value: string) { this.setImageCaptureColorEncoding(value); } public set detectionBox(value: boolean) { this.setDetectionBox(value); } public set detectionBoxColor(value: string) { this.setDetectionBoxColor(value); } public set detectionMinSize(value: string) { this.setDetectionMinSize(value); } public set detectionMaxSize(value: string) { this.setDetectionMaxSize(value); } public set detectionTopSize(value: number) { this.setDetectionTopSize(value); } public set detectionRightSize(value: number) { this.setDetectionRightSize(value); } public set detectionBottomSize(value: number) { this.setDetectionBottomSize(value); } public set detectionLeftSize(value: number) { this.setDetectionLeftSize(value); } public set roi(value: boolean) { this.setROI(value); } public set roiTopOffset(value: string) { this.setROITopOffset(value); } public set roiRightOffset(value: string) { this.setROIRightOffset(value); } public set roiBottomOffset(value: string) { this.setROIBottomOffset(value); } public set roiLeftOffset(value: string) { this.setROILeftOffset(value); } public set roiAreaOffsetColor(value: string) { this.setROIAreaOffsetColor(value); } public set roiAreaOffset(value: boolean) { this.setROIAreaOffset(value); } public set faceContours(value: boolean) { this.setFaceContours(value); } public set faceContoursColor(value: string) { this.setFaceContoursColor(value); } public set computerVision(value: boolean) { this.setComputerVision(value); } public set torch(value: boolean) { this.setTorch(value); } // METHODS =================================================================== // =========================================================================== public requestPermission(explanationText?: string): Promise<boolean> { return new Promise((resolve, reject) => resolve(true)); } public hasPermission(): boolean { return false; } public preview(): void { this.nativeView.startPreview(); } public stopCapture(): void { this.nativeView.stopCapture(); } public destroy(): void { this.nativeView.destroy(); } public toggleLens(): void { this.nativeView.toggleCameraLens(); } @ValidateProps('lens', ['front', 'back']) @NativeMethod({ name: 'setCameraLens', length: 1 }) public setCameraLens(@Required lens: string): void { this.nativeView.setCameraLens(lens); } public getLens(): string { return this.nativeView.getCameraLens(); } @ValidateProps('captureType', ['face', 'qrcode', 'frame', 'none']) @NativeMethod({ name: 'startCaptureType', length: 1 }) public startCapture(@Required type: string): void { this.nativeView.startCaptureType(type); } @ValidateProps('imageCaptureAmount', RegexNumber) @NativeMethod({ name: 'setNumberOfImages', length: 1 }) public setImageCaptureAmount(@Required amount: number): void { this.nativeView.setNumberOfImages(amount); } @ValidateProps('imageCaptureInterval', RegexNumber) @NativeMethod({ name: 'setTimeBetweenImages', length: 1 }) public setImageCaptureInterval(@Required interval: number): void { this.nativeView.setTimeBetweenImages(interval); } @ValidateProps('imageCaptureWidth', RegexPX) @NumberToPixel @NativeMethod({ name: 'setOutputImageWidth', length: 1 }) public setImageCaptureWidth(@Required width): void { this.nativeView.setOutputImageWidth(width); } @ValidateProps('imageCaptureHeight', RegexPX) @NumberToPixel @NativeMethod({ name: 'setOutputImageHeight', length: 1 }) public setImageCaptureHeight(@Required height): void { this.nativeView.setOutputImageHeight(height); } @ValidateProps('imageCapture', [false, true]) @NativeMethod({ name: 'setSaveImageCaptured', length: 1 }) public setImageCapture(@Required enable: boolean): void { this.nativeView.setSaveImageCaptured(enable); } public setImageCaptureColorEncoding(colorEncoding: string): void {} @ValidateProps('detectionBox', [false, true]) @NativeMethod({ name: 'setDetectionBox', length: 1 }) public setDetectionBox(@Required enable: boolean): void { this.nativeView.setDetectionBox(enable); } @ValidateProps('detectionBoxColor', RegexColor) @ParseToNsColor @NativeMethod({ name: 'setDetectionBoxColor', length: 4 }) public setDetectionBoxColor(@Required color) { this.nativeView.setDetectionBoxColor(...color); } @ValidateProps('detectionMinSize', RegexPercentage) @PercentageToNumber @NativeMethod({ name: 'setDetectionMinSize', length: 1 }) public setDetectionMinSize(@Required percentage): void { this.nativeView.setDetectionMinSize(percentage); } @ValidateProps('detectionMaxSize', RegexPercentage) @PercentageToNumber @NativeMethod({ name: 'setDetectionMaxSize', length: 1 }) public setDetectionMaxSize(@Required percentage): void { this.nativeView.setDetectionMaxSize(percentage); } @ValidateProps('detectionTopSize', RegexPercentage) @PercentageToNumber @NativeAttribute('detectionTopSize') public setDetectionTopSize(@Required percentage): void { this.nativeView.detectionTopSize = percentage; } @ValidateProps('detectionRightSize', RegexPercentage) @PercentageToNumber @NativeAttribute('detectionRightSize') public setDetectionRightSize(@Required percentage): void { this.nativeView.detectionRightSize = percentage; } @ValidateProps('detectionBottomSize', RegexPercentage) @PercentageToNumber @NativeAttribute('detectionBottomSize') public setDetectionBottomSize(@Required percentage): void { this.nativeView.detectionBottomSize = percentage; } @ValidateProps('detectionLeftSize', RegexPercentage) @PercentageToNumber @NativeAttribute('detectionLeftSize') public setDetectionLeftSize(@Required percentage): void { this.nativeView.detectionLeftSize = percentage; } @ValidateProps('roi', [false, true]) @NativeMethod({ name: 'setROI', length: 1 }) public setROI(@Required enable: boolean): void { this.nativeView.setROI(enable); } @ValidateProps('roiTopOffset', RegexPercentage) @PercentageToNumber @NativeMethod({ name: 'setROITopOffset', length: 1 }) public setROITopOffset(@Required percentage): void { this.nativeView.setROITopOffset(percentage); } @ValidateProps('roiRightOffset', RegexPercentage) @PercentageToNumber @NativeMethod({ name: 'setROIRightOffset', length: 1 }) public setROIRightOffset(@Required percentage): void { this.nativeView.setROIRightOffset(percentage); } @ValidateProps('roiBottomOffset', RegexPercentage) @PercentageToNumber @NativeMethod({ name: 'setROIBottomOffset', length: 1 }) public setROIBottomOffset(@Required percentage): void { this.nativeView.setROIBottomOffset(percentage); } @ValidateProps('roiLeftOffset', RegexPercentage) @PercentageToNumber @NativeMethod({ name: 'setROILeftOffset', length: 1 }) public setROILeftOffset(@Required percentage): void { this.nativeView.setROILeftOffset(percentage); } @ValidateProps('roiAreaOffset', [false, true]) @NativeMethod({ name: 'setROIAreaOffset', length: 1 }) public setROIAreaOffset(@Required enable: boolean) { this.nativeView.setROIAreaOffset(enable); } @ValidateProps('roiAreaOffsetColor', RegexColor) @ParseToNsColor @NativeMethod({ name: 'setROIAreaOffsetColor', length: 4 }) public setROIAreaOffsetColor(@Required color) { this.nativeView.setROIAreaOffsetColor(...color); } public setFaceContours(enable: boolean) {} public setFaceContoursColor(color: string) {} public setComputerVision(enable: boolean) {} public setComputerVisionLoadModels(modelPaths: Array<String>): void {} public computerVisionClearModels(): void {} @ValidateProps('torch', [false, true]) @NativeMethod({ name: 'setTorch', length: 1 }) public setTorch(@Required enable: boolean) { this.nativeView.setTorch(enable); } } export interface CameraBase { on(eventNames: string, callback: (data: EventData) => void, thisArg?: any); on(event: "imageCaptured", callback: (args: ImageCapturedEventData) => void, thisArg?: any); on(event: "faceDetected", callback: (args: FaceDetectedEventData) => void, thisArg?: any); on(event: "endCapture", callback: () => void, thisArg?: any); on(event: "qrCodeContent", callback: (args: QRCodeScannedEventData) => void, thisArg?: any); on(event: "status", callback: (args: StatusEventData) => void, thisArg?: any); on(event: "permissionDenied", callback: () => void, thisArg?: any); }
the_stack
module TDev.AST.Bytecode { export interface FuncInfo { name: string; type: string; args: number; value: number; } export interface ExtensionInfo { enums:StringMap<number>; functions:FuncInfo[]; errors:string; sha:string; compileData:string; hasExtension:boolean; } var funcInfo:StringMap<FuncInfo>; var hex:string[]; var jmpStartAddr:number; var jmpStartIdx:number; var bytecodeStartAddr:number; var bytecodeStartIdx:number; function swapBytes(str:string) { var r = "" for (var i = 0; i < str.length; i += 2) r = str[i] + str[i + 1] + r Util.assert(i == str.length) return r } function userError(msg:string) { var e = new Error(msg); (<any>e).bitvmUserError = true; throw e; } export function isSetupFor(extInfo:ExtensionInfo) { return currentSetup == extInfo.sha } function parseHexBytes(bytes:string):number[] { bytes = bytes.replace(/^[\s:]/, "") if (!bytes) return [] var m = /^([a-f0-9][a-f0-9])/i.exec(bytes) if (m) return [parseInt(m[1], 16)].concat(parseHexBytes(bytes.slice(2))) else Util.oops("bad bytes " + bytes) } var currentSetup:string = null; export function setupFor(extInfo:ExtensionInfo, bytecodeInfo:any) { if (isSetupFor(extInfo)) return; currentSetup = extInfo.sha; var jsinf = bytecodeInfo || (<any>TDev).bytecodeInfo hex = jsinf.hex; var i = 0; var upperAddr = "0000" var lastAddr = 0 var lastIdx = 0 bytecodeStartAddr = 0 for (; i < hex.length; ++i) { var m = /:02000004(....)/.exec(hex[i]) if (m) { upperAddr = m[1] } m = /^:..(....)00/.exec(hex[i]) if (m) { var newAddr = parseInt(upperAddr + m[1], 16) if (!bytecodeStartAddr && newAddr >= 0x3C000) { var bytes = parseHexBytes(hex[lastIdx]) if (bytes[0] != 0x10) { bytes.pop() // checksum bytes[0] = 0x10; while (bytes.length < 20) bytes.push(0x00) hex[lastIdx] = hexBytes(bytes) } Util.assert((bytes[2] & 0xf) == 0) bytecodeStartAddr = lastAddr + 16 bytecodeStartIdx = lastIdx + 1 } lastIdx = i lastAddr = newAddr } m = /^:10....000108010842424242010801083ED8E98D/.exec(hex[i]) if (m) { jmpStartAddr = lastAddr jmpStartIdx = i } } if (!jmpStartAddr) Util.oops("No hex start") funcInfo = {}; var funs:FuncInfo[] = jsinf.functions.concat(extInfo.functions); var addEnum = enums => Object.keys(enums).forEach(k => { funcInfo[k] = { name: k, type: "E", args: 0, value: enums[k] } }) addEnum(extInfo.enums) addEnum(jsinf.enums) for (var i = jmpStartIdx + 1; i < hex.length; ++i) { var m = /^:10(....)00(.{16})/.exec(hex[i]) if (!m) continue; var s = hex[i].slice(9) while (s.length >= 8) { var inf = funs.shift() if (!inf) return; funcInfo[inf.name] = inf; inf.value = parseInt(swapBytes(s.slice(0, 8)), 16) & 0xfffffffe Util.assert(!!inf.value) s = s.slice(8) } } Util.die(); } function isRefKind(k:Kind) { Util.assert(k != null) Util.assert(k != api.core.Unknown) var isSimple = k == api.core.Number || k == api.core.Boolean return !isSimple } function isRefExpr(e:Expr) { if (typeof e.getLiteral() == "string" && e.enumVal != null) return false; if (typeof e.getLiteral() == "number") return false; return isRefKind(e.getKind()) } function lookupFunc(name:string) { if (/^uBit\./.test(name)) name = name.replace(/^uBit\./, "micro_bit::").replace(/\.(.)/g, (x, y) => y.toUpperCase()) return funcInfo[name] } export function lookupFunctionAddr(name:string) { var inf = lookupFunc(name) if (inf) return inf.value - bytecodeStartAddr return null } export function tohex(n:number) { if (n < 0 || n > 0xffff) return ("0x" + n.toString(16)).toLowerCase() else return ("0x" + ("000" + n.toString(16)).slice(-4)).toLowerCase() } export class Location { isarg = false; constructor(public index:number, public def:Decl = null) { } toString() { var n = "" if (this.def) n += this.def.getName() if (this.isarg) n = "ARG " + n if (this.isRef()) n = "REF " + n if (this.isByRefLocal()) n = "BYREF " + n return "[" + n + "]" } isRef() { return this.def && isRefKind(this.def.getKind()) } refSuff() { if (this.isRef()) return "Ref" else return "" } isByRefLocal() { return this.def instanceof LocalDef && (<LocalDef>this.def).isByRef() } emitStoreByRef(proc:Procedure) { Util.assert(this.def instanceof LocalDef) if (this.isByRefLocal()) { this.emitLoadLocal(proc); proc.emit("pop {r1}"); proc.emitCallRaw("bitvm::stloc" + (this.isRef() ? "Ref" : "")); // unref internal } else { this.emitStore(proc) } } asmref(proc:Procedure) { if (this.isarg) { var idx = proc.args.length - this.index - 1 return "[sp, args@" + idx + "] ; " + this.toString() } else { var idx = this.index return "[sp, locals@" + idx + "] ; " + this.toString() } } emitStoreCore(proc:Procedure) { proc.emit("str r0, " + this.asmref(proc)) } emitStore(proc:Procedure) { if (this.isarg) Util.oops("store for arg") if (this.def instanceof GlobalDef) { proc.emitInt(this.index) proc.emitCall("bitvm::stglb" + this.refSuff(), 0); // unref internal } else { Util.assert(!this.isByRefLocal()) if (this.isRef()) { this.emitLoadCore(proc); proc.emitCallRaw("bitvm::decr"); } proc.emit("pop {r0}"); this.emitStoreCore(proc) } } emitLoadCore(proc:Procedure) { proc.emit("ldr r0, " + this.asmref(proc)) } emitLoadByRef(proc:Procedure) { if (this.isByRefLocal()) { this.emitLoadLocal(proc); proc.emitCallRaw("bitvm::ldloc" + this.refSuff()) proc.emit("push {r0}"); } else this.emitLoad(proc); } emitLoadLocal(proc:Procedure) { if (this.isarg && proc.argsInR5) { Util.assert(0 <= this.index && this.index < 32) proc.emit("ldr r0, [r5, #4*" + this.index + "]") } else { this.emitLoadCore(proc) } } emitLoad(proc:Procedure, direct = false) { if (this.def instanceof GlobalDef) { proc.emitInt(this.index) proc.emitCall("bitvm::ldglb" + this.refSuff(), 0); // unref internal } else { Util.assert(direct || !this.isByRefLocal()) this.emitLoadLocal(proc); proc.emit("push {r0}"); if (this.isRef() || this.isByRefLocal()) { proc.emitCallRaw("bitvm::incr"); } } } emitClrIfRef(proc:Procedure) { // Util.assert(!this.isarg) Util.assert(!(this.def instanceof GlobalDef)) if (this.isarg && this.isByRefLocal()) return // already handled by the local if (this.isRef() || this.isByRefLocal()) { this.emitLoadCore(proc); proc.emitCallRaw("bitvm::decr"); } } } export class Procedure { numArgs = 0; hasReturn = false; action:Action; argsInR5 = false; seqNo:number; lblNo = 0; label:string; prebody = ""; body = ""; locals:Location[] = []; args:Location[] = []; toString() { return this.prebody + this.body } mkLocal(def:LocalDef = null) { var l = new Location(this.locals.length, def) //if (def) console.log("LOCAL: " + def.getName() + ": ref=" + def.isByRef() + " cap=" + def._isCaptured + " mut=" + def._isMutable) this.locals.push(l) return l } emitClrs(omit:LocalDef, inclArgs = false) { var lst = this.locals if (inclArgs) lst = lst.concat(this.args) lst.forEach(p => { if (p.def != omit) p.emitClrIfRef(this) }) } emitCallRaw(name:string) { this.emit("bl " + name + " ; (raw)") } emitCall(name:string, mask:number) { var inf = lookupFunc(name) Util.assert(!!inf, "unimplemented function: " + name) Util.assert(inf.args <= 4) if (inf.args >= 4) this.emit("pop {r3}"); if (inf.args >= 3) this.emit("pop {r2}"); if (inf.args >= 2) this.emit("pop {r1}"); if (inf.args >= 1) this.emit("pop {r0}"); var reglist:string[] = [] for (var i = 0; i < 4; ++i) { if (mask & (1 << i)) reglist.push("r" + i) } var numMask = reglist.length if (inf.type == "F" && mask != 0) { // reserve space for return val reglist.push("r7") this.emit("@stackmark retval") } Util.assert((mask & ~0xf) == 0) if (reglist.length > 0) this.emit("push {" + reglist.join(",") + "}") this.emit("bl " + name) if (inf.type == "F") { if (mask == 0) this.emit("push {r0}"); else { this.emit("str r0, [sp, retval@-1]") } } else if (inf.type == "P") { // ok } else Util.oops("invalid call type " + inf.type) while (numMask-- > 0) { this.emitCall("bitvm::decr", 0); } } emitJmp(trg:string, name = "JMP") { var lbl = "" if (name == "JMPZ") { lbl = this.mkLabel("jmpz") this.emit("pop {r0}"); this.emit("cmp r0, #0") this.emit("bne " + lbl) // this is to *skip* the following 'b' instruction; bne itself has a very short range } else if (name == "JMPNZ") { lbl = this.mkLabel("jmpnz") this.emit("pop {r0}"); this.emit("cmp r0, #0") this.emit("beq " + lbl) } else if (name == "JMP") { // ok } else { Util.oops("bad jmp"); } this.emit("bb " + trg) if (lbl) this.emitLbl(lbl) } mkLabel(root:string):string { return "." + root + "." + this.seqNo + "." + this.lblNo++; } emitLbl(lbl:string) { this.emit(lbl + ":") } emit(name:string) { this.body += asmline(name) } emitMov(v:number) { Util.assert(0 <= v && v <= 255) this.emit("movs r0, #" + v) } emitAdd(v:number) { Util.assert(0 <= v && v <= 255) this.emit("adds r0, #" + v) } emitLdPtr(lbl:string, push = false) { Util.assert(!!lbl) this.emit("movs r0, " + lbl + "@hi ; ldptr " + lbl) this.emit("lsls r0, r0, #8") this.emit("adds r0, " + lbl + "@lo ; endldptr"); if (push) this.emit("push {r0}") } emitInt(v:number, keepInR0 = false) { Util.assert(v != null); var n = Math.floor(v) var isNeg = false if (n < 0) { isNeg = true n = -n } if (n <= 255) { this.emitMov(n) } else if (n <= 0xffff) { this.emitMov((n >> 8) & 0xff) this.emit("lsls r0, r0, #8") this.emitAdd(n & 0xff) } else { this.emitMov((n >> 24) & 0xff) this.emit("lsls r0, r0, #8") this.emitAdd((n >> 16) & 0xff) this.emit("lsls r0, r0, #8") this.emitAdd((n >> 8) & 0xff) this.emit("lsls r0, r0, #8") this.emitAdd((n >> 0) & 0xff) } if (isNeg) { this.emit("neg r0, r0") } if (!keepInR0) this.emit("push {r0}") } stackEmpty() { this.emit("@stackempty locals"); } pushLocals() { Util.assert(this.prebody == "") this.prebody = this.body this.body = "" } popLocals() { var suff = this.body this.body = this.prebody var len = this.locals.length if (len > 0) this.emit("movs r0, #0") this.locals.forEach(l => { this.emit("push {r0} ; loc") }) this.emit("@stackmark locals") this.body += suff Util.assert(0 <= len && len < 127); if (len > 0) this.emit("add sp, #4*" + len + " ; pop locals " + len) } } function hexBytes(bytes:number[]) { var chk = 0 var r = ":" bytes.forEach(b => chk += b) bytes.push((-chk) & 0xff) bytes.forEach(b => r += ("0" + b.toString(16)).slice(-2)) return r.toUpperCase(); } export class Binary { procs:Procedure[] = []; globals:Location[] = []; buf:number[]; csource = ""; strings:StringMap<string> = {}; stringsBody = ""; lblNo = 0; isDataRecord(s:string) { if (!s) return false var m = /^:......(..)/.exec(s) Util.assert(!!m) return m[1] == "00" } patchHex(shortForm:boolean) { var myhex = hex.slice(0, bytecodeStartIdx) Util.assert(this.buf.length < 32000) var ptr = 0 function nextLine(buf:number[], addr:number) { var bytes = [0x10, (addr>>8)&0xff, addr&0xff, 0] for (var j = 0; j < 8; ++j) { bytes.push((buf[ptr] || 0) & 0xff) bytes.push((buf[ptr] || 0) >>> 8) ptr++ } return bytes } var hd = [0x4207, this.globals.length, bytecodeStartAddr & 0xffff, bytecodeStartAddr >>> 16] var tmp = hexTemplateHash() for (var i = 0; i < 4; ++i) hd.push(parseInt(swapBytes(tmp.slice(i * 4, i * 4 + 4)), 16)) myhex[jmpStartIdx] = hexBytes(nextLine(hd, jmpStartAddr)) ptr = 0 if (shortForm) myhex = [] var addr = bytecodeStartAddr; var upper = (addr - 16) >> 16 while (ptr < this.buf.length) { if ((addr >> 16) != upper) { upper = addr >> 16 myhex.push(hexBytes([0x02, 0x00, 0x00, 0x04, upper >> 8, upper & 0xff])) } myhex.push(hexBytes(nextLine(this.buf, addr))) addr += 16 } if (!shortForm) hex.slice(bytecodeStartIdx).forEach(l => myhex.push(l)) return myhex; } addProc(proc:Procedure) { this.procs.push(proc) proc.seqNo = this.procs.length proc.label = "_" + (proc.action ? proc.action.getName().replace(/[^\w]/g, "") : "inline") + "_" + proc.seqNo } stringLiteral(s:string) { var r = "\"" for (var i = 0; i < s.length; ++i) { // TODO generate warning when seeing high character ? var c = s.charCodeAt(i) & 0xff var cc = String.fromCharCode(c) if (cc == "\\" || cc == "\"") r += "\\" + cc else if (cc == "\n") r += "\\n" else if (c <= 0xf) r += "\\x0" + c.toString(16) else if (c < 32 || c > 127) r += "\\x" + c.toString(16) else r += cc; } return r + "\"" } emitLiteral(s:string) { this.stringsBody += s + "\n" } emitString(s:string):string { if (this.strings.hasOwnProperty(s)) return this.strings[s] var lbl = "_str" + this.lblNo++ this.strings[s] = lbl; this.emitLiteral(".balign 4"); this.emitLiteral(lbl + "meta: .short 0xffff, " + s.length) this.emitLiteral(lbl + ": .string " + this.stringLiteral(s)) return lbl } emit(s:string) { this.csource += asmline(s) } serialize() { Util.assert(this.csource == ""); this.emit("; start") this.emit(".hex 708E3B92C615A841C49866C975EE5197") this.emit(".hex " + hexTemplateHash() + " ; hex template hash") this.emit(".hex 0000000000000000 ; @SRCHASH@") this.emit(".space 16 ; reserved") this.procs.forEach(p => { this.csource += "\n" + p.body }) this.csource += this.stringsBody this.emit("_program_end:"); } patchSrcHash() { var srcSha = Random.sha256buffer(Util.stringToUint8Array(Util.toUTF8(this.csource))) this.csource = this.csource.replace(/\n.*@SRCHASH@\n/, "\n .hex " + srcSha.slice(0, 16).toUpperCase() + " ; program hash\n") } addSource(meta:string, blob:Uint8Array) { var metablob = Util.stringToUint8Array(Util.toUTF8(meta)) var totallen = metablob.length + blob.length if (totallen > 40000) { return 0; } this.emit(".balign 16"); this.emit(".hex 41140E2FB82FA2BB"); this.emit(".short " + metablob.length); this.emit(".short " + blob.length); this.emit(".short 0"); // future use this.emit(".short 0"); // future use var str = "_stored_program: .string \"" var addblob = (b:Uint8Array) => { for (var i = 0; i < b.length; ++i) { var v = b[i] & 0xff if (v <= 0xf) str += "\\x0" + v.toString(16) else str += "\\x" + v.toString(16) } } addblob(metablob) addblob(blob) str += "\"" this.emit(str) return totallen + 16; } static extractSource(hexfile: string): { meta: string; text: Uint8Array;} { if (!hexfile) return undefined; var metaLen = 0 var textLen = 0 var toGo = 0 var buf:number[]; var ptr = 0; hexfile.split(/\r?\n/).forEach(ln => { var m = /^:10....0041140E2FB82FA2BB(....)(....)(....)(....)(..)/.exec(ln) if (m) { metaLen = parseInt(swapBytes(m[1]), 16) textLen = parseInt(swapBytes(m[2]), 16) toGo = metaLen + textLen buf = <any>new Uint8Array(toGo) } else if (toGo > 0) { m = /^:10....00(.*)(..)$/.exec(ln) if (!m) return var k = m[1] while (toGo > 0 && k.length > 0) { buf[ptr++] = parseInt(k[0] + k[1], 16) k = k.slice(2) toGo-- } } }) if (!buf || !(toGo == 0 && ptr == buf.length)) { return undefined; } var bufmeta = new Uint8Array(metaLen) var buftext = new Uint8Array(textLen) for (var i = 0; i < metaLen; ++i) bufmeta[i] = buf[i]; for (var i = 0; i < textLen; ++i) buftext[i] = buf[metaLen + i]; // iOS Safari doesn't seem to have slice() on Uint8Array return { meta: Util.fromUTF8Bytes(bufmeta), text: buftext } } assemble() { Thumb.test(); // just in case var b = new Thumb.Binary(); b.lookupExternalLabel = lookupFunctionAddr; // b.throwOnError = true; b.emit(this.csource); this.csource = b.getSource(!/peepdbg=1/.test(document.URL)); if (b.errors.length > 0) { var userErrors = "" b.errors.forEach(e => { var m = /^user(\d+)/.exec(e.scope) if (m) { // This generally shouldn't happen, but it may for certin kind of global // errors - jump range and label redefinitions var no = parseInt(m[1]) var proc = this.procs.filter(p => p.seqNo == no)[0] if (proc && proc.action) userErrors += lf("At function {0}:\n", proc.action.getName()) else userErrors += lf("At inline assembly:\n") userErrors += e.message } }) if (userErrors) { ModalDialog.showText(userErrors, lf("errors in inline assembly")) } else { throw new Error(b.errors[0].message) } } else { this.buf = b.buf; } } } export class ReachabilityVisitor extends PreCompiler { markShims = false; useAction(a:Action) { if (a.getShimName() != null) { if (this.markShims || a._compilerInlineBody) { // TODO mark stuff as used a.visitorState = true; } return; } super.useAction(a) } } export function computeReachableNodes(app:App, markShims = false) { var prev = Script try { Script = app var pre = new ReachabilityVisitor({}); pre.markShims = markShims pre.run(Script) } finally { Script = prev } } export class Compiler extends NodeVisitor { public binary = new Binary(); private proc:Procedure; private numStmts = 1; constructor(private app:App) { super() } private shouldCompile(d:Decl) { return d.visitorState === true; } public run() { setup(); if (AST.TypeChecker.tcApp(this.app) > 0) { HTML.showProgressNotification(lf("Your script has errors! Just saving the source.")) return; } var prev = Script try { Script = this.app computeReachableNodes(this.app) this.app.librariesAndThis().forEach(l => { if (l.isThis()) { l.resolved.libraries().forEach(lr => lr.getPublicActions().forEach((la : LibraryRefAction) => { la._compilerInfo = la.template })) } else { var ress = Util.toDictionary(<ResolveClause[]>l.resolveClauses.stmts, r => r.formalLib.getName()) l.resolved.libraries().forEach(lr => { var acts = Util.toDictionary(<ActionBinding[]>ress[lr.getName()].actionBindings.stmts, a => a.formal.getName()) lr.getPublicActions().forEach((la : LibraryRefAction) => { if (!acts[la.getName()]) return var act = acts[la.getName()].actual if (act instanceof LibraryRefAction && (<LibraryRefAction>act).template) la._compilerInfo = (<LibraryRefAction>act).template else la._compilerInfo = act }) }) } this.prepApp(l.resolved) }) this.app.librariesAndThis().forEach(l => { this.compileApp(l.resolved) }) while (this.finals.length > 0) { var f = this.finals.shift() f() } } finally { Script = prev; } } public serialize(shortForm:boolean, metainfo:string, blob:Uint8Array) { var compiled = false shortForm = false; // this doesn't work yet if (this.binary.procs.length == 0) { shortForm = true // which is great in case there are errors in the program } else { this.binary.serialize() compiled = true } var lenSrc = 0 if (metainfo != null && blob != null) lenSrc = this.binary.addSource(metainfo, blob); this.binary.patchSrcHash() var sourceSaved = lenSrc > 0; this.binary.assemble() var res = { data: null, contentType: "application/x-microbit-hex", csource: this.binary.csource, sourceSaved: sourceSaved, compiled: compiled, } if (!this.binary.buf) return res; var hex = this.binary.patchHex(shortForm).join("\r\n") + "\r\n"; res.data = hex; return res; } visitAstNode(n:AstNode) { this.visitChildren(n); } handleAssignment(e:Call) { Util.assert(e._assignmentInfo.targets.length == 1) var trg = e.args[0] var src = e.args[1] var refSuff = isRefKind(e.args[1].getKind()) ? "Ref" : "" if (trg.referencedRecordField()) { this.dispatch((<Call>trg).args[0]) this.emitInt(this.fieldIndex(trg.referencedRecordField())) this.dispatch(src) this.proc.emitCall("bitvm::stfld" + refSuff, 0); // it does the decr itself, no mask } else if (trg.referencedData()) { this.dispatch(src); this.globalIndex(trg.referencedData()).emitStore(this.proc); } else if (trg.referencedLocal()) { this.dispatch(src); this.localIndex(trg.referencedLocal()).emitStoreByRef(this.proc); } else { Util.oops("bad assignment: " + trg.nodeType()) } } visitBreak(b:Call) { this.proc.emitJmp(b.topAffectedStmt._compilerBreakLabel); } visitContinue(b:Call) { this.proc.emitJmp(b.topAffectedStmt._compilerContinueLabel); } visitReturn(r:Call) { if (r.topRetLocal) { this.dispatch(r.args[0]); this.localIndex(r.topRetLocal).emitStore(this.proc); } this.proc.emitJmp(r.topAffectedStmt._compilerBreakLabel) } getMask(args:Expr[]) { Util.assert(args.length <= 8) var m = 0 args.forEach((a, i) => { if (isRefExpr(a)) m |= (1 << i) }) return m } emitAsString(e:Expr) { this.dispatch(e) var kn = e.getKind().getName().toLowerCase() if (kn == "string") {} else if (kn == "number" || kn == "boolean") { this.proc.emitCall(kn + "::to_string", 0) } else { Util.oops("don't know how to convert " + kn + " to string") } } emitImageLiteral(s:string) { if (!s) s = "0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n"; var x = 0; var w = 0; var h = 0; var lit = ""; for (var i = 0; i < s.length; ++i) { switch (s[i]) { case "0": lit += "0,"; x++; break; case "1": lit += "1,"; x++; break; case " ": break; case "\n": if (w == 0) w = x; else if (x != w) // Sanity check throw new Error("Malformed string literal"); x = 0; h++; break; default: throw new Error("Malformed string literal"); } } if (x > 0) h++; // non-terminated last line var lbl = "_img" + this.binary.lblNo++ this.binary.emitLiteral(".balign 4"); this.binary.emitLiteral(lbl + ": .short 0xffff") this.binary.emitLiteral(" .short " + w + ", " + h) if (lit.length % 4 != 0) lit += "42" // pad this.binary.emitLiteral(" .byte " + lit) this.proc.emitLdPtr(lbl, true); } handleActionCall(e:Call) { var aa = e.calledExtensionAction() || e.calledAction() var args = e.args.slice(0) if (args[0].getKind() instanceof ThingSetKind || args[0].referencedLibrary() || (args[0] instanceof ThingRef && (<ThingRef>args[0]).namespaceLibraryName())) { args.shift() } Util.assert(args.length == aa.getInParameters().length) var a:Action = aa._compilerInfo || aa Util.assert(args.length == a.getInParameters().length) if (a != aa) { var params = a.getParameters().slice(-a.getInParameters().length) params.forEach(p => { var sv = p.getStringValues() if (!sv) return var emap = (<any>sv).enumMap if (emap) { var v = emap[args[0].getStringLiteral()] Util.assert(v != null) args[0].enumVal = v; } }) } var shm = a.getShimName(); var hasret = !!aa.getOutParameters()[0] if (shm == "TD_NOOP") { Util.assert(!hasret) return } if (/^micro_bit::(createImage|createReadOnlyImage|showAnimation|showLeds|plotLeds)$/.test(shm)) { Util.assert(args[0].getLiteral() != null) this.emitImageLiteral(args[0].getLiteral()) args.shift() args.forEach(a => this.dispatch(a)) // fake it, so we don't get assert down below and mask is correct args = [<Expr>mkLit(0)].concat(args) } else { args.forEach(a => this.dispatch(a)) } if (shm == "TD_ID") { Util.assert(args.length == 1) // argument already on stack return; } if (shm != null) { var mask = this.getMask(args) var msg = "{shim:" + shm + "} from " + a.getName() if (!shm) userError("called " + msg + " (with empty {shim:}") var inf = lookupFunc(shm) if (a._compilerInlineBody) { Util.assert(!inf); funcInfo[shm] = { name: shm, type: hasret ? "F" : "P", args: a.getInParameters().length, idx: 0, value: 0 } try { this.proc.emitCall(shm, mask) } finally { delete funcInfo[shm] } } else { if (!inf) userError("shim not found: " + msg) if (!hasret) { if (inf.type != "P") userError("expecting procedure for " + msg); } else { if (inf.type != "F") userError("expecting function for " + msg); } if (args.length != inf.args) userError("argument number mismatch: " + args.length + " vs " + inf.args + " in " + msg) this.proc.emitCall(shm, mask) } } else { this.proc.emit("bl " + this.procIndex(a).label) if (args.length > 0) { var len = args.length Util.assert(0 <= len && len < 127); this.proc.emit("add sp, #4*" + len) } if (hasret) this.proc.emit("push {r0}"); } } emitLazyOp(op:string, arg0:Expr, arg1:Expr) { this.dispatch(arg0) var lblEnd = this.proc.mkLabel("lazy") if (op == "and") { this.proc.emitJmp(lblEnd, "JMPZ") } else if (op == "or") { this.proc.emitJmp(lblEnd, "JMPNZ") } else { Util.die() } this.dispatch(arg1) this.proc.emit("pop {r0}") this.proc.emitLbl(lblEnd); this.proc.emit("push {r0}") } visitCall(e:Call) { var p = e.getCalledProperty() if (p == api.core.AssignmentProp) { this.handleAssignment(e) return } var emitCall = (name:string, args:Expr[]) => { args.forEach(a => this.dispatch(a)) this.proc.emitCall(name, this.getMask(args)); } var pkn = p.parentKind.getRoot().getName() if (e.args.length == 1 && p.getName() == "is invalid") { this.dispatch(e.args[0]) this.proc.emitCall("bitvm::is_invalid", this.getMask(e.args)); } else if (e.referencedData()) { this.globalIndex(e.referencedData()).emitLoad(this.proc) } else if (e.referencedLibrary()) { this.emitInt(0) } else if (e.calledAction() || e.calledExtensionAction()) { this.handleActionCall(e); } else if (e.args[0] && e.args[0].referencedRecord()) { var rrec = e.args[0].referencedRecord() if (p.getName() == "create") { this.emitInt(rrec._compilerInfo.refsize); this.emitInt(rrec._compilerInfo.size); this.proc.emitCall("record::mk", 0); } else if (p.getName() == "invalid") { this.emitInt(0) } else { Util.oops("unhandled record operation: " + p.getName()) } } else if (e.referencedRecordField()) { this.dispatch(e.args[0]) this.emitInt(this.fieldIndex(e.referencedRecordField())) this.proc.emitCall("bitvm::ldfld" + (isRefKind(e.getKind()) ? "Ref" : ""), 0); // internal unref } else if (p.parentKind instanceof RecordEntryKind) { if (p.getName() == "equals") { emitCall("number::eq", e.args) } else { Util.oops("unhandled entry record operation: " + p.getName()) } } else if (pkn == "Invalid") { this.emitInt(0); } else if ((e.getKind().getRoot() == api.core.Collection && e.args[0].getCalledProperty() && e.args[0].getCalledProperty().getName() == "Collection of")) { var argK = e.getKind().getParameter(0) if (argK == api.core.String) this.proc.emitInt(3); else if (isRefKind(argK)) this.proc.emitInt(1); else this.proc.emitInt(0); this.proc.emitCall("collection::mk", 0); } else if (p == api.core.StringConcatProp) { this.emitAsString(e.args[0]); this.emitAsString(e.args[1]); this.proc.emitCall("string::concat_op", 3); } else if (pkn == "Boolean" && /^(and|or)$/.test(p.getName())) { Util.assert(e.args.length == 2) this.emitLazyOp(p.getName(), e.args[0], e.args[1]) } else { var args = e.args.slice(0) if (args[0].getThing() instanceof SingletonDef) args.shift() var nm = pkn.toLowerCase() + "::" + Embedded.Helpers.mangle(p.getName()) var inf = lookupFunc(nm) if (!inf) { nm = pkn.toLowerCase() + "::" + p.runtimeName() inf = lookupFunc(nm) } if (nm == "contract::assert") { Util.assert(typeof args[1].getLiteral() == "string") this.dispatch(args[0]) var lbl = this.binary.emitString(args[1].getLiteral()) this.proc.emitLdPtr(lbl, true) this.proc.emitCall(nm, 0) return } if (inf) { if (e.getKind() == api.core.Nothing) { Util.assert(inf.type == "P", "expecting procedure for " + nm); } else { Util.assert(inf.type == "F", "expecting function for " + nm); } Util.assert(args.length == inf.args, "argument number mismatch: " + args.length + " vs " + inf.args) emitCall(nm, args); } else { Util.oops("function not found: " + nm) } } } visitExprHolder(eh:ExprHolder) { var ai = eh.assignmentInfo() if (ai && ai.definedVars) ai.definedVars.forEach(l => { if (l.isByRef()) { var li = this.localIndex(l) li.emitClrIfRef(this.proc) // in case there was something already there this.proc.emitCallRaw("bitvm::mkloc" + li.refSuff()) li.emitStoreCore(this.proc) } }) if (eh.isPlaceholder()) this.proc.emit("nop"); else this.dispatch(eh.parsed) } emitInt(v:number, keepInR0 = false) { this.proc.emitInt(v, keepInR0) } visitLiteral(l:Literal) { if (l.data === undefined) return if (typeof l.data == "number") { this.emitInt(l.data) } else if (typeof l.data == "string") { if (l.enumVal != null) { if (/^-?\d+$/.test(l.enumVal)) { this.emitInt(parseInt(l.enumVal)) } else { var inf = lookupFunc(l.enumVal) if (!inf) userError(lf("unhandled enum value: {0}", l.enumVal)) if (inf.type == "E") this.proc.emitInt(inf.value) else if (inf.type == "F" && inf.args == 0) this.proc.emitCall(l.enumVal, 0) else userError(lf("not valid enum: {0}; is it procedure name?", l.enumVal)) } } else if (l.data == "") { this.proc.emitCall("string::mkEmpty", 0); } else { var lbl = this.binary.emitString(l.data) this.proc.emitLdPtr(lbl + "meta", false); this.proc.emitCallRaw("bitvm::stringData") this.proc.emit("push {r0}"); } } else if (typeof l.data == "boolean") { this.emitInt(l.data ? 1 : 0) } else { Util.oops("invalid literal emit " + l.data) } } private finals:(()=>void)[] = []; emitInlineAction(inl:InlineAction) { var inlproc = new Procedure() inlproc.argsInR5 = true this.binary.addProc(inlproc); var isRef = (l:LocalDef) => l.isByRef() || isRefKind(l.getKind()) var refs = inl.closure.filter(l => isRef(l)) var flats = inl.closure.filter(l => !isRef(l)) var caps = refs.concat(flats) this.emitInt(refs.length) this.emitInt(caps.length) this.proc.emitLdPtr(inlproc.label, true); this.proc.emitCall("action::mk", 0) caps.forEach((l, i) => { this.emitInt(i) this.localIndex(l).emitLoad(this.proc, true) // direct load this.proc.emitCall("bitvm::stclo", 0) // already done by emitCall // this.proc.emit("push {r0}"); }) this.finals.push(() => { this.proc = inlproc this.proc.args = caps.map((p, i) => { var l = new Location(i, p); l.isarg = true return l }) inl.allLocals.forEach(l => { l._lastWriteLocation = null; if (caps.indexOf(l) == -1) this.proc.mkLocal(l) }) this.proc.emit(".section code"); this.proc.emit(".balign 4"); this.proc.emitLbl(this.proc.label); this.proc.emit(".short 0xffff, 0x0000 ; action literal"); this.proc.emit("@stackmark inlfunc"); this.proc.emit("push {r5, lr}"); this.proc.emit("mov r5, r1"); this.proc.pushLocals(); inl.inParameters.forEach((loc, i) => { Util.assert(i < 2) var l = this.localIndex(loc, true) this.proc.emit("push {r" + (i + 2) + "}") l.emitStore(this.proc) }) var ret = this.proc.mkLabel("inlret") inl._compilerBreakLabel = ret; this.dispatch(inl.body); this.proc.emitLbl(ret) this.proc.emitClrs(null, false); this.proc.popLocals(); this.proc.emit("pop {r5, pc}"); this.proc.emit("@stackempty inlfunc"); }) } visitThingRef(t:ThingRef) { var d = t.def if (d instanceof LocalDef) { if (d._lastWriteLocation instanceof InlineAction) { this.emitInlineAction(<InlineAction>d._lastWriteLocation) } else { this.localIndex(d).emitLoadByRef(this.proc); } } else if (d instanceof SingletonDef) { this.emitInt(0) } else { Util.oops("invalid thing: " + d ? d.nodeType() : "(null)") } } visitAnyIf(i:If) { if (i.isTopCommentedOut()) return if (!i.branches) return var afterall = this.proc.mkLabel("afterif"); i.branches.forEach((b, k) => { if (!b.condition) { this.dispatch(b.body) } else { this.dispatch(b.condition) var after = this.proc.mkLabel("else"); this.proc.emitJmp(after, "JMPZ"); this.dispatch(b.body) this.proc.emitJmp(afterall) this.proc.emitLbl(after) } }) this.proc.emitLbl(afterall) } globalIndex(l:GlobalDef):Location { return this.binary.globals.filter(n => n.def == l)[0] } fieldIndex(l:RecordField):number { Util.assert(l._compilerInfo.idx != null); return l._compilerInfo.idx; } procIndex(a:Action):Procedure { return this.binary.procs.filter(n => n.action == a)[0] } localIndex(l:LocalDef, noargs = false):Location { return this.proc.locals.filter(n => n.def == l)[0] || (noargs ? null : this.proc.args.filter(n => n.def == l)[0]) } visitFor(f:For) { var upper = this.proc.mkLocal() this.dispatch(f.upperBound); upper.emitStore(this.proc); var idx = this.localIndex(f.boundLocal); this.proc.emitInt(0); idx.emitStore(this.proc); var top = this.proc.mkLabel("fortop") this.proc.emitLbl(top); var brk = this.proc.mkLabel("forbrk"); idx.emitLoad(this.proc); upper.emitLoad(this.proc); this.proc.emitCall("number::lt", 0); this.proc.emitJmp(brk, "JMPZ"); var cont = this.proc.mkLabel("forcnt"); f._compilerBreakLabel = brk; f._compilerContinueLabel = cont; this.dispatch(f.body) this.proc.emitLbl(cont); idx.emitLoad(this.proc); this.emitInt(1); this.proc.emitCall("number::add", 0); idx.emitStore(this.proc); this.proc.stackEmpty(); this.proc.emitJmp(top); this.proc.emitLbl(brk); } visitForeach(f:Foreach) { //TODO Util.oops("foreach emit") } visitWhile(n:While) { var top = this.proc.mkLabel("whiletop") this.proc.emitLbl(top); var brk = this.proc.mkLabel("whilebrk") this.dispatch(n.condition) this.proc.emitJmp(brk, "JMPZ"); n._compilerBreakLabel = brk; n._compilerContinueLabel = top; this.dispatch(n.body) this.proc.emitJmp(top); this.proc.emitLbl(brk); } visitInlineActions(i:InlineActions) { i.normalActions().forEach(a => a.name._lastWriteLocation = a) this.visitExprStmt(i) } visitExprStmt(es:ExprStmt) { if (es.isPlaceholder()) return this.dispatch(es.expr); var k = es.expr.parsed.getKind() if (k == api.core.Nothing) { this.proc.stackEmpty(); } else { if (isRefKind(k)) // will pop this.proc.emitCall("bitvm::decr", 0); else this.proc.emit("pop {r0}"); this.proc.stackEmpty(); } } visitCodeBlock(b:CodeBlock) { this.proc.stackEmpty(); b.stmts.forEach(s => { this.numStmts++; this.dispatch(s); this.proc.stackEmpty(); }) } visitAction(a:Action) { this.numStmts++; this.proc = this.procIndex(a); if (a.getShimName() != null) { var body = AST.getEmbeddedLangaugeToken(a._compilerInlineBody) Util.assert(body != null) Util.assert(body.getStringLiteral() != null) this.proc.emit(body.getStringLiteral()) this.proc.emit("@stackempty func"); this.proc.emit("@scope"); return } var ret = this.proc.mkLabel("actret") a._compilerBreakLabel = ret; this.dispatch(a.body) this.proc.emitLbl(ret) this.proc.stackEmpty(); /* // clear all globals for memory debugging if (this.proc.index == 0) { this.binary.globals.forEach(g => { if (g.isRef()) { this.emitInt(0); g.emitStore(this.proc); } }) } */ var retl = a.getOutParameters()[0] this.proc.emitClrs(retl ? retl.local : null, true); if (retl) { var li = this.localIndex(retl.local); Util.assert(!li.isByRefLocal()) li.emitLoadCore(this.proc) } this.proc.popLocals(); this.proc.emit("pop {pc}"); this.proc.emit("@stackempty func"); } visitGlobalDef(g:GlobalDef) { var x = new Location(this.binary.globals.length, g) this.binary.globals.push(x) } visitLibraryRef(l:LibraryRef) { // skip } visitRecordDef(r:RecordDef) { Util.assert(r.recordType == RecordType.Object); var refs = r.getFields().filter(f => isRefKind(f.dataKind)) var flats = r.getFields().filter(f => !isRefKind(f.dataKind)) r._compilerInfo = { size: refs.length + flats.length, refsize: refs.length } refs.concat(flats).forEach((f, i) => { f._compilerInfo = { idx: i } }) } prepAction(a:Action) { var p = new Procedure() this.proc = p; p.action = a; this.binary.addProc(p) var shimname = a.getShimName() if (shimname != null) { Util.assert(!!a._compilerInlineBody) this.proc.label = shimname this.proc.emit(".section code"); this.proc.emit(".balign 4"); this.proc.emitLbl(this.proc.label); this.proc.emit("@scope user" + p.seqNo) this.proc.emit("@stackmark func"); return } var inparms = a.getInParameters().map(p => p.local) this.proc.args = inparms.map((p, i) => { var l = new Location(i, p); l.isarg = true return l }) this.proc.emit(".section code"); this.proc.emitLbl(this.proc.label); this.proc.emit("@stackmark func"); this.proc.emit("@stackmark args"); this.proc.emit("push {lr}"); this.proc.pushLocals(); var copyArgIntoLocal = (loc:LocalDef) => { if (!loc) return var idx = inparms.indexOf(loc) if (idx >= 0) { var curr = this.localIndex(loc, true) if (!curr) { var l = this.proc.mkLocal(loc) if (loc.isByRef()) { this.proc.emitCallRaw("bitvm::mkloc" + l.refSuff()) l.emitStoreCore(this.proc) } this.proc.args[idx].emitLoadLocal(this.proc) this.proc.emit("push {r0}") l.emitStoreByRef(this.proc) } } } visitStmts(a.body, s => { if (s instanceof ExprStmt) { var ai = (<ExprStmt>s).expr.assignmentInfo() if (ai) { ai.targets.forEach(t => copyArgIntoLocal(t.referencedLocal())) } } }) // this includes in and out parameters; we filter out the ins a.allLocals.forEach(l => { l._lastWriteLocation = null; if (inparms.indexOf(l) == -1) this.proc.mkLocal(l) }) } dump(lst:Decl[]) { lst.forEach(t => { if (this.shouldCompile(t)) this.dispatch(t) }) } prepApp(a:App) { this.actions(a).forEach(a => { if (!this.shouldCompile(a)) return this.prepAction(a) }) this.dump(a.libraries()) this.dump(a.variables()) this.dump(a.resources()) this.dump(a.records()) } actions(a:App):Action[] { var res = a.allActions().filter(a => !a.isActionTypeDef()); App.orderThings(res) return res; } compileApp(a:App) { this.dump(this.actions(a)) } visitApp(a:App) { Util.oops("") } visitComment(c:Comment) { // do nothing } visitStmt(s:Stmt) { Util.oops("unhandled stmt: " + s.nodeType()) } } function lintThumb(act:Action, asm:string) { setup(); var shimname = act.getShimName(); var b = new Thumb.Binary(); if (/{shim:/.test(act.getDescription())) b.pushError(lf("use {asm:{0}} with app->thumb, not {shim:{0}}", shimname)) if (lookupFunc(shimname)) b.pushError(lf("{asm:{0}} already defined in runtime", shimname)) if (!/^\w+$/.test(shimname)) b.pushError(lf("invalid characters in shim name: {asm:{0}}", shimname)) if (act.getInParameters().length > 4) b.pushError(lf("inline shims support only up to 4 arguments")); if (b.errors.length > 0) return b.errors; var code = ".section code\n" + "@stackmark func\n" + shimname + ":\n" + "@scope user\n" + asm + "\n" + "@stackempty func\n" + "@scope\n" b.lookupExternalLabel = lookupFunctionAddr; b.throwOnError = false; b.inlineMode = true; b.emit(code) return b.errors; } TypeChecker.lintThumb = lintThumb; function asmline(s:string) { if (!/(^\s)|(:$)/.test(s)) s = " " + s return s + "\n" } function hexTemplateHash() { var sha = currentSetup ? currentSetup.slice(0, 16) : "" while (sha.length < 16) sha += "0" return sha.toUpperCase() } function emptyExtInfo() { return <ExtensionInfo> { enums: {}, functions: [], errors: "", sha: "", compileData: "", hasExtension: false, } } function setup() { if (currentSetup == null) setupFor(emptyExtInfo(), null) } function parseExpr(e:string) { e = e.trim() e = e.replace(/^\(/, "") e = e.replace(/\)$/, "") e = e.trim(); if (/^-/.test(e) && parseExpr(e.slice(1)) != null) return -parseExpr(e.slice(1)) if (/^0x[0-9a-f]+$/i.exec(e)) return parseInt(e.slice(2), 16) if (/^0b[01]+$/i.exec(e)) return parseInt(e.slice(2), 2) if (/^0\d+$/i.exec(e)) return parseInt(e, 8) if (/^\d+$/i.exec(e)) return parseInt(e, 10) return null; } export interface GlueJson { dependencies?: StringMap<string>; config?: StringMap<string>; } export function getExtensionInfo(app:App) : ExtensionInfo { var res = emptyExtInfo(); var fileRepl:StringMap<string> = {} var pointersInc = "" var includesInc = "" var totalConfig:GlueJson = { dependencies: {}, config: {}, } var thisErrors = "" var err = (s) => thisErrors += " " + s + "\n"; var cfginc = "" function parseCpp(src:string) { res.hasExtension = true var currNs = "" src.split(/\r?\n/).forEach(ln => { var m = /^\s*namespace\s+(\w+)/.exec(ln) if (m) { if (currNs) err("more than one namespace declaration not supported") currNs = m[1] return; } m = /^\s*GLUE\s+(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(ln) if (m) { if (!currNs) err("missing namespace declaration before GLUE"); var retTp = (m[1] + m[2]).replace(/\s+/g, "") var funName = m[3] var args = m[4] var numArgs = 0 if (args.trim()) numArgs = args.replace(/[^,]/g, "").length + 1; var fi:FuncInfo = { name: currNs + "::" + funName, type: retTp == "void" ? "P" : "F", args: numArgs, value: null } res.functions.push(fi) pointersInc += "(uint32_t)(void*)::" + fi.name + ",\n" return; } if (/^\s*GLUE\s+/.test(ln)) { err("invalid GLUE line: " + ln) return; } ln = ln.replace(/\/\/.*/, "") var isEnum = false m = /^\s*#define\s+(\w+)\s+(.*)/.exec(ln) if (!m) { m = /^\s*(\w+)\s*=\s*(.*)/.exec(ln) isEnum = true } if (m) { var num = m[2] num = num.replace(/\/\/.*/, "") num = num.replace(/\/\*.*/, "") num = num.trim() if (isEnum) num = num.replace(/,$/, "") var val = parseExpr(num) var nm = m[1] if (isEnum) nm = currNs + "::" + nm //console.log(nm, num, val) if (val != null) { res.enums[nm] = val return; } } }) if (!currNs) err("missing namespace declaration") includesInc += "#include \"" + currNs + ".cpp\"\n" fileRepl["/generated/" + currNs + ".cpp"] = src } function parseJson(src:string) { var parsed = RT.JsonParser.parse(src, err); if (!parsed) return; var json = <GlueJson>parsed.value(); if (!json) return; res.hasExtension = true if (json.dependencies) Util.jsonCopyFrom(totalConfig.dependencies, json.dependencies) if (json.config) Object.keys(json.config).forEach(k => { if (!/^\w+$/.test(k)) err(lf("invalid config variable: {0}", k)) cfginc += "#undef " + k + "\n" if (!/^\w+$/.test(json.config[k])) err(lf("invalid config value: {0}: {1}", k, json.config[k])) cfginc += "#define " + k + " " + json.config[k] + "\n" }) } function isUsed(a:Action) { if (a.visitorState) return true var l = <LibraryRefAction>a if (l.template && l.template.visitorState) return true return false } if (app) { computeReachableNodes(app, true) app.librariesAndThis().forEach(l => { if (!l.isThis() && !l.getPublicActions().some(isUsed)) { Util.log("skip library " + l.getName()) return } thisErrors = "" l.resolved.resources().forEach(r => { if (r.getName() != "glue.cpp" && r.getName() != "glue.json") return; var src = r.stringResourceValue() if (src == null) { err(lf("'{0}' isn't a string resource", r.getName())) return } if (r.getName() == "glue.cpp") parseCpp(src) else parseJson(src) }) if (thisErrors) { res.errors += lf("Library {0}:\n", l.getName()) + thisErrors } }) } if (res.errors) return res; if (cfginc) fileRepl["/generated/extconfig.h"] = cfginc fileRepl["/generated/extpointers.inc"] = pointersInc fileRepl["/generated/extensions.inc"] = includesInc var creq = { config: "ws", tag: Cloud.config.microbitGitTag, replaceFiles: fileRepl, dependencies: totalConfig.dependencies, } var reqData = Util.toUTF8(JSON.stringify(creq)) res.sha = Random.sha256buffer(Util.stringToUint8Array(reqData)) res.compileData = Util.base64Encode(reqData) return res; } }
the_stack
import { PLUGIN_COMPONENT, PLUGIN_TOOLBAR_BUTTONS, DIVIDER_DROPDOWN_OPTIONS, STATIC_TOOLBAR_BUTTONS, INLINE_TOOLBAR_BUTTONS, COLLAPSIBLE_LIST_SETTINGS, ACTION_BUTTONS, } from '../cypress/dataHooks'; import { DEFAULT_DESKTOP_BROWSERS, DEFAULT_MOBILE_BROWSERS } from './settings'; import { usePlugins, plugins, usePluginsConfig } from '../cypress/testAppConfig'; const eyesOpen = ({ test: { parent: { title }, }, }: Mocha.Context) => cy.eyesOpen({ appName: 'Plugins', testName: title, browser: DEFAULT_DESKTOP_BROWSERS, }); describe('plugins', () => { afterEach(() => cy.matchContentSnapshot()); context('html', () => { before(function() { eyesOpen(this); }); beforeEach('load editor', () => { cy.switchToDesktop(); }); after(() => cy.eyesClose()); it('render html plugin with url', function() { cy.loadRicosEditorAndViewer('empty') .addUrl() .waitForHtmlToLoad(); cy.eyesCheckWindow(this.test.title); }); it('render html plugin toolbar', function() { cy.loadRicosEditorAndViewer('empty') .addHtml() .waitForHtmlToLoad(); cy.get(`[data-hook*=${PLUGIN_TOOLBAR_BUTTONS.EDIT}]`) .click({ multiple: true }) .click(); cy.eyesCheckWindow(this.test.title); }); }); context('spoiler', () => { before(function() { eyesOpen(this); }); beforeEach('load editor', () => { cy.switchToDesktop(); }); after(() => cy.eyesClose()); it(`check text spoilers in editor and reveal it in viewer`, () => { cy.loadRicosEditorAndViewer('empty', usePlugins(plugins.spoilerPreset)).enterParagraphs([ 'Leverage agile frameworks to provide a robust synopsis for high level overviews.', 'Iterative approaches to corporate strategy foster collaborative thinking to further the overall value proposition.', // eslint-disable-line max-len ]); cy.setTextStyle('textSpoilerButton', [15, 5]); cy.blurEditor(); cy.setTextStyle('textSpoilerButton', [30, 10]); cy.eyesCheckWindow('adding some spoilers'); cy.setLink([5, 5], 'https://www.wix.com/'); cy.setTextStyle('textSpoilerButton', [0, 13]); cy.eyesCheckWindow('adding spoiler around link'); cy.setTextStyle('textSpoilerButton', [20, 10]); cy.eyesCheckWindow('apply spoiler on two existing spoilers'); cy.setTextStyle('textSpoilerButton', [20, 5]); cy.eyesCheckWindow('split spoiler'); cy.setTextStyle('textSpoilerButton', [70, 35]); cy.eyesCheckWindow('spoiler on multiple blocks'); cy.get('[data-hook="spoiler_0"]:first').click(); cy.eyesCheckWindow('reveal spoiler'); cy.get('[data-hook="spoiler_3"]:last').click(); cy.eyesCheckWindow('reveal spoiler on multiple blocks'); }); function editText(dataHook, title) { cy.get(`[data-hook="${dataHook}"]`) .click() .type(' - In Plugin Editing') .blur(); cy.eyesCheckWindow(title); } function revealSpoilerOnBlock() { cy.get('[data-hook="revealSpoilerBtn"]').click({ multiple: true }); cy.eyesCheckWindow('reveal spoiler in viewer'); } it(`check spoilers on an image in editor and reveal it in viewer`, () => { cy.loadRicosEditorAndViewer('images', usePlugins(plugins.spoilerPreset)); cy.get('[data-hook="imageViewer"]:first') .parent() .click(); // check spoiler from inline toolbar // cy.get(`[data-hook=${PLUGIN_TOOLBAR_BUTTONS.SPOILER}]:visible`).click(); //check spoiler from settings modal cy.clickToolbarButton(PLUGIN_TOOLBAR_BUTTONS.SETTINGS); cy.get(`[data-hook=imageSpoilerToggle]`).click(); cy.get(`[data-hook=${ACTION_BUTTONS.SAVE}]`).click(); cy.wait(100); //wait for setRef to get width and adjust correct blur cy.eyesCheckWindow('adding spoiler on an image'); editText('spoilerTextArea', 'change the description'); editText('revealSpoilerContent', 'change the reveal button content'); revealSpoilerOnBlock(); }); it(`check spoilers on a gallery in editor and reveal it in viewer`, () => { cy.loadRicosEditorAndViewer('gallery', usePlugins(plugins.spoilerPreset)); cy.get('[data-hook="galleryViewer"]:first') .parent() .click(); cy.get('[data-hook="baseToolbarButton_layout"]').click(); cy.get('[data-hook="Slideshow_dropdown_option"]').click(); cy.wait(100); // check spoiler from inline toolbar // cy.get(`[data-hook=${PLUGIN_TOOLBAR_BUTTONS.SPOILER}]:visible`).click(); //check spoiler from settings modal cy.clickToolbarButton(PLUGIN_TOOLBAR_BUTTONS.ADV_SETTINGS); cy.get(`[data-hook=gallerySpoilerToggle]`).click(); cy.get(`[data-hook=${ACTION_BUTTONS.SAVE}]`).click(); cy.eyesCheckWindow('adding spoiler on a gallery'); editText('spoilerTextArea', 'change the description'); editText('revealSpoilerContent', 'change the reveal button content'); revealSpoilerOnBlock(); }); // it(`check spoilers on a video in editor and reveal it in viewer`, () => { // cy.loadRicosEditorAndViewer('empty', usePlugins(plugins.spoilerPreset)); // cy.openVideoUploadModal().addVideoFromURL(); // cy.waitForVideoToLoad(); // cy.get('[data-hook="videoPlayer"]:first') // .parent() // .click(); // cy.get(`[data-hook=${PLUGIN_TOOLBAR_BUTTONS.SPOILER}]:visible`).click(); // cy.eyesCheckWindow('adding spoiler on a video'); // editText('spoilerTextArea', 'change the description'); // editText('revealSpoilerContent', 'change the reveal button content'); // revealSpoilerOnBlock(); // }); }); context('divider', () => { before(function() { eyesOpen(this); }); beforeEach('load editor', () => { cy.switchToDesktop(); }); after(() => cy.eyesClose()); it('render plugin toolbar and change styling', () => { cy.loadRicosEditorAndViewer('divider') .openPluginToolbar(PLUGIN_COMPONENT.DIVIDER) .openDropdownMenu(); cy.eyesCheckWindow('render divider plugin toolbar'); cy.clickToolbarButton(PLUGIN_TOOLBAR_BUTTONS.SMALL); cy.clickToolbarButton(PLUGIN_TOOLBAR_BUTTONS.ALIGN_LEFT); cy.get('#RicosEditorContainer [data-hook=divider-double]') .parent() .click(); cy.get('[data-hook*="PluginToolbar"]:first'); cy.clickToolbarButton(PLUGIN_TOOLBAR_BUTTONS.MEDIUM); cy.clickToolbarButton(PLUGIN_TOOLBAR_BUTTONS.ALIGN_RIGHT); cy.get('#RicosEditorContainer [data-hook=divider-dashed]') .parent() .click(); cy.get('[data-hook*="PluginToolbar"]:first').openDropdownMenu( `[data-hook=${DIVIDER_DROPDOWN_OPTIONS.DOUBLE}]` ); cy.eyesCheckWindow('change divider styling'); }); }); context('map', () => { before('load editor', function() { eyesOpen(this); cy.switchToDesktop(); cy.loadRicosEditorAndViewer('map'); cy.get('.dismissButton').eq(1); }); after(() => cy.eyesClose()); it('render map plugin toolbar and settings', () => { cy.openPluginToolbar(PLUGIN_COMPONENT.MAP); cy.eyesCheckWindow('render map plugin toolbar'); cy.openMapSettings(); cy.get('.gm-style-cc'); cy.eyesCheckWindow('render map settings'); }); }); context('file-upload', () => { before('load editor', function() { eyesOpen(this); cy.switchToDesktop(); cy.loadRicosEditorAndViewer('file-upload'); }); after(() => cy.eyesClose()); it('render file-upload plugin toolbar', function() { cy.openPluginToolbar(PLUGIN_COMPONENT.FILE_UPLOAD); cy.eyesCheckWindow(this.test.title); }); }); context('drag and drop', () => { before('load editor', function() { eyesOpen(this); cy.switchToDesktop(); cy.loadRicosEditorAndViewer('dragAndDrop'); }); after(() => cy.eyesClose()); // eslint-disable-next-line mocha/no-skipped-tests it.skip('drag and drop plugins', function() { cy.focusEditor(); const src = `[data-hook=${PLUGIN_COMPONENT.IMAGE}] + [data-hook=componentOverlay]`; const dest = `span[data-offset-key="fjkhf-0-0"]`; cy.dragAndDropPlugin(src, dest); cy.get('img[style="opacity: 1;"]'); cy.eyesCheckWindow(this.test.title); }); }); context('alignment', () => { before(function() { eyesOpen(this); }); beforeEach('load editor', () => { cy.switchToDesktop(); }); after(() => cy.eyesClose()); function testAtomicBlockAlignment(align: 'left' | 'right' | 'center') { it('align atomic block ' + align, function() { cy.loadRicosEditorAndViewer('images').alignImage(align); cy.eyesCheckWindow(this.test.title); }); } testAtomicBlockAlignment('left'); testAtomicBlockAlignment('center'); testAtomicBlockAlignment('right'); }); context('link preview', () => { before(function() { eyesOpen(this); }); after(() => cy.eyesClose()); beforeEach('load editor', () => cy.loadRicosEditorAndViewer('link-preview', usePlugins(plugins.embedsPreset)) ); afterEach('take snapshot', function() { cy.waitForHtmlToLoad(); cy.triggerLinkPreviewViewerUpdate(); cy.eyesCheckWindow(this.test.title); }); it('change link preview settings', () => { cy.openPluginToolbar(PLUGIN_COMPONENT.LINK_PREVIEW); cy.setLinkSettings(); }); //TODO: fix this flaky test // eslint-disable-next-line mocha/no-skipped-tests it('convert link preview to regular link', () => { cy.openPluginToolbar(PLUGIN_COMPONENT.LINK_PREVIEW); cy.clickToolbarButton('baseToolbarButton_replaceToLink'); }); it('backspace key should convert link preview to regular link', () => { cy.focusEditor() .type('{downarrow}{downarrow}') .type('{backspace}'); }); it('delete link preview', () => { cy.openPluginToolbar(PLUGIN_COMPONENT.LINK_PREVIEW).wait(100); cy.clickToolbarButton('blockButton_delete'); }); }); context('convert link to preview', () => { context('with default config', () => { before(function() { eyesOpen(this); }); const testAppConfig = { ...usePlugins(plugins.embedsPreset), ...usePluginsConfig({ linkPreview: { enableEmbed: undefined, enableLinkPreview: undefined, }, }), }; after(() => cy.eyesClose()); beforeEach('load editor', () => cy.loadRicosEditorAndViewer('empty', testAppConfig)); it('should create link preview from link after enter key', function() { cy.insertLinkAndEnter('www.wix.com', { isPreview: true }); cy.eyesCheckWindow(this.test.title); }); it('should embed link that supports embed', function() { cy.insertLinkAndEnter('www.mockUrl.com'); cy.eyesCheckWindow(this.test.title); }); }); context('with custom config', () => { before(function() { eyesOpen(this); }); const testAppConfig = { ...usePlugins(plugins.embedsPreset), ...usePluginsConfig({ linkPreview: { enableEmbed: false, enableLinkPreview: false, }, }), }; after(() => cy.eyesClose()); beforeEach('load editor', () => cy.loadRicosEditorAndViewer('empty', testAppConfig)); it('should not create link preview when enableLinkPreview is off', function() { cy.insertLinkAndEnter('www.wix.com'); cy.eyesCheckWindow(this.test.title); }); it('should not embed link when enableEmbed is off', function() { cy.insertLinkAndEnter('www.mockUrl.com'); cy.eyesCheckWindow(this.test.title); }); }); }); context('social embed', () => { before(function() { eyesOpen(this); }); const testAppConfig = { plugins: [plugins.linkPreview], }; beforeEach('load editor', () => { cy.switchToDesktop(); cy.loadRicosEditorAndViewer('empty', testAppConfig); }); after(() => cy.eyesClose()); const embedTypes = ['TWITTER', 'INSTAGRAM']; embedTypes.forEach(embedType => { it(`render ${embedType.toLowerCase()} upload modals`, function() { cy.openEmbedModal(STATIC_TOOLBAR_BUTTONS[embedType]); cy.eyesCheckWindow(this.test.title + ' modal'); cy.addSocialEmbed('www.mockUrl.com').waitForHtmlToLoad(); cy.get(`#RicosViewerContainer [data-hook=HtmlComponent]`); cy.eyesCheckWindow(this.test.title + ' added'); }); }); }); context('list', () => { before(function() { eyesOpen(this); }); beforeEach('load editor', () => cy.loadRicosEditorAndViewer()); after(() => cy.eyesClose()); // TODO: figure out how to test keyboard combinations of command/ctrl keys in cypress ci // eslint-disable-next-line mocha/no-skipped-tests it.skip('create nested lists using CMD+M/CMD+SHIFT+M', function() { cy.loadRicosEditorAndViewer() .enterParagraphs(['1. Hey I am an ordered list in depth 1.']) .type('{command+m}') .enterParagraphs(['\n Hey I am an ordered list in depth 2.']) .type('{command+m}') .enterParagraphs(['\n Hey I am an ordered list in depth 1.']) .type('{command+shift+m}') .enterParagraphs(['\n\n1. Hey I am an ordered list in depth 0.']); // .enterParagraphs(['\n\n- Hey I am an unordered list in depth 1.']) // .tab() // .enterParagraphs(['\n Hey I am an unordered list in depth 2.']) // .tab() // .enterParagraphs(['\n Hey I am an unordered list in depth 1.']) // .tab({ shift: true }) // .enterParagraphs(['\n\n- Hey I am an unordered list in depth 0.']); cy.eyesCheckWindow(this.test.title); }); }); context('verticals embed', () => { before(function() { eyesOpen(this); }); after(() => cy.eyesClose()); context('verticals embed modal', () => { beforeEach('load editor', () => { cy.switchToDesktop(); cy.loadRicosEditorAndViewer('empty', usePlugins(plugins.verticalEmbed)); }); // const embedTypes = ['EVENT', 'PRODUCT', 'BOOKING']; const embedTypes = ['PRODUCT', 'BOOKING', 'EVENT']; it('render upload modals', function() { embedTypes.forEach(embedType => { cy.openEmbedModal(STATIC_TOOLBAR_BUTTONS[embedType]); cy.eyesCheckWindow(this.test.title); cy.get(`[data-hook*=verticalsItemsList]`) .children() .first() .click(); cy.get(`[data-hook=${ACTION_BUTTONS.SAVE}]`).click(); }); }); }); context('verticals embed widget', () => { beforeEach('load editor', () => { cy.switchToDesktop(); cy.loadRicosEditorAndViewer('vertical-embed', usePlugins(plugins.verticalEmbed)); }); it('should replace widget', () => { cy.openPluginToolbar(PLUGIN_COMPONENT.VERTICAL_EMBED); cy.clickToolbarButton('baseToolbarButton_replace'); cy.get(`[data-hook*=verticalsItemsList]`) .children() .first() .click(); cy.get(`[data-hook=${ACTION_BUTTONS.SAVE}]`).click(); }); }); }); context('link button', () => { before(function() { eyesOpen(this); }); beforeEach('load editor', () => cy.loadRicosEditorAndViewer('link-button')); after(() => cy.eyesClose()); //TODO: fix this flaky test // eslint-disable-next-line mocha/no-skipped-tests // it.skip('create link button & customize it', function() { // cy.openPluginToolbar(PLUGIN_COMPONENT.BUTTON) // .get(`[data-hook*=${PLUGIN_TOOLBAR_BUTTONS.ADV_SETTINGS}][tabindex!=-1]`) // .click() // .get(`[data-hook*=ButtonInputModal][placeholder="Enter a URL"]`) // .type('www.wix.com') // .get(`[data-hook*=${BUTTON_PLUGIN_MODAL.DESIGN_TAB}]`) // .click() // .get(`[data-hook*=${BUTTON_PLUGIN_MODAL.BUTTON_SAMPLE}]`) // .click() // .get(`[data-hook*=${BUTTON_PLUGIN_MODAL.DONE}]`) // .click(); // cy.eyesCheckWindow(this.test.title); // }); }); context('action button', () => { before(function() { eyesOpen(this); }); beforeEach('load editor', () => cy.loadRicosEditorAndViewer('action-button', usePlugins(plugins.actionButton)) ); after(() => cy.eyesClose()); // it('create action button & customize it', function() { // cy.focusEditor(); // cy.openPluginToolbar(PLUGIN_COMPONENT.BUTTON) // .wait(100) // .get(`[data-hook*=${PLUGIN_TOOLBAR_BUTTONS.ADV_SETTINGS}][tabindex!=-1]`) // .click({ force: true }) // .wait(100) // .get(`[data-hook*=${BUTTON_PLUGIN_MODAL.DESIGN_TAB}]`) // .click({ force: true }) // .wait(100) // .get(`[data-hook*=${BUTTON_PLUGIN_MODAL.BUTTON_SAMPLE}] button`) // .click({ force: true }) // .wait(100) // .get(`[data-hook*=${BUTTON_PLUGIN_MODAL.DONE}]`) // .click({ force: true }); // cy.eyesCheckWindow(this.test.title); // }); it('create action button & click it', function() { const stub = cy.stub(); cy.on('window:alert', stub); cy.get(`[data-hook*=${PLUGIN_COMPONENT.BUTTON}]`) .last() .click() .then(() => { expect(stub.getCall(0)).to.be.calledWith('onClick event..'); }); cy.eyesCheckWindow(this.test.title); }); }); context('headings', () => { before(function() { eyesOpen(this); }); const testAppConfig = { ...usePlugins(plugins.headings), ...usePluginsConfig({ headings: { customHeadings: ['P', 'H2', 'H3'], }, }), }; function setHeader(number, selection) { cy.setTextStyle('headingsDropdownButton', selection) .get(`[data-hook=headingsDropdownPanel] > :nth-child(${number})`) .click() .wait(500); } function testHeaders(config) { cy.loadRicosEditorAndViewer('empty', config).enterParagraphs([ 'Leverage agile frameworks', 'to provide a robust synopsis for high level overviews.', ]); setHeader(3, [0, 24]); cy.eyesCheckWindow('change heading type'); setHeader(2, [28, 40]); cy.setTextStyle('headingsDropdownButton', [28, 40]); cy.eyesCheckWindow('change heading type'); } after(() => cy.eyesClose()); it('Change headers - with customHeadings config', () => { testHeaders(testAppConfig); }); it('Change headers - without customHeadings config', () => { testHeaders(usePlugins(plugins.headings)); }); }); context('Headers markdown', () => { before(function() { cy.eyesOpen({ appName: 'Headers markdown', testName: this.test.parent.title, browser: DEFAULT_DESKTOP_BROWSERS, }); }); beforeEach(() => cy.switchToDesktop()); after(() => cy.eyesClose()); it('Should render header-two', function() { cy.loadRicosEditorAndViewer() .type('{$h') .type('2}Header-two{$h') .type('}'); cy.eyesCheckWindow(this.test.title); }); }); context('Text/Highlight Color - mobile', () => { before(function() { cy.eyesOpen({ appName: 'Text/Highlight Color - mobile', testName: this.test.parent.title, browser: DEFAULT_MOBILE_BROWSERS, }); }); beforeEach(() => cy.switchToMobile()); after(() => cy.eyesClose()); it('allow to color text', function() { cy.loadRicosEditorAndViewer() .enterParagraphs(['Color.']) .setTextColor([0, 5], 'color4'); cy.eyesCheckWindow(this.test.title); }); it('allow to highlight text', function() { cy.loadRicosEditorAndViewer() .enterParagraphs(['Highlight.']) .setHighlightColor([0, 9], 'color4'); cy.eyesCheckWindow(this.test.title); }); }); context('anchor', () => { const testAppConfig = { ...usePlugins(plugins.all), ...usePluginsConfig({ link: { linkTypes: { anchor: true }, }, }), }; function selectAnchorAndSave() { cy.get(`[data-hook=test-blockKey`).click({ force: true }); cy.get(`[data-hook=${ACTION_BUTTONS.SAVE}]`).click(); } // before(function() { // eyesOpen(this); // }); // after(() => cy.eyesClose()); context('anchor desktop', () => { before(function() { cy.eyesOpen({ appName: 'anchor', testName: this.test.parent.title, browser: DEFAULT_DESKTOP_BROWSERS, }); }); beforeEach('load editor', () => { cy.switchToDesktop(); cy.loadRicosEditorAndViewer('plugins-for-anchors', testAppConfig); }); after(() => cy.eyesClose()); it('should create anchor in text', function() { cy.setEditorSelection(0, 6); cy.wait(500); cy.get(`[data-hook=inlineToolbar] [data-hook=${INLINE_TOOLBAR_BUTTONS.LINK}]`).click({ force: true, }); cy.get(`[data-hook=linkPanelContainer] [data-hook=anchor-radio]`).click(); cy.wait(1000); cy.eyesCheckWindow(this.test.title); selectAnchorAndSave(); }); it('should create anchor in image', function() { cy.openPluginToolbar(PLUGIN_COMPONENT.IMAGE); cy.clickToolbarButton(PLUGIN_TOOLBAR_BUTTONS.LINK); cy.get(`[data-hook=linkPanelContainer] [data-hook=anchor-radio]`).click(); cy.wait(1000); cy.eyesCheckWindow(this.test.title); selectAnchorAndSave(); }); }); context('anchor mobile', () => { before(function() { cy.eyesOpen({ appName: 'anchor', testName: this.test.parent.title, browser: DEFAULT_MOBILE_BROWSERS, }); }); beforeEach('load editor', () => { cy.switchToMobile(); cy.loadRicosEditorAndViewer('plugins-for-anchors', testAppConfig); }); after(() => cy.eyesClose()); it('should create anchor in text', function() { cy.setEditorSelection(0, 6); cy.get(`[data-hook=mobileToolbar] [data-hook=LinkButton]`).click({ force: true }); cy.get(`[data-hook=linkPanelContainerAnchorTab]`).click({ force: true }); cy.wait(1000); cy.eyesCheckWindow(this.test.title); selectAnchorAndSave(); }); it('should create anchor in image', function() { cy.openPluginToolbar(PLUGIN_COMPONENT.IMAGE); cy.clickToolbarButton(PLUGIN_TOOLBAR_BUTTONS.LINK); cy.get(`[data-hook=linkPanelContainerAnchorTab]`).click({ force: true }); cy.wait(1000); cy.eyesCheckWindow(this.test.title); selectAnchorAndSave(); }); }); }); context('collapsible list', () => { before(function() { eyesOpen(this); }); beforeEach('load editor', () => { cy.switchToDesktop(); }); after(() => cy.eyesClose()); const setCollapsibleListSetting = setting => { cy.clickToolbarButton(PLUGIN_TOOLBAR_BUTTONS.SETTINGS); cy.get(`[data-hook=${setting}]`).click(); cy.get(`[data-hook=${ACTION_BUTTONS.SAVE}]`).click(); }; it('should change collapsible list settings', function() { cy.loadRicosEditorAndViewer('collapsible-list-rich-text', { plugins: [plugins.collapsibleList, plugins.embedsPreset, plugins.textPlugins], }); cy.getCollapsibleList(); setCollapsibleListSetting(COLLAPSIBLE_LIST_SETTINGS.RTL_DIRECTION); cy.eyesCheckWindow(this.test.title); setCollapsibleListSetting(COLLAPSIBLE_LIST_SETTINGS.COLLAPSED); cy.eyesCheckWindow(this.test.title); setCollapsibleListSetting(COLLAPSIBLE_LIST_SETTINGS.EXPANDED); cy.eyesCheckWindow(this.test.title); }); it('should focus & type', function() { cy.loadRicosEditorAndViewer('empty-collapsible-list', usePlugins(plugins.collapsibleList)) .focusCollapsibleList(1) .type('Yes\n') .focusCollapsibleList(2); cy.eyesCheckWindow(this.test.title); }); it('should insert image in collapsible list', function() { cy.loadRicosEditorAndViewer('empty-collapsible-list', usePlugins(plugins.all)) .focusCollapsibleList(2) .type('Image in collapsible list'); cy.insertPluginFromSideToolbar('ImagePlugin_InsertButton'); cy.wait(1000); cy.eyesCheckWindow(this.test.title); }); it('should collapse first pair', function() { cy.loadRicosEditorAndViewer('empty-collapsible-list', usePlugins(plugins.collapsibleList)) .getCollapsibleList() .toggleCollapseExpand(0); cy.eyesCheckWindow(this.test.title); }); it('should have only one expanded pair', function() { cy.loadRicosEditorAndViewer( 'empty-collapsible-list', usePlugins(plugins.collapsibleList) ).getCollapsibleList(); setCollapsibleListSetting(COLLAPSIBLE_LIST_SETTINGS.ONE_PAIR_EXPANDED); cy.getCollapsibleList().toggleCollapseExpand(1); cy.eyesCheckWindow(this.test.title); }); it('should delete second pair', function() { cy.loadRicosEditorAndViewer('empty-collapsible-list', usePlugins(plugins.collapsibleList)); cy.focusCollapsibleList(3).type('{backspace}'); cy.eyesCheckWindow(this.test.title); }); }); });
the_stack
import { InProcessProvisioning, WebSocketLibjoynrProvisioning, UdsLibJoynrProvisioning } from "joynr/joynr/start/interface/Provisioning"; import { log, prettyLog } from "./logging"; import joynr from "joynr"; import LocalStorage from "joynr/global/LocalStorageNode"; import RadioProxy from "../generated/js/joynr/vehicle/RadioProxy"; // eslint-disable-next-line @typescript-eslint/no-var-requires const provisioning: InProcessProvisioning & WebSocketLibjoynrProvisioning & UdsLibJoynrProvisioning = require("./provisioning_common"); import OnChangeSubscriptionQos = require("joynr/joynr/proxy/OnChangeSubscriptionQos"); import RadioStation from "../generated/js/joynr/vehicle/RadioStation"; import Country from "../generated/js/joynr/vehicle/Country"; import showHelp from "./console_common"; import readline from "readline"; import InProcessRuntime = require("joynr/joynr/start/InProcessRuntime"); import WebSocketLibjoynrRuntime from "joynr/joynr/start/WebSocketLibjoynrRuntime"; import JoynrRuntimeException from "../../../../../javascript/libjoynr-js/src/main/js/joynr/exceptions/JoynrRuntimeException"; const persistencyLocation = "./radioLocalStorageConsumer"; const localStorage = new LocalStorage({ location: persistencyLocation, clearPersistency: false }); let subscriptionQosOnChange: OnChangeSubscriptionQos; type Subscribable<T> = { [K in keyof T]: T[K] extends { subscribe: Function } ? K : never }[keyof T]; let isRuntimeOkay = true; const rl = readline.createInterface(process.stdin, process.stdout); function runDemo(radioProxy: RadioProxy): Promise<void> { prettyLog("ATTRIBUTE GET: currentStation..."); return radioProxy.currentStation .get() .catch((error: any) => { prettyLog(`ATTRIBUTE GET: currentStation failed: ${error}`); }) .then((value: any) => { prettyLog(`ATTRIBUTE GET: currentStation returned: ${JSON.stringify(value)}`); prettyLog("RPC: radioProxy.addFavoriteStation(radioStation)..."); return radioProxy.addFavoriteStation({ newFavoriteStation: new RadioStation({ name: "runDemoFavoriteStation", trafficService: true, country: Country.GERMANY }) }); }) .catch((error: any) => { prettyLog(`RPC: radioProxy.addFavoriteStation(radioStation) failed: ${JSON.stringify(error)}`); }) .then(() => { prettyLog("RPC: radioProxy.addFavoriteStation(radioStation) returned"); prettyLog("radioProxy.shuffleStations()..."); return radioProxy.shuffleStations(); }) .catch((error: any) => { prettyLog(`RPC: radioProxy.shuffleStations() failed: ${JSON.stringify(error)}`); }) .then(() => { prettyLog("RPC: radioProxy.shuffleStations() returned"); prettyLog("ATTRIBUTE GET: currentStation after shuffle..."); return radioProxy.currentStation.get(); }) .catch(error => { prettyLog(`ATTRIBUTE GET: currentStation failed: ${JSON.stringify(error)}`); }) .then(value => { prettyLog(`ATTRIBUTE GET: currentStation returned: ${JSON.stringify(value)}`); }); } function runInteractiveConsole(radioProxy: RadioProxy): Promise<void> { let currentStationSubscriptionId = localStorage.getItem("currentStationSubscriptionId"); let multicastSubscriptionId = localStorage.getItem("multicastSubscriptionId"); let multicastPSubscriptionId = localStorage.getItem("multicastPSubscriptionId"); let res: Function; // eslint-disable-next-line promise/avoid-new const promise = new Promise<void>(resolve => { res = resolve; }); rl.setPrompt(">> "); const MODES = { HELP: { value: "h", description: "help", options: {} }, QUIT: { value: "q", description: "quit", options: {} }, SHUFFLE_STATIONS: { value: "s", description: "shuffle stations", options: {} }, ADD_FAVORITE_STATION: { value: "a", description: "add a Favorite Station", options: { NAME: "name" } }, SUBSCRIBE: { value: "subscribe", description: "subscribe to current station", options: {} }, MULTICAST: { value: "subscribeMulticast", description: "subscribe to weak signal multicast", options: {} }, MULTICASTP: { value: "subscribeMulticastP", description: 'subscribe to weak signal multicast with partition "GERMANY"', options: {} }, UNSUBSCRIBE: { value: "unsubscribe", description: "unsubscribe from all subscriptions", options: {} }, GET_CURRENT_STATION: { value: "c", description: "get current station", options: {} } }; function subscribeHelper(settings: { subscribeToName: Subscribable<RadioProxy>; partitions?: string[]; subscriptionId: string; }): Promise<string> { const partitionsString = settings.partitions ? JSON.stringify(settings.partitions) : ""; const parameters = { subscriptionQos: subscriptionQosOnChange, onReceive: (value: any) => { prettyLog( `radioProxy.${settings.subscribeToName}${partitionsString}.subscribe.onReceive: ${JSON.stringify( value )}` ); }, onError: (error: any) => { prettyLog(`radioProxy.${settings.subscribeToName}${partitionsString}.subscribe.onError: ${error}`); }, partitions: settings.partitions, subscriptionId: settings.subscriptionId }; return radioProxy[settings.subscribeToName] .subscribe(parameters) .then((subscriptionId: string) => { prettyLog( `radioProxy.${settings.subscribeToName}${partitionsString}.subscribe.done. ` + `Subscription ID: ${subscriptionId}` ); return subscriptionId; }) .catch((error: any) => { prettyLog( `radioProxy.${settings.subscribeToName}${partitionsString}.subscribe.failed: ${JSON.stringify( error )}` ); throw error; }); } function unsubscribeHelper(settings: { subscribeToName: Subscribable<RadioProxy>; partitions?: string[]; subscriptionId: string; }): Promise<void> { const partitionsString = settings.partitions ? JSON.stringify(settings.partitions) : ""; return radioProxy[settings.subscribeToName] .unsubscribe({ subscriptionId: settings.subscriptionId }) .then(() => { prettyLog( `radioProxy.${settings.subscribeToName}${partitionsString}.unsubscribe.done. ` + `Subscription ID: ${settings.subscriptionId}` ); }) .catch((error: any) => { prettyLog( `radioProxy.${settings.subscribeToName}${partitionsString}.unsubscribe.fail. ` + `Subscription ID: ${settings.subscriptionId} ERROR: ${error}` ); }); } // Run until the user hits q or a fatal runtime error happens (onFatalRuntimeError is called) rl.on("line", line => { const input = line.trim().split(" "); switch (input[0]) { case MODES.HELP.value: showHelp(MODES); break; case MODES.QUIT.value: rl.close(); break; case MODES.ADD_FAVORITE_STATION.value: // eslint-disable-next-line no-case-declarations const newFavoriteStation = new RadioStation({ name: input[1] || "", trafficService: true, country: Country.GERMANY }); radioProxy .addFavoriteStation({ newFavoriteStation }) .then((returnValue: any) => { prettyLog( `RPC: radioProxy.addFavoriteStation(${JSON.stringify( newFavoriteStation )}) returned: ${JSON.stringify(returnValue)}` ); }) .catch((error: any) => { prettyLog( `RPC: radioProxy.addFavoriteStation(${JSON.stringify(newFavoriteStation)}) failed: ${error}` ); }); break; case MODES.SHUFFLE_STATIONS.value: radioProxy .shuffleStations() .then(() => { prettyLog("RPC: radioProxy.shuffleStations returned. "); }) .catch((error: any) => { prettyLog(`RPC: radioProxy.shuffleStations failed: ${JSON.stringify(error)}`); }); break; case MODES.SUBSCRIBE.value: subscribeHelper({ subscribeToName: "currentStation", subscriptionId: currentStationSubscriptionId }) .then((suscriptionId: string) => { currentStationSubscriptionId = suscriptionId; localStorage.setItem("currentStationSubscriptionId", suscriptionId); }) .catch((error: any) => prettyLog(error)); break; case MODES.MULTICAST.value: subscribeHelper({ subscribeToName: "weakSignal", subscriptionId: multicastSubscriptionId }) .then((suscriptionId: string) => { multicastSubscriptionId = suscriptionId; localStorage.setItem("multicastSubscriptionId", suscriptionId); }) .catch((error: any) => prettyLog(error)); break; case MODES.MULTICASTP.value: subscribeHelper({ subscribeToName: "weakSignal", partitions: ["GERMANY"], subscriptionId: multicastPSubscriptionId }) .then((suscriptionId: string) => { multicastPSubscriptionId = suscriptionId; localStorage.setItem("multicastPSubscriptionId", suscriptionId); }) .catch((error: any) => prettyLog(error)); break; case MODES.UNSUBSCRIBE.value: if (currentStationSubscriptionId !== undefined && currentStationSubscriptionId !== null) { unsubscribeHelper({ subscribeToName: "currentStation", subscriptionId: currentStationSubscriptionId }) .then(() => { localStorage.removeItem(currentStationSubscriptionId); currentStationSubscriptionId = undefined; }) .catch((error: any) => prettyLog(error)); } if (multicastSubscriptionId !== undefined && multicastSubscriptionId !== null) { unsubscribeHelper({ subscribeToName: "weakSignal", subscriptionId: multicastSubscriptionId }) .then(() => { localStorage.removeItem(multicastSubscriptionId); multicastSubscriptionId = undefined; }) .catch((error: any) => prettyLog(error)); } if (multicastPSubscriptionId !== undefined && multicastPSubscriptionId !== null) { unsubscribeHelper({ subscribeToName: "weakSignal", partitions: ["GERMANY"], subscriptionId: multicastPSubscriptionId }) .then(() => { localStorage.removeItem(multicastPSubscriptionId); multicastPSubscriptionId = undefined; }) .catch((error: any) => prettyLog(error)); } break; case MODES.GET_CURRENT_STATION.value: radioProxy.currentStation .get() .then(currentStation => { prettyLog(`RPC: radioProxy.getCurrentStation returned: ${JSON.stringify(currentStation)}`); }) .catch(error => { prettyLog(`RPC: radioProxy.getCurrentStation failed: ${error}`); }); break; case "": break; default: log(`unknown input: ${input}`); break; } rl.prompt(); }); rl.on("close", () => { res(); }); showHelp(MODES); rl.prompt(); return promise; } (async () => { if (process.env.domain === undefined) { log("please pass a domain as argument"); process.exit(1); } if (process.env.runtime === undefined) { log("please pass a runtime as argument"); process.exit(1); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const domain = process.env.domain!; log(`domain: ${domain}`); provisioning.persistency = { location: persistencyLocation }; if (process.env.runtime === "inprocess") { if (process.env.brokerUri === undefined || process.env.bounceProxyBaseUrl === undefined) { log("please pass brokerUri and bounceProxyBaseUrl as argument"); return process.exit(1); } provisioning.brokerUri = process.env.brokerUri; provisioning.bounceProxyBaseUrl = process.env.bounceProxyBaseUrl; provisioning.bounceProxyUrl = `${process.env.bounceProxyBaseUrl}/bounceproxy/`; joynr.selectRuntime(InProcessRuntime); } else if (process.env.runtime === "websocket") { if (process.env.wshost === undefined || process.env.wsport === undefined) { log("please pass wshost and wsport as argument"); return process.exit(1); } provisioning.ccAddress.host = process.env.wshost; provisioning.ccAddress.port = Number(process.env.wsport); joynr.selectRuntime(WebSocketLibjoynrRuntime); } else if (process.env.runtime === "uds") { if (!process.env.udspath || !process.env.udsclientid || !process.env.udsconnectsleeptimems) { log("please pass udspath, udsclientid, udsconnectsleeptimems as argument"); return process.exit(1); } provisioning.uds = { socketPath: process.env.udspath, clientId: process.env.udsclientid, connectSleepTimeMs: Number(process.env.udsconnectsleeptimems) }; // no selectRuntime: UdsLibJoynrRuntime is default } await localStorage.init(); // onFatalRuntimeError callback is optional, it is highly recommended to provide an implementation. const onFatalRuntimeError = (error: JoynrRuntimeException) => { isRuntimeOkay = false; log(`Unexpected joynr runtime error occurred: ${error}`); rl.close(); }; await joynr.load(provisioning, onFatalRuntimeError); log("joynr started"); const messagingQos = new joynr.messaging.MessagingQos({ ttl: 60000 }); subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({ minIntervalMs: 50 }); const radioProxy = await joynr.proxyBuilder.build(RadioProxy, { domain, messagingQos }); log("radio proxy build"); await runDemo(radioProxy); await runInteractiveConsole(radioProxy); log("exiting..."); await joynr.shutdown(); log("shutdown completed..."); process.exit(isRuntimeOkay ? 0 : 1); })().catch(e => { log(`error running radioProxy: ${e}`); joynr.shutdown(); });
the_stack
import { query as q } from 'faunadb'; import { FactoryContext } from '~/types/factory/factory.context'; import { FactoryUsersApi } from '~/types/factory/factory.users'; import { BiotaIndexName } from '~/factory/constructors'; import { BiotaCollectionName } from '~/factory/constructors/collection'; import { ThrowError } from '~/factory/constructors/error'; import { MethodDispatch, Query } from '~/factory/constructors/method'; import { ResultData } from '~/factory/constructors/result'; import { BiotaFunctionName } from '~/factory/constructors/udfunction'; import { user } from './user'; import { Pagination } from '../constructors/pagination'; // tslint:disable-next-line: only-arrow-functions export const users: FactoryContext<FactoryUsersApi> = function (context): FactoryUsersApi { return { getByAuthAccount(providerOrAccount, id) { const account = q.If(q.IsObject(providerOrAccount), providerOrAccount, { provider: providerOrAccount, id }); const provider = q.Select('provider', account, null); const accountId = q.Select('id', account, null); const inputs = { account, provider, accountId }; // --- const query = Query( { user: q.Select(0, q.Match(q.Index(BiotaIndexName('users__by__auth_account')), [q.Var('provider'), q.Var('accountId')]), null), userIsValid: q.If( q.IsDoc(q.Var('user')), true, ThrowError(q.Var('ctx'), "Could'nt find the user", { account: q.Var('account') }), ), }, q.Var('user'), ); // --- const offline = 'factory.users.getByAuthAccount'; const online = { name: BiotaFunctionName('UsersGetByAuthAccount'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, getByAuthEmail(email) { const inputs = { email }; // --- const query = Query( { user: q.Select(0, q.Match(q.Index(BiotaIndexName('users__by__auth_email')), q.Var('email')), null), userIsValid: q.If(q.IsDoc(q.Var('user')), true, ThrowError(q.Var('ctx'), "Could'nt find the user", { email: q.Var('email') })), }, q.Var('user'), ); // --- const offline = 'factory.users.getByAuthEmail'; const online = { name: BiotaFunctionName('UsersGetByAuthEmail'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, findAll(pagination) { const inputs = { pagination }; // --- const query = Query( { docs: q.Map( q.Paginate(q.Documents(q.Collection(BiotaCollectionName('users'))), Pagination(q.Var('pagination'))), q.Lambda('x', q.Get(q.Var('x'))), ), }, q.Var('docs'), ); // --- const offline = 'factory.users.paginate'; const online = { name: BiotaFunctionName('UsersFindAll'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, getMany(nameList) { const inputs = { nameList }; // --- const query = Query( { docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(user(q.Var('ctx'))(q.Var('name')).get()))), }, q.Var('docs'), ); // --- const offline = 'factory.users.getMany'; const online = { name: BiotaFunctionName('UsersGetMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, insertMany(optionsList) { const inputs = { optionsList }; // --- const query = Query( { docs: q.Map( q.Var('optionsList'), q.Lambda(['options'], ResultData(user(q.Var('ctx'))(q.Select('name', q.Var('options'), null)).insert(q.Var('options')))), ), }, q.Var('docs'), ); // --- const offline = 'factory.users.insertMany'; const online = { name: BiotaFunctionName('UsersInsertMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, updateMany(optionsList) { const inputs = { optionsList }; // --- const query = Query( { docs: q.Map( q.Var('optionsList'), q.Lambda(['options'], ResultData(user(q.Var('ctx'))(q.Select('name', q.Var('options'), null)).update(q.Var('options')))), ), }, q.Var('docs'), ); // --- const offline = 'factory.users.updateMany'; const online = { name: BiotaFunctionName('UsersUpdateMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, upsertMany(optionsList) { const inputs = { optionsList }; // --- const query = Query( { docs: q.Map( q.Var('optionsList'), q.Lambda(['options'], ResultData(user(q.Var('ctx'))(q.Select('name', q.Var('options'), null)).upsert(q.Var('options')))), ), }, q.Var('docs'), ); // --- const offline = 'factory.users.upsertMany'; const online = { name: BiotaFunctionName('UsersUpsertMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, replaceMany(optionsList) { const inputs = { optionsList }; // --- const query = Query( { docs: q.Map( q.Var('optionsList'), q.Lambda(['options'], ResultData(user(q.Var('ctx'))(q.Select('name', q.Var('options'), null)).replace(q.Var('options')))), ), }, q.Var('docs'), ); // --- const offline = 'factory.users.replaceMany'; const online = { name: BiotaFunctionName('UsersReplaceMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, repsertMany(optionsList) { const inputs = { optionsList }; // --- const query = Query( { docs: q.Map( q.Var('optionsList'), q.Lambda(['options'], ResultData(user(q.Var('ctx'))(q.Select('name', q.Var('options'), null)).repsert(q.Var('options')))), ), }, q.Var('docs'), ); // --- const offline = 'factory.users.repsertMany'; const online = { name: BiotaFunctionName('UsersRepsertMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, deleteMany(nameList) { const inputs = { nameList }; // --- const query = Query( { docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(user(q.Var('ctx'))(q.Var('name')).delete()))), }, q.Var('docs'), ); // --- const offline = 'factory.users.deleteMany'; const online = { name: BiotaFunctionName('UsersDeleteMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, restoreMany(nameList) { const inputs = { nameList }; // --- const query = Query( { docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(user(q.Var('ctx'))(q.Var('name')).restore()))), }, q.Var('docs'), ); // --- const offline = 'factory.users.restoreMany'; const online = { name: BiotaFunctionName('UsersRestoreMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, forgetMany(nameList) { const inputs = { nameList }; // --- const query = Query( { docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(user(q.Var('ctx'))(q.Var('name')).forget()))), }, q.Var('docs'), ); // --- const offline = 'factory.users.forgetMany'; const online = { name: BiotaFunctionName('UsersForgetMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, dropMany(nameList) { const inputs = { nameList }; // --- const query = Query( { docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(user(q.Var('ctx'))(q.Var('name')).drop()))), }, q.Var('docs'), ); // --- const offline = 'factory.users.dropMany'; const online = { name: BiotaFunctionName('UsersDropMany'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, expireManyAt(nameList, at) { const inputs = { nameList, at }; // --- const query = Query( { docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(user(q.Var('ctx'))(q.Var('name')).expireAt(q.Var('at'))))), }, q.Var('docs'), ); // --- const offline = 'factory.users.expireManyAt'; const online = { name: BiotaFunctionName('UsersExpireManyAt'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, expireManyIn(nameList, delay) { const inputs = { nameList, delay }; // --- const query = Query( { docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(user(q.Var('ctx'))(q.Var('name')).expireIn(q.Var('delay'))))), }, q.Var('docs'), ); // --- const offline = 'factory.users.expireManyAt'; const online = { name: BiotaFunctionName('UsersExpireManyAt'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, expireManyNow(nameList) { const inputs = { nameList }; // --- const query = Query( { docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(user(q.Var('ctx'))(q.Var('name')).expireNow()))), }, q.Var('docs'), ); // --- const offline = 'factory.users.expireManyNow'; const online = { name: BiotaFunctionName('UsersExpireManyNow'), role: null }; return MethodDispatch({ context, inputs, query })(offline, online); }, }; };
the_stack
import * as cp from 'child_process'; import * as fs from 'fs'; import * as minimatch from 'minimatch'; import * as path from 'path'; import * as tslint from 'tslint'; // this is a dev dependency only import * as typescript from 'typescript'; // this is a dev dependency only import * as util from 'util'; import * as server from 'vscode-languageserver'; import { MruCache } from './mruCache'; export interface RunConfiguration { readonly jsEnable?: boolean; readonly rulesDirectory?: string | string[]; readonly configFile?: string; readonly ignoreDefinitionFiles?: boolean; readonly exclude?: string | string[]; readonly validateWithDefaultConfig?: boolean; readonly nodePath?: string; readonly packageManager?: 'npm' | 'yarn'; readonly traceLevel?: 'verbose' | 'normal'; readonly workspaceFolderPath?: string; } interface Configuration { readonly linterConfiguration: tslint.Configuration.IConfigurationFile | undefined; isDefaultLinterConfig: boolean; readonly path?: string; } class ConfigCache { public configuration: Configuration | undefined; private filePath: string | undefined; constructor() { this.filePath = undefined; this.configuration = undefined; } public set(filePath: string, configuration: Configuration) { this.filePath = filePath; this.configuration = configuration; } public get(forPath: string): Configuration | undefined { return forPath === this.filePath ? this.configuration : undefined; } public isDefaultLinterConfig(): boolean { return !!(this.configuration && this.configuration.isDefaultLinterConfig); } public flush() { this.filePath = undefined; this.configuration = undefined; } } export interface RunResult { readonly lintResult: tslint.LintResult; readonly warnings: string[]; readonly workspaceFolderPath?: string; readonly configFilePath?: string; } const emptyLintResult: tslint.LintResult = { errorCount: 0, warningCount: 0, failures: [], fixes: [], format: '', output: '', }; const emptyResult: RunResult = { lintResult: emptyLintResult, warnings: [], }; export class TsLintRunner { private readonly tslintPath2Library = new Map<string, typeof tslint | undefined>(); private readonly document2LibraryCache = new MruCache<() => typeof tslint | undefined>(100); // map stores undefined values to represent failed resolutions private readonly globalPackageManagerPath = new Map<string, string>(); private readonly configCache = new ConfigCache(); constructor( private trace: (data: string) => void, ) { } public runTsLint( filePath: string, contents: string | typescript.Program, configuration: RunConfiguration, ): RunResult { this.trace('start validateTextDocument'); this.trace('validateTextDocument: about to load tslint library'); const warnings: string[] = []; if (!this.document2LibraryCache.has(filePath)) { this.loadLibrary(filePath, configuration, warnings); } this.trace('validateTextDocument: loaded tslint library'); if (!this.document2LibraryCache.has(filePath)) { return emptyResult; } const library = this.document2LibraryCache.get(filePath)!(); if (!library) { return { lintResult: emptyLintResult, warnings: [ getInstallFailureMessage( filePath, configuration.workspaceFolderPath, configuration.packageManager || 'npm'), ], }; } this.trace('About to validate ' + filePath); return this.doRun(filePath, contents, library, configuration, warnings); } /** * Filter failures for the given document */ public filterProblemsForFile( filePath: string, failures: tslint.RuleFailure[], ): tslint.RuleFailure[] { const normalizedPath = path.normalize(filePath); // we only show diagnostics targetting this open document, some tslint rule return diagnostics for other documents/files const normalizedFiles = new Map<string, string>(); return failures.filter((each) => { const fileName = each.getFileName(); if (!normalizedFiles.has(fileName)) { normalizedFiles.set(fileName, path.normalize(fileName)); } return normalizedFiles.get(fileName) === normalizedPath; }); } public onConfigFileChange(_tsLintFilePath: string) { this.configCache.flush(); } public getNonOverlappingReplacements(failures: tslint.RuleFailure[]): tslint.Replacement[] { function overlaps(a: tslint.Replacement, b: tslint.Replacement): boolean { return a.end >= b.start; } let sortedFailures = this.sortFailures(failures); let nonOverlapping: tslint.Replacement[] = []; for (let i = 0; i < sortedFailures.length; i++) { let replacements = this.getReplacements(sortedFailures[i].getFix()); if (i === 0 || !overlaps(nonOverlapping[nonOverlapping.length - 1], replacements[0])) { nonOverlapping.push(...replacements); } } return nonOverlapping; } private getReplacements(fix: tslint.Fix | undefined): tslint.Replacement[] { let replacements: tslint.Replacement[] | null = null; // in tslint4 a Fix has a replacement property with the Replacements if ((<any>fix).replacements) { // tslint4 replacements = (<any>fix).replacements; } else { // in tslint 5 a Fix is a Replacement | Replacement[] if (!Array.isArray(fix)) { replacements = [<any>fix]; } else { replacements = fix; } } return replacements || []; } private getReplacement(failure: tslint.RuleFailure, at: number): tslint.Replacement { return this.getReplacements(failure.getFix())[at]; } private sortFailures(failures: tslint.RuleFailure[]): tslint.RuleFailure[] { // The failures.replacements are sorted by position, we sort on the position of the first replacement return failures.sort((a, b) => { return this.getReplacement(a, 0).start - this.getReplacement(b, 0).start; }); } private loadLibrary(filePath: string, configuration: RunConfiguration, warningsOutput: string[]): void { this.trace(`loadLibrary for ${filePath}`); const getGlobalPath = () => this.getGlobalPackageManagerPath(configuration.packageManager); const directory = path.dirname(filePath); let np: string | undefined = undefined; if (configuration && configuration.nodePath) { const exists = fs.existsSync(configuration.nodePath); if (exists) { np = configuration.nodePath; } else { warningsOutput.push(`The setting 'tslint.nodePath' refers to '${configuration.nodePath}', but this path does not exist. The setting will be ignored.`); } } let tsLintPath: string; if (np) { try { tsLintPath = this.resolveTsLint(np, np!); if (tsLintPath.length === 0) { tsLintPath = this.resolveTsLint(getGlobalPath(), directory); } } catch { tsLintPath = this.resolveTsLint(getGlobalPath(), directory); } } else { try { tsLintPath = this.resolveTsLint(undefined, directory); if (tsLintPath.length === 0) { tsLintPath = this.resolveTsLint(getGlobalPath(), directory); } } catch { tsLintPath = this.resolveTsLint(getGlobalPath(), directory); } } this.document2LibraryCache.set(filePath, () => { let library; if (!this.tslintPath2Library.has(tsLintPath)) { try { library = require(tsLintPath); } catch (e) { this.tslintPath2Library.set(tsLintPath, undefined); return; } this.tslintPath2Library.set(tsLintPath, library); } return this.tslintPath2Library.get(tsLintPath); }); } private getGlobalPackageManagerPath(packageManager: string | undefined): string | undefined { this.trace(`Begin - Resolve Global Package Manager Path for: ${packageManager}`); if (!packageManager) { packageManager = 'npm'; } if (!this.globalPackageManagerPath.has(packageManager)) { let path: string | undefined; if (packageManager === 'npm') { path = server.Files.resolveGlobalNodePath(this.trace); } else if (packageManager === 'yarn') { path = server.Files.resolveGlobalYarnPath(this.trace); } this.globalPackageManagerPath.set(packageManager, path!); } this.trace(`Done - Resolve Global Package Manager Path for: ${packageManager}`); return this.globalPackageManagerPath.get(packageManager); } private doRun( filePath: string, contents: string | typescript.Program, library: typeof import('tslint'), configuration: RunConfiguration, warnings: string[], ): RunResult { this.trace('start doValidate ' + filePath); const uri = filePath; if (this.fileIsExcluded(configuration, filePath)) { this.trace(`No linting: file ${filePath} is excluded`); return emptyResult; } if (configuration.workspaceFolderPath) { this.trace(`Changed directory to ${configuration.workspaceFolderPath}`); process.chdir(configuration.workspaceFolderPath); } const configFile = configuration.configFile || null; let linterConfiguration: Configuration | undefined; this.trace('validateTextDocument: about to getConfiguration'); try { linterConfiguration = this.getConfiguration(uri, filePath, library, configFile); } catch (err) { this.trace(`No linting: exception when getting tslint configuration for ${filePath}, configFile= ${configFile}`); warnings.push(getConfigurationFailureMessage(err)); return { lintResult: emptyLintResult, warnings, }; } if (!linterConfiguration) { this.trace(`No linting: no tslint configuration`); return emptyResult; } this.trace('validateTextDocument: configuration fetched'); if (isJsDocument(filePath) && !configuration.jsEnable) { this.trace(`No linting: a JS document, but js linting is disabled`); return emptyResult; } if (configuration.validateWithDefaultConfig === false && this.configCache.configuration!.isDefaultLinterConfig) { this.trace(`No linting: linting with default tslint configuration is disabled`); return emptyResult; } if (isExcludedFromLinterOptions(linterConfiguration.linterConfiguration, filePath)) { this.trace(`No linting: file is excluded using linterOptions.exclude`); return emptyResult; } let result: tslint.LintResult; const options: tslint.ILinterOptions = { formatter: "json", fix: false, rulesDirectory: configuration.rulesDirectory || undefined, formattersDirectory: undefined, }; if (configuration.traceLevel && configuration.traceLevel === 'verbose') { this.traceConfigurationFile(linterConfiguration.linterConfiguration); } // tslint writes warnings using console.warn, capture these warnings and send them to the client const originalConsoleWarn = console.warn; const captureWarnings = (message?: any) => { warnings.push(message); originalConsoleWarn(message); }; console.warn = captureWarnings; try { // clean up if tslint crashes const tslint = new library.Linter(options, typeof contents === 'string' ? undefined : contents); this.trace(`Linting: start linting`); tslint.lint(filePath, typeof contents === 'string' ? contents : '', linterConfiguration.linterConfiguration); result = tslint.getResult(); this.trace(`Linting: ended linting`); } finally { console.warn = originalConsoleWarn; } return { lintResult: result, warnings, workspaceFolderPath: configuration.workspaceFolderPath, configFilePath: linterConfiguration.path, }; } private getConfiguration(uri: string, filePath: string, library: typeof tslint, configFileName: string | null): Configuration | undefined { this.trace('getConfiguration for' + uri); const config = this.configCache.get(filePath); if (config) { return config; } let isDefaultConfig = false; let linterConfiguration: tslint.Configuration.IConfigurationFile | undefined = undefined; const linter = library.Linter; if (linter.findConfigurationPath) { isDefaultConfig = linter.findConfigurationPath(configFileName, filePath) === undefined; } const configurationResult = linter.findConfiguration(configFileName, filePath); // between tslint 4.0.1 and tslint 4.0.2 the attribute 'error' has been removed from IConfigurationLoadResult // in 4.0.2 findConfiguration throws an exception as in version ^3.0.0 if ((configurationResult as any).error) { throw (configurationResult as any).error; } linterConfiguration = configurationResult.results; // In tslint version 5 the 'no-unused-variable' rules breaks the TypeScript language service plugin. // See https://github.com/Microsoft/TypeScript/issues/15344 // Therefore we remove the rule from the configuration. // // In tslint 5 the rules are stored in a Map, in earlier versions they were stored in an Object if (linterConfiguration) { if (linterConfiguration.rules && linterConfiguration.rules instanceof Map) { linterConfiguration.rules.delete('no-unused-variable'); } if (linterConfiguration.jsRules && linterConfiguration.jsRules instanceof Map) { linterConfiguration.jsRules.delete('no-unused-variable'); } } const configuration: Configuration = { isDefaultLinterConfig: isDefaultConfig, linterConfiguration, path: configurationResult.path }; this.configCache.set(filePath, configuration); return this.configCache.configuration; } private fileIsExcluded(settings: RunConfiguration, filePath: string): boolean { if (settings.ignoreDefinitionFiles) { if (filePath.endsWith('.d.ts')) { return true; } } if (settings.exclude) { if (Array.isArray(settings.exclude)) { for (const pattern of settings.exclude) { if (testForExclusionPattern(filePath, pattern)) { return true; } } } else if (testForExclusionPattern(filePath, settings.exclude)) { return true; } } return false; } private traceConfigurationFile(configuration: tslint.Configuration.IConfigurationFile | undefined) { if (!configuration) { this.trace("no tslint configuration"); return; } this.trace("tslint configuration:" + util.inspect(configuration, undefined, 4)); } private resolveTsLint(nodePath: string | undefined, cwd: string): string { const nodePathKey = 'NODE_PATH'; const app = [ "console.log(require.resolve('tslint'));", ].join(''); const env = process.env; const newEnv = Object.create(null); Object.keys(env).forEach(key => newEnv[key] = env[key]); if (nodePath) { if (newEnv[nodePathKey]) { newEnv[nodePathKey] = nodePath + path.delimiter + newEnv[nodePathKey]; } else { newEnv[nodePathKey] = nodePath; } this.trace(`NODE_PATH value is: ${newEnv[nodePathKey]}`); } newEnv.ELECTRON_RUN_AS_NODE = '1'; const spanwResults = cp.spawnSync(process.argv0, ['-e', app], { cwd, env: newEnv }); return spanwResults.stdout.toString().trim(); } } function testForExclusionPattern(filePath: string, pattern: string): boolean { return minimatch(filePath, pattern, { dot: true }); } function getInstallFailureMessage(filePath: string, workspaceFolder: string | undefined, packageManager: 'npm' | 'yarn'): string { const localCommands = { npm: 'npm install tslint', yarn: 'yarn add tslint', }; const globalCommands = { npm: 'npm install -g tslint', yarn: 'yarn global add tslint', }; if (workspaceFolder) { // workspace opened on a folder return [ '', `Failed to load the TSLint library for the document ${filePath}`, '', `To use TSLint in this workspace please install tslint using \'${localCommands[packageManager]}\' or globally using \'${globalCommands[packageManager]}\'.`, 'TSLint has a peer dependency on `typescript`, make sure that `typescript` is installed as well.', 'You need to reopen the workspace after installing tslint.', ].join('\n'); } else { return [ `Failed to load the TSLint library for the document ${filePath}`, `To use TSLint for single file install tslint globally using \'${globalCommands[packageManager]}\'.`, 'TSLint has a peer dependency on `typescript`, make sure that `typescript` is installed as well.', 'You need to reopen VS Code after installing tslint.', ].join('\n'); } } function isJsDocument(filePath: string) { return filePath.match(/\.jsx?$/i); } function isExcludedFromLinterOptions( config: tslint.Configuration.IConfigurationFile | undefined, fileName: string, ): boolean { if (config === undefined || config.linterOptions === undefined || config.linterOptions.exclude === undefined) { return false; } return config.linterOptions.exclude.some((pattern) => testForExclusionPattern(fileName, pattern)); } function getConfigurationFailureMessage(err: any): string { let errorMessage = `unknown error`; if (typeof err.message === 'string' || err.message instanceof String) { errorMessage = err.message; } return `vscode-tslint: Cannot read tslint configuration - '${errorMessage}'`; }
the_stack
import * as utils from './utils' import { v5 as uuidv5 } from 'uuid' // For version 5 import { Template } from './arm-parser-types' export default class ARMExpressionParser { public template: Template // We store the template to save use passing it millions of times constructor(t: Template) { this.template = t } // // Main ARM expression parser, attempts to evaluate and resolve ARM expressions // Most of the time it will evaluate down to a string, but a number can be returned also // public eval(exp: string, check = false): any { // Precheck called on top level calls to _evalExpression if (check) { const matchExp = exp.match(/^\[(.*)\]$/) if (matchExp) { exp = matchExp[1] } else { return exp } } // Catch some rare errors where non-strings are parsed if (typeof exp !== 'string') { return exp } exp = exp.trim() // It looks like a function call with a property reference e.g foo().bar or foo()['bar'] let match = exp.match(/(\w+)\((.*)\)((?:\.|\[).*)/) let funcProps if (match) { const funcName = match[1] const funcParams = match[2] funcProps = match[3] // Catch some special cases, with referenced properties, e.g. resourceGroup().location if (funcName === 'resourceGroup' && funcProps === '.id') { return '{res-group-id}' } if (funcName === 'resourceGroup' && funcProps === '.location') { return '{res-group-location}' } if (funcName === 'subscription' && funcProps === '.subscriptionid') { return '{subscription-id}' } if (funcName === 'deployment' && funcProps === '.name') { return '{deployment-name}' } if (funcName === 'variables') { return this.funcVarParam(this.template.variables, this.eval(funcParams), funcProps) } if (funcName === 'parameters') { return this.funcVarParam(this.template.parameters, this.eval(funcParams), funcProps) } } // It looks like a 'plain' function call without . something after it // For historic reasons we treat these separate and I don't want to mess with it, as it works match = exp.match(/(\w+)\((.*)\)/) if (match) { const funcName = match[1].toLowerCase() const funcParams = match[2] if (funcName === 'variables') { return this.funcVarParam(this.template.variables, this.eval(funcParams), '') } if (funcName === 'parameters') { return this.funcVarParam(this.template.parameters, this.eval(funcParams), '') } if (funcName === 'uniquestring') { return this.funcUniqueString(this.eval(funcParams)) } if (funcName === 'concat') { return this.funcConcat(funcParams, '') } if (funcName === 'uri') { return this.funcUri(funcParams) } if (funcName === 'replace') { return this.funcReplace(funcParams) } if (funcName === 'take') { return this.funcTake(funcParams) } if (funcName === 'tolower') { return this.funcToLower(funcParams) } if (funcName === 'toupper') { return this.funcToUpper(funcParams) } if (funcName === 'substring') { return this.funcSubstring(funcParams) } if (funcName === 'resourceid') { // Treat resourceId as a concat operation with slashes let resid = this.funcConcat(funcParams, '/') // clean up needed resid = resid.replace(/^\//, '') resid = resid.replace(/\/\//, '/') return resid } if (funcName === 'copyindex') { return 0 } if (funcName === 'guid') { return uuidv5(this.funcConcat(funcParams, ''), '36c56b01-f9c9-4c7d-9786-0372733417ea') } } // It looks like a string literal in single quotes match = exp.match(/^'(.*)'$/) if (match) { return match[1] } // It looks like a number literal match = exp.match(/^(\d+)/) if (match) { return match[1].toString() } // Catch all, just return the expression, unparsed return exp } // // Emulate the ARM function `variables()` and `parameters()` to reference template variables/parameters // The only difference is the source // private funcVarParam(source: any, varName: string, propAccessor: string): string { // propAccessor is the . or [] part of the object accessor // the [] notation requires some pre-processing for expressions e.g. foo[variable('bar')] if (propAccessor && propAccessor.charAt(0) === '[' && !(propAccessor.charAt(1) >= '0' && propAccessor.charAt(1) <= '9') && !(propAccessor.charAt(1) === '\'')) { // Evaluate propAccessor in case it includes an expression let propAccessorResolved = this.eval(propAccessor, false) // If we get a string back it need's quoting, e.g. foo['baz'] if (typeof propAccessorResolved === 'string') { propAccessorResolved = `'${propAccessorResolved}'` } // Otherwise it's hopefully a number propAccessor = `[${propAccessorResolved}]` } if (!source) { return '{undefined}' } const findKey = Object.keys(source).find(key => varName === key) if (findKey) { let val // For parameters we access `defaultValue` if (source === this.template.parameters) { val = source[findKey].defaultValue // Without a defaultValue it is impossible to know what the parameters value could be! // So a fall-back out is to return the param name inside {} if (!val && val !== 0) { return `{${this.eval(varName)}}` } } else { // For variables we use the actual value val = source[findKey] } // Variables can be JSON objects, MASSIVE SIGH LOOK AT THIS INSANITY if (typeof(val) === 'object') { if (!propAccessor) { // We're dealing with an object and have no property accessor, nothing we can do return `{${JSON.stringify(val)}}` } // Hack to try to handle copyIndex, default to first item in array propAccessor = propAccessor.replace('copyIndex()', '0') // Use eval to access property, I'm not happy about it, but don't have a choice try { // tslint:disable-next-line: no-eval const evalResult = eval('val' + propAccessor) if (typeof(evalResult) === 'undefined') { console.log(`### ArmView: Warn! Your template contains invalid references: ${varName} -> ${propAccessor}`) return '{undefined}' } if (typeof(evalResult) === 'string') { // variable references values can be expressions too, so down the rabbit hole we go... return this.eval(evalResult, true) } if (typeof(evalResult) === 'object') { // We got an object back, give up return `{${JSON.stringify(evalResult)}}` } } catch (err) { console.log(`### ArmView: Warn! Your template contains invalid references: ${varName} -> ${propAccessor}`) return '{undefined}' } } if (typeof(val) === 'string') { // variable values can be expressions too, so down the rabbit hole we go... return this.eval(val, true) } // Fall back return val } else { console.log(`### ArmView: Warn! Your template contains invalid references: ${varName} -> ${propAccessor}`) return '{undefined}' } } // // Emulate the ARM function `uniqueString()` // private funcUniqueString(baseStr: string): string { const hash = utils.hashCode(baseStr) return Buffer.from(`${hash}`).toString('base64').substr(0, 14) } // // Emulate the ARM function `concat()` // private funcConcat(funcParams: string, joinStr: string): string { const paramList = this.parseParams(funcParams) let res = '' for (const p in paramList) { let param = paramList[p] try { param = param.trim() } catch (err) { // Nothing } res += joinStr + this.eval(param) } return res } // // Emulate the ARM function `uri()` // private funcUri(funcParams: string): string { const paramList = this.parseParams(funcParams) if (paramList.length === 2) { let sep = '' let base = this.eval(paramList[0]) const rel = this.eval(paramList[1]) if (!(base.endsWith('/') || rel.startsWith('/'))) { sep = '/' } if (base.endsWith('/') && rel.startsWith('/')) { sep = '' base = base.substr(0, base.length - 1) } return base + sep + rel } return '{invalid-uri}' } // // Emulate the ARM function `replace()` // private funcReplace(funcParams: string): string { const paramList = this.parseParams(funcParams) const input = this.eval(paramList[0]) const search = this.eval(paramList[1]) const replace = this.eval(paramList[2]) return input.replace(new RegExp(search, 'g'), replace) } // // Emulate the ARM function `toLower()` // private funcToLower(funcParams: string): string { return this.eval(funcParams).toLowerCase() } // // Emulate the ARM function `toUpper()` // private funcToUpper(funcParams: string): string { return this.eval(funcParams).toUpperCase() } // // Emulate the ARM function `substring()` // private funcSubstring(funcParams: string): string { const paramList = this.parseParams(funcParams) const str = this.eval(paramList[0]) const start = parseInt(this.eval(paramList[1]), 10) const len = parseInt(this.eval(paramList[2]), 10) return this.eval(str).substring(start, start + len) } // // Emulate the ARM function `take()` // private funcTake(funcParams: string): string { const paramList = this.parseParams(funcParams) const value = this.eval(paramList[0]) const count = parseInt(this.eval(paramList[1]), 10) // Could be an array or string, but JS doesn't care return this.eval(value[count]) } // // This is a brute force parser for comma separated parameter lists in function calls, e.g. foo(bar, thing(1, 2)) // private parseParams(paramString: string): string[] { // Parsing non-nested commas in a param list is IMPOSSIBLE WITH A REGEX let depth = 0 const parts = [] let lastSplit = 0 for (let i = 0; i < paramString.length; i++) { const c = paramString.charAt(i) // paramString[i]; if (c === '(') { depth++ } if (c === ')') { depth-- } const endOfString = i === paramString.length - 1 if ((c === ',' && depth === 0) || endOfString) { const endPoint = endOfString ? paramString.length : i parts.push(paramString.substring(lastSplit, endPoint).trim()) lastSplit = i + 1 } } return parts } }
the_stack
import { withPlugins, createDiceRoller } from "@airjp73/dice-notation"; import type { Random, DiceRule } from "@airjp73/dice-notation"; import type { RollInformation } from "@airjp73/dice-notation/dist/roll"; import times from "lodash/times"; interface RollToken { numDice: number; numSides: number; numToDrop: number; } const generateRolls = (token: RollToken, { random }: { random: Random }) => times(token.numDice, () => random(1, token.numSides)); const getInvertedIndices = ( items: Array<unknown>, indices: Set<number> ): Set<number> => { const invertedIndices = new Set<number>(); items.forEach((_, index) => { if (!indices.has(index)) { invertedIndices.add(index); } }); return invertedIndices; }; export const getDroppedIndicesDropLowest = ( token: RollToken, rolls: Array<number> ): Set<number> => { const lowestIndices = new Set<number>(); const rollCopy = rolls.slice(); const droppedValues: Array<number> = []; for (let counter = 0; counter < token.numToDrop; counter++) { if (rollCopy.length === 0) { break; } const index = rollCopy.indexOf(Math.min(...rollCopy)); droppedValues.push(rollCopy[index]); rollCopy.splice(index, 1); } const valueIndexLookupMap = new Map<number, Array<number>>(); for (const [value, index] of rolls.entries()) { let indices = valueIndexLookupMap.get(index); if (!indices) { indices = []; valueIndexLookupMap.set(index, indices); } indices.push(value); } for (const droppedValue of droppedValues) { lowestIndices.add(valueIndexLookupMap.get(droppedValue)!.pop()!); } return lowestIndices; }; export const getDroppedIndicesDropHighest = ( token: RollToken, rolls: Array<number> ): Set<number> => { const lowestIndices = getDroppedIndicesDropLowest( { ...token, numToDrop: Math.max(0, token.numDice - token.numToDrop), }, rolls ); return getInvertedIndices(rolls, lowestIndices); }; export const getDroppedIndicesKeepHighestN = ( token: RollToken, rolls: Array<number> ) => getDroppedIndicesDropLowest( { ...token, numToDrop: token.numToDrop, }, rolls ); export const getDroppedIndicesKeepLowestN = ( token: RollToken, rolls: Array<number> ) => getDroppedIndicesDropHighest( { ...token, numToDrop: token.numToDrop, }, rolls ); const calculateValueRemovingLowest = ( token: RollToken, rolls: number[] ): number => Array.from( getInvertedIndices(rolls, getDroppedIndicesDropLowest(token, rolls)) ).reduce((aggregate: number, index: number) => aggregate + rolls[index], 0); const calculateValueKeepingHighest = ( token: RollToken, rolls: number[] ): number => Array.from( getInvertedIndices(rolls, getDroppedIndicesKeepHighestN(token, rolls)) ).reduce((aggregate: number, index: number) => aggregate + rolls[index], 0); const calculateValueRemovingHighest = ( token: RollToken, rolls: number[] ): number => Array.from( getInvertedIndices(rolls, getDroppedIndicesDropHighest(token, rolls)) ).reduce((aggregate: number, index: number) => aggregate + rolls[index], 0); const calculateValueKeepingLowest = ( token: RollToken, rolls: number[] ): number => Array.from( getInvertedIndices(rolls, getDroppedIndicesKeepLowestN(token, rolls)) ).reduce((aggregate: number, index: number) => aggregate + rolls[index], 0); // Custom dice roll rule for format [XdYdl] and [XdYdlN] // Roll XdY drop lowest N = 1 const dropLowestN: RegExp = /((\d+)d(\d+))dl(?:(\d+))?/; const detectDropLowestN: RegExp = /\d+d\d+dl(?:\d+)?/; const rollRuleDropLowestN: DiceRule<RollToken> = { regex: detectDropLowestN, typeConstant: "DropLowestN", tokenize: (raw: string): RollToken => { const result = raw.match(dropLowestN); if (!result) { throw new Error("Error while parsing."); } const [, , numDiceRaw, numSidesRaw, numToDropRaw = "1"] = result; return { numDice: parseInt(numDiceRaw, 10), numSides: parseInt(numSidesRaw, 10), numToDrop: parseInt(numToDropRaw, 10), }; }, roll: generateRolls, calculateValue: calculateValueRemovingLowest, }; // Custom dice roll rule for format [XdYdh] [XdYdhN] // Roll XdY drop highest N = 1 const dropHighestN: RegExp = /((\d+)d(\d+))dh(?:(\d+))?/; const detectDropHighestN: RegExp = /\d+d\d+dh(?:\d+)?/; const rollRuleDropHighestN: DiceRule<RollToken> = { regex: detectDropHighestN, typeConstant: "DropHighestN", tokenize: (raw: string): RollToken => { const result = raw.match(dropHighestN); if (!result) { throw new Error("Error while parsing."); } const [, , numDiceRaw, numSidesRaw, numToDropRaw = "1"] = result; return { numDice: parseInt(numDiceRaw, 10), numSides: parseInt(numSidesRaw, 10), numToDrop: parseInt(numToDropRaw, 10), }; }, roll: generateRolls, calculateValue: calculateValueRemovingHighest, }; // Custom dice roll rule for format[XdYkl] [XdYklN] // Roll XdY keep lowest N = 1 const keepLowestN: RegExp = /((\d+)d(\d+))kl(?:(\d+))?/; const detectKeepLowestN: RegExp = /\d+d\d+kl(?:\d+)?/; const rollRuleKeepLowestN: DiceRule<RollToken> = { regex: detectKeepLowestN, typeConstant: "KeepLowestN", tokenize: (raw: string): RollToken => { const result = raw.match(keepLowestN); if (!result) { throw new Error("Error while parsing."); } const [, , numDiceRaw, numSidesRaw, numToKeepRaw = "1"] = result; const numDice = parseInt(numDiceRaw, 10); const numToKeep = parseInt(numToKeepRaw, 10); return { numDice, numSides: parseInt(numSidesRaw, 10), numToDrop: Math.max(0, numDice - numToKeep), }; }, roll: generateRolls, calculateValue: calculateValueKeepingLowest, }; // Custom dice roll rule for format [XdYkh] or [XdYkhN] // Roll XdY keep highest N = 1 const keepHighestN: RegExp = /((\d+)d(\d+))kh(?:(\d+))?/; const detectKeepHighestN: RegExp = /\d+d\d+kh(?:\d+)?/; const rollRuleKeepHighestN: DiceRule<RollToken> = { regex: detectKeepHighestN, typeConstant: "KeepHighestN", tokenize: (raw: string): RollToken => { const result = raw.match(keepHighestN); if (!result) { throw new Error("Error while parsing."); } const [, , numDiceRaw, numSidesRaw, numToKeepRaw = "1"] = result; const numDice = parseInt(numDiceRaw, 10); const numToKeep = parseInt(numToKeepRaw, 10); return { numDice, numSides: parseInt(numSidesRaw, 10), numToDrop: Math.max(0, numDice - numToKeep), }; }, roll: generateRolls, calculateValue: calculateValueKeepingHighest, }; // Configure defined roll rules const rollRules: DiceRule<RollToken>[] = [ rollRuleDropLowestN, rollRuleDropHighestN, rollRuleKeepLowestN, rollRuleKeepHighestN, ]; const { roll } = createDiceRoller(withPlugins(...rollRules)); export type DiceRollDetail = | { type: "DiceRoll"; content: string; detail: { max: number; min: number; }; rolls: Array<{ value: number; crossedOut: boolean }>; } | { type: "Constant"; content: string; } | { type: "Operator"; content: string; } | { type: "OpenParen"; content: string; } | { type: "CloseParen"; content: string; }; const isDiceRollResultSymbol = Symbol("isDiceRollResult"); export type DiceRollResult = { id: string; [isDiceRollResultSymbol]: true; result: number; detail: Array<DiceRollDetail>; }; export const isDiceRollResult = (obj: unknown): obj is DiceRollResult => typeof obj === "object" && obj != null && isDiceRollResultSymbol in obj; const formatRoll = (result: RollInformation, id: string): DiceRollResult => { return Object.freeze({ [isDiceRollResultSymbol]: true, id, result: result.result, detail: result.tokens.map((token, index) => { if (token.type === "DiceRoll") { if (token.detailType === "_SimpleDieRoll") { const rollResults = result.rolls[index] as number[]; return { type: "DiceRoll" as const, content: token.content, detail: { min: 1, max: token.detail.numSides as number, }, rolls: rollResults.map((value) => ({ value, crossedOut: false })), }; } else if ( token.detailType === "DropLowestN" || token.detailType === "DropHighestN" || token.detailType === "KeepLowestN" || token.detailType === "KeepHighestN" ) { const rollResults = result.rolls[index] as number[]; let crossedOutIndices: null | Set<number> = null; const diceType: string = `${token.detail.numDice}d${token.detail.numSides}`; switch (token.detailType) { case "DropLowestN": crossedOutIndices = getDroppedIndicesDropLowest( token.detail, rollResults ); break; case "DropHighestN": crossedOutIndices = getDroppedIndicesDropHighest( token.detail, rollResults ); break; case "KeepHighestN": crossedOutIndices = getDroppedIndicesKeepHighestN( token.detail, rollResults ); break; case "KeepLowestN": crossedOutIndices = getDroppedIndicesKeepLowestN( token.detail, rollResults ); break; } return { type: "DiceRoll" as const, content: diceType, detail: { min: 1, max: token.detail.numSides as number, }, rolls: rollResults.map((value, index) => ({ value, crossedOut: crossedOutIndices?.has(index) ?? false, })), }; } else if (token.detailType === "_Constant") { return { type: "Constant" as const, content: token.content, }; } throw new Error(`Invalid Detail Type '${token.detailType}'.`); } else if (token.type === "Operator") { return { type: "Operator" as const, content: token.content, }; } else if (token.type === "OpenParen") { return { type: "OpenParen" as const, content: token.content, }; } else if (token.type === "CloseParen") { return { type: "CloseParen" as const, content: token.content, }; } // @ts-ignore throw new Error(`Invalid Type '${token.type}'.`); }), }); }; // We map the result to our own representation export const tryRoll = (input: string) => { try { const result = roll(input); return (id: string) => formatRoll(result, id); } catch (err) { // TODO: Better error handling :/ return null; } };
the_stack
* A third-party license is embeded for some of the code in this file: * The treemap layout implementation was originally copied from * "d3.js" with some modifications made for this project. * (See more details in the comment of the method "squarify" below.) * The use of the source code of this file is also subject to the terms * and consitions of the license of "d3.js" (BSD-3Clause, see * </licenses/LICENSE-d3>). */ import * as zrUtil from 'zrender/src/core/util'; import BoundingRect, { RectLike } from 'zrender/src/core/BoundingRect'; import {parsePercent, MAX_SAFE_INTEGER} from '../../util/number'; import * as layout from '../../util/layout'; import * as helper from '../helper/treeHelper'; import TreemapSeriesModel, { TreemapSeriesNodeItemOption } from './TreemapSeries'; import GlobalModel from '../../model/Global'; import ExtensionAPI from '../../core/ExtensionAPI'; import { TreeNode } from '../../data/Tree'; import Model from '../../model/Model'; import { TreemapRenderPayload, TreemapMovePayload, TreemapZoomToNodePayload } from './treemapAction'; const mathMax = Math.max; const mathMin = Math.min; const retrieveValue = zrUtil.retrieve; const each = zrUtil.each; const PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'] as const; const PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'] as const; const PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'] as const; const PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'] as const; export interface TreemapLayoutNode extends TreeNode { parentNode: TreemapLayoutNode children: TreemapLayoutNode[] viewChildren: TreemapLayoutNode[] } export interface TreemapItemLayout extends RectLike { area: number isLeafRoot: boolean dataExtent: [number, number] borderWidth: number upperHeight: number upperLabelHeight: number isInView: boolean invisible: boolean isAboveViewRoot: boolean }; type NodeModel = Model<TreemapSeriesNodeItemOption>; type OrderBy = 'asc' | 'desc' | boolean; type LayoutRow = TreemapLayoutNode[] & { area: number }; /** * @public */ export default { seriesType: 'treemap', reset: function ( seriesModel: TreemapSeriesModel, ecModel: GlobalModel, api: ExtensionAPI, payload?: TreemapZoomToNodePayload | TreemapRenderPayload | TreemapMovePayload ) { // Layout result in each node: // {x, y, width, height, area, borderWidth} const ecWidth = api.getWidth(); const ecHeight = api.getHeight(); const seriesOption = seriesModel.option; const layoutInfo = layout.getLayoutRect( seriesModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() } ); const size = seriesOption.size || []; // Compatible with ec2. const containerWidth = parsePercent( retrieveValue(layoutInfo.width, size[0]), ecWidth ); const containerHeight = parsePercent( retrieveValue(layoutInfo.height, size[1]), ecHeight ); // Fetch payload info. const payloadType = payload && payload.type; const types = ['treemapZoomToNode', 'treemapRootToNode']; const targetInfo = helper .retrieveTargetInfo(payload, types, seriesModel); const rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove') ? payload.rootRect : null; const viewRoot = seriesModel.getViewRoot(); const viewAbovePath = helper.getPathToRoot(viewRoot) as TreemapLayoutNode[]; if (payloadType !== 'treemapMove') { const rootSize = payloadType === 'treemapZoomToNode' ? estimateRootSize( seriesModel, targetInfo, viewRoot, containerWidth, containerHeight ) : rootRect ? [rootRect.width, rootRect.height] : [containerWidth, containerHeight]; let sort = seriesOption.sort; if (sort && sort !== 'asc' && sort !== 'desc') { // Default to be desc order. sort = 'desc'; } const options = { squareRatio: seriesOption.squareRatio, sort: sort, leafDepth: seriesOption.leafDepth }; // layout should be cleared because using updateView but not update. viewRoot.hostTree.clearLayouts(); // TODO // optimize: if out of view clip, do not layout. // But take care that if do not render node out of view clip, // how to calculate start po let viewRootLayout = { x: 0, y: 0, width: rootSize[0], height: rootSize[1], area: rootSize[0] * rootSize[1] }; viewRoot.setLayout(viewRootLayout); squarify(viewRoot, options, false, 0); // Supplement layout. viewRootLayout = viewRoot.getLayout(); each(viewAbovePath, function (node, index) { const childValue = (viewAbovePath[index + 1] || viewRoot).getValue(); node.setLayout(zrUtil.extend( { dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0 }, viewRootLayout )); }); } const treeRoot = seriesModel.getData().tree.root; treeRoot.setLayout( calculateRootPosition(layoutInfo, rootRect, targetInfo), true ); seriesModel.setLayoutInfo(layoutInfo); // FIXME // 现在没有clip功能,暂时取ec高宽。 prunning( treeRoot, // Transform to base element coordinate system. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight), viewAbovePath, viewRoot, 0 ); } }; /** * Layout treemap with squarify algorithm. * The original presentation of this algorithm * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>. * The implementation of this algorithm was originally copied from "d3.js" * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js> * with some modifications made for this program. * See the license statement at the head of this file. * * @protected * @param {module:echarts/data/Tree~TreeNode} node * @param {Object} options * @param {string} options.sort 'asc' or 'desc' * @param {number} options.squareRatio * @param {boolean} hideChildren * @param {number} depth */ function squarify( node: TreemapLayoutNode, options: { sort?: OrderBy squareRatio?: number leafDepth?: number }, hideChildren: boolean, depth: number ) { let width; let height; if (node.isRemoved()) { return; } const thisLayout = node.getLayout(); width = thisLayout.width; height = thisLayout.height; // Considering border and gap const nodeModel = node.getModel<TreemapSeriesNodeItemOption>(); const borderWidth = nodeModel.get(PATH_BORDER_WIDTH); const halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2; const upperLabelHeight = getUpperLabelHeight(nodeModel); const upperHeight = Math.max(borderWidth, upperLabelHeight); const layoutOffset = borderWidth - halfGapWidth; const layoutOffsetUpper = upperHeight - halfGapWidth; node.setLayout({ borderWidth: borderWidth, upperHeight: upperHeight, upperLabelHeight: upperLabelHeight }, true); width = mathMax(width - 2 * layoutOffset, 0); height = mathMax(height - layoutOffset - layoutOffsetUpper, 0); const totalArea = width * height; const viewChildren = initChildren( node, nodeModel, totalArea, options, hideChildren, depth ); if (!viewChildren.length) { return; } const rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height}; let rowFixedLength = mathMin(width, height); let best = Infinity; // the best row score so far const row = [] as LayoutRow; row.area = 0; for (let i = 0, len = viewChildren.length; i < len;) { const child = viewChildren[i]; row.push(child); row.area += child.getLayout().area; const score = worst(row, rowFixedLength, options.squareRatio); // continue with this orientation if (score <= best) { i++; best = score; } // abort, and try a different orientation else { row.area -= row.pop().getLayout().area; position(row, rowFixedLength, rect, halfGapWidth, false); rowFixedLength = mathMin(rect.width, rect.height); row.length = row.area = 0; best = Infinity; } } if (row.length) { position(row, rowFixedLength, rect, halfGapWidth, true); } if (!hideChildren) { const childrenVisibleMin = nodeModel.get('childrenVisibleMin'); if (childrenVisibleMin != null && totalArea < childrenVisibleMin) { hideChildren = true; } } for (let i = 0, len = viewChildren.length; i < len; i++) { squarify(viewChildren[i], options, hideChildren, depth + 1); } } /** * Set area to each child, and calculate data extent for visual coding. */ function initChildren( node: TreemapLayoutNode, nodeModel: NodeModel, totalArea: number, options: { sort?: OrderBy leafDepth?: number }, hideChildren: boolean, depth: number ) { let viewChildren = node.children || []; let orderBy = options.sort; orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null); const overLeafDepth = options.leafDepth != null && options.leafDepth <= depth; // leafDepth has higher priority. if (hideChildren && !overLeafDepth) { return (node.viewChildren = []); } // Sort children, order by desc. viewChildren = zrUtil.filter(viewChildren, function (child) { return !child.isRemoved(); }); sort(viewChildren, orderBy); const info = statistic(nodeModel, viewChildren, orderBy); if (info.sum === 0) { return (node.viewChildren = []); } info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren); if (info.sum === 0) { return (node.viewChildren = []); } // Set area to each child. for (let i = 0, len = viewChildren.length; i < len; i++) { const area = viewChildren[i].getValue() as number / info.sum * totalArea; // Do not use setLayout({...}, true), because it is needed to clear last layout. viewChildren[i].setLayout({ area: area }); } if (overLeafDepth) { viewChildren.length && node.setLayout({ isLeafRoot: true }, true); viewChildren.length = 0; } node.viewChildren = viewChildren; node.setLayout({ dataExtent: info.dataExtent }, true); return viewChildren; } /** * Consider 'visibleMin'. Modify viewChildren and get new sum. */ function filterByThreshold( nodeModel: NodeModel, totalArea: number, sum: number, orderBy: OrderBy, orderedChildren: TreemapLayoutNode[] ) { // visibleMin is not supported yet when no option.sort. if (!orderBy) { return sum; } const visibleMin = nodeModel.get('visibleMin'); const len = orderedChildren.length; let deletePoint = len; // Always travel from little value to big value. for (let i = len - 1; i >= 0; i--) { const value = orderedChildren[ orderBy === 'asc' ? len - i - 1 : i ].getValue() as number; if (value / sum * totalArea < visibleMin) { deletePoint = i; sum -= value; } } orderBy === 'asc' ? orderedChildren.splice(0, len - deletePoint) : orderedChildren.splice(deletePoint, len - deletePoint); return sum; } /** * Sort */ function sort( viewChildren: TreemapLayoutNode[], orderBy: OrderBy ) { if (orderBy) { viewChildren.sort(function (a, b) { const diff = orderBy === 'asc' ? a.getValue() as number - (b.getValue() as number) : b.getValue() as number - (a.getValue() as number); return diff === 0 ? (orderBy === 'asc' ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex ) : diff; }); } return viewChildren; } /** * Statistic */ function statistic( nodeModel: NodeModel, children: TreemapLayoutNode[], orderBy: OrderBy ) { // Calculate sum. let sum = 0; for (let i = 0, len = children.length; i < len; i++) { sum += children[i].getValue() as number; } // Statistic data extent for latter visual coding. // Notice: data extent should be calculate based on raw children // but not filtered view children, otherwise visual mapping will not // be stable when zoom (where children is filtered by visibleMin). const dimension = nodeModel.get('visualDimension'); let dataExtent: number[]; // The same as area dimension. if (!children || !children.length) { dataExtent = [NaN, NaN]; } else if (dimension === 'value' && orderBy) { dataExtent = [ children[children.length - 1].getValue() as number, children[0].getValue() as number ]; orderBy === 'asc' && dataExtent.reverse(); } // Other dimension. else { dataExtent = [Infinity, -Infinity]; each(children, function (child) { const value = child.getValue(dimension) as number; value < dataExtent[0] && (dataExtent[0] = value); value > dataExtent[1] && (dataExtent[1] = value); }); } return {sum: sum, dataExtent: dataExtent}; } /** * Computes the score for the specified row, * as the worst aspect ratio. */ function worst(row: LayoutRow, rowFixedLength: number, ratio: number) { let areaMax = 0; let areaMin = Infinity; for (let i = 0, area, len = row.length; i < len; i++) { area = row[i].getLayout().area; if (area) { area < areaMin && (areaMin = area); area > areaMax && (areaMax = area); } } const squareArea = row.area * row.area; const f = rowFixedLength * rowFixedLength * ratio; return squareArea ? mathMax( (f * areaMax) / squareArea, squareArea / (f * areaMin) ) : Infinity; } /** * Positions the specified row of nodes. Modifies `rect`. */ function position( row: LayoutRow, rowFixedLength: number, rect: RectLike, halfGapWidth: number, flush?: boolean ) { // When rowFixedLength === rect.width, // it is horizontal subdivision, // rowFixedLength is the width of the subdivision, // rowOtherLength is the height of the subdivision, // and nodes will be positioned from left to right. // wh[idx0WhenH] means: when horizontal, // wh[idx0WhenH] => wh[0] => 'width'. // xy[idx1WhenH] => xy[1] => 'y'. const idx0WhenH = rowFixedLength === rect.width ? 0 : 1; const idx1WhenH = 1 - idx0WhenH; const xy = ['x', 'y'] as const; const wh = ['width', 'height'] as const; let last = rect[xy[idx0WhenH]]; let rowOtherLength = rowFixedLength ? row.area / rowFixedLength : 0; if (flush || rowOtherLength > rect[wh[idx1WhenH]]) { rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow } for (let i = 0, rowLen = row.length; i < rowLen; i++) { const node = row[i]; const nodeLayout = {} as TreemapItemLayout; const step = rowOtherLength ? node.getLayout().area / rowOtherLength : 0; const wh1 = nodeLayout[wh[idx1WhenH]] = mathMax(rowOtherLength - 2 * halfGapWidth, 0); // We use Math.max/min to avoid negative width/height when considering gap width. const remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last; const modWH = (i === rowLen - 1 || remain < step) ? remain : step; const wh0 = nodeLayout[wh[idx0WhenH]] = mathMax(modWH - 2 * halfGapWidth, 0); nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin(halfGapWidth, wh1 / 2); nodeLayout[xy[idx0WhenH]] = last + mathMin(halfGapWidth, wh0 / 2); last += modWH; node.setLayout(nodeLayout, true); } rect[xy[idx1WhenH]] += rowOtherLength; rect[wh[idx1WhenH]] -= rowOtherLength; } // Return [containerWidth, containerHeight] as default. function estimateRootSize( seriesModel: TreemapSeriesModel, targetInfo: { node: TreemapLayoutNode }, viewRoot: TreemapLayoutNode, containerWidth: number, containerHeight: number ) { // If targetInfo.node exists, we zoom to the node, // so estimate whold width and heigth by target node. let currNode = (targetInfo || {}).node; const defaultSize = [containerWidth, containerHeight]; if (!currNode || currNode === viewRoot) { return defaultSize; } let parent; const viewArea = containerWidth * containerHeight; let area = viewArea * seriesModel.option.zoomToNodeRatio; while (parent = currNode.parentNode) { // jshint ignore:line let sum = 0; const siblings = parent.children; for (let i = 0, len = siblings.length; i < len; i++) { sum += siblings[i].getValue() as number; } const currNodeValue = currNode.getValue() as number; if (currNodeValue === 0) { return defaultSize; } area *= sum / currNodeValue; // Considering border, suppose aspect ratio is 1. const parentModel = parent.getModel<TreemapSeriesNodeItemOption>(); const borderWidth = parentModel.get(PATH_BORDER_WIDTH); const upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel)); area += 4 * borderWidth * borderWidth + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5); area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER); currNode = parent; } area < viewArea && (area = viewArea); const scale = Math.pow(area / viewArea, 0.5); return [containerWidth * scale, containerHeight * scale]; } // Root postion base on coord of containerGroup function calculateRootPosition( layoutInfo: layout.LayoutRect, rootRect: RectLike, targetInfo: { node: TreemapLayoutNode } ) { if (rootRect) { return {x: rootRect.x, y: rootRect.y}; } const defaultPosition = {x: 0, y: 0}; if (!targetInfo) { return defaultPosition; } // If targetInfo is fetched by 'retrieveTargetInfo', // old tree and new tree are the same tree, // so the node still exists and we can visit it. const targetNode = targetInfo.node; const layout = targetNode.getLayout(); if (!layout) { return defaultPosition; } // Transform coord from local to container. const targetCenter = [layout.width / 2, layout.height / 2]; let node = targetNode; while (node) { const nodeLayout = node.getLayout(); targetCenter[0] += nodeLayout.x; targetCenter[1] += nodeLayout.y; node = node.parentNode; } return { x: layoutInfo.width / 2 - targetCenter[0], y: layoutInfo.height / 2 - targetCenter[1] }; } // Mark nodes visible for prunning when visual coding and rendering. // Prunning depends on layout and root position, so we have to do it after layout. function prunning( node: TreemapLayoutNode, clipRect: BoundingRect, viewAbovePath: TreemapLayoutNode[], viewRoot: TreemapLayoutNode, depth: number ) { const nodeLayout = node.getLayout(); const nodeInViewAbovePath = viewAbovePath[depth]; const isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node; if ( (nodeInViewAbovePath && !isAboveViewRoot) || (depth === viewAbovePath.length && node !== viewRoot) ) { return; } node.setLayout({ // isInView means: viewRoot sub tree + viewAbovePath isInView: true, // invisible only means: outside view clip so that the node can not // see but still layout for animation preparation but not render. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout), isAboveViewRoot }, true); // Transform to child coordinate. const childClipRect = new BoundingRect( clipRect.x - nodeLayout.x, clipRect.y - nodeLayout.y, clipRect.width, clipRect.height ); each(node.viewChildren || [], function (child) { prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1); }); } function getUpperLabelHeight(model: NodeModel): number { return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0; }
the_stack
import { ProtectAccessory, ProtectReservedNames } from "./protect-accessory"; import { ProtectSensorConfig } from "unifi-protect"; import { Service } from "homebridge"; export class ProtectSensor extends ProtectAccessory { private savedAlarmSound!: boolean; private savedContact!: boolean; // Initialize and configure the sensor accessory for HomeKit. protected async configureDevice(): Promise<boolean> { // Save the device object before we wipeout the context. const device = this.accessory.context.device as ProtectSensorConfig; // Clean out the context object in case it's been polluted somehow. this.accessory.context = {}; this.accessory.context.device = device; this.accessory.context.nvr = this.nvr.nvrApi.bootstrap?.nvr.mac; // Configure accessory information. this.configureInfo(); // Configure accessory services. const enabledSensors = this.updateDevice(); // Configure MQTT services. this.configureMqtt(); // Inform the user what we're enabling on startup. if(enabledSensors.length) { this.log.info("%s: Enabled sensor%s: %s.", this.name(), enabledSensors.length > 1 ? "s" : "", enabledSensors.join(", ")); } else { this.log.info("%s: No sensors enabled.", this.name()); } return Promise.resolve(true); } // Update accessory services and characteristics. public updateDevice(): string[] { const enabledSensors: string[] = []; // Configure the alarm sound sensor. if(this.configureAlarmSoundSensor()) { enabledSensors.push("alarm sound"); } // Configure the ambient light sensor. if(this.configureAmbientLightSensor()) { enabledSensors.push("ambient light"); } // Configure the contact sensor. if(this.configureContactSensor()) { enabledSensors.push("contact"); } // Configure the humidity sensor. if(this.configureHumiditySensor()) { enabledSensors.push("humidity"); } // Configure the motion sensor. if(this.configureMotionSensor((this.accessory.context.device as ProtectSensorConfig)?.motionSettings?.isEnabled)) { // Sensor accessories also support battery, connection, and tamper status...we need to handle those ourselves. const motionService = this.accessory.getService(this.hap.Service.MotionSensor); if(motionService) { // Update the state characteristics. this.configureStateCharacteristics(motionService); } enabledSensors.push("motion sensor"); } // Configure the temperature sensor. if(this.configureTemperatureSensor()) { enabledSensors.push("temperature"); } return enabledSensors; } // Configure the alarm sound sensor for HomeKit. private configureAlarmSoundSensor(): boolean { const device = this.accessory.context.device as ProtectSensorConfig; // Find the service, if it exists. let contactService = this.accessory.getServiceById(this.hap.Service.ContactSensor, ProtectReservedNames.CONTACT_SENSOR_ALARM_SOUND); // Have we disabled the alarm sound sensor? if(!device?.alarmSettings?.isEnabled) { if(contactService) { this.accessory.removeService(contactService); this.log.info("%s: Disabling alarm sound contact sensor.", this.name()); } return false; } // Add the service to the accessory, if needed. if(!contactService) { contactService = new this.hap.Service.ContactSensor(this.accessory.displayName + " Alarm Sound", ProtectReservedNames.CONTACT_SENSOR_ALARM_SOUND); if(!contactService) { this.log.error("%s: Unable to add alarm sound contact sensor.", this.name()); return false; } this.accessory.addService(contactService); this.log.info("%s: Enabling alarm sound contact sensor.", this.name()); } // Retrieve the current contact sensor state when requested. contactService.getCharacteristic(this.hap.Characteristic.ContactSensorState)?.onGet(() => { return this.getAlarmSound(); }); // Update the sensor. contactService.updateCharacteristic(this.hap.Characteristic.ContactSensorState, this.getAlarmSound()); // Update the state characteristics. this.configureStateCharacteristics(contactService); return true; } // Configure the ambient light sensor for HomeKit. private configureAmbientLightSensor(): boolean { const device = this.accessory.context.device as ProtectSensorConfig; // Find the service, if it exists. let lightService = this.accessory.getService(this.hap.Service.LightSensor); // Have we disabled the light sensor? if(!device?.lightSettings?.isEnabled) { if(lightService) { this.accessory.removeService(lightService); this.log.info("%s: Disabling ambient light sensor.", this.name()); } return false; } // Add the service to the accessory, if needed. if(!lightService) { lightService = new this.hap.Service.LightSensor(this.accessory.displayName); if(!lightService) { this.log.error("%s: Unable to add ambient light sensor.", this.name()); return false; } this.accessory.addService(lightService); this.log.info("%s: Enabling ambient light sensor.", this.name()); } // Retrieve the current light level when requested. lightService.getCharacteristic(this.hap.Characteristic.CurrentAmbientLightLevel)?.onGet(() => { // The minimum value for ambient light in HomeKit is 0.0001. I have no idea why...but it is. Honor it. const value = this.getAmbientLight(); return value >= 0.0001 ? value : 0.0001; }); // Update the sensor. The minimum value for ambient light in HomeKit is 0.0001. I have no idea why...but it is. Honor it. const value = this.getAmbientLight(); lightService.updateCharacteristic(this.hap.Characteristic.CurrentAmbientLightLevel, value >= 0.0001 ? value : 0.0001); // Update the state characteristics. this.configureStateCharacteristics(lightService); return true; } // Configure the contact sensor for HomeKit. private configureContactSensor(): boolean { const device = this.accessory.context.device as ProtectSensorConfig; // Find the service, if it exists. let contactService = this.accessory.getServiceById(this.hap.Service.ContactSensor, ProtectReservedNames.CONTACT_SENSOR); // Have we disabled the sensor? if(!device?.mountType || (device.mountType === "none")) { if(contactService) { this.accessory.removeService(contactService); this.log.info("%s: Disabling contact sensor.", this.name()); } return false; } // Add the service to the accessory, if needed. if(!contactService) { contactService = new this.hap.Service.ContactSensor(this.accessory.displayName, ProtectReservedNames.CONTACT_SENSOR); if(!contactService) { this.log.error("%s: Unable to add contact sensor.", this.name()); return false; } this.accessory.addService(contactService); this.log.info("%s: Enabling contact sensor.", this.name()); } // Retrieve the current contact sensor state when requested. contactService.getCharacteristic(this.hap.Characteristic.ContactSensorState)?.onGet(() => { return this.getContact(); }); // Update the sensor. contactService.updateCharacteristic(this.hap.Characteristic.ContactSensorState, this.getContact()); // Update the state characteristics. this.configureStateCharacteristics(contactService); return true; } // Configure the humidity sensor for HomeKit. private configureHumiditySensor(): boolean { const device = this.accessory.context.device as ProtectSensorConfig; // Find the service, if it exists. let humidityService = this.accessory.getService(this.hap.Service.HumiditySensor); // Have we disabled the sensor? if(!device?.humiditySettings?.isEnabled) { if(humidityService) { this.accessory.removeService(humidityService); this.log.info("%s: Disabling humidity sensor.", this.name()); } return false; } // Add the service to the accessory, if needed. if(!humidityService) { humidityService = new this.hap.Service.HumiditySensor(this.accessory.displayName); if(!humidityService) { this.log.error("%s: Unable to add humidity sensor.", this.name()); return false; } this.accessory.addService(humidityService); this.log.info("%s: Enabling humidity sensor.", this.name()); } // Retrieve the current humidity when requested. humidityService.getCharacteristic(this.hap.Characteristic.CurrentRelativeHumidity)?.onGet(() => { const value = this.getHumidity(); return value < 0 ? 0 : value; }); // Update the sensor. const value = this.getHumidity(); humidityService.updateCharacteristic(this.hap.Characteristic.CurrentRelativeHumidity, value < 0 ? 0 : value); // Update the state characteristics. this.configureStateCharacteristics(humidityService); return true; } // Configure the temperature sensor for HomeKit. private configureTemperatureSensor(): boolean { const device = this.accessory.context.device as ProtectSensorConfig; // Find the service, if it exists. let temperatureService = this.accessory.getService(this.hap.Service.TemperatureSensor); // Have we disabled the temperature sensor? if(!device?.temperatureSettings?.isEnabled) { if(temperatureService) { this.accessory.removeService(temperatureService); this.log.info("%s: Disabling temperature sensor.", this.name()); } return false; } // Add the service to the accessory, if needed. if(!temperatureService) { temperatureService = new this.hap.Service.TemperatureSensor(this.accessory.displayName); if(!temperatureService) { this.log.error("%s: Unable to add temperature sensor.", this.name()); return false; } this.accessory.addService(temperatureService); this.log.info("%s: Enabling temperature sensor.", this.name()); } // Retrieve the current temperature when requested. temperatureService.getCharacteristic(this.hap.Characteristic.CurrentTemperature)?.onGet(() => { const value = this.getTemperature(); return value < 0 ? 0 : value; }); // Update the sensor. const value = this.getTemperature(); temperatureService.updateCharacteristic(this.hap.Characteristic.CurrentTemperature, value < 0 ? 0 : value); // Update the state characteristics. this.configureStateCharacteristics(temperatureService); return true; } // Configure the active connection status in HomeKit. private configureActiveStatus(service: Service): boolean { const device = this.accessory.context.device as ProtectSensorConfig; // Retrieve the current connection status when requested. service.getCharacteristic(this.hap.Characteristic.StatusActive)?.onGet(() => { return (this.accessory.context.device as ProtectSensorConfig).state === "CONNECTED"; }); // Update the current connection status. service.updateCharacteristic(this.hap.Characteristic.StatusActive, device.state === "CONNECTED"); return true; } // Configure the battery status in HomeKit. private configureBatteryStatus(service: Service): boolean { const device = this.accessory.context.device as ProtectSensorConfig; // Retrieve the current battery status when requested. service.getCharacteristic(this.hap.Characteristic.StatusLowBattery)?.onGet(() => { return (this.accessory.context.device as ProtectSensorConfig).batteryStatus?.isLow; }); // Update the battery status. service.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, device.batteryStatus?.isLow); return true; } // Configure the tamper status in HomeKit. private configureTamperedStatus(service: Service): boolean { const device = this.accessory.context.device as ProtectSensorConfig; // Retrieve the current tamper status when requested. service.getCharacteristic(this.hap.Characteristic.StatusTampered)?.onGet(() => { return (this.accessory.context.device as ProtectSensorConfig).tamperingDetectedAt !== null; }); // Update the tamper status. service.updateCharacteristic(this.hap.Characteristic.StatusTampered, device.tamperingDetectedAt !== null); return true; } // Configure the additional state characteristics in HomeKit. private configureStateCharacteristics(service: Service): boolean { // Update the active connection status. this.configureActiveStatus(service); // Update the battery status. this.configureBatteryStatus(service); // Update the tamper status. this.configureTamperedStatus(service); return true; } // Get the current alarm sound information. private getAlarmSound(): boolean { // Return true if we are not null, meaning the alarm has sounded. const value = (this.accessory.context.device as ProtectSensorConfig).alarmTriggeredAt !== null; // Save the state change and publish to MQTT. if(value !== this.savedAlarmSound) { this.savedAlarmSound = value; this.nvr.mqtt?.publish(this.accessory, "alarmsound", value.toString()); } return value; } // Get the current ambient light information. private getAmbientLight(): number { return (this.accessory.context.device as ProtectSensorConfig).stats.light.value ?? -1; } // Get the current contact sensor information. private getContact(): boolean { // Return true if we are open. const value = (this.accessory.context.device as ProtectSensorConfig).isOpened; // Save the state change and publish to MQTT. if(value !== this.savedContact) { this.savedContact = value; this.nvr.mqtt?.publish(this.accessory, "contact", value.toString()); } return value; } // Get the current humidity information. private getHumidity(): number { return (this.accessory.context.device as ProtectSensorConfig).stats.humidity.value ?? -1; } // Get the current temperature information. private getTemperature(): number { return (this.accessory.context.device as ProtectSensorConfig).stats.temperature.value ?? -1; } // Configure MQTT capabilities for sensors. private configureMqtt(): void { if(!this.nvrApi.bootstrap?.nvr.mac) { return; } this.nvr.mqtt?.subscribeGet(this.accessory, this.name(), "alarmsound", "Alarm sound", () => { return this.getAlarmSound().toString(); }); this.nvr.mqtt?.subscribeGet(this.accessory, this.name(), "ambientlight", "Ambient light", () => { return this.getAmbientLight().toString(); }); this.nvr.mqtt?.subscribeGet(this.accessory, this.name(), "contact", "Contact sensor", () => { return this.getContact().toString(); }); this.nvr.mqtt?.subscribeGet(this.accessory, this.name(), "humidity", "Humidity", () => { return this.getHumidity().toString(); }); this.nvr.mqtt?.subscribeGet(this.accessory, this.name(), "temperature", "Temperature", () => { return this.getTemperature().toString(); }); } }
the_stack
import Format = Fayde.Localization.Format; export function load() { QUnit.module("Format"); function ft(format: string, num: number, expected: string) { strictEqual(Format(format, num), expected); } function fdt(format: string, dt: DateTime, expected: string) { strictEqual(Format(format, dt), expected); } function ftt(format: string, ts: TimeSpan, expected: string) { strictEqual(Format(format, ts), expected); } function testCustomTimeSpan(msg: string, ts: TimeSpan, format: string, expected: string) { strictEqual(Format(format, ts), expected, msg); } function testCustomDateTime(dt: DateTime, format: string, expected: string) { strictEqual(Format(format, dt), expected, format); } var dt = new DateTime(2014, 4, 10, 8, 37, 46, 0, DateTimeKind.Local); test("DateTime: Short date", () => { fdt("{0:d}", dt, "4/10/2014"); }); test("DateTime: Long date", () => { fdt("{0:D}", dt, "Thursday, April 10, 2014"); }); test("DateTime: Full date/time (short time)", () => { fdt("{0:f}", dt, "Thursday, April 10, 2014 8:37 AM"); }); test("DateTime: Full date/time (long time)", () => { fdt("{0:F}", dt, "Thursday, April 10, 2014 8:37:46 AM"); }); test("DateTime: General date/time (short time)", () => { fdt("{0:g}", dt, "4/10/2014 8:37 AM"); }); test("DateTime: General date/time (long time)", () => { fdt("{0:G}", dt, "4/10/2014 8:37:46 AM"); }); test("DateTime: Month/day", () => { fdt("{0:m}", dt, "April 10"); fdt("{0:M}", dt, "April 10"); }); var dt2 = new DateTime(2014, 4, 10, 12, 37, 46, 0, DateTimeKind.Utc); test("DateTime: RFC123", () => { fdt("{0:r}", dt2, "Thu, 10 Apr 2014 12:37:46 GMT"); fdt("{0:R}", dt2, "Thu, 10 Apr 2014 12:37:46 GMT"); }); test("DateTime: Sortable date/time", () => { fdt("{0:s}", dt, "2014-04-10T08:37:46"); }); test("DateTime: Short time", () => { fdt("{0:t}", dt, "8:37 AM"); }); test("DateTime: Long time", () => { fdt("{0:T}", dt, "8:37:46 AM"); }); test("DateTime: Universal sortable date/time", () => { fdt("{0:u}", dt, "2014-04-10 08:37:46Z"); }); test("DateTime: Universal full date/time", () => { fdt("{0:U}", dt, "Thursday, April 10, 2014 8:37:46 AM"); }); test("DateTime: Year month", () => { fdt("{0:y}", dt, "April, 2014"); fdt("{0:Y}", dt, "April, 2014"); }); test("DateTime: Custom", () => { var dt1 = new DateTime(2014, 1, 1, 5, 1, 2); var dt2 = new DateTime(2014, 1, 15, 15, 16, 17); testCustomDateTime(dt1, "{0:%d}", "1"); testCustomDateTime(dt2, "{0:%d}", "15"); testCustomDateTime(dt1, "{0:dd}", "01"); testCustomDateTime(dt2, "{0:dd}", "15"); testCustomDateTime(dt1, "{0:ddd}", "Wed"); testCustomDateTime(dt1, "{0:dddd}", "Wednesday"); testCustomDateTime(dt1, "{0:%M}", "1"); testCustomDateTime(dt1, "{0:MM}", "01"); testCustomDateTime(dt1, "{0:MMM}", "Jan"); testCustomDateTime(dt1, "{0:MMMM}", "January"); var dt3 = new DateTime(2009, 1, 1); var dt4 = new DateTime(900, 1, 1); testCustomDateTime(dt1, "{0:%y}", "14"); testCustomDateTime(dt3, "{0:%y}", "9"); testCustomDateTime(dt1, "{0:yy}", "14"); testCustomDateTime(dt3, "{0:yy}", "09"); testCustomDateTime(dt4, "{0:yyy}", "900"); testCustomDateTime(dt3, "{0:yyy}", "2009"); testCustomDateTime(dt4, "{0:yyyy}", "0900"); testCustomDateTime(dt3, "{0:yyyy}", "2009"); testCustomDateTime(dt1, "{0:%t}", "A"); testCustomDateTime(dt2, "{0:%t}", "P"); testCustomDateTime(dt1, "{0:tt}", "AM"); testCustomDateTime(dt2, "{0:tt}", "PM"); testCustomDateTime(dt2, "{0:h}", "3"); testCustomDateTime(dt2, "{0:hh}", "03"); testCustomDateTime(dt2, "{0:H}", "15"); testCustomDateTime(dt2, "{0:HH}", "15"); testCustomDateTime(dt1, "{0:%m}", "1"); testCustomDateTime(dt2, "{0:%m}", "16"); testCustomDateTime(dt1, "{0:mm}", "01"); testCustomDateTime(dt2, "{0:mm}", "16"); testCustomDateTime(dt1, "{0:%s}", "2"); testCustomDateTime(dt2, "{0:%s}", "17"); testCustomDateTime(dt1, "{0:ss}", "02"); testCustomDateTime(dt2, "{0:ss}", "17"); var dt5 = new DateTime(0, 0, 0, 0, 0, 0, 123); testCustomDateTime(dt5, "{0:%f}", "1"); testCustomDateTime(dt5, "{0:ff}", "12"); testCustomDateTime(dt5, "{0:fff}", "123"); testCustomDateTime(dt5, "{0:ffff}", "1230"); testCustomDateTime(dt5, "{0:fffff}", "12300"); testCustomDateTime(dt5, "{0:ffffff}", "123000"); testCustomDateTime(dt5, "{0:fffffff}", "1230000"); testCustomDateTime(dt5, "{0:%F}", "1"); testCustomDateTime(dt5, "{0:FF}", "12"); testCustomDateTime(dt5, "{0:FFF}", "123"); testCustomDateTime(dt5, "{0:FFFF}", "123"); testCustomDateTime(dt5, "{0:FFFFF}", "123"); testCustomDateTime(dt5, "{0:FFFFFF}", "123"); testCustomDateTime(dt5, "{0:FFFFFFF}", "123"); /* testCustomDateTime(dt1, "{0:z}", "-4"); testCustomDateTime(dt1, "{0:zz}", "-04"); testCustomDateTime(dt1, "{0:zzz}", "-04:00"); testCustomDateTime(dt1, "{0:K}", ""); testCustomDateTime(dt1, "{0:g}", "A.D."); testCustomDateTime(dt1, "{0:gg}", "A.D."); */ }); test("DateTime: Edge #1", () => { testCustomDateTime(new DateTime(2014, 4, 27), "{0: dd MMM yyyy }", " 27 Apr 2014 "); testCustomDateTime(new DateTime(0, 0, 0, 10, 30, 45), "{0: HH:mm:ss}", " 10:30:45"); }); test("TimeSpan: Constant", () => { ftt("{0:c}", TimeSpan.Zero, "00:00:00"); ftt("{0:c}", new TimeSpan(0, 0, 30, 0), "00:30:00"); ftt("{0:c}", new TimeSpan(0, 0, -30, 0), "-00:30:00"); ftt("{0:c}", new TimeSpan(3, 17, 25, 30, 500), "3.17:25:30.5000000"); }); test("TimeSpan: General short", () => { ftt("{0:g}", new TimeSpan(1, 3, 16, 50, 500), "1:3:16:50.5"); ftt("{0:g}", new TimeSpan(-1, -3, -16, -50, -500), "-1:3:16:50.5"); ftt("{0:g}", new TimeSpan(1, 3, 16, 50, 599), "1:3:16:50.599"); }); test("TimeSpan: General long", () => { ftt("{0:G}", new TimeSpan(18, 30, 0), "0:18:30:00.0000000"); ftt("{0:G}", new TimeSpan(-18, -30, 0), "-0:18:30:00.0000000"); }); test("TimeSpan: Custom", () => { var ts1 = new TimeSpan(6, 14, 32, 17, 685); var ts2 = new TimeSpan(6, 8, 32, 17, 685); var ts3 = new TimeSpan(6, 14, 8, 17, 685); var ts4 = new TimeSpan(6, 8, 5, 17, 685); testCustomTimeSpan("d,%d", ts1, "{0:%d}", "6"); testCustomTimeSpan("d,%d", ts1, "{0:d\\.hh\\:mm}", "6.14:32"); testCustomTimeSpan("dd-dddddddd", ts1, "{0:ddd}", "006"); testCustomTimeSpan("dd-dddddddd", ts1, "{0:dd\\.hh\\:mm}", "06.14:32"); testCustomTimeSpan("h,%h", ts1, "{0:%h}", "14"); testCustomTimeSpan("h,%h", ts1, "{0:hh\\:mm}", "14:32"); testCustomTimeSpan("hh", ts1, "{0:hh}", "14"); testCustomTimeSpan("hh", ts2, "{0:hh}", "08"); testCustomTimeSpan("m,%m", ts3, "{0:%m}", "8"); testCustomTimeSpan("m,%m", ts3, "{0:h\\:m}", "14:8"); testCustomTimeSpan("mm", ts3, "{0:mm}", "08"); testCustomTimeSpan("mm", ts4, "{0:d\\.hh\\:mm\\:ss}", "6.08:05:17"); var ts5 = new TimeSpan(0, 0, 0, 12, 965); testCustomTimeSpan("s,%s", ts5, "{0:%s}", "12"); testCustomTimeSpan("s,%s", ts5, "{0:s\\.fff}", "12.965"); var ts6 = new TimeSpan(0, 0, 0, 6, 965); testCustomTimeSpan("ss", ts6, "{0:ss}", "06"); testCustomTimeSpan("ss", ts6, "{0:ss\\.fff}", "06.965"); var ts7 = new TimeSpan(0, 0, 0, 6, 895); testCustomTimeSpan("f,%f", ts7, "{0:f}", "8"); testCustomTimeSpan("f,%f", ts7, "{0:ss\\.f}", "06.8"); testCustomTimeSpan("ff", ts7, "{0:ff}", "89"); testCustomTimeSpan("ff", ts7, "{0:ss\\.ff}", "06.89"); testCustomTimeSpan("fff", ts7, "{0:fff}", "895"); testCustomTimeSpan("fff", ts7, "{0:ss\\.fff}", "06.895"); testCustomTimeSpan("ffff", ts7, "{0:ffff}", "8950"); testCustomTimeSpan("ffff", ts7, "{0:ss\\.ffff}", "06.8950"); testCustomTimeSpan("F,%F", ts7, "{0:%F}", "8"); testCustomTimeSpan("F,%F", ts7, "{0:ss\\.F}", "06.8"); testCustomTimeSpan("FF", ts7, "{0:FF}", "89"); testCustomTimeSpan("FF", ts7, "{0:ss\\.FF}", "06.89"); testCustomTimeSpan("FFF", ts7, "{0:FFF}", "895"); testCustomTimeSpan("FFF", ts7, "{0:ss\\.FFF}", "06.895"); testCustomTimeSpan("FFFF", ts7, "{0:FFFF}", "895"); testCustomTimeSpan("FFFF", ts7, "{0:ss\\.FFFF}", "06.895"); }); test("Number: Currency", () => { ft("{0:c}", 123.456, "$123.46"); ft("{0:C}", 123.456, "$123.46"); ft("{0:c3}", 123.456, "$123.456"); ft("{0:C3}", 123.456, "$123.456"); ft("{0:c3}", -123.456, "($123.456)"); ft("{0:C3}", -123.456, "($123.456)"); }); test("Number: Decimal", () => { ft("{0:d}", 1234, "1234"); ft("{0:D}", 1234, "1234"); ft("{0:d}", -1234, "-1234"); ft("{0:D}", -1234, "-1234"); ft("{0:d6}", -1234, "-001234"); ft("{0:D6}", -1234, "-001234"); }); test("Number: Exponential", () => { ft("{0:e}", 1052.0329112756, "1.052033e+003"); ft("{0:E}", 1052.0329112756, "1.052033E+003"); ft("{0:e}", -1052.0329112756, "-1.052033e+003"); ft("{0:E}", -1052.0329112756, "-1.052033E+003"); ft("{0:e2}", -1052.0329112756, "-1.05e+003"); ft("{0:E2}", -1052.0329112756, "-1.05E+003"); }); test("Number: Fixed-point", () => { ft("{0:f}", 1234.567, "1234.57"); ft("{0:F}", 1234.567, "1234.57"); ft("{0:f1}", 1234, "1234.0"); ft("{0:F1}", 1234, "1234.0"); ft("{0:f4}", -1234.56, "-1234.5600"); ft("{0:F4}", -1234.56, "-1234.5600"); }); test("Number: General", () => { ft("{0:g}", -123.456, "-123.456"); ft("{0:G}", -123.456, "-123.456"); ft("{0:g4}", 123.4546, "123.5"); ft("{0:G4}", 123.4546, "123.5"); }); test("Number: Number", () => { ft("{0:n}", 1234.567, "1,234.57"); ft("{0:N}", 1234.567, "1,234.57"); ft("{0:n1}", 1234, "1,234.0"); ft("{0:N1}", 1234, "1,234.0"); ft("{0:n3}", -1234.56, "-1,234.560"); ft("{0:N3}", -1234.56, "-1,234.560"); }); test("Number: Percent", () => { ft("{0:p}", 1, "100.00 %"); ft("{0:P}", 1, "100.00 %"); ft("{0:p0}", 0.39678, "40 %"); ft("{0:P0}", 0.39678, "40 %"); ft("{0:p1}", -0.39678, "-39.7 %"); ft("{0:P1}", -0.39678, "-39.7 %"); }); test("Number: Hexadecimal", () => { ft("{0:x}", -1, "ff"); ft("{0:X}", -1, "FF"); ft("{0:x}", 255, "ff"); ft("{0:X}", 255, "FF"); ft("{0:x4}", 255, "00ff"); ft("{0:X4}", 255, "00FF"); ft("{0:x4}", -1, "ffff"); ft("{0:X4}", -1, "FFFF"); }); test("Interpolation", () => { var interp = Fayde.Localization.Format("Testing {0} {1} {2}", 1, 2, 3); strictEqual(interp, "Testing 1 2 3"); }); }
the_stack
import React, { useEffect, useState, useCallback, useRef, useLayoutEffect, } from 'react' import { animated, useSpring } from 'react-spring' import styled, { css } from 'styled-components' import { useDebounceAnimationState } from '../../foundation/hooks' import { passiveEvents, isEdge } from '../../foundation/support' import CarouselButton, { Direction } from '../CarouselButton' export const GRADIENT_WIDTH = 72 /** * カルーセル系のスクロール量の定数 * * @example * const scrollAmount = containerElm.clientWidth * SCROLL_AMOUNT_COEF */ export const SCROLL_AMOUNT_COEF = 0.75 interface ScrollProps { align?: 'center' | 'left' | 'right' offset?: number } export interface CarouselBaseAppearanceProps { buttonOffset?: number buttonPadding?: number bottomOffset?: number defaultScroll?: ScrollProps } export type CarouselGradientProps = | { hasGradient?: false } | { hasGradient: true fadeInGradient?: boolean } type CarouselAppearanceProps = CarouselBaseAppearanceProps & CarouselGradientProps type Props = CarouselAppearanceProps & { onScroll?: (left: number) => void onResize?: (width: number) => void children: React.ReactNode centerItems?: boolean onScrollStateChange?: (canScroll: boolean) => void } export interface CarouselHandlerRef { resetScroll(): void } export default function Carousel({ buttonOffset = 0, buttonPadding = 16, bottomOffset = 0, defaultScroll: { align = 'left', offset: scrollOffset = 0 } = {}, onScroll, onResize, children, centerItems, onScrollStateChange, ...options }: Props) { // スクロール位置を保存する // アニメーション中の場合は、アニメーション終了時のスクロール位置が保存される const [scrollLeft, setScrollLeft] = useDebounceAnimationState(0) // アニメーション中かどうか const animation = useRef(false) // スクロール可能な領域を保存する const [maxScrollLeft, setMaxScrollLeft] = useState(0) // 左右のボタンの表示状態を保存する const [leftShow, setLeftShow] = useState(false) const [rightShow, setRightShow] = useState(false) // const [props, set, stop] = useSpring(() => ({ // scroll: 0 // })) const [styles, set] = useSpring(() => ({ scroll: 0 })) const ref = useRef<HTMLDivElement>(null) const innerRef = useRef<HTMLUListElement>(null) const handleRight = useCallback(() => { if (ref.current === null) { return } const { clientWidth } = ref.current // スクロール領域を超えないように、アニメーションを開始 // アニメーション中にアニメーションが開始されたときに、アニメーション終了予定の位置から再度計算するようにする const scroll = Math.min( scrollLeft + clientWidth * SCROLL_AMOUNT_COEF, maxScrollLeft ) setScrollLeft(scroll, true) set({ scroll, from: { scroll: scrollLeft }, reset: !animation.current }) animation.current = true }, [animation, maxScrollLeft, scrollLeft, set, setScrollLeft]) const handleLeft = useCallback(() => { if (ref.current === null) { return } const { clientWidth } = ref.current const scroll = Math.max(scrollLeft - clientWidth * SCROLL_AMOUNT_COEF, 0) setScrollLeft(scroll, true) set({ scroll, from: { scroll: scrollLeft }, reset: !animation.current }) animation.current = true }, [animation, scrollLeft, set, setScrollLeft]) // スクロール可能な場合にボタンを表示する // scrollLeftが変化したときに処理する (アニメーション開始時 & 手動スクロール時) useEffect(() => { const newleftShow = scrollLeft > 0 const newrightShow = scrollLeft < maxScrollLeft && maxScrollLeft > 0 if (newleftShow !== leftShow || newrightShow !== rightShow) { setLeftShow(newleftShow) setRightShow(newrightShow) onScrollStateChange?.(newleftShow || newrightShow) } }, [leftShow, maxScrollLeft, onScrollStateChange, rightShow, scrollLeft]) const handleScroll = useCallback(() => { if (ref.current === null) { return } // 手動でスクロールが開始されたときにアニメーションを中断 if (animation.current) { styles.scroll.stop() animation.current = false } // スクロール位置を保存 (アニメーションの基準になる) const manualScrollLeft = ref.current.scrollLeft // 過剰にsetStateが走らないようにDebouceする setScrollLeft(manualScrollLeft) }, [animation, setScrollLeft, styles]) // リサイズが起きたときに、アニメーション用のスクロール領域 & ボタンの表示状態 を再計算する const handleResize = useCallback(() => { if (ref.current === null) { return } const { clientWidth, scrollWidth } = ref.current const newMaxScrollLeft = scrollWidth - clientWidth setMaxScrollLeft(newMaxScrollLeft) if (onResize) { onResize(clientWidth) } }, [onResize]) const resizeObserverRef = useRef(new ResizeObserver(handleResize)) const resizeObserverInnerRef = useRef(new ResizeObserver(handleResize)) useLayoutEffect(() => { const elm = ref.current const innerElm = innerRef.current if (elm === null || innerElm === null) { return } elm.addEventListener( 'wheel', handleScroll, passiveEvents() && { passive: true } ) const resizeObserver = resizeObserverRef.current resizeObserver.observe(elm) const resizeObserverInner = resizeObserverInnerRef.current resizeObserverInner.observe(innerElm) return () => { elm.removeEventListener('wheel', handleScroll) resizeObserver.disconnect() resizeObserverInner.disconnect() } }, [handleResize, handleScroll]) // 初期スクロールを行う useLayoutEffect(() => { if (align !== 'left' || scrollOffset !== 0) { const scroll = ref.current if (scroll !== null) { const scrollLength = Math.max( 0, Math.min( align === 'left' && scrollOffset > 0 ? scrollOffset : align === 'center' ? maxScrollLeft / 2 + scrollOffset : align === 'right' && scrollOffset <= maxScrollLeft ? maxScrollLeft - scrollOffset / 2 : 0, maxScrollLeft ) ) scroll.scrollLeft = scrollLength setScrollLeft(scrollLength, true) } } // eslint-disable-next-line react-hooks/exhaustive-deps }, [ref.current]) const handleScrollMove = useCallback(() => { if (ref.current === null) { return } if (onScroll) { onScroll(ref.current.scrollLeft) } }, [onScroll]) // NOTE: Edgeではmaskを使うと要素のレンダリングがバグる(場合によっては画像が表示されない)のでグラデーションを無効にする if (!isEdge && options.hasGradient === true) { const fadeInGradient = options.fadeInGradient ?? false const overflowGradient = !fadeInGradient return ( <Container> <GradientContainer fadeInGradient={fadeInGradient}> <RightGradient> <LeftGradient show={overflowGradient || scrollLeft > 0}> <ScrollArea ref={ref} scrollLeft={styles.scroll} onScroll={handleScrollMove} > <CarouselContainer ref={innerRef} centerItems={centerItems}> {children} </CarouselContainer> </ScrollArea> </LeftGradient> </RightGradient> </GradientContainer> <ButtonsContainer> <CarouselButton direction={Direction.Left} show={leftShow} offset={buttonOffset} bottomOffset={bottomOffset} padding={buttonPadding} gradient={overflowGradient} onClick={handleLeft} /> <CarouselButton direction={Direction.Right} show={rightShow} offset={buttonOffset} bottomOffset={bottomOffset} padding={buttonPadding} gradient onClick={handleRight} /> </ButtonsContainer> </Container> ) } return ( <Container> <ScrollArea // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error ref={ref} scrollLeft={styles.scroll} onScroll={handleScrollMove} > <CarouselContainer ref={innerRef} centerItems={centerItems}> {children} </CarouselContainer> </ScrollArea> <ButtonsContainer> <CarouselButton direction={Direction.Left} show={leftShow} offset={buttonOffset} bottomOffset={bottomOffset} padding={buttonPadding} onClick={handleLeft} /> <CarouselButton direction={Direction.Right} show={rightShow} offset={buttonOffset} bottomOffset={bottomOffset} padding={buttonPadding} onClick={handleRight} /> </ButtonsContainer> </Container> ) } const CarouselContainer = styled.ul<{ centerItems?: boolean }>` vertical-align: top; overflow: hidden; list-style: none; padding: 0; /* 最小幅を100%にして親要素にぴったりくっつけることで子要素で要素を均等に割り付けるなどを出来るようにしてある */ min-width: 100%; box-sizing: border-box; ${({ centerItems = false }) => centerItems ? css` display: flex; width: max-content; margin: 0 auto; ` : css` display: inline-flex; margin: 0; `} ` const ButtonsContainer = styled.div` opacity: 0; transition: 0.4s opacity; ` const Container = styled.div` &:hover ${ButtonsContainer} { opacity: 1; } /* CarouselButtonの中にz-index:1があるのでここでコンテキストを切る */ position: relative; z-index: 0; ` const ScrollArea = styled(animated.div)` overflow-x: auto; padding: 0; margin: 0; &::-webkit-scrollbar { display: none; } scrollbar-width: none; ` const GradientContainer = styled.div<{ fadeInGradient: boolean }>` /* NOTE: LeftGradientがはみ出るためhidden */ overflow: hidden; ${(p) => !p.fadeInGradient && css` margin-left: ${-GRADIENT_WIDTH}px; ${CarouselContainer} { padding-left: ${GRADIENT_WIDTH}px; } `} margin-right: ${-GRADIENT_WIDTH}px; /* stylelint-disable-next-line no-duplicate-selectors */ ${CarouselContainer} { padding-right: ${GRADIENT_WIDTH}px; } ` const RightGradient = styled.div` mask-image: linear-gradient( to right, #000 calc(100% - ${GRADIENT_WIDTH}px), transparent ); ` const LeftGradient = styled.div<{ show: boolean }>` /* NOTE: mask-position が left → negative px の時、right → abs(negative px) の位置に表示されるため */ margin-right: ${-GRADIENT_WIDTH}px; padding-right: ${GRADIENT_WIDTH}px; /* NOTE: mask-position に transition をつけたいが vender prefixes 対策で all につける */ transition: 0.2s all ease-in; mask: linear-gradient(to right, transparent, #000 ${GRADIENT_WIDTH}px) ${(p) => (p.show ? 0 : -GRADIENT_WIDTH)}px 0; `
the_stack
import { AddPropertyCallback, CacheItem, ClassName, CSS, EngineOptions, FontFace, GenericProperties, Import, Keyframes, Properties, Property, RenderOptions, RenderResult, RenderResultVariant, Rule, RuleMap, RuleWithoutVariants, Value, VariablesMap, } from '@aesthetic/types'; import { arrayLoop, generateHash, isObject, joinQueries, objectLoop, objectReduce, } from '@aesthetic/utils'; import { StyleEngine } from '../types'; import { createCacheKey, createCacheManager } from './cache'; import { VARIANT_COMBO_PATTERN } from './constants'; import { isAtRule, isNestedSelector, isValidValue } from './helpers'; import { createDeclaration, createDeclarationBlock, formatDeclaration, formatFontFace, formatImport, formatProperty, formatRule, formatVariable, formatVariableBlock, } from './syntax'; type RenderCallback = ( styleEngine: StyleEngine, rule: Rule, opts: RenderOptions, ) => RenderResult<ClassName>; const CHARS = 'abcdefghijklmnopqrstuvwxyz'; const CHARS_LENGTH = CHARS.length; function generateClassName(key: string, options: RenderOptions, engine: StyleEngine): ClassName { // Avoid hashes that start with an invalid number if (options.deterministic) { return `c${generateHash(key)}`; } engine.nameIndex += 1; const index = engine.nameIndex; if (index < CHARS_LENGTH) { return CHARS[index]; } return CHARS[index % CHARS_LENGTH] + String(Math.floor(index / CHARS_LENGTH)); } function insertAtRule( cacheKey: string, rule: CSS, options: RenderOptions, engine: StyleEngine, ): CacheItem<ClassName> { const { cacheManager, sheetManager } = engine; let item = cacheManager.read(cacheKey); if (!item) { engine.ruleCount += 1; item = { result: '' }; sheetManager.insertRule(rule, { ...options, type: 'global' }); cacheManager.write(cacheKey, item); } return item; } function insertStyles( cacheKey: string, render: (className: ClassName) => CSS, options: RenderOptions, engine: StyleEngine, minimumRank?: number, ): CacheItem<ClassName> { const { cacheManager, sheetManager, vendorPrefixer } = engine; let item = cacheManager.read(cacheKey, minimumRank); if (!item) { engine.ruleCount += 1; // Generate class name and format CSS rule with class name const className = options.className ?? generateClassName(cacheKey, options, engine); const css = render(className); // Insert rule and return a rank (insert index) const rank = sheetManager.insertRule( options.selector && options.vendor && vendorPrefixer ? vendorPrefixer.prefixSelector(options.selector, css) : css, options, ); // Cache the results for subsequent performance item = { rank, result: className }; cacheManager.write(cacheKey, item); } return item; } function renderProperty<K extends Property>( engine: StyleEngine, property: K, value: NonNullable<Properties[K]>, options: RenderOptions, ): ClassName { const key = formatProperty(property); const { rankings } = options; const { result, rank } = insertStyles( createCacheKey(key, value, options), (name) => formatRule(name, createDeclaration(key, value, options, engine), options), options, engine, rankings?.[key], ); // Persist the rank for specificity guarantees if (rankings && rank !== undefined && (rankings[key] === undefined || rank > rankings[key])) { rankings[key] = rank; } return result; } function renderDeclaration<K extends Property>( engine: StyleEngine, property: K, value: NonNullable<Properties[K]>, options: RenderOptions, ): ClassName { const { customProperties } = engine; let className = ''; const handler: AddPropertyCallback = (prop, val) => { if (isValidValue(prop, val)) { className += renderProperty(engine, prop, val, options) + ' '; } }; if (customProperties && property in customProperties) { // @ts-expect-error Value is a complex union customProperties[property](value, handler, engine); } else { handler(property, value); } return className.trim(); } function renderFontFace(engine: StyleEngine, fontFace: FontFace, options: RenderOptions): string { let name = fontFace.fontFamily; let block = createDeclarationBlock( formatFontFace(fontFace) as GenericProperties, options, engine, ); if (!name) { name = `ff${generateHash(block)}`; block += formatDeclaration('font-family', name); } insertAtRule( createCacheKey('@font-face', name, options), `@font-face { ${block} }`, options, engine, ); return name; } function renderImport(engine: StyleEngine, value: Import | string, options: RenderOptions): string { const path = formatImport(value); insertAtRule(createCacheKey('@import', path, options), `@import ${path};`, options, engine); return path; } function renderKeyframes( engine: StyleEngine, keyframes: Keyframes, animationName: string, options: RenderOptions, ): string { const block = objectReduce( keyframes, (keyframe, step) => `${step} { ${createDeclarationBlock(keyframe as GenericProperties, options, engine)} } `, ); const name = animationName || `kf${generateHash(block)}`; insertAtRule( createCacheKey('@keyframes', name, options), `@keyframes ${name} { ${block} }`, options, engine, ); return name; } function renderVariable( engine: StyleEngine, name: string, value: Value, options: RenderOptions, ): ClassName { const key = formatVariable(name); return insertStyles( createCacheKey(key, value, options), (className) => formatRule(className, formatDeclaration(key, value), options), options, engine, ).result; } // It's much faster to set and unset options (conditions and selector) than it is // to spread and clone the options object. Since rendering is synchronous, it just works! function renderAtRules( engine: StyleEngine, rule: Rule, options: RenderOptions, render: RenderCallback, ): RenderResult<ClassName> { const { className: originalClassName, media: originalMedia, selector: originalSelector, supports: originalSupports, } = options; const variants: RenderResultVariant<ClassName>[] = []; let className = ''; objectLoop(rule['@media'], (condition, query) => { options.media = joinQueries(options.media, query); className += render(engine, condition, options).result + ' '; options.media = originalMedia; }); objectLoop(rule['@selectors'], (nestedRule, selectorGroup) => { arrayLoop(selectorGroup.split(','), (selector) => { if (originalSelector === undefined) { options.selector = ''; } // eslint-disable-next-line @typescript-eslint/restrict-plus-operands options.selector += selector.trim(); className += render(engine, nestedRule, options).result + ' '; options.selector = originalSelector; }); }); objectLoop(rule['@supports'], (condition, query) => { options.supports = joinQueries(options.supports, query); className += render(engine, condition, options).result + ' '; options.supports = originalSupports; }); objectLoop(rule['@variables'], (value, name) => { className += renderVariable(engine, formatVariable(name), value, options) + ' '; }); objectLoop(rule['@variants'], (nestedRule, variant) => { if (__DEV__ && !VARIANT_COMBO_PATTERN.test(variant)) { throw new Error( `Invalid variant "${variant}". Type and enumeration must be separated with a ":", and each part may only contain a-z, 0-9, -, _.`, ); } options.className = undefined; variants.push({ result: render(engine, nestedRule, options).result, types: variant.split('+').map((v) => v.trim()), }); options.className = originalClassName; }); return { result: className.trim(), variants, }; } function renderRule( engine: StyleEngine, rule: Rule, options: RenderOptions, ): RenderResult<ClassName> { let className = ''; objectLoop(rule, (value, property) => { if (isObject<Rule>(value)) { if (isNestedSelector(property)) { (rule['@selectors'] ||= {})[property] = value; } else if (!isAtRule(property) && __DEV__) { console.warn(`Unknown property selector or nested block "${property}".`); } } else if (isValidValue(property, value)) { className += renderDeclaration(engine, property as Property, value, options) + ' '; } }); // Render at-rules last to somewhat ensure specificity const atResult = renderAtRules(engine, rule, options, renderRule); return { result: (className + atResult.result).trim(), variants: atResult.variants, }; } function renderRuleGrouped( engine: StyleEngine, rule: Rule, options: RenderOptions, ): RenderResult<ClassName> { const atRules: Rule = {}; let variables: CSS = ''; let properties: CSS = ''; // Extract all nested rules first as we need to process them *after* properties objectLoop(rule, (value, property) => { if (isObject(value)) { // Extract and include variables in the top level class if (property === '@variables') { variables += formatVariableBlock(value as VariablesMap); // Extract all other at-rules } else if (isAtRule(property)) { atRules[property] = value as RuleMap; // Merge local selectors into the selectors at-rule } else if (isNestedSelector(property)) { (atRules['@selectors'] ||= {})[property] = value as RuleWithoutVariants; // Log for invalid value } else if (__DEV__) { console.warn(`Unknown property selector or nested block "${property}".`); } } else if (isValidValue(property, value)) { properties += createDeclaration(property, value, options, engine); } }); // Always use deterministic classes for grouped rules options.deterministic = true; // Insert rule styles only once const block = variables + properties; const { result } = insertStyles( createCacheKey(block, '', options), (name) => formatRule(name, block, options), options, engine, ); // Render all at/nested rules with the parent class name options.className = result; const { variants } = renderAtRules(engine, atRules, options, renderRuleGrouped); return { result: result.trim(), variants, }; } const noop = () => {}; export function createStyleEngine(engineOptions: EngineOptions<ClassName>): StyleEngine { const renderOptions = {}; const engine: StyleEngine = { cacheManager: createCacheManager(), direction: 'ltr', name: 'style', nameIndex: -1, ruleCount: -1, ...engineOptions, prefersColorScheme: () => false, prefersContrastLevel: () => false, renderDeclaration: (property, value, options = renderOptions) => renderDeclaration(engine, property, value, options), renderFontFace: (fontFace, options = renderOptions) => renderFontFace(engine, fontFace, options), renderImport: (path, options = renderOptions) => renderImport(engine, path, options), renderKeyframes: (keyframes, animationName = '', options = renderOptions) => renderKeyframes(engine, keyframes, animationName, options), renderRule: (rule, options = renderOptions) => renderRule(engine, rule, options), renderRuleGrouped: (rule, options = renderOptions) => renderRuleGrouped(engine, rule, options), renderVariable: (name, value, options = renderOptions) => renderVariable(engine, name, value, options), setDirection: noop, setRootVariables: noop, setTheme: noop, }; return engine; }
the_stack
import {CoreMath} from '../../../core/math/_Module'; import {Camera} from 'three/src/cameras/Camera'; import {CoreDomUtils} from '../../../core/DomUtils'; import {Euler} from 'three/src/math/Euler'; import {Vector2} from 'three/src/math/Vector2'; import {Vector3} from 'three/src/math/Vector3'; import {BaseCollisionHandler} from './BaseCollisionHandler'; interface TranslationData { direction: {x: number; y: number}; } interface RotationData { direction: {x: number; y: number}; } interface RotationRange { min: number; max: number; } // const VIEWER_CALLBACK_NAME = 'mobile-nav'; interface MobileJoystickControlsDefaultParams { rotationSpeed: number; rotationRange: RotationRange; translationSpeed: number; } export const DEFAULT_PARAMS: MobileJoystickControlsDefaultParams = { rotationSpeed: 1, rotationRange: {min: -Math.PI * 0.25, max: Math.PI * 0.25}, translationSpeed: 0.1, }; const EVENT_CHANGE = {type: 'change'}; export class MobileJoystickControls extends BaseCollisionHandler { private translationData: TranslationData = { direction: {x: 0, y: 0}, }; private rotationData: RotationData = { direction: {x: 0, y: 0}, }; private _boundMethods = { onRotateStart: this._onRotateStart.bind(this), onRotateMove: this._onRotateMove.bind(this), onRotateEnd: this._onRotateEnd.bind(this), onTranslateStart: this._onTranslateStart.bind(this), onTranslateMove: this._onTranslateMove.bind(this), onTranslateEnd: this._onTranslateEnd.bind(this), }; private _startCameraRotation = new Euler(); private _velocity = new Vector3(); // private _element: HTMLElement; // private _translationSpeed = 4; private _rotationSpeed = DEFAULT_PARAMS.rotationSpeed; private _rotationRange: RotationRange = { min: DEFAULT_PARAMS.rotationRange.min, max: DEFAULT_PARAMS.rotationRange.max, }; private _translationSpeed = DEFAULT_PARAMS.translationSpeed; constructor(private _camera: Camera, private domElement: HTMLElement) { super(); // this._element = this._viewer.domElement(); this._camera.rotation.order = 'ZYX'; // const clock = new Clock(); // this._viewer.registerOnBeforeRender(VIEWER_CALLBACK_NAME, () => { // const deltaTime = Math.min(0.1, clock.getDelta()); // this.update(deltaTime); // }); this._addEvents(); } dispose() { // this._viewer.unRegisterOnBeforeRender(VIEWER_CALLBACK_NAME); this._removeEvents(); } private _translateDomElement = this._createTranslateDomElement(); private _translateDomElementRect: DOMRect = this._translateDomElement.getBoundingClientRect(); private _createTranslateDomElement() { const element = document.createElement('div'); const rect = this.domElement.getBoundingClientRect(); const minDim = Math.min(rect.width, rect.height); const size = Math.round(0.4 * minDim); const margin = Math.round(0.1 * minDim); element.style.width = `${size}px`; element.style.height = element.style.width; element.style.border = '1px solid black'; element.style.borderRadius = `${size}px`; element.style.position = 'absolute'; element.style.bottom = `${margin}px`; element.style.left = `${margin}px`; return element; } private _addEvents() { CoreDomUtils.disableContextMenu(); this.domElement.addEventListener('touchstart', this._boundMethods.onRotateStart); this.domElement.addEventListener('touchmove', this._boundMethods.onRotateMove); this.domElement.addEventListener('touchend', this._boundMethods.onRotateEnd); this._translateDomElement.addEventListener('touchstart', this._boundMethods.onTranslateStart); this._translateDomElement.addEventListener('touchmove', this._boundMethods.onTranslateMove); this._translateDomElement.addEventListener('touchend', this._boundMethods.onTranslateEnd); this.domElement.parentElement?.append(this._translateDomElement); } private _removeEvents() { // TODO: ideally the viewer should know that // its element should have no context menu callback // if no mobile controls is attached. So the viewer should be in control // of re-establishing the event CoreDomUtils.reEstablishContextMenu(); this.domElement.removeEventListener('touchstart', this._boundMethods.onRotateStart); this.domElement.removeEventListener('touchmove', this._boundMethods.onRotateMove); this.domElement.removeEventListener('touchend', this._boundMethods.onRotateEnd); this._translateDomElement.removeEventListener('touchstart', this._boundMethods.onTranslateStart); this._translateDomElement.removeEventListener('touchmove', this._boundMethods.onTranslateMove); this._translateDomElement.removeEventListener('touchend', this._boundMethods.onTranslateEnd); this.domElement.parentElement?.removeChild(this._translateDomElement); } setRotationSpeed(speed: number) { this._rotationSpeed = speed; } setRotationRange(range: RotationRange) { this._rotationRange.min = range.min; this._rotationRange.max = range.max; } setTranslationSpeed(speed: number) { this._translationSpeed = speed; } // // // ROTATE // // private vLeft = new Vector3(); private vRight = new Vector3(); private vTop = new Vector3(); private vBottom = new Vector3(); private angleY = 0; private angleX = 0; private _rotationStartPosition = new Vector2(); private _rotationMovePosition = new Vector2(); private _rotationDelta = new Vector2(); private _onRotateStart(event: TouchEvent) { this._startCameraRotation.copy(this._camera.rotation); const touch = this._getTouch(event, this.domElement); if (!touch) { return; } this._rotationStartPosition.set(touch.clientX, touch.clientY); // x pan for rotation y this.vLeft.set(-1, 0, 0.5); this.vRight.set(1, 0, 0.5); [this.vLeft, this.vRight].forEach((v) => { v.unproject(this._camera); this._camera.worldToLocal(v); }); this.angleY = this.vLeft.angleTo(this.vRight); // y pan for rotation x this.vTop.set(0, 1, 0.5); this.vBottom.set(0, -1, 0.5); [this.vTop, this.vBottom].forEach((v) => { v.unproject(this._camera); this._camera.worldToLocal(v); }); this.angleX = this.vTop.angleTo(this.vBottom); } private _onRotateMove(event: TouchEvent) { const touch = this._getTouch(event, this.domElement); if (!touch) { return; } this._rotationMovePosition.set(touch.clientX, touch.clientY); this._rotationDelta.copy(this._rotationMovePosition).sub(this._rotationStartPosition); // delta.normalize(); this.rotationData.direction.x = this._rotationDelta.x / this.domElement.clientWidth; this.rotationData.direction.y = this._rotationDelta.y / this.domElement.clientHeight; // rotateData.speed = delta.length(); this._rotateCamera(this.rotationData); } private _onRotateEnd() { this.rotationData.direction.x = 0; this.rotationData.direction.y = 0; } private _rotateCamera(rotationData: RotationData) { const INVERT_Y = true; const INVERT_X = INVERT_Y; let angleY = this.angleY * rotationData.direction.x * this._rotationSpeed; this._camera.rotation.y = this._startCameraRotation.y + (INVERT_Y ? -angleY : angleY); let angleX = this.angleX * rotationData.direction.y * this._rotationSpeed; // apply bound this._camera.rotation.x = CoreMath.clamp( this._startCameraRotation.x + (INVERT_X ? -angleX : angleX), this._rotationRange.min, this._rotationRange.max ); this.dispatchEvent(EVENT_CHANGE); } // // // TRANSLATE // // private _startCameraPosition = new Vector3(); private _translationStartPosition = new Vector2(); private _translationMovePosition = new Vector2(); private _translationDelta = new Vector2(); private _onTranslateStart(event: TouchEvent) { this._startCameraPosition.copy(this._camera.position); const touch = this._getTouch(event, this._translateDomElement); if (!touch) { return; } this._translationStartPosition.set(touch.clientX, touch.clientY); this._translateDomElementRect = this._translateDomElement.getBoundingClientRect(); } private _onTranslateMove(event: TouchEvent) { const touch = this._getTouch(event, this._translateDomElement); if (!touch) { return; } this._translationMovePosition.set(touch.clientX, touch.clientY); this._translationDelta.copy(this._translationMovePosition).sub(this._translationStartPosition); this.translationData.direction.x = (this._translationSpeed * this._translationDelta.x) / this._translateDomElementRect.width; this.translationData.direction.y = (this._translationSpeed * -this._translationDelta.y) / this._translateDomElementRect.height; this.dispatchEvent(EVENT_CHANGE); } private _onTranslateEnd() { this.translationData.direction.x = 0; this.translationData.direction.y = 0; } private prevTime = performance.now(); update() { const time = performance.now(); const deltaTime = time - this.prevTime; this.prevTime = time; this._translateCamera(this.translationData, deltaTime); } private _camTmpPost = new Vector3(); private _camWorldDir = new Vector3(); private _up = new Vector3(0, 1, 0); private _camSideVector = new Vector3(); private _translateCamera(data: TranslationData, deltaTime: number) { this._camera.getWorldDirection(this._camWorldDir); this._camWorldDir.y = 0; this._camWorldDir.normalize(); this._camSideVector.crossVectors(this._up, this._camWorldDir); this._camSideVector.normalize(); this._camSideVector.multiplyScalar(-data.direction.x); this._camWorldDir.multiplyScalar(data.direction.y); this._velocity.copy(this._camWorldDir); this._velocity.add(this._camSideVector); const initialHeight = this._camera.position.y; this._camTmpPost.copy(this._camera.position); if (this._playerCollisionController) { // damping const damping = 1; //Math.exp(-3 * deltaTime) - 1; this._velocity.addScaledVector(this._velocity, damping); const deltaPosition = this._velocity.clone().multiplyScalar(deltaTime); this._camTmpPost.add(deltaPosition); const result = this._playerCollisionController.testPosition(this._camTmpPost); if (result) { // playerCollider.translate( result.normal.multiplyScalar( result.depth ) ); this._camTmpPost.add(result.normal.multiplyScalar(result.depth)); } this._camera.position.copy(this._camTmpPost); } else { this._camTmpPost.add(this._camSideVector); this._camTmpPost.add(this._camWorldDir); this._camera.position.copy(this._camTmpPost); } // ensure that the camera never changes y. this._camera.position.y = initialHeight; } // // // UTILS // // private _getTouch(event: TouchEvent, element: HTMLElement) { for (let i = 0; i < event.touches.length; i++) { const touch = event.touches[i]; if (touch.target === element) { return touch; } } } }
the_stack
import {ToolboxCategory} from "../../Toolbox"; import {Blocks} from '../blocks' import Blockly from '../../../blockly/blockly'; import {moreCategory, ToolboxCategorySpecial} from "./Common"; /* export function cachedBuiltinCategories(): ToolboxCategory[] { let categories: any = {}; categories[CategoryNameID.Loops] = { name: lf("{id:category}Loops"), nameid: CategoryNameID.Loops, blocks: [ { name: "controls_repeat_ext", attributes: { blockId: "controls_repeat_ext", weight: 49 }, blockXml: `<block type="controls_repeat_ext"> <value name="TIMES"> <shadow type="math_whole_number"> <field name="NUM">4</field> </shadow> </value> </block>` }, { name: "device_while", attributes: { blockId: "device_while", weight: 48 }, blockXml: `<block type="device_while"> <value name="COND"> <shadow type="logic_boolean"></shadow> </value> </block>` }, { name: "pxt_controls_for", attributes: { blockId: "pxt_controls_for", weight: 47 }, blockXml: `<block type="pxt_controls_for"> <value name="VAR"> <shadow type="variables_get_reporter"> <field name="VAR">${lf("{id:var}index")}</field> </shadow> </value> <value name="TO"> <shadow type="math_whole_number"> <field name="NUM">4</field> </shadow> </value> </block>` }, { name: "pxt_controls_for_of", attributes: { blockId: "pxt_controls_for_of", weight: 46 }, blockXml: `<block type="pxt_controls_for_of"> <value name="VAR"> <shadow type="variables_get_reporter"> <field name="VAR">${lf("{id:var}value")}</field> </shadow> </value> <value name="LIST"> <shadow type="variables_get"> <field name="VAR">list</field> </shadow> </value> </block>` } ], attributes: { //callingConvention: ts.pxtc.ir.CallingConvention.Plain, icon: "loops", weight: 50.09, paramDefl: {} } }; categories[CategoryNameID.Logic] = { name: lf("{id:category}Logic"), nameid: CategoryNameID.Logic, groups: [lf("Conditionals"), lf("Comparison"), lf("Boolean"), "other"], blocks: [ { name: "controls_if", attributes: { blockId: "controls_if", group: lf("Conditionals"), weight: 49 }, blockXml: `<block type="controls_if" gap="8"> <value name="IF0"> <shadow type="logic_boolean"> <field name="BOOL">TRUE</field> </shadow> </value> </block>` }, { name: "controls_if_else", attributes: { blockId: "controls_if", group: lf("Conditionals"), weight: 48 }, blockXml: `<block type="controls_if" gap="8"> <mutation else="1"></mutation> <value name="IF0"> <shadow type="logic_boolean"> <field name="BOOL">TRUE</field> </shadow> </value> </block>` }, { name: "logic_compare_eq", attributes: { blockId: "logic_compare", group: lf("Comparison"), weight: 47 }, blockXml: `<block type="logic_compare" gap="8"> <value name="A"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <value name="B"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> </block>` }, { name: "logic_compare_lt", attributes: { blockId: "logic_compare", group: lf("Comparison"), weight: 46 }, blockXml: `<block type="logic_compare"> <field name="OP">LT</field> <value name="A"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <value name="B"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> </block>` }, { name: "logic_compare_strings", attributes: { blockId: "logic_compare", group: lf("Comparison"), weight: 45 }, blockXml: `<block type="logic_compare" gap="8"> <value name="A"> <shadow type="text"> <field name="TEXT"></field> </shadow> </value> <value name="B"> <shadow type="text"> <field name="TEXT"></field> </shadow> </value> </block>` }, { name: "logic_operation_and", attributes: { blockId: "logic_operation", group: lf("Boolean"), weight: 44 }, blockXml: `<block type="logic_operation" gap="8"> <field name="OP">AND</field> </block>` }, { name: "logic_operation_or", attributes: { blockId: "logic_operation", group: lf("Boolean"), weight: 43 }, blockXml: `<block type="logic_operation" gap="8"> <field name="OP">OR</field> </block>` }, { name: "logic_negate", attributes: { blockId: "logic_negate", group: lf("Boolean"), weight: 42 }, blockXml: `<block type="logic_negate"></block>` }, { name: "logic_boolean_true", attributes: { blockId: "logic_boolean", group: lf("Boolean"), weight: 41 }, blockXml: `<block type="logic_boolean" gap="8"> <field name="BOOL">TRUE</field> </block>` }, { name: "logic_boolean_false", attributes: { blockId: "logic_boolean", group: lf("Boolean"), weight: 40 }, blockXml: `<block type="logic_boolean"> <field name="BOOL">FALSE</field> </block>` }], attributes: { //callingConvention: ts.pxtc.ir.CallingConvention.Plain, weight: 50.08, icon: "logic", paramDefl: {} } }; categories[CategoryNameID.Variables] = { name: lf("{id:category}Variables"), nameid: CategoryNameID.Variables, blocks: undefined, custom: true, customClick: () => { // theEditor.showVariablesFlyout(); return false; }, attributes: { weight: 50.07, icon: "variables", //callingConvention: ts.pxtc.ir.CallingConvention.Plain, paramDefl: {} } }; categories[CategoryNameID.Maths] = { name: lf("{id:category}Math"), nameid: CategoryNameID.Maths, blocks: [ { name: "math_arithmetic_ADD", attributes: { blockId: "math_arithmetic", weight: 90 }, blockXml: `<block type="math_arithmetic" gap="8"> <value name="A"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <value name="B"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <field name="OP">ADD</field> </block>` }, { name: "math_arithmetic_MINUS", attributes: { blockId: "math_arithmetic", weight: 89 }, blockXml: `<block type="math_arithmetic" gap="8"> <value name="A"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <value name="B"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <field name="OP">MINUS</field> </block>` }, { name: "math_arithmetic_TIMES", attributes: { blockId: "math_arithmetic", weight: 88 }, blockXml: `<block type="math_arithmetic" gap="8"> <value name="A"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <value name="B"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <field name="OP">MULTIPLY</field> </block>` }, { name: "math_arithmetic_DIVIDE", attributes: { blockId: "math_arithmetic", weight: 87 }, blockXml: `<block type="math_arithmetic" gap="8"> <value name="A"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <value name="B"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <field name="OP">DIVIDE</field> </block>` }, { name: "math_number", attributes: { blockId: "math_number", weight: 86 }, blockXml: `<block type="math_number" gap="8"> <field name="NUM">0</field> </block>` }, { name: "math_modulo", attributes: { blockId: "math_modulo", weight: 85 }, blockXml: `<block type="math_modulo"> <value name="DIVIDEND"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <value name="DIVISOR"> <shadow type="math_number"> <field name="NUM">1</field> </shadow> </value> </block>` }, { name: "math_op2_min", attributes: { blockId: "math_op2", weight: 84 }, blockXml: `<block type="math_op2" gap="8"> <value name="x"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <value name="y"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <field name="op">min</field> </block>` }, { name: "math_op2_max", attributes: { blockId: "math_op2", weight: 83 }, blockXml: `<block type="math_op2" gap="8"> <value name="x"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <value name="y"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <field name="op">max</field> </block>` }, { name: "math_op3", attributes: { blockId: "math_op3", weight: 82 }, blockXml: `<block type="math_op3"> <value name="x"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> </block>` }, { name: "math_js_op", attributes: { blockId: "math_js_op", weight: 81 }, blockXml: `<block type="math_js_op"> <field name="OP">sqrt</field> <value name="ARG0"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> </block>` }, { name: "math_js_round", attributes: { blockId: "math_js_round", weight: 80 }, blockXml: `<block type="math_js_round"> <field name="OP">round</field> <value name="ARG0"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> </block>` } ], attributes: { //callingConvention: ts.pxtc.ir.CallingConvention.Plain, weight: 50.06, icon: "math", paramDefl: {} } }; categories[CategoryNameID.Functions] = { name: lf("{id:category}Functions"), nameid: CategoryNameID.Functions, blocks: [], custom: true, customClick: () => { //theEditor.showFunctionsFlyout(); return false; }, attributes: { advanced: true, weight: 50.08, //callingConvention: ts.pxtc.ir.CallingConvention.Plain, icon: "functions", paramDefl: {} } }; categories[CategoryNameID.Arrays] = { name: lf("{id:category}Arrays"), nameid: CategoryNameID.Arrays, blocks: [ { name: "lists_create_with", attributes: { blockId: "lists_create_with", weight: 90 }, blockXml: `<block type="variables_set" gap="8"> <field name="VAR" variabletype="">${lf("{id:var}list")}</field> <value name="VALUE"> <block type="lists_create_with"> <mutation items="2"></mutation> <value name="ADD0"> <shadow type="math_number"> <field name="NUM">1</field> </shadow> </value> <value name="ADD1"> <shadow type="math_number"> <field name="NUM">2</field> </shadow> </value> </block> </value> </block>` }, { name: "lists_create_with", attributes: { blockId: "lists_create_with", weight: 89 }, blockXml: `<block type="variables_set"> <field name="VAR" variabletype="">${lf("{id:var}text list")}</field> <value name="VALUE"> <block type="lists_create_with"> <mutation items="3"></mutation> <value name="ADD0"> <shadow type="text"> <field name="TEXT">${lf("a")}</field> </shadow> </value> <value name="ADD1"> <shadow type="text"> <field name="TEXT">${lf("b")}</field> </shadow> </value> <value name="ADD2"> <shadow type="text"> <field name="TEXT">${lf("c")}</field> </shadow> </value> </block> </value> </block>` }, { name: "lists_create_with", attributes: { blockId: "lists_create_with", weight: 5 }, blockXml: `<block type="lists_create_with"> <mutation items="0"></mutation> </block>` }, { name: "lists_index_get", attributes: { blockId: "lists_index_get", weight: 87 }, blockXml: `<block type="lists_index_get"> <value name="LIST"> <block type="variables_get"> <field name="VAR">${lf("{id:var}list")}</field> </block> </value> <value name="INDEX"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> </block>` }, { name: "lists_index_set", attributes: { blockId: "lists_index_set", weight: 86 }, blockXml: `<block type="lists_index_set"> <value name="INDEX"> <shadow type="math_number"> <field name="NUM">0</field> </shadow> </value> <value name="LIST"> <block type="variables_get"> <field name="VAR">${lf("{id:var}list")}</field> </block> </value> </block>` }, { name: "lists_length", attributes: { blockId: "lists_length", weight: 88 }, blockXml: `<block type="lists_length"> <value name="VALUE"> <block type="variables_get"> <field name="VAR">${lf("{id:var}list")}</field> </block> </value> </block>` } ], attributes: { advanced: true, weight: 50.07, icon: "arrays", //callingConvention: ts.pxtc.ir.CallingConvention.Plain, paramDefl: {} } }; categories[CategoryNameID.Text] = { name: lf("{id:category}Text"), nameid: CategoryNameID.Text, blocks: [ { name: "text", attributes: { blockId: "text", weight: 90 }, blockXml: `<block type="text"></block>` }, { name: "text_length", attributes: { blockId: "text_length", weight: 89 }, blockXml: `<block type="text_length"> <value name="VALUE"> <shadow type="text"> <field name="TEXT">${lf("Hello")}</field> </shadow> </value> </block>` }, { name: "text_join", attributes: { blockId: "text_join", weight: 88 }, blockXml: `<block type="text_join"> <mutation items="2"></mutation> <value name="ADD0"> <shadow type="text"> <field name="TEXT">${lf("Hello")}</field> </shadow> </value> <value name="ADD1"> <shadow type="text"> <field name="TEXT">${lf("World")}</field> </shadow> </value> </block>` } ], attributes: { advanced: true, weight: 50.06, icon: "text", //callingConvention: ts.pxtc.ir.CallingConvention.Plain, paramDefl: {} } }; return categories; } */ let categories: ToolboxCategory[] = []; categories.push({ color: Blockly.Msg.LOGIC_HUE, icon: "\uf085", name: "Logic", blocks: [ { name: "controls_if", xml: Blocks.logic.controls_if, group: "Conditionals" }, { name: "controls_if_else", xml: Blocks.logic.controls_if_else, group: "Conditionals" }, { name: "logic_ternary", xml: Blocks.logic.logic_ternary, group: "Conditionals" }, { name: "logic_compare_eq", xml: Blocks.logic.logic_compare_eq, group: "Comparison" }, { name: "logic_compare_lt", xml: Blocks.logic.logic_compare_lt, group: "Comparison" }, { name: "logic_compare_str", xml: Blocks.logic.logic_compare_str, group: "Comparison" }, { name: "logic_and", xml: Blocks.logic.logic_and, group: "Boolean" }, { name: "logic_or", xml: Blocks.logic.logic_or, group: "Boolean" }, { name: "logic_negate", xml: Blocks.logic.logic_negate, group: "Boolean" }, { name: "logic_boolean_true", xml: Blocks.logic.logic_boolean_true, group: "Boolean" }, { name: "logic_boolean_false", xml: Blocks.logic.logic_boolean_false, group: "Boolean" }, ], subcategories: [ ], // ToolboxCategory advanced: false }); categories.push({ name: "Loops", icon: "\uf2f1", color: Blockly.Msg.LOOPS_HUE, blocks: [ { name: "loops_repeat_ext", xml: Blocks.loops.controls_repeat_ext }, { name: "loops_while", xml: Blocks.loops.controls_whileuntil }, { name: "loops_for", xml: Blocks.loops.controls_for }, { name: "loops_flowcontrol", xml: Blocks.loops.controls_flow_statements } ], subcategories: [ ] }); categories.push({ name: "Math", color: Blockly.Msg.MATH_HUE, icon: "\uf1ec", blocks: [ { name: "math_number", xml: Blocks.math.math_number }, { name: "math_const_pi", xml: Blocks.math.math_const_pi }, { name: "math_const_e", xml: Blocks.math.math_const_e }, { name: "math_round", xml: Blocks.math.math_round }, { name: "math_rand_int", xml: Blocks.math.math_random_int }, { name: "math_rand_float", xml: Blocks.math.math_random_float }, { name: "math_arithmetic_sum", xml: Blocks.math.math_arithmetic_sum, group: "Arithmetic" }, { name: "math_arithmetic_sub", xml: Blocks.math.math_arithmetic_sub, group: "Arithmetic" }, { name: "math_arithmetic_mul", xml: Blocks.math.math_arithmetic_mul, group: "Arithmetic" }, { name: "math_arithmetic_div", xml: Blocks.math.math_arithmetic_div, group: "Arithmetic" }, { name: "math_arithmetic_pow", xml: Blocks.math.math_arithmetic_pow, group: "Arithmetic" }, { name: "math_arithmetic_modulo", xml: Blocks.math.math_modulo, group: "Arithmetic" }, { name: "math_single_root", xml: Blocks.math.math_single_root, group: "Single operand" }, { name: "math_single_abs", xml: Blocks.math.math_single_abs, group: "Single operand" }, { name: "math_single_neg", xml: Blocks.math.math_single_neg, group: "Single operand" }, { name: "math_single_ln", xml: Blocks.math.math_single_ln, group: "Single operand" }, { name: "math_single_log", xml: Blocks.math.math_single_log, group: "Single operand" }, { name: "math_single_exp", xml: Blocks.math.math_single_exp, group: "Single operand" }, { name: "math_single_sci", xml: Blocks.math.math_single_sci, group: "Single operand" }, { name: "math_trig_sin", xml: Blocks.math.math_trig_sin, group: "Trigonometry" }, { name: "math_trig_cos", xml: Blocks.math.math_trig_cos, group: "Trigonometry" }, { name: "math_trig_tan", xml: Blocks.math.math_trig_tan, group: "Trigonometry" }, { name: "math_trig_asin", xml: Blocks.math.math_trig_asin, group: "Trigonometry" }, { name: "math_trig_acos", xml: Blocks.math.math_trig_acos, group: "Trigonometry" }, { name: "math_trig_atan", xml: Blocks.math.math_trig_atan, group: "Trigonometry" }, ], subcategories: [{ ...moreCategory, blocks: [ { name: "math_constraint", xml: Blocks.math.math_constrain }, { name: "math_property_even", xml: Blocks.math.math_property_even }, { name: "math_property_odd", xml: Blocks.math.math_property_odd }, /*{ name: "math_on_list", xml: Blocks.math.math_on_list }*/ ] }] }); categories.push({ name: "Text", color: Blockly.Msg.TEXTS_HUE, icon: "\uf031", blocks: [ { name: "text", xml: Blocks.text.text }, { name: "text_join", xml: Blocks.text.text_join }, { name: "text_length", xml: Blocks.text.text_length }, { name: "text_isempty", xml: Blocks.text.text_isempty }, { name: "text_case_upper", xml: Blocks.text.text_case_upper }, { name: "text_case_lower", xml: Blocks.text.text_case_lower } ], subcategories: [{ ...moreCategory, blocks: [ { name: "text_substring", xml: Blocks.text.text_getsubstring }, /*{ name: "text_trim", xml: Blocks.text.text_trim }, { name: "text_count", xml: Blocks.text.text_count },*/ { name: "text_replace", xml: Blocks.text.text_replace }, /*{ name: "text_reverse", xml: Blocks.text.text_reverse },*/ { name: "text_print", xml: Blocks.text.text_print }, { name: "text_prompt_ext", xml: Blocks.text.text_prompt_ext }, { name: "text_charat", xml: Blocks.text.text_charat }, { name: "text_indexof", xml: Blocks.text.text_indexof } ] }] }); categories.push({ name: "Variables", icon: "\uf01c", color: Blockly.Msg.VARIABLES_HUE, special: ToolboxCategorySpecial.VARIABLES, blocks: [], subcategories: [] }); categories.push({ name: "Functions", icon: "\uf013", color: Blockly.Msg.PROCEDURES_HUE, special: ToolboxCategorySpecial.FUNCTIONS, blocks: [], subcategories: [] }); categories.push({ name: "I/O", icon: "\uf360", color: Blockly.Msg.IO_HUE, blocks: [ { name: "update", xml: Blocks.phone.update }, { name: "button_action", xml: Blocks.phone.button_action }, { name: "button_held", xml: Blocks.phone.button_held }, { name: "button_repeat", xml: Blocks.phone.button_repeat }, { name: "joystick", xml: Blocks.phone.joystick }, { name: "led_colour", xml: Blocks.phone.led_colour }, { name: "led_colour_rgb", xml: Blocks.phone.led_rgb }, { name: "led_on", xml: Blocks.phone.led_on }, { name: "led_off", xml: Blocks.phone.led_off } ], subcategories: [] }); categories.push({ name: "Display", icon: "\uf108", color: Blockly.Msg.DISPLAY_HUE, blocks: [ { name: "screen_colour", xml: Blocks.display.colour }, { name: "display_popup", xml: Blocks.display.popup }, { name: "display_clear", xml: Blocks.display.clear }, { name: "display_invert", xml: Blocks.display.invert }, { name: "display_fontsize", group: "Text", xml: Blocks.display.fontsize }, { name: "display_fonttype", group: "Text", xml: Blocks.display.fonttype }, { name: "display_fontcolour", group: "Text", xml: Blocks.display.fontcolour }, { name: "display_fontcolour", group: "Text", xml: Blocks.display.println }, { name: "draw_text", group: "Text", xml: Blocks.display.drawtext }, { name: "draw_rect", group: "Shapes", xml: Blocks.display.drawrect }, { name: "draw_circle", group: "Shapes", xml: Blocks.display.drawcircle }, { name: "draw_ellipse", group: "Shapes", xml: Blocks.display.drawellipse }, { name: "draw_triangle", group: "Shapes", xml: Blocks.display.drawtriangle } ], subcategories: [] }); categories.push({ name: "Time", icon: "\uf2f2", color: Blockly.Msg.TIME_HUE, subcategories: [], blocks: [ { name: "infinite_loop", xml: Blocks.time.infinite_loop }, { name: "time_delay", xml: Blocks.time.time_delay }, { name: "time_delay_microseconds", xml: Blocks.time.time_delaymicros }, { name: "time_delay_seconds", xml: Blocks.time.time_delayseconds }, { name: "time_micros", xml: Blocks.time.time_micros }, { name: "time_millis", xml: Blocks.time.time_millis } ] }); export function getToolbox(): ToolboxCategory[] { return categories; }
the_stack
import type { CacheAnnotation, CacheHint } from 'apollo-server-types'; import type { CacheScope } from 'apollo-server-types'; import { DirectiveNode, getNamedType, GraphQLCompositeType, GraphQLField, isCompositeType, isInterfaceType, isObjectType, responsePathAsArray, } from 'graphql'; import { newCachePolicy } from '../../cachePolicy'; import type { InternalApolloServerPlugin } from '../../internalPlugin'; import LRUCache from 'lru-cache'; export interface ApolloServerPluginCacheControlOptions { /** * All root fields and fields returning objects or interfaces have this value * for `maxAge` unless they set a cache hint with a non-undefined `maxAge` * using `@cacheControl` or `setCacheHint`. The default is 0, which means "not * cacheable". (That is: if you don't set `defaultMaxAge`, then every root * field in your operation and every field with sub-fields must have a cache * hint or the overall operation will not be cacheable.) */ defaultMaxAge?: number; /** * Determines whether to set the `Cache-Control` HTTP header on cacheable * responses with no errors. The default is true. */ calculateHttpHeaders?: boolean; // For testing only. __testing__cacheHints?: Map<string, CacheHint>; } export function ApolloServerPluginCacheControl( options: ApolloServerPluginCacheControlOptions = Object.create(null), ): InternalApolloServerPlugin { const typeAnnotationCache = new LRUCache< GraphQLCompositeType, CacheAnnotation >(); const fieldAnnotationCache = new LRUCache< GraphQLField<unknown, unknown>, CacheAnnotation >(); function memoizedCacheAnnotationFromType( t: GraphQLCompositeType, ): CacheAnnotation { const existing = typeAnnotationCache.get(t); if (existing) { return existing; } const annotation = cacheAnnotationFromType(t); typeAnnotationCache.set(t, annotation); return annotation; } function memoizedCacheAnnotationFromField( field: GraphQLField<unknown, unknown>, ): CacheAnnotation { const existing = fieldAnnotationCache.get(field); if (existing) { return existing; } const annotation = cacheAnnotationFromField(field); fieldAnnotationCache.set(field, annotation); return annotation; } return { __internal_plugin_id__() { return 'CacheControl'; }, async serverWillStart({ schema }) { // Set the size of the caches to be equal to the number of composite types // and fields in the schema respectively. This generally means that the // cache will always have room for all the cache hints in the active // schema but we won't have a memory leak as schemas are replaced in a // gateway. (Once we're comfortable breaking compatibility with // versions of Gateway older than 0.35.0, we should also run this code // from a schemaDidLoadOrUpdate instead of serverWillStart. Using // schemaDidLoadOrUpdate throws when combined with old gateways.) typeAnnotationCache.max = Object.values(schema.getTypeMap()).filter( isCompositeType, ).length; fieldAnnotationCache.max = Object.values(schema.getTypeMap()) .filter(isObjectType) .flatMap((t) => Object.values(t.getFields())).length + Object.values(schema.getTypeMap()) .filter(isInterfaceType) .flatMap((t) => Object.values(t.getFields())).length; return undefined; }, async requestDidStart(requestContext) { const defaultMaxAge: number = options.defaultMaxAge ?? 0; const calculateHttpHeaders = options.calculateHttpHeaders ?? true; const { __testing__cacheHints } = options; return { async executionDidStart() { // Did something set the overall cache policy before we've even // started? If so, consider that as an override and don't touch it. // Just put set up fake `info.cacheControl` objects and otherwise // don't track cache policy. // // (This doesn't happen in practice using the core plugins: the main // use case for restricting overallCachePolicy outside of this plugin // is apollo-server-plugin-response-cache, but when it sets the policy // we never get to execution at all.) if (isRestricted(requestContext.overallCachePolicy)) { // This is "fake" in the sense that it never actually affects // requestContext.overallCachePolicy. const fakeFieldPolicy = newCachePolicy(); return { willResolveField({ info }) { info.cacheControl = { setCacheHint: (dynamicHint: CacheHint) => { fakeFieldPolicy.replace(dynamicHint); }, cacheHint: fakeFieldPolicy, cacheHintFromType: memoizedCacheAnnotationFromType, }; }, }; } return { willResolveField({ info }) { const fieldPolicy = newCachePolicy(); let inheritMaxAge = false; // If this field's resolver returns an object/interface/union // (maybe wrapped in list/non-null), look for hints on that return // type. const targetType = getNamedType(info.returnType); if (isCompositeType(targetType)) { const typeAnnotation = memoizedCacheAnnotationFromType(targetType); fieldPolicy.replace(typeAnnotation); inheritMaxAge = !!typeAnnotation.inheritMaxAge; } // Look for hints on the field itself (on its parent type), taking // precedence over previously calculated hints. const fieldAnnotation = memoizedCacheAnnotationFromField( info.parentType.getFields()[info.fieldName], ); // Note that specifying `@cacheControl(inheritMaxAge: true)` on a // field whose return type defines a `maxAge` gives precedence to // the type's `maxAge`. (Perhaps this should be some sort of // error.) if ( fieldAnnotation.inheritMaxAge && fieldPolicy.maxAge === undefined ) { inheritMaxAge = true; // Handle `@cacheControl(inheritMaxAge: true, scope: PRIVATE)`. // (We ignore any specified `maxAge`; perhaps it should be some // sort of error.) if (fieldAnnotation.scope) { fieldPolicy.replace({ scope: fieldAnnotation.scope }); } } else { fieldPolicy.replace(fieldAnnotation); } info.cacheControl = { setCacheHint: (dynamicHint: CacheHint) => { fieldPolicy.replace(dynamicHint); }, cacheHint: fieldPolicy, cacheHintFromType: memoizedCacheAnnotationFromType, }; // When the resolver is done, call restrict once. By calling // restrict after the resolver instead of before, we don't need to // "undo" the effect on overallCachePolicy of a static hint that // gets refined by a dynamic hint. return () => { // If this field returns a composite type or is a root field and // we haven't seen an explicit maxAge hint, set the maxAge to 0 // (uncached) or the default if specified in the constructor. // (Non-object fields by default are assumed to inherit their // cacheability from their parents. But on the other hand, while // root non-object fields can get explicit hints from their // definition on the Query/Mutation object, if that doesn't // exist then there's no parent field that would assign the // default maxAge, so we do it here.) // // You can disable this on a non-root field by writing // `@cacheControl(inheritMaxAge: true)` on it. If you do this, // then its children will be treated like root paths, since // there is no parent maxAge to inherit. // // We do this in the end hook so that dynamic cache control // prevents it from happening (eg, // `info.cacheControl.cacheHint.restrict({maxAge: 60})` should // work rather than doing nothing because we've already set the // max age to the default of 0). This also lets resolvers assume // any hint in `info.cacheControl.cacheHint` was explicitly set. if ( fieldPolicy.maxAge === undefined && ((isCompositeType(targetType) && !inheritMaxAge) || !info.path.prev) ) { fieldPolicy.restrict({ maxAge: defaultMaxAge }); } if (__testing__cacheHints && isRestricted(fieldPolicy)) { const path = responsePathAsArray(info.path).join('.'); if (__testing__cacheHints.has(path)) { throw Error( "shouldn't happen: addHint should only be called once per path", ); } __testing__cacheHints.set(path, { maxAge: fieldPolicy.maxAge, scope: fieldPolicy.scope, }); } requestContext.overallCachePolicy.restrict(fieldPolicy); }; }, }; }, async willSendResponse(requestContext) { const { response, overallCachePolicy } = requestContext; const policyIfCacheable = overallCachePolicy.policyIfCacheable(); // If the feature is enabled, there is a non-trivial cache policy, // there are no errors, and we actually can write headers, write the // header. if ( calculateHttpHeaders && policyIfCacheable && !response.errors && response.http ) { response.http.headers.set( 'Cache-Control', `max-age=${ policyIfCacheable.maxAge }, ${policyIfCacheable.scope.toLowerCase()}`, ); } }, }; }, }; } function cacheAnnotationFromDirectives( directives: ReadonlyArray<DirectiveNode> | undefined, ): CacheAnnotation | undefined { if (!directives) return undefined; const cacheControlDirective = directives.find( (directive) => directive.name.value === 'cacheControl', ); if (!cacheControlDirective) return undefined; if (!cacheControlDirective.arguments) return undefined; const maxAgeArgument = cacheControlDirective.arguments.find( (argument) => argument.name.value === 'maxAge', ); const scopeArgument = cacheControlDirective.arguments.find( (argument) => argument.name.value === 'scope', ); const inheritMaxAgeArgument = cacheControlDirective.arguments.find( (argument) => argument.name.value === 'inheritMaxAge', ); const scope = scopeArgument?.value?.kind === 'EnumValue' ? (scopeArgument.value.value as CacheScope) : undefined; if ( inheritMaxAgeArgument?.value?.kind === 'BooleanValue' && inheritMaxAgeArgument.value.value ) { // We ignore maxAge if it is also specified. return { inheritMaxAge: true, scope }; } return { maxAge: maxAgeArgument?.value?.kind === 'IntValue' ? parseInt(maxAgeArgument.value.value) : undefined, scope, }; } function cacheAnnotationFromType(t: GraphQLCompositeType): CacheAnnotation { if (t.astNode) { const hint = cacheAnnotationFromDirectives(t.astNode.directives); if (hint) { return hint; } } if (t.extensionASTNodes) { for (const node of t.extensionASTNodes) { const hint = cacheAnnotationFromDirectives(node.directives); if (hint) { return hint; } } } return {}; } function cacheAnnotationFromField( field: GraphQLField<unknown, unknown>, ): CacheAnnotation { if (field.astNode) { const hint = cacheAnnotationFromDirectives(field.astNode.directives); if (hint) { return hint; } } return {}; } function isRestricted(hint: CacheHint) { return hint.maxAge !== undefined || hint.scope !== undefined; } // This plugin does nothing, but it ensures that ApolloServer won't try // to add a default ApolloServerPluginCacheControl. export function ApolloServerPluginCacheControlDisabled(): InternalApolloServerPlugin { return { __internal_plugin_id__() { return 'CacheControl'; }, }; }
the_stack
import { Mechanics, Book, Section, Language, Disciplines, mechanicsEngine, ExpressionEvaluator, randomMechanics, LoreCircle } from ".."; /** * Tools to validate book mechanics */ export class BookValidator { /** Book mechanics */ private mechanics: Mechanics; /** Book XML */ public book: Book; /** Errors found */ public errors: string[] = []; /** Current testing section */ private currentSection: Section; /** Special values allowed on "drop" rule */ private specialDropValues = [ "allweapons" , "allweaponlike" , "backpackcontent" , "currentweapon" , "allspecial" , "allspecialgrdmaster", "allmeals" , "all" , "allobjects" ]; /** * XSD text for mechanics validation. null until is not loaded */ private static xsdText: string; /** * Constructor */ public constructor( mechanics: Mechanics , book: Book ) { this.mechanics = mechanics; this.book = book; } public static downloadBookAndGetValidator( bookNumber: number , language: Language ): JQueryPromise<BookValidator> { const book = new Book(bookNumber, language ); const mechanics = new Mechanics( book ); const promises = []; promises.push( book.downloadBookXml() ); promises.push( mechanics.downloadXml() ); promises.push( mechanics.downloadObjectsXml() ); const dfd = jQuery.Deferred<BookValidator>(); $.when.apply($, promises) .done( () => { dfd.resolve( new BookValidator(mechanics, book) ); } ) .fail( () => { dfd.reject("Error downloading book files"); }); return dfd.promise(); } /** * Validate the entire book. Errors will be stored at this.errors */ public validateBook() { this.errors = []; // Validate the XML with XSD this.validateXml(); // Traverse book sections const lastSectionId = this.mechanics.getLastSectionId(); let currentSectionId = Book.INITIAL_SECTION; while ( currentSectionId !== lastSectionId ) { // The book section this.validateSectionInternal(currentSectionId); currentSectionId = this.currentSection.getNextSectionId(); } } /** * Validate a single section. Errors will be stored at this.errors * @param sectionId Section to validate */ public validateSection( sectionId: string ) { this.errors = []; this.validateSectionInternal(sectionId); } /** Check book disciplines ids and applicacion disciplines ids match */ private validateDisciplines() { const bookIds = Object.keys( this.book.getDisciplinesTable() ); const enumIds = Disciplines.getSeriesDisciplines(this.book.getBookSeries().id); for (const d of bookIds) { if (!enumIds.contains(d)) { this.addError(null, `Book discipline id ${d} not found in application enum`); } } for (const d of enumIds) { if (!bookIds.contains(d)) { this.addError(null, `Application enum discipline id ${d} not found in book disciplines`); } } } private validateSectionInternal( sectionId: string ) { // The book section this.currentSection = new Section( this.book , sectionId , this.mechanics ); // The section mechanics const $sectionMechanics = this.mechanics.getSection( sectionId ); this.validateChildrenRules( $sectionMechanics ); if (sectionId === Book.DISCIPLINES_SECTION) { this.validateDisciplines(); } } private validateChildrenRules($parent: JQuery<Element>) { if ( !$parent ) { return; } for ( const child of $parent.children().toArray() ) { this.validateRule( child ); } } private validateRule(rule: Element) { try { const $rule = $(rule); if ( this[rule.nodeName] ) { // There is a function to validate the rule. Validate it: this[rule.nodeName]( $rule ); } if ( rule.nodeName === "test" ) { // Special case: If this is a "test" rule with "bookLanguage" attr. set, check it: // (there are semantic differences between languages...) const language: string = $rule.attr("bookLanguage"); if ( language && language !== this.book.language ) { // Ignore children return; } // Other special case for books XML update. If the current XML does not contain the test text, ignore children const text: string = $rule.attr("sectionContainsText"); if ( text && !this.currentSection.containsText( text ) ) { // Ignore children return; } } this.validateChildrenRules( $rule ); } catch (e) { mechanicsEngine.debugWarning(e); this.addError( $(rule) , "Exception validating rule: " + e ); } } /** * Add a validation error * @param $rule The wrong rule. It can be null * @param errorMsg Error message */ private addError($rule: JQuery<Element>, errorMsg: string) { let msg = "Section " + this.currentSection.sectionId; if ($rule) { msg += ", rule " + $rule[0].nodeName; } msg += ": " + errorMsg; this.errors.push(msg); } ////////////////////////////////////////////////////////// // COMMON ATTRIBUTRES VALIDATION ////////////////////////////////////////////////////////// private getPropertyValueAsArray( $rule: JQuery<Element> , property: string , allowMultiple: boolean ): string[] { if ( allowMultiple ) { return mechanicsEngine.getArrayProperty( $rule , property ); } // Single value const value: string = $rule.attr( property ); if ( value ) { return [ value ]; } else { return []; } } private validateObjectIdsAttribute( $rule: JQuery<Element> , property: string , allowMultiple: boolean , onlyWeapons: boolean ): boolean { const objectIds = this.getPropertyValueAsArray( $rule , property , allowMultiple ); if ( objectIds.length === 0 ) { return false; } for ( const objectId of objectIds ) { const item = this.mechanics.getObject(objectId); if ( !item ) { this.addError( $rule , "Object id " + objectId + " not found"); } else if ( onlyWeapons && !item.isWeapon() ) { this.addError( $rule , "Object id " + objectId + " is not a weapon"); } } return true; } private validateDisciplinesAttribute( $rule: JQuery<Element> , property: string , allowMultiple: boolean ) { const disciplinesIds = this.getPropertyValueAsArray( $rule , property , allowMultiple ); if ( disciplinesIds.length === 0 ) { return; } const disciplinesTable = this.book.getDisciplinesTable(); for ( const disciplineId of disciplinesIds ) { if ( !disciplinesTable[disciplineId] ) { this.addError( $rule , "Wrong discipline id: " + disciplineId ); } } } private validateSectionsAttribute( $rule: JQuery<Element> , property: string , allowMultiple: boolean ) { const sectionIds = this.getPropertyValueAsArray( $rule , property , allowMultiple ); for ( const sectionId of sectionIds ) { if ( this.book.getSectionXml(sectionId).length === 0 ) { this.addError( $rule , "Section does not exists: " + sectionId ); } } } private validateSectionChoiceAttribute( $rule: JQuery<Element>, property: string, allowAll: boolean ) { const sectionId: string = $rule.attr( property ); if ( !sectionId ) { return; } if ( allowAll && sectionId === "all" ) { return; } // If the rule is under a "registerGlobalRule", do no check this if ( $rule.closest( "registerGlobalRule" ).length > 0 ) { return; } const $choices = this.currentSection.$xmlSection.find( "choice[idref=" + sectionId + "]" ); if ( $choices.length === 0 ) { // If there is a "textToChoice" link with that destination, it's ok const $sectionMechanics = this.mechanics.getSection( this.currentSection.sectionId ); if ( $sectionMechanics && $sectionMechanics.find("textToChoice[section=" + sectionId + "]").length > 0 ) { return; } this.addError( $rule , "No choice found on this section with destination to " + sectionId ); } } private checkThereAreCombats( $rule: JQuery<Element> ) { // If the rule is under a "registerGlobalRule", do no check this if ( $rule.closest( "registerGlobalRule" ).length > 0 ) { return; } // Check there are combats on this section if ( this.currentSection.getCombats().length === 0 ) { this.addError( $rule , "There are no combats on this section"); } } ////////////////////////////////////////////////////////// // EXPRESSIONS VALIDATION ////////////////////////////////////////////////////////// private validateAndEvalExpression( $rule: JQuery<Element> , expression: string ): any { try { for ( const keyword of ExpressionEvaluator.getKeywords( expression ) ) { if ( !ExpressionEvaluator.isValidKeyword( keyword ) ) { this.addError( $rule , "Unkwown keyword " + keyword ); } expression = expression.replaceAll( keyword , "0" ); } // tslint:disable-next-line: no-eval return eval( expression ); } catch (e) { mechanicsEngine.debugWarning(e); this.addError( $rule , "Error evaluating expression: " + e ); return null; } } private validateExpression( $rule: JQuery<Element> , property: string , expectedType: string ) { const expression = $rule.attr( property ); if ( !expression ) { return; } const value = this.validateAndEvalExpression( $rule , expression ); if ( value !== null ) { const type = typeof value; if ( type !== expectedType ) { this.addError( $rule , "Wrong expression type. Expected: " + expectedType + ", expression type: " + type ); } } } private validateNumericExpression( $rule: JQuery<Element> , property: string ) { this.validateExpression( $rule , property , "number" ); } private validateBooleanExpression( $rule: JQuery<Element> , property: string ) { this.validateExpression( $rule , property , "boolean" ); } private validateRandomTableIndex($rule: JQuery<Element>) { // Check index: let txtIndex: string = $rule.attr("index"); if (!txtIndex) { txtIndex = "0"; } const $random = this.currentSection.$xmlSection.find("a[href=random]:eq( " + txtIndex + ")"); if (!$random) { this.addError($rule, "Link to random table not found"); } } ////////////////////////////////////////////////////////// // VALIDATE XML ////////////////////////////////////////////////////////// /** * Download the XSD to validate the XML, if this has not been done yet */ public static downloadXsd(): JQueryPromise<void> { if ( BookValidator.xsdText ) { // Already downloaded return jQuery.Deferred<void>().resolve().promise(); } return $.ajax({ url: "data/mechanics.xsd", dataType: "text" }) .done((xmlText: string) => { BookValidator.xsdText = xmlText; }); } /** * Validate the mechanics XML. Errors will be stored at this.errors */ private validateXml() { if ( typeof validateXML === "undefined" ) { // On production, the xmllint.js is not available (size = 2.2 MB minified...) return; } if ( !BookValidator.xsdText ) { this.errors.push( "The XSD for mechanics validation has not been downloaded" ); return; } // The book mechanics let xmlText; if ( this.mechanics.mechanicsXmlText ) { xmlText = this.mechanics.mechanicsXmlText; } else { // This will NOT be the same as the original, and line numbers reported by "validateXML" will be aproximated xmlText = new XMLSerializer().serializeToString( this.mechanics.mechanicsXml.documentElement ); } // There is some kind of error with the UTF8 encoding. acute characters throw errors of invalid character... xmlText = xmlText.replace( /[áéíóú¡¿\’]/gi , "" ); // xmllint.js call parameters const mechanicsFileName = "mechanics-" + this.book.bookNumber + ".xml"; const module = { xml: xmlText, schema: BookValidator.xsdText, arguments: ["--noout", "--schema", "mechanics.xsd", mechanicsFileName ] }; // Do the XSD validation const xmllint = validateXML(module).trim(); if ( xmllint !== mechanicsFileName + " validates") { // Error: this.errors.push( xmllint ); } console.log( xmllint ); } ////////////////////////////////////////////////////////// // RULES VALIDATION ////////////////////////////////////////////////////////// private pick( $rule: JQuery<Element> ) { const objectIdFound = this.validateObjectIdsAttribute( $rule , "objectId" , false , false ); const classFound = $rule.attr("class"); const onlyOne = ( ( objectIdFound && !classFound ) || ( !objectIdFound && classFound ) ); if ( !onlyOne ) { this.addError( $rule , 'Must to have a "objectId" or "class" attribute, and only one' ); } if ( classFound && !$rule.attr("count") ) { this.addError( $rule , 'Must to have a "count" attribute' ); } this.validateNumericExpression( $rule , "count" ); } private randomTable( $rule: JQuery<Element> ) { if ( !$rule.attr("text-en") ) { this.validateRandomTableIndex($rule); } // Check numbers coverage const coverage: number[] = []; let overlapped = false; let nCasesFound = 0; for ( const child of $rule.children().toArray() ) { if ( child.nodeName === "case" ) { nCasesFound++; const bounds = randomMechanics.getCaseRuleBounds( $(child) ); if ( bounds && bounds[0] <= bounds[1] ) { for ( let i = bounds[0]; i <= bounds[1]; i++) { if ( coverage.contains(i) ) { overlapped = true; } else { coverage.push(i); } } } } } // There can be randomTable's without cases: In that case, do no check coverage: if ( nCasesFound === 0 ) { return; } // TODO: Check randomTableIncrement, and [BOWBONUS]: If it exists, the bounds should be -99, +99 let numberToTest; if ( $rule.attr( "zeroAsTen" ) === "true" ) { numberToTest = [1, 10]; } else { numberToTest = [0, 9]; } let missedNumbers = false; for ( let i = numberToTest[0]; i <= numberToTest[1]; i++) { if ( !coverage.contains(i) ) { missedNumbers = true; } } if ( missedNumbers ) { this.addError( $rule, "Missed numbers"); } if ( overlapped ) { this.addError( $rule, "Overlapped numbers"); } } private randomTableIncrement( $rule: JQuery<Element> ) { if ( $rule.attr( "increment" ) !== "reset" ) { this.validateNumericExpression( $rule , "increment" ); } this.validateRandomTableIndex( $rule ); } private case( $rule: JQuery<Element> ) { const bounds = randomMechanics.getCaseRuleBounds( $rule ); if ( !bounds ) { this.addError( $rule, 'Needs "value" or "from" / "to" attributes' ); return; } if ( bounds[0] > bounds[1] ) { this.addError( $rule, "Wrong range" ); } } private test( $rule: JQuery<Element> ) { this.validateDisciplinesAttribute( $rule , "hasDiscipline" , true ); this.validateObjectIdsAttribute( $rule , "hasObject" , true , false ); this.validateBooleanExpression( $rule , "expression" ); this.validateSectionsAttribute( $rule , "sectionVisited" , true ); this.validateObjectIdsAttribute( $rule , "currentWeapon" , true , true ); this.validateObjectIdsAttribute( $rule , "objectOnSection" , true , false ); const language: string = $rule.attr("bookLanguage"); if ( language ) { let langFound = false; for (const langKey of Object.keys(Language)) { if (Language[langKey] === language) { langFound = true; break; } } if (!langFound) { this.addError( $rule , "Language key not found in Language enum: " + language ); } } this.validateSectionChoiceAttribute( $rule , "isChoiceEnabled" , false ); this.validateObjectIdsAttribute( $rule , "hasWeaponType" , true , false ); const circle: string = $rule.attr( "hasCircle" ); if ( circle && !LoreCircle.getCircle( circle ) ) { this.addError( $rule , "Wrong circle: " + circle ); } this.validateObjectIdsAttribute( $rule , "hasWeaponskillWith" , false , true ); // TODO: attribute "isGlobalRuleRegistered". Check the ruleId exists on the current mechanics XML } private choiceState( $rule: JQuery<Element> ) { this.validateSectionChoiceAttribute( $rule , "section" , true ); } private object( $rule: JQuery<Element> ) { this.validateObjectIdsAttribute( $rule , "objectId" , false , false ); this.validateNumericExpression( $rule , "price" ); } private combat( $rule: JQuery<Element> ) { this.validateNumericExpression( $rule , "combatSkillModifier" ); this.validateNumericExpression( $rule , "combatSkillModifierIncrement" ); if ( $rule.attr("disabledObjects") !== "none" ) { this.validateObjectIdsAttribute( $rule , "disabledObjects" , true , false ); } this.checkThereAreCombats( $rule ); const combatIndex = parseInt( $rule.attr("index"), 10 ); if ( combatIndex ) { const nCombats = this.currentSection.getCombats().length; if ( nCombats <= combatIndex ) { this.addError( $rule , "There is no combat with index " + combatIndex ); } } if ($rule.attr("eludeEnemyEP") && !$rule.attr("eludeTurn")) { this.addError($rule, "If attribute eludeEnemyEP is set, eludeTurn attribute must be set too"); } if ($rule.attr("noPsiSurge") === "true" && $rule.attr("noMindblast") !== "true") { this.addError($rule, "If noPsiSurge attr. is true, noMindblast attribute should be true too"); } if ($rule.attr("noKaiSurge") === "true" && ( $rule.attr("noMindblast") !== "true" || $rule.attr("noPsiSurge") !== "true" ) ) { this.addError($rule, "If noKaiSurge attr. is true, noMindblast and noKaiSurge attributes should be true too"); } // TODO: Check attr "noWeapon" is boolean or number } private afterCombats( $rule: JQuery<Element> ) { this.checkThereAreCombats( $rule ); } private afterElude( $rule: JQuery<Element> ) { this.checkThereAreCombats( $rule ); } private afterCombatTurn( $rule: JQuery<Element> ) { this.checkThereAreCombats( $rule ); } private choiceSelected( $rule: JQuery<Element> ) { this.validateSectionChoiceAttribute( $rule , "section" , true ); } private numberPickerChoosed( $rule: JQuery<Element> ) { const $sectionMechanics = this.mechanics.getSection( this.currentSection.sectionId ); if ( $sectionMechanics.find( "numberPicker" ).length === 0 ) { this.addError( $rule , 'No "numberPicker" rule found on this section' ); } } private endurance( $rule: JQuery<Element> ) { this.validateNumericExpression( $rule , "count" ); } private resetSectionState( $rule: JQuery<Element> ) { this.validateSectionsAttribute( $rule , "sectionId" , false ); } private message( $rule: JQuery<Element> ) { const msgId: string = $rule.attr("id"); if ( $rule.attr( "op" ) ) { if ( !msgId ) { this.addError( $rule , '"id" attribute required' ); } else { // Find the referenced message const $sectionMechanics = this.mechanics.getSection( this.currentSection.sectionId ); if ( $sectionMechanics.find( "message[id=" + msgId + "]:not([op])" ).length === 0 ) { this.addError( $rule , 'No "message" found with id ' + msgId ); } } } else { if ( msgId ) { // Check there are no duplicated ids const $sectionMechanics = this.mechanics.getSection( this.currentSection.sectionId ); if ( $sectionMechanics.find( "message[id=" + msgId + "]:not([op])" ).length > 1 ) { this.addError( $rule , 'Multiple "message" with the same id=' + msgId ); } } if ( !$rule.attr( "en-text" ) ) { this.addError( $rule , '"en-text" or "op" attribute required' ); } } } private drop( $rule: JQuery<Element> ) { // Special values: const objectId = $rule.attr( "objectId" ); if ( objectId && this.specialDropValues.contains( objectId ) ) { return; } this.validateObjectIdsAttribute( $rule , "objectId" , true , false ); // TODO: Validate "backpackItemSlots" / "specialItemSlots" property values // TODO: "objectId" AND/OR "backpackItemSlots"/"specialItemSlots" should have value } private disableCombats( $rule: JQuery<Element> ) { this.checkThereAreCombats( $rule ); } private currentWeapon( $rule: JQuery<Element> ) { this.validateObjectIdsAttribute( $rule , "objectId" , false , true ); } private sell( $rule: JQuery<Element> ) { const objectId = $rule.attr("objectId"); if ( objectId ) { this.validateObjectIdsAttribute( $rule , "objectId" , false , false ); } const cls = $rule.attr("class"); if ( cls && cls !== "special" ) { this.addError( $rule , 'Wrong "class" property value' ); } if ( !cls && $rule.attr("except") ) { this.addError( $rule , 'Attribute "except" only applies if "class" is present' ); } this.validateObjectIdsAttribute( $rule , "except" , true , false ); // "objectId" or "class" are mandatory, and exclusive if ( ( !objectId && !cls ) || ( objectId && cls ) ) { this.addError( $rule , 'One and only one of "objectId" and "class" are mandatory' ); } } private goToSection( $rule: JQuery<Element> ) { this.validateSectionsAttribute( $rule , "section" , false ); } private objectUsed( $rule: JQuery<Element> ) { this.validateObjectIdsAttribute( $rule , "objectId" , true , false ); } private textToChoice( $rule: JQuery<Element> ) { this.validateSectionsAttribute( $rule , "section" , false ); const html = this.currentSection.getHtml(); const linkText: string = $rule.attr("text-" + this.book.language); if ( $(html).find(':contains("' + linkText + '")').length === 0 ) { this.addError( $rule , 'Text to replace "' + linkText + '" not found'); } } private kaiMonasteryStorage( $rule: JQuery<Element> ) { // Only available on "equipment" sections if ( $rule.closest( "section[id=equipmnt]" ).length === 0 ) { this.addError( $rule , 'Rule "kaiMonasteryStorage" should be included only on section with id=equipmnt' ); } } private displayIllustration( $rule: JQuery<Element> ) { this.validateSectionsAttribute( $rule , "section" , false ); const sectionId: string = $rule.attr( "section" ); const section = new Section( this.book , sectionId , this.mechanics ); if ( !section.getFirstIllustrationHtml() ) { this.addError( $rule , "There are no illustrations on " + sectionId ); } } private use( $rule: JQuery<Element> ) { this.validateObjectIdsAttribute( $rule , "objectId" , true , false ); } }
the_stack
import { Attribute, ChangeDetectorRef, ComponentFactory, ComponentFactoryResolver, ComponentRef, Directive, Inject, InjectionToken, Injector, OnDestroy, EventEmitter, Output, Type, ViewContainerRef, ElementRef, InjectFlags, NgZone } from '@angular/core'; import { ActivatedRoute, ActivatedRouteSnapshot, ChildrenOutletContexts, PRIMARY_OUTLET } from '@angular/router'; import { Frame, Page, NavigatedData, profile, Device } from '@nativescript/core'; import { BehaviorSubject } from 'rxjs'; import { PAGE_FACTORY, PageFactory } from '../platform-providers'; import { NativeScriptDebug } from '../trace'; import { DetachedLoader } from '../common/detached-loader'; import { ViewUtil } from '../view-util'; import { NSLocationStrategy } from './ns-location-strategy'; import { Outlet } from './ns-location-utils'; import { NSRouteReuseStrategy } from './ns-route-reuse-strategy'; import { findTopActivatedRouteNodeForOutlet, pageRouterActivatedSymbol, loaderRefSymbol, destroyComponentRef } from './page-router-outlet-utils'; export class PageRoute { activatedRoute: BehaviorSubject<ActivatedRoute>; constructor(startRoute: ActivatedRoute) { this.activatedRoute = new BehaviorSubject(startRoute); } } export class DestructibleInjector implements Injector { private refs = new Set<any>(); constructor(private destructableProviders: ProviderSet, private parent: Injector) {} get<T>(token: Type<T> | InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): T { const ref = this.parent.get(token, notFoundValue, flags); if (this.destructableProviders.has(token)) { this.refs.add(ref); } return ref; } destroy() { this.refs.forEach((ref) => { if (ref.ngOnDestroy instanceof Function) { ref.ngOnDestroy(); } }); this.refs.clear(); } } type ProviderSet = Set<Type<any> | InjectionToken<any>>; const routeToString = function (activatedRoute: ActivatedRoute | ActivatedRouteSnapshot): string { return activatedRoute.pathFromRoot.join('->'); }; @Directive({ selector: 'page-router-outlet' }) // tslint:disable-line:directive-selector export class PageRouterOutlet implements OnDestroy { // tslint:disable-line:directive-class-suffix private activated: ComponentRef<any> | null = null; private _activatedRoute: ActivatedRoute | null = null; private detachedLoaderFactory: ComponentFactory<DetachedLoader>; private outlet: Outlet; private name: string; private isEmptyOutlet: boolean; private viewUtil: ViewUtil; private frame: Frame; @Output('activate') activateEvents = new EventEmitter<any>(); // tslint:disable-line:no-output-rename @Output('deactivate') deactivateEvents = new EventEmitter<any>(); // tslint:disable-line:no-output-rename /** @deprecated from Angular since v4 */ get locationInjector(): Injector { return this.location.injector; } /** @deprecated from Angular since v4 */ get locationFactoryResolver(): ComponentFactoryResolver { return this.resolver; } get isActivated(): boolean { return !!this.activated; } get component(): Object { if (!this.activated) { if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog('Outlet is not activated'); } return; } return this.activated.instance; } get activatedRoute(): ActivatedRoute { if (!this.activated) { if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog('Outlet is not activated'); } return; } return this._activatedRoute; } constructor(private parentContexts: ChildrenOutletContexts, private location: ViewContainerRef, @Attribute('name') name: string, @Attribute('actionBarVisibility') actionBarVisibility: string, @Attribute('isEmptyOutlet') isEmptyOutlet: boolean, private locationStrategy: NSLocationStrategy, private componentFactoryResolver: ComponentFactoryResolver, private resolver: ComponentFactoryResolver, private changeDetector: ChangeDetectorRef, @Inject(PAGE_FACTORY) private pageFactory: PageFactory, private routeReuseStrategy: NSRouteReuseStrategy, private ngZone: NgZone, elRef: ElementRef) { this.isEmptyOutlet = isEmptyOutlet; this.frame = elRef.nativeElement; this.setActionBarVisibility(actionBarVisibility); if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog(`PageRouterOutlet.constructor frame: ${this.frame}`); } this.name = name || PRIMARY_OUTLET; parentContexts.onChildOutletCreated(this.name, <any>this); this.viewUtil = new ViewUtil(Device); this.detachedLoaderFactory = resolver.resolveComponentFactory(DetachedLoader); } setActionBarVisibility(actionBarVisibility: string): void { switch (actionBarVisibility) { case 'always': case 'never': this.frame.actionBarVisibility = actionBarVisibility; return; default: this.frame.actionBarVisibility = 'auto'; } } ngOnDestroy(): void { // Clear accumulated modal view page cache when page-router-outlet // destroyed on modal view closing this.parentContexts.onChildOutletDestroyed(this.name); if (this.outlet) { this.outlet.outletKeys.forEach((key) => { this.routeReuseStrategy.clearModalCache(key); }); this.locationStrategy.clearOutlet(this.frame); } else { NativeScriptDebug.routerLog('PageRouterOutlet.ngOnDestroy: no outlet available for page-router-outlet'); } if (this.isActivated) { const c = this.activated.instance; this.activated.hostView.detach(); destroyComponentRef(this.activated); this.deactivateEvents.emit(c); this.activated = null; } } deactivate(): void { if (!this.outlet || !this.outlet.isPageNavigationBack) { if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog('Currently not in page back navigation - component should be detached instead of deactivated.'); } return; } if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog('PageRouterOutlet.deactivate() while going back - should destroy'); } if (!this.isActivated) { return; } const c = this.activated.instance; destroyComponentRef(this.activated); this.activated = null; this._activatedRoute = null; this.deactivateEvents.emit(c); } /** * Called when the `RouteReuseStrategy` instructs to detach the subtree */ detach(): ComponentRef<any> { if (!this.isActivated) { if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog('Outlet is not activated'); } return; } if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog(`PageRouterOutlet.detach() - ${routeToString(this._activatedRoute)}`); } // Detach from ChangeDetection this.activated.hostView.detach(); const component = this.activated; this.activated = null; this._activatedRoute = null; return component; } /** * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree */ attach(ref: ComponentRef<any>, activatedRoute: ActivatedRoute) { if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog(`PageRouterOutlet.attach() - ${routeToString(activatedRoute)}`); } this.activated = ref; // reattach to ChangeDetection this.activated.hostView.markForCheck(); this.activated.hostView.reattach(); this._activatedRoute = activatedRoute; this.markActivatedRoute(activatedRoute); this.locationStrategy._finishBackPageNavigation(this.frame); } /** * Called by the Router to instantiate a new component during the commit phase of a navigation. * This method in turn is responsible for calling the `routerOnActivate` hook of its child. */ @profile activateWith(activatedRoute: ActivatedRoute, resolver: ComponentFactoryResolver | null): void { this.outlet = this.outlet || this.getOutlet(activatedRoute.snapshot); if (!this.outlet) { if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerError('No outlet found relative to activated route'); } return; } this.outlet.isNSEmptyOutlet = this.isEmptyOutlet; this.locationStrategy.updateOutletFrame(this.outlet, this.frame, this.isEmptyOutlet); if (this.outlet && this.outlet.isPageNavigationBack) { if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog('Currently in page back navigation - component should be reattached instead of activated.'); } this.locationStrategy._finishBackPageNavigation(this.frame); } if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog(`PageRouterOutlet.activateWith() - ${routeToString(activatedRoute)}`); } this._activatedRoute = activatedRoute; this.markActivatedRoute(activatedRoute); resolver = resolver || this.resolver; this.activateOnGoForward(activatedRoute, resolver); this.activateEvents.emit(this.activated.instance); } private activateOnGoForward(activatedRoute: ActivatedRoute, loadedResolver: ComponentFactoryResolver): void { if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog('PageRouterOutlet.activate() forward navigation - ' + 'create detached loader in the loader container'); } const factory = this.getComponentFactory(activatedRoute, loadedResolver); const page = this.pageFactory({ isNavigation: true, componentType: factory.componentType, }); const destructables = new Set([]); const injector = Injector.create({ providers: [ { provide: Page, useValue: page }, { provide: Frame, useValue: this.frame }, { provide: PageRoute, useValue: new PageRoute(activatedRoute) }, { provide: ActivatedRoute, useValue: activatedRoute }, { provide: ChildrenOutletContexts, useValue: this.parentContexts.getOrCreateContext(this.name).children }, ], parent: this.location.injector, }); const childInjector = new DestructibleInjector(destructables, injector); const loaderRef = this.location.createComponent(this.detachedLoaderFactory, this.location.length, childInjector, []); loaderRef.onDestroy(() => childInjector.destroy()); this.changeDetector.markForCheck(); this.activated = loaderRef.instance.loadWithFactory(factory); this.loadComponentInPage(page, this.activated, { activatedRoute }); this.activated[loaderRefSymbol] = loaderRef; } @profile private loadComponentInPage(page: Page, componentRef: ComponentRef<any>, navigationContext): void { // Component loaded. Find its root native view. const componentView = componentRef.location.nativeElement; // Remove it from original native parent. this.viewUtil.removeChild(componentView.parent, componentView); // Add it to the new page this.viewUtil.insertChild(page, componentView); const navigatedFromCallback = (<any>global).Zone.current.wrap((args: NavigatedData) => { if (args.isBackNavigation) { this.locationStrategy._beginBackPageNavigation(this.frame); this.locationStrategy.back(null, this.frame); } }); // TODO: experiment with using NgZone instead of global above // const navigatedFromCallback = (args: NavigatedData) => { // if (args.isBackNavigation) { // this.ngZone.run(() => { // this.locationStrategy._beginBackPageNavigation(this.frame); // this.locationStrategy.back(null, this.frame); // }); // } // }; page.on(Page.navigatedFromEvent, navigatedFromCallback); componentRef.onDestroy(() => { if (page) { page.off(Page.navigatedFromEvent, navigatedFromCallback); page = null; } }); const navOptions = this.locationStrategy._beginPageNavigation(this.frame); // Clear refCache if navigation with clearHistory if (navOptions.clearHistory) { const clearCallback = () => setTimeout(() => { if (this.outlet) { this.routeReuseStrategy.clearCache(this.outlet.outletKeys[0]); } }); page.once(Page.navigatedToEvent, clearCallback); } this.frame.navigate({ create() { return page; }, context: navigationContext, clearHistory: navOptions.clearHistory, animated: navOptions.animated, transition: navOptions.transition, }); } // Find and mark the top activated route as an activated one. // In ns-location-strategy we are reusing components only if their corresponing routes // are marked as activated from this method. private markActivatedRoute(activatedRoute: ActivatedRoute) { const queue = []; queue.push(activatedRoute.snapshot); let currentRoute = queue.shift(); while (currentRoute) { currentRoute.children.forEach((childRoute) => { queue.push(childRoute); }); const topActivatedRoute = findTopActivatedRouteNodeForOutlet(currentRoute); let outletKey = this.locationStrategy.getRouteFullPath(topActivatedRoute); let outlet = this.locationStrategy.findOutlet(outletKey, topActivatedRoute); if (outlet && outlet.frames.length) { topActivatedRoute[pageRouterActivatedSymbol] = true; if (NativeScriptDebug.isLogEnabled()) { NativeScriptDebug.routerLog('Activated route marked as page: ' + routeToString(topActivatedRoute)); } } currentRoute = queue.shift(); } } private getComponentFactory(activatedRoute: ActivatedRoute, loadedResolver: ComponentFactoryResolver): ComponentFactory<any> { const { component } = activatedRoute.routeConfig; return loadedResolver ? loadedResolver.resolveComponentFactory(component) : this.componentFactoryResolver.resolveComponentFactory(component); } private getOutlet(activatedRouteSnapshot: ActivatedRouteSnapshot): Outlet { const topActivatedRoute = findTopActivatedRouteNodeForOutlet(activatedRouteSnapshot); const outletKey = this.locationStrategy.getRouteFullPath(topActivatedRoute); let outlet = this.locationStrategy.findOutlet(outletKey, topActivatedRoute); // Named lazy loaded outlet. if (!outlet && this.isEmptyOutlet) { const parentOutletKey = this.locationStrategy.getRouteFullPath(topActivatedRoute.parent); outlet = this.locationStrategy.findOutlet(parentOutletKey, topActivatedRoute.parent); if (outlet) { outlet.outletKeys.push(outletKey); } } return outlet; } }
the_stack
import { BaseResource } from 'ms-rest-azure'; import { CloudError } from 'ms-rest-azure'; import * as moment from 'moment'; export { BaseResource } from 'ms-rest-azure'; export { CloudError } from 'ms-rest-azure'; /** * @class * Initializes a new instance of the OperationDisplay class. * @constructor * Display metadata associated with the operation. * * @member {string} [provider] Service provider: Microsoft * OperationsManagement. * @member {string} [resource] Resource on which the operation is performed * etc. * @member {string} [operation] Type of operation: get, read, delete, etc. */ export interface OperationDisplay { provider?: string; resource?: string; operation?: string; } /** * @class * Initializes a new instance of the Operation class. * @constructor * Supported operation of OperationsManagement resource provider. * * @member {string} [name] Operation name: {provider}/{resource}/{operation} * @member {object} [display] Display metadata associated with the operation. * @member {string} [display.provider] Service provider: Microsoft * OperationsManagement. * @member {string} [display.resource] Resource on which the operation is * performed etc. * @member {string} [display.operation] Type of operation: get, read, delete, * etc. */ export interface Operation { name?: string; display?: OperationDisplay; } /** * @class * Initializes a new instance of the SolutionProperties class. * @constructor * Solution properties supported by the OperationsManagement resource provider. * * @member {string} workspaceResourceId The azure resourceId for the workspace * where the solution will be deployed/enabled. * @member {string} [provisioningState] The provisioning state for the * solution. * @member {array} [containedResources] The azure resources that will be * contained within the solutions. They will be locked and gets deleted * automatically when the solution is deleted. * @member {array} [referencedResources] The resources that will be referenced * from this solution. Deleting any of those solution out of band will break * the solution. */ export interface SolutionProperties extends BaseResource { workspaceResourceId: string; readonly provisioningState?: string; containedResources?: string[]; referencedResources?: string[]; } /** * @class * Initializes a new instance of the ManagementAssociationProperties class. * @constructor * ManagementAssociation properties supported by the OperationsManagement * resource provider. * * @member {string} applicationId The applicationId of the appliance for this * association. */ export interface ManagementAssociationProperties extends BaseResource { applicationId: string; } /** * @class * Initializes a new instance of the ArmTemplateParameter class. * @constructor * Parameter to pass to ARM template * * @member {string} [name] name of the parameter. * @member {string} [value] value for the parameter. In Jtoken */ export interface ArmTemplateParameter { name?: string; value?: string; } /** * @class * Initializes a new instance of the ManagementConfigurationProperties class. * @constructor * ManagementConfiguration properties supported by the OperationsManagement * resource provider. * * @member {string} [applicationId] The applicationId of the appliance for this * Management. * @member {string} parentResourceType The type of the parent resource. * @member {array} parameters Parameters to run the ARM template * @member {string} [provisioningState] The provisioning state for the * ManagementConfiguration. * @member {object} template The Json object containing the ARM template to * deploy */ export interface ManagementConfigurationProperties extends BaseResource { applicationId?: string; parentResourceType: string; parameters: ArmTemplateParameter[]; readonly provisioningState?: string; template: any; } /** * @class * Initializes a new instance of the SolutionPlan class. * @constructor * Plan for solution object supported by the OperationsManagement resource * provider. * * @member {string} [name] name of the solution to be created. For Microsoft * published solution it should be in the format of * solutionType(workspaceName). SolutionType part is case sensitive. For third * party solution, it can be anything. * @member {string} [publisher] Publisher name. For gallery solution, it is * Microsoft. * @member {string} [promotionCode] promotionCode, Not really used now, can you * left as empty * @member {string} [product] name of the solution to enabled/add. For * Microsoft published gallery solution it should be in the format of * OMSGallery/<solutionType>. This is case sensitive */ export interface SolutionPlan { name?: string; publisher?: string; promotionCode?: string; product?: string; } /** * @class * Initializes a new instance of the Solution class. * @constructor * The container for solution. * * @member {string} [id] Resource ID. * @member {string} [name] Resource name. * @member {string} [type] Resource type. * @member {string} [location] Resource location * @member {object} [plan] Plan for solution object supported by the * OperationsManagement resource provider. * @member {string} [plan.name] name of the solution to be created. For * Microsoft published solution it should be in the format of * solutionType(workspaceName). SolutionType part is case sensitive. For third * party solution, it can be anything. * @member {string} [plan.publisher] Publisher name. For gallery solution, it * is Microsoft. * @member {string} [plan.promotionCode] promotionCode, Not really used now, * can you left as empty * @member {string} [plan.product] name of the solution to enabled/add. For * Microsoft published gallery solution it should be in the format of * OMSGallery/<solutionType>. This is case sensitive * @member {object} [properties] Properties for solution object supported by * the OperationsManagement resource provider. * @member {string} [properties.workspaceResourceId] The azure resourceId for * the workspace where the solution will be deployed/enabled. * @member {string} [properties.provisioningState] The provisioning state for * the solution. * @member {array} [properties.containedResources] The azure resources that * will be contained within the solutions. They will be locked and gets deleted * automatically when the solution is deleted. * @member {array} [properties.referencedResources] The resources that will be * referenced from this solution. Deleting any of those solution out of band * will break the solution. */ export interface Solution extends BaseResource { readonly id?: string; readonly name?: string; readonly type?: string; location?: string; plan?: SolutionPlan; properties?: SolutionProperties; } /** * @class * Initializes a new instance of the SolutionPropertiesList class. * @constructor * the list of solution response * * @member {array} [value] List of solution properites within the subscription. */ export interface SolutionPropertiesList { value?: Solution[]; } /** * @class * Initializes a new instance of the ManagementAssociation class. * @constructor * The container for solution. * * @member {string} [id] Resource ID. * @member {string} [name] Resource name. * @member {string} [type] Resource type. * @member {string} [location] Resource location * @member {object} [properties] Properties for ManagementAssociation object * supported by the OperationsManagement resource provider. * @member {string} [properties.applicationId] The applicationId of the * appliance for this association. */ export interface ManagementAssociation extends BaseResource { readonly id?: string; readonly name?: string; readonly type?: string; location?: string; properties?: ManagementAssociationProperties; } /** * @class * Initializes a new instance of the ManagementAssociationPropertiesList class. * @constructor * the list of ManagementAssociation response * * @member {array} [value] List of Management Association properites within the * subscription. */ export interface ManagementAssociationPropertiesList { value?: ManagementAssociation[]; } /** * @class * Initializes a new instance of the ManagementConfiguration class. * @constructor * The container for solution. * * @member {string} [id] Resource ID. * @member {string} [name] Resource name. * @member {string} [type] Resource type. * @member {string} [location] Resource location * @member {object} [properties] Properties for ManagementConfiguration object * supported by the OperationsManagement resource provider. * @member {string} [properties.applicationId] The applicationId of the * appliance for this Management. * @member {string} [properties.parentResourceType] The type of the parent * resource. * @member {array} [properties.parameters] Parameters to run the ARM template * @member {string} [properties.provisioningState] The provisioning state for * the ManagementConfiguration. * @member {object} [properties.template] The Json object containing the ARM * template to deploy */ export interface ManagementConfiguration extends BaseResource { readonly id?: string; readonly name?: string; readonly type?: string; location?: string; properties?: ManagementConfigurationProperties; } /** * @class * Initializes a new instance of the ManagementConfigurationPropertiesList class. * @constructor * the list of ManagementConfiguration response * * @member {array} [value] List of Management Configuration properites within * the subscription. */ export interface ManagementConfigurationPropertiesList { value?: ManagementConfiguration[]; } /** * @class * Initializes a new instance of the CodeMessageErrorError class. * @constructor * The error details for a failed request. * * @member {string} [code] The error type. * @member {string} [message] The error message. */ export interface CodeMessageErrorError { code?: string; message?: string; } /** * @class * Initializes a new instance of the CodeMessageError class. * @constructor * The error body contract. * * @member {object} [error] The error details for a failed request. * @member {string} [error.code] The error type. * @member {string} [error.message] The error message. */ export interface CodeMessageError { error?: CodeMessageErrorError; } /** * @class * Initializes a new instance of the OperationListResult class. * @constructor * Result of the request to list solution operations. * */ export interface OperationListResult extends Array<Operation> { }
the_stack
import * as Knex from "knex"; import { BoundingBox, Entity, EntityCreateData, EntityType, EntityUpdateData, GenericAttributes, GenericRelationships, isSymbol, Paginated, PaperIdInfo, Relationship, SharedSymbolData, sharedSymbolFields, Symbol } from "./types/api"; import * as validation from "./types/validation"; import { DBConfig } from "./conf"; /** * Create a Knex query builder that can be used to submit queries to the database. */ export function createQueryBuilder(params: DBConfig) { const { host, port, database, user, password } = params; const config: Knex.Config = { client: "pg", connection: { host, port, database, user, password }, pool: { min: 0, max: 10, idleTimeoutMillis: 500 }, }; if (params.schema) { config.searchPath = [params.schema]; } return Knex(config); } /** * An error in loading data for an entity from the API. Based on custom error class declaration from: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error */ export class EntityLoadError extends Error { constructor(id: string, type: string, ...params: any[]) { super(...params); if (Error.captureStackTrace) { Error.captureStackTrace(this, EntityLoadError); } this.name = "ValidationError"; this.message = `Data for entity ${id} of type ${type} is either missing or typed incorrectly`; } } /** * An interface to the database. Performs queries and returns santized, typed objects. */ export class Connection { constructor(params: DBConfig) { this._knex = createQueryBuilder(params); } async close() { await this._knex.destroy(); } async insertLogEntry(logEntry: LogEntryRow) { return await this._knex("logentry").insert(logEntry); } async getAllPapers(offset: number = 0, size: number = 25, entity_type: EntityType = 'citation'): Promise<Paginated<PaperIdInfo>> { type Row = PaperIdInfo & { total_count: string; } const response = await this._knex.raw<{ rows: Row[] }>(` SELECT paper.arxiv_id, paper.s2_id, version.index AS version, COUNT(*) OVER() as total_count FROM paper JOIN ( SELECT MAX(index) AS index, paper_id FROM version GROUP BY paper_id ) AS version ON version.paper_id = paper.s2_id JOIN entity ON entity.paper_id = paper.s2_id AND entity.version = version.index AND entity.type = ? GROUP BY paper.s2_id, paper.arxiv_id, version.index ORDER BY paper.arxiv_id DESC OFFSET ${offset} LIMIT ${size} `, [entity_type]); const rows = response.rows.map(r => ({ arxiv_id: r.arxiv_id, s2_id: r.s2_id, version: r.version, })); const total = parseInt(response.rows[0].total_count); return { rows, offset, size, total }; } async getPaperEntityCount(paperSelector: PaperSelector, entityType: string): Promise<number | null> { const idField = isS2Selector(paperSelector) ? 'p.s2_id' : 'p.arxiv_id'; const idValue = isS2Selector(paperSelector) ? paperSelector.s2_id : `${paperSelector.arxiv_id}%`; const whereClause = `${idField} ${isS2Selector(paperSelector) ? '=' : 'ilike'} ?` const response = await this._knex.raw<{ rows: {count: number, id: string}[] }>(` SELECT count(e.*), ${idField} FROM paper p JOIN entity e on e.paper_id = p.s2_id JOIN ( SELECT paper_id, MAX(index) AS max_version FROM version GROUP BY paper_id ) AS maximum ON maximum.paper_id = e.paper_id WHERE e.version = maximum.max_version AND ${whereClause} AND e.type = ? GROUP BY p.s2_id `, [idValue, entityType]); if (response.rows.length > 0) { return response.rows[0].count; } return null; } async checkPaper(paperSelector: PaperSelector): Promise<boolean> { const rows = await this._knex("paper") .where(paperSelector); return rows.length > 0; } async getLatestPaperDataVersion(paperSelector: PaperSelector): Promise<number | null> { const rows = await this._knex("version") .max("index") .join("paper", { "paper.s2_id": "version.paper_id" }) .where(paperSelector); const version = Number(rows[0].max); return isNaN(version) ? null : version; } async getLatestProcessedArxivVersion(paperSelector: PaperSelector): Promise<number | null> { if (isS2Selector(paperSelector)) { return null; } // Provided arXiv IDs might have a version suffix, but ignore that for this check. const versionDelimiterIndex = paperSelector.arxiv_id.indexOf('v'); const arxivId = versionDelimiterIndex > -1 ? paperSelector.arxiv_id.substring(0, versionDelimiterIndex) : paperSelector.arxiv_id; // TODO(mjlangan): This won't support arXiv IDs prior to 03/2007 as written const response = await this._knex.raw<{ rows: { arxiv_version: number }[] }>(` SELECT CAST((REGEXP_MATCHES(arxiv_id,'^\\d{4}\\.\\d{4,5}v(\\d+)$'))[1] AS integer) AS arxiv_version FROM paper WHERE arxiv_id ilike ? ORDER BY arxiv_version DESC LIMIT 1 `, [`${arxivId}%`]); if (response.rows.length > 0) { return response.rows[0].arxiv_version; } return null; } createBoundingBoxes( boundingBoxRows: Omit<BoundingBoxRow, "id">[] ): BoundingBox[] { return boundingBoxRows.map((bbr) => ({ source: bbr.source, page: bbr.page, left: bbr.left, top: bbr.top, width: bbr.width, height: bbr.height, })); } /** * Extract attributes and relationships for an entity from database rows. These attributes and * relationships may need to be cleaned, as they contain *anything* that was found in the * entity table, which could include junk uploaded by annotators. */ unpackEntityDataRows(rows: Omit<EntityDataRow, "id">[], slim: boolean = false) { const attributes: GenericAttributes = {}; const relationships: GenericRelationships = {}; for (const row of rows) { /** * Read attributes. */ let casted_value; if (row.value === null) { if (!row.of_list) { casted_value = null; } } else if (row.item_type === "integer") { casted_value = parseInt(row.value); } else if (row.item_type === "float") { casted_value = parseFloat(row.value); } else if (row.item_type === "string") { casted_value = row.value; } if (casted_value !== undefined) { if (row.of_list) { if (attributes[row.key] === undefined) { attributes[row.key] = []; } attributes[row.key].push(casted_value); } else { attributes[row.key] = casted_value; } } /** * Read relationships. */ if (row.item_type === "relation-id" && row.relation_type !== null) { // optionally return a more compact representation for relationships const relationship = slim ? { id: row.value } : { type: row.relation_type, id: row.value }; if (row.of_list) { if (relationships[row.key] === undefined) { relationships[row.key] = []; } (relationships[row.key] as Relationship[]).push(relationship); } else { relationships[row.key] = relationship; } } } return { attributes, relationships }; } /** * Convert entity information from the database into an entity object. */ createEntityObjectFromRows( entityRow: EntityRow, boundingBoxRows: Omit<BoundingBoxRow, "id">[], entityDataRows: Omit<EntityDataRow, "id">[], slim?: boolean, ): Entity { const boundingBoxes = this.createBoundingBoxes(boundingBoxRows); const { attributes, relationships } = this.unpackEntityDataRows( entityDataRows, slim ); const entity = { id: String(entityRow.id), type: entityRow.type as EntityType, attributes: { ...attributes, version: entityRow.version, source: entityRow.source, bounding_boxes: boundingBoxes, tags: attributes.tags || [] }, relationships: { ...relationships, }, }; if (isSymbol(entity)) { entity.attributes.disambiguated_id = entity.attributes.mathml; } return entity; } async getEntitiesForPaper(paperSelector: PaperSelector, entityTypes: EntityType[], includeDuplicateSymbolData: boolean, slim: boolean, version?: number) { if (version === undefined) { try { let latestVersion = await this.getLatestPaperDataVersion(paperSelector); if (latestVersion === null) { return []; } version = latestVersion; } catch (e) { console.log("Error fetching latest data version number:", e); } } const entityColumns = slim ? ["entity.paper_id AS paper_id", "id", "type"] : ["entity.paper_id AS paper_id", "id", "version", "type", "source"]; const entityRows: EntityRow[] = await this._knex("entity") .select(entityColumns) .join("paper", { "paper.s2_id": "entity.paper_id" }) .where({ ...paperSelector, version }).andWhere(builder => { if (entityTypes.length > 0) { builder.whereIn('type', entityTypes); } else { builder.where(true); } }); const entityIds = entityRows.map(e => e.id); const boundingBoxColumns = slim ? ["id", "entity_id", "page", "left", "top", "width", "height"] : ["id", "entity_id", "source", "page", "left", "top", "width", "height"]; let boundingBoxRows: BoundingBoxRow[]; try { boundingBoxRows = await this._knex("boundingbox") .select(boundingBoxColumns) .whereIn("entity_id", entityIds); } catch (e) { console.log(e); throw "Error"; } /* * Organize bounding box data by the entity they belong to. */ const boundingBoxRowsByEntity = boundingBoxRows.reduce( (dict, row) => { if (dict[row.entity_id] === undefined) { dict[row.entity_id] = []; } dict[row.entity_id].push(row); return dict; }, {} as { [entity_id: string]: BoundingBoxRow[]; } ); const entityDataColumns = slim ? ["entity.id AS entity_id", "key", "value", "item_type", "of_list", "relation_type"] : ["entity.id AS entity_id", "entitydata.source AS source", "key", "value", "item_type", "of_list", "relation_type"]; const entityDataRows: EntityDataRow[] = await this._knex("entitydata") .select(entityDataColumns) .join("entity", { "entitydata.entity_id": "entity.id" }) /* * Order by entity ID to ensure that items from lists are retrieved in * the order they were written to the database. */ .orderBy("entitydata.id", "asc") .whereIn("entity.id", entityIds) .whereNot( (builder) => { if (!includeDuplicateSymbolData) { builder .where("entity.type", "symbol") .whereIn("entitydata.key", sharedSymbolFields) } } ) /* * Organize entity data entries by the entity they belong to. */ const entityDataRowsByEntity = entityDataRows.reduce( (dict, row) => { if (dict[row.entity_id] === undefined) { dict[row.entity_id] = []; } dict[row.entity_id].push(row); return dict; }, {} as { [entity_id: string]: EntityDataRow[]; } ); /** * Create entities from entity data. */ const entities: Entity[] = entityRows .map((entityRow) => { const boundingBoxRowsForEntity = boundingBoxRowsByEntity[entityRow.id] || []; const entityDataRowsForEntity = entityDataRowsByEntity[entityRow.id] || []; return this.createEntityObjectFromRows( entityRow, boundingBoxRowsForEntity, entityDataRowsForEntity, slim ); }) /* * Validation with Joi does two things: * 1. It adds default values to fields for an entity. * 2. It lists errors when an entity is still missing reuqired properties. */ .map((e) => validation.loadedEntity.validate(e, { stripUnknown: true })) .filter((validationResult) => { if (validationResult.error !== undefined) { console.error( "Invalid entity will not be returned. Error:", validationResult.error ); return false; } return true; }) .map((validationResult) => validationResult.value as Entity); return entities; } /** * Default implementation in `getEntitiesForPaper` naively retrieves all entities, * which includes quadratic data duplication across multiple instances of the same symbol. * This variant method is meant as a placeholder bridge until the underlying DB schema and * extraction write layer is changed to be non-duplicative. * Leaving the underlying data unchanged in the DB, we selectively exclude the entity data * types known to be redundant. These are retrieved later and added into lookup tables. */ async getDedupedEntitiesForPaper(paperSelector: PaperSelector, entityTypes: EntityType[], version?: number) { const entities = await this.getEntitiesForPaper(paperSelector, entityTypes, false, true, version); // Short-circuit fancy behavior below if we don't need the shared symbol data. if (entityTypes.indexOf("symbol") === -1 && entityTypes.length > 0) { return { entities } } // To provide a deduped copy of shared data between symbol instances, we // identify each symbol by its "disambiguated" id (currently the `mathml` attribute). // An arbitrary symbol entity from within each `mathml` is chosen as an exemplar from // which to look up supporting data that is identical across instances. const disambiguatedSymbolIdsToExemplarEntityIds = entities .filter((row) => isSymbol(row)) .reduce( (dict, symbol) => { const disambiguatedId = (symbol as Symbol).attributes.mathml; if (disambiguatedId !== null) { dict[disambiguatedId] = symbol.id; } return dict; }, {} as { [disambiguatedId: string]: string } ); const exemplarEntityIdsToDisambiguatedSymbolIds = Object.keys(disambiguatedSymbolIdsToExemplarEntityIds).reduce( (dict, key) => { const exemplarEntityId = disambiguatedSymbolIdsToExemplarEntityIds[key]; dict[exemplarEntityId] = key; return dict; }, {} as { [exemplarEntityId: string]: string } ); const dedupedSymbolData = await this._knex("entitydata") .select( "entity_id", "key", "value" ) .orderBy("id", "asc") .whereIn("key", sharedSymbolFields) .whereIn("entity_id", Object.values(disambiguatedSymbolIdsToExemplarEntityIds)) const sharedSymbolData = dedupedSymbolData.reduce( (dict, row) => { const disambiguatedId = exemplarEntityIdsToDisambiguatedSymbolIds[row.entity_id]; if (!(disambiguatedId in dict)) { dict[disambiguatedId] = sharedSymbolFields.reduce( (dict, key) => { dict[key] = []; return dict; }, {} as {[sharedSymbolField: string]: string[]} ); } dict[disambiguatedId][row.key].push(row.value) return dict; }, {} as { [disambiguatedId: string]: SharedSymbolData } ) return { entities, sharedSymbolData }; } createBoundingBoxRows( entity_id: number, bounding_boxes: BoundingBox[] ): Omit<BoundingBoxRow, "id">[] { return bounding_boxes.map((bb) => ({ entity_id, source: bb.source, page: bb.page, left: bb.left, top: bb.top, width: bb.width, height: bb.height, })); } /** * Take an input entity and extract from it a list of rows that can be inserted into the * 'entitydata' table to preserve all that's worth knowing about this entity. It is expected that * if an entity has undergone the validation from the './validation.ts' validators, then all * attributes and relationships are valid and therefore will be entered in the database. */ createEntityDataRows( entity_id: number, source: string, attributes: GenericAttributes, relationships: GenericRelationships ) { const rows: Omit<EntityDataRow, "id">[] = []; const keys = []; const addRow = ( key: string, value: string | null, item_type: EntityDataRowType, of_list: boolean, relation_type?: string | null ) => { rows.push({ entity_id, source, key, value, item_type, of_list, relation_type: relation_type || null, }); }; for (const key of Object.keys(attributes)) { if (["source", "version", "bounding_boxes"].indexOf(key) !== -1) { continue; } if (keys.indexOf(key) === -1) { keys.push(key); } const value = attributes[key]; let values = []; let of_list; if (Array.isArray(value)) { values = value; of_list = true; } else { values = [value]; of_list = false; } for (let v of values) { let item_type: EntityDataRowType | undefined = undefined; if (typeof v === "boolean") { item_type = "boolean"; v = v ? 1 : 0; } else if (typeof v === "number") { /** * This check for whether a number is an integer is based on the polyfill from MDN: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger#Polyfill */ if (isFinite(v) && Math.floor(v) === v) { item_type = "integer"; } else { item_type = "float"; } } else if (typeof v === "string") { item_type = "string"; } if (item_type !== undefined) { addRow(key, String(v), item_type, of_list, null); } } } for (const key of Object.keys(relationships)) { if (keys.indexOf(key) === -1) { keys.push(key); } const value = relationships[key]; if (Array.isArray(value)) { for (const r of value) { addRow(key, r.id, "relation-id", true, r.type); } } else { addRow(key, value.id, "relation-id", false, value.type); } } return { rows, keys }; } async createEntity(paperSelector: PaperSelector, data: EntityCreateData) { /** * Fetch the ID for the specified paper. */ const paperRows = await this._knex("paper") .select("s2_id AS id") .where(paperSelector); const paperId = paperRows[0].id; /** * Create entity with the most recent data version for this paper if the data version was * not specified by the client. */ let version; if (typeof data.attributes.version === "number") { version = data.attributes.version; } else { version = await this.getLatestPaperDataVersion(paperSelector); if (version === null) { throw Error( "No data version was specified, and no data version exists for this paper." ); } } /** * Create new entity. */ const entityRow: Omit<EntityRow, "id"> = { paper_id: paperId, type: data.type, version, source: data.attributes.source, }; const id = Number( (await this._knex("entity").insert(entityRow).returning("id"))[0] ); /** * Insert bounding boxes and data for entity. Must occur after the entity is inserted in * order to have access to the entity ID. */ const boundingBoxRows = this.createBoundingBoxRows( id, data.attributes.bounding_boxes ); const { rows: entityDataRows } = this.createEntityDataRows( id, data.attributes.source, data.attributes, data.relationships as GenericRelationships ); await this._knex.batchInsert("boundingbox", boundingBoxRows); await this._knex.batchInsert("entitydata", entityDataRows); /** * Create a completed version of the entity to return to the client. */ return { ...data, id: String(id), attributes: { ...data.attributes, version, }, }; } async updateEntity(data: EntityUpdateData) { /** * Update entity data. */ let entityRowUpdates: EntityRowUpdates | null = null; if (data.attributes !== undefined) { entityRowUpdates = { source: data.attributes.source, version: data.attributes.version, }; } if (entityRowUpdates !== null && Object.keys(entityRowUpdates).length > 0) { await this._knex("entity") .update(entityRowUpdates) .where({ id: data.id, type: data.type }); } const entityId = Number(data.id); /* * Update bounding boxes. */ if (data.attributes.bounding_boxes !== undefined) { await this._knex("boundingbox").delete().where({ entity_id: data.id }); const boundingBoxRows = this.createBoundingBoxRows( entityId, data.attributes.bounding_boxes ); await this._knex.batchInsert("boundingbox", boundingBoxRows); } /* * Update custom attributes, by removing previous values for known attributes and updating * them to the new values. */ const { rows: attributeRows, keys: attributeKeys, } = this.createEntityDataRows( entityId, data.attributes.source, data.attributes, {} ); for (const key of attributeKeys) { await this._knex("entitydata") .delete() .where({ entity_id: data.id, key }); } await this._knex.batchInsert("entitydata", attributeRows); /* * Update relationships. */ if (data.relationships !== undefined) { const { keys: relationshipKeys, rows: relationshipRows, } = this.createEntityDataRows( entityId, data.attributes.source, {}, data.relationships as GenericRelationships ); for (const key of relationshipKeys) { await this._knex("entitydata") .delete() .where({ entity_id: data.id, key }); } await this._knex.batchInsert("entitydata", relationshipRows); } } async deleteEntity(entity_id: string) { await this._knex("entity").delete().where({ id: entity_id }); } private _knex: Knex; } /** * Expected knex.js parameters for selecting a paper. Map from paper table column ID to value. */ export type PaperSelector = ArxivIdPaperSelector | S2IdPaperSelector; interface ArxivIdPaperSelector { arxiv_id: string; } interface S2IdPaperSelector { s2_id: string; } function isArxivSelector(selector: PaperSelector): selector is ArxivIdPaperSelector { return (selector as ArxivIdPaperSelector).arxiv_id !== undefined; } function isS2Selector(selector: PaperSelector): selector is S2IdPaperSelector { return (selector as S2IdPaperSelector).s2_id !== undefined; }
the_stack
import * as Nock from "nock"; import * as Temp from "temp"; import * as Sinon from "sinon"; import { expect } from "chai"; import CodePushReleaseCommand from "../../../src/commands/codepush/release"; import * as updateContentsTasks from "../../../src/commands/codepush/lib/update-contents-tasks"; import { getFakeParamsForRequest, createFile, getCommandArgsForReleaseCommand, FakeParamsForRequests, nockPlatformRequest, getLastFolderForSignPath, releaseUploadResponse, setMetadataResponse, } from "./utils"; import * as fileUtils from "../../../src/commands/codepush/lib/file-utils"; import { CommandArgs, CommandFailedResult } from "../../../src/util/commandline"; import chalk = require("chalk"); import * as pfs from "../../../src/util/misc/promisfied-fs"; describe("codepush release command", () => { const tmpFolderPath = Temp.mkdirSync("releaseTest"); const releaseFileName = "releaseBinaryFile"; const releaseFileContent = "Hello World!"; const appDescription = "app description"; const fakeParamsForRequests: FakeParamsForRequests = getFakeParamsForRequest(); let nockedApiGatewayRequests: Nock.Scope; let nockedFileUploadServiceRequests: Nock.Scope; let nockedCreateReleaseInterceptor: Nock.Interceptor; let sandbox: Sinon.SinonSandbox; let stubbedSign: Sinon.SinonStub; beforeEach(() => { nockedApiGatewayRequests = Nock(fakeParamsForRequests.host) .get( `/${fakeParamsForRequests.appVersion}/apps/${fakeParamsForRequests.userName}/${fakeParamsForRequests.appName}/deployments/Staging` ) .reply(200, (uri: any, requestBody: any) => { return {}; }); nockedApiGatewayRequests .post( `/${fakeParamsForRequests.appVersion}/apps/${fakeParamsForRequests.userName}/${fakeParamsForRequests.appName}/deployments/Staging/uploads` ) .reply(200, releaseUploadResponse); nockedFileUploadServiceRequests = Nock(releaseUploadResponse.upload_domain) .post(`/upload/set_metadata/${releaseUploadResponse.id}`) .query(true) .reply(200, setMetadataResponse); nockedFileUploadServiceRequests .post(`/upload/upload_chunk/${releaseUploadResponse.id}`) .query({ token: releaseUploadResponse.token, block_number: 1, }) .reply(200, { error: false, chunk_num: 0, error_code: "None", state: "Done", }); nockedFileUploadServiceRequests .post(`/upload/finished/${releaseUploadResponse.id}`) .query({ token: releaseUploadResponse.token, }) .reply(200, { error: false, chunk_num: 0, error_code: "None", state: "Done", }); nockCreateRelease({ mandatory: false, disabled: false, statusCode: 201 }); sandbox = Sinon.createSandbox(); stubbedSign = sandbox.stub(updateContentsTasks, "sign"); }); afterEach(() => { Nock.cleanAll(); nockedCreateReleaseInterceptor = null; sandbox.restore(); }); it("succeed if all parameters are passed", async function () { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); const goldenArgs = { // prettier-ignore args: [ "--update-contents-path", releaseFilePath, "--target-binary-version", fakeParamsForRequests.appVersion, "--deployment-name", "Staging", "--description", "app description", "--disabled", "--mandatory", "--private-key-path", "fake/private-key-path", "--disable-duplicate-release-error", "--rollout", "100", "--app", `${fakeParamsForRequests.userName}/${fakeParamsForRequests.appName}`, "--token", fakeParamsForRequests.token, ], command: ["codepush", "release"], commandPath: "fake/path", }; nockPlatformRequest("Cordova", fakeParamsForRequests, nockedApiGatewayRequests); nockCreateRelease({ mandatory: true, disabled: true, statusCode: 201 }); // Act const command = new CodePushReleaseCommand(goldenArgs); const result = await command.execute(); // Assert expect(result.succeeded).to.be.true; }); context("--update-contents-path validation", function () { it("should fail if --update-contents-path is not binary or zip", async function () { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); const args: CommandArgs = getCommandArgsForReleaseCommand( // prettier-ignore [ "-c", releaseFilePath, "-k", "fakePrivateKey.pem", "--description", appDescription, "-t", fakeParamsForRequests.appVersion, ], fakeParamsForRequests ); sandbox.stub(fileUtils, "isBinaryOrZip").returns(true); // Act const command = new CodePushReleaseCommand(args); const result = (await command.execute()) as CommandFailedResult; // Assert expect(result.succeeded).to.be.false; expect(result.errorMessage).to.eql( "It is unnecessary to package releases in a .zip or binary file. Please specify the direct path to the update content's directory (e.g. /platforms/ios/www) or file (e.g. main.jsbundle)." ); }); }); context("--target-binary-version validation", function () { it("should fail if --target-binary-version is not valid", async function () { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); const args: CommandArgs = getCommandArgsForReleaseCommand( // prettier-ignore [ "-c", releaseFilePath, "-k", "fakePrivateKey.pem", "--description", appDescription, "-t", "invalid" ], fakeParamsForRequests ); // Act const command = new CodePushReleaseCommand(args); const result = (await command.execute()) as CommandFailedResult; // Assert expect(result.succeeded).to.be.false; expect(result.errorMessage).to.eql("Invalid binary version(s) for a release."); }); }); context("--rollout validation", function () { describe("should fail when --rollout is", async function () { [ { value: "somestring", desc: "string value" }, { value: "1.234", desc: "a decimal value" }, // negative integers are treated by option parser as command parameter so there's no point to validate it here // { value: "-1", desc: "an integer value beyong 0..100 range" }, { value: "101", desc: "an integer value beyong 0..100 range" }, ].forEach((testCase) => { it(`${testCase.desc} e.g. ${testCase.value}`, async function () { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // prettier-ignore const args: CommandArgs = getCommandArgsForReleaseCommand( [ "-c", releaseFilePath, "-k", "fakePrivateKey.pem", "--description", appDescription, "-t", fakeParamsForRequests.appVersion, "--rollout", testCase.value ], fakeParamsForRequests ); // Act const command = new CodePushReleaseCommand(args); const result = (await command.execute()) as CommandFailedResult; // Assert expect(result.succeeded).to.be.false; expect(result.errorMessage).to.eql( `Rollout value should be integer value between ${chalk.bold("0")} or ${chalk.bold("100")}.` ); }); }); }); }); context("edge cases after uploading release", function () { describe("when 409 error is returned after uploading the bundle", function () { it("should fail if --disable-duplicate-release-error is not set", async function () { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // prettier-ignore const args: CommandArgs = getCommandArgsForReleaseCommand( [ "-c", releaseFilePath, "--description", appDescription, "-t", fakeParamsForRequests.appVersion, ], fakeParamsForRequests ); nockCreateRelease({ mandatory: false, disabled: false, statusCode: 409 }); // Act const command = new CodePushReleaseCommand(args); const result = (await command.execute()) as CommandFailedResult; // Assert expect(result.succeeded).to.be.false; }); it("should succeed if --disable-duplicate-release-error is set", async function () { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // prettier-ignore const args: CommandArgs = getCommandArgsForReleaseCommand( [ "-c", releaseFilePath, "--description", appDescription, "-t", fakeParamsForRequests.appVersion, "--disable-duplicate-release-error" ], fakeParamsForRequests ); nockCreateRelease({ mandatory: false, disabled: false, statusCode: 409 }); // Act const command = new CodePushReleaseCommand(args); const result = await command.execute(); // Assert expect(result.succeeded).to.be.true; }); }); it("should fail if 403 error is returned", async function () { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); // prettier-ignore const args: CommandArgs = getCommandArgsForReleaseCommand( [ "-c", releaseFilePath, "--description", appDescription, "-t", fakeParamsForRequests.appVersion ], fakeParamsForRequests ); nockCreateRelease({ mandatory: false, disabled: false, statusCode: 403 }); // Act const command = new CodePushReleaseCommand(args); const result = await command.execute(); // Assert expect(result.succeeded).to.be.false; }); it("should remove temporary zip bundle at the end", async function () { const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); const goldenArgs = { // prettier-ignore args: [ "--update-contents-path", releaseFilePath, "--target-binary-version", fakeParamsForRequests.appVersion, "--deployment-name", "Staging", "--description", "app description", "--disabled", "--mandatory", "--private-key-path", "fake/private-key-path", "--disable-duplicate-release-error", "--rollout", "100", "--app", `${fakeParamsForRequests.userName}/${fakeParamsForRequests.appName}`, "--token", fakeParamsForRequests.token, ], command: ["codepush", "release"], commandPath: "fake/path", }; nockPlatformRequest("Cordova", fakeParamsForRequests, nockedApiGatewayRequests); nockCreateRelease({ mandatory: true, disabled: true, statusCode: 201 }); const rmDirSpy = sandbox.spy(pfs, "rmDir"); // Act const command = new CodePushReleaseCommand(goldenArgs); await command.execute(); // Assert expect(rmDirSpy.calledOnce).to.be.true; }); }); context("signed release", () => { describe("path generation should correctly work", () => { [ { platform: "React-Native", lastFolderForSignPathCheck: true }, { platform: "Cordova", lastFolderForSignPathCheck: false }, { platform: "Electron", lastFolderForSignPathCheck: false }, ].forEach((testCase) => { it(`for ${testCase.platform} with private key`, async () => { // Arrange const releaseFilePath = createFile(tmpFolderPath, releaseFileName, releaseFileContent); nockPlatformRequest(testCase.platform, fakeParamsForRequests, nockedApiGatewayRequests); const args: CommandArgs = getCommandArgsForReleaseCommand( // prettier-ignore [ "-c", releaseFilePath, "-k", "fakePrivateKey.pem", "--description", appDescription, "-t", fakeParamsForRequests.appVersion, ], fakeParamsForRequests ); // Act const testRelaseSkeleton = new CodePushReleaseCommand(args); const result = await testRelaseSkeleton.execute(); // Assert expect(result.succeeded).to.be.true; const lastFolderForSignPath = getLastFolderForSignPath(stubbedSign); expect(lastFolderForSignPath === "CodePush").to.eql( testCase.lastFolderForSignPathCheck, `Last folder in path should ${!testCase.lastFolderForSignPathCheck ? "not" : ""} be 'CodePush'` ); nockedApiGatewayRequests.done(); }); }); }); }); function nockCreateRelease(options: { mandatory: boolean; disabled: boolean; statusCode: number }) { if (nockedCreateReleaseInterceptor) { Nock.removeInterceptor(nockedCreateReleaseInterceptor); } nockedCreateReleaseInterceptor = nockedApiGatewayRequests.post( `/${fakeParamsForRequests.appVersion}/apps/${fakeParamsForRequests.userName}/${fakeParamsForRequests.appName}/deployments/Staging/releases`, { release_upload: releaseUploadResponse, target_binary_version: fakeParamsForRequests.appVersion, mandatory: options.mandatory, disabled: options.disabled, description: appDescription, rollout: 100, } ); nockedCreateReleaseInterceptor .reply(options.statusCode, { target_binary_range: fakeParamsForRequests.appVersion, blob_url: "storagePackage.blobUrl", description: "storagePackage.description", is_disabled: "storagePackage.isDisabled", is_mandatory: options.mandatory, label: "storagePackage.label", original_deployment: "storagePackage.originalDeployment", original_label: "storagePackage.originalLabel", package_hash: "storagePackage.packageHash", released_by: "userEmail", release_method: "releaseMethod", rollout: 100, size: 512, upload_time: "uploadTime", }) .persist(); } });
the_stack
import { Yok } from "../lib/common/yok"; import * as stubs from "./stubs"; import { ProjectTemplatesService } from "../lib/services/project-templates-service"; import { assert } from "chai"; import * as path from "path"; import * as constants from "../lib/constants"; import { INpmInstallResultInfo, INodePackageManagerInstallOptions, INpmPackageNameParts, INpmInstallOptions, } from "../lib/declarations"; import { IProjectTemplatesService } from "../lib/definitions/project"; import { IInjector } from "../lib/common/definitions/yok"; import { IAnalyticsService, IFileSystem } from "../lib/common/declarations"; import { IEventActionData } from "../lib/common/definitions/google-analytics"; const nativeScriptValidatedTemplatePath = "nsValidatedTemplatePath"; function createTestInjector( configuration: { shouldNpmInstallThrow?: boolean; packageJsonContent?: any; packageVersion?: string; packageName?: string; } = {} ): IInjector { const injector = new Yok(); injector.register("errors", stubs.ErrorsStub); injector.register("logger", stubs.LoggerStub); injector.register("fs", { exists: (pathToCheck: string) => false, readJson: (pathToFile: string) => configuration.packageJsonContent || {}, }); injector.register("staticConfig", { version: "8.0.0" }); class NpmStub extends stubs.NodePackageManagerStub { public async install( packageName: string, pathToSave: string, config: INodePackageManagerInstallOptions ): Promise<INpmInstallResultInfo> { if (configuration.shouldNpmInstallThrow) { throw new Error("NPM install throws error."); } return { name: "Some Result", version: "1" }; } async getPackageNameParts( fullPackageName: string ): Promise<INpmPackageNameParts> { return { name: configuration.packageName || fullPackageName, version: configuration.packageVersion || "", }; } } injector.register("packageManager", NpmStub); class NpmInstallationManagerStub extends stubs.PackageInstallationManagerStub { async install( packageName: string, pathToSave?: string, options?: INpmInstallOptions ): Promise<string> { if (configuration.shouldNpmInstallThrow) { throw new Error("NPM install throws error."); } return Promise.resolve(nativeScriptValidatedTemplatePath); } } injector.register("packageInstallationManager", NpmInstallationManagerStub); injector.register("projectTemplatesService", ProjectTemplatesService); injector.register("analyticsService", { track: async (): Promise<any[]> => undefined, trackEventActionInGoogleAnalytics: (data: IEventActionData) => Promise.resolve(), }); injector.register("pacoteService", { manifest: (packageName: string) => { const packageJsonContent = configuration.packageJsonContent || {}; packageJsonContent.name = packageName; return Promise.resolve(packageJsonContent); }, }); return injector; } describe("project-templates-service", () => { describe("prepareTemplate", () => { // describe("returns correct path to template", () => { // // it("when reserved template name is used", async () => { // // const testInjector = createTestInjector(); // // const projectTemplatesService = testInjector.resolve< // // IProjectTemplatesService // // >("projectTemplatesService"); // // const { templatePath } = await projectTemplatesService.prepareTemplate( // // "typescript", // // "tempFolder" // // ); // // assert.strictEqual( // // path.basename(templatePath), // // nativeScriptValidatedTemplatePath // // ); // // assert.strictEqual( // // isDeleteDirectoryCalledForNodeModulesDir, // // true, // // "When correct path is returned, template's node_modules directory should be deleted." // // ); // // }); // // // // it("when reserved template name is used (case-insensitive test)", async () => { // // const testInjector = createTestInjector(); // // const projectTemplatesService = testInjector.resolve< // // IProjectTemplatesService // // >("projectTemplatesService"); // // const { templatePath } = await projectTemplatesService.prepareTemplate( // // "tYpEsCriPT", // // "tempFolder" // // ); // // assert.strictEqual( // // path.basename(templatePath), // // nativeScriptValidatedTemplatePath // // ); // // assert.strictEqual( // // isDeleteDirectoryCalledForNodeModulesDir, // // true, // // "When correct path is returned, template's node_modules directory should be deleted." // // ); // // }); // // // }); it("uses defaultTemplate when undefined is passed as parameter", async () => { const testInjector = createTestInjector(); const projectTemplatesService = testInjector.resolve< IProjectTemplatesService >("projectTemplatesService"); const { templateName } = await projectTemplatesService.prepareTemplate( undefined, //constants.RESERVED_TEMPLATE_NAMES["default"], "tempFolder" ); assert.strictEqual( templateName, constants.RESERVED_TEMPLATE_NAMES["default"] ); // assert.strictEqual( // isDeleteDirectoryCalledForNodeModulesDir, // true, // "When correct path is returned, template's node_modules directory should be deleted." // ); }); describe("sends correct information to Google Analytics", () => { let analyticsService: IAnalyticsService; let dataSentToGoogleAnalytics: IEventActionData[] = []; let testInjector: IInjector; let projectTemplatesService: IProjectTemplatesService; beforeEach(() => { testInjector = createTestInjector({ shouldNpmInstallThrow: false }); analyticsService = testInjector.resolve<IAnalyticsService>( "analyticsService" ); const fs = testInjector.resolve<IFileSystem>("fs"); fs.exists = (filePath: string) => false; dataSentToGoogleAnalytics = []; analyticsService.trackEventActionInGoogleAnalytics = async ( data: IEventActionData ): Promise<void> => { dataSentToGoogleAnalytics.push(data); }; projectTemplatesService = testInjector.resolve( "projectTemplatesService" ); }); it("sends template name when the template is used from npm", async () => { const templateName = "template-from-npm"; await projectTemplatesService.prepareTemplate( templateName, "tempFolder" ); assert.deepStrictEqual(dataSentToGoogleAnalytics, [ { action: constants.TrackActionNames.CreateProject, isForDevice: null, additionalData: templateName, }, { action: constants.TrackActionNames.UsingTemplate, additionalData: templateName, }, ]); }); it("sends template name (from template's package.json) when the template is used from local path", async () => { const templateName = "my-own-local-template"; const localTemplatePath = "/Users/username/localtemplate"; const fs = testInjector.resolve<IFileSystem>("fs"); fs.exists = (filePath: string): boolean => true; const pacoteService = testInjector.resolve<IPacoteService>( "pacoteService" ); pacoteService.manifest = () => Promise.resolve({ name: templateName }); await projectTemplatesService.prepareTemplate( localTemplatePath, "tempFolder" ); assert.deepStrictEqual(dataSentToGoogleAnalytics, [ { action: constants.TrackActionNames.CreateProject, isForDevice: null, additionalData: `${constants.ANALYTICS_LOCAL_TEMPLATE_PREFIX}${templateName}`, }, { action: constants.TrackActionNames.UsingTemplate, additionalData: `${constants.ANALYTICS_LOCAL_TEMPLATE_PREFIX}${templateName}`, }, ]); }); it("sends the template name (path to dirname) when the template is used from local path but there's no package.json at the root", async () => { const templateName = "localtemplate"; const localTemplatePath = `/Users/username/${templateName}`; const fs = testInjector.resolve<IFileSystem>("fs"); fs.exists = (localPath: string): boolean => path.basename(localPath) !== constants.PACKAGE_JSON_FILE_NAME; const pacoteService = testInjector.resolve<IPacoteService>( "pacoteService" ); pacoteService.manifest = () => Promise.resolve({}); await projectTemplatesService.prepareTemplate( localTemplatePath, "tempFolder" ); assert.deepStrictEqual(dataSentToGoogleAnalytics, [ { action: constants.TrackActionNames.CreateProject, isForDevice: null, additionalData: `${constants.ANALYTICS_LOCAL_TEMPLATE_PREFIX}${templateName}`, }, { action: constants.TrackActionNames.UsingTemplate, additionalData: `${constants.ANALYTICS_LOCAL_TEMPLATE_PREFIX}${templateName}`, }, ]); }); }); describe("uses correct version", () => { [ { name: "is correct when package version is passed", templateName: "some-template@1.0.0", expectedVersion: "1.0.0", expectedTemplateName: "some-template", }, { name: "is correct when reserved package name with version is passed", templateName: "typescript@1.0.0", expectedVersion: "1.0.0", expectedTemplateName: "@nativescript/template-hello-world-ts", }, { name: "is correct when scoped package name without version is passed", templateName: "@nativescript/vue-template", expectedVersion: "^8.0.0", expectedTemplateName: "@nativescript/vue-template", }, { name: "is correct when scoped package name with version is passed", templateName: "@nativescript/vue-template@1.0.0", expectedVersion: "1.0.0", expectedTemplateName: "@nativescript/vue-template", }, ].forEach((testCase) => { it(testCase.name, async () => { const testInjector = createTestInjector({ packageVersion: testCase.expectedVersion, packageName: testCase.expectedTemplateName, }); const projectTemplatesService = testInjector.resolve< IProjectTemplatesService >("projectTemplatesService"); const { version, templateName, } = await projectTemplatesService.prepareTemplate( testCase.templateName, "tempFolder" ); assert.strictEqual(version, testCase.expectedVersion); assert.strictEqual(templateName, testCase.expectedTemplateName); }); }); }); }); });
the_stack
try { // eslint-disable-next-line @typescript-eslint/no-var-requires require("fs").statSync(`${__filename}.map`); // We check if source maps are available // eslint-disable-next-line @typescript-eslint/no-var-requires require("source-map-support").install(); // If they are, we enable stack traces translation to typescript } catch (exceptions) { // If something goes wrong, we just ignore the errors } // @endif import * as path from "path"; import * as fs from "fs"; import * as vscode from "vscode"; import * as semver from "semver"; import * as nls from "vscode-nls"; import { EntryPointHandler, ProcessType } from "../common/entryPointHandler"; import { ErrorHelper } from "../common/error/errorHelper"; import { InternalErrorCode } from "../common/error/internalErrorCode"; import { ProjectVersionHelper } from "../common/projectVersionHelper"; import { Telemetry } from "../common/telemetry"; import { TelemetryHelper, ICommandTelemetryProperties } from "../common/telemetryHelper"; import { DebugSessionBase } from "../debugger/debugSessionBase"; import { CONTEXT_VARIABLES_NAMES } from "../common/contextVariablesNames"; import { getExtensionVersion, getExtensionName, findFileInFolderHierarchy, } from "../common/extensionHelper"; import { SettingsHelper } from "./settingsHelper"; import { ReactDirManager } from "./reactDirManager"; import { OutputChannelLogger } from "./log/OutputChannelLogger"; import { ReactNativeDebugConfigProvider } from "./debuggingConfiguration/reactNativeDebugConfigProvider"; import { ReactNativeDebugDynamicConfigProvider } from "./debuggingConfiguration/reactNativeDebugDynamicConfigProvider"; import { DEBUG_TYPES } from "./debuggingConfiguration/debugConfigTypesAndConstants"; import { LaunchJsonCompletionProvider, JsonLanguages, } from "./debuggingConfiguration/launchJsonCompletionProvider"; import { ReactNativeSessionManager } from "./reactNativeSessionManager"; import { ProjectsStorage } from "./projectsStorage"; import { AppLauncher } from "./appLauncher"; import { LogCatMonitorManager } from "./android/logCatMonitorManager"; import { ExtensionConfigManager } from "./extensionConfigManager"; import { TipNotificationService } from "./services/tipsNotificationsService/tipsNotificationService"; import { SurveyService } from "./services/surveyService/surveyService"; import { RNProjectObserver } from "./rnProjectObserver"; import { StopElementInspector, StopPackager } from "./commands"; nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone, })(); const localize = nls.loadMessageBundle(); /* all components use the same packager instance */ const outputChannelLogger = OutputChannelLogger.getMainChannel(); const entryPointHandler = new EntryPointHandler(ProcessType.Extension, outputChannelLogger); // #todo> are we sure we need null here and this is the correct place for this? export let debugConfigProvider: ReactNativeDebugConfigProvider | null; const APP_NAME = "react-native-tools"; interface ISetupableDisposable extends vscode.Disposable { setup(): Promise<any>; } let EXTENSION_CONTEXT: vscode.ExtensionContext; /** * We initialize the counter starting with a large value in order * to not overlap indices of the workspace folders originally generated by VS Code * {@link https://code.visualstudio.com/api/references/vscode-api#WorkspaceFolder} */ let COUNT_WORKSPACE_FOLDERS = 9000; export async function activate(context: vscode.ExtensionContext): Promise<void> { const extensionName = getExtensionName(); const appVersion = getExtensionVersion(); if (!appVersion) { throw new Error(localize("ExtensionVersionNotFound", "Extension version is not found")); } if (extensionName) { const extensionFirstTimeInstalled = !cachedVersionExists(); const isUpdatedExtension = isUpdatedVersion(appVersion); if (extensionName.includes("preview")) { if (showTwoVersionFoundNotification()) { return; } } else if (isUpdatedExtension) { showChangelogNotificationOnUpdate(appVersion); } if (isUpdatedExtension) { TipNotificationService.getInstance().updateTipsConfig(); } void TipNotificationService.getInstance().showTipNotification(); SurveyService.getInstance().setExtensionFirstTimeInstalled(extensionFirstTimeInstalled); void SurveyService.getInstance().promptSurvey(); } outputChannelLogger.debug("Begin to activate..."); outputChannelLogger.debug(`Extension version: ${appVersion}`); // eslint-disable-next-line @typescript-eslint/no-var-requires const ExtensionTelemetryReporter = require("vscode-extension-telemetry").default; const reporter = new ExtensionTelemetryReporter( APP_NAME, appVersion, Telemetry.APPINSIGHTS_INSTRUMENTATIONKEY, ); const configProvider = (debugConfigProvider = new ReactNativeDebugConfigProvider()); const dymConfigProvider = new ReactNativeDebugDynamicConfigProvider(); const completionItemProviderInst = new LaunchJsonCompletionProvider(); const workspaceFolders: readonly vscode.WorkspaceFolder[] | undefined = vscode.workspace.workspaceFolders; let extProps: ICommandTelemetryProperties = {}; if (workspaceFolders) { extProps = { workspaceFoldersCount: { value: workspaceFolders.length, isPii: false }, }; } EXTENSION_CONTEXT = context; return entryPointHandler.runApp( APP_NAME, appVersion, ErrorHelper.getInternalError(InternalErrorCode.ExtensionActivationFailed), reporter, async () => { EXTENSION_CONTEXT.subscriptions.push( vscode.workspace.onDidChangeWorkspaceFolders(event => onChangeWorkspaceFolders(event), ), ); EXTENSION_CONTEXT.subscriptions.push( vscode.workspace.onDidChangeConfiguration(() => onChangeConfiguration()), ); EXTENSION_CONTEXT.subscriptions.push(TipNotificationService.getInstance()); EXTENSION_CONTEXT.subscriptions.push(SurveyService.getInstance()); EXTENSION_CONTEXT.subscriptions.push( vscode.debug.registerDebugConfigurationProvider( DEBUG_TYPES.REACT_NATIVE, configProvider, ), ); EXTENSION_CONTEXT.subscriptions.push( vscode.debug.registerDebugConfigurationProvider( DEBUG_TYPES.REACT_NATIVE, dymConfigProvider, vscode.DebugConfigurationProviderTriggerKind.Dynamic, ), ); EXTENSION_CONTEXT.subscriptions.push( vscode.debug.registerDebugConfigurationProvider( DEBUG_TYPES.REACT_NATIVE_DIRECT, dymConfigProvider, vscode.DebugConfigurationProviderTriggerKind.Dynamic, ), ); EXTENSION_CONTEXT.subscriptions.push( vscode.languages.registerCompletionItemProvider( { language: JsonLanguages.json }, completionItemProviderInst, ), ); EXTENSION_CONTEXT.subscriptions.push( vscode.languages.registerCompletionItemProvider( { language: JsonLanguages.jsonWithComments }, completionItemProviderInst, ), ); const sessionManager = new ReactNativeSessionManager(); EXTENSION_CONTEXT.subscriptions.push( vscode.debug.registerDebugAdapterDescriptorFactory( DEBUG_TYPES.REACT_NATIVE, sessionManager, ), ); EXTENSION_CONTEXT.subscriptions.push( vscode.debug.registerDebugAdapterDescriptorFactory( DEBUG_TYPES.REACT_NATIVE_DIRECT, sessionManager, ), ); EXTENSION_CONTEXT.subscriptions.push(sessionManager); EXTENSION_CONTEXT.subscriptions.push( DebugSessionBase.onDidTerminateRootDebugSession(terminateEvent => { sessionManager.terminate(terminateEvent); }), ); const activateExtensionEvent = TelemetryHelper.createTelemetryEvent("activate"); Telemetry.send(activateExtensionEvent); const promises: Promise<void>[] = []; if (workspaceFolders) { outputChannelLogger.debug(`Projects found: ${workspaceFolders.length}`); workspaceFolders.forEach((folder: vscode.WorkspaceFolder) => { promises.push(onFolderAdded(folder)); }); } else { outputChannelLogger.warning("Could not find workspace while activating"); TelemetryHelper.sendErrorEvent( "ActivateCouldNotFindWorkspace", ErrorHelper.getInternalError(InternalErrorCode.CouldNotFindWorkspace), ); } await Promise.all(promises); await registerVscodeCommands(); }, extProps, ); } export function deactivate(): Promise<void> { return new Promise<void>(resolve => { // Kill any packager processes that we spawned void entryPointHandler.runFunction( "extension.deactivate", ErrorHelper.getInternalError(InternalErrorCode.FailedToStopPackagerOnExit), async () => { debugConfigProvider = null; await Promise.all( Object.values(ProjectsStorage.projectsCache).map(it => StopPackager.formInstance().executeLocally(it), ), ); await StopElementInspector.formInstance().executeLocally(); LogCatMonitorManager.cleanUp(); resolve(); }, true, ); }); } function onChangeWorkspaceFolders(event: vscode.WorkspaceFoldersChangeEvent) { if (event.removed.length) { event.removed.forEach(folder => { onFolderRemoved(folder); }); } if (event.added.length) { event.added.forEach(folder => { void onFolderAdded(folder); }); } } // eslint-disable-next-line @typescript-eslint/no-unused-vars function onChangeConfiguration() { // TODO implements } export function createAdditionalWorkspaceFolder(folderPath: string): vscode.WorkspaceFolder | null { if (fs.existsSync(folderPath)) { const folderUri = vscode.Uri.file(folderPath); const folderName = path.basename(folderPath); const newFolder = { uri: folderUri, name: folderName, index: ++COUNT_WORKSPACE_FOLDERS, }; return newFolder; } return null; } export function getCountOfWorkspaceFolders(): number { return COUNT_WORKSPACE_FOLDERS; } export async function onFolderAdded(folder: vscode.WorkspaceFolder): Promise<void> { const rootPath = folder.uri.fsPath; const projectRootPath = SettingsHelper.getReactNativeProjectRoot(rootPath); outputChannelLogger.debug(`Add project: ${projectRootPath}`); const versions = await ProjectVersionHelper.tryToGetRNSemverValidVersionsFromProjectPackage( projectRootPath, ProjectVersionHelper.generateAllAdditionalPackages(), projectRootPath, ); outputChannelLogger.debug(`React Native version: ${versions.reactNativeVersion}`); const promises = []; if (ProjectVersionHelper.isVersionError(versions.reactNativeVersion)) { outputChannelLogger.debug( `react-native package version is not found in ${projectRootPath}. Reason: ${versions.reactNativeVersion}`, ); TelemetryHelper.sendErrorEvent( "AddProjectReactNativeVersionIsEmpty", ErrorHelper.getInternalError(InternalErrorCode.CouldNotFindProjectVersion), versions.reactNativeVersion, ); } else if (isSupportedVersion(versions.reactNativeVersion)) { activateCommands(); promises.push( entryPointHandler.runFunction( "debugger.setupLauncherStub", ErrorHelper.getInternalError(InternalErrorCode.DebuggerStubLauncherFailed), async () => { const reactDirManager = new ReactDirManager(rootPath); const projectObserver = new RNProjectObserver(projectRootPath, versions); await setupAndDispose(reactDirManager); ProjectsStorage.addFolder( projectRootPath, new AppLauncher(reactDirManager, projectObserver, folder), ); COUNT_WORKSPACE_FOLDERS++; }, ), ); } else { outputChannelLogger.debug(`react-native@${versions.reactNativeVersion} isn't supported`); } await Promise.all(promises); } function activateCommands(): void { void vscode.commands.executeCommand("setContext", CONTEXT_VARIABLES_NAMES.IS_RN_PROJECT, true); } function onFolderRemoved(folder: vscode.WorkspaceFolder): void { const appLauncher = ProjectsStorage.getFolder(folder); Object.keys(appLauncher).forEach(key => { if (appLauncher[key].dispose) { appLauncher[key].dispose(); } }); outputChannelLogger.debug(`Delete project: ${folder.uri.fsPath}`); ProjectsStorage.delFolder(folder); try { // Preventing memory leaks EXTENSION_CONTEXT.subscriptions.forEach((element: any, index: number) => { if (element.isDisposed) { EXTENSION_CONTEXT.subscriptions.splice(index, 1); // Array.prototype.filter doesn't work, "context.subscriptions" is read only } }); } catch (err) { // Ignore } } async function setupAndDispose<T extends ISetupableDisposable>( setuptableDisposable: T, ): Promise<T> { await setuptableDisposable.setup(); EXTENSION_CONTEXT.subscriptions.push(setuptableDisposable); return setuptableDisposable; } function isSupportedVersion(version: string): boolean { if ( !!semver.valid(version) && !semver.gte(version, "0.19.0") && !ProjectVersionHelper.isCanaryVersion(version) ) { TelemetryHelper.sendSimpleEvent("unsupportedRNVersion", { rnVersion: version }); const shortMessage = localize( "ReactNativeToolsRequiresMoreRecentVersionThan019", "React Native Tools need React Native version 0.19.0 or later to be installed in <PROJECT_ROOT>/node_modules/", ); const longMessage = `${shortMessage}: ${version}`; void vscode.window.showWarningMessage(shortMessage); outputChannelLogger.warning(longMessage); return false; } // !!semver.valid(version) === false is OK for us, someone can use custom RN implementation with custom version e.g. -> "0.2018.0107-v1" return true; } function showTwoVersionFoundNotification(): boolean { if (vscode.extensions.getExtension("msjsdiag.vscode-react-native")) { void vscode.window.showInformationMessage( localize( "RNTTwoVersionsFound", "React Native Tools: Both Stable and Preview extensions are installed. Stable will be used. Disable or remove it to work with Preview version.", ), ); return true; } return false; } function isUpdatedVersion(currentVersion: string): boolean { if (!cachedVersionExists() || ExtensionConfigManager.config.get("version") !== currentVersion) { ExtensionConfigManager.config.set("version", currentVersion); return true; } return false; } function cachedVersionExists(): boolean { return ExtensionConfigManager.config.has("version"); } function showChangelogNotificationOnUpdate(currentVersion: string) { const changelogFile = findFileInFolderHierarchy(__dirname, "CHANGELOG.md"); if (changelogFile) { void vscode.window .showInformationMessage( localize( "RNTHaveBeenUpdatedToVersion", "React Native Tools have been updated to {0}", currentVersion, ), localize("MoreDetails", "More details"), ) .then(() => { void vscode.commands.executeCommand( "markdown.showPreview", vscode.Uri.file(changelogFile), ); }); } } async function registerVscodeCommands() { const commands = await import("./commands"); Object.values(commands).forEach(it => { EXTENSION_CONTEXT.subscriptions.push(it.formInstance().register(entryPointHandler)); }); }
the_stack
import Benchmarkjs from 'benchmark' import endent from 'endent' import kleur, { underline } from 'kleur' import { difference, differenceWith, isEmpty, sortBy } from 'lodash' import { EOL } from 'os' import { inspect } from 'util' import VError from 'verror' import * as Config from '../declaration/config' import { renderCaseSummary, renderGroupResultForTerminal } from '../render' import { AfterGroupContext, CaseReport, CaseResult, GroupResult, GroupResultSimplified, ParameterChangeCallbackInfo, ParameterName, Report, } from '../types' import { d, millisecondsToSeconds } from '../utils' import { lintError, UserError } from '../utils/errors' import { ARROW_POINTING_RIGHT, indent, INDENT, renderIndentedList } from '../utils/terminal' import { applyParametersFilterAcrossCases, logUsageResults } from './filtering' import { createGroupResult } from './helpers' import { compileContext, countCases, PrimedBema, PrimedCase } from './prime' export async function runBema({ config, bema, }: { config: Config.Config bema: PrimedBema }): Promise<Report> { const bemaTimeStarted = Date.now() const report: Report = { name: config.name, time: { elapsed: 0, finished: 0, started: 0, }, groups: [], } let parametersOfCurrentCase: Record<string, string> = {} const caseCount = countCases(bema) d('starting analysis and run of (%d) collected benchmarks', caseCount) if (caseCount === 0) { const message = kleur.red(`No cases were defined.`) throw new UserError({ message }) } // todo frontload filter of benchmarks with no cases defined // todo warn when a benchmark is filtered out this way // todo handle case of all benchmarks filtered out this way and thus effectively no benchmarks defined (like initial check) /** Apply group filter if any */ const groups = bema.groups let selectedGroups = groups // const config = Config.resolve(_bema.$.state.configInput) const logger = config.logger if (config.onlyGroups) { const { onlyGroups } = config selectedGroups = selectedGroups.filter((group) => onlyGroups.exec(group.name)) } if (config.skipGroups) { const { skipGroups } = config selectedGroups = selectedGroups.filter((group) => !skipGroups.exec(group.name)) } /** Give feedback about filtered groups */ if (Config.hasGroupFilters(config)) { const excludedGroups = differenceWith(groups, selectedGroups, (g1, g2) => { return g1.name === g2.name }) if (isEmpty(selectedGroups)) { const message = kleur.yellow(`All groups filtered out so nothing to do. Stopping benchmark run now.`) throw new UserError({ message }) } else { d(`excluded ${excludedGroups.length} group(s): ${excludedGroups.map((group) => group.name).join(', ')}`) const message = endent` ${kleur.green(`Excluded ${excludedGroups.length} group(s) by group filters.`)} ${renderIndentedList(excludedGroups.map((s) => `${s.name}`))} ` logger.info(message) } } /** Validate that cases did supply required parameters */ const errorsIndex: Record< string, { benchmarkName: string requiredParameters: ParameterName[] badCases: { caseName: string missingKeys: string[] }[] } > = {} for (const g of selectedGroups) { for (const c of g.cases) { const keyDifference = difference(c.parameterDefinitions, Object.keys(c.parameters)) if (!isEmpty(keyDifference)) { errorsIndex[g.name] = errorsIndex[g.name] ?? { benchmarkName: g.name, requiredParameters: c.parameterDefinitions, badCases: [], } // @ts-expect-error FIXME errorsIndex[g.name].badCases.push({ caseName: c.name, missingKeys: keyDifference, }) } } } const errors = Object.values(errorsIndex) if (!isEmpty(errors)) { let m = '' m += kleur.bold( kleur.red( `${errors.flatMap((be) => be.badCases).length} case(s) among ${ errors.length } group(s) are missing required parameters.\n` ) ) m += '\n' m += errors .map((be) => { let m = '' m += underline( `Suite ${kleur.bold(be.benchmarkName)} has ${ be.badCases.length } case(s) missing required parameters` ) + '\n' m += '\n' m += `${INDENT}Required parameters:\n` m += be.requiredParameters .map((x) => { const errorCount = be.badCases.filter((bc) => bc.missingKeys.includes(x)).length if (errorCount > 0) { return `${INDENT}${ARROW_POINTING_RIGHT} ${kleur.bold(x)} ${kleur.red( `✖ ${errorCount} case(s) missing this` )}` } else { return `${INDENT}${ARROW_POINTING_RIGHT} ${kleur.bold(x)} ${kleur.green(`✔`)}` } }) .join('\n') + '\n' m += '\n' m += `${INDENT}Cases missing one or more required parameters:\n` m += be.badCases .map((ce) => { let m = '' m += `${INDENT}${ARROW_POINTING_RIGHT} ${kleur.bold(ce.caseName)} is missing: ` + ce.missingKeys.map((x) => `${kleur.red(x)}`).join(', ') return m }) .join('\n') m += '\n' return m }) .join('\n\n') + '\n' throw new UserError({ message: m }) } /** Run selected benchmarks */ let initial = true for (const group of selectedGroups) { const groupTimeStarted = Date.now() if (isEmpty(group.cases)) { lintError(config.logger, { message: endent`The group "${group.name}" has no cases defined, skipping.` }) continue } const caseResults: CaseResult[] = [] d('running group "%s"', group.name) logger.info(underline(kleur.bold(EOL + EOL + `Starting Group ${kleur.magenta(group.name)}`)) + EOL) logger.info(kleur.dim(`${group.cases.length} case(s)`)) /** Apply parameter filters if any (aka. select cases) */ if (Config.hasParameterFilters(config)) { d('applying parameter filters', config.parametersFilter) } const caseFilteringByParamsResult = applyParametersFilterAcrossCases(config.parametersFilter, group.cases) logUsageResults(config.logger, caseFilteringByParamsResult) if (isEmpty(caseFilteringByParamsResult.casesSelected)) { lintError(config.logger, { message: endent` ${kleur.red('All cases filtered out by parameter filters! This is probably not what you intended.')} ${kleur.dim(`Note: Multiple filters use AND semantic.`)} ${kleur.bold(`"Only" Filters:`)} ${ isEmpty(config.parametersFilter.only) ? indent('NA') : renderIndentedList( config.parametersFilter.only.map((f) => { const parts: string[] = [] if (f.name) parts.push(`name: ${inspect(f.name)}`) if (f.value) parts.push(`value: ${inspect(f.value)}`) return parts.join(' ') }) ) } ${kleur.bold(`"Skip" Filters:`)} ${ isEmpty(config.parametersFilter.skip) ? indent('NA') : renderIndentedList( config.parametersFilter.skip.map((f) => { const parts: string[] = [] if (f.name) parts.push(`name: ${inspect(f.name)}`) if (f.value) parts.push(`value: ${inspect(f.value)}`) return parts.join(' ') }) ) } ${kleur.bold(`The available parameter types are:`)} ${renderIndentedList(group.cases[0]?.parameterDefinitions ?? []) /* todo list out each case? */} ${kleur.bold(`The parameters of each case are:`)} ${renderIndentedList( group.cases.map((c) => Object.entries(c.parameters) .map((ent) => `${ent[0]}:${ent[1]}`) .join(', ') ) )} `, }) } else if (Config.hasParameterFilters(config)) { const message = kleur.dim( `${caseFilteringByParamsResult.casesSkipped.length} case(s) excluded by parameter filters.` ) + EOL + renderIndentedList(caseFilteringByParamsResult.casesSkipped.map((c) => c.name)) + EOL logger.info(message) } /** Sort selected cases according to group parameter order */ const paramDefs = group.cases[0]?.parameterDefinitions ?? [] const casesSelectedSorted = isEmpty(paramDefs) ? caseFilteringByParamsResult.casesSelected : sortBy( caseFilteringByParamsResult.casesSelected, paramDefs.map((parameterName) => (c: PrimedCase) => c.parameters[parameterName]) ) /** Run selected cases */ logger.info('') for (const c of casesSelectedSorted) { /** Handle parameter change callbacks */ const callbackInfo: ParameterChangeCallbackInfo = { activeCases: casesSelectedSorted.map((c) => { return { parameters: c.parameters, } }), } const parametersOfPreviousCase = parametersOfCurrentCase parametersOfCurrentCase = c.parameters for (const [paramName, paramVal] of Object.entries(parametersOfCurrentCase)) { if (parametersOfPreviousCase[paramName] !== paramVal) { const event = { initial, name: paramName, value: { before: parametersOfPreviousCase[paramName], after: paramVal, }, } for (const { callback, parameterName } of group.parameterChangeCallbacks) { if (parameterName === paramName) { d('running callback for parameterChange ("%s") event', paramName, event) try { await callback(event, callbackInfo) } catch (error) { throw new VError( error, `"onParameterChange" hook callback "${callback.name}" failed while running for parameter "${paramName}"` ) } } } } } /** Run case runner (finally!) */ d('running benchmark group case "%s"', c.name) const beforeCaseContext = await compileContext(c) for (const cb of c.beforeCallbacks) { try { await cb(beforeCaseContext) } catch (error) { throw new VError( error, `"Before case" hook callback "${cb.name}" failed while running before case "${c.name}"` ) } } const { runCallback } = c if (!runCallback) { throw new Error('No runner was defined for this benchmark case') } let caseReport: CaseReport let returnValue: unknown try { if (config.quick) { d('running in quick mode') const start = Date.now() returnValue = await runCallback(beforeCaseContext) const elpased = Date.now() - start caseReport = { quickMode: true, group: group.name, name: c.name, matrix: c.matrixChain, parameters: c.parameters, parametersFromMatrix: c.parametersFromMatrix, parametersFromNotMatrix: c.parametersFromNotMatrix, stats: { moe: 0, rme: 0, sem: 0, variance: 0, deviation: 0, hz: 1000 / elpased, mean: elpased, sample: [elpased], times: { cycle: millisecondsToSeconds(elpased), elapsed: millisecondsToSeconds(elpased), period: millisecondsToSeconds(elpased), timeStamp: start, }, }, } } else { const benchmarkjs = new Benchmarkjs({ defer: true, name: c.name, fn(deferred: Benchmarkjs.Deferred) { Promise.resolve(runCallback(beforeCaseContext)) .then((result_) => { returnValue = result_ }) .finally(() => { deferred.resolve() }) }, ...(config.maxTime ? { maxTime: millisecondsToSeconds(config.maxTime) } : {}), }) await new Promise((res, rej) => { benchmarkjs.on('error', rej) benchmarkjs.on('complete', res) benchmarkjs.run() }) caseReport = { quickMode: false, group: group.name, name: c.name, matrix: c.matrixChain, parameters: parametersOfCurrentCase, parametersFromMatrix: c.parametersFromMatrix, parametersFromNotMatrix: c.parametersFromNotMatrix, stats: { ...benchmarkjs.stats, deviation: benchmarkjs.stats.deviation * 1000, hz: benchmarkjs.hz, mean: benchmarkjs.stats.mean * 1000, times: { ...benchmarkjs.times, }, }, } } } catch (error) { throw new VError(error, `The case "${c.name}" failed while running`) } d( 'got benchmark run return:', inspect(returnValue, { maxArrayLength: 1, maxStringLength: 50, }) ) caseResults.push({ report: caseReport, returnValue, }) /** Run afterEach hooks */ const afterEachCallbackContext = { ...beforeCaseContext, $info: { report: caseReport, returnValue, }, } for (const cb of c.afterCallbacks) { try { await cb(afterEachCallbackContext) } catch (error) { throw new VError( error, `"After case" hook callback "${cb.name}" failed while running for case "${c.name}"` ) } } d('done case') logger.info(renderCaseSummary(caseReport)) initial = false } /** Run afterAll hooks */ const groupResult: GroupResult = createGroupResult({ casesSelected: casesSelectedSorted, group, caseResults, }) const afterAllCallbackInput: AfterGroupContext = { $info: groupResult, } for (const cb of group.afterCallbacks) { try { await cb(afterAllCallbackInput) } catch (error) { throw new VError( error, `"After group" hook callback "${cb.name}" failed while running for group "${group.name}"` ) } } const groupTimeFimished = Date.now() groupResult.time = { finished: groupTimeFimished, started: groupTimeStarted, elapsed: (groupTimeFimished - groupTimeStarted) / 1000, } const GroupResultSimplified: GroupResultSimplified = { time: groupResult.time, name: groupResult.name, caseResultsByMatrix: Object.values(groupResult.caseResults.byMatrix).map((caseResults) => { return caseResults.map(({ report }) => { return { report } }) }), } const summaryTableText = renderGroupResultForTerminal(GroupResultSimplified) logger.info(EOL + summaryTableText) d('done group') report.groups.push(GroupResultSimplified) } const bemaTimeFinished = Date.now() report.time = { started: bemaTimeStarted, finished: bemaTimeFinished, elapsed: (bemaTimeFinished - bemaTimeStarted) / 1000, } d('done') return report }
the_stack
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { StringMap } from '../declarations/string-map'; import removeUndefinedProperties from '../utils/object/remove-undefined-properties'; import { CHILDREN_TO_APPEND_PROP } from './react-content'; import { getComponentClass } from './registry'; const DEBUG = false; export function isReactNode(node: any): node is ReactNode { return (<ReactNode>node).setRenderPendingCallback !== undefined; } /** * Logical representation of everything needed to render a React element in the * DOM, with the needed methods to do so. */ export class ReactNode { // Access to these properties are restricted through setters and functions // so that the dirty "render pending" state of this object can be properly // tracked and all nodes with "render pending" can be flushed at the end // of a render operation. private _props = {}; private _comment: string; private _text: string; private _typeIsReactElementClass: boolean | undefined; private _children: Array<ReactNode> = []; private _typeName: string; private _childrenToAppend: Array<HTMLElement> = []; private _renderedDomElement: HTMLElement; private _parent: HTMLElement | ReactNode; private _isNotRenderable: boolean; private _isDestroyPending: boolean = false; private _isRenderPending = true; get domElement() { return this._renderedDomElement; } set parent(parent: HTMLElement | ReactNode) { this._parent = parent; this.setRenderPending(); } get parent(): HTMLElement | ReactNode { return this._parent; } get shouldRender() { return !this._isNotRenderable; } get destroyPending() { return this._isDestroyPending; } constructor(private type?: React.ReactType | string) { this.setRenderPending(); this._tryResolveTypeIsReactElementClass(); } setRenderPendingCallback = () => null; /** * Track all pending render operations internally and set flag on * renderer factory so that a flush operation can be scheduled for * the "end" of render. */ setRenderPending() { this.setRenderPendingCallback(); this._isRenderPending = true; } /** * Marks the node to be removed from the DOM in the next render cycle. */ destroyNode() { this.setRenderPending(); this._isDestroyPending = true; } /** * Sets an attribute on the node. * @note the value can only be a `string`. See `setProperty` for other use-cases. * @see `Renderer2#setAttribute`. * * @param name The attribute name. * @param value The new value. */ setAttribute(name: string, value: string) { this.setAttributes({ [name]: value }); } /** * Set attributes on this node. * Note that values can only be of type `string`. See `setProperties` for other use-cases. * @see `Renderer2#setAttribute`. * * @param attributes the attributes to set. */ setAttributes(attributes: StringMap<string>) { this.setProperties(attributes); } /** * Sets a prop in the underlying React element. * @see `Renderer2#setProperty`. * * @param name The property name. * @param value The new value. */ setProperty(name: string, value: any) { this.setProperties({ [name]: value }); } /** * Like `setProperty` but for multiple props at once. * * @param properties An object with the props. */ setProperties(properties: StringMap) { this.setRenderPending(); Object.assign(this._props, removeUndefinedProperties(properties)); } /** * Remove a prop or an attribute from the underlying React element. * @see `Renderer2#removeAttribute`. * * @param name The property name. * @param childName _Optional_ A property of `name` to remove instead. * @returns the deleted property */ removeProperty(name: string, childName?: string) { this.setRenderPending(); if (childName) { return delete this._props[name][childName]; } return delete this._props[name]; } /** * Add a direct child of this node. * @see `Renderer2#addChild`. * * @param node The node to add. */ addChild(node: ReactNode) { this.setRenderPending(); this._children.push(node); } /** * Remove a direct child of this node. * @see `Renderer2#removeChild`. * * @param node The node to remove. */ removeChild(node: ReactNode) { this.setRenderPending(); this._children = this._children.filter(child => child !== node); } /** * Cast the node to a comment node. * @see `Renderer2#createComment`. * * @param value the text in the comment to render. * @returns itself. */ asComment(value: string) { this.setRenderPending(); this.type = undefined; this._comment = value; return this; } /** * Cast the node to a text node. * @see `Renderer2#createText`. * * @param value the text to render. * @returns itself. */ asText(value: string) { this.setRenderPending(); this.type = undefined; this._text = value; // Skip appending and rendering of empty text nodes. This may cause a bug // if a single space is desired... if (!value || !value.trim()) { this._isNotRenderable = true; } return this; } /** * Render the node to the DOM, or unmount it, as necessary. * * @returns itself. */ render(): ReactNode { // Only complete render operations for ReactNodes that are parented by HTMLElements. // Those that are parented by other ReactNodes will be rendered recursively by their // parent. if (!isReactNode(this._parent)) { if (this._isDestroyPending && this._parent) { if (DEBUG) { console.log('ReactNode > render > destroy > node:', this.toString(), 'parent:', this.parent); } ReactDOM.unmountComponentAtNode(this._parent); return this; } if (this._isRenderPending) { if (DEBUG) { console.log('ReactNode > render > node:', this.toString(), 'parent:', this.parent); } // It is expected that the element will be recreated and re-rendered with each attribute change. // See: https://reactjs.org/docs/rendering-elements.html ReactDOM.render(this._renderRecursive() as React.ReactElement<{}>, this._parent); this._isRenderPending = false; } } return this; } /** * Appends a child. * * @see `Renderer2#appendChild`. * @note This is called by Angular core when projected content is being added. * * @param projectedContent the content to project. */ appendChild(projectedContent: HTMLElement) { if (DEBUG) { console.error( 'ReactNode > appendChild > node:', this.toString(), 'projectedContent:', projectedContent.toString().trim() ); } this._childrenToAppend.push(projectedContent); } /** * @note for easier debugging. */ toString(): string { if (this._typeName) { return `[${this._typeName} ReactNode]`; } if (this._text) { return '[text ReactNode]'; } if (this._comment) { return '[comment ReactNode]'; } return '[undefined ReactNode]'; } private _renderRecursive(key?: string): React.ReactElement<{}> | string { const children = this._children ? this._children.map((child, index) => child._renderRecursive(index.toString())) : []; if (this._text) { return this._text; } this._props[CHILDREN_TO_APPEND_PROP] = this._childrenToAppend; if (key) { this._props['key'] = key; } // Just having some props on a React element can cause it to // behave undesirably, and since the templates are hard-coded to pass // all Inputs all the time, they pass `undefined` values too. // This ensures these are removed. // Additionally, there are some things that Angular templating forbids, // and stops at-compile time (with errors), such as `Input`s being prefixed with `on`. // Since React does not have the notion of `Output`s as Angular (they are just props of type function, essentially callbacks). // To work around this, we, by convention, prefix any PascalCased prop with `on` here, after the template has already been compiled. const clearedProps = this._transformProps(removeUndefinedProperties(this._props)); if (DEBUG) { console.warn( 'ReactNode > renderRecursive > type:', this.toString(), 'props:', this._props, 'children:', children ); } return React.createElement(this.type, clearedProps, children.length > 0 ? children : undefined); } private _transformProps<TProps extends object>(props: TProps) { return Object.entries(props).reduce((acc, [key, value]) => { const [newKey, newValue] = typeof key !== 'string' ? [key, value] : this._transformProp(key, value); return Object.assign(acc, { [newKey]: newValue }); }, {}); } private _transformProp<TValue = any>(name: string, value: TValue): [string, TValue] { // prop name is camelCased already const firstLetter = name[0]; if (firstLetter === firstLetter.toLowerCase()) { return [name, value]; } // prop name is PascalCased & is a function - assuming render prop or callback prop that has return value // NOTE: Angular doesn't allow passing @Inputs that are prefixed with "on". This is useful for render props and properties representing the "on" state (for example, Toggle). // As a convention, any @Input that starts with a capital letter is prefixed with "on" when passed as a prop to the underlying React component. return [`on${name}`, value]; } private _tryResolveTypeIsReactElementClass() { if (this._typeIsReactElementClass === undefined) { // Comments and text have no type. if (!this.type) { return; } // Store the name of the type for the toString message (debugging). this._typeName = this.type as string; // Attempt to resolve the type as a React Element class name/type. // Since Angular templates are just strings, we can't include types in them. // Therefore, we use the component registry to resolve the type of a component from a string. if (typeof this.type === 'string') { this.type = getComponentClass(this.type); } // If type is still a string, then no React Element matches this string. this._typeIsReactElementClass = typeof this.type !== 'string'; if (DEBUG) { console.log('ReactNode > tryResolveTypeIsReactElementClass > type:', this._typeName); } } } }
the_stack
import * as fs from 'fs-extra'; import walkSync from 'klaw-sync'; import * as path from 'path'; import { ModuleConfiguration } from './ModuleConfiguration'; type PreparedPrefixes = [nameWithExpoPrefix: string, nameWithoutExpoPrefix: string]; /** * prepares _Expo_ prefixes for specified name * @param name module name, e.g. JS package name * @param prefix prefix to prepare with, defaults to _Expo_ * @returns tuple `[nameWithPrefix: string, nameWithoutPrefix: string]` */ const preparePrefixes = (name: string, prefix: string = 'Expo'): PreparedPrefixes => name.startsWith(prefix) ? [name, name.substr(prefix.length)] : [`${prefix}${name}`, name]; const asyncForEach = async <T>( array: T[], callback: (value: T, index: number, array: T[]) => Promise<void> ) => { for (let index = 0; index < array.length; index++) { await callback(array[index], index, array); } }; /** * Removes specified files. If one file doesn't exist already, skips it * @param directoryPath directory containing files to remove * @param filenames array of filenames to remove */ async function removeFiles(directoryPath: string, filenames: string[]) { await Promise.all(filenames.map((filename) => fs.remove(path.resolve(directoryPath, filename)))); } /** * Renames files names * @param directoryPath - directory that holds files to be renamed * @param extensions - array of extensions for files that would be renamed, must be provided with leading dot or empty for no extension, e.g. ['.html', ''] * @param renamings - array of filenames and their replacers */ const renameFilesWithExtensions = async ( directoryPath: string, extensions: string[], renamings: { from: string; to: string }[] ) => { await asyncForEach( renamings, async ({ from, to }) => await asyncForEach(extensions, async (extension) => { const fromFilename = `${from}${extension}`; if (!fs.existsSync(path.join(directoryPath, fromFilename))) { return; } const toFilename = `${to}${extension}`; await fs.rename( path.join(directoryPath, fromFilename), path.join(directoryPath, toFilename) ); }) ); }; /** * Enters each file recursively in provided dir and replaces content by invoking provided callback function * @param directoryPath - root directory * @param replaceFunction - function that converts current content into something different */ const replaceContents = async ( directoryPath: string, replaceFunction: (contentOfSingleFile: string) => string ) => { await Promise.all( walkSync(directoryPath, { nodir: true }).map((file) => replaceContent(file.path, replaceFunction) ) ); }; /** * Replaces content in file. Does nothing if the file doesn't exist * @param filePath - provided file * @param replaceFunction - function that converts current content into something different */ const replaceContent = async ( filePath: string, replaceFunction: (contentOfSingleFile: string) => string ) => { if (!fs.existsSync(filePath)) { return; } const content = await fs.readFile(filePath, 'utf8'); const newContent = replaceFunction(content); if (newContent !== content) { await fs.writeFile(filePath, newContent); } }; /** * Removes all empty subdirs up to and including dirPath * Recursively enters all subdirs and removes them if one is empty or cantained only empty subdirs * @param dirPath - directory path that is being inspected * @returns whether the given base directory and any empty subdirectories were deleted or not */ const removeUponEmptyOrOnlyEmptySubdirs = async (dirPath: string): Promise<boolean> => { const contents = await fs.readdir(dirPath); const results = await Promise.all( contents.map(async (file) => { const filePath = path.join(dirPath, file); const fileStats = await fs.lstat(filePath); return fileStats.isDirectory() && (await removeUponEmptyOrOnlyEmptySubdirs(filePath)); }) ); const isRemovable = results.reduce((acc, current) => acc && current, true); if (isRemovable) { await fs.remove(dirPath); } return isRemovable; }; /** * Prepares iOS part, mainly by renaming all files and some template word in files * Versioning is done automatically based on package.json from JS/TS part * @param modulePath - module directory * @param configuration - naming configuration */ async function configureIOS( modulePath: string, { podName, jsPackageName, viewManager }: ModuleConfiguration ) { const iosPath = path.join(modulePath, 'ios'); // remove ViewManager from template if (!viewManager) { await removeFiles(path.join(iosPath, 'EXModuleTemplate'), [ `EXModuleTemplateView.h`, `EXModuleTemplateView.m`, `EXModuleTemplateViewManager.h`, `EXModuleTemplateViewManager.m`, ]); } await renameFilesWithExtensions( path.join(iosPath, 'EXModuleTemplate'), ['.h', '.m'], [ { from: 'EXModuleTemplateModule', to: `${podName}Module` }, { from: 'EXModuleTemplateView', to: `${podName}View`, }, { from: 'EXModuleTemplateViewManager', to: `${podName}ViewManager`, }, ] ); await renameFilesWithExtensions( iosPath, ['', '.podspec'], [{ from: 'EXModuleTemplate', to: `${podName}` }] ); await replaceContents(iosPath, (singleFileContent) => singleFileContent .replace(/EXModuleTemplate/g, podName) .replace(/ExpoModuleTemplate/g, jsPackageName) ); } /** * Gets path to Android source base dir: android/src/main/[java|kotlin] * Defaults to Java path if both exist * @param androidPath path do module android/ directory * @param flavor package flavor e.g main, test. Defaults to main * @returns path to flavor source base directory */ function findAndroidSourceDir(androidPath: string, flavor: string = 'main'): string { const androidSrcPathBase = path.join(androidPath, 'src', flavor); const javaExists = fs.pathExistsSync(path.join(androidSrcPathBase, 'java')); const kotlinExists = fs.pathExistsSync(path.join(androidSrcPathBase, 'kotlin')); if (!javaExists && !kotlinExists) { throw new Error( `Invalid template. Android source directory not found: ${androidSrcPathBase}/[java|kotlin]` ); } return path.join(androidSrcPathBase, javaExists ? 'java' : 'kotlin'); } /** * Finds java package name based on directory structure * @param flavorSrcPath Path to source base directory: e.g. android/src/main/java * @returns java package name */ function findTemplateAndroidPackage(flavorSrcPath: string) { const srcFiles = walkSync(flavorSrcPath, { filter: (item) => item.path.endsWith('.kt') || item.path.endsWith('.java'), nodir: true, traverseAll: true, }); if (srcFiles.length === 0) { throw new Error('No Android source files found in the template'); } // srcFiles[0] will always be at the most top-level of the package structure const packageDirNames = path.relative(flavorSrcPath, srcFiles[0].path).split('/').slice(0, -1); if (packageDirNames.length === 0) { throw new Error('Template Android sources must be within a package.'); } return packageDirNames.join('.'); } /** * Prepares Android part, mainly by renaming all files and template words in files * Sets all versions in Gradle to 1.0.0 * @param modulePath - module directory * @param configuration - naming configuration */ async function configureAndroid( modulePath: string, { javaPackage, jsPackageName, viewManager }: ModuleConfiguration ) { const androidPath = path.join(modulePath, 'android'); const [, moduleName] = preparePrefixes(jsPackageName, 'Expo'); const androidSrcPath = findAndroidSourceDir(androidPath); const templateJavaPackage = findTemplateAndroidPackage(androidSrcPath); const sourceFilesPath = path.join(androidSrcPath, ...templateJavaPackage.split('.')); const destinationFilesPath = path.join(androidSrcPath, ...javaPackage.split('.')); // remove ViewManager from template if (!viewManager) { removeFiles(sourceFilesPath, [`ModuleTemplateView.kt`, `ModuleTemplateViewManager.kt`]); replaceContent(path.join(sourceFilesPath, 'ModuleTemplatePackage.kt'), (packageContent) => packageContent .replace(/(^\s+)+(^.*?){1}createViewManagers[\s\W\w]+?\}/m, '') .replace(/^.*ViewManager$/, '') ); } await fs.mkdirp(destinationFilesPath); await fs.copy(sourceFilesPath, destinationFilesPath); // Remove leaf directory content await fs.remove(sourceFilesPath); // Cleanup all empty subdirs up to template package root dir await removeUponEmptyOrOnlyEmptySubdirs( path.join(androidSrcPath, templateJavaPackage.split('.')[0]) ); // prepare tests if (fs.existsSync(path.resolve(androidPath, 'src', 'test'))) { const androidTestPath = findAndroidSourceDir(androidPath, 'test'); const templateTestPackage = findTemplateAndroidPackage(androidTestPath); const testSourcePath = path.join(androidTestPath, ...templateTestPackage.split('.')); const testDestinationPath = path.join(androidTestPath, ...javaPackage.split('.')); await fs.mkdirp(testDestinationPath); await fs.copy(testSourcePath, testDestinationPath); await fs.remove(testSourcePath); await removeUponEmptyOrOnlyEmptySubdirs( path.join(androidTestPath, templateTestPackage.split('.')[0]) ); await replaceContents(testDestinationPath, (singleFileContent) => singleFileContent.replace(new RegExp(templateTestPackage, 'g'), javaPackage) ); await renameFilesWithExtensions( testDestinationPath, ['.kt', '.java'], [{ from: 'ModuleTemplateModuleTest', to: `${moduleName}ModuleTest` }] ); } // Replace contents of destination files await replaceContents(androidPath, (singleFileContent) => singleFileContent .replace(new RegExp(templateJavaPackage, 'g'), javaPackage) .replace(/ModuleTemplate/g, moduleName) .replace(/ExpoModuleTemplate/g, jsPackageName) ); await replaceContent(path.join(androidPath, 'build.gradle'), (gradleContent) => gradleContent .replace(/\bversion = ['"][\w.-]+['"]/, "version = '1.0.0'") .replace(/versionCode \d+/, 'versionCode 1') .replace(/versionName ['"][\w.-]+['"]/, "versionName '1.0.0'") ); await renameFilesWithExtensions( destinationFilesPath, ['.kt', '.java'], [ { from: 'ModuleTemplateModule', to: `${moduleName}Module` }, { from: 'ModuleTemplatePackage', to: `${moduleName}Package` }, { from: 'ModuleTemplateView', to: `${moduleName}View` }, { from: 'ModuleTemplateViewManager', to: `${moduleName}ViewManager` }, ] ); } /** * Prepares TS part. * @param modulePath - module directory * @param configuration - naming configuration */ async function configureTS( modulePath: string, { jsPackageName, viewManager }: ModuleConfiguration ) { const [moduleNameWithExpoPrefix, moduleName] = preparePrefixes(jsPackageName); const tsPath = path.join(modulePath, 'src'); // remove View Manager from template if (!viewManager) { await removeFiles(path.join(tsPath), [ 'ExpoModuleTemplateView.tsx', 'ExpoModuleTemplateNativeView.ts', 'ExpoModuleTemplateNativeView.web.tsx', ]); await replaceContent(path.join(tsPath, 'ModuleTemplate.ts'), (fileContent) => fileContent.replace(/(^\s+)+(^.*?){1}ExpoModuleTemplateView.*$/m, '') ); } await renameFilesWithExtensions( path.join(tsPath, '__tests__'), ['.ts'], [{ from: 'ModuleTemplate-test', to: `${moduleName}-test` }] ); await renameFilesWithExtensions( tsPath, ['.tsx', '.ts'], [ { from: 'ExpoModuleTemplateView', to: `${moduleNameWithExpoPrefix}View` }, { from: 'ExpoModuleTemplateNativeView', to: `${moduleNameWithExpoPrefix}NativeView` }, { from: 'ExpoModuleTemplateNativeView.web', to: `${moduleNameWithExpoPrefix}NativeView.web` }, { from: 'ExpoModuleTemplate', to: moduleNameWithExpoPrefix }, { from: 'ExpoModuleTemplate.web', to: `${moduleNameWithExpoPrefix}.web` }, { from: 'ModuleTemplate', to: moduleName }, { from: 'ModuleTemplate.types', to: `${moduleName}.types` }, ] ); await replaceContents(tsPath, (singleFileContent) => singleFileContent .replace(/ExpoModuleTemplate/g, moduleNameWithExpoPrefix) .replace(/ModuleTemplate/g, moduleName) ); } /** * Prepares files for npm (package.json and README.md). * @param modulePath - module directory * @param configuration - naming configuration */ async function configureNPM( modulePath: string, { npmModuleName, podName, jsPackageName }: ModuleConfiguration ) { const [, moduleName] = preparePrefixes(jsPackageName); await replaceContent(path.join(modulePath, 'package.json'), (singleFileContent) => singleFileContent .replace(/expo-module-template/g, npmModuleName) .replace(/"version": "[\w.-]+"/, '"version": "1.0.0"') .replace(/ExpoModuleTemplate/g, jsPackageName) .replace(/ModuleTemplate/g, moduleName) ); await replaceContent(path.join(modulePath, 'README.md'), (readmeContent) => readmeContent .replace(/expo-module-template/g, npmModuleName) .replace(/ExpoModuleTemplate/g, jsPackageName) .replace(/EXModuleTemplate/g, podName) ); } /** * Configures TS, Android and iOS parts of generated module mostly by applying provided renamings. * @param modulePath - module directory * @param configuration - naming configuration */ export default async function configureModule( newModulePath: string, configuration: ModuleConfiguration ) { await configureNPM(newModulePath, configuration); await configureTS(newModulePath, configuration); await configureAndroid(newModulePath, configuration); await configureIOS(newModulePath, configuration); }
the_stack
import { ethers, network, upgrades, waffle } from "hardhat"; import { Signer } from "ethers"; import chai from "chai"; import { solidity } from "ethereum-waffle"; import "@openzeppelin/test-helpers"; import { MockERC20, MockERC20__factory, WETH, WETH__factory, MockVaultForRestrictedAddTwosideOptimalStrat, MockVaultForRestrictedAddTwosideOptimalStrat__factory, MdexFactory__factory, MdexFactory, MdexRouter, MdexRouter__factory, MdexPair__factory, MdexPair, MdexRestrictedStrategyAddTwoSidesOptimal__factory, MdexRestrictedStrategyAddTwoSidesOptimal, MockMdexWorker__factory, MockMdexWorker, SwapMining, SwapMining__factory, Oracle, Oracle__factory, } from "../../../../../typechain"; import * as Assert from "../../../../helpers/assert"; import { MdxToken } from "../../../../../typechain/MdxToken"; import { formatEther } from "ethers/lib/utils"; import { MdxToken__factory } from "../../../../../typechain/factories/MdxToken__factory"; import * as TimeHelpers from "../../../../helpers/time"; chai.use(solidity); const { expect } = chai; describe("MdexRestrictedStrategyAddTwoSideOptimal", () => { const FOREVER = "2000000000"; const MAX_ROUNDING_ERROR = Number("15"); const mdxPerBlock = "51600000000000000000"; /// Mdex-related instance(s) let factory: MdexFactory; let router: MdexRouter; let swapMining: SwapMining; let oracle: Oracle; /// Token-related instance(s) let mdxToken: MdxToken; let wbnb: WETH; let baseToken: MockERC20; let farmingToken: MockERC20; let mockedVault: MockVaultForRestrictedAddTwosideOptimalStrat; // Mdex let mockMdexWorkerAsBob: MockMdexWorker; let mockMdexWorkerAsAlice: MockMdexWorker; let mockMdexEvilWorkerAsBob: MockMdexWorker; let mockMdexWorker: MockMdexWorker; let mockMdexEvilWorker: MockMdexWorker; // Accounts let deployer: Signer; let alice: Signer; let bob: Signer; let addRestrictedStrat: MdexRestrictedStrategyAddTwoSidesOptimal; let addRestrictedStratAsDeployer: MdexRestrictedStrategyAddTwoSidesOptimal; // Contract Signer let addRestrictedStratAsBob: MdexRestrictedStrategyAddTwoSidesOptimal; let baseTokenAsBob: MockERC20; let farmingTokenAsAlice: MockERC20; let lp: MdexPair; const setupFullFlowTest = async () => { /// Setup token stuffs const MockERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory; baseToken = (await upgrades.deployProxy(MockERC20, ["BTOKEN", "BTOKEN", 18])) as MockERC20; await baseToken.deployed(); await baseToken.mint(await deployer.getAddress(), ethers.utils.parseEther("100")); await baseToken.mint(await alice.getAddress(), ethers.utils.parseEther("100")); await baseToken.mint(await bob.getAddress(), ethers.utils.parseEther("100")); farmingToken = (await upgrades.deployProxy(MockERC20, ["FTOKEN", "FTOKEN", 18])) as MockERC20; await farmingToken.deployed(); await farmingToken.mint(await deployer.getAddress(), ethers.utils.parseEther("100")); await farmingToken.mint(await alice.getAddress(), ethers.utils.parseEther("100")); await farmingToken.mint(await bob.getAddress(), ethers.utils.parseEther("100")); const WBNB = (await ethers.getContractFactory("WETH", deployer)) as WETH__factory; wbnb = await WBNB.deploy(); await wbnb.deployed(); const MdxToken = (await ethers.getContractFactory("MdxToken", deployer)) as MdxToken__factory; mdxToken = await MdxToken.deploy(); await mdxToken.deployed(); await mdxToken.addMinter(await deployer.getAddress()); await mdxToken.mint(await deployer.getAddress(), ethers.utils.parseEther("100")); // Setup Mdex const MdexFactory = (await ethers.getContractFactory("MdexFactory", deployer)) as MdexFactory__factory; factory = await MdexFactory.deploy(await deployer.getAddress()); await factory.deployed(); const MdexRouter = (await ethers.getContractFactory("MdexRouter", deployer)) as MdexRouter__factory; router = await MdexRouter.deploy(factory.address, wbnb.address); await router.deployed(); const Oracle = (await ethers.getContractFactory("Oracle", deployer)) as Oracle__factory; oracle = await Oracle.deploy(factory.address); await oracle.deployed(); // Mdex SwapMinig const blockNumber = await TimeHelpers.latestBlockNumber(); const SwapMining = (await ethers.getContractFactory("SwapMining", deployer)) as SwapMining__factory; swapMining = await SwapMining.deploy( mdxToken.address, factory.address, oracle.address, router.address, farmingToken.address, mdxPerBlock, blockNumber ); await swapMining.deployed(); // set swapMining to router await router.setSwapMining(swapMining.address); /// Setup BTOKEN-FTOKEN pair on Mdex await factory.createPair(farmingToken.address, baseToken.address); lp = MdexPair__factory.connect(await factory.getPair(farmingToken.address, baseToken.address), deployer); await lp.deployed(); await factory.addPair(lp.address); await mdxToken.addMinter(swapMining.address); await swapMining.addPair(100, lp.address, false); await swapMining.addWhitelist(baseToken.address); await swapMining.addWhitelist(farmingToken.address); // Deployer adds 0.1 FTOKEN + 1 BTOKEN await baseToken.approve(router.address, ethers.utils.parseEther("1")); await farmingToken.approve(router.address, ethers.utils.parseEther("0.1")); await router.addLiquidity( baseToken.address, farmingToken.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("0.1"), "0", "0", await deployer.getAddress(), FOREVER ); // Deployer adds 1 BTOKEN + 1 NATIVE await baseToken.approve(router.address, ethers.utils.parseEther("1")); await router.addLiquidityETH( baseToken.address, ethers.utils.parseEther("1"), "0", "0", await deployer.getAddress(), FOREVER, { value: ethers.utils.parseEther("1") } ); }; const setupRestrictedTest = async () => { const MockVaultForRestrictedAddTwosideOptimalStrat = (await ethers.getContractFactory( "MockVaultForRestrictedAddTwosideOptimalStrat", deployer )) as MockVaultForRestrictedAddTwosideOptimalStrat__factory; mockedVault = (await upgrades.deployProxy( MockVaultForRestrictedAddTwosideOptimalStrat )) as MockVaultForRestrictedAddTwosideOptimalStrat; await mockedVault.deployed(); const MdexRestrictedStrategyAddTwoSidesOptimal = (await ethers.getContractFactory( "MdexRestrictedStrategyAddTwoSidesOptimal", deployer )) as MdexRestrictedStrategyAddTwoSidesOptimal__factory; addRestrictedStrat = (await upgrades.deployProxy(MdexRestrictedStrategyAddTwoSidesOptimal, [ router.address, mockedVault.address, mdxToken.address, ])) as MdexRestrictedStrategyAddTwoSidesOptimal; await addRestrictedStrat.deployed(); // / Setup MockMdexWorker const MockMdexWorker = (await ethers.getContractFactory("MockMdexWorker", deployer)) as MockMdexWorker__factory; mockMdexWorker = (await MockMdexWorker.deploy( lp.address, baseToken.address, farmingToken.address )) as MockMdexWorker; await mockMdexWorker.deployed(); mockMdexEvilWorker = (await MockMdexWorker.deploy( lp.address, baseToken.address, farmingToken.address )) as MockMdexWorker; await mockMdexEvilWorker.deployed(); // Set block base fee per gas to 0 await network.provider.send("hardhat_setNextBlockBaseFeePerGas", ["0x0"]); }; const setupContractSigner = async () => { // Contract signer addRestrictedStratAsBob = MdexRestrictedStrategyAddTwoSidesOptimal__factory.connect( addRestrictedStrat.address, bob ); addRestrictedStratAsDeployer = MdexRestrictedStrategyAddTwoSidesOptimal__factory.connect( addRestrictedStrat.address, deployer ); baseTokenAsBob = MockERC20__factory.connect(baseToken.address, bob); farmingTokenAsAlice = MockERC20__factory.connect(farmingToken.address, alice); mockMdexWorkerAsBob = MockMdexWorker__factory.connect(mockMdexWorker.address, bob); mockMdexWorkerAsAlice = MockMdexWorker__factory.connect(mockMdexWorker.address, alice); mockMdexEvilWorkerAsBob = MockMdexWorker__factory.connect(mockMdexEvilWorker.address, bob); }; async function fixture() { [deployer, alice, bob] = await ethers.getSigners(); await setupFullFlowTest(); await setupRestrictedTest(); await setupContractSigner(); await addRestrictedStratAsDeployer.setWorkersOk([mockMdexWorker.address], true); } beforeEach(async () => { await waffle.loadFixture(fixture); }); describe("full flow test", async () => { context("when strategy execution is not in the scope", async () => { it("should revert", async () => { await expect( addRestrictedStratAsBob.execute( await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode(["uint256", "uint256"], ["0", "0"]) ) ).to.be.reverted; }); }); context("when bad calldata", async () => { it("should revert", async () => { await mockedVault.setMockOwner(await alice.getAddress()); await baseToken.mint(mockMdexWorker.address, ethers.utils.parseEther("1")); await expect( mockMdexWorkerAsAlice.work( 0, await alice.getAddress(), ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addRestrictedStrat.address, ethers.utils.defaultAbiCoder.encode(["address"], [await bob.getAddress()])] ) ) ).to.reverted; }); }); it("should convert all BTOKEN to LP tokens at best rate", async () => { // set lp pair fee await factory.setPairFees(lp.address, 25); // Now Alice leverage 2x on her 1 BTOKEN. // So totally Alice will take 1 BTOKEN from the pool and 1 BTOKEN from her pocket to // Provide liquidity in the BTOKEN-FTOKEN pool on Pancakeswap await mockedVault.setMockOwner(await alice.getAddress()); await baseToken.mint(mockMdexWorker.address, ethers.utils.parseEther("2")); await mockMdexWorkerAsAlice.work( 0, await alice.getAddress(), ethers.utils.parseEther("0"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ addRestrictedStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256", "uint256"], ["0", ethers.utils.parseEther("0.01")]), ] ) ); // the calculation is ratio between balance and reserve * total supply // let total supply = sqrt(1 * 0.1) = 0.31622776601683794 // current reserve after swap is 1732967258967755614 // ths lp will be (1267032741032244386 (optimal swap amount) / 1732967258967755614 (reserve)) * 0.31622776601683794 // lp will be 0.23120513736969137 const stratLPBalance = await lp.balanceOf(mockMdexWorker.address); Assert.assertAlmostEqual(stratLPBalance.toString(), ethers.utils.parseEther("0.23120513736969137").toString()); expect(stratLPBalance).to.above(ethers.utils.parseEther("0")); expect(await farmingToken.balanceOf(addRestrictedStrat.address)).to.be.below(MAX_ROUNDING_ERROR); // Now Alice leverage 2x on her 0.1 BTOKEN. // So totally Alice will take 0.1 BTOKEN from the pool and 0.1 BTOKEN from her pocket to // Provide liquidity in the BTOKEN-FTOKEN pool on Pancakeswap await baseToken.mint(mockMdexWorker.address, ethers.utils.parseEther("0.1")); await mockMdexWorkerAsAlice.work( 0, await alice.getAddress(), ethers.utils.parseEther("0.1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ addRestrictedStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256", "uint256"], ["0", ethers.utils.parseEther("0")]), ] ) ); // the calculation is ratio between balance and reserve * total supply // let total supply = 0.556470668763341270 coming from 0.31622776601683794 + 0.23120513736969137 // current reserve after swap is 3049652202279806938 // ths lp will be (50347797720193062 (optimal swap amount) / 3049652202279806938 (reserve)) * 0.556470668763341270 // lp will be 0.009037765376812014 // thus the accum lp will be 0.009037765376812014 + 0.23120513736969137 = 0.240242902746503337 Assert.assertAlmostEqual( (await lp.balanceOf(mockMdexWorker.address)).toString(), ethers.utils.parseEther("0.240242902746503337").toString() ); expect(await lp.balanceOf(mockMdexWorker.address)).to.above(stratLPBalance); expect(await farmingToken.balanceOf(addRestrictedStrat.address)).to.be.below(MAX_ROUNDING_ERROR); }); it("should convert some BTOKEN and some FTOKEN to LP tokens at best rate (fee 20)", async () => { // set lp pair fee await factory.setPairFees(lp.address, 20); // Now Alice leverage 2x on her 1 BTOKEN. // So totally Alice will take 1 BTOKEN from the pool and 1 BTOKEN from her pocket to // Provide liquidity in the BTOKEN-FTOKEN pool on Pancakeswap await mockedVault.setMockOwner(await alice.getAddress()); await baseToken.mint(mockMdexWorker.address, ethers.utils.parseEther("2")); await farmingTokenAsAlice.approve(mockedVault.address, ethers.utils.parseEther("1")); await mockMdexWorkerAsAlice.work( 0, await alice.getAddress(), ethers.utils.parseEther("0"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ addRestrictedStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256"], [ethers.utils.parseEther("0.05"), ethers.utils.parseEther("0")] ), ] ) ); // the calculation is ratio between balance and reserve * total supply // let total supply = sqrt(1 * 0.1) = 0.31622776601683793 // current reserve after swap is 1414628251406192119 // ths lp will be (1585371748593807881 (optimal swap amount) / 1414628251406192119 (reserve)) * 0.31622776601683794 // lp will be 0.354395980615881993 const stratLPBalance = await lp.balanceOf(mockMdexWorker.address); Assert.assertAlmostEqual(stratLPBalance.toString(), ethers.utils.parseEther("0.354395980615881993").toString()); expect(stratLPBalance).to.above(ethers.utils.parseEther("0")); expect(await farmingToken.balanceOf(addRestrictedStrat.address)).to.be.below(MAX_ROUNDING_ERROR); // Now Alice leverage 2x on her 0.1 BTOKEN. // So totally Alice will take 0.1 BTOKEN from the pool and 0.1 BTOKEN from her pocket to // Provide liquidity in the BTOKEN-FTOKEN pool on Pancakeswap await baseToken.mint(mockMdexWorker.address, ethers.utils.parseEther("1")); await farmingTokenAsAlice.approve(mockedVault.address, ethers.utils.parseEther("1")); await mockMdexWorkerAsAlice.work( 0, await alice.getAddress(), ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ addRestrictedStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256"], [ethers.utils.parseEther("1"), ethers.utils.parseEther("0.1")] ), ] ) ); // the calculation is ratio between balance and reserve * total supply // let total supply = 0.31622776601683794 + 0.354346766435591663 = 0.6705745324524296 // current reserve after swap is 1251999642993914466 // ths lp will be (2748183224992804794 (optimal swap amount) / 1251816775007195206 (reserve)) * 0.6705745324524296 // lp will be 1.472149693139052074 // thus, the accum lp will be 1.472149693139052074 + 0.354346766435591663 = 1.8264964595746437379 Assert.assertAlmostEqual( (await lp.balanceOf(mockMdexWorker.address)).toString(), ethers.utils.parseEther("1.826496459574643737").toString() ); expect(await lp.balanceOf(mockMdexWorker.address)).to.above(stratLPBalance); expect(await farmingToken.balanceOf(addRestrictedStrat.address)).to.be.below(MAX_ROUNDING_ERROR); }); it("should convert some BTOKEN and some FTOKEN to LP tokens at best rate (fee 25)", async () => { // set lp pair fee await factory.setPairFees(lp.address, 25); // Now Alice leverage 2x on her 1 BTOKEN. // So totally Alice will take 1 BTOKEN from the pool and 1 BTOKEN from her pocket to // Provide liquidity in the BTOKEN-FTOKEN pool on Pancakeswap await mockedVault.setMockOwner(await alice.getAddress()); await baseToken.mint(mockMdexWorker.address, ethers.utils.parseEther("2")); await farmingTokenAsAlice.approve(mockedVault.address, ethers.utils.parseEther("1")); await mockMdexWorkerAsAlice.work( 0, await alice.getAddress(), ethers.utils.parseEther("0"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ addRestrictedStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256"], [ethers.utils.parseEther("0.05"), ethers.utils.parseEther("0")] ), ] ) ); // the calculation is ratio between balance and reserve * total supply // let total supply = sqrt(1 * 0.1) = 0.31622776601683794 // current reserve after swap is 1414732072482656002 // ths lp will be (1585267927517343998 (optimal swap amount) / 1414732072482656002 (reserve)) * 0.31622776601683794 // lp will be 0.354346766435591663 const stratLPBalance = await lp.balanceOf(mockMdexWorker.address); Assert.assertAlmostEqual(stratLPBalance.toString(), ethers.utils.parseEther("0.354346766435591663").toString()); expect(stratLPBalance).to.above(ethers.utils.parseEther("0")); expect(await farmingToken.balanceOf(addRestrictedStrat.address)).to.be.below(MAX_ROUNDING_ERROR); // Now Alice leverage 2x on her 0.1 BTOKEN. // So totally Alice will take 0.1 BTOKEN from the pool and 0.1 BTOKEN from her pocket to // Provide liquidity in the BTOKEN-FTOKEN pool on Pancakeswap await baseToken.mint(mockMdexWorker.address, ethers.utils.parseEther("1")); await farmingTokenAsAlice.approve(mockedVault.address, ethers.utils.parseEther("1")); await mockMdexWorkerAsAlice.work( 0, await alice.getAddress(), ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ addRestrictedStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256"], [ethers.utils.parseEther("1"), ethers.utils.parseEther("0.1")] ), ] ) ); // the calculation is ratio between balance and reserve * total supply // let total supply = 0.31622776601683794 + 0.354346766435591663 = 0.6705745324524296 // current reserve after swap is 1251999642993914466 // ths lp will be (2748000357006085534 (optimal swap amount) / 1251999642993914466 (reserve)) * 0.6705745324524296 // lp will be 0.1471836725266080870 // thus, the accum lp will be 1.471836725266080870 + 0.354346766435591663 = 1.8261834917016726 Assert.assertAlmostEqual( (await lp.balanceOf(mockMdexWorker.address)).toString(), ethers.utils.parseEther("1.8261834917016726").toString() ); expect(await lp.balanceOf(mockMdexWorker.address)).to.above(stratLPBalance); expect(await farmingToken.balanceOf(addRestrictedStrat.address)).to.be.below(MAX_ROUNDING_ERROR); }); it("should be able to withdraw trading rewards", async () => { // set lp pair fee await factory.setPairFees(lp.address, 25); // Now Alice leverage 2x on her 1 BTOKEN. // So totally Alice will take 1 BTOKEN from the pool and 1 BTOKEN from her pocket to // Provide liquidity in the BTOKEN-FTOKEN pool on Pancakeswap await mockedVault.setMockOwner(await alice.getAddress()); await baseToken.mint(mockMdexWorker.address, ethers.utils.parseEther("2")); await farmingTokenAsAlice.approve(mockedVault.address, ethers.utils.parseEther("1")); await mockMdexWorkerAsAlice.work( 0, await alice.getAddress(), ethers.utils.parseEther("0"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ addRestrictedStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256"], [ethers.utils.parseEther("0.05"), ethers.utils.parseEther("0")] ), ] ) ); const mdxBefore = await mdxToken.balanceOf(await deployer.getAddress()); // withdraw trading reward to deployer const withDrawTx = await addRestrictedStrat.withdrawTradingRewards(await deployer.getAddress()); const mdxAfter = await mdxToken.balanceOf(await deployer.getAddress()); // get trading reward of the previos block const pIds = [0]; const totalRewardPrev = await addRestrictedStrat.getMiningRewards(pIds, { blockTag: Number(withDrawTx.blockNumber) - 1, }); const withDrawBlockReward = await swapMining["reward()"]({ blockTag: withDrawTx.blockNumber }); const totalReward = totalRewardPrev.add(withDrawBlockReward); expect(mdxAfter.sub(mdxBefore)).to.eq(totalReward); }); }); describe("restricted test", async () => { context("When the setOkWorkers caller is not an owner", async () => { it("should be reverted", async () => { await expect(addRestrictedStratAsBob.setWorkersOk([mockMdexEvilWorkerAsBob.address], true)).to.reverted; }); }); context("When the withdrawTradingRewards caller is not an owner", async () => { it("should be reverted", async () => { await expect(addRestrictedStratAsBob.withdrawTradingRewards(await bob.getAddress())).to.reverted; }); }); context("When the caller worker is not whitelisted", async () => { it("should revert", async () => { await baseTokenAsBob.transfer(mockMdexEvilWorkerAsBob.address, ethers.utils.parseEther("0.01")); await expect( mockMdexEvilWorkerAsBob.work( 0, await bob.getAddress(), 0, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ addRestrictedStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256"], [ethers.utils.parseEther("0"), ethers.utils.parseEther("0.01")] ), ] ) ) ).to.revertedWith("MdexRestrictedStrategyAddTwoSidesOptimal::onlyWhitelistedWorkers:: bad worker"); }); }); context("When the caller worker has been revoked from callable", async () => { it("should revert", async () => { await baseTokenAsBob.transfer(mockMdexEvilWorkerAsBob.address, ethers.utils.parseEther("0.01")); await addRestrictedStratAsDeployer.setWorkersOk([mockMdexWorker.address], false); await expect( mockMdexWorkerAsBob.work( 0, await bob.getAddress(), 0, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ addRestrictedStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256"], [ethers.utils.parseEther("0"), ethers.utils.parseEther("0.01")] ), ] ) ) ).to.revertedWith("MdexRestrictedStrategyAddTwoSidesOptimal::onlyWhitelistedWorkers:: bad worker"); }); }); }); });
the_stack
import * as layout from '../../util/layout'; import * as zrUtil from 'zrender/src/core/util'; import {groupData} from '../../util/model'; import ExtensionAPI from '../../core/ExtensionAPI'; import SankeySeriesModel, { SankeySeriesOption, SankeyNodeItemOption } from './SankeySeries'; import { GraphNode, GraphEdge } from '../../data/Graph'; import { LayoutOrient } from '../../util/types'; import GlobalModel from '../../model/Global'; export default function sankeyLayout(ecModel: GlobalModel, api: ExtensionAPI) { ecModel.eachSeriesByType('sankey', function (seriesModel: SankeySeriesModel) { const nodeWidth = seriesModel.get('nodeWidth'); const nodeGap = seriesModel.get('nodeGap'); const layoutInfo = getViewRect(seriesModel, api); seriesModel.layoutInfo = layoutInfo; const width = layoutInfo.width; const height = layoutInfo.height; const graph = seriesModel.getGraph(); const nodes = graph.nodes; const edges = graph.edges; computeNodeValues(nodes); const filteredNodes = zrUtil.filter(nodes, function (node) { return node.getLayout().value === 0; }); const iterations = filteredNodes.length !== 0 ? 0 : seriesModel.get('layoutIterations'); const orient = seriesModel.get('orient'); const nodeAlign = seriesModel.get('nodeAlign'); layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign); }); } /** * Get the layout position of the whole view */ function getViewRect(seriesModel: SankeySeriesModel, api: ExtensionAPI) { return layout.getLayoutRect( seriesModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() } ); } function layoutSankey( nodes: GraphNode[], edges: GraphEdge[], nodeWidth: number, nodeGap: number, width: number, height: number, iterations: number, orient: LayoutOrient, nodeAlign: SankeySeriesOption['nodeAlign'] ) { computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign); computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient); computeEdgeDepths(nodes, orient); } /** * Compute the value of each node by summing the associated edge's value */ function computeNodeValues(nodes: GraphNode[]) { zrUtil.each(nodes, function (node) { const value1 = sum(node.outEdges, getEdgeValue); const value2 = sum(node.inEdges, getEdgeValue); const nodeRawValue = node.getValue() as number || 0; const value = Math.max(value1, value2, nodeRawValue); node.setLayout({value: value}, true); }); } /** * Compute the x-position for each node. * * Here we use Kahn algorithm to detect cycle when we traverse * the node to computer the initial x position. */ function computeNodeBreadths( nodes: GraphNode[], edges: GraphEdge[], nodeWidth: number, width: number, height: number, orient: LayoutOrient, nodeAlign: SankeySeriesOption['nodeAlign'] ) { // Used to mark whether the edge is deleted. if it is deleted, // the value is 0, otherwise it is 1. const remainEdges = []; // Storage each node's indegree. const indegreeArr = []; //Used to storage the node with indegree is equal to 0. let zeroIndegrees: GraphNode[] = []; let nextTargetNode: GraphNode[] = []; let x = 0; // let kx = 0; for (let i = 0; i < edges.length; i++) { remainEdges[i] = 1; } for (let i = 0; i < nodes.length; i++) { indegreeArr[i] = nodes[i].inEdges.length; if (indegreeArr[i] === 0) { zeroIndegrees.push(nodes[i]); } } let maxNodeDepth = -1; // Traversing nodes using topological sorting to calculate the // horizontal(if orient === 'horizontal') or vertical(if orient === 'vertical') // position of the nodes. while (zeroIndegrees.length) { for (let idx = 0; idx < zeroIndegrees.length; idx++) { const node = zeroIndegrees[idx]; const item = node.hostGraph.data.getRawDataItem(node.dataIndex) as SankeyNodeItemOption; const isItemDepth = item.depth != null && item.depth >= 0; if (isItemDepth && item.depth > maxNodeDepth) { maxNodeDepth = item.depth; } node.setLayout({depth: isItemDepth ? item.depth : x}, true); orient === 'vertical' ? node.setLayout({dy: nodeWidth}, true) : node.setLayout({dx: nodeWidth}, true); for (let edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++) { const edge = node.outEdges[edgeIdx]; const indexEdge = edges.indexOf(edge); remainEdges[indexEdge] = 0; const targetNode = edge.node2; const nodeIndex = nodes.indexOf(targetNode); if (--indegreeArr[nodeIndex] === 0 && nextTargetNode.indexOf(targetNode) < 0) { nextTargetNode.push(targetNode); } } } ++x; zeroIndegrees = nextTargetNode; nextTargetNode = []; } for (let i = 0; i < remainEdges.length; i++) { if (remainEdges[i] === 1) { throw new Error('Sankey is a DAG, the original data has cycle!'); } } const maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1; if (nodeAlign && nodeAlign !== 'left') { adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth); } const kx = orient === 'vertical' ? (height - nodeWidth) / maxDepth : (width - nodeWidth) / maxDepth; scaleNodeBreadths(nodes, kx, orient); } function isNodeDepth(node: GraphNode) { const item = node.hostGraph.data.getRawDataItem(node.dataIndex) as SankeyNodeItemOption; return item.depth != null && item.depth >= 0; } function adjustNodeWithNodeAlign( nodes: GraphNode[], nodeAlign: SankeySeriesOption['nodeAlign'], orient: LayoutOrient, maxDepth: number ) { if (nodeAlign === 'right') { let nextSourceNode: GraphNode[] = []; let remainNodes = nodes; let nodeHeight = 0; while (remainNodes.length) { for (let i = 0; i < remainNodes.length; i++) { const node = remainNodes[i]; node.setLayout({skNodeHeight: nodeHeight}, true); for (let j = 0; j < node.inEdges.length; j++) { const edge = node.inEdges[j]; if (nextSourceNode.indexOf(edge.node1) < 0) { nextSourceNode.push(edge.node1); } } } remainNodes = nextSourceNode; nextSourceNode = []; ++nodeHeight; } zrUtil.each(nodes, function (node) { if (!isNodeDepth(node)) { node.setLayout({depth: Math.max(0, maxDepth - node.getLayout().skNodeHeight)}, true); } }); } else if (nodeAlign === 'justify') { moveSinksRight(nodes, maxDepth); } } /** * All the node without outEgdes are assigned maximum x-position and * be aligned in the last column. * * @param nodes. node of sankey view. * @param maxDepth. use to assign to node without outEdges as x-position. */ function moveSinksRight(nodes: GraphNode[], maxDepth: number) { zrUtil.each(nodes, function (node) { if (!isNodeDepth(node) && !node.outEdges.length) { node.setLayout({depth: maxDepth}, true); } }); } /** * Scale node x-position to the width * * @param nodes node of sankey view * @param kx multiple used to scale nodes */ function scaleNodeBreadths(nodes: GraphNode[], kx: number, orient: LayoutOrient) { zrUtil.each(nodes, function (node) { const nodeDepth = node.getLayout().depth * kx; orient === 'vertical' ? node.setLayout({y: nodeDepth}, true) : node.setLayout({x: nodeDepth}, true); }); } /** * Using Gauss-Seidel iterations method to compute the node depth(y-position) * * @param nodes node of sankey view * @param edges edge of sankey view * @param height the whole height of the area to draw the view * @param nodeGap the vertical distance between two nodes * in the same column. * @param iterations the number of iterations for the algorithm */ function computeNodeDepths( nodes: GraphNode[], edges: GraphEdge[], height: number, width: number, nodeGap: number, iterations: number, orient: LayoutOrient ) { const nodesByBreadth = prepareNodesByBreadth(nodes, orient); initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient); resolveCollisions(nodesByBreadth, nodeGap, height, width, orient); for (let alpha = 1; iterations > 0; iterations--) { // 0.99 is a experience parameter, ensure that each iterations of // changes as small as possible. alpha *= 0.99; relaxRightToLeft(nodesByBreadth, alpha, orient); resolveCollisions(nodesByBreadth, nodeGap, height, width, orient); relaxLeftToRight(nodesByBreadth, alpha, orient); resolveCollisions(nodesByBreadth, nodeGap, height, width, orient); } } function prepareNodesByBreadth(nodes: GraphNode[], orient: LayoutOrient) { const nodesByBreadth: GraphNode[][] = []; const keyAttr = orient === 'vertical' ? 'y' : 'x'; const groupResult = groupData(nodes, function (node) { return node.getLayout()[keyAttr] as number; }); groupResult.keys.sort(function (a, b) { return a - b; }); zrUtil.each(groupResult.keys, function (key) { nodesByBreadth.push(groupResult.buckets.get(key)); }); return nodesByBreadth; } /** * Compute the original y-position for each node */ function initializeNodeDepth( nodesByBreadth: GraphNode[][], edges: GraphEdge[], height: number, width: number, nodeGap: number, orient: LayoutOrient ) { let minKy = Infinity; zrUtil.each(nodesByBreadth, function (nodes) { const n = nodes.length; let sum = 0; zrUtil.each(nodes, function (node) { sum += node.getLayout().value; }); const ky = orient === 'vertical' ? (width - (n - 1) * nodeGap) / sum : (height - (n - 1) * nodeGap) / sum; if (ky < minKy) { minKy = ky; } }); zrUtil.each(nodesByBreadth, function (nodes) { zrUtil.each(nodes, function (node, i) { const nodeDy = node.getLayout().value * minKy; if (orient === 'vertical') { node.setLayout({x: i}, true); node.setLayout({dx: nodeDy}, true); } else { node.setLayout({y: i}, true); node.setLayout({dy: nodeDy}, true); } }); }); zrUtil.each(edges, function (edge) { const edgeDy = +edge.getValue() * minKy; edge.setLayout({dy: edgeDy}, true); }); } /** * Resolve the collision of initialized depth (y-position) */ function resolveCollisions( nodesByBreadth: GraphNode[][], nodeGap: number, height: number, width: number, orient: LayoutOrient ) { const keyAttr = orient === 'vertical' ? 'x' : 'y'; zrUtil.each(nodesByBreadth, function (nodes) { nodes.sort(function (a, b) { return a.getLayout()[keyAttr] - b.getLayout()[keyAttr]; }); let nodeX; let node; let dy; let y0 = 0; const n = nodes.length; const nodeDyAttr = orient === 'vertical' ? 'dx' : 'dy'; for (let i = 0; i < n; i++) { node = nodes[i]; dy = y0 - node.getLayout()[keyAttr]; if (dy > 0) { nodeX = node.getLayout()[keyAttr] + dy; orient === 'vertical' ? node.setLayout({x: nodeX}, true) : node.setLayout({y: nodeX}, true); } y0 = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap; } const viewWidth = orient === 'vertical' ? width : height; // If the bottommost node goes outside the bounds, push it back up dy = y0 - nodeGap - viewWidth; if (dy > 0) { nodeX = node.getLayout()[keyAttr] - dy; orient === 'vertical' ? node.setLayout({x: nodeX}, true) : node.setLayout({y: nodeX}, true); y0 = nodeX; for (let i = n - 2; i >= 0; --i) { node = nodes[i]; dy = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap - y0; if (dy > 0) { nodeX = node.getLayout()[keyAttr] - dy; orient === 'vertical' ? node.setLayout({x: nodeX}, true) : node.setLayout({y: nodeX}, true); } y0 = node.getLayout()[keyAttr]; } } }); } /** * Change the y-position of the nodes, except most the right side nodes * @param nodesByBreadth * @param alpha parameter used to adjust the nodes y-position */ function relaxRightToLeft( nodesByBreadth: GraphNode[][], alpha: number, orient: LayoutOrient ) { zrUtil.each(nodesByBreadth.slice().reverse(), function (nodes) { zrUtil.each(nodes, function (node) { if (node.outEdges.length) { let y = sum(node.outEdges, weightedTarget, orient) / sum(node.outEdges, getEdgeValue); if (isNaN(y)) { const len = node.outEdges.length; y = len ? sum(node.outEdges, centerTarget, orient) / len : 0; } if (orient === 'vertical') { const nodeX = node.getLayout().x + (y - center(node, orient)) * alpha; node.setLayout({x: nodeX}, true); } else { const nodeY = node.getLayout().y + (y - center(node, orient)) * alpha; node.setLayout({y: nodeY}, true); } } }); }); } function weightedTarget(edge: GraphEdge, orient: LayoutOrient) { return center(edge.node2, orient) * (edge.getValue() as number); } function centerTarget(edge: GraphEdge, orient: LayoutOrient) { return center(edge.node2, orient); } function weightedSource(edge: GraphEdge, orient: LayoutOrient) { return center(edge.node1, orient) * (edge.getValue() as number); } function centerSource(edge: GraphEdge, orient: LayoutOrient) { return center(edge.node1, orient); } function center(node: GraphNode, orient: LayoutOrient) { return orient === 'vertical' ? node.getLayout().x + node.getLayout().dx / 2 : node.getLayout().y + node.getLayout().dy / 2; } function getEdgeValue(edge: GraphEdge) { return edge.getValue() as number; } function sum<T>(array: T[], cb: (item: T, orient?: LayoutOrient) => number, orient?: LayoutOrient) { let sum = 0; const len = array.length; let i = -1; while (++i < len) { const value = +cb(array[i], orient); if (!isNaN(value)) { sum += value; } } return sum; } /** * Change the y-position of the nodes, except most the left side nodes */ function relaxLeftToRight(nodesByBreadth: GraphNode[][], alpha: number, orient: LayoutOrient) { zrUtil.each(nodesByBreadth, function (nodes) { zrUtil.each(nodes, function (node) { if (node.inEdges.length) { let y = sum(node.inEdges, weightedSource, orient) / sum(node.inEdges, getEdgeValue); if (isNaN(y)) { const len = node.inEdges.length; y = len ? sum(node.inEdges, centerSource, orient) / len : 0; } if (orient === 'vertical') { const nodeX = node.getLayout().x + (y - center(node, orient)) * alpha; node.setLayout({x: nodeX}, true); } else { const nodeY = node.getLayout().y + (y - center(node, orient)) * alpha; node.setLayout({y: nodeY}, true); } } }); }); } /** * Compute the depth(y-position) of each edge */ function computeEdgeDepths(nodes: GraphNode[], orient: LayoutOrient) { const keyAttr = orient === 'vertical' ? 'x' : 'y'; zrUtil.each(nodes, function (node) { node.outEdges.sort(function (a, b) { return a.node2.getLayout()[keyAttr] - b.node2.getLayout()[keyAttr]; }); node.inEdges.sort(function (a, b) { return a.node1.getLayout()[keyAttr] - b.node1.getLayout()[keyAttr]; }); }); zrUtil.each(nodes, function (node) { let sy = 0; let ty = 0; zrUtil.each(node.outEdges, function (edge) { edge.setLayout({sy: sy}, true); sy += edge.getLayout().dy; }); zrUtil.each(node.inEdges, function (edge) { edge.setLayout({ty: ty}, true); ty += edge.getLayout().dy; }); }); }
the_stack
import { watchers, baseWatchers } from './watchers' import { AudioWatcher } from './audio' import { RecordData, RecordType, TerminateRecord } from '@timecat/share' import { logError, nodeStore, getTime, tempEmptyFn, tempEmptyPromise, IDB, idb, delay } from '@timecat/utils' import { Snapshot } from './snapshot' import { getHeadData } from './head' import { LocationWatcher } from './watchers/location' import { Pluginable } from './pluginable' import { Watcher } from './watcher' import { VideoWatcher } from './watchers/video' import { RecorderMiddleware, RecorderStatus, RecordInternalOptions, RecordOptions } from './types' export class Recorder { public startTime: number public destroyTime: number public status: RecorderStatus = RecorderStatus.PAUSE public onData: RecorderModule['onData'] = tempEmptyFn public destroy: RecorderModule['destroy'] = tempEmptyPromise public pause: RecorderModule['pause'] = tempEmptyPromise as RecorderModule['pause'] public record: RecorderModule['record'] = tempEmptyPromise as RecorderModule['record'] public use: RecorderModule['use'] = tempEmptyFn public clearDB: RecorderModule['clearDB'] = tempEmptyPromise constructor(options?: RecordOptions) { const recorder = new RecorderModule(options) Object.keys(this).forEach((key: keyof Recorder) => { Object.defineProperty(this, key, { get() { return typeof recorder[key] === 'function' ? (recorder[key] as Function).bind(recorder) : recorder[key] } }) }) } } export class RecorderModule extends Pluginable { private static defaultRecordOpts = { mode: 'default', write: true, keep: false, audio: false, video: false, emitLocationImmediate: true, context: window, rewriteResource: [], disableWatchers: [] } as RecordOptions private defaultMiddleware: RecorderMiddleware[] = [] private destroyStore: Set<Function> = new Set() private listenStore: Set<Function> = new Set() private middleware: RecorderMiddleware[] = [...this.defaultMiddleware] private watchers: Array<typeof Watcher> private watchersInstance = new Map<string, Watcher<RecordData>>() private watchesReadyPromise = new Promise(resolve => (this.watcherResolve = resolve)) private watcherResolve: Function private startTime: number private destroyTime: number public status: RecorderStatus = RecorderStatus.PAUSE public db: IDB public options: RecordInternalOptions constructor(options?: RecordOptions) { super(options) const opts = this.initOptions(options) opts.rootContext = opts.rootContext || opts.context this.options = opts this.watchers = this.getWatchers() as typeof Watcher[] this.init() } private initOptions(options?: RecordOptions) { const opts = { ...RecorderModule.defaultRecordOpts, ...options } as RecordInternalOptions if (opts.video === true) { opts.video = { fps: 24 } } else if (opts.video && 'fps' in opts.video) { if (opts.video.fps > 24) { opts.video.fps = 24 } } return opts } private init() { this.startTime = getTime() const options = this.options this.db = idb this.loadPlugins() this.hooks.beforeRun.call(this) this.record(options) this.hooks.run.call(this) } public onData(fn: (data: RecordData, next: () => Promise<void>) => Promise<void>) { this.middleware.unshift(fn) } public async destroy() { if (this.status === RecorderStatus.HALT) { return } const ret = await this.pause() if (ret) { this.status = RecorderStatus.HALT this.destroyTime = ret.lastTime || getTime() } } private async pause() { if (this.status === RecorderStatus.RUNNING) { this.status = RecorderStatus.PAUSE const last = await this.db.last().catch(() => {}) await this.cancelListener() this.destroyStore.forEach(un => un()) this.destroyStore.clear() let lastTime: number | null = null if (last) { lastTime = last.time + 1 const data = { type: RecordType.TERMINATE, data: null, relatedId: window.G_RECORD_RELATED_ID, time: lastTime } if (data.relatedId) { if (this.options.write) { this.db.add(data as TerminateRecord) } this.connectCompose(this.middleware)(data as RecordData) } } return { lastTime } } } public clearDB() { this.db.clear() } private async cancelListener() { // wait for watchers loaded await this.watchesReadyPromise this.listenStore.forEach(un => un()) this.listenStore.clear() nodeStore.reset() } private getWatchers() { const { video, audio, disableWatchers } = this.options const watchersList = [Snapshot, ...Object.values(watchers)] as typeof Watcher[] if (audio) { watchersList.push(AudioWatcher as typeof Watcher) } if (video) { watchersList.push(VideoWatcher as typeof Watcher) } return watchersList.filter(watcher => { return !~disableWatchers.indexOf(watcher.name as keyof typeof watchers) }) } private record(options: RecordOptions | RecordInternalOptions): void { if (this.status === RecorderStatus.PAUSE) { const opts = { ...RecorderModule.defaultRecordOpts, ...options } as RecordInternalOptions this.startRecord((opts.context.G_RECORD_OPTIONS = opts)) return } } private async startRecord(options: RecordInternalOptions) { this.status = RecorderStatus.RUNNING let activeWatchers = [...this.watchers, ...this.pluginWatchers] const isSameCtx = options.context === this.options.rootContext if (isSameCtx) { if (!options.keep) { this.db.clear() } } else { // for iframe watchers activeWatchers = [Snapshot, ...Object.values(baseWatchers)] as typeof Watcher[] } const onEmit = (options: RecordOptions) => { const { write } = options const emitTasks: Array<RecordData> = [] const { middleware: rootMiddleware } = this.options.rootRecorder || { middleware: [] } const execTasksChain = (() => { let concurrency = 0 const MAX_CONCURRENCY = 1 return async () => { if (concurrency >= MAX_CONCURRENCY) { return } concurrency++ while (emitTasks.length) { const record = emitTasks.shift()! await delay(0) if (this.status === RecorderStatus.RUNNING) { if (write) { this.db.add(record) } const middleware = [...rootMiddleware, ...this.middleware] await this.connectCompose(middleware)(record) this.hooks.emit.call(record) } } concurrency-- } })() return (data: RecordData) => { if (!data) { return } emitTasks.push(data) execTasksChain() } } const isInRoot = options.context === this.options.rootContext const emit = onEmit(options) const headData = getHeadData() const relatedId = isInRoot ? headData.relatedId : options.rootContext.G_RECORD_RELATED_ID options.context.G_RECORD_RELATED_ID = relatedId if (isInRoot) { emit({ type: RecordType.HEAD, data: headData, relatedId, time: getTime() }) } activeWatchers.forEach(Watcher => { try { const watcher = new Watcher({ recorder: this, context: options && options.context, listenStore: this.listenStore, relatedId, emit, watchers: this.watchersInstance }) this.watchersInstance.set(Watcher.name, watcher) } catch (e) { logError(e) } }) if (isInRoot && options.emitLocationImmediate) { const locationInstance = this.watchersInstance.get(LocationWatcher.name) as InstanceType< typeof LocationWatcher > locationInstance?.emitOne() } this.watcherResolve() await this.recordSubIFrames(options.context) } private async waitingSubIFramesLoaded(context: Window) { const frames = context.frames const validFrames = Array.from(frames) .filter(frame => { try { return frame.frameElement && frame.frameElement.getAttribute('src') } catch (e) { logError(e) return false } }) .map(async frame => { await delay(0) return await new Promise(resolve => { if (frame.document.readyState === 'complete') { resolve(frame) } else { frame.addEventListener('load', () => { resolve(frame) }) } }) }) if (!validFrames.length) { return Promise.resolve([]) } return Promise.all(validFrames) as Promise<Window[]> } private async waitingIFrameLoaded(frame: Window): Promise<Window | undefined> { try { frame.document && frame.frameElement && frame.frameElement.getAttribute('src')! } catch (e) { logError(e) return } return new Promise(resolve => { const timer = window.setInterval(() => { try { if (frame.document) { clearInterval(timer) resolve(frame) } } catch (e) { logError(e) clearInterval(timer) resolve(undefined) } }, 200) }) } public async recordSubIFrames(context: Window) { const frames = await this.waitingSubIFramesLoaded(context) frames.forEach(frameWindow => { this.createIFrameRecorder(frameWindow) }) } public async recordIFrame(context: Window) { const frameWindow = await this.waitingIFrameLoaded(context) if (frameWindow) { this.createIFrameRecorder(frameWindow) } } private createIFrameRecorder(frameWindow: Window) { const frameRecorder = new RecorderModule({ ...this.options, context: frameWindow, keep: true, rootRecorder: this.options.rootRecorder || this, rootContext: this.options.rootContext }) const frameElement = frameWindow.frameElement as Element & { frameRecorder: RecorderModule } frameElement.frameRecorder = frameRecorder this.destroyStore.add(() => frameRecorder.destroy()) } private connectCompose(list: RecorderMiddleware[]) { return async (data: RecordData) => { return await list.reduce( (next: () => Promise<void>, fn: RecorderMiddleware) => { return this.createNext(fn, data, next) }, () => Promise.resolve() )() } } private createNext(fn: RecorderMiddleware, data: RecordData, next: () => Promise<void>) { return async () => await fn(data, next) } }
the_stack
import File = require("fs"); import Path = require("path"); import ChildProcess = require("child_process"); // Note: Because ambrosia-node is a TypeScript library, and therefore any Node app using it will have to // install TypeScript to use it, we don't need to add "typescript" to the "dependencies" in package.json. // Further, since we're using the TypeScript compiler API to reflect on the developer's code, it's better to use // the same version of TypeScript that the developer is using to write their app (instead of a likely different // version tied to ambrosia-node [see https://www.typescriptlang.org/docs/handbook/module-resolution.html]). import TS = require("typescript"); // For TypeScript AST parsing // Note: The 'import * as Foo from "./Foo' syntax avoids the "compiler re-write problem" that breaks debugger hover inspection import * as Configuration from "./Configuration"; import * as IC from "./ICProcess"; import * as Messages from "./Messages"; import * as Utils from "./Utils/Utils-Index"; import * as Root from "./AmbrosiaRoot"; // Shorthand for "Utils.assertDefined()". // For example, this is used with the optional FileGenOptions members (which all have default values) to // both transform their type (to satisfy 'strictNullChecks') and to verify that they are not _undefined_ // (which the FileGenOptions constructor explicitly prevents). import { assertDefined } from "./Utils/Utils"; /** * The methods that this Ambrosia app/service has published (with publishMethod/publishPostMethod). */ let _publishedMethods: { [methodName: string]: { [version: number]: Method } } = {}; /** * The types that this Ambrosia app/service has published (with publishType). Typically, these are complex types but they may also be enums.\ * The key is the type name (eg. "employee"), and the value is the type definition (eg. "{ name: { firstName: string, lastName: string}, startDate: number }"). */ let _publishedTypes: { [typeName: string]: Type } = {}; /** * The types that have been referenced by other types, but which have not yet been published (ie. forward references). * This list must be empty for publishMethod() and publishPostMethod() to succeed. "Dangling" types (ie. references to * unpublished types) can still happen if the user only publishes types but no methods (which is essentially pointless). * * Key = Missing type name, Value = Description of the usage context where the missing type was encountered. */ let _missingTypes: Map<string, string> = new Map<string, string>(); /** * [Internal] Clears all published types and methods.\ * This method is for **internal testing only**. */ export function clearPublishedEntities(): number { const entitiesCleared: number = Object.keys(_publishedMethods).length + Object.keys(_publishedTypes).length; _publishedMethods = {}; _publishedTypes = {}; _missingTypes.clear(); AST.clearPublishedSourceFile(); return (entitiesCleared); } /** * [Interna] Class that describes a method that can be called using Ambrosia.\ * The meta data is used to both check incoming post method calls (see postInterceptDispatcher) and for documentation purposes (see getPublishedMethodsAsync). * Identifiers and types will be checked for correctness. */ export class Method { /** The ID of the method. */ id: number; /** The name of the method. */ name: string; /** * The type returned by the method.\ * Simple type examples: "void", "number", "boolean", "string", "Uint8Array".\ * Complex type example: "{ userName: string, phoneNumbers: number[] }".\ * Will always be "void" for a non-post method. */ returnType: string; /** The names of the method parameters. */ parameterNames: string[]; /** The types of the method parameters (see returnType for examples). */ parameterTypes: string[]; /** The expanded versions of parameterTypes (ie. all published types replaced with their expandedDefinitions, and without any generic-type specifiers). */ expandedParameterTypes: string[]; /** The version number of the method. Will always be 1 for a non-post method (to retain compatibility with C# Fork/Impulse methods, whose RPC message format doesn't include a version). */ version: number; /** * A flag indicating whether the parameter types of the [post] method should be checked when the method is called. * If the method relies on JavaScript type coercion, then set this to false. */ isTypeChecked: boolean; /** [Internal] Options to facilitate code generation for the method. */ codeGenOptions: CodeGenOptions | null = null; /** [ReadOnly] True if the method is a 'post' method. */ get isPost(): boolean { return (this.id === IC.POST_METHOD_ID); } /** [ReadOnly] True if the method takes raw-byte (ie. custom serialized) parameters (specified as a single parameter "rawParams: Uint8Array"). */ get takesRawParams(): boolean { return ((this.parameterNames.length === 1) && (this.parameterNames[0] === "rawParams") && (this.parameterTypes[0] === "Uint8Array")); } /** * ReadOnly] The name of the method for use in a TypeScript (TS) wrapper for the method (produced during code generation). * Only when the version of the method is greater than 1 will the 'nameForTsWrapper' be different from 'name' (eg. "myMethod_v3"), * which means this only applies to post methods. */ get nameForTSWrapper(): string { return ((this.version === 1) ? this.name : `${this.name}_v${this.version}`); } constructor(id: number, name: string, version: number = 1, parameters: string[] = [], returnType: string = "void", doRuntimeTypeChecking: boolean = true, codeGenOptions?: CodeGenOptions) { this.id = id; this.name = name.trim(); this.parameterNames = []; this.parameterTypes = []; this.expandedParameterTypes = []; this.version = this.isPost ? version : 1; this.codeGenOptions = codeGenOptions || null; this.returnType = this.isPost ? Type.formatType(returnType) : "void"; this.isTypeChecked = this.isPost ? doRuntimeTypeChecking : false; this.validateMethod(name, parameters, this.returnType); } /** Throws if any of the method parameters (or the returnType) are invalid. */ private validateMethod(methodName: string, parameters: string[], returnType?: string): void { let firstOptionalParameterFound: boolean = false; checkName(methodName, "method"); for (let i = 0; i < parameters.length; i++) { let pos: number = parameters[i].indexOf(":"); if (pos === -1) { throw new Error(`Method '${methodName}' has a malformed method parameter ('${parameters[i]}')`); } let paramName: string = parameters[i].substring(0, pos).trim(); let paramType: string = parameters[i].substring(pos + 1).trim(); let isOptionalParam: boolean = paramName.endsWith("?"); let isRestParam: boolean = paramName.startsWith("..."); let description: string = `parameter '${paramName}' of method '${methodName}'`; // Note: checkType() will also check paramName checkType(TypeCheckContext.Method, paramType, paramName, description, true, true); this.parameterNames.push(paramName); const formattedParamType: string = Type.formatType(paramType); this.parameterTypes.push(formattedParamType); // This is an optimization so that we don't have to repeatedly expand parameter types at runtime let expandedType: string = Type.expandType(this.parameterTypes[i]); if (!expandedType) { // This should never happen since publishMethod() and publishPostMethod() both call checkForMissingPublishedTypes() throw new Error(`Unable to expand the type definition for parameter '${paramName}' of method '${methodName}'`); } if ((this.parameterTypes[i] !== "any") && (expandedType === "any")) { reportTypeSimplificationWarning(`the type of parameter '${paramName}' of method '${methodName}'`, this.parameterTypes[i]); } this.expandedParameterTypes.push(expandedType); // Check that any optional parameters come AFTER all non-optional parameters [to help code-gen in emitTypeScriptFileEx()] if (isOptionalParam && !firstOptionalParameterFound) { firstOptionalParameterFound = true; } if (firstOptionalParameterFound && !isOptionalParam) { throw new Error(`Required parameter '${paramName}' of method '${methodName}' must be specified before all optional parameters`); } if (isRestParam) { // Check that a rest parameter is an array if (!formattedParamType.endsWith("[]")) { throw new Error(`Rest parameter '${paramName}' of method '${methodName}' must be an array`); } // Check that a rest parameter comes last in the parameter list if (i !== parameters.length - 1) { throw new Error(`Rest parameter '${paramName}' of method '${methodName}' must be specified after all other parameters`); } } } // Post methods don't support a single 'rawParams' parameter like Fork and Impulse methods do (post methods ALWAYS serialize parameters as JSON) if (this.isPost && this.takesRawParams) { // Note: The user can easily workaround this error by simply using a parameter name other than "rawParams". The reason // for throwing the error is to ensure that code-gen/Method.makeTSWrappers() and Method.getSignature() produce // the correct signature for the method. It also informs the user that Post methods do not support the 'rawParams: Uint8Array' // pattern (like non-Post methods do), and that Post method parameters will always be serialized to JSON. throw new Error(`Post method '${methodName}' is defined as taking a single 'rawParams' Uint8Array parameter; Post methods do NOT support custom (raw byte) parameter serialization - all parameters are always serialized to JSON`); } if (returnType && !Utils.equalIgnoringCase(returnType, "void")) { const typeDescription: string = `return type of method '${methodName}'`; const result: { kindFound: CompoundTypeKind, components: string[] } = Type.getCompoundTypeComponents(returnType); // returnType can be an [in-line] union or intersection if (result.components.length > 0) { const kindName: string = CompoundTypeKind[result.kindFound].toLowerCase(); result.components.map((t, i) => checkType(TypeCheckContext.Method, t, null, `${kindName}-type component #${i + 1} of ${typeDescription}`)); } else { checkType(TypeCheckContext.Method, returnType, null, typeDescription); } } } /** Returns the method definition as XML, including the Ambrosia call signatures for the method. */ getXml(expandTypes: boolean = false): string { let xml: string = `<Method isPost=\"${this.isPost}\" name=\"${this.name}\" `; if (this.isPost) { xml += `version=\"${this.version}\" resultType=\"${expandTypes ? Type.expandType(this.returnType) : this.returnType}\" isTypeChecked=\"${this.isTypeChecked}\">`; } else { xml += `id=\"${this.id}\">`; } for (let i = 0; i < this.parameterNames.length; i++) { xml += `<Parameter name="${this.parameterNames[i]}" type="${expandTypes ? Type.expandType(this.parameterTypes[i]) : this.parameterTypes[i]}"/>`; } if (this.isPost) { xml += `<CallSignature type=\"Fork\">${Utils.encodeXmlValue(this.getSignature(Messages.RPCType.Fork, expandTypes))}</CallSignature>`; xml += `<CallSignature type=\"Impulse\">${Utils.encodeXmlValue(this.getSignature(Messages.RPCType.Impulse, expandTypes))}</CallSignature>`; } else { xml += `<CallSignature type=\"Fork\">${Utils.encodeXmlValue(this.getSignature(Messages.RPCType.Fork, expandTypes))}</CallSignature>`; xml += `<CallSignature type=\"Impulse\">${Utils.encodeXmlValue(this.getSignature(Messages.RPCType.Impulse, expandTypes))}</CallSignature>`; xml += `<CallSignature type=\"Fork\">${Utils.encodeXmlValue(this.getSignature(Messages.RPCType.Fork, expandTypes, true))}</CallSignature>`; xml += `<CallSignature type=\"Impulse\">${Utils.encodeXmlValue(this.getSignature(Messages.RPCType.Impulse, expandTypes, true))}</CallSignature>`; } xml += "</Method>"; return (xml); } /** Returns a psuedo-JS "template" of the Ambrosia call signature for the method. */ getSignature(rpcType: Messages.RPCType, expandTypes: boolean = false, enqueueVersion: boolean = false): string { let paramList: string = ""; let localInstanceName: string = Configuration.loadedConfig().instanceName; for (let i = 0; i < this.parameterNames.length; i++) { let paramName: string = Method.trimRest(this.parameterNames[i]); let paramType: string = expandTypes ? Type.expandType(this.parameterTypes[i]) : this.parameterTypes[i]; if (this.isPost) { let isComplexType: boolean = (paramType[0] === "{"); paramList += `${(i > 0) ? ", " : ""}IC.arg("${paramName}", ${isComplexType ? paramType : `${paramType}`})`; } else { paramList += `${(i > 0) ? ", " : ""}${paramName}: ${paramType}`; } } if (this.isPost) { return (`IC.post${Messages.RPCType[rpcType]}("${localInstanceName}", "${this.name}", ${this.version}, -1, null /* callContextData */, ${paramList});`); } else { paramList = this.takesRawParams ? `<${paramList}>` : `{ ${paramList} }`; return (`IC.${enqueueVersion ? "queue" : "call"}${Messages.RPCType[rpcType]}("${localInstanceName}", ${this.id}, ${paramList});`); } } /** Returns the parameters of the method in a form suitable for constructing a TypeScript function/method. */ makeTSFunctionParameters(): string { let functionParameters: string = ""; for (let i = 0; i < this.parameterNames.length; i++) { functionParameters += `${this.parameterNames[i]}: ${this.parameterTypes[i]}` + ((i === this.parameterNames.length - 1) ? "" : ", "); } return (functionParameters); } /** Removes the "..." rest parameter prefix (if any). */ static trimRest(paramName: string): string { return (paramName.replace(/^\.\.\./, "")); } /** * Returns definitions for TypeScript wrapper functions for the published method. * Post methods produce a Fork-based ("xxxx_Post") and an Impulse-based ("xxxx_PostByImpulse") wrapper.\ * Non-post methods produce a Fork and Impulse wrapper, and an EnqueueFork and EnqueueImpulse wrapper [for explicit batching that must be flushed using IC.flushQueue()]. */ makeTSWrappers(startingIndent: number = 0, fileOptions: FileGenOptions, jsDocComment?: string): string { const tabIndent: number = fileOptions.tabIndent || 4; const publisherContactInfo: string = fileOptions.publisherContactInfo || ""; const apiName: string = fileOptions.apiName; const NL: string = Utils.NEW_LINE; // Just for short-hand const pad: string = " ".repeat(startingIndent); const tab: string = " ".repeat(tabIndent); const NOTE_PLACEHOLDER : string = "[NOTE_PLACEHOLDER]"; let wrapperFunctions: string = ""; let functionParameters: string = this.makeTSFunctionParameters(); jsDocComment = jsDocComment ? jsDocComment.split(NL).map(line => pad + line).join(NL) + NL : ""; if (jsDocComment) { const lines: string[] = jsDocComment.trimEnd().split(NL); if (lines.length === 1) { const matches: RegExpExecArray | null = /^\/\*\*(.+)\*\/$/g.exec(lines[0].trim()); const commentBody: string = (matches && (matches.length > 0)) ? matches[1].trim() : ""; jsDocComment = pad + "/**" + NL + pad + " * " + NOTE_PLACEHOLDER + NL + pad + " * " + NL + pad + " * " + commentBody + NL + pad + " */" + NL; } else { const matches: RegExpExecArray | null = /^\/\*\*(.+)$/g.exec(lines[0].trim()); const firstLineBody: string = (matches && (matches.length > 0)) ? matches[1].trim() : ""; jsDocComment = pad + "/**" + NL + pad + " * " + NOTE_PLACEHOLDER + NL + pad + " * " + NL; if (firstLineBody) { jsDocComment += pad + " * " + firstLineBody + NL; } jsDocComment += lines.slice(1, lines.length).join(NL) + NL; } } else { jsDocComment = pad + "/**" + NL + pad + " * " + NOTE_PLACEHOLDER + NL + pad + " */" + NL; } if (this.isPost) { let postFunction: string = `${pad}export function ${this.nameForTSWrapper}_Post[WRAPPER_SUFFIX]`; // Since there is no "_PostImpulse" we don't use "_PostFork", just "_Post" let postFunctionParameters: string = ""; let postArgs: string = ""; postFunctionParameters = `(callContextData: any${(functionParameters.length > 0) ? ", " : ""}${functionParameters}): [RETURN_TYPE]`; for (let i = 0; i < this.parameterNames.length; i++) { if (this.parameterNames.length > 1) { postArgs += pad + tab.repeat(2); } postArgs += `IC.arg("${Method.trimRest(this.parameterNames[i])}", ${Method.trimRest(this.parameterNames[i]).replace("?", "")})` + ((i === this.parameterNames.length - 1) ? ");" : ", ") + NL; } // Reminder: When IC.postFork()/postByImpulse() is called, the return value is processed via the PostResultDispatcher let postFunctionBody: string = pad + "{" + NL; postFunctionBody += pad + tab + "checkDestinationSet();" + NL; postFunctionBody += pad + tab + `[CALL_ID]IC.post[RPC_TYPE_TOKEN](_destinationInstanceName, "${this.name}", ${this.version}, _postTimeoutInMs, callContextData` + (this.parameterNames.length > 0 ? ", " : `);${NL}`) + (this.parameterNames.length > 1 ? NL : "") + postArgs; postFunctionBody += pad + "[RETURN_STATEMENT]" + "}"; // Add a comment about how to obtain the result (and the type of the result) const resultNote: string = `The result (${this.returnType.replace(/`/g, "\\`")}) produced by this post method is received via the PostResultDispatcher provided to IC.start().[CALL_ID_RETURN_COMMENT]`; jsDocComment = addNote(jsDocComment, resultNote, false); const postForkFunction: string = (postFunction + postFunctionParameters + NL + postFunctionBody) .replace(/\[WRAPPER_SUFFIX]/g, "").replace(/\[RPC_TYPE_TOKEN]/g, "Fork").replace(/\[RETURN_TYPE]/g, "number") .replace(/\[CALL_ID]/g, "const callID = ").replace(/\[RETURN_STATEMENT]/g, tab + "return (callID);" + NL + pad); const postByImpulseFunction: string = (postFunction + postFunctionParameters + NL + postFunctionBody) .replace(/\[WRAPPER_SUFFIX]/g, "ByImpulse").replace(/\[RPC_TYPE_TOKEN]/g, "ByImpulse").replace(/\[RETURN_TYPE]/g, "void") .replace(/\[CALL_ID]/g, "").replace(/\[RETURN_STATEMENT]/g, ""); const postForkComment: string = addNote(jsDocComment.replace(/\[CALL_ID_RETURN_COMMENT]/g, " Returns the post method callID."), "\"_Post\" methods should **only** be called from deterministic events."); const postByImpulseComment: string = addNote(jsDocComment.replace(/\[CALL_ID_RETURN_COMMENT]/g, ""), "\"_PostByImpulse\" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc)."); wrapperFunctions += postForkComment + postForkFunction + NL.repeat(2); wrapperFunctions += postByImpulseComment + postByImpulseFunction; } else { let jsonArgs: string = "{}"; if (this.parameterNames.length > 0) { jsonArgs = "{ "; for (let i = 0; i < this.parameterNames.length; i++) { const paramName: string = Method.trimRest(this.parameterNames[i]).replace("?", ""); jsonArgs += `${(i > 0) ? ", " : ""}${paramName}: ${paramName}`; } jsonArgs += " }"; } let jsonOrRawArgs: string = this.takesRawParams ? this.parameterNames[0].replace("?", "") : jsonArgs; let functionTemplate: string = `${pad}export function ${this.name}[NAME_TOKEN](${functionParameters}): void` + NL; functionTemplate += pad + "{" + NL; functionTemplate += pad + tab + "checkDestinationSet();" + NL; functionTemplate += pad + tab + `IC.[IC_METHOD_TOKEN](_destinationInstanceName, ${this.id}, ` + jsonOrRawArgs + ");" + NL; functionTemplate += pad + "}"; if (this.takesRawParams) { // If not already described in the jsDocComment, add a JSDoc @param tag for the [lone] 'rawParams' parameter [because it's "special"] if (!jsDocComment || !RegExp("\\*[ ]*@param[ ]+(?:{.+}[ ]+)?rawParams[ ]").test(jsDocComment)) { const contactInfo: string = publisherContactInfo ? ` (${publisherContactInfo})` : ""; const newComment: string = `@param rawParams A custom serialization (byte array) of all required parameters. Contact the '${apiName}' API publisher${contactInfo} for details of the serialization format.`; if (jsDocComment) { jsDocComment = jsDocComment.trimEnd().replace("*/", "").trimEnd() + NL + pad + " * " + newComment + NL + pad + " */" + NL; } else { jsDocComment = pad + `/** ${newComment} */` + NL; } } } let forkFunction: string = functionTemplate.replace(/\[NAME_TOKEN]/g, "_Fork").replace(/\[IC_METHOD_TOKEN]/g, "callFork"); let impulseFunction: string = functionTemplate.replace(/\[NAME_TOKEN]/g, "_Impulse").replace(/\[IC_METHOD_TOKEN]/g, "callImpulse"); let enqueueForkFunction: string = functionTemplate.replace(/\[NAME_TOKEN]/g, "_EnqueueFork").replace(/\[IC_METHOD_TOKEN]/g, "queueFork"); let enqueueImpulseFunction: string = functionTemplate.replace(/\[NAME_TOKEN]/g, "_EnqueueImpulse").replace(/\[IC_METHOD_TOKEN]/g, "queueImpulse"); wrapperFunctions += addNote(jsDocComment, "\"_Fork\" methods should **only** be called from deterministic events.") + forkFunction + NL.repeat(2); wrapperFunctions += addNote(jsDocComment, "\"_Impulse\" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc).") + impulseFunction + NL.repeat(2); wrapperFunctions += addNote(jsDocComment, "\"_EnqueueFork\" methods should **only** be called from deterministic events, and will not be sent until IC.flushQueue() is called.") + enqueueForkFunction + NL.repeat(2); wrapperFunctions += addNote(jsDocComment, "\"_EnqueueImpulse\" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc), and will not be sent until IC.flushQueue() is called.") + enqueueImpulseFunction; } return (wrapperFunctions); /** [Local function] In the supplied jsDocComment, replaces the NOTE_PLACEHOLDER token with a "Note: {note}". */ function addNote(jsDocComment: string, note: string, isFinalNote: boolean = true): string { const newPlaceHolder: string = isFinalNote ? "" : (NL + `${pad} * ` + NL + `${pad} * ${NOTE_PLACEHOLDER}`); let modifiedComment = jsDocComment.replace(NOTE_PLACEHOLDER, `*Note: ${note}*${newPlaceHolder}`); return (modifiedComment); } } } /** Either 'None', 'Union', 'Intersection', or 'All'. */ enum CompoundTypeKind { None, Union, Intersection, All } /** * [Internal] Class that describes a published (named) type - typically a complex type - that can be used in an Ambrosia method, or in another published type.\ * The class also includes several type utility methods, like getNativeTypes(). */ export class Type { /** The type name, eg. "employee". */ name: string; /** * The definition of the type, which may include references to other published (named) types, * eg. "{ employeeName: name, startDate: number, jobs: Job[] }". */ definition: string; /** * The definition of the type with all published (named) types replaced with their expandedDefinitions, eg. * "{ employeeName: { firstName: string, lastName: string}, startDate: number }", and without any generic-type specifiers. */ expandedDefinition: string; /** If this type is an Enum, these are the available values (eg. "1=Foo,2=Bar"). */ enumValues: string | null = null; // Note: We do NOT check enum ranges as part of runtime type-checking (this was explored, but deemed to add too much complexity; plus, no other type values are range checked by the LB) /** [Internal] Options to facilitate code generation for the type. */ codeGenOptions: CodeGenOptions | null = null; /** [ReadOnly] Whether the type is a complex type. */ get isComplexType(): boolean { return (this.definition.startsWith("{")); } constructor(typeName: string, typeDefinition: string, enumValues: string | null = null, codeGenOptions?: CodeGenOptions) { typeName = typeName.trim(); typeDefinition = typeDefinition.trim(); const typeDescription: string = `published type '${typeName}'`; checkType(TypeCheckContext.Type, typeDefinition, typeName, typeDescription, false); // Note: A published type name cannot be optional (ie. end with '?') this.name = typeName; this.definition = Type.formatType(typeDefinition); this.expandedDefinition = Type.expandType(this.definition); if ((typeDefinition === "number") && enumValues) { this.enumValues = enumValues; } this.codeGenOptions = codeGenOptions || null; } /** * Attempts to parse the supplied 'typeDefinition' as the specified CompoundTypeKind, and returns a { kindFound, components } result.\ * For example, given "A | (B & C)" and a 'kind' of CompoundTypeKind.All (the default), the result will be { CompoundTypeKind.UnionType, ["A", "(B & C)"] }.\ * Returns { CompoundTypeKind.None, [] } if the 'typeDefinition' is not a compound type of the specified 'kind'. */ static getCompoundTypeComponents(typeDefinition: string, kind: CompoundTypeKind = CompoundTypeKind.All): { kindFound: CompoundTypeKind, components: string[] } { const compoundType = typeDefinition.replace(/^\(/, "").replace(/[\[\]]*$/, "").replace(/\)$/, "") // Convert "(A | B)[]" to "A | B" const unionRegEx: RegExp = /(?<![:{\(][^|&]+)[|]/g; // Takes into account bracketed/braced components, like "A | (B & C)[] | (D | E) | { p1: F | G}" const intersectionRegEx: RegExp = /(?<![:{\(][^|&]+)[&]/g; // Takes into account bracketed/braced components, like "A | (B & C)[] | (D | E) | { p1: F | G}" let compoundComponents: string[] = []; let foundKind: CompoundTypeKind = CompoundTypeKind.None; switch (kind) { case CompoundTypeKind.Union: compoundComponents = compoundType.split(unionRegEx); foundKind = (compoundComponents.length > 1) ? kind : CompoundTypeKind.None; break; case CompoundTypeKind.Intersection: compoundComponents = compoundType.split(intersectionRegEx); foundKind = (compoundComponents.length > 1) ? kind : CompoundTypeKind.None; break; case CompoundTypeKind.All: // In TypeScript, intersection has higher precedence than union, so "A | B & C" is evaluated as "A | (B & C)" (see https://github.com/microsoft/TypeScript/pull/3622). // This is why we parse for union (lower precedence) before intersection (higher precedence). const unionComponents: string[] = compoundType.split(unionRegEx); if (unionComponents.length > 1) // length can be 1 if the type is an intersection type that contains a [bracketed] union component (eg. "A & (B | C)") { compoundComponents = unionComponents; foundKind = CompoundTypeKind.Union; } else { const intersectionComponents: string[] = compoundType.split(intersectionRegEx); if (intersectionComponents.length > 1) // length can be 1 if the type is an union type that contains a [bracketed] intersection component (eg. "A | (B & C)") { compoundComponents = intersectionComponents; foundKind = CompoundTypeKind.Intersection; } } break; default: throw new Error(`Unsupported CompoundTypeKind '${CompoundTypeKind[kind]}'`); } return ({ kindFound: foundKind, components: (compoundComponents.length > 1) ? compoundComponents.map(c => c.trim()) : [] }); } /** Returns true if the type is currently referenced by any published method. */ isReferenced(): boolean { for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { const method: Method = _publishedMethods[name][version]; if (method.returnType === this.name) { return (true); } for (let i = 0; i < method.parameterTypes.length; i++) { if (method.parameterTypes[i] === this.name) { return (true); } } } } return (false); } /** Returns a TypeScript class, type-alias, or enum definition for the published type. */ makeTSType(startingIndent: number = 0, tabIndent: number = 4, jsDocComment?: string, isPublic: boolean = true): string { const NL: string = Utils.NEW_LINE; // Just for short-hand const tab: string = " ".repeat(tabIndent); const pad: string = " ".repeat(startingIndent); let className: string = this.name; let classDefinition: string = ""; jsDocComment = jsDocComment ? jsDocComment.split(NL).map(line => pad + line).join(NL) + NL : ""; if (!this.isComplexType) { if (this.enumValues) { let enumValues: string = "{ " + this.enumValues.split(",").map(pair => `${pair.split("=")[1]} = ${pair.split("=")[0]}`).join(", ") + " }"; return (`${jsDocComment}${pad}${isPublic ? "export " : ""}enum ${this.name} ${enumValues}`); } else { // An aliased simple type doesn't need a full-blown class definition return (`${jsDocComment}${pad}${isPublic ? "export " : ""}type ${this.name} = ${this.definition};`); } } // Is the type an array of a complex type, eg. "{ p1: string }[]" ? // If so, we create BOTH a class (eg. "class Foo_Element") for the "base" type (eg. { p1: string }) and an alias (eg. "type Foo = Foo_Element[];") for the array of the "base" type. // This makes it easier for the developer using ConsumerInterface.g.ts to create an instance of, in this case, Foo (eg. "let f: Foo = [ new Foo_Element(...) ];"). // If the user wants to control the naming of the auto-generated "base" type (eg. "Foo_Element"), they can explicitly publish the "base" type separately (which is recommended). const arraySuffix: string = Type.getArraySuffix(this.definition); if (arraySuffix) { className = className + "_Element"; // An auto-generated name while (_publishedTypes[className]) { className = "_" + className; // Keep prepending "_" until we find a unique name } classDefinition = `${pad}${isPublic ? "export " : ""}type ${this.name} = ${className}${arraySuffix};` + NL.repeat(2); } classDefinition += `${pad}${isPublic ? "export " : ""}class ${className}` + NL + pad + '{' + NL; let topLevelTokens: string[] = Type.tokenizeComplexType(Type.removeArraySuffix(this.definition), false); // We DON'T remove generics here since we're creating a TS type if (topLevelTokens.length % 2 !== 0) { throw new Error(`Published type '${this.name}' could not be tokenized (it contains ${topLevelTokens.length} tokens, not an even number as expected)`); } // Add class members [all public] for (let i = 0; i < topLevelTokens.length; i += 2) { let nameToken: string = topLevelTokens[i]; let typeToken: string = Type.formatType(topLevelTokens[i + 1]); classDefinition += `${pad}${tab}${nameToken} ${typeToken};` + NL; } // Add class constructor classDefinition += NL + `${pad}${tab}constructor(`; for (let i = 0; i < topLevelTokens.length; i += 2) { let nameToken: string = topLevelTokens[i]; let typeToken: string = Type.formatType(topLevelTokens[i + 1]); classDefinition += `${nameToken} ${typeToken}` + ((i === topLevelTokens.length - 2) ? ")" : ", " ); } classDefinition += NL + pad + tab + "{" + NL; for (let i = 0; i < topLevelTokens.length; i += 2) { let propertyName: string = topLevelTokens[i].substring(0, topLevelTokens[i].length - 1); classDefinition += `${pad}${tab.repeat(2)}this.${propertyName} = ${propertyName};` + NL; } classDefinition += pad + tab + "}" + NL + pad + "}"; return (jsDocComment + classDefinition); } /** Formats the type definition into a displayable, mono-spaced format. */ static formatType(typeDefinition: string): string { const isTemplateStringType: boolean = typeDefinition.trim().startsWith("`"); if (isTemplateStringType) { // We preserve spacing (or lack thereof) for a template string type return (typeDefinition); } let formattedTypeDefinition: string = typeDefinition.replace(/\s+/g, ""); // Remove all space formattedTypeDefinition = formattedTypeDefinition.replace(/}/g, " }").replace(/[{:,]/g, "$& "); // Add space before '}' and after '{', ':', ',' formattedTypeDefinition = formattedTypeDefinition.replace(/\[](?=[^,\[]])/g, "[] "); // Add space after trailing '[]' formattedTypeDefinition = formattedTypeDefinition.replace(/[&|]/g, " $& "); // Add space before and after '|' and '&' (union and intersection) return (formattedTypeDefinition); // Note: Arrays of complex types will be formatted as "{...}[]", ie. with no space between '}' and '[' } /** * Returns the expanded definition of the specified type (ie. with named [published] types replaced, but without any generic-types specifiers). * Returns "" if the type cannot be expanded (due to unresolved forward references).\ * Throws if expanding the type isn't possible because of a circular reference. */ static expandType(type: string, parentTypeChain: string[] = []): string { type = type.trim(); // Check for a circular reference (since we can't expand in this case) if (parentTypeChain.indexOf(type) !== -1) { // TODO: This message would be better if it could reference the actual published types involved (simply looking // them up by their definition is not viable since multiple published types can have the same definition) throw new Error(`Unable to expand type definition '${type}' because it has a circular reference with definition '${parentTypeChain[parentTypeChain.length - 1]}'`); } parentTypeChain.push(type); // The expanded definition of a published type (or published method parameter) is used for comparison with a runtime type. However, // because generic-types specifiers are a compile-time feature, they are NOT included in the type definition produced by getRuntimeType() // (which, for example, will return "Set" for a serialized "Set<string>" instance). So we don't include them in the expanded definition. let expandedDefinition: string = Type.removeGenericsSpecifiers(type); // For simplicity, we treat [validated] template string types (eg. `Hello ${number | string}`) as "string" const isTemplateStringType: boolean = (expandedDefinition.indexOf("`") === 0); if (isTemplateStringType) { return ("string"); } // For simplicity, we treat [validated] union and intersection types as "any" [thus opting them out of runtime type checking]. // Note: Simplifying to "any" [during expansion] is different from an explicit use of "any" in a type, because the type being // simplified has already been checked (so, unless it too contains null, we know it will serialize). // Note: A complex type with an "in-line" union/intersection type (eg. { p1: number, p2: string | null }) will become "any", whereas a complex type using a // published union/intersection type (eg. { p1: number, p2: MyUnionType }, where MyUnionType is "string | null") will become "{ p1: number, p2: any }", // which will result in better runtime type checking. So the recommendation is to publish, not in-line, compound types. The warning message emitted by // publishType() and publish[Post]Method() calls this out [see reportTypeSimplificationWarning()]. // TODO: We could fix this by finding/replacing all compound types in the complex type below (but this would be tricky). const isOrContainsCompoundType: boolean = (expandedDefinition.indexOf("|") !== -1) || (expandedDefinition.indexOf("&") !== -1); if (isOrContainsCompoundType) { return ("any"); } if (type.startsWith("{")) // A complex type { // Find all used type names (by looking for ": typeName, " or ": typeName }" or ": typeName[], " or ": typeName[] }") // Note: We don't replace published type names in compound types (unions/intersections) because these are always expanded to "any" (see above). // Note: Test at https://regex101.com/ (set "Flavor" to ECMAScript) let regex: RegExp = /: ([A-Za-z][A-Za-z0-9_]*)(?:\[])*?(?:, | })/g; let result: RegExpExecArray | null; let usedPublishedTypeNames: string[] = []; while (result = regex.exec(type)) // Because regex use /g, exec() does a stateful search, returning only the next match with each call { let typeName: string = result[1]; if (_publishedTypes[typeName] && (usedPublishedTypeNames.indexOf(typeName) === -1)) { usedPublishedTypeNames.push(typeName); } if (_missingTypes.has(typeName)) { // We can't expand (we have to wait until the missing type is published), so return "" (that way we can easily find it and fix it later) return (""); } } for (let i = 0; i < usedPublishedTypeNames.length; i++) { const publishedTypeName: string = usedPublishedTypeNames[i]; const publishedType: Type = _publishedTypes[publishedTypeName]; const publishedTypeExpandedDefinition: string = publishedType.expandedDefinition ? publishedType.expandedDefinition : Type.expandType(publishedType.definition, parentTypeChain); if (!publishedTypeExpandedDefinition) { // We can't expand (we have to wait until the missing type is published), so return "" (that way we can easily find it and fix it later) // Note: Unlike earlier, in this case it's a dependency of one of the used published types which has not yet been defined return (""); } expandedDefinition = expandedDefinition.replace(RegExp("(?<=: )" + publishedTypeName + "(?=, | }|\\[)", "g"), publishedTypeExpandedDefinition); } } else { // The 'type' is [potentially] a published type name (eg. "employee") const typeName = type.replace(/\[]/g, ""); // Remove all square brackets (eg. "Name[]" => "Name") if (_missingTypes.has(typeName)) { // We can't expand (we have to wait until the missing type is published), so return "" (that way we can easily find it and fix it later) return (""); } if (_publishedTypes[typeName]) { const publishedType: Type = _publishedTypes[typeName]; const publishedTypeExpandedDefinition: string = publishedType.expandedDefinition ? publishedType.expandedDefinition : Type.expandType(publishedType.definition, parentTypeChain); if (!publishedTypeExpandedDefinition) { // We can't expand (we have to wait until the missing type is published), so return "" (that way we can easily find it and fix it later) // Note: Unlike earlier, in this case it's a dependency of one of the used published types which has not yet been defined return (""); } expandedDefinition = type.replace(typeName, publishedTypeExpandedDefinition); } } return (expandedDefinition); } /** Compares a type definition against an expected definition, returning null if the types match or returning a failure reason if they don't. */ static compareTypes(typeDefinition: string, expectedDefinition: string, tokenName: string = "", objectPath: string = ""): string | null { typeDefinition = typeDefinition.replace(/\s+/g,""); // Remove all whitespace expectedDefinition = expectedDefinition.replace(/\s+/g,""); // Remove all whitespace // Do the fast check first if (typeDefinition === expectedDefinition) { return (null); // Match } if ((typeDefinition[0] === "{") && (expectedDefinition[0] === "{")) { return (Type.compareComplexTypes(typeDefinition, expectedDefinition, objectPath)); } else { // Allow "object" to match with any object if (((expectedDefinition === "object") && (typeDefinition[0] === "{")) || ((typeDefinition === "object") && (expectedDefinition[0] === "{"))) { return (null); // Match } // Allow "object" arrays (of n dimensions) to match an object array (also of n dimensions) if ((expectedDefinition.startsWith("object[]") && (typeDefinition[0] === "{") && (Type.getArraySuffix(expectedDefinition) === Type.getArraySuffix(typeDefinition))) || (typeDefinition.startsWith("object[]") && (expectedDefinition[0] === "{") && (Type.getArraySuffix(typeDefinition) === Type.getArraySuffix(expectedDefinition)))) { return (null); // Match } // Allow "any" to match with any type, and "any[]" to match with any array (including allowing any[] to match any array even when the dimensions don't match) // Note: "any" and "any[]" may be inserted into the type definition returned by getRuntimeType(). if ((typeDefinition === "any") || (expectedDefinition === "any") || ((typeDefinition === "any[]") && expectedDefinition.endsWith("[]")) || ((expectedDefinition === "any[]") && typeDefinition.endsWith("[]")) || ((typeDefinition.startsWith("any[]") || expectedDefinition.startsWith("any[]")) && (Type.getArraySuffix(typeDefinition) === Type.getArraySuffix(expectedDefinition)))) { return (null); // Match } if (tokenName) { return (`${tokenName} ${objectPath ? `(in '${objectPath}') ` : ""}should be '${expectedDefinition}', not '${typeDefinition}'`); } else { return (`expected '${expectedDefinition}', not '${typeDefinition}'`); } } } /** * Compares a [complex] type definition against an expected definition, returning null if the types match or returning an error message if they don't.\ * Note: This does a simplistic positional [ordered] match of tokens, which is why we don't support optional members in published types. */ static compareComplexTypes(typeDefinition: string, expectedDefinition: string, objectPath: string = ""): string | null { let failureReason: string | null = null; let typeTokens: string[] = Type.tokenizeComplexType(Type.removeArraySuffix(typeDefinition)); let expectedTokens: string[] = Type.tokenizeComplexType(Type.removeArraySuffix(expectedDefinition)); let maxTokensToCheck: number = Math.min(typeTokens.length, expectedTokens.length); let typeArraySuffix: string = Type.getArraySuffix(typeDefinition); let expectedArraySuffix: string = Type.getArraySuffix(expectedDefinition); for (let i = 0; i < maxTokensToCheck; i++) { const isTypeDefinitionToken: boolean = (i > 0) && typeTokens[i - 1].endsWith(":"); const propertyName: string = isTypeDefinitionToken ? typeTokens[i - 1].slice(0, -1) : ""; const tokenName: string = isTypeDefinitionToken ? `type of '${propertyName}'` : `property #${Math.floor(i / 2) + 1}`; const tokenPath: string = objectPath + ((isTypeDefinitionToken && typeTokens[i].startsWith("{")) ? ((objectPath ? "." : "") + propertyName) : ""); // Note: We're using compareTypes() here to check ALL tokens, not just types if (failureReason = this.compareTypes(typeTokens[i], expectedTokens[i], tokenName, tokenPath)) { break; } } if (!failureReason && (typeTokens.length !== expectedTokens.length)) { const location: string = objectPath ? ` in '${objectPath}'` : ""; if (typeTokens.length > expectedTokens.length) { failureReason = `mismatched structure${location}: unexpected member '${typeTokens[expectedTokens.length]}' provided`; } if (expectedTokens.length > typeTokens.length) { failureReason = `mismatched structure${location}: expected member '${expectedTokens[typeTokens.length]}' not provided`; } } if (!failureReason && (typeArraySuffix !== expectedArraySuffix)) { const location: string = objectPath ? `type of '${objectPath}' (${Type.formatType(typeDefinition)})` : Type.formatType(typeDefinition); failureReason = `${location} should have array suffix ${expectedArraySuffix || '(None)'}, not ${typeArraySuffix || '(None)'}`; } return (failureReason); } /** Returns the supplied 'typeDefinition' without its array suffix, if it has any. For example, "{ p1: string }[]" becomes "{ p1: string }" and "Foo[][]" becomes "Foo". */ static removeArraySuffix(typeDefinition: string): string { const typeWithoutArraySuffix: string = typeDefinition.replace(/[\[\] ]+$/, ""); return (typeWithoutArraySuffix); } /** Returns the array suffix (eg. "[][]") of the supplied 'typeDefinition' (eg. "{ p1: string }[][]"), if it has any. Returns "" otherwise. */ private static getArraySuffix(typeDefinition: string): string { let result: RegExpExecArray | null = /[\[\] ]+$/.exec(typeDefinition); return (result ? result[0].replace(/\s+/g, "") : ""); } /** Returns the supplied type definition without its generic-types specifier(s) (if any), eg. "Map<number, string>" becomes "Map". */ // Note: We can't use RegEx for this because it doesn't support finding "balanced pairs" of tokens. static removeGenericsSpecifiers(type: string): string { let result: string = ""; if (type.indexOf("<") === -1) { return (type); } for (let pos = 0; pos < type.length; pos++) { switch (type[pos]) { case "<": let nestLevel: number = 1; while ((nestLevel > 0) && (++pos < type.length - 1)) { if (type[pos] === "<") { nestLevel++; } if (type[pos] === ">") { nestLevel--; } } break; default: result += type[pos]; } } return (result); } /** * Returns all the [top-level] generic-type specifiers (if any) from the supplied type, for example * "{ p1: Set&lt;Foo>, p2: Map<number, Set&lt;string>> }" returns ["&lt;Foo>", "<number, Set&lt;string>>"]. */ static getGenericsSpecifiers(type: string): string[] { let results: string[] = []; let currentSpecifier: string = ""; if (type.indexOf("<") === -1) { return ([]); } for (let pos = 0; pos < type.length; pos++) { switch (type[pos]) { case "<": let nestLevel: number = 1; while ((nestLevel > 0) && (pos < type.length - 1)) { currentSpecifier += type[pos++]; if (type[pos] === "<") { nestLevel++; } if ((type[pos] === ">") && (type[pos - 1] !== "=")) { nestLevel--; } // Note: Have to handle lambda notation ("=>") if (nestLevel === 0) { currentSpecifier += type[pos]; // Add the trailing ">" } } results.push(currentSpecifier); currentSpecifier = ""; break; } } return (results); } /** Given a generic-types specifier (eg. "<number, Map<number, string>>") returns the component types (eg. ["number", "Map<number, string>"]). */ static parseGenericsSpecifier(specifier: string): string[] { let results: string[] = []; let nestLevel: number = 0; let currentType: string = ""; specifier = specifier.trim(); if ((specifier.length <= 2) || (specifier[0] !== "<") || (specifier[specifier.length - 1] !== ">")) { throw new Error (`The supplied specifier ('${specifier}') is invalid; it must start with '<' and end with '>'`); } if (specifier[1] === "{") { results.push(specifier.substr(1, specifier.length - 2)); } else { for (let pos = 1; pos < specifier.length - 1; pos++) { switch (specifier[pos]) { case "<": case "[": // This is only to handle tuples [which we don't support], but it will [benignly] trigger for array suffixes too nestLevel++; break; case ">": case "]": // This is only to handle tuples [which we don't support], but it will [benignly] trigger for array suffixes too if ((specifier[pos] === ">") && (specifier[pos - 1] === "=")) // Skip lambda notation ("=>") { break; } nestLevel--; break; case ",": if (nestLevel === 0) { results.push(currentType); currentType = ""; pos++; } break; } currentType += specifier[pos]; } results.push(currentType); } results.forEach((v, i) => results[i] = v.trim().replace(/\s+/g, " ")); return (results); } /** * Parses a complex type into a set of [top-level only] tokens that can be used for comparing it to another [complex] type. * A complex type must start with "{" but must NOT end with an array suffix (eg. "{...}[]" is invalid). * Because this only returns top-level tokens, it may need to be called recursively on any returned complex-type tokens. */ private static tokenizeComplexType(type: string, removeGenerics: boolean = true): string[] { const enum TokenType { None, Name, SimpleType, ComplexType } type = type.trim(); if (type[0] !== "{") { throw new Error(`The supplied type ('${type}') is not a complex type`); } if (removeGenerics) { type = Type.removeGenericsSpecifiers(type); } if (Type.getArraySuffix(type)) { throw new Error(`The supplied type ('${type}') cannot be tokenized because it has an array suffix`); } // Example: The type "{ addressLines: string[], name: { firstName: string, lastName: { middleInitial: { mi: string }[], lastName: string }[][] }[], startDate: number }" // would yield these 6 [top-level] tokens: // "addressLines:" -> Name // "string[]" -> Simple Type // "name:" -> Name // "{ firstName: string, lastName: { middleInitial: { mi: string }[], lastName: string }[][] }[]" -> Complex Type // "startDate:" -> Name // "number" -> Simple Type let tokens: string[] = []; let nameToken: string = ""; // The current name token let simpleTypeToken: string = ""; // The current simple-type token let complexTypeToken: string = ""; // The current complex-type token let currentTokenType: TokenType = TokenType.None; let depth: number = -1; let complexTypeStartDepth: number = 0; let validCharRegEx: RegExp = /[ A-Za-z0-9_\[\]"'|&]/; for (let pos = 0; pos < type.length; pos++) { let char: string = type[pos]; switch (char) { case "{": switch (currentTokenType) { case TokenType.Name: if (nameToken.length === 0) { throw new Error(`Unexpected character '${char}' at position ${pos} of "${type}"`); } // Fall-through case TokenType.SimpleType: // Our earlier assumption that the next token would be a SimpleType was wrong currentTokenType = TokenType.ComplexType; complexTypeToken = char; complexTypeStartDepth = depth; break; case TokenType.ComplexType: complexTypeToken += char; break; case TokenType.None: // Only happens when pos = 0 currentTokenType = TokenType.Name; break; } depth++; break; case ":": switch (currentTokenType) { case TokenType.Name: if (nameToken.length === 0) { throw new Error(`Unexpected character '${char}' at position ${pos} of "${type}"`); } nameToken += char; // Including the trailing ":" makes it easy to distinguish names from types in the returned tokens list tokens.push(nameToken); nameToken = ""; currentTokenType = TokenType.SimpleType; // We'll assume this until we see "{" break; case TokenType.SimpleType: throw new Error(`Unexpected character '${char}' at position ${pos} of "${type}"`); case TokenType.ComplexType: complexTypeToken += char; break; } break; case "}": depth--; switch (currentTokenType) { case TokenType.SimpleType: tokens.push(simpleTypeToken); simpleTypeToken = ""; // We should now be at the end of 'type' if (pos !== type.length - 1) { throw new Error("tokenizeComplexType() logic error"); } break; case TokenType.ComplexType: complexTypeToken += char; if (depth === complexTypeStartDepth) { if ((pos < type.length - 1) && (type[pos + 1] === "[")) { // Note: We're not validating the type here (we're just tokenizing it), so we don't check for balanced bracket characters while ((++pos < type.length) && ((type[pos] === "[") || (type[pos] === "]"))) { complexTypeToken += type[pos]; } if (!complexTypeToken.endsWith("]")) { throw new Error(`Unexpected character '${complexTypeToken[complexTypeToken.length - 1]}' at position ${pos} of "${type}"`); } } tokens.push(complexTypeToken.trim()); complexTypeToken = ""; currentTokenType = TokenType.Name; } break; } break; case ",": switch (currentTokenType) { case TokenType.ComplexType: complexTypeToken += char; break; case TokenType.SimpleType: tokens.push(simpleTypeToken); simpleTypeToken = ""; currentTokenType = TokenType.Name; break; } break; case "<": if (currentTokenType !== TokenType.SimpleType) { throw new Error(`Unexpected character '${char}' at position ${pos} of "${type}"`); } let nestLevel: number = 1; while ((nestLevel > 0) && (pos < type.length - 1)) { simpleTypeToken += type[pos++]; if (type[pos] === "<") { nestLevel++; } if (type[pos] === ">") { nestLevel--; } if (nestLevel === 0) { simpleTypeToken += type[pos]; // Add the trailing ">" } } break; default: // Space, alphanumeric, double/single quote, union (|), intersection (&), non-terminal [ and ] if (!validCharRegEx.test(char) || ((char === "[") && (pos < type.length - 1) && (type[pos + 1] !== "]")) || // "[" not followed by "]" ((char === "]") && (pos > 0) && (type[pos - 1] !== "["))) // "]" not preceded by "[" { throw new Error(`Unexpected character '${char}' at position ${pos} of "${type}"`); } switch (currentTokenType) { case TokenType.None: throw new Error(`Unexpected character '${complexTypeToken[complexTypeToken.length - 1]}' at position ${pos} of "${type}"`); case TokenType.Name: if (char !== " ") { nameToken += char; } break; case TokenType.SimpleType: if (char !== " ") { simpleTypeToken += char; } break; case TokenType.ComplexType: complexTypeToken += char; break; } break; } } if ((nameToken.length > 0) || (simpleTypeToken.length > 0) || (complexTypeToken.length > 0) || (tokens.length % 2 !== 0)) { throw new Error(`The type definition is incomplete ("${type}")`); } return (tokens); } /** * Returns an array of the supported JavaScript native types, optionally including the boxed versions (eg. String, Number) of the primitive types, the typed arrays (eg. Uint8Array), * and the supported (serializable) built-in types (eg. Date). The list excludes "function" and "Function" for security.\ * All the types returned are serializable, although the boxed primitives cannot be used in published types/methods - the primitives must be used instead. */ // WARNING: If you change this list, you MUST also update jsonStringify() and jsonParse(). // See checkType() and getNativeType() for more on the "boxed-primitive vs. primitive" issue. [TODO: This needs a better explanation]. static getSupportedNativeTypes(includeBoxedPrimitives: boolean = true, includeTypedArrays: boolean = true, includeSupportedBuiltInTypes: boolean = true) : string[] { let primitives: string[] = ["number", "boolean", "string", "object", "bigint" /* es2020 only*/, "null", "undefined"]; // Note: we omit "function" by design let boxedPrimitives: string[] = !includeBoxedPrimitives ? [] : ["Number", "Boolean", "String", "Object", "BigInt" /* es2020 only*/]; // Note: we omit "Function" by design ("Array" is in the supportedBuiltInTypes list) let typedArrays: string[] = !includeTypedArrays ? [] : ["Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array", "BigInt64Array", "BigUint64Array"]; let supportedBuiltInTypes: string[] = !includeSupportedBuiltInTypes ? [] : ["Array", "Set", "Map", "Date", "RegExp", "Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError"]; let nativeTypeNames: string[] = [...primitives, ...boxedPrimitives, ...typedArrays, ...supportedBuiltInTypes]; return (nativeTypeNames); } /** * Returns an array of the unsupported JavaScript native types (to distinguish between missing published types and "known unsupported" native types).\ * The list also includes the unsupported TypeScript built-in types. */ static getUnsupportedNativeTypes(): string[] { return (["function", "Function", "symbol", "Symbol", "WeakSet", "WeakMap", ...["unknown" /* Use "any" instead */, "never" /* Use "void" instead */]]); } /** * Returns either the primitive type name ("number", "string", etc.) or the built-in object type name ("Uint8Array", "Date", etc.). * User-defined objects will always return "object" (although static classes return "function"). */ static getNativeType(value: unknown): string { let result: string = ""; if (value && (typeof value === "object") && (value !== null)) // The additional "(value !== null)" check is to make the compiler happy when using 'strictNullChecks' { // Note: While Ambrosia doesn't do any script "minification", downstream bundlers might. In such cases, 'constructor.name' will return the minified name for // user-defined types. This isn't an issue in our usage below because we're looking for the contructor names of built-in types, which won't get minified. const typeName: string = (value.constructor.name === "Object") ? "object" : value.constructor.name; if (Type.isConstructedBuiltInObject(value)) { result = typeName; // Check for a non-object equivalent type (eg. so that "Number" becomes "number") const startsWithUpperCase: boolean = (result.charCodeAt(0) < 97); if (startsWithUpperCase) { const lcPrimitiveTypeName: string = (typeof value.valueOf()).toLowerCase(); if (result.toLowerCase() === lcPrimitiveTypeName) { result = lcPrimitiveTypeName; } } } else { // A user-defined object (typically a class) result = "object"; } } else { // A non-object type (or null, whose typeof is "object") result = typeof value; } return (result); } /** Returns true if 'obj' is a typed array (eg. Uint8Array). */ public static isTypedArray(obj: any): boolean { const isTypedArray: boolean = (obj instanceof Int8Array) || (obj instanceof Uint8Array) || (obj instanceof Uint8ClampedArray) || (obj instanceof Int16Array) || (obj instanceof Uint16Array) || (obj instanceof Int32Array) || (obj instanceof Uint32Array) || (obj instanceof Float32Array) || (obj instanceof Float64Array) || (obj instanceof BigInt64Array) || (obj instanceof BigUint64Array); return (isTypedArray); } /** Returns true if 'obj' is a built-in object that has a constructor (eg. Uint8Array). Excludes Object. */ private static isConstructedBuiltInObject(obj: any): boolean { // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects // Aside: An alternative, but MUCH slower approach, is this: // const isBuiltInObject: boolean = /\{\s+\[native code\]/.test(Function.prototype.toString.call(obj.constructor)) const isBuiltInObject: boolean = // Fundamental objects // (obj instanceof Object) || // Omitted so that user-defined objects (eg. class instances) don't get reported as being built-in objects (obj instanceof Function) || (obj instanceof Boolean) || (obj instanceof Symbol) || // Error objects (obj instanceof Error) || // (obj instanceof AggregateError) || // No TypeScript definition for this [in TS 4.1.2] (obj instanceof EvalError) || // (obj instanceof InternalError) || // No TypeScript definition for this [in TS 4.1.2] (obj instanceof RangeError) || (obj instanceof ReferenceError) || (obj instanceof SyntaxError) || (obj instanceof TypeError) || (obj instanceof URIError) || // Numbers and dates (obj instanceof Number) || (obj instanceof BigInt) || (obj instanceof Date) || // Text processing (obj instanceof String) || (obj instanceof RegExp) || // Indexed collections (obj instanceof Array) || (obj instanceof Int8Array) || (obj instanceof Uint8Array) || (obj instanceof Uint8ClampedArray) || (obj instanceof Int16Array) || (obj instanceof Uint16Array) || (obj instanceof Int32Array) || (obj instanceof Uint32Array) || (obj instanceof Float32Array) || (obj instanceof Float64Array) || (obj instanceof BigInt64Array) || (obj instanceof BigUint64Array) || // Keyed collections (obj instanceof Map) || (obj instanceof Set) || (obj instanceof WeakMap) || (obj instanceof WeakSet) || // Structured data (obj instanceof ArrayBuffer) || (obj instanceof SharedArrayBuffer) || (obj instanceof DataView) || // Control abstraction objects (obj instanceof Promise) || // Internationalization (obj instanceof Intl.Collator) || (obj instanceof Intl.DateTimeFormat) || (obj instanceof Intl.NumberFormat) || (obj instanceof Intl.PluralRules) || // WebAssembly (obj instanceof WebAssembly.Module) || (obj instanceof WebAssembly.Instance) || (obj instanceof WebAssembly.Memory) || (obj instanceof WebAssembly.Table) || (obj instanceof WebAssembly.CompileError) || (obj instanceof WebAssembly.LinkError) || (obj instanceof WebAssembly.RuntimeError); return (isBuiltInObject); } /** * Returns the type of the supplied object (eg. "string", "number[]", "{ count: number }", "Set").\ * TODO: This method needs more testing. */ static getRuntimeType(obj: any): string { let result: string = ""; /** [Local function] If needed, recursively walks the object (or array) 'obj' of the property named 'key'. */ function buildType(obj: Utils.SimpleObject, key: string, isLastProperty: boolean): void { let nativeType: string = Type.getNativeType(obj); if (obj && (nativeType === "object")) { const lastPropertyName: string = Object.keys(obj)[Object.keys(obj).length - 1]; result += `${key ? `${key}: ` : ""}{ `; for (const k in obj) { // JSON.stringify() doesn't serialize prototype-inherited properties, so we can skip those [see: https://stackoverflow.com/questions/8779249/how-to-stringify-inherited-objects-to-json] if (Object.prototype.hasOwnProperty.call(obj, k)) // Using Object.prototype because obj.hasOwnProperty() can be redefined (shadowed) { const isLastProperty: boolean = (k === lastPropertyName); buildType(obj[k], k, isLastProperty); } } result += isLastProperty ? "} " : "}, "; } else { // Special handling for arrays. // Arrays usually have their type specified (eg. "let myArr: string[] = [];" or "let myArr: Array<string> = [];"), but may not (eg. "let myArr = []"). // There are 3 choices for how to handle determining an array's type: // 1) Don't even try and simply return the type as "any[]" for all arrays. // While simple and fast, it won't allow us to catch any kind of array type mistmatch. // 2) Examine all the elements and if they are all of the same type, return "<type>[]", otherwise return "any[]". // Better accuracy than 1, but won't catch a non-homogenous array being passed when a homogeneous array is expected (when comparing types). // However, if a non-homogenous array IS expected, then this approach will work. // 3) Examine all the elements and if they are all of the same type, return "<type>[]", otherwise return "_mixed[]"". // Better accuracy than 1, and will catch a non-homogenous array being passed when a homogeneous array is expected (when comparing types). // However, if a non-homogenous array IS expected (ie. "any[]"), then this approach will fail. // // We chose approach #2 because this is the approach that works best with a code-gen'd ConsumerInterface.g.ts, which always specifies types (including "any[]"). // So if we're receiving a non-homogeneous array, this is because it's expected (ie. it's an "any[]" in the ConsumerInterface.g.ts). // But approach #2 (unlike approach #1) still allows us to detect homogenous array type mistmatches, like the case of an accidental change to // ConsumerInterface.g.ts (eg. a number[] being unintentionally changed to a string[]), or the case of not using ConsumerInterface.g.ts at all. // // Note: For simplicity, we don't try to determine the type of Set or Map objects. While Typescript will allow un-typed Sets and Maps (eg. "let mySet = new Set()'"), // it's more typical - because they represent collections - that the types will be provided via generic-type specifiers (eg. "let mySet: Map<number, string>;"). // Because of this, we fully rely on ConsumerInterface.g.ts and the compile-time checks to prevent passing invalid types is Set and Map collections. if (Array.isArray(obj)) { // Are all the array elements (items) the same type? let firstNonNullElementType: string = ""; let allElementsHaveTheSameType: boolean = true; if (obj.length > 0) { for (const element of obj) { if (!firstNonNullElementType) { if (element !== null) { firstNonNullElementType = Type.getRuntimeType(element); } } else { if (element !== null) { const elementType: string = Type.getRuntimeType(element); if (Type.compareTypes(firstNonNullElementType, elementType) !== null) { allElementsHaveTheSameType = false; break; } } } } nativeType = allElementsHaveTheSameType ? `${firstNonNullElementType}[]` : "any[]"; } else { nativeType = "any[]"; } } // Special handling for null and undefined if ((obj === null) || (obj === undefined)) { nativeType = "any"; } result += `${key ? `${key}: ` : ""}${nativeType}${isLastProperty ? " " : ", "}`; } } buildType(obj, "", true); return (result.trim()); } } /** * [Internal] Validates that the specified name (of a parameter or object property) is a valid identifier, returning true if it is or throwing if it's not. * The 'nameDescription' describes where 'name' is used (eg. "parameter 'p1' of method 'foo'") so that it can be included in the exception * message (if thrown).\ * Note: A null name (eg. for a function return type) will return true. */ export function checkName(name: string | null, nameDescription: string, optionalAllowed: boolean = true, restPrefixAllowed: boolean = false): boolean { const regex: RegExp = optionalAllowed ? /^[A-Za-z_][A-Za-z0-9_]*[\?]?$/ : /^[A-Za-z_][A-Za-z0-9_]*$/; if (name && (!regex.test(restPrefixAllowed ? Method.trimRest(name) : name) || (Type.getSupportedNativeTypes().indexOf(name) !== -1))) { let optionalNotAllowed: string = (name.endsWith("?") && !optionalAllowed) ? "; the optional indicator ('?') is not allowed in this context" : ""; throw new Error(`The ${nameDescription} has an invalid name ('${name}')${optionalNotAllowed}`); } return (true); } /** The context in which a type is being checked. */ enum TypeCheckContext { /** The type is being checked while creating a published type. */ Type, /** The type is being checked while creating a published method. */ Method } /** * TypeScript built-in "utility" types that create a new type by transforming an existing type (which is supplied as a generic-type specifier).\ * See https://www.typescriptlang.org/docs/handbook/utility-types.html. \ * Note: Technically, "ReadonlyArray" is not a utility type, but since it behaves like one we include it in the list. */ const _tsUtilityTypes: ReadonlyArray<string> = ["Partial", "Required", "Readonly", "ReadonlyArray", "Record", "Pick", "Omit", "Exclude", "Extract", "NonNullable", "Parameters", "ConstructorParameters", "ReturnType", "InstanceType", "OmitThisParameter", "ThisType", "Uppercase", "Lowercase", "Capitalize", "Uncapitalize"]; /** * Validates if the supplied 'runtimeValue' has a valid type (ie. is supported and serializable). Throws if it's an invalid type.\ * Typically, this is used to validate parameters passed to LB APIs that can be 'any'. */ export function checkRuntimeType(runtimeValue: any, name: string): void { try { Utils.suppressLoggingOf(/^Warning:/); // 'null' and 'undefined' become 'any' in getRuntimeType(), which checkType() will then log a warning about (which we don't want in this context) checkType(TypeCheckContext.Type, Type.getRuntimeType(runtimeValue), name, `runtime type of '${name}'`, false); } finally { Utils.suppressLoggingOf(); // Clear the suppression } } /** * Validates the specified type (eg. "string[]") returning true if the type is valid, or throwing if it's invalid. * @param type Either a property type, parameter type, a return type, or a published type definition. This is case-sensitive. * @param name Either a property name, parameter name, null (for a return type), or a published type name. This is case-sensitive. * @param typeDescription Describes where 'type' is used (eg. "return type of method 'foo'") so that it can be included in the exception message (if thrown). * @param optionalAllowed Whether 'name' can have the optional suffix ("?"). Defaults to true. * @param restPrefixAllowed Whether 'name' can have the rest-parameters prefix ("..."). Defaults to false. */ function checkType(context: TypeCheckContext, type: string, name: string | null, typeDescription: string, optionalAllowed: boolean = true, restPrefixAllowed: boolean = false): boolean { type = type.replace(/([ ]+)(?=[\[\]])/g, "").trim(); // Remove all space before (or between) array suffix characters ([]) // Look for a bad parameter (or object property) name, like "some-Name[]" checkName(name, typeDescription, optionalAllowed, restPrefixAllowed); if (type.length > 0) { // Since TS utility types are not meaningful without their generic-type specifier (which we always remove), we cannot support them if (type.indexOf("<") > 0) { for (const tsUtilityType of _tsUtilityTypes) { if (type.startsWith(`${tsUtilityType}<`)) { throw new Error(`The ${typeDescription} uses a TypeScript utility type ('${tsUtilityType}'); utility types are not supported`) } } } // For type-checking purposes we remove all TS generic specifiers, eg. "Map<number, string>" becomes "Map"; generics [currently] aren't part of native JS. // But since the generic specifier(s) will still be used in TS wrappers, we need to check that the generic types are valid too; this also checks that the // generic types are serializable. for (const genericsSpecifier of Type.getGenericsSpecifiers(type)) { for (const genericType of Type.parseGenericsSpecifier(genericsSpecifier)) { checkType(context, genericType, name, `generic-type specifier in ${typeDescription}`, optionalAllowed, restPrefixAllowed); } } type = Type.removeGenericsSpecifiers(type); // Check against the built-in [or published] types, and arrays of built-in [or published] types if (type[0] !== "{") // A named type, not a complex/compound type { // Note: Even though "any" is not a native JavaScript type, we (like TypeScript) use it as the "no specific type" type let validTypeNames: string[] = Type.getSupportedNativeTypes(false).concat(Object.keys(_publishedTypes)).concat(["any"]); let lcType: string = type.toLowerCase(); for (let i = 0; i < validTypeNames.length; i++) { if ((type === validTypeNames[i]) || type.startsWith(validTypeNames[i] + "[]")) // We want to include arrays of arrays, eg. string[][] { if (type.startsWith("any") || type.startsWith("object")) // Include any[] and object[] { Utils.log(`Warning: The ${typeDescription} uses type '${type}' which is too general to determine if it can be safely serialized; it is strongly recommended to use a more specific type`); } // We allow null and undefined, but only when being used in a union type (eg. "string | null") // [Note that "string & null" is 'never', so we don't support null (or undefined) with intersection types] if (((type === "null") || (type === "undefined")) && (typeDescription.indexOf("union") === -1)) // TODO: Checking typeDescription is brittle { throw new Error(`The ${typeDescription} has a type ('${type}') that's not supported in this context`); } // "null[]" and "undefined[]" are nonsensical types if (type.startsWith("null[") || type.startsWith("undefined[")) { throw new Error(`The ${typeDescription} has an unsupported type ('${type}')`); } return (true); // Success } // Check for mismatched casing [Note: We disallow published type names that differ only by case] if (Utils.equalIgnoringCase(type, validTypeNames[i]) || lcType.startsWith(validTypeNames[i].toLowerCase() + "[]")) { let brackets: string = type.replace(/[^\[\]]+/g, ""); throw new Error(`The ${typeDescription} has an invalid type ('${type}'); did you mean '${validTypeNames[i] + brackets}'?`); } } // We do this to get a better error message; without it the error message asks the user to publish the missing type, which is invalid for a native (or TS built-in) type. for (const unsupportedTypeName of Type.getUnsupportedNativeTypes()) { if (type === unsupportedTypeName) { throw new Error(`The ${typeDescription} has an unsupported type ('${type}')`); } } // We support template string types (technically TemplateLiteralType) on a "best effort" basis, since the syntax can be arbitrarily complex. // Our goal is to cover the common/basic use case for these types (ie. with unions of string literals). // Note: Template string types will end up with an expanded definition of "string" (for simplicity). if (type.indexOf("`") === 0) // Eg. "`Hello ${number}`" { const templateStringRegEx: RegExp = /(?<=\${)[^/}]+(?=})/g;// Find all the "type" in "${type}" templates let result: RegExpExecArray | null; let templateNumber: number = 1; while (result = templateStringRegEx.exec(type)) // Because regex use /g, exec() does a stateful search, returning only the next match with each call { const templateType: string = result[0]; // Note: Since we're always going to use "string" as the expandedType, the only reason to check the individual template types is to catch // errors when NOT doing code-gen from source [the TypeScript compiler will have already done the checking in that case], ie. when // publishing "manually" using hand-written publishType() calls. checkType(context, templateType, name, `replacement template #${templateNumber++} of ${typeDescription}`, optionalAllowed, restPrefixAllowed); } return (true); } // A string literal is valid (eg. as can appear in a union) if (/^"[^"]*"$/.test(type) || /^'[^']*'$/.test(type)) { return (true); } // We support union and intersection types on a "best effort" basis, since the syntax can be arbitrarily complex. Our goal is to cover all the common/basic use cases for these types. // Note: Union and intersection types will end up with an expanded definition of "any", which is done to opt them out of runtime type checking (for simplicity). But we still want to // check each type used in the the union/intersection so that we can verify they are serializable. if ((type.indexOf("|") !== -1) || (type.indexOf("&") !== -1)) // Eg. "string | (number | boolean)[]" or "Foo & (Bar | Baz)[]" { const result: { kindFound: CompoundTypeKind, components: string[] } = Type.getCompoundTypeComponents(type); if (result.components.length > 0) { const kindName: string = CompoundTypeKind[result.kindFound].toLowerCase(); result.components.map((t, i) => checkType(context, t, name, `${kindName}-type component #${i + 1} of ${typeDescription}`, optionalAllowed, restPrefixAllowed)); return (true); } } // Check for unsupported types (which are unsupported either for simplicity of our code, or because it's not practical/feasible to support it) if (type.indexOf("[") === 0) // Eg. "[string, number]" { // Note: The developer can downcast a tuple to an any[] to pass it to an Ambrosia method throw new Error(`The ${typeDescription} has an invalid type ('${type}'); tuple types are not supported`); } if (type.indexOf("(") === 0) // Eg. "(p1: string) => number" { throw new Error(`The ${typeDescription} has an invalid type ('${type}'); function types are not supported`); } // Conditional types are almost always used with generics, whose use will have been caught by AST.publishTypeAlias() and AST.publishFunction(). // But there are still valid non-generic (if nonsensical) conditional types that will slip by those checks, and this check will still apply // if publishing "manually" using hand-written publishType() calls. if (type.indexOf(" extends ") !== -1) // Eg. "string extends undefined? never : string" (this is a valid, but nonsensical, example) { throw new Error(`The ${typeDescription} has an invalid type ('${type}'); conditional types are not supported`); } // The type is either an incorrectly spelled native type, or is a yet-to-be published custom type. // We'll assume the latter, since this allows forward references to be used when publishing types. let missingTypeName: string = type.replace(/\[]/g, ""); // Remove all square brackets (eg. "Name[]" => "Name") // Since we're expecting the type to be a name, we check that it is indeed a valid name. This is to catch "unexpected" TypeScript syntax that's other than // Tuple/Function type syntax, since we only check for these 2 cases above - but other cases exist (including in future versions of TypeScript). try { checkName(missingTypeName, typeDescription, false); } catch { throw new Error(`The ${typeDescription} has an unsupported definition (${type})`); } if (context === TypeCheckContext.Type) { if (!_missingTypes.has(missingTypeName)) { _missingTypes.set(missingTypeName, typeDescription); } } // We don't allow forward references for a method parameter/return type, because we don't do any "deferred checking" for methods as we do for types [see updateUnexpandedPublishedTypes()] if (context === TypeCheckContext.Method) { throw new Error(`The ${typeDescription} references an unpublished type ('${type}')`); } return (true); } // Check a complex/compound type (eg. "{ names: { firstName: string, lastName: string }, startDate: number, jobs: { title: string, durationInSeconds: bigint[] }[] }") if (type[0] === "{") { let obj: object; let json: string = type.replace(/[\s]/g, "").replace(/[\"]/g, "'"); // Remove all spaces and replace all double-quotes with single-quotes (the type may include string literals) // Check if the type definition is using JSON-style array notation ("[{}]"), which is not allowed as the definition must use TypeScript-style array notation ("{}[]") if (/{\s*\[/g.test(type) || /}\s*]/g.test(type)) { throw new Error(`The ${typeDescription} has an invalid type ('${type}'); the type uses JSON-style array notation ("[{}]") when it should be using TypeScript-style ("{}[]")`); } if (json === "{}") { throw new Error(`The ${typeDescription} has an invalid type ('${type}'); the type is empty`); } // For the purpose of validation ONLY, convert the type from TypeScript-style array notation "{}[]" to JSON-style "[{}]" json = convertToJsonArrayNotation(json); // Note: Using multiple, simple steps here makes this easier to understand/debug (at the possible expense of some performance) json = json.replace(/{/g, "{\"").replace(/}/g, "\"}").replace(/:/g, "\":\"").replace(/,/g, "\",\""); // Add quotes around all keys and values json = json.replace(/\"{/g, "{").replace(/}\"/g, "}").replace(/\"\[/g, "[").replace(/]\"/g, "]"); // Remove quotes unintentionally added by previous step json = json.replace(/\[](?=[^\[])/g, "[]\""); // Add quotes unintentionally removed by previous step try { // We pass the [complex] type through JSON parsing to validate its structure (ie. that its a valid tree that we can walk) obj = JSON.parse(json); } catch (error: unknown) { // Note: We remove the "at position N" message because the position applies to the temporary JSON we created, not to the supplied 'type', so it would be misleading throw new Error(`Unable to parse the type of ${typeDescription} (reason: ${Utils.makeError(error).message.replace(/ at position \d+/, "").replace(/ in JSON/, "") }); ` + `check for missing/misplaced '{', '}', '[', ']', ':' or ',' characters in type`); } /** [Local function] Recursively walks to all leaf nodes and calls checkType() for each. */ function findBadLeafType(obj: Utils.SimpleObject, key: string): void { if ((typeof obj === "object") && (Object.keys(obj).length > 0)) { // We're at a non-leaf node for (const k in obj) { // JSON.stringify() doesn't serialize prototype-inherited properties, so we can skip those [see: https://stackoverflow.com/questions/8779249/how-to-stringify-inherited-objects-to-json] if (Object.prototype.hasOwnProperty.call(obj, k)) // Using Object.prototype because obj.hasOwnProperty() can be redefined (shadowed) { findBadLeafType(obj[k], k); } } } else { // We're at a leaf node const leafPropertyName: string = key; const leafTypeName: string = obj.toString(); // Note: While valid in TypeScript, we don't allow optional object property names (ie. names ending with '?') [see Type.compareComplexTypes()] checkType(context, leafTypeName, leafPropertyName, `${typeDescription} [property '${leafPropertyName}']`, false); } } findBadLeafType(obj, ""); return (true); // Success } } throw new Error(`The ${typeDescription} has an invalid type ('${type}'); check the syntax or casing or, if this is a custom type, check that it has been published`); /** [Local function] Converts the type from TypeScript-style "{}[]" to JSON-style "[{}]". */ function convertToJsonArrayNotation(type: string): string { if (type.indexOf(" ") !== -1) { // Remove whitespace from "{} [ ] []" type = type.replace(/}\s+\[/g, "}[").replace(/]\s+\[/g, "][").replace(/\[\s+\]/g, "[]"); } let convertedType: string = type; let startPos: number = 0; let regex: RegExp = /}]*\[]/; // DON'T use /g (we want regex to NOT be stateful). Note: As we progress, {}[][][] will become {}][][] then {}]][] then finally {}]]] // Eg. "{ names: { firstName: string, lastName: string }, startDate: number, jobs: { title: { full: string, abbreviation: string}, durationInSeconds: bigint[] }[] }" while (true) { let result: RegExpExecArray | null = regex.exec(convertedType); if (result === null) { break; } startPos = result.index; let match: string = result[0]; // Eg: "}]][]" let replacement: string = match.substr(0, match.length - 2) + "]"; // Eg: "}]]]" // Backtrack to find the matching opening '{' let insertionPos: number = 0; let depth: number = 0; for (let i = startPos; i >= 0; i--) { if (convertedType[i] === '}') depth++; if (convertedType[i] === '{') depth--; if (depth === 0) { insertionPos = i; break; } } convertedType = convertedType.replace(match, replacement); // Note: This ONLY replaces the first occurrance of 'match' convertedType = convertedType.substring(0, insertionPos) + "[" + convertedType.substring(insertionPos, convertedType.length); } return (convertedType); } } /** * Publishes a 'post' method so that it's available to be called by a consumer; used by code-gen and by the built-in Meta.getPublishedMethods_Post() method.\ * Note that this only publishes the method signature, not the implementation.\ * If you use code-gen (ie. emitTypeScriptFileFromSource()) there is no need to explicitly call this method because it will be called for you.\ * Returns the published method. * * Each parameter in 'parameters' must be of the form "name[?]:type", where 'type' can either be * simple (eg. number, string[]) or complex (eg. { name: { firstName: string, lastName: string }, age: number }) or a published type (eg. Employee).\ * Note: Any optional parameters must be specified (in 'parameters') after all non-optional parameters.\ * Note: The 'methodName' is case-sensitive. * @param codeGenOptions [Internal] For internal use only. */ export function publishPostMethod(methodName: string, methodVersion: number, parameters: string[], returnType: string, doRuntimeTypeChecking: boolean = true, codeGenOptions?: CodeGenOptions): Method { checkForMissingPublishedTypes(); methodName = methodName.trim(); if (methodName.startsWith("_")) { // We reserve use of a leading underscore for internal 'post' methods (like "_echo") to prevents name collisions with user-defined 'post' method names throw new Error(`A published 'post' method name ('${methodName}') cannot begin with an underscore character`); } if (!_publishedMethods[methodName]) { _publishedMethods[methodName] = {}; } if (!_publishedMethods[methodName][methodVersion]) { const method: Method = new Method(IC.POST_METHOD_ID, methodName, methodVersion, parameters, returnType, doRuntimeTypeChecking, codeGenOptions); _publishedMethods[methodName][methodVersion] = method; return (method); } else { throw new Error(`Published 'post' method '${methodName}' (version ${methodVersion}) already exists`); } } /** * Publishes a [non-post] method so that it's available to be called by a consumer; used by code-gen and by the built-in Meta.getPublishedMethods_Post() method. * Note that this only publishes the method signature, not the implementation.\ * If you use code-gen (ie. emitTypeScriptFileFromSource()) there is no need to explicitly call this method because it will be called for you.\ * Returns the published method. * * Each parameter in 'parameters' must be of the form "name[?]:type", where 'type' can either be * simple (eg. number, string[]) or complex (eg. { name: { firstName: string, lastName: string }, age: number }) or a published type (eg. Employee).\ * If the method uses binary serialized parameters (not JSON serialized parameters) then specify a single "rawParams:Uint8Array" parameter.\ * Note: Any optional parameters must be specified (in 'parameters') after all non-optional parameters.\ * Note: The 'methodName' is case-sensitive. * @param codeGenOptions [Internal] For internal use only. */ export function publishMethod(methodID: number, methodName: string, parameters: string[], codeGenOptions?: CodeGenOptions): Method { checkForMissingPublishedTypes(); methodName = methodName.trim(); // Negative methodID's are reserved for built-in methods if (methodID < 0) { throw new Error(`Method ID ${methodID} is invalid`); } for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { let method: Method = _publishedMethods[name][version]; if ((method.id === methodID) && (method.name !== methodName)) { throw new Error(`Method ID ${methodID} is already in use (by method '${method.name}')`); } if ((method.name === methodName) && (method.id !== methodID)) { throw new Error(`Method name '${methodName}' is invalid (reason: ${method.isPost ? "Post" : "Another"} method ${method.isPost ? `'${method.name}'` : `(ID ${method.id})`} is already using the name)`); } } } if (!_publishedMethods[methodName]) { _publishedMethods[methodName] = {}; } // Note: By design, non-post methods do not support versioning (so their version will always be 1). // This is done in order to retain compatibility with C# Fork/Impulse methods (whose RPC message format doesn't include a version). let methodVersion: number = 1; if (!_publishedMethods[methodName][methodVersion]) { const method: Method = new Method(methodID, methodName, methodVersion, parameters, "void", false, codeGenOptions); _publishedMethods[methodName][methodVersion] = method; return (method); } else { throw new Error(`Published method '${methodName}' already exists`); } } /** Throws if the _missingTypes list not empty, since this indicates that a custom type was referenced but not defined (published). */ function checkForMissingPublishedTypes(): void { if (_missingTypes.size > 0) { const missingTypesList: string = [..._missingTypes].map(kvp => `'${kvp[0]}' found in ${kvp[1]}`).join(", ") throw new Error(`The following types must be published before any method can be published: ${missingTypesList}`); } } /** * Updates the 'expandedDefinition' property of all published types that need it, and returns the number of types updated. * Throws if _missingTypes is not empty. */ function updateUnexpandedPublishedTypes(): number { let updateCount: number = 0; if (_missingTypes.size === 0) { // There are no missing types, so we can now safely update the expandedDefinition of all types that could not be expanded during publishing (because of forward references). // The only "expected" reason for expansion to fail is a circular reference. for (const typeName in _publishedTypes) { const type: Type = _publishedTypes[typeName]; if (!type.expandedDefinition) { const expandedDefinition: string = Type.expandType(type.definition); if (expandedDefinition) { type.expandedDefinition = expandedDefinition; updateCount++; } else { throw new Error(`Unable to expand the definition for type '${type.name}'`); } } } } else { throw new Error(`Unable to expand type definitions (reason: There are are still ${_missingTypes.size} missing types ('${[..._missingTypes.keys()].join("', '")}'))`); } return (updateCount); } /** * Unpublishes a method so that it's no longer be available to be called by a consumer, or used by code-gen. * Returns true only if the method was unpublished.\ * **Caution**: If 'methodVersion' is not supplied, all versions will be unpublished. */ export function unpublishMethod(methodName: string, methodVersion?: number): boolean { methodName = methodName.trim(); if (_publishedMethods[methodName]) { if (methodVersion === undefined) { // Remove ALL versions delete _publishedMethods[methodName]; return (true); } else { if (_publishedMethods[methodName][methodVersion]) { // Remove specific version delete _publishedMethods[methodName][methodVersion]; if (Object.keys(_publishedMethods[methodName]).length === 0) { delete _publishedMethods[methodName]; } return (true); } } } return (false); } /** Logs a warning that the expanded definition for the specified type has been simplified to "any". */ function reportTypeSimplificationWarning(typeDescription: string, typeDefinition: string): void { const isCompoundType: boolean = (Type.getCompoundTypeComponents(typeDefinition).components.length > 0); const fix: string = !isCompoundType ? "; the strongly recommended fix is to publish all in-line compound types (unions and intersections)" : ""; Utils.log(`Warning: The expanded definition for ${typeDescription} was simplified to "any", which will bypass runtime type checking${fix}`); } /** * Publishes a [typically] complex type (used as either a method parameter or a return value) so that it can be referenced by * published methods (see publishMethod and publishPostMethod) or other published types. Returns the published type. * * Forward references are allowed, but if not eventually published they will cause both publishMethod() and publishPostMethod() to fail.\ * Publishing a type is similar to declaring a type alias in TypeScript (but without support for optional members or union/tuple/function types). * However, during code generation [emitTypeScriptFile[FromSource]()] it will be converted to a class to a) allow concise constructor syntax * to be used [in generated consumer-side code], and b) to allow independent augmentation with methods (for appropriate encapsulation). * But a published type itself does not have any methods: it is only a data structure.\ * Published types can be queried using the built-in Meta.getPublishedTypes_Post() method. * @param typeName The [case-sensitive] name of the type (eg. "Employee"). * @param typeDefinition The type definition, eg. "{ name: string, age: number }" or "string[&nbsp;][&nbsp;]". * @param enumType [Optional] An actual enum type, eg. RPCType (and whose name will typically match the supplied 'typeName'). * When used, specify the 'typeDefinition' as "number". Specifying a string value for 'enumType' is for internal use only. * @param codeGenOptions [Internal] For internal use only. */ export function publishType(typeName: string, typeDefinition: string, enumType?: Utils.EnumType | string, codeGenOptions?: CodeGenOptions): Type { // Prevent publishing types that differ only by case, eg. "Employee" and "employee" (even though this is // valid in TypeScript). We do this so that checkType() can detect a mis-cased type name in the same way // for both native types and published types (ie. case-only name differences are invalid for both) which // lets it more accurately detect a forward reference (ie. a reference to a not-yet-published type). for (const name in _publishedTypes) { if (Utils.equalIgnoringCase(typeName, name)) { throw new Error(`Published type '${name}' already exists${(typeName !== name) ? "; published type names cannot differ only by case" : ""}`); } } if (!_publishedTypes[typeName]) { if (enumType && (typeDefinition !== "number")) { throw new Error("It is invalid to specify an 'enumType' when the 'typeDefinition' is not 'number'"); } let enumValues: string | null = null; if (enumType) { if (typeof enumType === "string") // Only used by AST.publishEnum() { // Eg. "0=First,1=Second,2=Third" if (!RegExp(/^(-?[0-9]+=[A-Za-z][A-Za-z0-9_]*,?)+$/g).test(enumType)) { throw new Error(`The specified 'enumType' ("${enumType}") is invalid`); } enumValues = enumType; } else { enumValues = Utils.getEnumValues(typeName, enumType); } } const newType: Type = new Type(typeName, typeDefinition, enumValues, codeGenOptions); _publishedTypes[typeName] = newType; if ((newType.definition !== "any") && (newType.expandedDefinition === "any")) { reportTypeSimplificationWarning(`type '${newType.name}'`, newType.definition); } // If needed, take the type off the "missing" list if (_missingTypes.has(typeName)) { _missingTypes.delete(typeName); if (_missingTypes.size === 0) { try { // Although we don't know if this was the "last" publishType() call, we do know that we can now fix // up any 'expandedDefinition' properties that couldn't be set previously due to forward references const updatedTypeCount: number = updateUnexpandedPublishedTypes(); Utils.log(`Expanded ${updatedTypeCount} type(s)`); } catch (error: unknown) { throw new Error(`Deferred expansion of type(s) failed (reason: ${Utils.makeError(error).message})`); } } } } return (_publishedTypes[typeName]); } /** * Result: An XML document (as unformatted text) describing the methods available on the specified instance * Handle the result in your PostResultDispatcher() for method name '_getPublishedMethods'. * Returns a unique callID for the method. */ export function getPublishedMethods_Post(destinationInstance: string, expandTypes: boolean = false, includePostMethodsOnly: boolean = false, callContextData: any = null): number { let callID: number = IC.postFork(destinationInstance, "_getPublishedMethods", 1, 8000, callContextData, IC.arg("expandTypes", expandTypes), IC.arg("includePostMethodsOnly", includePostMethodsOnly)); return (callID); } /** An Impulse wrapper for getPublishedMethods_Post(). Returns void, unlike getPublishedMethods_Post(). */ export function getPublishedMethods_PostByImpulse(destinationInstance: string, expandTypes: boolean = false, includePostMethodsOnly: boolean = false, callContextData: any = null): void { IC.postByImpulse(destinationInstance, "_getPublishedMethods", 1, 8000, callContextData, IC.arg("expandTypes", expandTypes), IC.arg("includePostMethodsOnly", includePostMethodsOnly)); } /** * Result: An XML document (as unformatted text) describing the types available on the specified instance. * Handle the result in your PostResultDispatcher() for method name '_getPublishedTypes'. * Returns a unique callID for the method. */ export function getPublishedTypes_Post(destinationInstance: string, expandTypes: boolean = false, callContextData: any = null): number { const callID: number = IC.postFork(destinationInstance, "_getPublishedTypes", 1, 8000, callContextData, IC.arg("expandTypes", expandTypes)); return (callID); } /** An Impulse wrapper for getPublishedTypes_Post(). Returns void, unlike getPublishedTypes_Post(). */ export function getPublishedTypes_PostByImpulse(destinationInstance: string, expandTypes: boolean = false, callContextData: any = null): void { IC.postByImpulse(destinationInstance, "_getPublishedTypes", 1, 8000, callContextData, IC.arg("expandTypes", expandTypes)); } /** * Result: true if the specified method/version has been published (ie. is available) on the specified instance. * Handle the result in your PostResultDispatcher() for method name '_isPublishedMethod'. * Returns a unique callID for the method. */ export function isPublishedMethod_Post(destinationInstance: string, methodName: string, methodVersion: number = 1, callContextData: any = null): number { const callID: number = IC.postFork(destinationInstance, "_isPublishedMethod", 1, 8000, callContextData, IC.arg("methodName", methodName), IC.arg("methodVersion", methodVersion)); return (callID); } /** An Impulse wrapper for isPublishedMethod_PostByImpulse(). Returns void, unlike isPublishedMethod_Post(). */ export function isPublishedMethod_PostByImpulse(destinationInstance: string, methodName: string, methodVersion: number = 1, callContextData: any = null): void { IC.postFork(destinationInstance, "_isPublishedMethod", 1, 8000, callContextData, IC.arg("methodName", methodName), IC.arg("methodVersion", methodVersion)); } /** [Internal] Returns XML text describing all published methods (on the local instance). */ export function getPublishedMethodsXml(expandTypes: boolean = false, includePostMethodsOnly: boolean = false): string { let methodListXml: string = ""; for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { let method: Method = _publishedMethods[name][version]; if (includePostMethodsOnly && !method.isPost) { continue; } methodListXml += method.getXml(expandTypes); } } return (methodListXml); } /** [Internal] Returns XML text describing all published types (on the local instance). */ export function getPublishedTypesXml(expandTypes: boolean = false): string { let typeListXml: string = ""; for (const typeName in _publishedTypes) { let type: Type = _publishedTypes[typeName]; typeListXml += `<Type name="${typeName}" definition="${expandTypes ? type.expandedDefinition : type.definition}"${type.enumValues ? ` EnumValues="${type.enumValues}"` : ""}/>`; } return (typeListXml); } /** [Internal] Returns the published Type with the specified typeName (if it exists), or null (if it doesn't). */ export function getPublishedType(typeName: string): Type | null { return (_publishedTypes[typeName] ?? null); } /** [Internal] Returns the published Method with the specified name and version (if it exists), or null (if it doesn't). */ export function getPublishedMethod(methodName: string, methodVersion: number = 1): Method | null { if (_publishedMethods[methodName] && _publishedMethods[methodName][methodVersion]) { return (_publishedMethods[methodName][methodVersion]); } return (null); } /** [Internal] Returns true if the specified method name is published. */ export function isPublishedMethod(methodName: string): boolean { return (_publishedMethods[methodName] !== undefined); } /** The prefix for replaceable tokens in PublisherFramework.template.ts. */ const CODEGEN_TEMPLATE_TOKEN_PREFIX: string = "// [TOKEN:"; /** The name of the JSDoc tag used to identify which entities to [attempt to] publish in the input source file. */ const CODEGEN_TAG_NAME: string = "@ambrosia"; /** The prefix for a generated comment related to the code-gen process. */ const CODEGEN_COMMENT_PREFIX: string = "Code-gen"; /** Flags for the kind of code file to generate. Can be combined. */ export enum GeneratedFileKind { /** * Generates the code file for the consumer-side interface (method wrappers).\ * The publisher can (if desired) also include this file to make self-calls. */ Consumer = 1, /** Generates the code file for the publisher-side (Ambrosia framework). */ Publisher = 2, /** Generates the code files for both the consumer-side interface (method wrappers) and publisher-side (Ambrosia framework). */ All = Consumer | Publisher } /** When doing code generation, a TypeScript file can either be an Input file (provided by the developer) or a Generated file (created by Ambrosia). */ enum CodeGenerationFileType { Input, Generated } /** The type of [git] file merge that can be performed on a code file generated by emitTypeScriptFile[FromSource](). If git is not installed, only FileMergeType.None is valid. */ export enum FileMergeType { /** The generated file will always be overwritten, with no merge taking place. Any edits you have made will be lost. If git is not installed, this is the only valid choice. */ None, /** The generated file will be automatically merged. You will still need to check the diff for merge correctness. */ Auto, /** The generated file will be annotated with merge conflict markers. You will need to manually resolve each merge conflict. */ Annotate } /** * The sections of TypeScript code that can be generated by emitPublisherTypeScriptFile().\ * Except 'None', these MUST match the token names used in PublisherFramework.template.ts. */ export enum CodeGenSection { None = 0, Header = 1, AppState = 2, PostMethodHandlers = 4, NonPostMethodHandlers = 8, PublishTypes = 16, PublishMethods = 32, /** Note: This section is only generated when **not** publishing from a source file. */ MethodImplementations = 64, // Note: For all the 'xxxEventHandler' sections, the 'xxx' comes from Messages.AppEventType. See also: _appEventHandlerFunctions. ICStartingEventHandler = 4096, ICStartedEventHandler = 8192, ICStoppedEventHandler = 16384, ICReadyForSelfCallRpcEventHandler = 32768, RecoveryCompleteEventHandler = 65536, UpgradeStateEventHandler = 131072, UpgradeCodeEventHandler = 262144, IncomingCheckpointStreamSizeEventHandler = 524288, FirstStartEventHandler = 1048576, BecomingPrimaryEventHandler = 2097152, CheckpointLoadedEventHandler = 4194304, CheckpointSavedEventHandler = 8388608, UpgradeCompleteEventHandler = 16777216, ICConnectedEventHandler = 33554432 } /** Class of details (both known and discovered) about an AppEvent handler function (in an input source file). */ class AppEventHandlerFunctionDetails { expectedParameters: string = ""; expectedReturnType: string = "void"; foundInInputSource: boolean = false; // Set at runtime nsPath: string | null = null; // Set at runtime location: string | null = null; // Set at runtime constructor(expectedParameters: string = "", expectedReturnType: string = "void") { this.expectedParameters = expectedParameters; this.expectedReturnType = expectedReturnType; } /** Resets the properties set ("discovered") at runtime. */ reset(): void { this.foundInInputSource = false; this.nsPath = null; this.location = null; } } /** The "well known" Ambrosia AppEvent handler function names (eg. 'onFirstStart'), and the details about them (both known and discovered). */ // Note: This effectively provides an analog for the 'OnFirstStart()' and 'BecomingPrimary()' overridable methods in the 'abstract class Immortal' in C#. const _appEventHandlerFunctions: { [functionName: string]: AppEventHandlerFunctionDetails } = {}; Object.keys(Messages.AppEventType).forEach(enumValue => { if (isNaN(parseInt(enumValue))) { _appEventHandlerFunctions["on" + enumValue] = new AppEventHandlerFunctionDetails(); } }); _appEventHandlerFunctions["on" + Messages.AppEventType[Messages.AppEventType.ICStopped]].expectedParameters = "exitCode: number"; _appEventHandlerFunctions["on" + Messages.AppEventType[Messages.AppEventType.UpgradeState]].expectedParameters = "upgradeMode: Messages.AppUpgradeMode"; _appEventHandlerFunctions["on" + Messages.AppEventType[Messages.AppEventType.UpgradeCode]].expectedParameters = "upgradeMode: Messages.AppUpgradeMode"; _appEventHandlerFunctions["on" + Messages.AppEventType[Messages.AppEventType.CheckpointLoaded]].expectedParameters = "checkpointSizeInBytes: number"; /** * Class that defines options which affect how source files are generated (emitted). * - apiName is required. This is the generic name of the Ambrosia app/service, not an instance name. * - fileKind defaults to GeneratedFileKind.All. * - mergeType defaults to MergeType.Annotate. * - checkGeneratedTS defaults to true. * - ignoreTSErrorsInSourceFile defaults to false. * - generatedFilePrefix defaults "". * - generatedFileName defaults to "ConsumerInterface" for GeneratedFileKind.Consumer and "PublisherFramework" for GeneratedFileKind.Publisher. * If supplied, generatedFileName should not include an extension (if it does it will be ignored: the extension is always ".g.ts") but it can include a path. * - outputPath defaults to the current folder. * - tabIndent defaults to 4. * - emitGeneratedTime defaults to true. * - allowImplicitTypes defaults to true. * - publisherName defaults to the git user name (if using git), or null otherwise. * - publisherEmail defaults to the git user email (if using git), or null otherwise. */ export class FileGenOptions { // Indexer (for 'noImplicitAny' compliance), although this does end up hiding ts(2551): "Property 'xxxxx' does not exist on type 'FileGenOptions'" [key: string]: unknown; /** * [Required] The name of the API (an Ambrosia app/service) that files are being generated for. * This is a generic name, and does **not** refer to a specific registered instance of the app/service (other than by coincidence). */ apiName: string = ""; /** The kind of file(s) to generate. Defaults to GeneratedFileKind.All. */ fileKind?: GeneratedFileKind = GeneratedFileKind.All; /** How to handle [git] merging any changes (made to a previously generated file) back into the newly generated file. Defaults to FileMergeType.Annotate. */ // Note: We default 'mergeType' to 'Annotate' for 2 reasons: // 1) It gives us a way to prevent merging again before conflicts have been resolved (repeatedly auto-merging can lead to lots of cruft in the code). // 2) Because the merge is non-optimal (because it uses an empty file as the common ancestor) it's better to have the merge conflicts explicitly annotated. mergeType?: FileMergeType = FileMergeType.Annotate; /** Whether the generated file(s) should be checked for errors. Defaults to true. */ checkGeneratedTS?: boolean = true; /** Whether the source [input] file - if supplied - should be checked for errors. Defaults to false. */ ignoreTSErrorsInSourceFile?: boolean = false; /** * Whether to enable the 'strict' TypeScript compiler flag (and 'noImplicitReturns'). Defaults to true.\ * See https://www.typescriptlang.org/tsconfig#strict. */ strictCompilerChecks?: boolean = true; /** * A prefix that will be applied to the standard generated file names (PublisherFramework.g.ts and ConsumerInterface.g.ts). * To completely change the generated file name, use 'generatedFileName'. Defaults to "". */ generatedFilePrefix?: string = ""; /** An override name for the generated file. Can include a path, but not an extension. Overrides 'generatedFilePrefix' if provided. Defaults to "". */ generatedFileName?: string = ""; /** The folder where generated files will be written (if a path is specified in 'generatedFileName' it will overwrite this setting). Defaults to the current folder. */ outputPath?: string = process.cwd(); /** The number of spaces in a logical tab. Used to format the generated source code. Defaults to 4. */ tabIndent?: number = 4; /** Whether to write a timestamp in the generated file for its creation date/time. Defaults to true. */ emitGeneratedTime?: boolean = true; /** * Whether to allow a published method/type that does not explicitly declare all parameter/property/return types * (by default, missing parameter/property types are assumed to be 'any' and missing return types are assumed to be 'void').\ * If set to false, a missing parameter/property/return type will result in an error.\ * Defaults to true. */ allowImplicitTypes?: boolean = true; /** * [Internal] Whether to stop code generation if an error is encountered.\ * This setting is for **internal testing only**.\ * If you set it to false, the generated file(s) **will be unusable**.\ * Defaults to true. */ // Note: The primary purpose of this flag is so that we can run ALL the tests in NegativeTests.ts at once haltOnError?: boolean = true; /** * [Experimental] The set of sections (or'd together) to **not** generate publisher code for. Defaults to 'None'. * Setting this can help reduce merge conflicts in some instances, but it can also introduce code errors in the generated code. */ publisherSectionsToSkip?: CodeGenSection = CodeGenSection.None; /** The name of the publisher of the Ambrosia instance (eg. "Microsoft"). Defaults to the git user name (if using git), or "" otherwise. */ publisherName?: string = ""; /** The email address of the publisher of the Ambrosia instance. Defaults to the git user email (if using git), or "" otherwise. */ publisherEmail?: string = ""; /** * The publisher contact information, as constructed from the supplied 'publisherName' and 'publisherEmail' (in the format "name [email]", "name", or "email").\ * Alternatively, any contact information can be provided (eg. URL, phone number) which will override the constructed value.\ * Set to null to omit contact information (not recommended). */ publisherContactInfo?: string | null = ""; constructor(partialOptions: FileGenOptions) { for (let optionName in partialOptions) { if (this[optionName] !== undefined) { const value: any = partialOptions[optionName]; // Prevent [accidental] clearing of the default value if (value === undefined) { continue; } this[optionName] = value; if (optionName === "outputPath") { if (!File.existsSync(value)) { throw new Error(`The specified FileGenOptions.outputPath ('${value}') does not exist`); } this.outputPath = Path.resolve(value); } } else { throw new Error(`'${optionName}' is not a valid FileGenOptions setting`); } } if (this.generatedFileName && Path.parse(this.generatedFileName).dir) // Note: the 'dir' property is empty when Path.dirname() returns '.' { this.outputPath = Path.resolve(Path.dirname(this.generatedFileName)); } if (this.generatedFilePrefix && !/^[A-Za-z0-9-_\.]+$/.test(this.generatedFilePrefix)) { throw new Error(`The specified FileGenOptions.generatedFilePrefix ('${this.generatedFilePrefix}') contains one or more invalid characters`); } // If needed, read git config settings. // Note: The user should set 'publisherContactInfo' (or 'publisherName' AND 'publisherEmail') to suppress the git lookup (eg. if they are using another source control system). if ((this.publisherContactInfo === "") && ((this.publisherName === "") || (this.publisherEmail === ""))) { const publisherProperties: string[] = ["Name", "Email"]; publisherProperties.forEach(prop => { const propName: string = "publisher" + prop; if (this[propName] === "") { try { // Note: In launch.json, set '"autoAttachChildProcesses": false' to prevent the VS Code debugger from attaching to this process // Note: This operation takes about 150ms this[propName] = ChildProcess.execSync(`git config user.${prop.toLowerCase()}`, { encoding: "utf8", windowsHide: true }).trim(); } catch (error: unknown) { const errorMsg: string = Utils.makeError(error).message.replace(/\s+/g, " ").trim().replace(/\.$/, ""); Utils.log(`Warning: Unable to read user.${prop.toLowerCase()} from git config (reason: ${errorMsg}); FileGenOptions.${propName} (or FileGenOptions.publisherContactInfo) must be set explicitly`); } } }); } if (this.publisherContactInfo === null) // The "omit contact info" case { this.publisherContactInfo = ""; } else { if (this.publisherContactInfo === "") // The "not explicitly set" case { this.publisherContactInfo = (this.publisherName && this.publisherEmail) ? `${this.publisherName} [${this.publisherEmail}]` : (this.publisherName || this.publisherEmail || ""); } } } } /** * **Note:** It is recommended that emitTypeScriptFileFromSource() is used instead of this method, because it avoids the need to explicitly call * any publishX() methods (publishType, publishMethod, or publishPostMethod). * * Generates consumer-side (method wrappers) and/or publisher-side (Ambrosia framework) TypeScript files (*.g.ts) from the currently * published types and methods. Returns the number of files successfully generated. */ export function emitTypeScriptFile(fileOptions: FileGenOptions): number { return (emitTypeScriptFileEx(null, fileOptions)); } /** * Generates consumer-side (method wrappers) and/or publisher-side (Ambrosia framework) TypeScript files (*.g.ts) * from the annotated functions, static methods, type-aliases and enums in the specified TypeScript source file ('sourceFileName').\ * Returns the number of files successfully generated. * * The types and methods in the supplied TypeScript file that need to be published must be annotated with a special JSDoc tag: @ambrosia. * - Example for a type or enum:\ * &#64;ambrosia publish=true * - Example for a function that implements a post method:\ * &#64;ambrosia publish=true, [version=1], [doRuntimeTypeChecking=true] * - Example for a function that implements a non-post method:\ * &#64;ambrosia publish=true, methodID=123 * * The only required attribute is 'publish'. * * Automatically publishing types and methods from an [annotated] TypeScript source file provides 3 major benefits over hand-crafting * publishType(), publishPostMethod(), and publishMethod() calls then calling emitTypeScriptFile(): * 1) The developer gets design-time support from the TypeScript compiler and the IDE (eg. VSCode). * 2) The types and methods can be "verified correct" before doing code-gen, speeding up the edit/compile/run cycle. * 3) The majority of the developer-provided code no longer resides in the generated PublisherFramework.g.ts, so less time is spent resolving merges conflicts. */ export function emitTypeScriptFileFromSource(sourceFileName: string, fileOptions: FileGenOptions): number { if (!sourceFileName || !sourceFileName.trim()) { throw new Error("The 'sourceFileName' parameter cannot be null or empty"); } return (emitTypeScriptFileEx(sourceFileName, fileOptions)); } function emitTypeScriptFileEx(sourceFileName: string | null = null, fileOptions: FileGenOptions): number { fileOptions = new FileGenOptions(fileOptions); // To force assignment of default values for non-supplied properties let expectedFileCount: number = (fileOptions.fileKind !== GeneratedFileKind.All) ? 1 : 2; let generatedFileCount: number = 0; let totalErrorCount: number = 0; let totalMergConflictCount: number = 0; try { if (Root.initializationMode() !== Root.LBInitMode.CodeGen) { throw new Error(`Code generation requires Ambrosia to be initialized with the 'CodeGen' LBInitMode, not the '${Root.LBInitMode[Root.initializationMode()]}' mode`); } if (fileOptions.fileKind === GeneratedFileKind.All) { Utils.log(`Generating TypeScript files for Consumer and Publisher...`); } else { Utils.log(`Generating ${GeneratedFileKind[assertDefined(fileOptions.fileKind)]} TypeScript file...`); } if (sourceFileName) { if (AST.publishedSourceFile()) { // Handle the case where emitTypeScriptFileFromSource() is being called more than once [typically this is so that a FileGenOptions.generatedFileName can be supplied]. // In this case, the second call should not try to publish again since that would fail with duplicate type/methods errors. // Further, if a different source file is being specified we must prevent this since the generated consumer/producer files need to be based on the same set of published types/methods. let originalSourceFile: string = Path.resolve(AST.publishedSourceFile()); if (Utils.equalIgnoringCase(Path.resolve(sourceFileName), originalSourceFile)) { Utils.log(`Skipping publish step: Entities have already been published from ${originalSourceFile}`); } else { throw new Error(`The 'sourceFileName' (${Path.resolve(sourceFileName)}) cannot be different from the previously used file (${originalSourceFile})`); } } else { AST.publishFromAST(sourceFileName, fileOptions); } if (AST.publishedEntityCount() === 0) { // publishedEntityCount can be 0 because there are no @ambrosia tags, all the @ambrosia 'publish' attributes are 'false', or because none of the tagged entities are exported throw new Error(`The input source file (${Path.basename(sourceFileName)}) does not publish any entities (exported functions, static methods, type aliases and enums annotated with an ${CODEGEN_TAG_NAME} JSDoc tag)`); } } // This will only happen if no methods have been published because publish[Post]Method() also catches this condition if (_missingTypes.size > 0) { const missingTypesList: string = [..._missingTypes].map(kvp => `'${kvp[0]}' found in ${kvp[1]}`).join(", ") throw new Error(`The following types are referenced by other types, but have not been published: ${missingTypesList}`); } if (fileOptions.generatedFileName && (fileOptions.fileKind === GeneratedFileKind.All)) { throw new Error("When a FileGenOptions.generatedFileName is specified the FileGenOptions.fileKind cannot be GeneratedFileKind.All; instead, call emitTypeScriptFile() or emitTypeScriptFileFromSource() for each required GeneratedFileKind using a different FileGenOptions.generatedFileName in each call"); } function incrementTotals(result: SourceFileProblemCheckResult | null): void { if (result !== null) { totalErrorCount += result.errorCount; totalMergConflictCount += result.mergeConflictCount; generatedFileCount++; } } if ((assertDefined(fileOptions.fileKind) & GeneratedFileKind.Consumer) === GeneratedFileKind.Consumer) { let result: SourceFileProblemCheckResult | null = emitConsumerTypeScriptFile(fileOptions.generatedFileName || (fileOptions.generatedFilePrefix + "ConsumerInterface"), fileOptions, sourceFileName || undefined); incrementTotals(result); } if ((assertDefined(fileOptions.fileKind) & GeneratedFileKind.Publisher) === GeneratedFileKind.Publisher) { let result: SourceFileProblemCheckResult | null = emitPublisherTypeScriptFile(fileOptions.generatedFileName || (fileOptions.generatedFilePrefix + "PublisherFramework"), fileOptions, sourceFileName || undefined); incrementTotals(result); } } catch (error: unknown) { const err: Error = Utils.makeError(error); Utils.log(`Error: ${err.message} [origin: ${Utils.getErrorOrigin(err) ?? "N/A"}]`); } let success: boolean = (expectedFileCount === generatedFileCount) && (totalErrorCount === 0); let prefix: string = (fileOptions.fileKind === GeneratedFileKind.All) ? "Code" : (GeneratedFileKind[assertDefined(fileOptions.fileKind)] + " code"); let outcomeMessage: string = `${prefix} file generation ${success ? "SUCCEEDED" : "FAILED"}: ${generatedFileCount} of ${expectedFileCount} files generated`; if (generatedFileCount > 0) { outcomeMessage += fileOptions.checkGeneratedTS ? `; ${totalErrorCount} TypeScript errors, ${totalMergConflictCount} merge conflicts` : `; File${expectedFileCount > 1 ? "s" : ""} not checked for TypeScript errors`; } Utils.log(outcomeMessage); return (generatedFileCount); } /** * Generates a TypeScript file (called PublisherFramework.g.ts by default) for all published types and methods. * The purpose of this file is to be included by the publishing immortal as the message dispatch framework.\ * The 'fileName' should not include an extension (if it does it will be ignored) but it may include a path.\ * Returns a SourceFileProblemCheckResult for the generated file, or null if no file was generated. */ function emitPublisherTypeScriptFile(fileName: string, fileOptions: FileGenOptions, sourceFileName?: string): SourceFileProblemCheckResult | null { const NL: string = Utils.NEW_LINE; // Just for short-hand // Note: When 'sourceFileName' is supplied, code generation behaves slightly differently: // 1) In the Header section it creates a 'import * as PTM from "${sourceFileName}"; // PTM = "Published Types and Methods"'. // 2) In the PostMethodHandlers and NonPostMethodHandlers sections it uses "PTM." as the method/type "namespace" qualifier. // 3) The MethodImplementations section is left empty (because the implementations are in the supplied input source file). try { let templateFileName: string = "PublisherFramework.template.ts"; let pathedTemplateFile: string = getPathedTemplateFile(templateFileName); let pathedOutputFile: string = Path.join(assertDefined(fileOptions.outputPath), `${Path.basename(fileName).replace(Path.extname(fileName), "")}.g.ts`); let template: string = removeDevOnlyTemplateCommentLines(File.readFileSync(pathedTemplateFile, { encoding: "utf8" })); let content: string = template; checkForFileNameConflicts(pathedOutputFile, sourceFileName); checkForGitMergeMarkers(pathedOutputFile); // If the user defined their app-state in the input file, then we'll skip adding CodeGenSection.AppState and instead reference their state variable if (sourceFileName && AST.appStateVar() !== "") { // Update the checkpointProducer() and checkpointConsumer() in the template [since they reference _appState] to reference the user-provided app-state variable from the input file content = content.replace(/State\._appState/g, SOURCE_MODULE_ALIAS + "." + AST.appStateVar()); // Also update the "State.AppState" references in checkpointConsumer() content = content.replace(/State\.AppState/g, SOURCE_MODULE_ALIAS + "." + AST.appStateVarClassName()); } content = replaceTemplateToken(content, CodeGenSection.Header, fileOptions, "", sourceFileName); content = replaceTemplateToken(content, CodeGenSection.AppState, fileOptions, "", sourceFileName); content = replaceTemplateToken(content, CodeGenSection.PostMethodHandlers, fileOptions, `// ${CODEGEN_COMMENT_PREFIX}: Post method handlers will go here` + NL, sourceFileName); content = replaceTemplateToken(content, CodeGenSection.NonPostMethodHandlers, fileOptions, `// ${CODEGEN_COMMENT_PREFIX}: Fork/Impulse method handlers will go here` + NL, sourceFileName); content = replaceTemplateToken(content, CodeGenSection.PublishTypes, fileOptions, `// ${CODEGEN_COMMENT_PREFIX}: Published types will go here`); content = replaceTemplateToken(content, CodeGenSection.PublishMethods, fileOptions, `// ${CODEGEN_COMMENT_PREFIX}: Published methods will go here`); content = replaceTemplateToken(content, CodeGenSection.MethodImplementations, fileOptions, sourceFileName ? "" : (NL + `// ${CODEGEN_COMMENT_PREFIX}: Method implementation stubs will go here`), sourceFileName); // Wire-up (or simply add "TODO" comments for) AppEvent handlers for (let enumValue in CodeGenSection) { if (RegExp(/.*EventHandler$/g).test(enumValue)) { const eventHandlerSection: CodeGenSection = CodeGenSection[enumValue as keyof typeof CodeGenSection]; content = replaceTemplateToken(content, eventHandlerSection, fileOptions, makeEventHandlerComment(eventHandlerSection), sourceFileName); } } // Check that all tokens got replaced if (content.indexOf(CODEGEN_TEMPLATE_TOKEN_PREFIX) !== -1) { const regExp: RegExp = new RegExp(Utils.regexEscape(CODEGEN_TEMPLATE_TOKEN_PREFIX) + "Name=\\w+", "g"); const matches: RegExpMatchArray | null = content.match(regExp); if (matches && (matches.length > 0)) { let tokenNameList: string[] = [...matches].map(item => item.split("=")[1]); throw new Error(`The following template token(s) [in ${pathedTemplateFile}] were not handled: ${tokenNameList.join(", ")}`); } else { // Safety net in case our RegExp didn't work [so that we don't emit a bad file] throw new Error(`Not all template token(s) [in ${pathedTemplateFile}] were handled`); } } writeGeneratedFile(content, pathedOutputFile, assertDefined(fileOptions.mergeType)); Utils.log(`Code file generated: ${pathedOutputFile}${!fileOptions.checkGeneratedTS ? " (TypeScript checks skipped)" : ""}`); return (fileOptions.checkGeneratedTS ? checkGeneratedFile(pathedOutputFile, (fileOptions.mergeType !== FileMergeType.None)) : new SourceFileProblemCheckResult()); } catch (error: unknown) { Utils.log(`Error: emitPublisherTypeScriptFile() failed (reason: ${Utils.makeError(error).message})`); return (null); } /** [Local function] Returns a 'call to action' comment for creating the specified app-event handler. */ function makeEventHandlerComment(section: CodeGenSection): string { let codeGenComment: string = "// TODO: Add your [non-async] handler here"; if (sourceFileName) { const fnName: string = "on" + CodeGenSection[section].replace("EventHandler", ""); const fnDetails: AppEventHandlerFunctionDetails = _appEventHandlerFunctions[fnName]; const signature: string = `${fnName}(${fnDetails.expectedParameters}): ${fnDetails.expectedReturnType}`; codeGenComment = `// TODO: Add an exported [non-async] function '${signature}' to ${makeRelativePath(assertDefined(fileOptions.outputPath), sourceFileName)}, then (after the next code-gen) a call to it will be generated here`; if ((section === CodeGenSection.UpgradeStateEventHandler) || (section === CodeGenSection.UpgradeCodeEventHandler)) { // Needed because this handler takes a Messages.AppUpgradeMode parameter codeGenComment += NL + `// Note: You will need to import Ambrosia to ${sourceFileName} in order to reference the 'Messages' namespace.`; if (section === CodeGenSection.UpgradeStateEventHandler) { codeGenComment += NL + `// Upgrading is performed by calling _appState.upgrade(), for example:`; codeGenComment += NL + `// _appState = _appState.upgrade<AppStateVNext>(AppStateVNext);`; } if (section === CodeGenSection.UpgradeCodeEventHandler) { codeGenComment += NL + `// Upgrading is performed by calling IC.upgrade(), passing the new handlers from the "upgraded" PublisherFramework.g.ts,`; codeGenComment += NL + `// which should be part of your app (alongside your original PublisherFramework.g.ts).`; } } } return (codeGenComment); } } /** * Returns the relative path to the specified [pathed] file from the specified starting path. * For example, if 'fromPath' is "./src" and 'toPathedFile' is "./test/PI.ts", the method returns "../test/PI.ts". */ function makeRelativePath(fromPath: string, toPathedFile: string): string { let relativeSourceFileName: string = Path.relative(fromPath, toPathedFile); relativeSourceFileName = (relativeSourceFileName.startsWith("..") ? "" : "./") + relativeSourceFileName.replace(/\\/g, "/"); return (relativeSourceFileName); } /** * Generates a TypeScript file (called ConsumerInterface.g.ts by default) for all published types and methods. * The purpose of this file is to be included by another [Ambrosia Node] immortal so that it can call methods on this immortal. * The 'fileName' should not include an extension (if it does it will be ignored) but it may include a path. * Returns a SourceFileProblemCheckResult for the generated file, or null if no file was generated. */ function emitConsumerTypeScriptFile(fileName: string, fileOptions: FileGenOptions, sourceFileName?: string): SourceFileProblemCheckResult | null { try { const NL: string = Utils.NEW_LINE; // Just for short-hand const tab: string = " ".repeat(assertDefined(fileOptions.tabIndent)); let pathedOutputFile: string = Path.join(assertDefined(fileOptions.outputPath), `${Path.basename(fileName).replace(Path.extname(fileName), "")}.g.ts`); let content: string = ""; let namespaces: string[] = []; let namespaceComments: { [namespace: string]: string | undefined } = {}; // Effectively a rebuilt AST._namespaceJSDocComments but just for the namespaces that contain published entities let previousNsPath: string = ""; checkForFileNameConflicts(pathedOutputFile, sourceFileName); checkForGitMergeMarkers(pathedOutputFile); // Note: We emit the types and methods using their original namespaces. If we didn't they'd all get emitted at the root level in the file (ie. no namespace) so we'd // lose the original organizational structure of the code (which imparts the logical grouping/meaning of members). However, using namespaces is not required to prevent // name collisions [in Ambrosia] because published types and methods must ALWAYS have unique names, even if defined in different TS namespaces. // 1) Populate the 'namespaces' list if (Object.keys(_publishedTypes).length > 0) { for (const typeName in _publishedTypes) { let type: Type = _publishedTypes[typeName]; if (type.codeGenOptions?.nsPath && (namespaces.indexOf(type.codeGenOptions.nsPath) === -1)) { addNamespaces(type.codeGenOptions.nsPath); namespaceComments[type.codeGenOptions.nsPath] = type.codeGenOptions.nsComment; } } } if (Object.keys(_publishedMethods).length > 0) { for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { let method: Method = _publishedMethods[name][version]; if (method.codeGenOptions?.nsPath && (namespaces.indexOf(method.codeGenOptions.nsPath) === -1)) { addNamespaces(method.codeGenOptions.nsPath); namespaceComments[method.codeGenOptions.nsPath] = method.codeGenOptions.nsComment; } } } } // 2) Emit types and methods if (namespaces.length === 0) // The empty namespace (ie. no namespace) { // Emit types and methods at the root of the file emitTypesAndMethods(0); content = content.trimRight(); } else { // Emit types and methods in their originating namespaces namespaces.push(""); // We manually add the empty namespace (ie. no namespace) to emit entities which have no nsPath namespaces = namespaces.sort(); // Eg. A, A.B, A.B.C, A.D, B, B.D, B.D.E, ... for (const nsPath of namespaces) { const nsNestDepth: number = nsPath.split(".").length - 1; const nsIndent: string = tab.repeat(nsNestDepth); const nsName: string = nsPath ? nsPath.split(".")[nsNestDepth] : ""; const nsComment: string = namespaceComments[nsPath] ? AST.formatJSDocComment(assertDefined(namespaceComments[nsPath]), nsIndent.length) : ""; const previousNsNestDepth: number = previousNsPath.split(".").length - 1; if (nsNestDepth > previousNsNestDepth) { // Start new nested namespace if (nsComment) { content += nsComment + NL; } content += `${nsIndent}export namespace ${nsName}` + NL; content += `${nsIndent}{` + NL; } else { if (previousNsPath) { // Emit closing braces (from the previous namespace depth back to the current depth) content = content.trimRight() + NL; for (let depth = previousNsNestDepth; depth >= nsNestDepth; depth--) { content += tab.repeat(depth) + "}" + NL; } content = content.trimRight() + NL.repeat(2); } if (nsPath) { if (nsComment) { content += nsComment + NL; } content += `${nsIndent}export namespace ${nsName}` + NL; content += `${nsIndent}{` + NL; } } emitTypesAndMethods(nsPath ? assertDefined(fileOptions.tabIndent) * (nsNestDepth + 1) : 0, nsPath); previousNsPath = nsPath; } // Emit closing braces (back to the root) content = content.trimRight() + NL; for (let depth = previousNsPath.split(".").length - 1; depth >= 0; depth--) { content += tab.repeat(depth) + "}" + (depth !== 0 ? NL : ""); } } // 3) If there are published post methods, write a PostResultDispatcher(). // This is just a minimal outline with "TODO" placeholders where the developer should add their own code. // Further, if the app includes multiple ConsumerInterface.g.ts files (because it uses more than one type of Ambrosia app/service), then the // developer will need to unify the [potentially] multiple PostResultDispatcher's into a single dispatcher which can be passed to IC.start(). if (publishedPostMethodsExist()) { let postResultDispatcher: string = ""; postResultDispatcher += "/**" + NL; postResultDispatcher += " * Handler for the results of previously called post methods (in Ambrosia, only 'post' methods return values). See Messages.PostResultDispatcher.\\" + NL; postResultDispatcher += " * Must return true only if the result (or error) was handled." + NL + " */" + NL; postResultDispatcher += "export function postResultDispatcher(senderInstanceName: string, methodName: string, methodVersion: number, callID: number, callContextData: any, result: any, errorMsg: string): boolean" + NL; postResultDispatcher += "{" + NL; postResultDispatcher += tab + "const sender: string = IC.isSelf(senderInstanceName) ? \"local\" : `'${senderInstanceName}'`;" + NL; postResultDispatcher += tab + "let handled: boolean = true;" + NL.repeat(2); // We do this to help catch the case where the developer forgets to create a "unified" PostResultDispatcher [ie. that can // handle post results for ALL used ConsumerInterface.g.ts files] so they end up accidentally re-using a PostResultDispatcher // that's specific to just one type of Ambrosia app/service (and one destination [or set of destinations]) postResultDispatcher += tab + "if (_knownDestinations.indexOf(senderInstanceName) === -1)" + NL; postResultDispatcher += tab + "{" + NL; postResultDispatcher += tab + tab + `return (false); // Not handled: this post result is from a different instance than the destination instance currently (or previously) targeted by the '${fileOptions.apiName}' API` + NL; postResultDispatcher += tab + "}" + NL.repeat(2); postResultDispatcher += tab + "if (errorMsg)" + NL; postResultDispatcher += tab + "{" + NL; postResultDispatcher += tab + tab + "switch (methodName)" + NL; postResultDispatcher += tab + tab + "{" + NL; for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { const method: Method = _publishedMethods[name][version]; if (method.isPost) { postResultDispatcher += tab.repeat(3) + `case \"${method.nameForTSWrapper}\":` + NL; } } } postResultDispatcher += tab.repeat(4) + "Utils.log(`Error: ${errorMsg}`);" + NL; postResultDispatcher += tab.repeat(4) + "break;" + NL; postResultDispatcher += tab.repeat(3) + "default:" + NL; postResultDispatcher += tab.repeat(4) + "handled = false;" + NL; postResultDispatcher += tab.repeat(4) + "break;" + NL; postResultDispatcher += tab + tab + "}" + NL; postResultDispatcher += tab + "}" + NL; postResultDispatcher += tab + "else" + NL; postResultDispatcher += tab + "{" + NL; postResultDispatcher += tab + tab + "switch (methodName)" + NL; postResultDispatcher += tab + tab + "{" + NL; for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { const method: Method = _publishedMethods[name][version]; if (method.isPost) { let nsPathOfReturnType: string = getPublishedType(Type.removeArraySuffix(method.returnType))?.codeGenOptions?.nsPath || ""; if (nsPathOfReturnType) { nsPathOfReturnType += "."; } postResultDispatcher += tab.repeat(3) + `case \"${method.nameForTSWrapper}\":` + NL; if (method.returnType === "void") { postResultDispatcher += tab.repeat(4) + `// TODO: Handle the method completion (it returns void), optionally using the callContextData passed in the call` + NL; } else { postResultDispatcher += tab.repeat(4) + `const ${method.nameForTSWrapper}_Result: ${nsPathOfReturnType}${method.returnType} = result;` + NL; postResultDispatcher += tab.repeat(4) + `// TODO: Handle the result, optionally using the callContextData passed in the call` + NL; } postResultDispatcher += tab.repeat(4) + "Utils.log(`Post method '${methodName}' from ${sender} IC succeeded`);" + NL; postResultDispatcher += tab.repeat(4) + "break;" + NL; } } } postResultDispatcher += tab.repeat(3) + "default:" + NL; postResultDispatcher += tab.repeat(4) + "handled = false;" + NL; postResultDispatcher += tab.repeat(4) + "break;" + NL; postResultDispatcher += tab + tab + "}" + NL; postResultDispatcher += tab + "}" + NL; postResultDispatcher += tab + "return (handled);" + NL; postResultDispatcher += "}"; content += NL.repeat(2) + postResultDispatcher; } /** [Local function] Returns true if any published method is a post method. */ function publishedPostMethodsExist(): boolean { for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { const method: Method = _publishedMethods[name][version]; if (method.isPost) { return (true); } } } return (false); } /** [Local function] Adds all the sub-paths for a given namespace path. */ function addNamespaces(nsPath: string): void { let nsSubPath: string = ""; for (let namespace of nsPath.split(".")) { nsSubPath += ((nsSubPath.length > 0) ? "." : "") + namespace; if (namespaces.indexOf(nsSubPath) === -1) { namespaces.push(nsSubPath); } } } /** [Local function] Adds published Types (as classes, type-definitions, or enum definitions) and published Methods (as function wrappers) to the 'content'. */ function emitTypesAndMethods(startingIndent: number, nsPath: string = ""): void { const pad: string = " ".repeat(startingIndent); if (Object.keys(_publishedTypes).length > 0) { for (const typeName in _publishedTypes) { let type: Type = _publishedTypes[typeName]; if (type.codeGenOptions?.nsPath === nsPath) { content += type.makeTSType(startingIndent, fileOptions.tabIndent, type.codeGenOptions?.jsDocComment) + NL.repeat(2); } } } if (Object.keys(_publishedMethods).length > 0) { for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { let method: Method = _publishedMethods[name][version]; if (method.codeGenOptions?.nsPath === nsPath) { content += method.makeTSWrappers(startingIndent, fileOptions, method.codeGenOptions?.jsDocComment) + NL.repeat(2); } } } } } if (content.length > 0) { let header: string = getHeaderCommentLines(GeneratedFileKind.Consumer, fileOptions).join(NL) + NL; header += "import Ambrosia = require(\"ambrosia-node\");" + NL; header += "import IC = Ambrosia.IC;" + NL; header += "import Utils = Ambrosia.Utils;" + NL.repeat(2); header += `const _knownDestinations: string[] = []; // All previously used destination instances (the '${fileOptions.apiName}' Ambrosia app/service can be running on multiple instances, potentially simultaneously); used by the postResultDispatcher (if any)` + NL; header += "let _destinationInstanceName: string = \"\"; // The current destination instance" + NL; header += "let _postTimeoutInMs: number = 8000; // -1 = Infinite" + NL.repeat(2); header += "/** " + NL; header += " * Sets the destination instance name that the API targets.\\" + NL; header += ` * Must be called at least once (with the name of a registered Ambrosia instance that implements the '${fileOptions.apiName}' API) before any other method in the API is used.` + NL; header += " */" + NL; header += "export function setDestinationInstance(instanceName: string): void" + NL; header += "{" + NL; header += `${tab}_destinationInstanceName = instanceName.trim();` + NL; header += `${tab}if (_destinationInstanceName && (_knownDestinations.indexOf(_destinationInstanceName) === -1))` + NL; header += `${tab}{` + NL; header += `${tab+tab}_knownDestinations.push(_destinationInstanceName);` + NL; header += `${tab}}` + NL; header += "}" + NL.repeat(2); header += "/** Returns the destination instance name that the API currently targets. */" + NL; header += "export function getDestinationInstance(): string" + NL; header += "{" + NL; header += `${tab}return (_destinationInstanceName);` + NL; header += "}" + NL.repeat(2); header += "/** Throws if _destinationInstanceName has not been set. */" + NL; header += "function checkDestinationSet(): void" + NL; header += "{" + NL; header += `${tab}if (!_destinationInstanceName)` + NL; header += `${tab}{` + NL; header += `${tab+tab}throw new Error("setDestinationInstance() must be called to specify the target destination before the '${fileOptions.apiName}' API can be used.");` + NL; header += `${tab}}` + NL; header += "}" + NL.repeat(2); header += "/**" + NL; header += " * Sets the post method timeout interval (in milliseconds), which is how long to wait for a post result from the destination instance before raising an error.\\" + NL; header += " * All post methods will use this timeout value. Specify -1 for no timeout. " + NL; header += " */" + NL; header += "export function setPostTimeoutInMs(timeoutInMs: number): void" + NL; header += "{" + NL; header += `${tab}_postTimeoutInMs = Math.max(-1, timeoutInMs);` + NL; header += "}" + NL.repeat(2); header += "/**" + NL; header += " * Returns the post method timeout interval (in milliseconds), which is how long to wait for a post result from the destination instance before raising an error.\\" + NL; header += " * A value of -1 means there is no timeout." + NL; header += " */" + NL; header += "export function getPostTimeoutInMs(): number" + NL; header += "{" + NL; header += `${tab}return (_postTimeoutInMs);` + NL; header += "}" + NL.repeat(2); content = header + content; writeGeneratedFile(content, pathedOutputFile, assertDefined(fileOptions.mergeType)); Utils.log(`Code file generated: ${pathedOutputFile}${!fileOptions.checkGeneratedTS ? " (TypeScript checks skipped)" : ""}`); return (fileOptions.checkGeneratedTS ? checkGeneratedFile(pathedOutputFile, (fileOptions.mergeType !== FileMergeType.None)) : new SourceFileProblemCheckResult()); } else { throw new Error(sourceFileName ? `The input source file (${Path.basename(sourceFileName)}) does not publish any entities (exported functions, static methods, type aliases and enums annotated with an ${CODEGEN_TAG_NAME} JSDoc tag)` : "No entities have been published; call publishType() / publishMethod() / publishPostMethod() then retry"); } } catch (error: unknown) { Utils.log(`Error: emitConsumerTypeScriptFile() failed (reason: ${Utils.makeError(error).message})`); return (null); } } /** * Writes the specified content to the specified pathedOutputFile, merging [using git] any existing changes in * pathedOutputFile back into the newly generated file (according to mergeType). Throws if the merge fails. * Returns the number of merge conflicts if 'mergeType' is FileMergeType.Annotate, or 0 otherwise. */ function writeGeneratedFile(content: string, pathedOutputFile: string, mergeType: FileMergeType): number { let conflictCount: number = 0; let outputPath: string = Path.dirname(pathedOutputFile); if ((mergeType === FileMergeType.None) || !File.existsSync(pathedOutputFile)) { File.writeFileSync(pathedOutputFile, content); // This will overwrite the file if it already exists } else { // See https://stackoverflow.com/questions/9122948/run-git-merge-algorithm-on-two-individual-files const pathedEmptyFile: string = Path.join(outputPath, "__empty.g.ts"); // This is a temporary file [but we don't want the name to collide with a real file] const pathedRenamedOutputFile: string = Path.join(outputPath, "__" + Path.basename(pathedOutputFile) + ".original"); // This is a temporary file [but we don't want the name to collide with a real file] try { // The output file already exists [possibly modified by the user], so merge the user's changes into new generated file // using "git merge-file --union .\PublisherFramework.g.ts .\__empty.g.ts .\__PublisherFramework.g.ts.original". This will result in // PublisherFramework.g.ts containing BOTH the new [generated] changes and the existing [user] changes (from .\__PublisherFramework.g.ts.original). // Note: To just insert the merge markers that the developer will need to resolve manually, omit "--union" from "git merge-file" // (ie. set mergeType to MergeType.Annotate). Utils.log(`${FileMergeType[mergeType]}-merging existing ${pathedOutputFile} into generated version...`); File.writeFileSync(pathedEmptyFile, ""); // The "common base" file File.renameSync(pathedOutputFile, pathedRenamedOutputFile); // Save the original version (which may contain user edits); Will overwrite pathedRenamedOutputFile if it already exists File.writeFileSync(pathedOutputFile, content); // This will overwrite the file // Note: In launch.json, set '"autoAttachChildProcesses": false' to prevent the VS Code debugger from attaching to this process // Note: See https://docs.npmjs.com/misc/config let mergeOutput: string = ChildProcess.execSync(`git merge-file ${(mergeType === FileMergeType.Auto) ? "--union " : ""}-L Generated -L Base -L Original ${pathedOutputFile} ${pathedEmptyFile} ${pathedRenamedOutputFile}`, { encoding: "utf8", windowsHide: true, stdio: ["ignore"] }).trim(); if (mergeOutput) { throw (mergeOutput); } } catch (error: unknown) { // Note: 'error' will be an Error object with some additional properties (output, pid, signal, status, stderr, stdout) const err: Error = Utils.makeError(error); // The 'git merge-file' exit code is negative on error, or the number of conflicts otherwise (truncated // to 127 if there are more than that many conflicts); if the merge was clean, the exit value is 0 const gitExitCode: number = (err as any).status; // TODO: Hack to make compiler happy if (gitExitCode >= 0) // 0 = clean merge, >0 = conflict count (typically this will only happen for a non-automatic merge, ie. if "--union" is omitted from "git merge-file") { conflictCount = gitExitCode; } else { // An error occurred, so restore the original version File.renameSync(pathedRenamedOutputFile, pathedOutputFile); const errorMsg: string = err.message.replace(/\s+/g, " ").trim().replace(/\.$/, ""); throw new Error(`Merge failed (reason: ${errorMsg} [exit code: ${gitExitCode}])`); } } finally { // Remove temporary files Utils.deleteFile(pathedEmptyFile); Utils.deleteFile(pathedRenamedOutputFile); } // Note: Resolving merges requires that the "Editor: Code Lens" setting is enabled in VSCode let userAction: string = (conflictCount === 0) ? "Please diff the changes to check merge correctness" : `Please manually resolve ${conflictCount} merge conflicts`; Utils.logWithColor(Utils.ConsoleForegroundColors.Yellow, `${FileMergeType[mergeType]}-merge succeeded - ${userAction}`); } return (conflictCount); } /** Checks the generated 'pathedOutputFile' for TypeScript errors. Returns a SourceFileProblemCheckResult. */ function checkGeneratedFile(pathedOutputFile: string, mergeConflictMarkersAllowed: boolean = false): SourceFileProblemCheckResult { let result: SourceFileProblemCheckResult = AST.checkFileForTSProblems(pathedOutputFile, CodeGenerationFileType.Generated, mergeConflictMarkersAllowed); if ((result.errorCount > 0)) { Utils.log(`Error: TypeScript [${TS.version}] check failed for generated file ${Path.basename(pathedOutputFile)}: ${result.errorCount} error(s) found`); } else { Utils.log(`Success: No TypeScript errors found in generated file ${Path.basename(pathedOutputFile)}`); } return (result); } /** Returns the fully pathed version of the supplied TypeScript template file name [which is shipped in the ambrosia-node package], or throws an the file cannot be found. */ function getPathedTemplateFile(templateFileName: string): string { let pathedTemplateFile: string = ""; let searchFolders: string[] = [process.cwd(), Path.join(process.cwd(), "node_modules/ambrosia-node")]; // This only works if ambrosia-node has been installed locally (not globally, which we handle below) for (const folder of searchFolders) { if (File.existsSync(Path.join(folder, templateFileName))) { pathedTemplateFile = Path.join(folder, templateFileName); break; } } if (pathedTemplateFile.length === 0) { // Last ditch (and costly) attempt, try to locate the global npm install location try { // Note: In launch.json, set '"autoAttachChildProcesses": false' to prevent the VS Code debugger from attaching to this process // Note: See https://docs.npmjs.com/misc/config let globalNpmInstallFolder: string = ChildProcess.execSync("npm config get prefix", { encoding: "utf8", windowsHide: true }).trim(); // See https://docs.npmjs.com/files/folders globalNpmInstallFolder = Path.join(globalNpmInstallFolder, Utils.isWindows() ? "" : "lib", "node_modules/ambrosia-node"); pathedTemplateFile = Path.join(globalNpmInstallFolder, templateFileName); if (!File.existsSync(pathedTemplateFile)) { searchFolders.push(globalNpmInstallFolder); // So that we can report where we tried to look for the [shipped] template pathedTemplateFile = ""; } } catch (error: unknown) { const errorMsg: string = Utils.makeError(error).message.replace(/\s+/g, " ").trim().replace(/\.$/, ""); Utils.log(`Error: Unable to determine global npm install folder (reason: ${errorMsg})`); } if (pathedTemplateFile.length === 0) { throw new Error(`Unable to find template file ${templateFileName} in ${searchFolders.join(" or ")}`); } } return (pathedTemplateFile); } /** The [TypeScript] alias used to reference the input source file in the generated PublisherFramework.g.ts file. */ const SOURCE_MODULE_ALIAS: string = "PTM"; // PTM = "Published Types and Methods" /** Generates TypeScript code for the specified template section [of PublisherFramework.template.ts]. May return an empty string if there is no code for the section. */ function codeGen(section: CodeGenSection, fileOptions: FileGenOptions, sourceFileName?: string): string { const NL: string = Utils.NEW_LINE; // Just for short-hand const tab: string = " ".repeat(assertDefined(fileOptions.tabIndent)); let lines: string[] = []; let moduleAlias: string = sourceFileName ? SOURCE_MODULE_ALIAS + "." : ""; /** [Local function] Returns the TypeScript namespace (if any) of the supplied published type (if it exists), including the trailing ".". */ function makeParamTypePrefix(publishedType?: Type): string { if (publishedType) { if (publishedType.codeGenOptions?.nsPath) { return (moduleAlias + publishedType.codeGenOptions.nsPath + "."); } else { return (moduleAlias); } } else { // No prefix required for a non-published type (eg. "string") return (""); } } // Skip this section if requested if ((section & assertDefined(fileOptions.publisherSectionsToSkip)) === section) { return (""); } switch (section) { case CodeGenSection.Header: lines.push(...getHeaderCommentLines(GeneratedFileKind.Publisher, fileOptions)); if (sourceFileName) { // Add an 'import' for the developer-provided source file that contains the implementations of published types and methods // Note: We don't just want to use an absolute path to the source file (even though that would be simpler for us) because // we want to retain any relative path so that it's easier for the user to move their code-base around. // The reference to the source file must be relative to location of the generated file. For example, if the generated // file is in ./src and the input source file is ./test/Foo.ts, then the import file reference should be '../test/Foo' const relativeSourceFileName: string = Path.relative(assertDefined(fileOptions.outputPath), sourceFileName); let filePath: string = Path.dirname(relativeSourceFileName.replace(/\\/g, "/")); if ((filePath !== ".") && !filePath.startsWith("../") && !filePath.startsWith("./")) { filePath = "./" + filePath; } let fileReference: string = filePath + "/" + Path.basename(relativeSourceFileName).replace(Path.extname(relativeSourceFileName), ""); lines.push(`import * as ${SOURCE_MODULE_ALIAS} from "${fileReference}"; // ${SOURCE_MODULE_ALIAS} = "Published Types and Methods", but this file can also include app-state and app-event handlers`); } break; case CodeGenSection.AppState: if (sourceFileName) { if (AST.appStateVar() !== "") { lines.push(`// ${CODEGEN_COMMENT_PREFIX}: '${CodeGenSection[section]}' section skipped (using provided state variable '${SOURCE_MODULE_ALIAS}.${AST.appStateVar()}' and class '${AST.appStateVarClassName()}' instead)`); break; } else { // Note: The _appState variable MUST be in an exported namespace (or module) so that it becomes a [mutable] property of an exported object [the namespace], // thus allowing it to be set [by checkpointConsumer()] at runtime (see https://stackoverflow.com/questions/53617972/exported-variables-are-read-only). // If it's exported from the root-level of the source file, the generated PublisherFramework.g.ts code will contain this error [in checkpointConsumer()]: // Cannot assign to '_myAppState' because it is a read-only property. (ts:2540) lines.push(`// TODO: It's recommended that you move this namespace to your input file (${makeRelativePath(assertDefined(fileOptions.outputPath), sourceFileName)}) then re-run code-gen`); } } lines.push("export namespace State"); lines.push("{"); lines.push(tab + "export class AppState extends Ambrosia.AmbrosiaAppState" + NL + tab + "{"); lines.push(tab.repeat(2) + "// TODO: Define your application state here" + NL); lines.push(tab.repeat(2) + "/**"); lines.push(tab.repeat(2) + " * @param restoredAppState Supplied only when loading (restoring) a checkpoint, or (for a \"VNext\" AppState) when upgrading from the prior AppState.\\"); lines.push(tab.repeat(2) + " * **WARNING:** When loading a checkpoint, restoredAppState will be an object literal, so you must use this to reinstantiate any members that are (or contain) class references."); lines.push(tab.repeat(2) + " */"); lines.push(tab.repeat(2) + "constructor(restoredAppState?: AppState)"); lines.push(tab.repeat(2) + "{"); lines.push(tab.repeat(3) + "super(restoredAppState);" + NL); lines.push(tab.repeat(3) + "if (restoredAppState)"); lines.push(tab.repeat(3) + "{"); lines.push(tab.repeat(4) + "// TODO: Re-initialize your application state from restoredAppState here"); lines.push(tab.repeat(4) + "// WARNING: You MUST reinstantiate all members that are (or contain) class references because restoredAppState is data-only"); lines.push(tab.repeat(3) + "}"); lines.push(tab.repeat(3) + "else"); lines.push(tab.repeat(3) + "{"); lines.push(tab.repeat(4) + "// TODO: Initialize your application state here"); lines.push(tab.repeat(3) + "}"); lines.push(tab.repeat(2) + "}" + NL + tab + "}" + NL); lines.push(tab + "/**"); lines.push(tab + " * Only assign this using the return value of IC.start(), the return value of the upgrade() method of your AmbrosiaAppState"); lines.push(tab + " * instance, and [if not using the generated checkpointConsumer()] in the 'onFinished' callback of an IncomingCheckpoint object."); lines.push(tab + " */"); lines.push(tab + "export let _appState: AppState;"); lines.push("}") break; case CodeGenSection.PostMethodHandlers: for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { let method: Method = _publishedMethods[name][version]; let variableNames: string[] = method.parameterNames.map(name => name.endsWith("?") ? name.slice(0, -1) : name); let nsPathForMethod: string = method.codeGenOptions?.nsPath ? (method.codeGenOptions.nsPath + ".") : ""; if (method.isPost) { let caseTab: string = tab; lines.push(`case "${method.name}":`); if (variableNames.length > 0) { // To prevent variable name collisions in the switch statement (eg. if 2 methods use the same parameter name), if needed, we create a new block scope for each case statement lines.push(`${tab}{`); caseTab = tab + tab; } for (let i = 0; i < variableNames.length; i++) { let prefix: string = makeParamTypePrefix(_publishedTypes[Type.removeArraySuffix(method.parameterTypes[i])]); lines.push(`${caseTab}const ${Method.trimRest(variableNames[i])}: ${prefix}${method.parameterTypes[i]} = IC.getPostMethodArg(rpc, "${Method.trimRest(method.parameterNames[i])}");`); } let prefix: string = makeParamTypePrefix(_publishedTypes[Type.removeArraySuffix(method.returnType)]); lines.push(`${caseTab}IC.postResult<${prefix}${method.returnType}>(rpc, ${moduleAlias + nsPathForMethod}${method.name}(${variableNames.join(", ")}));`); if (variableNames.length > 0) { lines.push(`${tab}}`); } lines.push(`${tab}break;${NL}`); } } } break; case CodeGenSection.NonPostMethodHandlers: for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { let method: Method = _publishedMethods[name][version]; let variableNames: string[] = method.parameterNames.map(name => name.endsWith("?") ? name.slice(0, -1) : name); let nsPathForMethod: string = method.codeGenOptions?.nsPath ? (method.codeGenOptions.nsPath + ".") : ""; if (!method.isPost) { let caseTab: string = tab; lines.push(`case ${method.id}:`); if (variableNames.length > 0) { // To prevent variable name collisions in the switch statement (eg. if 2 methods use the same parameter name), if needed, we create a new block scope for each case statement lines.push(`${tab}{`); caseTab = tab + tab; } for (let i = 0; i < variableNames.length; i++) { let prefix: string = makeParamTypePrefix(_publishedTypes[Type.removeArraySuffix(method.parameterTypes[i])]); if (method.takesRawParams) { lines.push(`${caseTab}const ${variableNames[i]}: ${prefix}${method.parameterTypes[i]} = rpc.getRawParams();`); } else { const isOptionalParam: boolean = method.parameterNames[i].endsWith("?"); const paramName: string = isOptionalParam ? method.parameterNames[i].slice(0, -1) : method.parameterNames[i]; lines.push(`${caseTab}const ${Method.trimRest(variableNames[i])}: ${prefix}${method.parameterTypes[i]} = rpc.getJsonParam("${Method.trimRest(paramName)}");${isOptionalParam ? " // Optional parameter" : ""}`); } } lines.push(`${caseTab}${moduleAlias + nsPathForMethod}${method.name}(${variableNames.join(", ")});`); if (variableNames.length > 0) { lines.push(`${tab}}`); } lines.push(`${tab}break;${NL}`); } } } break; case CodeGenSection.PublishTypes: for (const typeName in _publishedTypes) { let type: Type = _publishedTypes[typeName]; lines.push(`Meta.publishType("${type.name}", "${type.definition.replace(/"/g, "\\\"")}");`); } break; case CodeGenSection.PublishMethods: for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { let method: Method = _publishedMethods[name][version]; let paramList: string[] = []; paramList.push(...method.parameterNames.map((name, index) => `"${name}: ${method.parameterTypes[index].replace(/"/g, "\\\"")}"`)); let methodParams: string = `[${paramList.join(", ")}]`; if (method.isPost) { lines.push(`Meta.publishPostMethod("${method.name}", ${method.version}, ${methodParams}, "${method.returnType.replace(/"/g, "\\\"")}"${method.isTypeChecked ? "" : ", false"});`); } else { lines.push(`Meta.publishMethod(${method.id}, "${method.name}", ${methodParams});`); } } } break; case CodeGenSection.MethodImplementations: if (sourceFileName) { // The methods (and supporting types) have already been implemented in the developer-provided source file, so we're done return (""); } // First, emit classes/type-aliases/enums for types that are used by the methods for (const typeName in _publishedTypes) { let type: Type = _publishedTypes[typeName]; if (type.isReferenced()) { lines.push(NL + "// This class is for a published type referenced by one or more published methods"); lines.push("// CAUTION: Do NOT change the data 'shape' of this class directly; instead, change the Meta.publishType() call in your code-gen program and re-run it"); lines.push(type.makeTSType(0, fileOptions.tabIndent, "", false)); } } // Emit method stubs [that the developer must implement] for (const name in _publishedMethods) { for (const version in _publishedMethods[name]) { let method: Method = _publishedMethods[name][version]; lines.push(`${NL}// CAUTION: Do NOT change the parameter list (or return type) of this method directly; instead, change the Meta.publish${method.isPost ? "Post" : ""}Method() call in your code-gen program and re-run it`); lines.push(`function ${method.nameForTSWrapper}(${method.makeTSFunctionParameters()}): ${method.returnType}`); lines.push(`{${NL}${tab}// TODO: Implement this method`); lines.push(`${tab}throw new Error("The '${method.name}' method has not been implemented");`); if (method.returnType !== "void") { lines.push(`${tab}return (undefined);`); } lines.push(`}`); } } break; // This case handles all CodeGenSection.xxxEventHandler sections case RegExp(/.*EventHandler$/g).test(CodeGenSection[section]) ? section : CodeGenSection.None: if (section !== CodeGenSection.None) { const fnName: string = "on" + CodeGenSection[section].replace("EventHandler", ""); const fnDetails: AppEventHandlerFunctionDetails = _appEventHandlerFunctions[fnName]; if (fnDetails.foundInInputSource || !sourceFileName) { const prefix: string = moduleAlias + (fnDetails.nsPath ? fnDetails.nsPath + "." : ""); const argList: string[] = []; const blockTab: string = fnDetails.expectedParameters ? tab : ""; if (fnDetails.expectedParameters) { // To prevent variable name collisions in the switch statement (eg. if 2 event handlers use the same parameter name), if needed, we create a new block scope for each case statement lines.push("{") } if (fnDetails.expectedParameters) { const parameters: string[] = fnDetails.expectedParameters.split(",").map(p => p.replace(/\s/g, "")); for (let i = 0; i < parameters.length; i++) { const paramName: string = parameters[i].split(":")[0]; const paramType: string = parameters[i].split(":")[1]; lines.push(`${blockTab}const ${paramName}: ${paramType} = appEvent.args[${i}];`); argList.push(paramName); } } if (fnDetails.foundInInputSource) { lines.push(`${blockTab}${prefix}${fnName}(${argList.join(", ")});`); } if (!sourceFileName) { lines.push(`${blockTab}// TODO: Add your [non-async] handler here`); } if (fnDetails.expectedParameters) { lines.push("}") } } } break; default: throw new Error(`The '${CodeGenSection[section]}' CodeGenSection is not currently supported`); } return ((lines.length > 0) ? lines.join(NL) : ""); } /** Replaces the token in 'template' for the specified CodeGenSection with code (or with 'defaultReplacementText' if no code is generated) and returns the result. */ function replaceTemplateToken(template: string, section: CodeGenSection, fileOptions: FileGenOptions, defaultReplacementText: string = "", sourceFileName?: string): string { let tokenName: string = CodeGenSection[section]; let replacementText: string = codeGen(section, fileOptions, sourceFileName); let updatedTemplate: string = template; let tokenStartIndex: number = template.indexOf(`${CODEGEN_TEMPLATE_TOKEN_PREFIX}Name=${tokenName}`); let tokenEndIndex: number = template.indexOf("]", tokenStartIndex); /** [Local function] Returns the value of the specified attribute (eg. "StartingIndent") from the specified replaceable token (eg. "[TOKEN:Name=Header,StartingIndent=0]"). */ function extractTokenAttributeValue(token: string, attrName: string): string { let attrValue: string = token.replace(CODEGEN_TEMPLATE_TOKEN_PREFIX, "").replace("]", "").split(",").filter(kvp => (kvp.split("=")[0] === attrName))[0].split("=")[1]; return (attrValue); } if ((section & assertDefined(fileOptions.publisherSectionsToSkip)) === section) { defaultReplacementText = `// ${CODEGEN_COMMENT_PREFIX}: '${CodeGenSection[section]}' section skipped by request`; } if ((tokenStartIndex !== -1) && (tokenEndIndex !== -1)) { let token: string = template.substring(tokenStartIndex, tokenEndIndex + 1); let startingIndent: number = Number.parseInt(extractTokenAttributeValue(token, "StartingIndent")); let indent: string = " ".repeat(isNaN(startingIndent) ? 0 : startingIndent); let newText: string = replacementText || defaultReplacementText; let newLines: string[] = newText.split(Utils.NEW_LINE).map((line, index) => ((index === 0) ? "" : indent) + line); updatedTemplate = template.replace(token, newLines.join(Utils.NEW_LINE)); } return (updatedTemplate); } /** Returns an array of lines containing the comments that should appear at the start of a generated code file. */ function getHeaderCommentLines(fileKind: GeneratedFileKind, fileOptions: FileGenOptions): string[] { let headerLines: string[] = []; let localInstanceName: string = Configuration.loadedConfig().instanceName; let fileDescription: string = (fileKind === GeneratedFileKind.Consumer) ? "consumer-side API" : (fileKind === GeneratedFileKind.Publisher ? "publisher-side framework" : "(unknown description)") headerLines.push(`// Generated ${fileDescription} for the '${fileOptions.apiName}' Ambrosia Node app/service.`); if (fileKind === GeneratedFileKind.Consumer) { headerLines.push(`// Publisher: ${fileOptions.publisherContactInfo || "(Not specified)"}.`); } headerLines.push("// Note: This file was generated" + (fileOptions.emitGeneratedTime ? ` on ${Utils.getTime().replace(" ", " at ")}.` : "")); headerLines.push(`// Note [to publisher]: You can edit this file, but to avoid losing your changes be sure to specify a 'mergeType' other than 'None' (the default is 'Annotate') when re-running emitTypeScriptFile[FromSource]().`); return (headerLines); } /** Removes lines that contain "[DEV-ONLY COMMENT]" from the supplied template. */ function removeDevOnlyTemplateCommentLines(template: string): string { let lines: string[] = template.split(Utils.NEW_LINE); return (lines.filter(line => line.indexOf("[DEV-ONLY COMMENT]") === -1).join(Utils.NEW_LINE)); } /** Throws if the specified [generated] output file contains a git merge conflict marker. */ function checkForGitMergeMarkers(pathedFile: string): void { if (File.existsSync(pathedFile)) { let content: string = File.readFileSync(pathedFile, { encoding: "utf8" }); let startMarkerIndex: number = content.indexOf(Utils.NEW_LINE + "<<<<<<< "); let splitMarkerIndex: number = content.indexOf(Utils.NEW_LINE + "======="); let endMarkerIndex: number = content.indexOf(Utils.NEW_LINE + ">>>>>>> "); if ((startMarkerIndex !== -1) && (splitMarkerIndex !== -1) && (endMarkerIndex !== -1) && (startMarkerIndex < splitMarkerIndex) && (splitMarkerIndex < endMarkerIndex)) { throw new Error(`${pathedFile} contains a git merge conflict marker: resolve the conflict(s) then retry`) } } } /** Throws if there is a name or location collision between 'pathedOutputFile' and 'sourceFileName'. */ function checkForFileNameConflicts(pathedOutputFile: string, sourceFileName?: string): void { if (sourceFileName) { if (Path.resolve(sourceFileName) === pathedOutputFile) { throw new Error(`The input source file (${Path.resolve(sourceFileName)}) cannot be the same as the generated file`); } if (Path.basename(sourceFileName) === Path.basename(pathedOutputFile)) { throw new Error(`To avoid confusion, the input source file (${Path.basename(sourceFileName)}) should not have the same name as the generated file`); } } } /** * [Internal] This method is for **internal testing only**.\ * Use emitTypeScriptFileFromSource() instead. */ export function publishFromSource(tsFileName: string, fileOptions?: FileGenOptions) : void { if (!fileOptions) { const apiName: string = Path.basename(tsFileName).replace(Path.extname(tsFileName), ""); fileOptions = new FileGenOptions({ apiName: apiName}); } AST.publishFromAST(tsFileName, fileOptions); } /** Type for Ambrosia code-gen attributes parsed from an @ambrosia JSDoc tag. */ type AmbrosiaAttrs = { [attrName: string]: boolean | number | string }; /** [Internal] Type for options (eg. details about the entity) used during code generation. */ type CodeGenOptions = { /** The namespace path (in the input source file) where the entity was found, eg. "Foo.Bar.Baz". [Applies to functions, type aliases, and enums].*/ nsPath: string, /** If available, the text of the JSDoc comment for nsPath. */ nsComment?: string, /** If available, the JSDoc comment that describes the entity. [Applies to functions, type aliases, and enums]. */ jsDocComment?: string }; /** Type of the result from checkFileForTSProblems(). */ class SourceFileProblemCheckResult { errorCount: number = 0; warningCount: number = 0; mergeConflictCount: number = 0; constuctor() { } } // See https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API // Note: A great tool to help with debugging is https://ts-ast-viewer.com/# /** Class of static methods used to walk the abstract syntax tree (AST) of a TypeScript file in order to publish types and methods from it. */ class AST { private static _fileGenOptions: FileGenOptions; private static _typeChecker: TS.TypeChecker; private static _sourceFile: TS.SourceFile; private static _publishedEntityCount: number = 0; // A running count of the entities (functions, type aliases, enums) published during the AST walk private static _ignoredErrorCount: number = 0; // A running count of ignored errors (ie. errors encountered while FileGenOptions.haltOnError is false) private static _compilerOptions: TS.CompilerOptions = { module: TS.ModuleKind.CommonJS, target: TS.ScriptTarget.ES2018, strict: true }; // Controls the "flavor" of TS to check/emit, and the strictness of the compiler checks private static _targetNodeKinds: TS.SyntaxKind[] = [TS.SyntaxKind.FunctionDeclaration, TS.SyntaxKind.MethodDeclaration, TS.SyntaxKind.TypeAliasDeclaration, TS.SyntaxKind.EnumDeclaration]; // The kinds of AST nodes we can publish from // The set of supported @ambrosia tag "attributes" for each target node kind private static _supportedAttrs: { [nodeKind: number]: string[] } = { [TS.SyntaxKind.FunctionDeclaration]: ["publish", "version", "methodID", "doRuntimeTypeChecking"], [TS.SyntaxKind.MethodDeclaration]: ["publish", "version", "methodID", "doRuntimeTypeChecking"], // Note: Static methods only [TS.SyntaxKind.TypeAliasDeclaration]: ["publish"], [TS.SyntaxKind.EnumDeclaration]: ["publish"] }; private static _knownAttrs: string[] = Object.values(AST._supportedAttrs).reduce((acc, values) => { acc.push(...values.filter(v => acc.indexOf(v) === -1)); return (acc); }); private static _namespaces: string[] = []; // A "stack" of strings in the format "namespaceName:namespaceEndPosition" (eg. "Test:740") private static _currentNamespaceEndPos: number = 0; // The end-offset of the current namespace (0 before the first namespace, or the EOF position after leaving the last namespace) private static _functionEndPos: number = 0; // The end-offset of the current function (or 0 if the AST walk is not currently in a function) private static _publishedSourceFile: string = ""; // The TypeScript source file that was used to publish from (only set once publishing has succeeded) private static _appStateVar: string = ""; // The name [with namespace path] of the exported variable (if found) in the input source file that extends AmbrosiaAppState private static _appStateVarClassName: string = ""; // The name [with namespace path] of the class of _appStateVar private static _namespaceJSDocComments: { [pathedNamespace: string]: string } = {}; // Value is the JSDocComment text // Private because AST is a static class private constructor() { } /** The name [with namespace path] of the exported variable (if found) in the input source file that extends AmbrosiaAppState. */ public static appStateVar(): string { return (AST._appStateVar); } /** The name [with namespace path] of the class of the exported variable (if found) in the input source file that extends AmbrosiaAppState. */ public static appStateVarClassName(): string { return (AST._appStateVarClassName); } /** The TypeScript source file that was used to publish from (only set once publishing has succeeded). */ public static publishedSourceFile(): string { return (AST._publishedSourceFile); } /** * [Internal] Clears the last published source file (to enable iterative publishing of source files). * This method is for **internal testing only**. */ public static clearPublishedSourceFile(): void { AST._publishedSourceFile = ""; } /** The final count of entities (functions, type aliases, enums) published in publishedSourceFile(). */ public static publishedEntityCount(): number { return (AST._publishedSourceFile ? AST._publishedEntityCount : 0); } /** * Returns the current namespace path (eg. "Root.Outer.Inner") at the current point in time of the AST walk. May return an empty string.\ * DEPRECATED: Use AST.getNamespacePath() instead. */ public static getCurrentNamespacePath(): string { return (AST._namespaces.map(pair => pair.split(":")[0]).join(".")); } /** Returns the namespace path (eg. "Root.Outer.Inner") of the supplied node. May return an empty string. */ public static getNamespacePath(node: TS.Node): string { // TODO: The cast to 'any' here is a workaround for a "bug" in getSymbolAtLocation() [see https://github.com/Microsoft/TypeScript/issues/5218]. // Despite getSymbolAtLocation() being observed to almost always return 'undefined' [F11 into it to see why], we still call it in the // hope that one day it will be fixed to work as "expected". const symbol: TS.Symbol = AST._typeChecker.getSymbolAtLocation(node) || (node as any).symbol; if (!symbol) { throw new Error(`Unable to determine symbol for node '${node.getText()}' at ${AST.getLocation(node.getStart())}`); } return (AST.getNamespacePathOfSymbol(symbol)); } /** Returns the namespace path (eg. "Root.Outer.Inner") of the supplied symbol. May return an empty string. */ public static getNamespacePathOfSymbol(symbol: TS.Symbol): string { // Note: TypeChecker.getFullyQualifiedName() returns a string in one of two forms: // Either "test/PI".State._myAppState (if exported) or State._myAppState (if not exported) [see https://github.com/dsherret/ts-morph/issues/132]. // BUGBUG: If a nested namespace is not exported (eg. if Baz is not exported in Foo.Bar.Baz) then TypeChecker.getFullyQualifiedName() will // return 'Baz' for the Baz namespace node instead of 'Foo.Bar' as expected. In practice, this is never a problem since the generated // PublisherFramework.g.ts will contain errors for each reference to the non-exported type/method, which the developer would fix by // adding the missing 'export' keyword to the namespace. Only in the case of an unreferenced published type would the containing // namespace be silently moved to the root in ConsumerInterface.g.ts; but since the type is unreferenced, this is harmless. let nsPath: string = AST._typeChecker.getFullyQualifiedName(symbol); // Remove the leading file-path portion (if any) of the path [Note: this may contain "."] if (nsPath.startsWith("\"")) { nsPath = nsPath.replace(/^"[^"]*"\./, ""); } // Remove the trailing member name nsPath = nsPath.split(".").slice(0, -1).join("."); return (nsPath); } /** * Reads the supplied TypeScript file and dynamically executes publishType/publishPostMethod/publishMethod calls for the annotated functions, static methods, type-aliases and enums. * Returns a count of the number of entities published. */ static publishFromAST(tsFileName: string, fileOptions: FileGenOptions): number { let pathedFileName: string = Path.resolve(tsFileName); // Check that the input TypeScript file exists if (!File.existsSync(tsFileName)) { throw new Error(`The TypeScript file specified (${pathedFileName}) does not exist`); } Utils.log(`Publishing types and methods from ${pathedFileName}...`); AST._compilerOptions.strict = fileOptions.strictCompilerChecks; // We support this omnibus flag from the "strictness" family because it's the most comprehensive (and for simplicity in our code) AST._compilerOptions.noImplicitReturns = fileOptions.strictCompilerChecks; // We also include this flag in our [single] 'strictCompilerChecks' option // Note: Setting 'noImplicitReturns' to true will enable the [additional] error "Not all code paths return a value (ts:7030)", but when it's false [the default] it will // NOT suppress "Function lacks ending return statement and return type does not include 'undefined' (ts:2366)" which is reported when 'strictNullCheck' is enabled. let program: TS.Program = TS.createProgram([tsFileName], AST._compilerOptions); // Note: Setting 'removeComments' to true does NOT remove JSDocComment nodes AST._fileGenOptions = fileOptions; AST._sourceFile = assertDefined(program.getSourceFile(tsFileName)); AST._typeChecker = program.getTypeChecker(); AST._publishedEntityCount = 0; AST._ignoredErrorCount = 0; AST._namespaces = []; AST._currentNamespaceEndPos = 0; AST._functionEndPos = 0; AST._appStateVar = ""; AST._appStateVarClassName = ""; AST._namespaceJSDocComments = {}; // Reset the "discovered" attributes of _appEventHandlerFunctions Object.keys(_appEventHandlerFunctions).forEach(fnName => _appEventHandlerFunctions[fnName].reset()); // Check that the [input] source file "compiles" let result: SourceFileProblemCheckResult = AST.checkFileForTSProblems(tsFileName, CodeGenerationFileType.Input); if (result.errorCount > 0) { if (fileOptions.ignoreTSErrorsInSourceFile) { Utils.log(`Ignoring ${result.errorCount} TypeScript error(s) found compiling input file ${Path.basename(tsFileName)}`); } else { throw new Error(`TypeScript [${TS.version}] check failed for input file ${tsFileName}: ${result.errorCount} error(s) found`); } } // Note: A great tool to help with debugging is https://ts-ast-viewer.com/# AST.walkAST(AST._sourceFile, fileOptions.haltOnError); Utils.log(`Publishing finished: ${AST._publishedEntityCount} entities published${!fileOptions.haltOnError && (AST._ignoredErrorCount > 0) ? `, ${AST._ignoredErrorCount} errors found` : ""}`); AST._publishedSourceFile = tsFileName; return (AST._publishedEntityCount); } /** Reports (logs) any TypeScript compiler errors and warnings present in the specified .ts file. Returns the counts of errors/warnings found. */ static checkFileForTSProblems(tsFileName: string, fileType: CodeGenerationFileType, mergeConflictMarkersAllowed: boolean = false): SourceFileProblemCheckResult { let program: TS.Program = TS.createProgram([tsFileName], AST._compilerOptions); let diagnostics: readonly TS.Diagnostic[] = TS.getPreEmitDiagnostics(program); let result: SourceFileProblemCheckResult = new SourceFileProblemCheckResult(); let mergeConflictMarkerCount: number = 0; let displayFileType: string = CodeGenerationFileType[fileType].toLowerCase(); /** [Local function] Type guard: returns true if 'obj' is a TS.DiagnosticMessageChain. */ function isDiagnosticMessageChain(obj: any): obj is TS.DiagnosticMessageChain { return (obj.hasOwnProperty("messageText") && obj.hasOwnProperty("category") && obj.hasOwnProperty("code")); } if (diagnostics.length > 0) { diagnostics.forEach(diagnostic => { // If we did a merge then we don't report the errors that will [knowingly] arise from the resulting merge conflict markers; // without this, the error ouput would be too "noisy" making it harder to see any "real" errors in the generated code const canIgnoreError: boolean = ((fileType === CodeGenerationFileType.Generated) && (diagnostic.code === 1185) && mergeConflictMarkersAllowed); // 1185 = "Merge conflict marker encountered" let diagnosticMsg: string = "Unknown failure"; if (diagnostic.code === 1185) { mergeConflictMarkerCount++; } if (typeof diagnostic.messageText === "string") { diagnosticMsg = diagnostic.messageText; } else { if (isDiagnosticMessageChain(diagnostic.messageText)) { diagnosticMsg = diagnostic.messageText.messageText; // if (diagnostic.messageText.next) // { // diagnosticMsg += "; " + diagnostic.messageText.next.map(d => Utils.trimTrailingChar(d.messageText, ".")).join("; "); // } } } diagnosticMsg = Utils.trimTrailingChar(diagnosticMsg, "."); // Note: If tsFileName imports another file which has a problem, then diagnostic.file will refer to the imported file instead of tsFileName if ((diagnostic.category === TS.DiagnosticCategory.Error) && !canIgnoreError) { let message: string = `Error: TypeScript error compiling ${displayFileType} file: ${diagnosticMsg} (ts:${diagnostic.code})` + (diagnostic.start ? ` at ${AST.getLocation(assertDefined(diagnostic.start), diagnostic.file)}` : ""); Utils.log(message); result.errorCount++; } if (diagnostic.category === TS.DiagnosticCategory.Warning) { let message: string = `Warning: TypeScript warning compiling ${displayFileType} file: ${diagnosticMsg} (ts:${diagnostic.code})` + (diagnostic.start ? ` at ${AST.getLocation(assertDefined(diagnostic.start), diagnostic.file)}` : ""); Utils.log(message); result.warningCount++; } }); } if (mergeConflictMarkerCount > 0) { result.mergeConflictCount = mergeConflictMarkerCount / 3; } return (result); } // Walks ALL nodes (including those for keywords, punctuation, and - critically - JSDoc) // Note: A great tool to help with debugging is https://ts-ast-viewer.com/# (just copy/paste your input .ts file into the viewer to explore the AST) // Note: The 'haltOnError' parameter is for testing purposes only. Setting it to false is unsafe. private static walkAST(nodeToWalk: TS.Node, haltOnError: boolean = true): void { let nodes: TS.Node[] = nodeToWalk.getChildren(); nodes.forEach(node => { try { const isStatic: boolean = (node.modifiers !== undefined) && (node.modifiers.filter(m => m.kind === TS.SyntaxKind.StaticKeyword).length === 1); const isPrivate: boolean = (node.modifiers !== undefined) && (node.modifiers.filter(m => m.kind === TS.SyntaxKind.PrivateKeyword).length === 1); let isExported: boolean = (node.modifiers !== undefined) && (node.modifiers.filter(m => m.kind === TS.SyntaxKind.ExportKeyword).length === 1); const isStaticMethod: boolean = isStatic && (node.kind === TS.SyntaxKind.MethodDeclaration); const isNestedFunction: boolean = (node.kind === TS.SyntaxKind.FunctionDeclaration) && (AST._functionEndPos > 0); let isWellKnownFunction: boolean = false; // Check for an @ambrosia tag on unsupported nodes if (AST._targetNodeKinds.indexOf(node.kind) === -1) { const attrs: AmbrosiaAttrs = AST.getAmbrosiaAttrs(node); if (attrs["hasAmbrosiaTag"] === true) { const targetNames: string = (this._targetNodeKinds .slice(0, this._targetNodeKinds.length - 1) .map(kind => AST.getNodeKindName(kind)) .join(", ") + ", and " + AST.getNodeKindName(this._targetNodeKinds[this._targetNodeKinds.length - 1])) .replace("method", "static method"); throw new Error(`The ${CODEGEN_TAG_NAME} tag is not valid on a ${AST.getNodeKindName(node.kind)} (at ${attrs["location"]}); valid targets are: ${targetNames}`); } } // Checks for an @ambrosia tag on a method if (node.kind === TS.SyntaxKind.MethodDeclaration) { const attrs: AmbrosiaAttrs = AST.getAmbrosiaAttrs(node); if (attrs["hasAmbrosiaTag"] === true) { // Check for an @ambrosia tag on a non-static method if (!isStatic) { throw new Error(`The ${CODEGEN_TAG_NAME} tag is not valid on a non-static method (at ${attrs["location"]})`); } // A static method has to directly belong to an exported class: it cannot belong to a class expression [because there is no way to reference the method] if (TS.isClassExpression(node.parent)) { throw new Error(`The ${CODEGEN_TAG_NAME} tag is not valid on a static method of a class expression (at ${attrs["location"]})`); } // Check for an @ambrosia tag on a private static method if (isPrivate && isStatic) { throw new Error(`The ${CODEGEN_TAG_NAME} tag is not valid on a private static method (at ${attrs["location"]})`); } } } // Check for an @ambrosia tag on a local function if (isNestedFunction) { const attrs: AmbrosiaAttrs = AST.getAmbrosiaAttrs(node); if (attrs["hasAmbrosiaTag"] === true) { throw new Error(`The ${CODEGEN_TAG_NAME} tag is not valid on a local function (at ${attrs["location"]})`); } } // Look for the first exported variable whose type is a class that extends AmbrosiaAppState // TODO: This is brittle, since the target variable may not be the first matching variable we find (it may be declared later in the input file). if ((AST._appStateVar === "") && (node.kind === TS.SyntaxKind.VariableDeclaration)) { const result: { varName: string, varType: TS.Type } | null = AST.getVarOfBaseType(node as TS.VariableDeclaration, "AmbrosiaAppState", "AmbrosiaRoot.ts"); if (result) { // Note: The app state variable may no longer be in the same namespace as the AppState class (as they were in the generated code). So we must explicitly // determine the namespace path for the type (class) of the app state variable rather than assuming it's the same as AST.getNamespacePath(node). const varClassSymbol: TS.Symbol = result.varType.symbol; AST._appStateVar = AST.getNamespacePath(node) ? (AST.getNamespacePath(node) + "." + result.varName) : result.varName; AST._appStateVarClassName = AST.getNamespacePathOfSymbol(varClassSymbol) ? (AST.getNamespacePathOfSymbol(varClassSymbol) + "." + varClassSymbol.name) : varClassSymbol.name; // Utils.log(`DEBUG: Exported variable ${AST._appStateVar} (of type ${AST._appStateVarClassName}) extends AmbrosiaAppState`); } } // Keep track of JSDoc comments for namespaces/classes [although we won't need all of these since not all namespaces/classes contain published entities] if ((node.kind === TS.SyntaxKind.ModuleDeclaration) || (node.kind === TS.SyntaxKind.ClassDeclaration)) { const jsDocComment: TS.JSDoc | null = AST.getJSDocComment(node); if (jsDocComment) { const namespaceName: string = node.getChildren().filter(c => TS.isIdentifier(c))[0].getText(); const namespacePath: string = AST.getNamespacePath(node); const pathedNamespace: string = namespacePath ? `${namespacePath}.${namespaceName}` : namespaceName; AST._namespaceJSDocComments[pathedNamespace] = jsDocComment.getText(); } } // Keep track of entering/leaving namespaces and classes [so that we can track the "path" to published entities] if ((node.kind === TS.SyntaxKind.ModuleDeclaration) || (node.kind === TS.SyntaxKind.ClassDeclaration)) { const moduleOrClassDecl: TS.ModuleDeclaration = (node as TS.ModuleDeclaration); const namespaceName: string = moduleOrClassDecl.name.getText(); const namespaceEndPos: number = moduleOrClassDecl.getStart() + moduleOrClassDecl.getWidth() - 1; AST._namespaces.push(`${namespaceName}:${namespaceEndPos}`); AST._currentNamespaceEndPos = namespaceEndPos; Utils.log(`Entering namespace '${namespaceName}' (now in '${AST.getCurrentNamespacePath()}') at ${AST.getLocation(node.getStart())}`, null, Utils.LoggingLevel.Debug); } if ((node.getStart() >= AST._currentNamespaceEndPos) && (AST._namespaces.length > 0)) { const leavingNamespaceName: string = assertDefined(AST._namespaces.pop()).split(":")[0]; const enteringNamespaceEndPos = (AST._namespaces.length > 0) ? parseInt(AST._namespaces[AST._namespaces.length - 1].split(":")[1]) : AST._sourceFile.getWidth(); AST._currentNamespaceEndPos = enteringNamespaceEndPos; Utils.log(`Leaving namespace '${leavingNamespaceName}' (now in '${AST.getCurrentNamespacePath() || "[Root]"}') at ${AST.getLocation(node.getStart())}`, null, Utils.LoggingLevel.Debug); } // Keep track of entering/leaving a function (or static method) so that we can we can detect nested (local) functions (which are never candidates to be published) if (((node.kind === TS.SyntaxKind.FunctionDeclaration) || isStaticMethod) && (AST._functionEndPos === 0)) { const functionDecl: TS.FunctionDeclaration = (node as TS.FunctionDeclaration); AST._functionEndPos = functionDecl.getStart() + functionDecl.getWidth() - 1; Utils.log(`Entering ${isStaticMethod ? "static method" : "function"} '${functionDecl.name?.getText() || "N/A"}' at ${AST.getLocation(node.getStart())}`, null, Utils.LoggingLevel.Debug); } if ((AST._functionEndPos > 0) && (node.getStart() >= AST._functionEndPos)) { Utils.log(`Leaving function (or static method) at ${AST.getLocation(node.getStart())}`, null, Utils.LoggingLevel.Debug); AST._functionEndPos = 0; } // Keep track of whether we have found any of the "well known" Ambrosia AppEvent handlers if (node.kind === TS.SyntaxKind.FunctionDeclaration) { const functionDecl: TS.FunctionDeclaration = node as TS.FunctionDeclaration; const isAsync: boolean = node.modifiers ? (node.modifiers.filter(m => m.kind === TS.SyntaxKind.AsyncKeyword).length === 1) : false; const fnName: string = functionDecl.name?.getText() || "N/A"; const location: string = AST.getLocation(node.getStart()); if (isExported && (Object.keys(_appEventHandlerFunctions).indexOf(fnName) !== -1)) { const fnDetails: AppEventHandlerFunctionDetails = _appEventHandlerFunctions[fnName]; const ambrosiaAttrs: AmbrosiaAttrs = AST.getAmbrosiaAttrs(functionDecl, AST._supportedAttrs[functionDecl.kind]); if (ambrosiaAttrs["hasAmbrosiaTag"]) { throw new Error(`The ${CODEGEN_TAG_NAME} tag is not valid on an AppEvent handler ('${fnName}') at ${ambrosiaAttrs["location"]}`); } if (isAsync) { throw new Error(`The AppEvent handler '${fnName}' (at ${location}) cannot be async`); } if (fnDetails.foundInInputSource) { throw new Error(`The AppEvent handler '${fnName}' (at ${location}) has already been defined (at ${fnDetails.location})`); } else { const parameters: string = functionDecl.parameters.map(p => p.getText()).join(", "); const expectedParameters: string = fnDetails.expectedParameters; const returnType: string = functionDecl.type?.getText() || "void"; const expectedReturnType: string = fnDetails.expectedReturnType; if (parameters.replace(/\s*/, "") !== expectedParameters.replace(/\s*/, "")) { Utils.log(`Warning: Skipping Ambrosia AppEvent handler function '${fnName}' (at ${location}) because it has different parameters (${parameters.replace(/\s/g, "").replace(":", ": ")}) than expected (${expectedParameters})`); } else { if (returnType.replace(/\s*/, "") !== expectedReturnType.replace(/\s*/, "")) { Utils.log(`Warning: Skipping Ambrosia AppEvent handler function '${fnName}' (at ${location}) because it has a different return type (${returnType}) than expected (${expectedReturnType})`); } else { fnDetails.foundInInputSource = true; fnDetails.nsPath = AST.getNamespacePath(functionDecl); fnDetails.location = location; } } isWellKnownFunction = true; } } } // Publish functions/types/enums and static methods marked with an @ambrosia JSDoc tag, and which are exported if (!isWellKnownFunction && (AST._targetNodeKinds.indexOf(node.kind) >= 0)) { let location: string = AST.getLocation(node.getStart()); let entityName: string = (node as TS.DeclarationStatement).name?.getText() || "N/A"; let nodeName: string = `${isStatic ? "static " : ""}${AST.getNodeKindName(node.kind)} '${entityName}'`; let skipSilently: boolean = ((node.kind === TS.SyntaxKind.MethodDeclaration) && !isStatic) || isNestedFunction || isPrivate; if (!skipSilently) { // Static methods are not explicitly exported, rather they have to [directly] belong to an exported class if (!isExported && (node.kind === TS.SyntaxKind.MethodDeclaration)) { if (TS.isClassDeclaration(node.parent) && node.parent.modifiers && (node.parent.modifiers.filter(m => m.kind === TS.SyntaxKind.ExportKeyword).length === 1)) { isExported = true; } } if (AST._supportedAttrs[node.kind] === undefined) { throw new Error(`Internal error: No _supportedAttrs defined for a ${TS.SyntaxKind[node.kind]}`); } let ambrosiaAttrs: AmbrosiaAttrs = AST.getAmbrosiaAttrs(node, AST._supportedAttrs[node.kind]); let hasAmbrosiaTag: boolean = ambrosiaAttrs["hasAmbrosiaTag"] as boolean; let isPublished: boolean = ambrosiaAttrs["publish"] as boolean; if (hasAmbrosiaTag) { if (isPublished) { if (isExported) { let publishedEntity: string = ""; switch (node.kind) { case TS.SyntaxKind.FunctionDeclaration: publishedEntity = AST.publishFunction(node as TS.FunctionDeclaration, nodeName, location, ambrosiaAttrs); break; case TS.SyntaxKind.MethodDeclaration: // Note: Static methods only publishedEntity = AST.publishFunction(node as TS.MethodDeclaration, nodeName, location, ambrosiaAttrs); break; case TS.SyntaxKind.TypeAliasDeclaration: publishedEntity = AST.publishTypeAlias(node as TS.TypeAliasDeclaration, nodeName, location, ambrosiaAttrs); break; case TS.SyntaxKind.EnumDeclaration: publishedEntity = AST.publishEnum(node as TS.EnumDeclaration, nodeName, location, ambrosiaAttrs); // To check the result: // Utils.log(getPublishedType(entityName).makeTSType()); break; default: throw new Error(`Unsupported AST node type '${nodeName}'`); } Utils.log(`Successfully published ${nodeName} as a ${publishedEntity}`); AST._publishedEntityCount++; } else { Utils.log(`Warning: Skipping ${nodeName} at ${location} because it is not exported`); } } else { Utils.log(`Warning: Skipping ${nodeName} at ${location} because its ${CODEGEN_TAG_NAME} 'publish' attribute is missing or 'false'`); } } else { // We don't support the @ambrosia tag on the declaration of an overloaded function, so it's expected to be missing in this case, // therefore we don't report the warning. However, this will also be a common "mistake", so publishFunction() checks for this too. let isOverloadFunctionDeclaration: boolean = (node.kind === TS.SyntaxKind.FunctionDeclaration) && ((node as TS.FunctionDeclaration).body === undefined); if (!isOverloadFunctionDeclaration) { Utils.log(`Warning: Skipping ${nodeName} at ${location} because it has no ${CODEGEN_TAG_NAME} JSDoc tag`); } } } } } catch (error: unknown) { if (haltOnError) { // Halt the walk throw error; } else { // Log the error and continue [even though continuing is potentially unsafe] Utils.log(`Error: ${Utils.makeError(error).message}`); AST._ignoredErrorCount++; } } this.walkAST(node, haltOnError); }); } /** * Returns the type(s) of root base class(es) of the specified class type.\ * The returned array will typically have a single element.\ * If the supplied type is not a class, returns an empty array. */ // Note: It's unclear how a type would ever have multiple base types [unless it's for future support of polymorphism] // yet this is what the compiler API supports [via TS.Type.getBaseTypes()], so we adhere to it. Note that having // both an 'extends' and an 'implements' clause does not lead to TS.Type.getBaseTypes() returning more than one type. private static getRootBaseTypes(type: TS.BaseType): TS.Type[] { const baseTypes: TS.BaseType[] = type.getBaseTypes() || []; if (!type.isClass()) { return ([]); } if (baseTypes.length > 0) { const types: TS.Type[] = []; baseTypes.forEach(t => types.push(...AST.getRootBaseTypes(t))); // Recurse return (types); } else { return ([type]); } } /** * If the supplied 'varDecl' is a for a variable of a type [or of a union type] that derives (at its root) from the specified * 'baseTypeName', then it returns the name and type [extracted from the union if needed] of the variable. Otherwise, returns null.\ * The supplied 'baseTypeHostFileName' (eg. "AmbrosiaRoot.ts") should **not** include a path. */ private static getVarOfBaseType(varDecl: TS.VariableDeclaration, baseTypeName: string, baseTypeHostFileName: string): { varName: string, varType: TS.Type } | null { let result: { varName: string, varType: TS.Type } | null = null; const varName: string = varDecl.name.getText(); // Although we don't need this until later on, it helps (for debugging) to know this early if ((varDecl.type?.kind === TS.SyntaxKind.TypeReference) || (varDecl.type?.kind === TS.SyntaxKind.UnionType)) { const varTypes: TS.TypeNode[] = []; if (varDecl.type?.kind === TS.SyntaxKind.TypeReference) { varTypes.push(varDecl.type); } if (varDecl.type?.kind === TS.SyntaxKind.UnionType) { varTypes.push(...(varDecl.type as TS.UnionTypeNode).types); } for (const varType of varTypes) { const referencedType: TS.Type = AST._typeChecker.getTypeAtLocation(varType); if (referencedType.isClass()) { const rootBaseTypes: TS.Type[] = [...AST.getRootBaseTypes(referencedType)]; for (let i = 0; i < rootBaseTypes.length; i++) { const baseType: TS.Type = rootBaseTypes[i]; if (baseType && baseType.symbol && (baseType.symbol.name === baseTypeName) && baseType.symbol.declarations) { const typeSourceFile: TS.SourceFile = baseType.symbol.declarations[0].getSourceFile(); // Can refer to either the .ts or .d.ts file name const typeSourceFileName: string = Path.basename(typeSourceFile.fileName, ".ts"); if (Utils.equalIgnoringCase(Path.basename(typeSourceFileName, ".d"), Path.basename(baseTypeHostFileName, ".ts"))) { // A VariableDeclaration is under a VariableStatement, which is what the 'export' keyword (if specified) applies to let parent: TS.Node = varDecl.parent; while (parent && (parent.kind !== TS.SyntaxKind.VariableStatement)) { parent = parent.parent; } if (parent) { const isVarExported: boolean = parent.modifiers ? (parent.modifiers.filter(n => n.kind === TS.SyntaxKind.ExportKeyword).length === 1) : false; if (isVarExported) { return ({ varName: varName, varType: referencedType }); } } } } } } } } return (result); } /** Returns a "friendly" name for a TS.SyntaxKind; for example, returns "method" for a MethodDeclaration. */ private static getNodeKindName(nodeKind: TS.SyntaxKind): string { let spacedName: string = TS.SyntaxKind[nodeKind].split("").map(ch => /^[A-Z]*$/g.test(ch) ? " " + ch : ch).join(""); return (spacedName.replace("Declaration", "").trim().toLowerCase()); } /** Given a character offset into the source file, returns a string (clickable in VSCode) that describes the location. */ private static getLocation(offset: number, sourceFile: TS.SourceFile = AST._sourceFile): string { let position: TS.LineAndCharacter = sourceFile.getLineAndCharacterOfPosition(offset); // Note: line and character are both 0-based let location: string = `${Path.resolve(sourceFile.fileName)}:${position.line + 1}:${position.character + 1}`; // Note: This format makes it clickable in VSCode return (location); } /** Returns the closest (ie. last) JSDoc comment before the supplied 'declNode', or null if there is no JSDoc comment for the node. */ private static getJSDocComment(node: TS.Node): TS.JSDoc | null { let closestJSDocComment: TS.JSDoc | null = null; // The closest (ie. last) JSDoc comment before the node const childNodes: TS.Node[] = node.getChildren(); for (let i = 0; i < childNodes.length; i++) { if (childNodes[i].kind === TS.SyntaxKind.JSDocComment) { closestJSDocComment = childNodes[i] as TS.JSDoc; } else { break; } } return (closestJSDocComment); } /** * Returns a formatted (for multi-line) JSDoc comment, optionally indented by the specified 'tabIndent' spaces. * If the comment is empty, returns an empty string. */ static formatJSDocComment(jsDocCommentText: string, tabIndent: number = 0): string { // Handle the empty JSDocComment case (eg. "/** */") const isEmptyComment: boolean = RegExp(/^\/*\*+\*\/$/g).test(jsDocCommentText.replace(/\s*/g, "")); if (isEmptyComment) { return (""); } // 1) Strip off all leading whitespace from each line // 2) Add back a single leading space for all but the start-comment line (this is just a style preference) const indent: string = " ".repeat(tabIndent); const formattedComment: string = indent + jsDocCommentText.split(Utils.NEW_LINE).map(line => line.trim()).map(line => (line.indexOf("*") === 0) ? indent + " " + line : line).join(Utils.NEW_LINE); return (formattedComment); } /** * Extracts the @ambrosia JSDoc tag attributes (if present on the supplied declaration node).\ * If an attribute is encountered that is not one of the [optionally] supplied 'supportedAttrs' then an error will be thrown.\ * Note: Even if there is no tag, an AmbrosiaAttrs object will still be returned, but its 'hasAmbrosiaTag' attribute will be false. */ private static getAmbrosiaAttrs(declNode: TS.Node, supportedAttrs: string[] = []): AmbrosiaAttrs { let attrs: AmbrosiaAttrs = { "hasAmbrosiaTag": false }; let closestJSDocComment: TS.JSDoc | null = AST.getJSDocComment(declNode); if (closestJSDocComment) { let ambrosiaTagCount: number = 0; for (const jsDocNode of closestJSDocComment.getChildren()) { if ((jsDocNode.kind === TS.SyntaxKind.JSDocTag) && ((jsDocNode as TS.JSDocTag).tagName.escapedText === CODEGEN_TAG_NAME.substr(1))) { let jsDocTag: TS.JSDocTag = jsDocNode as TS.JSDocTag; let attrsString: string = ""; if (typeof jsDocTag.comment === "string") { attrsString = jsDocTag.comment; // The JSDocTag.comment is the text (if any) that comes after "@ambrosia" (the comment excludes '*' chars, but not NL chars) } if (jsDocTag.comment instanceof Array) { // Combine the JSDocText node(s) to create our attributes string const jsDocCommentNodes: TS.NodeArray<TS.Node> = jsDocTag.comment; // As of TypeScript 4.3.5, the only node types are JSDocText | TS.JSDocLink, but that may change in future attrsString = jsDocCommentNodes.filter(n => n.kind === TS.SyntaxKind.JSDocText).map(n => (n as TS.JSDocText).text.trim()).join(""); } let attrPairs: string[] = attrsString.split(",").map(p => p.trim()).filter(p => p.length > 0); let location: string = AST.getLocation(jsDocNode.pos); let jsDocCommentWithoutAmbrosiaTag: string = closestJSDocComment.getText().trim().split(Utils.NEW_LINE).filter(line => line.indexOf(CODEGEN_TAG_NAME) === -1).join(Utils.NEW_LINE); if (jsDocCommentWithoutAmbrosiaTag.endsWith("*/") && !jsDocCommentWithoutAmbrosiaTag.startsWith("/**")) { // This can happen when the closestJSDocComment is of the form: // /** @ambrosia publish=true // */ jsDocCommentWithoutAmbrosiaTag = "/**" + jsDocCommentWithoutAmbrosiaTag; } if (jsDocCommentWithoutAmbrosiaTag.startsWith("/**") && !jsDocCommentWithoutAmbrosiaTag.endsWith("*/")) { // This can happen when the closestJSDocComment is of the form: // /** // @ambrosia publish=true */ jsDocCommentWithoutAmbrosiaTag += " */"; } let jsDocComment: string = jsDocCommentWithoutAmbrosiaTag .replace(/[ ]\*[ /*\r\n]+\*\/$/g , " */") // Contract variants of " * */" endings to just " */" (but avoid contracting "/** */"") .replace(/[ ]+/g, " "); // Condense all space runs to a single space if (jsDocTag.comment && (typeof jsDocTag.comment === "string") && ((jsDocTag.comment.indexOf("\r") >= 0) || (jsDocTag.comment.indexOf("\n") >= 0))) { // We throw because we removed the '@ambrosia' line, so the [associated] line that follows it is now out of context throw new Error(`A newline is not allowed in the attributes of an ${CODEGEN_TAG_NAME} tag (at ${location})`); } if (++ambrosiaTagCount > 1) { throw new Error(`The ${CODEGEN_TAG_NAME} tag is defined more than once (at ${location})`); } // These are internal-only attributes (they aren't attributes set via the @ambrosia tag) attrs["hasAmbrosiaTag"] = true; attrs["location"] = location; attrs["JSDocComment"] = AST.formatJSDocComment(jsDocComment); for (const attrPair of attrPairs) { const parts: string[] = attrPair.split("=").map(p => p.trim()); if (parts.length === 2) { const name: string = parts[0]; // Eg. published, version, methodID, doRuntimeTypeChecking const value: string = parts[1]; if (AST._knownAttrs.indexOf(name) === -1) { throw new Error(`Unknown ${CODEGEN_TAG_NAME} attribute '${name}' at ${location}${(supportedAttrs.length > 0) ? `; valid attributes are: ${supportedAttrs.join(", ")}` : ""}`); } if ((supportedAttrs.length > 0) && (supportedAttrs.indexOf(name) === -1)) { throw new Error(`The ${CODEGEN_TAG_NAME} attribute '${name}' is invalid for a ${AST.getNodeKindName(declNode.kind)} (at ${location}); valid attributes are: ${supportedAttrs.join(", ")}`); } switch (name) { case "publish": checkBoolean(name, value); attrs[name] = (value === "true"); break; case "version": checkPositiveInteger(name, value); attrs[name] = parseInt(value); break; case "methodID": checkPositiveInteger(name, value); attrs[name] = parseInt(value); break; case "doRuntimeTypeChecking": checkBoolean(name, value); attrs[name] = (value === "true"); break; default: throw new Error(`Unsupported ${CODEGEN_TAG_NAME} attribute '${name}' at ${location}`); } } else { throw new Error(`Malformed ${CODEGEN_TAG_NAME} attribute '${attrPair}' at ${location}; expected format is: attrName=attrValue, ...`); } } } } } return (attrs); /** [Local function] Throws if the specified 'attrValue' is not a boolean. */ function checkBoolean(attrName: string, attrValue: string): void { if ((attrValue !== "true") && (attrValue !== "false")) { throw new Error(`The value ('${attrValue}') supplied for ${CODEGEN_TAG_NAME} attribute '${attrName}' is not a boolean (at ${attrs["location"]})`); } } /** [Local function] Throws if the specified 'attrValue' is not a positive integer. */ function checkPositiveInteger(attrName: string, attrValue: string): void { if (!RegExp(/^-?[0-9]+$/g).test(attrValue)) { throw new Error(`The value ('${attrValue}') supplied for ${CODEGEN_TAG_NAME} attribute '${attrName}' is not an integer (at ${attrs["location"]})`); } if (parseInt(attrValue) < 0) { throw new Error(`The value (${parseInt(attrValue)}) supplied for ${CODEGEN_TAG_NAME} attribute '${attrName}' cannot be negative (at ${attrs["location"]})`); } } } /** * Executes publishType() for an enum decorated with an @ambrosia JSDoc comment tag (eg. "@ambrosia publish=true").\ * Note: The enum cannot contain any expressions or computed values. */ private static publishEnum(enumDeclNode: TS.EnumDeclaration, nodeName: string, location: string, ambrosiaAttrs: AmbrosiaAttrs): string { try { if (enumDeclNode.members.length === 0) { throw new Error("The enum contains no values"); } // Note: Here we are extracting the names and MANUALLY computing the values of the enum (which the compiler would // normally do if we were using Utils.getEnumValues(), but which we can't use when statically processing the AST). let rawEnumValues: string[] = []; let enumValueNames: string[] = []; const childNodes: TS.Node[] = enumDeclNode.getChildren(); for (let i = 0; i < childNodes.length; i++) { if ((childNodes[i].kind === TS.SyntaxKind.OpenBraceToken) && (childNodes[i + 1].kind === TS.SyntaxKind.SyntaxList)) { const enumMembers: TS.EnumMember[] = childNodes[i + 1].getChildren().filter(n => n.kind === TS.SyntaxKind.EnumMember) as TS.EnumMember[]; for (let m = 0; m < enumMembers.length; m++) { const childNodes: TS.Node[] = enumMembers[m].getChildren(); rawEnumValues.push(''); // Assume no explicit value is assigned (for now) enumValueNames.push(enumMembers[m].name.getText()); for (let i = 0; i < childNodes.length; i++) { if (childNodes[i].kind === TS.SyntaxKind.EqualsToken) { rawEnumValues[m] = childNodes[i + 1].getText(); break; } } } } } let enumValues: number[] = [enumValueNames.length]; let lastValue: number = -1; for (let i = 0; i < rawEnumValues.length; i++) { if (rawEnumValues[i]) { if (!RegExp("^[+-]?[0-9]+$").test(rawEnumValues[i])) // We don't support computed enum values, like "1 + 2" or "'foo'.length" { throw new Error(`Unable to parse enum value '${enumValueNames[i]}' (${rawEnumValues[i]}); only integers are supported`); } else { enumValues[i] = lastValue = parseInt(rawEnumValues[i]); } } else { enumValues[i] = ++lastValue; } } let enumDefinition: string = enumValues.map((value, i) => `${value}=${enumValueNames[i]}`).join(","); // Matches the format returned by Utils.getEnumValues() [which we can't use during AST processing] let enumName: string = enumDeclNode.name.getText(); let jsDocComment: string = ambrosiaAttrs["JSDocComment"] as string; // The complete JSDoc comment containing the @ambrosia tag (sans the @ambrosia tag itself) let nsPath: string = AST.getNamespacePath(enumDeclNode); publishType(enumName, "number", enumDefinition, { nsPath: nsPath, nsComment: AST._namespaceJSDocComments[nsPath], jsDocComment: jsDocComment }); return ("type"); } catch (error: unknown) { throw new Error(`Unable to publish ${nodeName} (at ${location}) as a type (reason: ${Utils.makeError(error).message})`); } } /** Executes publishType() for a type alias decorated with an @ambrosia JSDoc comment tag (eg. "@ambrosia publish=true"). */ private static publishTypeAlias(typeAliasDeclNode: TS.TypeAliasDeclaration, nodeName: string, location: string, ambrosiaAttrs: AmbrosiaAttrs): string { try { let typeName: string = typeAliasDeclNode.name.getText(); let jsDocComment: string = ambrosiaAttrs["JSDocComment"] as string; // The complete JSDoc comment containing the @ambrosia tag (sans the @ambrosia tag itself) let nsPath: string = AST.getNamespacePath(typeAliasDeclNode); let tsType: TS.Type = AST._typeChecker.getTypeAtLocation(typeAliasDeclNode); let typeDefinition: string = ""; if (tsType.aliasTypeArguments || typeAliasDeclNode.typeParameters) { // Given the declaration "type PersonName<T extends string | number> = boolean | T;", tsType.aliasTypeArguments will return "T" let genericTypePlaceholderNames: string = ""; if (tsType.aliasTypeArguments) { genericTypePlaceholderNames = tsType.aliasTypeArguments.map(arg => arg.symbol.name).join("' and '"); } else { // Given the declaration "type misusedGeneric<T> = string;", tsType.aliasTypeArguments will be undefined, but typeAliasDeclNode.typeParameters will return "T" if (typeAliasDeclNode.typeParameters) { genericTypePlaceholderNames = typeAliasDeclNode.typeParameters.map(p => p.getText()).join("' and '"); } } throw new Error(`Generic type aliases are not supported; since the type of '${genericTypePlaceholderNames}' will not be known until runtime, ` + "Ambrosia cannot determine [at code-gen time] if the type(s) can be serialized"); } const childNodes: TS.Node[] = typeAliasDeclNode.getChildren(); for (let i = 0; i < childNodes.length; i++) { if (childNodes[i].kind === TS.SyntaxKind.EqualsToken) { typeDefinition = AST.buildTypeDefinition(childNodes[i + 1]); break; } } publishType(typeName, typeDefinition, undefined, { nsPath: nsPath, nsComment: AST._namespaceJSDocComments[nsPath], jsDocComment: jsDocComment }); return ("type"); } catch (error: unknown) { throw new Error(`Unable to publish ${nodeName} (at ${location}) as a type (reason: ${Utils.makeError(error).message})`); } } /** * Executes publishPostMethod() or publishMethod() for a function (or static method) decorated with an @ambrosia JSDoc comment tag (eg. "@ambrosia publish=true, version=3, doRuntimeTypeChecking=false").\ * Functions are assumed to be post method implementations unless the 'methodID' attribute is provided. The only required attribute is 'published'. */ private static publishFunction(functionDeclNode: TS.FunctionDeclaration | TS.MethodDeclaration, nodeName: string, location: string, ambrosiaAttrs: AmbrosiaAttrs): string { let methodName: string | undefined = functionDeclNode.name?.getText(); let methodParams: string[] = []; let returnType: string = "void"; let version: number = (ambrosiaAttrs["version"] || 1) as number; // Extracted from @ambrosia JSDoc tag let methodID: number = (ambrosiaAttrs["methodID"] || IC.POST_METHOD_ID) as number; // Extracted from @ambrosia JSDoc tag let doRuntimeTypeChecking: boolean = (ambrosiaAttrs["doRuntimeTypeChecking"] || true) as boolean; // Extracted from @ambrosia JSDoc tag let isPostMethod: boolean = (methodID === IC.POST_METHOD_ID); let isAsyncFunction: boolean = functionDeclNode.modifiers ? (functionDeclNode.modifiers.filter(m => m.kind === TS.SyntaxKind.AsyncKeyword).length === 1) : false; let isGenericFunction: boolean = false; let genericTypePlaceholderNames: string = ""; let isOverloadDeclaration: boolean = (functionDeclNode.body === undefined); let jsDocComment: string = ambrosiaAttrs["JSDocComment"] as string; // The complete JSDoc comment containing the @ambrosia tag (sans the @ambrosia tag itself) let nsPath: string = AST.getNamespacePath(functionDeclNode); if (functionDeclNode.typeParameters) { genericTypePlaceholderNames = functionDeclNode.typeParameters.map(p => p.getText()).join(", "); isGenericFunction = true; } if ((methodID !== IC.POST_METHOD_ID) && ambrosiaAttrs["doRuntimeTypeChecking"]) { // Only post methods provide a way (the postResultDispatcher) to communicate a type-mismatch back to the caller, so we don't support type checking for non-post methods throw new Error(`The 'doRuntimeTypeChecking' attribute only applies to a post method (ie. when a 'methodID' is not provided in the ${CODEGEN_TAG_NAME} tag) at ${ambrosiaAttrs["location"]}`); } try { if (!methodName) { throw new Error("The function has no name"); } if (isOverloadDeclaration) { throw new Error(`The ${CODEGEN_TAG_NAME} tag must appear on the implementation of an overloaded function`); } // Note: publish[Post]Method() - which runs later - would typically catch this, but as an "unpublished type" error and only if the // name of the generic type parameter (eg. "T") - which are aliases (placeholders), NOT actual type names - didn't match a // [non-primitive] native type name or published type. For example, "fn<Uint8Array>(p1: Uint8Array): void" would pass the // publish[Post]Method() checks (although only because we pass the method name as "fn", not "fn<Uint8Array>" which would error). // So we take advantage of the available AST information to report a much more accurate error here. if (isGenericFunction) { throw new Error(`Generic functions are not supported; since the type of '${genericTypePlaceholderNames}' will not be known until runtime, ` + "Ambrosia cannot determine [at code-gen time] if the type(s) can be serialized"); } // Get the parameters (if any) for (let i = 0; i < functionDeclNode.parameters.length; i++) { // Note: We replace a parameter that specifies a default value with an optional parameter [the function will behave the same when executed] const isOptionalParam: boolean = (functionDeclNode.parameters[i].questionToken !== undefined) || (functionDeclNode.parameters[i].initializer !== undefined); const isRestParam: boolean = (functionDeclNode.parameters[i].dotDotDotToken !== undefined); const paramName: string = (isRestParam ? "..." : "") + functionDeclNode.parameters[i].name.getText(); const paramType: string = functionDeclNode.parameters[i].type ? AST.buildTypeDefinition(assertDefined(functionDeclNode.parameters[i].type)) : "any"; // We use 'any' if the parameter type is not specified const param: string = `${paramName}${isOptionalParam ? "?:" : ":"}${paramType}`; if (!functionDeclNode.parameters[i].type && !AST._fileGenOptions.allowImplicitTypes) { throw new Error(`Implicit 'any' type not allowed for parameter '${paramName}'`) } methodParams.push(param); } // Get the return type (if any) returnType = functionDeclNode.type ? AST.buildTypeDefinition(functionDeclNode.type) : "void"; if (!functionDeclNode.type && !AST._fileGenOptions.allowImplicitTypes) { throw new Error("Implicit 'void' return type not allowed"); } if (isAsyncFunction) { // All message handling must be done synchronously throw new Error("async functions are not supported"); } if (!isPostMethod && (returnType !== "void")) { throw new Error("A non-post method can only have a return type of 'void'"); } if (isPostMethod) { publishPostMethod(methodName, version, methodParams, returnType, doRuntimeTypeChecking, { nsPath: nsPath, nsComment: AST._namespaceJSDocComments[nsPath], jsDocComment: jsDocComment }); return ("post method"); } else { publishMethod(methodID, methodName, methodParams, { nsPath: nsPath, nsComment: AST._namespaceJSDocComments[nsPath], jsDocComment: jsDocComment }); return ("non-post method"); } } catch (error: unknown) { throw new Error(`Unable to publish ${nodeName} (at ${location}) as a ${isPostMethod ? "post " : ""}method (reason: ${Utils.makeError(error).message})`); } } /** * Returns the text-only (and single-line) definition of a type.\ * startNode must be a TS.TypeNode and the method will throw if it's not. */ private static buildTypeDefinition(startNode: TS.Node): string { let typeDefinition: string = ""; if (!TS.isTypeNode(startNode)) { throw new Error(`The specified 'startNode' is a ${TS.SyntaxKind[startNode.kind]} when a TypeNode was expected`); } walkType(startNode); // Builds typeDefinition typeDefinition = trimTrailingComma(typeDefinition); return (typeDefinition); /** [Local function] Builds typeDefinition as it walks the type. */ function walkType(node: TS.Node): void { if (node.kind === TS.SyntaxKind.TypeLiteral) // A complex type { const childNodes: TS.Node[] = node.getChildren(); if ((childNodes[0].kind === TS.SyntaxKind.OpenBraceToken) && (childNodes[1].kind === TS.SyntaxKind.SyntaxList)) { const propertySignatures: TS.PropertySignature[] = childNodes[1].getChildren().filter(n => n.kind === TS.SyntaxKind.PropertySignature) as TS.PropertySignature[]; typeDefinition += "{"; for (let p = 0; p < propertySignatures.length; p++) { const childNodes: TS.Node[] = propertySignatures[p].getChildren(); const propertyName: string = propertySignatures[p].name.getText(); let propertyHasType: boolean = false; if (propertySignatures[p].questionToken) { throw new Error(`Property '${propertyName}' is optional; types with optional properties are not supported`); } typeDefinition += propertyName + ":"; for (let i = 0; i < childNodes.length; i++) { if (childNodes[i].kind === TS.SyntaxKind.ColonToken) { walkType(childNodes[i + 1]); propertyHasType = true; break; } } if (!propertyHasType) { if (!AST._fileGenOptions.allowImplicitTypes) { throw new Error(`Implicit 'any' type not allowed for property '${propertyName}'`) } typeDefinition += "any,"; } } typeDefinition = trimTrailingComma(typeDefinition) + "},"; } else { throw new Error(`Unexpected syntax on or after ${AST.getLocation(childNodes[0].getStart())}`); } } else { // Note: Instead of checking here for unsupported types (like TupleType and FunctionType), we let publishType() / publish[Post]Method() // do the type validation; this way the validation will always be the same no matter how we publish (manually or from source). // Note: The node could be an array of a complex type, in which case 'node.getText()' will return the complete complex type (plus the array suffix). Further, // since TypeScript allows the use of BOTH ';' and ',' as member separators, we normalize to only use ',' because this is what publishType() expects. typeDefinition += AST.removeWhiteSpaceAndComments(node.getText()).replace(/;/g, ",") + ","; } } /** [Local function] Returns the specified value with any trailing comma removed. */ function trimTrailingComma(value: string): string { return (Utils.trimTrailingChar(value, ",")); } } /** * Removes "excess" whitespace [including newlines], any inline [including multi-line] comments (eg. "/* Foo \*\/" or "/** Bar \*\/") and any comment lines (eg. "// Baz"). * This simplifies subsequent parsing. For example, this is needed when node.getText() is called on a complex or union type, and also to remove spaces in-and-around array suffixes. */ private static removeWhiteSpaceAndComments(value: string): string { const valueWithoutCommentLines: string = value.split(Utils.NEW_LINE).filter(line => !RegExp("^\/\/.+$").test(line.trim())).join(""); // Condense to a single line, eliminating any "//" comment lines const newValue: string = valueWithoutCommentLines.replace("[\t\r\n\f]+/g", "") // Remove newlines and tabs .replace(/[ ]+/g, " ") // Condense all space runs to a single space .replace(/([ ]+)(?=[\[\]])/g, "") // Remove all space before (or between) array suffix characters ([]) .replace(/\/\*.*?\*\//g, ""); // Remove "/*[*] */" comments return (newValue); } }
the_stack
import { inject, TestBed, waitForAsync } from '@angular/core/testing'; import { Overlay } from '@angular/cdk/overlay'; import { ModalGalleryService } from './modal-gallery.service'; import { ConfigService } from '../../services/config.service'; import { Image, ImageModalEvent } from '../../model/image.class'; import { ModalGalleryRef } from './modal-gallery-ref'; import { Action } from '../../model/action.enum'; import { KeyboardService } from '../../services/keyboard.service'; import { ButtonConfig, ButtonEvent, ButtonType } from '../../model/buttons-config.interface'; import { InternalLibImage } from '../../model/image-internal.class'; const IMAGES: Image[] = [ new Image(0, { // modal img: '../assets/images/gallery/img1.jpg', extUrl: 'http://www.google.com' }), new Image(1, { // modal img: '../assets/images/gallery/img2.png', description: 'Description 2' }), new Image( 2, { // modal img: '../assets/images/gallery/img3.jpg', description: 'Description 3', extUrl: 'http://www.google.com' }, { // plain img: '../assets/images/gallery/thumbs/img3.png', title: 'custom title 2', alt: 'custom alt 2', ariaLabel: 'arial label 2' } ), new Image(3, { // modal img: '../assets/images/gallery/img4.jpg', description: 'Description 4', extUrl: 'http://www.google.com' }), new Image( 4, { // modal img: '../assets/images/gallery/img5.jpg' }, { // plain img: '../assets/images/gallery/thumbs/img5.jpg' } ) ]; describe('ModalGalleryService', () => { beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ providers: [ { provide: ModalGalleryService, useClass: ModalGalleryService }, { provide: ConfigService, useClass: ConfigService }, { provide: Overlay, useClass: Overlay }, { provide: KeyboardService, useValue: jasmine.createSpyObj('KeyboardService', ['reset']) } ] }); }) ); it('should instantiate service when inject service', inject([ModalGalleryService], (service: ModalGalleryService) => { expect(service instanceof ModalGalleryService).toEqual(true); }) ); describe('#open()', () => { describe('---YES---', () => { it(`should call open and return a ModalGalleryRef instance`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ref: ModalGalleryRef | undefined = service.open({ id: 1, images: IMAGES, currentImage: IMAGES[0] }); expect(ref).toBeDefined(); expect(ref instanceof ModalGalleryRef).toBeTrue(); }) ); }); }); describe('#updateModalImages()', () => { it(`should call updateModalImages`, inject([ModalGalleryService], (service: ModalGalleryService) => { service.updateImages$.subscribe((images: Image[]) => { expect(images).toEqual(IMAGES); }); service.updateModalImages(IMAGES); }) ); }); describe('#emitClose()', () => { describe('---YES---', () => { it(`should call close with clickOutside=false`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const ref: ModalGalleryRef | undefined = service.open({ id: ID, images: IMAGES, currentImage: IMAGES[0] }); expect(ref).toBeDefined(); expect(ref instanceof ModalGalleryRef).toBeTrue(); // the close service.close(ID, false); }) ); it(`should call close with clickOutside=true`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const ref: ModalGalleryRef | undefined = service.open({ id: ID, images: IMAGES, currentImage: IMAGES[0] }); expect(ref).toBeDefined(); expect(ref instanceof ModalGalleryRef).toBeTrue(); // the close service.close(ID, true); }) ); }); describe('---NO---', () => { it(`should call close without calling open before with clickOutside=false`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; // the close service.close(ID, false); }) ); // aggiungere caso clickOutside e libConfig.enableCloseOutside it(`should call close without calling open before with clickOutside=true`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; // the close service.close(ID, true); }) ); }); }); describe('#emitClose()', () => { describe('---YES---', () => { it(`should call emitClose`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ImageModalEvent = new ImageModalEvent(ID, Action.NORMAL, true); const ref: ModalGalleryRef | undefined = service.open({ id: ID, images: IMAGES, currentImage: IMAGES[0] }); expect(ref).toBeDefined(); expect(ref instanceof ModalGalleryRef).toBeTrue(); (ref as ModalGalleryRef).close$.subscribe((event: ImageModalEvent) => { expect(EVENT).toEqual(event); }); service.emitClose(EVENT); }) ); }); describe('---NO---', () => { it(`shouldn't call emitClose because gallery is closed`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ImageModalEvent = new ImageModalEvent(ID, Action.NORMAL, true); // don't trigger event service.emitClose(EVENT); }) ); }); }); describe('#emitShow()', () => { describe('---YES---', () => { it(`should call emitShow`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ImageModalEvent = new ImageModalEvent(ID, Action.NORMAL, true); const ref: ModalGalleryRef | undefined = service.open({ id: ID, images: IMAGES, currentImage: IMAGES[0] }); expect(ref).toBeDefined(); expect(ref instanceof ModalGalleryRef).toBeTrue(); (ref as ModalGalleryRef).show$.subscribe((event: ImageModalEvent) => { expect(EVENT).toEqual(event); }); service.emitShow(EVENT); }) ); }); describe('---NO---', () => { it(`shouldn't call emitShow because gallery is closed`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ImageModalEvent = new ImageModalEvent(ID, Action.NORMAL, true); // don't trigger event service.emitShow(EVENT); }) ); }); }); describe('#emitFirstImage()', () => { describe('---YES---', () => { it(`should call emitFirstImage`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ImageModalEvent = new ImageModalEvent(ID, Action.NORMAL, true); const ref: ModalGalleryRef | undefined = service.open({ id: ID, images: IMAGES, currentImage: IMAGES[0] }); expect(ref).toBeDefined(); expect(ref instanceof ModalGalleryRef).toBeTrue(); (ref as ModalGalleryRef).firstImage$.subscribe((event: ImageModalEvent) => { expect(EVENT).toEqual(event); }); service.emitFirstImage(EVENT); }) ); }); describe('---NO---', () => { it(`shouldn't call emitFirstImage because gallery is closed`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ImageModalEvent = new ImageModalEvent(ID, Action.NORMAL, true); // don't trigger event service.emitFirstImage(EVENT); }) ); }); }); describe('#emitLastImage()', () => { describe('---YES---', () => { it(`should call emitLastImage`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ImageModalEvent = new ImageModalEvent(ID, Action.NORMAL, true); const ref: ModalGalleryRef | undefined = service.open({ id: ID, images: IMAGES, currentImage: IMAGES[0] }); expect(ref).toBeDefined(); expect(ref instanceof ModalGalleryRef).toBeTrue(); (ref as ModalGalleryRef).lastImage$.subscribe((event: ImageModalEvent) => { expect(EVENT).toEqual(event); }); service.emitLastImage(EVENT); }) ); }); describe('---NO---', () => { it(`shouldn't call emitLastImage because gallery is closed`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ImageModalEvent = new ImageModalEvent(ID, Action.NORMAL, true); // don't trigger event service.emitLastImage(EVENT); }) ); }); }); describe('#emitHasData()', () => { describe('---YES---', () => { it(`should call emitHasData`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ImageModalEvent = new ImageModalEvent(ID, Action.NORMAL, true); const ref: ModalGalleryRef | undefined = service.open({ id: ID, images: IMAGES, currentImage: IMAGES[0] }); expect(ref).toBeDefined(); expect(ref instanceof ModalGalleryRef).toBeTrue(); (ref as ModalGalleryRef).hasData$.subscribe((event: ImageModalEvent) => { expect(EVENT).toEqual(event); }); service.emitHasData(EVENT); }) ); }); describe('---NO---', () => { it(`shouldn't call emitHasData because gallery is closed`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ImageModalEvent = new ImageModalEvent(ID, Action.NORMAL, true); // don't trigger event service.emitHasData(EVENT); }) ); }); }); describe('#emitButtonBeforeHook()', () => { describe('---YES---', () => { it(`should call emitButtonBeforeHook`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ButtonEvent = { button: { type: ButtonType.CLOSE } as ButtonConfig, image: IMAGES[ID] as InternalLibImage, action: Action.NORMAL, galleryId: ID }; const ref: ModalGalleryRef | undefined = service.open({ id: ID, images: IMAGES, currentImage: IMAGES[0] }); expect(ref).toBeDefined(); expect(ref instanceof ModalGalleryRef).toBeTrue(); (ref as ModalGalleryRef).buttonBeforeHook$.subscribe((event: ButtonEvent) => { expect(EVENT).toEqual(event); }); service.emitButtonBeforeHook(EVENT); }) ); }); describe('---NO---', () => { it(`shouldn't call emitButtonBeforeHook because gallery is closed`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ButtonEvent = { button: { type: ButtonType.CLOSE } as ButtonConfig, image: IMAGES[ID] as InternalLibImage, action: Action.NORMAL, galleryId: ID }; // don't trigger event service.emitButtonBeforeHook(EVENT); }) ); }); }); describe('#emitButtonAfterHook()', () => { describe('---YES---', () => { it(`should call emitButtonAfterHook`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ButtonEvent = { button: { type: ButtonType.CLOSE } as ButtonConfig, image: IMAGES[ID] as InternalLibImage, action: Action.NORMAL, galleryId: ID }; const ref: ModalGalleryRef | undefined = service.open({ id: ID, images: IMAGES, currentImage: IMAGES[0] }); expect(ref).toBeDefined(); expect(ref instanceof ModalGalleryRef).toBeTrue(); (ref as ModalGalleryRef).buttonAfterHook$.subscribe((event: ButtonEvent) => { expect(EVENT).toEqual(event); }); service.emitButtonAfterHook(EVENT); }) ); }); describe('---NO---', () => { it(`shouldn't call emitButtonAfterHook because gallery is closed`, inject([ModalGalleryService], (service: ModalGalleryService) => { const ID: number = 1; const EVENT: ButtonEvent = { button: { type: ButtonType.CLOSE } as ButtonConfig, image: IMAGES[ID] as InternalLibImage, action: Action.NORMAL, galleryId: ID }; // don't trigger event service.emitButtonAfterHook(EVENT); }) ); }); }); });
the_stack
import * as React from 'react'; import { IEditCategoriesProps } from './IEditCategoriesProps'; import { IEditCategoriesState } from './IEditCategoriesState'; import { IPlannerPlanExtended } from '../../services/IPlannerPlanExtended'; import { IPlannerPlanDetails } from '../../services/IPlannerPlanDetails'; import { Stack, Checkbox, MessageBar, MessageBarType, IconButton } from 'office-ui-fabric-react'; import { IAppliedCategories } from '../../services/IAppliedCategories'; import { getTheme } from '@uifabric/styling'; import { textFieldSearchStyles } from '../UploadFile/UploadStyles'; import * as tsStyles from './EditCategoriesStyles'; const categoriesColors = { category1: '#e000f1', category2: '#f44b1d', category3: '#e39e27', category4: '#aee01e', category5: '#46A08E', category6: '#62cef0' }; export class EditCategories extends React.Component<IEditCategoriesProps, IEditCategoriesState> { private _plannerPlanDetails: IPlannerPlanDetails; private _appliedCategoryKeys: IAppliedCategories = {}; constructor(props: IEditCategoriesProps) { super(props); this.state = { task: this.props.task, appliedCategories: [] as JSX.Element[], hasError: false, errorMessage: '', category1Value: this.props.task.appliedCategories["category1"], category2Value: this.props.task.appliedCategories["category2"], category3Value: this.props.task.appliedCategories["category3"], category4Value: this.props.task.appliedCategories["category4"], category5Value: this.props.task.appliedCategories["category5"], category6Value: this.props.task.appliedCategories["category6"], plannerDetails : {} as IPlannerPlanDetails, }; } public async componentWillMount(): Promise<void> { this._appliedCategoryKeys = this.props.task.appliedCategories; this._plannerPlanDetails = await this.props.spservice.getPlanDetails(this.props.task.planId); // const allCategoriesKeys = Object.keys(categoriesColors); // const appliedCategories: JSX.Element[] = []; let categoriesCheched: {[key:string]: boolean} = {}; this.setState({ plannerDetails: this._plannerPlanDetails}); } public async componentDidUpdate(prevProps: IEditCategoriesProps, prevState: IEditCategoriesState): Promise<void> { if (!this._plannerPlanDetails){ this._plannerPlanDetails = await this.props.spservice.getPlanDetails(this.props.task.planId); } } /** * Determines whether check box category changed on */ private _onCheckBoxCategory1Changed = async (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean) => { ev.preventDefault(); try { this._appliedCategoryKeys["category1"] = checked; const updatedTask = await this.props.spservice.updateTaskProperty( this.state.task.id, 'appliedCategories', this._appliedCategoryKeys, this.state.task['@odata.etag'] ); this.setState({task: updatedTask , category1Value: checked}); } catch (error) { this.setState({ hasError: true, errorMessage: error.message }); } }; private _onCheckBoxCategory2Changed = async (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean) => { ev.preventDefault(); try { this._appliedCategoryKeys["category2"] = checked; const updatedTask = await this.props.spservice.updateTaskProperty( this.state.task.id, 'appliedCategories', this._appliedCategoryKeys, this.state.task['@odata.etag'] ); this.setState({task: updatedTask , category2Value: checked}); } catch (error) { this.setState({ hasError: true, errorMessage: error.message }); } }; private _onCheckBoxCategory3Changed = async (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean) => { ev.preventDefault(); try { this._appliedCategoryKeys["category3"] = checked; const updatedTask = await this.props.spservice.updateTaskProperty( this.state.task.id, 'appliedCategories', this._appliedCategoryKeys, this.state.task['@odata.etag'] ); this.setState({task: updatedTask , category3Value: checked}); } catch (error) { this.setState({ hasError: true, errorMessage: error.message }); } }; private _onCheckBoxCategory5Changed = async (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean) => { ev.preventDefault(); try { this._appliedCategoryKeys["category5"] = checked; const updatedTask = await this.props.spservice.updateTaskProperty( this.state.task.id, 'appliedCategories', this._appliedCategoryKeys, this.state.task['@odata.etag'] ); this.setState({task: updatedTask , category5Value: checked}); } catch (error) { this.setState({ hasError: true, errorMessage: error.message }); } }; private _onCheckBoxCategory6Changed = async (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean) => { ev.preventDefault(); try { this._appliedCategoryKeys["category6"] = checked; const updatedTask = await this.props.spservice.updateTaskProperty( this.state.task.id, 'appliedCategories', this._appliedCategoryKeys, this.state.task['@odata.etag'] ); this.setState({task: updatedTask , category6Value: checked}); } catch (error) { this.setState({ hasError: true, errorMessage: error.message }); } }; private _onCheckBoxCategory4Changed = async (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean) => { ev.preventDefault(); try { this._appliedCategoryKeys["category4"] = checked; const updatedTask = await this.props.spservice.updateTaskProperty( this.state.task.id, 'appliedCategories', this._appliedCategoryKeys, this.state.task['@odata.etag'] ); this.setState({task: updatedTask , category4Value: checked}); } catch (error) { this.setState({ hasError: true, errorMessage: error.message }); } }; /** * Renders edit categories * @returns render */ public render(): React.ReactElement<IEditCategoriesProps> { return ( <div> <Stack horizontal horizontalAlign='start' gap={10}> {this.state.hasError ? ( <MessageBar messageBarType={MessageBarType.error}>{this.state.errorMessage}</MessageBar> ) : ( <> <div title={ this.state.plannerDetails && this.state.plannerDetails.categoryDescriptions ? this.state.plannerDetails.categoryDescriptions["category1"] : '' }> <Checkbox onChange={this._onCheckBoxCategory1Changed} checked={ this.state.category1Value} styles={{ ...tsStyles.checkboxStyles, label: { selectors: { [':hover .ms-Checkbox-checkbox']: { background: categoriesColors["category1"] } } }, checkbox: { selectors: { [':hover']: { backgroundColor: 'rgba(0, 0, 0, 0.2)' } }, width: 90, height: 25, borderStyle: 'none', marginRight: 0, background: categoriesColors["category1"] } }}> </Checkbox> </div> <div title={ this.state.plannerDetails && this.state.plannerDetails.categoryDescriptions ? this.state.plannerDetails.categoryDescriptions["category2"] : '' }> <Checkbox onChange={this._onCheckBoxCategory2Changed} checked={ this.state.category2Value} styles={{ ...tsStyles.checkboxStyles, label: { selectors: { [':hover .ms-Checkbox-checkbox']: { background: categoriesColors["category2"] } } }, checkbox: { selectors: { [':hover']: { backgroundColor: 'rgba(0, 0, 0, 0.2)' } }, width: 90, height: 25, borderStyle: 'none', marginRight: 0, background: categoriesColors["category2"] } }}> </Checkbox> </div> <div title={ this.state.plannerDetails && this.state.plannerDetails.categoryDescriptions ? this.state.plannerDetails.categoryDescriptions["category3"] : '' }> <Checkbox onChange={this._onCheckBoxCategory3Changed} checked={ this.state.category3Value} styles={{ ...tsStyles.checkboxStyles, label: { selectors: { [':hover .ms-Checkbox-checkbox']: { background: categoriesColors["category3"] } } }, checkbox: { selectors: { [':hover']: { backgroundColor: 'rgba(0, 0, 0, 0.2)' } }, width: 90, height: 25, borderStyle: 'none', marginRight: 0, background: categoriesColors["category3"] } }}> </Checkbox> </div> <div title={ this.state.plannerDetails && this.state.plannerDetails.categoryDescriptions ? this.state.plannerDetails.categoryDescriptions["category4"] : '' }> <Checkbox onChange={this._onCheckBoxCategory4Changed} checked={ this.state.category4Value} styles={{ ...tsStyles.checkboxStyles, label: { selectors: { [':hover .ms-Checkbox-checkbox']: { background: categoriesColors["category4"] } } }, checkbox: { selectors: { [':hover']: { backgroundColor: 'rgba(0, 0, 0, 0.2)' } }, width: 90, height: 25, borderStyle: 'none', marginRight: 0, background: categoriesColors["category4"] } }}> </Checkbox> </div> <div title={ this.state.plannerDetails && this.state.plannerDetails.categoryDescriptions ? this.state.plannerDetails.categoryDescriptions["category5"] : '' }> <Checkbox onChange={this._onCheckBoxCategory5Changed} checked={ this.state.category5Value} styles={{ ...tsStyles.checkboxStyles, label: { selectors: { [':hover .ms-Checkbox-checkbox']: { background: categoriesColors["category5"] } } }, checkbox: { selectors: { [':hover']: { backgroundColor: 'rgba(0, 0, 0, 0.2)' } }, width: 90, height: 25, borderStyle: 'none', marginRight: 0, background: categoriesColors["category5"] } }}> </Checkbox> </div > <div title={ this.state.plannerDetails && this.state.plannerDetails.categoryDescriptions ? this.state.plannerDetails.categoryDescriptions["category6"] : '' }> <Checkbox onChange={this._onCheckBoxCategory6Changed} checked={ this.state.category6Value} styles={{ ...tsStyles.checkboxStyles, label: { selectors: { [':hover .ms-Checkbox-checkbox']: { background: categoriesColors["category6"] } } }, checkbox: { selectors: { [':hover']: { backgroundColor: 'rgba(0, 0, 0, 0.2)' } }, width: 90, height: 25, borderStyle: 'none', marginRight: 0, background: categoriesColors["category6"] } }}> </Checkbox> </div> </> )} </Stack> </div> ); } }
the_stack
import { IResult } from "./IResult"; import { IResultAlternate } from "./IResultAlternate"; import { IScoreIntent } from "./IScoreIntent"; import { IScoreLabel } from "./IScoreLabel"; import { IScoreLabelByPosition } from "./IScoreLabelByPosition"; import { IScoreEntity } from "./IScoreEntity"; import { IScoreEntityByPosition } from "./IScoreEntityByPosition"; import { Label } from "./Label"; import { LabelType } from "./LabelType"; import { Utility } from "../utility/Utility"; export class Result { public static utilityRound(score: number, digits: number): number { return score; // ---- NOTE ---- default logic per request for see the original, raw score that is not rounded. // ---- NOTE-FOR-REFERENCE-ALTERNATIVE-PLACE-HOLDER ---- return Utility.round(score, digits); } public label: Label; public score: number; public closesttext: string; constructor(label: Label, score: number, closesttext: string) { this.label = label; this.score = score; this.closesttext = closesttext; } public equals(other: Result): boolean { if (other) { if (this.label) { if (!this.label.equals(other.label)) { return false; } } else { if (other.label) { return false; } } if (other.score !== this.score) { return false; } if (other.closesttext !== this.closesttext) { return false; } return true; } return false; } public toObject(): IResult { return { label: this.label.toObject(), score: this.score, closesttext: this.closesttext, }; } public toObjectFormatted(toObfuscate: boolean = false, digits: number = 10000): IResult { if (toObfuscate) { return this.toObfuscatedObjectFormatted(digits); } return this.toSimpleObjectFormatted(digits); } public toSimpleObjectFormatted(digits: number = 10000): IResult { return { label: this.label.toObject(), score: Result.utilityRound(this.score, digits), closesttext: this.closesttext, }; } public toObfuscatedObjectFormatted(digits: number = 10000): IResult { return { label: this.label.toObfuscatedObject(), score: Result.utilityRound(this.score, digits), closesttext: Utility.obfuscateString(this.closesttext), }; } public toAlternateObject(): IResultAlternate { return { label: this.label.toAlternateObject(), score: this.score, closest_text: this.closesttext, }; } public toAlternateObjectFormatted(toObfuscate: boolean = false, digits: number = 10000): IResultAlternate { if (toObfuscate) { return this.toObfuscatedAlternateObjectFormatted(digits); } return this.toSimpleAlternateObjectFormatted(digits); } public toSimpleAlternateObjectFormatted(digits: number = 10000): IResultAlternate { return { label: this.label.toAlternateObject(), score: Result.utilityRound(this.score, digits), closest_text: this.closesttext, }; } public toObfuscatedAlternateObjectFormatted(digits: number = 10000): IResultAlternate { return { label: this.label.toObfuscatedAlternateObject(), score: Result.utilityRound(this.score, digits), closest_text: Utility.obfuscateString(this.closesttext), }; } public toScoreLabelObject(): IScoreLabel { return { label: this.label.name, offset: this.label.span.offset, length: this.label.span.length, score: this.score, }; } public toScoreLabelObjectFormatted(toObfuscate: boolean = false, digits: number = 10000): IScoreLabel { if (toObfuscate) { return this.toObfuscatedScoreLabelObjectFormatted(digits); } return this.toSimpleScoreLabelObjectFormatted(digits); } public toSimpleScoreLabelObjectFormatted(digits: number = 10000): IScoreLabel { return { label: this.label.name, offset: this.label.span.offset, length: this.label.span.length, score: Result.utilityRound(this.score, digits), }; } public toObfuscatedScoreLabelObjectFormatted(digits: number = 10000): IScoreLabel { return { label: Utility.obfuscateString(this.label.name), offset: Utility.obfuscateNumber(this.label.span.offset), length: Utility.obfuscateNumber(this.label.span.length), score: Result.utilityRound(this.score, digits), }; } public toScoreLabelObjectByPosition(): IScoreLabelByPosition { return { label: this.label.name, startPos: this.label.span.offset, endPos: (this.label.span.offset + this.label.span.length - 1), score: this.score, }; } public toScoreLabelObjectByPositionFormatted( toObfuscate: boolean = false, digits: number = 10000): IScoreLabelByPosition { if (toObfuscate) { return this.toObfuscatedScoreLabelObjectByPositionFormatted(digits); } return this.toSimpleScoreLabelObjectByPositionFormatted(digits); } public toSimpleScoreLabelObjectByPositionFormatted(digits: number = 10000): IScoreLabelByPosition { return { label: this.label.name, startPos: this.label.span.offset, endPos: (this.label.span.offset + this.label.span.length - 1), score: Result.utilityRound(this.score, digits), }; } public toObfuscatedScoreLabelObjectByPositionFormatted(digits: number = 10000): IScoreLabelByPosition { return { label: Utility.obfuscateString(this.label.name), startPos: Utility.obfuscateNumber(this.label.span.offset), endPos: Utility.obfuscateNumber(this.label.span.offset + this.label.span.length - 1), score: Result.utilityRound(this.score, digits), }; } public toScoreEntityObject(): IScoreEntity { if (this.label.labeltype !== LabelType.Entity) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Entity|${LabelType.Entity}|`); } return { entity: this.label.name, offset: this.label.span.offset, length: this.label.span.length, score: this.score, }; } public toScoreEntityObjectFormatted(toObfuscate: boolean = false, digits: number = 10000): IScoreEntity { if (this.label.labeltype !== LabelType.Entity) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Entity|${LabelType.Entity}|`); } if (toObfuscate) { return this.toObfuscatedScoreEntityObjectFormatted(digits); } return this.toSimpleScoreEntityObjectFormatted(digits); } public toSimpleScoreEntityObjectFormatted(digits: number = 10000): IScoreEntity { if (this.label.labeltype !== LabelType.Entity) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Entity|${LabelType.Entity}|`); } return { entity: this.label.name, offset: this.label.span.offset, length: this.label.span.length, score: Result.utilityRound(this.score, digits), }; } public toObfuscatedScoreEntityObjectFormatted(digits: number = 10000): IScoreEntity { if (this.label.labeltype !== LabelType.Entity) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Entity|${LabelType.Entity}|`); } return { entity: Utility.obfuscateString(this.label.name), offset: Utility.obfuscateNumber(this.label.span.offset), length: Utility.obfuscateNumber(this.label.span.length), score: Result.utilityRound(this.score, digits), }; } public toScoreEntityObjectByPosition(): IScoreEntityByPosition { if (this.label.labeltype !== LabelType.Entity) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Entity|${LabelType.Entity}|`); } return { entity: this.label.name, startPos: this.label.span.offset, endPos: (this.label.span.offset + this.label.span.length - 1), score: this.score, }; } public toScoreEntityObjectByPositionFormatted( toObfuscate: boolean = false, digits: number = 10000): IScoreEntityByPosition { if (this.label.labeltype !== LabelType.Entity) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Entity|${LabelType.Entity}|`); } if (toObfuscate) { return this.toObfuscatedScoreEntityObjectByPositionFormatted(digits); } return this.toSimpleScoreEntityObjectByPositionFormatted(digits); } public toSimpleScoreEntityObjectByPositionFormatted(digits: number = 10000): IScoreEntityByPosition { if (this.label.labeltype !== LabelType.Entity) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Entity|${LabelType.Entity}|`); } return { entity: this.label.name, startPos: this.label.span.offset, endPos: (this.label.span.offset + this.label.span.length - 1), score: Result.utilityRound(this.score, digits), }; } public toObfuscatedScoreEntityObjectByPositionFormatted(digits: number = 10000): IScoreEntityByPosition { if (this.label.labeltype !== LabelType.Entity) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Entity|${LabelType.Entity}|`); } return { entity: Utility.obfuscateString(this.label.name), startPos: Utility.obfuscateNumber(this.label.span.offset), endPos: Utility.obfuscateNumber(this.label.span.offset + this.label.span.length - 1), score: Result.utilityRound(this.score, digits), }; } public toScoreIntentObject(): IScoreIntent { if (this.label.labeltype !== LabelType.Intent) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Intent|${LabelType.Intent}|`); } return { intent: this.label.name, score: this.score, }; } public toScoreIntentObjectFormatted(toObfuscate: boolean = false, digits: number = 10000): IScoreIntent { if (this.label.labeltype !== LabelType.Intent) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Intent|${LabelType.Intent}|`); } if (toObfuscate) { return this.toObfuscatedScoreIntentObjectFormatted(digits); } return this.toSimpleScoreIntentObjectFormatted(digits); } public toSimpleScoreIntentObjectFormatted(digits: number = 10000): IScoreIntent { if (this.label.labeltype !== LabelType.Intent) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Intent|${LabelType.Intent}|`); } return { intent: this.label.name, score: Result.utilityRound(this.score, digits), }; } public toObfuscatedScoreIntentObjectFormatted(digits: number = 10000): IScoreIntent { if (this.label.labeltype !== LabelType.Intent) { Utility.debuggingThrow(`this.label.labeltype|${this.label.labeltype}| !== LabelType.Intent|${LabelType.Intent}|`); } return { intent: Utility.obfuscateString(this.label.name), score: Result.utilityRound(this.score, digits), }; } }
the_stack
import { Button, Icon, Progress } from 'antd'; import axios from 'axios'; import * as chatito from 'chatito'; import * as webAdapter from 'chatito/dist/adapters/web'; import * as utils from 'chatito/dist/utils'; import { saveAs } from 'file-saver'; import { withPrefix } from 'gatsby-link'; import { debounce } from 'lodash'; import * as React from 'react'; import englishTokenizer from '../../../src/languages/en/EnglishTokenizer'; import { IDatasetParams, IPretrainedDictionary, ITestingParams, ITrainingParams } from '../../../src/types'; import { dictionariesFromDataset } from '../../../src/utils/dictionaryUtils'; import { ITrainingDashboardProps } from '../TrainingDashboard'; import { chatitoPrism, IEditorTabs } from './editorConfig'; import * as es from './editorStyles'; interface IEditorProps { tabs: IEditorTabs[]; children: (p: ITrainingDashboardProps) => any; } interface IEditorState { error: null | string; warning: null | string; activeTabIndex: number; trainingDataset: webAdapter.IDefaultDataset; testingDataset: webAdapter.IDefaultDataset; showDrawer: boolean; generating: boolean; isDownloading: boolean; downloadProgress: number; datasetParams?: IDatasetParams; trainingParams?: ITrainingParams; testingParams?: ITestingParams; embeddingsAndTrainingDatasetLoaded?: boolean; ngramToIdDictionary?: IPretrainedDictionary['NGRAM_TO_ID_MAP']; pretrainedNGramVectors?: IPretrainedDictionary['PRETRAINED']; datasetStats?: Array<{ intent: string; training: number; testing: number }>; } // NOTE: for SSR, wrap the require in check for window (since it's pre rendered by gatsbyjs) let CodeFlask: any = null; let ReactJson: any = null; if (typeof window !== `undefined`) { // tslint:disable-next-line:no-var-requires CodeFlask = require('codeflask').default; // tslint:disable-next-line:no-var-requires ReactJson = require('react-json-view').default; } export default class Editor extends React.Component<IEditorProps, IEditorState> { public state: IEditorState = { activeTabIndex: 0, downloadProgress: 0, error: null, generating: false, isDownloading: false, showDrawer: false, testingDataset: {}, trainingDataset: {}, warning: null }; private tabsContainer = React.createRef() as React.RefObject<HTMLDivElement>; private codeflask: any = null; private editorUpdatesSetupCount = 0; private codeInputValue = ''; private tabs: IEditorTabs[] = []; private debouncedTabDSLValidation = debounce(() => { if (!this.codeInputValue.length) { if (this.state.error || this.state.warning) { this.setState({ error: null, warning: null }); } return; } const validation = this.getDSLValidation(this.codeInputValue); let newState = {}; if (validation && validation.error) { newState = { error: validation.error, warning: null }; } else if (validation && validation.warning) { newState = { error: null, warning: validation.warning }; } else { newState = { error: null, warning: null }; } this.setState(newState, () => { this.saveToLocalStorage(); }); }, 300); public componentWillMount() { this.loadFromLocalStorage(); } public componentDidMount() { if (typeof window === `undefined` || !CodeFlask) { return; } const flask = new CodeFlask('#my-code-editor', { language: 'chatito', lineNumbers: true }); flask.addLanguage('chatito', chatitoPrism); if (this.tabs && this.tabs[this.state.activeTabIndex]) { flask.updateCode(this.tabs[this.state.activeTabIndex].value); } flask.onUpdate((code: string) => { if (!this.tabs || !this.tabs[this.state.activeTabIndex]) { return; } this.codeInputValue = code; this.tabs[this.state.activeTabIndex].value = code; // NOTE: ugly hack to know when codeflask is mounted (it makes 2 calls to update on mount) if (this.editorUpdatesSetupCount < 2) { this.editorUpdatesSetupCount++; } else { this.setState({ trainingDataset: {}, testingDataset: {} }); this.debouncedTabDSLValidation(); } }); flask.setLineNumber(); this.codeflask = flask; } public render() { const s = this.state; if ( !s.generating && !s.isDownloading && s.embeddingsAndTrainingDatasetLoaded && s.datasetParams && s.trainingParams && s.testingParams && s.datasetStats && this.props.children && s.ngramToIdDictionary && s.pretrainedNGramVectors ) { return this.props.children({ datasetParams: s.datasetParams, datasetStats: s.datasetStats, ngramToIdDictionary: s.ngramToIdDictionary, pretrainedNGramVectors: s.pretrainedNGramVectors, testDataset: s.testingParams, trainDataset: s.trainingParams }); } const alertState = !!s.error ? 'error' : !!s.warning ? 'warning' : 'success'; const loading = s.generating ? <Icon type="loading" theme="outlined" /> : null; const onClickDrawer = (e: MouseEvent) => e.stopPropagation(); return ( <div> <h2>Train a custom assistant</h2> <p> <a href="https://github.com/rodrigopivi/Chatito/blob/master/spec.md" target="_blank" title="Chatito DSL docs"> Chatito </a> &nbsp; is a language that helps create and maintain datasets. You can improve and customize the assistant accuracy and knowledge by extending intents, slots and sentences to build a cloud of possible combinations and only pull the examples needed. Click 'Generate dataset' to continue. </p> <es.EditorWrapper> <es.EditorHeader style={{ display: 'block', textAlign: 'right', padding: 16 }}> <Button onClick={this.onAddFile} style={{ marginRight: 32 }} type="dashed"> <Icon type="plus" theme="outlined" /> Add new file </Button> <Button type="primary" onClick={this.onToggleDrawer} disabled={!!s.error}> <Icon type="play-circle" theme="outlined" /> Generate dataset </Button> </es.EditorHeader> <es.EditorHeader> <es.TabsArea innerRef={this.tabsContainer}>{this.tabs.map(this.renderTabButton)}</es.TabsArea> </es.EditorHeader> <es.CodeStyles id="my-code-editor" /> <es.AlertNotification state={alertState}> {s.error || s.warning || `Correct syntax!`}</es.AlertNotification> <es.EditorOverlay onClick={this.onCloseDrawer} showDrawer={s.showDrawer || s.generating}> {loading} <es.Drawer onClick={onClickDrawer} showDrawer={s.showDrawer}> <Icon type="close" theme="outlined" onClick={this.onCloseDrawer} /> {this.renderDatasetPreviewer()} </es.Drawer> </es.EditorOverlay> </es.EditorWrapper> </div> ); } /* ================== Renderers ================== */ private renderDatasetPreviewer = () => { if (!ReactJson) { return null; } return [ <div style={{ padding: '20px 20px 0 20px', textAlign: 'center' }} key="top_drawer"> <Progress type="circle" percent={this.state.downloadProgress} style={{ marginBottom: 20, marginLeft: 30 }} /> <br /> <Button type="primary" onClick={this.trainTestAndSaveModels} disabled={this.state.isDownloading}> <Icon type="play-circle" theme="outlined" /> Start training! </Button> <es.StrokeText> Will download the embeddings dictionary (about 1mb) then train and test the models with your dataset. This process may take some time to complete depending on your hardware, please don't change the browser tab. </es.StrokeText> </div>, <es.BlockWrapper key="bottom_drawer"> <es.BlockWrapperTitle>Review the generated training dataset:</es.BlockWrapperTitle> <ReactJson style={{ padding: 20 }} src={this.state.trainingDataset} theme="chalk" iconStyle="square" enableClipboard={false} displayDataTypes={false} name={false} collapsed={1} /> </es.BlockWrapper> ]; }; private renderTabButton = (t: IEditorTabs, i: number) => { const changeTab = () => this.changeTab(i); const onCloseTab = this.closerTab(i); return ( <es.TabButton active={this.state.activeTabIndex === i} key={`tab-${i}`} onClick={changeTab}> {t.title} <Icon type="close" theme="outlined" onClick={onCloseTab} /> </es.TabButton> ); }; /* ================== Event Handlers ================== */ private onCloseDrawer = () => { this.setState({ showDrawer: false, trainingDataset: {}, testingDataset: {} }); }; private onAddFile = () => { let filename = 'newFile'; if (typeof window !== 'undefined' && window.prompt) { filename = prompt('Please enter the new .chatito file name:', filename) || ''; } if (filename) { this.tabs.push({ title: `${filename}.chatito`, value: '' }); this.changeTab(this.tabs.length - 1, () => { if (!this.tabsContainer || !this.tabsContainer.current) { return; } this.tabsContainer.current.scrollTo({ behavior: 'smooth', left: this.tabsContainer.current.scrollWidth }); }); } }; private onToggleDrawer = () => { if (!this.state.showDrawer) { let validChatitoFiles = false; try { validChatitoFiles = this.validateChatitoFiles(); } catch (e) { return; } if (validChatitoFiles) { this.setState({ showDrawer: false, generating: true }, () => { // NOTE: using setTimeout to render a loading state before dataset generation may block the ui setTimeout(this.generateDataset, 600); }); } else { if (typeof window !== 'undefined' && window.alert) { window.alert('Please fix the errors or warnings found in the code.'); } } } }; /* ================== Utils ================== */ private importFile = (startPath: string, endPath: string) => { const filename = endPath.replace(/^\.\//, ''); const tabFound = this.tabs.find(t => t.title.trim() === filename); if (!tabFound) { throw new Error(`Can't import ${endPath}. Not found.`); } // note: returning empty path since there is no actual filesystem return { filePath: '', dsl: tabFound.value }; }; private saveToLocalStorage = () => { if (typeof window !== `undefined` && localStorage) { localStorage.setItem('tabs', JSON.stringify(this.tabs)); } }; private loadFromLocalIfPresent = (key: string, parseAsJSON: boolean) => { if (typeof window !== `undefined` && localStorage) { try { const item = localStorage.getItem(key); if (!parseAsJSON) { return item; } if (item) { try { return JSON.parse(item); } catch (e) { // just catch the error } } } catch (e) { // tslint:disable-next-line:no-console console.error(e); } } }; private loadFromLocalStorage = () => { if (typeof window !== `undefined` && localStorage) { const localTabs = this.loadFromLocalIfPresent('tabs', true); this.tabs = localTabs ? localTabs : this.props.tabs; } else { this.tabs = this.props.tabs; } }; private changeTab = (i: number, cb?: () => void) => { if (!this.codeflask) { return; } this.setState({ activeTabIndex: i }, () => { this.codeflask.updateCode(this.tabs[this.state.activeTabIndex].value); this.codeflask.setLineNumber(); if (cb) { setTimeout(cb, 600); // note; hack using setTimeout because codeflask uses a timeout on update code } }); }; private closerTab = (i: number) => { return (e: React.SyntheticEvent) => { if (e) { e.stopPropagation(); } if (this.tabs[i].value) { if (!window.confirm(`Do you really want to remove '${this.tabs[i].title}'?`)) { return; } } const ati = this.state.activeTabIndex; let newActiveTabIndex = this.state.activeTabIndex; if (ati === i && ati > 0) { newActiveTabIndex = ati - 1; } this.tabs = [...this.tabs.slice(0, i), ...this.tabs.slice(i + 1)]; if (!this.tabs.length) { this.tabs.push({ title: 'newFile.chatito', value: '' }); newActiveTabIndex = 0; } this.saveToLocalStorage(); this.changeTab(newActiveTabIndex); }; }; private getDSLValidation = (dsl: string): null | { error?: string; warning?: string } => { try { const ast = chatito.astFromString(dsl); const intentsWithoutLimit = ast.filter(entity => entity.type === 'IntentDefinition' && entity.args === null); if (intentsWithoutLimit.length) { return { warning: `Warning: Limit the number of generated examples for intents. E.g.: %[${intentsWithoutLimit[0].key}]('training': '100')` }; } return null; } catch (e) { const error = e.constructor === Error ? e.toString() : `${e.name}: ${e.message} Line: ${e.location.start.line}, Column: ${e.location.start.column}`; return { error }; } }; private validateChatitoFiles = () => { return !this.tabs.some((tab, i) => { if (tab.value) { const validation = this.getDSLValidation(tab.value); if (validation !== null) { this.changeTab(i); return true; } } return false; }); }; private generateDataset = async () => { let trainingDataset: webAdapter.IDefaultDataset = {}; const testingDataset: webAdapter.IDefaultDataset = {}; for (const [i, tab] of this.tabs.entries()) { try { const { training, testing } = await webAdapter.adapter(tab.value, trainingDataset, this.importFile, ''); trainingDataset = training; utils.mergeDeep(testingDataset, testing); } catch (e) { this.setState({ trainingDataset: {}, testingDataset: {}, showDrawer: false, generating: false }, () => { this.changeTab(i, () => this.setState({ error: e.message }, () => { if (typeof window !== 'undefined' && window.alert) { window.alert(`Please fix error: ${e.message}`); } }) ); }); return; } } this.setState({ trainingDataset, testingDataset, generating: false, showDrawer: true }); }; private downloadFiles = async (files: string[]) => { let total = 0; let progress = 0; this.setState({ isDownloading: true, downloadProgress: 0 }); const downloads = await Promise.all( files.map(file => axios.get(file, { onDownloadProgress: progressEvent => { const totalLength = progressEvent.lengthComputable ? progressEvent.total : progressEvent.target.getResponseHeader('content-length') || progressEvent.target.getResponseHeader('x-decompressed-content-length'); if (totalLength !== null) { total += totalLength; progress += Math.round((progressEvent.loaded * 100) / total); } this.setState({ downloadProgress: progress }); } }) ) ); this.setState({ isDownloading: false, downloadProgress: 100 }); return downloads; }; private trainTestAndSaveModels = async () => { const files = [withPrefix('/models/dictionary.json'), withPrefix('/models/ngram_to_id_dictionary.json')]; const jsonFiles = await this.downloadFiles(files); const pretrainedNGramVectors = new Map<string, Float32Array>(jsonFiles[0].data); const ngramToIdDictionary = jsonFiles[1].data; const { dictionary: { maxWordsPerSentence, slotsToId, intents, intentsWithSlots, testX, testY, testY2, trainX, trainY, trainY2, language }, stats } = dictionariesFromDataset(this.state.trainingDataset, this.state.testingDataset, englishTokenizer, 'en'); const trainingParams: ITrainingParams = { trainX, trainY, trainY2 }; const testingParams: ITestingParams = { testX, testY, testY2 }; const datasetParams = { intents, intentsWithSlots, language, maxWordsPerSentence, slotsToId } as IDatasetParams; const paramsBlob = new Blob([JSON.stringify(datasetParams)], { type: 'text/json;charset=utf-8' }); const trainingBlob = new Blob([JSON.stringify(trainingParams)], { type: 'text/json;charset=utf-8' }); const testingBlob = new Blob([JSON.stringify(testingParams)], { type: 'text/json;charset=utf-8' }); // NOTE: timeout to allow multiple downloads at once saveAs(paramsBlob, `dataset_params_${Math.round(new Date().getTime() / 1000)}.json`); setTimeout(() => { saveAs(trainingBlob, `training_dataset_${Math.round(new Date().getTime() / 1000)}.json`); setTimeout(() => { saveAs(testingBlob, `testing_dataset_${Math.round(new Date().getTime() / 1000)}.json`); // NOTE: using setTimeout here to render a loading state before blocking the ui setTimeout(() => { this.setState({ datasetParams, datasetStats: stats, embeddingsAndTrainingDatasetLoaded: true, ngramToIdDictionary, pretrainedNGramVectors, testingParams, trainingParams }); }, 200); }, 200); }, 200); }; }
the_stack
import {Component, OnInit, ViewChild, OnDestroy} from '@angular/core'; import {PrepareDatasetComponent} from './forms/prepare-dataset/prepare-dataset.component'; import {GeneralSettingsComponent} from './forms/general-settings/general-settings.component'; import {HyperParametersComponent} from './forms/hyper-parameters/hyper-parameters.component'; import {DataGetterFirstApiService} from '../../Services/data-getter-first-api.service'; import {environment} from '../../../environments/environment'; import {AddJob} from '../../Interfaces/addJob'; import {DataSenderFirstApiService} from '../../Services/data-sender-first-api.service'; import {RemoveJob} from '../../Interfaces/removeJob'; import {IConfig} from '../../Interfaces/config'; import {BasicConfig} from '../../Interfaces/basicConfig'; import {HttpResponse} from '@angular/common/http'; import {Dataset} from '../../Interfaces/dataset'; import {Config} from 'codelyzer'; import {DataSenderSecondApiService} from '../../Services/data-sender-second-api.service'; import {AdvancedHyperParametersComponent} from './forms/advanced-hyper-parameters/advanced-hyper-parameters.component'; import {NzMessageService} from 'ng-zorro-antd'; import set = Reflect.set; import {Router} from '@angular/router'; @Component({ selector: 'app-stepper-page', templateUrl: './stepper-page.component.html', styleUrls: ['./stepper-page.component.css'] }) export class StepperPageComponent implements OnInit, OnDestroy{ @ViewChild(PrepareDatasetComponent) prepareDataset: PrepareDatasetComponent; @ViewChild(GeneralSettingsComponent) generalSettings: GeneralSettingsComponent; @ViewChild(HyperParametersComponent) hyperParameters: HyperParametersComponent; @ViewChild(AdvancedHyperParametersComponent) advancedHyperParameters: AdvancedHyperParametersComponent; current = 0; card1Hidden = false; card2Hidden = true; card3Hidden = true; card4Hidden = true; step2PreviousButtonDisabled: boolean; step2NextButtonLoading: boolean; doneButtonLoading: boolean; cancelButtonDisabled: boolean; switchState: boolean; hyperParametersHidden = false; advancedHyperParametersHidden = true; baseURL = environment.url; basedEndPoint = environment.baseEndPoint; URL = this.baseURL + this.basedEndPoint + '/models/'; allJobs: Array<string> = []; downloadableModels: any; downloadableModelsKey = []; downloadableModelsValue = []; addJob: AddJob = { name: '', api_port: 0, gpus_count: [] }; removeJob: RemoveJob = { name: '' }; advancedConfig: IConfig = { lr: 0, batch_size: 0, epochs: 0, gpus_count: [], processor: '', weights_type: '', weights_name: '', model_name: '', new_model: '', momentum: 0, wd: 0, lr_factor: 0, num_workers: 0, jitter_param: 0, lighting_param: 0, Xavier: null, MSRAPrelu: null, data_augmenting: null, }; basicConfig: BasicConfig = { lr: 0, batch_size: 0, epochs: 0, gpus_count: [], processor: '', weights_type: '', weights_name: '', model_name: '', new_model: '', }; dataset: Dataset = { dataset_name: '', training_ratio: 0, validation_ratio: 0, testing_ratio: 0 }; interval; finishedJobs: Array<string> = []; dot; exactValue; jobMessageValue = ''; mobile: boolean; popoverPlacement; // cancel(), per(), next() and done() are all linked to the nz action buttons cancel(): void { this.removeJob.name = this.generalSettings.validateForm.value.containerName; this.dataSenderFirstApi.removeJob(this.removeJob).subscribe(); } pre(): void { this.current -= 1; this.changeContent(); } next(): void { if (this.current === 0) { this.prepareDataset.submitForm(this.prepareDataset.validateForm.value); if (!this.prepareDataset.validateForm.valid){ // do nothing } else if (this.prepareDataset.sum !== 100) { this.message.error('Sum of split percentage is not 100', { nzDuration: 3000 }); } else { this.generalSettings.datasetIndex = null; this.generalSettings.datasetValue = []; this.generalSettings.datasetIndex = this.prepareDataset.availableFoldersKeys.indexOf(this.prepareDataset.validateForm.value.dataset_name); this.generalSettings.datasetValue = this.prepareDataset.availableFoldersValue[this.generalSettings.datasetIndex]; if (this.generalSettings.selectedWeightType === 'checkpoint') { this.generalSettings.checkpointsList = []; let index; for (let i = 0; i < this.generalSettings.checkpointsValue.length; i++) { if (this.generalSettings.checkpointsValue[i].length === this.generalSettings.datasetValue.length) { for (let j = 0; j < this.generalSettings.datasetValue.length; j++) { if (this.generalSettings.checkpointsValue[i].includes(this.generalSettings.datasetValue[j])) { index = 1; } else { index = 0; break; } } if (index === 1) { this.generalSettings.checkpointsList.push(this.generalSettings.checkpointsKeys[i].split('/')[1] + ' | ' + this.generalSettings.checkpointsKeys[i].split('/')[0]); } } } } else { } this.current += 1; this.changeContent(); } } else if (this.current === 1) { this.generalSettings.submitForm(this.generalSettings.validateForm.value); if (!this.generalSettings.validateForm.valid){ // do nothing } else { this.addJob.name = this.generalSettings.validateForm.value.containerName; this.addJob.api_port = this.generalSettings.validateForm.value.APIPort; this.addJob.gpus_count = this.generalSettings.validateForm.value.gpus_count; this.generalSettings.containerNameDisabled = true; this.generalSettings.gpusCountDisabled = true; this.generalSettings.weightTypeDisabled = true; this.generalSettings.networksDisabled = true; this.generalSettings.checkpointsDisabled = true; this.step2PreviousButtonDisabled = true; this.step2NextButtonLoading = true; // @ts-ignore this.dataSenderFirstApi.addJob(this.addJob).subscribe((message1: string) => { this.jobMessageValue = message1; if (this.jobMessageValue === 'Success') { setTimeout( () => { this.current += 1; this.changeContent(); this.cancelButtonDisabled = true; this.doneButtonLoading = true; setTimeout(() => { this.cancelButtonDisabled = false; this.doneButtonLoading = false; }, 3000); }, 0); } }); this.dataGetterFirstApi.getAllJobs().subscribe(allJobs => { this.allJobs = allJobs; }); } } } done(): void { if (this.hyperParametersHidden === true) { this.advancedHyperParameters.submitForm(this.advancedHyperParameters.validateForm.value); if (!this.advancedHyperParameters.validateForm.valid){ // do nothing } else { this.advancedConfig.lr = this.advancedHyperParameters.validateForm.value.learning_rate; this.advancedConfig.batch_size = this.advancedHyperParameters.validateForm.value.batch_size; this.advancedConfig.epochs = this.advancedHyperParameters.validateForm.value.epochs; this.advancedConfig.momentum = this.advancedHyperParameters.validateForm.value.momentum; this.advancedConfig.wd = this.advancedHyperParameters.validateForm.value.wd; this.advancedConfig.lr_factor = this.advancedHyperParameters.validateForm.value.lr_factor; this.advancedConfig.num_workers = this.advancedHyperParameters.validateForm.value.num_workers; this.advancedConfig.jitter_param = this.advancedHyperParameters.validateForm.value.jitter_param; this.advancedConfig.lighting_param = this.advancedHyperParameters.validateForm.value.lighting_param; this.advancedConfig.Xavier = this.advancedHyperParameters.validateForm.value.Xavier; this.advancedConfig.MSRAPrelu = this.advancedHyperParameters.validateForm.value.MSRAPrelu; this.advancedConfig.data_augmenting = this.advancedHyperParameters.validateForm.value.data_augmenting; this.advancedConfig.processor = this.advancedHyperParameters.validateForm.value.processor; this.advancedConfig.new_model = this.generalSettings.validateForm.value.containerName; this.advancedConfig.gpus_count = this.generalSettings.validateForm.value.gpus_count; this.dataset.dataset_name = this.prepareDataset.validateForm.value.dataset_name; this.dataset.training_ratio = this.prepareDataset.validateForm.value.training; this.dataset.validation_ratio = this.prepareDataset.validateForm.value.validation; this.dataset.testing_ratio = this.prepareDataset.validateForm.value.testing; if (this.generalSettings.validateForm.value.weightType === 'from_scratch' || this.generalSettings.validateForm.value.weightType === 'pre_trained') { this.advancedConfig.weights_type = this.generalSettings.validateForm.value.weightType; this.advancedConfig.weights_name = this.generalSettings.validateForm.value.networks; } else { this.advancedConfig.weights_type = this.generalSettings.validateForm.value.weightType; this.advancedConfig.model_name = this.generalSettings.validateForm.value.checkPoints.split(' ')[0].toString(); this.advancedConfig.weights_name = this.generalSettings.validateForm.value.checkPoints.split(' ')[2].toString(); } this.doneButtonLoading = true; this.dataSenderSecondApi.datasetPost(this.dataset, this.generalSettings.validateForm.value.APIPort).subscribe( (message: HttpResponse<Config>) => { this.dataSenderSecondApi.advancedConfigPost(this.advancedConfig, this.generalSettings.validateForm.value.APIPort).subscribe( (message1: HttpResponse<Config>) => { if (message1.toString() === 'Training Started') { this.doneButtonLoading = false; this.current += 1; this.changeContent(); this.router.navigate(['/jobs']); } else { this.doneButtonLoading = true; } }); }); } } else { this.hyperParameters.submitForm(this.hyperParameters.validateForm.value); if (!this.hyperParameters.validateForm.valid){ // do nothing } else { this.basicConfig.lr = this.hyperParameters.validateForm.value.learning_rate; this.basicConfig.batch_size = this.hyperParameters.validateForm.value.batch_size; this.basicConfig.epochs = this.hyperParameters.validateForm.value.epochs; this.basicConfig.new_model = this.generalSettings.validateForm.value.containerName; this.basicConfig.gpus_count = this.generalSettings.validateForm.value.gpus_count; this.basicConfig.processor = this.advancedHyperParameters.validateForm.value.processor; this.dataset.dataset_name = this.prepareDataset.validateForm.value.dataset_name; this.dataset.training_ratio = this.prepareDataset.validateForm.value.training; this.dataset.validation_ratio = this.prepareDataset.validateForm.value.validation; this.dataset.testing_ratio = this.prepareDataset.validateForm.value.testing; // tslint:disable-next-line:max-line-length if (this.generalSettings.validateForm.value.weightType === 'from_scratch' || this.generalSettings.validateForm.value.weightType === 'pre_trained') { this.basicConfig.weights_type = this.generalSettings.validateForm.value.weightType; this.basicConfig.weights_name = this.generalSettings.validateForm.value.networks; } else { this.basicConfig.weights_type = this.generalSettings.validateForm.value.weightType; this.basicConfig.model_name = this.generalSettings.validateForm.value.checkPoints.split(' ')[0].toString(); this.basicConfig.weights_name = this.generalSettings.validateForm.value.checkPoints.split(' ')[2].toString(); } this.doneButtonLoading = true; this.dataSenderSecondApi.datasetPost(this.dataset, this.generalSettings.validateForm.value.APIPort).subscribe( (message: HttpResponse<Config>) => { this.dataSenderSecondApi.basicConfigPost(this.basicConfig, this.generalSettings.validateForm.value.APIPort).subscribe( (message1: HttpResponse<Config>) => { if (message1.toString() === 'Training Started') { this.doneButtonLoading = false; this.current += 1; this.changeContent(); this.router.navigate(['/jobs']); } else { this.doneButtonLoading = true; } }); }); } } } // change content of each step changeContent(): void { switch (this.current) { case 0: { this.card1Hidden = false; this.card2Hidden = true; this.card3Hidden = true; this.card4Hidden = true; this.step2PreviousButtonDisabled = false; this.step2NextButtonLoading = false; break; } case 1: { this.card1Hidden = true; this.card2Hidden = false; this.card3Hidden = true; this.card4Hidden = true; this.step2PreviousButtonDisabled = false; this.step2NextButtonLoading = false; break; } case 2: { this.card1Hidden = true; this.card2Hidden = true; this.card3Hidden = false; this.card4Hidden = true; this.step2PreviousButtonDisabled = true; this.step2NextButtonLoading = false; break; } case 3: { this.card1Hidden = true; this.card2Hidden = true; this.card3Hidden = true; this.card4Hidden = false; break; } default: { } } } testWithSwagger(){ window.open(environment.inferenceAPIUrl, '_blank'); } jobIsDone = (jobs: string) => { if (this.finishedJobs !== undefined) { return this.finishedJobs.indexOf(jobs); } return -1; } // switch between hyper and advanced hyper parameters switch() { this.switchState = !this.switchState; if (this.switchState === true) { this.hyperParametersHidden = true; this.advancedHyperParametersHidden = false; } else { this.hyperParametersHidden = false; this.advancedHyperParametersHidden = true; } } onDownloadableModelClick() { this.dot = false; if (this.mobile === false) { // tslint:disable-next-line:prefer-for-of for (let i = 0; i < this.downloadableModelsKey.length; i++){ if (this.downloadableModelsKey[i].slice(0, -4).length > 6) { this.popoverPlacement = 'bottomRight'; break; } else { this.popoverPlacement = 'bottom'; } } } } constructor(private dataGetterFirstApi: DataGetterFirstApiService, private dataSenderFirstApi: DataSenderFirstApiService, private dataSenderSecondApi: DataSenderSecondApiService, private message: NzMessageService, private router: Router) { this.interval = setInterval(() => { this.dataGetterFirstApi.getFinishedJobs().subscribe((finishedJobs) => { if (finishedJobs.length > this.finishedJobs.length) { this.dot = true; } this.finishedJobs = finishedJobs; }); this.dataGetterFirstApi.getDownloadableModels().subscribe((downloadableModels) => { this.downloadableModels = downloadableModels; const extraKey = []; let missingKey; for (const [key, value] of Object.entries(this.downloadableModels)) { extraKey.push(key); if (!extraKey.every(n => this.downloadableModelsKey.includes(missingKey = n))) { this.exactValue = value; this.downloadableModelsKey.push(missingKey); } } if (this.exactValue !== undefined) { this.downloadableModelsValue.push(this.exactValue); } }); }, 5000); } ngOnInit() { if (window.screen.width < 769) { // 768px portrait this.mobile = true; } else { this.mobile = false; } window.onresize = () => { if (window.screen.width < 769) { // 768px portrait this.mobile = true; } else { this.mobile = false; } }; this.dataGetterFirstApi.getDownloadableModels().subscribe((models) => { this.downloadableModels = models; for (const [key, value] of Object.entries(this.downloadableModels)) { this.downloadableModelsKey.push(key); this.downloadableModelsValue.push(value); } }); this.dataGetterFirstApi.getFinishedJobs().subscribe((finishedJobs) => { this.finishedJobs = finishedJobs; }); this.dataGetterFirstApi.getAllJobs().subscribe(allJobs => { this.allJobs = allJobs; }); } ngOnDestroy() { clearInterval(this.interval); } }
the_stack
import { TransactionList } from '../../src/transaction_list'; import { Transaction } from '../../src/types'; const insertNTransactions = ( transactionList: TransactionList, n: number, nonceStart = 0, ): Transaction[] => { const addedTransactions = []; for (let i = nonceStart; i < nonceStart + n; i += 1) { const tx = { id: Buffer.from(i.toString()), nonce: BigInt(i), fee: BigInt(i * 1000), } as Transaction; addedTransactions.push(tx); transactionList.add(tx); } return addedTransactions; }; describe('TransactionList class', () => { const defaultAddress = Buffer.from('d04699e57c4a3846c988f3c15306796f8eae5c1c', 'hex'); let transactionList: TransactionList; beforeEach(() => { transactionList = new TransactionList(defaultAddress); }); describe('constructor', () => { describe('when option are not given', () => { it('should set default values', () => { expect((transactionList as any)._maxSize).toEqual(64); expect((transactionList as any)._minReplacementFeeDifference.toString()).toEqual('10'); }); }); describe('when option are given', () => { it('should set the value to given option values', () => { transactionList = new TransactionList(defaultAddress, { maxSize: 10, minReplacementFeeDifference: BigInt(100), }); expect((transactionList as any)._maxSize).toEqual(10); expect((transactionList as any)._minReplacementFeeDifference.toString()).toEqual('100'); }); }); }); describe('add', () => { beforeEach(() => { transactionList = new TransactionList(defaultAddress, { maxSize: 10, minReplacementFeeDifference: BigInt(10), }); }); describe('given list still has spaces', () => { describe('when the same nonce transaction with higher fee is added', () => { it('should replace with the new transaction', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 5); const replacing = { ...addedTxs[0], id: Buffer.from(Buffer.from('new-id')), fee: addedTxs[0].fee + BigInt(500000000), }; // Act const { added, removedID } = transactionList.add(replacing); // Assert expect(removedID).toEqual(addedTxs[0].id); expect(added).toEqual(true); expect(transactionList.size).toEqual(5); expect(transactionList.get(addedTxs[0].nonce)?.id).toEqual(Buffer.from('new-id')); }); it('should demote all subsequent transactions', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 5); transactionList.promote(addedTxs); const replacing = { ...addedTxs[0], id: Buffer.from('new-id'), fee: addedTxs[0].fee + BigInt(500000000), }; // Act const { added, removedID } = transactionList.add(replacing); // Assert expect(added).toEqual(true); expect(removedID).toEqual(addedTxs[0].id); expect(transactionList.size).toEqual(5); expect(transactionList.getProcessable()).toHaveLength(0); expect(transactionList.getUnprocessable()).toHaveLength(5); expect(transactionList.get(addedTxs[0].nonce)?.id).toEqual(Buffer.from('new-id')); }); }); describe('when the same nonce transaction with higher fee but lower than minReplaceFeeDiff is added', () => { it('should not replace and not add to the list', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 5); const replacing = { ...addedTxs[0], id: Buffer.from('new-id'), fee: addedTxs[0].fee + BigInt(5), }; // Act const { added } = transactionList.add(replacing); // Assert expect(added).toEqual(false); expect(transactionList.size).toEqual(5); expect(transactionList.get(addedTxs[0].nonce)?.id).toEqual(addedTxs[0].id); }); }); describe('when the same nonce transaction with a lower fee than min replacement fee is added', () => { it('should not replace and not add to the list', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 5); const replacing = { ...addedTxs[0], id: Buffer.from('new-id'), fee: addedTxs[0].fee - BigInt(100), }; // Act const { added, reason } = transactionList.add(replacing); // Assert expect(added).toEqual(false); expect(reason).toEqual( 'Incoming transaction fee is not sufficient to replace existing transaction', ); expect(transactionList.size).toEqual(5); expect(transactionList.get(addedTxs[0].nonce)?.id).toEqual(addedTxs[0].id); }); }); describe('when the same nonce transaction with the same fee is added', () => { it('should not replace and not add to the list', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 5); const replacing = { ...addedTxs[0], id: Buffer.from('new-id'), fee: addedTxs[0].fee, }; // Act const { added } = transactionList.add(replacing); // Assert expect(added).toEqual(false); expect(transactionList.size).toEqual(5); expect(transactionList.get(addedTxs[0].nonce)?.id).toEqual(addedTxs[0].id); }); }); describe('when new transaction is added', () => { it('should add to the list', () => { insertNTransactions(transactionList, 5); const adding = { id: Buffer.from('new-id'), fee: BigInt(500000000), nonce: BigInt(6), } as Transaction; // Act const { added } = transactionList.add(adding); // Assert expect(added).toEqual(true); expect(transactionList.size).toEqual(6); expect(transactionList.get(BigInt(6))?.id).toEqual(Buffer.from('new-id')); }); }); describe('when new transaction is added with processable true while having empty processable', () => { it('should add to the list and mark as processable', () => { insertNTransactions(transactionList, 5, 1); const adding = { id: Buffer.from('new-id'), fee: BigInt(500000000), nonce: BigInt(0), } as Transaction; // Act const { added } = transactionList.add(adding, true); // Assert expect(added).toEqual(true); expect(transactionList.size).toEqual(6); expect(transactionList.get(BigInt(0))?.id).toEqual(Buffer.from('new-id')); expect(transactionList.getProcessable()[0].id).toEqual(Buffer.from('new-id')); }); }); }); describe('when the transaction list is full', () => { describe('when the same nonce transaction with higher fee is added', () => { it('should replace with the new transaction', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); const replacing = { ...addedTxs[0], id: Buffer.from('new-id'), fee: addedTxs[0].fee + BigInt(500000000), }; // Act const { added, removedID } = transactionList.add(replacing); // Assert expect(added).toEqual(true); expect(removedID).toEqual(addedTxs[0].id); expect(transactionList.size).toEqual(10); expect(transactionList.get(addedTxs[0].nonce)?.id).toEqual(Buffer.from('new-id')); }); it('should demote all subsequent transactions', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); transactionList.promote(addedTxs); const replacing = { ...addedTxs[0], id: Buffer.from('new-id'), fee: addedTxs[0].fee + BigInt(500000000), }; // Act const { added, removedID } = transactionList.add(replacing); // Assert expect(added).toEqual(true); expect(removedID).toEqual(addedTxs[0].id); expect(transactionList.size).toEqual(10); expect(transactionList.getProcessable()).toHaveLength(0); expect(transactionList.getUnprocessable()).toHaveLength(10); expect(transactionList.get(addedTxs[0].nonce)?.id).toEqual(Buffer.from('new-id')); }); }); describe('when the same nonce transaction with higher fee and greater than minReplaceFeeDiff is added', () => { it('should replace with the new transaction', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); const replacing = { ...addedTxs[0], id: Buffer.from('new-id'), fee: addedTxs[0].fee + BigInt(11), }; // Act const { added } = transactionList.add(replacing); // Assert expect(added).toEqual(true); expect(transactionList.size).toEqual(10); expect(transactionList.get(replacing.nonce)?.id).toEqual(replacing.id); }); }); describe('when the same nonce transaction with higher fee but lower than minReplaceFeeDiff is added', () => { it('should reject the new incoming replacing transaction', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); const replacing = { ...addedTxs[0], id: Buffer.from('new-id'), fee: addedTxs[0].fee + BigInt(5), }; // Act const { added, reason } = transactionList.add(replacing); // Assert expect(added).toEqual(false); expect(reason).toEqual( 'Incoming transaction fee is not sufficient to replace existing transaction', ); expect(transactionList.size).toEqual(10); expect(transactionList.get(addedTxs[0].nonce)?.id).toEqual(addedTxs[0].id); }); }); describe('when the same nonce transaction with a lower fee than min replacement fee is added', () => { it('should not replace and not add to the list', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); const replacing = { ...addedTxs[0], id: Buffer.from('new-id'), fee: addedTxs[0].fee - BigInt(100), }; // Act const { added } = transactionList.add(replacing); // Assert expect(added).toEqual(false); expect(transactionList.size).toEqual(10); expect(transactionList.get(addedTxs[0].nonce)?.id).toEqual(addedTxs[0].id); }); }); describe('when the same nonce transaction with the same fee is added', () => { it('should not replace and not add to the list', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); const replacing = { ...addedTxs[0], id: Buffer.from('new-id'), fee: addedTxs[0].fee, }; // Act const { added } = transactionList.add(replacing); // Assert expect(added).toEqual(false); expect(transactionList.size).toEqual(10); expect(transactionList.get(addedTxs[0].nonce)?.id).toEqual(addedTxs[0].id); }); }); describe('when new transaction is added with higher nonce than the existing highest nonce', () => { it('should not add to the list', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); const adding = { id: Buffer.from('new-id'), fee: addedTxs[0].fee + BigInt(500000000), nonce: BigInt(100), } as Transaction; // Act const { added, reason } = transactionList.add(adding); // Assert expect(added).toEqual(false); expect(reason).toEqual( 'Incoming transaction exceeds maximum transaction limit per account', ); expect(transactionList.size).toEqual(10); }); }); describe('when new transaction is added with lower nonce than the existing highest nonce', () => { it('should add the new transaction and remove the highest nonce transaction', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10, 1); const adding = { id: Buffer.from('new-id'), fee: addedTxs[0].fee + BigInt(500000000), nonce: BigInt(0), } as Transaction; // Act const { added, removedID } = transactionList.add(adding); // Assert expect(added).toEqual(true); expect(removedID).toEqual(Buffer.from('10')); expect(transactionList.size).toEqual(10); expect(transactionList.get(BigInt(0))?.id).toEqual(Buffer.from('new-id')); }); }); }); }); describe('remove', () => { describe('when removing transaction does not exist', () => { it('should not change the size and return false', () => { // Arrange insertNTransactions(transactionList, 10, 1); // Act const removed = transactionList.remove(BigInt(0)); // Assert expect(removed).toBeUndefined(); expect(transactionList.size).toEqual(10); }); }); describe('when removing transaction exists and is processable', () => { it('should remove the transaction and all the rest are demoted', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); transactionList.promote(addedTxs); // Act const removed = transactionList.remove(BigInt(5)); // Assert expect(removed).toEqual(Buffer.from('5')); expect(transactionList.size).toEqual(9); expect(transactionList.getProcessable()).toHaveLength(5); expect(transactionList.getUnprocessable()).toHaveLength(4); }); }); }); describe('promote', () => { describe('when promoting transaction id does not exist', () => { it('should not mark any transactions as promotable', () => { // Arrange insertNTransactions(transactionList, 10); // Act transactionList.promote([ { id: Buffer.from('11'), nonce: BigInt(11), fee: BigInt(1000000), } as Transaction, ]); // Assert expect(transactionList.getProcessable()).toHaveLength(0); }); }); describe('when promoting transaction matches id', () => { it('should mark all the transactions as processable', () => { // Arrange const addedTrx = insertNTransactions(transactionList, 10); // Act transactionList.promote(addedTrx.slice(0, 3)); // Assert expect(transactionList.getProcessable()).toHaveLength(3); }); it('should maintain processable in order', () => { // Arrange const addedTrx = insertNTransactions(transactionList, 60); // Act transactionList.promote(addedTrx.slice(9, 10)); transactionList.promote(addedTrx.slice(10, 22)); // Assert const processable = transactionList.getProcessable(); expect(processable[0].nonce.toString()).toEqual('9'); expect(processable[processable.length - 1].nonce.toString()).toEqual('21'); }); }); }); describe('size', () => { it('should give back the total size of processable and nonprocessable', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); // Act transactionList.promote(addedTxs.slice(0, 3)); // Assert expect(transactionList.size).toEqual(10); }); }); describe('getProcessable', () => { describe('when there are only processable transactions', () => { it('should return all the transactions in order of nonce', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); transactionList.promote(addedTxs.slice(0, 3)); // Act const processable = transactionList.getProcessable(); expect(processable).toHaveLength(3); expect(processable[0].nonce + BigInt(1)).toEqual(processable[1].nonce); expect(processable[1].nonce + BigInt(1)).toEqual(processable[2].nonce); }); }); describe('when there are only unprocessable transactions', () => { it('should return empty array', () => { // Arrange insertNTransactions(transactionList, 10); // Act const processable = transactionList.getProcessable(); expect(processable).toHaveLength(0); }); }); }); describe('getUnprocessable', () => { describe('when there are only processable transactions', () => { it('should return empty array', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); transactionList.promote(addedTxs); // Act expect(transactionList.getUnprocessable()).toHaveLength(0); }); }); describe('when there are only unprocessable transactions', () => { it('should return all the transactions in order of nonce', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 5); insertNTransactions(transactionList, 5, 15); transactionList.promote(addedTxs.slice(0, 3)); // Act const unprocessable = transactionList.getUnprocessable(); expect(unprocessable).toHaveLength(7); expect.assertions(1 + unprocessable.length - 1); for (let i = 0; i < unprocessable.length - 1; i += 1) { expect(Number(unprocessable[i].nonce.toString())).toBeLessThan( Number(unprocessable[i + 1].nonce.toString()), ); } }); }); }); describe('getPromotable', () => { describe('when there are only processable transactions', () => { it('should return empty array', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 10); transactionList.promote(addedTxs); // Act expect(transactionList.getPromotable()).toHaveLength(0); }); }); describe('when there are processable and unprocessable transactions and unprocessable nonce is not continuous to processable', () => { it('should return empty array', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 5); insertNTransactions(transactionList, 5, 10); transactionList.promote(addedTxs.slice(0, 6)); // Act expect(transactionList.getPromotable()).toHaveLength(0); }); }); describe('when there are only unprocessable transactions and all nonces are not continuous', () => { it('should return only the first unprocessable transaction', () => { // Arrange const addedTxs = insertNTransactions(transactionList, 1); insertNTransactions(transactionList, 1, 3); insertNTransactions(transactionList, 1, 5); insertNTransactions(transactionList, 1, 7); // Act const promotable = transactionList.getPromotable(); // Assert expect(promotable).toHaveLength(1); expect(promotable[0].id).toEqual(addedTxs[0].id); }); }); describe('when there are only unprocessable transactions and all nonces are in sequence order', () => { it('should return all the promotables in order of nonce', () => { // Arrange insertNTransactions(transactionList, 10, 10); // Act const promotable = transactionList.getPromotable(); // Assert expect(promotable).toHaveLength(10); expect.assertions(1 + promotable.length - 1); for (let i = 0; i < promotable.length - 1; i += 1) { expect(Number(promotable[i].nonce.toString())).toBeLessThan( Number(promotable[i + 1].nonce.toString()), ); } }); }); }); });
the_stack
import * as commonmark from "commonmark"; import * as chev from "chevrotain"; import {parserErrors, EveError} from "./errors"; var {Lexer, tokenMatcher} = chev; export var Token = chev.Token; import * as uuid from "uuid"; //----------------------------------------------------------- // Utils //----------------------------------------------------------- function cleanString(str:string) { let cleaned = str .replace(/\\n/g, "\n") .replace(/\\t/g, "\t") .replace(/\\r/g, "\r") .replace(/\\"/g, "\"") .replace(/\\{/g, "{") .replace(/\\}/g, "}"); return cleaned; } function toEnd(node:any) { if(node && node.tokenType !== undefined) { return node.endOffset! + 1; } return node.endOffset; } //----------------------------------------------------------- // Markdown //----------------------------------------------------------- let markdownParser = new commonmark.Parser(); function parseMarkdown(markdown: string, docId: string) { let parsed = markdownParser.parse(markdown); let walker = parsed.walker(); var cur; let tokenId = 0; var text = []; var extraInfo:any = {}; var pos = 0; var lastLine = 1; var spans = []; var context = []; var blocks = []; while(cur = walker.next()) { let node = cur.node as any; if(cur.entering) { while(node.sourcepos && node.sourcepos[0][0] > lastLine) { lastLine++; pos++; text.push("\n"); } if(node.type !== "text") { context.push({node, start: pos}); } if(node.type == "text" || node.type === "code_block" || node.type == "code") { text.push(node.literal); pos += node.literal.length; } if(node.type == "softbreak") { text.push("\n"); pos += 1; lastLine++; context.pop(); } if(node.type == "code_block") { let spanId = `${docId}|block|${tokenId++}`; let start = context.pop()!.start; node.id = spanId; node.startOffset = start; let type = node.type; if(!(node as any)._isFenced) { type = "indented_code_block"; } else { blocks.push(node); } spans.push(start, pos, node.type, spanId); lastLine = node.sourcepos[1][0] + 1; } if(node.type == "code") { let spanId = `${docId}|${tokenId++}`; let start = context.pop()!.start; spans.push(start, pos, node.type, spanId); } } else { let info = context.pop()!; if(node !== info.node) { throw new Error("Common mark is exiting a node that doesn't agree with the context stack"); } if(node.type == "emph" || node.type == "strong" || node.type == "link") { let spanId = `${docId}|${tokenId++}`; spans.push(info.start, pos, node.type, spanId); if(node.type === "link") { extraInfo[spanId] = {destination: node._destination}; } } else if(node.type == "heading" || node.type == "item") { let spanId = `${docId}|${tokenId++}`; spans.push(info.start, info.start, node.type, spanId); extraInfo[spanId] = {level: node._level, listData: node._listData}; } } } return {text: text.join(""), spans, blocks, extraInfo}; } //----------------------------------------------------------- // Tokens //----------------------------------------------------------- const breakChars = "@#\\.,\\(\\)\\[\\]\\{\\}⦑⦒:\\\""; // Markdown export class DocContent extends Token { static PATTERN = /[^\n]+/; } export class Fence extends Token { static PATTERN = /```|~~~/; static PUSH_MODE = "code"; } export class CloseFence extends Token { static PATTERN = /```|~~~/; static POP_MODE = true; } // Comments export class CommentLine extends Token { static PATTERN = /\/\/.*\n/; label = "comment"; static GROUP = "comments"; } // Operators export class Equality extends Token { static PATTERN = /:|=/; label = "equality"; } export class Comparison extends Token { static PATTERN = />=|<=|!=|>|</; label = "comparison"; } export class AddInfix extends Token { static PATTERN = /\+|-/; label = "infix"; } export class MultInfix extends Token { static PATTERN = /\*|\//; label = "infix"; } export class Merge extends Token { static PATTERN = /<-/; label = "merge"; } export class Set extends Token { static PATTERN = /:=/; label = "set"; } export class Mutate extends Token { static PATTERN = /\+=|-=/; label = "mutate"; } export class Dot extends Token { static PATTERN = /\./; label = "dot"; } export class Pipe extends Token { static PATTERN = /\|/; label = "pipe"; } // Identifier export class Identifier extends Token { static PATTERN = new RegExp(`([\\+-/\\*][^\\s${breakChars}]+|[^\\d${breakChars}\\+-/\\*][^\\s${breakChars}]*)(?=[^\\[])`); label = "identifier"; } export class FunctionIdentifier extends Token { static PATTERN = new RegExp(`([\\+-/\\*][^\\s${breakChars}]+|[^\\d${breakChars}\\+-/\\*][^\\s${breakChars}]*)(?=\\[)`); label = "functionIdentifier"; } // Keywords export class Keyword extends Token { static PATTERN = Lexer.NA; static LONGER_ALT = Identifier; } export class Lookup extends Keyword { static PATTERN = /lookup(?=\[)/; label = "lookup"; } export class Action extends Keyword { static PATTERN = /bind|commit/; label = "action"; } export class Search extends Keyword { static PATTERN = /search/; label = "search"; } export class If extends Keyword { static PATTERN = /if/; label = "if"; } export class Else extends Keyword { static PATTERN = /else/; label = "else"; } export class Then extends Keyword { static PATTERN = /then/; label = "then"; } export class Not extends Keyword { static PATTERN = /not/; label = "not"; } // Values export class Bool extends Keyword { static PATTERN = /true|false/; label = "bool"; } export class Num extends Token { static PATTERN = /-?\d+(\.\d+)?/; label = "num"; } export class None extends Keyword { static PATTERN = /none/; label = "none"; } export class Name extends Token { static PATTERN = /@/; label = "name"; } export class Tag extends Token { static PATTERN = /#/; label = "tag"; } // Delimiters export class OpenBracket extends Token { static PATTERN = /\[/; label = "open-bracket"; } export class CloseBracket extends Token { static PATTERN = /\]/; label = "close-bracket"; } export class OpenParen extends Token { static PATTERN = /\(/; label = "open-paren"; } export class CloseParen extends Token { static PATTERN = /\)/; label = "close-paren"; } // Strings export class StringChars extends Token { static PATTERN = /(\\.|{(?=[^{])|[^"\\{])+/; label = "string"; } export class OpenString extends Token { static PATTERN = /"/; static PUSH_MODE = "string"; label = "quote"; } export class CloseString extends Token { static PATTERN = /"/; static POP_MODE = true; label = "quote"; } // String Embeds export class StringEmbedOpen extends Token { static PATTERN = /{{/; static PUSH_MODE = "code"; label = "string-embed-open"; } export class StringEmbedClose extends Token { static PATTERN = /}}/; static POP_MODE = true; label = "string-embed-close"; } // Whitespace export class WhiteSpace extends Token { static PATTERN = /\s+|,/; static GROUP = Lexer.SKIPPED; } //----------------------------------------------------------- // Lexers //----------------------------------------------------------- let codeTokens: any[] = [ CloseFence, WhiteSpace, CommentLine, OpenBracket, CloseBracket, OpenParen, CloseParen, StringEmbedClose, OpenString, Bool, Action, Set, Equality, Dot, Pipe, Merge, Mutate, Comparison, Num, Search, Lookup, If, Else, Then, Not, None, Name, Tag, FunctionIdentifier, Identifier, AddInfix, MultInfix ]; let stringEmbedTokens: any[] = [StringEmbedClose].concat(codeTokens); let LexerModes:any = { "doc": [WhiteSpace, Fence, DocContent], "code": codeTokens, "string": [CloseString, StringEmbedOpen, StringChars], // "stringEmbed": stringEmbedTokens, }; let allTokens: any[] = codeTokens.concat([Fence, DocContent, CloseString, StringEmbedOpen, StringEmbedClose, StringChars]); let EveDocLexer = new Lexer({modes: LexerModes, defaultMode: "doc"}); let EveBlockLexer = new Lexer({modes: LexerModes, defaultMode: "code"}); //----------------------------------------------------------- // Parse Nodes //----------------------------------------------------------- export type NodeDependent = chev.IToken | ParseNode; export interface ParseNode { type?: string id?: string startOffset?: number, endOffset?: number, from: NodeDependent[] [property: string]: any } export class ParseBlock { id: string; start: number; nodeId = 0; variables: {[name: string]: ParseNode} = {}; equalities: any[] = []; scanLike: ParseNode[] = []; expressions: ParseNode[] = []; binds: ParseNode[] = []; commits: ParseNode[] = []; variableLookup: {[name: string]: ParseNode}; links: string[] = []; tokens: chev.Token[]; searchScopes: string[] = []; parent: ParseBlock | undefined; constructor(id:string, variableLookup?:any) { this.id = id; this.variableLookup = variableLookup || {}; } toVariable(name:string, generated = false) { let variable = this.variableLookup[name]; if(!variable) { this.variableLookup[name] = this.makeNode("variable", {name, from: [], generated}); } variable = this.variables[name] = this.variableLookup[name]; return {id: variable.id, type: "variable", name, from: [], generated}; } addUsage(variable:any, usage:any) { let global = this.variableLookup[variable.name]; global.from.push(usage) if(global.from.length === 1) { global.startOffset = usage.startOffset; global.endOffset = toEnd(usage); } variable.from.push(usage); variable.startOffset = usage.startOffset; variable.endOffset = toEnd(usage); this.links.push(variable.id, usage.id); } equality(a:any, b:any) { this.equalities.push([a, b]); } commit(node: ParseNode) { this.commits.push(node); } bind(node: ParseNode) { this.binds.push(node); } expression(node: ParseNode) { this.expressions.push(node); } scan(node: ParseNode) { this.scanLike.push(node); } makeNode(type:any, node: ParseNode) { if(!node.id) { node.id = `${this.id}|node|${this.nodeId++}`; } for(let from of node.from as any[]) { this.links.push(node.id, from.id); } if(node.from.length) { node.startOffset = node.from[0].startOffset; node.endOffset = toEnd(node.from[node.from.length - 1]); } node.type = type; return node; } addSearchScopes(scopes: string[]) { for(let scope of scopes) { if(this.searchScopes.indexOf(scope) === -1) { this.searchScopes.push(scope); } } } subBlock() { let neue = new ParseBlock(`${this.id}|sub${this.nodeId++}`, this.variableLookup); neue.parent = this; return neue; } } //----------------------------------------------------------- // Parser //----------------------------------------------------------- export class Parser extends chev.Parser { customErrors: any[]; block: ParseBlock; activeScopes: string[]; currentAction: string; // Parser patterns doc: any; codeBlock: any; fencedBlock: any; section: any; searchSection: any; actionSection: any; value: any; bool: any; num: any; scopeDeclaration: any; name: any; statement: any; expression: any; attribute: any; attributeEquality: any; attributeComparison: any; attributeNot: any; attributeOperation: any; record: any; tag: any; functionRecord: any; notStatement: any; comparison: any; infix: any; attributeAccess: any; actionStatement: any; actionEqualityRecord: any; actionAttributeExpression: any; actionOperation: any; actionLookup: any; variable: any; recordOperation: any; ifExpression: any; ifBranch: any; elseIfBranch: any; elseBranch: any; multiplication: any; addition: any; infixValue: any; parenthesis: any; attributeMutator: any; singularAttribute: any; stringInterpolation: any; constructor(input:any) { super(input, allTokens, {}); let self = this; let asValue = (node:any) => { if(node.type === "constant" || node.type === "variable" || node.type === "parenthesis") { return node; } else if(node.variable) { return node.variable; } throw new Error("Tried to get value of a node that is neither a constant nor a variable.\n\n" + JSON.stringify(node)); } let ifOutputs = (expression:any) => { let outputs = []; if(expression.type === "parenthesis") { for(let item of expression.items) { outputs.push(asValue(item)); } } else { outputs.push(asValue(expression)); } return outputs; } let makeNode = (type:string, node:any) => { return self.block.makeNode(type, node); } let blockStack:any[] = []; let pushBlock = (blockId?:string) => { let block; let prev = blockStack[blockStack.length - 1]; if(prev) { block = prev.subBlock(); } else { block = new ParseBlock(blockId || "block"); } blockStack.push(block); self.block = block; return block; } let popBlock = () => { let popped = blockStack.pop(); self.block = blockStack[blockStack.length - 1]; return popped; } //----------------------------------------------------------- // Doc rules //----------------------------------------------------------- self.RULE("doc", () => { let doc = { full: [] as any[], content: [] as any[], blocks: [] as any[], } self.MANY(() => { self.OR([ {ALT: () => { let content = self.CONSUME(DocContent); doc.full.push(content); doc.content.push(content); }}, {ALT: () => { let block : any = self.SUBRULE(self.fencedBlock); if(doc.content.length) { block.name = doc.content[doc.content.length - 1].image; } else { block.name = "Unnamed block"; } doc.full.push(block); doc.blocks.push(block); }}, ]) }); return doc; }); self.RULE("fencedBlock", () => { self.CONSUME(Fence); let block = self.SUBRULE(self.codeBlock); let fence = self.CONSUME(CloseFence); return block; }); //----------------------------------------------------------- // Blocks //----------------------------------------------------------- self.RULE("codeBlock", (blockId = "block") => { blockStack = []; let block = pushBlock(blockId); self.MANY(() => { self.SUBRULE(self.section) }) return popBlock(); }) self.RULE("section", () => { return self.OR([ {ALT: () => { return self.SUBRULE(self.searchSection) }}, {ALT: () => { return self.SUBRULE(self.actionSection) }}, {ALT: () => { return self.CONSUME(CommentLine); }}, ]); }); //----------------------------------------------------------- // Scope declaration //----------------------------------------------------------- self.RULE("scopeDeclaration", () => { let scopes:any[] = []; self.OR([ {ALT: () => { self.CONSUME(OpenParen); self.AT_LEAST_ONE(() => { let name: any = self.SUBRULE(self.name); scopes.push(name.name); }) self.CONSUME(CloseParen); }}, {ALT: () => { self.AT_LEAST_ONE2(() => { let name: any = self.SUBRULE2(self.name); scopes.push(name.name); }) }}, ]); return scopes; }); //----------------------------------------------------------- // Search section //----------------------------------------------------------- self.RULE("searchSection", () => { // @TODO fill in from let from:any[] = []; self.CONSUME(Search); let scopes:any = ["session"]; self.OPTION(() => { scopes = self.SUBRULE(self.scopeDeclaration) }) self.activeScopes = scopes; self.currentAction = "match"; self.block.addSearchScopes(scopes); let statements:any[] = []; self.MANY(() => { let statement: any = self.SUBRULE(self.statement); if(statement) { statements.push(statement); statement.scopes = scopes; } }); return makeNode("searchSection", {statements, scopes, from}); }); self.RULE("statement", () => { return self.OR([ {ALT: () => { return self.SUBRULE(self.comparison); }}, {ALT: () => { return self.SUBRULE(self.notStatement); }}, ]) }); //----------------------------------------------------------- // Action section //----------------------------------------------------------- self.RULE("actionSection", () => { // @TODO fill in from let from:any[] = []; let action = self.CONSUME(Action).image; let actionKey = action; let scopes:any = ["session"]; self.OPTION(() => { scopes = self.SUBRULE(self.scopeDeclaration) }) self.activeScopes = scopes; self.currentAction = action!; let statements:any[] = []; self.MANY(() => { let statement = self.SUBRULE(self.actionStatement, [actionKey]) as any; if(statement) { statements.push(statement); statement.scopes = scopes; } }); return makeNode("actionSection", {statements, scopes, from}); }); self.RULE("actionStatement", (actionKey) => { return self.OR([ {ALT: () => { let record = self.SUBRULE(self.record, [false, actionKey, "+="]); return record; }}, {ALT: () => { return self.SUBRULE(self.actionEqualityRecord, [actionKey]); }}, {ALT: () => { let record = self.SUBRULE(self.actionOperation, [actionKey]); (self.block as any)[actionKey](record); return record; }}, {ALT: () => { return self.SUBRULE(self.actionLookup, [actionKey]); }}, ]) }); //----------------------------------------------------------- // Action operations //----------------------------------------------------------- self.RULE("actionOperation", (actionKey) => { return self.OR([ {ALT: () => { return self.SUBRULE(self.recordOperation, [actionKey]) }}, {ALT: () => { return self.SUBRULE(self.attributeOperation, [actionKey]) }}, ]); }); self.RULE("attributeOperation", (actionKey) => { let mutator = self.SUBRULE(self.attributeMutator) as any; let {attribute, parent} = mutator; return self.OR([ {ALT: () => { let variable = self.block.toVariable(`${attribute.image}|${attribute.startLine}|${attribute.startColumn}`, true); let scan = makeNode("scan", {entity: parent, attribute: makeNode("constant", {value: attribute.image, from: [attribute]}), value: variable, scopes: self.activeScopes, from: [mutator]}); self.block.addUsage(variable, scan); self.block.scan(scan); self.CONSUME(Merge); let record = self.SUBRULE(self.record, [true, actionKey, "+=", undefined, variable]) as any; record.variable = variable; record.action = "<-"; return record; }}, {ALT: () => { let op = self.CONSUME(Set); let none = self.CONSUME(None); return makeNode("action", {action: "erase", entity: asValue(parent), attribute: attribute.image, from: [mutator, op, none]}); }}, {ALT: () => { let op = self.CONSUME2(Set); let value = self.SUBRULE(self.infix); return makeNode("action", {action: op.image, entity: asValue(parent), attribute: attribute.image, value: asValue(value), from: [mutator, op, value]}); }}, {ALT: () => { let op = self.CONSUME3(Set); let value = self.SUBRULE2(self.record, [false, actionKey, "+=", parent]); return makeNode("action", {action: op.image, entity: asValue(parent), attribute: attribute.image, value: asValue(value), from: [mutator, op, value]}); }}, {ALT: () => { let variable = self.block.toVariable(`${attribute.image}|${attribute.startLine}|${attribute.startColumn}`, true); let scan = makeNode("scan", {entity: parent, attribute: makeNode("constant", {value: attribute.image, from: [attribute]}), value: variable, scopes: self.activeScopes, from: [mutator]}); self.block.addUsage(variable, scan); self.block.scan(scan); let op = self.CONSUME(Mutate); let tag : any = self.SUBRULE(self.tag); return makeNode("action", {action: op.image, entity: variable, attribute: "tag", value: makeNode("constant", {value: tag.tag, from: [tag]}), from: [mutator, op, tag]}); }}, {ALT: () => { let op = self.CONSUME2(Mutate); let value: any = self.SUBRULE2(self.actionAttributeExpression, [actionKey, op.image, parent]); if(value.type === "record" && !value.extraProjection) { value.extraProjection = [parent]; } if(value.type === "parenthesis") { let autoIndex = 0; for(let item of value.items) { if(item.type === "record" && !value.extraProjection) { item.extraProjection = [parent]; } if(item.from[0] && item.from[0].type === "record") { let record = item.from[0]; record.attributes.push(makeNode("attribute", {attribute: "eve-auto-index", value: makeNode("constant", {value: autoIndex, from: [record]}), from: [record]})); autoIndex++; } } } return makeNode("action", {action: op.image, entity: asValue(parent), attribute: attribute.image, value: asValue(value), from: [mutator, op, value]}); }}, ]) }); self.RULE("recordOperation", (actionKey) => { let variable = self.SUBRULE(self.variable) as any; return self.OR([ {ALT: () => { let set = self.CONSUME(Set); let none = self.CONSUME(None); return makeNode("action", {action: "erase", entity: asValue(variable), from: [variable, set, none]}); }}, {ALT: () => { self.CONSUME(Merge); let record = self.SUBRULE(self.record, [true, actionKey, "+=", undefined, variable]) as any; record.needsEntity = true; record.action = "<-"; return record; }}, {ALT: () => { let op = self.CONSUME(Mutate); let tag : any = self.SUBRULE(self.tag); return makeNode("action", {action: op.image, entity: asValue(variable), attribute: "tag", value: makeNode("constant", {value: tag.tag, from: [tag]}), from: [variable, op, tag]}); }}, ]) }); self.RULE("actionLookup", (actionKey) => { let lookup = self.CONSUME(Lookup); let record: any = self.SUBRULE(self.record, [true]); let info: any = {}; for(let attribute of record.attributes) { info[attribute.attribute] = attribute.value; } let actionType = "+="; self.OPTION(() => { self.CONSUME(Set); self.CONSUME(None); if(info["value"] !== undefined) { actionType = "-="; } else { actionType = "erase"; } }) let action = makeNode("action", {action: actionType, entity: info.record, attribute: info.attribute, value: info.value, node: info.node, scopes: self.activeScopes, from: [lookup, record]}); (self.block as any)[actionKey](action); return action; }); self.RULE("actionAttributeExpression", (actionKey, action, parent) => { return self.OR([ {ALT: () => { return self.SUBRULE(self.record, [false, actionKey, action, parent]); }}, {ALT: () => { return self.SUBRULE(self.infix); }}, ]) }) self.RULE("actionEqualityRecord", (actionKey) => { let variable = self.SUBRULE(self.variable); self.CONSUME(Equality); let record : any = self.SUBRULE(self.record, [true, actionKey, "+="]); record.variable = variable; (self.block as any)[actionKey](record); return record; }); //----------------------------------------------------------- // Record + attribute //----------------------------------------------------------- self.RULE("record", (noVar = false, blockKey = "scan", action = false, parent?, passedVariable?) => { let attributes:any[] = []; let start = self.CONSUME(OpenBracket); let from: NodeDependent[] = [start]; let info: any = {attributes, action, scopes: self.activeScopes, from}; if(parent) { info.extraProjection = [parent]; } if(passedVariable) { info.variable = passedVariable; info.variable.nonProjecting = true; } else if(!noVar) { info.variable = self.block.toVariable(`record|${start.startLine}|${start.startColumn}`, true); info.variable.nonProjecting = true; } let nonProjecting = false; self.MANY(() => { self.OR([ {ALT: () => { let attribute: any = self.SUBRULE(self.attribute, [false, blockKey, action, info.variable]); // Inline handles attributes itself and so won't return any attribute for us to add // to this object if(!attribute) return; if(attribute.constructor === Array) { for(let attr of attribute as any[]) { attr.nonProjecting = nonProjecting; attributes.push(attr); from.push(attr); } } else { attribute.nonProjecting = nonProjecting; attributes.push(attribute); from.push(attribute); } }}, {ALT: () => { nonProjecting = true; let pipe = self.CONSUME(Pipe); from.push(pipe); return pipe; }}, ]); }) from.push(self.CONSUME(CloseBracket)); let record : any = makeNode("record", info); if(!noVar) { self.block.addUsage(info.variable, record); (self.block as any)[blockKey](record); } return record; }); self.RULE("attribute", (noVar, blockKey, action, recordVariable) => { return self.OR([ {ALT: () => { return self.SUBRULE(self.attributeEquality, [noVar, blockKey, action, recordVariable]); }}, {ALT: () => { return self.SUBRULE(self.attributeComparison); }}, {ALT: () => { return self.SUBRULE(self.attributeNot, [recordVariable]); }}, {ALT: () => { return self.SUBRULE(self.singularAttribute); }}, {ALT: () => { let value: any = self.SUBRULE(self.value); let token = value.from[0]; let message = "Value missing attribute"; if (value.hasOwnProperty("value")) { message = `"${value.value}" needs to be labeled with an attribute`; } self.customErrors.push({ message, name: "Unlabeled value", resyncedTokens: [], context: { ruleOccurrenceStack: [], ruleStack: [] }, token }); }}, ]); }); self.RULE("singularAttribute", (forceGenerate) => { return self.OR([ {ALT: () => { let tag : any = self.SUBRULE(self.tag); return makeNode("attribute", {attribute: "tag", value: makeNode("constant", {value: tag.tag, from: [tag]}), from: [tag]}); }}, {ALT: () => { let variable : any = self.SUBRULE(self.variable, [forceGenerate]); return makeNode("attribute", {attribute: variable.from[0].image, value: variable, from: [variable]}); }}, ]); }); self.RULE("attributeMutator", () => { let scans:any[] = []; let entity:any, attribute:any, value:any; let needsEntity = true; let from:any[] = []; entity = self.SUBRULE(self.variable); let dot = self.CONSUME(Dot); from.push(entity, dot); self.MANY(() => { attribute = self.CONSUME(Identifier); from.push(attribute); from.push(self.CONSUME2(Dot)); value = self.block.toVariable(`${attribute.image}|${attribute.startLine}|${attribute.startColumn}`, true); self.block.addUsage(value, attribute); let scopes = self.activeScopes; if(self.currentAction !== "match") { scopes = self.block.searchScopes; } let scan = makeNode("scan", {entity, attribute: makeNode("constant", {value: attribute.image, from: [value]}), value, needsEntity, scopes, from: [entity, dot, attribute]}); self.block.scan(scan); needsEntity = false; entity = value; }); attribute = self.CONSUME2(Identifier); from.push(attribute); return makeNode("attributeMutator", {attribute: attribute, parent: entity, from}); }); self.RULE("attributeAccess", () => { let scans:any[] = []; let entity:any, attribute:any, value:any; let needsEntity = true; entity = self.SUBRULE(self.variable); let parentId = entity.name; self.AT_LEAST_ONE(() => { let dot = self.CONSUME(Dot); attribute = self.CONSUME(Identifier); parentId = `${parentId}|${attribute.image}`; value = self.block.toVariable(parentId, true); self.block.addUsage(value, attribute); let scopes = self.activeScopes; if(self.currentAction !== "match") { scopes = self.block.searchScopes; } let scan = makeNode("scan", {entity, attribute: makeNode("constant", {value: attribute.image, from: [attribute]}), value, needsEntity, scopes, from: [entity, dot, attribute]}); self.block.scan(scan); needsEntity = false; entity = value; }); return value; }); self.RULE("attributeEquality", (noVar, blockKey, action, parent) => { let attributes:any[] = []; let autoIndex = 1; let attributeNode:any; let attribute: any = self.OR([ {ALT: () => { attributeNode = self.CONSUME(Identifier); return attributeNode.image; }}, {ALT: () => { attributeNode = self.CONSUME(Num); return parseFloat(attributeNode.image) as any; }} ]); let equality = self.CONSUME(Equality); let result : any; self.OR2([ {ALT: () => { result = self.SUBRULE(self.infix); // if the result is a parenthesis, we have to make sure that if there are sub-records // inside that they get eve-auto-index set on them and they also have the parent transfered // down to them. If we don't do this, we'll end up with children that are shared between // the parents instead of one child per parent. if(result.type === "parenthesis") { for(let item of result.items) { // this is a bit sad, but by the time we see the parenthesis, the records have been replaced // with their variables. Those variables are created from the record object though, so we can // check the from of the variable for a reference to the record. if(item.type === "variable" && item.from[0] && item.from[0].type === "record") { let record = item.from[0]; // if we have a parent, we need to make sure it ends up part of our extraProjection set if(parent && !item.extraProjection) { record.extraProjection = [parent]; } else if(parent) { record.extraProjection.push(parent); } // Lastly we need to add the eve-auto-index attribute to make sure this is consistent with the case // where we leave the parenthesis off and just put records one after another. record.attributes.push(makeNode("attribute", {attribute: "eve-auto-index", value: makeNode("constant", {value: autoIndex, from: [record]}), from: [record]})); autoIndex++; } } } }}, {ALT: () => { result = self.SUBRULE(self.record, [noVar, blockKey, action, parent]); self.MANY(() => { autoIndex++; let record : any = self.SUBRULE2(self.record, [noVar, blockKey, action, parent]); record.attributes.push(makeNode("attribute", {attribute: "eve-auto-index", value: makeNode("constant", {value: autoIndex, from: [record]}), from: [record]})); attributes.push(makeNode("attribute", {attribute, value: asValue(record), from: [attributeNode, equality, record]})); }) if(autoIndex > 1) { result.attributes.push(makeNode("attribute", {attribute: "eve-auto-index", value: makeNode("constant", {value: 1, from: [result]}), from: [result]})); } }}, ]); attributes.push(makeNode("attribute", {attribute, value: asValue(result), from: [attributeNode, equality, result]})) return attributes; }); self.RULE("attributeComparison", () => { let attribute = self.CONSUME(Identifier); let comparator = self.CONSUME(Comparison); let result = self.SUBRULE(self.expression); let variable = self.block.toVariable(`attribute|${attribute.startLine}|${attribute.startColumn}`, true); let expression = makeNode("expression", {op: `compare/${comparator.image}`, args: [asValue(variable), asValue(result)], from: [attribute, comparator, result]}) self.block.addUsage(variable, expression); self.block.expression(expression); return makeNode("attribute", {attribute: attribute.image, value: variable, from: [attribute, comparator, expression]}); }); self.RULE("attributeNot", (recordVariable) => { let block = pushBlock(); block.type = "not"; let not = self.CONSUME(Not); let start = self.CONSUME(OpenParen); let attribute: any = self.OR([ {ALT: () => { return self.SUBRULE(self.attributeComparison); }}, {ALT: () => { return self.SUBRULE(self.singularAttribute, [true]); }}, ]); let end = self.CONSUME(CloseParen); // we have to add a record for this guy let scan : any = makeNode("scan", {entity: recordVariable, attribute: makeNode("constant", {value: attribute.attribute, from: [attribute]}), value: attribute.value, needsEntity: true, scopes: self.activeScopes, from: [attribute]}); block.variables[recordVariable.name] = recordVariable; block.scan(scan); block.from = [not, start, attribute, end]; block.startOffset = not.startOffset; block.endOffset = toEnd(end); popBlock(); self.block.scan(block); return; }); //----------------------------------------------------------- // Name and tag //----------------------------------------------------------- self.RULE("name", () => { let at = self.CONSUME(Name); let name = self.CONSUME(Identifier); self.customErrors.push({message: `Databases have been deprecated, so @${name.image} has no meaning here`, name: "Database deprecation", resyncedTokens: [], context:{ruleOccurrenceStack: [], ruleStack: []}, token:name}) return makeNode("name", {name: name.image, from: [at, name]}); }); self.RULE("tag", () => { let hash = self.CONSUME(Tag); let tag = self.CONSUME(Identifier); return makeNode("tag", {tag: tag.image, from: [hash, tag]}); }); //----------------------------------------------------------- // Function //----------------------------------------------------------- self.RULE("functionRecord", (): any => { let name = self.OR([ {ALT: () => { return self.CONSUME(FunctionIdentifier); }}, {ALT: () => { return self.CONSUME(Lookup); }} ]); let record: any = self.SUBRULE(self.record, [true]); if(name.image === "lookup") { let info: any = {}; for(let attribute of record.attributes) { info[attribute.attribute] = attribute.value; } let scan = makeNode("scan", {entity: info.record, attribute: info.attribute, value: info.value, node: info.node, scopes: self.activeScopes, from: [name, record]}); self.block.scan(scan); return scan; } else { let variable = self.block.toVariable(`return|${name.startLine}|${name.startColumn}`, true); let functionRecord = makeNode("functionRecord", {op: name.image, record, variable, from: [name, record]}); self.block.addUsage(variable, functionRecord); self.block.expression(functionRecord); return functionRecord; } }); //----------------------------------------------------------- // Comparison //----------------------------------------------------------- self.RULE("comparison", (nonFiltering) : any => { let left = self.SUBRULE(self.expression); let from = [left]; let rights:any[] = []; self.MANY(() => { let comparator = self.OR([ {ALT: () => { return self.CONSUME(Comparison); }}, {ALT: () => { return self.CONSUME(Equality); }} ]); let value = self.OR2([ {ALT: () => { return self.SUBRULE2(self.expression); }}, {ALT: () => { return self.SUBRULE(self.ifExpression); }} ]); from.push(comparator, value); rights.push({comparator, value}); }) if(rights.length) { let expressions = []; let curLeft: any = left; for(let pair of rights) { let {comparator, value} = pair; let expression = null; // if this is a nonFiltering comparison, then we return an expression // with a variable for its return value if(nonFiltering) { let variable = self.block.toVariable(`comparison|${comparator.startLine}|${comparator.startColumn}`, true); expression = makeNode("expression", {variable, op: `compare/${comparator.image}`, args: [asValue(curLeft), asValue(value)], from: [curLeft, comparator, value]}); self.block.addUsage(variable, expression); self.block.expression(expression); } else if(tokenMatcher(comparator, Equality)) { if(value.type === "choose" || value.type === "union") { value.outputs = ifOutputs(left); self.block.scan(value); } else if(value.type === "functionRecord" && curLeft.type === "parenthesis") { value.returns = curLeft.items.map(asValue); self.block.equality(asValue(value.returns[0]), asValue(value)); } else if(curLeft.type === "parenthesis") { throw new Error("Left hand parenthesis without an if or function on the right"); } else { self.block.equality(asValue(curLeft), asValue(value)); } } else { expression = makeNode("expression", {op: `compare/${comparator.image}`, args: [asValue(curLeft), asValue(value)], from: [curLeft, comparator, value]}); self.block.expression(expression); } curLeft = value; if(expression) { expressions.push(expression); } } return makeNode("comparison", {expressions, from}); }; return left; }); //----------------------------------------------------------- // Special Forms //----------------------------------------------------------- self.RULE("notStatement", () => { let block = pushBlock(); block.type = "not"; let from: NodeDependent[] = [ self.CONSUME(Not), self.CONSUME(OpenParen), ]; self.MANY(() => { from.push(self.SUBRULE(self.statement) as ParseNode); }); from.push(self.CONSUME(CloseParen)); popBlock(); block.from = from; block.startOffset = from[0].startOffset; block.endOffset = toEnd(from[from.length - 1]); self.block.scan(block); return; }); //----------------------------------------------------------- // If ... then //----------------------------------------------------------- self.RULE("ifExpression", () => { let branches:any[] = []; let exclusive = false; let from = branches; branches.push(self.SUBRULE(self.ifBranch)); self.MANY(() => { branches.push(self.OR([ {ALT: () => { return self.SUBRULE2(self.ifBranch); }}, {ALT: () => { exclusive = true; return self.SUBRULE(self.elseIfBranch); }}, ])); }); self.OPTION(() => { exclusive = true; branches.push(self.SUBRULE(self.elseBranch)); }); let expressionType = exclusive ? "choose" : "union"; return makeNode(expressionType, {branches, from}); }); self.RULE("ifBranch", () => { let block = pushBlock(); let from: NodeDependent[] = [ self.CONSUME(If) ] self.AT_LEAST_ONE(() => { let statement = self.SUBRULE(self.statement) as ParseNode; if(statement) { from.push(statement); } }) from.push(self.CONSUME(Then)); let expression = self.SUBRULE(self.expression) as ParseNode; from.push(expression); block.startOffset = from[0].startOffset; block.endOffset = toEnd(from[from.length - 1]); popBlock(); return makeNode("ifBranch", {block, outputs: ifOutputs(expression), exclusive: false, from}); }); self.RULE("elseIfBranch", () => { let block = pushBlock(); let from: NodeDependent[] = [ self.CONSUME(Else), self.CONSUME(If), ] self.AT_LEAST_ONE(() => { let statement = self.SUBRULE(self.statement) as ParseNode; if(statement) { from.push(statement); } }) from.push(self.CONSUME(Then)); let expression = self.SUBRULE(self.expression) as ParseNode; from.push(expression); block.startOffset = from[0].startOffset; block.endOffset = toEnd(from[from.length - 1]); popBlock(); return makeNode("ifBranch", {block, outputs: ifOutputs(expression), exclusive: true, from}); }); self.RULE("elseBranch", () => { let block = pushBlock(); let from: NodeDependent[] = [self.CONSUME(Else)]; let expression = self.SUBRULE(self.expression) as ParseNode; from.push(expression); block.startOffset = from[0].startOffset; block.endOffset = toEnd(from[from.length - 1]); popBlock(); return makeNode("ifBranch", {block, outputs: ifOutputs(expression), exclusive: true, from}); }); //----------------------------------------------------------- // Infix and operator precedence //----------------------------------------------------------- self.RULE("infix", () => { return self.SUBRULE(self.addition); }); self.RULE("addition", () : any => { let left = self.SUBRULE(self.multiplication); let from = [left]; let ops:any[] = []; self.MANY(function() { let op = self.CONSUME(AddInfix); let right = self.SUBRULE2(self.multiplication); from.push(op, right); ops.push({op, right}) }); if(!ops.length) { return left; } else { let expressions = []; let curVar; let curLeft = left; for(let pair of ops) { let {op, right} = pair; curVar = self.block.toVariable(`addition|${op.startLine}|${op.startColumn}`, true); let expression = makeNode("expression", {op: `math/${op.image}`, args: [asValue(curLeft), asValue(right)], variable: curVar, from: [curLeft, op, right]}); expressions.push(expression); self.block.addUsage(curVar, expression); self.block.expression(expression) curLeft = expression; } return makeNode("addition", {expressions, variable: curVar, from}); } }); self.RULE("multiplication", () : any => { let left = self.SUBRULE(self.infixValue); let from = [left]; let ops:any = []; self.MANY(function() { let op = self.CONSUME(MultInfix); let right = self.SUBRULE2(self.infixValue); from.push(op, right); ops.push({op, right}) }); if(!ops.length) { return left; } else { let expressions = []; let curVar; let curLeft = left; for(let pair of ops) { let {op, right} = pair; curVar = self.block.toVariable(`addition|${op.startLine}|${op.startColumn}`, true); let expression = makeNode("expression", {op: `math/${op.image}`, args: [asValue(curLeft), asValue(right)], variable: curVar, from: [curLeft, op, right]}); expressions.push(expression); self.block.addUsage(curVar, expression); self.block.expression(expression) curLeft = expression; } return makeNode("multiplication", {expressions, variable: curVar, from}); } }); self.RULE("parenthesis", () => { let items:any[] = []; let from:any[] = []; from.push(self.CONSUME(OpenParen)); self.AT_LEAST_ONE(() => { let item = self.SUBRULE(self.expression); items.push(asValue(item)); from.push(item); }) from.push(self.CONSUME(CloseParen)); if(items.length === 1) { return items[0]; } return makeNode("parenthesis", {items, from}); }); self.RULE("infixValue", () => { return self.OR([ {ALT: () => { return self.SUBRULE(self.attributeAccess); }}, {ALT: () => { return self.SUBRULE(self.functionRecord); }}, {ALT: () => { return self.SUBRULE(self.variable); }}, {ALT: () => { return self.SUBRULE(self.value); }}, {ALT: () => { return self.SUBRULE(self.parenthesis); }}, ]); }) //----------------------------------------------------------- // Expression //----------------------------------------------------------- self.RULE("expression", () => { let blockKey:any, action:any; if(self.currentAction !== "match") { blockKey = self.currentAction; action = "+="; } return self.OR([ {ALT: () => { return self.SUBRULE(self.infix); }}, {ALT: () => { return self.SUBRULE(self.record, [false, blockKey, action]); }}, ]); }); //----------------------------------------------------------- // Variable //----------------------------------------------------------- self.RULE("variable", (forceGenerate = false) => { let token = self.CONSUME(Identifier); let name = token.image; if(forceGenerate) { name = `${token.image}-${token.startLine}-${token.startColumn}`; } let variable = self.block.toVariable(name!, forceGenerate); self.block.addUsage(variable, token); return variable; }); //----------------------------------------------------------- // Values //----------------------------------------------------------- self.RULE("stringInterpolation", () : any => { let args:any[] = []; let start = self.CONSUME(OpenString); let from: NodeDependent[] = [start]; self.MANY(() => { let arg = self.OR([ {ALT: () => { let str = self.CONSUME(StringChars)!; return makeNode("constant", {value: cleanString(str.image!), from: [str]}); }}, {ALT: () => { self.CONSUME(StringEmbedOpen); let expression = self.SUBRULE(self.infix); self.CONSUME(StringEmbedClose); return expression; }}, ]); args.push(asValue(arg)); from.push(arg as ParseNode); }); from.push(self.CONSUME(CloseString)); if(args.length === 1 && args[0].type === "constant") { return args[0]; } else if(args.length === 0) { return makeNode("constant", {value: "", from}); } let variable = self.block.toVariable(`concat|${start.startLine}|${start.startColumn}`, true); let expression = makeNode("expression", {op: "eve/internal/concat", args, variable, from}); self.block.addUsage(variable, expression); self.block.expression(expression); return expression; }); self.RULE("value", () => { return self.OR([ {ALT: () => { return self.SUBRULE(self.stringInterpolation) }}, {ALT: () => { return self.SUBRULE(self.num) }}, {ALT: () => { return self.SUBRULE(self.bool) }}, ]) }) self.RULE("bool", () => { let value = self.CONSUME(Bool); return makeNode("constant", {value: value.image === "true", from: [value]}); }) self.RULE("num", () => { let num = self.CONSUME(Num); return makeNode("constant", {value: parseFloat(num.image!), from: [num]}) ; }); //----------------------------------------------------------- // Chevrotain analysis //----------------------------------------------------------- Parser.performSelfAnalysis(this); } } //----------------------------------------------------------- // Public API //----------------------------------------------------------- export function nodeToBoundaries(node:any, offset = 0) { return [node.startOffset, toEnd(node)]; } let eveParser = new Parser([]); export function parseBlock(block:any, blockId:string, offset = 0, spans:any[] = [], extraInfo:any = {}) { let lex: any = EveBlockLexer.tokenize(block); let token: any; let tokenIx = 0; for(token of lex.tokens) { let tokenId = `${blockId}|token|${tokenIx++}`; token.id = tokenId; token.startOffset += offset; spans.push(token.startOffset, token.startOffset + token.image.length, token.label, tokenId); } for(token of lex.groups.comments) { let tokenId = `${blockId}|token|${tokenIx++}`; token.id = tokenId; token.startOffset += offset; spans.push(token.startOffset, token.startOffset + token.image.length, token.label, tokenId); } eveParser.input = lex.tokens; let results; try { eveParser.customErrors = []; // The parameters here are a strange quirk of how Chevrotain works, I believe the // 1 tells chevrotain what level the rule is starting at, we then pass our params // to the codeBlock parser function as an array results = eveParser.codeBlock(1, [blockId]); } catch(e) { console.error("The parser threw an error: " + e); } if(results) { results.start = offset; results.startOffset = offset; results.tokens = lex.tokens; for(let scan of results.scanLike) { let type = "scan-boundary"; if(scan.type === "record") { type = "record-boundary"; } spans.push(scan.startOffset, scan.endOffset, type, scan.id); } for(let action of results.binds) { let type = "action-boundary"; if(action.type === "record") { type = "action-record-boundary"; } spans.push(action.startOffset, action.endOffset, type, action.id); extraInfo[action.id] = {kind: "bind"}; } for(let action of results.commits) { let type = "action-boundary"; if(action.type === "record") { type = "action-record-boundary"; } spans.push(action.startOffset, action.endOffset, type, action.id); extraInfo[action.id] = {kind: "commits"}; } } let errors = parserErrors(eveParser.errors.concat(eveParser.customErrors), {blockId, blockStart: offset, spans, extraInfo, tokens: lex.tokens}); lex.groups.comments.length = 0; return { results, lex, errors, } } let docIx = 0; export function parseDoc(doc:string, docId = `doc|${docIx++}`) { let {text, spans, blocks, extraInfo} = parseMarkdown(doc, docId); let parsedBlocks = []; let allErrors = []; for(let block of blocks) { extraInfo[block.id] = {info: block.info, block}; if(block.info.indexOf("disabled") > -1) { extraInfo[block.id].disabled = true; } if(block.info !== "" && block.info.indexOf("eve") === -1) continue; let {results, lex, errors} = parseBlock(block.literal, block.id, block.startOffset, spans, extraInfo); // if this block is disabled, we want the parsed spans and such, but we don't want // the block to be in the set sent to the builder if(!extraInfo[block.id].disabled) { if(errors.length) { allErrors.push(errors); } else if(results) { results.endOffset = block.endOffset; parsedBlocks.push(results); } } } let eavs:any[] = []; for(let block of parsedBlocks) { //if(typeof process === "undefined") console.log(block); toFacts(eavs, block); } for(let errorSet of allErrors) { for(let error of errorSet) { errorToFacts(eavs, error, extraInfo[error.blockId].block); } } return { results: {blocks: parsedBlocks, text, spans, extraInfo, eavs}, errors: allErrors, } } export function errorToFacts(eavs:any[], error:EveError, block:any) { let text = block.literal; let offset = block.startOffset; let blockStartLine = block.sourcepos[0][0]; let blockLines = text.split("\n"); let pos = 0; let start = error.start - offset; let stop = error.stop - offset; if(isNaN(stop)) stop = text.length + offset; if(isNaN(start)) start = offset; let curLine = 0; let startLine = 0; let startChar = 0; let stopLine = 0; let stopChar = 0; while(curLine < blockLines.length && pos < start) { pos += blockLines[curLine++].length + 1; } startLine = blockStartLine + curLine; startChar = start - (pos - (blockLines[curLine - 1] || "").length) + 2; while(curLine < blockLines.length && pos < stop) { pos += (blockLines[curLine++] || "").length + 1; } stopLine = blockStartLine + curLine; stopChar = stop - (pos - (blockLines[curLine - 1] || "").length) + 2; let sampleText = []; let relativeStart = startLine - blockStartLine; let relativeStop = stopLine - blockStartLine; if(relativeStart != 0) { sampleText.push(blockLines[relativeStart - 1]); sampleText.push(blockLines[relativeStart]); } if(relativeStop > relativeStart) { let cur = relativeStart; while(cur <= relativeStop) { sampleText.push(blockLines[cur]); cur++; } } if(relativeStop < blockLines.length && blockLines[relativeStop + 1]) { sampleText.push(blockLines[relativeStop + 1]); } let errorId = uuid(); let startId = uuid(); let stopId = uuid(); eavs.push([errorId, "tag", "eve/compiler/error"]); eavs.push([errorId, "message", error.message]); eavs.push([errorId, "start", startId]); eavs.push([startId, "line", startLine]); eavs.push([startId, "char", startChar]); eavs.push([errorId, "stop", stopId]); eavs.push([stopId, "line", stopLine]); eavs.push([stopId, "char", stopChar]); eavs.push([errorId, "sample", sampleText.join("\n")]) } export function recordToFacts(eavs:any[], vars:any, scanLike:any) { let rec = uuid(); eavs.push([rec, "tag", "eve/compiler/record"]); eavs.push([rec, "record", vars[scanLike.variable.name]]); for(let attr of scanLike.attributes) { if(attr.type === "attribute") { let values; if(attr.value && attr.value.type === "parenthesis") { values = attr.value.items; } else { values = [attr.value]; } for(let value of values) { let attrId = uuid(); eavs.push([attrId, "attribute", attr.attribute]); eavs.push([attrId, "value", asFactValue(vars, value)]); eavs.push([rec, "attribute", attrId]); } } } return rec; } function asFactValue(vars:any, value:any) { if(typeof value !== "object") return value; return value.type == "constant" ? value.value : vars[value.name]; } export function outputToFacts(eavs:any[], vars:any, scanLike:any, blockId:string) { let rec = uuid(); eavs.push([rec, "tag", "eve/compiler/output"]); eavs.push([rec, "record", vars[scanLike.variable.name]]); if(scanLike.action === "-=" || scanLike.action === "erase") { eavs.push([rec, "tag", "eve/compiler/remove"]); } else if(scanLike.action === ":=" || scanLike.action === "<-") { let attrs = []; for(let attribute of scanLike.attributes) { attribute.nonProjecting = true; if(attribute.type === "attribute") { if(scanLike.action === ":=" || (attribute.attribute !== "tag")) { attrs.push({type: "attribute", attribute: attribute.attribute, nonProjecting:true}); } } } outputToFacts(eavs, vars, {variable:scanLike.variable, action: "erase", attributes:attrs}, blockId); } for(let attr of scanLike.attributes) { if(attr.type === "attribute") { let values; if(attr.value && attr.value.type === "parenthesis") { values = attr.value.items; } else { values = [attr.value]; } for(let value of values) { let attrId = uuid(); eavs.push([attrId, "attribute", asFactValue(vars, attr.attribute)]); if(value) { eavs.push([attrId, "value", asFactValue(vars, value)]); } if(attr.nonProjecting) { eavs.push([attrId, "tag", "eve/compiler/attribute/non-identity"]); } eavs.push([rec, "attribute", attrId]); } } } eavs.push([blockId, "constraint", rec]); return rec; } function subBlockToFacts(eavs:any[], vars:any, blockId: string, block:any) { for(let [left, right] of block.equalities) { let eqId = uuid(); eavs.push([eqId, "tag", "eve/compiler/equality"]); eavs.push([eqId, "left", asFactValue(vars, left)]); eavs.push([eqId, "right", asFactValue(vars, right)]); eavs.push([blockId, "constraint", eqId]); } for(let scanLike of block.scanLike) { switch(scanLike.type) { case "record": let constraint = recordToFacts(eavs, vars, scanLike); eavs.push([blockId, "constraint", constraint]); break; case "scan": let lookupId = uuid(); eavs.push([lookupId, "tag", "eve/compiler/lookup"]); eavs.push([lookupId, "record", asFactValue(vars, scanLike.entity)]); eavs.push([lookupId, "attribute", asFactValue(vars, scanLike.attribute)]); eavs.push([lookupId, "value", asFactValue(vars, scanLike.value)]); eavs.push([blockId, "constraint", lookupId]); break; case "not": let notId = uuid(); eavs.push([notId, "tag", "eve/compiler/not"]); eavs.push([notId, "tag", "eve/compiler/block"]); eavs.push([blockId, "constraint", notId]); subBlockToFacts(eavs, vars, notId, scanLike); break; case "choose": case "union": let chooseId = uuid(); if(scanLike.type === "choose") { eavs.push([chooseId, "tag", "eve/compiler/choose"]); } else { eavs.push([chooseId, "tag", "eve/compiler/union"]); } eavs.push([chooseId, "tag", "eve/compiler/branch-set"]); eavs.push([blockId, "constraint", chooseId]); for(let branch of scanLike.branches) { let branchId = uuid(); eavs.push([chooseId, "branch", branchId]); eavs.push([branchId, "tag", "eve/compiler/block"]); subBlockToFacts(eavs, vars, branchId, branch.block); let ix = 1; for(let output of branch.outputs) { let outputId = uuid(); eavs.push([branchId, "output", outputId]); eavs.push([outputId, "value", asFactValue(vars, output)]); eavs.push([outputId, "index", ix]); ix++; } } let ix = 1; for(let output of scanLike.outputs) { let outputId = uuid(); eavs.push([chooseId, "output", outputId]); eavs.push([outputId, "value", asFactValue(vars, output)]); eavs.push([outputId, "index", ix]); ix++; } break; } } for(let expr of block.expressions) { let exprId = uuid(); let isAggregate = expr.op.indexOf("gather/") === 0; eavs.push([blockId, "constraint", exprId]); eavs.push([exprId, "tag", "eve/compiler/expression"]); if(isAggregate) { eavs.push([exprId, "tag", "eve/compiler/aggregate"]); } eavs.push([exprId, "op", expr.op]); if(expr.type === "expression") { let ix = 1; for(let arg of expr.args) { let argId = uuid(); eavs.push([exprId, "arg", argId]); eavs.push([argId, "index", ix]); eavs.push([argId, "value", asFactValue(vars, arg)]); ix++; } if(expr.variable) { let returnId = uuid(); eavs.push([exprId, "return", returnId]); eavs.push([returnId, "index", 1]); eavs.push([returnId, "value", asFactValue(vars, expr.variable)]); } } else if(expr.type === "functionRecord") { for(let arg of expr.record.attributes) { let ix = 1; if(arg.value.type === "parenthesis") { for(let value of arg.value.items) { let argId = uuid(); eavs.push([exprId, "arg", argId]); eavs.push([argId, "name", arg.attribute]); eavs.push([argId, "value", asFactValue(vars, value)]); eavs.push([argId, "index", ix]); ix++; } } else { let argId = uuid(); eavs.push([exprId, "arg", argId]); eavs.push([argId, "name", arg.attribute]); eavs.push([argId, "value", asFactValue(vars, arg.value)]); eavs.push([argId, "index", ix]); } } if(expr.returns) { let ix = 1; for(let ret of expr.returns) { let returnId = uuid(); eavs.push([exprId, "return", returnId]); eavs.push([returnId, "index", ix]); eavs.push([returnId, "value", asFactValue(vars, ret.value)]); ix++; } } else if(expr.variable) { let returnId = uuid(); eavs.push([exprId, "return", returnId]); eavs.push([returnId, "index", 1]); eavs.push([returnId, "value", asFactValue(vars, expr.variable)]); } } } } export function toFacts(eavs:any[], block:any) { let blockId = uuid(); eavs.push([blockId, "tag", "eve/compiler/rule"]); eavs.push([blockId, "tag", "eve/compiler/block"]); eavs.push([blockId, "name", block.id]); let blockType = "bind"; if(block.commits.length) { blockType = "commit"; } eavs.push([blockId, "type", blockType]); let vars:any = {}; for(let variable in block.variableLookup) { let varId = uuid(); vars[variable] = varId; eavs.push([varId, "tag", "eve/compiler/var"]); } subBlockToFacts(eavs, vars, blockId, block); let outputs = block.binds.concat(block.commits); for(let output of outputs) { switch(output.type) { case "record": outputToFacts(eavs, vars, output, blockId); break; case "action": outputToFacts(eavs, vars, { action: output.action, variable: output.entity, attributes: [{type: "attribute", attribute: output.attribute, value: output.value, nonProjecting: true}] }, blockId) break; } } return eavs; // let lookup = find("eve/compiler/lookup"); // let {record:rec, attribute, value} = lookup; }
the_stack
import aceEvent, { AceEvent } from "@wowts/ace_event-3.0"; import { LuaArray, LuaObj, pairs } from "@wowts/lua"; import { huge as infinity } from "@wowts/math"; import { AceModule } from "@wowts/tsaddon"; import { GetTime, SpellId, TalentId } from "@wowts/wow-mock"; import { DebugTools, Tracer } from "../engine/debug"; import { SpellCastEventHandler, States, StateModule } from "../engine/state"; import { OvaleClass } from "../Ovale"; import { OvaleAuraClass } from "./Aura"; import { OvalePaperDollClass } from "./PaperDoll"; import { OvaleSpellBookClass } from "./SpellBook"; interface BloodtalonsTriggerAura { start: number; ending: number; } class BloodtalonsData { // eslint-disable-next-line @typescript-eslint/naming-convention brutal_slash: BloodtalonsTriggerAura = { start: 0, ending: 0 }; // eslint-disable-next-line @typescript-eslint/naming-convention moonfire_cat: BloodtalonsTriggerAura = { start: 0, ending: 0 }; rake: BloodtalonsTriggerAura = { start: 0, ending: 0 }; shred: BloodtalonsTriggerAura = { start: 0, ending: 0 }; // eslint-disable-next-line @typescript-eslint/naming-convention swipe_cat: BloodtalonsTriggerAura = { start: 0, ending: 0 }; // eslint-disable-next-line @typescript-eslint/naming-convention thrash_cat: BloodtalonsTriggerAura = { start: 0, ending: 0 }; } type BloodtalonsTrigger = keyof BloodtalonsData; const btTriggerIdByName: LuaObj<number> = { brutal_slash: SpellId.brutal_slash, moonfire_cat: 115625, rake: SpellId.rake, shred: SpellId.shred, swipe_cat: 106785, thrash_cat: 106830, }; const btTriggerNameById: LuaArray<BloodtalonsTrigger> = {}; for (const [name, spellId] of pairs(btTriggerIdByName)) { const btTrigger = name as BloodtalonsTrigger; btTriggerNameById[spellId] = btTrigger; } /* Number of seconds for the window in which abilities must be cast * in order to proc Bloodtalons. The countdown starts after the GCD * of the cast is complete, which effectively expands the window by * one second. */ const btWindow = 4 + 1; /* Number of combo point generators that must be cast in the window * in order to proc Bloodtalons. */ const btThreshold = 3; // Number of charges in a Bloodtalons buff proc. const btMaxCharges = 2; export class Bloodtalons extends States<BloodtalonsData> implements StateModule { private module: AceModule & AceEvent; private tracer: Tracer; private hasBloodtalonsHandlers = false; constructor( private ovale: OvaleClass, debug: DebugTools, private aura: OvaleAuraClass, private paperDoll: OvalePaperDollClass, private spellBook: OvaleSpellBookClass ) { super(BloodtalonsData); this.module = ovale.createModule( "Bloodtalons", this.onEnable, this.onDisable, aceEvent ); this.tracer = debug.create(this.module.GetName()); } private onEnable = () => { if (this.ovale.playerClass == "DRUID") { this.module.RegisterMessage( "Ovale_SpecializationChanged", this.onOvaleSpecializationChanged ); const specialization = this.paperDoll.getSpecialization(); this.onOvaleSpecializationChanged( "onEnable", specialization, specialization ); } }; private onDisable = () => { if (this.ovale.playerClass == "DRUID") { this.module.UnregisterMessage("Ovale_SpecializationChanged"); this.module.UnregisterMessage("Ovale_TalentsChanged"); this.unregisterBloodtalonsHandlers(); } }; private onOvaleSpecializationChanged = ( event: string, newSpecialization: string, oldSpecialization: string ) => { if (newSpecialization == "feral") { this.module.RegisterMessage( "Ovale_TalentsChanged", this.onOvaleTalentsChanged ); this.onOvaleTalentsChanged(event); } }; private onOvaleTalentsChanged = (event: string) => { const hasBloodtalonsTalent = this.spellBook.getTalentPoints(TalentId.bloodtalons_talent) > 0; if (hasBloodtalonsTalent) { this.registerBloodtalonsHandlers(); } else { this.unregisterBloodtalonsHandlers(); } }; private registerBloodtalonsHandlers = () => { if (!this.hasBloodtalonsHandlers) { this.tracer.debug("Installing Bloodtalons event handlers."); this.module.RegisterEvent( "UNIT_SPELLCAST_SUCCEEDED", this.onUnitSpellCastSucceeded ); this.module.RegisterMessage( "Ovale_AuraAdded", this.onOvaleAuraAddedOrChanged ); this.module.RegisterMessage( "Ovale_AuraChanged", this.onOvaleAuraAddedOrChanged ); this.hasBloodtalonsHandlers = true; } }; private unregisterBloodtalonsHandlers = () => { if (this.hasBloodtalonsHandlers) { this.tracer.debug("Removing Bloodtalons event handlers."); this.module.UnregisterEvent("UNIT_SPELLCAST_SUCCEEDED"); this.module.UnregisterMessage("Ovale_AuraAdded"); this.module.UnregisterMessage("Ovale_AuraChanged"); this.hasBloodtalonsHandlers = false; } }; private onUnitSpellCastSucceeded = ( event: string, unit: string, castGUID: string, spellId: number ) => { if (unit === "player") { const name = btTriggerNameById[spellId]; if (name) { const now = GetTime(); const btTrigger = name as BloodtalonsTrigger; const aura = this.current[btTrigger]; aura.start = now; aura.ending = now + btWindow; if (this.tracer.isDebugging()) { const [active] = this.getActiveTrigger(); this.tracer.debug( `active: ${active}, ${name} (${spellId})` ); } } } }; private onOvaleAuraAddedOrChanged = ( event: string, atTime: number, guid: string, auraId: number, caster: string ) => { if ( guid === caster && guid === this.ovale.playerGUID && auraId === SpellId.bloodtalons_buff ) { let resetTriggers = false; if (event === "Ovale_AuraAdded") { resetTriggers = true; } else if (event === "Ovale_AuraChanged") { const aura = this.aura.getAuraByGUID( guid, auraId, undefined, true, atTime ); if (aura) { // Bloodtalons procced again if it's at max stacks. resetTriggers = aura.stacks === btMaxCharges; } } if (resetTriggers) { this.tracer.debug("active: 0, Bloodtalons proc!"); for (const [name] of pairs(btTriggerIdByName)) { const btTrigger = name as BloodtalonsTrigger; const aura = this.current[btTrigger]; aura.start = 0; aura.ending = 0; } } } }; getActiveTrigger(atTime?: number, name?: string) { const state = this.getState(atTime); atTime = atTime || GetTime(); if (name === undefined) { let numActive = 0; let start = 0; let ending = infinity; for (const [name] of pairs(btTriggerIdByName)) { const btTrigger = name as BloodtalonsTrigger; const aura = state[btTrigger]; if (aura.start <= atTime && atTime < aura.ending) { numActive += 1; if (start < aura.start) { start = aura.start; } if (ending > aura.ending) { ending = aura.ending; } } } if (numActive > 0) { return [numActive, start, ending]; } } else if (btTriggerIdByName[name]) { const btTrigger = name as BloodtalonsTrigger; const aura = state[btTrigger]; if (aura.start <= atTime && atTime < aura.ending) { return [1, aura.start, aura.ending]; } } return [0, 0, infinity]; } // State module initializeState() {} resetState() { if (this.hasBloodtalonsHandlers) { const current = this.current; const state = this.next; for (const [name] of pairs(btTriggerIdByName)) { const btTrigger = name as BloodtalonsTrigger; state[btTrigger].start = current[btTrigger].start; state[btTrigger].ending = current[btTrigger].ending; } } } cleanState() {} applySpellAfterCast: SpellCastEventHandler = ( spellId, targetGUID, startCast, endCast, channel, spellcast ) => { if (this.hasBloodtalonsHandlers) { const name = btTriggerNameById[spellId]; if (name) { const btTrigger = name as BloodtalonsTrigger; const aura = this.next[btTrigger]; aura.start = endCast; aura.ending = endCast + btWindow; const [active] = this.getActiveTrigger(endCast); if (active >= btThreshold) { for (const [name] of pairs(btTriggerIdByName)) { const trigger = name as BloodtalonsTrigger; const triggerAura = this.next[trigger]; triggerAura.start = 0; triggerAura.ending = 0; } } this.triggerBloodtalons(endCast); } } }; private triggerBloodtalons = (atTime: number) => { this.tracer.log("Triggering Bloodtalons."); const aura = this.aura.addAuraToGUID( this.ovale.playerGUID, SpellId.bloodtalons_buff, this.ovale.playerGUID, "HELPFUL", undefined, atTime, atTime + 30, // Bloodtalons lasts 30 seconds atTime ); aura.stacks = btMaxCharges; }; }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/projectsMappers"; import * as Parameters from "../models/parameters"; import { MLTeamAccountManagementClientContext } from "../mLTeamAccountManagementClientContext"; /** Class representing a Projects. */ export class Projects { private readonly client: MLTeamAccountManagementClientContext; /** * Create a Projects. * @param {MLTeamAccountManagementClientContext} client Reference to the service client. */ constructor(client: MLTeamAccountManagementClientContext) { this.client = client; } /** * Gets the properties of the specified machine learning project. * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param [options] The optional parameters * @returns Promise<Models.ProjectsGetResponse> */ get(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsGetResponse>; /** * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param callback The callback */ get(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, callback: msRest.ServiceCallback<Models.Project>): void; /** * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Project>): void; get(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Project>, callback?: msRest.ServiceCallback<Models.Project>): Promise<Models.ProjectsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, workspaceName, projectName, options }, getOperationSpec, callback) as Promise<Models.ProjectsGetResponse>; } /** * Creates or updates a project with the specified parameters. * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param parameters The parameters for creating or updating a project. * @param [options] The optional parameters * @returns Promise<Models.ProjectsCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: Models.Project, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsCreateOrUpdateResponse>; /** * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param parameters The parameters for creating or updating a project. * @param callback The callback */ createOrUpdate(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: Models.Project, callback: msRest.ServiceCallback<Models.Project>): void; /** * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param parameters The parameters for creating or updating a project. * @param options The optional parameters * @param callback The callback */ createOrUpdate(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: Models.Project, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Project>): void; createOrUpdate(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: Models.Project, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Project>, callback?: msRest.ServiceCallback<Models.Project>): Promise<Models.ProjectsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, workspaceName, projectName, parameters, options }, createOrUpdateOperationSpec, callback) as Promise<Models.ProjectsCreateOrUpdateResponse>; } /** * Deletes a project. * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param callback The callback */ deleteMethod(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, workspaceName, projectName, options }, deleteMethodOperationSpec, callback); } /** * Updates a project with the specified parameters. * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param parameters The parameters for updating a machine learning team account. * @param [options] The optional parameters * @returns Promise<Models.ProjectsUpdateResponse> */ update(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: Models.ProjectUpdateParameters, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsUpdateResponse>; /** * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param parameters The parameters for updating a machine learning team account. * @param callback The callback */ update(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: Models.ProjectUpdateParameters, callback: msRest.ServiceCallback<Models.Project>): void; /** * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param projectName The name of the machine learning project under a team account workspace. * @param parameters The parameters for updating a machine learning team account. * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: Models.ProjectUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Project>): void; update(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: Models.ProjectUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Project>, callback?: msRest.ServiceCallback<Models.Project>): Promise<Models.ProjectsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, workspaceName, projectName, parameters, options }, updateOperationSpec, callback) as Promise<Models.ProjectsUpdateResponse>; } /** * Lists all the available machine learning projects under the specified workspace. * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param [options] The optional parameters * @returns Promise<Models.ProjectsListByWorkspaceResponse> */ listByWorkspace(accountName: string, workspaceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsListByWorkspaceResponse>; /** * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param callback The callback */ listByWorkspace(accountName: string, workspaceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.ProjectListResult>): void; /** * @param accountName The name of the machine learning team account. * @param workspaceName The name of the machine learning team account workspace. * @param resourceGroupName The name of the resource group to which the machine learning team * account belongs. * @param options The optional parameters * @param callback The callback */ listByWorkspace(accountName: string, workspaceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectListResult>): void; listByWorkspace(accountName: string, workspaceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectListResult>, callback?: msRest.ServiceCallback<Models.ProjectListResult>): Promise<Models.ProjectsListByWorkspaceResponse> { return this.client.sendOperationRequest( { accountName, workspaceName, resourceGroupName, options }, listByWorkspaceOperationSpec, callback) as Promise<Models.ProjectsListByWorkspaceResponse>; } /** * Lists all the available machine learning projects under the specified workspace. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ProjectsListByWorkspaceNextResponse> */ listByWorkspaceNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsListByWorkspaceNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByWorkspaceNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ProjectListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByWorkspaceNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectListResult>): void; listByWorkspaceNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectListResult>, callback?: msRest.ServiceCallback<Models.ProjectListResult>): Promise<Models.ProjectsListByWorkspaceNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByWorkspaceNextOperationSpec, callback) as Promise<Models.ProjectsListByWorkspaceNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningExperimentation/accounts/{accountName}/workspaces/{workspaceName}/projects/{projectName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.workspaceName, Parameters.projectName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Project }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningExperimentation/accounts/{accountName}/workspaces/{workspaceName}/projects/{projectName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.workspaceName, Parameters.projectName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.Project, required: true } }, responses: { 200: { bodyMapper: Mappers.Project }, 201: { bodyMapper: Mappers.Project }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningExperimentation/accounts/{accountName}/workspaces/{workspaceName}/projects/{projectName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.workspaceName, Parameters.projectName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningExperimentation/accounts/{accountName}/workspaces/{workspaceName}/projects/{projectName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName, Parameters.workspaceName, Parameters.projectName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.ProjectUpdateParameters, required: true } }, responses: { 200: { bodyMapper: Mappers.Project }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByWorkspaceOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningExperimentation/accounts/{accountName}/workspaces{workspaceName}/projects", urlParameters: [ Parameters.subscriptionId, Parameters.accountName, Parameters.workspaceName, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProjectListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByWorkspaceNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProjectListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import geolocation from 'mock-geolocation'; import {createMap, setWebGlContext, setPerformance, setMatchMedia} from '../../util/test/util'; import GeolocateControl from './geolocate_control'; geolocation.use(); let map; // convert the coordinates of a LngLat object to a fixed number of digits function lngLatAsFixed(lngLat, digits) { return Object.keys(lngLat).reduce((previous, current) => { previous[current] = lngLat[current].toFixed(digits); return previous; }, {}); } beforeEach(() => { setWebGlContext(); setPerformance(); setMatchMedia(); map = createMap(undefined, undefined); }); afterEach(() => { map.remove(); }); describe('GeolocateControl with no options', () => { test('error event', done => { const geolocate = new GeolocateControl(undefined); map.addControl(geolocate); const click = new window.Event('click'); geolocate.on('error', (error) => { expect(error.code).toBe(2); expect(error.message).toBe('error message'); done(); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.sendError({code: 2, message: 'error message'}); }); test('outofmaxbounds event in active lock state', done => { const geolocate = new GeolocateControl(undefined); map.addControl(geolocate); map.setMaxBounds([[0, 0], [10, 10]]); geolocate._watchState = 'ACTIVE_LOCK'; const click = new window.Event('click'); geolocate.on('outofmaxbounds', (position) => { expect(geolocate._watchState).toBe('ACTIVE_ERROR'); expect(position.coords.latitude).toBe(10); expect(position.coords.longitude).toBe(20); expect(position.coords.accuracy).toBe(3); expect(position.timestamp).toBe(4); done(); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 3, timestamp: 4}); }); test('outofmaxbounds event in background state', done => { const geolocate = new GeolocateControl(undefined); map.addControl(geolocate); map.setMaxBounds([[0, 0], [10, 10]]); geolocate._watchState = 'BACKGROUND'; const click = new window.Event('click'); geolocate.on('outofmaxbounds', (position) => { expect(geolocate._watchState).toBe('BACKGROUND_ERROR'); expect(position.coords.latitude).toBe(10); expect(position.coords.longitude).toBe(20); expect(position.coords.accuracy).toBe(3); expect(position.timestamp).toBe(4); done(); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 3, timestamp: 4}); }); test('geolocate event', done => { const geolocate = new GeolocateControl(undefined); map.addControl(geolocate); const click = new window.Event('click'); geolocate.on('geolocate', (position) => { expect(position.coords.latitude).toBe(10); expect(position.coords.longitude).toBe(20); expect(position.coords.accuracy).toBe(30); expect(position.timestamp).toBe(40); done(); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 30, timestamp: 40}); }); test('trigger', () => { const geolocate = new GeolocateControl(undefined); map.addControl(geolocate); expect(geolocate.trigger()).toBeTruthy(); }); test('trigger before added to map', () => { jest.spyOn(console, 'warn').mockImplementation(() => { }); const geolocate = new GeolocateControl(undefined); expect(geolocate.trigger()).toBeFalsy(); expect(console.warn).toHaveBeenCalledWith('Geolocate control triggered before added to a map'); }); test('geolocate fitBoundsOptions', done => { const geolocate = new GeolocateControl({ fitBoundsOptions: { duration: 0, maxZoom: 10 } }); map.addControl(geolocate); const click = new window.Event('click'); map.once('moveend', () => { expect(map.getZoom()).toBe(10); done(); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 1}); }); test('with removed before Geolocation callback', () => { expect(() => { const geolocate = new GeolocateControl(undefined); map.addControl(geolocate); geolocate.trigger(); map.removeControl(geolocate); }).not.toThrow(); }); test('non-zero bearing', done => { map.setBearing(45); const geolocate = new GeolocateControl({ fitBoundsOptions: { duration: 0, maxZoom: 10 } }); map.addControl(geolocate); const click = new window.Event('click'); map.once('moveend', () => { expect(lngLatAsFixed(map.getCenter(), 4)).toEqual({'lat': '10.0000', 'lng': '20.0000'}); expect(map.getBearing()).toBe(45); expect(map.getZoom()).toBe(10); done(); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 1}); }); test('no watching map camera on geolocation', done => { const geolocate = new GeolocateControl({ fitBoundsOptions: { maxZoom: 20, duration: 0 } }); map.addControl(geolocate); const click = new window.Event('click'); map.once('moveend', () => { expect(lngLatAsFixed(map.getCenter(), 4)).toEqual({'lat': '10.0000', 'lng': '20.0000'}); const mapBounds = map.getBounds(); // map bounds should contain or equal accuracy bounds, that is the ensure accuracy bounds doesn't fall outside the map bounds const accuracyBounds = map.getCenter().toBounds(1000); expect(accuracyBounds.getNorth().toFixed(4) <= mapBounds.getNorth().toFixed(4)).toBeTruthy(); expect(accuracyBounds.getSouth().toFixed(4) >= mapBounds.getSouth().toFixed(4)).toBeTruthy(); expect(accuracyBounds.getEast().toFixed(4) <= mapBounds.getEast().toFixed(4)).toBeTruthy(); expect(accuracyBounds.getWest().toFixed(4) >= mapBounds.getWest().toFixed(4)).toBeTruthy(); // map bounds should not be too much bigger on all edges of the accuracy bounds (this test will only work for an orthogonal bearing), // ensures map bounds does not contain buffered accuracy bounds, as if it does there is too much gap around the accuracy bounds const bufferedAccuracyBounds = map.getCenter().toBounds(1100); expect( (bufferedAccuracyBounds.getNorth().toFixed(4) < mapBounds.getNorth().toFixed(4)) && (bufferedAccuracyBounds.getSouth().toFixed(4) > mapBounds.getSouth().toFixed(4)) && (bufferedAccuracyBounds.getEast().toFixed(4) < mapBounds.getEast().toFixed(4)) && (bufferedAccuracyBounds.getWest().toFixed(4) > mapBounds.getWest().toFixed(4)) ).toBeFalsy(); done(); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 1000}); }); test('watching map updates recenter on location with dot', done => { const geolocate = new GeolocateControl({ trackUserLocation: true, showUserLocation: true, fitBoundsOptions: { duration: 0 } }); map.addControl(geolocate); const click = new window.Event('click'); let moveendCount = 0; map.once('moveend', () => { // moveend was being called a second time, this ensures that we don't run the tests a second time if (moveendCount > 0) return; moveendCount++; expect(lngLatAsFixed(map.getCenter(), 4)).toEqual({'lat': '10.0000', 'lng': '20.0000'}); expect(geolocate._userLocationDotMarker._map).toBeTruthy(); expect( geolocate._userLocationDotMarker._element.classList.contains('maplibregl-user-location-dot-stale') ).toBeFalsy(); map.once('moveend', () => { expect(lngLatAsFixed(map.getCenter(), 4)).toEqual({'lat': '40.0000', 'lng': '50.0000'}); geolocate.once('error', () => { expect(geolocate._userLocationDotMarker._map).toBeTruthy(); expect( geolocate._userLocationDotMarker._element.classList.contains('maplibregl-user-location-dot-stale') ).toBeTruthy(); done(); }); geolocation.changeError({code: 2, message: 'position unavaliable'}); }); geolocation.change({latitude: 40, longitude: 50, accuracy: 60}); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 30}); }); test('watching map background event', done => { const geolocate = new GeolocateControl({ trackUserLocation: true, fitBoundsOptions: { duration: 0 } }); map.addControl(geolocate); const click = new window.Event('click'); let moveendCount = 0; map.once('moveend', () => { // moveend was being called a second time, this ensures that we don't run the tests a second time if (moveendCount > 0) return; moveendCount++; geolocate.once('trackuserlocationend', () => { expect(map.getCenter()).toEqual({lng: 10, lat: 5}); done(); }); // manually pan the map away from the geolocation position which should trigger the 'trackuserlocationend' event above map.jumpTo({ center: [10, 5] }); }); // click the button to activate it into the enabled watch state geolocate._geolocateButton.dispatchEvent(click); // send through a location update which should reposition the map and trigger the 'moveend' event above geolocation.send({latitude: 10, longitude: 20, accuracy: 30}); }); test('watching map background state', done => { const geolocate = new GeolocateControl({ trackUserLocation: true, fitBoundsOptions: { duration: 0 } }); map.addControl(geolocate); const click = new window.Event('click'); let moveendCount = 0; map.once('moveend', () => { // moveend was being called a second time, this ensures that we don't run the tests a second time if (moveendCount > 0) return; moveendCount++; map.once('moveend', () => { geolocate.once('geolocate', () => { expect(map.getCenter()).toEqual({lng: 10, lat: 5}); done(); }); // update the geolocation position, since we are in background state when 'geolocate' is triggered above, the camera shouldn't have changed geolocation.change({latitude: 0, longitude: 0, accuracy: 10}); }); // manually pan the map away from the geolocation position which should trigger the 'moveend' event above map.jumpTo({ center: [10, 5] }); }); // click the button to activate it into the enabled watch state geolocate._geolocateButton.dispatchEvent(click); // send through a location update which should reposition the map and trigger the 'moveend' event above geolocation.send({latitude: 10, longitude: 20, accuracy: 30}); }); test('trackuserlocationstart event', done => { const geolocate = new GeolocateControl({ trackUserLocation: true, fitBoundsOptions: { duration: 0 } }); map.addControl(geolocate); const click = new window.Event('click'); geolocate.once('trackuserlocationstart', () => { expect(map.getCenter()).toEqual({lng: 0, lat: 0}); done(); }); geolocate._geolocateButton.dispatchEvent(click); }); test('does not switch to BACKGROUND and stays in ACTIVE_LOCK state on window resize', done => { const geolocate = new GeolocateControl({ trackUserLocation: true, }); map.addControl(geolocate); const click = new window.Event('click'); geolocate.once('geolocate', () => { expect(geolocate._watchState).toBe('ACTIVE_LOCK'); window.dispatchEvent(new window.Event('resize')); expect(geolocate._watchState).toBe('ACTIVE_LOCK'); done(); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 30, timestamp: 40}); }); test('switches to BACKGROUND state on map manipulation', done => { const geolocate = new GeolocateControl({ trackUserLocation: true, }); map.addControl(geolocate); const click = new window.Event('click'); geolocate.once('geolocate', () => { expect(geolocate._watchState).toBe('ACTIVE_LOCK'); map.jumpTo({ center: [0, 0] }); expect(geolocate._watchState).toBe('BACKGROUND'); done(); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 30, timestamp: 40}); }); test('accuracy circle not shown if showAccuracyCircle = false', done => { const geolocate = new GeolocateControl({ trackUserLocation: true, showUserLocation: true, showAccuracyCircle: false, }); map.addControl(geolocate); const click = new window.Event('click'); geolocate.once('geolocate', () => { map.jumpTo({ center: [10, 20] }); map.once('zoomend', () => { expect(!geolocate._circleElement.style.width).toBeTruthy(); done(); }); map.zoomTo(10, {duration: 0}); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 700}); }); test('accuracy circle radius matches reported accuracy', done => { const geolocate = new GeolocateControl({ trackUserLocation: true, showUserLocation: true, }); map.addControl(geolocate); const click = new window.Event('click'); geolocate.once('geolocate', () => { expect(geolocate._accuracyCircleMarker._map).toBeTruthy(); expect(geolocate._accuracy).toBe(700); map.jumpTo({ center: [10, 20] }); map.once('zoomend', () => { expect(geolocate._circleElement.style.width).toBe('20px'); // 700m = 20px at zoom 10 map.once('zoomend', () => { expect(geolocate._circleElement.style.width).toBe('79px'); // 700m = 79px at zoom 12 done(); }); map.zoomTo(12, {duration: 0}); }); map.zoomTo(10, {duration: 0}); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 700}); }); test('shown even if trackUserLocation = false', done => { const geolocate = new GeolocateControl({ trackUserLocation: false, showUserLocation: true, showAccuracyCircle: true, }); map.addControl(geolocate); const click = new window.Event('click'); geolocate.once('geolocate', () => { map.jumpTo({ center: [10, 20] }); map.once('zoomend', () => { expect(geolocate._circleElement.style.width).toBeTruthy(); done(); }); map.zoomTo(10, {duration: 0}); }); geolocate._geolocateButton.dispatchEvent(click); geolocation.send({latitude: 10, longitude: 20, accuracy: 700}); }); });
the_stack
import express, {Express} from 'express'; import _ from 'lodash'; import chalk from 'chalk'; import P from 'pino'; import got from 'got'; import ms from 'ms'; import {StopWatch} from 'stopwatch-node'; import prettyMilliseconds from 'pretty-ms'; import {WalletConfig} from '../src/config'; import {ObjectiveDoneResult, UpdateChannelResult, Wallet} from '../src/wallet'; import {SocketIOMessageService} from '../src/message-service/socket-io-message-service'; import {createLogger} from '../src/logger'; import {LatencyOptions} from '../src/message-service/test-message-service'; import { CloseChannelStep, CreateChannelStep, CreateLedgerChannelStep, JobChannelLink, LoadNodeConfig, Peers, Step, UpdateChannelStep, } from './types'; export class WalletLoadNode { private steps: Step[] = []; private jobToChannelMap: JobChannelLink[] = []; private completedSteps = 0; private server: Express; private proposedObjectives = new Set<string>(); private proposedObjectivePromises = new Array<Promise<ObjectiveDoneResult>>(); private constructor( private serverWallet: Wallet, private loadNodeConfig: LoadNodeConfig, private peers: Peers, private logger: P.Logger ) { // This will approve any new objectives proposed by other participants this.serverWallet.on('ObjectiveProposed', async o => { if (o.type === 'OpenChannel') { // This is an easy work around for https://github.com/statechannels/statechannels/issues/3668 if (!this.proposedObjectives.has(o.objectiveId)) { this.logger.trace({objectiveId: o.objectiveId}, 'Auto approving objective'); const [result] = await this.serverWallet.approveObjectives([o.objectiveId]); this.proposedObjectives.add(o.objectiveId); this.proposedObjectivePromises.push(result.done); } } }); this.server = express(); this.server.use(express.json({limit: '50mb'})); // This endpoint is used to kick off processing // It will return once all the jobs (and peer's) jobs are done // Load data must be loaded prior to calling this this.server.get('/start', async (req, res) => { req.setTimeout(ms('1 day')); this.logger.trace('Starting job processing'); console.log(chalk.whiteBright('Starting job processing..')); this.outputChannelStats(); // If we didn't receive this from a peer it means it came from the user // We want to kick off processing in all nodes so we message our peers const fromPeer = req.query['fromPeer']; const stopWatch = new StopWatch(); stopWatch.start(); if (!fromPeer) { await Promise.all([this.runJobs(), this.sendGetRequestToPeers('/start?fromPeer=true')]); } else { await this.runJobs(); } await Promise.all(this.proposedObjectivePromises); stopWatch.stop(); console.log(`Job processing took ${prettyMilliseconds(stopWatch.getTotalTime())}`); res.end(); }); // This endpoint is used to reset the job ids so the same load file can be used again // It doesn't erase channels just the association between a jobId and a channel // This lets the same load file be run multiple times this.server.get('/reset', async (req, res) => { this.steps = []; this.jobToChannelMap = []; const fromPeer = req.query['fromPeer']; if (!fromPeer) { await this.sendGetRequestToPeers('/reset?fromPeer=true'); } this.logger.info('Jobs have been reset'); res.end(); }); // This endpoint is used to receive a channel id that was created for a job id // One peer will create a channel for a job and then alert other peers using this endpoint this.server.post('/channelId', async (req, res) => { const {channelId, jobId}: JobChannelLink = req.body; this.jobToChannelMap.push({jobId, channelId}); res.end(); }); // This endpoint loads the load file into the load node // It will not start processing the jobs unless the start query param is set to true this.server.post('/load', async (req, res) => { const requests: Step[] = req.body; const fromPeer = this.parseBooleanQueryParam('fromPeer', req); const startProcessing = this.parseBooleanQueryParam('start', req); await this.updateJobQueue(requests); // If we received this from a peer we don't want to send it right back to them if (!fromPeer) { await this.shareJobsWithPeers(requests); } if (startProcessing) { await Promise.all([this.sendGetRequestToPeers('/start?fromPeer=true'), this.runJobs()]); } res.end(); }); // Simple endpoint for checking if the server is ready this.server.get('/', (req, res) => res.end()); } private outputChannelStats() { const ourSteps = this.steps.filter(s => s.serverId === this.loadNodeConfig.serverId); const createdAmount = ourSteps.filter(s => s.type === 'CreateChannel').length; const ledgerAmount = ourSteps.filter(s => s.type === 'CreateLedgerChannel').length; const isLedgerFunding = this.steps.some(s => s.type === 'CreateLedgerChannel'); console.log( chalk.whiteBright( `This node will create ${createdAmount} channel(s) using ${ isLedgerFunding ? 'ledger' : 'direct' } funding` ) ); if (ledgerAmount > 0) { console.log(chalk.whiteBright(`This node will create ${ledgerAmount} ledger channel(s)`)); } const closedAmount = ourSteps.filter(s => s.type === 'CloseChannel').length; if (closedAmount > 0) { console.log(chalk.whiteBright(`This node will close ${closedAmount} channel(s)`)); } } private parseBooleanQueryParam(paramName: string, req: express.Request): boolean { const param = req.query[paramName]; return !!param && param.toString().toLocaleLowerCase() === 'true'; } /** * Runs any jobs that have been loaded. Returns when all jobs for this server are complete. * @returns */ private runJobs(): Promise<void> { const startTimestamp = Date.now(); return new Promise<void>(resolve => { this.steps .filter(s => s.serverId === this.loadNodeConfig.serverId) .forEach(s => setTimeout(async () => { this.logger.trace({step: s}, 'Starting job'); const result = await this.handleStep(s); if (result.type !== 'Success') { this.logger.error({result, step: s}, 'Load step failed!'); console.error(chalk.redBright(`Step failed for ${s.jobId}-${s.timestamp}`)); process.exit(1); } else { // We use a simple counter to determine when we're done this.completedSteps++; this.logger.trace({step: s, timestamp: Date.now() - startTimestamp}, 'Completed job'); const ourSteps = this.steps.filter(s => s.serverId === this.loadNodeConfig.serverId); // We only care if we've completed our steps if (this.completedSteps === ourSteps.length) { this.logger.trace( {jobIds: this.jobToChannelMap.map(e => e.jobId)}, 'All jobs completed!' ); console.log(chalk.greenBright(`All jobs complete!`)); resolve(); } } }, s.timestamp) ); }); } private async shareChannelIdsWithPeers(jobAndChannel: {channelId: string; jobId: string}) { for (const {loadServerPort} of this.peers) { await got.post(`http://localhost:${loadServerPort}/channelId/`, {json: jobAndChannel}); } } private async shareJobsWithPeers(steps: Step[]) { for (const {loadServerPort} of this.peers) { await got.post(`http://localhost:${loadServerPort}/load/?fromPeer=true`, {json: steps}); } } private async sendGetRequestToPeers(urlPath: string) { for (const {loadServerPort} of this.peers) { await got.get(`http://localhost:${loadServerPort}${urlPath}`, {retry: 0}); } } private async updateJobQueue(steps: Step[]): Promise<void> { this.steps = _.uniq(this.steps.concat(steps)); console.log(chalk.yellow(`Updated job queue with ${steps.length} steps`)); this.logger.info({steps}, 'Updated queue with steps'); } private getChannelIdForJob(jobId: string): string { const entry = this.jobToChannelMap.find(e => e.jobId === jobId); if (!entry) { throw new Error(`No channel id for ${jobId}`); } return entry.channelId; } /** * These are the various handlers for different step types * TODO: Typing should not use any type for the request */ private stepHandlers: Record<Step['type'], (step: any) => Promise<ObjectiveDoneResult>> = { CreateChannel: async (step: CreateChannelStep) => { const {fundingInfo} = step; if (fundingInfo.type === 'Direct') { const [result] = await this.serverWallet.createChannels([ {...step.channelParams, fundingStrategy: 'Direct'}, ]); const {jobId} = step; const {channelId} = result; this.jobToChannelMap.push({jobId, channelId}); await this.shareChannelIdsWithPeers({jobId, channelId}); return result.done; } else { const ledgerResult = this.jobToChannelMap.find( j => j.jobId === fundingInfo.fundingLedgerJob ); if (!ledgerResult) { throw new Error(`Cannot find channel id for ledger job ${fundingInfo.fundingLedgerJob}`); } const {channelId: fundingLedgerChannelId} = ledgerResult; const [result] = await this.serverWallet.createChannels([ {...step.channelParams, fundingStrategy: 'Ledger', fundingLedgerChannelId}, ]); const {jobId} = step; const {channelId} = result; this.jobToChannelMap.push({jobId, channelId}); await this.shareChannelIdsWithPeers({jobId, channelId}); return result.done; } }, CloseChannel: async (step: CloseChannelStep) => { const channelId = this.getChannelIdForJob(step.jobId); const [result] = await this.serverWallet.closeChannels([channelId]); return result.done; }, UpdateChannel: async (step: UpdateChannelStep) => { const channelId = this.getChannelIdForJob(step.jobId); const {allocations, appData} = step.updateParams; const result = await this.serverWallet.updateChannel(channelId, allocations, appData); return result; }, CreateLedgerChannel: async (step: CreateLedgerChannelStep) => { const result = await this.serverWallet.createLedgerChannel({ ...step.ledgerChannelParams, fundingStrategy: 'Direct', }); const {jobId} = step; const {channelId} = result; this.jobToChannelMap.push({jobId, channelId}); await this.shareChannelIdsWithPeers({jobId, channelId}); return result.done; }, }; /** * Handles an individual step from a load file. * @param step * @returns A promise that resolves to a result object. The result object may indicate success or an error. */ private async handleStep(step: Step): Promise<ObjectiveDoneResult | UpdateChannelResult> { return this.stepHandlers[step.type](step); } public async destroy(): Promise<void> { this.server.removeAllListeners(); await this.serverWallet.destroy(); } public listen(): void { this.server.listen(this.loadNodeConfig.loadServerPort); } /** * This is used to register a peer with the wallet * @param port The message port for the peer. */ public async registerMessagePeer(port: number): Promise<void> { this.serverWallet.messageService.registerPeer(`http://localhost:${port}`); } public setLatencyOptions(latencyOptions: LatencyOptions): void { (this.serverWallet.messageService as SocketIOMessageService).setLatencyOptions(latencyOptions); } public static async create( walletConfig: WalletConfig, loadNodeConfig: LoadNodeConfig, peers: Peers ): Promise<WalletLoadNode> { // Create a message service factory that will use the port we specify const messageServiceFactory = await SocketIOMessageService.createFactory( 'localhost', loadNodeConfig.messagePort ); const serverWallet = await Wallet.create(walletConfig, messageServiceFactory); // We'll use the same log file as the wallet const logger = createLogger(walletConfig); return new WalletLoadNode(serverWallet, loadNodeConfig, peers, logger); } public get loadPort(): number { return this.loadNodeConfig.loadServerPort; } }
the_stack
$(function () { var simpleVerticalAnimation = new $.gameQuery.Animation({ imageURL: "sv.png", type: $.gameQuery.ANIMATION_VERTICAL, numberOfFrame: 4, delta: 32, rate: 300 }); var simpleHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "sh.png", type: $.gameQuery.ANIMATION_HORIZONTAL, numberOfFrame: 4, delta: 32, rate: 300 }); var multiVerticalAnimation = new $.gameQuery.Animation({ imageURL: "mv.png", type: $.gameQuery.ANIMATION_VERTICAL | $.gameQuery.ANIMATION_MULTI, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 }); var multiHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "mh.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 }); var simpleOffsetVerticalAnimation = new $.gameQuery.Animation({ imageURL: "sov.png", type: $.gameQuery.ANIMATION_VERTICAL, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300 }); var simpleOffsetHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "soh.png", type: $.gameQuery.ANIMATION_HORIZONTAL, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300 }); var multiOffsetVerticalAnimation = new $.gameQuery.Animation({ imageURL: "mov.png", type: $.gameQuery.ANIMATION_VERTICAL | $.gameQuery.ANIMATION_MULTI, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 }); var multiOffsetHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "moh.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 }); var pingpongAnimation = new $.gameQuery.Animation({ imageURL: "rebound.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG, numberOfFrame: 9, delta: 64, rate: 60 }); var multiPingpongAnimation = new $.gameQuery.Animation({ imageURL: "reboundm.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG | $.gameQuery.ANIMATION_MULTI, numberOfFrame: 9, delta: 64, rate: 60, distance: 64 }); var callbackAnim = new $.gameQuery.Animation({ imageURL: "sv.png", type: $.gameQuery.ANIMATION_VERTICAL | $.gameQuery.ANIMATION_ONCE | $.gameQuery.ANIMATION_CALLBACK, numberOfFrame: 4, delta: 32, rate: 300 }); var counter = 0; $("#playground").playground({ height: 64, width: 500 }); $.playground() .addSprite("simpleVertical", { animation: simpleVerticalAnimation, posx: 0 }) .addSprite("simpleHorizontal", { animation: simpleHorizontalAnimation, posx: 34 }) .addSprite("multiVertical", { animation: multiVerticalAnimation, posx: 75 }) .addSprite("multiHorizontal", { animation: multiHorizontalAnimation, posx: 109 }) .addSprite("simpleOffsetVertical", { animation: simpleOffsetVerticalAnimation, posx: 150 }) .addSprite("simpleOffsetHorizontal", { animation: simpleOffsetHorizontalAnimation, posx: 184 }) .addSprite("multiOffsetVertical", { animation: multiOffsetVerticalAnimation, posx: 225 }) .addSprite("multiOffsetHorizontal", { animation: multiOffsetHorizontalAnimation, posx: 259 }) .addSprite("pingpong", { animation: pingpongAnimation, posx: 286, width: 64, height: 64 }) .addSprite("multiPingpong", { animation: multiPingpongAnimation, posx: 350, width: 64, height: 64 }) .addSprite("callback", { animation: callbackAnim, posx: 414, callback: function () { counter++; if (counter > 1) { $("#callback").remove(); } } }); $("#multiVertical").setAnimation(1); $("#multiHorizontal").setAnimation(1); $("#multiOffsetVertical").setAnimation(1); $("#multiOffsetHorizontal").setAnimation(1); $("#multiPingpong").setAnimation(1); $.playground().startGame(); }); $(function () { var red = new $.gameQuery.Animation({ imageURL: "red.png", type: $.gameQuery.ANIMATION_HORIZONTAL }); var blue = new $.gameQuery.Animation({ imageURL: "blue.png", type: $.gameQuery.ANIMATION_HORIZONTAL }); $("#playground").playground({ height: 450, width: 350 }); // no group, no translation, no transformation $.playground() .addSprite("a1", { animation: red, width: 30, height: 30, posx: 0, posy: 0 }) .addSprite("b1", { animation: red, width: 30, height: 30, posx: 15, posy: 15 }); // one group, no translation, no transformation $.playground() .addSprite("a2", { animation: red, width: 30, height: 30, posx: 0, posy: 50 }) .addGroup("g1", { width: 100, height: 100, posx: -55, posy: -5 }) .addSprite("b2", { animation: red, width: 30, height: 30, posx: 70, posy: 70 }); // no group, absolute translation, no rotation $.playground() .addSprite("a3", { animation: red, width: 30, height: 30, posx: 0, posy: 100 }) .addSprite("b3", { animation: red, width: 30, height: 30, posx: 100, posy: 131 }); $("#b3").x(15).y(115); // no group, relative translation, scale $.playground() .addSprite("a4", { animation: red, width: 30, height: 30, posx: 0, posy: 150 }) .addSprite("b4", { animation: red, width: 30, height: 30, posx: 100, posy: 181 }); $("#b4").x(-85, true).y(-16, true); // no group, no translation, flip $.playground() .addSprite("a5", { animation: red, width: 30, height: 30, posx: 0, posy: 200 }) .addSprite("b5", { animation: red, width: 30, height: 30, posx: 15, posy: 215 }); $("#a5").flipv(); $("#b5").fliph(); // no group, no translation, rotation $.playground() .addSprite("a6", { animation: red, width: 30, height: 30, posx: 0, posy: 250 }) .addSprite("b6", { animation: red, width: 30, height: 30, posx: 30, posy: 265 }); $("#b6").rotate(45); // no group, no translation, scale $.playground() .addSprite("a7", { animation: red, width: 30, height: 30, posx: 0, posy: 300 }) .addSprite("b7", { animation: red, width: 30, height: 30, posx: 30, posy: 315 }); $("#b7").scale(1.5); // no group, no translation, override $.playground() .addSprite("a8", { animation: red, width: 30, height: 30, posx: 0, posy: 370 }) .addSprite("b8", { animation: red, width: 30, height: 30, posx: 40, posy: 385 }); // now we try to turn every b* sprites blue $("#a1").collision().each(function () { $(this).setAnimation(blue); }); $("#a2").collision().each(function () { $(this).setAnimation(blue); }); $("#a3").collision().each(function () { $(this).setAnimation(blue); }); $("#a4").collision().each(function () { $(this).setAnimation(blue); }); $("#a5").collision().each(function () { $(this).setAnimation(blue); }); $("#a6").collision().each(function () { $(this).setAnimation(blue); }); $("#a7").collision().each(function () { $(this).setAnimation(blue); }); $("#a8").collision({ x: 35 }).each(function () { $(this).setAnimation(blue); }); $.playground().startGame(); }); $(function () { var multiAnimation = new $.gameQuery.Animation({ imageURL: "m.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI, numberOfFrame: 3, delta: 10, distance: 10, rate: 300 }); var multiAnimationPingpong = new $.gameQuery.Animation({ imageURL: "m.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI | $.gameQuery.ANIMATION_PINGPONG, numberOfFrame: 3, delta: 10, distance: 10, rate: 300 }); var animations = []; animations[0] = new $.gameQuery.Animation({ imageURL: "s1.png", type: $.gameQuery.ANIMATION_HORIZONTAL, numberOfFrame: 3, delta: 10, rate: 300 }); animations[1] = new $.gameQuery.Animation({ imageURL: "s2.png", type: $.gameQuery.ANIMATION_HORIZONTAL, numberOfFrame: 3, delta: 10, rate: 300 }); animations[2] = new $.gameQuery.Animation({ imageURL: "s3.png", type: $.gameQuery.ANIMATION_HORIZONTAL, numberOfFrame: 3, delta: 10, rate: 300 }); var animationsPingpong = []; animationsPingpong[0] = new $.gameQuery.Animation({ imageURL: "s1.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG, numberOfFrame: 3, delta: 10, rate: 300 }); animationsPingpong[1] = new $.gameQuery.Animation({ imageURL: "s2.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG, numberOfFrame: 3, delta: 10, rate: 300 }); animationsPingpong[2] = new $.gameQuery.Animation({ imageURL: "s3.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG, numberOfFrame: 3, delta: 10, rate: 300 }); var tileDef = [[1, 2, 3], [2, 3, 1], [3, 1, 2]]; var tileFun = function (i, j) { return 1 + (i + j) % 3; }; $("#playground").playground({ height: 64, width: 350 }); $.playground() .addTilemap("multiArray", tileDef, multiAnimation, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 0 }).end() .addTilemap("multiFunction", tileFun, multiAnimation, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 40 }).end() .addTilemap("arrayArray", tileDef, animations, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 80 }).end() .addTilemap("arrayFunction", tileFun, animations, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 120 }).end() .addTilemap("multiArrayPingpong", tileDef, multiAnimationPingpong, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 160 }).end() .addTilemap("arrayArrayPingpong", tileDef, animationsPingpong, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 200 }).end() .addGroup("testGroup", { height: 30, width: 30, posx: -40 }).addTilemap("outside", tileDef, multiAnimation, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 0 }); $("#testGroup").x(240); $.playground().startGame(); }); $(function () { var multiAnimation = new $.gameQuery.Animation({ imageURL: "m.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI, numberOfFrame: 3, delta: 10, distance: 10, rate: 300 }); var tileDef = [[1, 2, 3, 1, 2, 3, 1, 2, 3], [2, 3, 1, 2, 3, 1, 2, 3, 1], [3, 1, 2, 3, 1, 2, 3, 1, 2]]; $("#playground").playground({ height: 60, width: 90 }); $.playground() .addGroup("testGroup1", { height: 60, width: 180, posx: 0 }) .addTilemap("map1", tileDef, multiAnimation, { width: 10, height: 10, sizex: 9, sizey: 3, posx: 0 }).end() .addTilemap("map2", tileDef, multiAnimation, { width: 10, height: 10, sizex: 9, sizey: 3, posx: 90 }).end() .end() .addGroup("testGroup2", { height: 60, width: 90, posy: 60 }) .addTilemap("map3", tileDef, multiAnimation, { width: 10, height: 10, sizex: 9, sizey: 3, posx: 0 }); $("#testGroup1").x(-45); $("#testGroup2").y(30); $.playground().startGame(); }); $(function () { var animation = new $.gameQuery.Animation({ imageURL: "sh.png", type: $.gameQuery.ANIMATION_HORIZONTAL, numberOfFrame: 4, delta: 32, rate: 300 }); $("#playground").playground({ height: 64, width: 480 }); $.playground() .addSprite("rotate", { animation: animation, posx: 0, posy: 16 }) .addSprite("scale", { animation: animation, posx: 80, posy: 16 }) .addSprite("rotateScale", { animation: animation, posx: 160, posy: 16 }) .addSprite("scaleRotate", { animation: animation, posx: 240, posy: 16 }) .addSprite("flipH", { animation: animation, posx: 320, posy: 16 }) .addSprite("flipV", { animation: animation, posx: 400, posy: 16 }) $("#rotate").rotate(45); $("#scale").scale(4); $("#scale").scale(0.5, true); $("#rotateScale").rotate(45).scale(2); $("#scaleRotate").scale(2).rotate(45); $("#flipV").flipv(true); $("#flipH").fliph(true); $.playground().startGame(); });
the_stack
import * as Sparse from "./sparse"; import * as common from "./common"; import { FactoryProgressCallback, flashZip as flashFactoryZip, } from "./factory"; const FASTBOOT_USB_CLASS = 0xff; const FASTBOOT_USB_SUBCLASS = 0x42; const FASTBOOT_USB_PROTOCOL = 0x03; const BULK_TRANSFER_SIZE = 16384; const DEFAULT_DOWNLOAD_SIZE = 512 * 1024 * 1024; // 512 MiB // To conserve RAM and work around Chromium's ~2 GiB size limit, we limit the // max download size even if the bootloader can accept more data. const MAX_DOWNLOAD_SIZE = 1024 * 1024 * 1024; // 1 GiB const GETVAR_TIMEOUT = 10000; // ms /** * Exception class for USB errors not directly thrown by WebUSB. */ export class UsbError extends Error { constructor(message: string) { super(message); this.name = "UsbError"; } } /** * Exception class for errors returned by the bootloader, as well as high-level * fastboot errors resulting from bootloader responses. */ export class FastbootError extends Error { status: string; bootloaderMessage: string; constructor(status: string, message: string) { super(`Bootloader replied with ${status}: ${message}`); this.status = status; this.bootloaderMessage = message; this.name = "FastbootError"; } } interface CommandResponse { text: string; // hex string from DATA dataSize?: string; } /** * Callback for progress updates while flashing or uploading an image. * * @callback FlashProgressCallback * @param {number} progress - Progress for the current action, between 0 and 1. */ export type FlashProgressCallback = (progress: number) => void; /** * Callback for reconnecting to the USB device. * This is necessary because some platforms do not support automatic reconnection, * and USB connection requests can only be triggered as the result of explicit * user action. * * @callback ReconnectCallback */ export type ReconnectCallback = () => void; /** * This class is a client for executing fastboot commands and operations on a * device connected over USB. */ export class FastbootDevice { device: USBDevice | null; epIn: number | null; epOut: number | null; private _registeredUsbListeners: boolean; private _connectResolve: ((value: any) => void) | null; private _connectReject: ((err: Error) => void) | null; private _disconnectResolve: ((value: any) => void) | null; /** * Create a new fastboot device instance. This doesn't actually connect to * any USB devices; call {@link connect} to do so. */ constructor() { this.device = null; this.epIn = null; this.epOut = null; this._registeredUsbListeners = false; this._connectResolve = null; this._connectReject = null; this._disconnectResolve = null; } /** * Returns whether a USB device is connected and ready for use. */ get isConnected() { return ( this.device !== null && this.device.opened && this.device.configurations[0].interfaces[0].claimed ); } /** * Validate the current USB device's details and connect to it. * * @private */ private async _validateAndConnectDevice() { if (this.device === null) { throw new UsbError("Attempted to connect to null device"); } // Validate device let ife = this.device!.configurations[0].interfaces[0].alternates[0]; if (ife.endpoints.length !== 2) { throw new UsbError("Interface has wrong number of endpoints"); } this.epIn = null; this.epOut = null; for (let endpoint of ife.endpoints) { common.logVerbose("Checking endpoint:", endpoint); if (endpoint.type !== "bulk") { throw new UsbError("Interface endpoint is not bulk"); } if (endpoint.direction === "in") { if (this.epIn === null) { this.epIn = endpoint.endpointNumber; } else { throw new UsbError("Interface has multiple IN endpoints"); } } else if (endpoint.direction === "out") { if (this.epOut === null) { this.epOut = endpoint.endpointNumber; } else { throw new UsbError("Interface has multiple OUT endpoints"); } } } common.logVerbose("Endpoints: in =", this.epIn, ", out =", this.epOut); try { await this.device!.open(); // Opportunistically reset to fix issues on some platforms try { await this.device!.reset(); } catch (error) { /* Failed = doesn't support reset */ } await this.device!.selectConfiguration(1); await this.device!.claimInterface(0); // fastboot } catch (error) { // Propagate exception from waitForConnect() if (this._connectReject !== null) { this._connectReject(error); this._connectResolve = null; this._connectReject = null; } throw error; } // Return from waitForConnect() if (this._connectResolve !== null) { this._connectResolve(undefined); this._connectResolve = null; this._connectReject = null; } } /** * Wait for the current USB device to disconnect, if it's still connected. * Returns immediately if no device is connected. */ async waitForDisconnect() { if (this.device === null) { return; } return await new Promise((resolve, _reject) => { this._disconnectResolve = resolve; }); } /** * Wait for the USB device to connect. Returns at the next connection, * regardless of whether the connected USB device matches the previous one. * * @param {ReconnectCallback} onReconnect - Callback to request device reconnection on Android. */ async waitForConnect(onReconnect: ReconnectCallback = () => {}) { // On Android, we need to request the user to reconnect the device manually // because there is no support for automatic reconnection. if (navigator.userAgent.includes("Android")) { await this.waitForDisconnect(); onReconnect(); } return await new Promise((resolve, reject) => { this._connectResolve = resolve; this._connectReject = reject; }); } /** * Request the user to select a USB device and connect to it using the * fastboot protocol. * * @throws {UsbError} */ async connect() { let devices = await navigator.usb.getDevices(); common.logDebug("Found paired USB devices:", devices); if (devices.length === 1) { this.device = devices[0]; } else { // If multiple paired devices are connected, request the user to // select a specific one to reduce ambiguity. This is also necessary // if no devices are already paired, i.e. first use. common.logDebug( "No or multiple paired devices are connected, requesting one" ); this.device = await navigator.usb.requestDevice({ filters: [ { classCode: FASTBOOT_USB_CLASS, subclassCode: FASTBOOT_USB_SUBCLASS, protocolCode: FASTBOOT_USB_PROTOCOL, }, ], }); } common.logDebug("Using USB device:", this.device); if (!this._registeredUsbListeners) { navigator.usb.addEventListener("disconnect", (event) => { if (event.device === this.device) { common.logDebug("USB device disconnected"); if (this._disconnectResolve !== null) { this._disconnectResolve(undefined); this._disconnectResolve = null; } } }); navigator.usb.addEventListener("connect", async (event) => { common.logDebug("USB device connected"); this.device = event.device; // Check whether waitForConnect() is pending and save it for later let hasPromiseReject = this._connectReject !== null; try { await this._validateAndConnectDevice(); } catch (error) { // Only rethrow errors from the event handler if waitForConnect() // didn't already handle them if (!hasPromiseReject) { throw error; } } }); this._registeredUsbListeners = true; } await this._validateAndConnectDevice(); } /** * Read a raw command response from the bootloader. * * @private * @returns {Promise<CommandResponse>} Object containing response text and data size, if any. * @throws {FastbootError} */ private async _readResponse(): Promise<CommandResponse> { let respData = { text: "", } as CommandResponse; let respStatus; do { let respPacket = await this.device!.transferIn(this.epIn!, 64); let response = new TextDecoder().decode(respPacket.data); respStatus = response.substring(0, 4); let respMessage = response.substring(4); common.logDebug(`Response: ${respStatus} ${respMessage}`); if (respStatus === "OKAY") { // OKAY = end of response for this command respData.text += respMessage; } else if (respStatus === "INFO") { // INFO = additional info line respData.text += respMessage + "\n"; } else if (respStatus === "DATA") { // DATA = hex string, but it's returned separately for safety respData.dataSize = respMessage; } else { // Assume FAIL or garbage data throw new FastbootError(respStatus, respMessage); } // INFO = more packets are coming } while (respStatus === "INFO"); return respData; } /** * Send a textual command to the bootloader and read the response. * This is in raw fastboot format, not AOSP fastboot syntax. * * @param {string} command - The command to send. * @returns {Promise<CommandResponse>} Object containing response text and data size, if any. * @throws {FastbootError} */ async runCommand(command: string): Promise<CommandResponse> { // Command and response length is always 64 bytes regardless of protocol if (command.length > 64) { throw new RangeError(); } // Send raw UTF-8 command let cmdPacket = new TextEncoder().encode(command); await this.device!.transferOut(this.epOut!, cmdPacket); common.logDebug("Command:", command); return this._readResponse(); } /** * Read the value of a bootloader variable. Returns undefined if the variable * does not exist. * * @param {string} varName - The name of the variable to get. * @returns {Promise<string>} Textual content of the variable. * @throws {FastbootError} */ async getVariable(varName: string): Promise<string | null> { let resp; try { resp = ( await common.runWithTimeout( this.runCommand(`getvar:${varName}`), GETVAR_TIMEOUT ) ).text; } catch (error) { // Some bootloaders return FAIL instead of empty responses, despite // what the spec says. Normalize it here. if (error instanceof FastbootError && error.status == "FAIL") { resp = null; } else { throw error; } } // Some bootloaders send whitespace around some variables. // According to the spec, non-existent variables should return empty // responses return resp ? resp.trim() : null; } /** * Get the maximum download size for a single payload, in bytes. * * @private * @returns {Promise<number>} * @throws {FastbootError} */ private async _getDownloadSize(): Promise<number> { try { let resp = (await this.getVariable( "max-download-size" ))!.toLowerCase(); if (resp) { // AOSP fastboot requires hex return Math.min(parseInt(resp, 16), MAX_DOWNLOAD_SIZE); } } catch (error) { /* Failed = no value, fallthrough */ } // FAIL or empty variable means no max, set a reasonable limit to conserve memory return DEFAULT_DOWNLOAD_SIZE; } /** * Send a raw data payload to the bootloader. * * @private */ private async _sendRawPayload( buffer: ArrayBuffer, onProgress: FlashProgressCallback ) { let i = 0; let remainingBytes = buffer.byteLength; while (remainingBytes > 0) { let chunk = buffer.slice( i * BULK_TRANSFER_SIZE, (i + 1) * BULK_TRANSFER_SIZE ); if (i % 1000 === 0) { common.logVerbose( ` Sending ${chunk.byteLength} bytes to endpoint, ${remainingBytes} remaining, i=${i}` ); } if (i % 10 === 0) { onProgress( (buffer.byteLength - remainingBytes) / buffer.byteLength ); } await this.device!.transferOut(this.epOut!, chunk); remainingBytes -= chunk.byteLength; i += 1; } onProgress(1.0); } /** * Upload a payload to the bootloader for later use, e.g. flashing. * Does not handle raw images, flashing, or splitting. * * @param {string} partition - Name of the partition the payload is intended for. * @param {ArrayBuffer} buffer - Buffer containing the data to upload. * @param {FlashProgressCallback} onProgress - Callback for upload progress updates. * @throws {FastbootError} */ async upload( partition: string, buffer: ArrayBuffer, onProgress: FlashProgressCallback = (_progress) => {} ) { common.logDebug( `Uploading single sparse to ${partition}: ${buffer.byteLength} bytes` ); // Bootloader requires an 8-digit hex number let xferHex = buffer.byteLength.toString(16).padStart(8, "0"); if (xferHex.length !== 8) { throw new FastbootError( "FAIL", `Transfer size overflow: ${xferHex} is more than 8 digits` ); } // Check with the device and make sure size matches let downloadResp = await this.runCommand(`download:${xferHex}`); if (downloadResp.dataSize === undefined) { throw new FastbootError( "FAIL", `Unexpected response to download command: ${downloadResp.text}` ); } let downloadSize = parseInt(downloadResp.dataSize!, 16); if (downloadSize !== buffer.byteLength) { throw new FastbootError( "FAIL", `Bootloader wants ${buffer.byteLength} bytes, requested to send ${buffer.byteLength} bytes` ); } common.logDebug(`Sending payload: ${buffer.byteLength} bytes`); await this._sendRawPayload(buffer, onProgress); common.logDebug("Payload sent, waiting for response..."); await this._readResponse(); } /** * Reboot to the given target, and optionally wait for the device to * reconnect. * * @param {string} target - Where to reboot to, i.e. fastboot or bootloader. * @param {boolean} wait - Whether to wait for the device to reconnect. * @param {ReconnectCallback} onReconnect - Callback to request device reconnection, if wait is enabled. */ async reboot( target: string = "", wait: boolean = false, onReconnect: ReconnectCallback = () => {} ) { if (target.length > 0) { await this.runCommand(`reboot-${target}`); } else { await this.runCommand("reboot"); } if (wait) { await this.waitForConnect(onReconnect); } } /** * Flash the given Blob to the given partition on the device. Any image * format supported by the bootloader is allowed, e.g. sparse or raw images. * Large raw images will be converted to sparse images automatically, and * large sparse images will be split and flashed in multiple passes * depending on the bootloader's payload size limit. * * @param {string} partition - The name of the partition to flash. * @param {Blob} blob - The Blob to retrieve data from. * @param {FlashProgressCallback} onProgress - Callback for flashing progress updates. * @throws {FastbootError} */ async flashBlob( partition: string, blob: Blob, onProgress: FlashProgressCallback = (_progress) => {} ) { // Use current slot if partition is A/B if ((await this.getVariable(`has-slot:${partition}`)) === "yes") { partition += "_" + (await this.getVariable("current-slot")); } let maxDlSize = await this._getDownloadSize(); let fileHeader = await common.readBlobAsBuffer( blob.slice(0, Sparse.FILE_HEADER_SIZE) ); let totalBytes = blob.size; let isSparse = false; try { let sparseHeader = Sparse.parseFileHeader(fileHeader); if (sparseHeader !== null) { totalBytes = sparseHeader.blocks * sparseHeader.blockSize; isSparse = true; } } catch (error) { // ImageError = invalid, so keep blob.size } // Logical partitions need to be resized before flashing because they're // sized perfectly to the payload. if ((await this.getVariable(`is-logical:${partition}`)) === "yes") { // As per AOSP fastboot, we reset the partition to 0 bytes first // to optimize extent allocation. await this.runCommand(`resize-logical-partition:${partition}:0`); // Set the actual size await this.runCommand( `resize-logical-partition:${partition}:${totalBytes}` ); } // Convert image to sparse (for splitting) if it exceeds the size limit if (blob.size > maxDlSize && !isSparse) { common.logDebug(`${partition} image is raw, converting to sparse`); // Assume that non-sparse images will always be small enough to convert in RAM. // The buffer is converted to a Blob for compatibility with the existing flashing code. let rawData = await common.readBlobAsBuffer(blob); let sparse = Sparse.fromRaw(rawData); blob = new Blob([sparse]); } common.logDebug( `Flashing ${blob.size} bytes to ${partition}, ${maxDlSize} bytes per split` ); let splits = 0; let sentBytes = 0; for await (let split of Sparse.splitBlob(blob, maxDlSize)) { await this.upload(partition, split.data, (progress) => { onProgress((sentBytes + progress * split.bytes) / totalBytes); }); common.logDebug("Flashing payload..."); await this.runCommand(`flash:${partition}`); splits += 1; sentBytes += split.bytes; } common.logDebug(`Flashed ${partition} with ${splits} split(s)`); } /** * Flash the given factory images zip onto the device, with automatic handling * of firmware, system, and logical partitions as AOSP fastboot and * flash-all.sh would do. * Equivalent to `fastboot update name.zip`. * * @param {Blob} blob - Blob containing the zip file to flash. * @param {boolean} wipe - Whether to wipe super and userdata. Equivalent to `fastboot -w`. * @param {ReconnectCallback} onReconnect - Callback to request device reconnection. * @param {FactoryProgressCallback} onProgress - Progress callback for image flashing. */ async flashFactoryZip( blob: Blob, wipe: boolean, onReconnect: ReconnectCallback, onProgress: FactoryProgressCallback = (_progress) => {} ) { return await flashFactoryZip(this, blob, wipe, onReconnect, onProgress); } }
the_stack
import { FocusKeyManager } from '@angular/cdk/a11y'; import { BACKSPACE, DELETE, ENTER, SPACE } from '@angular/cdk/keycodes'; import { Component, DebugElement, NgZone, QueryList, ViewChild, ViewChildren } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { createKeyboardEvent, dispatchFakeEvent, dispatchKeyboardEvent, fastTestSetup, typeInElement, } from '../../../../test/helpers'; import { MockNgZone } from '../../../../test/mocks/browser'; import { FormFieldModule } from '../form-field'; import { ChipDirective } from './chip'; import { ChipInputEvent } from './chip-input.directive'; import { ChipListComponent } from './chip-list.component'; import { ChipsModule } from './chips.module'; describe('browser.ui.chips.ChipListComponent', () => { let fixture: ComponentFixture<InputChipListComponent>; let chipListDebugElement: DebugElement; let chipListNativeElement: HTMLElement; let chipListInstance: ChipListComponent; let chips: QueryList<ChipDirective>; let manager: FocusKeyManager<ChipDirective>; let zone: MockNgZone; fastTestSetup(); beforeAll(async () => { await TestBed .configureTestingModule({ imports: [ ReactiveFormsModule, ChipsModule, FormFieldModule, ], declarations: [InputChipListComponent], providers: [ { provide: NgZone, useFactory: () => zone = new MockNgZone() }, ], }) .compileComponents(); }); describe('chip list with chip input', () => { let nativeChips: HTMLElement[]; beforeEach(() => { fixture = TestBed.createComponent(InputChipListComponent); fixture.detectChanges(); nativeChips = fixture.debugElement .queryAll(By.css('gd-chip')) .map((chip) => chip.nativeElement); chipListDebugElement = fixture.debugElement.query(By.directive(ChipListComponent)); chipListNativeElement = chipListDebugElement.nativeElement; chipListInstance = chipListDebugElement.componentInstance; chips = chipListInstance.chips; }); it('should take an initial view value with reactive forms', () => { fixture.componentInstance.control = new FormControl(['pizza-1']); fixture.detectChanges(); const array = fixture.componentInstance.chips.toArray(); expect(array[1].selected).toBeTruthy('Expect pizza-1 chip to be selected'); dispatchKeyboardEvent(nativeChips[1], 'keydown', SPACE); fixture.detectChanges(); expect(array[1].selected).toBeFalsy('Expect chip to be not selected after toggle selected'); }); it('should set the view value from the form', () => { const array = fixture.componentInstance.chips.toArray(); expect(array[1].selected).toBeFalsy('Expect chip to not be selected'); fixture.componentInstance.control.setValue(['pizza-1']); fixture.detectChanges(); expect(array[1].selected).toBeTruthy('Expect chip to be selected'); }); it('should update the form value when the view changes', () => { expect(fixture.componentInstance.control.value) .toEqual(null, `Expected the control's value to be empty initially.`); dispatchKeyboardEvent(nativeChips[0], 'keydown', SPACE); fixture.detectChanges(); expect(fixture.componentInstance.control.value) .toEqual(['steak-0'], `Expected control's value to be set to the new option.`); }); it('should clear the selection when a nonexistent option value is selected', () => { const array = fixture.componentInstance.chips.toArray(); fixture.componentInstance.control.setValue(['pizza-1']); fixture.detectChanges(); expect(array[1].selected) .toBeTruthy(`Expected chip with the value to be selected.`); fixture.componentInstance.control.setValue(['gibberish']); fixture.detectChanges(); expect(array[1].selected) .toBeFalsy(`Expected chip with the old value not to be selected.`); }); it('should clear the selection when the control is reset', () => { const array = fixture.componentInstance.chips.toArray(); fixture.componentInstance.control.setValue(['pizza-1']); fixture.detectChanges(); fixture.componentInstance.control.reset(); fixture.detectChanges(); expect(array[1].selected) .toBeFalsy(`Expected chip with the old value not to be selected.`); }); it('should set the control to touched when the chip list is touched', fakeAsync(() => { expect(fixture.componentInstance.control.touched) .toBe(false, 'Expected the control to start off as untouched.'); const nativeChipList = fixture.debugElement.query(By.css('.ChipList')).nativeElement; dispatchFakeEvent(nativeChipList, 'blur'); tick(); expect(fixture.componentInstance.control.touched) .toBe(true, 'Expected the control to be touched.'); })); it('should not set touched when a disabled chip list is touched', () => { expect(fixture.componentInstance.control.touched) .toBe(false, 'Expected the control to start off as untouched.'); fixture.componentInstance.control.disable(); const nativeChipList = fixture.debugElement.query(By.css('.ChipList')).nativeElement; dispatchFakeEvent(nativeChipList, 'blur'); expect(fixture.componentInstance.control.touched) .toBe(false, 'Expected the control to stay untouched.'); }); it('should set the control to dirty when the chip list\'s value changes in the DOM', () => { expect(fixture.componentInstance.control.dirty) .toEqual(false, `Expected control to start out pristine.`); dispatchKeyboardEvent(nativeChips[1], 'keydown', SPACE); fixture.detectChanges(); expect(fixture.componentInstance.control.dirty) .toEqual(true, `Expected control to be dirty after value was changed by user.`); }); it('should not set the control to dirty when the value changes programmatically', () => { expect(fixture.componentInstance.control.dirty) .toEqual(false, `Expected control to start out pristine.`); fixture.componentInstance.control.setValue(['pizza-1']); expect(fixture.componentInstance.control.dirty) .toEqual(false, `Expected control to stay pristine after programmatic change.`); }); it('should keep focus on the input after adding the first chip', fakeAsync(() => { const nativeInput = fixture.nativeElement.querySelector('input'); const chipEls = Array.from<HTMLElement>( fixture.nativeElement.querySelectorAll('.Chip')).reverse(); // Remove the chips via backspace to simulate the user removing them. chipEls.forEach(chip => { chip.focus(); dispatchKeyboardEvent(chip, 'keydown', BACKSPACE); fixture.detectChanges(); tick(); }); nativeInput.focus(); expect(fixture.componentInstance.foods).toEqual([], 'Expected all chips to be removed.'); expect(document.activeElement).toBe(nativeInput, 'Expected input to be focused.'); typeInElement('123', nativeInput); fixture.detectChanges(); dispatchKeyboardEvent(nativeInput, 'keydown', ENTER); fixture.detectChanges(); tick(); expect(document.activeElement).toBe(nativeInput, 'Expected input to remain focused.'); })); describe('keyboard behavior', () => { beforeEach(() => { chipListDebugElement = fixture.debugElement.query(By.directive(ChipListComponent)); chipListInstance = chipListDebugElement.componentInstance; chips = chipListInstance.chips; manager = fixture.componentInstance.chipList._keyManager; }); describe('when the input has focus', () => { it('should not focus the last chip when press DELETE', () => { const nativeInput = fixture.nativeElement.querySelector('input'); const DELETE_EVENT: KeyboardEvent = createKeyboardEvent('keydown', DELETE, nativeInput); // Focus the input nativeInput.focus(); expect(manager.activeItemIndex).toBe(-1); // Press the DELETE key chipListInstance._keydown(DELETE_EVENT); fixture.detectChanges(); // It doesn't focus the last chip expect(manager.activeItemIndex).toEqual(-1); }); it('should focus the last chip when press BACKSPACE', () => { const nativeInput = fixture.nativeElement.querySelector('input'); const BACKSPACE_EVENT: KeyboardEvent = createKeyboardEvent('keydown', BACKSPACE, nativeInput); // Focus the input nativeInput.focus(); expect(manager.activeItemIndex).toBe(-1); // Press the BACKSPACE key chipListInstance._keydown(BACKSPACE_EVENT); fixture.detectChanges(); // It focuses the last chip expect(manager.activeItemIndex).toEqual(chips.length - 1); }); }); }); }); }); @Component({ template: ` <gd-form-field> <gd-chip-list [multiple]="true" [formControl]="control" [required]="isRequired" #chipList> <gd-chip *ngFor="let food of foods" [value]="food.value" (removed)="remove(food)"> {{ food.viewValue }} </gd-chip> </gd-chip-list> <input placeholder="New food..." [gdChipInputFor]="chipList" [gdChipInputSeparatorKeyCodes]="separatorKeyCodes" [gdChipInputAddOnBlur]="addOnBlur" (gdChipInputTokenEnd)="add($event)"/> </gd-form-field> `, }) class InputChipListComponent { foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos', disabled: true }, { value: 'sandwich-3', viewValue: 'Sandwich' }, { value: 'chips-4', viewValue: 'Chips' }, { value: 'eggs-5', viewValue: 'Eggs' }, { value: 'pasta-6', viewValue: 'Pasta' }, { value: 'sushi-7', viewValue: 'Sushi' }, ]; control = new FormControl(); separatorKeyCodes = [ENTER, SPACE]; addOnBlur: boolean = true; isRequired: boolean; @ViewChild(ChipListComponent) chipList: ChipListComponent; @ViewChildren(ChipDirective) chips: QueryList<ChipDirective>; add(event: ChipInputEvent): void { const input = event.input; const value = event.value; // Add our foods if ((value || '').trim()) { this.foods.push({ value: `${value.trim().toLowerCase()}-${this.foods.length}`, viewValue: value.trim(), }); } // Reset the input value if (input) { input.value = ''; } } remove(food: any): void { const index = this.foods.indexOf(food); if (index > -1) { this.foods.splice(index, 1); } } }
the_stack
import * as peggy from "../../lib/peg.js"; import fs from "fs"; import path from "path"; import { spawn } from "child_process"; type Options = { args?: string[]; encoding?: BufferEncoding; env?: Record<string, string>; stdin?: string | Buffer; }; const foobarbaz = `\ foo = '1' bar = '2' baz = '3' `; /** Execution failed */ class ExecError extends Error { /** Result error code, always non-zero */ code: number; /** Stdout as a Buffer */ buf: Buffer; /** Stdout as a string, decoded with opts.encoding */ str: string; constructor(message: string, code: number, buf: Buffer, str: string) { super(`${message}: error code "${code}" ${str}`); this.name = "ExecError"; Object.setPrototypeOf(this, ExecError.prototype); this.code = code; this.buf = buf; this.str = str; } } function exec(opts: Options = {}) { opts = { args: [], encoding: "utf8", env: {}, ...opts, }; return new Promise((resolve, reject) => { let bin = path.join(__dirname, "..", "..", "bin", "peggy.js"); const env = { ...process.env, ...opts.env, }; // On Windows, use "node" to launch, rather than relying on shebang. In // real-world usage, `npm install` will also write a .cmd file so "node" // isn't required. const args = opts.args ? opts.args : []; if (process.platform === "win32") { args.unshift(bin); [bin] = process.argv; } const c = spawn(bin, args, { stdio: "pipe", env, }); c.on("error", reject); const bufs: Buffer[] = []; c.stdout.on("data", b => bufs.push(b)); c.stderr.on("data", b => bufs.push(b)); c.on("close", code => { const buf = Buffer.concat(bufs); const str = buf.toString(opts.encoding); if (code) { const err = new ExecError(`process fail, "${bin}"`, code, buf, str); reject(err); } else { resolve(str); } }); if (opts.stdin) { c.stdin.write(opts.stdin); } c.stdin.end(); }); } describe("Command Line Interface", () => { it("has help", async() => { const HELP = `\ Usage: peggy [options] [input_file] Options: -v, --version output the version number --allowed-start-rules <rules> Comma-separated list of rules the generated parser will be allowed to start parsing from. (Can be specified multiple times) (default: the first rule in the grammar) --cache Make generated parser cache results -d, --dependency <dependency> Comma-separated list of dependencies, either as a module name, or as \`variable:module\`. (Can be specified multiple times) -e, --export-var <variable> Name of a global variable into which the parser object is assigned to when no module loader is detected. --extra-options <options> Additional options (in JSON format as an object) to pass to peggy.generate -c, --extra-options-file <file> File with additional options (in JSON as an object or commonjs module format) to pass to peggy.generate --format <format> Format of the generated parser (choices: "amd", "bare", "commonjs", "es", "globals", "umd", default: "commonjs") -o, --output <file> Output file for generated parser. Use '-' for stdout (the default, unless a test is specified, in which case no parser is output without this option) --plugin <module> Comma-separated list of plugins. (can be specified multiple times) -t, --test <text> Test the parser with the given text, outputting the result of running the parser instead of the parser itself -T, --test-file <filename> Test the parser with the contents of the given file, outputting the result of running the parser instead of the parser itself --trace Enable tracing in generated parser -h, --help display help for command `; await expect(await exec({ args: ["-h"], })).toBe(HELP); await expect(await exec({ args: ["--help"], })).toBe(HELP); }); it("rejects invalid options", async() => { await expect(exec({ args: ["--invalid-option"], })).rejects.toThrow(ExecError); }); it("handles start rules", async() => { await expect(exec({ args: ["--allowed-start-rules", "foo,bar,baz"], stdin: foobarbaz, })).resolves.toMatch( /startRuleFunctions = { foo: [^, ]+, bar: [^, ]+, baz: \S+ }/ ); await expect(exec({ args: ["--allowed-start-rules"], stdin: "foo = '1'", })).rejects.toThrow("option '--allowed-start-rules <rules>' argument missing"); }); it("enables caching", async() => { await expect(exec({ args: ["--cache"], stdin: "foo = '1'", })).resolves.toMatch(/^\s*var peg\$resultsCache/m); }); it("prints version", async() => { await expect(exec({ args: ["--version"], })).resolves.toMatch(peggy.VERSION); await expect(exec({ args: ["-v"], })).resolves.toMatch(peggy.VERSION); }); it("handles dependencies", async() => { await expect(exec({ args: ["-d", "c:commander", "-d", "jest"], stdin: "foo = '1' { return new c.Command(); }", })).resolves.toMatch(/c = require\("commander"\)/); await expect(exec({ args: ["-d", "c:commander,jest"], stdin: "foo = '1' { return new c.Command(); }", })).resolves.toMatch(/jest = require\("jest"\)/); await expect(exec({ args: ["--dependency"], stdin: "foo = '1' { return new c.Command(); }", })).rejects.toThrow("option '-d, --dependency <dependency>' argument missing"); await expect(exec({ args: ["-d", "c:commander", "--format", "globals"], stdin: "foo = '1' { return new c.Command(); }", })).rejects.toThrow("Can't use the -d/--dependency option with the \"globals\" module format."); }); it("handles exportVar", async() => { await expect(exec({ args: ["--format", "globals", "-e", "football"], stdin: "foo = '1'", })).resolves.toMatch(/^\s*root\.football = /m); await expect(exec({ args: ["--export-var"], stdin: "foo = '1'", })).rejects.toThrow("option '-e, --export-var <variable>' argument missing"); await expect(exec({ args: ["--export-var", "football"], stdin: "foo = '1'", })).rejects.toThrow("Can't use the -e/--export-var option with the \"commonjs\" module format."); }); it("handles extra options", async() => { await expect(exec({ args: ["--extra-options", '{"format": "amd"}'], stdin: 'foo = "1"', })).resolves.toMatch(/^define\(/m); await expect(exec({ args: ["--extra-options"], stdin: 'foo = "1"', })).rejects.toThrow("--extra-options <options>' argument missing"); await expect(exec({ args: ["--extra-options", "{"], stdin: 'foo = "1"', })).rejects.toThrow("Error parsing JSON:"); await expect(exec({ args: ["--extra-options", "1"], stdin: 'foo = "1"', })).rejects.toThrow("The JSON with extra options has to represent an object."); }); it("handles extra options in a file", async() => { const optFile = path.join(__dirname, "fixtures", "options.json"); const optFileJS = path.join(__dirname, "fixtures", "options.js"); const res = await exec({ args: ["--extra-options-file", optFile], stdin: foobarbaz, }); expect(res).toMatch( /startRuleFunctions = { foo: [^, ]+, bar: [^, ]+, baz: \S+ }/ ); expect(res).toMatch("(function(root, factory) {"); // Intentional overwrite await expect(exec({ args: ["-c", optFile, "--format", "amd"], stdin: foobarbaz, })).resolves.toMatch(/^define\(/m); await expect(exec({ args: ["-c", optFileJS], stdin: "foo = zazzy:'1'", })).rejects.toThrow("Error: Label can't be a reserved word \"zazzy\""); await expect(exec({ args: ["-c", optFile, "____ERROR____FILE_DOES_NOT_EXIST"], stdin: "foo = '1'", })).rejects.toThrow("Do not specify input both on command line and in config file."); await expect(exec({ args: ["--extra-options-file"], stdin: 'foo = "1"', })).rejects.toThrow("--extra-options-file <file>' argument missing"); await expect(exec({ args: ["--extra-options-file", "____ERROR____FILE_DOES_NOT_EXIST"], stdin: 'foo = "1"', })).rejects.toThrow("Can't read from file"); }); it("handles formats", async() => { await expect(exec({ args: ["--format"], })).rejects.toThrow("option '--format <format>' argument missing"); await expect(exec({ args: ["--format", "BAD_FORMAT"], })).rejects.toThrow("option '--format <format>' argument 'BAD_FORMAT' is invalid. Allowed choices are amd, bare, commonjs, es, globals, umd."); }); it("doesn't fail with optimize", async() => { await expect(exec({ args: ["--optimize", "anything"], stdin: 'foo = "1"', })).resolves.toMatch(/deprecated/); await expect(exec({ args: ["-O", "anything"], stdin: 'foo = "1"', })).resolves.toMatch(/deprecated/); await expect(exec({ args: ["-O"], stdin: 'foo = "1"', })).rejects.toThrow("-O, --optimize <style>' argument missing"); }); it("outputs to a file", async() => { const test_output = path.resolve(__dirname, "test_output.js"); expect(() => { // Make sure the file isn't there before we start fs.statSync(test_output); }).toThrow(); await expect(exec({ args: ["-o", test_output], stdin: "foo = '1'", })).resolves.toBe(""); expect(fs.statSync(test_output)).toBeInstanceOf(fs.Stats); fs.unlinkSync(test_output); await expect(exec({ args: ["--output"], stdin: "foo = '1'", })).rejects.toThrow("-o, --output <file>' argument missing"); await expect(exec({ args: ["--output", "__DIRECTORY__/__DOES/NOT__/__EXIST__/none.js"], stdin: "foo = '1'", })).rejects.toThrow("Can't write to file \"__DIRECTORY__/__DOES/NOT__/__EXIST__/none.js\""); }); it("handles plugins", async() => { // Plugin, starting with "./" const plugin = "./" + path.relative( process.cwd(), path.resolve(__dirname, "./fixtures/plugin.js") ); const bad = "./" + path.relative( process.cwd(), path.resolve(__dirname, "./fixtures/bad.js") ); await expect(exec({ args: [ "--plugin", plugin, "--extra-options", '{"cli_test": {"words": ["foo"]}}', "-t", "1", ], stdin: "var = bar:'1'", })).resolves.toMatch("'1'"); await expect(exec({ args: [ "--plugin", `${plugin},${plugin}`, "--extra-options", '{"cli_test": {"words": ["foo"]}}', "-t", "1", ], stdin: "var = bar:'1'", })).resolves.toMatch("'1'"); await expect(exec({ args: [ "--plugin", plugin, "--extra-options", '{"cli_test": {"words": ["foo"]}}', ], stdin: "var = foo:'1'", })).rejects.toThrow("Label can't be a reserved word \"foo\""); await expect(exec({ args: ["--plugin"], stdin: "foo = '1'", })).rejects.toThrow("--plugin <module>' argument missing"); await expect(exec({ args: ["--plugin", "ERROR BAD MODULE DOES NOT EXIST"], stdin: "foo = '1'", })).rejects.toThrow("Can't load module \"ERROR BAD MODULE DOES NOT EXIST\""); await expect(exec({ args: ["--plugin", bad], stdin: "foo = '1'", })).rejects.toThrow("SyntaxError"); }); it("handlers trace", async() => { await expect(exec({ args: ["--trace"], stdin: "foo = '1'", })).resolves.toMatch("DefaultTracer: peg$DefaultTracer"); }); it("uses dash-dash", async() => { await expect(exec({ args: ["--", "--trace"], })).rejects.toThrow(/no such file or directory, open '[^']*--trace'/); await expect(exec({ args: ["--", "--trace", "--format"], })).rejects.toThrow("Too many arguments."); }); it("handles input tests", async() => { await expect(exec({ args: ["-t", "boo"], stdin: "foo = 'boo'", })).resolves.toMatch("'boo'"); const grammarFile = path.join(__dirname, "..", "..", "examples", "json.pegjs"); const testFile = path.join(__dirname, "..", "..", "package.json"); await expect(exec({ args: ["-T", testFile, grammarFile], })).resolves.toMatch("name: 'peggy'"); // Output is JS, not JSON await expect(exec({ args: ["-T", "____ERROR____FILE_DOES_NOT_EXIST.js", grammarFile], })).rejects.toThrow("Can't read from file \"____ERROR____FILE_DOES_NOT_EXIST.js\"."); await expect(exec({ args: ["-t", "boo", "-T", "foo"], })).rejects.toThrow("The -t/--test and -T/--test-file options are mutually exclusive."); await expect(exec({ args: ["-t", "2"], stdin: "foo='1'", })).rejects.toThrow('Expected "1" but "2" found'); await expect(exec({ args: ["-t", "1"], stdin: "foo='1' { throw new Error('bar') }", })).rejects.toThrow("Error: bar"); await expect(exec({ args: ["-t", "1", "--verbose"], stdin: "foo='1' { throw new Error('bar') }", })).rejects.toThrow("Error: bar"); }); });
the_stack
import * as React from "react"; import { Link } from "react-router-dom"; import "./LeftStatusIndicator.css"; import { ipcRenderer } from "electron"; interface State { abPerms: any; fdPerms: any; statusColorIndicator: any; showStatusTooltip: boolean; } class LeftStatusIndicator extends React.Component<unknown, State> { backgroundPermissionsCheck: NodeJS.Timeout; constructor(props: Readonly<{}>) { super(props); this.state = { abPerms: "deauthorized", fdPerms: "deauthorized", statusColorIndicator: { backgroundColor: "red" }, showStatusTooltip: false }; } async componentDidMount() { this.checkPermissions(); this.backgroundPermissionsCheck = setInterval(() => { this.checkPermissions(); }, 20000); } componentWillUnmount() { clearInterval(this.backgroundPermissionsCheck); } checkPermissions = async () => { const res = await ipcRenderer.invoke("check_perms"); this.setState({ abPerms: res.abPerms, fdPerms: res.fdPerms }); if (this.state.abPerms === "authorized" && this.state.fdPerms === "authorized") { this.setState({ statusColorIndicator: { backgroundColor: "#38d744" } }); } else { this.setState({ statusColorIndicator: { backgroundColor: "red" } }); } }; invokeMain(event: string, args: any) { ipcRenderer.invoke(event, args); } showStatusTooltip() { this.setState({ showStatusTooltip: true }); } hideStatusTooltip() { this.setState({ showStatusTooltip: false }); } render() { return ( <div id="leftStatusBar"> <Link to="/debug"> <svg id="debugIcon" viewBox="0 0 512 512"> <g> <path d="M376.493,310.998c-1.577-29.167-24.972-52.562-54.139-54.139v-21.72h-6.235v21.72 c-29.167,1.577-52.562,24.972-54.139,54.139h-21.465v6.235h21.465c1.577,29.167,24.972,52.568,54.139,54.145v21.715h6.235v-21.715 c29.167-1.576,52.562-24.978,54.139-54.145h26.141v-6.235H376.493z M316.119,365.143c-25.733-1.56-46.345-22.178-47.903-47.91 h47.903V365.143z M316.119,310.998h-47.903c1.559-25.732,22.17-46.345,47.903-47.903V310.998z M322.354,365.143v-47.91h47.903 C368.692,342.965,348.087,363.583,322.354,365.143z M322.354,310.998v-47.903c25.732,1.559,46.344,22.171,47.903,47.903H322.354z M291.336,90.016c-0.755-4.676,2.43-9.091,7.106-9.852c2.064-0.338,50.595-8.716,53.512-50.531 c0.322-4.677,4.365-8.257,9.151-7.974c4.737,0.335,8.312,4.445,7.989,9.17c-3.879,55.512-67.291,66.201-67.931,66.302 c-0.438,0.067-0.901,0.104-1.358,0.104C295.574,97.235,292.012,94.2,291.336,90.016z M32.383,30.83 c-0.329-4.725,3.249-8.835,7.971-9.164c4.874-0.344,8.841,3.291,9.17,7.968c2.92,41.82,51.441,50.199,53.512,50.537 c4.67,0.761,7.858,5.176,7.109,9.846c-0.679,4.184-4.241,7.225-8.473,7.225c-0.457,0-0.916-0.037-1.379-0.11 C99.668,97.031,36.255,86.341,32.383,30.83z M330.562,162.532c2.448,0.101,60.922,3.069,72.655,50.017 c0.555,2.229,0.214,4.536-0.962,6.503c-1.181,1.967-3.062,3.361-5.291,3.91c-0.67,0.182-1.382,0.268-2.083,0.268 c-3.945,0-7.367-2.68-8.33-6.504c-8.592-34.382-56.27-37.01-56.75-37.027c-2.284-0.095-4.403-1.078-5.956-2.768 c-1.553-1.69-2.356-3.885-2.259-6.181c0.195-4.612,3.939-8.229,8.531-8.229L330.562,162.532z M73.686,179.698 c-0.472,0.024-48.193,2.761-56.76,37.027c-0.959,3.824-4.381,6.504-8.33,6.504c-0.703,0-1.41-0.086-2.088-0.268 c-2.22-0.549-4.095-1.943-5.282-3.91c-1.179-1.967-1.52-4.274-0.965-6.503c11.734-46.947,70.208-49.916,72.692-50.022l0.359-0.006 c4.615,0,8.381,3.611,8.58,8.217C82.098,175.471,78.42,179.487,73.686,179.698z M160.925,49.106 c-0.219-1.708-0.332-3.428-0.332-5.133c0-22.289,18.14-40.429,40.429-40.429c22.293,0,40.426,18.14,40.426,40.429 c0,1.705-0.115,3.419-0.335,5.133c24.266,10.692,45.236,31.113,59.291,57.771l1.607,3.054l-3.069,1.589 c-26.348,13.707-55.752,20.658-87.392,20.658l0,0c-46.841,0-86.804-15.013-106.457-23.967l-3.398-1.553l1.827-3.261 C117.494,78.493,137.804,59.306,160.925,49.106z M116.005,298.235c1.148,4.592-1.653,9.262-6.241,10.412 c-0.441,0.122-46.098,12.398-52.008,53.037c-0.612,4.189-4.265,7.355-8.494,7.355c-0.411,0-0.828-0.024-1.245-0.098 c-4.683-0.676-7.946-5.048-7.265-9.736c7.618-52.349,62.502-66.646,64.834-67.23c0.679-0.17,1.388-0.256,2.095-0.256 C111.621,291.732,115.046,294.399,116.005,298.235z M319.236,222.145c-1.419,0-2.801,0.152-4.201,0.219 c2.643-11.971,4.11-24.527,4.11-37.503c0-22.94-4.287-44.88-12.732-65.215l-1.438-3.449l-3.318,1.717 c-21.896,11.317-57.305,17.881-83.147,20.247l-2.405,0.216l-0.603,2.338c-7.021,27.088-11.162,60.313-13.594,91.155 c-3.851-49.042-9.508-90.613-9.603-91.249l-0.429-2.947c-45.039-4.82-83.361-20.372-90.08-23.435l-3.157-1.44l-1.416,3.169 c-9.372,21.029-14.322,44.85-14.322,68.893c0,79.579,52.988,144.319,118.12,144.319c8.675,0,17.11-1.23,25.246-3.41 c5.054,46.838,44.804,83.445,92.963,83.445c51.569,0,93.529-41.96,93.529-93.529C412.76,264.112,370.812,222.145,319.236,222.145z M319.236,402.968c-48.135,0-87.294-39.153-87.294-87.294c0-48.129,39.159-87.294,87.294-87.294s87.294,39.165,87.294,87.294 C406.53,363.815,367.365,402.968,319.236,402.968z" /> </g> </svg> </Link> <Link to="/devices"> <svg id="deviceIcon" viewBox="0 0 512 512"> <g> <path d="M206.759,332.99H39.225c-3.894,0-7.065-3.173-7.065-7.067V53.353c0-3.893,3.172-7.065,7.065-7.065 h401.631c3.895,0,7.065,3.172,7.065,7.065v59.696c11.763,1.389,22.785,5.244,32.159,11.581V53.353 c0-21.63-17.602-39.225-39.225-39.225H39.225C17.602,14.128,0,31.722,0,53.353v272.569c0,21.631,17.602,39.227,39.225,39.227 h134.62v52.581h-21.229c-13.316,0-24.12,10.796-24.12,24.12c0,13.324,10.804,24.12,24.12,24.12h67.71 c-8.463-11.902-13.566-26.35-13.566-42.037V332.99z" /> <path d="M341.739,441.645v-34.742h-70.662V184.999c0-4.681,3.8-8.489,8.479-8.489h159.887 c4.679,0,8.478,3.808,8.478,8.489v68.676h12.046c7.364,0,14.179,2.127,20.113,5.597v-74.273c0-22.417-18.23-40.648-40.638-40.648 H279.556c-22.407,0-40.638,18.231-40.638,40.648v238.933c0,22.417,18.23,40.647,40.638,40.647h69.438 C344.566,458.22,341.739,449.359,341.739,441.645z" /> <path d="M459.967,273.775h-77.996c-11.104,0-20.132,9.037-20.132,20.138v147.732 c0,11.101,9.028,20.131,20.132,20.131h77.996c11.102,0,20.13-9.03,20.13-20.131V293.912 C480.097,282.811,471.068,273.775,459.967,273.775z M385.958,297.894h70.019v127.703h-70.019V297.894z M420.977,451.993 c-2.215,0-4.193-0.896-5.7-2.277c-1.713-1.555-2.812-3.739-2.812-6.228c0-4.694,3.801-8.495,8.512-8.495 c4.679,0,8.479,3.801,8.479,8.495c0,2.489-1.1,4.672-2.795,6.228C425.152,451.098,423.174,451.993,420.977,451.993z" /> </g> </svg> </Link> {this.state.showStatusTooltip ? ( <div id="statusTooltip"> <div> <h3>Full Disk Access:</h3>{" "} <span id="fdSubIcon" style={{ backgroundColor: this.state.fdPerms === "authorized" ? "#38d744" : "red" }} /> </div> <div> <h3>Accessibilty Access:</h3>{" "} <span id="accessibilitySubIcon" style={{ backgroundColor: this.state.abPerms === "authorized" ? "#38d744" : "red" }} /> </div> </div> ) : null} <div id="statusColorIndicator" style={this.state.statusColorIndicator} onMouseEnter={() => this.showStatusTooltip()} onMouseLeave={() => this.hideStatusTooltip()} /> <svg id="restartIcon" onClick={() => this.invokeMain("restart-server", null)} viewBox="0 0 512 512"> <g> <path d="M403.678,272c0,40.005-15.615,77.651-43.989,106.011C331.33,406.385,293.683,422,253.678,422 c-40.005,0-77.651-15.615-106.011-43.989c-28.374-28.359-43.989-66.006-43.989-106.011s15.615-77.651,43.989-106.011 C176.027,137.615,213.673,122,253.678,122c25.298,0,49.849,6.343,71.88,18.472L267.023,212h231.299L440.49,0l-57.393,70.13 C344.323,45.14,299.865,32,253.678,32c-64.116,0-124.395,24.961-169.702,70.298C38.639,147.605,13.678,207.884,13.678,272 s24.961,124.395,70.298,169.702C129.284,487.039,189.562,512,253.678,512s124.395-24.961,169.702-70.298 c45.337-45.308,70.298-105.586,70.298-169.702v-15h-90V272z" /> </g> </svg> </div> ); } } export default LeftStatusIndicator;
the_stack
import { BlueprintActionTemplates, Modifiers, Action2Response, Defaults } from './interfaces'; import { OpenApi } from '../types/openapi'; import { Reference } from 'swagger-schema-official'; /* eslint-disable @typescript-eslint/camelcase */ /** * Created by theophy on 02/08/2017. * * this modules helps us to stick with swagger specifications for formatting types */ export type SwaggerTypeAlias = 'integer' | 'long' | 'bigint' | 'float' | 'double' | 'string' | 'byte' | 'binary' | 'boolean' | 'date' | 'datetime' | 'password' | 'object' | 'any'; /** * this is used to map our sails types with the allowed type defintions based on swagger specification */ export const swaggerTypes: Record<SwaggerTypeAlias, OpenApi.UpdatedSchema> = { integer: { type: 'integer', format: 'int64', /* comments: 'signed 64 bits' */ }, // all JavaScript numbers 64-bit long: { type: 'integer', format: 'int64', /* comments: 'signed 64 bits' */ }, bigint: { type: 'integer' }, float: { type: 'number', format: 'float' }, double: { type: 'number', format: 'double' }, string: { type: 'string' }, byte: { type: 'string', format: 'byte', /* comments: 'base64 encoded characters' */ }, binary: { type: 'string', format: 'binary', /* comments: 'any sequence of octets' */ }, boolean: { type: 'boolean' }, date: { type: 'string', format: 'date', /* comments: 'As defined by full-date - RFC3339' */ }, datetime: { type: 'string', format: 'date-time', /* comments: 'As defined by date-time - RFC3339' */ }, password: { type: 'string', format: 'password', /* comments: 'A hint to UIs to obscure input' */ }, object: { type: 'object' }, any: {}, }; /** * Defines direct mappings from Sails model attribute definition values (key) to Swagger/OpenAPI * schema names (value). */ export const sailsAttributePropertiesMap: { [n in keyof Sails.AttributeDefinition]?: string } = { allowNull: 'nullable', defaultsTo: 'default', description: 'description', moreInfoUrl: 'externalDocs', example: 'example', }; /** * Defines direct mappings from Sails attribute validation (key) to Swagger/OpenAPI * schema name (value). */ export const validationsMap: { [n in keyof Sails.AttributeValidation]: string } = { max: 'maximum', min: 'minimum', maxLength: 'maxLength', minLength: 'minLength', isIn: 'enum' }; /** * Defines template for generating Swagger for each Sails blueprint action routes. * * In summary/description strings the value `{globalId}` is replaced with the applicable Sails model. * * Parameters values are Swagger definitions, with the exception of the string value * `primaryKeyPathParameter` used to include a reference to a model's primary key (this is * handled in `generatePaths()`). * * Modifiers are used to apply custom changes to the generated Swagger: * - String values are predefined in `generatePaths()` * - Functions are called with `func(blueprintActionTemplate, routeInfo, pathEntry)` * * These templates may be modfied / added to using the `updateBlueprintActionTemplates` config option * e.g. to support custom blueprint actions/routes. */ export const blueprintActionTemplates: BlueprintActionTemplates = { findone: { summary: 'Get {globalId} (find one)', description: 'Look up the **{globalId}** record with the specified ID.', externalDocs: { url: 'https://sailsjs.com/documentation/reference/blueprint-api/find-one', description: 'See https://sailsjs.com/documentation/reference/blueprint-api/find-one' }, parameters: [ 'primaryKeyPathParameter', // special case; filtered and substituted during generation phase ], resultDescription: 'Responds with a single **{globalId}** record as a JSON dictionary', notFoundDescription: 'Response denoting **{globalId}** record with specified ID **NOT** found', // if functions, each called with (blueprintActionTemplate, routeInfo, pathEntry) modifiers: [Modifiers.ADD_SELECT_QUERY_PARAM, Modifiers.ADD_OMIT_QUERY_PARAM, Modifiers.ADD_POPULATE_QUERY_PARAM, Modifiers.ADD_RESULT_OF_MODEL, Modifiers.ADD_RESULT_NOT_FOUND, Modifiers.ADD_SHORTCUT_BLUEPRINT_ROUTE_NOTE], }, find: { summary: 'List {globalId} (find where)', description: 'Find a list of **{globalId}** records that match the specified criteria.', externalDocs: { url: 'https://sailsjs.com/documentation/reference/blueprint-api/find-where', description: 'See https://sailsjs.com/documentation/reference/blueprint-api/find-where' }, parameters: [ { $ref: '#/components/parameters/AttributeFilterParam' }, { $ref: '#/components/parameters/WhereQueryParam' }, { $ref: '#/components/parameters/LimitQueryParam' }, { $ref: '#/components/parameters/SkipQueryParam' }, { $ref: '#/components/parameters/SortQueryParam' }, ], resultDescription: 'Responds with a paged list of **{globalId}** records that match the specified criteria', modifiers:[Modifiers.ADD_SELECT_QUERY_PARAM, Modifiers.ADD_OMIT_QUERY_PARAM, Modifiers.ADD_POPULATE_QUERY_PARAM, Modifiers.ADD_RESULT_OF_ARRAY_OF_MODELS, Modifiers.ADD_SHORTCUT_BLUEPRINT_ROUTE_NOTE] }, create: { summary: 'Create {globalId}', description: 'Create a new **{globalId}** record.', externalDocs: { url: 'https://sailsjs.com/documentation/reference/blueprint-api/create', description: 'See https://sailsjs.com/documentation/reference/blueprint-api/create' }, parameters: [], resultDescription: 'Responds with a JSON dictionary representing the newly created **{globalId}** instance', modifiers: [Modifiers.ADD_MODEL_BODY_PARAM, Modifiers.ADD_RESULT_OF_MODEL, Modifiers.ADD_RESULT_VALIDATION_ERROR, Modifiers.ADD_SHORTCUT_BLUEPRINT_ROUTE_NOTE] }, update: { summary: 'Update {globalId}', description: 'Update an existing **{globalId}** record.', externalDocs: { url: 'https://sailsjs.com/documentation/reference/blueprint-api/update', description: 'See https://sailsjs.com/documentation/reference/blueprint-api/update' }, parameters: [ 'primaryKeyPathParameter', ], resultDescription: 'Responds with the newly updated **{globalId}** record as a JSON dictionary', notFoundDescription: 'Cannot update, **{globalId}** record with specified ID **NOT** found', modifiers: [Modifiers.ADD_MODEL_BODY_PARAM_UPDATE, Modifiers.ADD_RESULT_OF_MODEL, Modifiers.ADD_RESULT_VALIDATION_ERROR, Modifiers.ADD_RESULT_NOT_FOUND, Modifiers.ADD_SHORTCUT_BLUEPRINT_ROUTE_NOTE] }, destroy: { summary: 'Delete {globalId} (destroy)', description: 'Delete the **{globalId}** record with the specified ID.', externalDocs: { url: 'https://sailsjs.com/documentation/reference/blueprint-api/destroy', description: 'See https://sailsjs.com/documentation/reference/blueprint-api/destroy' }, parameters: [ 'primaryKeyPathParameter', ], resultDescription: 'Responds with a JSON dictionary representing the destroyed **{globalId}** instance', notFoundDescription: 'Cannot destroy, **{globalId}** record with specified ID **NOT** found', modifiers: [Modifiers.ADD_RESULT_OF_MODEL, Modifiers.ADD_RESULT_NOT_FOUND, Modifiers.ADD_SHORTCUT_BLUEPRINT_ROUTE_NOTE], }, populate: { summary: 'Populate association for {globalId}', description: 'Populate and return foreign record(s) for the given association of this **{globalId}** record.', externalDocs: { url: 'https://sailsjs.com/documentation/reference/blueprint-api/populate-where', description: 'See https://sailsjs.com/documentation/reference/blueprint-api/populate-where' }, parameters: [ 'primaryKeyPathParameter', { $ref: '#/components/parameters/WhereQueryParam' }, { $ref: '#/components/parameters/LimitQueryParam' }, { $ref: '#/components/parameters/SkipQueryParam' }, { $ref: '#/components/parameters/SortQueryParam' }, ], resultDescription: 'Responds with the list of associated records as JSON dictionaries', notFoundDescription: 'Cannot populate, **{globalId}** record with specified ID **NOT** found', modifiers: [Modifiers.ADD_ASSOCIATION_PATH_PARAM, Modifiers.ADD_SELECT_QUERY_PARAM, Modifiers.ADD_OMIT_QUERY_PARAM, Modifiers.ADD_ASSOCIATION_RESULT_OF_ARRAY, Modifiers.ADD_RESULT_NOT_FOUND, Modifiers.ADD_SHORTCUT_BLUEPRINT_ROUTE_NOTE], }, add: { summary: 'Add to for {globalId}', description: 'Add a foreign record to one of this **{globalId}** record\'s collections.', externalDocs: { url: 'https://sailsjs.com/documentation/reference/blueprint-api/add-to', description: 'See https://sailsjs.com/documentation/reference/blueprint-api/add-to' }, parameters: [ 'primaryKeyPathParameter', ], resultDescription: 'Responds with the newly updated **{globalId}** record as a JSON dictionary', notFoundDescription: 'Cannot perform add to, **{globalId}** record OR **FK record** with specified ID **NOT** found', modifiers: [Modifiers.ADD_ASSOCIATION_PATH_PARAM, Modifiers.ADD_ASSOCIATION_FK_PATH_PARAM,Modifiers.ADD_RESULT_OF_MODEL, Modifiers.ADD_RESULT_NOT_FOUND, Modifiers.ADD_SHORTCUT_BLUEPRINT_ROUTE_NOTE], }, remove: { summary: 'Remove from for {globalId}', description: 'Remove a foreign record from one of this **{globalId}** record\'s collections.', externalDocs: { url: 'https://sailsjs.com/documentation/reference/blueprint-api/remove-from', description: 'See https://sailsjs.com/documentation/reference/blueprint-api/remove-from' }, parameters: [ 'primaryKeyPathParameter', ], resultDescription: 'Responds with the newly updated **{globalId}** record as a JSON dictionary', notFoundDescription: 'Cannot perform remove from, **{globalId}** record OR **FK record** with specified ID **NOT** found', modifiers: [Modifiers.ADD_ASSOCIATION_PATH_PARAM, Modifiers.ADD_ASSOCIATION_FK_PATH_PARAM, Modifiers.ADD_RESULT_OF_MODEL, Modifiers.ADD_RESULT_NOT_FOUND, Modifiers.ADD_SHORTCUT_BLUEPRINT_ROUTE_NOTE] }, replace: { summary: 'Replace for {globalId}', description: 'Replace all of the child records in one of this **{globalId}** record\'s associations.', externalDocs: { url: 'https://sailsjs.com/documentation/reference/blueprint-api/replace', description: 'See https://sailsjs.com/documentation/reference/blueprint-api/replace' }, parameters: [ 'primaryKeyPathParameter', ], resultDescription: 'Responds with the newly updated **{globalId}** record as a JSON dictionary', notFoundDescription: 'Cannot replace, **{globalId}** record with specified ID **NOT** found', modifiers: [Modifiers.ADD_ASSOCIATION_PATH_PARAM, Modifiers.ADD_FKS_BODY_PARAM, Modifiers.ADD_RESULT_OF_MODEL, Modifiers.ADD_RESULT_NOT_FOUND, Modifiers.ADD_SHORTCUT_BLUEPRINT_ROUTE_NOTE], }, }; /** * Defines standard parameters for generated Swagger for each Sails blueprint action routes. */ export const blueprintParameterTemplates: Record<string, OpenApi.Parameter | Reference> = { AttributeFilterParam: { in: 'query', name: '_*_', required: false, schema: { type: 'string' }, description: 'To filter results based on a particular attribute, specify a query parameter with the same name' + ' as the attribute defined on your model. For instance, if our `Purchase` model has an `amount` attribute, we' + ' could send `GET /purchase?amount=99.99` to return a list of $99.99 purchases.', }, WhereQueryParam: { in: 'query', name: 'where', required: false, schema: { type: 'string' }, description: 'Instead of filtering based on a specific attribute, you may instead choose to provide' + ' a `where` parameter with the WHERE piece of a' + ' [Waterline criteria](https://sailsjs.com/documentation/concepts/models-and-orm/query-language),' + ' _encoded as a JSON string_. This allows you to take advantage of `contains`, `startsWith`, and' + ' other sub-attribute criteria modifiers for more powerful `find()` queries.' + '\n\ne.g. `?where={"name":{"contains":"theodore"}}`' }, LimitQueryParam: { in: 'query', name: 'limit', required: false, schema: { type: 'integer' }, description: 'The maximum number of records to send back (useful for pagination). Defaults to 30.' }, SkipQueryParam: { in: 'query', name: 'skip', required: false, schema: { type: 'integer' }, description: 'The number of records to skip (useful for pagination).' }, SortQueryParam: { in: 'query', name: 'sort', required: false, schema: { type: 'string' }, description: 'The sort order. By default, returned records are sorted by primary key value in ascending order.' + '\n\ne.g. `?sort=lastName%20ASC`' }, }; /** * Defines standard Sails responses as used within actions2 actions. */ export const actions2Responses: Action2Response = { success: { statusCode: '200', description: 'Success' }, badRequest: { statusCode: '400', description: 'Bad request' }, forbidden: { statusCode: '403', description: 'Forbidden' }, notFound: { statusCode: '404', description: 'Not found' }, error: { statusCode: '500', description: 'Server error' }, }; /** * Default values for produces/consumes and responses for custom actions. */ export const defaults: Defaults = { responses: { '200': { description: 'The requested resource' }, '404': { description: 'Resource not found' }, '500': { description: 'Internal server error' } } };
the_stack
import * as tfwebgl from '@tensorflow/tfjs-backend-webgl'; import * as tfwasm from '@tensorflow/tfjs-backend-wasm'; import {GraphModel, loadGraphModel} from '@tensorflow/tfjs-converter'; import * as tf from '@tensorflow/tfjs-core'; import {ApplyConfigDefaults} from '../../util/config_helper'; import {IsWebglOneAvailable, IsWebglTwoAvailable} from '../../util/webgl_helper'; import { IModelCb, IDownloadProgressCb, IModelInput, ITypedArrayInput, ModelInputType, IModelResult, DownloadMultipleYohaModelBlobs, DownloadMultipleModelBlobs, DownloadBlobs, IBlobs, CreateCacheReadingFetchFunc, } from './base'; const DEFAULT_TFJS_WEBGL_ATTRIBUTES = { alpha: false, antialias: false, premultipliedAlpha: false, preserveDrawingBuffer: false, depth: false, stencil: false, failIfMajorPerformanceCaveat: true, powerPreference: 'default', }; /** * @public * The computational backend type to use as the tfjs backend. */ export const enum TfjsBackendType { /** * WebGPU backend. * Currently not supported. */ WEBGPU = 'WEBGPU', /** * Webgl backend. */ WEBGL = 'WEBGL', /** * WASM backend. * Currently not supported. */ WASM = 'WASM', /** * CPU backend. * Currently not supported. */ CPU = 'CPU', /** * Experimental. * No backend is set explicitly by Yoha. You have to set up tfjs yourself with the backend of * your choice before instantiating the Yoha models. */ MANUAL = 'MANUAL', } /** * @public * A tfjs model. */ export interface ITfjsModel { /** * The tfjs model. */ model: GraphModel /** * The tfjs backend type with which this model was created. */ backendType: TfjsBackendType } /** * @public * The two models required for running the Yoha engine. */ export interface IYohaTfjsModelBlobs { /** * This field adds some type safety to protect against mismatching blobs/backends. */ modelType: 'tfjs' /** * The file blobs of the box model for detecting initial hand position within stream. */ box: IBlobs /** * The file blobs of the landmark model for detecting landmark locations and detecting hand poses. */ lan: IBlobs } /** * @public * Downloads the Yoha tfjs models. * @param boxUrl - Url to model.json file of box model. * @param lanUrl - Url to model.json file of landmark model. * @param progressCb - A callback that is called with the cumulative download progress for all * models. */ export async function DownloadMultipleYohaTfjsModelBlobs( boxUrl: string, lanUrl: string, progressCb: IDownloadProgressCb ) : Promise<IYohaTfjsModelBlobs> { return { ...await DownloadMultipleYohaModelBlobs(boxUrl, lanUrl, progressCb, DownloadTfjsModelBlobs), modelType: 'tfjs', }; } /** * @public * Downloads a list of tfjs models. * @param urls - A list of URLs. Each URL must point to a model.json file. * @param progressCb - A callback that is called with the cumulative download progress for all * models. */ export async function DownloadTfjsModelBlobs( urls: string[], progressCb: IDownloadProgressCb ): Promise<IBlobs[]> { return DownloadMultipleModelBlobs(urls, progressCb, DownloadTfjsModel); } /** * @public * Downloads a tfjs model and reports download progress via a callback. * @param url - The URL to the model.json file of the tfjs model. * @param progressCb - Callback that informs about download progress. */ export async function DownloadTfjsModel( url: string, progressCb: IDownloadProgressCb ) : Promise<IBlobs> { const f = tf.env().platform.fetch; // Fetch model.json const modelJsonResponse = await f(url); const modelJsonBlob = await modelJsonResponse.blob(); const modelJsonString = await modelJsonBlob.text(); const modelJson = JSON.parse(modelJsonString); // Fetch binary chunks while keeping track of progress const weightPaths : string[] = modelJson.weightsManifest[0].paths; const urlBase = url.substring(0, url.lastIndexOf('/') + 1); const fullPaths : string[] = weightPaths.map((p: string) => urlBase + p); const res = await DownloadBlobs(fullPaths, progressCb); // Need to include the model json that was downloaded beforehand. res.blobs.set(url, modelJsonBlob); return res; } export interface ITfjsManualBackendConfig { backendType: TfjsBackendType.MANUAL } export interface IInternalTfjsManualBackendConfig { backendType: TfjsBackendType.MANUAL } export interface ITfjsWebglBackendConfig { backendType: TfjsBackendType.WEBGL } export interface IInternalTfjsWebglBackendConfig { backendType: TfjsBackendType.WEBGL } /** * @public * Configuration that is specific to the tfjs wasm backend. * */ export interface ITfjsWasmBackendConfig { /** * See https://github.com/tensorflow/tfjs/tree/master/tfjs-backend-wasm#using-bundlers */ wasmPaths: string } export interface IInternalTfjsWasmBackendConfig { backendType: TfjsBackendType.WASM wasmPaths: string } /** * We create external and interal configs just so that users don't have to deal with * setting the 'backendType' fields... */ export type ITfjsBackendConfig = ITfjsWebglBackendConfig | ITfjsWasmBackendConfig | ITfjsManualBackendConfig; export type IInternalTfjsBackendConfig = IInternalTfjsWebglBackendConfig | IInternalTfjsWasmBackendConfig | IInternalTfjsManualBackendConfig; export const DEFAULT_TFJS_MANUAL_BACKEND_CONFIG = { type: TfjsBackendType.MANUAL, }; export const DEFAULT_TFJS_WEBGL_BACKEND_CONFIG = { type: TfjsBackendType.WEBGL, }; export const DEFAULT_TFJS_WASM_BACKEND_CONFIG = { type: TfjsBackendType.WASM, wasmPath: '' }; /** * Creates a tfjs graph model from tfjs model files. * @param modelBlobs - The model files from which to create a tfjs model. * @param backendType - What computational backend to use for creation of the model. */ export async function CreateTfjsModelFromModelBlobs( modelBlobs: IBlobs, config: IInternalTfjsBackendConfig, ) : Promise<ITfjsModel> { const defaultConfig = GetTfjsDefaultBackendConfigForBackendType(config.backendType); config = ApplyConfigDefaults(defaultConfig, config); const t = config.backendType; if (t === TfjsBackendType.WEBGL) { await SetTfjsBackendToWebgl(); } else if (t === TfjsBackendType.WASM) { await SetTfjsBackendToWasm(config.wasmPaths); } else if (t === TfjsBackendType.MANUAL) { // no-op } else { throw 'Backend ' + t + ' is currently not supported.'; } const cacheReadingFetchFunc = CreateCacheReadingFetchFunc(modelBlobs); const graphModel = await loadGraphModel(ExtractModelJsonUrlFromModelBlobs(modelBlobs), { fetchFunc: cacheReadingFetchFunc }); return { model: graphModel, backendType: t, }; } function GetTfjsDefaultBackendConfigForBackendType(backendType: TfjsBackendType) { if (backendType === TfjsBackendType.WEBGL) { return DEFAULT_TFJS_WEBGL_BACKEND_CONFIG; } else if (backendType === TfjsBackendType.WASM) { return DEFAULT_TFJS_WASM_BACKEND_CONFIG; } else if (backendType === TfjsBackendType.MANUAL) { return DEFAULT_TFJS_MANUAL_BACKEND_CONFIG; } else { throw 'Backend ' + backendType + ' is currently not supported.'; } } function ExtractModelJsonUrlFromModelBlobs(modelBlobs: IBlobs) { let url : string = null; for (const k of modelBlobs.blobs.keys()) { if (k.endsWith('model.json')) { if (url) { throw 'modelBlobs contained two model.json entries.'; } url = k; } } if (!url) { throw 'modelBlobs did not contain a model.json entry.'; } return url; } /** * Sets the tfjs webgl backend. */ export async function SetTfjsBackendToWebgl() { // Tfjs has its own mechanism for determining whether webgl is available. In // particular they create a canvas with a webgl context and a custom set of // webgl attributes among which they use 'failIfMajorPerformanceCaveat' === // true. This causes some browsers, in particular late versions of firefox, to // disable webgl if the browser determines that webgl would lead to similar or // worse performance than other contexts like software rendering. If this // happens tfjs records that there is no WEBGL available (even though the // browser supports it). It turned out that at least on firefox the heuristic // it uses to determine whether to disable webgl or not works poorly i.e. // webgl is disabled even though it would lead to incredible performance // improvements for us. // // Thus we override tfjs determination of whether webgl is available. tf.env().set('HAS_WEBGL', true); if (IsWebglTwoAvailable()) { tf.env().set('WEBGL_VERSION', 2); } else if (IsWebglOneAvailable()) { tf.env().set('WEBGL_VERSION', 1); } else { throw 'No webgl available.'; } const webglAttributes = JSON.parse(JSON.stringify(DEFAULT_TFJS_WEBGL_ATTRIBUTES)); webglAttributes.failIfMajorPerformanceCaveat = false; webglAttributes.powerPreference = 'high-performance'; tf.removeBackend('webgl'); tf.registerBackend('webgl', () => { const canvas = document.createElement('canvas'); let ctx : WebGLRenderingContext; if (IsWebglTwoAvailable()) { // in tfjs source code they also do this cast ctx = <WebGLRenderingContext>(canvas.getContext('webgl2', webglAttributes)); } else { // in tfjs source code they also do this cast ctx = <WebGLRenderingContext>(canvas.getContext('webgl', webglAttributes)); } const backend = new tfwebgl.MathBackendWebGL(new tfwebgl.GPGPUContext(ctx)); return backend; }, 999); await tf.setBackend('webgl'); await tf.ready(); } /** * Sets the tfjs wasm backend. */ export async function SetTfjsBackendToWasm(wasmPaths: string) { if (!wasmPaths) { throw '`wasmPaths` not set. Got ' + wasmPaths; } tfwasm.setWasmPaths(wasmPaths); await tf.setBackend('wasm'); await tf.ready(); } function GetCurrentTfjsBackend() : TfjsBackendType { const t = tf.getBackend(); if (t === 'webgl') { return TfjsBackendType.WEBGL; } else if (t === 'webgpu') { return TfjsBackendType.WEBGPU; } else if (t === 'cpu') { return TfjsBackendType.CPU; } else if (t === 'wasm') { return TfjsBackendType.WASM; } else { throw 'Unknown backend type string: ' + t; } } function DoesTfjsBackendTypeMatchCurrentlySetBackend(bt: TfjsBackendType) : boolean { return GetCurrentTfjsBackend() === bt || bt === TfjsBackendType.MANUAL; } /** * Creates a model callback from a tfjs graph model and information about how the model * is to be invoked. * @param model - The graph model to create a callback for. * @param execAsync - Whether to execute the model asynchronously. */ export function CreateModelCbFromTfjsModel(model: ITfjsModel, execAsync: boolean) : IModelCb { return async (modelInput: IModelInput) : Promise<IModelResult> => { if (!DoesTfjsBackendTypeMatchCurrentlySetBackend(model.backendType)) { console.warn('The tfjs model was created with backend ' + model.backendType + ' but the backend was switched to ' + GetCurrentTfjsBackend()); } const t = CreateTensorFromModelInput(modelInput); const tfjsRes = <tf.Tensor<tf.Rank>[]>(model.model.execute( t, ['coordinates', 'classes'] )); t.dispose(); const readOutputFn = async (index: number) : Promise<number[][]> => { const outputEl = tfjsRes[index]; const batchedRes = <number[][][]>( execAsync ? (await outputEl.array()) : outputEl.arraySync()); const noBatchDimRes = batchedRes[0]; return noBatchDimRes; }; const [coords, classes] = await Promise.all( [readOutputFn(0), readOutputFn(1)] ); for (const resultTensor of tfjsRes) { resultTensor.dispose(); } return { // need to convert coordinates from [-1,1] into range [0,1] coordinates: coords.map(c => [(c[0] + 1) / 2, (c[1] + 1) / 2]), // classes is list of bernulli distributions. We just keep one value of it. classes: classes.map(v => v[1]) }; }; } export function CreateTensorFromModelInput(mi: IModelInput) { let t : tf.Tensor; if (mi.type === ModelInputType.TRACK_SOURCE) { // Typescript complains here about offscreen canvas but it's fine to pass it. // eslint-disable-next-line @typescript-eslint/no-explicit-any t = tf.browser.fromPixels(<any>mi.data); } else if (mi.type === ModelInputType.TYPED_ARRAY) { t = CreateTensorFromTypedArrayInput(mi); } else { throw 'not implemented'; } const reshaped = tf.reshape(t, [1, t.shape[0], t.shape[1], t.shape[2]]); const casted = tf.cast(reshaped, 'float32'); reshaped.dispose(); t.dispose(); return casted; } function CreateTensorFromTypedArrayInput(tai: ITypedArrayInput) { if (tai.data instanceof Uint8Array) { return tf.tensor(tai.data, tai.shape, 'int32'); } else { throw 'not implemented'; } } /** * Given a Tfjs model where the first input tensor is of shape [B,H,W,C]. * returns [H,W]. Returns undefined if such tensor was not found. */ export function GetInputDimensionsFromTfjsModel(model: ITfjsModel): number[] { if (!model.model.inputs.length) { return; } const dims = model.model.inputs[0].shape; if (dims.length !== 4) { return; } return [dims[1], dims[2]]; }
the_stack
import * as moment from "moment"; /** * Defines the query context that Bing used for the request. */ export interface QueryContext { /** * The query string as specified in the request. */ originalQuery: string; /** * The query string used by Bing to perform the query. Bing uses the altered query string if the * original query string contained spelling mistakes. For example, if the query string is "saling * downwind", the altered query string will be "sailing downwind". This field is included only if * the original query string contains a spelling mistake. */ readonly alteredQuery?: string; /** * The query string to use to force Bing to use the original string. For example, if the query * string is "saling downwind", the override query string will be "+saling downwind". Remember to * encode the query string which results in "%2Bsaling+downwind". This field is included only if * the original query string contains a spelling mistake. */ readonly alterationOverrideQuery?: string; /** * A Boolean value that indicates whether the specified query has adult intent. The value is true * if the query has adult intent; otherwise, false. */ readonly adultIntent?: boolean; /** * A Boolean value that indicates whether Bing requires the user's location to provide accurate * results. If you specified the user's location by using the X-MSEdge-ClientIP and * X-Search-Location headers, you can ignore this field. For location aware queries, such as * "today's weather" or "restaurants near me" that need the user's location to provide accurate * results, this field is set to true. For location aware queries that include the location (for * example, "Seattle weather"), this field is set to false. This field is also set to false for * queries that are not location aware, such as "best sellers". */ readonly askUserForLocation?: boolean; } export interface ResponseBase { /** * Polymorphic Discriminator */ _type: string; } /** * Defines the identity of a resource. */ export interface Identifiable extends ResponseBase { /** * A String identifier. */ readonly id?: string; } /** * Defines a response. All schemas that could be returned at the root of a response should inherit * from this */ export interface Response extends Identifiable { /** * A list of rules that you must adhere to if you display the item. */ readonly contractualRules?: ContractualRulesContractualRule[]; /** * The URL To Bing's search result for this item. */ readonly webSearchUrl?: string; } export interface Thing extends Response { /** * The name of the thing represented by this object. */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. */ readonly url?: string; readonly image?: ImageObject; /** * A short description of the item. */ readonly description?: string; /** * Additional information about the entity such as hints that you can use to determine the * entity's type. To determine the entity's type, use the entityScenario and entityTypeHint * fields. */ readonly entityPresentationInfo?: EntitiesEntityPresentationInfo; /** * An ID that uniquely identifies this item. */ readonly bingId?: string; } export interface CreativeWork extends Thing { /** * The URL to a thumbnail of the item. */ readonly thumbnailUrl?: string; /** * The source of the creative work. */ readonly provider?: Thing[]; readonly text?: string; } export interface MediaObject extends CreativeWork { /** * Original URL to retrieve the source (file) for the media object (e.g the source URL for the * image). */ readonly contentUrl?: string; /** * URL of the page that hosts the media object. */ readonly hostPageUrl?: string; /** * The width of the source media object, in pixels. */ readonly width?: number; /** * The height of the source media object, in pixels. */ readonly height?: number; } /** * Defines an image */ export interface ImageObject extends MediaObject { /** * The URL to a thumbnail of the image */ readonly thumbnail?: ImageObject; } /** * Defines additional information about an entity such as type hints. */ export interface EntitiesEntityPresentationInfo { /** * The supported scenario. Possible values include: 'DominantEntity', 'DisambiguationItem', * 'ListItem' */ entityScenario: string; /** * A list of hints that indicate the entity's type. The list could contain a single hint such as * Movie or a list of hints such as Place, LocalBusiness, Restaurant. Each successive hint in the * array narrows the entity's type. */ readonly entityTypeHints?: string[]; /** * A display version of the entity hint. For example, if entityTypeHints is Artist, this field * may be set to American Singer. */ readonly entityTypeDisplayHint?: string; } export interface Answer extends Response { } export interface SearchResultsAnswer extends Answer { readonly queryContext?: QueryContext; } /** * Defines an entity answer. */ export interface Entities extends SearchResultsAnswer { /** * The supported query scenario. This field is set to DominantEntity or DisambiguationItem. The * field is set to DominantEntity if Bing determines that only a single entity satisfies the * request. For example, a book, movie, person, or attraction. If multiple entities could satisfy * the request, the field is set to DisambiguationItem. For example, if the request uses the * generic title of a movie franchise, the entity's type would likely be DisambiguationItem. But, * if the request specifies a specific title from the franchise, the entity's type would likely * be DominantEntity. Possible values include: 'DominantEntity', * 'DominantEntityWithDisambiguation', 'Disambiguation', 'List', 'ListWithPivot' */ readonly queryScenario?: string; /** * A list of entities. */ value: Thing[]; } /** * Defines a local entity answer. */ export interface Places extends SearchResultsAnswer { /** * A list of local entities, such as restaurants or hotels. */ value: Thing[]; } /** * Defines the top-level object that the response includes when the request succeeds. */ export interface SearchResponse extends Response { /** * An object that contains the query string that Bing used for the request. This object contains * the query string as entered by the user. It may also contain an altered query string that Bing * used for the query if the query string contained a spelling mistake. */ readonly queryContext?: QueryContext; /** * A list of entities that are relevant to the search query. */ readonly entities?: Entities; /** * A list of local entities such as restaurants or hotels that are relevant to the query. */ readonly places?: Places; } export interface ContractualRulesContractualRule { /** * The name of the field that the rule applies to. */ readonly targetPropertyName?: string; /** * Polymorphic Discriminator */ _type: string; } /** * Defines the error that occurred. */ export interface ErrorModel { /** * The error code that identifies the category of error. Possible values include: 'None', * 'ServerError', 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization', * 'InsufficientAuthorization' */ code: string; /** * The error code that further helps to identify the error. Possible values include: * 'UnexpectedError', 'ResourceError', 'NotImplemented', 'ParameterMissing', * 'ParameterInvalidValue', 'HttpNotAllowed', 'Blocked', 'AuthorizationMissing', * 'AuthorizationRedundancy', 'AuthorizationDisabled', 'AuthorizationExpired' */ readonly subCode?: string; /** * A description of the error. */ message: string; /** * A description that provides additional information about the error. */ readonly moreDetails?: string; /** * The parameter in the request that caused the error. */ readonly parameter?: string; /** * The parameter's value in the request that was not valid. */ readonly value?: string; } /** * The top-level response that represents a failed request. */ export interface ErrorResponse extends Response { /** * A list of errors that describe the reasons why the request failed. */ errors: ErrorModel[]; } export interface Intangible extends Thing { } export interface StructuredValue extends Intangible { } /** * Defines a postal address. */ export interface PostalAddress extends StructuredValue { readonly streetAddress?: string; /** * The city where the street address is located. For example, Seattle. */ readonly addressLocality?: string; readonly addressSubregion?: string; /** * The state or province code where the street address is located. This could be the two-letter * code. For example, WA, or the full name , Washington. */ readonly addressRegion?: string; /** * The zip code or postal code where the street address is located. For example, 98052. */ readonly postalCode?: string; readonly postOfficeBoxNumber?: string; /** * The country/region where the street address is located. This could be the two-letter ISO code. * For example, US, or the full name, United States. */ readonly addressCountry?: string; /** * The two letter ISO code of this country. For example, US. */ readonly countryIso?: string; /** * The neighborhood where the street address is located. For example, Westlake. */ readonly neighborhood?: string; /** * Region Abbreviation. For example, WA. */ readonly addressRegionAbbreviation?: string; /** * The complete address. For example, 2100 Westlake Ave N, Bellevue, WA 98052. */ readonly text?: string; } /** * Defines information about a local entity, such as a restaurant or hotel. */ export interface Place extends Thing { /** * The postal address of where the entity is located */ readonly address?: PostalAddress; /** * The entity's telephone number */ readonly telephone?: string; } /** * Defines an organization. */ export interface Organization extends Thing { } export interface LocalBusiness extends Place { /** * $$. */ readonly priceRange?: string; readonly panoramas?: ImageObject[]; readonly isPermanentlyClosed?: boolean; readonly tagLine?: string; } export interface EntertainmentBusiness extends LocalBusiness { } export interface MovieTheater extends EntertainmentBusiness { readonly screenCount?: number; } export interface ContractualRulesAttribution extends ContractualRulesContractualRule { /** * A Boolean value that determines whether the contents of the rule must be placed in close * proximity to the field that the rule applies to. If true, the contents must be placed in close * proximity. If false, or this field does not exist, the contents may be placed at the caller's * discretion. */ readonly mustBeCloseToContent?: boolean; } export interface CivicStructure extends Place { } export interface TouristAttraction extends Place { } export interface Airport extends CivicStructure { readonly iataCode?: string; readonly icaoCode?: string; } /** * Defines the license under which the text or photo may be used. */ export interface License extends CreativeWork { } /** * Defines a contractual rule for license attribution. */ export interface ContractualRulesLicenseAttribution extends ContractualRulesAttribution { /** * The license under which the content may be used. */ readonly license?: License; /** * The license to display next to the targeted field. */ readonly licenseNotice?: string; } /** * Defines a contractual rule for link attribution. */ export interface ContractualRulesLinkAttribution extends ContractualRulesAttribution { /** * The attribution text. */ text: string; /** * The URL to the provider's website. Use text and URL to create the hyperlink. */ url: string; /** * Indicates whether this provider's attribution is optional. */ readonly optionalForListDisplay?: boolean; } /** * Defines a contractual rule for media attribution. */ export interface ContractualRulesMediaAttribution extends ContractualRulesAttribution { /** * The URL that you use to create of hyperlink of the media content. For example, if the target * is an image, you would use the URL to make the image clickable. */ readonly url?: string; } /** * Defines a contractual rule for text attribution. */ export interface ContractualRulesTextAttribution extends ContractualRulesAttribution { /** * The attribution text. Text attribution applies to the entity as a whole and should be * displayed immediately following the entity presentation. If there are multiple text or link * attribution rules that do not specify a target, you should concatenate them and display them * using a "Data from:" label. */ text: string; /** * Indicates whether this provider's attribution is optional. */ readonly optionalForListDisplay?: boolean; } export interface FoodEstablishment extends LocalBusiness { } export interface LodgingBusiness extends LocalBusiness { } export interface Restaurant extends FoodEstablishment { readonly acceptsReservations?: boolean; readonly reservationUrl?: string; readonly servesCuisine?: string[]; readonly menuUrl?: string; } export interface Hotel extends LodgingBusiness { readonly hotelClass?: string; readonly amenities?: string[]; }
the_stack
* @group integration/did */ import { UUID } from '@kiltprotocol/utils' import { encodeAddress } from '@polkadot/keyring' import { DemoKeystore, DidChain, DidTypes, DidUtils, SigningAlgorithms, EncryptionAlgorithms, LightDidDetails, resolveDoc, } from '@kiltprotocol/did' import { BlockchainUtils, BlockchainApiConnection, } from '@kiltprotocol/chain-helpers' import { KeyRelationship, IDidServiceEndpoint, KeyringPair, KeystoreSigner, IDidResolvedDetails, } from '@kiltprotocol/types' import { BN } from '@polkadot/util' import { disconnect, init } from '../kilt' import { CType } from '../ctype' import { devAlice, devBob } from './utils' let paymentAccount: KeyringPair const keystore = new DemoKeystore() beforeAll(async () => { await init({ address: 'ws://localhost:9944' }) paymentAccount = devAlice }) it('fetches the correct deposit amount', async () => { const depositAmount = await DidChain.queryDepositAmount() expect(depositAmount.toString()).toStrictEqual( new BN(2000000000000000).toString() ) }) describe('write and didDeleteTx', () => { let didIdentifier: string let key: DidTypes.INewPublicKey beforeAll(async () => { const { publicKey, alg } = await keystore.generateKeypair({ alg: SigningAlgorithms.Ed25519, }) didIdentifier = encodeAddress(publicKey, 38) key = { publicKey, type: alg } }) it('fails to create a new DID on chain with a different submitter than the one in the creation operation', async () => { const otherAccount = devBob const tx = await DidChain.generateCreateTx({ didIdentifier, signer: keystore as KeystoreSigner<string>, // A different address than the one submitting the tx (paymentAccount) is specified submitter: otherAccount.address, signingPublicKey: key.publicKey, alg: key.type, }) await expect( BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).rejects.toThrow() }, 60_000) it('writes a new DID record to chain', async () => { const tx = await DidChain.generateCreateTx({ didIdentifier, signer: keystore as KeystoreSigner<string>, submitter: paymentAccount.address, signingPublicKey: key.publicKey, alg: key.type, endpoints: [ { id: 'test-id-1', types: ['test-type-1'], urls: ['test-url-1'], }, { id: 'test-id-2', types: ['test-type-2'], urls: ['test-url-2'], }, ], }) const did = DidUtils.getKiltDidFromIdentifier(didIdentifier, 'full') await expect( BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() await expect(DidChain.queryDidDetails(did)).resolves.toMatchObject< Partial<DidTypes.IDidChainRecordJSON> >({ did, }) await expect(DidChain.queryServiceEndpoints(did)).resolves.toMatchObject< IDidServiceEndpoint[] >([ { id: DidUtils.assembleDidFragment(did, 'test-id-1'), types: ['test-type-1'], urls: ['test-url-1'], }, { id: DidUtils.assembleDidFragment(did, 'test-id-2'), types: ['test-type-2'], urls: ['test-url-2'], }, ]) await expect( DidChain.queryServiceEndpoint(`${did}#test-id-1`) ).resolves.toMatchObject<IDidServiceEndpoint>({ id: DidUtils.assembleDidFragment(did, 'test-id-1'), types: ['test-type-1'], urls: ['test-url-1'], }) // Test that the negative results are also properly returned const emptyDid = DidUtils.getKiltDidFromIdentifier( paymentAccount.address, 'full' ) // Should be defined and have 0 elements await expect( DidChain.queryServiceEndpoints(emptyDid) ).resolves.toBeDefined() await expect( DidChain.queryServiceEndpoints(emptyDid) ).resolves.toHaveLength(0) // Should return null await expect( DidChain.queryServiceEndpoint(`${emptyDid}#non-existing-service-id`) ).resolves.toBeNull // Should return 0 await expect(DidChain.queryEndpointsCounts(emptyDid)).resolves.toBe(0) }, 60_000) it('fails to delete the DID using a different submitter than the one specified in the DID operation or using a services count that is too low', async () => { const otherAccount = devBob // 10 is an example value. It is not used here since we are testing another error let call = await DidChain.getDeleteDidExtrinsic(10) let submittable = await DidChain.generateDidAuthenticatedTx({ didIdentifier, txCounter: 1, call, signer: keystore as KeystoreSigner<string>, signingPublicKey: key.publicKey, alg: key.type, // Use a different account than the submitter one submitter: otherAccount.address, }) await expect( BlockchainUtils.signAndSubmitTx(submittable, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).rejects.toThrow() // We use 1 here and this should fail as there are two service endpoints stored. call = await DidChain.getDeleteDidExtrinsic(1) submittable = await DidChain.generateDidAuthenticatedTx({ didIdentifier, txCounter: 1, call, signer: keystore as KeystoreSigner<string>, signingPublicKey: key.publicKey, alg: key.type, // We use the expected submitter's account submitter: paymentAccount.address, }) // Will fail because count provided is too low await expect( BlockchainUtils.signAndSubmitTx(submittable, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).rejects.toThrow() }, 60_000) it('deletes DID from previous step', async () => { const did = DidUtils.getKiltDidFromIdentifier(didIdentifier, 'full') await expect(DidChain.queryById(didIdentifier)).resolves.toMatchObject< Partial<DidTypes.IDidChainRecordJSON> >({ did: DidUtils.getKiltDidFromIdentifier(didIdentifier, 'full'), }) const storedEndpointsCount = await DidChain.queryEndpointsCounts(did) const call = await DidChain.getDeleteDidExtrinsic(storedEndpointsCount) const submittable = await DidChain.generateDidAuthenticatedTx({ didIdentifier, txCounter: 2, call, signer: keystore as KeystoreSigner<string>, signingPublicKey: key.publicKey, alg: key.type, submitter: paymentAccount.address, }) // Check that DID is not blacklisted. await expect(DidChain.queryDeletedDids()).resolves.toStrictEqual([]) await expect(DidChain.queryDidDeletionStatus(did)).resolves.toBeFalsy() await expect( BlockchainUtils.signAndSubmitTx(submittable, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() await expect(DidChain.queryById(didIdentifier)).resolves.toBe(null) // Check that DID is now blacklisted. await expect(DidChain.queryDeletedDids()).resolves.toStrictEqual([did]) await expect(DidChain.queryDidDeletionStatus(did)).resolves.toBeTruthy() }, 60_000) }) it('creates and updates DID, and then reclaims the deposit back', async () => { const { publicKey, alg } = await keystore.generateKeypair({ alg: SigningAlgorithms.Ed25519, }) const didIdentifier = encodeAddress(publicKey, 38) const did = DidUtils.getKiltDidFromIdentifier(didIdentifier, 'full') const key: DidTypes.INewPublicKey = { publicKey, type: alg } const tx = await DidChain.generateCreateTx({ didIdentifier, signer: keystore as KeystoreSigner<string>, submitter: paymentAccount.address, signingPublicKey: key.publicKey, alg: key.type, }) await expect( BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() await expect(DidChain.queryById(didIdentifier)).resolves.toMatchObject< Partial<DidTypes.IDidChainRecordJSON> >({ did, }) const newKeypair = await keystore.generateKeypair({ alg: SigningAlgorithms.Ed25519, }) const newKeyDetails: DidTypes.INewPublicKey = { publicKey: newKeypair.publicKey, type: newKeypair.alg, } const updateAuthenticationKeyCall = await DidChain.getSetKeyExtrinsic( KeyRelationship.authentication, newKeyDetails ) const tx2 = await DidChain.generateDidAuthenticatedTx({ didIdentifier, txCounter: 1, call: updateAuthenticationKeyCall, signer: keystore as KeystoreSigner<string>, signingPublicKey: key.publicKey, alg: key.type, submitter: paymentAccount.address, }) await expect( BlockchainUtils.signAndSubmitTx(tx2, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() await expect(DidChain.queryById(didIdentifier)).resolves.toMatchObject< Partial<DidTypes.IDidChainRecordJSON> >({ did: DidUtils.getKiltDidFromIdentifier(didIdentifier, 'full'), }) // Add a new service endpoint const newEndpoint: IDidServiceEndpoint = { id: 'new-endpoint', types: ['new-type'], urls: ['new-url'], } const updateEndpointCall = await DidChain.getAddEndpointExtrinsic(newEndpoint) const tx3 = await DidChain.generateDidAuthenticatedTx({ didIdentifier, txCounter: 2, call: updateEndpointCall, signer: keystore as KeystoreSigner<string>, signingPublicKey: newKeyDetails.publicKey, alg: newKeyDetails.type, submitter: paymentAccount.address, }) await expect( BlockchainUtils.signAndSubmitTx(tx3, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() await expect( DidChain.queryServiceEndpoint(`${did}#${newEndpoint.id}`) ).resolves.toMatchObject<IDidServiceEndpoint>({ ...newEndpoint, id: DidUtils.assembleDidFragment(did, newEndpoint.id), }) // Delete the added service endpoint const removeEndpointCall = await DidChain.getRemoveEndpointExtrinsic( newEndpoint.id ) const tx4 = await DidChain.generateDidAuthenticatedTx({ didIdentifier, txCounter: 3, call: removeEndpointCall, signer: keystore as KeystoreSigner<string>, signingPublicKey: newKeyDetails.publicKey, alg: newKeyDetails.type, submitter: paymentAccount.address, }) await expect( BlockchainUtils.signAndSubmitTx(tx4, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() // There should not be any endpoint with the given ID now. await expect( DidChain.queryServiceEndpoint(`${did}#${newEndpoint.id}`) ).resolves.toBeNull() // Claim the deposit back const storedEndpointsCount = await DidChain.queryEndpointsCounts(did) const reclaimDepositTx = await DidChain.getReclaimDepositExtrinsic( didIdentifier, storedEndpointsCount ) await expect( BlockchainUtils.signAndSubmitTx(reclaimDepositTx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() // Verify that the DID has been deleted await expect(DidChain.queryById(didIdentifier)).resolves.toBeNull() await expect(DidChain.queryServiceEndpoints(did)).resolves.toHaveLength(0) await expect(DidChain.queryEndpointsCounts(did)).resolves.toBe(0) }, 80_000) describe('DID migration', () => { it('migrates light DID with ed25519 auth key and encryption key', async () => { const didEd25519AuthenticationKeyDetails = await keystore.generateKeypair({ alg: SigningAlgorithms.Ed25519, }) const didEncryptionKeyDetails = await keystore.generateKeypair({ seed: '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', alg: EncryptionAlgorithms.NaclBox, }) const lightDidDetails = new LightDidDetails({ authenticationKey: { publicKey: didEd25519AuthenticationKeyDetails.publicKey, type: DemoKeystore.getKeypairTypeForAlg( didEd25519AuthenticationKeyDetails.alg ), }, encryptionKey: { publicKey: didEncryptionKeyDetails.publicKey, type: DemoKeystore.getKeypairTypeForAlg(didEncryptionKeyDetails.alg), }, }) const { extrinsic, did } = await DidUtils.upgradeDid( lightDidDetails, paymentAccount.address, keystore ) await expect( BlockchainUtils.signAndSubmitTx(extrinsic, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() await expect( DidChain.queryById(DidUtils.getIdentifierFromKiltDid(did)) ).resolves.not.toBeNull() const { details, metadata } = (await resolveDoc( lightDidDetails.did )) as IDidResolvedDetails expect(details?.did).toStrictEqual(lightDidDetails.did) expect(metadata.canonicalId).toStrictEqual(did) expect(metadata.deactivated).toBeFalsy() }) it('migrates light DID with sr25519 auth key', async () => { const didSr25519AuthenticationKeyDetails = await keystore.generateKeypair({ alg: SigningAlgorithms.Sr25519, }) const lightDidDetails = new LightDidDetails({ authenticationKey: { publicKey: didSr25519AuthenticationKeyDetails.publicKey, type: DemoKeystore.getKeypairTypeForAlg( didSr25519AuthenticationKeyDetails.alg ), }, }) const { extrinsic, did } = await DidUtils.upgradeDid( lightDidDetails, paymentAccount.address, keystore ) await expect( BlockchainUtils.signAndSubmitTx(extrinsic, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() await expect( DidChain.queryById(DidUtils.getIdentifierFromKiltDid(did)) ).resolves.not.toBeNull() const { details, metadata } = (await resolveDoc( lightDidDetails.did )) as IDidResolvedDetails expect(details?.did).toStrictEqual(lightDidDetails.did) expect(metadata.canonicalId).toStrictEqual(did) expect(metadata.deactivated).toBeFalsy() }) it('migrates light DID with ed25519 auth key, encryption key, and service endpoints', async () => { const didEd25519AuthenticationKeyDetails = await keystore.generateKeypair({ alg: SigningAlgorithms.Ed25519, }) const didEncryptionKeyDetails = await keystore.generateKeypair({ seed: '0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', alg: EncryptionAlgorithms.NaclBox, }) const serviceEndpoints: IDidServiceEndpoint[] = [ { id: 'id-1', types: ['type-1'], urls: ['url-1'], }, ] const lightDidDetails = new LightDidDetails({ authenticationKey: { publicKey: didEd25519AuthenticationKeyDetails.publicKey, type: DemoKeystore.getKeypairTypeForAlg( didEd25519AuthenticationKeyDetails.alg ), }, encryptionKey: { publicKey: didEncryptionKeyDetails.publicKey, type: DemoKeystore.getKeypairTypeForAlg(didEncryptionKeyDetails.alg), }, serviceEndpoints, }) const { extrinsic, did } = await DidUtils.upgradeDid( lightDidDetails, paymentAccount.address, keystore ) await expect( BlockchainUtils.signAndSubmitTx(extrinsic, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() let chainDetails = await DidChain.queryDidDetails(did) expect(chainDetails).not.toBeNull() expect(chainDetails?.authenticationKey).toBeDefined() expect(chainDetails?.keyAgreementKeys).toHaveLength(1) // The returned service endpoints will have the initial ID, prepended with the full DID identifier. await expect(DidChain.queryServiceEndpoints(did)).resolves.toMatchObject< IDidServiceEndpoint[] >([ { ...serviceEndpoints[0], id: DidUtils.assembleDidFragment(did, serviceEndpoints[0].id), }, ]) const { details, metadata } = (await resolveDoc( lightDidDetails.did )) as IDidResolvedDetails expect(details?.did).toStrictEqual(lightDidDetails.did) // Verify service endpoints for light DID resolution expect(details?.getEndpoints()).toMatchObject( serviceEndpoints.map((service) => { return { ...service, id: `${lightDidDetails.did}#${service.id}` } }) ) expect(metadata.canonicalId).toStrictEqual(did) expect(metadata.deactivated).toBeFalsy() // Remove and claim the deposit back const fullDidIdentifier = DidUtils.getIdentifierFromKiltDid(did) const storedEndpointsCount = await DidChain.queryEndpointsCounts(did) const reclaimDepositTx = await DidChain.getReclaimDepositExtrinsic( fullDidIdentifier, storedEndpointsCount ) await expect( BlockchainUtils.signAndSubmitTx(reclaimDepositTx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() chainDetails = await DidChain.queryDidDetails(did) expect(chainDetails).toBeNull() await expect(DidChain.queryDidDeletionStatus(did)).resolves.toBeTruthy() }, 60_000) }) describe('DID authorization', () => { let didIdentifier: string let key: DidTypes.INewPublicKey let lastTxIndex = new BN(0) beforeAll(async () => { const { publicKey, alg } = await keystore.generateKeypair({ alg: SigningAlgorithms.Ed25519, }) didIdentifier = encodeAddress(publicKey, 38) key = { publicKey, type: alg } const tx = await DidChain.generateCreateTx({ didIdentifier, submitter: paymentAccount.address, keys: { [KeyRelationship.assertionMethod]: key, [KeyRelationship.capabilityDelegation]: key, }, signer: keystore as KeystoreSigner<string>, signingPublicKey: key.publicKey, alg: key.type, }) await expect( BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() await expect(DidChain.queryById(didIdentifier)).resolves.toMatchObject< Partial<DidTypes.IDidChainRecordJSON> >({ did: DidUtils.getKiltDidFromIdentifier(didIdentifier, 'full'), }) }, 60_000) beforeEach(async () => { lastTxIndex = await DidChain.queryLastTxCounter( DidUtils.getKiltDidFromIdentifier(didIdentifier, 'full') ) }) it('authorizes ctype creation with DID signature', async () => { const ctype = CType.fromSchema({ title: UUID.generate(), properties: {}, type: 'object', $schema: 'http://kilt-protocol.org/draft-01/ctype#', }) const call = await ctype.store() const tx = await DidChain.generateDidAuthenticatedTx({ didIdentifier, txCounter: lastTxIndex.addn(1), call, signer: keystore as KeystoreSigner<string>, signingPublicKey: key.publicKey, alg: key.type, submitter: paymentAccount.address, }) await expect( BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() await expect(ctype.verifyStored()).resolves.toEqual(true) }, 60_000) it.skip('authorizes batch with DID signature', async () => { const ctype1 = CType.fromSchema({ title: UUID.generate(), properties: {}, type: 'object', $schema: 'http://kilt-protocol.org/draft-01/ctype#', }) const ctype2 = CType.fromSchema({ title: UUID.generate(), properties: {}, type: 'object', $schema: 'http://kilt-protocol.org/draft-01/ctype#', }) const calls = await Promise.all([ctype1, ctype2].map((c) => c.store())) const batch = await BlockchainApiConnection.getConnectionOrConnect().then( ({ api }) => api.tx.utility.batch(calls) ) const tx = await DidChain.generateDidAuthenticatedTx({ didIdentifier, txCounter: lastTxIndex.addn(1), call: batch, signer: keystore as KeystoreSigner<string>, signingPublicKey: key.publicKey, alg: key.type, submitter: paymentAccount.address, }) await expect( BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() await expect(ctype1.verifyStored()).resolves.toEqual(true) await expect(ctype2.verifyStored()).resolves.toEqual(true) }, 60_000) it('no longer authorizes ctype creation after DID deletion', async () => { const did = DidUtils.getKiltDidFromIdentifier(didIdentifier, 'full') const storedEndpointsCount = await DidChain.queryEndpointsCounts(did) const deleteCall = await DidChain.getDeleteDidExtrinsic( storedEndpointsCount ) const tx = await DidChain.generateDidAuthenticatedTx({ didIdentifier, txCounter: lastTxIndex.addn(1), call: deleteCall, signer: keystore as KeystoreSigner<string>, signingPublicKey: key.publicKey, alg: key.type, submitter: paymentAccount.address, }) await expect( BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).resolves.not.toThrow() const ctype = CType.fromSchema({ title: UUID.generate(), properties: {}, type: 'object', $schema: 'http://kilt-protocol.org/draft-01/ctype#', }) const call = await ctype.store() const tx2 = await DidChain.generateDidAuthenticatedTx({ didIdentifier, txCounter: lastTxIndex.addn(2), call, signer: keystore as KeystoreSigner<string>, signingPublicKey: key.publicKey, alg: key.type, submitter: paymentAccount.address, }) await expect( BlockchainUtils.signAndSubmitTx(tx2, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ).rejects.toThrow() await expect(ctype.verifyStored()).resolves.toEqual(false) }, 60_000) }) afterAll(async () => disconnect())
the_stack
import {fakeAsync, TestBed, tick} from "@angular/core/testing"; import {ViewFileFilterService} from "../../../../services/files/view-file-filter.service"; import {LoggerService} from "../../../../services/utils/logger.service"; import {ViewFileFilterCriteria, ViewFileService} from "../../../../services/files/view-file.service"; import {MockViewFileService} from "../../../mocks/mock-view-file.service"; import {ViewFile} from "../../../../services/files/view-file"; import {ViewFileOptionsService} from "../../../../services/files/view-file-options.service"; import {MockViewFileOptionsService} from "../../../mocks/mock-view-file-options.service"; import {ViewFileOptions} from "../../../../services/files/view-file-options"; describe("Testing view file filter service", () => { let viewFilterService: ViewFileFilterService; let viewFileService: MockViewFileService; let viewFileOptionsService: MockViewFileOptionsService; let filterCriteria: ViewFileFilterCriteria; beforeEach(() => { TestBed.configureTestingModule({ providers: [ ViewFileFilterService, LoggerService, {provide: ViewFileService, useClass: MockViewFileService}, {provide: ViewFileOptionsService, useClass: MockViewFileOptionsService} ] }); viewFileService = TestBed.get(ViewFileService); spyOn(viewFileService, "setFilterCriteria").and.callFake( value => filterCriteria = value ); viewFileOptionsService = TestBed.get(ViewFileOptionsService); viewFilterService = TestBed.get(ViewFileFilterService); }); it("should create an instance", () => { expect(viewFilterService).toBeDefined(); }); it("does not set a filter criteria by default", () => { expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(0); expect(filterCriteria).toBeUndefined(); }); it("calls setFilterCriteria on filter name set", fakeAsync(() => { expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(0); viewFileOptionsService._options.next(new ViewFileOptions({ nameFilter: "something", })); tick(); expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(1); })); it("does not call setFilterCriteria on duplicate filter names", fakeAsync(() => { expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(0); viewFileOptionsService._options.next(new ViewFileOptions({ nameFilter: "something", })); tick(); expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(1); viewFileOptionsService._options.next(new ViewFileOptions({ nameFilter: "something", })); tick(); expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(1); })); it("does not call setFilterCriteria for filter name " + "when a different option is changed", fakeAsync(() => { expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(0); viewFileOptionsService._options.next(new ViewFileOptions({ nameFilter: "something", showDetails: true, })); tick(); expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(1); viewFileOptionsService._options.next(new ViewFileOptions({ nameFilter: "something", showDetails: false, })); tick(); expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(1); })); it("correctly filters by name", fakeAsync(() => { viewFileOptionsService._options.next(new ViewFileOptions({ nameFilter: "tofu", })); tick(); // exact match expect(filterCriteria.meetsCriteria(new ViewFile({name: "tofu"}))).toBe(true); // no match expect(filterCriteria.meetsCriteria(new ViewFile({name: "flower"}))).toBe(false); // partial matches expect(filterCriteria.meetsCriteria(new ViewFile({name: "tofuflower"}))).toBe(true); expect(filterCriteria.meetsCriteria(new ViewFile({name: "flowertofu"}))).toBe(true); expect(filterCriteria.meetsCriteria(new ViewFile({name: "aaatofubbb"}))).toBe(true); // Another filter viewFileOptionsService._options.next(new ViewFileOptions({ nameFilter: "flower", })); tick(); // exact match expect(filterCriteria.meetsCriteria(new ViewFile({name: "flower"}))).toBe(true); // no match expect(filterCriteria.meetsCriteria(new ViewFile({name: "tofu"}))).toBe(false); // partial matches expect(filterCriteria.meetsCriteria(new ViewFile({name: "flowertofu"}))).toBe(true); expect(filterCriteria.meetsCriteria(new ViewFile({name: "tofuflower"}))).toBe(true); expect(filterCriteria.meetsCriteria(new ViewFile({name: "aaaflowerbbb"}))).toBe(true); })); it("ignores cases when filtering by name", fakeAsync(() => { viewFileOptionsService._options.next(new ViewFileOptions({ nameFilter: "tofu", })); tick(); expect(filterCriteria.meetsCriteria(new ViewFile({name: "TOFU"}))).toBe(true); expect(filterCriteria.meetsCriteria(new ViewFile({name: "TofU"}))).toBe(true); expect(filterCriteria.meetsCriteria(new ViewFile({name: "aaaToFubbb"}))).toBe(true); // Another filter viewFileOptionsService._options.next(new ViewFileOptions({ nameFilter: "flOweR", })); tick(); expect(filterCriteria.meetsCriteria(new ViewFile({name: "FLowEr"}))).toBe(true); expect(filterCriteria.meetsCriteria(new ViewFile({name: "tofuflowertofu"}))).toBe(true); expect(filterCriteria.meetsCriteria(new ViewFile({name: "floWer"}))).toBe(true); })); it("treats dots as spaces when filtering by name", fakeAsync(() => { viewFileOptionsService._options.next(new ViewFileOptions({ nameFilter: "to.fu", })); tick(); expect(filterCriteria.meetsCriteria(new ViewFile({name: "to.fu"}))).toBe(true); expect(filterCriteria.meetsCriteria(new ViewFile({name: "to fu"}))).toBe(true); // Another filter viewFileOptionsService._options.next(new ViewFileOptions({ nameFilter: "flo wer", })); tick(); expect(filterCriteria.meetsCriteria(new ViewFile({name: "flo wer"}))).toBe(true); expect(filterCriteria.meetsCriteria(new ViewFile({name: "flo.wer"}))).toBe(true); })); it("calls setFilterCriteria on filter status set", fakeAsync(() => { expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(0); viewFileOptionsService._options.next(new ViewFileOptions({ selectedStatusFilter: ViewFile.Status.QUEUED })); tick(); expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(1); })); it("does not call setFilterCriteria on duplicate filter status", fakeAsync(() => { expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(0); viewFileOptionsService._options.next(new ViewFileOptions({ selectedStatusFilter: ViewFile.Status.QUEUED })); tick(); expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(1); viewFileOptionsService._options.next(new ViewFileOptions({ selectedStatusFilter: ViewFile.Status.QUEUED })); tick(); expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(1); })); it("does not call setFilterCriteria for filter status " + "when a different option is changed", fakeAsync(() => { expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(0); viewFileOptionsService._options.next(new ViewFileOptions({ selectedStatusFilter: ViewFile.Status.QUEUED, showDetails: true, })); tick(); expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(1); viewFileOptionsService._options.next(new ViewFileOptions({ selectedStatusFilter: ViewFile.Status.QUEUED, showDetails: false, })); tick(); expect(viewFileService.setFilterCriteria).toHaveBeenCalledTimes(1); })); it("correctly filters by status", fakeAsync(() => { viewFileOptionsService._options.next(new ViewFileOptions({ selectedStatusFilter: ViewFile.Status.DEFAULT, })); tick(); // exact match expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.DEFAULT}))).toBe(true); // no match expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.QUEUED}))).toBe(false); expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.DOWNLOADING}))).toBe(false); expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.DELETED}))).toBe(false); // Another filter viewFileOptionsService._options.next(new ViewFileOptions({ selectedStatusFilter: ViewFile.Status.EXTRACTING, })); tick(); // exact match expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.EXTRACTING}))).toBe(true); // no match expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.QUEUED}))).toBe(false); expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.DOWNLOADING}))).toBe(false); expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.DELETED}))).toBe(false); // Disable status filter viewFileOptionsService._options.next(new ViewFileOptions({ selectedStatusFilter: null, })); tick(); // all matches expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.DEFAULT}))).toBe(true); expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.QUEUED}))).toBe(true); expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.DOWNLOADING}))).toBe(true); expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.DOWNLOADED}))).toBe(true); expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.STOPPED}))).toBe(true); expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.DELETED}))).toBe(true); expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.EXTRACTING}))).toBe(true); expect(filterCriteria.meetsCriteria( new ViewFile({status: ViewFile.Status.EXTRACTED}))).toBe(true); })); it("correctly filters by name AND status", fakeAsync(() => { viewFileOptionsService._options.next(new ViewFileOptions({ selectedStatusFilter: ViewFile.Status.DEFAULT, nameFilter: "tofu", })); tick(); // both match expect(filterCriteria.meetsCriteria(new ViewFile({ name: "tofu", status: ViewFile.Status.DEFAULT }))).toBe(true); // only one matches expect(filterCriteria.meetsCriteria(new ViewFile({ name: "flower", status: ViewFile.Status.DEFAULT }))).toBe(false); expect(filterCriteria.meetsCriteria(new ViewFile({ name: "tofu", status: ViewFile.Status.QUEUED }))).toBe(false); // neither matches expect(filterCriteria.meetsCriteria(new ViewFile({ name: "flower", status: ViewFile.Status.QUEUED }))).toBe(false); })); });
the_stack
import { assert, expect } from 'chai'; import 'mocha'; import * as dataForge from '../index'; import { DataFrame, Series, ISeries, Index } from '../index'; describe('DataFrame window', () => { it('can compute window - creates an empty series from an empty data set', () => { var df = new DataFrame(); var windowed = df.window(2) .select(window => { throw new Error("This should never be executed."); }); expect(windowed.count()).to.eql(0); }); it('can compute window - with even window size and even number of rows', () => { var df = new DataFrame({ index: [10, 20, 30, 40], values: [1, 2, 3, 4] }); var windowed = df .window(2) .select(window => [window.getIndex().last(), window.toArray()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); expect(windowed.toPairs()).to.eql([ [20, [1, 2]], [40, [3, 4]], ]); }); it('can compute window - with even window size and odd number of rows', () => { var df = new DataFrame({ index: [10, 20, 30, 40, 50], values: [1, 2, 3, 4, 5] }); var windowed = df .window(2) .select(window => [window.getIndex().first(), window.toArray()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); expect(windowed.toPairs()).to.eql([ [10, [1, 2]], [30, [3, 4]], [50, [5]], ]); }); it('can compute window - with odd window size and odd number of rows', () => { var df = new DataFrame({ values: [1, 2, 3, 4, 5, 6] }); var windowed = df .window(3) .select((window, windowIndex) => [windowIndex, window.toArray()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); expect(windowed.toPairs()).to.eql([ [0, [1, 2, 3]], [1, [4, 5, 6]], ]); }); it('can compute window - with odd window size and even number of rows', () => { var df = new DataFrame({ values: [1, 2, 3, 4, 5] }); var windowed = df .window(3) .select((window, windowIndex) => [windowIndex, window.toArray()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); expect(windowed.toPairs()).to.eql([ [0, [1, 2, 3]], [1, [4, 5]], ]); }); it('can compute rolling window - from empty data set', () => { var df = new DataFrame(); var windowed = df .rollingWindow(2) .select((window, windowIndex) => [windowIndex, window.toArray()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); expect(windowed.toArray().length).to.eql(0); }); it('rolling window returns 0 values when there are not enough values in the data set', () => { var df = new DataFrame({ index: [0, 1], values: [1, 2] }); var windowed = df .rollingWindow(3) .select((window, windowIndex) => [windowIndex, window.toArray()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); expect(windowed.toArray().length).to.eql(0); }); it('can compute rolling window - odd data set with even period', () => { var df = new DataFrame({ index: [10, 20, 30, 40, 50], values: [0, 1, 2, 3, 4] }); var windowed = df .rollingWindow(2) .select(window => [window.getIndex().last(), window.toArray()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); expect(windowed.toPairs()).to.eql([ [20, [0, 1]], [30, [1, 2]], [40, [2, 3]], [50, [3, 4]], ]); }); it('can compute rolling window - odd data set with odd period', () => { var df = new DataFrame({ index: [0, 1, 2, 3, 4], values: [0, 1, 2, 3, 4] }); var windowed = df .rollingWindow(3) .select((window, windowIndex) => [windowIndex, window.toArray()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); var index = windowed.getIndex().toArray(); expect(index).to.eql([0, 1, 2]); var values = windowed.toArray(); expect(values.length).to.eql(3); expect(values[0]).to.eql([0, 1, 2]); expect(values[1]).to.eql([1, 2, 3]); expect(values[2]).to.eql([2, 3, 4]); }); it('can compute rolling window - even data set with even period', () => { var df = new DataFrame({ index: [0, 1, 2, 3, 4, 5], values: [0, 1, 2, 3, 4, 5] }); var windowed = df .rollingWindow(2) .select((window, windowIndex) => [windowIndex+10, window.toArray()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); var index = windowed.getIndex().toArray(); expect(index).to.eql([10, 11, 12, 13, 14]); var values = windowed.toArray(); expect(values.length).to.eql(5); expect(values[0]).to.eql([0, 1]); expect(values[1]).to.eql([1, 2]); expect(values[2]).to.eql([2, 3]); expect(values[3]).to.eql([3, 4]); expect(values[4]).to.eql([4, 5]); }); it('can compute rolling window - even data set with odd period', () => { var df = new DataFrame({ index: [0, 1, 2, 3, 4, 5], values: [0, 1, 2, 3, 4, 5] }); var windowed = df .rollingWindow(3) .select((window, windowIndex) => [windowIndex, window.toArray()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); var index = windowed.getIndex().toArray(); expect(index).to.eql([0, 1, 2, 3]); var values = windowed.toArray(); expect(values.length).to.eql(4); expect(values[0]).to.eql([0, 1, 2]); expect(values[1]).to.eql([1, 2, 3]); expect(values[2]).to.eql([2, 3, 4]); expect(values[3]).to.eql([3, 4, 5]); }); it('can compute rolling window - can take last index and value from each window', () => { var df = new DataFrame({ index: [0, 1, 2, 3, 4, 5], values: [0, 1, 2, 3, 4, 5] }); var windowed = df .rollingWindow(3) .select(window => [window.getIndex().last(), window.last()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); var index = windowed.getIndex().toArray(); expect(index).to.eql([2, 3, 4, 5]); var values = windowed.toArray(); expect(values).to.eql([2, 3, 4, 5]); }); it('variable window', () => { var df = new DataFrame({ index: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], values: [1, 1, 2, 1, 1, 2, 3, 4, 3, 3], }); var windowed = df .variableWindow((a, b) => a === b) .select(window => [window.getIndex().first(), window.count()]) .withIndex(pair => pair[0]) .inflate(pair => pair[1]); expect(windowed.toPairs()).to.eql([ [0, 2], [2, 1], [3, 2], [5, 1], [6, 1], [7, 1], [8, 2] ]); }); it('variable window compares each adjacent pair', () => { var df = new DataFrame({ index: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], values: [1, 2, 3, 4, 3, 3, 3, 4, 5, 8, 9], }); var windowed = df .variableWindow((a, b) => a === b-1) .select(window => window.toArray()); expect(windowed.toArray()).to.eql([ [1, 2, 3, 4], [3], [3], [3, 4, 5], [8, 9], ]); }); it('can collapse sequential duplicates and take first index', () => { var df = new DataFrame({ index: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], values: [1, 1, 2, 3, 3, 3, 5, 6, 6, 7], }); var collapsed = df.sequentialDistinct(); expect(collapsed.toPairs()).to.eql([ [0, 1], [2, 2], [3, 3], [6, 5], [7, 6], [9, 7], ]); }); it('can collapse sequential duplicates with custom selector', () => { var df = new DataFrame({ index: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], values: [{ A: 1 }, { A: 1 }, { A: 2 }, { A: 3 }, { A: 3 }, { A: 3 }, { A: 5 }, { A: 6 }, { A: 6 }, { A: 7 }], }); var collapsed = df .sequentialDistinct(value => value.A) .select(value => value.A) ; expect(collapsed.toPairs()).to.eql([ [0, 1], [2, 2], [3, 3], [6, 5], [7, 6], [9, 7], ]); }); it('rolling window', () => { var df = new DataFrame({ columns: { Value: dataForge.range(1, 12) }, index: dataForge.range(10, 12), }); var newSeries = df.getSeries<number>('Value') .rollingWindow(5) .select(window => [window.getIndex().last(), window.last()]) .withIndex(pair => pair[0]) .select(pair => pair[1]); expect(newSeries.getIndex().toArray()).to.eql([14, 15, 16, 17, 18, 19, 20, 21]); expect(newSeries.toArray()).to.eql([5, 6, 7, 8, 9, 10, 11, 12]); var newDataFrame = df.withSeries('Value2', newSeries); expect(newDataFrame.getIndex().toArray()).to.eql([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]); expect(newDataFrame.toRows()).to.eql([ [1, undefined], [2, undefined], [3, undefined], [4, undefined], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9], [10, 10], [11, 11], [12, 12], ]); }); function initDataFrame (columns: any[], rows: any[], index?: any[]) { assert.isArray(columns); assert.isArray(rows); var config: any = { columnNames: columns, rows: rows, }; if (index) { config.index = index; } return new DataFrame(config); } // // Generate a data frame for testing. // function genDataFrame (numColumns: number, numRows: number) { const columnNames: string[] = []; for (let i = 0; i < numColumns; ++i) { columnNames.push((i+1).toString()); } const rows: any[] = []; for (let i = 0; i < numRows; ++i) { const row: any[] = []; for (let j = 0; j < numColumns; ++j) { row.push((i+1) * (j+1)); } rows.push(row); } return initDataFrame(columnNames, rows); } it('can use window and selectMany to generate multiple elements', () => { var dataFrame = genDataFrame(2, 4); var series = dataFrame .window(2) .select((window, windowIndex): [number, number[]] => [windowIndex, [window.getSeries("1").sum(), window.getSeries("2").sum()]]) .withIndex(pair => pair[0]) .selectMany(pair => { assert.isArray(pair[1]); return pair[1]; // The value is already a list. }); expect(series.toPairs()).to.eql([ [0, 3], [0, 6], [1, 7], [1, 14], ]); }); it('can use rollingWindow and selectMany to generate multiple elements', () => { var dataFrame = genDataFrame(2, 4); var series = dataFrame .rollingWindow(2) .select((window, windowIndex): [number, number[]] => { return [ windowIndex, [ window.getSeries("1").sum(), window.getSeries("2").sum() ] ]; }) .withIndex(pair => pair[0]) .selectMany(pair => { assert.isArray(pair[1]); return pair[1]; // The value is already a list. }); expect(series.toPairs()).to.eql([ [0, 3], [0, 6], [1, 5], [1, 10], [2, 7], [2, 14], ]); }); });
the_stack
import { ChangeHighlights } from "../../../ComplexProperties/ChangeHighlights"; import { ComplexPropertyDefinition } from "../../../PropertyDefinitions/ComplexPropertyDefinition"; import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion"; import { GenericPropertyDefinition, GenericEnumType } from "../../../PropertyDefinitions/GenericPropertyDefinition"; import { LegacyFreeBusyStatus } from "../../../Enumerations/LegacyFreeBusyStatus"; import { MeetingRequestType } from "../../../Enumerations/MeetingRequestType"; import { PropertyDefinition } from "../../../PropertyDefinitions/PropertyDefinition"; import { PropertyDefinitionFlags } from "../../../Enumerations/PropertyDefinitionFlags"; import { Schemas } from "./Schemas"; import { XmlElementNames } from "../../XmlElementNames"; import { MeetingMessageSchema } from "./MeetingMessageSchema"; /** * Field URIs for meeting request. */ module FieldUris { export var MeetingRequestType: string = "meetingRequest:MeetingRequestType"; export var IntendedFreeBusyStatus: string = "meetingRequest:IntendedFreeBusyStatus"; export var ChangeHighlights: string = "meetingRequest:ChangeHighlights"; } /** * Represents the schema for meeting requests. */ export class MeetingRequestSchema extends MeetingMessageSchema { /** * Defines the **MeetingRequestType** property. */ public static MeetingRequestType: PropertyDefinition = new GenericPropertyDefinition<MeetingRequestType>( "MeetingRequestType", XmlElementNames.MeetingRequestType, FieldUris.MeetingRequestType, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1, MeetingRequestType ); /** * Defines the **IntendedFreeBusyStatus** property. */ public static IntendedFreeBusyStatus: PropertyDefinition = new GenericPropertyDefinition<LegacyFreeBusyStatus>( "IntendedFreeBusyStatus", XmlElementNames.IntendedFreeBusyStatus, FieldUris.IntendedFreeBusyStatus, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, LegacyFreeBusyStatus ); /** * Defines the **ChangeHighlights** property. */ public static ChangeHighlights: PropertyDefinition = new ComplexPropertyDefinition<ChangeHighlights>( "ChangeHighlights", XmlElementNames.ChangeHighlights, FieldUris.ChangeHighlights, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2013, () => { return new ChangeHighlights(); } ); /** * Defines the **EnhancedLocation** property. */ public static EnhancedLocation: PropertyDefinition = Schemas.AppointmentSchema.EnhancedLocation; /** * Defines the **Start** property. */ public static Start: PropertyDefinition = Schemas.AppointmentSchema.Start; /** * Defines the **End** property. */ public static End: PropertyDefinition = Schemas.AppointmentSchema.End; /** * Defines the **OriginalStart** property. */ public static OriginalStart: PropertyDefinition = Schemas.AppointmentSchema.OriginalStart; /** * Defines the **IsAllDayEvent** property. */ public static IsAllDayEvent: PropertyDefinition = Schemas.AppointmentSchema.IsAllDayEvent; /** * Defines the **LegacyFreeBusyStatus** property. */ public static LegacyFreeBusyStatus: PropertyDefinition = Schemas.AppointmentSchema.LegacyFreeBusyStatus; /** * Defines the **Location** property. */ public static Location: PropertyDefinition = Schemas.AppointmentSchema.Location; /** * Defines the **When** property. */ public static When: PropertyDefinition = Schemas.AppointmentSchema.When; /** * Defines the **IsMeeting** property. */ public static IsMeeting: PropertyDefinition = Schemas.AppointmentSchema.IsMeeting; /** * Defines the **IsCancelled** property. */ public static IsCancelled: PropertyDefinition = Schemas.AppointmentSchema.IsCancelled; /** * Defines the **IsRecurring** property. */ public static IsRecurring: PropertyDefinition = Schemas.AppointmentSchema.IsRecurring; /** * Defines the **MeetingRequestWasSent** property. */ public static MeetingRequestWasSent: PropertyDefinition = Schemas.AppointmentSchema.MeetingRequestWasSent; /** * Defines the **AppointmentType** property. */ public static AppointmentType: PropertyDefinition = Schemas.AppointmentSchema.AppointmentType; /** * Defines the **MyResponseType** property. */ public static MyResponseType: PropertyDefinition = Schemas.AppointmentSchema.MyResponseType; /** * Defines the **Organizer** property. */ public static Organizer: PropertyDefinition = Schemas.AppointmentSchema.Organizer; /** * Defines the **RequiredAttendees** property. */ public static RequiredAttendees: PropertyDefinition = Schemas.AppointmentSchema.RequiredAttendees; /** * Defines the **OptionalAttendees** property. */ public static OptionalAttendees: PropertyDefinition = Schemas.AppointmentSchema.OptionalAttendees; /** * Defines the **Resources** property. */ public static Resources: PropertyDefinition = Schemas.AppointmentSchema.Resources; /** * Defines the **ConflictingMeetingCount** property. */ public static ConflictingMeetingCount: PropertyDefinition = Schemas.AppointmentSchema.ConflictingMeetingCount; /** * Defines the **AdjacentMeetingCount** property. */ public static AdjacentMeetingCount: PropertyDefinition = Schemas.AppointmentSchema.AdjacentMeetingCount; /** * Defines the **ConflictingMeetings** property. */ public static ConflictingMeetings: PropertyDefinition = Schemas.AppointmentSchema.ConflictingMeetings; /** * Defines the **AdjacentMeetings** property. */ public static AdjacentMeetings: PropertyDefinition = Schemas.AppointmentSchema.AdjacentMeetings; /** * Defines the **Duration** property. */ public static Duration: PropertyDefinition = Schemas.AppointmentSchema.Duration; /** * Defines the **TimeZone** property. */ public static TimeZone: PropertyDefinition = Schemas.AppointmentSchema.TimeZone; /** * Defines the **AppointmentReplyTime** property. */ public static AppointmentReplyTime: PropertyDefinition = Schemas.AppointmentSchema.AppointmentReplyTime; /** * Defines the **AppointmentSequenceNumber** property. */ public static AppointmentSequenceNumber: PropertyDefinition = Schemas.AppointmentSchema.AppointmentSequenceNumber; /** * Defines the **AppointmentState** property. */ public static AppointmentState: PropertyDefinition = Schemas.AppointmentSchema.AppointmentState; /** * Defines the **Recurrence** property. */ public static Recurrence: PropertyDefinition = Schemas.AppointmentSchema.Recurrence; /** * Defines the **FirstOccurrence** property. */ public static FirstOccurrence: PropertyDefinition = Schemas.AppointmentSchema.FirstOccurrence; /** * Defines the **LastOccurrence** property. */ public static LastOccurrence: PropertyDefinition = Schemas.AppointmentSchema.LastOccurrence; /** * Defines the **ModifiedOccurrences** property. */ public static ModifiedOccurrences: PropertyDefinition = Schemas.AppointmentSchema.ModifiedOccurrences; /** * Defines the **DeletedOccurrences** property. */ public static DeletedOccurrences: PropertyDefinition = Schemas.AppointmentSchema.DeletedOccurrences; /** * Defines the **MeetingTimeZone** property. */ public static MeetingTimeZone: PropertyDefinition = Schemas.AppointmentSchema.MeetingTimeZone; /** * Defines the **StartTimeZone** property. */ public static StartTimeZone: PropertyDefinition = Schemas.AppointmentSchema.StartTimeZone; /** * Defines the **EndTimeZone** property. */ public static EndTimeZone: PropertyDefinition = Schemas.AppointmentSchema.EndTimeZone; /** * Defines the **ConferenceType** property. */ public static ConferenceType: PropertyDefinition = Schemas.AppointmentSchema.ConferenceType; /** * Defines the **AllowNewTimeProposal** property. */ public static AllowNewTimeProposal: PropertyDefinition = Schemas.AppointmentSchema.AllowNewTimeProposal; /** * Defines the **IsOnlineMeeting** property. */ public static IsOnlineMeeting: PropertyDefinition = Schemas.AppointmentSchema.IsOnlineMeeting; /** * Defines the **MeetingWorkspaceUrl** property. */ public static MeetingWorkspaceUrl: PropertyDefinition = Schemas.AppointmentSchema.MeetingWorkspaceUrl; /** * Defines the **NetShowUrl** property. */ public static NetShowUrl: PropertyDefinition = Schemas.AppointmentSchema.NetShowUrl; /** * @internal Instance of **MeetingRequestSchema** */ static Instance: MeetingRequestSchema = new MeetingRequestSchema(); /** * Registers properties. * * /remarks/ IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd) */ RegisterProperties(): void { super.RegisterProperties(); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.MeetingRequestType); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.IntendedFreeBusyStatus); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.ChangeHighlights); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.Start); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.End); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.OriginalStart); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.IsAllDayEvent); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.LegacyFreeBusyStatus); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.Location); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.When); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.IsMeeting); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.IsCancelled); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.IsRecurring); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.MeetingRequestWasSent); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.AppointmentType); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.MyResponseType); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.Organizer); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.RequiredAttendees); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.OptionalAttendees); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.Resources); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.ConflictingMeetingCount); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.AdjacentMeetingCount); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.ConflictingMeetings); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.AdjacentMeetings); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.Duration); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.TimeZone); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.AppointmentReplyTime); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.AppointmentSequenceNumber); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.AppointmentState); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.Recurrence); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.FirstOccurrence); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.LastOccurrence); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.ModifiedOccurrences); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.DeletedOccurrences); this.RegisterInternalProperty(MeetingRequestSchema, MeetingRequestSchema.MeetingTimeZone); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.StartTimeZone); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.EndTimeZone); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.ConferenceType); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.AllowNewTimeProposal); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.IsOnlineMeeting); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.MeetingWorkspaceUrl); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.NetShowUrl); this.RegisterProperty(MeetingRequestSchema, MeetingRequestSchema.EnhancedLocation); } } /** * Represents the schema for meeting requests. */ export interface MeetingRequestSchema { /** * Defines the **MeetingRequestType** property. */ MeetingRequestType: PropertyDefinition; /** * Defines the **IntendedFreeBusyStatus** property. */ IntendedFreeBusyStatus: PropertyDefinition; /** * Defines the **ChangeHighlights** property. */ ChangeHighlights: PropertyDefinition; /** * Defines the **EnhancedLocation** property. */ EnhancedLocation: PropertyDefinition; /** * Defines the **Start** property. */ Start: PropertyDefinition; /** * Defines the **End** property. */ End: PropertyDefinition; /** * Defines the **OriginalStart** property. */ OriginalStart: PropertyDefinition; /** * Defines the **IsAllDayEvent** property. */ IsAllDayEvent: PropertyDefinition; /** * Defines the **LegacyFreeBusyStatus** property. */ LegacyFreeBusyStatus: PropertyDefinition; /** * Defines the **Location** property. */ Location: PropertyDefinition; /** * Defines the **When** property. */ When: PropertyDefinition; /** * Defines the **IsMeeting** property. */ IsMeeting: PropertyDefinition; /** * Defines the **IsCancelled** property. */ IsCancelled: PropertyDefinition; /** * Defines the **IsRecurring** property. */ IsRecurring: PropertyDefinition; /** * Defines the **MeetingRequestWasSent** property. */ MeetingRequestWasSent: PropertyDefinition; /** * Defines the **AppointmentType** property. */ AppointmentType: PropertyDefinition; /** * Defines the **MyResponseType** property. */ MyResponseType: PropertyDefinition; /** * Defines the **Organizer** property. */ Organizer: PropertyDefinition; /** * Defines the **RequiredAttendees** property. */ RequiredAttendees: PropertyDefinition; /** * Defines the **OptionalAttendees** property. */ OptionalAttendees: PropertyDefinition; /** * Defines the **Resources** property. */ Resources: PropertyDefinition; /** * Defines the **ConflictingMeetingCount** property. */ ConflictingMeetingCount: PropertyDefinition; /** * Defines the **AdjacentMeetingCount** property. */ AdjacentMeetingCount: PropertyDefinition; /** * Defines the **ConflictingMeetings** property. */ ConflictingMeetings: PropertyDefinition; /** * Defines the **AdjacentMeetings** property. */ AdjacentMeetings: PropertyDefinition; /** * Defines the **Duration** property. */ Duration: PropertyDefinition; /** * Defines the **TimeZone** property. */ TimeZone: PropertyDefinition; /** * Defines the **AppointmentReplyTime** property. */ AppointmentReplyTime: PropertyDefinition; /** * Defines the **AppointmentSequenceNumber** property. */ AppointmentSequenceNumber: PropertyDefinition; /** * Defines the **AppointmentState** property. */ AppointmentState: PropertyDefinition; /** * Defines the **Recurrence** property. */ Recurrence: PropertyDefinition; /** * Defines the **FirstOccurrence** property. */ FirstOccurrence: PropertyDefinition; /** * Defines the **LastOccurrence** property. */ LastOccurrence: PropertyDefinition; /** * Defines the **ModifiedOccurrences** property. */ ModifiedOccurrences: PropertyDefinition; /** * Defines the **DeletedOccurrences** property. */ DeletedOccurrences: PropertyDefinition; /** * Defines the **MeetingTimeZone** property. */ MeetingTimeZone: PropertyDefinition; /** * Defines the **StartTimeZone** property. */ StartTimeZone: PropertyDefinition; /** * Defines the **EndTimeZone** property. */ EndTimeZone: PropertyDefinition; /** * Defines the **ConferenceType** property. */ ConferenceType: PropertyDefinition; /** * Defines the **AllowNewTimeProposal** property. */ AllowNewTimeProposal: PropertyDefinition; /** * Defines the **IsOnlineMeeting** property. */ IsOnlineMeeting: PropertyDefinition; /** * Defines the **MeetingWorkspaceUrl** property. */ MeetingWorkspaceUrl: PropertyDefinition; /** * Defines the **NetShowUrl** property. */ NetShowUrl: PropertyDefinition; /** * @internal Instance of **MeetingRequestSchema** */ Instance: MeetingRequestSchema; } /** * Represents the schema for meeting requests. */ export interface MeetingRequestSchemaStatic extends MeetingRequestSchema { }
the_stack
import {observable} from "mobx"; import {provideInstance} from "../../common/utils/IOC"; import {asyncAction} from "mobx-utils"; import { getConnectionCollectTime, getInstanceConfig, getInstanceConnections, getInstanceDetailInfo, getMachineStateInitTrend, queryAvgLoad, queryByClusterId, queryByInstanceStatus, queryCpu, queryCpuSingle, queryDisk, queryMemory, queryNetTraffic, queryNetTrafficDetail, searchConnectionHistory, updateInstanceConnCollectMonitor } from "../service/instance"; // 实例基本信息 export class InstanceInfoVo { id: number; clusterId: number; clusterName: string; machineId: number; host: string; port: number; connectionMonitor: boolean; deployType: number; serverStateLag: number; status: number; param1: string; createTime: Date; createTimeStr: string; modifyTime: Date; modifyTimestr: string; } // 实例状态信息 export class InstanceStateVo { id: number; instanceId: number; clusterId: number; version: string; leaderId: number; avgLatency: number; maxLatency: number; minLatency: number; received: number; sent: number; currConnections: number; currOutstandings: number; serverStateLag: number; currZnodeCount: number; currWatchCount: number; currEphemeralsCount: number; approximateDataSize: number; openFileDescriptorCount: number; maxFileDescriptorCount: number; followers: number; syncedFollowers: number; pendingSyncs: number; zxid: number; runOk: boolean; param1: string; createTime: Date; createTimeStr: string; modifyTime: Date; modifyTimeStr: string; } // 实例详细信息,包含基本信息以及状态信息 export class InstanceVo { instanceInfo: InstanceInfoVo; instanceState: InstanceStateVo; } // 实例列表展示信息 export class InstanceListVo { instanceId: number; host: string; port: number; clusterName: string; currConnections: number; received: number; serverStateLag: number; status: number; clusterId:number; } // 实例配置信息 export class InstanceConfigVo { clusterId: number; instanceId: number; clientPort: number; dataDir: string; dataLogDir: string; tickTime: number; maxClientCnxns: number; minSessionTimeout: number; maxSessionTimeout: number; serverId: number; initLimit: number; syncLimit: number; electionAlg: number; electionPort: number; quorumPort: number; peerType: number; } // 实例连接信息 export class InstanceConnectionVo { ip: string; port: number; hostInfo: string; recved: number; sent: number; queued: number; lop: string; maxlat: number; avglat: number; lzxid: string; to: number; infoLine: string; } // 机器历史状态搜索条件,包含实例id,起始时间、结束时间 export class MachineStatSearchVo { id: number; start: string; end: string; } // 实例连接历史情况信息 export class InstanceConnectionHistoryVo { key: string; id: number; instanceId: number; clusterId: number; clientIp: string; clientPort: number; sid: string; queued: number; recved: number; sent: number; est: number; estDate: string; toTime: number; lcxid: string; lzxid: string; lresp: number; lrespStr: string; llat: number; minlat: number; avglat: number; maxlat: number; createTimeStr: string; info: string; clientInfoList: Array<InstanceConnectionHistoryVo>; } // 实例连接信息搜索条件 export class ClientConnectionSearchVo { clusterId: number; instanceId: number; startDate: string; endDate: string; orderBy: string; } // 实例配置运维操作VO,更新实例配置使用 export class InstanceConfigOpsVo { instanceId: number; confDir: string; zooConfFileContent: string; } // 实例配置文件信息VO,用于新增myid配置使用 export class ConfigFileVo { host: string; confDir: string; confFileName: string; confFileContent: string; } @provideInstance(InstanceModel) export class InstanceModel { /** * 数据加载标志 * @type {boolean} */ @observable loading: boolean = false; /** * 实例列表 * @type {Array} */ @observable instances: Array<InstanceVo> = []; /** * 实例详情信息,包含实例基本信息以及实例状态信息 * @type {any} */ @observable instance: InstanceVo = null; /** * 实例配置信息 * @type {any} */ @observable instanceConfigVo: InstanceConfigVo = null; /** * 实例连接信息 * @type {Array} */ @observable instanceConnections: Array<InstanceConnectionVo> = []; /** * 最近一次实例连接信息收集时间点 * @type {any} */ @observable connectionCollectTime = null; /** * 实例历史连接信息情况 * @type {Array} */ @observable connectionsHistory: Array<InstanceConnectionHistoryVo> = []; /** * 实例基本信息 * @type {any} */ @observable instanceInfo: InstanceInfoVo = null; /** * 实例状态信息 * @type {any} */ @observable instanceState: InstanceStateVo = null; /** * 机器维度监控数据 * @type {{}} */ @observable netTrafficTrendData: any = {}; @observable avgLoadTrendData: any = {}; @observable cpuTrendData: any = {}; @observable cpuSingleTrendData: any = {}; @observable memoryTrendData: any = {}; @observable diskTrendData: any = {}; /** * 查询所有实例详情信息 * @param clusterId 集群id */ @asyncAction * queryAllData(clusterId: number) { this.loading = true; const result = yield queryByClusterId(clusterId); if (result.success) { this.instances = result.data; } this.loading = false; } /** * 查询实例的所有异常信息 * @param status 实例status */ @asyncAction * queryAllExceptionData(status: number) { this.loading = true; const result = yield queryByInstanceStatus(status); if (result.success) { this.instances = result.data; } this.loading = false; } /** * 获取某个实例详情信息 * @param instanceId 实例id */ @asyncAction * getInstanceDetailInfo(instanceId: number) { const result = yield getInstanceDetailInfo(instanceId); if (result.success) { this.instance = result.data; } } /** * 获取实例配置信息 * @param instanceId 实例id */ @asyncAction * getInstanceConfig(instanceId: number) { const result = yield getInstanceConfig(instanceId); if (result.success) { this.instanceConfigVo = result.data; } } /** * 获取实例连接信息,同时获取最后一次该实例信息重置时间点 * @param instanceId 实例id */ @asyncAction * getInstanceConnections(instanceId: number) { this.loading = true; const result = yield getInstanceConnections(instanceId); if (result.success) { this.instanceConnections = result.data; const timeResult = yield getConnectionCollectTime(instanceId); if (timeResult.success) { this.connectionCollectTime = timeResult.data; } } this.loading = false; } /** * 初始加载机器状态历史信息 * @param searchVo 搜索条件 */ @asyncAction * initMachineStateData(searchVo: MachineStatSearchVo) { this.loading = true; const result = yield getMachineStateInitTrend(searchVo); if (result.success) { this.netTrafficTrendData = result.data.netTraffic; this.avgLoadTrendData = result.data.avgLoad; this.cpuTrendData = result.data.cpu; this.cpuSingleTrendData = result.data.cpuSingle; this.memoryTrendData = result.data.memory; this.diskTrendData = result.data.disk; } this.loading = false; } /** * 查询机器网络历史信息 * @param searchVo 查询条件 */ @asyncAction * queryNetTraffic(searchVo: MachineStatSearchVo) { this.loading = true; const result = yield queryNetTraffic(searchVo); if (result.success) { this.netTrafficTrendData = result.data; } this.loading = false; } /** * 查询机器平均负载历史信息 * @param searchVo 查询条件 */ @asyncAction * queryAvgLoad(searchVo: MachineStatSearchVo) { this.loading = true; const result = yield queryAvgLoad(searchVo); if (result.success) { this.avgLoadTrendData = result.data; } this.loading = false; } /** * 查询机器CPU历史信息 * @param searchVo 查询条件 */ @asyncAction * queryCpu(searchVo: MachineStatSearchVo) { this.loading = true; const result = yield queryCpu(searchVo); if (result.success) { this.cpuTrendData = result.data; } this.loading = false; } /** * 查询机器单CPU历史信息 * @param searchVo 查询条件 */ @asyncAction * queryCpuSingle(searchVo: MachineStatSearchVo) { this.loading = true; const result = yield queryCpuSingle(searchVo); if (result.success) { this.cpuSingleTrendData = result.data; } this.loading = false; } /** * 查询机器内存历史信息 * @param searchVo 查询条件 */ @asyncAction * queryMemory(searchVo: MachineStatSearchVo) { this.loading = true; const result = yield queryMemory(searchVo); if (result.success) { this.memoryTrendData = result.data; } this.loading = false; } /** * 查询机器磁盘历史信息,dataDir所在目录 * @param searchVo 查询条件 */ @asyncAction * queryDisk(searchVo: MachineStatSearchVo) { this.loading = true; const result = yield queryDisk(searchVo); if (result.success) { this.diskTrendData = result.data; } this.loading = false; } /** * 更新实例连接信息收集开关 * @param instanceId 实例id * @param monitor 监控开关 * @param callback 回调处理结果 */ @asyncAction * updateInstanceConnCollectMonitor(instanceId: number, monitor: boolean, callback: any) { this.loading = true; const result = yield updateInstanceConnCollectMonitor({instanceId: instanceId, monitor: monitor}); if (result.success) { callback && callback(); } this.loading = false; } /** * 搜索实例连接历史信息 * @param search 搜索条件 */ @asyncAction * searchConnectionHistory(search: ClientConnectionSearchVo) { this.loading = true; const result = yield searchConnectionHistory(search); if (result.success) { this.connectionsHistory = result.data; } this.loading = false; } /** * 获取流量TOP10信息 * @param instanceId 实例id * @param dateTime 时间点 * @param callback 回调处理结果 */ @asyncAction * queryNetTrafficDetail(instanceId, dateTime, callback) { this.loading = true; const result = yield queryNetTrafficDetail({instanceId: instanceId, dateTime: dateTime}); if (result.success) { callback && callback(result.data) } this.loading = false; } }
the_stack
export interface S { // Computation root root<T>(fn : (dispose : () => void) => T) : T; // Computation constructors <T>(fn : () => T) : () => T; <T>(fn : (v : T) => T, seed : T) : () => T; on<T>(ev : () => any, fn : () => T) : () => T; on<T>(ev : () => any, fn : (v : T) => T, seed : T, onchanges?: boolean) : () => T; // Data signal constructors data<T>(value : T) : DataSignal<T>; value<T>(value : T, eq? : (a : T, b : T) => boolean) : DataSignal<T>; // Batching changes freeze<T>(fn : () => T) : T; // Sampling a signal sample<T>(fn : () => T) : T; // Freeing external resources cleanup(fn : (final : boolean) => any) : void; // subclocks subclock() : <T>(fn : () => T) => T; subclock<T>(fn : () => T) : T; } export interface DataSignal<T> { () : T; (val : T) : T; } // Public interface const S = <S>function S<T>(fn : (v : T) => T, value : T) : () => T { var owner = Owner, clock = RunningClock === null ? RootClock : RunningClock, running = RunningNode; if (owner === null) console.warn("computations created without a root or parent will never be disposed"); var node = new ComputationNode(clock, fn, value); Owner = RunningNode = node; if (RunningClock === null) { toplevelComputation(node); } else { node.value = node.fn!(node.value); } if (owner && owner !== UNOWNED) { if (owner.owned === null) owner.owned = [node]; else owner.owned.push(node); } Owner = owner; RunningNode = running; return function computation() { if (RunningNode !== null) { var rclock = RunningClock!, sclock = node.clock; while (rclock.depth > sclock.depth + 1) rclock = rclock.parent!; if (rclock === sclock || rclock.parent === sclock) { if (node.preclocks !== null) { for (var i = 0; i < node.preclocks.count; i++) { var preclock = node.preclocks.clocks[i]; updateClock(preclock); } } if (node.age === node.clock.time()) { if (node.state === RUNNING) throw new Error("circular dependency"); else updateNode(node); // checks for state === STALE internally, so don't need to check here } if (node.preclocks !== null) { for (var i = 0; i < node.preclocks.count; i++) { var preclock = node.preclocks.clocks[i]; if (rclock === sclock) logNodePreClock(preclock, RunningNode); else logClockPreClock(preclock, rclock, RunningNode); } } } else { if (rclock.depth > sclock.depth) rclock = rclock.parent!; while (sclock.depth > rclock.depth + 1) sclock = sclock.parent!; if (sclock.parent === rclock) { logNodePreClock(sclock, RunningNode); } else { if (sclock.depth > rclock.depth) sclock = sclock.parent!; while (rclock.parent !== sclock.parent) rclock = rclock.parent!, sclock = sclock.parent!; logClockPreClock(sclock, rclock, RunningNode); } updateClock(sclock); } logComputationRead(node, RunningNode); } return node.value; } }; // compatibility with commonjs systems that expect default export to be at require('s.js').default rather than just require('s-js') Object.defineProperty(S, 'default', { value : S }); export default S; S.root = function root<T>(fn : (dispose : () => void) => T) : T { var owner = Owner, root = fn.length === 0 ? UNOWNED : new ComputationNode(RunningClock || RootClock, null, null), result : T = undefined!, disposer = fn.length === 0 ? null : function _dispose() { if (RunningClock !== null) { markClockStale(root.clock); root.clock.disposes.add(root); } else { dispose(root); } }; Owner = root; if (RunningClock === null) { result = topLevelRoot(fn, disposer, owner); } else { result = disposer === null ? (fn as any)() : fn(disposer); Owner = owner; } return result; }; function topLevelRoot<T>(fn : (dispose : () => void) => T, disposer : (() => void) | null, owner : ComputationNode | null) { try { return disposer === null ? (fn as any)() : fn(disposer); } finally { Owner = owner; } } S.on = function on<T>(ev : () => any, fn : (v? : T) => T, seed? : T, onchanges? : boolean) { if (Array.isArray(ev)) ev = callAll(ev); onchanges = !!onchanges; return S(on, seed); function on(value : T | undefined) { var running = RunningNode; ev(); if (onchanges) onchanges = false; else { RunningNode = null; value = fn(value); RunningNode = running; } return value; } }; function callAll(ss : (() => any)[]) { return function all() { for (var i = 0; i < ss.length; i++) ss[i](); } } S.data = function data<T>(value : T) : (value? : T) => T { var node = new DataNode(RunningClock === null ? RootClock : RunningClock, value); return function data(value? : T) : T { var rclock = RunningClock!, sclock = node.clock; if (RunningClock !== null) { while (rclock.depth > sclock.depth) rclock = rclock.parent!; while (sclock.depth > rclock.depth && sclock.parent !== rclock) sclock = sclock.parent!; if (sclock.parent !== rclock) while (rclock.parent !== sclock.parent) rclock = rclock.parent!, sclock = sclock.parent!; if (rclock !== sclock) { updateClock(sclock); } } var cclock = rclock === sclock ? sclock! : sclock.parent!; if (arguments.length > 0) { if (RunningClock !== null) { if (node.pending !== NOTPENDING) { // value has already been set once, check for conflicts if (value !== node.pending) { throw new Error("conflicting changes: " + value + " !== " + node.pending); } } else { // add to list of changes markClockStale(cclock); node.pending = value; cclock.changes.add(node); } } else { // not batching, respond to change now if (node.log !== null) { node.pending = value; RootClock.changes.add(node); event(); } else { node.value = value; } } return value!; } else { if (RunningNode !== null) { logDataRead(node, RunningNode); if (sclock.parent === rclock) logNodePreClock(sclock, RunningNode); else if (sclock !== rclock) logClockPreClock(sclock, rclock, RunningNode); } return node.value; } } }; S.value = function value<T>(current : T, eq? : (a : T, b : T) => boolean) : DataSignal<T> { var data = S.data(current), clock = RunningClock || RootClock, age = -1; return function value(update? : T) { if (arguments.length === 0) { return data(); } else { var same = eq ? eq(current, update!) : current === update; if (!same) { var time = clock.time(); if (age === time) throw new Error("conflicting values: " + update + " is not the same as " + current); age = time; current = update!; data(update!); } return update!; } } }; S.freeze = function freeze<T>(fn : () => T) : T { var result : T = undefined!; if (RunningClock !== null) { result = fn(); } else { RunningClock = RootClock; RunningClock.changes.reset(); try { result = fn(); event(); } finally { RunningClock = null; } } return result; }; S.sample = function sample<T>(fn : () => T) : T { var result : T, running = RunningNode; if (running !== null) { RunningNode = null; result = fn(); RunningNode = running; } else { result = fn(); } return result; } S.cleanup = function cleanup(fn : (final : boolean) => void) : void { if (Owner !== null) { if (Owner.cleanups === null) Owner.cleanups = [fn]; else Owner.cleanups.push(fn); } else { console.warn("cleanups created without a root or parent will never be run"); } }; S.subclock = function subclock<T>(fn? : () => T) { var clock = new Clock(RunningClock || RootClock); return fn === undefined ? subclock : subclock(fn); function subclock<T>(fn : () => T) { var result : T = null!, running = RunningClock; RunningClock = clock; clock.state = STALE; try { result = fn(); clock.subtime++; run(clock); } finally { RunningClock = running; } // if we were run from top level, have to flush any changes in RootClock if (RunningClock === null) event(); return result; } } // Internal implementation /// Graph classes and operations class Clock { static count = 0; id = Clock.count++; depth : number; age : number; state = CURRENT; subtime = 0; preclocks = null as ClockPreClockLog | null; changes = new Queue<DataNode>(); // batched changes to data nodes subclocks = new Queue<Clock>(); // subclocks that need to be updated updates = new Queue<ComputationNode>(); // computations to update disposes = new Queue<ComputationNode>(); // disposals to run after current batch of updates finishes constructor( public parent : Clock | null ) { if (parent !== null) { this.age = parent.time(); this.depth = parent.depth + 1; } else { this.age = 0; this.depth = 0; } } time () { var time = this.subtime, p = this as Clock; while ((p = p.parent!) !== null) time += p.subtime; return time; } } class DataNode { pending = NOTPENDING as any; log = null as Log | null; constructor( public clock : Clock, public value : any ) { } } class ComputationNode { age : number; state = CURRENT; source1 = null as null | Log; source1slot = 0; sources = null as null | Log[]; sourceslots = null as null | number[]; log = null as Log | null; preclocks = null as NodePreClockLog | null; owned = null as ComputationNode[] | null; cleanups = null as (((final : boolean) => void)[]) | null; constructor( public clock : Clock, public fn : ((v : any) => any) | null, public value : any ) { this.age = this.clock.time(); } } class Log { node1 = null as null | ComputationNode; node1slot = 0; nodes = null as null | ComputationNode[]; nodeslots = null as null | number[]; } class NodePreClockLog { count = 0; clocks = [] as Clock[]; // [clock], where clock.parent === node.clock ages = [] as number[]; // clock.id -> node.age ucount = 0; // number of ancestor clocks with preclocks from this node uclocks = [] as Clock[]; uclockids = [] as number[]; } class ClockPreClockLog { count = 0; clockcounts = [] as number[]; // clock.id -> ref count clocks = [] as (Clock | null)[]; // clock.id -> clock ids = [] as number[]; // [clock.id] } class Queue<T> { items = [] as T[]; count = 0; reset() { this.count = 0; } add(item : T) { this.items[this.count++] = item; } run(fn : (item : T) => void) { var items = this.items; for (var i = 0; i < this.count; i++) { fn(items[i]!); items[i] = null!; } this.count = 0; } } // Constants var NOTPENDING = {}, CURRENT = 0, STALE = 1, RUNNING = 2; // "Globals" used to keep track of current system state var RootClock = new Clock(null), RunningClock = null as Clock | null, // currently running clock RunningNode = null as ComputationNode | null, // currently running computation Owner = null as ComputationNode | null, // owner for new computations UNOWNED = new ComputationNode(RootClock, null, null); // Functions function logRead(from : Log, to : ComputationNode) { var fromslot : number, toslot = to.source1 === null ? -1 : to.sources === null ? 0 : to.sources.length; if (from.node1 === null) { from.node1 = to; from.node1slot = toslot; fromslot = -1; } else if (from.nodes === null) { from.nodes = [to]; from.nodeslots = [toslot]; fromslot = 0; } else { fromslot = from.nodes.length; from.nodes.push(to); from.nodeslots!.push(toslot); } if (to.source1 === null) { to.source1 = from; to.source1slot = fromslot; } else if (to.sources === null) { to.sources = [from]; to.sourceslots = [fromslot]; } else { to.sources.push(from); to.sourceslots!.push(fromslot); } } function logDataRead(data : DataNode, to : ComputationNode) { if (data.log === null) data.log = new Log(); logRead(data.log, to); } function logComputationRead(node : ComputationNode, to : ComputationNode) { if (node.log === null) node.log = new Log(); logRead(node.log, to); } function logNodePreClock(clock : Clock, to : ComputationNode) { if (to.preclocks === null) to.preclocks = new NodePreClockLog(); else if (to.preclocks.ages[clock.id] === to.age) return; to.preclocks.ages[clock.id] = to.age; to.preclocks.clocks[to.preclocks.count++] = clock; } function logClockPreClock(sclock : Clock, rclock : Clock, rnode : ComputationNode) { var clocklog = rclock.preclocks === null ? (rclock.preclocks = new ClockPreClockLog()) : rclock.preclocks, nodelog = rnode.preclocks === null ? (rnode.preclocks = new NodePreClockLog()) : rnode.preclocks; if (nodelog.ages[sclock.id] === rnode.age) return; nodelog.ages[sclock.id] = rnode.age; nodelog.uclocks[nodelog.ucount] = rclock; nodelog.uclockids[nodelog.ucount++] = sclock.id; var clockcount = clocklog.clockcounts[sclock.id]; if (clockcount === undefined) { clocklog.ids[clocklog.count++] = sclock.id; clocklog.clockcounts[sclock.id] = 1; clocklog.clocks[sclock.id] = sclock; } else if (clockcount === 0) { clocklog.clockcounts[sclock.id] = 1; clocklog.clocks[sclock.id] = sclock; } else { clocklog.clockcounts[sclock.id]++; } } function event() { // b/c we might be under a top level S.root(), have to preserve current root var owner = Owner; RootClock.subclocks.reset(); RootClock.updates.reset(); RootClock.subtime++; try { run(RootClock); } finally { RunningClock = RunningNode = null; Owner = owner; } } function toplevelComputation<T>(node : ComputationNode) { RunningClock = RootClock; RootClock.changes.reset(); RootClock.subclocks.reset(); RootClock.updates.reset(); try { node.value = node.fn!(node.value); if (RootClock.changes.count > 0 || RootClock.subclocks.count > 0 || RootClock.updates.count > 0) { RootClock.subtime++; run(RootClock); } } finally { RunningClock = Owner = RunningNode = null; } } function run(clock : Clock) { var running = RunningClock, count = 0; RunningClock = clock; clock.disposes.reset(); // for each batch ... while (clock.changes.count !== 0 || clock.subclocks.count !== 0 || clock.updates.count !== 0 || clock.disposes.count !== 0) { if (count > 0) // don't tick on first run, or else we expire already scheduled updates clock.subtime++; clock.changes.run(applyDataChange); clock.subclocks.run(updateClock); clock.updates.run(updateNode); clock.disposes.run(dispose); // if there are still changes after excessive batches, assume runaway if (count++ > 1e5) { throw new Error("Runaway clock detected"); } } RunningClock = running; } function applyDataChange(data : DataNode) { data.value = data.pending; data.pending = NOTPENDING; if (data.log) markComputationsStale(data.log); } function markComputationsStale(log : Log) { var node1 = log.node1, nodes = log.nodes; // mark all downstream nodes stale which haven't been already if (node1 !== null) markNodeStale(node1); if (nodes !== null) { for (var i = 0, len = nodes.length; i < len; i++) { markNodeStale(nodes[i]); } } } function markNodeStale(node : ComputationNode) { var time = node.clock.time(); if (node.age < time) { markClockStale(node.clock); node.age = time; node.state = STALE; node.clock.updates.add(node); if (node.owned !== null) markOwnedNodesForDisposal(node.owned); if (node.log !== null) markComputationsStale(node.log); } } function markOwnedNodesForDisposal(owned : ComputationNode[]) { for (var i = 0; i < owned.length; i++) { var child = owned[i]; child.age = child.clock.time(); child.state = CURRENT; if (child.owned !== null) markOwnedNodesForDisposal(child.owned); } } function markClockStale(clock : Clock) { var time = 0; if ((clock.parent !== null && clock.age < (time = clock.parent!.time())) || clock.state === CURRENT) { if (clock.parent !== null) { clock.age = time; markClockStale(clock.parent); clock.parent.subclocks.add(clock); } clock.changes.reset(); clock.subclocks.reset(); clock.updates.reset(); clock.state = STALE; } } function updateClock(clock : Clock) { var time = clock.parent!.time(); if (clock.age < time || clock.state === STALE) { if (clock.age < time) clock.state = CURRENT; if (clock.preclocks !== null) { for (var i = 0; i < clock.preclocks.ids.length; i++) { var preclock = clock.preclocks.clocks[clock.preclocks.ids[i]]; if (preclock) updateClock(preclock); } } clock.age = time; } if (clock.state === RUNNING) { throw new Error("clock circular reference"); } else if (clock.state === STALE) { clock.state = RUNNING; run(clock); clock.state = CURRENT; } } function updateNode(node : ComputationNode) { if (node.state === STALE) { var owner = Owner, running = RunningNode, clock = RunningClock; Owner = RunningNode = node; RunningClock = node.clock; node.state = RUNNING; cleanup(node, false); node.value = node.fn!(node.value); node.state = CURRENT; Owner = owner; RunningNode = running; RunningClock = clock; } } function cleanup(node : ComputationNode, final : boolean) { var source1 = node.source1, sources = node.sources, sourceslots = node.sourceslots, cleanups = node.cleanups, owned = node.owned, preclocks = node.preclocks, i : number, len : number; if (cleanups !== null) { for (i = 0; i < cleanups.length; i++) { cleanups[i](final); } node.cleanups = null; } if (owned !== null) { for (i = 0; i < owned.length; i++) { dispose(owned[i]); } node.owned = null; } if (source1 !== null) { cleanupSource(source1, node.source1slot); node.source1 = null; } if (sources !== null) { for (i = 0, len = sources.length; i < len; i++) { cleanupSource(sources.pop()!, sourceslots!.pop()!); } } if (preclocks !== null) { for (i = 0; i < preclocks.count; i++) { preclocks.clocks[i] = null!; } preclocks.count = 0; for (i = 0; i < preclocks.ucount; i++) { var upreclocks = preclocks.uclocks[i].preclocks!, uclockid = preclocks.uclockids[i]; if (--upreclocks.clockcounts[uclockid] === 0) { upreclocks.clocks[uclockid] = null; } } preclocks.ucount = 0; } } function cleanupSource(source : Log, slot : number) { var nodes = source.nodes!, nodeslots = source.nodeslots!, last : ComputationNode, lastslot : number; if (slot === -1) { source.node1 = null; } else { last = nodes.pop()!; lastslot = nodeslots.pop()!; if (slot !== nodes.length) { nodes[slot] = last; nodeslots[slot] = lastslot; if (lastslot === -1) { last.source1slot = slot; } else { last.sourceslots![lastslot] = slot; } } } } function dispose(node : ComputationNode) { node.clock = null!; node.fn = null; node.log = null; node.preclocks = null; cleanup(node, true); }
the_stack
import * as bSemver from 'balena-semver'; // tslint:disable-next-line:import-blacklist import * as _ from 'lodash'; import { expect } from 'chai'; import * as parallel from 'mocha.parallel'; import { balena, credentials, givenAnApplication, givenLoggedInUser, IS_BROWSER, applicationRetrievalFields, } from '../setup'; import { timeSuite } from '../../util'; import type * as BalenaSdk from '../../..'; import type { Resolvable } from '../../../typings/utils'; const eventuallyExpectProperty = <T>(promise: Promise<T>, prop: string) => expect(promise).to.eventually.have.property(prop); const { _getNormalizedDeviceTypeSlug, _getDownloadSize, _getMaxSatisfyingVersion, _clearDeviceTypesAndOsVersionCaches, } = balena.models.os as ReturnType< typeof import('../../../lib/models/os').default >; const containsVersion = ( versions: BalenaSdk.OsVersion[], expected: Partial<BalenaSdk.OsVersion>, ) => { const os = _.find(versions, expected); expect(os).to.not.be.undefined; }; const itShouldClearMethodCacheFactory = <T>( title: string, fn: () => Resolvable<T>, prepareFn?: (result: T) => T, ) => { return (stepFn: () => Resolvable<void>) => it(`should clear the result cache of ${title}`, async function () { const p1 = fn(); let result1 = await p1; await stepFn(); const p2 = fn(); let result2 = await p2; if (prepareFn) { // @ts-expect-error result1 = prepareFn(result1); // @ts-expect-error result2 = prepareFn(result2); } expect(p1).to.not.equal(p2); if (!['string', 'number'].includes(typeof result1)) { expect(result1).to.not.equal(result2); } expect(result1).to.deep.equal(result2); }); }; const itShouldClear = { getAllOsVersions: itShouldClearMethodCacheFactory( 'balena.models.os.getAllOsVersions()', () => balena.models.os.getAllOsVersions('raspberry-pi'), ), getAvailableOsVersions: itShouldClearMethodCacheFactory( 'balena.models.os.getAvailableOsVersions()', () => balena.models.os.getAvailableOsVersions('raspberry-pi'), ), getDeviceTypesCache: itShouldClearMethodCacheFactory( 'balena.models.os._getNormalizedDeviceTypeSlug()', () => _getNormalizedDeviceTypeSlug('raspberrypi'), ), getDownloadSizeCache: itShouldClearMethodCacheFactory( 'balena.models.os._getDownloadSize()', () => _getDownloadSize('raspberry-pi', '1.26.1'), ), }; const describeCacheInvalidationChanges = function ( itFnWithStep: (fn: () => Resolvable<void>) => Mocha.Test, ) { describe('cache invalidation', function () { describe('when not logged in', function () { beforeEach(() => balena.auth.logout()); describe('balena.auth.logout()', () => itFnWithStep(() => balena.auth.logout())); describe('balena.auth.login()', () => itFnWithStep(() => balena.auth.login({ email: credentials.email, password: credentials.password, }), )); describe('balena.auth.loginWithToken()', () => itFnWithStep(() => balena.auth .authenticate(credentials) .then(balena.auth.loginWithToken), )); }); describe('when logged in with credentials', function () { givenLoggedInUser(beforeEach); afterEach(() => balena.auth.logout()); describe('balena.auth.logout()', () => itFnWithStep(() => balena.auth.logout())); describe('balena.auth.login()', () => itFnWithStep(() => balena.auth.login({ email: credentials.email, password: credentials.password, }), )); describe('balena.auth.loginWithToken()', () => itFnWithStep(() => balena.auth .authenticate(credentials) .then(balena.auth.loginWithToken), )); }); }); }; describe('OS model', function () { timeSuite(before); before(function () { return balena.auth.logout(); }); describe('balena.models.os.getAllOsVersions()', function () { parallel('', function () { it('should contain both balenaOS and balenaOS ESR OS types [string device type argument]', async () => { const res = await balena.models.os.getAllOsVersions('fincm3'); expect(res).to.be.an('array'); containsVersion(res, { strippedVersion: '2.29.0+rev1', variant: 'dev', }); containsVersion(res, { strippedVersion: '2.29.0+rev1', variant: 'prod', }); containsVersion(res, { strippedVersion: '2020.04.0', variant: 'dev', }); containsVersion(res, { strippedVersion: '2020.04.0', variant: 'prod', }); }); it('should contain both balenaOS and balenaOS ESR OS types [array of single device type]', async () => { const res = await balena.models.os.getAllOsVersions(['fincm3']); expect(res).to.be.an('object'); expect(res).to.have.property('fincm3'); expect(res).to.not.have.property('raspberrypi3'); containsVersion(res['fincm3'], { strippedVersion: '2.29.0+rev1', variant: 'dev', }); containsVersion(res['fincm3'], { strippedVersion: '2.29.0+rev1', variant: 'prod', }); containsVersion(res['fincm3'], { strippedVersion: '2020.04.0', variant: 'dev', }); containsVersion(res['fincm3'], { strippedVersion: '2020.04.0', variant: 'prod', }); }); it('should contain both balenaOS and balenaOS ESR OS types [multiple device types]', async () => { const res = await balena.models.os.getAllOsVersions([ 'fincm3', 'raspberrypi3', ]); expect(res).to.be.an('object'); expect(res).to.have.property('fincm3'); expect(res).to.have.property('raspberrypi3'); containsVersion(res['fincm3'], { strippedVersion: '2.29.0+rev1', variant: 'dev', }); containsVersion(res['fincm3'], { strippedVersion: '2.29.0+rev1', variant: 'prod', }); containsVersion(res['fincm3'], { strippedVersion: '2020.04.0', variant: 'dev', }); containsVersion(res['fincm3'], { strippedVersion: '2020.04.0', variant: 'prod', }); containsVersion(res['raspberrypi3'], { strippedVersion: '2.29.0+rev1', variant: 'dev', }); containsVersion(res['raspberrypi3'], { strippedVersion: '2.29.0+rev1', variant: 'prod', }); containsVersion(res['raspberrypi3'], { strippedVersion: '2020.04.0', variant: 'dev', }); containsVersion(res['raspberrypi3'], { strippedVersion: '2020.04.0', variant: 'prod', }); }); it('should return an empty object for non-existent DTs', async () => { const res = await balena.models.os.getAllOsVersions(['blahbleh']); expect(res).to.deep.equal({}); }); it('should cache the results when not providing extra options', async () => { const firstRes = await balena.models.os.getAllOsVersions([ 'raspberrypi3', ]); const secondRes = await balena.models.os.getAllOsVersions([ 'raspberrypi3', ]); expect(firstRes).to.equal(secondRes); }); it('should not cache the results when providing extra options', async () => { const firstRes = await balena.models.os.getAllOsVersions( ['raspberrypi3'], { $filter: { is_invalidated: false } }, ); const secondRes = await balena.models.os.getAllOsVersions( ['raspberrypi3'], { $filter: { is_invalidated: false } }, ); expect(firstRes).to.not.equal(secondRes); }); }); describeCacheInvalidationChanges(itShouldClear.getAllOsVersions); }); describe('balena.models.os.getAvailableOsVersions()', function () { parallel('', function () { it('should contain both balenaOS and balenaOS ESR OS types [string device type argument]', async () => { const res = await balena.models.os.getAvailableOsVersions('fincm3'); expect(res).to.be.an('array'); containsVersion(res, { strippedVersion: '2.29.0+rev1', variant: 'dev', }); containsVersion(res, { strippedVersion: '2.29.0+rev1', variant: 'prod', }); containsVersion(res, { strippedVersion: '2020.04.0', variant: 'dev', }); containsVersion(res, { strippedVersion: '2020.04.0', variant: 'prod', }); }); it('should contain both balenaOS and balenaOS ESR OS types [array of single device type]', async () => { const res = await balena.models.os.getAvailableOsVersions(['fincm3']); expect(res).to.be.an('object'); expect(res).to.have.property('fincm3'); expect(res).to.not.have.property('raspberrypi3'); containsVersion(res['fincm3'], { strippedVersion: '2.29.0+rev1', variant: 'dev', }); containsVersion(res['fincm3'], { strippedVersion: '2.29.0+rev1', variant: 'prod', }); containsVersion(res['fincm3'], { strippedVersion: '2020.04.0', variant: 'dev', }); containsVersion(res['fincm3'], { strippedVersion: '2020.04.0', variant: 'prod', }); }); it('should contain both balenaOS and balenaOS ESR OS types [multiple device types]', async () => { const res = await balena.models.os.getAvailableOsVersions([ 'fincm3', 'raspberrypi3', ]); expect(res).to.be.an('object'); expect(res).to.have.property('fincm3'); expect(res).to.have.property('raspberrypi3'); containsVersion(res['fincm3'], { strippedVersion: '2.29.0+rev1', variant: 'dev', }); containsVersion(res['fincm3'], { strippedVersion: '2.29.0+rev1', variant: 'prod', }); containsVersion(res['fincm3'], { strippedVersion: '2020.04.0', variant: 'dev', }); containsVersion(res['fincm3'], { strippedVersion: '2020.04.0', variant: 'prod', }); containsVersion(res['raspberrypi3'], { strippedVersion: '2.29.0+rev1', variant: 'dev', }); containsVersion(res['raspberrypi3'], { strippedVersion: '2.29.0+rev1', variant: 'prod', }); containsVersion(res['raspberrypi3'], { strippedVersion: '2020.04.0', variant: 'dev', }); containsVersion(res['raspberrypi3'], { strippedVersion: '2020.04.0', variant: 'prod', }); }); it('should return an empty object for non-existent DTs', async () => { const res = await balena.models.os.getAvailableOsVersions(['blahbleh']); expect(res).to.deep.equal({}); }); it('should cache the results', async () => { const firstRes = await balena.models.os.getAvailableOsVersions([ 'raspberrypi3', ]); const secondRes = await balena.models.os.getAvailableOsVersions([ 'raspberrypi3', ]); expect(firstRes).to.equal(secondRes); }); }); describeCacheInvalidationChanges(itShouldClear.getAvailableOsVersions); }); describe('balena.models.os._getMaxSatisfyingVersion()', function () { const esrOsVersions = [ { raw_version: '2021.10.2.prod', rawVersion: '2021.10.2.prod', isRecommended: true, }, { raw_version: '2021.10.2.dev', rawVersion: '2021.10.2.dev' }, { raw_version: '2021.07.1.prod', rawVersion: '2021.07.1.prod' }, { raw_version: '2021.07.1.dev', rawVersion: '2021.07.1.dev' }, { raw_version: '2021.04.0.prod', rawVersion: '2021.04.0.prod' }, { raw_version: '2021.04.0.dev', rawVersion: '2021.04.0.dev' }, { raw_version: '2021.01.0.prod', rawVersion: '2021.01.0.prod' }, { raw_version: '2021.01.0.dev', rawVersion: '2021.01.0.dev' }, { raw_version: '2020.07.2.prod', rawVersion: '2020.07.2.prod' }, { raw_version: '2020.07.2.dev', rawVersion: '2020.07.2.dev' }, { raw_version: '2020.07.1.prod', rawVersion: '2020.07.1.prod' }, { raw_version: '2020.07.1.dev', rawVersion: '2020.07.1.dev' }, { raw_version: '2020.07.0.prod', rawVersion: '2020.07.0.prod' }, { raw_version: '2020.07.0.dev', rawVersion: '2020.07.0.dev' }, { raw_version: '2020.04.1.prod', rawVersion: '2020.04.1.prod' }, { raw_version: '2020.04.1.dev', rawVersion: '2020.04.1.dev' }, { raw_version: '2020.04.0.prod', rawVersion: '2020.04.0.prod' }, { raw_version: '2020.04.0.dev', rawVersion: '2020.04.0.dev' }, ]; const defaultOsVersions = [ { raw_version: '2.85.2+rev3.prod', rawVersion: '2.85.2+rev3.prod', isRecommended: true, }, { raw_version: '2.85.2+rev3.dev', rawVersion: '2.85.2+rev3.dev' }, { raw_version: '2.83.10+rev1.prod', rawVersion: '2.83.10+rev1.prod' }, { raw_version: '2.83.10+rev1.dev', rawVersion: '2.83.10+rev1.dev' }, { raw_version: '2.80.5+rev1.prod', rawVersion: '2.80.5+rev1.prod' }, { raw_version: '2.80.5+rev1.dev', rawVersion: '2.80.5+rev1.dev' }, { raw_version: '2.80.3+rev1.prod', rawVersion: '2.80.3+rev1.prod' }, { raw_version: '2.80.3+rev1.dev', rawVersion: '2.80.3+rev1.dev' }, { raw_version: '2.75.0+rev1.prod', rawVersion: '2.75.0+rev1.prod' }, { raw_version: '2.75.0+rev1.dev', rawVersion: '2.75.0+rev1.dev' }, { raw_version: '2.73.1+rev1.prod', rawVersion: '2.73.1+rev1.prod' }, { raw_version: '2.73.1+rev1.dev', rawVersion: '2.73.1+rev1.dev' }, { raw_version: '2.0.0.rev1.prod', rawVersion: '2.0.0.rev1.prod' }, { raw_version: '2.0.0.rev1.dev', rawVersion: '2.0.0.rev1.dev' }, ]; const osVersions = [...esrOsVersions, ...defaultOsVersions]; it("should support 'latest'", () => expect(_getMaxSatisfyingVersion('latest', osVersions)).to.equal( '2021.10.2.prod', )); it("should support 'latest' with among default OS versions", () => expect(_getMaxSatisfyingVersion('latest', defaultOsVersions)).to.equal( '2.85.2+rev3.prod', )); it("should support 'latest' with among esr OS versions", () => expect(_getMaxSatisfyingVersion('latest', esrOsVersions)).to.equal( '2021.10.2.prod', )); it("should support 'recommended'", () => expect( _getMaxSatisfyingVersion('recommended', defaultOsVersions), ).to.equal('2.85.2+rev3.prod')); it("should support 'default'", () => expect(_getMaxSatisfyingVersion('default', defaultOsVersions)).to.equal( '2.85.2+rev3.prod', )); it('should support exact version', () => expect(_getMaxSatisfyingVersion('2.73.1+rev1.prod', osVersions)).to.equal( '2.73.1+rev1.prod', )); it('should support stripped version', () => expect(_getMaxSatisfyingVersion('2.73.1', osVersions)).to.equal( '2.73.1+rev1.prod', )); it('should support exact non-semver version', () => expect(_getMaxSatisfyingVersion('2.0.0.rev1', osVersions)).to.equal( '2.0.0.rev1.prod', )); it('should return an exact match, if it exists, when given a specific version', () => // Concern here is that semver says .dev is equivalent to .prod, but // we want provide an exact version and use _exactly_ that version. expect(_getMaxSatisfyingVersion('2.73.1+rev1.dev', osVersions)).to.equal( '2.73.1+rev1.dev', )); it('should return an exact match, if it exists, when given a specific ESR version', () => expect(_getMaxSatisfyingVersion('2020.07.2.dev', osVersions)).to.equal( '2020.07.2.dev', )); it('should return an equivalent result, if no exact result exists, when given a specific version', () => expect(_getMaxSatisfyingVersion('2.73.1+rev1', osVersions)).to.equal( '2.73.1+rev1.prod', )); it('should support ^ semver ranges in default OS releases', () => expect(_getMaxSatisfyingVersion('^2.0.1', osVersions)).to.equal( '2.85.2+rev3.prod', )); it('should support ~ semver ranges in default OS releases', () => expect(_getMaxSatisfyingVersion('~2.80.3', osVersions)).to.equal( '2.80.5+rev1.prod', )); it('should support > semver ranges in default OS releases', () => { expect(_getMaxSatisfyingVersion('>2.80.3', defaultOsVersions)).to.equal( '2.85.2+rev3.prod', ); expect( _getMaxSatisfyingVersion('>2.80.3+rev1.prod', defaultOsVersions), ).to.equal('2.85.2+rev3.prod'); expect(_getMaxSatisfyingVersion('>2.80.3', osVersions)).to.equal( '2021.10.2.prod', ); }); it('should support ^ semver ranges in ESR OS releases', () => expect(_getMaxSatisfyingVersion('^2020.04.0', osVersions)).to.equal( '2020.07.2.prod', )); it('should support ~ semver ranges in ESR OS releases', () => expect(_getMaxSatisfyingVersion('~2020.04.0', osVersions)).to.equal( '2020.04.1.prod', )); it('should support > semver ranges in ESR OS releases', () => { expect(_getMaxSatisfyingVersion('>2020.04.0', esrOsVersions)).to.equal( '2021.10.2.prod', ); expect( _getMaxSatisfyingVersion('>2020.04.0.prod', esrOsVersions), ).to.equal('2021.10.2.prod'); expect(_getMaxSatisfyingVersion('>2020.04.0', osVersions)).to.equal( '2021.10.2.prod', ); }); it('should support non-semver version ranges', () => expect(_getMaxSatisfyingVersion('^2020.04.0', osVersions)).to.equal( '2020.07.2.prod', )); it('should drop unsupported exact versions', () => { expect(_getMaxSatisfyingVersion('2.8.8+rev8.prod', osVersions)).to.equal( null, ); expect(_getMaxSatisfyingVersion('2.8.8', osVersions)).to.equal(null); }); it('should drop unsupported semver ranges', () => { expect(_getMaxSatisfyingVersion('~2.8.8', osVersions)).to.equal(null); expect(_getMaxSatisfyingVersion('^2.999.0', osVersions)).to.equal(null); }); }); describe('balena.models.os._getNormalizedDeviceTypeSlug()', function () { it('should cache the results', async function () { const p1 = _getNormalizedDeviceTypeSlug('raspberrypi'); const p2 = _getNormalizedDeviceTypeSlug('raspberrypi'); expect(p1).to.equal(p2); // wait for the promises to resolve before starting the new request await p1; await p2; const p3 = _getNormalizedDeviceTypeSlug('raspberrypi'); expect(p1).to.equal(p3); }); describeCacheInvalidationChanges(itShouldClear.getDeviceTypesCache); }); describe('balena.models.os.getDownloadSize()', function () { parallel('given a valid device slug', function () { it('should eventually be a valid number', function () { const promise = balena.models.os.getDownloadSize('raspberry-pi'); return expect(promise).to.eventually.be.a('number'); }); it('should eventually be a valid number if passing a device type alias', function () { const promise = balena.models.os.getDownloadSize('raspberrypi'); return expect(promise).to.eventually.be.a('number'); }); }); parallel('given a specific OS version', function () { it('should get a result for ResinOS v1', function () { const promise = balena.models.os.getDownloadSize( 'raspberry-pi', '1.26.1', ); return expect(promise).to.eventually.be.a('number'); }); it('should get a result for ResinOS v2', function () { const promise = balena.models.os.getDownloadSize( 'raspberry-pi', '2.0.6+rev3.prod', ); return expect(promise).to.eventually.be.a('number'); }); it('should cache the results', () => balena.models.os .getDownloadSize('raspberry-pi', '1.26.1') .then((result1) => balena.models.os .getDownloadSize('raspberry-pi', '1.26.1') .then((result2) => expect(result1).to.equal(result2)), )); it('should cache download sizes independently for each version', () => Promise.all([ balena.models.os.getDownloadSize('raspberry-pi', '1.26.1'), balena.models.os.getDownloadSize('raspberry-pi', '2.0.6+rev3.prod'), ]).then(function ([os1Size, os2Size]) { expect(os1Size).not.to.equal(os2Size); })); }); describe('given an invalid device slug', () => it('should be rejected with an error message', function () { const promise = balena.models.os.getDownloadSize('foo-bar-baz'); return expect(promise).to.be.rejectedWith( 'Invalid device type: foo-bar-baz', ); })); }); describe('balena.models.os._getDownloadSize()', function () { it('should cache the results', function () { const p1 = _getDownloadSize('raspberry-pi', '1.26.1'); return p1.then(function (result1) { const p2 = _getDownloadSize('raspberry-pi', '1.26.1'); return p2.then(function (result2) { expect(result1).to.equal(result2); expect(p1).to.equal(p2); }); }); }); describeCacheInvalidationChanges(itShouldClear.getDownloadSizeCache); }); describe('balena.models.os._clearDeviceTypesAndOsVersionCaches()', function () { itShouldClear.getDeviceTypesCache(() => _clearDeviceTypesAndOsVersionCaches(), ); itShouldClear.getDownloadSizeCache(() => _clearDeviceTypesAndOsVersionCaches(), ); itShouldClear.getAllOsVersions(() => _clearDeviceTypesAndOsVersionCaches()); itShouldClear.getAvailableOsVersions(() => _clearDeviceTypesAndOsVersionCaches(), ); }); describe('balena.models.os.getLastModified()', function () { parallel('given a valid device slug', function () { it('should eventually be a valid Date instance', function () { const promise = balena.models.os.getLastModified('raspberry-pi'); return expect(promise).to.eventually.be.an.instanceof(Date); }); it('should eventually be a valid Date instance if passing a device type alias', function () { const promise = balena.models.os.getLastModified('raspberrypi'); return expect(promise).to.eventually.be.an.instanceof(Date); }); it('should be able to query for a specific version', function () { const promise = balena.models.os.getLastModified( 'raspberrypi', '1.26.1', ); return expect(promise).to.eventually.be.an.instanceof(Date); }); it('should be able to query for a version containing a plus', function () { const promise = balena.models.os.getLastModified( 'raspberrypi', '2.0.6+rev3.prod', ); return expect(promise).to.eventually.be.an.instanceof(Date); }); }); describe('given an invalid device slug', () => it('should be rejected with an error message', function () { const promise = balena.models.os.getLastModified('foo-bar-baz'); return expect(promise).to.be.rejectedWith( 'Invalid device type: foo-bar-baz', ); })); }); describe('balena.models.os.download()', function () { if (IS_BROWSER) { return; } const rindle = require('rindle'); const tmp = require('tmp'); const fs = require('fs') as typeof import('fs'); describe('given a valid device slug', function () { it('should contain a valid mime property', () => balena.models.os .download('raspberry-pi') .then((stream) => expect(stream.mime).to.equal('application/octet-stream'), )); it('should contain a valid mime property if passing a device type alias', () => balena.models.os .download('raspberrypi') .then((stream) => expect(stream.mime).to.equal('application/octet-stream'), )); it('should be able to download the image', function () { const tmpFile = tmp.tmpNameSync(); return balena.models.os .download('raspberry-pi') .then((stream) => stream.pipe(fs.createWriteStream(tmpFile))) .then(rindle.wait) .then(() => fs.promises.stat(tmpFile)) .then((stat) => expect(stat.size).to.not.equal(0)) .finally(() => fs.promises.unlink(tmpFile)); }); }); describe('given an invalid device slug', () => it('should be rejected with an error message', function () { const promise = balena.models.os.download('foo-bar-baz'); return expect(promise).to.be.rejectedWith( 'Invalid device type: foo-bar-baz', ); })); }); describe('balena.models.os.isSupportedOsUpdate()', function () { describe('given an invalid device slug', () => it('should be rejected with an error message', function () { const promise = balena.models.os.isSupportedOsUpdate( 'foo-bar-baz', '2.0.0+rev1.prod', '2.29.2+rev1.prod', ); return expect(promise).to.be.rejectedWith( 'Invalid device type: foo-bar-baz', ); })); describe('given a valid device slug', function () { describe('given a unsupported low starting version number', () => it('should return false', () => expect( balena.models.os.isSupportedOsUpdate( 'raspberrypi3', '2.0.0+rev0.prod', '2.2.0+rev2.prod', ), ).to.eventually.equal(false))); describe('given a unsupported low target version number', () => it('should return false', () => expect( balena.models.os.isSupportedOsUpdate( 'raspberrypi3', '2.0.0+rev1.prod', '2.1.0+rev1.prod', ), ).to.eventually.equal(false))); describe('given a dev starting version number', () => it('should return false', () => expect( balena.models.os.isSupportedOsUpdate( 'raspberrypi3', '2.0.0+rev1.dev', '2.2.0+rev2.prod', ), ).to.eventually.equal(false))); describe('given a dev target version number', () => it('should return false', () => expect( balena.models.os.isSupportedOsUpdate( 'raspberrypi3', '2.0.0+rev1.prod', '2.1.0+rev1.dev', ), ).to.eventually.equal(false))); describe('given a supported os update path', () => { [ ['2.0.0+rev1.prod', '2.2.0+rev2.prod'], ['2.8.0+rev1.dev', '2.10.0+rev2.dev'], ['2.2.0+rev2.prod', '2.88.4'], ['2.2.0+rev2.dev', '2.88.4'], ].forEach(([current, target]) => { it(`should return true when updating ${current} -> ${target}`, async () => { expect( await balena.models.os.isSupportedOsUpdate( 'raspberrypi3', current, target, ), ).to.equal(true); }); }); }); }); }); describe('balena.models.os.getSupportedOsUpdateVersions()', function () { describe('given an invalid device slug', () => it('should be rejected with an error message', function () { const promise = balena.models.os.getSupportedOsUpdateVersions( 'foo-bar-baz', '2.9.6+rev1.prod', ); return expect(promise).to.be.rejectedWith( 'Invalid device type: foo-bar-baz', ); })); describe('given a valid device slug', () => it('should return the list of supported hup targets', () => balena.models.os .getSupportedOsUpdateVersions('raspberrypi3', '2.9.6+rev1.prod') .then(function ({ current, recommended, versions }) { expect(current).to.equal('2.9.6+rev1.prod'); expect(recommended).to.be.a('string'); expect(versions).to.be.an('array'); expect(versions).to.not.have.length(0); _.each(versions, function (v) { expect(v).to.be.a('string'); expect(bSemver.gte(v, current)).to.be.true; }); expect(versions.length > 2).to.be.true; const sortedVersions = versions.slice().sort(bSemver.rcompare); expect(versions).to.deep.equal(sortedVersions); }))); }); describe('when logged in as a user with a single application', function () { givenLoggedInUser(before); givenAnApplication(before); let ctx: Mocha.Context; before(function () { ctx = this; }); parallel('balena.models.os.getConfig()', function () { const DEFAULT_OS_VERSION = '2.12.7+rev1.prod'; it('should fail if no version option is provided', function () { return expect( (balena.models.os.getConfig as any)(ctx.application.id), ).to.be.rejectedWith( 'An OS version is required when calling os.getConfig', ); }); applicationRetrievalFields.forEach((prop) => { it(`should be able to get an application config by ${prop}`, function () { const promise = balena.models.os.getConfig(ctx.application[prop], { version: DEFAULT_OS_VERSION, }); return Promise.all([ eventuallyExpectProperty(promise, 'applicationId'), eventuallyExpectProperty(promise, 'apiKey'), eventuallyExpectProperty(promise, 'userId'), eventuallyExpectProperty(promise, 'deviceType'), eventuallyExpectProperty(promise, 'apiEndpoint'), eventuallyExpectProperty(promise, 'registryEndpoint'), eventuallyExpectProperty(promise, 'vpnEndpoint'), eventuallyExpectProperty(promise, 'listenPort'), ]); }); }); it('should be rejected if the version is invalid', function () { const promise = balena.models.os.getConfig(ctx.application.id, { version: 'v1+foo', }); return expect(promise).to.be.rejected.then((error) => { expect(error).to.have.property('message'); expect(error.message.replace('&lt;', '<')).to.contain( 'balenaOS versions <= 1.2.0 are no longer supported, please update', ); }); }); it('should be rejected if the version is <= 1.2.0', function () { const promise = balena.models.os.getConfig(ctx.application.id, { version: '1.2.0', }); return expect(promise).to.be.rejected.then((error) => { expect(error).to.have.property('message'); expect(error.message.replace('&lt;', '<')).to.contain( 'balenaOS versions <= 1.2.0 are no longer supported, please update', ); }); }); it('should be able to configure v1 image parameters', function () { const configOptions = { appUpdatePollInterval: 72, network: 'wifi' as const, wifiKey: 'foobar', wifiSsid: 'foobarbaz', ip: '1.2.3.4', gateway: '5.6.7.8', netmask: '9.10.11.12', version: '1.26.1', }; return balena.models.os .getConfig(ctx.application.id, configOptions) .then(function (config) { expect(config).to.deep.match({ // NOTE: the interval is converted to ms in the config object appUpdatePollInterval: configOptions.appUpdatePollInterval * 60 * 1000, wifiKey: configOptions.wifiKey, wifiSsid: configOptions.wifiSsid, }); expect(config) .to.have.property('files') .that.has.property('network/network.config') .that.includes( `${configOptions.ip}/${configOptions.netmask}/${configOptions.gateway}`, ); }); }); it('should be able to configure v2 image parameters', function () { const configOptions = { appUpdatePollInterval: 72, network: 'wifi' as const, wifiKey: 'foobar', wifiSsid: 'foobarbaz', ip: '1.2.3.4', gateway: '5.6.7.8', netmask: '9.10.11.12', version: '2.0.8+rev1.prod', }; return balena.models.os .getConfig(ctx.application.id, configOptions) .then(function (config) { expect(config).to.deep.match({ // NOTE: the interval is converted to ms in the config object appUpdatePollInterval: configOptions.appUpdatePollInterval * 60 * 1000, wifiKey: configOptions.wifiKey, wifiSsid: configOptions.wifiSsid, }); expect(config).to.not.have.property('files'); }); }); it('should be able to configure v2 image with a provisioning key name', async function () { const provisioningKeyName = `provision-key-${Date.now()}`; const configOptions = { appUpdatePollInterval: 72, network: 'wifi' as const, wifiKey: 'foobar', wifiSsid: 'foobarbaz', ip: '1.2.3.4', gateway: '5.6.7.8', netmask: '9.10.11.12', version: '2.11.8+rev1.prod', provisioningKeyName, }; await balena.models.os.getConfig(ctx.application.id, configOptions); const provisioningKeys = await balena.models.apiKey.getProvisioningApiKeysByApplication( ctx.application.id, { $filter: { name: provisioningKeyName } }, ); expect(provisioningKeys).to.be.an('array'); expect(provisioningKeys.length).is.equal(1); expect(provisioningKeys[0]) .to.have.property('name') .to.be.equal(provisioningKeyName); }); it('should be able to configure v2 image with a provisioning key expiry date', async function () { const provisioningKeyExpiryDate = new Date().toISOString(); const configOptions = { appUpdatePollInterval: 72, network: 'wifi' as const, wifiKey: 'foobar', wifiSsid: 'foobarbaz', ip: '1.2.3.4', gateway: '5.6.7.8', netmask: '9.10.11.12', version: '2.11.8+rev1.prod', provisioningKeyExpiryDate, }; await balena.models.os.getConfig(ctx.application.id, configOptions); const provisioningKeys = await balena.models.apiKey.getProvisioningApiKeysByApplication( ctx.application.id, { $filter: { expiry_date: provisioningKeyExpiryDate } }, ); expect(provisioningKeys).to.be.an('array'); expect(provisioningKeys.length).is.equal(1); expect(provisioningKeys[0]) .to.have.property('expiry_date') .to.be.equal(provisioningKeyExpiryDate); }); it('should be rejected if the application id does not exist', function () { const promise = balena.models.os.getConfig(999999, { version: DEFAULT_OS_VERSION, }); return expect(promise).to.be.rejectedWith( 'Application not found: 999999', ); }); it('should be rejected if the application name does not exist', function () { const promise = balena.models.os.getConfig('foobarbaz', { version: DEFAULT_OS_VERSION, }); return expect(promise).to.be.rejectedWith( 'Application not found: foobarbaz', ); }); }); }); describe('helpers', () => describe('balena.models.os.isArchitectureCompatibleWith()', function () { [ ['armv7hf', 'i386'], ['aarch64', 'i386'], ['i386', 'armv7hf'], ['i386', 'aarch64'], ['armv7hf', 'amd64'], ['aarch64', 'amd64'], ['amd64', 'armv7hf'], ['amd64', 'aarch64'], ['amd64', 'i386'], ['i386', 'amd64'], // arm architectures ['armv5e', 'rpi'], ['armv5e', 'armv7hf'], ['armv5e', 'aarch64'], ['rpi', 'armv5e'], ['rpi', 'armv7hf'], ['rpi', 'aarch64'], ['armv7hf', 'armv5e'], ['armv7hf', 'aarch64'], ['aarch64', 'armv5e'], ].forEach(function ([deviceArch, appArch]) { it(`should return false when comparing ${deviceArch} and ${appArch} architectures`, () => expect(balena.models.os.isArchitectureCompatibleWith(deviceArch, appArch)).to.equal(false)); }); it('should return true when comparing the same architecture slugs', function () { expect( balena.models.os.isArchitectureCompatibleWith('rpi', 'rpi'), ).to.equal(true); expect( balena.models.os.isArchitectureCompatibleWith('armv5e', 'armv5e'), ).to.equal(true); expect( balena.models.os.isArchitectureCompatibleWith('armv7hf', 'armv7hf'), ).to.equal(true); expect( balena.models.os.isArchitectureCompatibleWith('aarch64', 'aarch64'), ).to.equal(true); expect( balena.models.os.isArchitectureCompatibleWith('i386', 'i386'), ).to.equal(true); expect( balena.models.os.isArchitectureCompatibleWith('i386-nlp', 'i386-nlp'), ).to.equal(true); expect( balena.models.os.isArchitectureCompatibleWith('amd64', 'amd64'), ).to.equal(true); }); return [ ['aarch64', 'armv7hf'], ['aarch64', 'rpi'], ['armv7hf', 'rpi'], ].forEach(function ([deviceArch, appArch]) { it(`should return true when comparing ${deviceArch} and ${appArch} architectures`, () => expect(balena.models.os.isArchitectureCompatibleWith(deviceArch, appArch)).to.equal(true)); }); })); });
the_stack
export interface RawCompilerOptions { /** * No longer supported. In early versions, manually set the text encoding for reading files. */ charset?: string /** * Enable constraints that allow a TypeScript project to be used with project references. */ composite?: boolean /** * Generate .d.ts files from TypeScript and JavaScript files in your project. */ declaration?: boolean /** * Specify the output directory for generated declaration files. */ declarationDir?: string | null /** * Output compiler performance information after building. */ diagnostics?: boolean /** * Reduce the number of projects loaded automatically by TypeScript. */ disableReferencedProjectLoad?: boolean /** * Enforces using indexed accessors for keys declared using an indexed type */ noPropertyAccessFromIndexSignature?: boolean /** * Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ emitBOM?: boolean /** * Only output d.ts files and not JavaScript files. */ emitDeclarationOnly?: boolean /** * Save .tsbuildinfo files to allow for incremental compilation of projects. */ incremental?: boolean /** * Specify the folder for .tsbuildinfo incremental compilation files. */ tsBuildInfoFile?: string /** * Include sourcemap files inside the emitted JavaScript. */ inlineSourceMap?: boolean /** * Include source code in the sourcemaps inside the emitted JavaScript. */ inlineSources?: boolean /** * Specify what JSX code is generated. */ jsx?: 'preserve' | 'react' | 'react-jsx' | 'react-jsxdev' | 'react-native' /** * Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ reactNamespace?: string /** * Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ jsxFactory?: string /** * Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ jsxFragmentFactory?: string /** * Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ jsxImportSource?: string /** * Print all of the files read during the compilation. */ listFiles?: boolean /** * Specify the location where debugger should locate map files instead of generated locations. */ mapRoot?: string /** * Specify what module code is generated. */ module?: ('CommonJS' | 'AMD' | 'System' | 'UMD' | 'ES6' | 'ES2015' | 'ES2020' | 'ESNext' | 'None') | string /** * Specify how TypeScript looks up a file from a given module specifier. */ moduleResolution?: ('Classic' | 'Node') | string /** * Set the newline character for emitting files. */ newLine?: ('crlf' | 'lf') | string /** * Disable emitting file from a compilation. */ noEmit?: boolean /** * Disable generating custom helper functions like `__extends` in compiled output. */ noEmitHelpers?: boolean /** * Disable emitting files if any type checking errors are reported. */ noEmitOnError?: boolean /** * Enable error reporting for expressions and declarations with an implied `any` type.. */ noImplicitAny?: boolean /** * Enable error reporting when `this` is given the type `any`. */ noImplicitThis?: boolean /** * Enable error reporting when a local variables aren't read. */ noUnusedLocals?: boolean /** * Raise an error when a function parameter isn't read */ noUnusedParameters?: boolean /** * Disable including any library files, including the default lib.d.ts. */ noLib?: boolean /** * Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */ noResolve?: boolean /** * Disable strict checking of generic signatures in function types. */ noStrictGenericChecks?: boolean /** * Skip type checking .d.ts files that are included with TypeScript. */ skipDefaultLibCheck?: boolean /** * Skip type checking all .d.ts files. */ skipLibCheck?: boolean /** * Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ outFile?: string /** * Specify an output folder for all emitted files. */ outDir?: string /** * Disable erasing `const enum` declarations in generated code. */ preserveConstEnums?: boolean /** * Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ preserveSymlinks?: boolean /** * Disable wiping the console in watch mode */ preserveWatchOutput?: boolean /** * Enable color and formatting in output to make compiler errors easier to read */ pretty?: boolean /** * Disable emitting comments. */ removeComments?: boolean /** * Specify the root folder within your source files. */ rootDir?: string /** * Ensure that each file can be safely transpiled without relying on other imports. */ isolatedModules?: boolean /** * Create source map files for emitted JavaScript files. */ sourceMap?: boolean /** * Specify the root path for debuggers to find the reference source code. */ sourceRoot?: string /** * Disable reporting of excess property errors during the creation of object literals. */ suppressExcessPropertyErrors?: boolean /** * Suppress `noImplicitAny` errors when indexing objects that lack index signatures. */ suppressImplicitAnyIndexErrors?: boolean /** * Disable emitting declarations that have `@internal` in their JSDoc comments. */ stripInternal?: boolean /** * Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ target?: ('ES3' | 'ES5' | 'ES6' | 'ES2015' | 'ES2016' | 'ES2017' | 'ES2018' | 'ES2019' | 'ES2020' | 'ESNext') | string /** * Watch input files. */ watch?: boolean /** * Specify what approach the watcher should use if the system runs out of native file watchers. */ fallbackPolling?: 'fixedPollingInterval' | 'priorityPollingInterval' | 'dynamicPriorityPolling' /** * Specify how directories are watched on systems that lack recursive file-watching functionality. */ watchDirectory?: 'useFsEvents' | 'fixedPollingInterval' | 'dynamicPriorityPolling' /** * Specify how the TypeScript watch mode works. */ watchFile?: | 'fixedPollingInterval' | 'priorityPollingInterval' | 'dynamicPriorityPolling' | 'useFsEvents' | 'useFsEventsOnParentDirectory' /** * Enable experimental support for TC39 stage 2 draft decorators. */ experimentalDecorators?: boolean /** * Emit design-type metadata for decorated declarations in source files. */ emitDecoratorMetadata?: boolean /** * Disable error reporting for unused labels. */ allowUnusedLabels?: boolean /** * Enable error reporting for codepaths that do not explicitly return in a function. */ noImplicitReturns?: boolean /** * Add `undefined` to a type when accessed using an index. */ noUncheckedIndexedAccess?: boolean /** * Enable error reporting for fallthrough cases in switch statements. */ noFallthroughCasesInSwitch?: boolean /** * Disable error reporting for unreachable code. */ allowUnreachableCode?: boolean /** * Ensure that casing is correct in imports. */ forceConsistentCasingInFileNames?: boolean /** * Emit a v8 CPU profile of the compiler run for debugging. */ generateCpuProfile?: string /** * Specify the base directory to resolve non-relative module names. */ baseUrl?: string /** * Specify a set of entries that re-map imports to additional lookup locations. */ paths?: { [k: string]: string[] } /** * Specify a list of language service plugins to include. */ plugins?: Array<{ /** * Plugin name. */ name?: string [k: string]: unknown }> /** * Allow multiple folders to be treated as one when resolving modules. */ rootDirs?: string[] /** * Specify multiple folders that act like `./node_modules/@types`. */ typeRoots?: string[] /** * Specify type package names to be included without being referenced in a source file. */ types?: string[] /** * Log paths used during the `moduleResolution` process. */ traceResolution?: boolean /** * Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ allowJs?: boolean /** * Disable truncating types in error messages. */ noErrorTruncation?: boolean /** * Allow 'import x from y' when a module doesn't have a default export. */ allowSyntheticDefaultImports?: boolean /** * Disable adding 'use strict' directives in emitted JavaScript files. */ noImplicitUseStrict?: boolean /** * Print the names of emitted files after a compilation. */ listEmittedFiles?: boolean /** * Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server. */ disableSizeLimit?: boolean /** * Specify a set of bundled library declaration files that describe the target runtime environment. */ lib?: Array< | ( | 'ES5' | 'ES6' | 'ES2015' | 'ES2015.Collection' | 'ES2015.Core' | 'ES2015.Generator' | 'ES2015.Iterable' | 'ES2015.Promise' | 'ES2015.Proxy' | 'ES2015.Reflect' | 'ES2015.Symbol.WellKnown' | 'ES2015.Symbol' | 'ES2016' | 'ES2016.Array.Include' | 'ES2017' | 'ES2017.Intl' | 'ES2017.Object' | 'ES2017.SharedMemory' | 'ES2017.String' | 'ES2017.TypedArrays' | 'ES2018' | 'ES2018.AsyncGenerator' | 'ES2018.AsyncIterable' | 'ES2018.Intl' | 'ES2018.Promise' | 'ES2018.Regexp' | 'ES2019' | 'ES2019.Array' | 'ES2019.Object' | 'ES2019.String' | 'ES2019.Symbol' | 'ES2020' | 'ES2020.BigInt' | 'ES2020.Promise' | 'ES2020.String' | 'ES2020.Symbol.WellKnown' | 'ESNext' | 'ESNext.Array' | 'ESNext.AsyncIterable' | 'ESNext.BigInt' | 'ESNext.Intl' | 'ESNext.Promise' | 'ESNext.String' | 'ESNext.Symbol' | 'DOM' | 'DOM.Iterable' | 'ScriptHost' | 'WebWorker' | 'WebWorker.ImportScripts' ) | string > /** * When type checking, take into account `null` and `undefined`. */ strictNullChecks?: boolean /** * Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ maxNodeModuleJsDepth?: number /** * Allow importing helper functions from tslib once per project, instead of including them per-file. */ importHelpers?: boolean /** * Specify emit/checking behavior for imports that are only used for types. */ importsNotUsedAsValues?: 'remove' | 'preserve' | 'error' /** * Ensure 'use strict' is always emitted. */ alwaysStrict?: boolean /** * Enable all strict type checking options. */ strict?: boolean /** * Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ strictBindCallApply?: boolean /** * Emit more compliant, but verbose and less performant JavaScript for iteration. */ downlevelIteration?: boolean /** * Enable error reporting in type-checked JavaScript files. */ checkJs?: boolean /** * When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ strictFunctionTypes?: boolean /** * Check for class properties that are declared but not set in the constructor. */ strictPropertyInitialization?: boolean /** * Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ esModuleInterop?: boolean /** * Allow accessing UMD globals from modules. */ allowUmdGlobalAccess?: boolean /** * Make keyof only return strings instead of string, numbers or symbols. Legacy option. */ keyofStringsOnly?: boolean /** * Emit ECMAScript-standard-compliant class fields. */ useDefineForClassFields?: boolean /** * Create sourcemaps for d.ts files. */ declarationMap?: boolean /** * Enable importing .json files */ resolveJsonModule?: boolean /** * Have recompiles in projects that use `incremental` and `watch` mode assume that changes within a file will only affect files directly depending on it. */ assumeChangesOnlyAffectDirectDependencies?: boolean /** * Output more detailed compiler performance information after building. */ extendedDiagnostics?: boolean /** * Print names of files that are part of the compilation and then stop processing. */ listFilesOnly?: boolean /** * Disable preferring source files instead of declaration files when referencing composite projects */ disableSourceOfProjectReferenceRedirect?: boolean /** * Opt a project out of multi-project reference checking when editing. */ disableSolutionSearching?: boolean [k: string]: unknown }
the_stack
namespace MakerJs.layout { /** * @private */ interface IChildPlacement { childId: string; xRatio: number; origin?: IPoint; angle?: number; } /** * @private */ function getChildPlacement(parentModel: IModel, baseline: number) { //measure everything and cache the results var atlas = new measure.Atlas(parentModel); var measureParent = measure.modelExtents(parentModel, atlas); //measure height of the model from the baseline 0 var parentTop = measureParent.high[1]; var cpa: IChildPlacement[] = []; var xMap: { [childId: string]: number } = {}; var walkOptions: IWalkOptions = { beforeChildWalk: function (context: IWalkModel) { var child = context.childModel; //get cached measurement of the child var m = atlas.modelMap[context.routeKey]; if (!m) return; var childMeasure = measure.augment(m); //set a new origin at the x-center and y-baseline of the child model.originate(child, [childMeasure.center[0], parentTop * baseline]); //get the x-center of the child var x = child.origin[0] - measureParent.low[0]; xMap[context.childId] = x; //get the x-center of the child as a percentage var xRatio = x / measureParent.width; cpa.push({ childId: context.childId, xRatio }); //do not walk the grandchildren. This is only for immediate children of the parentModel. return false; } }; model.walk(parentModel, walkOptions); cpa.sort((a, b) => a.xRatio - b.xRatio); var first = cpa[0]; var last = cpa[cpa.length - 1]; var min = first.xRatio; var max = last.xRatio; var span = max - min; cpa.forEach(cp => cp.xRatio = (cp.xRatio - min) / span); return { cpa, firstX: xMap[first.childId], lastX: measureParent.width - xMap[last.childId] }; } /** * @private */ function moveAndRotate(parentModel: IModel, cpa: IChildPlacement[], rotate: boolean) { cpa.forEach(cp => { var child = parentModel.models[cp.childId]; //move the child to the new location child.origin = cp.origin; //rotate the child if (rotate) model.rotate(child, cp.angle, cp.origin); }); } /** * @private */ var onPathMap: { [pathType: string]: (onPath: IPath, reversed: boolean, cpa: IChildPlacement[]) => void } = {}; onPathMap[pathType.Arc] = function (arc: IPathArc, reversed: boolean, cpa: IChildPlacement[]) { var arcSpan = angle.ofArcSpan(arc); cpa.forEach(p => p.angle = reversed ? arc.endAngle - p.xRatio * arcSpan - 90 : arc.startAngle + p.xRatio * arcSpan + 90); }; onPathMap[pathType.Line] = function (line: IPathLine, reversed: boolean, cpa: IChildPlacement[]) { var lineAngle = angle.ofLineInDegrees(line as IPathLine); cpa.forEach(p => p.angle = lineAngle); }; /** * Layout the children of a model along a path. * The x-position of each child will be projected onto the path so that the proportion between children is maintained. * Each child will be rotated such that it will be perpendicular to the path at the child's x-center. * * @param parentModel The model containing children to lay out. * @param onPath The path on which to lay out. * @param baseline Numeric percentage value of vertical displacement from the path. Default is zero. * @param reversed Flag to travel along the path in reverse. Default is false. * @param contain Flag to contain the children layout within the length of the path. Default is false. * @param rotate Flag to rotate the child to perpendicular. Default is true. * @returns The parentModel, for cascading. */ export function childrenOnPath(parentModel: IModel, onPath: IPath, baseline = 0, reversed = false, contain = false, rotate = true) { var result = getChildPlacement(parentModel, baseline); var cpa = result.cpa; var chosenPath = onPath; if (contain) { //see if we need to clip var onPathLength = measure.pathLength(onPath); if (result.firstX + result.lastX < onPathLength) { chosenPath = path.clone(onPath); path.alterLength(chosenPath, -result.firstX, true); path.alterLength(chosenPath, -result.lastX); } } cpa.forEach(p => p.origin = point.middle(chosenPath, reversed ? 1 - p.xRatio : p.xRatio)); var fn = onPathMap[chosenPath.type]; if (fn) { fn(chosenPath, reversed, cpa); } moveAndRotate(parentModel, cpa, rotate); return parentModel; } /** * @private */ function miterAngles(points: IPoint[], offsetAngle: number): number[] { var arc = new paths.Arc([0, 0], 0, 0, 0); return points.map((p, i) => { var a: number; if (i === 0) { a = angle.ofPointInDegrees(p, points[i + 1]) + 90; } else if (i === points.length - 1) { a = angle.ofPointInDegrees(points[i - 1], p) + 90; } else { arc.origin = p; arc.startAngle = angle.ofPointInDegrees(p, points[i + 1]); arc.endAngle = angle.ofPointInDegrees(p, points[i - 1]); a = angle.ofArcMiddle(arc); } return a + offsetAngle; }); } /** * Layout the children of a model along a chain. * The x-position of each child will be projected onto the chain so that the proportion between children is maintained. * The projected positions of the children will become an array of points that approximate the chain. * Each child will be rotated such that it will be mitered according to the vertex angles formed by this series of points. * * @param parentModel The model containing children to lay out. * @param onChain The chain on which to lay out. * @param baseline Numeric percentage value of vertical displacement from the chain. Default is zero. * @param reversed Flag to travel along the chain in reverse. Default is false. * @param contain Flag to contain the children layout within the length of the chain. Default is false. * @param rotate Flag to rotate the child to mitered angle. Default is true. * @returns The parentModel, for cascading. */ export function childrenOnChain(parentModel: IModel, onChain: IChain, baseline = 0, reversed = false, contain = false, rotated = true) { var result = getChildPlacement(parentModel, baseline); var cpa = result.cpa; var chainLength = onChain.pathLength; if (contain) chainLength -= result.firstX + result.lastX; var absolutes = cpa.map(cp => (reversed ? 1 - cp.xRatio : cp.xRatio) * chainLength); var relatives: number[]; if (reversed) absolutes.reverse(); relatives = absolutes.map((ab, i) => Math.abs(ab - (i == 0 ? 0 : absolutes[i - 1]))); if (contain) { relatives[0] += reversed ? result.lastX : result.firstX; } else { relatives.shift(); } //chain.toPoints always follows the chain in its order, from beginning to end. This is why we needed to contort the points input var points = chain.toPoints(onChain, relatives); if (points.length < cpa.length) { //add last point of chain, since our distances exceeded the chain var endLink = onChain.links[onChain.links.length - 1]; points.push(endLink.endPoints[endLink.reversed ? 0 : 1]); } if (contain) points.shift(); //delete the first point which is the beginning of the chain if (reversed) points.reverse(); var angles = miterAngles(points, -90); cpa.forEach((cp, i) => { cp.angle = angles[i]; cp.origin = points[i]; }); moveAndRotate(parentModel, cpa, rotated); return parentModel; } /** * Layout clones in a radial format. * * Example: * ``` * //daisy petals * var makerjs = require('makerjs'); * * var belt = new makerjs.models.Belt(5, 50, 20); * * makerjs.model.move(belt, [25, 0]); * * var petals = makerjs.layout.cloneToRadial(belt, 8, 45); * * document.write(makerjs.exporter.toSVG(petals)); * ``` * * @param itemToClone: Either a model or a path object. * @param count Number of clones in the radial result. * @param angleInDegrees angle of rotation between clones.. * @returns A new model with clones in a radial format. */ export function cloneToRadial(itemToClone: IModel | IPath, count: number, angleInDegrees: number, rotationOrigin?: IPoint) { var result: IModel = {}; var add: IPathMap | IModelMap; var rotateFn: (x: IModel | IPath, angleInDegrees: number, rotationOrigin?: IPoint) => IModel | IPath; if (isModel(itemToClone)) { add = result.models = {}; rotateFn = model.rotate; } else { add = result.paths = {}; rotateFn = path.rotate; } for (var i = 0; i < count; i++) { add[i] = rotateFn(cloneObject(itemToClone), i * angleInDegrees, rotationOrigin); } return result; } /** * @private */ function cloneTo(dimension: number, itemToClone: IModel | IPath, count: number, margin: number): IModel { var result: IModel = {}; var add: IPathMap | IModelMap; var measureFn: (x: IModel | IPath) => IMeasure; var moveFn: (x: IModel | IPath, origin: IPoint) => IModel | IPath; if (isModel(itemToClone)) { measureFn = measure.modelExtents; add = result.models = {}; moveFn = model.move; } else { measureFn = measure.pathExtents; add = result.paths = {}; moveFn = path.move; } var m = measureFn(itemToClone); var size = m.high[dimension] - m.low[dimension]; for (var i = 0; i < count; i++) { var origin: IPoint = [0, 0]; origin[dimension] = i * (size + margin); add[i] = moveFn(cloneObject(itemToClone), origin); } return result; } /** * Layout clones in a column format. * * Example: * ``` * //Grooves for a finger joint * var m = require('makerjs'); * * var dogbone = new m.models.Dogbone(50, 20, 2, -1, false); * * var grooves = m.layout.cloneToColumn(dogbone, 5, 20); * * document.write(m.exporter.toSVG(grooves)); * ``` * * @param itemToClone: Either a model or a path object. * @param count Number of clones in the column. * @param margin Optional distance between each clone. * @returns A new model with clones in a column. */ export function cloneToColumn(itemToClone: IModel | IPath, count: number, margin = 0): IModel { return cloneTo(1, itemToClone, count, margin); } /** * Layout clones in a row format. * * Example: * ``` * //Tongue and grooves for a box joint * var m = require('makerjs'); * var tongueWidth = 60; * var grooveWidth = 50; * var grooveDepth = 30; * var groove = new m.models.Dogbone(grooveWidth, grooveDepth, 5, 0, true); * * groove.paths['leftTongue'] = new m.paths.Line([-tongueWidth / 2, 0], [0, 0]); * groove.paths['rightTongue'] = new m.paths.Line([grooveWidth, 0], [grooveWidth + tongueWidth / 2, 0]); * * var tongueAndGrooves = m.layout.cloneToRow(groove, 3); * * document.write(m.exporter.toSVG(tongueAndGrooves)); * ``` * * @param itemToClone: Either a model or a path object. * @param count Number of clones in the row. * @param margin Optional distance between each clone. * @returns A new model with clones in a row. */ export function cloneToRow(itemToClone: IModel | IPath, count: number, margin = 0): IModel { return cloneTo(0, itemToClone, count, margin); } /** * Layout clones in a grid format. * * Example: * ``` * //Grid of squares * var m = require('makerjs'); * var square = new m.models.Square(43); * var grid = m.layout.cloneToGrid(square, 5, 5, 7); * document.write(m.exporter.toSVG(grid)); * ``` * * @param itemToClone: Either a model or a path object. * @param xCount Number of columns in the grid. * @param yCount Number of rows in the grid. * @param margin Optional numeric distance between each clone. Can also be a 2 dimensional array of numbers, to specify distances in x and y dimensions. * @returns A new model with clones in a grid layout. */ export function cloneToGrid(itemToClone: IModel | IPath, xCount: number, yCount: number, margin?: number | IPoint): IModel { var margins = getMargins(margin); return cloneToColumn(cloneToRow(itemToClone, xCount, margins[0]), yCount, margins[1]); } /** * @private */ function getMargins(margin?: number | IPoint): IPoint { if (Array.isArray(margin)) { return margin; } else { return [margin as number, margin as number]; } } /** * @private */ interface IGridSpacing { x: number; y: number; xMargin: number; } /** * @private */ function cloneToAlternatingRows(itemToClone: IModel | IPath, xCount: number, yCount: number, spacingFn: (modelToMeasure: IModel) => IGridSpacing): IModel { var modelToMeasure: IModel; if (isModel(itemToClone)) { modelToMeasure = itemToClone; } else { modelToMeasure = { paths: { "0": itemToClone as IPath } }; } var spacing = spacingFn(modelToMeasure); var result: IModel = { models: {} }; for (var i = 0; i < yCount; i++) { var i2 = i % 2; result.models[i] = model.move(cloneToRow(itemToClone, xCount + i2, spacing.xMargin), [i2 * spacing.x, i * spacing.y]); } return result; } /** * Layout clones in a brick format. Alternating rows will have an additional item in each row. * * Examples: * ``` * //Brick wall * var m = require('makerjs'); * var brick = new m.models.RoundRectangle(50, 30, 4); * var wall = m.layout.cloneToBrick(brick, 8, 6, 3); * document.write(m.exporter.toSVG(wall)); * ``` * * ``` * //Fish scales * var m = require('makerjs'); * var arc = new m.paths.Arc([0, 0], 50, 20, 160); * var scales = m.layout.cloneToBrick(arc, 8, 20); * document.write(m.exporter.toSVG(scales)); * ``` * * @param itemToClone: Either a model or a path object. * @param xCount Number of columns in the brick grid. * @param yCount Number of rows in the brick grid. * @param margin Optional numeric distance between each clone. Can also be a 2 dimensional array of numbers, to specify distances in x and y dimensions. * @returns A new model with clones in a brick layout. */ export function cloneToBrick(itemToClone: IModel | IPath, xCount: number, yCount: number, margin?: number | IPoint): IModel { var margins = getMargins(margin); function spacing(modelToMeasure: IModel): IGridSpacing { var m = measure.modelExtents(modelToMeasure); var xMargin = margins[0] || 0; var yMargin = margins[1] || 0; return { x: (m.width + xMargin) / -2, y: m.height + yMargin, xMargin: xMargin }; } return cloneToAlternatingRows(itemToClone, xCount, yCount, spacing); } /** * Layout clones in a honeycomb format. Alternating rows will have an additional item in each row. * * Examples: * ``` * //Honeycomb * var m = require('makerjs'); * var hex = new m.models.Polygon(6, 50, 30); * var pattern = m.layout.cloneToHoneycomb(hex, 8, 9, 10); * document.write(m.exporter.toSVG(pattern)); * ``` * * @param itemToClone: Either a model or a path object. * @param xCount Number of columns in the honeycomb grid. * @param yCount Number of rows in the honeycomb grid. * @param margin Optional distance between each clone. * @returns A new model with clones in a honeycomb layout. */ export function cloneToHoneycomb(itemToClone: IModel | IPath, xCount: number, yCount: number, margin = 0): IModel { function spacing(modelToMeasure: IModel): IGridSpacing { var hex = measure.boundingHexagon(modelToMeasure); var width = 2 * solvers.equilateralAltitude(hex.radius); var s = width + margin; return { x: s / -2, y: solvers.equilateralAltitude(s), xMargin: margin }; } return cloneToAlternatingRows(itemToClone, xCount, yCount, spacing); } }
the_stack
/* eslint-disable @typescript-eslint/no-floating-promises */ import * as crypto from 'crypto' import { handlePasswordEntry } from '../background' import { hashPasswordWithSalt } from '../lib/generateHash' import { getPasswordHashes, checkStoredHashes, hashAndSavePassword, removeHash } from '../lib/userInfo' import { setConfigOverride } from '../config' import { PasswordContent, PasswordHandlingReturnValue } from '../types' import { getHashDataIfItExists, checkForExistingAccount } from '../lib/userInfo' import { getHostFromUrl } from '../lib/getHostFromUrl' Object.defineProperty(global.self, 'crypto', { value: { getRandomValues: (arr: any) => crypto.randomBytes(arr.length), }, }) const salt = '0000000000000000000000000000000000' const passwordOne = 'passwordOne' const passwordTwo = 'passwordTwo' const emojiPassword = '🌔🙉🐵🐬🎄🌝💦💧🍃🌻🌹🌹🌷🐀🐴🦄' const enterpriseDomain = 'corporate.com' const enterpriseUrl = 'http://corporate.com/login' const ignoredDomain = 'ignored.com' const ignoredUrl = 'http://ignored.com/bar' const evilUrl = 'http://evil.com/foo' describe('Password hashing should work', () => { it('A password should always hash to the same value (given the salt is the same)', async () => { await setConfigOverride({ enterprise_domains: [enterpriseDomain], phishcatch_server: '', psk: '', data_expiry: 90, display_reuse_alerts: false, ignored_domains: [ignoredDomain], pbkdf2_iterations: 100000, expire_hash_on_use: false, }) const firstHash = await hashPasswordWithSalt(passwordOne, salt) expect(firstHash.hash).toEqual( '64784cee716bd764a8ca4c51ee4a931d33ab7d2a38ae80ce675c70571f44724b7d8837b2b2f3c9d1f77923a193e0a0ff38dfeaca706e10554fe08afb4caeb519', ) }) it('If the salt is different, the resulting hash should be too', async () => { const firstHash = await hashPasswordWithSalt(passwordOne, salt) const secondHash = await hashPasswordWithSalt(passwordOne, '11111111111111111111111111111111111111') expect(firstHash.hash).not.toEqual(secondHash.hash) }) it('A different string should not produce the same hash', async () => { const firstHash = await hashPasswordWithSalt(passwordOne, salt) const secondHash = await hashPasswordWithSalt(passwordTwo, salt) expect(firstHash.hash).not.toEqual(secondHash.hash) }) it('Weird strings should produce correct hashes', async () => { expect((await hashPasswordWithSalt('', salt)).hash).toEqual( '544a34746c7a2c739b0b970dce127cd8f7f21d2ca51bc765968c5dcb5c823fe7e15e3d772e8952b6da87a84be2ca4cbe6696da02300e1f45c601b03ff89dc814', ) expect((await hashPasswordWithSalt('sometext🌖🌕🌕🌕🌕', salt)).hash).toEqual( '5c1cf476936f512c75577679e6dab6f82bc8de341a9c441f1771ac30871d6dcf22141c49d6d80958e831a5968f9fc064b743ae1c4e54433649693c72d99aecb4', ) expect((await hashPasswordWithSalt(emojiPassword, salt)).hash).toEqual( '665547b2e1f90874099531c891772677a753e1c50e1b9b28bf4fefd74d22222d3e750659275a83d31bac2a5942ed164c9e23dd0764b39fe09d9775fa582ed636', ) }) it('Passing a bad salt should cause an error', () => { expect(hashPasswordWithSalt(passwordOne, '')).rejects.toEqual('No/bad salt! This is unsafe.') expect(hashPasswordWithSalt(passwordOne, 'too short')).rejects.toEqual('No/bad salt! This is unsafe.') }) it('Changing the number of iterations should produce a different result', async () => { await setConfigOverride({ enterprise_domains: [enterpriseDomain], phishcatch_server: '', psk: '', data_expiry: 90, display_reuse_alerts: false, ignored_domains: [ignoredDomain], pbkdf2_iterations: 100, }) const firstHash = await hashPasswordWithSalt(passwordOne, salt) expect(firstHash.hash).not.toEqual( '64784cee716bd764a8ca4c51ee4a931d33ab7d2a38ae80ce675c70571f44724b7d8837b2b2f3c9d1f77923a193e0a0ff38dfeaca706e10554fe08afb4caeb519', ) }) }) describe('Hash saving/checking should work', () => { it('Password hash saving should work', async () => { await hashAndSavePassword(passwordOne, 'username1', 'hostname.com') const hashes = await getPasswordHashes() expect(hashes.length).toEqual(1) expect(typeof hashes[0].dateAdded).toEqual('number') expect(typeof hashes[0].salt).toEqual('string') expect(hashes[0].salt.length).toBeGreaterThan(10) expect(hashes[0].username).toEqual('username1') expect(hashes[0].hostname).toEqual('hostname.com') }) it('We should be able to see if a hash matches a password', async () => { const passwordOneExists = await checkStoredHashes(passwordOne) const passwordTwoExists = await checkStoredHashes(passwordTwo) expect(passwordOneExists.hashExists).toEqual(true) expect(passwordTwoExists.hashExists).toEqual(false) }) it("The same password shouldn't result in a new hash", async () => { let hashes = await getPasswordHashes() expect(hashes.length).toEqual(1) await hashAndSavePassword(passwordOne) await hashAndSavePassword(passwordOne) hashes = await getPasswordHashes() expect(hashes.length).toEqual(1) }) it('Saving the same password should update the associated metadata', async (callback) => { let hashes = await getPasswordHashes() const oldHashTimestamp = hashes[0].dateAdded // eslint-disable-next-line @typescript-eslint/no-misused-promises setTimeout(async () => { await hashAndSavePassword(passwordOne, 'username2', 'anotherhostname.com') hashes = await getPasswordHashes() expect(hashes[0].dateAdded).toBeGreaterThan(oldHashTimestamp) expect(hashes[0].username).toEqual('username2') expect(hashes[0].hostname).toEqual('anotherhostname.com') callback() }, 100) }) it('Checking for an existing account works', async () => { const hashes = await getPasswordHashes() let hashIndex = checkForExistingAccount(hashes, 'username2', 'anotherhostname.com') expect(hashIndex).toEqual(0) hashIndex = checkForExistingAccount(hashes, 'no such user', 'no such hostname') expect(hashIndex).toEqual(-1) }) it('A new password with the same username and hostname should replace the old one', async () => { let hashes = await getPasswordHashes() expect(hashes.length).toEqual(1) const oldHash = hashes[0] await hashAndSavePassword('ejfowefowfjwefnwefjnjknkjrnnewru', 'username2', 'anotherhostname.com') hashes = await getPasswordHashes() expect(hashes.length).toEqual(1) const newHash = hashes[0] expect(oldHash.hash !== newHash.hash) expect(oldHash.dateAdded !== newHash.dateAdded) expect(oldHash.username === newHash.username) expect(oldHash.hostname === newHash.hostname) expect(oldHash.salt === newHash.salt) await hashAndSavePassword(passwordOne, 'username2', 'anotherhostname.com') expect(hashes.length).toEqual(1) const newNewHash = hashes[0] expect(oldHash.hash === newNewHash.hash) expect(oldHash.dateAdded !== newNewHash.dateAdded) expect(oldHash.username === newNewHash.username) expect(oldHash.hostname === newNewHash.hostname) expect(oldHash.salt !== newNewHash.salt) }) it('A different password should result in a new hash', async () => { await hashAndSavePassword(passwordTwo) const hashes = await getPasswordHashes() expect(hashes.length).toEqual(2) }) it('Saving and checking multiple passwords should work', async () => { await hashAndSavePassword('jkfkefejf', 'eijijefe', 'kejfjef') await hashAndSavePassword('passwordTwo') await hashAndSavePassword('oejflkwnefk.newfknwekfjnkwenfkjew') expect((await checkStoredHashes('jkfkefejf')).hashExists).toEqual(true) expect((await checkStoredHashes('passwordTwo')).hashExists).toEqual(true) expect((await checkStoredHashes('oejflkwnefk.newfknwekfjnkwenfkjew')).hashExists).toEqual(true) }) it('We should be able to get hash data by passing a password', async () => { const passwordOneData = await getHashDataIfItExists(passwordOne) if (!passwordOneData) throw 'no data' expect(typeof passwordOneData.dateAdded).toEqual('number') expect(typeof passwordOneData.salt).toEqual('string') expect(passwordOneData.salt.length).toBeGreaterThan(10) expect(passwordOneData.username).toEqual('username2') expect(passwordOneData.hostname).toEqual('anotherhostname.com') }) it('Saving and checking weird passwords should work', async () => { await hashAndSavePassword(emojiPassword) expect((await checkStoredHashes(emojiPassword)).hashExists).toEqual(true) }) it('Storage should not contain plaintext passwords', (done) => { const hashArray = [passwordOne, passwordTwo, emojiPassword] chrome.storage.local.get(null, (data) => { const hashStorageString = JSON.stringify(data) const hashStorageContainsPassword = hashArray.reduce((previousValue, currentValue) => { if (previousValue === true) { return true } return hashStorageString.includes(currentValue) }, false) expect(hashStorageContainsPassword).toEqual(false) done() }) }) it('Removing passwords should work', async () => { await hashAndSavePassword(emojiPassword) await hashAndSavePassword('pwekeofj') const hash1Details = await checkStoredHashes(emojiPassword) const hash2Details = await checkStoredHashes('pwekeofj') expect(hash1Details.hashExists).toEqual(true) expect(hash2Details.hashExists).toEqual(true) await removeHash(hash1Details.hash.hash) await removeHash(hash2Details.hash.hash) expect((await checkStoredHashes(emojiPassword)).hashExists).toEqual(false) expect((await checkStoredHashes('pwekeofj')).hashExists).toEqual(false) }) }) describe('Password message handling works as expected', () => { const passwordToBeSaved = 'somerandomtext' it('Saving enterprise passwords should work', async () => { const message: PasswordContent = { password: passwordToBeSaved, save: true, url: enterpriseUrl, referrer: "doesn't matter", timestamp: new Date().getTime(), username: 'exampleUsername', } expect(await handlePasswordEntry(message)).toEqual(PasswordHandlingReturnValue.EnterpriseSave) expect((await checkStoredHashes(passwordToBeSaved)).hashExists).toEqual(true) const passwordOneData = await getHashDataIfItExists(passwordToBeSaved) if (!passwordOneData) throw 'no data' expect(passwordOneData.username).toEqual('exampleUsername') expect(passwordOneData.hostname).toEqual(getHostFromUrl(enterpriseUrl)) }) it('Not saving enterprise passwords should work', async () => { const message: PasswordContent = { password: 'someotherrandomtext', save: false, url: enterpriseUrl, referrer: "doesn't matter", timestamp: new Date().getTime(), username: 'whocares', } expect(await handlePasswordEntry(message)).toEqual(PasswordHandlingReturnValue.EnterpriseNoSave) expect((await checkStoredHashes('someotherrandomtext')).hashExists).toEqual(false) }) it('Reused passwords should alert', async () => { const message: PasswordContent = { password: passwordToBeSaved, save: false, url: evilUrl, referrer: 'doesntmatter.com', timestamp: new Date().getTime(), username: 'exampleUsername', } expect((await checkStoredHashes(passwordToBeSaved)).hashExists).toEqual(true) expect(await handlePasswordEntry(message)).toEqual(PasswordHandlingReturnValue.ReuseAlert) }) it('Ignored domains should not alert even if password is reused', async () => { const message: PasswordContent = { password: passwordToBeSaved, save: false, url: ignoredUrl, referrer: 'doesntmatter.com', timestamp: new Date().getTime(), username: 'exampleUsername', } expect(await handlePasswordEntry(message)).toEqual(PasswordHandlingReturnValue.IgnoredDomain) }) it('Non-Reused passwords should not alert', async () => { const message: PasswordContent = { password: 'non-reused-password', save: false, url: evilUrl, referrer: 'doesntmatter.com', timestamp: new Date().getTime(), username: 'exampleUsername', } expect(await handlePasswordEntry(message)).toEqual(PasswordHandlingReturnValue.NoReuse) }) it('Setting expire_hash_on_use should prevent passwords from alerting twice', async () => { await setConfigOverride({ enterprise_domains: [enterpriseDomain], phishcatch_server: '', psk: '', data_expiry: 90, display_reuse_alerts: false, ignored_domains: [ignoredDomain], pbkdf2_iterations: 100000, expire_hash_on_use: true, }) let message: PasswordContent = { password: passwordToBeSaved, save: true, url: enterpriseUrl, referrer: 'doesntmatter.com', timestamp: new Date().getTime(), username: 'exampleUsername', } expect(await handlePasswordEntry(message)).toEqual(PasswordHandlingReturnValue.EnterpriseSave) expect((await checkStoredHashes(passwordToBeSaved)).hashExists).toEqual(true) message = { password: passwordToBeSaved, save: false, url: evilUrl, referrer: 'doesntmatter.com', timestamp: new Date().getTime(), username: 'exampleUsername', } expect(await handlePasswordEntry(message)).toEqual(PasswordHandlingReturnValue.ReuseAlert) expect((await checkStoredHashes(passwordToBeSaved)).hashExists).toEqual(false) }) }) describe('Password hash truncation works', () => { beforeAll(async () => { await setConfigOverride({ enterprise_domains: [enterpriseDomain], phishcatch_server: '', psk: '', data_expiry: 90, display_reuse_alerts: false, ignored_domains: [ignoredDomain], pbkdf2_iterations: 100000, hash_truncation_amount: 10, }) }) it('Truncating password hashes should work', async () => { const firstHash = await hashPasswordWithSalt(passwordOne, salt) expect(firstHash.hash).toEqual( '64784cee716bd764a8ca4c51ee4a931d33ab7d2a38ae80ce675c70571f44724b7d8837b2b2f3c9d1f77923a193e0a0ff38dfeaca706e10554fe08a', ) }) it('Saving and checking multiple passwords should work', async () => { await hashAndSavePassword('lkef', 'powekfpokr98', 'oiejf9237') await hashAndSavePassword('4j2r903jfioemf') await hashAndSavePassword('oemfoemfiwe.x.d,<<<') expect((await checkStoredHashes('lkef')).hashExists).toEqual(true) expect((await checkStoredHashes('4j2r903jfioemf')).hashExists).toEqual(true) expect((await checkStoredHashes('oemfoemfiwe.x.d,<<<')).hashExists).toEqual(true) }) it('Saving and checking weird passwords should work', async () => { await hashAndSavePassword(emojiPassword) expect((await checkStoredHashes(emojiPassword)).hashExists).toEqual(true) }) })
the_stack
function chain() { var name: string = "John"; var result: IQueryResponse = __.chain() .filter(function (doc: any) { return doc.name == name; }) .map(function (doc: any) { return { name: doc.name, age: doc.age }; }) .value(); if (!result.isAccepted) throw new Error("The call was not accepted"); } function filter() { // Example 1: get documents(people) with age < 30. var result: IQueryResponse = __.filter(function (doc: any) { return doc.age < 30; }); if (!result.isAccepted) throw new Error("The call was not accepted"); // Example 2: get documents (people) with age < 30 and select only name. var result: IQueryResponse = __.chain() .filter(function (doc: any) { return doc.age < 30; }) .pluck("name") .value(); if (!result.isAccepted) throw new Error("The call was not accepted"); // Example 3: get document (person) with id = 1 and delete it. var result: IQueryResponse = __.filter( function (doc: any) { return doc.id === 1; }, function (err: IFeedCallbackError, feed: Array<any>, options: IFeedCallbackOptions) { if (err) throw err; if (!__.deleteDocument(feed[0].getSelfLink())) throw new Error("deleteDocument was not accepted"); }); if (!result.isAccepted) throw new Error("The call was not accepted"); } function flatten() { // Get documents (people) with age < 30, select tags (an array property) // and flatten the result into one array for all documents. var result: IQueryResponse = __.chain() .filter(function (doc: any) { return doc.age < 30; }) .map(function (doc: any) { return doc.tags; }) .flatten() .value(); if (!result.isAccepted) throw new Error("The call was not accepted"); } function map() { // Example 1: select only name and age for each document (person). var result: IQueryResponse = __.map(function (doc: any) { return { name: doc.name, age: doc.age }; }); if (!result.isAccepted) throw new Error("The call was not accepted"); // Example 2: select name and age for each document (person), and return only people with age < 30. var result: IQueryResponse = __.chain() .map(function (doc: any) { return { name: doc.name, age: doc.age }; }) .filter(function (doc: any) { return doc.age < 30; }) .value(); if (!result.isAccepted) throw new Error("The call was not accepted"); } function pluck() { // Get documents (people) with age < 30 and select only name. var result: IQueryResponse = __.chain() .filter(function (doc: any) { return doc.age < 30; }) .pluck("name") .value(); if (!result.isAccepted) throw new Error("The call was not accepted"); } function sortBy() { // Example 1: sort documents (people) by age var result: IQueryResponse = __.sortBy(function (doc: any) { return doc.age; }) if (!result.isAccepted) throw new Error("The call was not accepted"); // Example 2: sortBy in a chain by name var result: IQueryResponse = __.chain() .filter(function (doc: any) { return doc.age < 30; }) .sortBy(function (doc: any) { return doc.name; }) .value(); if (!result.isAccepted) throw new Error("The call was not accepted"); } function sortByDescending() { // Example 1: sort documents (people) by age in descending order var result: IQueryResponse = __.sortByDescending(function (doc: any) { return doc.age; }) if (!result.isAccepted) throw new Error("The call was not accepted"); // Example 2: sortBy in a chain by name in descending order var result: IQueryResponse = __.chain() .filter(function (doc: any) { return doc.age < 30; }) .sortByDescending(function (doc: any) { return doc.name; }) .value(); if (!result.isAccepted) throw new Error("The call was not accepted"); } function value() { // Example 1: use defaults: the result goes to the response body. var result: IQueryResponse = __.chain() .filter(function (doc: any) { return doc.name == "John"; }) .pluck("age") .value(); if (!result.isAccepted) throw new Error("The call was not accepted"); // Example 2: use options and callback. function usingOptionsAndCallback (continuationToken: string) { var result = __.chain() .filter(function (doc: any) { return doc.name == "John"; }) .pluck("age") .value({ continuation: continuationToken }, function (err: IFeedCallbackError, feed: Array<any>, options: IFeedCallbackOptions) { if (err) throw err; __.response.setBody({ result: feed, continuation: options.continuation }); }); if (!result.isAccepted) throw new Error("The call was not accepted"); } } // Samples taken from https://github.com/Azure/azure-documentdb-js-server/tree/master/samples /** * This script called as stored procedure to import lots of documents in one batch. * The script sets response body to the number of docs imported and is called multiple times * by the client until total number of docs desired by the client is imported. * @param {Object[]} docs - Array of documents to import. */ function bulkImport(docs: Array<Object>) { var collection: ICollection = getContext().getCollection(); var collectionLink: string = collection.getSelfLink(); // The count of imported docs, also used as current doc index. var count: number = 0; // Validate input. if (!docs) throw new Error("The array is undefined or null."); var docsLength: number = docs.length; if (docsLength == 0) { getContext().getResponse().setBody(0); return; } // Call the CRUD API to create a document. tryCreate(docs[count], callback); // Note that there are 2 exit conditions: // 1) The createDocument request was not accepted. // In this case the callback will not be called, we just call setBody and we are done. // 2) The callback was called docs.length times. // In this case all documents were created and we don't need to call tryCreate anymore. Just call setBody and we are done. function tryCreate(doc: Object, callback: (err: IRequestCallbackError, doc: Object, options: IRequestCallbackOptions) => void): void { var isAccepted = collection.createDocument(collectionLink, doc, callback); // If the request was accepted, callback will be called. // Otherwise report current count back to the client, // which will call the script again with remaining set of docs. // This condition will happen when this stored procedure has been running too long // and is about to get cancelled by the server. This will allow the calling client // to resume this batch from the point we got to before isAccepted was set to false if (!isAccepted) getContext().getResponse().setBody(count); } // This is called when collection.createDocument is done and the document has been persisted. function callback(err: IRequestCallbackError, doc: Object, options: IRequestCallbackOptions) { if (err) throw err; // One more document has been inserted, increment the count. count++; if (count >= docsLength) { // If we have created all documents, we are done. Just set the response. getContext().getResponse().setBody(count); } else { // Create next document. tryCreate(docs[count], callback); } } } /** * This is executed as stored procedure to count the number of docs in the collection. * To avoid script timeout on the server when there are lots of documents (100K+), the script executed in batches, * each batch counts docs to some number and returns continuation token. * The script is run multiple times, starting from empty continuation, * then using continuation returned by last invocation script until continuation returned by the script is null/empty string. * * @param {String} filterQuery - Optional filter for query (e.g. "SELECT * FROM docs WHERE docs.category = 'food'"). * @param {String} continuationToken - The continuation token passed by request, continue counting from this token. */ function count(filterQuery: string, continuationToken: string) { var collection: ICollection = getContext().getCollection(); var maxResult: number = 25; // MAX number of docs to process in one batch, when reached, return to client/request continuation. // intentionally set low to demonstrate the concept. This can be much higher. Try experimenting. // We've had it in to the high thousands before seeing the stored proceudre timing out. // The number of documents counted. var result: number = 0; tryQuery(continuationToken); // Helper method to check for max result and call query. function tryQuery(nextContinuationToken: string) { var responseOptions: Object = { continuation: nextContinuationToken, pageSize: maxResult }; // In case the server is running this script for long time/near timeout, it would return false, // in this case we set the response to current continuation token, // and the client will run this script again starting from this continuation. // When the client calls this script 1st time, is passes empty continuation token. if (result >= maxResult || !query(responseOptions)) { setBody(nextContinuationToken); } } function query(responseOptions: IFeedOptions) { // For empty query string, use readDocuments rather than queryDocuments -- it's faster as doesn't need to process the query. return (filterQuery && filterQuery.length) ? collection.queryDocuments(collection.getSelfLink(), filterQuery, responseOptions, onReadDocuments) : collection.readDocuments(collection.getSelfLink(), responseOptions, onReadDocuments); } // This is callback is called from collection.queryDocuments/readDocuments. function onReadDocuments(err: IFeedCallbackError, docFeed: Array<any>, responseOptions: IFeedCallbackOptions) { if (err) { throw 'Error while reading document: ' + err; } // Increament the number of documents counted so far. result += docFeed.length; // If there is continuation, call query again with it, // otherwise we are done, in which case set continuation to null. if (responseOptions.continuation) { tryQuery(responseOptions.continuation); } else { setBody(null); } } // Set response body: use an object the client is expecting (2 properties: result and continuationToken). function setBody(continuationToken: string) { var body: Object = { count: result, continuationToken: continuationToken }; getContext().getResponse().setBody(body); } } /** * This is run as stored procedure and does the following: * - get 1st document in the collection, convert to JSON, prepend string specified by the prefix parameter * and set response to the result of that. * * @param {String} prefix - The string to prepend to the 1st document in collection. */ function simple(prefix: string) { var collection: ICollection = getContext().getCollection(); // Query documents and take 1st item. var isAccepted: boolean = collection.queryDocuments( collection.getSelfLink(), 'SELECT * FROM root r', function (err: IFeedCallbackError, feed: Array<any>, options: IFeedCallbackOptions) { if (err) throw err; // Check the feed and if it's empty, set the body to 'no docs found', // Otherwise just take 1st element from the feed. if (!feed || !feed.length) getContext().getResponse().setBody("no docs found"); else getContext().getResponse().setBody(prefix + JSON.stringify(feed[0])); }); if (!isAccepted) throw new Error("The query wasn't accepted by the server. Try again/use continuation token between API and script."); } /** * A DocumentDB stored procedure that bulk deletes documents for a given query.<br/> * Note: You may need to execute this sproc multiple times (depending whether the sproc is able to delete every document within the execution timeout limit). * * @function * @param {string} query - A query that provides the documents to be deleted (e.g. "SELECT * FROM c WHERE c.founded_year = 2008") * @returns {Object.<number, boolean>} Returns an object with the two properties:<br/> * deleted - contains a count of documents deleted<br/> * continuation - a boolean whether you should execute the sproc again (true if there are more documents to delete; false otherwise). */ function bulkDeleteSproc(query: string) { var collection: ICollection = getContext().getCollection(); var collectionLink: string = collection.getSelfLink(); var response: IResponse = getContext().getResponse(); var responseBody: any = { deleted: 0, continuation: true }; // Validate input. if (!query) throw new Error("The query is undefined or null."); tryQueryAndDelete(); // Recursively runs the query w/ support for continuation tokens. // Calls tryDelete(documents) as soon as the query returns documents. function tryQueryAndDelete(continuation?: string) { var requestOptions: IFeedOptions = { continuation: continuation }; var isAccepted: boolean = collection.queryDocuments(collectionLink, query, requestOptions, function (err: IFeedCallbackError, retrievedDocs: Array<any>, responseOptions: IFeedCallbackOptions) { if (err) throw err; if (retrievedDocs.length > 0) { // Begin deleting documents as soon as documents are returned form the query results. // tryDelete() resumes querying after deleting; no need to page through continuation tokens. // - this is to prioritize writes over reads given timeout constraints. tryDelete(retrievedDocs); } else if (responseOptions.continuation) { // Else if the query came back empty, but with a continuation token; repeat the query w/ the token. tryQueryAndDelete(responseOptions.continuation); } else { // Else if there are no more documents and no continuation token - we are finished deleting documents. responseBody.continuation = false; response.setBody(responseBody); } }); // If we hit execution bounds - return continuation: true. if (!isAccepted) { response.setBody(responseBody); } } // Recursively deletes documents passed in as an array argument. // Attempts to query for more on empty array. function tryDelete(documents: Array<IDocumentMeta>) { if (documents.length > 0) { // Delete the first document in the array. var isAccepted: boolean = collection.deleteDocument(documents[0]._self, {}, function (err, responseOptions) { if (err) throw err; responseBody.deleted++; documents.shift(); // Delete the next document in the array. tryDelete(documents); }); // If we hit execution bounds - return continuation: true. if (!isAccepted) { response.setBody(responseBody); } } else { // If the document array is empty, query for more documents. tryQueryAndDelete(); } } } // NOTE: the sample `sum` stored procedure (https://github.com/Azure/azure-documentdb-js-server/blob/master/samples/stored-procedures/sum.js) does not currently work, because it appears to throw an invalid Error object. See https://github.com/Azure/azure-documentdb-js-server/issues/23 to track this issue. /** * A DocumentDB stored procedure that updates a document by id, using a similar syntax to MongoDB's update operator.<br/> * <br/> * The following operations are supported:<br/> * <br/> * Field Operators:<br/> * <ul> * <li>$inc - Increments the value of the field by the specified amount.</li> * <li>$mul - Multiplies the value of the field by the specified amount.</li> * <li>$rename - Renames a field.</li> * <li>$set - Sets the value of a field in a document.</li> * <li>$unset - Removes the specified field from a document.</li> * <li>$min - Only updates the field if the specified value is less than the existing field value.</li> * <li>$max - Only updates the field if the specified value is greater than the existing field value.</li> * <li>$currentDate - Sets the value of a field to current date as a Unix Epoch.</li> * </ul> * <br/> * Array Operators:<br/> * <ul> * <li>$addToSet - Adds elements to an array only if they do not already exist in the set.</li> * <li>$pop - Removes the first or last item of an array.</li> * <li>$push - Adds an item to an array.</li> * </ul> * <br/> * Note: Performing multiple operations on the same field may yield unexpected results.<br/> * * @example <caption>Increment the property "counter" by 1 in the document where id = "foo".</caption> * updateSproc("foo", {$inc: {counter: 1}}); * * @example <caption>Set the property "message" to "Hello World" and the "messageDate" to the current date in the document where id = "bar".</caption> * updateSproc("bar", {$set: {message: "Hello World"}, $currentDate: {messageDate: ""}}); * * @function * @param {string} id - The id for your document. * @param {object} update - the modifications to apply. * @returns {object} the updated document. */ function updateSproc(id: string, update: Object) { var collection: ICollection = getContext().getCollection(); var collectionLink: string = collection.getSelfLink(); var response: IResponse = getContext().getResponse(); // Validate input. if (!id) throw new Error("The id is undefined or null."); if (!update) throw new Error("The update is undefined or null."); tryQueryAndUpdate(); // Recursively queries for a document by id w/ support for continuation tokens. // Calls tryUpdate(document) as soon as the query returns a document. function tryQueryAndUpdate(continuation?: string) { var query: IParameterizedQuery = { query: "select * from root r where r.id = @id", parameters: [{ name: "@id", value: id }] }; var requestOptions: IFeedOptions = { continuation: continuation }; var isAccepted: boolean = collection.queryDocuments(collectionLink, query, requestOptions, function (err: IFeedCallbackError, documents: Array<any>, responseOptions: IFeedCallbackOptions) { if (err) throw err; if (documents.length > 0) { // If the document is found, update it. // There is no need to check for a continuation token since we are querying for a single document. tryUpdate(documents[0]); } else if (responseOptions.continuation) { // Else if the query came back empty, but with a continuation token; repeat the query w/ the token. // It is highly unlikely for this to happen when performing a query by id; but is included to serve as an example for larger queries. tryQueryAndUpdate(responseOptions.continuation); } else { // Else a document with the given id does not exist.. throw new Error("Document not found."); } }); // If we hit execution bounds - throw an exception. // This is highly unlikely given that this is a query by id; but is included to serve as an example for larger queries. if (!isAccepted) { throw new Error("The stored procedure timed out."); } } // Updates the supplied document according to the update object passed in to the sproc. function tryUpdate(document: IDocumentMeta) { // DocumentDB supports optimistic concurrency control via HTTP ETag. var requestOptions: IReplaceOptions = { etag: document._etag }; // Update operators. inc(document, update); mul(document, update); rename(document, update); set(document, update); unset(document, update); min(document, update); max(document, update); currentDate(document, update); addToSet(document, update); pop(document, update); push(document, update); // Update the document. var isAccepted: boolean = collection.replaceDocument(document._self, document, requestOptions, function (err, updatedDocument, responseOptions) { if (err) throw err; // If we have successfully updated the document - return it in the response body. response.setBody(updatedDocument); }); // If we hit execution bounds - throw an exception. if (!isAccepted) { throw new Error("The stored procedure timed out."); } } // Operator implementations. // The $inc operator increments the value of a field by a specified amount. function inc(document: any, update: any) { var fields: Array<string>, i: number; if (update.$inc) { fields = Object.keys(update.$inc); for (i = 0; i < fields.length; i++) { if (isNaN(update.$inc[fields[i]])) { // Validate the field; throw an exception if it is not a number (can't increment by NaN). throw new Error("Bad $inc parameter - value must be a number") } else if (document[fields[i]]) { // If the field exists, increment it by the given amount. document[fields[i]] += update.$inc[fields[i]]; } else { // Otherwise set the field to the given amount. document[fields[i]] = update.$inc[fields[i]]; } } } } // The $mul operator multiplies the value of the field by the specified amount. function mul(document: any, update: any) { var fields: Array<string>, i: number; if (update.$mul) { fields = Object.keys(update.$mul); for (i = 0; i < fields.length; i++) { if (isNaN(update.$mul[fields[i]])) { // Validate the field; throw an exception if it is not a number (can't multiply by NaN). throw new Error("Bad $mul parameter - value must be a number") } else if (document[fields[i]]) { // If the field exists, multiply it by the given amount. document[fields[i]] *= update.$mul[fields[i]]; } else { // Otherwise set the field to 0. document[fields[i]] = 0; } } } } // The $rename operator renames a field. function rename(document: any, update: any) { var fields: Array<string>, i: number, existingFieldName: string, newFieldName: string; if (update.$rename) { fields = Object.keys(update.$rename); for (i = 0; i < fields.length; i++) { existingFieldName = fields[i]; newFieldName = update.$rename[fields[i]]; if (existingFieldName == newFieldName) { throw new Error("Bad $rename parameter: The new field name must differ from the existing field name.") } else if (document[existingFieldName]) { // If the field exists, set/overwrite the new field name and unset the existing field name. document[newFieldName] = document[existingFieldName]; delete document[existingFieldName]; // tslint:disable-line no-dynamic-delete } else { // Otherwise this is a noop. } } } } // The $set operator sets the value of a field. function set(document: any, update: any) { var fields: Array<string>, i: number; if (update.$set) { fields = Object.keys(update.$set); for (i = 0; i < fields.length; i++) { document[fields[i]] = update.$set[fields[i]]; } } } // The $unset operator removes the specified field. function unset(document: any, update: any) { var fields: Array<string>, i: number; if (update.$unset) { fields = Object.keys(update.$unset); for (i = 0; i < fields.length; i++) { delete document[fields[i]]; // tslint:disable-line no-dynamic-delete } } } // The $min operator only updates the field if the specified value is less than the existing field value. function min(document: any, update: any) { var fields: Array<string>, i: number; if (update.$min) { fields = Object.keys(update.$min); for (i = 0; i < fields.length; i++) { if (update.$min[fields[i]] < document[fields[i]]) { document[fields[i]] = update.$min[fields[i]]; } } } } // The $max operator only updates the field if the specified value is greater than the existing field value. function max(document: any, update: any) { var fields: Array<string>, i: number; if (update.$max) { fields = Object.keys(update.$max); for (i = 0; i < fields.length; i++) { if (update.$max[fields[i]] > document[fields[i]]) { document[fields[i]] = update.$max[fields[i]]; } } } } // The $currentDate operator sets the value of a field to current date as a POSIX epoch. function currentDate(document: any, update: any) { var currentDate: Date = new Date(); var fields: Array<string>, i: number; if (update.$currentDate) { fields = Object.keys(update.$currentDate); for (i = 0; i < fields.length; i++) { // ECMAScript's Date.getTime() returns milliseconds, where as POSIX epoch are in seconds. document[fields[i]] = Math.round(currentDate.getTime() / 1000); } } } // The $addToSet operator adds elements to an array only if they do not already exist in the set. function addToSet(document: any, update: any) { var fields: Array<string>, i: number; if (update.$addToSet) { fields = Object.keys(update.$addToSet); for (i = 0; i < fields.length; i++) { if (!Array.isArray(document[fields[i]])) { // Validate the document field; throw an exception if it is not an array. throw new Error("Bad $addToSet parameter - field in document must be an array.") } else if (document[fields[i]].indexOf(update.$addToSet[fields[i]]) === -1) { // Add the element if it doesn't already exist in the array. document[fields[i]].push(update.$addToSet[fields[i]]); } } } } // The $pop operator removes the first or last item of an array. // Pass $pop a value of -1 to remove the first element of an array and 1 to remove the last element in an array. function pop(document: any, update: any) { var fields: Array<string>, i: number; if (update.$pop) { fields = Object.keys(update.$pop); for (i = 0; i < fields.length; i++) { if (!Array.isArray(document[fields[i]])) { // Validate the document field; throw an exception if it is not an array. throw new Error("Bad $pop parameter - field in document must be an array.") } else if (update.$pop[fields[i]] < 0) { // Remove the first element from the array if it's less than 0 (be flexible). document[fields[i]].shift(); } else { // Otherwise, remove the last element from the array (have 0 default to javascript's pop()). document[fields[i]].pop(); } } } } // The $push operator adds an item to an array. function push(document: any, update: any) { var fields: Array<string>, i: number; if (update.$push) { fields = Object.keys(update.$push); for (i = 0; i < fields.length; i++) { if (!Array.isArray(document[fields[i]])) { // Validate the document field; throw an exception if it is not an array. throw new Error("Bad $push parameter - field in document must be an array.") } else { // Push the element in to the array. document[fields[i]].push(update.$push[fields[i]]); } } } } } /** * This script runs as a pre-trigger when a document is inserted: * for each inserted document, validate/canonicalize document.weekday and create field document.createdTime. */ function validateClass() { var collection: ICollection = getContext().getCollection(); var collectionLink: string = collection.getSelfLink(); var doc: any = getContext().getRequest().getBody(); // Validate/canonicalize the data. doc.weekday = canonicalizeWeekDay(doc.weekday); // Insert auto-created field 'createdTime'. doc.createdTime = new Date(); // Update the request -- this is what is going to be inserted. getContext().getRequest().setBody(doc); function canonicalizeWeekDay(day: string) { // Simple input validation. if (!day || !day.length || day.length < 3) throw new Error("Bad input: " + day); // Try to see if we can canonicalize the day. var days: Array<string> = ["Monday", "Tuesday", "Wednesday", "Friday", "Saturday", "Sunday"]; var fullDay: string; days.forEach(function (x: string) { if (day.substring(0, 3).toLowerCase() == x.substring(0, 3).toLowerCase()) fullDay = x; }); if (fullDay) return fullDay; // Couldn't get the weekday from input. Throw. throw new Error("Bad weekday: " + day); } } /** * This script runs as a trigger: * for each inserted document, look at document.size and update aggregate properties of metadata document: minSize, maxSize, totalSize. */ function updateMetadata() { // HTTP error codes sent to our callback funciton by DocDB server. var ErrorCode: any = { RETRY_WITH: 449, } var collection: ICollection = getContext().getCollection(); var collectionLink: string = collection.getSelfLink(); // Get the document from request (the script runs as trigger, thus the input comes in request). var doc: any = getContext().getRequest().getBody(); // Check the doc (ignore docs with invalid/zero size and metaDoc itself) and call updateMetadata. if (!doc.isMetadata && doc.size != undefined && doc.size > 0) { getAndUpdateMetadata(); } function getAndUpdateMetadata() { // Get the meta document. We keep it in the same collection. it's the only doc that has .isMetadata = true. var isAccepted: boolean = collection.queryDocuments(collectionLink, 'SELECT * FROM root r WHERE r.isMetadata = true', function (err: IFeedCallbackError, feed: Array<any>, options: IFeedCallbackOptions) { if (err) throw err; if (!feed || !feed.length) throw new Error("Failed to find the metadata document."); // The metadata document. var metaDoc: any = feed[0]; // Update metaDoc.minSize: // for 1st document use doc.Size, for all the rest see if it's less than last min. if (metaDoc.minSize == 0) metaDoc.minSize = doc.size; else metaDoc.minSize = Math.min(metaDoc.minSize, doc.size); // Update metaDoc.maxSize. metaDoc.maxSize = Math.max(metaDoc.maxSize, doc.size); // Update metaDoc.totalSize. metaDoc.totalSize += doc.size; // Update/replace the metadata document in the store. var isAccepted: boolean = collection.replaceDocument(metaDoc._self, metaDoc, function (err: IRequestCallbackError) { if (err) throw err; // Note: in case concurrent updates causes conflict with ErrorCode.RETRY_WITH, we can't read the meta again // and update again because due to Snapshot isolation we will read same exact version (we are in same transaction). // We have to take care of that on the client side. }); if (!isAccepted) throw new Error("The call replaceDocument(metaDoc) returned false."); }); if (!isAccepted) throw new Error("The call queryDocuments for metaDoc returned false."); } } // NOTE: the sample `uniqueConstraint` trigger (https://github.com/Azure/azure-documentdb-js-server/blob/master/samples/triggers/uniqueConstraint.js) does not currently work, because it appears to use a method that does not exist on `Request`, and also appears to throw an invalid Error object. See https://github.com/Azure/azure-documentdb-js-server/issues/22 and https://github.com/Azure/azure-documentdb-js-server/issues/23 to track these issues.
the_stack
import { registerExamples } from '../register'; const schema = { $schema: 'http://json-schema.org/schema#', definitions: { confidenceTypes: { type: 'string', enum: [ 'http://gedcomx.org/High', 'http://gedcomx.org/Medium', 'http://gedcomx.org/Low' ] }, genderTypes: { type: 'string', enum: [ 'http://gedcomx.org/Male', 'http://gedcomx.org/Female', 'http://gedcomx.org/Unknown', 'http://gedcomx.org/Intersex' ] }, nameTypes: { type: 'string', enum: [ 'http://gedcomx.org/BirthName', 'http://gedcomx.org/MarriedName', 'http://gedcomx.org/AlsoKnownAs', 'http://gedcomx.org/Nickname', 'http://gedcomx.org/AdoptiveName', 'http://gedcomx.org/FormalName', 'http://gedcomx.org/ReligiousName' ] }, namePartTypes: { enum: [ 'http://gedcomx.org/Prefix', 'http://gedcomx.org/Suffix', 'http://gedcomx.org/Given', 'http://gedcomx.org/Surname' ] }, personFactTypes: { type: 'string', enum: [ 'http://gedcomx.org/Adoption', 'http://gedcomx.org/AdultChristening', 'http://gedcomx.org/Amnesty', 'http://gedcomx.org/Apprenticeship', 'http://gedcomx.org/Arrest', 'http://gedcomx.org/Baptism', 'http://gedcomx.org/BarMitzvah', 'http://gedcomx.org/BatMitzvah', 'http://gedcomx.org/Birth', 'http://gedcomx.org/Blessing', 'http://gedcomx.org/Burial', 'http://gedcomx.org/Caste', 'http://gedcomx.org/Census', 'http://gedcomx.org/Christening', 'http://gedcomx.org/Circumcision', 'http://gedcomx.org/Clan', 'http://gedcomx.org/Confirmation', 'http://gedcomx.org/Cremation', 'http://gedcomx.org/Death', 'http://gedcomx.org/Education', 'http://gedcomx.org/Emigration', 'http://gedcomx.org/Ethnicity', 'http://gedcomx.org/Excommunication', 'http://gedcomx.org/FirstCommunion', 'http://gedcomx.org/Funeral', 'http://gedcomx.org/GenderChange', 'http://gedcomx.org/Heimat', 'http://gedcomx.org/Immigration', 'http://gedcomx.org/Imprisonment', 'http://gedcomx.org/LandTransaction', 'http://gedcomx.org/Language', 'http://gedcomx.org/Living', 'http://gedcomx.org/MaritalStatus', 'http://gedcomx.org/Medical', 'http://gedcomx.org/MilitaryAward', 'http://gedcomx.org/MilitaryDischarge', 'http://gedcomx.org/MilitaryDraftRegistration', 'http://gedcomx.org/MilitaryInduction', 'http://gedcomx.org/MilitaryService', 'http://gedcomx.org/Mission', 'http://gedcomx.org/MoveTo', 'http://gedcomx.org/MoveFrom', 'http://gedcomx.org/MultipleBirth', 'http://gedcomx.org/NationalId', 'http://gedcomx.org/Nationality', 'http://gedcomx.org/Naturalization', 'http://gedcomx.org/NumberOfChildren', 'http://gedcomx.org/NumberOfMarriages', 'http://gedcomx.org/Occupation', 'http://gedcomx.org/Ordination', 'http://gedcomx.org/Pardon', 'http://gedcomx.org/PhysicalDescription', 'http://gedcomx.org/Probate', 'http://gedcomx.org/Property', 'http://gedcomx.org/Religion', 'http://gedcomx.org/Residence', 'http://gedcomx.org/Retirement', 'http://gedcomx.org/Stillbirth', 'http://gedcomx.org/Will', 'http://gedcomx.org/Visit', 'http://gedcomx.org/Yahrzeit' ] }, uri: { type: 'string' }, localeTag: { type: 'string' // pattern: // "^(((((?'language'[a-z]{2,3})(-(?'extlang'[a-z]{3})){0,3})|(?'language'[a-z]{4})|(?'language'[a-z]{5,8}))(-(?'script'[a-z]{4}))?(-(?'region'[a-z]{2}|[0-9]{3}))?(-(?'variant'[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*(-(?'extensions'[a-z0-9-[x]](-[a-z0-9]{2,8})+))*(-x(- (?'privateuse'[a-z0-9]{1,8}))+)?)|(x(- (?'privateuse'[a-z0-9]{1,8}))+)|(?'grandfathered'(?'irregular'en-GB-oed |i-ami |i-bnn |i-default |i-enochian |i-hak |i-klingon |i-lux |i-mingo |i-navajo |i-pwn |i-tao |i-tay |i-tsu |sgn-BE-FR |sgn-BE-NL |sgn-CH-DE)|(?'regular'art-lojban |cel-gaulish |no-bok |no-nyn |zh-guoyu |zh-hakka |zh-min |zh-min-nan |zh-xiang)))$" }, resourceReference: { type: 'object', properties: { resource: { $ref: '#/definitions/uri' } } }, identifier: { type: 'object' }, attribution: { title: 'Attribution', properties: { contributor: { $ref: '#/definitions/resourceReference', description: 'Reference to the agent to whom the attributed data is attributed.' }, modified: { type: 'number', description: 'Timestamp of when the attributed data was contributed.' }, changeMessage: { type: 'string', description: 'A statement of why the attributed data is being provided by the contributor.' }, creator: { $ref: '#/definitions/resourceReference', description: 'Reference to the agent that created the attributed data. The creator MAY be different from the contributor if changes were made to the attributed data.' }, created: { type: 'number', description: 'Timestamp of when the attributed data was contributed.' } } }, note: { title: 'Note', properties: { lang: { $ref: '#/definitions/localeTag', description: 'The locale identifier for the note.' }, subject: { type: 'string', description: 'A subject or title for the note.' }, text: { type: 'string', description: 'The text of the note.' }, attribution: { $ref: '#/definitions/attribution', description: 'The attribution of this note.' } }, required: ['text'] }, textValue: { type: 'object', properties: { lang: { $ref: '#/definitions/localeTag', description: 'The locale identifier for the value of the text.' }, value: { type: 'string', description: 'The text value.' } }, required: ['value'] }, sourceCitation: { type: 'object', properties: { lang: { $ref: '#/definitions/localeTag', description: 'The locale identifier for the bibliographic metadata.' }, value: { type: 'string', description: 'The bibliographic metadata rendered as a full citation.' } }, required: ['value'] }, sourceReference: { title: 'SourceReference', properties: { description: { $ref: '#/definitions/uri', description: 'Reference to a description of the target source.' }, descriptionId: { type: 'string', description: 'The id of the target source.' }, attribution: { $ref: '#/definitions/attribution', description: 'The attribution of this source reference.' }, qualifiers: { items: { $ref: '#/definitions/sourceReferenceQualifier' }, description: 'Qualifiers for the reference, used to identify specific fragments of the source that are being referenced.' } }, required: ['description'] }, sourceReferenceQualifier: { properties: { name: { anyOf: [ { $ref: '#/definitions/sourceReferenceQualifierNames' }, { $ref: '#/definitions/uri' } ] }, value: { type: 'string' } }, required: ['name'] }, sourceReferenceQualifierNames: { enum: [ 'http://gedcomx.org/CharacterRegion', 'http://gedcomx.org/RectangleRegion', 'http://gedcomx.org/TimeRegion' ] }, evidenceReference: { title: 'EvidenceReference', properties: { resource: { $ref: '#/definitions/uri' }, //subject attribution: { $ref: '#/definitions/attribution' } }, required: ['resource'] }, onlineAccount: { type: 'object', properties: { serviceHomepage: { $ref: '#/definitions/resourceReference' }, accountName: { type: 'string' } }, required: ['serviceHomepage', 'accountName'] }, address: { type: 'object', properties: { value: { type: 'string' }, city: { type: 'string' }, country: { type: 'string' }, postalCode: { type: 'string' }, stateOrProvince: { type: 'string' }, street: { type: 'string' }, street2: { type: 'string' }, street3: { type: 'string' }, street4: { type: 'string' }, street5: { type: 'string' }, street6: { type: 'string' } } }, conclusion: { type: 'object', title: 'Conclusion', properties: { id: { type: 'string', description: 'An identifier for the conclusion data.' }, lang: { $ref: '#/definitions/localeTag', description: 'The locale identifier for the conclusion.' }, sources: { items: { $ref: '#/definitions/sourceReference' }, description: 'The list of references to the sources of related to this conclusion.' }, analysis: { $ref: '#/definitions/resourceReference', description: 'Reference to a document containing analysis supporting this conclusion.' }, notes: { items: { $ref: '#/definitions/note' }, description: 'A list of notes about this conclusion.' }, confidence: { anyOf: [ { $ref: '#/definitions/uri' }, { $ref: '#/definitions/confidenceTypes' } ], description: 'Reference to a confidence level for this conclusion.' }, attribution: { $ref: '#/definitions/attribution', description: 'The attribution of this conclusion.' } } }, subject: { title: 'Subject', allOf: [ { $ref: '#/definitions/conclusion' }, { properties: { extracted: { type: 'boolean', description: 'Whether this subject is to be constrained as an extracted conclusion.' }, evidence: { items: { $ref: '#/definitions/evidenceReference' }, description: 'References to other subjects that support this subject.' }, media: { items: { $ref: '#/definitions/sourceReference' }, description: 'References to multimedia resources for this subject, such as photos or videos, intended to provide additional context or illustration for the subject and not considered evidence supporting the identity of the subject or its supporting conclusions.' }, identifiers: { $ref: '#/definitions/identifier', description: 'A list of identifiers for the subject.' } } } ] }, gender: { allOf: [ { $ref: '#/definitions/conclusion' }, { properties: { type: { anyOf: [ { $ref: '#/definitions/uri' }, { $ref: '#/definitions/genderTypes' } ], description: 'Enumerated value identifying the gender.' } }, required: ['type'] } ] }, date: { type: 'object', properties: { original: { type: 'string', description: 'The original value of the date as supplied by the contributor.' }, formal: { type: 'string', pattern: '^(A?[\\+-]\\d{4}(-\\d{2})?(-\\d{2})?T?(\\d{2})?(:\\d{2})?(:\\d{2})?([\\+-]\\d{2}(:\\d{2})?|Z)?)|(P(\\d{0,4}Y)?(\\d{0,4}M)?(\\d{0,4}D)?(T(\\d{0,4}H)?(\\d{0,4}M)?(\\d{0,4}S)?)?)$', description: 'The standardized formal value of the date, formatted according to the GEDCOM X Date Format specification.' } } }, name: { title: 'Name', allOf: [ { $ref: '#/definitions/conclusion' }, { properties: { type: { anyOf: [ { $ref: '#/definitions/uri' }, { $ref: '#/definitions/nameTypes' } ], description: 'Enumerated value identifying the name type.' }, date: { $ref: '#/definitions/date', description: 'The date of applicability of the name.' }, nameForms: { items: { $ref: '#/definitions/nameForm' }, description: "The name form(s) that best express this name, usually representations considered proper and well formed in the person's native, historical cultural context." } }, required: ['nameForms'] } ] }, namePart: { title: 'NamePart', description: 'The NamePart data type is used to model a portion of a full name, including the terms that make up that portion. Some name parts may have qualifiers to provide additional semantic meaning to the name part (e.g., "given name" or "surname").', properties: { type: { anyOf: [ { $ref: '#/definitions/uri' }, { $ref: '#/definitions/namePartTypes' } ], description: 'Enumerated value identifying the type of the name part.' }, value: { type: 'string', description: 'The term(s) from the name that make up this name part.' }, qualifiers: { items: { $ref: '#/definitions/namePartQualifier' }, description: 'Qualifiers to add additional semantic meaning to the name part.' } }, required: ['value'] }, namePartQualifier: { properties: { name: { anyOf: [ { $ref: '#/definitions/namePartQualifierNames' }, { $ref: '#/definitions/uri' } ] }, value: { type: 'string' } }, required: ['name'] }, namePartQualifierNames: { enum: [ 'http://gedcomx.org/Title', //A designation for honorifics (e.g. Dr., Rev., His Majesty, Haji), ranks (e.g. Colonel, General, Knight, Esquire), positions (e.g. Count, Chief, Father, King) or other titles (e.g., PhD, MD). Name part qualifiers of type Title SHOULD NOT provide a value. 'http://gedcomx.org/Primary', //A designation for the name of most prominent in importance among the names of that type (e.g., the primary given name). Name part qualifiers of type Primary SHOULD NOT provide a value. 'http://gedcomx.org/Secondary', //A designation for a name that is not primary in its importance among the names of that type (e.g., a secondary given name). Name part qualifiers of type Secondary SHOULD NOT provide a value. 'http://gedcomx.org/Middle', //A designation useful for cultures that designate a middle name that is distinct from a given name and a surname. Name part qualifiers of type Middle SHOULD NOT provide a value. 'http://gedcomx.org/Familiar', //A designation for one's familiar name. Name part qualifiers of type Familiar SHOULD NOT provide a value. 'http://gedcomx.org/Religious', //A designation for a name given for religious purposes. Name part qualifiers of type Religious SHOULD NOT provide a value. 'http://gedcomx.org/Family', //A name that associates a person with a group, such as a clan, tribe, or patriarchal hierarchy. Name part qualifiers of type Family SHOULD NOT provide a value. 'http://gedcomx.org/Maiden', //A designation given by women to their original surname after they adopt a new surname upon marriage. Name part qualifiers of type Maiden SHOULD NOT provide a value. 'http://gedcomx.org/Patronymic', //A name derived from a father or paternal ancestor. Name part qualifiers of type Patronymic SHOULD NOT provide a value. 'http://gedcomx.org/Matronymic', //A name derived from a mother or maternal ancestor. Name part qualifiers of type Matronymic SHOULD NOT provide a value. 'http://gedcomx.org/Geographic', //A name derived from associated geography. Name part qualifiers of type Geographic SHOULD NOT provide a value. 'http://gedcomx.org/Occupational', //A name derived from one's occupation. Name part qualifiers of type Occupational SHOULD NOT provide a value. 'http://gedcomx.org/Characteristic', //A name derived from a characteristic. Name part qualifiers of type Characteristic SHOULD NOT provide a value. 'http://gedcomx.org/Postnom', //A name mandated by law for populations from Congo Free State / Belgian Congo / Congo / Democratic Republic of Congo (formerly Zaire). Name part qualifiers of type Postnom SHOULD NOT provide a value. 'http://gedcomx.org/Particle', //A grammatical designation for articles (a, the, dem, las, el, etc.), prepositions (of, from, aus, zu, op, etc.), initials, annotations (e.g. twin, wife of, infant, unknown), comparators (e.g. Junior, Senior, younger, little), ordinals (e.g. III, eighth), descendancy words (e.g. ben, ibn, bat, bin, bint, bar), and conjunctions (e.g. and, or, nee, ou, y, o, ne, &). Name part qualifiers of type Particle SHOULD NOT provide a value. 'http://gedcomx.org/RootName' //The "root" of a name part as distinguished from prefixes or suffixes. For example, the root of the Polish name "Wilkówna" is "Wilk". A RootName qualifier MUST provide a value property. ] }, nameForm: { title: 'NameForm', description: `The NameForm data type defines a representation of a name (a "name form") within a given cultural context, such as a given language and script. As names are captured (both in records or in applications), the terms in the name are sometimes classified by type. For example, a certificate of death might prompt for "given name(s)" and "surname". The parts list can be used to represent the terms in the name that have been classified. If both a full rendering of the name and a list of parts are provided, it NOT REQUIRED that every term in the fully rendered name appear in the list of parts. Name parts in the parts list SHOULD be ordered in the natural order they would be used in the applicable cultural context. If a full rendering of the name is not provided (i.e., the name has only been expressed in parts), a full rendering of the name MAY be derived (sans punctuation) by concatenating, in order, each name part value in the list of parts, separating each part with the name part separator appropriate for the applicable cultural context.`, properties: { lang: { $ref: '#/definitions/localeTag', description: 'The locale identifier for the name form.' }, fullText: { type: 'string', description: 'A full rendering of the name (or as much of the name as is known).' }, parts: { items: { $ref: '#/definitions/namePart' }, description: 'Any identified name parts from the name.' } } }, fact: { title: 'PersonFact', allOf: [ { $ref: '#/definitions/conclusion' }, { properties: { type: { anyOf: [ { $ref: '#/definitions/uri' }, { $ref: '#/definitions/personFactTypes' } ], description: 'Enumerated value identifying the type of the fact.' }, date: { $ref: '#/definitions/date', description: 'The date of applicability of the fact.' }, place: { $ref: '#/definitions/placeReference', description: 'A reference to the place applicable to this fact.' }, value: { type: 'string', description: 'The value of the fact.' }, qualifiers: { items: { $ref: '#/definitions/factQualifier' }, description: 'Qualifiers to add additional details about the fact.' } }, required: ['type'] } ] }, factQualifier: { properties: { name: { anyOf: [ { $ref: '#/definitions/factQualifierNames' }, { $ref: '#/definitions/uri' } ] }, value: { type: 'string' } }, required: ['name'] }, factQualifierNames: { enum: [ 'http://gedcomx.org/Age', 'http://gedcomx.org/Cause', 'http://gedcomx.org/Religion', 'http://gedcomx.org/Transport', 'http://gedcomx.org/NonConsensual' ] }, eventRole: { allOf: [ { $ref: '#/definitions/conclusion' }, { properties: { person: { $ref: '#/definitions/resourceReference', description: 'Reference to the event participant.' }, type: { anyOf: [ { $ref: '#/definitions/uri' }, { $ref: '#/definitions/eventRoleTypes' } ], description: "Enumerated value identifying the participant's role." }, details: { type: 'string', description: 'Details about the role of participant in the event.' } }, required: ['person'] } ] }, eventRoleTypes: { enum: [ 'http://gedcomx.org/Principal', 'http://gedcomx.org/Participant', 'http://gedcomx.org/Official', 'http://gedcomx.org/Witness' ] }, placeReference: { type: 'object', properties: { original: { type: 'string', description: 'The original place name text as supplied by the contributor.' }, description: { $ref: '#/definitions/uri', description: 'A reference to a description of this place.' } } }, coverage: { properties: { spatial: { $ref: '#/definitions/placeReference', description: 'The spatial (i.e., geographic) coverage.' }, temporal: { $ref: '#/definitions/date', description: 'The temporal coverage.' } } }, groupRole: { allOf: [ { $ref: '#/definitions/conclusion' }, { properties: { person: { $ref: '#/definitions/resourceReference', description: 'Reference to the group participant.' }, type: { $ref: '#/definitions/uri', description: "Enumerated value identifying the participant's role." }, date: { $ref: '#/definitions/date', description: 'The date of applicability of the role.' }, details: { type: 'string', description: 'Details about the role of he participant in the group.' } }, required: ['person'] } ] }, person: { title: 'Person', allOf: [ { $ref: '#/definitions/subject' }, { properties: { private: { type: 'boolean', description: 'Whether this instance of Person has been designated for limited distribution or display.' }, gender: { $ref: '#/definitions/gender', description: 'The sex of the person as assigned at birth.' }, names: { items: { $ref: '#/definitions/name' }, description: 'The names of the person.' }, facts: { items: { $ref: '#/definitions/fact' }, description: 'The facts of the person.' } } } ] }, relationship: { allOf: [ { $ref: '#/definitions/subject' }, { properties: { type: { anyOf: [ { $ref: '#/definitions/relationshipType' }, { $ref: '#/definitions/uri' } ], description: 'Enumerated value identifying the type of the relationship.' }, person1: { $ref: '#/definitions/resourceReference', description: 'Reference to the first person in the relationship.' }, person2: { $ref: '#/definitions/resourceReference', description: 'Reference to the second person in the relationship.' }, facts: { items: { $ref: '#/definitions/fact' }, description: 'The facts about the relationship.' } }, required: ['person1', 'person2'] } ] }, relationshipType: { enum: [ 'http://gedcomx.org/Couple', // A relationship of a pair of persons. 'http://gedcomx.org/ParentChild', // A relationship from a parent to a child. 'http://gedcomx.org/EnslavedBy' // A relationship from an enslaved person to the enslaver or slaveholder of the person. ] }, sourceDescription: { title: 'SourceDescription', properties: { id: { type: 'string', description: 'An identifier for the data structure holding the source description data.' }, resourceType: { anyOf: [ { $ref: '#/definitions/resourceTypes' }, { $ref: '#/definitions/uri' } ], description: 'Enumerated value identifying the type of resource being described.' }, citations: { items: { $ref: '#/definitions/sourceCitation' }, description: 'The citation(s) for this source.' }, mediaType: { type: 'string', description: 'A hint about the media type of the resource being described.' }, about: { $ref: '#/definitions/uri', description: 'A uniform resource identifier (URI) for the resource being described.' }, mediator: { $ref: '#/definitions/resourceReference', description: 'A reference to the entity that mediates access to the described source.' }, publisher: { $ref: '#/definitions/resourceReference', description: 'A reference to the entity responsible for making the described source available.' }, sources: { items: { $ref: '#/definitions/sourceReference' }, description: 'A list of references to any sources from which this source is derived.' }, analysis: { $ref: '#/definitions/resourceReference', description: 'A reference to a document containing analysis about this source.' }, componentOf: { $ref: '#/definitions/sourceReference', description: 'A reference to the source that contains this source, i.e. its parent context. Used when the description of a source is not complete without the description of its parent (or containing) source.' }, titles: { items: { $ref: '#/definitions/textValue' }, description: 'The display name(s) for this source.' }, notes: { items: { $ref: '#/definitions/note' }, description: 'A list of notes about a source.' }, attribution: { $ref: '#/definitions/attribution', description: 'The attribution of this source description.' }, rights: { items: { $ref: '#/definitions/resourceReference' }, description: 'The rights for this resource.' }, coverage: { $ref: '#/definitions/coverage', description: 'The coverage of the resource.' }, descriptions: { items: { $ref: '#/definitions/textValue' }, description: 'Human-readable descriptions of this source.' }, identifiers: { items: { $ref: '#/definitions/identifier' }, description: 'A list of identifiers for the resource being described.' }, created: { type: 'number', description: 'Timestamp of when the resource being described was created.' }, modified: { type: 'number', description: 'Timestamp of when the resource being described was modified.' }, repository: { $ref: '#/definitions/resourceReference', description: 'A reference to the repository that contains the described resource.' } }, required: ['citations'] }, resourceTypes: { enum: [ 'http://gedcomx.org/Collection', //A collection of genealogical resources. A collection may contain physical artifacts (such as a collection of books in a library), records (such as the 1940 U.S. Census), or digital artifacts (such as an online genealogical application). 'http://gedcomx.org/PhysicalArtifact', //A physical artifact, such as a book. 'http://gedcomx.org/DigitalArtifact', //A digital artifact, such as a digital image of a birth certificate or other record. 'http://gedcomx.org/Record' //A historical record, such as a census record or a vital record. ] }, agent: { title: 'Agent', properties: { id: { type: 'string' }, identifiers: { type: 'array', items: { $ref: '#/definitions/identifier' } }, names: { type: 'array', items: { $ref: '#/definitions/textValue' } }, homepage: { $ref: '#/definitions/resourceReference' }, openid: { $ref: '#/definitions/resourceReference' }, accounts: { type: 'array', items: { $ref: '#/definitions/onlineAccount' } }, emails: { type: 'array', items: { $ref: '#/definitions/resourceReference' } }, phones: { type: 'array', items: { $ref: '#/definitions/resourceReference' } }, addresses: { type: 'array', items: { $ref: '#/definitions/address' } }, person: { $ref: '#/definitions/resourceReference' } } }, event: { allOf: [ { $ref: '#/definitions/subject' }, { properties: { type: { anyOf: [ { $ref: '#/definitions/eventTypes' }, { $ref: '#/definitions/uri' } ] }, date: { $ref: '#/definitions/date' }, place: { $ref: '#/definitions/placeReference' }, roles: { type: 'array', items: { $ref: '#/definitions/eventRole' } } } } ] }, eventTypes: { enum: [ 'http://gedcomx.org/Adoption', //An adoption event. 'http://gedcomx.org/AdultChristening', //An adult christening event. 'http://gedcomx.org/Annulment', //An annulment event of a marriage. 'http://gedcomx.org/Baptism', //A baptism event. 'http://gedcomx.org/BarMitzvah', //A bar mitzvah event. 'http://gedcomx.org/BatMitzvah', //A bat mitzvah event. 'http://gedcomx.org/Birth', //A birth event. 'http://gedcomx.org/Blessing', //A an official blessing event, such as at the hands of a clergy member or at another religious rite. 'http://gedcomx.org/Burial', //A burial event. 'http://gedcomx.org/Census', //A census event. 'http://gedcomx.org/Christening', //A christening event at birth. Note: use AdultChristening for a christening event as an adult. 'http://gedcomx.org/Circumcision', //A circumcision event. 'http://gedcomx.org/Confirmation', //A confirmation event (or other rite of initiation) in a church or religion. 'http://gedcomx.org/Cremation', //A cremation event after death. 'http://gedcomx.org/Death', //A death event. 'http://gedcomx.org/Divorce', //A divorce event. 'http://gedcomx.org/DivorceFiling', //A divorce filing event. 'http://gedcomx.org/Education', //A education or an educational achievement event (e.g. diploma, graduation, scholarship, etc.). 'http://gedcomx.org/Engagement', //An engagement to be married event. 'http://gedcomx.org/Emigration', //An emigration event. 'http://gedcomx.org/Excommunication', //An excommunication event from a church. 'http://gedcomx.org/FirstCommunion', //A first communion event. 'http://gedcomx.org/Funeral', //A funeral event. 'http://gedcomx.org/Immigration', //An immigration event. 'http://gedcomx.org/LandTransaction', //A land transaction event. 'http://gedcomx.org/Marriage', //A marriage event. 'http://gedcomx.org/MilitaryAward', //A military award event. 'http://gedcomx.org/MilitaryDischarge', //A military discharge event. 'http://gedcomx.org/Mission', //A mission event. 'http://gedcomx.org/MoveFrom', //An event of a move (i.e. change of residence) from a location. 'http://gedcomx.org/MoveTo', //An event of a move (i.e. change of residence) to a location. 'http://gedcomx.org/Naturalization', //A naturalization event (i.e. acquisition of citizenship and nationality). 'http://gedcomx.org/Ordination', //An ordination event. 'http://gedcomx.org/Retirement' //A retirement event. ] }, document: { title: 'Document', allOf: [ { $ref: '#/definitions/conclusion' }, { properties: { type: { anyOf: [ { $ref: '#/definitions/documentTypes' }, { $ref: '#/definitions/uri' } ] }, extracted: { type: 'boolean' }, textType: { type: 'string' }, text: { type: 'string' }, attribution: { $ref: '#/definitions/attribution' } }, required: ['text'] } ] }, documentTypes: { enum: [ 'http://gedcomx.org/Abstract', //The document is an abstract of a record or document. 'http://gedcomx.org/Transcription', //The document is a transcription of a record or document. 'http://gedcomx.org/Translation', //The document is a translation of a record or document. 'http://gedcomx.org/Analysis' //The document is an analysis done by a researcher; a genealogical proof statement is an example of one kind of analysis document. ] }, placeDescription: { title: 'PlaceDescription', allOf: [ { $ref: '#/definitions/subject' }, { properties: { names: { items: { $ref: '#/definitions/textValue' } }, type: { $ref: '#/definitions/uri' }, place: { $ref: '#/definitions/resourceReference' }, jurisdiction: { $ref: '#/definitions/resourceReference' }, latitude: { type: 'number' }, longitude: { type: 'number' }, temporalDescription: { $ref: '#/definitions/date' }, spatialDescription: { $ref: '#/definitions/resourceReference' } }, required: ['names'] } ] }, group: { allOf: [ { $ref: '#/definitions/subject' }, { properties: { names: { type: 'array', items: { $ref: '#/definitions/textValue' } }, date: { $ref: '#/definitions/date' }, place: { $ref: '#/definitions/resourceReference' }, roles: { type: 'array', items: { $ref: '#/definitions/groupRole' } } }, required: ['names'] } ] } }, type: 'object', properties: { persons: { type: 'array', items: { $ref: '#/definitions/person' } }, relationships: { type: 'array', items: { $ref: '#/definitions/relationship' } }, sourceDescriptions: { type: 'array', items: { $ref: '#/definitions/sourceDescription' } }, agents: { type: 'array', items: { $ref: '#/definitions/agent' } }, events: { type: 'array', items: { $ref: '#/definitions/event' } }, documents: { type: 'array', items: { $ref: '#/definitions/document' } }, places: { type: 'array', items: { $ref: '#/definitions/placeDescription' } }, groups: { type: 'array', items: { $ref: '#/definitions/group' } }, description: { $ref: '#/definitions/uri' }, id: { type: 'string' }, lang: { $ref: '#/definitions/localeTag' }, attribution: { $ref: '#/definitions/attribution' } } }; const data: any = { attribution: { contributor: { resource: '#A-1' }, modified: 1398405600000 }, persons: [ { names: [ { nameForms: [ { fullText: 'Samuel Ham' } ] } ], gender: { type: 'http://gedcomx.org/Male' }, facts: [ { type: 'http://gedcomx.org/Residence', date: { original: '3 November 1828', formal: '+1828-11-03' }, place: { original: 'parish of Honiton, Devon, England' } } ], extracted: true, sources: [ { description: '#S-2' } ], id: 'P-1' }, { names: [ { nameForms: [ { fullText: 'Elizabeth Spiller' } ] } ], gender: { type: 'http://gedcomx.org/Female' }, facts: [ { type: 'http://gedcomx.org/Residence', date: { original: '3 November 1828', formal: '+1828-11-03' }, place: { original: 'parish of Wilton, Somerset, England' } } ], extracted: true, sources: [ { description: '#S-2' } ], id: 'P-2' }, { names: [ { nameForms: [ { fullText: 'Jno. Pain' } ] } ], extracted: true, sources: [ { description: '#S-2' } ], id: 'P-3' }, { names: [ { nameForms: [ { fullText: 'R.G. Halls' } ] } ], extracted: true, sources: [ { description: '#S-2' } ], id: 'P-4' }, { names: [ { nameForms: [ { fullText: 'Peggy Hammet' } ] } ], extracted: true, sources: [ { description: '#S-2' } ], id: 'P-5' }, { names: [ { nameForms: [ { fullText: 'David Smith Stone' } ] } ], extracted: true, sources: [ { description: '#S-2' } ], id: 'P-6' }, { evidence: [ { resource: '#P-1' } ], analysis: { resource: '#D-2' }, id: 'C-1' } ], relationships: [ { type: 'http://gedcomx.org/Couple', extracted: true, facts: [ { type: 'http://gedcomx.org/Marriage', date: { original: '3 November 1828', formal: '+1828-11-03' }, place: { original: 'Wilton St George, Wilton, Somerset, England' } } ], person1: { resource: '#P-1' }, person2: { resource: '#P-2' } } ], sourceDescriptions: [ { description: [ { value: 'Marriage entry for Samuel Ham and Elizabeth in a copy of the registers of the baptisms, marriages, and burials at the church of St. George in the parish of Wilton : adjoining Taunton, in the county of Somerset from A.D. 1558 to A.D. 1837.' } ], resourceType: 'http://gedcomx.org/PhysicalArtifact', citations: [ { value: 'Joseph Houghton Spencer, transcriber, Church of England, Parish Church of Wilton (Somerset). A copy of the registers of the baptisms, marriages, and burials at the church of St. George in the parish of Wilton : adjoining Taunton, in the county of Somerset from A.D. 1558 to A.D. 1837; Marriage entry for Samuel Ham and Elizabeth Spiller (3 November 1828), (Taunton: Barnicott, 1890), p. 224, No. 86.' } ], titles: [ { value: 'Marriage entry for Samuel Ham and Elizabeth Spiller, Parish Register, Wilton, Somerset, England' } ], repository: { resource: '#A-2' }, id: 'S-1' }, { description: [ { value: 'Transcription of marriage entry for Samuel Ham and Elizabeth in a copy of the registers of the baptisms, marriages, and burials at the church of St. George in the parish of Wilton : adjoining Taunton, in the county of Somerset from A.D. 1558 to A.D. 1837.' } ], sources: [ { description: '#S-1' } ], resourceType: 'http://gedcomx.org/DigitalArtifact', citations: [ { value: 'Joseph Houghton Spencer, transcriber, Church of England, Parish Church of Wilton (Somerset). A copy of the registers of the baptisms, marriages, and burials at the church of St. George in the parish of Wilton : adjoining Taunton, in the county of Somerset from A.D. 1558 to A.D. 1837; Marriage entry for Samuel Ham and Elizabeth Spiller (3 November 1828), (Taunton: Barnicott, 1890), p. 224, No. 86.' } ], about: '#D-1', titles: [ { value: 'Transcription of marriage entry for Samuel Ham and Elizabeth Spiller, Parish Register, Wilton, Somerset, England' } ], id: 'S-2' } ], agents: [ { names: [ { value: 'Jane Doe' } ], emails: [ { resource: 'mailto:example@example.org' } ], id: 'A-1' }, { names: [ { value: 'Family History Library' } ], addresses: [ { city: 'Salt Lake City', stateOrProvince: 'Utah' } ], id: 'A-2' } ], events: [ { type: 'http://gedcomx.org/Marriage', date: { original: '3 November 1828', formal: '+1828-11-03' }, place: { original: 'Wilton St George, Wilton, Somerset, England' }, roles: [ { type: 'http://gedcomx.org/Principal', person: { resource: '#P-1' } }, { type: 'http://gedcomx.org/Principal', person: { resource: '#P-2' } }, { type: 'http://gedcomx.org/Witness', person: { resource: '#P-3' } }, { type: 'http://gedcomx.org/Witness', person: { resource: '#P-4' } }, { type: 'http://gedcomx.org/Witness', person: { resource: '#P-5' } }, { type: 'http://gedcomx.org/Official', person: { resource: '#P-6' } } ], extracted: true, id: 'E-1' } ], documents: [ { type: 'http://gedcomx.org/Transcription', text: 'Samuel Ham of the parish of Honiton and Elizabeth Spiller\nwere married this 3rd day of November 1828 by David Smith\nStone, Pl Curate,\nIn the Presence of\nJno Pain.\nR.G. Halls. Peggy Hammet.\nNo. 86.', sources: [ { description: '#S-1' } ], lang: 'en', id: 'D-1' }, { text: '...Jane Doe`s analysis document...', id: 'D-2' } ] }; export const uischema: any = { type: 'Categorization', elements: [ { type: 'Category', label: 'Persons', elements: [{ type: 'ListWithDetail', scope: '#/properties/persons' }] }, { type: 'Category', label: 'Relationships', elements: [ { type: 'ListWithDetail', scope: '#/properties/relationships' } ] }, { type: 'Category', label: 'SourceDescriptions', elements: [ { type: 'ListWithDetail', scope: '#/properties/sourceDescriptions' } ] }, { type: 'Category', label: 'Agents', elements: [{ type: 'ListWithDetail', scope: '#/properties/agents' }] }, { type: 'Category', label: 'Events', elements: [{ type: 'ListWithDetail', scope: '#/properties/events' }] }, { type: 'Category', label: 'Documents', elements: [{ type: 'ListWithDetail', scope: '#/properties/documents' }] }, { type: 'Category', label: 'Places', elements: [{ type: 'ListWithDetail', scope: '#/properties/places' }] }, { type: 'Category', label: 'Generic', elements: [ { type: 'Control', scope: '#/properties/description' }, { type: 'Control', scope: '#/properties/lang' }, { type: 'Control', scope: '#/properties/attribution' }, { type: 'Control', scope: '#/properties/id' } ] } ] }; registerExamples([ { name: 'huge', label: 'Huge Test', data, schema, uischema } ]);
the_stack
import { EventEmitter } from 'events' import { priorityQueue, AsyncPriorityQueue } from 'async' import { Logger, LoggerOptions } from 'node-log-it' import { merge, map, filter, difference, isArray, uniq } from 'lodash' import { MemoryStorage } from '../storages/memory-storage' import { MongodbStorage } from '../storages/mongodb-storage' import { BlockHelper } from '../helpers/block-helper' const MODULE_NAME = 'BlockAnalyzer' const DEFAULT_OPTIONS: BlockAnalyzerOptions = { minHeight: 1, maxHeight: undefined, startOnInit: true, toEvaluateTransactions: true, toEvaluateAssets: false, blockQueueConcurrency: 5, transactionQueueConcurrency: 10, enqueueEvaluateBlockIntervalMs: 5 * 1000, verifyBlocksIntervalMs: 30 * 1000, maxBlockQueueLength: 30 * 1000, maxTransactionQueueLength: 100 * 1000, standardEvaluateBlockPriority: 5, missingEvaluateBlockPriority: 3, legacyEvaluateBlockPriority: 3, standardEvaluateTransactionPriority: 5, missingEvaluateTransactionPriority: 5, legacyEvaluateTransactionPriority: 5, loggerOptions: {}, } export interface BlockAnalyzerOptions { minHeight?: number maxHeight?: number startOnInit?: boolean toEvaluateTransactions?: boolean toEvaluateAssets?: boolean blockQueueConcurrency?: number transactionQueueConcurrency?: number enqueueEvaluateBlockIntervalMs?: number verifyBlocksIntervalMs?: number maxBlockQueueLength?: number maxTransactionQueueLength?: number standardEvaluateBlockPriority?: number missingEvaluateBlockPriority?: number legacyEvaluateBlockPriority?: number standardEvaluateTransactionPriority?: number missingEvaluateTransactionPriority?: number legacyEvaluateTransactionPriority?: number loggerOptions?: LoggerOptions } export class BlockAnalyzer extends EventEmitter { /** * Flags for determine version of the metadata (akin to Android API level) */ private BLOCK_META_API_LEVEL = 1 private TRANSACTION_META_API_LEVEL = 1 private _isRunning = false private blockQueue: AsyncPriorityQueue<object> private transactionQueue: AsyncPriorityQueue<object> private blockWritePointer: number = 0 private storage?: MemoryStorage | MongodbStorage private options: BlockAnalyzerOptions private logger: Logger private enqueueEvaluateBlockIntervalId?: NodeJS.Timer private blockVerificationIntervalId?: NodeJS.Timer private isVerifyingBlocks = false constructor(storage?: MemoryStorage | MongodbStorage, options: BlockAnalyzerOptions = {}) { super() // Associate required properties this.storage = storage // Associate optional properties this.options = merge({}, DEFAULT_OPTIONS, options) this.validateOptionalParameters() // Bootstrapping this.logger = new Logger(MODULE_NAME, this.options.loggerOptions) this.blockQueue = this.getPriorityQueue(this.options.blockQueueConcurrency!) this.transactionQueue = this.getPriorityQueue(this.options.transactionQueueConcurrency!) if (this.options.startOnInit) { this.start() } this.logger.debug('constructor completes.') } isRunning(): boolean { return this._isRunning } start() { if (this._isRunning) { this.logger.info('BlockAnalyzer has already started.') return } if (!this.storage) { this.logger.info('Unable to start BlockAnalyzer when no storage are defined.') return } this.logger.info('Start BlockAnalyzer.') this._isRunning = true this.emit('start') this.initEvaluateBlock() this.initBlockVerification() } stop() { if (!this._isRunning) { this.logger.info('BlockAnalyzer is not running at the moment.') return } this.logger.info('Stop BlockAnalyzer.') this._isRunning = false this.emit('stop') clearInterval(this.enqueueEvaluateBlockIntervalId!) clearInterval(this.blockVerificationIntervalId!) } close() { this.stop() } private validateOptionalParameters() { // TODO } private getPriorityQueue(concurrency: number): AsyncPriorityQueue<object> { return priorityQueue((task: object, callback: () => void) => { const method: (attrs: object) => Promise<any> = (task as any).method const attrs: object = (task as any).attrs const meta: object = (task as any).meta this.logger.debug('New worker for queue. meta:', meta, 'attrs:', attrs) method(attrs) .then(() => { callback() this.logger.debug('Worker queued method completed.') this.emit('queue:worker:complete', { isSuccess: true, task }) }) .catch((err: any) => { this.logger.info('Worker queued method failed, but to continue... meta:', meta, 'Message:', err.message) callback() this.emit('queue:worker:complete', { isSuccess: false, task }) }) }, concurrency) } private initEvaluateBlock() { this.logger.debug('initEvaluateBlock triggered.') this.setBlockWritePointer() .then(() => { // Enqueue blocks for evaluation this.enqueueEvaluateBlockIntervalId = setInterval(() => { this.doEnqueueEvaluateBlock() }, this.options.enqueueEvaluateBlockIntervalMs!) }) .catch((err: any) => { this.logger.warn('setBlockWritePointer() failed. Error:', err.message) }) } private async setBlockWritePointer(): Promise<void> { this.logger.debug('setBlockWritePointer triggered.') try { const height = await this.storage!.getHighestBlockMetaHeight() this.logger.debug('getBlockMetaCount success. height:', height) if (this.options.minHeight && height < this.options.minHeight) { this.logger.info(`storage height is smaller than designated minHeight. BlockWritePointer will be set to minHeight [${this.options.minHeight}] instead.`) this.blockWritePointer = this.options.minHeight } else { this.blockWritePointer = height } } catch (err) { this.logger.warn('storage.getBlockMetaCount() failed. Error:', err.message) this.logger.info('Assumed that there are no blocks.') this.blockWritePointer = this.options.minHeight! // Suppress error and continue } } private initBlockVerification() { this.logger.debug('initBlockVerification triggered.') this.blockVerificationIntervalId = setInterval(() => { this.doBlockVerification() }, this.options.verifyBlocksIntervalMs!) } private async doBlockVerification() { this.logger.debug('doBlockVerification triggered.') this.emit('blockVerification:init') // Queue sizes this.logger.info('blockQueue.length:', this.blockQueue.length()) this.logger.info('transactionQueue.length:', this.transactionQueue.length()) // Check if this process is currently executing if (this.isVerifyingBlocks) { this.logger.info('doBlockVerification() is already running. Skip this turn.') this.emit('blockVerification:complete', { isSkipped: true }) return } // Prepare this.isVerifyingBlocks = true const startHeight = this.options.minHeight! const endHeight = this.options.maxHeight && this.blockWritePointer > this.options.maxHeight ? this.options.maxHeight : this.blockWritePointer // Act let blockMetasFullySynced = false let transactionMetasFullySynced = false try { blockMetasFullySynced = await this.verifyBlockMetas(startHeight, endHeight) transactionMetasFullySynced = await this.verifyTransactionMetas(startHeight, endHeight) } catch (err) { this.logger.info('Block verification failed. Message:', err.message) this.isVerifyingBlocks = false this.emit('blockVerification:complete', { isSuccess: false }) return } // Check if fully sync'ed if (this.isReachedMaxHeight()) { if (blockMetasFullySynced && transactionMetasFullySynced) { this.logger.info('BlockAnalyzer is up to date.') this.emit('upToDate') } } // Conclude this.isVerifyingBlocks = false this.emit('blockVerification:complete', { isSuccess: true }) } private async verifyBlockMetas(startHeight: number, endHeight: number): Promise<boolean> { this.logger.debug('verifyBlockMetas triggered.') const blockMetaReport = await this.storage!.analyzeBlockMetas(startHeight, endHeight) this.logger.debug('Analyzing block metas complete!') const all = this.getNumberArray(startHeight, endHeight) const availableBlocks: number[] = map(blockMetaReport, (item: any) => item.height) this.logger.info('Block metas available count:', availableBlocks.length) // Enqueue missing block heights const missingBlocks = difference(all, availableBlocks) this.logger.info('Block metas missing count:', missingBlocks.length) this.emit('blockVerification:blockMetas:missing', { count: missingBlocks.length }) missingBlocks.forEach((height: number) => { this.enqueueEvaluateBlock(height, this.options.missingEvaluateBlockPriority!) }) // Truncate legacy block meta right away const legacyBlockObjs = filter(blockMetaReport, (item: any) => { return item.apiLevel < this.BLOCK_META_API_LEVEL }) const legacyBlocks = map(legacyBlockObjs, (item: any) => item.height) this.logger.info('Legacy block metas count:', legacyBlockObjs.length) this.emit('blockVerification:blockMetas:legacy', { count: legacyBlocks.length }) legacyBlocks.forEach((height: number) => { // TODO: use queue instead of unmanaged parallel tasks for removing block metas this.storage!.removeBlockMetaByHeight(height) this.enqueueEvaluateBlock(height, this.options.legacyEvaluateBlockPriority!) }) const fullySynced = missingBlocks.length === 0 && legacyBlocks.length === 0 return fullySynced } private async verifyTransactionMetas(startHeight: number, endHeight: number): Promise<boolean> { this.logger.debug('verifyTransactionMetas triggered.') // TODO; add capability for detecting missing transaction metas const legacyCount = await this.storage!.countLegacyTransactionMeta(this.TRANSACTION_META_API_LEVEL) this.emit('blockVerification:transactionMetas:legacy', { metaCount: legacyCount }) if (legacyCount === 0) { return true } await this.storage!.pruneLegacyTransactionMeta(this.TRANSACTION_META_API_LEVEL) return false } private doEnqueueEvaluateBlock() { this.logger.debug('doEnqueueEvaluateBlock triggered.') if (this.isReachedMaxHeight()) { this.logger.info(`BlockWritePointer is greater or equal to designated maxHeight [${this.options.maxHeight}]. There will be no enqueue block beyond this point.`) return } while (!this.isReachedMaxHeight() && !this.isReachedMaxQueueLength()) { this.increaseBlockWritePointer() this.enqueueEvaluateBlock(this.blockWritePointer!, this.options.standardEvaluateBlockPriority!) } } private isReachedMaxHeight(): boolean { return !!(this.options.maxHeight && this.blockWritePointer >= this.options.maxHeight) } private isReachedMaxQueueLength(): boolean { return this.blockQueue.length() >= this.options.maxBlockQueueLength! } private increaseBlockWritePointer() { this.logger.debug('increaseBlockWritePointer triggered.') this.blockWritePointer += 1 } /** * @param priority Lower value, the higher its priority to be executed. */ private enqueueEvaluateBlock(height: number, priority: number) { this.logger.debug('enqueueEvaluateBlock triggered. height:', height, 'priority:', priority) // if the block height is above the current height, increment the write pointer. if (height > this.blockWritePointer) { this.logger.debug('height > this.blockWritePointer, blockWritePointer is now:', height) this.blockWritePointer = height } this.blockQueue.push( { method: this.evaluateBlock.bind(this), attrs: { height, }, meta: { methodName: 'evaluateBlock', }, }, priority ) } private async evaluateBlock(attrs: object): Promise<any> { this.logger.debug('evaluateBlock triggered. attrs:', attrs) const height: number = (attrs as any).height let previousBlock: object | undefined if (height > 1) { previousBlock = await this.storage!.getBlock(height - 1) } const block: any = await this.storage!.getBlock(height) const blockMeta = { height, time: block.time, size: block.size, generationTime: BlockHelper.getGenerationTime(block, previousBlock), transactionCount: BlockHelper.getTransactionCount(block), apiLevel: this.BLOCK_META_API_LEVEL, } if (this.options.toEvaluateTransactions) { this.enqueueEvaluateTransaction(block, this.options.standardEvaluateTransactionPriority!) } await this.storage!.setBlockMeta(blockMeta) } private enqueueEvaluateTransaction(block: any, priority: number) { this.logger.debug('enqueueEvaluateTransaction triggered.') if (!block || !block.tx) { this.logger.info('Invalid block object. Skipping...') return } block.tx.forEach((transaction: any) => { this.transactionQueue.push( { method: this.evaluateTransaction.bind(this), attrs: { height: block.index, time: block.time, transaction, }, meta: { methodName: 'evaluateTransaction', }, }, priority ) }) } private async enqueueEvaluateTransactionWithHeight(height: number, priority: number) { this.logger.debug('enqueueEvaluateTransactionWithHeight triggered.') const block: any = await this.storage!.getBlock(height) this.enqueueEvaluateTransaction(block, priority) } private async evaluateTransaction(attrs: object): Promise<any> { this.logger.debug('evaluateTransaction triggered.') const height: number = (attrs as any).height const time: number = (attrs as any).time const tx: any = (attrs as any).transaction const voutCount: number | undefined = isArray(tx.vout) ? tx.vout.length : undefined const vinCount: number | undefined = isArray(tx.vin) ? tx.vin.length : undefined const transactionMeta = { height, time, transactionId: tx.txid, type: tx.type, size: tx.size, networkFee: tx.net_fee, systemFee: tx.sys_fee, voutCount, vinCount, apiLevel: this.TRANSACTION_META_API_LEVEL, } await this.storage!.setTransactionMeta(transactionMeta) } private getNumberArray(start: number, end: number): number[] { const all: number[] = [] for (let i = start; i <= end; i++) { all.push(i) } return all } }
the_stack
import { Source, Manga, Chapter, ChapterDetails, SearchRequest, LanguageCode, MangaStatus, PagedResults, SourceInfo, HomeSection, } from "paperback-extensions-common" import { chapId, chapNum, chapName, chapVol, chapGroup, unixToDate, } from "./Functions" const HACHIRUMI_DOMAIN = "https://hachirumi.com" const HACHIRUMI_API = `${HACHIRUMI_DOMAIN}/api` const HACHIRUMI_IMAGES = ( slug: string, folder: string, group: string, ext: string ) => `https://hachirumi.com/media/manga/${slug}/chapters/${folder}/${group}/${ext}` /* * # Error Methods * {Message}. @{Method} on {traceback-able method/function/constants/variables} * eg: Failed to parse the response. @getResult on result. * ``` * getResult(){ * const fetch = // * } * ``` */ // Types for no reason interface getAllTitlesType { /** * MangaID/ slug of this object. */ mangaId: string /** * Title of this object. */ title: string /** * Author of this object. */ author: string /** * Artist of this object. */ artist: string /** * Description of this object. */ desc: string /** * Cover of this object. */ cover: string /** * Array of groups of this object. */ group: string[] /** * Unix time stamp of this object. */ last: number } export const HachirumiInfo: SourceInfo = { version: "1.0.0", name: "Hachirumi", icon: "icon.png", author: "Curstantine", authorWebsite: "https://github.com/Curstantine", description: "Extension that pulls manga from Hachirumi.", language: LanguageCode.ENGLISH, hentaiSource: false, websiteBaseURL: HACHIRUMI_DOMAIN, } export class Hachirumi extends Source { /* Though "mangaId" is mentioned here Hachirumi uses slugs. eg: the-story-about-living */ async getMangaDetails(mangaId: string): Promise<Manga> { const methodName = this.getMangaDetails.name const request = createRequestObject({ url: HACHIRUMI_API + "/series/" + mangaId, method: "GET", headers: { "accept-encoding": "application/json", }, }) const response = await this.requestManager.schedule(request, 1) if (response.status > 400) { throw new Error( `Failed to fetch data on ${methodName} with status code: ` + response.status ) } const result = typeof response.data === "string" || typeof response.data !== "object" ? JSON.parse(response.data) : response.data if (!result || result === undefined) throw new Error(`Failed to parse the response on ${methodName}.`) return createManga({ id: result.slug, titles: [result.title], image: HACHIRUMI_DOMAIN + result.cover, rating: 0, // Rating is not supported by Hachirumi. status: MangaStatus.ONGOING, artist: result.artist, author: result.author, desc: "Hachirumi doesn't support descriptions!", // Description has html tags, even if we remove those there are useless information such as "arthor's twitter/pixiv" which doesn't make sense if it doesn't redirect upon click/press }) } /* Follows the same format as `getMangaDetails`. Hachirumi serves both chapters and manga in single request. */ async getChapters(mangaId: string): Promise<Chapter[]> { const methodName: string = this.getChapters.name const request = createRequestObject({ url: HACHIRUMI_API + "/series/" + mangaId, method: "GET", headers: { "accept-encoding": "application/json", }, }) const response = await this.requestManager.schedule(request, 1) if (response.status > 400) { throw new Error( `Failed to fetch data on ${methodName} with status code: ` + response.status ) } const result = typeof response.data === "string" || typeof response.data !== "object" ? JSON.parse(response.data) : response.data if (!result || result === undefined) throw new Error(`Failed to parse the response on ${methodName}.`) const chapterObject = result.chapters const groupObject = result.groups if (!chapterObject || !groupObject) throw new Error(`Failed to read chapter/group data on ${methodName}.`) let chapters = [] for (const key in chapterObject) { const metadata = chapterObject[key] if (!metadata || metadata === undefined) throw new Error(`Failed to read metadata on ${methodName}.`) for (const groupKey in metadata.groups) { const id = chapId(key, groupKey, metadata.folder, result.slug) chapters.push( createChapter({ id: id, mangaId: result.slug, chapNum: chapNum(key, result.slug, id), langCode: LanguageCode.ENGLISH, name: chapName(metadata.title), volume: chapVol(metadata.volume, result.slug, id), group: chapGroup(groupObject[groupKey]), time: unixToDate(metadata.release_date[groupKey]), }) ) } } return chapters } /* * Follows the chapterId format used in `getChapter` method. * `chapterKey|groupKey|folderId` */ async getChapterDetails( mangaId: string, chapterId: string ): Promise<ChapterDetails> { const methodName = this.getChapterDetails.name const request = createRequestObject({ url: HACHIRUMI_API + "/series/" + mangaId, method: "GET", headers: { "accept-encoding": "application/json", }, }) const response = await this.requestManager.schedule(request, 1) if (response.status > 400) { throw new Error( `Failed to fetch data on ${methodName} with status code: ` + response.status ) } const result = typeof response.data === "string" || typeof response.data !== "object" ? JSON.parse(response.data) : response.data if (!result || result === undefined) throw new Error(`Failed to parse the response on ${methodName}.`) const [chapterKey, groupKey, folder] = chapterId.split("|") // Splits the given generic chapter id to chapterkey and such. if (!chapterKey || !groupKey || !folder) throw new Error(`ChapterId is malformed on ${methodName}.`) const chapterObject = result.chapters if (!chapterObject || chapterObject === undefined) throw new Error(`Failed to read chapter data on ${methodName}.`) const groupObject = chapterObject[chapterKey].groups[groupKey] if (!groupObject || groupObject === undefined) throw new Error(`Failed to read chapter metadata on ${methodName}.`) return createChapterDetails({ id: chapterId, longStrip: false, // Not implemented. mangaId: mangaId, pages: groupObject.map((ext: string) => HACHIRUMI_IMAGES(mangaId, folder, groupKey, ext) ), }) } /* This method doesn't query anything, instead finds a specific title from `get_all_series` endpoint */ async searchRequest( query: SearchRequest, metadata: any ): Promise<PagedResults> { const methodName = this.searchRequest.name if (metadata?.limitReached) return createPagedResults({ results: [], metadata: { limitReached: true }, }) // Prevents title duplication. const request = createRequestObject({ url: HACHIRUMI_API + "/get_all_series", method: "GET", headers: { "accept-encoding": "application/json", }, }) const response = await this.requestManager.schedule(request, 1) if (response.status > 400) { throw new Error( `Failed to fetch data on ${methodName} with status code: ` + response.status ) } const result = typeof response.data === "string" || typeof response.data !== "object" ? JSON.parse(response.data) : response.data if (!result || result === undefined) throw new Error(`Failed to parse the response on ${methodName}.`) const queryTitle: string = query.title ? query.title.toLowerCase() : "" const filterer = (titles: object[]) => Object.keys(titles).filter((title) => title.replace("-", " ").toLowerCase().includes(queryTitle) ) const filteredRequest = filterer(result).map((title) => { const metadata = result[title] if (!metadata || metadata === undefined) throw new Error(`Failed to read chapter metadata on ${methodName}.`) return createMangaTile({ id: metadata.slug, image: HACHIRUMI_DOMAIN + metadata.cover, title: createIconText({ text: title }), }) }) return createPagedResults({ results: filteredRequest, metadata: { limitReached: true, }, }) } // Makes my life easier. <( ̄︶ ̄)> async getAllTitles(): Promise<getAllTitlesType[]> { const methodName = this.getAllTitles.name const request = createRequestObject({ url: HACHIRUMI_API + "/get_all_series", method: "GET", headers: { "accept-encoding": "application/json", }, }) const response = await this.requestManager.schedule(request, 1) if (!response || response === undefined) throw new Error(`Failed to fetch data from the server on ${methodName}.`) const result = typeof response.data === "string" || typeof response.data !== "object" ? JSON.parse(response.data) : response.data if (!result || result === undefined) throw new Error(`Failed to parse the response on ${methodName}.`) return Object.keys(result).map((title) => { const metadata = result[title] if (!metadata || metadata === undefined) throw new Error(`Failed to read chapter metadata on ${methodName}.`) return { mangaId: metadata.slug, title: title, author: metadata.author, artist: metadata.artist, desc: metadata.description, cover: metadata.cover, group: Object.keys(metadata.groups).map((key) => metadata.groups[key]), last: metadata.last_updated, } }) } async getHomePageSections( sectionCallback: (section: HomeSection) => void ): Promise<void> { let latestSection = createHomeSection({ id: "latest", title: "Latest Updates", view_more: false, }) let allSection = createHomeSection({ id: "all", title: "All Titles", view_more: true, }) sectionCallback(latestSection) sectionCallback(allSection) const allTitles = await this.getAllTitles() allSection.items = allTitles.map((title) => createMangaTile({ id: title.mangaId, image: HACHIRUMI_DOMAIN + title.cover, title: createIconText({ text: title.title }), }) ) sectionCallback(allSection) const sortedTitles = allTitles.sort((a, b) => b.last - a.last) while (sortedTitles.length > 9) sortedTitles.pop() while (allTitles.length > 9) allTitles.pop() latestSection.items = sortedTitles.map((title) => createMangaTile({ id: title.mangaId, image: HACHIRUMI_DOMAIN + title.cover, title: createIconText({ text: title.title }), }) ) sectionCallback(latestSection) } async getViewMoreItems( homepageSectionId: string, metadata: any ): Promise<PagedResults | null> { if (metadata?.limitReached) return createPagedResults({ results: [], metadata: { limitReached: true }, }) // Prevents title duplication. const allTitles = await this.getAllTitles() return createPagedResults({ results: allTitles.map((title) => createMangaTile({ id: title.mangaId, image: HACHIRUMI_DOMAIN + title.cover, title: createIconText({ text: title.title }), }) ), metadata: { limitReached: true, }, }) } getMangaShareUrl(mangaId: string) { return `${HACHIRUMI_DOMAIN}/read/manga/${mangaId}/` } getCloudflareBypassRequest() { return createRequestObject({ url: HACHIRUMI_DOMAIN, method: "GET", }) } }
the_stack
import {refine, Parser, TokenRange} from '../Parsec'; import * as K from '../Kit'; import {OK, Err, Charset} from '../Kit'; import Unicode from '../Unicode'; import * as UnicodeProperty from '../UnicodeProperty'; import * as AST from '../AST'; import {Omit} from 'utility-types'; import * as Parsec from '../Parsec'; export {TokenRange} from '../Parsec'; export type RawLexeme = { type: 'VBar' | 'Paren' | 'CharClassBracket' | 'GroupBehavior' | 'GroupAssertionBehavior'; range: TokenRange; }; export type Lexeme = AST.LeafNode | AST.CharRangeNode | RawLexeme; export type RegexError = { type: | 'SyntaxError' | 'ParenMismatch' | 'OctEscape' | 'IdentityEscape' | 'NothingToRepeat' | 'CharClassEscapeB' | 'CharClassEscapeInRange' | 'UnicodeEscape' | 'UnicodeIDEscape' | 'BackrefNotExist' | 'BackrefEmpty' | 'DupGroupName' | 'QuantifierOutOfOrder' | 'CharRangeOutOfOrder' | 'Identifier' | 'UnicodePropertyName' | 'UnicodePropertyValue'; // A more precise error range range: TokenRange; }; export type RegexParseState = { flags: AST.RegexFlags; features: { legacy: Partial<{ octalEscape: boolean; identityEscape: boolean; charClassEscapeInCharRange: boolean; }>; }; loose?: boolean; // Previous unclosed open paren or bracket positions openPairs: number[]; }; export type RegexParser<T> = Parser<string, T, RegexParseState, RegexError>; export type RegexParseResult = K.Result<AST.Regex, RegexError>; export const lineTerms = '\n\r\u2028\u2029'; export const syntaxChars = '^$\\.*+?()[]{}|/'; export const controlEscapeMap: {[c: string]: string} = { f: '\f', n: '\n', r: '\r', t: '\t', v: '\v' }; export const charClassEscapeTypeMap: {[c: string]: AST.BaseCharClass} = { s: 'Space', S: 'NonSpace', d: 'Digit', D: 'NonDigit', w: 'Word', W: 'NonWord' }; export const baseAssertionTypeMap: {[k: string]: AST.BaseAssertionType} = { '\\b': 'WordBoundary', '\\B': 'NonWordBoundary', '^': 'Begin', $: 'End' }; export const groupAssertionTypeMap: Record< string, [AST.GroupAssertionNode['look'], AST.GroupAssertionNode['negative']] > = { '?=': ['Lookahead', false], '?!': ['Lookahead', true], '?<=': ['Lookbehind', false], '?<!': ['Lookbehind', true] }; export const invCharClassEscapeTypeMap = K.invertRecord(charClassEscapeTypeMap); export const invBaseAssertionTypeMap = K.invertRecord(baseAssertionTypeMap); export const invGroupAssertionTypeMap = K.invertRecord(groupAssertionTypeMap); /** Parse "*,+,?" with optional non greedy mark "?" */ export function parseBaseQuantifier(q?: string): AST.QuantifierNode { let a = {type: 'Quantifier' as const, min: 0, max: Infinity, greedy: true, range: [0, 0] as [number, number]}; if (!q) return a; if (q[0] === '?') { a.max = 1; } else if (q[0] === '+') { a.min = 1; } if (q[1] === '?') { a.greedy = false; } return a; } export function showQuantifier(n: Omit<AST.QuantifierNode, 'range'>) { let q = ''; if (n.min === 0 && n.max === 1) { q = '?'; } else if (n.min === 0 && n.max === Infinity) { q = '*'; } else if (n.min === 1 && n.max === Infinity) { q = '+'; } else if (n.max === Infinity) { q = '{' + n.min + ',}'; } else if (n.min === n.max) { q = '{' + n.min + '}'; } else { q = '{' + n.min + ',' + n.max + '}'; } if (n.greedy === false) { q += '?'; } return q; } export const IDCharset = { ID_Start: Unicode.Binary_Property.ID_Start.union(Charset.fromChars('$_')), // ZWJ = \u200D; ZWNJ = \u200C ID_Continue: Unicode.Binary_Property.ID_Continue.union(Charset.fromChars('$_\u200C\u200D')) }; export const IDRegex = new RegExp( '^' + IDCharset.ID_Start.toRegex().source + IDCharset.ID_Continue.toRegex().source + '*$', 'u' ); export function asNode<T extends AST.NodeBase>(type?: T['type']) { return function(v: Omit<T, 'range' | 'type'>, ctx: {range: TokenRange}): T { let a = v as any; if (!a.type && type) { a.type = type; } a.range = ctx.range; return a; }; } const P = refine<string, RegexParseState, RegexError>(); /** Base Regex Grammar Definition */ export abstract class BaseGrammar { Char = P.parseBy<AST.CharNode>(ctx => { const _charRegex = /[^$^\\.*+?()[{|]/y; const _unicodeCharRegex = /[^$^\\.*+?()[{|]/uy; let re = ctx.state.flags.unicode ? _unicodeCharRegex : _charRegex; re.lastIndex = ctx.position; let m = re.exec(ctx.input); if (m === null) { return {error: true, consumed: 0}; } let c = m[0]; return {value: {type: 'Char', value: c, range: [ctx.position, ctx.position + c.length]}, consumed: c.length}; }); Dot = P.exact('.').map((_, ctx) => asNode<AST.DotNode>('Dot')({}, ctx)); BaseCharClassEscape = P.re(/\\([dDsSwW])/).map((m, ctx) => asNode<AST.CharClassEscapeNode>('CharClassEscape')({charClass: charClassEscapeTypeMap[m[1]]}, ctx) ); RawUnicodeCharClassEscape = P.re(/\\(p)\{([^{}=]*)(?:=([^{}]*))?\}/i); UnicodeCharClassEscape = this.RawUnicodeCharClassEscape.mapE<AST.UnicodeCharClass>((m, ctx) => { let loose = ctx.state.loose; let invert = m[1] === 'P'; let name = m[2]; let value = m[3]; function makeError(t: RegexError['type'], range: TokenRange): K.Result<AST.UnicodeCharClass, RegexError> { if (loose) { return K.OK({name, invert, value}); } return {error: {type: t, range}}; } if (!name) return makeError('UnicodePropertyName', [ctx.range[0] + 2, ctx.range[1] - 1]); name = UnicodeProperty.aliasMap.get(name) || name; if (value) { value = UnicodeProperty.aliasMap.get(value) || value; if (!UnicodeProperty.RawAliasData.NonBinary_Property.hasOwnProperty(name)) { return makeError('UnicodePropertyName', [ctx.range[0] + 2, ctx.range[0] + 2 + m[2].length]); } let unicodePropValues = (UnicodeProperty.canonical as any)[name]; if (!unicodePropValues.has(value)) { return makeError('UnicodePropertyValue', [ctx.range[0] + 3 + m[2].length, ctx.range[1] - 1]); } return K.OK({name, value, invert}); } else { if (UnicodeProperty.canonical.Binary_Property.has(name)) { return K.OK({name, invert}); } else if (UnicodeProperty.canonical.General_Category.has(name)) { return K.OK({name: 'General_Category', value: name, invert}); } else { return makeError('UnicodePropertyValue', [ctx.range[0] + 2, ctx.range[1] - 1]); } } }).map((cat, ctx) => asNode<AST.CharClassEscapeNode>('CharClassEscape')({charClass: cat}, ctx)); NullCharEscape = P.re(/\\0(?=\D|$)/).map((_, ctx) => asNode<AST.CharNode>('Char')({value: '\0'}, ctx)); DecimalEscape = P.alts( P.re(/\\([1-9]\d*)/).mapE((m, ctx) => { let index = +m[1]; return {value: asNode<AST.BackrefNode>('Backref')({index}, ctx)}; }), this.NullCharEscape, P.re(/\\(0\d+)/).mapE<AST.CharNode>((m, ctx) => { if (ctx.state.features.legacy.octalEscape) { return {value: asNode<AST.CharNode>('Char')({value: String.fromCharCode(parseInt(m[1], 8))}, ctx)}; } return {error: {type: 'OctEscape', range: ctx.range}}; }) ); /* Full unicode atom /^\u{1F437}+$/u == /^\uD83D\uDC37+$/u , match "🐷🐷🐷". Isolated Unicode LeadSurrogate or TrailSurrogate only match char not follow or followed by Surrogate. But /^\u{D83D}\u{DC37}$/u never match anthing, any char specified by /\u{CodePoint}/ form always be regarded as single char even consecutive surrogates wont be merged. */ RegExpUnicodeEscapeSequence = P.parseBy<string>(ctx => { let unicodeMode = ctx.state.flags.unicode; /* \u LeadSurrogate \u TrailSurrogate /\\u(D[89AB][0-9A-F]{2})\\u(D[CDEF][0-9A-F]{2})/i \u{CodePoint} or \u Hex4Digits (include isolated Lead or Tail Surrogate) /\\u\{([0-9A-F]+)\}|\\u([0-9A-F]{4})/i */ let re = unicodeMode ? /\\u(D[89AB][0-9A-F]{2})\\u(D[CDEF][0-9A-F]{2})|\\u\{([0-9A-F]+)\}|\\u([0-9A-F]{4})/iy : /\\u([A-F0-9]{4})/iy; re.lastIndex = ctx.position; let m = re.exec(ctx.input); if (m === null) { return {error: true, consumed: 0}; } let a: any = makeUnicodeEscape(...m.slice(1).filter(Boolean)); if (a.error) { a.error.range = [ctx.position, ctx.position + m[0].length]; } a.consumed = m[0].length; return a; }); ID_Start = P.charset(IDCharset.ID_Start); ID_Continue = P.charset(IDCharset.ID_Continue); RegExpIdentifierStart = P.alts( this.ID_Start, this.RegExpUnicodeEscapeSequence.mapE(checkIDEscape(IDCharset.ID_Start)) ); RegExpIdentifierContinue = P.alts( this.ID_Continue, this.RegExpUnicodeEscapeSequence.mapE(checkIDEscape(IDCharset.ID_Continue)) ); RegExpIdentifierName = P.seqs(this.RegExpIdentifierStart, this.RegExpIdentifierContinue.repeat()).map(a => { return a[0] + a[1].join(''); }); CharEscape = P.alts( P.re(/\\([fnrtv])/).map(m => controlEscapeMap[m[1]]), /* ControlLetter */ P.re(/\\c([A-Z])/i).map(m => K.Char.ctrl(m[1])), /* HexEscapeSequence */ P.re(/\\(x[A-F0-9][A-F0-9])/i).map(m => String.fromCharCode(parseInt('0' + m[1], 16))), this.RegExpUnicodeEscapeSequence, /* IdentityEscape */ P.re(/\\(.)/s).mapE((m, ctx) => { let unicodeMode = ctx.state.flags.unicode; let c = m[1]; if (!ctx.state.features.legacy.identityEscape && unicodeMode && !syntaxChars.includes(c)) { return K.Err({type: 'IdentityEscape', range: ctx.range}); } else { return {value: c}; } }) ).map((c, ctx) => asNode<AST.CharNode>('Char')({value: c}, ctx)); CharClassEscape = P.alts(this.BaseCharClassEscape, this.UnicodeCharClassEscape); CharClass() { return P.seqs(P.exact('^').opt(), this.CharClassRanges()) .betweens('[', ']') .map(([sign, ranges], ctx) => asNode<AST.CharClassNode>('CharClass')({invert: !!sign, body: ranges}, ctx)); } CharClassRanges() { return this.CharClassAtom() .repeat() .mapE<AST.CharClassItem[]>((ranges, ctx) => { let allowCharClassEscapeInCharRange = ctx.state.features.legacy.charClassEscapeInCharRange; let stack: Array<AST.CharClassItem> = []; let prevHyphen = false; for (let r of ranges) { let hyphen = r.type === 'Char' && ctx.input.slice(...r.range) === '-'; let prev = stack[stack.length - 2]; if (!prevHyphen || stack.length === 1 || prev.type === 'CharRange') { // Case: [-a], [a-c-f] at "f" prevHyphen = hyphen; stack.push(r); continue; } prevHyphen = hyphen; let begin = prev; let end = r; if (begin.type === 'CharClassEscape' || end.type === 'CharClassEscape') { if (allowCharClassEscapeInCharRange) { stack.push(r); continue; } return { error: { type: 'CharClassEscapeInRange', range: (begin.type === 'CharClassEscape' ? begin : end).range } }; } if (K.compareFullUnicode(begin.value, end.value) > 0) { if (ctx.state.loose) { stack.push(end); continue; } return { error: { type: 'CharRangeOutOfOrder', range: [begin.range[0], end.range[1]] } }; } stack.length -= 2; // pop hyphen and prev stack.push({type: 'CharRange', begin, end, range: [begin.range[0], end.range[1]]}); } return OK(stack); }); } CharClassAtom() { const specialChars: {[k: string]: string} = {'\\b': '\x08', '\\-': '-', '\\0': '\0', '\\B': 'B'}; const _classAtomRegex = /\\[bB0-]|[^\\\]]/y; const _unicodeClassAtomRegex = new RegExp(_classAtomRegex.source, 'uy'); return P.alts( P.parseBy<AST.CharNode>(ctx => { let re = ctx.state.flags.unicode ? _unicodeClassAtomRegex : _classAtomRegex; re.lastIndex = ctx.position; let m = re.exec(ctx.input); if (m === null) { return {error: true, consumed: 0}; } let s = m[0]; let consumed = s.length; let range = [ctx.position, ctx.position + consumed]; if (s === '\\B' && !ctx.state.loose) { return {error: {type: 'CharClassEscapeB', range} as RegexError, consumed}; } s = specialChars[s] || s; return {value: {type: 'Char', value: s, range: range} as AST.CharNode, consumed}; }), P.alts(this.CharClassEscape, this.CharEscape) ); } Quantifier: RegexParser<AST.QuantifierNode> = P.re(/(?:{(\d+)(,(\d+)?)?}|([*+?]))\??/).mapE((m, ctx) => { let toQNode = (q: Omit<AST.QuantifierNode, 'range'>) => OK(asNode<AST.QuantifierNode>('Quantifier')(q, ctx)); if (m[4]) return toQNode(parseBaseQuantifier(m[0])); let [_, mins, c, maxs] = m; let r = parseBaseQuantifier(); r.min = +mins; if (c === undefined) { r.max = r.min; } else if (maxs !== undefined) { r.max = +maxs; } if (r.min > r.max && !ctx.state.loose) { return {error: {type: 'QuantifierOutOfOrder', range: ctx.range}}; } if (m[0].slice(-1) === '?') { r.greedy = false; } return toQNode(r); }); BaseAssertion = P.re(/\^|\$|\\b|\\B/).map((m, ctx) => { return asNode<AST.BaseAssertionNode>('BaseAssertion')({kind: baseAssertionTypeMap[m[0]]}, ctx); }); GroupAssertionBehavior = P.alts(...Object.keys(groupAssertionTypeMap).map(s => P.exact('(' + s))).map( (prefix, ctx) => { let [look, negative] = groupAssertionTypeMap[prefix.slice(1)]; ctx.state.openPairs.push(ctx.range[0]); return {assertion: <Omit<AST.GroupAssertionNode, 'body'>>{look, negative}}; } ); openParen = P.exact('(').stateF((st, ctx) => { st.openPairs.push(ctx.range[0]); return st; }); closeParen = P.alts(P.exact(')'), P.eof).mapE((s, ctx) => { // Not reentrant path, it's safe to modifiy state let pos = ctx.state.openPairs.pop(); if (s === undefined) { return {error: {type: 'ParenMismatch', range: [pos, pos]}} as Err<RegexError>; } return {value: s}; }); abstract Term(): RegexParser<AST.ListNode['body'][number]>; Disjunction(): RegexParser<AST.Expr> { // Disjunction function toNodeList<T extends AST.ListNode['body'][number]>(nodes: T[]): T | AST.ListNode { if (nodes.length === 1) { return nodes[0]; } else { return asNode<AST.ListNode>('List')( {body: nodes}, {range: [nodes[0].range[0], nodes[nodes.length - 1].range[1]]} ); } } return P.seqs( this.Term() .many() .map((terms, ctx) => (terms.length ? toNodeList(terms) : AST.makeEmptyNode(ctx.range[0]))), P.seqs(P.exact('|'), this.Disjunction()).opt() ).map((v, ctx) => { let [left, remain] = v; let right = remain ? remain[1] : undefined; if (right) { let body = right.type === 'Disjunction' ? [left, ...right.body] : [left, right]; return asNode<AST.DisjunctionNode>('Disjunction')({body}, ctx); } else { return left; } }); } } export function check(re: AST.Node): K.Maybe<RegexError> { let totalGroups = AST.renumberGroups(re); type GroupEnv = {names: string[]; indices: number[]}; type EnvBackup = {namesLength: number; indicesLength: number}; let groupEnv: GroupEnv = {names: [], indices: []}; let regexError: K.Maybe<RegexError>; function backupEnv(): EnvBackup { return {indicesLength: groupEnv.indices.length, namesLength: groupEnv.names.length}; } function restoreEnv(backup: EnvBackup) { groupEnv.indices.length = backup.indicesLength; groupEnv.names.length = backup.namesLength; } try { _check(re); } catch (e) { if (regexError) { return regexError; } throw e; } function _check(node: AST.Node) { AST.match(node, { Backref(n) { let errType: K.Maybe<RegexError['type']>; if (typeof n.index === 'number') { if (n.index > totalGroups.count) { errType = 'BackrefNotExist'; } else if (!groupEnv.indices.includes(n.index)) { errType = 'BackrefEmpty'; } } else { if (!totalGroups.names.has(n.index)) { errType = 'BackrefNotExist'; } else if (!groupEnv.names.includes(n.index)) { errType = 'BackrefEmpty'; } } if (errType) { regexError = {type: errType, range: n.range}; throw null; } }, Group(n) { _check(n.body); if (n.behavior.type === 'Capturing') { groupEnv.indices.push(n.behavior.index); if (n.behavior.name) { groupEnv.names.push(n.behavior.name); } } }, GroupAssertion(n) { if (n.negative) { let backup = backupEnv(); _check(n.body); restoreEnv(backup); } else { _check(n.body); } }, Disjunction(n) { let backup = backupEnv(); let merged = {names: groupEnv.names.slice(), indices: groupEnv.indices.slice()}; n.body.forEach(a => { _check(a); merged.names.push(...groupEnv.names.slice(backup.namesLength)); merged.indices.push(...groupEnv.indices.slice(backup.indicesLength)); restoreEnv(backup); }); groupEnv = merged; }, List(n) { n.body.forEach(_check); }, Repeat(n) { _check(n.body); }, defaults(n) {} }); } } function checkIDEscape(ch: Charset): (c: string, ctx: {range: TokenRange}) => K.Result<string, RegexError> { return (c, ctx) => { if (ch.includeChar(c)) { return {value: c}; } else { return {error: {type: 'UnicodeIDEscape', range: ctx.range}}; } }; } function makeUnicodeEscape(...points: string[]): K.Result<string, Omit<RegexError, 'range'>> { let codePoints = points.map(c => parseInt('0x' + c, 16)); let c; try { c = String.fromCodePoint.apply(String, codePoints); return K.OK(c); } catch (e) { // CodePoint out of range return {error: {type: 'UnicodeEscape'}}; } } /** Convert Regex Node to source string */ export function toSource(node: AST.Node): string { return AST.bottomUp<string>(node, (n, parent) => { function escape(node: AST.CharNode) { let s = K.escapeRegex(node.value, parent && (parent.type === 'CharRange' || parent.type === 'CharClass')); const escapes: {[k: string]: string} = { '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t' }; const re = /[\b\f\n\r\t\u2028\u2029\uD800-\uDBFF\uDC00-\uDFFF]/g; s = s.replace(re, c => { let e = escapes[c]; if (e) return e; return K.escapeUnicodes(c, false); }); return s; } function fixStickyDecimalEscape(a: string[]): string { return a .reduce( (prev, cur) => { let end = prev[prev.length - 1]; if (end && /\\\d*$/.test(end) && /^\d/.test(cur)) { prev.push(K.Char.hexEscape(cur[0]), cur.slice(1)); } else { prev.push(cur); } return prev; }, [] as string[] ) .join(''); } return AST.match<string, string>(n, { Char: escape, Dot: _ => '.', CharRange(n) { return n.begin + '-' + n.end; }, CharClass(n) { return '[' + (n.invert ? '^' : '') + fixStickyDecimalEscape(n.body) + ']'; }, CharClassEscape(n) { if (typeof n.charClass === 'string') { return '\\' + invCharClassEscapeTypeMap[n.charClass]; } else { let cat = n.charClass; let p = cat.invert ? 'P' : 'p'; return '\\' + p + '{' + cat.name + (cat.value ? '=' + cat.value : '') + '}'; } }, Backref(n) { if (typeof n.index === 'string') { return '\\k<' + n.index + '>'; } else { return '\\' + n.index; } }, GroupAssertion(n) { let prefix = invGroupAssertionTypeMap[[n.look, n.negative] + '']; return '(' + prefix + n.body + ')'; }, BaseAssertion(n) { return invBaseAssertionTypeMap[n.kind]; }, Group(n) { let specifier = ''; if (n.behavior.type === 'NonCapturing') { specifier = '?:'; } else if (n.behavior.type === 'Capturing' && n.behavior.name) { specifier = '?<' + n.behavior.name + '>'; } return '(' + specifier + n.body + ')'; }, Repeat(n) { return n.body + n.quantifier; }, Quantifier: showQuantifier, List(n) { return fixStickyDecimalEscape(n.body); }, Disjunction(n) { return n.body.join('|'); } }); }); }
the_stack
import { CustomPropertyDecorator, TypeOverride } from "@plumier/reflect" import validatorJs from "validator" import * as v from "./validation" interface Opt { message?: string } namespace val { function check(validator: (x: string) => boolean, message: string) { return v.createValidation(x => !validator(x) ? message : undefined) } /** * Check if the string is a date that's after the specified date * @param date date, default now */ export function after(date?: string): CustomPropertyDecorator /** * Check if the string is a date that's after the specified date * @param opt options */ export function after(opt?: Opt & { date?: string }): CustomPropertyDecorator export function after(op?: string | Opt & { date?: string }) { const opt = typeof op === "string" ? { date: op, message: undefined } : op return check(x => validatorJs.isAfter(x, opt && opt.date), opt && opt.message || `Date must be greater than ${opt && opt.date || "today"}`) } /** * Check if the string contains only letters (a-zA-Z). * @param opt options */ export function alpha(opt?: Opt & { locale?: validatorJs.AlphaLocale }) { return check(x => validatorJs.isAlpha(x, opt && opt.locale), opt && opt.message || "Invalid alpha") } /** * Check if the string contains only letters and numbers. * @param opt options */ export function alphanumeric(opt?: Opt & { locale?: validatorJs.AlphaLocale }) { return check(x => validatorJs.isAlphanumeric(x, opt && opt.locale), opt && opt.message || "Invalid alpha numeric") } /** * Check if the string contains ASCII chars only. * @param opt options */ export function ascii(opt?: Opt) { return check(x => validatorJs.isAscii(x), opt && opt.message || "Invalid ascii") } /** * Check if a string is base64 encoded. * @param opt options */ export function base64(opt?: Opt) { return check(x => validatorJs.isBase64(x), opt && opt.message || "Invalid base 64") } /** * Check if the string is a date that's before the specified date. * @param date date, default now */ export function before(date?: string): CustomPropertyDecorator /** * Check if the string is a date that's before the specified date. * @param opt options */ export function before(opt?: Opt & { date?: string }): CustomPropertyDecorator export function before(op?: string | Opt & { date?: string }) { const opt = typeof op === "string" ? { date: op, message: undefined } : op return check(x => validatorJs.isBefore(x, opt && opt.date), opt && opt.message || `Date must be less than ${opt && opt.date || "today"}`) } /** * Check if the string's length (in UTF-8 bytes) falls in a range. * @param opt options */ export function byteLength(opt: Opt & validatorJs.IsByteLengthOptions) { return check(x => validatorJs.isByteLength(x, opt), opt && opt.message || "Invalid byte length") } /** * Check if the string is a credit card. * @param opt options */ export function creditCard(opt?: Opt) { return check(x => validatorJs.isCreditCard(x), opt && opt.message || "Invalid credit card number") } /** * Check if the string is a valid currency amount. * @param opt options */ export function currency(opt?: Opt & validatorJs.IsCurrencyOptions) { return check(x => validatorJs.isCurrency(x, opt), opt && opt.message || "Invalid currency") } /** * Check if the string is a [data uri format](https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs). * @param opt options */ export function dataURI(opt?: Opt) { return check(x => validatorJs.isDataURI(x), opt && opt.message || "Invalid data URI") } /** * Check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0 etc. * @param opt options */ export function decimal(opt?: Opt & validatorJs.IsDecimalOptions) { return check(x => validatorJs.isDecimal(x, opt), opt && opt.message || "Invalid decimal") } /** * Check if the string is a number that's divisible by another. * @param num divider number */ export function divisibleBy(num: number): CustomPropertyDecorator /** * Check if the string is a number that's divisible by another. * @param opt options */ export function divisibleBy(opt: Opt & { num: number }): CustomPropertyDecorator export function divisibleBy(op: number | Opt & { num: number }) { const opt = typeof op === "number" ? { num: op, message: undefined } : op return check(x => validatorJs.isDivisibleBy(x, opt.num), opt && opt.message || `Not divisible by ${opt.num}`) } /** * Check if the string is an email. * @param opt options */ export function email(opt?: Opt & validatorJs.IsEmailOptions) { return check(x => validatorJs.isEmail(x, opt), opt && opt.message || "Invalid email address") } /** * Check if the string is a fully qualified domain name (e.g. domain.com). * @param opt options */ export function fqdn(opt?: Opt & validatorJs.IsFQDNOptions) { return check(x => validatorJs.isFQDN(x, opt), opt && opt.message || "Invalid FQDN") } /** * Check if the string is a float. * @param opt options */ export function float(opt?: Opt & validatorJs.IsFloatOptions) { return check(x => validatorJs.isFloat(x, opt), opt && opt.message || "Invalid float number") } /** * Check if the string contains any full-width chars. * @param opt options */ export function fullWidth(opt?: Opt) { return check(x => validatorJs.isFullWidth(x), opt && opt.message || "Invalid value provided") } /** * Check if the string contains any half-width chars. * @param opt options */ export function halfWidth(opt?: Opt) { return check(x => validatorJs.isHalfWidth(x), opt && opt.message || "Invalid value provided") } /** * Check if the string is a hash of type algorithm. * @param algorithm algorithm */ export function hash(algorithm: validatorJs.HashAlgorithm): CustomPropertyDecorator /** * Check if the string is a hash of type algorithm. * @param opt options */ export function hash(opt: Opt & { algorithm: validatorJs.HashAlgorithm }): CustomPropertyDecorator export function hash(op: validatorJs.HashAlgorithm | Opt & { algorithm: validatorJs.HashAlgorithm }) { const opt = typeof op === "string" ? { algorithm: op, message: undefined } : op return check(x => validatorJs.isHash(x, opt.algorithm), opt && opt.message || "Invalid hash") } /** * Check if the string is a hexadecimal color. * @param opt options */ export function hexColor(opt?: Opt) { return check(x => validatorJs.isHexColor(x), opt && opt.message || "Invalid hex color") } /** * Check if the string is a hexadecimal number. * @param opt options */ export function hexadecimal(opt?: Opt) { return check(x => validatorJs.isHexadecimal(x), opt && opt.message || "Invalid hexadecimal") } /** * Check if the string is an IP (version 4 or 6). * @param version IP version */ export function ip(version?: "4" | "6"): CustomPropertyDecorator /** * Check if the string is an IP (version 4 or 6). * @param opt options */ export function ip(opt?: Opt & { version?: "4" | "6" }): CustomPropertyDecorator export function ip(op?: "4" | "6" | Opt & { version?: "4" | "6" }) { const opt = typeof op === "string" ? { version: op, message: undefined } : op return check(x => validatorJs.isIP(x, opt && opt.version), opt && opt.message || "Invalid IP address") } /** * Check if the string is an ISBN (version 10 or 13). * @param version ISBN version */ export function isbn(version?: "10" | "13"): CustomPropertyDecorator /** * Check if the string is an ISBN (version 10 or 13). * @param opt options */ export function isbn(opt?: Opt & { version?: "10" | "13" }): CustomPropertyDecorator export function isbn(op?: "10" | "13" | Opt & { version?: "10" | "13" }) { const opt = typeof op === "string" ? { version: op, message: undefined } : op return check(x => validatorJs.isISBN(x, opt && opt.version), opt && opt.message || "Invalid ISBN") } /** * Check if the string is an [ISIN](https://en.wikipedia.org/wiki/International_Securities_Identification_Number) (stock/security identifier). * @param opt options */ export function isin(opt?: Opt) { return check(x => validatorJs.isISIN(x), opt && opt.message || "Invalid ISIN") } /** * Check if the string is a valid [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) officially assigned country code. * @param opt options */ export function iso31661Alpha2(opt?: Opt) { return check(x => validatorJs.isISO31661Alpha2(x), opt && opt.message || "Invalid ISO 31661 Alpha 2") } /** * Check if the string is a valid [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date. * @param opt options */ export function iso8601(opt?: Opt) { return check(x => validatorJs.isISO8601(x), opt && opt.message || "Invalid ISO 8601 date") } /** * Check if the string is a [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code). * @param opt options */ export function isrc(opt?: Opt) { return check(x => validatorJs.isISRC(x), opt && opt.message || "Invalid ISRC") } /** * Check if the string is an [ISSN](https://en.wikipedia.org/wiki/International_Standard_Serial_Number). * @param opt options */ export function issn(opt?: Opt & validatorJs.IsISSNOptions) { return check(x => validatorJs.isISSN(x, opt), opt && opt.message || "Invalid ISSN") } /** * Check if the string is an integer. * @param opt options */ export function int(opt?: Opt & validatorJs.IsIntOptions) { return check(x => validatorJs.isInt(x, opt), opt && opt.message || "Invalid integer") } /** * Check if the string is valid JSON (note: uses JSON.parse). * @param opt options */ export function json(opt?: Opt) { return check(x => validatorJs.isJSON(x), opt && opt.message || "Invalid JSON") } /** * Check if the string is a valid latitude-longitude coordinate in the format: * * `lat,long` or `lat, long`. * @param opt options */ export function latLong(opt?: Opt) { return check(x => validatorJs.isLatLong(x), opt && opt.message || "Invalid lat long") } /** * Check if the string's length falls in a range. * * Note: this function takes into account surrogate pairs. * @param opt options */ export function length(opt: Opt & validatorJs.IsLengthOptions) { return check(x => validatorJs.isLength(x, opt), opt && opt.message || "Invalid length") } /** * Check if the string is lowercase. * @param opt options */ export function lowerCase(opt?: Opt) { return check(x => validatorJs.isLowercase(x), opt && opt.message || "Invalid lower case") } /** * Check if the string is a MAC address. * @param opt options */ export function macAddress(opt?: Opt) { return check(x => validatorJs.isMACAddress(x), opt && opt.message || "Invalid MAC address") } /** * Check if the string is a MD5 hash. * @param opt options */ export function md5(opt?: Opt) { return check(x => validatorJs.isMD5(x), opt && opt.message || "Invalid MD5 hash") } /** * Check if the string matches to a valid [MIME type](https://en.wikipedia.org/wiki/Media_type) format. * @param opt options */ export function mimeType(opt?: Opt) { return check(x => validatorJs.isMimeType(x), opt && opt.message || "Invalid mime type") } /** * Check if the string is a mobile phone number. * @param opt options */ export function mobilePhone(opt?: Opt & { locale?: validatorJs.MobilePhoneLocale, options?: validatorJs.IsMobilePhoneOptions }) { return check(x => validatorJs.isMobilePhone(x, opt && opt.locale, opt && opt.options), opt && opt.message || "Invalid mobile phone") } /** * Check if the string is a valid hex-encoded representation of a [MongoDB ObjectId](http://docs.mongodb.org/manual/reference/object-id/). * @param opt options */ export function mongoId(opt?: Opt) { return check(x => validatorJs.isMongoId(x), opt && opt.message || "Invalid MongoDb id") } /** * Check if the string contains one or more multibyte chars. * @param opt options */ export function multibyte(opt?: Opt) { return check(x => validatorJs.isMultibyte(x), opt && opt.message || "Invalid multi byte") } /** * Check if the string contains only numbers. * @param opt options */ export function numeric(opt?: Opt & validatorJs.IsNumericOptions) { return check(x => validatorJs.isNumeric(x), opt && opt.message || "Invalid numeric") } /** * Check if the string is a valid port number. * @param opt options */ export function port(opt?: Opt) { return check(x => validatorJs.isPort(x), opt && opt.message || "Invalid port") } /** * Check if the string is a postal code * @param opt options */ export function postalCode(opt?: Opt & { locale?: validatorJs.PostalCodeLocale }) { return check(x => validatorJs.isPostalCode(x, opt && opt.locale || "any"), opt && opt.message || "Invalid postal code") } /** * Check if string matches the pattern. * @param pattern RegExp pattern */ export function regex(pattern: RegExp): CustomPropertyDecorator /** * Check if string matches the pattern. * @param opt options */ export function regex(opt: Opt & { pattern: RegExp }): CustomPropertyDecorator export function regex(op: RegExp | Opt & { pattern: RegExp }) { const opt = op instanceof RegExp ? { pattern: op, message: undefined } : op return check(x => validatorJs.matches(x, opt.pattern), opt.message || "Invalid string") } /** * Check if the string is of type slug. * @param opt options */ export function slug(opt?: Opt) { return check(x => validatorJs.isSlug(x), opt && opt.message || "Invalid slug") } /** * Check if the string contains any surrogate pairs chars. * @param opt options */ export function surrogatePair(opt?: Opt) { return check(x => validatorJs.isSurrogatePair(x), opt && opt.message || "Invalid surrogate pair") } /** * Check if the string is an URL. * @param opt options */ export function url(opt?: Opt & validatorJs.IsURLOptions) { return check(x => validatorJs.isURL(x, opt), opt && opt.message || "Invalid url") } /** * Check if the string is a UUID (version 3, 4 or 5). * @param opt options */ export function UUID(opt?: Opt & { version?: 3 | 4 | 5 | "3" | "4" | "5" | "all" }) { return check(x => validatorJs.isUUID(x), opt && opt.message || "Invalid UUID") } /** * Check if the string is uppercase. * @param opt options */ export function uppercase(opt?: Opt) { return check(x => validatorJs.isUppercase(x), opt && opt.message || "Invalid uppercase") } /** * Check if the string contains a mixture of full and half-width chars. * @param opt options */ export function variableWidth(opt?: Opt) { return check(x => validatorJs.isVariableWidth(x), opt && opt.message || "Invalid variable width") } /** * Checks characters if they appear in the whitelist. * @param opt options */ export function whiteListed(opt: Opt & { chars: string | string[] }) { return check(x => validatorJs.isWhitelisted(x, opt && opt.chars), opt && opt.message || "Invalid white listed") } /** * Mark if the property is required */ export function required() { return v.required() } /** * Mark parameter data type as partial, any required validation will be ignored * @param typ parameter data type */ export function partial(typ: TypeOverride | ((x: any) => TypeOverride)) { return v.partial(typ) } } export { val, Opt }
the_stack
declare module Thrift { /** * Thrift JavaScript library version. */ var Version: string; /** * Thrift IDL type string to Id mapping. * @property {number} STOP - End of a set of fields. * @property {number} VOID - No value (only legal for return types). * @property {number} BOOL - True/False integer. * @property {number} BYTE - Signed 8 bit integer. * @property {number} I08 - Signed 8 bit integer. * @property {number} DOUBLE - 64 bit IEEE 854 floating point. * @property {number} I16 - Signed 16 bit integer. * @property {number} I32 - Signed 32 bit integer. * @property {number} I64 - Signed 64 bit integer. * @property {number} STRING - Array of bytes representing a string of characters. * @property {number} UTF7 - Array of bytes representing a string of UTF7 encoded characters. * @property {number} STRUCT - A multifield type. * @property {number} MAP - A collection type (map/associative-array/dictionary). * @property {number} SET - A collection type (unordered and without repeated values). * @property {number} LIST - A collection type (unordered). * @property {number} UTF8 - Array of bytes representing a string of UTF8 encoded characters. * @property {number} UTF16 - Array of bytes representing a string of UTF16 encoded characters. */ interface Type { 'STOP': number; 'VOID': number; 'BOOL': number; 'BYTE': number; 'I08': number; 'DOUBLE': number; 'I16': number; 'I32': number; 'I64': number; 'STRING': number; 'UTF7': number; 'STRUCT': number; 'MAP': number; 'SET': number; 'LIST': number; 'UTF8': number; 'UTF16': number; } var Type: Type; /** * Thrift RPC message type string to Id mapping. * @property {number} CALL - RPC call sent from client to server. * @property {number} REPLY - RPC call normal response from server to client. * @property {number} EXCEPTION - RPC call exception response from server to client. * @property {number} ONEWAY - Oneway RPC call from client to server with no response. */ interface MessageType { 'CALL': number; 'REPLY': number; 'EXCEPTION': number; 'ONEWAY': number; } var MessageType: MessageType; /** * Utility function returning the count of an object's own properties. * @param {object} obj - Object to test. * @returns {number} number of object's own properties */ function objectLength(obj: any): number; /** * Utility function to establish prototype inheritance. * @param {function} constructor - Contstructor function to set as derived. * @param {function} superConstructor - Contstructor function to set as base. * @param {string} [name] - Type name to set as name property in derived prototype. */ function inherits(constructor: Function, superConstructor: Function, name?: string): void; /** * TException is the base class for all Thrift exceptions types. */ class TException implements Error { name: string; message: string; /** * Initializes a Thrift TException instance. * @param {string} message - The TException message (distinct from the Error message). */ constructor(message: string); /** * Returns the message set on the exception. * @returns {string} exception message */ getMessage(): string; } /** * Thrift Application Exception type string to Id mapping. * @property {number} UNKNOWN - Unknown/undefined. * @property {number} UNKNOWN_METHOD - Client attempted to call a method unknown to the server. * @property {number} INVALID_MESSAGE_TYPE - Client passed an unknown/unsupported MessageType. * @property {number} WRONG_METHOD_NAME - Unused. * @property {number} BAD_SEQUENCE_ID - Unused in Thrift RPC, used to flag proprietary sequence number errors. * @property {number} MISSING_RESULT - Raised by a server processor if a handler fails to supply the required return result. * @property {number} INTERNAL_ERROR - Something bad happened. * @property {number} PROTOCOL_ERROR - The protocol layer failed to serialize or deserialize data. * @property {number} INVALID_TRANSFORM - Unused. * @property {number} INVALID_PROTOCOL - The protocol (or version) is not supported. * @property {number} UNSUPPORTED_CLIENT_TYPE - Unused. */ interface TApplicationExceptionType { 'UNKNOWN': number; 'UNKNOWN_METHOD': number; 'INVALID_MESSAGE_TYPE': number; 'WRONG_METHOD_NAME': number; 'BAD_SEQUENCE_ID': number; 'MISSING_RESULT': number; 'INTERNAL_ERROR': number; 'PROTOCOL_ERROR': number; 'INVALID_TRANSFORM': number; 'INVALID_PROTOCOL': number; 'UNSUPPORTED_CLIENT_TYPE': number; } var TApplicationExceptionType: TApplicationExceptionType; /** * TApplicationException is the exception class used to propagate exceptions from an RPC server back to a calling client. */ class TApplicationException extends TException { code: number; /** * Initializes a Thrift TApplicationException instance. * @param {string} message - The TApplicationException message (distinct from the Error message). * @param {Thrift.TApplicationExceptionType} [code] - The TApplicationExceptionType code. */ constructor(message: string, code?: number); /** * Read a TApplicationException from the supplied protocol. * @param {object} input - The input protocol to read from. */ read(input: any): void; /** * Write a TApplicationException to the supplied protocol. * @param {object} output - The output protocol to write to. */ write(output: any): void; /** * Returns the application exception code set on the exception. * @returns {Thrift.TApplicationExceptionType} exception code */ getCode(): number; } /** * The Apache Thrift Transport layer performs byte level I/O between RPC * clients and servers. The JavaScript Transport object type uses Http[s]/XHR and is * the sole browser based Thrift transport. Target servers must implement the http[s] * transport (see: node.js example server). */ class TXHRTransport { url: string; wpos: number; rpos: number; useCORS: any; send_buf: string; recv_buf: string; /** * If you do not specify a url then you must handle XHR operations on * your own. This type can also be constructed using the Transport alias * for backward compatibility. * @param {string} [url] - The URL to connect to. * @param {any} [options] - Options. */ constructor(url?: string, options?: any); /** * Gets the browser specific XmlHttpRequest Object. * @returns {object} the browser XHR interface object */ getXmlHttpRequestObject(): any; /** * Sends the current XRH request if the transport was created with a URL and * the async parameter if false. If the transport was not created with a URL * or the async parameter is True or the URL is an empty string, the current * send buffer is returned. * @param {object} async - If true the current send buffer is returned. * @param {object} callback - Optional async completion callback. * @returns {undefined|string} Nothing or the current send buffer. */ flush(async: any, callback?: Function): string; /** * Creates a jQuery XHR object to be used for a Thrift server call. * @param {object} client - The Thrift Service client object generated by the IDL compiler. * @param {object} postData - The message to send to the server. * @param {function} args - The function to call if the request suceeds. * @param {function} recv_method - The Thrift Service Client receive method for the call. * @returns {object} A new jQuery XHR object. */ jqRequest(client: any, postData: any, args: Function, recv_method: Function): any; /** * Sets the buffer to use when receiving server responses. * @param {string} buf - The buffer to receive server responses. */ setRecvBuffer(buf: string): void; /** * Returns true if the transport is open, in browser based JavaScript * this function always returns true. * @returns {boolean} Always True. */ isOpen(): boolean; /** * Opens the transport connection, in browser based JavaScript * this function is a nop. */ open(): void; /** * Closes the transport connection, in browser based JavaScript * this function is a nop. */ close(): void; /** * Returns the specified number of characters from the response * buffer. * @param {number} len - The number of characters to return. * @returns {string} Characters sent by the server. */ read(len: number): string; /** * Returns the entire response buffer. * @returns {string} Characters sent by the server. */ readAll(): string; /** * Sets the send buffer to buf. * @param {string} buf - The buffer to send. */ write(buf: string): void; /** * Returns the send buffer. * @returns {string} The send buffer. */ getSendBuffer(): string; } /** * Old alias of the TXHRTransport for backwards compatibility. */ class Transport extends TXHRTransport { } /** * The Apache Thrift Transport layer performs byte level I/O * between RPC clients and servers. The JavaScript TWebSocketTransport object * uses the WebSocket protocol. Target servers must implement WebSocket. */ class TWebSocketTransport { url: string; //Where to connect socket: any; //The web socket callbacks: any[]; //Pending callbacks send_pending: any[]; //Buffers/Callback pairs waiting to be sent send_buf: string; //Outbound data, immutable until sent recv_buf: string; //Inbound data rb_wpos: number; //Network write position in receive buffer rb_rpos: number; //Client read position in receive buffer /** * Constructor Function for the WebSocket transport. * @param {string } [url] - The URL to connect to. */ constructor(url: string); __reset(url): void; /** * Sends the current WS request and registers callback. The async * parameter is ignored (WS flush is always async) and the callback * function parameter is required. * @param {object} async - Ignored. * @param {object} callback - The client completion callback. * @returns {undefined|string} Nothing (undefined) */ flush(async: any, callback: any): string; __onOpen(): void; __onClose(): void; __onMessage(): void; __onError(): void; /** * Sets the buffer to use when receiving server responses. * @param {string} buf - The buffer to receive server responses. */ setRecvBuffer(buf: string): void; /** * Returns true if the transport is open * @returns {boolean} */ isOpen(): boolean; /** * Opens the transport connection */ open(): void; /** * Closes the transport connection */ close(): void; /** * Returns the specified number of characters from the response * buffer. * @param {number} len - The number of characters to return. * @returns {string} Characters sent by the server. */ read(len: number): string; /** * Returns the entire response buffer. * @returns {string} Characters sent by the server. */ readAll(): string; /** * Sets the send buffer to buf. * @param {string} buf - The buffer to send. */ write(buf: string): void; /** * Returns the send buffer. * @returns {string} The send buffer. */ getSendBuffer(): string; } /** * Apache Thrift Protocols perform serialization which enables cross * language RPC. The Protocol type is the JavaScript browser implementation * of the Apache Thrift TJSONProtocol. */ class TJSONProtocol { transport: Transport; /** * Thrift IDL type Id to string mapping. * The mapping table looks as follows: * Thrift.Type.BOOL -> "tf": True/False integer. * Thrift.Type.BYTE -> "i8": Signed 8 bit integer. * Thrift.Type.I16 -> "i16": Signed 16 bit integer. * Thrift.Type.I32 -> "i32": Signed 32 bit integer. * Thrift.Type.I64 -> "i64": Signed 64 bit integer. * Thrift.Type.DOUBLE -> "dbl": 64 bit IEEE 854 floating point. * Thrift.Type.STRUCT -> "rec": A multifield type. * Thrift.Type.STRING -> "str": Array of bytes representing a string of characters. * Thrift.Type.MAP -> "map": A collection type (map/associative-array/dictionary). * Thrift.Type.LIST -> "lst": A collection type (unordered). * Thrift.Type.SET -> "set": A collection type (unordered and without repeated values). */ Type: { [k: number]: string }; /** * Thrift IDL type string to Id mapping. * The mapping table looks as follows: * "tf" -> Thrift.Type.BOOL * "i8" -> Thrift.Type.BYTE * "i16" -> Thrift.Type.I16 * "i32" -> Thrift.Type.I32 * "i64" -> Thrift.Type.I64 * "dbl" -> Thrift.Type.DOUBLE * "rec" -> Thrift.Type.STRUCT * "str" -> Thrift.Type.STRING * "map" -> Thrift.Type.MAP * "lst" -> Thrift.Type.LIST * "set" -> Thrift.Type.SET */ RType: { [k: string]: number }; /** * The TJSONProtocol version number. */ Version: number; /** * Initializes a Thrift JSON protocol instance. * @param {Thrift.Transport} transport - The transport to serialize to/from. */ constructor(transport: Transport); /** * Returns the underlying transport. * @returns {Thrift.Transport} The underlying transport. */ getTransport(): Transport; /** * Serializes the beginning of a Thrift RPC message. * @param {string} name - The service method to call. * @param {Thrift.MessageType} messageType - The type of method call. * @param {number} seqid - The sequence number of this call (always 0 in Apache Thrift). */ writeMessageBegin(name: string, messageType: number, seqid: number): void; /** * Serializes the end of a Thrift RPC message. */ writeMessageEnd(): void; /** * Serializes the beginning of a struct. * @param {string} name - The name of the struct. */ writeStructBegin(name?: string): void; /** * Serializes the end of a struct. */ writeStructEnd(): void; /** * Serializes the beginning of a struct field. * @param {string} name - The name of the field. * @param {Thrift.Protocol.Type} fieldType - The data type of the field. * @param {number} fieldId - The field's unique identifier. */ writeFieldBegin(name: string, fieldType: string[], fieldId: number): void; /** * Serializes the end of a field. */ writeFieldEnd(): void; /** * Serializes the end of the set of fields for a struct. */ writeFieldStop(): void; /** * Serializes the beginning of a map collection. * @param {Thrift.Type} keyType - The data type of the key. * @param {Thrift.Type} valType - The data type of the value. * @param {number} [size] - The number of elements in the map (ignored). */ writeMapBegin(keyType: number, valType: number, size?: number): void; /** * Serializes the end of a map. */ writeMapEnd(): void; /** * Serializes the beginning of a list collection. * @param {Thrift.Type} elemType - The data type of the elements. * @param {number} size - The number of elements in the list. */ writeListBegin(elemType: number, size: number): void; /** * Serializes the end of a list. */ writeListEnd(): void; /** * Serializes the beginning of a set collection. * @param {Thrift.Type} elemType - The data type of the elements. * @param {number} size - The number of elements in the list. */ writeSetBegin(elemType: number, size: number): void; /** * Serializes the end of a set. */ writeSetEnd(): void; /** Serializes a boolean */ writeBool(value: boolean): void; /** Serializes a number */ writeByte(i8: number): void; /** Serializes a number */ writeI16(i16: number): void; /** Serializes a number */ writeI32(i32: number): void; /** Serializes a number */ writeI64(i64: number): void; /** Serializes a number */ writeDouble(dbl: number): void; /** Serializes a string */ writeString(str: string): void; /** Serializes a string */ writeBinary(str: string): void; /** @class @name AnonReadMessageBeginReturn @property {string} fname - The name of the service method. @property {Thrift.MessageType} mtype - The type of message call. @property {number} rseqid - The sequence number of the message (0 in Thrift RPC). */ /** * Deserializes the beginning of a message. * @returns {AnonReadMessageBeginReturn} */ readMessageBegin(): { fname: string; mtype: number; rseqid: number }; /** Deserializes the end of a message. */ readMessageEnd(): void; /** * Deserializes the beginning of a struct. * @param {string} [name] - The name of the struct (ignored). * @returns {object} - An object with an empty string fname property. */ readStructBegin(name?: string): any; /** Deserializes the end of a struct. */ readStructEnd(): void; /** @class @name AnonReadFieldBeginReturn @property {string} fname - The name of the field (always ''). @property {Thrift.Type} ftype - The data type of the field. @property {number} fid - The unique identifier of the field. */ /** * Deserializes the beginning of a field. * @returns {AnonReadFieldBeginReturn} */ readFieldBegin(): { fname: string; ftype: number; fid: number }; /** Deserializes the end of a field. */ readFieldEnd(): void; /** @class @name AnonReadMapBeginReturn @property {Thrift.Type} ktype - The data type of the key. @property {Thrift.Type} vtype - The data type of the value. @property {number} size - The number of elements in the map. */ /** * Deserializes the beginning of a map. * @returns {AnonReadMapBeginReturn} */ readMapBegin(): { ktype: number; vtype: number; size: number }; /** Deserializes the end of a map. */ readMapEnd(): void; /** @class @name AnonReadColBeginReturn @property {Thrift.Type} etype - The data type of the element. @property {number} size - The number of elements in the collection. */ /** * Deserializes the beginning of a list. * @returns {AnonReadColBeginReturn} */ readListBegin(): { etype: number; size: number }; /** Deserializes the end of a list. */ readListEnd(): void; /** * Deserializes the beginning of a set. * @param {Thrift.Type} elemType - The data type of the elements (ignored). * @param {number} size - The number of elements in the list (ignored). * @returns {AnonReadColBeginReturn} */ readSetBegin(elemType?: number, size?: number): { etype: number; size: number }; /** Deserializes the end of a set. */ readSetEnd(): void; /** Returns an object with a value property set to * False unless the next number in the protocol buffer * is 1, in which case the value property is True. */ readBool(): Object; /** Returns an object with a value property set to the next value found in the protocol buffer. */ readByte(): Object; /** Returns an object with a value property set to the next value found in the protocol buffer. */ readI16(): Object; /** Returns an object with a value property set to the next value found in the protocol buffer. */ readI32(f?: any): Object; /** Returns an object with a value property set to the next value found in the protocol buffer. */ readI64(): Object; /** Returns an object with a value property set to the next value found in the protocol buffer. */ readDouble(): Object; /** Returns an object with a value property set to the next value found in the protocol buffer. */ readString(): Object; /** Returns an object with a value property set to the next value found in the protocol buffer. */ readBinary(): Object; /** * Method to arbitrarily skip over data (not implemented). */ skip(type: any): void; } /** * Old alias of the TXHRTransport for backwards compatibility. */ class Protocol extends TJSONProtocol { } class MultiplexProtocol extends Protocol { serviceName: string; /** * Initializes a MutilplexProtocol Implementation as a Wrapper for Thrift.Protocol. * @param {string} srvName * @param {Thrift.Transport} trans * @param {any} [strictRead] * @param {any} [strictWrite] */ constructor(srvName: string, trans: Transport, strictRead?: any, strictWrite?: any); } class Multiplexer { seqid: number; /** Instantiates a multiplexed client for a specific service. * @param {String} serviceName - The transport to serialize to/from. * @param {Thrift.ServiceClient} SCl - The Service Client Class. * @param {Thrift.Transport} transport - Thrift.Transport instance which provides remote host:port. */ createClient(serviceName: string, SCl: any, transport: Transport); } }
the_stack
import colors from "colors"; import { Widget } from "./widget/Widget"; import { IPty } from "node-pty-prebuilt-multiarch"; import * as NodePTY from "node-pty-prebuilt-multiarch"; import * as os from "os"; import { Logger } from "../common/Logger"; import { IBlessedView } from "./IBlessedView"; import { Reader } from "../common/Reader"; import { File } from "../common/File"; import { XTerminal } from "./xterm/XTerminal"; import { AttributeData } from "./xterm/common/buffer/AttributeData"; import { ColorConfig } from "../config/ColorConfig"; import which from "which"; import { KeyMappingInfo, KeyMapping, IHelpService, Hint, Help, RefreshType } from "../config/KeyMapConfig"; import { T } from "../common/Translation"; import { SftpReader } from "../panel/sftp/SftpReader"; import { IEvent, EventEmitter } from "./xterm/common/EventEmitter"; import mainFrame from "./MainFrame"; const log = Logger("BlassedXTerm"); interface IOSC1337 { [ text: string ]: string; RemoteHost?: string; CurrentDir?: string; } class SshPty implements IPty { private _ssh2Socket; private _stream; private _cols; private _rows; async init({ reader, cols, rows, term, result }: { reader: SftpReader; cols: number; rows: number; term: string; result: ( err?: string ) => void; }) { log.debug( "shellInit: %j", { cols, rows, term } ); if ( reader.isEachConnect() ) { const sshConnReader = new SftpReader(); const connInfo = sshConnReader.convertConnectionInfo( reader.getConnInfoConfig(), /^SSH$/ ); log.debug( "RECONNECT INFO : %s", connInfo ); await sshConnReader.sessionConnect( connInfo, (err) => { if ( err === "close" ) { process.nextTick( async () => { log.info( "SSH CLOSE EVENT !!!" ); this._onExit.fire( { exitCode: -1, signal: -1 } ); }); } }, true); log.debug( "RECONNECT : %s", sshConnReader ); this._ssh2Socket = sshConnReader.getSSH2Client(); } else { log.debug( "getSSH2Client : %s", reader.getConnectInfo() ); this._ssh2Socket = reader.getSSH2Client(); } this._ssh2Socket.on("close", () => { log.debug( "this._ssh2Socket: close !!!" ); this._stream = null; this._onExit.fire( { exitCode: -1, signal: -1 } ); }); this._ssh2Socket.shell({ term, cols, rows }, (err, stream) => { if ( err ) { log.error( "shellInit: ERROR: %s", err ); result( err ); return; } this._stream = stream; this.initEvent(); result(); }); } protected initEvent() { this._stream.on("data", (data) => { this._onData.fire( data ); }); this._stream.on("close", () => { this._onExit.fire( { exitCode: -1, signal: -1 } ); }); } protected get socket() { return this._ssh2Socket; } protected get stream() { return this._stream; } get pid() { return -1; } get cols() { return this._cols; } get rows() { return this._rows; } get process() { return "ssh"; } handleFlowControl: boolean; private _onData = new EventEmitter<string>(); public get onData(): IEvent<string> { return this._onData.event; } private _onExit = new EventEmitter<{ exitCode: number; signal?: number }>(); public get onExit(): IEvent<{ exitCode: number; signal?: number }> { return this._onExit.event; } on(event: any, listener: any) { if ( event === "data" ) { this._stream?.on( event, listener ); } else if ( event === "exit" ) { this._stream?.on( "close", (code, signal) => { log.error( "close %d %d", code, signal ); listener( code, signal ); }); } } resize(columns: number, rows: number): void { this.stream?.setWindow( rows, columns ); } write(data: string): void { log.debug( "WRITE: [%s]", data ); this.stream?.write( Buffer.from(data, "utf8") ); } kill(signal: string): void { this.stream?.signal( signal || "KILL" ); } } @KeyMapping(KeyMappingInfo.XTerm) export class BlessedXterm extends Widget implements IBlessedView, IHelpService { options: any; shell: string; args: string[]; cursorBlink: boolean; screenKeys: string; termName: string; term: XTerminal = null; pty: IPty = null; reader: Reader = null; panel: Widget = null; header: Widget = null; osc1337: IOSC1337 = {}; isCursorDraw: boolean = true; cursorPos = { y: -1, x: -1 }; isFullscreen: boolean = false; inputBlock: boolean = false; outputBlock: boolean = false; constructor( options: any, reader: Reader ) { super( { ...options, scrollable: false } ); const statColor = ColorConfig.instance().getBaseColor("stat"); this.panel = new Widget({ parent: this, border: "line", left: 0, top: 1, width: "100%", height: "100%-2", scrollable: true }); this.header = new Widget({ parent: this, left: 0, top: 0, width: "100%", height: 1, style: { bg: statColor.back, fg: statColor.font } }); this.setReader( reader ); this.options = options; // XXX Workaround for all motion if (this.screen.program.tmux && this.screen.program.tmuxVersion >= 2) { this.screen.program.enableMouse(); } const osShell = { "win32": [ "powershell.exe", "cmd.exe" ], "darwin": [ "zsh", "bash", "sh" ], "linux": [ "zsh", "bash", "sh" ] }; this.shell = options.shell || this.shellCheck(osShell[os.platform()]) || process.env.SHELL || "sh"; this.args = options.args || []; this.cursorBlink = options.cursorBlink; this.screenKeys = options.screenKeys; this.box.style = this.box.style || { bg: "default", fg: "default" }; this.panel.box.style = this.panel.box.style || { bg: "default", fg: "default" }; this.termName = options.terminal || options.term || process.env.TERM || "xterm"; this.panel.on("detach", () => { log.debug( "HIDE CURSOR !!!"); this.box.screen.program.hideCursor(); }); this.panel.on("render", () => { if ( this.box.screen.program.cursorHidden ) { log.debug( "SHOW CURSOR !!!"); this.box.screen.program.showCursor(); } }); (this.panel.box as any).render = () => { this._render(); }; } viewName() { return "XTerm"; } setBoxDraw( boxDraw: boolean ) { this.panel.setBorderLine( boxDraw ); } hasBoxDraw(): boolean { return this.panel.hasBorderLine(); } shellCheck( cmd: string[] ) { for ( const item of cmd ) { try { if ( which.sync(item) ) { return item; } // eslint-disable-next-line no-empty } catch ( e ) {} } return null; } async bootstrap(firstPath: File) { const box = this.panel.box; this.term = new XTerminal({ cols: (box.width as number) - (box.iwidth as number), rows: (box.height as number) - (box.iheight as number), cursorBlink: this.cursorBlink }); this.panel.on("focus", () => { this.term.focus(); }); this.panel.on("blur", () => { this.term && this.term.blur(); }); this.on("focus", () => { this.term.focus(); }); this.on("blur", () => { this.term && this.term.blur(); }); this.term.onTitleChange((title) => { this.header.setContent( title || "" ); }); this.term.onData( () => { this._render(); }); this.term.onRefreshRows( (startRow, endRow) => { this._render(startRow, endRow); }); this.panel.box.once("render", () => { try { this.term && this.term.resize((box.width as number) - (box.iwidth as number), (box.height as number) - (box.iheight as number)); } catch( e ) { log.error( "TERM RESIZE ERROR: %s", e ); } }); this.panel.on("destroy", () => { this.kill(); }); this.inputBlock = true; this.outputBlock = false; if ( this.getReader() instanceof SftpReader ) { log.debug( "SFTP SHELL : %s", (this.getReader() as SftpReader).getConnectInfo() ); try { const sftpReader = this.getReader() as SftpReader; this.on("widget.changetitle", () => { if ( !this.isFullscreen ) { this.header.setContent( sftpReader.getConnectInfo() + (this.getCurrentPath() || "") ); this.box.screen.render(); } }); const sshPty = new SshPty(); await sshPty.init({ reader: sftpReader, term: this.termName, cols: (box.width as number) - (box.iwidth as number), rows: (box.height as number) - (box.iheight as number), result: async (err) => { if ( err ) { this.box.emit( "error", err ); } else { this.pty = sshPty; await this.initPtyEvent(); } } }); this.header.setContent( sftpReader.getConnectInfo() ); } catch( e ) { process.nextTick(() => { this.box.emit( "error", e ); }); } } else { log.debug( "SHELL : %s %s", this.shell, this.args ); this.on("widget.changetitle", () => { try { if ( !this.isFullscreen ) { this.header.setContent( this.getCurrentPath() || "" ); this.box.screen.render(); } } catch( e ) { log.error( "wigdet.changetitle - render: %s", e ); } }); try { this.pty = NodePTY.spawn(this.shell, this.args, { name: this.termName, cols: (box.width as number) - (box.iwidth as number), rows: (box.height as number) - (box.iheight as number), cwd: firstPath ? firstPath.fullname : process.env.HOME, encoding: os.platform() !== "win32" ? "utf-8" : null, env: this.options.env || process.env }); await this.initPtyEvent(); } catch( e ) { log.error( "Exception - ", e ); try { this.box.emit( "error", e ); } catch( e ) {} return; } this.header.setContent( [ this.shell, ...(this.args || []) ].join(" ") || "" ); } (this.screen as any)._listenKeys(this); } async initPtyEvent() { const box = this.panel.box; this.on("resize", () => { log.debug( "BlessedXterm - resize !!!" ); process.nextTick(() => { log.debug( "BLESSED TERM RESIZE !!! - TERMINAL"); try { if ( !this.isFullscreen ) { this.term && this.term.resize((box.width as number) - (box.iwidth as number), (box.height as number) - (box.iheight as number)); } else { this.term && this.term.resize(this.screen.width as number, this.screen.height as number); } } catch( e ) { log.debug( "TERM RESIZE ERROR: %s", e ); } }); process.nextTick(() => { log.debug( "BLESSED PTY RESIZE !!! - TERMINAL"); if ( !this.isFullscreen ) { try { this.pty.resize((box.width as number) - (box.iwidth as number), (box.height as number) - (box.iheight as number)); } catch (e) { log.debug( e ); } } else { try { this.pty.resize( this.screen.width as number, this.screen.height as number); } catch (e) { log.debug( e ); } } }); }); this.pty.on( "data", (data) => { if ( Buffer.isBuffer(data) ) { this.parseOSC1337((data as Buffer).toString()); if( !this.outputBlock ) { this.write(data); } } else { this.parseOSC1337(data); if( !this.outputBlock ) { this.write(data); } } }); this.pty.on( "exit", async (exit, signal) => { log.error( "on exit !!! - [%d] [%s]", exit, signal ); await this.fullscreenRecover(); this.box.emit( "process_exit", exit, signal ); }); await new Promise<void>((resolve) => { let tm = null; this.box.once("OSC1337.CurrentDir", () => { if ( tm ) { log.debug( "DETECT : OSC1337.CurrentDir 2" ); clearTimeout( tm ); resolve(); } }); tm = setTimeout(resolve, 500); }); this.outputBlock = false; const listenDetectCheck = ( writeText: string, detectText: string | RegExp, timeout: number ) => { return new Promise<void>( (resolve) => { let tm = null; const detectShell = (d) => { const data: string = Buffer.isBuffer(d) ? (d as Buffer).toString() : d; if ( data.match( detectText ) ) { (this.pty as any)?.removeListener( "data", detectShell ); clearTimeout(tm); resolve(); } }; this.pty?.on("data", detectShell); this.pty?.write( writeText ); tm = setTimeout(() => { (this.pty as any)?.removeListener( "data", detectShell ); resolve(); }, timeout); }); }; const isSftp = this.getReader() instanceof SftpReader; if ( [ "zsh", "bash", "sh", "cmd.exe", "powershell.exe" ].indexOf(this.shell) > -1 || isSftp ) { try { if ( !this.getCurrentPath() && this.pty ) { if ( !isSftp && this.shell === "powershell.exe" ) { // function prompt {"PS [$Env:username@$Env:computername]$($PWD.ProviderPath)> "} await listenDetectCheck( "cls\r", "cls\r", 1000 ); const remoteHost = "$([char]27)]1337;RemoteHost=$Env:username@$Env:computername$([char]7)"; const currentDir = "$([char]27)]1337;CurrentDir=$($PWD.ProviderPath)$([char]7)"; const msg = `function prompt {"PS $($PWD.ProviderPath)>${remoteHost}${currentDir} "}\r`; this.pty?.write( msg ); await listenDetectCheck( "cls\r", "cls\r", 1000 ); } else if ( !isSftp && this.shell === "cmd.exe" ) { await listenDetectCheck( "cls\r", "cls\r", 1000 ); const remoteHost = "$E]1337;RemoteHost=localhost\x07"; const currentDir = "$E]1337;CurrentDir=$P\x07"; this.pty?.write( `prompt $P$G${remoteHost}${currentDir}\r` ); await listenDetectCheck( "cls\r", "cls\r", 1000 ); } else { let writeText = `function setOSC1337() { SHELL=\`ps -p $$ -ocomm=\` if [[ $SHELL =~ "zsh$" ]]; then echo -e "\\x1b]1337;CurrentDir=%d\\x07\\x1b]1337;RemoteHost=%n@%m\\x07" else echo -e "\\x1b]1337;CurrentDir=\\w\\x07\\x1b]1337;RemoteHost=\\u@\\h\\x07" fi }\r`; // eslint-disable-next-line @typescript-eslint/quotes writeText += `PS1="$PS1\$(setOSC1337)"\r`; await listenDetectCheck( writeText, "1337;CurrentDir=", 1000 ); await listenDetectCheck( "clear\r", "clear\r", 1000 ); } log.debug( "PROMPT UPDATE !!!" ); } } catch( e ) { log.error( e ); } } if ( this.pty && this.getReader() instanceof SftpReader && (this.getReader() as SftpReader).isSFTPSession() ) { const curDir = await this.getReader().currentDir(); if ( curDir && curDir.fullname ) { const changeDirCmd = `cd "${curDir.fullname}"\r`; await listenDetectCheck( changeDirCmd, changeDirCmd, 1000 ); log.debug( `CHANGE DIRECTORY: "${curDir.fullname}"` ); } } this.outputBlock = false; this.inputBlock = false; this.emit("widget.changetitle"); } /** * ref.) * 1. https://iterm2.com/documentation-escape-codes.html * 2. http://www.iterm2.com/documentation-shell-integration.html */ parseOSC1337( data ) { const convertProps = ( text ) => { const j = text.split("="); if (j.length > 1) { const oldValue = this.osc1337[ j[0] ]; const value = j.slice(1).join("="); this.osc1337[ j[0] ] = value; if ( oldValue !== value ) { this.emit( "OSC1337." + j[0], value ); } } }; let isFind = false; const beforePath = this.getCurrentPath(); const findOSC1337 = ( text ) => { const idx1 = text.indexOf("\x1b]1337;"); if ( idx1 > -1 ) { const idx2 = text.indexOf("\x07", idx1); if ( idx2 > -1 ) { text.substring(idx1 + 7, idx2).split(";").forEach((item) => convertProps(item)); isFind = true; findOSC1337( text.substr(idx2+1) ); } } }; findOSC1337(data); //log.debug( "OSC1337: %j", this.osc1337 ); if ( isFind && this.getCurrentPath() !== beforePath ) { this.emit( "widget.changetitle" ); } } hasFocus() { return this.panel.hasFocus(); } setFocus() { this.panel.setFocus(); } ptyKeyWrite( keyInfo ): RefreshType { if ( this.inputBlock ) { return RefreshType.NONE; } if ( keyInfo && keyInfo.name !== "enter" && keyInfo ) { log.debug( "pty write : [%j]", keyInfo ); this.pty && this.pty.write(keyInfo.sequence || keyInfo.ch); return RefreshType.OBJECT; } else { log.debug( "NOT - pty write : [%j]", keyInfo ); } return RefreshType.NONE; } write(data) { // log.debug( "term write [%d]", data.length ); if ( this.term ) { this.term.write(data); } if ( this.isFullscreen ) { process.stdout.write( data ); } } public clear(): void { if (this.term.buffer.ybase === 0 && this.term.buffer.y === 0) { // Don't clear if it's already clear return; } this.term.clear(); this._render(); } _render(startRow = -1, endRow = -1) { const box = this.panel.box as any; const screen = this.screen as any; if ( this.isFullscreen ) { return; } let ret = null; try { ret = box._render(); } catch( e ) { log.error( e ); this.cursorPos = { y: -1, x: -1 }; return; } if (!ret) { this.cursorPos = { y: -1, x: -1 }; return; } if ( !this.term ) { log.debug( "term is null !!!" ); this.cursorPos = { y: -1, x: -1 }; return; } box.dattr = box.sattr(box.style); // eslint-disable-next-line prefer-const let xi = ret.xi + box.ileft, xl = ret.xl - box.iright, yi = ret.yi + box.itop, yl = ret.yl - box.ibottom, cursor; //let scrollback = this.term.buffer.lines.length - (yl - yi); // let scrollback = this.term.buffer.ydisp - (yl - yi); const scrollback = this.term.buffer.ydisp; this.cursorPos = { y: yi + this.term.buffer.y, x: xi + this.term.buffer.x }; for (let y = Math.max(yi, 0); y < yl; y++) { const line = screen.lines[y]; const bufferLine = this.term.buffer.lines.get(scrollback + y - yi); if ( !bufferLine ) { continue; } if (!line) break; if ( this.isCursorDraw ) { if (y === yi + this.term.buffer.y && this.screen.focused === box && (this.term.buffer.ydisp === this.term.buffer.ybase)) { cursor = xi + this.term.buffer.x; } else { cursor = -1; } } // const str = bufferLine.translateToString(true); // log.debug( "line : %d, COLOR [%d/%d] [%d] [%s]", scrollback + y - yi, bufferLine.getFg(0), bufferLine.getBg(0), str.length, str ); const attr = new AttributeData(); for (let x = Math.max(xi, 0); x < xl; x++) { if (!line[x]) break; attr.bg = bufferLine.getBg(x - xi); attr.fg = bufferLine.getFg(x - xi); const sattr = { bold: !!attr.isBold(), underline: !!attr.isUnderline(), blink: !!attr.isBlink(), inverse: !!attr.isInverse(), invisible: !!attr.isInvisible(), bg: attr.getBgColor(), fg: attr.getFgColor() }; line[x][0] = (box as any).sattr(sattr); if ( this.isCursorDraw && x === cursor) { line[x][0] = (box as any).sattr({ bold: false, underline: false, blink: false, inverse: false, invisible: false, bg: box.style.bg, fg: box.style.fg, }) | (8 << 18); } line[x][1] = bufferLine.getString(x - xi) || " "; } line.dirty = true; screen.lines[y] = line; } if ( startRow !== -1 && endRow !== -1 ) { screen.draw(yi + startRow, yi + endRow); } return ret; } updateCursor() { if ( !this.isCursorDraw ) { const { x, y } = this.cursorPos; log.debug( "updateCursor: Row %d/ Col %d", y, x); if ( this.panel.box && x > -1 && y > -1 ) { this.panel.box.screen.program.cursorPos( y, x ); } } } _isMouse(buf) { let s = buf; if (Buffer.isBuffer(s)) { if (s[0] > 127 && s[1] === undefined) { s[0] -= 128; s = "\x1b" + s.toString("utf-8"); } else { s = s.toString("utf-8"); } } return (buf[0] === 0x1b && buf[1] === 0x5b && buf[2] === 0x4d) || /^\x1b\[M([\x00\u0020-\uffff]{3})/.test(s) || /^\x1b\[(\d+;\d+;\d+)M/.test(s) || /^\x1b\[<(\d+;\d+;\d+)([mM])/.test(s) || /^\x1b\[<(\d+;\d+;\d+;\d+)&w/.test(s) || /^\x1b\[24([0135])~\[(\d+),(\d+)\]\r/.test(s) || /^\x1b\[(O|I)/.test(s); } setScroll(offset) { this.term.buffer.ydisp = offset; return this.panel.box.emit("scroll"); } scrollTo(offset) { this.term.buffer.ydisp = offset; return this.panel.box.emit("scroll"); } getScroll() { return this.term.buffer.ydisp; } resetScroll() { this.term.buffer.ydisp = 0; this.term.buffer.ybase = 0; return this.panel.box.emit("scroll"); } getScrollHeight() { return this.term.rows - 1; } getScrollPerc() { return (this.term.buffer.ydisp / this.term.buffer.ybase) * 100; } setScrollPerc(i) { return this.setScroll((i / 100) * this.term.buffer.ybase | 0); } screenshot(xi, xl, yi, yl) { xi = 0 + (xi || 0); if (xl != null) { xl = 0 + (xl || 0); } else { xl = this.term.buffer.lines[0].length; } yi = 0 + (yi || 0); if (yl != null) { yl = 0 + (yl || 0); } else { yl = this.term.buffer.lines.length; } return this.screen.screenshot(xi, xl, yi, yl, this.term); } kill() { /* this.screen.program.input.removeListener('data', ( data ) => { this._onData( data ); }); */ if ( this.term ) { this.term.write("\x1b[H\x1b[J"); this.term.dispose(); delete this.term; this.term = null; } if (this.pty instanceof SshPty ) { try { (this.pty as SshPty).kill( "QUIT" ); delete this.pty; } catch ( e ) { log.error( e ); } this.pty = null; } else if ( this.pty ) { try { (this.pty as any).emit("exit", 0); log.debug( "PROCESS KILL - %d", this.pty.pid ); process.kill( this.pty.pid ); /* BUG - process stop this.pty.kill(); */ delete this.pty; } catch ( e ) { log.error( e ); } this.pty = null; } log.debug( "kill() END"); } destroy() { this.off(); this.kill(); super.destroy(); } getReader() { return this.reader; } setReader( reader ) { this.reader = reader; } getWidget() { return this; } getCurrentPath() { return this.osc1337 && this.osc1337.CurrentDir; } @Help( T("Help.TermScrollUp") ) @Hint({ hint: T("Hint.TermScrollUp"), order: 3 }) keyScrollUp() { this.term.buffer.ydisp += -2; if ( this.term.buffer.ydisp < 0 ) { this.term.buffer.ydisp = 0; } this.box.screen.render(); } @Help( T("Help.TermScrollDown") ) @Hint({ hint: T("Hint.TermScrollDown"), order: 3 }) keyScrollDown() { this.term.buffer.ydisp += 2; if ( this.term.buffer.ydisp > this.term.buffer.ybase ) { this.term.buffer.ydisp = this.term.buffer.ybase; } this.box.screen.render(); } @Help( T("Help.TermScrollPageUp") ) keyScrollPageUp() { this.term.buffer.ydisp += -this.term.rows; if ( this.term.buffer.ydisp < 0 ) { this.term.buffer.ydisp = 0; } this.box.screen.render(); } @Help( T("Help.TermScrollPageDown") ) keyScrollPageDown() { this.term.buffer.ydisp += this.term.rows; if ( this.term.buffer.ydisp > this.term.buffer.ybase ) { this.term.buffer.ydisp = this.term.buffer.ybase; } this.box.screen.render(); } private fullscreenKeyPressEvent = null; private fullscreenKeyPressEventPty = null; private isHintshowed = false; async fullscreenRecover() { if ( this.isFullscreen ) { this.isFullscreen = false; if ( this.fullscreenKeyPressEvent ) { this.screen.program.removeListener( "keypress", this.fullscreenKeyPressEvent ); this.fullscreenKeyPressEvent = null; } if ( this.fullscreenKeyPressEventPty ) { process.stdin.removeListener( "data", this.fullscreenKeyPressEventPty ); this.fullscreenKeyPressEventPty = null; } this.screen.enter(); mainFrame().lockKeyRelease("xtermFullScreen"); await mainFrame().refreshPromise(); mainFrame().execRefreshType( RefreshType.ALL ); } } @Help( T("Help.FullscreenView") ) @Hint({ hint: T("Hint.FullscreenView"), order: 2 }) keyXtermFullScreen() { mainFrame().lockKey("xtermFullScreen", this); setTimeout( () => { this.screen.leave(); this.isFullscreen = true; try { this.pty.resize( this.screen.width as number, this.screen.height as number); } catch (e) { log.error( e ); } this.fullscreenKeyPressEventPty = ( buf ) => { if ( buf.toString("hex") === "15" ) { // Ctrl-U return; } // log.debug( "stdin: [%s] [%s]", buf.toString("hex"), buf.toString("utf8") ); this.pty && this.pty.write( buf.toString("utf8") ); }; process.stdin.on( "data", this.fullscreenKeyPressEventPty ); if ( !this.isHintshowed ) { process.stdout.write( "\n\n" ); process.stdout.write( " > " + colors.white(T("Message.FullscreenReturnKey")) + "\n" ); this.pty.write("\n"); this.isHintshowed = true; } this.fullscreenKeyPressEvent = (ch, keyInfo) => { log.debug( "KEY: [%s]", keyInfo ); if ( keyInfo && keyInfo.full === "C-u" ) { this.fullscreenRecover(); } }; this.screen.program.on( "keypress", this.fullscreenKeyPressEvent); }, 300 ); return RefreshType.NO_KEYEXEC; } }
the_stack
import { BlockquoteBlockComponent } from '@root/src/web/components/elements/BlockquoteBlockComponent'; import { CalloutBlockComponent } from '@root/src/web/components/elements/CalloutBlockComponent'; import { CaptionBlockComponent } from '@root/src/web/components/elements/CaptionBlockComponent'; import { CommentBlockComponent } from '@root/src/web/components/elements/CommentBlockComponent'; import { CodeBlockComponent } from '@root/src/web/components/elements/CodeBlockComponent'; import { DefaultRichLink } from '@root/src/web/components/DefaultRichLink'; import { DocumentBlockComponent } from '@root/src/web/components/elements/DocumentBlockComponent'; import { DisclaimerBlockComponent } from '@root/src/web/components/elements/DisclaimerBlockComponent'; import { DividerBlockComponent } from '@root/src/web/components/elements/DividerBlockComponent'; import { EmbedBlockComponent } from '@root/src/web/components/elements/EmbedBlockComponent'; import { UnsafeEmbedBlockComponent } from '@root/src/web/components/elements/UnsafeEmbedBlockComponent'; import { GuVideoBlockComponent } from '@root/src/web/components/elements/GuVideoBlockComponent'; import { HighlightBlockComponent } from '@root/src/web/components/elements/HighlightBlockComponent'; import { ImageBlockComponent } from '@root/src/web/components/elements/ImageBlockComponent'; import { InstagramBlockComponent } from '@root/src/web/components/elements/InstagramBlockComponent'; import { InteractiveBlockComponent } from '@root/src/web/components/elements/InteractiveBlockComponent'; import { ItemLinkBlockElement } from '@root/src/web/components/elements/ItemLinkBlockElement'; import { InteractiveContentsBlockComponent } from '@root/src/web/components/elements/InteractiveContentsBlockComponent'; import { MainMediaEmbedBlockComponent } from '@root/src/web/components/elements/MainMediaEmbedBlockComponent'; import { NumberedTitleBlockComponent } from '@root/src/web/components/elements/NumberedTitleBlockComponent'; import { MapEmbedBlockComponent } from '@root/src/web/components/elements/MapEmbedBlockComponent'; import { MultiImageBlockComponent } from '@root/src/web/components/elements/MultiImageBlockComponent'; import { PullQuoteBlockComponent } from '@root/src/web/components/elements/PullQuoteBlockComponent'; import { SoundcloudBlockComponent } from '@root/src/web/components/elements/SoundcloudBlockComponent'; import { SpotifyBlockComponent } from '@root/src/web/components/elements/SpotifyBlockComponent'; import { StarRatingBlockComponent } from '@root/src/web/components/elements/StarRatingBlockComponent'; import { SubheadingBlockComponent } from '@root/src/web/components/elements/SubheadingBlockComponent'; import { TableBlockComponent } from '@root/src/web/components/elements/TableBlockComponent'; import { TextBlockComponent } from '@root/src/web/components/elements/TextBlockComponent'; import { TweetBlockComponent } from '@root/src/web/components/elements/TweetBlockComponent'; import { VideoFacebookBlockComponent } from '@root/src/web/components/elements/VideoFacebookBlockComponent'; import { VimeoBlockComponent } from '@root/src/web/components/elements/VimeoBlockComponent'; import { VineBlockComponent } from '@root/src/web/components/elements/VineBlockComponent'; import { YoutubeEmbedBlockComponent } from '@root/src/web/components/elements/YoutubeEmbedBlockComponent'; import { YoutubeBlockComponent } from '@root/src/web/components/elements/YoutubeBlockComponent'; import { WitnessVideoBlockComponent, WitnessImageBlockComponent, WitnessTextBlockComponent, } from '@root/src/web/components/elements/WitnessBlockComponent'; import { getSharingUrls } from '@root/src/lib/sharing-urls'; import { ClickToView } from '@root/src/web/components/ClickToView'; import { AudioAtom, ChartAtom, ExplainerAtom, InteractiveAtom, InteractiveLayoutAtom, QandaAtom, GuideAtom, ProfileAtom, TimelineAtom, VideoAtom, PersonalityQuizAtom, KnowledgeQuizAtom, } from '@guardian/atoms-rendering'; import { ArticleDesign, ArticleFormat } from '@guardian/libs'; import { Figure } from '../components/Figure'; import { isInteractive, interactiveLegacyFigureClasses, } from '../layouts/lib/interactiveLegacyStyling'; type Props = { format: ArticleFormat; palette: Palette; element: CAPIElement; adTargeting?: AdTargeting; host?: string; index: number; isMainMedia: boolean; hideCaption?: boolean; starRating?: number; pageId: string; webTitle: string; }; // updateRole modifies the role of an element in a way appropriate for most // article types. export const updateRole = ( el: CAPIElement, format: ArticleFormat, ): CAPIElement => { const isLiveBlog = format.design === ArticleDesign.LiveBlog || format.design === ArticleDesign.DeadBlog; switch (el._type) { case 'model.dotcomrendering.pageElements.ImageBlockElement': if (isLiveBlog && el.role !== 'thumbnail') { el.role = 'inline'; } return el; case 'model.dotcomrendering.pageElements.RichLinkBlockElement': if (isLiveBlog) { el.role = 'inline'; } else { el.role = 'richLink'; } return el; default: if (isLiveBlog && 'role' in el) { el.role = 'inline'; } return el; } }; // renderElement converts a CAPI element to JSX. A boolean 'ok' flag is returned // along with the element to indicate if the element is null, in which case // callers can e.g. avoid further work/wrapping as required. Unfortunately, // there is no straightforward way to tell if a React element is null by direct // inspection. export const renderElement = ({ format, palette, element, adTargeting, host, index, hideCaption, isMainMedia, starRating, pageId, webTitle, }: Props): [boolean, JSX.Element] => { switch (element._type) { case 'model.dotcomrendering.pageElements.AudioAtomBlockElement': return [ true, <AudioAtom id={element.id} trackUrl={element.trackUrl} kicker={element.kicker} title={element.title} duration={element.duration} pillar={format.theme} />, ]; case 'model.dotcomrendering.pageElements.BlockquoteBlockElement': return [ true, <BlockquoteBlockComponent key={index} html={element.html} palette={palette} quoted={element.quoted} />, ]; case 'model.dotcomrendering.pageElements.CalloutBlockElement': return [ true, <CalloutBlockComponent callout={element} format={format} />, ]; case 'model.dotcomrendering.pageElements.CaptionBlockElement': return [ true, <CaptionBlockComponent key={index} format={format} palette={palette} captionText={element.captionText} padCaption={element.padCaption} credit={element.credit} displayCredit={element.displayCredit} shouldLimitWidth={element.shouldLimitWidth} isOverlayed={element.isOverlayed} />, ]; case 'model.dotcomrendering.pageElements.ChartAtomBlockElement': return [true, <ChartAtom id={element.id} html={element.html} />]; case 'model.dotcomrendering.pageElements.CodeBlockElement': return [ true, <CodeBlockComponent code={element.html} language={element.language} />, ]; case 'model.dotcomrendering.pageElements.CommentBlockElement': return [ true, <CommentBlockComponent body={element.body} avatarURL={element.avatarURL} profileURL={element.profileURL} profileName={element.profileName} dateTime={element.dateTime} permalink={element.permalink} />, ]; case 'model.dotcomrendering.pageElements.DisclaimerBlockElement': return [true, <DisclaimerBlockComponent html={element.html} />]; case 'model.dotcomrendering.pageElements.DividerBlockElement': return [ true, <DividerBlockComponent size={element.size} spaceAbove={element.spaceAbove} />, ]; case 'model.dotcomrendering.pageElements.DocumentBlockElement': return [ true, <ClickToView role={element.role} isTracking={element.isThirdPartyTracking} isMainMedia={isMainMedia} source={element.source} sourceDomain={element.sourceDomain} > <DocumentBlockComponent embedUrl={element.embedUrl} height={element.height} width={element.width} title={element.title} source={element.source} /> </ClickToView>, ]; case 'model.dotcomrendering.pageElements.EmbedBlockElement': if (!element.safe) { if (isMainMedia) { return [ true, <MainMediaEmbedBlockComponent title={element.alt || ''} srcDoc={element.html} />, ]; } return [ true, <ClickToView role={element.role} isTracking={element.isThirdPartyTracking} isMainMedia={isMainMedia} source={element.source} sourceDomain={element.sourceDomain} > <UnsafeEmbedBlockComponent key={index} html={element.html} alt={element.alt || ''} index={index} /> </ClickToView>, ]; } return [ true, <ClickToView role={element.role} isTracking={element.isThirdPartyTracking} isMainMedia={isMainMedia} source={element.source} sourceDomain={element.sourceDomain} > <EmbedBlockComponent key={index} html={element.html} caption={element.caption} /> </ClickToView>, ]; case 'model.dotcomrendering.pageElements.ExplainerAtomBlockElement': return [ true, <ExplainerAtom key={index} id={element.id} title={element.title} html={element.body} />, ]; case 'model.dotcomrendering.pageElements.GuideAtomBlockElement': return [ true, <GuideAtom id={element.id} title={element.title} html={element.html} image={element.img} credit={element.credit} pillar={format.theme} likeHandler={() => {}} dislikeHandler={() => {}} expandCallback={() => {}} />, ]; case 'model.dotcomrendering.pageElements.GuVideoBlockElement': return [ true, <GuVideoBlockComponent html={element.html} format={format} palette={palette} credit={element.source} caption={element.caption} />, ]; case 'model.dotcomrendering.pageElements.HighlightBlockElement': return [ true, <HighlightBlockComponent key={index} html={element.html} />, ]; case 'model.dotcomrendering.pageElements.ImageBlockElement': return [ true, <ImageBlockComponent format={format} palette={palette} key={index} element={element} hideCaption={hideCaption} isMainMedia={isMainMedia} starRating={starRating || element.starRating} title={element.title} isAvatar={element.isAvatar} />, ]; case 'model.dotcomrendering.pageElements.InstagramBlockElement': return [ true, <ClickToView role={element.role} isTracking={element.isThirdPartyTracking} isMainMedia={isMainMedia} source={element.source} sourceDomain={element.sourceDomain} > <InstagramBlockComponent key={index} element={element} index={index} /> </ClickToView>, ]; case 'model.dotcomrendering.pageElements.InteractiveAtomBlockElement': if (format.design === ArticleDesign.Interactive) { return [ true, <InteractiveLayoutAtom id={element.id} elementHtml={element.html} elementJs={element.js} elementCss={element.css} />, ]; } return [ true, <InteractiveAtom isMainMedia={isMainMedia} id={element.id} elementHtml={element.html} elementJs={element.js} elementCss={element.css} format={format} />, ]; case 'model.dotcomrendering.pageElements.InteractiveBlockElement': return [ true, <InteractiveBlockComponent url={element.url} scriptUrl={element.scriptUrl} alt={element.alt} role={element.role} format={format} elementId={element.elementId} />, ]; case 'model.dotcomrendering.pageElements.ItemLinkBlockElement': return [true, <ItemLinkBlockElement html={element.html} />]; case 'model.dotcomrendering.pageElements.InteractiveContentsBlockElement': return [ true, <div id={element.elementId}> <InteractiveContentsBlockComponent subheadingLinks={element.subheadingLinks} endDocumentElementId={element.endDocumentElementId} /> </div>, ]; case 'model.dotcomrendering.pageElements.MapBlockElement': return [ true, <ClickToView role={element.role} isTracking={element.isThirdPartyTracking} isMainMedia={isMainMedia} source={element.source} sourceDomain={element.sourceDomain} > <MapEmbedBlockComponent format={format} embedUrl={element.embedUrl} height={element.height} width={element.width} caption={element.caption} credit={element.source} title={element.title} /> </ClickToView>, ]; case 'model.dotcomrendering.pageElements.MediaAtomBlockElement': return [ true, <VideoAtom assets={element.assets} poster={element.posterImage && element.posterImage[0].url} />, ]; case 'model.dotcomrendering.pageElements.MultiImageBlockElement': return [ true, <MultiImageBlockComponent format={format} palette={palette} key={index} images={element.images} caption={element.caption} />, ]; case 'model.dotcomrendering.pageElements.NumberedTitleBlockElement': return [ true, <NumberedTitleBlockComponent position={element.position} html={element.html} format={element.format} />, ]; case 'model.dotcomrendering.pageElements.ProfileAtomBlockElement': return [ true, <ProfileAtom id={element.id} title={element.title} html={element.html} image={element.img} credit={element.credit} pillar={format.theme} likeHandler={() => {}} dislikeHandler={() => {}} expandCallback={() => {}} />, ]; case 'model.dotcomrendering.pageElements.PullquoteBlockElement': return [ true, <PullQuoteBlockComponent key={index} html={element.html} palette={palette} design={format.design} attribution={element.attribution} role={element.role} />, ]; case 'model.dotcomrendering.pageElements.QABlockElement': return [ true, <QandaAtom id={element.id} title={element.title} html={element.html} image={element.img} credit={element.credit} pillar={format.theme} likeHandler={() => {}} dislikeHandler={() => {}} expandCallback={() => {}} />, ]; case 'model.dotcomrendering.pageElements.QuizAtomBlockElement': return [ true, <> {element.quizType === 'personality' && ( <PersonalityQuizAtom id={element.id} questions={element.questions} resultBuckets={element.resultBuckets} sharingUrls={getSharingUrls(pageId, webTitle)} theme={format.theme} /> )} {element.quizType === 'knowledge' && ( <KnowledgeQuizAtom id={element.id} questions={element.questions} resultGroups={element.resultGroups} sharingUrls={getSharingUrls(pageId, webTitle)} theme={format.theme} /> )} </>, ]; case 'model.dotcomrendering.pageElements.RichLinkBlockElement': return [ true, <DefaultRichLink index={index} headlineText={element.text} url={element.url} isPlaceholder={true} />, ]; case 'model.dotcomrendering.pageElements.SoundcloudBlockElement': return [true, <SoundcloudBlockComponent element={element} />]; case 'model.dotcomrendering.pageElements.SpotifyBlockElement': return [ true, <ClickToView role={element.role} isTracking={element.isThirdPartyTracking} isMainMedia={isMainMedia} source={element.source} sourceDomain={element.sourceDomain} > <SpotifyBlockComponent embedUrl={element.embedUrl} height={element.height} width={element.width} title={element.title} format={format} caption={element.caption} credit="Spotify" /> </ClickToView>, ]; case 'model.dotcomrendering.pageElements.StarRatingBlockElement': return [ true, <StarRatingBlockComponent key={index} rating={element.rating} size={element.size} />, ]; case 'model.dotcomrendering.pageElements.SubheadingBlockElement': return [ true, <SubheadingBlockComponent key={index} html={element.html} />, ]; case 'model.dotcomrendering.pageElements.TableBlockElement': return [true, <TableBlockComponent element={element} />]; case 'model.dotcomrendering.pageElements.TextBlockElement': return [ true, <> <TextBlockComponent key={index} isFirstParagraph={index === 0} html={element.html} format={format} forceDropCap={element.dropCap} /> </>, ]; case 'model.dotcomrendering.pageElements.TimelineBlockElement': return [ true, <TimelineAtom id={element.id} title={element.title} pillar={format.theme} events={element.events} description={element.description} likeHandler={() => {}} dislikeHandler={() => {}} expandCallback={() => {}} />, ]; case 'model.dotcomrendering.pageElements.TweetBlockElement': return [true, <TweetBlockComponent element={element} />]; case 'model.dotcomrendering.pageElements.VideoFacebookBlockElement': return [ true, <ClickToView role={element.role} isTracking={element.isThirdPartyTracking} isMainMedia={isMainMedia} source={element.source} sourceDomain={element.sourceDomain} > <VideoFacebookBlockComponent format={format} embedUrl={element.embedUrl} height={element.height} width={element.width} caption={element.caption} credit={element.caption} title={element.caption} /> </ClickToView>, ]; case 'model.dotcomrendering.pageElements.VideoVimeoBlockElement': return [ true, <VimeoBlockComponent format={format} palette={palette} embedUrl={element.embedUrl} height={element.height} width={element.width} caption={element.caption} credit={element.credit} title={element.title} />, ]; case 'model.dotcomrendering.pageElements.VideoYoutubeBlockElement': return [ true, <YoutubeEmbedBlockComponent format={format} palette={palette} embedUrl={element.embedUrl} height={element.height} width={element.width} caption={element.caption} credit={element.credit} title={element.title} />, ]; case 'model.dotcomrendering.pageElements.VineBlockElement': return [ true, <ClickToView // No role given by CAPI // eslint-disable-next-line jsx-a11y/aria-role role="inline" isTracking={element.isThirdPartyTracking} source={element.source} sourceDomain={element.sourceDomain} > <VineBlockComponent element={element} /> </ClickToView>, ]; case 'model.dotcomrendering.pageElements.WitnessBlockElement': { const witnessType = element.witnessTypeData._type; switch (witnessType) { case 'model.dotcomrendering.pageElements.WitnessTypeDataImage': const witnessTypeDataImage = element.witnessTypeData; return [ true, <WitnessImageBlockComponent assets={element.assets} caption={witnessTypeDataImage.caption} title={witnessTypeDataImage.title} authorName={witnessTypeDataImage.authorName} dateCreated={witnessTypeDataImage.dateCreated} alt={witnessTypeDataImage.alt} palette={palette} />, ]; case 'model.dotcomrendering.pageElements.WitnessTypeDataVideo': const witnessTypeDataVideo = element.witnessTypeData; return [ true, <WitnessVideoBlockComponent title={witnessTypeDataVideo.title} description={witnessTypeDataVideo.description} authorName={witnessTypeDataVideo.authorName} youtubeHtml={witnessTypeDataVideo.youtubeHtml} dateCreated={witnessTypeDataVideo.dateCreated} palette={palette} />, ]; case 'model.dotcomrendering.pageElements.WitnessTypeDataText': const witnessTypeDataText = element.witnessTypeData; return [ true, <WitnessTextBlockComponent title={witnessTypeDataText.title} description={witnessTypeDataText.description} authorName={witnessTypeDataText.authorName} dateCreated={witnessTypeDataText.dateCreated} palette={palette} />, ]; default: return [false, <></>]; } } case 'model.dotcomrendering.pageElements.YoutubeBlockElement': return [ true, <YoutubeBlockComponent format={format} key={index} hideCaption={hideCaption} // eslint-disable-next-line jsx-a11y/aria-role role="inline" adTargeting={adTargeting} isMainMedia={isMainMedia} id={element.id} assetId={element.assetId} expired={element.expired} overrideImage={element.overrideImage} posterImage={element.posterImage} duration={element.duration} mediaTitle={element.mediaTitle} altText={element.altText} origin={host} />, ]; case 'model.dotcomrendering.pageElements.AudioBlockElement': case 'model.dotcomrendering.pageElements.ContentAtomBlockElement': case 'model.dotcomrendering.pageElements.GenericAtomBlockElement': case 'model.dotcomrendering.pageElements.VideoBlockElement': default: return [false, <></>]; } }; // bareElements is the set of element types that don't get wrapped in a Figure // for most article types, either because they don't need it or because they // add the figure themselves. // We might assume that InteractiveBlockElement should be included in this list, // however we can't do this while we maintain the current component abstraction. // If no outer figure, then HydrateOnce uses the component's figure as the root // for hydration. For InteractiveBlockElements, the result is that the state that // determines height is never updated leaving an empty placeholder space in the // article even after the interactive content has loaded. const bareElements = new Set([ 'model.dotcomrendering.pageElements.BlockquoteBlockElement', 'model.dotcomrendering.pageElements.CaptionBlockElement', 'model.dotcomrendering.pageElements.CodeBlockElement', 'model.dotcomrendering.pageElements.DividerBlockElement', 'model.dotcomrendering.pageElements.MediaAtomBlockElement', 'model.dotcomrendering.pageElements.PullquoteBlockElement', 'model.dotcomrendering.pageElements.StarRatingBlockElement', 'model.dotcomrendering.pageElements.SubheadingBlockElement', 'model.dotcomrendering.pageElements.TextBlockElement', 'model.dotcomrendering.pageElements.InteractiveContentsBlockElement', ]); // renderArticleElement is a wrapper for renderElement that wraps elements in a // Figure and adds metadata and (role-) styling appropriate for most article // types. export const renderArticleElement = ({ format, palette, element, adTargeting, host, index, hideCaption, isMainMedia, starRating, pageId, webTitle, }: Props): JSX.Element => { const withUpdatedRole = updateRole(element, format); const [ok, el] = renderElement({ format, palette, element: withUpdatedRole, adTargeting, host, index, isMainMedia, hideCaption, starRating, pageId, webTitle, }); if (!ok) { return <></>; } const needsFigure = !bareElements.has(element._type); const role = 'role' in element ? (element.role as RoleType) : undefined; return needsFigure ? ( <Figure isMainMedia={isMainMedia} id={'elementId' in element ? element.elementId : undefined} role={role} className={ isInteractive(format.design) ? interactiveLegacyFigureClasses(element._type, role) : '' } > {el} </Figure> ) : ( el ); };
the_stack
'use strict'; import type {Moment, Duration} from 'moment'; import type {Moment as MomentTZ} from 'moment-timezone'; import type {Dayjs} from 'dayjs'; import type {DateTime as LuxonDateTime} from 'luxon'; import type { RRule } from 'rrule'; import {ICalDateTimeValue, ICalOrganizer} from './types'; /** * Converts a valid date/time object supported by this library to a string. */ export function formatDate (timezone: string | null, d: ICalDateTimeValue, dateonly?: boolean, floating?: boolean): string { if(timezone?.startsWith('/')) { timezone = timezone.substr(1); } if(typeof d === 'string' || d instanceof Date) { const m = new Date(d); // (!dateonly && !floating) || !timezone => utc let s = m.getUTCFullYear() + String(m.getUTCMonth() + 1).padStart(2, '0') + m.getUTCDate().toString().padStart(2, '0'); // (dateonly || floating) && timezone => tz if(timezone) { s = m.getFullYear() + String(m.getMonth() + 1).padStart(2, '0') + m.getDate().toString().padStart(2, '0'); } if(dateonly) { return s; } if(timezone) { s += 'T' + m.getHours().toString().padStart(2, '0') + m.getMinutes().toString().padStart(2, '0') + m.getSeconds().toString().padStart(2, '0'); return s; } s += 'T' + m.getUTCHours().toString().padStart(2, '0') + m.getUTCMinutes().toString().padStart(2, '0') + m.getUTCSeconds().toString().padStart(2, '0') + (floating ? '' : 'Z'); return s; } else if(isMoment(d)) { // @see https://momentjs.com/timezone/docs/#/using-timezones/parsing-in-zone/ const m = timezone ? (isMomentTZ(d) && !d.tz() ? d.clone().tz(timezone) : d) : (floating ? d : d.utc()); return m.format('YYYYMMDD') + (!dateonly ? ( 'T' + m.format('HHmmss') + (floating || timezone ? '' : 'Z') ) : ''); } else if(isLuxonDate(d)) { const m = timezone ? d.setZone(timezone) : (floating ? d : d.setZone('utc')); return m.toFormat('yyyyLLdd') + (!dateonly ? ( 'T' + m.toFormat('HHmmss') + (floating || timezone ? '' : 'Z') ) : ''); } else { // @see https://day.js.org/docs/en/plugin/utc let m = d; if(timezone) { // @see https://day.js.org/docs/en/plugin/timezone // @ts-ignore m = typeof d.tz === 'function' ? d.tz(timezone) : d; } else if(floating) { // m = d; } // @ts-ignore else if (typeof d.utc === 'function') { // @ts-ignore m = d.utc(); } else { throw new Error('Unable to convert dayjs object to UTC value: UTC plugin is not available!'); } return m.format('YYYYMMDD') + (!dateonly ? ( 'T' + m.format('HHmmss') + (floating || timezone ? '' : 'Z') ) : ''); } } /** * Converts a valid date/time object supported by this library to a string. * For information about this format, see RFC 5545, section 3.3.5 * https://tools.ietf.org/html/rfc5545#section-3.3.5 */ export function formatDateTZ (timezone: string | null, property: string, date: ICalDateTimeValue | Date | string, eventData?: {floating?: boolean | null, timezone?: string | null}): string { let tzParam = ''; let floating = eventData?.floating || false; if (eventData?.timezone) { tzParam = ';TZID=' + eventData.timezone; // This isn't a 'floating' event because it has a timezone; // but we use it to omit the 'Z' UTC specifier in formatDate() floating = true; } return property + tzParam + ':' + formatDate(timezone, date, false, floating); } /** * Escapes special characters in the given string */ export function escape (str: string | unknown): string { return String(str).replace(/[\\;,"]/g, function (match) { return '\\' + match; }).replace(/(?:\r\n|\r|\n)/g, '\\n'); } /** * Trim line length of given string */ export function foldLines (input: string): string { return input.split('\r\n').map(function (line) { let result = ''; let c = 0; for (let i = 0; i < line.length; i++) { let ch = line.charAt(i); // surrogate pair, see https://mathiasbynens.be/notes/javascript-encoding#surrogate-pairs if (ch >= '\ud800' && ch <= '\udbff') { ch += line.charAt(++i); } const charsize = Buffer.from(ch).length; c += charsize; if (c > 74) { result += '\r\n '; c = charsize; } result += ch; } return result; }).join('\r\n'); } export function addOrGetCustomAttributes (data: {x: [string, string][]}, keyOrArray: ({key: string, value: string})[] | [string, string][] | Record<string, string>): void; export function addOrGetCustomAttributes (data: {x: [string, string][]}, keyOrArray: string, value: string): void; export function addOrGetCustomAttributes (data: {x: [string, string][]}): ({key: string, value: string})[]; export function addOrGetCustomAttributes (data: {x: [string, string][]}, keyOrArray?: ({key: string, value: string})[] | [string, string][] | Record<string, string> | string | undefined, value?: string | undefined): void | ({key: string, value: string})[] { if (Array.isArray(keyOrArray)) { data.x = keyOrArray.map((o: {key: string, value: string} | [string, string]) => { if(Array.isArray(o)) { return o; } if (typeof o.key !== 'string' || typeof o.value !== 'string') { throw new Error('Either key or value is not a string!'); } if (o.key.substr(0, 2) !== 'X-') { throw new Error('Key has to start with `X-`!'); } return [o.key, o.value] as [string, string]; }); } else if (typeof keyOrArray === 'object') { data.x = Object.entries(keyOrArray).map(([key, value]) => { if (typeof key !== 'string' || typeof value !== 'string') { throw new Error('Either key or value is not a string!'); } if (key.substr(0, 2) !== 'X-') { throw new Error('Key has to start with `X-`!'); } return [key, value]; }); } else if (typeof keyOrArray === 'string' && typeof value === 'string') { if (keyOrArray.substr(0, 2) !== 'X-') { throw new Error('Key has to start with `X-`!'); } data.x.push([keyOrArray, value]); } else { return data.x.map(a => ({ key: a[0], value: a[1] })); } } export function generateCustomAttributes (data: {x: [string, string][]}): string { const str = data.x .map(([key, value]) => key.toUpperCase() + ':' + escape(value)) .join('\r\n'); return str.length ? str + '\r\n' : ''; } /** * Check the given string or ICalOrganizer. Parses * the string for name and email address if possible. * * @param attribute Attribute name for error messages * @param value Value to parse name/email from */ export function checkNameAndMail (attribute: string, value: string | ICalOrganizer): ICalOrganizer { let result: ICalOrganizer | null = null; if (typeof value === 'string') { const match = value.match(/^(.+) ?<([^>]+)>$/); if (match) { result = { name: match[1].trim(), email: match[2].trim() }; } else if(value.includes('@')) { result = { name: value.trim(), email: value.trim() }; } } else if (typeof value === 'object') { result = { name: value.name, email: value.email, mailto: value.mailto }; } if (!result && typeof value === 'string') { throw new Error( '`' + attribute + '` isn\'t formated correctly. See https://sebbo2002.github.io/ical-generator/develop/'+ 'reference/interfaces/icalorganizer.html' ); } else if (!result) { throw new Error( '`' + attribute + '` needs to be a valid formed string or an object. See https://sebbo2002.github.io/'+ 'ical-generator/develop/reference/interfaces/icalorganizer.html' ); } if (!result.name) { throw new Error('`' + attribute + '.name` is empty!'); } return result; } /** * Checks if the given string `value` is a * valid one for the type `type` */ export function checkEnum(type: Record<string, string>, value: unknown): unknown { const allowedValues = Object.values(type); const valueStr = String(value).toUpperCase(); if (!valueStr || !allowedValues.includes(valueStr)) { throw new Error(`Input must be one of the following: ${allowedValues.join(', ')}`); } return valueStr; } /** * Checks if the given input is a valid date and * returns the internal representation (= moment object) */ export function checkDate(value: ICalDateTimeValue, attribute: string): ICalDateTimeValue { // Date & String if( (value instanceof Date && isNaN(value.getTime())) || (typeof value === 'string' && isNaN(new Date(value).getTime())) ) { throw new Error(`\`${attribute}\` has to be a valid date!`); } if(value instanceof Date || typeof value === 'string') { return value; } // Luxon if(isLuxonDate(value) && value.isValid === true) { return value; } // Moment / Moment Timezone if((isMoment(value) || isDayjs(value)) && value.isValid()) { return value; } throw new Error(`\`${attribute}\` has to be a valid date!`); } export function toDate(value: ICalDateTimeValue): Date { if(typeof value === 'string' || value instanceof Date) { return new Date(value); } // @ts-ignore if(isLuxonDate(value)) { return value.toJSDate(); } return value.toDate(); } export function isMoment(value: ICalDateTimeValue): value is Moment { // @ts-ignore return value != null && value._isAMomentObject != null; } export function isMomentTZ(value: ICalDateTimeValue): value is MomentTZ { return isMoment(value) && typeof value.tz === 'function'; } export function isDayjs(value: ICalDateTimeValue): value is Dayjs { return typeof value === 'object' && value !== null && !(value instanceof Date) && !isMoment(value) && !isLuxonDate(value); } export function isLuxonDate(value: ICalDateTimeValue): value is LuxonDateTime { return typeof value === 'object' && value !== null && typeof (value as LuxonDateTime).toJSDate === 'function'; } export function isMomentDuration(value: unknown): value is Duration { // @ts-ignore return value !== null && typeof value === 'object' && typeof value.asSeconds === 'function'; } export function isRRule(value: unknown): value is RRule { // @ts-ignore return value !== null && typeof value === 'object' && typeof value.between === 'function' && typeof value.toString === 'function'; } export function toJSON(value: ICalDateTimeValue | null | undefined): string | null | undefined { if(!value) { return value; } if(typeof value === 'string') { return value; } return value.toJSON(); } export function toDurationString(seconds: number): string { let string = ''; // < 0 if(seconds < 0) { string = '-'; seconds *= -1; } string += 'P'; // DAYS if(seconds >= 86400) { string += Math.floor(seconds / 86400) + 'D'; seconds %= 86400; } if(!seconds && string.length > 1) { return string; } string += 'T'; // HOURS if(seconds >= 3600) { string += Math.floor(seconds / 3600) + 'H'; seconds %= 3600; } // MINUTES if(seconds >= 60) { string += Math.floor(seconds / 60) + 'M'; seconds %= 60; } // SECONDS if(seconds > 0) { string += seconds + 'S'; } else if(string.length <= 2) { string += '0S'; } return string; }
the_stack
import { allNumbersAreSame } from './utils'; import { BigObject, MaskType } from './interfaces'; /** * BASED ON https://github.com/gammasoft/ie/ */ export const generateInscricaoEstadual: BigObject<Function> = { ac: function (valor: any) { if (tamanhoNaoE(valor, 13)) { return false; } if (naoComecaCom(valor, '01')) { return false; } const base = primeiros(valor, 11); const primeiroDigito = substracaoPor11SeMaiorQue2CasoContrario0(mod(base)); const segundoDigito = substracaoPor11SeMaiorQue2CasoContrario0(mod(base + primeiroDigito)); return base + primeiroDigito + segundoDigito; }, am: function (valor: any) { if (tamanhoNaoE(valor)) { return false; } return calculoTrivialGenerate(valor); }, al: function (valor: any) { if (tamanhoNaoE(valor)) { return false; } if (naoComecaCom(valor, '24')) { return false; } // FORMAÇÃO: 24XNNNNND, sendo: // 24 – Código do Estado // X – Tipo de empresa (0-Normal, 3-Produtor Rural, 5-Substituta, 7- Micro-Empresa Ambulante, 8-Micro-Empresa) // NNNNN – Número da empresa // D – Dígito de verificação calculado pelo Módulo11, pêsos 2 à 9 da direita para a esquerda, exceto D // Exemplo: Número 2 4 0 0 0 0 0 4 D // 2 4 X N N N N N D // Fonte: http://www.sintegra.gov.br/Cad_Estados/cad_AL.html const base: any = primeiros(valor); // Pesos 9 8 7 6 5 4 3 2 // SOMA = (2 * 4) + (3 * 0) + (4 * 0) + (5 * 0) + (6 * 0) + (7 * 0) + (8 * 4) + (9 * 2) = 58 const soma = base.split('').reduce((acc: number, v: string, i: number) => { return acc + (9-i) * Number(v) }, 0) // PRODUTO = 58 * 10 = 580 const produto = soma * 10 // RESTO = 580 – INTEIRO(580 / 11)*11 = 580 – (52*11) = 8 const resto = produto - Math.floor(produto / 11) * 11 // DÍGITO = 8 - Caso RESTO seja igual a 10 o DÍGITO será 0 (zero) const digito = resto === 10 ? 0 : resto return base + digito; }, ap: function (valor: any) { if (tamanhoNaoE(valor)) { return false; } if (naoComecaCom(valor, '03')) { return false; } const base: any = primeiros(valor); let p: number, d: number; if (entre(base, 3000001, 3017000)) { p = 5; d = 0; } else if (entre(base, 3017001, 3019022)) { p = 9; d = 1; } else { p = 0; d = 0; } const resto = mod(p + base, [2, 3, 4, 5, 6, 7, 8, 9, 1]); let digito: number; if (resto === 1) { digito = 0; } else if (resto === 0) { digito = d; } else { digito = 11 - resto; } return base + digito; }, ba: function (valor: any) { if (tamanhoNaoE(valor, 8) && tamanhoNaoE(valor)) { return false; } const base: any = primeiros(valor, valor.length - 2); let primeiroDigito: number, segundoDigito: number; const segundoMultiplicador = serie(2, 7); const primeiroMultiplicador = serie(2, 8); let primeiroResto: number, segundoResto: number; let digitoComparacao = valor.substring(0, 1); if (tamanhoE(valor, 9)) { segundoMultiplicador.push(8); primeiroMultiplicador.push(9); digitoComparacao = valor.substring(1, 2); } if ('0123458'.split('').indexOf(digitoComparacao) !== -1) { segundoResto = mod(base, segundoMultiplicador, 10); segundoDigito = segundoResto === 0 ? 0 : 10 - segundoResto; primeiroResto = mod(base + segundoDigito, primeiroMultiplicador, 10); primeiroDigito = primeiroResto === 0 ? 0 : 10 - primeiroResto; } else { segundoResto = mod(base, segundoMultiplicador); segundoDigito = substracaoPor11SeMaiorQue2CasoContrario0(segundoResto); primeiroResto = mod(base + segundoDigito, primeiroMultiplicador); primeiroDigito = substracaoPor11SeMaiorQue2CasoContrario0(primeiroResto); } return base + primeiroDigito + segundoDigito; }, ce: function (valor: any) { if (tamanhoNaoE(valor)) { return false; } return calculoTrivialGenerate(valor); }, df: function (valor: any) { if (tamanhoNaoE(valor, 13)) { return false; } if (naoComecaCom(valor, '07') && naoComecaCom(valor, '08')) { return false; } const base: any = primeiros(valor, 11); const primeiro = substracaoPor11SeMaiorQue2CasoContrario0(mod(base)); const segundo = substracaoPor11SeMaiorQue2CasoContrario0(mod(base + primeiro)); return base + primeiro + segundo; }, es: function (valor: any) { return calculoTrivialGenerate(valor); }, go: function (valor: any) { if (tamanhoNaoE(valor)) { return false; } if (['10', '11', '15'].indexOf(valor.substring(0, 2)) === -1) { return false; } const base: any = primeiros(valor); if (base === '11094402') { return valor.substr(8) === '1' || valor.substr(8) === '0'; } const resto = mod(base); let digito: number; if (resto === 0) { digito = 0; } else if (resto === 1) { if (entre(base, 10103105, 10119997)) { digito = 1; } else { digito = 0; } } else { digito = 11 - resto; } return base + digito; }, ma: function (valor: any) { if (tamanhoNaoE(valor)) { return false; } if (naoComecaCom(valor, '12')) { return false; } return calculoTrivialGenerate(valor); }, mg: function (valor: any) { if (tamanhoNaoE(valor, 13)) { return false; } const base = primeiros(valor, 11); const baseComZero = valor.substring(0, 3) + '0' + valor.substring(3, 11); let i = 0; const produtorioLiteral = baseComZero.split('').reduceRight(function (anterior, atual) { if (i > [2, 1].length - 1) { i = 0; } return ([2, 1][i++] * parseInt(atual, 10)).toString() + anterior.toString(); }, '').split('').reduce(function (anterior, atual) { return anterior + parseInt(atual, 10); }, 0); let primeiro: any = ((Math.floor(produtorioLiteral / 10) + 1) * 10) - produtorioLiteral; if (primeiro === 10) { primeiro = 0; } const segundo = substracaoPor11SeMaiorQue2CasoContrario0(mod(base + primeiro, serie(2, 11))); return base + primeiro + segundo; }, ms: function (valor: any) { if (naoComecaCom(valor, '28')) { return false; } return calculoTrivialGenerate(valor); }, mt: function (valor: any) { if (tamanhoNaoE(valor, 11) && tamanhoNaoE(valor)) { return false; } const base = tamanhoE(valor, 11) ? valor.substring(0, 10) : primeiros(valor); return calculoTrivialGenerate(valor, base, true); }, pa: function (valor: any) { if (tamanhoNaoE(valor)) { return false; } if (naoComecaCom(valor, '15')) { return false; } return calculoTrivialGenerate(valor); }, pb: function (valor: any) { if (tamanhoNaoE(valor)) { return false; } return calculoTrivialGenerate(valor); }, pe: function (valor: any) { const base: any = valor.substring(0, valor.length - 2); const restoPrimeiro = mod(base); const primeiro = 11 - restoPrimeiro >= 10 ? 0 : 11 - restoPrimeiro; const restoSegundo = mod(base + primeiro); const segundo = 11 - restoSegundo >= 10 ? 0 : 11 - restoSegundo; return base + primeiro + segundo; }, pi: function (valor: any) { return calculoTrivialGenerate(valor); }, pr: function (valor: any) { if (tamanhoNaoE(valor, 10)) { return false; } const base = primeiros(valor); const restoPrimeiro = mod(base, serie(2, 7)); const primeiro = 11 - restoPrimeiro >= 10 ? 0 : 11 - restoPrimeiro; const restoSegundo = mod(base + primeiro, serie(2, 7)); const segundo = 11 - restoSegundo >= 10 ? 0 : 11 - restoSegundo; return base + primeiro + segundo; }, rj: function (valor: any) { if (tamanhoNaoE(valor, 8)) { return false; } const base = primeiros(valor, 7); const digito = substracaoPor11SeMaiorQue2CasoContrario0(mod(base, serie(2, 7))); return base + digito; }, rn: function (valor: any) { if (tamanhoNaoE(valor) && tamanhoNaoE(valor, 10)) { return false; } if (naoComecaCom(valor, '20')) { return false; } const base = valor.substring(0, valor.length - 1); const multiplicadores = serie(2, 9); if (tamanhoE(valor, 10)) { multiplicadores.push(10); } const resto = (mod(base, multiplicadores) * 10) % 11; const digito = resto === 10 ? 0 : resto; return base + digito; }, ro: function (valor: any) { let base: any, digito: number, resultadoMod: number; if (tamanhoE(valor, 9)) { base = valor.substring(3, 8); digito = substracaoPor11SeMaiorQue2CasoContrario0(mod(base)); return valor === valor.substring(0, 3) + base + digito; } else if (tamanhoE(valor, 14)) { base = primeiros(valor, 13); resultadoMod = mod(base); digito = resultadoMod <= 1 ? 1 : 11 - resultadoMod; return base + digito; } else { return false; } }, rr: function (valor: any) { if (tamanhoNaoE(valor)) { return false; } if (naoComecaCom(valor, '24')) { return false; } const base = primeiros(valor); const digito = mod(base, [8, 7, 6, 5, 4, 3, 2, 1], 9); return base + digito; }, rs: function (valor: any) { if (tamanhoNaoE(valor, 10)) { return false; } const base = primeiros(valor, 9); return calculoTrivialGenerate(valor, base, true); }, sc: function (valor: any) { return calculoTrivialGenerate(valor); }, se: function (valor: any) { if (tamanhoNaoE(valor)) { return false; } return calculoTrivialGenerate(valor); }, sp: function (valor: any) { valor = valor.toUpperCase(); let segundaBase: string; if (valor.substr(0, 1) === 'P') { if (tamanhoNaoE(valor, 13)) { return false; } const base = valor.substring(1, 9); segundaBase = valor.substring(10, 13); const resto = mod(base, [10, 8, 7, 6, 5, 4, 3, 1]).toString(); const digito = resto.length > 1 ? resto[1] : resto[0]; return 'P' + base + digito + segundaBase; } else { if (tamanhoNaoE(valor, 12)) { return false; } const primeiraBase = primeiros(valor); segundaBase = valor.substring(9, 11); const primeiroResto = mod(primeiraBase, [10, 8, 7, 6, 5, 4, 3, 1]).toString(); const primeiro = primeiroResto.length > 1 ? primeiroResto[1] : primeiroResto[0]; const segundoResto = mod(primeiraBase + primeiro + segundaBase, serie(2, 10)).toString(); const segundo = segundoResto.length > 1 ? segundoResto[1] : segundoResto[0]; return primeiraBase + primeiro + segundaBase + segundo; } }, to: function (valor: any) { if (tamanhoNaoE(valor) && tamanhoNaoE(valor, 11)) { return false; } let base: any; if (tamanhoE(valor, 11)) { if (['01', '02', '03', '99'].indexOf(valor.substring(2, 4)) === -1) { return false; } base = valor.substring(0, 2) + valor.substring(4, 10); } else { base = primeiros(valor); } const digito = substracaoPor11SeMaiorQue2CasoContrario0(mod(base)); return valor.substring(0, valor.length - 1) + digito; }, }; const funcoes: BigObject<Function> = { ac: function (valor: any) { return valor === generateInscricaoEstadual.ac(valor); }, am: function (valor: any) { return valor === generateInscricaoEstadual.am(valor); }, al: function (valor: any) { return valor === generateInscricaoEstadual.al(valor); }, ap: function (valor: any) { return valor === generateInscricaoEstadual.ap(valor); }, ba: function (valor: any) { return valor === generateInscricaoEstadual.ba(valor); }, ce: function (valor: any) { return valor === generateInscricaoEstadual.ce(valor); }, df: function (valor: any) { return valor === generateInscricaoEstadual.df(valor); }, es: function (valor: any) { return valor === generateInscricaoEstadual.es(valor); }, go: function (valor: any) { return valor === generateInscricaoEstadual.go(valor); }, ma: function (valor: any) { return valor === generateInscricaoEstadual.ma(valor); }, mg: function (valor: any) { return valor === generateInscricaoEstadual.mg(valor); }, ms: function (valor: any) { return valor === generateInscricaoEstadual.ms(valor); }, mt: function (valor: any) { return valor === generateInscricaoEstadual.mt(valor); }, pa: function (valor: any) { return valor === generateInscricaoEstadual.pa(valor); }, pb: function (valor: any) { return valor === generateInscricaoEstadual.pb(valor); }, pe: function (valor: any) { return valor === generateInscricaoEstadual.pe(valor); }, pi: function (valor: any) { return valor === generateInscricaoEstadual.pi(valor); }, pr: function (valor: any) { return valor === generateInscricaoEstadual.pr(valor); }, rj: function (valor: any) { return valor === generateInscricaoEstadual.rj(valor); }, rn: function (valor: any) { return valor === generateInscricaoEstadual.rn(valor); }, ro: function (valor: any) { return valor === generateInscricaoEstadual.ro(valor); }, rr: function (valor: any) { return valor === generateInscricaoEstadual.rr(valor); }, rs: function (valor: any) { return valor === generateInscricaoEstadual.rs(valor); }, sc: function (valor: any) { return valor === generateInscricaoEstadual.sc(valor); }, se: function (valor: any) { return valor === generateInscricaoEstadual.se(valor); }, sp: function (valor: string | boolean) { return valor === generateInscricaoEstadual.sp(valor); }, to: function (valor: any) { return valor === generateInscricaoEstadual.to(valor); }, }; export function validate_inscricaoestadual(ie: string | Array<string>, estado: any) { if (eIndefinido(estado) || estado === null) { estado = ''; } estado = estado.toLowerCase(); if (estado !== '' && !(estado in funcoes)) { return new Error('estado não é válido'); } if (eIndefinido(ie)) { return new Error('ie deve ser fornecida'); } if (Array.isArray(ie)) { let retorno = true; ie.forEach(function (i) { if (!validate_inscricaoestadual(i, estado)) { retorno = false; } }); return retorno; } if (typeof ie !== 'string') { return new Error('ie deve ser string ou array de strings'); } if (!allNumbersAreSame(ie)) { return new Error('ie com todos dígitos iguais'); } if (ie.match(/^ISENTO$/i)) { return true; } ie = ie.replace(/[\.|\-|\/|\s]/g, ''); if (estado === '') { if (lookup(ie)) { return true; } else { return false; } } if (/^\d+$/.test(ie) || estado === 'sp' || funcoes[estado]) { return funcoes[estado](ie); } return false; } export const MASKSIE: BigObject<MaskType> = { ac: { text: '01.004.823/001-12', textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, '-', /\d/, /\d/] }, al: { text: '240000048', textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/] }, am: { text: '04.145.871-0', textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/] }, ap: { text: '240000048', textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/] }, ba: { text: '1234567-48', textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/], textMaskFunction: function mask(userInput: any) { const numberLength = getSizeNumbers(userInput); if (!userInput || numberLength > 8) { return [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/]; } else { return [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/]; } } }, ce: { text: '06.000001-5', textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/] }, df: { text: '06 000001 123-55', textMask: [/\d/, /\d/, ' ', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/] }, es: { text: '082.560.67-6', textMask: [/\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, '-', /\d/] }, go: { text: '06.000.001-5', textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/] }, ma: { text: '12.104.376-2', textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/] }, mg: { text: '001.819.263/0048', textMask: [/\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/] }, ms: { text: '001819263', textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/] }, mt: { text: '0018192630-1', textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/] }, pa: { text: '06-000001-5', textMask: [/\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/] }, pb: { text: '06000001-5', textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/] }, pe: { text: '0192310-24', textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/] }, pi: { text: '19.301.656-7', textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/] }, pr: { text: '19301656-78', textMask: [/\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/] }, rj: { text: '20.040.04-1', textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, '-', /\d/] }, rn: { text: '20.040.040-1', textMask: [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/], textMaskFunction: function mask(userInput: any) { const numberLength = getSizeNumbers(userInput); if (!userInput || numberLength > 9) { return [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/]; } else { return [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/]; } } }, ro: { text: '101.62521-3', textMask: [/\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/] }, rr: { text: '24006628-1', textMask: [/\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/] }, rs: { text: '024/0440013', textMask: [/\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/] }, sc: { text: '271.234.563', textMask: [/\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/] }, se: { text: '27123456-3', textMask: [/\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/] }, sp: { text: '114.814.878.119', textMask: [/\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/] }, to: { text: '11 81 4878119', textMask: [/\d/, /\d/, ' ', /\d/, /\d/, ' ', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/] }, }; function getSizeNumbers(userInput: string) { const numbers: any = userInput.match(/\d/g); let numberLength = 0; if (numbers) { numberLength = numbers.join('').length; } return numberLength } function eIndefinido(objeto: any) { return typeof objeto === typeof undefined; } function tamanhoNaoE(string: { length: number; }, tamanho = 9) { if (eIndefinido(tamanho)) { tamanho = 9; } return string.length !== tamanho; } function tamanhoE(string: any[], tamanho: number) { return !tamanhoNaoE(string, tamanho); } function serie(de: number, ate: number) { const resultado = []; while (de <= ate) { resultado.push(de++); } return resultado; } function primeiros(string: any, quantidade = 8) { if (eIndefinido(quantidade)) { quantidade = 8; } return string.substring(0, quantidade); } function substracaoPor11SeMaiorQue2CasoContrario0(valor: number) { return valor < 2 ? 0 : 11 - valor; } function mod(valor: string, multiplicadores = serie(2, 9), divisor = 11) { if (eIndefinido(divisor)) { divisor = 11; } if (eIndefinido(multiplicadores)) { multiplicadores = serie(2, 9); } let i = 0; return valor.split('').reduceRight(function (anterior: number, atual: string) { if (i > multiplicadores.length - 1) { i = 0; } return (multiplicadores[i++] * parseInt(atual, 10)) + anterior; }, 0) % divisor; } function calculoTrivialGenerate(valor: any, base: any = null, validarTamanho = false) { if (!validarTamanho && tamanhoNaoE(valor)) { return false; } if (eIndefinido(base)) { base = primeiros(valor); } if (!base) { base = primeiros(valor); } const digito = substracaoPor11SeMaiorQue2CasoContrario0(mod(base)); return base + digito; } function naoComecaCom(string: any, valor: string) { return string.substring(0, valor.length) !== valor; } function entre(valor: string | number, limiteInferior: number, limiteSuperior: number) { if (typeof valor === 'string') { valor = parseInt(valor, 10); } return valor >= limiteInferior && valor <= limiteSuperior; } function lookup(ie: any) { const resultado = []; for (const estado in funcoes) { if (funcoes[estado](ie)) { resultado.push(estado); } } if (tamanhoE(resultado, 0)) { return false; } else { return resultado; } }
the_stack
interface AccessTokenAuthorizeOptions extends AuthorizeOptions { response_type?: "token" | undefined; } /** * Option form to request a code. */ interface CodeAuthorizeOptions extends AuthorizeOptions { response_type: "code"; } /** * Options that may be passed to `authorize`. */ interface AuthorizeOptions { /** * Specifies when to show a login screen to the user. * `"auto"` will attempt to use a cached token. If the cached token fails or does not exist, the user will be presented with a login screen. * `"always"` does not use the cached token and always presents a login screen. * `"never"` will used the cached token; if the token does not work, authorize will return `invalid_grant`. * Defaults to `"auto"`. */ interactive?: AuthorizeInteractiveOption | undefined; /** * `true` to use a popup window for login, `false` to redirect the current browser window to the authorization dialog. Defaults to `true`. If `false`, the next parameter MUST be a redirect URL. */ popup?: boolean | undefined; /** * The grant type requested. Specify `token` to request an Implicit grant or `code` to request an Authorization Code grant. Defaults to `token`. */ response_type?: AuthorizeResponseType | undefined; /** * The access scope requested. */ scope: AuthorizeScope; /** * An opaque value used by the client to maintain state between this request and the response. The Login with Amazon authorization service will include this value when redirecting the user back * to the client. It is also used to prevent cross-site request forgery. * For more information see [Cross-site Request Forgery](https://developer.amazon.com/docs/login-with-amazon/cross-site-request-forgery.html). * */ state?: string | undefined; scope_data?: AuthorizeScopeData | undefined; } type AuthorizeScopeData = { [scope in AuthorizationScopeOptions]?: { essential: boolean; } }; /** * * Accepted values for `scope` member of `authorize` options. */ type AuthorizationScopeOptions = "profile" | "profile:user_id" | "postal_code"; type AuthorizeResponseType = "token" | "code"; type AuthorizeScope = AuthorizationScopeOptions | AuthorizationScopeOptions[]; type AuthorizeInteractiveOption = "auto" | "always" | "never"; type AuthorizeRequest = CodeRequest | AccessTokenRequest; interface CodeRequest extends AuthorizeRequestBase<CodeRequest> { /** * An authorization code that can be exchanged for an access token. */ code: string; /** * The state value provided to authorize using the options object. */ state: string; } interface AccessTokenRequest extends AuthorizeRequestBase<AccessTokenRequest> { /** * The type of token issued. Must be `"bearer"`. */ token_type: "bearer"; /** * The access token issued by the authorization server. */ access_token: string; /** * The number of seconds until the access token expires. */ expires_in: number; } /** * Base interface that contains common members to an `authorize` request (whether for token or code). * Contains optional error-related members; these will be defined if there was an error. */ interface AuthorizeRequestBase<T extends AuthorizeRequest> { /** * The current status of the request. */ status: AuthorizeRequestStatus; /** * A short error code indicating why the authorization failed. */ error?: AuthorizeRequestErrorType | undefined; /** * A human-readable description of the error. */ error_description?: string | undefined; /** * A URI for a web page with more information on the error. */ error_uri?: string | undefined; /** * Registers a callback function or sets a redirect URI to call when the * authorization request is complete. If this function is called after the * request is complete, the function or redirect will happen immediately. * If a callback function is used, the `AuthorizeRequest` will be the first * parameter. If a redirect URI is used, the browser will redirect to that * URI with the OAuth 2 response parameters included in the query string. * @param next A URI to redirect the browser response,or a JavaScript * function to call with the authorization response. */ onComplete(next: string | NextCallback<T>): void; } type AuthorizeRequestErrorType = | "access_denied" | "invalid_grant" | "invalid_request" | "invalid_scope" | "server_error" | "temporarily_unavailable" | "unauthorized_client"; type AuthorizeRequestStatus = "queued" | "in_progress" | "complete"; /** * Type of callback invoked after `authorize` completes. */ type NextCallback<T extends AuthorizeRequest> = (response: T) => void; type RetrieveProfileResponse = | RetrieveProfileResponseError | RetrieveProfileResponseSuccess; /** * Response type if `retrieveProfile` call failed. */ interface RetrieveProfileResponseError { /** * Indicates whether profile was successfully retrieved. * For this type, it is always false. */ success: false; /** * The error message given with the response. */ error: string; } /** * Response type if `retrieveProfile` call succeeded. */ interface RetrieveProfileResponseSuccess { /** * Indicates whether profile was successfully retrieved. * For this type, it is always true. */ success: true; /** * Contains the user's profile information. */ profile: UserProfile; } /** * Contains profile information. */ type UserProfile = Partial<{ /** * An identifier that uniquely identifies the logged-in user for this caller. Only present if the `profile` or `profile:user_id` scopes are requested and granted. */ CustomerId: string; /** * The customer's name. Only present if the `profile` scope is requested and granted. */ Name: string; /** * The postal code of the customer's primary address. Only present if the `postal_code` scope is requested and granted. */ PostalCode: string; /** * The primary email address for the customer. Only present if the `profile` scope is requested and granted. */ PrimaryEmail: string; }>; type RetrieveProfileCallback = (response: RetrieveProfileResponse) => void; declare namespace amazon { namespace Login { function authorize( options: AccessTokenAuthorizeOptions, next?: string | NextCallback<AccessTokenRequest> ): AccessTokenRequest; function authorize( options: CodeAuthorizeOptions, next?: string | NextCallback<CodeRequest> ): CodeRequest; function authorize( options: AuthorizeOptions, next?: string | NextCallback<AuthorizeRequest> ): AuthorizeRequest; /** * Retrieves the customer profile and passes it to a callback function. * Uses an access token provided by `authorize`. * @param accessToken An access token. If this parameter is omitted, retrieveProfile will call authorize, requesting the profile scope. * @param callback Called with the profile data or an error string */ function retrieveProfile( accessToken: string, callback?: RetrieveProfileCallback ): void; /** * Retrieves the customer profile and passes it to a callback function. * If no `access_token` is provided, this function will call `authorize` * with a `profile` scope. * @param callback Called with the profile data or an error string */ function retrieveProfile(callback: RetrieveProfileCallback): void; /** * Sets the client identifier that will be used to request authorization. * You must call this function before calling `authorize`. */ function setClientId(clientId: string): void; /** * Gets the client identifier that will be used to request authorization. * You must call `setClientId` before calling this function. */ function getClientId(): string; /** * Determines whether or not Login with Amazon should use the * Amazon Pay sandbox for requests. To use the Amazon Pay sandbox, * call `setSandboxMode(true)` before calling `authorize`. */ function setSandboxMode(sandboxMode: boolean): void; /** * Sets the domain to use for saving cookies. * The domain must match the origin of the current page. * Defaults to the full domain for the current page. For example, if * you have two pages using the Login with Amazon SDK for JavaScript, * `site1.example.com` and `site2.example.com`, you would set the site * domain to `example.com` in the header of each site. * This will ensure that the cookies on both sites have access * to the same cached tokens. */ function setSiteDomain(siteDomain: string): void; /** * Determines whether or not Login with Amazon should use access tokens * written to the `amazon_Login_accessToken` cookie. You can use this * value to share an access token with another page. Access tokens * will still only grant access to the registered account for whom they * were created. When `true`, the Login with Amazon SDK for JavaScript * will check this cookie for cached tokens, and store newly granted * tokens in that cookie. */ function setUseCookie(useCookie: boolean): void; /** * Logs out the current user after a call to `authorize`. */ function logout(): void; /** * Login With Amazon has multiple authorization and resource endpoints. * This API determines the region of the authorization and resource * endpoints Login with Amazon SDK should talk to. This needs to be * called before the authorize and retreiveProfile APIs. * When not set, it defaults to “NorthAmerica” */ function setRegion(region: Region): void; enum Region { NorthAmerica, Europe, AsiaPacific } } }
the_stack
// The MIT License (MIT) // // vs-deploy (https://github.com/mkloubert/vs-deploy) // Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as deploy_contracts from './contracts'; import * as deploy_globals from './globals'; import * as deploy_helpers from './helpers'; import * as deploy_workspace from './workspace'; import * as FS from 'fs'; import * as OS from 'os'; import * as Path from 'path'; import * as vs_deploy from './deploy'; import * as vscode from 'vscode'; /** * A basic value. */ export abstract class ValueBase implements deploy_contracts.ObjectWithNameAndValue { /** * Stores the underlying item. */ protected readonly _ITEM: deploy_contracts.ValueWithName; /** * Initializes a new instance of that class. * * @param {deploy_contracts.ValueWithName} [item] The underlying item. */ constructor(item?: deploy_contracts.ValueWithName) { if (!item) { item = { name: undefined, type: undefined, }; } this._ITEM = item; } /** * Anything that identifies that value. */ public id: any; /** * Gets the underlying item. */ public get item(): deploy_contracts.ValueWithName { return this._ITEM; } /** * Gets the list of "other" values. */ public get otherValues(): ValueBase[] { let result: ValueBase[] = []; let ovp = this.otherValueProvider; if (ovp) { try { result = result.concat(deploy_helpers.asArray(ovp())); } catch (e) { //TODO: log } } return result.filter(x => x); } /** * The function that provides the "other" values. */ public otherValueProvider: () => ValueBase[]; /** @inheritdoc */ public get name(): string { return this.item.name; } /** @inheritdoc */ public abstract get value(): any; } /** * A value generated by (JavaScript) code. */ export class CodeValue extends ValueBase { /** @inheritdoc */ constructor(value?: deploy_contracts.CodeValueWithName) { super(value); } /** @inheritdoc */ public get code(): string { return deploy_helpers.toStringSafe(this.item.code); } /** @inheritdoc */ public get item(): deploy_contracts.CodeValueWithName { return <deploy_contracts.CodeValueWithName>super.item; } /** @inheritdoc */ public get value(): any { let $cwd = process.cwd(); let $homeDir = OS.homedir(); let $globalState = globalScriptValueState; let $me = this; let $others = {}; let $require = function(id: string) { return require(deploy_helpers.toStringSafe(id)); }; let $workspaceRoot = deploy_workspace.getRootPath(); // define properties for $others this.otherValues.forEach(ov => { try { let propertyName = deploy_helpers.toStringSafe(ov.name); if ('' === propertyName) { return; } Object.defineProperty($others, propertyName, { enumerable: true, configurable: true, get: () => { return ov.value; } }); } catch (e) { //TODO: log } }); return eval(this.code); } } /** * A value that accesses an environment variable. */ export class EnvValue extends ValueBase { /** @inheritdoc */ constructor(value?: deploy_contracts.EnvValueWithName) { super(value); } /** @inheritdoc */ public get alias(): string { return this.item.alias; } /** @inheritdoc */ public get name(): string { return deploy_helpers.isEmptyString(this.alias) ? this.realName : this.alias; } /** @inheritdoc */ public get item(): deploy_contracts.EnvValueWithName { return <deploy_contracts.EnvValueWithName>super.item; } /** @inheritdoc */ public get value(): any { let value: any; let myName = deploy_helpers.toStringSafe(this.realName).trim(); for (let p in process.env) { if (deploy_helpers.toStringSafe(p).trim() === myName) { value = process.env[p]; // found break; } } return value; } /** * Gets the "real" name. */ public get realName(): string { return super.name; } } /** * A value from a file. */ export class FileValue extends ValueBase { /** @inheritdoc */ constructor(value?: deploy_contracts.FileValueWithName) { super(value); } /** @inheritdoc */ public get item(): deploy_contracts.FileValueWithName { return <deploy_contracts.FileValueWithName>super.item; } /** @inheritdoc */ public get value(): any { let file = deploy_helpers.toStringSafe(this.item.file); file = replaceWithValues(this.otherValues, file); if (!Path.isAbsolute(file)) { file = Path.join(deploy_workspace.getRootPath(), file) } file = Path.resolve(file); let content = FS.readFileSync(file); if (content) { if (deploy_helpers.toBooleanSafe(this.item.asBinary)) { return content; } else { // as string let enc = deploy_helpers.normalizeString(this.item.encoding); if ('' === enc) { enc = 'utf8'; } let str = content.toString(enc); if (deploy_helpers.toBooleanSafe(this.item.usePlaceholders)) { str = replaceWithValues(this.otherValues, str); } return str; } } return content; } } /** * A value provided by a script. */ export class ScriptValue extends ValueBase { protected _config: deploy_contracts.DeployConfiguration; /** @inheritdoc */ constructor(value?: deploy_contracts.ScriptValueWithName, cfg?: deploy_contracts.DeployConfiguration) { super(value); this._config = cfg; } /** * Gets the underlying configuration. */ public get config(): deploy_contracts.DeployConfiguration { return this._config || <any>{}; } /** @inheritdoc */ public get item(): deploy_contracts.ScriptValueWithName { return <deploy_contracts.ScriptValueWithName>super.item; } /** @inheritdoc */ public get value(): any { let me = this; let result: any; let script = deploy_helpers.toStringSafe(me.item.script); script = replaceWithValues(me.otherValues, script); if (!deploy_helpers.isEmptyString(script)) { if (!Path.isAbsolute(script)) { script = Path.join(deploy_workspace.getRootPath(), script); } script = Path.resolve(script); if (FS.existsSync(script)) { let scriptModule = deploy_helpers.loadModule<deploy_contracts.ScriptValueModule>(script); if (scriptModule) { if (scriptModule.getValue) { let args: deploy_contracts.ScriptValueProviderArguments = { emitGlobal: function() { return deploy_globals.EVENTS.emit .apply(deploy_globals.EVENTS, arguments); }, globals: deploy_helpers.cloneObject(me.config.globals), globalState: undefined, name: undefined, options: deploy_helpers.cloneObject(me.item.options), others: undefined, replaceWithValues: function(val) { return replaceWithValues(me.otherValues, val); }, require: (id) => { return require(deploy_helpers.toStringSafe(id)); }, state: undefined, }; let others: Object = {}; me.otherValues.forEach(ov => { try { let propertyName = deploy_helpers.toStringSafe(ov.name); if ('' === propertyName) { return; } Object.defineProperty(others, propertyName, { enumerable: true, configurable: true, get: () => { return ov.value; } }); } catch (e) { //TODO: log } }); // args.globalState Object.defineProperty(args, 'globalState', { enumerable: true, get: () => { return globalScriptValueState; }, }); // args.name Object.defineProperty(args, 'name', { enumerable: true, get: () => { return me.name; }, }); // args.others Object.defineProperty(args, 'others', { enumerable: true, get: () => { return others; }, }); // args.state Object.defineProperty(args, 'state', { enumerable: true, get: () => { return scriptValueStates[script]; }, set: (newValue) => { scriptValueStates[script] = newValue; } }); result = scriptModule.getValue(args); } } } } return result; } } /** * A static value. */ export class StaticValue extends ValueBase { /** @inheritdoc */ constructor(value?: deploy_contracts.StaticValueWithName) { super(value); } /** @inheritdoc */ public get item(): deploy_contracts.StaticValueWithName { return <deploy_contracts.StaticValueWithName>super.item; } /** @inheritdoc */ public get value(): any { return this.item.value; } } let additionalValues: ValueBase[]; let globalScriptValueState: Object; let scriptValueStates: Object; /** * Returns a list of "build-in" values. * * @return {ValueBase[]} The list of values. */ export function getBuildInValues(): ValueBase[] { let objs: ValueBase[] = []; // ${cwd} { objs.push(new CodeValue({ name: 'cwd', type: "code", code: "process.cwd()", })); } // ${EOL} { objs.push(new CodeValue({ name: 'EOL', type: "code", code: "require('os').EOL", })); } // ${hostName} { objs.push(new CodeValue({ name: 'hostName', type: "code", code: "require('os').hostname()", })); } // ${homeDir} { objs.push(new CodeValue({ name: 'homeDir', type: "code", code: "require('os').homedir()", })); } // ${tempDir} { objs.push(new CodeValue({ name: 'tempDir', type: "code", code: "require('os').tmpdir()", })); } // ${userName} { objs.push(new CodeValue({ name: 'userName', type: "code", code: "require('os').userInfo().username", })); } // ${workspaceRoot} { objs.push(new CodeValue({ name: 'workspaceRoot', type: "code", code: "require('./workspace').getRootPath()", })); } return objs; } /** * Gets the current list of values. * * @return {ValueBase[]} The values. */ export function getValues(): ValueBase[] { let me: vs_deploy.Deployer = this; let myName = me.name; let values = deploy_helpers.asArray(me.config.values) .filter(x => x); // isFor values = values.filter(v => { let validHosts = deploy_helpers.asArray(v.isFor) .map(x => deploy_helpers.normalizeString(x)) .filter(x => '' !== x); if (validHosts.length < 1) { return true; } return validHosts.indexOf(myName) > -1; }); // platforms values = deploy_helpers.filterPlatformItems(values); let objs = toValueObjects(values, me.config); objs = objs.concat(additionalValues || []); objs = objs.concat(getBuildInValues()); return objs; } /** * Reloads the list of additional values. */ export function reloadAdditionalValues() { let me: vs_deploy.Deployer = this; let cfg = me.config; let av = []; if (cfg.env) { if (deploy_helpers.toBooleanSafe(cfg.env.importVarsAsPlaceholders)) { // automatically import environment variables as // placeholders / values for (let p in process.env) { av.push(new EnvValue({ name: p, type: 'env', })); } } } additionalValues = av; } /** * Handles a value as string and replaces placeholders. * * @param {deploy_contracts.ObjectWithNameAndValue|deploy_contracts.ObjectWithNameAndValue[]} values The "placeholders". * @param {any} val The value to parse. * * @return {string} The parsed value. */ export function replaceWithValues(values: deploy_contracts.ObjectWithNameAndValue | deploy_contracts.ObjectWithNameAndValue[], val: any): string { let allValues = deploy_helpers.asArray(values).filter(x => x); if (!deploy_helpers.isNullOrUndefined(val)) { let str = deploy_helpers.toStringSafe(val); allValues.forEach(v => { let vn = deploy_helpers.normalizeString(v.name); // ${VAR_NAME} str = str.replace(/(\$)(\{)([^\}]*)(\})/gm, (match, varIdentifier, openBracket, varName: string, closedBracked) => { let newValue: string = match; if (deploy_helpers.normalizeString(varName) === vn) { try { newValue = deploy_helpers.toStringSafe(v.value); } catch (e) { //TODO: log } } return newValue; }); }); return str; } return val; } /** * Resets all code / script based state values and objects. */ export function resetScriptStates() { globalScriptValueState = {}; scriptValueStates = {}; } /** * Converts a list of value items to objects. * * @param {(deploy_contracts.ValueWithName|deploy_contracts.ValueWithName[])} items The item(s) to convert. * * @returns {ValueBase[]} The items as objects. */ export function toValueObjects(items: deploy_contracts.ValueWithName | deploy_contracts.ValueWithName[], cfg?: deploy_contracts.DeployConfiguration): ValueBase[] { let result: ValueBase[] = []; deploy_helpers.asArray(items).filter(i => i).forEach((i, idx) => { let newValue: ValueBase; switch (deploy_helpers.normalizeString(i.type)) { case '': case 'static': newValue = new StaticValue(<deploy_contracts.StaticValueWithName>i); break; case 'code': newValue = new CodeValue(<deploy_contracts.CodeValueWithName>i); break; case 'env': case 'environment': newValue = new EnvValue(<deploy_contracts.EnvValueWithName>i); break; case 'file': newValue = new FileValue(<deploy_contracts.FileValueWithName>i); break; case 'script': newValue = new ScriptValue(<deploy_contracts.ScriptValueWithName>i, cfg); break; } if (newValue) { newValue.id = idx; newValue.otherValueProvider = () => { return result.filter(x => x.id !== newValue.id); }; result.push(newValue); } }); return result; }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { PrivateLinkService, PrivateLinkServicesListOptionalParams, PrivateLinkServicesListBySubscriptionOptionalParams, PrivateEndpointConnection, PrivateLinkServicesListPrivateEndpointConnectionsOptionalParams, AutoApprovedPrivateLinkService, PrivateLinkServicesListAutoApprovedPrivateLinkServicesOptionalParams, PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupOptionalParams, PrivateLinkServicesDeleteOptionalParams, PrivateLinkServicesGetOptionalParams, PrivateLinkServicesGetResponse, PrivateLinkServicesCreateOrUpdateOptionalParams, PrivateLinkServicesCreateOrUpdateResponse, PrivateLinkServicesGetPrivateEndpointConnectionOptionalParams, PrivateLinkServicesGetPrivateEndpointConnectionResponse, PrivateLinkServicesUpdatePrivateEndpointConnectionOptionalParams, PrivateLinkServicesUpdatePrivateEndpointConnectionResponse, PrivateLinkServicesDeletePrivateEndpointConnectionOptionalParams, CheckPrivateLinkServiceVisibilityRequest, PrivateLinkServicesCheckPrivateLinkServiceVisibilityOptionalParams, PrivateLinkServicesCheckPrivateLinkServiceVisibilityResponse, PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupOptionalParams, PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a PrivateLinkServices. */ export interface PrivateLinkServices { /** * Gets all private link services in a resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ list( resourceGroupName: string, options?: PrivateLinkServicesListOptionalParams ): PagedAsyncIterableIterator<PrivateLinkService>; /** * Gets all private link service in a subscription. * @param options The options parameters. */ listBySubscription( options?: PrivateLinkServicesListBySubscriptionOptionalParams ): PagedAsyncIterableIterator<PrivateLinkService>; /** * Gets all private end point connections for a specific private link service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param options The options parameters. */ listPrivateEndpointConnections( resourceGroupName: string, serviceName: string, options?: PrivateLinkServicesListPrivateEndpointConnectionsOptionalParams ): PagedAsyncIterableIterator<PrivateEndpointConnection>; /** * Returns all of the private link service ids that can be linked to a Private Endpoint with auto * approved in this subscription in this region. * @param location The location of the domain name. * @param options The options parameters. */ listAutoApprovedPrivateLinkServices( location: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesOptionalParams ): PagedAsyncIterableIterator<AutoApprovedPrivateLinkService>; /** * Returns all of the private link service ids that can be linked to a Private Endpoint with auto * approved in this subscription in this region. * @param location The location of the domain name. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ listAutoApprovedPrivateLinkServicesByResourceGroup( location: string, resourceGroupName: string, options?: PrivateLinkServicesListAutoApprovedPrivateLinkServicesByResourceGroupOptionalParams ): PagedAsyncIterableIterator<AutoApprovedPrivateLinkService>; /** * Deletes the specified private link service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param options The options parameters. */ beginDelete( resourceGroupName: string, serviceName: string, options?: PrivateLinkServicesDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Deletes the specified private link service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param options The options parameters. */ beginDeleteAndWait( resourceGroupName: string, serviceName: string, options?: PrivateLinkServicesDeleteOptionalParams ): Promise<void>; /** * Gets the specified private link service by resource group. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param options The options parameters. */ get( resourceGroupName: string, serviceName: string, options?: PrivateLinkServicesGetOptionalParams ): Promise<PrivateLinkServicesGetResponse>; /** * Creates or updates an private link service in the specified resource group. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param parameters Parameters supplied to the create or update private link service operation. * @param options The options parameters. */ beginCreateOrUpdate( resourceGroupName: string, serviceName: string, parameters: PrivateLinkService, options?: PrivateLinkServicesCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<PrivateLinkServicesCreateOrUpdateResponse>, PrivateLinkServicesCreateOrUpdateResponse > >; /** * Creates or updates an private link service in the specified resource group. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param parameters Parameters supplied to the create or update private link service operation. * @param options The options parameters. */ beginCreateOrUpdateAndWait( resourceGroupName: string, serviceName: string, parameters: PrivateLinkService, options?: PrivateLinkServicesCreateOrUpdateOptionalParams ): Promise<PrivateLinkServicesCreateOrUpdateResponse>; /** * Get the specific private end point connection by specific private link service in the resource * group. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param peConnectionName The name of the private end point connection. * @param options The options parameters. */ getPrivateEndpointConnection( resourceGroupName: string, serviceName: string, peConnectionName: string, options?: PrivateLinkServicesGetPrivateEndpointConnectionOptionalParams ): Promise<PrivateLinkServicesGetPrivateEndpointConnectionResponse>; /** * Approve or reject private end point connection for a private link service in a subscription. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param peConnectionName The name of the private end point connection. * @param parameters Parameters supplied to approve or reject the private end point connection. * @param options The options parameters. */ updatePrivateEndpointConnection( resourceGroupName: string, serviceName: string, peConnectionName: string, parameters: PrivateEndpointConnection, options?: PrivateLinkServicesUpdatePrivateEndpointConnectionOptionalParams ): Promise<PrivateLinkServicesUpdatePrivateEndpointConnectionResponse>; /** * Delete private end point connection for a private link service in a subscription. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param peConnectionName The name of the private end point connection. * @param options The options parameters. */ beginDeletePrivateEndpointConnection( resourceGroupName: string, serviceName: string, peConnectionName: string, options?: PrivateLinkServicesDeletePrivateEndpointConnectionOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Delete private end point connection for a private link service in a subscription. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the private link service. * @param peConnectionName The name of the private end point connection. * @param options The options parameters. */ beginDeletePrivateEndpointConnectionAndWait( resourceGroupName: string, serviceName: string, peConnectionName: string, options?: PrivateLinkServicesDeletePrivateEndpointConnectionOptionalParams ): Promise<void>; /** * Checks whether the subscription is visible to private link service. * @param location The location of the domain name. * @param parameters The request body of CheckPrivateLinkService API call. * @param options The options parameters. */ checkPrivateLinkServiceVisibility( location: string, parameters: CheckPrivateLinkServiceVisibilityRequest, options?: PrivateLinkServicesCheckPrivateLinkServiceVisibilityOptionalParams ): Promise<PrivateLinkServicesCheckPrivateLinkServiceVisibilityResponse>; /** * Checks whether the subscription is visible to private link service in the specified resource group. * @param location The location of the domain name. * @param resourceGroupName The name of the resource group. * @param parameters The request body of CheckPrivateLinkService API call. * @param options The options parameters. */ checkPrivateLinkServiceVisibilityByResourceGroup( location: string, resourceGroupName: string, parameters: CheckPrivateLinkServiceVisibilityRequest, options?: PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupOptionalParams ): Promise< PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupResponse >; }
the_stack
import { expect } from "chai"; import * as sinon from "sinon"; import { logger } from "../../../../logger"; import * as backend from "../../../../deploy/functions/backend"; import * as reporter from "../../../../deploy/functions/release/reporter"; import * as track from "../../../../track"; const ENDPOINT_BASE: Omit<backend.Endpoint, "httpsTrigger"> = { platform: "gcfv1", id: "id", region: "region", project: "project", entryPoint: "id", runtime: "nodejs16", }; const ENDPOINT: backend.Endpoint = { ...ENDPOINT_BASE, httpsTrigger: {} }; describe("reporter", () => { describe("triggerTag", () => { it("detects v1.https", () => { expect( reporter.triggerTag({ ...ENDPOINT_BASE, httpsTrigger: {}, }) ).to.equal("v1.https"); }); it("detects v2.https", () => { expect( reporter.triggerTag({ ...ENDPOINT_BASE, platform: "gcfv2", httpsTrigger: {}, }) ).to.equal("v2.https"); }); it("detects v1.callable", () => { expect( reporter.triggerTag({ ...ENDPOINT_BASE, httpsTrigger: {}, labels: { "deployment-callable": "true", }, }) ).to.equal("v1.callable"); }); it("detects v2.callable", () => { expect( reporter.triggerTag({ ...ENDPOINT_BASE, platform: "gcfv2", httpsTrigger: {}, labels: { "deployment-callable": "true", }, }) ).to.equal("v2.callable"); }); it("detects v1.scheduled", () => { expect( reporter.triggerTag({ ...ENDPOINT_BASE, scheduleTrigger: {}, }) ).to.equal("v1.scheduled"); }); it("detects v2.scheduled", () => { expect( reporter.triggerTag({ ...ENDPOINT_BASE, platform: "gcfv2", scheduleTrigger: {}, }) ).to.equal("v2.scheduled"); }); it("detects others", () => { expect( reporter.triggerTag({ ...ENDPOINT_BASE, platform: "gcfv2", eventTrigger: { eventType: "google.pubsub.topic.publish", eventFilters: {}, retry: false, }, }) ).to.equal("google.pubsub.topic.publish"); }); }); describe("logAndTrackDeployStats", () => { let trackStub: sinon.SinonStub; let debugStub: sinon.SinonStub; beforeEach(() => { trackStub = sinon.stub(track, "track"); debugStub = sinon.stub(logger, "debug"); }); afterEach(() => { sinon.verifyAndRestore(); }); it("tracks global summaries", async () => { const summary: reporter.Summary = { totalTime: 2_000, results: [ { endpoint: ENDPOINT, durationMs: 2_000, }, { endpoint: ENDPOINT, durationMs: 1_000, error: new reporter.DeploymentError(ENDPOINT, "update", undefined), }, { endpoint: ENDPOINT, durationMs: 0, error: new reporter.AbortedDeploymentError(ENDPOINT), }, ], }; await reporter.logAndTrackDeployStats(summary); expect(trackStub).to.have.been.calledWith("function_deploy_success", "v1.https", 2_000); expect(trackStub).to.have.been.calledWith("function_deploy_failure", "v1.https", 1_000); // Aborts aren't tracked because they would throw off timing metrics expect(trackStub).to.not.have.been.calledWith("function_deploy_failure", "v1.https", 0); expect(debugStub).to.have.been.calledWith("Total Function Deployment time: 2000"); expect(debugStub).to.have.been.calledWith("3 Functions Deployed"); expect(debugStub).to.have.been.calledWith("1 Functions Errored"); expect(debugStub).to.have.been.calledWith("1 Function Deployments Aborted"); // The 0ms for an aborted function isn't counted. expect(debugStub).to.have.been.calledWith("Average Function Deployment time: 1500"); }); it("tracks v1 vs v2 codebases", async () => { const v1 = { ...ENDPOINT }; const v2: backend.Endpoint = { ...ENDPOINT, platform: "gcfv2" }; const summary: reporter.Summary = { totalTime: 1_000, results: [ { endpoint: v1, durationMs: 1_000, }, { endpoint: v2, durationMs: 1_000, }, ], }; await reporter.logAndTrackDeployStats(summary); expect(trackStub).to.have.been.calledWith("functions_codebase_deploy", "v1+v2", 2); trackStub.resetHistory(); summary.results = [{ endpoint: v1, durationMs: 1_000 }]; await reporter.logAndTrackDeployStats(summary); expect(trackStub).to.have.been.calledWith("functions_codebase_deploy", "v1", 1); trackStub.resetHistory(); summary.results = [{ endpoint: v2, durationMs: 1_000 }]; await reporter.logAndTrackDeployStats(summary); expect(trackStub).to.have.been.calledWith("functions_codebase_deploy", "v2", 1); }); it("tracks overall success/failure", async () => { const success: reporter.DeployResult = { endpoint: ENDPOINT, durationMs: 1_000, }; const failure: reporter.DeployResult = { endpoint: ENDPOINT, durationMs: 1_000, error: new reporter.DeploymentError(ENDPOINT, "create", undefined), }; const summary: reporter.Summary = { totalTime: 1_000, results: [success, failure], }; await reporter.logAndTrackDeployStats(summary); expect(trackStub).to.have.been.calledWith("functions_deploy_result", "partial_success", 1); expect(trackStub).to.have.been.calledWith("functions_deploy_result", "partial_failure", 1); expect(trackStub).to.have.been.calledWith( "functions_deploy_result", "partial_error_ratio", 0.5 ); trackStub.resetHistory(); summary.results = [success]; await reporter.logAndTrackDeployStats(summary); expect(trackStub).to.have.been.calledWith("functions_deploy_result", "success", 1); trackStub.resetHistory(); summary.results = [failure]; await reporter.logAndTrackDeployStats(summary); expect(trackStub).to.have.been.calledWith("functions_deploy_result", "failure", 1); }); }); describe("printErrors", () => { let infoStub: sinon.SinonStub; beforeEach(() => { infoStub = sinon.stub(logger, "info"); }); afterEach(() => { sinon.verifyAndRestore(); }); it("does nothing if there are no errors", () => { const summary: reporter.Summary = { totalTime: 1_000, results: [ { endpoint: ENDPOINT, durationMs: 1_000, }, ], }; reporter.printErrors(summary); expect(infoStub).to.not.have.been.called; }); it("only prints summaries for non-aborted errors", () => { const summary: reporter.Summary = { totalTime: 1_000, results: [ { endpoint: { ...ENDPOINT, id: "failedCreate" }, durationMs: 1_000, error: new reporter.DeploymentError(ENDPOINT, "create", undefined), }, { endpoint: { ...ENDPOINT, id: "abortedDelete" }, durationMs: 0, error: new reporter.AbortedDeploymentError(ENDPOINT), }, ], }; reporter.printErrors(summary); // N.B. The lists of functions are printed in one call along with their header // so that we know why a function label was printed (e.g. abortedDelete shouldn't // show up in the main list of functions that had deployment errors but should show // up in the list of functions that weren't deleted). To match these regexes we must // pass the "s" modifier to regexes to make . capture newlines. expect(infoStub).to.have.been.calledWithMatch(/Functions deploy had errors.*failedCreate/s); expect(infoStub).to.not.have.been.calledWithMatch( /Functions deploy had errors.*abortedDelete/s ); }); it("prints IAM errors", () => { const explicit: backend.Endpoint = { ...ENDPOINT, httpsTrigger: { invoker: ["public"], }, }; const summary: reporter.Summary = { totalTime: 1_000, results: [ { endpoint: explicit, durationMs: 1_000, error: new reporter.DeploymentError(explicit, "set invoker", undefined), }, ], }; reporter.printErrors(summary); expect(infoStub).to.have.been.calledWithMatch("Unable to set the invoker for the IAM policy"); expect(infoStub).to.not.have.been.calledWithMatch( "One or more functions were being implicitly made publicly available" ); infoStub.resetHistory(); // No longer explicitly setting invoker summary.results[0].endpoint = ENDPOINT; reporter.printErrors(summary); expect(infoStub).to.have.been.calledWithMatch("Unable to set the invoker for the IAM policy"); expect(infoStub).to.have.been.calledWithMatch( "One or more functions were being implicitly made publicly available" ); }); it("prints quota errors", () => { const rawError = new Error("Quota exceeded"); (rawError as any).status = 429; const summary: reporter.Summary = { totalTime: 1_000, results: [ { endpoint: ENDPOINT, durationMs: 1_000, error: new reporter.DeploymentError(ENDPOINT, "create", rawError), }, ], }; reporter.printErrors(summary); expect(infoStub).to.have.been.calledWithMatch( "Exceeded maximum retries while deploying functions." ); }); it("prints aborted errors", () => { const summary: reporter.Summary = { totalTime: 1_000, results: [ { endpoint: { ...ENDPOINT, id: "failedCreate" }, durationMs: 1_000, error: new reporter.DeploymentError(ENDPOINT, "create", undefined), }, { endpoint: { ...ENDPOINT, id: "abortedDelete" }, durationMs: 1_000, error: new reporter.AbortedDeploymentError(ENDPOINT), }, ], }; reporter.printErrors(summary); expect(infoStub).to.have.been.calledWithMatch( /the following functions were not deleted.*abortedDelete/s ); expect(infoStub).to.not.have.been.calledWith( /the following functions were not deleted.*failedCreate/s ); }); }); });
the_stack
import * as _ from 'lodash'; import * as Types from './types'; import { ReferenceNode } from './types'; // tslint:disable-next-line // https://raw.githubusercontent.com/sogko/graphql-shorthand-notation-cheat-sheet/master/graphql-shorthand-notation-cheat-sheet.png export default class Emitter { renames:{[key:string]:string} = {}; constructor(private types:Types.TypeMap) { this.types = <Types.TypeMap>_.omitBy(types, (node, name) => this._preprocessNode(node, name!)); } emitAll(stream:NodeJS.WritableStream) { stream.write('\n'); _.each(this.types, (node, name) => this.emitTopLevelNode(node, name!, stream)); } emitTopLevelNode(node:Types.Node, name:Types.SymbolName, stream:NodeJS.WritableStream) { let content; if (node.type === 'alias') { content = this._emitAlias(node, name); } else if (node.type === 'interface') { content = this._emitInterface(node, name); } else if (node.type === 'enum') { content = this._emitEnum(node, name); } else { throw new Error(`Don't know how to emit ${node.type} as a top level node`); } stream.write(`${content}\n\n`); } // Preprocessing _preprocessNode(node:Types.Node, name:Types.SymbolName):boolean { if (node.type === 'alias' && node.target.type === 'reference') { const referencedNode = this.types[node.target.target]; if (this._isPrimitive(referencedNode) || referencedNode.type === 'enum') { this.renames[name] = node.target.target; return true; } } else if (node.type === 'alias' && this._hasDocTag(node, 'ID')) { this.renames[name] = 'ID'; return true; } return false; } // Nodes _emitAlias(node:Types.AliasNode, name:Types.SymbolName):string { if (this._isPrimitive(node.target)) { return `scalar ${this._name(name)}`; } else if (node.target.type === 'reference') { return `union ${this._name(name)} = ${this._name(node.target.target)}`; } else if (node.target.type === 'union') { return this._emitUnion(node.target, name); } else { throw new Error(`Can't serialize ${JSON.stringify(node.target)} as an alias`); } } _emitUnion(node:Types.UnionNode, name:Types.SymbolName):string { if (_.every(node.types, entry => entry.type === 'string literal')) { const nodeValues = node.types.map((type:Types.StringLiteralNode) => type.value); return this._emitEnum({ type: 'enum', values: _.uniq(nodeValues), }, this._name(name)); } node.types.map(type => { if (type.type !== 'reference') { throw new Error(`GraphQL unions require that all types are references. Got a ${type.type}`); } }); const firstChild = node.types[0] as ReferenceNode; const firstChildType = this.types[firstChild.target]; if (firstChildType.type === 'enum') { const nodeTypes = node.types.map((type:ReferenceNode) => { const subNode = this.types[type.target]; if (subNode.type !== 'enum') { throw new Error(`ts2gql expected a union of only enums since first child is an enum. Got a ${type.type}`); } return subNode.values; }); return this._emitEnum({ type: 'enum', values: _.uniq(_.flatten(nodeTypes)), }, this._name(name)); } else if (firstChildType.type === 'interface') { const nodeNames = node.types.map((type:ReferenceNode) => { const subNode = this.types[type.target]; if (subNode.type !== 'interface') { throw new Error(`ts2gql expected a union of only interfaces since first child is an interface. ` + `Got a ${type.type}`); } return type.target; }); return `union ${this._name(name)} = ${nodeNames.join(' | ')}`; } else { throw new Error(`ts2gql currently does not support unions for type: ${firstChildType.type}`); } } _emitInterface(node:Types.InterfaceNode, name:Types.SymbolName):string { // GraphQL expects denormalized type interfaces const members = <Types.Node[]>_(this._transitiveInterfaces(node)) .map(i => i.members) .flatten() .uniqBy('name') .sortBy('name') .value(); // GraphQL can't handle empty types or interfaces, but we also don't want // to remove all references (complicated). if (!members.length) { members.push({ type: 'property', name: '_placeholder', signature: {type: 'boolean'}, }); } const properties = _.map(members, (member) => { if (member.type === 'method') { let parameters = ''; if (_.size(member.parameters) > 1) { throw new Error(`Methods can have a maximum of 1 argument`); } else if (_.size(member.parameters) === 1) { let argType = _.values(member.parameters)[0] as Types.Node; if (argType.type === 'reference') { argType = this.types[argType.target]; } parameters = `(${this._emitExpression(argType)})`; } const nonNullable = this._hasDocTag(member, 'non-nullable'); const returnType = this._emitExpression(member.returns, nonNullable); const directives = this._buildDirectives(member); return `${this._name(member.name)}${parameters}: ${returnType}${directives}`; } else if (member.type === 'property') { const directives = this._buildDirectives(member); const nonNullable = this._hasDocTag(member, 'non-nullable'); return `${this._name(member.name)}: ${this._emitExpression(member.signature, nonNullable)}${directives}`; } else { throw new Error(`Can't serialize ${member.type} as a property of an interface`); } }); if (this._getDocTag(node, 'schema')) { return `schema {\n${this._indent(properties)}\n}`; } else if (this._getDocTag(node, 'input')) { return `input ${this._name(name)} {\n${this._indent(properties)}\n}`; } if (node.concrete) { const directives = this._buildDirectives(node); const extendKeyword = this._hasDocTag(node, 'extend') ? 'extend ' : ''; return `${extendKeyword}type ${this._name(name)}${directives} {\n${this._indent(properties)}\n}`; } let result = `interface ${this._name(name)} {\n${this._indent(properties)}\n}`; const fragmentDeclaration = this._getDocTag(node, 'fragment'); if (fragmentDeclaration) { result = `${result}\n\n${fragmentDeclaration} {\n${this._indent(members.map((m:any) => m.name))}\n}`; } return result; } _emitEnum(node:Types.EnumNode, name:Types.SymbolName):string { return `enum ${this._name(name)} {\n${this._indent(node.values)}\n}`; } _emitExpression = (node:Types.Node, nonNullable?:boolean):string => { const suffix = nonNullable ? '!' : ''; if (!node) { return ''; } else if (node.type === 'string') { return `String${suffix}`; // TODO: ID annotation } else if (node.type === 'number') { return `Float${suffix}`; // TODO: Int/Float annotation } else if (node.type === 'boolean') { return `Boolean${suffix}`; } else if (node.type === 'reference') { return `${this._name(node.target)}${suffix}`; } else if (node.type === 'array') { return `[${node.elements.map(e => this._emitExpression(e, nonNullable)).join(' | ')}]${suffix}`; } else if (node.type === 'literal object' || node.type === 'interface') { return _(this._collectMembers(node)) .map((member:Types.PropertyNode) => { const nonNullable = this._hasDocTag(member, 'non-nullable'); return `${this._name(member.name)}: ${this._emitExpression(member.signature, nonNullable)}`; }) .join(', ') + suffix; } else { throw new Error(`Can't serialize ${node.type} as an expression`); } } _collectMembers = (node:Types.InterfaceNode|Types.LiteralObjectNode):Types.PropertyNode[] => { let members:Types.Node[] = []; if (node.type === 'literal object') { members = node.members; } else { const seenProps = new Set<Types.SymbolName>(); let interfaceNode:Types.InterfaceNode|null; interfaceNode = node; // loop through this interface and any super-interfaces while (interfaceNode) { for (const member of interfaceNode.members) { if (seenProps.has(member.name)) continue; seenProps.add(member.name); members.push(member); } if (interfaceNode.inherits.length > 1) { throw new Error(`No support for multiple inheritence: ${JSON.stringify(interfaceNode.inherits)}`); } else if (interfaceNode.inherits.length === 1) { const supertype:Types.Node = this.types[interfaceNode.inherits[0]]; if (supertype.type !== 'interface') { throw new Error(`Expected supertype to be an interface node: ${supertype}`); } interfaceNode = supertype; } else { interfaceNode = null; } } } for (const member of members) { if (member.type !== 'property') { throw new Error(`Expected members to be properties; got ${member.type}`); } } return members as Types.PropertyNode[]; } // Utility _name = (name:Types.SymbolName):string => { name = this.renames[name] || name; return name.replace(/\W/g, '_'); } _isPrimitive(node:Types.Node):boolean { return node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'any'; } _indent(content:string|string[]):string { if (!_.isArray(content)) content = content.split('\n'); return content.map(s => ` ${s}`).join('\n'); } _transitiveInterfaces(node:Types.InterfaceNode):Types.InterfaceNode[] { let interfaces = [node]; for (const name of node.inherits) { const inherited = <Types.InterfaceNode>this.types[name]; interfaces = interfaces.concat(this._transitiveInterfaces(inherited)); } return _.uniq(interfaces); } _hasDocTag(node:Types.ComplexNode, prefix:string):boolean { return !!this._getDocTag(node, prefix); } _getDocTag(node:Types.ComplexNode, prefix:string):string|null { if (!node.documentation) return null; for (const tag of node.documentation.tags) { if (tag.title !== 'graphql') continue; if (tag.description.startsWith(prefix)) return tag.description; } return null; } // Returns ALL matching tags from the given node. _getDocTags(node:Types.ComplexNode, prefix:string):string[] { const matchingTags:string[] = []; if (!node.documentation) return matchingTags; for (const tag of node.documentation.tags) { if (tag.title !== 'graphql') continue; if (tag.description.startsWith(prefix)) matchingTags.push(tag.description); } return matchingTags; } _buildDirectives(node:Types.ComplexNode) { // @key (on types) - federation let directives = this._getDocTags(node, 'key') .map(tag => ` @key(fields: "${tag.substring(4)}")`) .join(''); // @cost (on types or fields) const costExists = this._getDocTag(node, 'cost'); if (costExists) { directives = `${directives} @cost${costExists.substring(5)}`; } // @external (on fields) - federation if (this._hasDocTag(node, 'external')) { directives = `${directives} @external`; } // @requires (on fields) - federation const requires = this._getDocTag(node, 'requires'); if (requires) { directives = `${directives} @${requires}`; } return directives; } }
the_stack
import { Indexer } from '@salesforce/lightning-lsp-common'; import { parse } from 'jest-editor-support'; import * as vscode from 'vscode'; import { LwcJestTestResults, RawTestResult, TestCaseInfo, TestFileInfo, TestInfoKind, TestResultStatus, TestType } from '../types'; import { LWC_TEST_GLOB_PATTERN } from '../types/constants'; import { extractPositionFromFailureMessage, IExtendedParseResults, ItBlockWithAncestorTitles, populateAncestorTitles, sanitizeFailureMessage } from './jestUtils'; class LwcTestIndexer implements Indexer, vscode.Disposable { private disposables: vscode.Disposable[] = []; private hasIndexedTestFiles = false; private testFileInfoMap = new Map<string, TestFileInfo>(); private diagnosticCollection = vscode.languages.createDiagnosticCollection( 'lwcTestErrors' ); private onDidUpdateTestResultsIndexEventEmitter = new vscode.EventEmitter< undefined >(); private onDidUpdateTestIndexEventEmitter = new vscode.EventEmitter< undefined >(); public onDidUpdateTestResultsIndex = this .onDidUpdateTestResultsIndexEventEmitter.event; public onDidUpdateTestIndex = this.onDidUpdateTestIndexEventEmitter.event; /** * Register Test Indexer with extension context * @param context extension context */ public register(context: vscode.ExtensionContext) { context.subscriptions.push(this); // It's actually a synchronous function to start file watcher. // Finding test files will only happen when going into test explorer // Parsing test files will happen when expanding on the test group nodes, // or open a test file, or on watched files change this.configureAndIndex().catch(error => console.error(error)); } public dispose() { while (this.disposables.length) { const disposable = this.disposables.pop(); if (disposable) { disposable.dispose(); } } } /** * Set up file system watcher for test files change/create/delete. */ public async configureAndIndex() { const lwcTestWatcher = vscode.workspace.createFileSystemWatcher( LWC_TEST_GLOB_PATTERN ); lwcTestWatcher.onDidCreate( async testUri => { await this.indexTestCases(testUri); this.onDidUpdateTestIndexEventEmitter.fire(undefined); }, this, this.disposables ); lwcTestWatcher.onDidChange( async testUri => { await this.indexTestCases(testUri); this.onDidUpdateTestIndexEventEmitter.fire(undefined); }, this, this.disposables ); lwcTestWatcher.onDidDelete( testUri => { const { fsPath } = testUri; this.resetTestFileIndex(fsPath); this.onDidUpdateTestIndexEventEmitter.fire(undefined); }, this, this.disposables ); } /** * Reset test indexer */ public resetIndex() { this.hasIndexedTestFiles = false; this.testFileInfoMap.clear(); this.diagnosticCollection.clear(); this.onDidUpdateTestIndexEventEmitter.fire(undefined); } /** * Find test files in the workspace if needed. * It lazily index all test files until opening test explorer */ public async findAllTestFileInfo(): Promise<TestFileInfo[]> { if (this.hasIndexedTestFiles) { return [...this.testFileInfoMap.values()]; } return await this.indexAllTestFiles(); } public async indexTestCases(testUri: vscode.Uri) { // parse const { fsPath: testFsPath } = testUri; let testFileInfo = this.testFileInfoMap.get(testFsPath); if (!testFileInfo) { testFileInfo = this.indexTestFile(testFsPath); } return this.parseTestFileAndMergeTestResults(testFileInfo); } /** * Parse and create test case information if needed. * It lazily parses test information, until expanding the test file or providing code lens * @param testUri uri of test file */ public async findTestInfoFromLwcJestTestFile( testUri: vscode.Uri ): Promise<TestCaseInfo[]> { // parse const { fsPath: testFsPath } = testUri; let testFileInfo = this.testFileInfoMap.get(testFsPath); if (!testFileInfo) { testFileInfo = this.indexTestFile(testFsPath); } if (testFileInfo.testCasesInfo) { return testFileInfo.testCasesInfo; } return this.parseTestFileAndMergeTestResults(testFileInfo); } private parseTestFileAndMergeTestResults( testFileInfo: TestFileInfo ): TestCaseInfo[] { try { const { testUri } = testFileInfo; const { fsPath: testFsPath } = testUri; const parseResults = parse(testFsPath) as IExtendedParseResults; populateAncestorTitles(parseResults); const itBlocks = (parseResults.itBlocksWithAncestorTitles || parseResults.itBlocks) as ItBlockWithAncestorTitles[]; const testCasesInfo: TestCaseInfo[] = itBlocks.map(itBlock => { const { name, nameRange, ancestorTitles } = itBlock; const testName = name; const testRange = new vscode.Range( new vscode.Position( nameRange.start.line - 1, nameRange.start.column - 1 ), new vscode.Position(nameRange.end.line - 1, nameRange.end.column) ); const testLocation = new vscode.Location(testUri, testRange); const testCaseInfo: TestCaseInfo = { kind: TestInfoKind.TEST_CASE, testType: TestType.LWC, testName, testUri, testLocation, ancestorTitles }; return testCaseInfo; }); if (testFileInfo.rawTestResults) { this.mergeTestResults(testCasesInfo, testFileInfo.rawTestResults); } testFileInfo.testCasesInfo = testCasesInfo; return testCasesInfo; } catch (error) { console.error(error); testFileInfo.testCasesInfo = []; return []; } } /** * Find all LWC test files in the workspace by glob pattern. * This does not start parsing the test files. */ private async indexAllTestFiles(): Promise<TestFileInfo[]> { // TODO, infer package directory from sfdx project json const lwcJestTestFiles = await vscode.workspace.findFiles( LWC_TEST_GLOB_PATTERN, '**/node_modules/**' ); const allTestFileInfo = lwcJestTestFiles.map(lwcJestTestFile => { const { fsPath } = lwcJestTestFile; let testFileInfo = this.testFileInfoMap.get(fsPath); if (!testFileInfo) { testFileInfo = this.indexTestFile(fsPath); } return testFileInfo; }); this.hasIndexedTestFiles = true; return allTestFileInfo; } private indexTestFile(testFsPath: string): TestFileInfo { const testUri = vscode.Uri.file(testFsPath); const testLocation = new vscode.Location( testUri, new vscode.Position(0, 0) ); const testFileInfo: TestFileInfo = { kind: TestInfoKind.TEST_FILE, testType: TestType.LWC, testUri, testLocation }; this.testFileInfoMap.set(testFsPath, testFileInfo); return testFileInfo; } private resetTestFileIndex(testFsPath: string) { this.testFileInfoMap.delete(testFsPath); } private mergeTestResults( testCasesInfo: TestCaseInfo[], rawTestResults: RawTestResult[] ) { const rawTestResultsByTitle = new Map<string, RawTestResult[]>(); rawTestResults.forEach(rawTestResult => { const { title } = rawTestResult; rawTestResultsByTitle.set(title, [ ...(rawTestResultsByTitle.get(title) || []), rawTestResult ]); }); testCasesInfo.forEach(testCaseInfo => { const { testName, ancestorTitles: testCaseAncestorTitles } = testCaseInfo; const rawTestResultsOfTestName = rawTestResultsByTitle.get(testName); if (rawTestResultsOfTestName) { const matchedRawTestResults = rawTestResultsOfTestName.filter( rawTestResultOfTestName => { const { title, ancestorTitles } = rawTestResultOfTestName; // match ancestor titles if possible const isMatched = testCaseAncestorTitles ? testName === title && JSON.stringify(testCaseAncestorTitles) === JSON.stringify(ancestorTitles) : testName === title; return isMatched; } ); if (matchedRawTestResults && matchedRawTestResults.length > 0) { testCaseInfo.testResult = { status: matchedRawTestResults[0].status }; } } }); } /** * Update and merge Jest test results with test locations. * Upon finishing update, it emits an event to update the test explorer. * @param testResults test result JSON object provided by test result watcher */ public updateTestResults(testResults: LwcJestTestResults) { testResults.testResults.forEach(testResult => { const { name, status: testFileStatus, assertionResults } = testResult; const testFsPath = vscode.Uri.file(name).fsPath; let testFileInfo = this.testFileInfoMap.get(testFsPath); if (!testFileInfo) { // If testFileInfo not found index it by fsPath. // it should be handled by file watcher on creating file, but just in case. testFileInfo = this.indexTestFile(testFsPath); } let testFileResultStatus: TestResultStatus = TestResultStatus.UNKNOWN; if (testFileStatus === 'passed') { testFileResultStatus = TestResultStatus.PASSED; } else if (testFileStatus === 'failed') { testFileResultStatus = TestResultStatus.FAILED; } testFileInfo.testResult = { status: testFileResultStatus }; const testUri = vscode.Uri.file(testFsPath); const diagnostics = assertionResults.reduce( (diagnosticsResult: vscode.Diagnostic[], assertionResult) => { const { failureMessages, location } = assertionResult; if (failureMessages && failureMessages.length > 0) { const failureMessage = sanitizeFailureMessage(failureMessages[0]); const failurePosition = extractPositionFromFailureMessage(testFsPath, failureMessage) || new vscode.Position(location.line - 1, location.column - 1); const diagnostic = new vscode.Diagnostic( new vscode.Range(failurePosition, failurePosition), failureMessage ); diagnosticsResult.push(diagnostic); } return diagnosticsResult; }, [] ); this.diagnosticCollection.set(testUri, diagnostics); // Generate test results const rawTestResults: RawTestResult[] = assertionResults.map( assertionResult => { const { title, status, ancestorTitles } = assertionResult; let testResultStatus: TestResultStatus; if (status === 'passed') { testResultStatus = TestResultStatus.PASSED; } else if (status === 'failed') { testResultStatus = TestResultStatus.FAILED; } else { testResultStatus = TestResultStatus.SKIPPED; } const testCaseInfo: RawTestResult = { title, status: testResultStatus, ancestorTitles }; return testCaseInfo; } ); // Set raw test results testFileInfo.rawTestResults = rawTestResults; const testCasesInfo = testFileInfo.testCasesInfo; if (testCasesInfo) { // Merge if test case info is available, // If it's not available at the moment, merging will happen on parsing the test file this.mergeTestResults(testCasesInfo, rawTestResults); } }); // Update Test Explorer View this.onDidUpdateTestResultsIndexEventEmitter.fire(undefined); } } export const lwcTestIndexer = new LwcTestIndexer();
the_stack
import { useState, useRef, useEffect, useCallback } from "react"; import { PHASE } from "../../../common"; import useTitleBar from "../../hooks/useTitleBar"; import { helpers, toWorker, useLocal } from "../../util"; import AssetList from "./AssetList"; import Buttons from "./Buttons"; import type { TradeClearType } from "./Buttons"; import Summary from "./Summary"; import type { TradeTeams, View } from "../../../common/types"; import classNames from "classnames"; export type HandleToggle = ( userOrOther: "other" | "user", playerOrPick: "pick" | "player", includeOrExclude: "include" | "exclude", id: number, ) => Promise<void>; const Trade = (props: View<"trade">) => { const [state, setState] = useState({ accepted: false, asking: false, forceTrade: false, message: null as string | null, prevTeams: undefined as TradeTeams | undefined, }); const handleChangeAsset: HandleToggle = async ( userOrOther: "other" | "user", playerOrPick: "pick" | "player", includeOrExclude: "include" | "exclude", id: number, ) => { setState(prevState => ({ ...prevState, message: null, prevTeams: undefined, })); const ids = { "user-pids": props.userPids, "user-pids-excluded": props.userPidsExcluded, "user-dpids": props.userDpids, "user-dpids-excluded": props.userDpidsExcluded, "other-pids": props.otherPids, "other-pids-excluded": props.otherPidsExcluded, "other-dpids": props.otherDpids, "other-dpids-excluded": props.otherDpidsExcluded, }; const idType = playerOrPick === "player" ? "pids" : "dpids"; const excluded = includeOrExclude === "exclude" ? "-excluded" : ""; const key = `${userOrOther}-${idType}${excluded}` as keyof typeof ids; if (ids[key].includes(id)) { ids[key] = ids[key].filter(currId => currId !== id); } else { ids[key].push(id); } const teams = [ { tid: props.userTid, pids: ids["user-pids"], pidsExcluded: ids["user-pids-excluded"], dpids: ids["user-dpids"], dpidsExcluded: ids["user-dpids-excluded"], }, { tid: props.otherTid, pids: ids["other-pids"], pidsExcluded: ids["other-pids-excluded"], dpids: ids["other-dpids"], dpidsExcluded: ids["other-dpids-excluded"], }, ] as TradeTeams; await toWorker("main", "updateTrade", teams); }; const handleBulk = async ( type: "check" | "clear", userOrOther: "other" | "user", playerOrPick: "pick" | "player", draftRoundOnly?: number, ) => { const ids = { "user-pids": props.userPids, "user-pids-excluded": props.userPidsExcluded, "user-dpids": props.userDpids, "user-dpids-excluded": props.userDpidsExcluded, "other-pids": props.otherPids, "other-pids-excluded": props.otherPidsExcluded, "other-dpids": props.otherDpids, "other-dpids-excluded": props.otherDpidsExcluded, }; const idType = playerOrPick === "player" ? "pids" : "dpids"; const key = `${userOrOther}-${idType}-excluded` as keyof typeof ids; if (type === "clear") { ids[key] = []; } else if (playerOrPick === "player") { const players = userOrOther === "other" ? otherRoster : userRoster; ids[key] = players.map(p => p.pid); } else { let picks = userOrOther === "other" ? otherPicks : userPicks; if (draftRoundOnly !== undefined) { picks = picks.filter(dp => dp.round === draftRoundOnly); } ids[key] = Array.from( new Set([...ids[key], ...picks.map(dp => dp.dpid)]), ); } const teams: TradeTeams = [ { tid: props.userTid, pids: ids["user-pids"], pidsExcluded: ids["user-pids-excluded"], dpids: ids["user-dpids"], dpidsExcluded: ids["user-dpids-excluded"], }, { tid: props.otherTid, pids: ids["other-pids"], pidsExcluded: ids["other-pids-excluded"], dpids: ids["other-dpids"], dpidsExcluded: ids["other-dpids-excluded"], }, ]; await toWorker("main", "updateTrade", teams); }; const handleChangeTeam = async (tid: number) => { setState(prevState => ({ ...prevState, message: null, prevTeams: undefined, })); const teams: TradeTeams = [ { tid: props.userTid, pids: props.userPids, pidsExcluded: props.userPidsExcluded, dpids: props.userDpids, dpidsExcluded: props.userDpidsExcluded, }, { tid, pids: [], pidsExcluded: [], dpids: [], dpidsExcluded: [], }, ]; await toWorker("main", "createTrade", teams); }; const handleClickAsk = async () => { let newPrevTeams = [ { tid: props.userTid, pids: props.userPids, pidsExcluded: props.userPidsExcluded, dpids: props.userDpids, dpidsExcluded: props.userDpidsExcluded, }, { tid: props.otherTid, pids: props.otherPids, pidsExcluded: props.otherPidsExcluded, dpids: props.otherDpids, dpidsExcluded: props.otherDpidsExcluded, }, ] as TradeTeams | undefined; setState(prevState => ({ ...prevState, asking: true, message: null, prevTeams: undefined, })); const { changed, message } = await toWorker( "main", "tradeCounterOffer", undefined, ); if (!changed) { newPrevTeams = undefined; } setState(prevState => ({ ...prevState, asking: false, message, prevTeams: newPrevTeams, })); }; const handleClickClear = async (type: TradeClearType) => { setState(prevState => ({ ...prevState, message: null, prevTeams: undefined, })); await toWorker("main", "clearTrade", type); }; const handleClickForceTrade = () => { setState(prevState => ({ ...prevState, forceTrade: !prevState.forceTrade, })); }; const handleClickPropose = async () => { const [accepted, message] = await toWorker( "main", "proposeTrade", state.forceTrade, ); setState(prevState => ({ ...prevState, accepted, message, prevTeams: undefined, })); }; const { challengeNoRatings, challengeNoTrades, gameOver, otherTeamsWantToHire, godMode, lost, multiTeamMode, numDraftRounds, spectator, otherPicks, otherRoster, otherTid, otl, phase, salaryCap, salaryCapType, summary, showResigningMsg, stats, strategy, teams, tied, userPicks, userRoster, userTeamName, won, } = props; useTitleBar({ title: "Trade", }); const summaryText = useRef<HTMLDivElement>(null); const summaryControls = useRef<HTMLDivElement>(null); const userTids = useLocal(state => state.userTids); const updateSummaryHeight = useCallback(() => { if (summaryControls.current && summaryText.current) { // Keep in sync with .trade-affix if (window.matchMedia("(min-width:768px)").matches) { // 60 for top navbar, 24 for spacing between asset list and trade controls let newHeight = window.innerHeight - 60 - 24 - summaryControls.current.clientHeight; // Multi team menu if (userTids.length > 1) { newHeight -= 40; } summaryText.current.style.maxHeight = `${newHeight}px`; } else if (summaryText.current.style.maxHeight !== "") { summaryText.current.style.removeProperty("height"); } } }, [userTids]); // Run every render, in case it changes useEffect(() => { updateSummaryHeight(); }); useEffect(() => { window.addEventListener("optimizedResize", updateSummaryHeight); return () => { window.removeEventListener("optimizedResize", updateSummaryHeight); }; }, [updateSummaryHeight]); const noTradingAllowed = (phase >= PHASE.AFTER_TRADE_DEADLINE && phase <= PHASE.PLAYOFFS) || phase === PHASE.FANTASY_DRAFT || phase === PHASE.EXPANSION_DRAFT || gameOver || otherTeamsWantToHire || spectator || challengeNoTrades; const numAssets = summary.teams[0].picks.length + summary.teams[0].trade.length + summary.teams[1].picks.length + summary.teams[1].trade.length; const otherTeamIndex = teams.findIndex(t => t.tid === otherTid); const otherTeam = teams[otherTeamIndex]; const otherTeamName = otherTeam ? `${otherTeam.region} ${otherTeam.name}` : "Other team"; const teamNames = [otherTeamName, userTeamName] as [string, string]; return ( <> <div className="row"> <div className="col-md-9"> {showResigningMsg ? ( <p> You can't trade players whose contracts expired this season, but their old contracts still count against team salary caps until they are either re-signed or become free agents. </p> ) : null} <p> If a player has been signed within the past 14 days, he is not allowed to be traded. </p> <div className="d-flex mb-2"> <div className="btn-group"> <button className="btn btn-light-bordered btn-xs" disabled={otherTeamIndex <= 0} onClick={() => { handleChangeTeam(teams[otherTeamIndex - 1].tid); }} title="Previous" > <span className="glyphicon glyphicon-menu-left" /> </button> <button className="btn btn-light-bordered btn-xs" disabled={otherTeamIndex >= teams.length - 1} onClick={() => { handleChangeTeam(teams[otherTeamIndex + 1].tid); }} title="Next" > <span className="glyphicon glyphicon-menu-right" /> </button> </div> <select className="float-start form-select select-team mx-2" value={otherTid} onChange={event => { handleChangeTeam(parseInt(event.currentTarget.value)); }} > {teams.map(t => ( <option key={t.tid} value={t.tid}> {t.region} {t.name} </option> ))} </select> <div style={{ paddingTop: 7, }} > {won}-{lost} {otl > 0 ? <>-{otl}</> : null} {tied > 0 ? <>-{tied}</> : null}, {strategy} </div> </div> <AssetList challengeNoRatings={challengeNoRatings} handleBulk={handleBulk} handleToggle={handleChangeAsset} numDraftRounds={numDraftRounds} picks={otherPicks} roster={otherRoster} stats={stats} userOrOther="other" /> <h2 className="mt-3">{userTeamName}</h2> <AssetList challengeNoRatings={challengeNoRatings} handleBulk={handleBulk} handleToggle={handleChangeAsset} numDraftRounds={numDraftRounds} picks={userPicks} roster={userRoster} stats={stats} userOrOther="user" /> </div> <div className="col-md-3"> <div className="trade-affix"> <Summary challengeNoRatings={challengeNoRatings} handleToggle={handleChangeAsset} ref={summaryText} salaryCap={salaryCap} salaryCapType={salaryCapType} summary={summary} /> <div ref={summaryControls}> {summary.warning ? ( <div className="alert alert-danger mb-0"> <strong>Warning!</strong> {summary.warning} </div> ) : null} {state.message ? ( <div className={classNames( "alert mb-0", state.accepted ? "alert-success" : "alert-info", { "mt-2": summary.warning, }, )} > {state.message} {state.prevTeams ? ( <div className="mt-1 text-end"> <button className="btn btn-secondary btn-sm" onClick={async () => { if (state.prevTeams) { await toWorker( "main", "updateTrade", state.prevTeams, ); setState(prevState => ({ ...prevState, message: null, prevTeams: undefined, })); } }} > Undo </button> </div> ) : null} </div> ) : null} <div className={classNames({ "trade-extra-margin-bottom": multiTeamMode, "mt-3": summary.warning || state.message, })} > {!noTradingAllowed ? ( <div className="text-center"> <Buttons asking={state.asking} enablePropose={summary.enablePropose} forceTrade={state.forceTrade} godMode={godMode} handleClickAsk={handleClickAsk} handleClickClear={handleClickClear} handleClickForceTrade={handleClickForceTrade} handleClickPropose={handleClickPropose} numAssets={numAssets} teamNames={teamNames} /> </div> ) : challengeNoTrades ? ( <p className="alert alert-danger"> <b>Challenge Mode:</b> You're not allowed to make trades. </p> ) : spectator ? ( <p className="alert alert-danger"> You're not allowed to make trades in spectator mode. </p> ) : otherTeamsWantToHire ? ( <p className="alert alert-danger"> You're not allowed to make trades while you have{" "} <a href={helpers.leagueUrl(["new_team"])}> open job offers from other teams </a> . </p> ) : ( <p className="alert alert-danger"> You're not allowed to make trades{" "} {phase === PHASE.AFTER_TRADE_DEADLINE ? "after the trade deadline" : "now"} . </p> )} </div> </div> </div> </div> </div> </> ); }; export default Trade;
the_stack
import { Logger } from "../../components/common_components/logger"; import { IApiJobCreateResult, IApiEngineInitParameters, ICsvChunk } from "./helper_interfaces"; import { ApiInfo, IApiEngine } from "."; import { Common } from "../../components/common_components/common"; import { CsvChunks, ScriptObject } from ".."; import { IOrgConnectionData, IFieldMapping, IFieldMappingResult } from "../common_models/helper_interfaces"; import { BINARY_DATA_CACHES, OPERATION } from "../../components/common_components/enumerations"; import { CONSTANTS } from "../../components/common_components/statics"; import * as fs from 'fs'; import * as path from 'path'; /** * Base class for all ApiProcess inherited classes * * @export * @class ApiProcessBase */ export default class ApiEngineBase implements IApiEngine, IFieldMapping { concurrencyMode: string; pollingIntervalMs: number bulkApiV1BatchSize: number; allOrNone: boolean; operation: OPERATION; updateRecordId: boolean; sObjectName: string; oldSObjectName: string; targetCSVFullFilename: string; createTargetCSVFiles: boolean; logger: Logger; simulationMode: boolean; connectionData: IOrgConnectionData; apiJobCreateResult: IApiJobCreateResult; numberJobRecordProcessed: number = 0; numberJobRecordsFailed: number = 0; numberJobTotalRecordsToProcess: number = 0; binaryDataCache: BINARY_DATA_CACHES = BINARY_DATA_CACHES.InMemory; restApiBatchSize: number; binaryCacheDirectory: string; fieldsNotToWriteInTargetCSVFile: Array<string> = new Array<string>(); get instanceUrl() { return this.connectionData.instanceUrl; } get accessToken() { return this.connectionData.accessToken; } get version() { return this.connectionData.apiVersion; } get proxyUrl() { return this.connectionData.proxyUrl; } get strOperation(): string { return ScriptObject.getStrOperation(this.operation); } constructor(init: IApiEngineInitParameters) { this.logger = init.logger; this.connectionData = init.connectionData; this.sObjectName = init.sObjectName; this.operation = init.operation; this.pollingIntervalMs = init.pollingIntervalMs; this.concurrencyMode = init.concurrencyMode; this.updateRecordId = init.updateRecordId; this.bulkApiV1BatchSize = init.bulkApiV1BatchSize; this.restApiBatchSize = init.restApiBatchSize; this.allOrNone = init.allOrNone; this.createTargetCSVFiles = init.createTargetCSVFiles; this.targetCSVFullFilename = init.targetCSVFullFilename; this.simulationMode = init.simulationMode; this.binaryDataCache = init.binaryDataCache; this.binaryCacheDirectory = init.binaryCacheDirectory; this.fieldsNotToWriteInTargetCSVFile = CONSTANTS.FELDS_NOT_TO_OUTPUT_TO_TARGET_CSV.get(this.sObjectName) || new Array<string>(); if (init.targetFieldMapping) { Object.assign(this, init.targetFieldMapping); } } sourceQueryToTarget = (query: string, sourceObjectName: string) => <IFieldMappingResult>{ query, targetSObjectName: sourceObjectName }; sourceRecordsToTarget = (records: any[], sourceObjectName: string) => <IFieldMappingResult>{ records, targetSObjectName: sourceObjectName }; targetRecordsToSource = (records: any[], sourceObjectName: string) => <IFieldMappingResult>{ records, targetSObjectName: sourceObjectName }; transformQuery: (query: string, sourceObjectName: string) => IFieldMappingResult; // ----------------------- Interface IApiProcess ---------------------------------- getEngineName(): string { return "REST API"; } async executeCRUD(allRecords: Array<any>, progressCallback: (progress: ApiInfo) => void): Promise<Array<any>> { // Map source records this.oldSObjectName = this.sObjectName; let mappedRecords = this.sourceRecordsToTarget(allRecords, this.sObjectName); this.sObjectName = mappedRecords.targetSObjectName; allRecords = mappedRecords.records; this.numberJobTotalRecordsToProcess = allRecords.length; // Create CRUD job if (!this.simulationMode) { await this.createCRUDApiJobAsync(allRecords); } else { await this.createCRUDSimulationJobAsync(allRecords); } // Execute CRUD job let resultRecords = await this.processCRUDApiJobAsync(progressCallback); // Map target records this.sObjectName = this.oldSObjectName; resultRecords = this.targetRecordsToSource(resultRecords, this.sObjectName).records; // Return return resultRecords; } async createCRUDApiJobAsync(allRecords: Array<any>): Promise<IApiJobCreateResult> { return null; } async createCRUDSimulationJobAsync(allRecords: Array<any>): Promise<IApiJobCreateResult> { let chunks = new CsvChunks().fromArray(this.getSourceRecordsArray(allRecords)); this.apiJobCreateResult = { chunks, apiInfo: new ApiInfo({ jobState: "Undefined", strOperation: this.strOperation, sObjectName: this.sObjectName, jobId: "SIMULATION", batchId: "SIMULATION" }), allRecords }; return this.apiJobCreateResult; } async processCRUDApiJobAsync(progressCallback: (progress: ApiInfo) => void): Promise<Array<any>> { let allResultRecords = new Array<any>(); for (let index = 0; index < this.apiJobCreateResult.chunks.chunks.length; index++) { const csvCunk = this.apiJobCreateResult.chunks.chunks[index]; let resultRecords = new Array<any>(); if (!this.simulationMode) { resultRecords = await this.processCRUDApiBatchAsync(csvCunk, progressCallback); } else { resultRecords = await this.processCRUDSimulationBatchAsync(csvCunk, progressCallback); } if (!resultRecords) { // ERROR RESULT await this.writeToTargetCSVFileAsync(new Array<any>()); return null; } else { allResultRecords = allResultRecords.concat(resultRecords); } } await this.writeToTargetCSVFileAsync(allResultRecords); return allResultRecords; } async processCRUDApiBatchAsync(csvChunk: ICsvChunk, progressCallback: (progress: ApiInfo) => void): Promise<Array<any>> { return null; } async processCRUDSimulationBatchAsync(csvChunk: ICsvChunk, progressCallback: (progress: ApiInfo) => void): Promise<Array<any>> { // Progress message: operation started --------- if (progressCallback) { progressCallback(new ApiInfo({ jobState: "OperationStarted" })); } // Simulation ----------------------------------- if (this.operation == OPERATION.Insert && this.updateRecordId) { csvChunk.records.forEach(record => { record["Id"] = Common.makeId(18); }); } // Progress message: operation finished --------- if (progressCallback) { progressCallback(new ApiInfo({ jobState: "OperationFinished" })); } // Create result records return this.getResultRecordsArray(csvChunk.records); } getStrOperation(): string { return this.strOperation; } // ----------------------- ---------------- ------------------------------------------- // ----------------------- Protected members ------------------------------------------- /** * Writes target records to csv file during CRUD api operation * * @param {Array<any>} records * @returns {Promise<void>} * @memberof ApiEngineBase */ protected async writeToTargetCSVFileAsync(records: Array<any>): Promise<void> { // Filter records to write to CSV file if (this.fieldsNotToWriteInTargetCSVFile.length > 0) { records.forEach(record => { this.fieldsNotToWriteInTargetCSVFile.forEach(fieldName => { record[fieldName] = !!record[fieldName] ? record[fieldName] = `[${fieldName}]` : record[fieldName]; }); }); } if (this.createTargetCSVFiles) { await Common.writeCsvFileAsync(this.targetCSVFullFilename, records, true); } } protected getSourceRecordsArray(records: Array<any>): Array<any> { if (this.operation == OPERATION.Delete && !this.simulationMode) { return records.map(x => x["Id"]); } else { return records; } } protected getResultRecordsArray(records: Array<any>): Array<any> { if (this.operation == OPERATION.Delete) { return records.map(record => { if (!this.simulationMode) { return { Id: record }; } else { delete record[CONSTANTS.__ID_FIELD_NAME]; return record; } }); } else { return records; } } protected loadBinaryDataFromCache(records: Array<any>): Array<any> { if (records.length == 0) { return records; } // Load from cache if (this.binaryDataCache == BINARY_DATA_CACHES.FileCache || this.binaryDataCache == BINARY_DATA_CACHES.CleanFileCache) { let binaryFields = Object.keys(records[0]).filter(key => (records[0][key] || '').startsWith(CONSTANTS.BINARY_FILE_CACHE_RECORD_PLACEHOLDER_PREFIX)); // Check from cache if (binaryFields.length > 0) { records.forEach(record => { binaryFields.forEach(field => { let binaryId = CONSTANTS.BINARY_FILE_CACHE_RECORD_PLACEHOLDER_ID(record[field]); if (binaryId) { let cacheFilename = path.join(this.binaryCacheDirectory, CONSTANTS.BINARY_FILE_CACHE_TEMPLATE(binaryId)); if (fs.existsSync(cacheFilename)) { let blob = fs.readFileSync(cacheFilename, 'utf-8'); record[field] = blob; } } }); }); } } } }
the_stack