text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
export default { "PI-SceI": { rseq: "ATCTATGTCGGGTGCGGAGAAAGAGGTAATGAAATGG", rcut: 11, fcut: 15 }, "PI-PspI": { rseq: "TGGCAAACAGCTATTATGGGTATTATGGGT", rcut: 13, fcut: 17 }, "I-CeuI": { rseq: "TAACTATAACGGTCCTAAGGTAGCGAA", rcut: 14, fcut: 18 }, "I-SceI": { rseq: "TAGGGATAACAGGGTAAT", rcut: 5, fcut: 9 }, AscI: { rseq: "GGCGCGCC", rcut: 6, fcut: 2 }, AsiSI: { rseq: "GCGATCGC", rcut: 3, fcut: 5 }, FseI: { rseq: "GGCCGGCC", rcut: 2, fcut: 6 }, NotI: { rseq: "GCGGCCGC", rcut: 6, fcut: 2 }, PacI: { rseq: "TTAATTAA", rcut: 3, fcut: 5 }, PmeI: { rseq: "GTTTAAAC", rcut: 4, fcut: 4 }, PspXI: { rseq: "VCTCGAGB", rcut: 6, fcut: 2 }, SbfI: { rseq: "CCTGCAGG", rcut: 2, fcut: 6 }, SfiI: { rseq: "GGCCNNNNNGGCC", rcut: 5, fcut: 8 }, SgrAI: { rseq: "CRCCGGYG", rcut: 6, fcut: 2 }, SrfI: { rseq: "GCCCGGGC", rcut: 4, fcut: 4 }, SwaI: { rseq: "ATTTAAAT", rcut: 4, fcut: 4 }, BaeI: { rseq: "NNNNNNNNNNNNNNNACNNNNGTAYCNNNNNNNNNNNN", rcut: 33, fcut: 38 }, BbvCI: { rseq: "CCTCAGC", rcut: 5, fcut: 2 }, BspQI: { rseq: "GCTCTTCNNNN", rcut: 11, fcut: 8 }, CspCI: { rseq: "NNNNNNNNNNNNNCAANNNNNGTGGNNNNNNNNNNNN", rcut: 35, fcut: 37 }, PpuMI: { rseq: "RGGWCCY", rcut: 5, fcut: 2 }, RsrII: { rseq: "CGGWCCG", rcut: 5, fcut: 2 }, SapI: { rseq: "GCTCTTCNNNN", rcut: 11, fcut: 8 }, SexAI: { rseq: "ACCWGGT", rcut: 6, fcut: 1 }, AatII: { rseq: "GACGTC", rcut: 1, fcut: 5 }, Acc65I: { rseq: "GGTACC", rcut: 5, fcut: 1 }, AccI: { rseq: "GTMKAC", rcut: 4, fcut: 2 }, AclI: { rseq: "AACGTT", rcut: 4, fcut: 2 }, AcuI: { rseq: "CTGAAGNNNNNNNNNNNNNNNN", rcut: 20, fcut: 22 }, AfeI: { rseq: "AGCGCT", rcut: 3, fcut: 3 }, AflII: { rseq: "CTTAAG", rcut: 5, fcut: 1 }, AflIII: { rseq: "ACRYGT", rcut: 5, fcut: 1 }, AgeI: { rseq: "ACCGGT", rcut: 5, fcut: 1 }, AhdI: { rseq: "GACNNNNNGTC", rcut: 5, fcut: 6 }, AleI: { rseq: "CACNNNNGTG", rcut: 5, fcut: 5 }, AlwNI: { rseq: "CAGNNNCTG", rcut: 3, fcut: 6 }, ApaI: { rseq: "GGGCCC", rcut: 1, fcut: 5 }, ApaLI: { rseq: "GTGCAC", rcut: 5, fcut: 1 }, ApoI: { rseq: "RAATTY", rcut: 5, fcut: 1 }, AseI: { rseq: "ATTAAT", rcut: 4, fcut: 2 }, AvaI: { rseq: "CYCGRG", rcut: 5, fcut: 1 }, AvrII: { rseq: "CCTAGG", rcut: 5, fcut: 1 }, BaeGI: { rseq: "GKGCMC", rcut: 1, fcut: 5 }, BamHI: { rseq: "GGATCC", rcut: 5, fcut: 1 }, BanI: { rseq: "GGYRCC", rcut: 5, fcut: 1 }, BanII: { rseq: "GRGCYC", rcut: 1, fcut: 5 }, BbsI: { rseq: "GAAGACNNNNNN", rcut: 12, fcut: 8 }, BcgI: { rseq: "NNNNNNNNNNNNCGANNNNNNTGCNNNNNNNNNNNN", rcut: 34, fcut: 36 }, BciVI: { rseq: "GTATCCNNNNNN", rcut: 11, fcut: 12 }, BclI: { rseq: "TGATCA", rcut: 5, fcut: 1 }, BfuAI: { rseq: "ACCTGCNNNNNNNN", rcut: 14, fcut: 10 }, BglI: { rseq: "GCCNNNNNGGC", rcut: 4, fcut: 7 }, BglII: { rseq: "AGATCT", rcut: 5, fcut: 1 }, BlpI: { rseq: "GCTNAGC", rcut: 5, fcut: 2 }, BmgBI: { rseq: "CACGTC", rcut: 3, fcut: 3 }, BmrI: { rseq: "ACTGGGNNNNN", rcut: 10, fcut: 11 }, BmtI: { rseq: "GCTAGC", rcut: 1, fcut: 5 }, BpmI: { rseq: "CTGGAGNNNNNNNNNNNNNNNN", rcut: 20, fcut: 22 }, Bpu10I: { rseq: "CCTNAGC", rcut: 5, fcut: 2 }, BpuEI: { rseq: "CTTGAGNNNNNNNNNNNNNNNN", rcut: 20, fcut: 22 }, BsaAI: { rseq: "YACGTR", rcut: 3, fcut: 3 }, BsaBI: { rseq: "GATNNNNATC", rcut: 5, fcut: 5 }, BsaHI: { rseq: "GRCGYC", rcut: 4, fcut: 2 }, BsaI: { rseq: "GGTCTCNNNNN", rcut: 11, fcut: 7 }, BsaWI: { rseq: "WCCGGW", rcut: 5, fcut: 1 }, BsaXI: { rseq: "NNNNNNNNNNNNACNNNNNCTCCNNNNNNNNNN", rcut: 30, fcut: 33 }, BseRI: { rseq: "GAGGAGNNNNNNNNNN", rcut: 14, fcut: 16 }, BseYI: { rseq: "CCCAGC", rcut: 5, fcut: 1 }, BsgI: { rseq: "GTGCAGNNNNNNNNNNNNNNNN", rcut: 20, fcut: 22 }, BsiEI: { rseq: "CGRYCG", rcut: 2, fcut: 4 }, BsiHKAI: { rseq: "GWGCWC", rcut: 1, fcut: 5 }, BsiWI: { rseq: "CGTACG", rcut: 5, fcut: 1 }, BsmBI: { rseq: "CGTCTCNNNNN", rcut: 11, fcut: 7 }, BsmI: { rseq: "GAATGCN", rcut: 5, fcut: 7 }, BsoBI: { rseq: "CYCGRG", rcut: 5, fcut: 1 }, Bsp1286I: { rseq: "GDGCHC", rcut: 1, fcut: 5 }, BspDI: { rseq: "ATCGAT", rcut: 4, fcut: 2 }, BspEI: { rseq: "TCCGGA", rcut: 5, fcut: 1 }, BspHI: { rseq: "TCATGA", rcut: 5, fcut: 1 }, BspMI: { rseq: "ACCTGCNNNNNNNN", rcut: 14, fcut: 10 }, BsrBI: { rseq: "CCGCTC", rcut: 3, fcut: 3 }, BsrDI: { rseq: "GCAATGNN", rcut: 6, fcut: 8 }, BsrFI: { rseq: "RCCGGY", rcut: 5, fcut: 1 }, BsrGI: { rseq: "TGTACA", rcut: 5, fcut: 1 }, BssHII: { rseq: "GCGCGC", rcut: 5, fcut: 1 }, BssSI: { rseq: "CACGAG", rcut: 5, fcut: 1 }, BstAPI: { rseq: "GCANNNNNTGC", rcut: 4, fcut: 7 }, BstBI: { rseq: "TTCGAA", rcut: 4, fcut: 2 }, BstEII: { rseq: "GGTNACC", rcut: 6, fcut: 1 }, BstXI: { rseq: "CCANNNNNNTGG", rcut: 4, fcut: 8 }, BstYI: { rseq: "RGATCY", rcut: 5, fcut: 1 }, BstZ17I: { rseq: "GTATAC", rcut: 3, fcut: 3 }, Bsu36I: { rseq: "CCTNAGG", rcut: 5, fcut: 2 }, BtgI: { rseq: "CCRYGG", rcut: 5, fcut: 1 }, BtgZI: { rseq: "GCGATGNNNNNNNNNNNNNN", rcut: 20, fcut: 16 }, BtsI: { rseq: "GCAGTGNN", rcut: 6, fcut: 8 }, ClaI: { rseq: "ATCGAT", rcut: 4, fcut: 2 }, DraI: { rseq: "TTTAAA", rcut: 3, fcut: 3 }, DraIII: { rseq: "CACNNNGTG", rcut: 3, fcut: 6 }, DrdI: { rseq: "GACNNNNNNGTC", rcut: 5, fcut: 7 }, EaeI: { rseq: "YGGCCR", rcut: 5, fcut: 1 }, EagI: { rseq: "CGGCCG", rcut: 5, fcut: 1 }, EarI: { rseq: "CTCTTCNNNN", rcut: 10, fcut: 7 }, EciI: { rseq: "GGCGGANNNNNNNNNNN", rcut: 15, fcut: 17 }, Eco53kI: { rseq: "GAGCTC", rcut: 3, fcut: 3 }, EcoNI: { rseq: "CCTNNNNNAGG", rcut: 6, fcut: 5 }, EcoO109I: { rseq: "RGGNCCY", rcut: 5, fcut: 2 }, EcoRI: { rseq: "GAATTC", rcut: 5, fcut: 1 }, EcoRV: { rseq: "GATATC", rcut: 3, fcut: 3 }, Esp3I: { rseq: "CGTCTCNNNNN", rcut: 11, fcut: 7 }, FspI: { rseq: "TGCGCA", rcut: 3, fcut: 3 }, HaeII: { rseq: "RGCGCY", rcut: 1, fcut: 5 }, HincII: { rseq: "GTYRAC", rcut: 3, fcut: 3 }, HindIII: { rseq: "AAGCTT", rcut: 5, fcut: 1 }, HpaI: { rseq: "GTTAAC", rcut: 3, fcut: 3 }, KasI: { rseq: "GGCGCC", rcut: 5, fcut: 1 }, KpnI: { rseq: "GGTACC", rcut: 1, fcut: 5 }, MfeI: { rseq: "CAATTG", rcut: 5, fcut: 1 }, MluI: { rseq: "ACGCGT", rcut: 5, fcut: 1 }, MmeI: { rseq: "TCCRACNNNNNNNNNNNNNNNNNNNN", rcut: 24, fcut: 26 }, MscI: { rseq: "TGGCCA", rcut: 3, fcut: 3 }, MslI: { rseq: "CAYNNNNRTG", rcut: 5, fcut: 5 }, MspA1I: { rseq: "CMGCKG", rcut: 3, fcut: 3 }, NaeI: { rseq: "GCCGGC", rcut: 3, fcut: 3 }, NarI: { rseq: "GGCGCC", rcut: 4, fcut: 2 }, NcoI: { rseq: "CCATGG", rcut: 5, fcut: 1 }, NdeI: { rseq: "CATATG", rcut: 4, fcut: 2 }, NgoMIV: { rseq: "GCCGGC", rcut: 5, fcut: 1 }, NheI: { rseq: "GCTAGC", rcut: 5, fcut: 1 }, NmeAIII: { rseq: "GCCGAGNNNNNNNNNNNNNNNNNNNN", rcut: 25, fcut: 26 }, NruI: { rseq: "TCGCGA", rcut: 3, fcut: 3 }, NsiI: { rseq: "ATGCAT", rcut: 1, fcut: 5 }, NspI: { rseq: "RCATGY", rcut: 1, fcut: 5 }, PaeR7I: { rseq: "CTCGAG", rcut: 5, fcut: 1 }, PciI: { rseq: "ACATGT", rcut: 5, fcut: 1 }, PflFI: { rseq: "GACNNNGTC", rcut: 5, fcut: 4 }, PflMI: { rseq: "CCANNNNNTGG", rcut: 4, fcut: 7 }, PluTI: { rseq: "GGCGCC", rcut: 1, fcut: 5 }, PmlI: { rseq: "CACGTG", rcut: 3, fcut: 3 }, PshAI: { rseq: "GACNNNNGTC", rcut: 5, fcut: 5 }, PsiI: { rseq: "TTATAA", rcut: 3, fcut: 3 }, PspOMI: { rseq: "GGGCCC", rcut: 5, fcut: 1 }, PstI: { rseq: "CTGCAG", rcut: 1, fcut: 5 }, PvuI: { rseq: "CGATCG", rcut: 2, fcut: 4 }, PvuII: { rseq: "CAGCTG", rcut: 3, fcut: 3 }, SacI: { rseq: "GAGCTC", rcut: 1, fcut: 5 }, SacII: { rseq: "CCGCGG", rcut: 2, fcut: 4 }, SalI: { rseq: "GTCGAC", rcut: 5, fcut: 1 }, ScaI: { rseq: "AGTACT", rcut: 3, fcut: 3 }, SfcI: { rseq: "CTRYAG", rcut: 5, fcut: 1 }, SfoI: { rseq: "GGCGCC", rcut: 3, fcut: 3 }, SmaI: { rseq: "CCCGGG", rcut: 3, fcut: 3 }, SmlI: { rseq: "CTYRAG", rcut: 5, fcut: 1 }, SnaBI: { rseq: "TACGTA", rcut: 3, fcut: 3 }, SpeI: { rseq: "ACTAGT", rcut: 5, fcut: 1 }, SphI: { rseq: "GCATGC", rcut: 1, fcut: 5 }, SspI: { rseq: "AATATT", rcut: 3, fcut: 3 }, StuI: { rseq: "AGGCCT", rcut: 3, fcut: 3 }, StyI: { rseq: "CCWWGG", rcut: 5, fcut: 1 }, TspMI: { rseq: "CCCGGG", rcut: 5, fcut: 1 }, Tth111I: { rseq: "GACNNNGTC", rcut: 5, fcut: 4 }, XbaI: { rseq: "TCTAGA", rcut: 5, fcut: 1 }, XcmI: { rseq: "CCANNNNNNNNNTGG", rcut: 7, fcut: 8 }, XhoI: { rseq: "CTCGAG", rcut: 5, fcut: 1 }, XmaI: { rseq: "CCCGGG", rcut: 5, fcut: 1 }, XmnI: { rseq: "GAANNNNTTC", rcut: 5, fcut: 5 }, ZraI: { rseq: "GACGTC", rcut: 3, fcut: 3 }, AlwI: { rseq: "GGATCNNNNN", rcut: 10, fcut: 9 }, ApeKI: { rseq: "GCWGC", rcut: 4, fcut: 1 }, AvaII: { rseq: "GGWCC", rcut: 4, fcut: 1 }, BbvI: { rseq: "GCAGCNNNNNNNNNNNN", rcut: 17, fcut: 13 }, BccI: { rseq: "CCATCNNNNN", rcut: 10, fcut: 9 }, BceAI: { rseq: "ACGGCNNNNNNNNNNNNNN", rcut: 19, fcut: 17 }, BcoDI: { rseq: "GTCTCNNNNN", rcut: 10, fcut: 6 }, BsmAI: { rseq: "GTCTCNNNNN", rcut: 10, fcut: 6 }, BsmFI: { rseq: "GGGACNNNNNNNNNNNNNN", rcut: 19, fcut: 15 }, BspCNI: { rseq: "CTCAGNNNNNNNNN", rcut: 12, fcut: 14 }, BsrI: { rseq: "ACTGGN", rcut: 4, fcut: 6 }, BstNI: { rseq: "CCWGG", rcut: 3, fcut: 2 }, BtsCI: { rseq: "GGATGNN", rcut: 5, fcut: 7 }, BtsIMutI: { rseq: "CAGTGNN", rcut: 5, fcut: 7 }, DpnI: { rseq: "GmATC", rcut: 3, fcut: 3 }, FauI: { rseq: "CCCGCNNNNNN", rcut: 11, fcut: 9 }, FokI: { rseq: "GGATGNNNNNNNNNNNNN", rcut: 18, fcut: 14 }, HgaI: { rseq: "GACGCNNNNNNNNNN", rcut: 15, fcut: 10 }, HphI: { rseq: "GGTGANNNNNNNN", rcut: 12, fcut: 13 }, Hpy99I: { rseq: "CGWCG", rcut: 0, fcut: 5 }, HpyAV: { rseq: "CCTTCNNNNNN", rcut: 10, fcut: 11 }, LpnPI: { rseq: "CmCDGNNNNNNNNNNNNNN", rcut: 19, fcut: 15 }, MboII: { rseq: "GAAGANNNNNNNN", rcut: 12, fcut: 13 }, MlyI: { rseq: "GAGTCNNNNN", rcut: 10, fcut: 10 }, NciI: { rseq: "CCSGG", rcut: 3, fcut: 2 }, PleI: { rseq: "GAGTCNNNNN", rcut: 10, fcut: 9 }, PspGI: { rseq: "CCWGG", rcut: 5, fcut: 0 }, SfaNI: { rseq: "GCATCNNNNNNNNN", rcut: 14, fcut: 10 }, TfiI: { rseq: "GAWTC", rcut: 4, fcut: 1 }, TseI: { rseq: "GCWGC", rcut: 4, fcut: 1 }, Tsp45I: { rseq: "GTSAC", rcut: 5, fcut: 0 }, TspRI: { rseq: "NNCASTGNN", rcut: 0, fcut: 9 }, AciI: { rseq: "CCGC", rcut: 3, fcut: 1 }, AluI: { rseq: "AGCT", rcut: 2, fcut: 2 }, BfaI: { rseq: "CTAG", rcut: 3, fcut: 1 }, BsaJI: { rseq: "CCNNGG", rcut: 5, fcut: 1 }, BslI: { rseq: "CCNNNNNNNGG", rcut: 4, fcut: 7 }, BstUI: { rseq: "CGCG", rcut: 2, fcut: 2 }, Cac8I: { rseq: "GCNNGC", rcut: 3, fcut: 3 }, CviAII: { rseq: "CATG", rcut: 3, fcut: 1 }, "CviKI-1": { rseq: "RGCY", rcut: 2, fcut: 2 }, CviQI: { rseq: "GTAC", rcut: 3, fcut: 1 }, DdeI: { rseq: "CTNAG", rcut: 4, fcut: 1 }, DpnII: { rseq: "GATC", rcut: 4, fcut: 0 }, FatI: { rseq: "CATG", rcut: 4, fcut: 0 }, Fnu4HI: { rseq: "GCNGC", rcut: 3, fcut: 2 }, HaeIII: { rseq: "GGCC", rcut: 2, fcut: 2 }, HhaI: { rseq: "GCGC", rcut: 1, fcut: 3 }, HinP1I: { rseq: "GCGC", rcut: 3, fcut: 1 }, HinfI: { rseq: "GANTC", rcut: 4, fcut: 1 }, HpaII: { rseq: "CCGG", rcut: 3, fcut: 1 }, Hpy166II: { rseq: "GTNNAC", rcut: 3, fcut: 3 }, Hpy188I: { rseq: "TCNGA", rcut: 2, fcut: 3 }, Hpy188III: { rseq: "TCNNGA", rcut: 4, fcut: 2 }, HpyCH4III: { rseq: "ACNGT", rcut: 2, fcut: 3 }, HpyCH4IV: { seq: "ACGT", rcut: 3, fcut: 1 }, HpyCH4V: { rseq: "TGCA", rcut: 2, fcut: 2 }, MboI: { rseq: "GATC", rcut: 4, fcut: 0 }, MluCI: { rseq: "AATT", rcut: 4, fcut: 0 }, MnlI: { rseq: "CCTCNNNNNNN", rcut: 10, fcut: 11 }, MseI: { rseq: "TTAA", rcut: 3, fcut: 1 }, MspI: { rseq: "CCGG", rcut: 3, fcut: 1 }, MwoI: { rseq: "GCNNNNNNNGC", rcut: 4, fcut: 7 }, NlaIII: { rseq: "CATG", rcut: 0, fcut: 4 }, NlaIV: { rseq: "GGNNCC", rcut: 3, fcut: 3 }, RsaI: { rseq: "GTAC", rcut: 2, fcut: 2 }, Sau3AI: { rseq: "GATC", rcut: 4, fcut: 0 }, Sau96I: { rseq: "GGNCC", rcut: 4, fcut: 1 }, ScrFI: { rseq: "CCNGG", rcut: 3, fcut: 2 }, StyD4I: { rseq: "CCNGG", rcut: 5, fcut: 0 }, TaqI: { rseq: "TCGA", rcut: 3, fcut: 1 }, AbaSI: { rseq: "hmCNNNNNNNNNNN", rcut: 12, fcut: 14 }, FspEI: { rseq: "CmCNNNNNNNNNNNNNNNN", rcut: 19, fcut: 15 }, MspJI: { rseq: "mCNNRNNNNNNNNNNNNN", rcut: 18, fcut: 14 } };
the_stack
import { MetaUtils } from "../metadata/utils"; import * as Utils from "../utils"; import { Decorators } from '../constants/decorators'; import { DecoratorType } from '../enums/decorator-type'; import { IProcessControlParams } from './interfaces/IProcessControlParams'; import { IProcessControlService, processControlServiceName, processControlContext } from './interfaces/IProcessControlService'; import * as Enumerable from 'linq'; import {executeWorkerHandler} from './workerAssociation'; import {Container} from '../../di'; import Q = require('q'); //This function is a private function and not exposed as an attribute //process type=1 process_start //process type=2 processend //process type=3 processstart and end function preProcessHandler(params: IProcessControlParams, target, propertyKey, descriptor, originalMethod, type: string) { return function () { console.log("preProcessHandler", params); var meta = MetaUtils.getMetaData(target, type, propertyKey); var targetObjectId: any; if (params.indexofArgumentForTargetObjectId != undefined) { targetObjectId = arguments[params.indexofArgumentForTargetObjectId]; } if (params.indexofArgumentForTargetObject != undefined) { targetObjectId = arguments[params.indexofArgumentForTargetObject] && arguments[params.indexofArgumentForTargetObject]._id; } var services = MetaUtils.getMetaDataForDecorators([Decorators.SERVICE]); var procService = Enumerable.from(services).where(x => x.metadata[0].params.serviceName == processControlServiceName).select(x => x.metadata[0]).firstOrDefault(); if (!procService) return originalMethod.apply(this, arguments); var processControlService: IProcessControlService = <IProcessControlService>Container.resolve(procService.params.target); var targetServices = MetaUtils.getMetaData(target, Decorators.SERVICE); var serviceName = targetServices[0].params.serviceName; if (processControlService && meta) { if (type == Decorators.PROCESS_START || type == Decorators.PROCESS_START_AND_END) { //preprocess let argsObj = Utils.getMethodArgs(originalMethod, arguments); if (params.executeInDistributedWorker ) { // Parent - processcontrol management executing with worker console.log('process control initializing started'); let workerParams = executeWorkerHandler({}, target, propertyKey, originalMethod, Decorators.WORKER,true).apply(this, arguments); return processControlService.initialize(serviceName, propertyKey, targetObjectId, params, workerParams).then((sucess) => { // var taskInfo = executeWorkerHandler({}, target, propertyKey, originalMethod, Decorators.WORKER).apply(this, arguments); console.log('process control initialized successfully'); return processControlService.sendResponse(sucess); }); } else if (params.executeInWorker && !MetaUtils.childProcessId && Utils.config().Config.isMultiThreaded) { // Parent - processcontrol management executing with worker console.log('process control initializing started'); return processControlService.initialize(serviceName, propertyKey, targetObjectId, params).then((sucess) => { var taskInfo = executeWorkerHandler({}, target, propertyKey, originalMethod, Decorators.WORKER).apply(this, arguments); console.log('process control initialized successfully'); return processControlService.sendResponse(sucess); }); } else { let initialize; if (params.executeInWorker && MetaUtils.childProcessId) { // already initialized in parent process initialize = Q.when(true); console.log('process control already initialized'); } else { console.log('process control initialized started'); initialize = processControlService.initialize(serviceName, propertyKey, targetObjectId, params, argsObj); } return initialize.then(res => { return processControlService.startProcess().then((sucess) => { console.log('process control In progress'); if (sucess) { //actual method of caller //console.log('method execution started', originalMethod.name, argsObj); var result = originalMethod.apply(this, arguments); if (Utils.isPromise(result)) { console.log('method executing...'); return result.then((sucess) => { if (type == Decorators.PROCESS_START_AND_END) { //return statement return processControlService.completeProcess(sucess).then((result) => { console.log('method execution completed'); return sucess; }); } else { return sucess; } }).catch(error => { console.log("throw>>>>>>>>>>>>>>>>>>>"); if (type == Decorators.PROCESS_START_AND_END) { //return statement return processControlService.errorOutProcess(JSON.stringify(error)).then((result) => { console.log('method execution error', error); throw error; }).catch((err) => { console.log('method execution error', error); throw error; }) } else { throw error; } }); } else { if (type == Decorators.PROCESS_START_AND_END) { //return statement console.log('method execution started', originalMethod.name, argsObj); return processControlService.completeProcess(result).then(res => { console.log('method execution completed'); return result; }); } } } else { return Promise.reject("already running process"); } }, (error) => { return Promise.reject("Error while starting process : " + error); }); }); } } if (type == Decorators.PROCESS_END) { var result = originalMethod.apply(this, arguments); if (Utils.isPromise(result)) { return result.then((sucess) => { return processControlService.completeProcess(sucess).then((result) => { return sucess; }); }, (error) => { return processControlService.errorOutProcess(JSON.stringify(error)).then((result) => { throw error; }).catch((err) => { throw error; }); }); } else { processControlService.completeProcess(result); return result; } } return descriptor; } else { return originalMethod.apply(this, arguments); } }; } export function processStart(params: IProcessControlParams): any { params = params || <any>{}; return function (target: Function, propertyKey: string, descriptor: any) { MetaUtils.addMetaData(target, { decorator: Decorators.PROCESS_START, decoratorType: DecoratorType.METHOD, params: params, propertyKey: propertyKey }); var origianlmethod = descriptor.value; descriptor.value = preProcessHandler(params, target, propertyKey, descriptor, origianlmethod, Decorators.PROCESS_START); //descriptor.value = preProcessHandler(params, target, propertyKey, descriptor, rsProcessDecorators.PROCESS_START); } } export function processEnd(params: IProcessControlParams): any { params = params || <any>{}; return function (target: Function, propertyKey: string, descriptor: any) { MetaUtils.addMetaData(target, { decorator: Decorators.PROCESS_END, decoratorType: DecoratorType.METHOD, params: params, propertyKey: propertyKey }); var origianlmethod = descriptor.value; descriptor.value = preProcessHandler(params, target, propertyKey, descriptor, origianlmethod, Decorators.PROCESS_END); //descriptor.value = preProcessHandler(params, target, propertyKey, descriptor, rsProcessDecorators.PROCESS_END); } } export function processStartEnd(params: IProcessControlParams): any { params = params || <any>{}; return function (target: Function, propertyKey: string, descriptor: any) { MetaUtils.addMetaData(target, { decorator: Decorators.PROCESS_START_AND_END, decoratorType: DecoratorType.METHOD, params: params, propertyKey: propertyKey }); var origianlmethod = descriptor.value; descriptor.value = preProcessHandler(params, target, propertyKey, descriptor, origianlmethod, Decorators.PROCESS_START_AND_END); } }
the_stack
// tslint:disable:no-unused-expression max-func-body-length promise-function-async max-line-length insecure-random // tslint:disable:object-literal-key-quotes no-function-expression no-non-null-assertion align no-http-string import * as assert from "assert"; import { Position, Range, Uri } from "vscode"; import { IGotoParameterValueArgs, IParameterValuesSource, IParameterValuesSourceProvider, ParameterDefinitionCodeLens, ParentOrChildCodeLens, ShowCurrentParameterFileCodeLens } from "../extension.bundle"; import { IDeploymentTemplate, IPartialDeploymentTemplate } from "./support/diagnostics"; import { ensureLanguageServerAvailable } from "./support/ensureLanguageServerAvailable"; import { parseParametersWithMarkers, parseTemplate } from "./support/parseTemplate"; import { rangeToString } from "./support/rangeToString"; import { sortBy } from "./support/sortBy"; import { stringify } from "./support/stringify"; import { testWithLanguageServer } from "./support/testWithLanguageServer"; suite("DeploymentTemplate code lenses", () => { class FakeParameterValuesSourceProvider implements IParameterValuesSourceProvider { public constructor( public readonly parameterFileUri: Uri | undefined, private readonly parameterValuesSource: IParameterValuesSource) { } public async getValuesSource(): Promise<IParameterValuesSource> { return this.parameterValuesSource; } } const template1: IDeploymentTemplate = { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "requiredInt": { "type": "int" }, "optionalInt": { "type": "int", "defaultValue": 123 }, "requiredString": { "type": "string" }, "optionalString": { "type": "string", "defaultValue": "abc" }, "optionalString2": { "type": "string", "defaultValue": "[parameters('optionalString')]" }, "requiredSecureString": { "type": "securestring" }, "optionalSecureString": { "type": "securestring", "defaultValue": "abc" }, "requiredBool": { "type": "bool" }, "optionalBool": { "type": "bool", "defaultValue": true }, "requiredArray": { "type": "array" }, "optionalArray": { "type": "array", "defaultValue": [ true ] }, "requiredObject": { "type": "object" }, "optionalObject": { "type": "object", "defaultValue": { "myTrueProp": true } }, "requiredSecureObject": { "type": "secureObject" }, "optionalSecureObject": { "type": "secureObject", "defaultValue": { "value1": true } } }, "functions": [ ], "variables": { }, "resources": [ ], "outputs": { "output1": { "type": "array", "value": [ // Get rid of unused warnings "[add(parameters('optionalInt'),parameters('requiredInt'))]", "[concat(parameters('optionalString'),parameters('optionalString2'),parameters('requiredString'))]", "[concat(parameters('optionalBool'),parameters('requiredBool'))]", "[concat(parameters('optionalArray'),parameters('requiredArray'))]", "[concat(parameters('optionalObject'),parameters('requiredObject'))]", "[concat(parameters('optionalSecureObject'),parameters('requiredSecureObject'))]", "[concat(parameters('optionalSecureString'),parameters('requiredSecureString'))]" ] } } }; suite("parameters section code lens", () => { suite("if no parameter file then", () => { test("expect only a single parameters section code lens", async () => { const dt = parseTemplate(template1); const lenses = dt.getCodeLenses(undefined); assert.equal(lenses.length, 1, "Expecting only a code lens for the parameters section itself"); }); test("code lens should show command to select/create one", async () => { const dt = parseTemplate(template1); const lenses = dt.getCodeLenses(undefined); for (const lens of lenses) { const result = await lens.resolve(); assert(result); } assert.equal(stringify(lenses[0].range), stringify(new Range(new Position(3, 2), new Position(63, 3)))); assert.equal(lenses[0].command?.title, "Select or create a parameter file to enable full validation..."); assert.equal(lenses[0].command?.command, "azurerm-vscode-tools.selectParameterFile"); assert.equal(lenses[0].command?.arguments?.length, 1); assert(lenses[0].command?.arguments![0] instanceof Uri); assert.equal(lenses[0].command?.arguments![0].toString(), dt.documentUri.toString()); }); }); suite("if there is a parameter file then", () => { test("parameter section code lens should show command to open current parameter file and one to change the selection", async () => { const dt = parseTemplate(template1); const { dp } = parseParametersWithMarkers({}); const lenses = dt.getCodeLenses(new FakeParameterValuesSourceProvider(dp.documentUri, dp.topLevelParameterValuesSource)); assert.equal(lenses.length, 2 + dt.topLevelScope.parameterDefinitions.length); for (const lens of lenses) { const result = await lens.resolve(); assert(result); } const openLens = lenses.filter(l => l instanceof ShowCurrentParameterFileCodeLens)[0]; assert.equal(stringify(openLens.range), stringify(new Range(new Position(3, 2), new Position(63, 3)))); assert.equal(openLens.command?.title, `Parameter file: "test parameter file.json" $(error) Not found`); assert.equal(openLens.command?.command, "azurerm-vscode-tools.openParameterFile"); assert.equal(openLens.command?.arguments?.length, 1); assert(openLens.command?.arguments![0] instanceof Uri); assert.equal(openLens.command?.arguments![0].toString(), dt.documentUri.toString()); const selectLens = lenses[1]; assert.equal(stringify(selectLens.range), stringify(new Range(new Position(3, 2), new Position(63, 3)))); assert.equal(selectLens.command?.title, `Change...`); assert.equal(selectLens.command?.command, "azurerm-vscode-tools.selectParameterFile"); assert.equal(selectLens.command?.arguments?.length, 1); assert(selectLens.command?.arguments![0] instanceof Uri); assert.equal(selectLens.command?.arguments![0].toString(), dt.documentUri.toString()); }); }); }); suite("parameter definition code lenses", () => { suite("with top-level parameter definitions and values in a parameter file", async () => { function createParamLensTest(topLevelParamName: string, valueInParamFile: { value?: string; reference?: string } | undefined, expectedTitle: string): void { const testName = valueInParamFile === undefined ? `${topLevelParamName} with no value in param file` : `${topLevelParamName} with value ${JSON.stringify(valueInParamFile).replace(/\r\n|\n/g, ' ')}`; test(testName, async () => { let a = testName; a = a; const dt = parseTemplate(template1); const param = dt.topLevelScope.getParameterDefinition(topLevelParamName); assert(!!param); const { dp } = parseParametersWithMarkers( valueInParamFile === undefined ? { "parameters": {} } : valueInParamFile.value ? `{ "parameters": { "${topLevelParamName}": { "value": ${valueInParamFile.value} } } }` : `{ "parameters": { "${topLevelParamName}": { "reference": ${valueInParamFile.reference} } } }`); const lenses = dt.getCodeLenses(new FakeParameterValuesSourceProvider(dp.documentUri, dp.topLevelParameterValuesSource)) .filter(l => l instanceof ParameterDefinitionCodeLens) .map(l => <ParameterDefinitionCodeLens>l); assert.equal(lenses.length, dt.topLevelScope.parameterDefinitions.length); // Find the code lens for the parameter const lens = lenses.find(l => l.parameterDefinition === param); assert(!!lens, `Couldn't find a code lens for parameter ${param.nameValue.unquotedValue}`); const result = await lens.resolve(); assert.equal(result, true); assert.equal(lens.command?.command, "azurerm-vscode-tools.codeLens.gotoParameterValue"); const expectedArgs: IGotoParameterValueArgs = { inParameterFile: { parameterFileUri: dp.documentUri, parameterName: param.nameValue.unquotedValue } }; assert.deepEqual(lens.command?.arguments, [expectedArgs]); assert.equal(lens.command?.title, expectedTitle); }); } createParamLensTest('requiredInt', { value: '123' }, 'Value: 123'); createParamLensTest('requiredInt', { value: '-123' }, 'Value: -123'); createParamLensTest('optionalInt', undefined, 'Using default value'); createParamLensTest('requiredInt', undefined, '$(warning) No value found - click here to enter a value'); createParamLensTest('requiredString', { value: '"def"' }, 'Value: "def"'); createParamLensTest('optionalString', undefined, 'Using default value'); createParamLensTest('requiredString', undefined, '$(warning) No value found - click here to enter a value'); // Value too long createParamLensTest( 'requiredString', { value: '"I am a very long string, yes, sir, a very long string indeed. If I were a very long string, I would say that I am a very long string, yes, sir, a very long string indeed."' }, 'Value: "I am a very long string, yes, sir, a very long string indeed. If I were a very long string, I would say that I ...'); createParamLensTest('optionalSecureString', { value: '"def"' }, 'Value: "def"'); createParamLensTest('optionalSecureString', undefined, 'Using default value'); createParamLensTest( 'optionalSecureString', { reference: `{ "keyVault": { "id": "/subscriptions/*************/resourceGroups/*******/providers/Microsoft.KeyVault/vaults/****" }, "secretName": "mysecretpassword" }`}, 'Value: (KeyVault reference)'); createParamLensTest('optionalBool', { value: 'true' }, 'Value: true'); createParamLensTest('optionalBool', { value: 'false' }, 'Value: false'); createParamLensTest('optionalBool', undefined, 'Using default value'); createParamLensTest('optionalArray', { value: '[]' }, 'Value: []'); createParamLensTest('optionalArray', { value: '[\n]' }, 'Value: []'); createParamLensTest('optionalArray', { value: '[\r\n]' }, 'Value: []'); createParamLensTest('optionalArray', { value: '[\r\n\t 123\t\r\n ]' }, 'Value: [123]'); createParamLensTest('optionalArray', { value: '[\r\n\t {"a": "b"}\t\r\n ]' }, 'Value: [{"a": "b"}]'); createParamLensTest('optionalArray', undefined, 'Using default value'); createParamLensTest('optionalObject', { value: '{}' }, 'Value: {}'); createParamLensTest('optionalObject', { value: '{\r\n"a": "b",\r\n "i": -123}' }, 'Value: {"a": "b", "i": -123}'); createParamLensTest('optionalObject', undefined, 'Using default value'); createParamLensTest('optionalSecureObject', { value: '{}' }, 'Value: {}'); createParamLensTest('optionalSecureObject', undefined, 'Using default value'); suite("undefined in param value", () => { createParamLensTest('optionalString', { value: 'undefined' }, 'Using default value'); }); suite("Expression in default value", () => { createParamLensTest('optionalString2', { value: '"123"' }, 'Value: "123"'); createParamLensTest('optionalString2', undefined, `Using default value`); }); }); suite("parameters for nested inner-scoped template", () => { function createCodeLensTest(testName: string, template: IPartialDeploymentTemplate, expected: (string | RegExp)[]): void { testWithLanguageServer(testName, async () => { testName = testName; const dt = parseTemplate(template); await ensureLanguageServerAvailable(); let lenses = dt.getCodeLenses(undefined).filter(cl => !(cl instanceof ParentOrChildCodeLens)); for (const lens of lenses) { const result = await lens.resolve(); assert(result); if (lens.command) { lens.command.title = lens.command.title.replace(" - loading schemas...", ""); } } lenses = sortBy(lenses, l => l.range); const actual: string[] = lenses.map(l => { return `${l.scope.scopeKind}: "${l.command?.title}" (${l.command?.command}) at ${rangeToString(l.range)}`; }); assert.deepEqual(actual, expected); }); } createCodeLensTest( "nested inner-scope template with parameter values", { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "resources": [ { "type": "Microsoft.Resources/deployments", "apiVersion": "2019-10-01", "name": "inner1", "properties": { "expressionEvaluationOptions": { "scope": "inner" }, "parameters": { "p2": { "value": "p2 value" }, "p3": { "value": "[add(1, 2)]" } }, "mode": "Incremental", "template": { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "p1": { "type": "string", "defaultValue": "p1 default value" }, "p2": { "type": "string" }, "p3": { "type": "int" }, "p4": { "type": "string" } }, "resources": [ ], "outputs": { "v1": { "type": "string", "value": "[parameters('p1')]" } } } } } ] }, [ "TopLevel: \"Select or create a parameter file to enable full validation...\" (azurerm-vscode-tools.selectParameterFile) at [1,1-1,1]", "NestedDeploymentWithInnerScope: \"Nested template with inner scope\" () at [22,21-47,10]", "NestedDeploymentWithInnerScope: \"$(warning) Full template validation off. Add parameter file or top-level parameter defaults to enable.\" (azurerm-vscode-tools.selectParameterFile) at [22,21-47,10]", "NestedDeploymentWithInnerScope: \"Using default value\" (azurerm-vscode-tools.codeLens.gotoParameterValue) at [26,13-26,17]", "NestedDeploymentWithInnerScope: \"Value: \"p2 value\"\" (azurerm-vscode-tools.codeLens.gotoParameterValue) at [30,13-30,17]", "NestedDeploymentWithInnerScope: \"Value: \"[add(1, 2)]\"\" (azurerm-vscode-tools.codeLens.gotoParameterValue) at [33,13-33,17]", "NestedDeploymentWithInnerScope: \"$(warning) No value found - click here to enter a value\" (azurerm-vscode-tools.codeLens.gotoParameterValue) at [36,13-36,17]", ] ); createCodeLensTest( "nested inner-scope template with no parameters object", { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "resources": [ { "type": "Microsoft.Resources/deployments", "apiVersion": "2019-10-01", "name": "inner1", "properties": { "expressionEvaluationOptions": { "scope": "inner" }, "mode": "Incremental", "template": { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "p1": { "type": "string", "defaultValue": "p1 default value" }, "p2": { "type": "string" }, "p3": { "type": "int" }, "p4": { "type": "string" } }, "resources": [ ], "outputs": { "v1": { "type": "string", "value": "[parameters('p1')]" } } } } } ] }, [ "TopLevel: \"Select or create a parameter file to enable full validation...\" (azurerm-vscode-tools.selectParameterFile) at [1,1-1,1]", "NestedDeploymentWithInnerScope: \"Nested template with inner scope\" () at [14,21-39,10]", "NestedDeploymentWithInnerScope: \"$(warning) Full template validation off. Add parameter file or top-level parameter defaults to enable.\" (azurerm-vscode-tools.selectParameterFile) at [14,21-39,10]", "NestedDeploymentWithInnerScope: \"Using default value\" (azurerm-vscode-tools.codeLens.gotoParameterValue) at [18,13-18,17]", "NestedDeploymentWithInnerScope: \"$(warning) No value found - click here to enter a value\" (azurerm-vscode-tools.codeLens.gotoParameterValue) at [22,13-22,17]", "NestedDeploymentWithInnerScope: \"$(warning) No value found - click here to enter a value\" (azurerm-vscode-tools.codeLens.gotoParameterValue) at [25,13-25,17]", "NestedDeploymentWithInnerScope: \"$(warning) No value found - click here to enter a value\" (azurerm-vscode-tools.codeLens.gotoParameterValue) at [28,13-28,17]", ] ); }); }); });
the_stack
import { TransformationRuleService } from './transformation-rule.service'; import { Logger } from '../../shared/logger/default-log.service'; import { CreateNestedRuleDescription, DeleteRuleDescription, EventPropertyNested, EventPropertyPrimitive, EventPropertyUnion, EventSchema, MoveRuleDescription, RenameRuleDescription } from '../../core-model/gen/streampipes-model'; describe('TransformationRuleService', () => { const service = new TransformationRuleService(new Logger()); it('Get complete key from schema nested', () => { const eventProperties: EventPropertyUnion[] = []; const eventPropertyPrimitive: EventPropertyPrimitive = new EventPropertyPrimitive(); eventPropertyPrimitive.elementId = 'id_1'; eventPropertyPrimitive.runtimeName = 'a'; const eventPropertyNested: EventPropertyNested = new EventPropertyNested(); eventPropertyNested.elementId = 'id_2'; eventPropertyNested.runtimeName = 'b'; eventPropertyNested.eventProperties = []; eventPropertyNested.eventProperties.push(eventPropertyPrimitive); eventProperties.push(eventPropertyNested); const result: string = service.getCompleteRuntimeNameKey(eventProperties, 'id_1'); expect(result).toBe('b.a'); }); it('Get complete key from schema primitve', () => { const eventProperties: EventPropertyUnion[] = []; const eventPropertyPrimitive: EventPropertyPrimitive = new EventPropertyPrimitive(); eventPropertyPrimitive.elementId = 'id_1'; eventPropertyPrimitive.runtimeName = 'a'; eventProperties.push(eventPropertyPrimitive); const result: string = service.getCompleteRuntimeNameKey(eventProperties, 'id_1'); expect(result).toBe('a'); }); it('check get all ids with one id', () => { const eventProperties: EventPropertyUnion[] = []; const eventPropertyPrimitive: EventPropertyPrimitive = new EventPropertyPrimitive(); eventPropertyPrimitive.elementId = 'id_1'; eventProperties.push(eventPropertyPrimitive); const result: string[] = service.getAllIds(eventProperties); expect(result.length).toBe(1); expect(result[0]).toBe('id_1'); }); it('check get all ids with multiple ids', () => { const eventProperties: EventPropertyUnion[] = []; const eventPropertyPrimitive: EventPropertyPrimitive = new EventPropertyPrimitive(); eventPropertyPrimitive.elementId = 'id_1'; const eventPropertyPrimitive1: EventPropertyPrimitive = new EventPropertyPrimitive(); eventPropertyPrimitive1.elementId = 'id_2'; const eventPropertyNested: EventPropertyNested = new EventPropertyNested(); eventPropertyNested.elementId = 'id_3'; eventPropertyNested.eventProperties = []; eventPropertyNested.eventProperties.push(eventPropertyPrimitive1); eventProperties.push(eventPropertyPrimitive); eventProperties.push(eventPropertyNested); const result: string[] = service.getAllIds(eventProperties); expect(result.length).toBe(3); expect(result[0]).toBe('id_1'); expect(result[2]).toBe('id_2'); expect(result[1]).toBe('id_3'); }); it('Create Nested Rules simple', () => { const oldEventSchema: EventSchema = new EventSchema(); oldEventSchema.eventProperties = []; const newEventSchema: EventSchema = new EventSchema(); const propertyNested: EventPropertyNested = new EventPropertyNested(); propertyNested.eventProperties = []; propertyNested.elementId = 'id'; propertyNested.runtimeName = 'a'; newEventSchema.eventProperties = []; newEventSchema.eventProperties.push(propertyNested); const result: CreateNestedRuleDescription[] = service.getCreateNestedRules( newEventSchema.eventProperties, oldEventSchema, newEventSchema); expect(result.length).toBe(1); expect(result[0].runtimeKey).toBe('a'); }); it('Create Nested Rules nested', () => { const oldEventSchema: EventSchema = new EventSchema(); oldEventSchema.eventProperties = []; const newEventSchema: EventSchema = new EventSchema(); newEventSchema.eventProperties = []; const nestedNested: EventPropertyNested = new EventPropertyNested(); nestedNested.runtimeName = 'a'; nestedNested.elementId = 'deepnested'; nestedNested.eventProperties = []; const nestedProperty: EventPropertyNested = new EventPropertyNested(); nestedProperty.runtimeName = 'b'; nestedNested.elementId = 'nested'; nestedProperty.eventProperties = []; nestedNested.eventProperties.push(nestedProperty); newEventSchema.eventProperties.push(nestedNested); const result: CreateNestedRuleDescription[] = service.getCreateNestedRules( newEventSchema.eventProperties, oldEventSchema, newEventSchema); expect(result.length).toBe(2); expect(result[0].runtimeKey).toBe('a'); expect(result[1].runtimeKey).toBe('a.b'); }); it('Create Move Rules simple', () => { const oldEventSchema: EventSchema = new EventSchema(); const oldPropertyToMove: EventPropertyPrimitive = new EventPropertyPrimitive(); oldPropertyToMove.runtimeName = 'a'; oldPropertyToMove.elementId = 'a1'; const oldNestedProperty: EventPropertyNested = new EventPropertyNested(); oldNestedProperty.runtimeName = 'b'; oldNestedProperty.elementId = 'b1'; oldNestedProperty.eventProperties = []; oldEventSchema.eventProperties = []; oldEventSchema.eventProperties.push(oldPropertyToMove); oldEventSchema.eventProperties.push(oldNestedProperty); const newEventSchema: EventSchema = new EventSchema(); newEventSchema.eventProperties = []; const newPropertyToMove: EventPropertyPrimitive = new EventPropertyPrimitive(); newPropertyToMove.runtimeName = 'a'; newPropertyToMove.elementId = 'a1'; const newNestedProperty: EventPropertyNested = new EventPropertyNested(); newNestedProperty.runtimeName = 'b'; newNestedProperty.elementId = 'b1'; newNestedProperty.eventProperties = []; newNestedProperty.eventProperties.push(newPropertyToMove); newEventSchema.eventProperties.push(newNestedProperty); const result: MoveRuleDescription[] = service.getMoveRules( newEventSchema.eventProperties, oldEventSchema, newEventSchema); expect(result.length).toBe(1); expect(result[0].oldRuntimeKey).toBe('a'); // expect(result[0].newRuntimeKey).toBe('b.a'); }); it('Delete simple', () => { const oldEventSchema: EventSchema = new EventSchema(); const eventProperty: EventPropertyPrimitive = new EventPropertyPrimitive(); eventProperty.runtimeName = 'a'; oldEventSchema.eventProperties = []; oldEventSchema.eventProperties.push(eventProperty); const newEventSchema: EventSchema = new EventSchema(); newEventSchema.eventProperties = []; const result: DeleteRuleDescription[] = service.getDeleteRules(newEventSchema.eventProperties, oldEventSchema, newEventSchema); expect(result.length).toBe(1); expect(result[0].runtimeKey).toBe('a'); }); it('Delete nested', () => { const oldEventSchema: EventSchema = new EventSchema(); const eventProperty: EventPropertyPrimitive = new EventPropertyPrimitive(); eventProperty.elementId = 'id_2'; eventProperty.runtimeName = 'a'; const eventPropertyNested: EventPropertyNested = new EventPropertyNested(); eventPropertyNested.elementId = 'id_1'; eventPropertyNested.eventProperties = []; eventPropertyNested.eventProperties.push(eventProperty); eventPropertyNested.runtimeName = 'b'; oldEventSchema.eventProperties = []; oldEventSchema.eventProperties.push(eventPropertyNested); let newEventSchema: EventSchema = new EventSchema(); const newEventPropertyNested: EventPropertyNested = new EventPropertyNested(); newEventPropertyNested.elementId = 'id_1'; newEventPropertyNested.runtimeName = 'b'; newEventPropertyNested.eventProperties = []; newEventSchema.eventProperties = []; newEventSchema.eventProperties.push(newEventPropertyNested); let result: DeleteRuleDescription[] = service.getDeleteRules( newEventSchema.eventProperties, oldEventSchema, newEventSchema); expect(result.length).toBe(1); expect(result[0].runtimeKey).toBe('b.a'); newEventSchema = new EventSchema(); newEventSchema.eventProperties = []; result = service.getDeleteRules(newEventSchema.eventProperties, oldEventSchema, newEventSchema); expect(result.length).toBe(1); expect(result[0].runtimeKey).toBe('b'); }); it('Rename simple', () => { const oldEventSchema: EventSchema = new EventSchema(); const oldEventPropertyPrimitive: EventPropertyPrimitive = new EventPropertyPrimitive(); oldEventPropertyPrimitive.elementId = 'id_1'; oldEventPropertyPrimitive.runtimeName = 'a'; oldEventSchema.eventProperties = []; oldEventSchema.eventProperties.push(oldEventPropertyPrimitive); const newEventSchema: EventSchema = new EventSchema(); const newEventPropertyPrimitive: EventPropertyPrimitive = new EventPropertyPrimitive(); newEventPropertyPrimitive.elementId = 'id_1'; newEventPropertyPrimitive.runtimeName = 'b'; newEventSchema.eventProperties = []; newEventSchema.eventProperties.push(newEventPropertyPrimitive); const result: RenameRuleDescription[] = service.getRenameRules(newEventSchema.eventProperties, oldEventSchema, newEventSchema); expect(result.length).toBe(1); expect(result[0].oldRuntimeKey).toBe('a'); expect(result[0].newRuntimeKey).toBe('b'); }); it('Rename nested', () => { const oldEventSchema: EventSchema = new EventSchema(); const oldNestedEventProperty: EventPropertyNested = new EventPropertyNested(); oldNestedEventProperty.elementId = 'id_2'; oldNestedEventProperty.runtimeName = 'b'; oldNestedEventProperty.eventProperties = []; const oldEventPropertyPrimitive: EventPropertyPrimitive = new EventPropertyPrimitive(); oldEventPropertyPrimitive.elementId = 'id_1'; oldEventPropertyPrimitive.runtimeName = 'a'; oldNestedEventProperty.eventProperties.push(oldEventPropertyPrimitive); oldEventSchema.eventProperties = []; oldEventSchema.eventProperties.push(oldNestedEventProperty); const newEventSchema: EventSchema = new EventSchema(); const newNestedEventProperty: EventPropertyNested = new EventPropertyNested(); newNestedEventProperty.elementId = 'id_2'; newNestedEventProperty.runtimeName = 'b'; const newEventPropertyPrimitive: EventPropertyPrimitive = new EventPropertyPrimitive(); newEventPropertyPrimitive.elementId = 'id_1'; newEventPropertyPrimitive.runtimeName = 'b'; newNestedEventProperty.eventProperties = []; newNestedEventProperty.eventProperties.push(newEventPropertyPrimitive); newEventSchema.eventProperties = []; newEventSchema.eventProperties.push(newNestedEventProperty); const result: RenameRuleDescription[] = service.getRenameRules(newEventSchema.eventProperties, oldEventSchema, newEventSchema); expect(result.length).toBe(1); expect(result[0].oldRuntimeKey).toBe('b.a'); expect(result[0].newRuntimeKey).toBe('b.b'); }); });
the_stack
declare namespace javaemul.internal { /** * Private implementation class for GWT. This API should not be * considered public or stable. * @class */ class Coercions { /** * Coerce js int to 32 bits. * Trick related to JS and lack of integer rollover. * {@see com.google.gwt.lang.Cast#narrow_int} * @param {number} value * @return {number} */ static ensureInt(value: number): number; constructor(); } } declare namespace javaemul.internal { class JreHelper { static LOG10E: number; static LOG10E_$LI$(): number; } } declare namespace javaemul.internal { /** * Wraps native <code>boolean</code> as an object. * @param {boolean} value * @class */ class BooleanHelper implements java.lang.Comparable<BooleanHelper>, java.io.Serializable { static FALSE: boolean; static TRUE: boolean; static TYPE: any; static TYPE_$LI$(): any; static compare(x: boolean, y: boolean): number; static hashCode(value: boolean): number; static logicalAnd(a: boolean, b: boolean): boolean; static logicalOr(a: boolean, b: boolean): boolean; static logicalXor(a: boolean, b: boolean): boolean; static parseBoolean(s: string): boolean; static toString(x: boolean): string; static valueOf$boolean(b: boolean): boolean; static valueOf$java_lang_String(s: string): boolean; static valueOf(s?: any): boolean; booleanValue(): boolean; static unsafeCast(value: any): boolean; compareTo$javaemul_internal_BooleanHelper(b: BooleanHelper): number; /** * * @param {javaemul.internal.BooleanHelper} b * @return {number} */ compareTo(b?: any): number; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ hashCode(): number; /** * * @return {string} */ toString(): string; constructor(); } } declare namespace javaemul.internal { /** * Hashcode caching for strings. * @class */ class StringHashCache { /** * The "old" cache; it will be dumped when front is full. */ static back: any; static back_$LI$(): any; /** * Tracks the number of entries in front. */ static count: number; /** * The "new" cache; it will become back when it becomes full. */ static front: any; static front_$LI$(): any; /** * Pulled this number out of thin air. */ static MAX_CACHE: number; static getHashCode(str: string): number; static compute(str: string): number; static increment(): void; static getProperty(map: any, key: string): any; static createNativeObject(): any; static unsafeCastToInt(o: any): number; } } declare namespace javaemul.internal.stream { class ConsumingFunction<T> { consumer: (p1: T) => void; constructor(consumer: (p1: T) => void); /** * * @param {*} t * @return {*} */ apply(t: T): T; } } declare namespace javaemul.internal.stream { abstract class TerminalStreamRow implements javaemul.internal.stream.StreamRow { chain(next: javaemul.internal.stream.StreamRow): void; end(): void; abstract item(a?: any): any; constructor(); } } declare namespace javaemul.internal.stream { class RunnableChain { run: () => void; next: RunnableChain; constructor(run: () => void); chain(next: RunnableChain): void; runChain(): void; } } declare namespace javaemul.internal.stream { interface StreamRow { chain(next: StreamRow): any; item(a: any): boolean; end(): any; } } declare namespace javaemul.internal.stream { class QuiteRunnable { loudRunnable: () => void; constructor(loudRunnable: () => void); /** * */ run(): void; } } declare namespace javaemul.internal.stream { class ChooseSmallest<T> { comparator: java.util.Comparator<T>; constructor(comparator: java.util.Comparator<T>); apply(t1: T, t2: T): T; } } declare namespace javaemul.internal.stream { class StreamHelper<T> implements java.util.stream.Stream<T> { onCloseChain: javaemul.internal.stream.RunnableChain; head: javaemul.internal.stream.StreamRow; end: javaemul.internal.stream.StreamRow; data: java.util.Collection<T>; chain(streamRow: javaemul.internal.stream.StreamRow): java.util.stream.Stream<any>; play(): void; foldRight(identity: java.util.Optional<T>, accumulator: any): java.util.Optional<any>; constructor(data: java.util.Collection<T>); filter(predicate: (p1: any) => boolean): java.util.stream.Stream<T>; map<R>(mapper: (p1: any) => any): java.util.stream.Stream<R>; mapToObj<U>(mapper: (p0: number) => any): java.util.stream.Stream<U>; flatMap<R>(mapper: (p1: any) => any): java.util.stream.Stream<R>; distinct(): java.util.stream.Stream<T>; sorted$(): java.util.stream.Stream<T>; sorted$java_util_Comparator(comparator: java.util.Comparator<any>): java.util.stream.Stream<T>; sorted(comparator?: any): java.util.stream.Stream<T>; peek(action: (p1: any) => void): java.util.stream.Stream<T>; limit(maxSize: number): java.util.stream.Stream<T>; skip(n: number): java.util.stream.Stream<T>; forEach(action: (p1: any) => void): void; forEachOrdered(action: (p1: any) => void): void; toArray$(): any[]; toArray$java_util_function_IntFunction<A>(generator: (p0: number) => A[]): A[]; toArray<T0 = any>(generator?: any): any; reduce$java_lang_Object$java_util_function_BinaryOperator(identity: T, accumulator: (p1: T, p2: T) => T): T; reduce$java_util_function_BinaryOperator(accumulator: (p1: T, p2: T) => T): java.util.Optional<T>; collect$java_util_stream_Collector<R, A>(collector: java.util.stream.Collector<any, A, R>): R; min(comparator: java.util.Comparator<any>): java.util.Optional<T>; max(comparator: java.util.Comparator<any>): java.util.Optional<T>; count(): number; anyMatch(predicate: (p1: any) => boolean): boolean; allMatch(predicate: (p1: any) => boolean): boolean; noneMatch(predicate: (p1: any) => boolean): boolean; findFirst(): java.util.Optional<T>; findAny(): java.util.Optional<T>; iterator(): java.util.Iterator<T>; isParallel(): boolean; sequential(): java.util.stream.Stream<T>; parallel(): java.util.stream.Stream<T>; unordered(): java.util.stream.Stream<T>; onClose(closeHandler: () => void): java.util.stream.Stream<T>; close(): void; mapToInt(mapper: () => any): java.util.stream.IntStream; mapToLong(mapper: () => any): java.util.stream.LongStream; mapToDouble(mapper: () => any): java.util.stream.DoubleStream; flatMapToInt(mapper: (p1: any) => any): java.util.stream.IntStream; flatMapToLong(mapper: (p1: any) => any): java.util.stream.LongStream; flatMapToDouble(mapper: (p1: any) => any): java.util.stream.DoubleStream; spliterator(): java.util.Spliterator<T>; reduce$java_lang_Object$java_util_function_BiFunction$java_util_function_BinaryOperator<U>(identity: U, accumulator: (p1: U, p2: any) => U, combiner: (p1: U, p2: U) => U): U; reduce<T0 = any>(identity?: any, accumulator?: any, combiner?: any): any; collect$java_util_function_Supplier$java_util_function_BiConsumer$java_util_function_BiConsumer<R>(supplier: () => R, accumulator: (p1: R, p2: any) => void, combiner: (p1: R, p2: R) => void): R; collect<T0 = any, T1 = any>(supplier?: any, accumulator?: any, combiner?: any): any; } } declare namespace javaemul.internal.stream { class CountingPredicate<T> { countDown: number; constructor(n: number); /** * * @param {*} t * @return {boolean} */ test(t: T): boolean; } } declare namespace javaemul.internal.stream { abstract class TransientStreamRow implements javaemul.internal.stream.StreamRow { next: javaemul.internal.stream.StreamRow; chain(next: javaemul.internal.stream.StreamRow): void; abstract end(): any; abstract item(a?: any): any; constructor(); } } declare namespace javaemul.internal.stream { class VoidRunnable { static dryRun: VoidRunnable; static dryRun_$LI$(): VoidRunnable; run(): void; constructor(); } } declare namespace javaemul.internal { /** * Provides an interface for simple JavaScript idioms that can not be expressed in Java. * @class */ class JsUtils { static getInfinity(): number; static isUndefined(value: any): boolean; static unsafeCastToString(string: any): string; static setPropertySafe(map: any, key: string, value: any): void; static getIntProperty(map: any, key: string): number; static setIntProperty(map: any, key: string, value: number): void; static typeOf(o: any): string; } } declare namespace javaemul.internal { /** * A helper class for long comparison. * @class */ class LongCompareHolder { static getLongComparator(): any; } } declare namespace javaemul.internal.annotations { } declare namespace javaemul.internal.annotations { } declare namespace javaemul.internal.annotations { } declare namespace javaemul.internal.annotations { } declare namespace javaemul.internal.annotations { } declare namespace javaemul.internal.annotations { } declare namespace javaemul.internal { class ObjectHelper { static clone(obj: any): any; } } declare namespace javaemul.internal { /** * Wraps a native <code>char</code> as an object. * * TODO(jat): many of the classification methods implemented here are not * correct in that they only handle ASCII characters, and many other methods are * not currently implemented. I think the proper approach is to introduce * a * deferred binding parameter which substitutes an implementation using a * fully-correct Unicode character database, at the expense of additional data * being downloaded. That way developers that need the functionality can get it * without those who don't need it paying for it. * * <pre> * The following methods are still not implemented -- most would require Unicode * character db to be useful: * - digit / is* / to*(int codePoint) * - isDefined(char) * - isIdentifierIgnorable(char) * - isJavaIdentifierPart(char) * - isJavaIdentifierStart(char) * - isJavaLetter(char) -- deprecated, so probably not * - isJavaLetterOrDigit(char) -- deprecated, so probably not * - isISOControl(char) * - isMirrored(char) * - isSpaceChar(char) * - isTitleCase(char) * - isUnicodeIdentifierPart(char) * - isUnicodeIdentifierStart(char) * - getDirectionality(*) * - getNumericValue(*) * - getType(*) * - reverseBytes(char) -- any use for this at all in the browser? * - toTitleCase(*) * - all the category constants for classification * * The following do not properly handle characters outside of ASCII: * - digit(char c, int radix) * - isDigit(char c) * - isLetter(char c) * - isLetterOrDigit(char c) * - isLowerCase(char c) * - isUpperCase(char c) * </pre> * @param {string} value * @class */ class CharacterHelper implements java.lang.Comparable<CharacterHelper>, java.io.Serializable { static TYPE: any; static TYPE_$LI$(): any; static MIN_RADIX: number; static MAX_RADIX: number; static MIN_VALUE: string; static MAX_VALUE: string; static MIN_SURROGATE: string; static MAX_SURROGATE: string; static MIN_LOW_SURROGATE: string; static MAX_LOW_SURROGATE: string; static MIN_HIGH_SURROGATE: string; static MAX_HIGH_SURROGATE: string; static MIN_SUPPLEMENTARY_CODE_POINT: number; static MIN_CODE_POINT: number; static MAX_CODE_POINT: number; static SIZE: number; static charCount(codePoint: number): number; static codePointAt$char_A$int(a: string[], index: number): number; static codePointAt$char_A$int$int(a: string[], index: number, limit: number): number; static codePointAt(a?: any, index?: any, limit?: any): number; static codePointAt$java_lang_CharSequence$int(seq: any, index: number): number; static codePointBefore$char_A$int(a: string[], index: number): number; static codePointBefore$char_A$int$int(a: string[], index: number, start: number): number; static codePointBefore(a?: any, index?: any, start?: any): number; static codePointBefore$java_lang_CharSequence$int(cs: any, index: number): number; static codePointCount$char_A$int$int(a: string[], offset: number, count: number): number; static codePointCount(a?: any, offset?: any, count?: any): number; static codePointCount$java_lang_CharSequence$int$int(seq: any, beginIndex: number, endIndex: number): number; static compare(x: string, y: string): number; static digit(c: string, radix: number): number; static getNumericValue(ch: string): number; static forDigit$int$int(digit: number, radix: number): string; static forDigit(digit?: any, radix?: any): string; /** * @skip * * public for shared implementation with Arrays.hashCode * @param {string} c * @return {number} */ static hashCode(c: string): number; static isDigit(c: string): boolean; static digitRegex(): RegExp; static isHighSurrogate(ch: string): boolean; static isLetter(c: string): boolean; static leterRegex(): RegExp; static isLetterOrDigit(c: string): boolean; static leterOrDigitRegex(): RegExp; static isLowerCase(c: string): boolean; static isLowSurrogate(ch: string): boolean; /** * Deprecated - see isWhitespace(char). * @param {string} c * @return {boolean} */ static isSpace(c: string): boolean; static isWhitespace$char(ch: string): boolean; static isWhitespace(ch?: any): boolean; static isWhitespace$int(codePoint: number): boolean; static whitespaceRegex(): RegExp; static isSupplementaryCodePoint(codePoint: number): boolean; static isSurrogatePair(highSurrogate: string, lowSurrogate: string): boolean; static isUpperCase(c: string): boolean; static isValidCodePoint(codePoint: number): boolean; static offsetByCodePoints$char_A$int$int$int$int(a: string[], start: number, count: number, index: number, codePointOffset: number): number; static offsetByCodePoints(a?: any, start?: any, count?: any, index?: any, codePointOffset?: any): number; static offsetByCodePoints$java_lang_CharSequence$int$int(seq: any, index: number, codePointOffset: number): number; static toChars$int(codePoint: number): string[]; static toChars$int$char_A$int(codePoint: number, dst: string[], dstIndex: number): number; static toChars(codePoint?: any, dst?: any, dstIndex?: any): any; static toCodePoint(highSurrogate: string, lowSurrogate: string): number; static toLowerCase$char(c: string): string; static toLowerCase(c?: any): any; static toLowerCase$int(c: number): number; static toString(x: string): string; static toUpperCase$char(c: string): string; static toUpperCase(c?: any): string; static toUpperCase$int(c: number): string; static valueOf(c: string): string; static codePointAt$java_lang_CharSequence$int$int(cs: any, index: number, limit: number): number; static codePointBefore$java_lang_CharSequence$int$int(cs: any, index: number, start: number): number; static forDigit$int(digit: number): string; /** * Computes the high surrogate character of the UTF16 representation of a * non-BMP code point. See {@link getLowSurrogate}. * * @param {number} codePoint * requested codePoint, required to be >= * MIN_SUPPLEMENTARY_CODE_POINT * @return {string} high surrogate character */ static getHighSurrogate(codePoint: number): string; /** * Computes the low surrogate character of the UTF16 representation of a non-BMP * code point. See {@link getHighSurrogate}. * * @param {number} codePoint * requested codePoint, required to be >= * MIN_SUPPLEMENTARY_CODE_POINT * @return {string} low surrogate character */ static getLowSurrogate(codePoint: number): string; value: string; constructor(value: string); charValue(): string; compareTo$javaemul_internal_CharacterHelper(c: CharacterHelper): number; /** * * @param {javaemul.internal.CharacterHelper} c * @return {number} */ compareTo(c?: any): number; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ hashCode(): number; /** * * @return {string} */ toString(): string; } namespace CharacterHelper { /** * Use nested class to avoid clinit on outer. * @class */ class BoxedValues { static boxedValues: string[]; static boxedValues_$LI$(): string[]; constructor(); } } } declare namespace javaemul.internal { /** * Simple Helper class to return Date.now. * @class */ class DateUtil { /** * Returns the numeric value corresponding to the current time - the number * of milliseconds elapsed since 1 January 1970 00:00:00 UTC. * @return {number} */ static now(): number; } } declare namespace javaemul.internal { /** * Provides utilities to perform operations on Arrays. * @class */ class ArrayHelper { static ARRAY_PROCESS_BATCH_SIZE: number; static clone<T>(array: T[], fromIndex: number, toIndex: number): T[]; /** * Unlike clone, this method returns a copy of the array that is not type * marked. This is only safe for temp arrays as returned array will not do * any type checks. * @param {*} array * @param {number} fromIndex * @param {number} toIndex * @return {java.lang.Object[]} */ static unsafeClone(array: any, fromIndex: number, toIndex: number): any[]; static createFrom<T>(array: T[], length: number): T[]; static createNativeArray(length: number): any; static getLength(array: any): number; static setLength(array: any, length: number): void; static removeFrom(array: any, index: number, deleteCount: number): void; static insertTo$java_lang_Object$int$java_lang_Object(array: any, index: number, value: any): void; static insertTo$java_lang_Object$int$java_lang_Object_A(array: any, index: number, values: any[]): void; static insertTo(array?: any, index?: any, values?: any): any; /** * This version of insertTo is specified only for arrays. * Same implementation (and arguments) as "public static void insertTo(Object array, int index, Object[] values)" * @param {*} array * @param {number} index * @param {java.lang.Object[]} values */ static insertValuesToArray(array: any, index: number, values: any[]): void; static copy$java_lang_Object$int$java_lang_Object$int$int(array: any, srcOfs: number, dest: any, destOfs: number, len: number): void; static copy$java_lang_Object$int$java_lang_Object$int$int$boolean(src: any, srcOfs: number, dest: any, destOfs: number, len: number, overwrite: boolean): void; static copy(src?: any, srcOfs?: any, dest?: any, destOfs?: any, len?: any, overwrite?: any): any; static applySplice(arrayObject: any, index: number, deleteCount: number, arrayToAdd: any): void; } } declare namespace javaemul.internal { /** * Math utility methods and constants. * @class */ class MathHelper { static EPSILON: number; static EPSILON_$LI$(): number; static MAX_VALUE: number; static MAX_VALUE_$LI$(): number; static MIN_VALUE: number; static MIN_VALUE_$LI$(): number; static nextDown(x: number): number; static ulp(x: number): number; static nextUp(x: number): number; static E: number; static PI: number; static PI_OVER_180: number; static PI_OVER_180_$LI$(): number; static PI_UNDER_180: number; static PI_UNDER_180_$LI$(): number; static abs$double(x: number): number; static abs$float(x: number): number; static abs$int(x: number): number; static abs(x?: any): any; static abs$long(x: number): number; static acos(x: number): number; static asin(x: number): number; static atan(x: number): number; static atan2(y: number, x: number): number; static cbrt(x: number): number; static ceil(x: number): number; static copySign$double$double(magnitude: number, sign: number): number; static copySign$float$float(magnitude: number, sign: number): number; static copySign(magnitude?: any, sign?: any): any; static cos(x: number): number; static cosh(x: number): number; static exp(x: number): number; static expm1(d: number): number; static floor(x: number): number; static hypot(x: number, y: number): number; static log(x: number): number; static log10(x: number): number; static log1p(x: number): number; static max$double$double(x: number, y: number): number; static max$float$float(x: number, y: number): number; static max$int$int(x: number, y: number): number; static max(x?: any, y?: any): any; static max$long$long(x: number, y: number): number; static min$double$double(x: number, y: number): number; static min$float$float(x: number, y: number): number; static min$int$int(x: number, y: number): number; static min(x?: any, y?: any): any; static min$long$long(x: number, y: number): number; static pow(x: number, exp: number): number; static random(): number; static rint(d: number): number; static round$double(x: number): number; static round$float(x: number): number; static round(x?: any): any; static unsafeCastToInt(d: number): number; static scalb$double$int(d: number, scaleFactor: number): number; static scalb$float$int(f: number, scaleFactor: number): number; static scalb(f?: any, scaleFactor?: any): any; static signum$double(d: number): number; static signum$float(f: number): number; static signum(f?: any): any; static sin(x: number): number; static sinh(x: number): number; static sqrt(x: number): number; static tan(x: number): number; static tanh(x: number): number; static toDegrees(x: number): number; static toRadians(x: number): number; static IEEEremainder(f1: number, f2: number): number; } } declare namespace javaemul.internal { /** * A utility to provide array stamping. Provided as a separate class to simplify * super-source. * @class */ class ArrayStamper { static stampJavaTypeInfo<T>(array: any, referenceType: T[]): T[]; } } declare namespace javaemul.internal { /** * Contains logics for calculating hash codes in JavaScript. * @class */ class HashCodes { static sNextHashId: number; static HASH_CODE_PROPERTY: string; static hashCodeForString(s: string): number; static getIdentityHashCode(o: any): number; static getObjectIdentityHashCode(o: any): number; /** * Called from JSNI. Do not change this implementation without updating: * <ul> * <li>{@link com.google.gwt.user.client.rpc.impl.SerializerBase}</li> * </ul> * @return {number} * @private */ static getNextHashId(): number; } } declare namespace javaemul.internal { /** * Abstract base class for numeric wrapper classes. * @class */ abstract class NumberHelper implements java.io.Serializable { /** * Stores a regular expression object to verify the format of float values. */ static floatRegex: RegExp; /** * @skip * * This function will determine the radix that the string is expressed * in based on the parsing rules defined in the Javadocs for * Integer.decode() and invoke __parseAndValidateInt. * @param {string} s * @param {number} lowerBound * @param {number} upperBound * @return {number} */ static __decodeAndValidateInt(s: string, lowerBound: number, upperBound: number): number; static __decodeNumberString(s: string): NumberHelper.__Decode; /** * @skip * * This function contains common logic for parsing a String as a * floating- point number and validating the range. * @param {string} s * @return {number} */ static __parseAndValidateDouble(s: string): number; /** * @skip * * This function contains common logic for parsing a String in a given * radix and validating the result. * @param {string} s * @param {number} radix * @param {number} lowerBound * @param {number} upperBound * @return {number} */ static __parseAndValidateInt(s: string, radix: number, lowerBound: number, upperBound: number): number; /** * @skip * * This function contains common logic for parsing a String in a given * radix and validating the result. * @param {string} s * @param {number} radix * @return {number} */ static __parseAndValidateLong(s: string, radix: number): number; /** * @skip * * @param {string} str * @return {boolean} {@code true} if the string matches the float format, * {@code false} otherwise * @private */ static __isValidDouble(str: string): boolean; static createFloatRegex(): RegExp; byteValue(): number; abstract doubleValue(): number; abstract floatValue(): number; abstract intValue(): number; abstract longValue(): number; shortValue(): number; constructor(); } namespace NumberHelper { class __Decode { payload: string; radix: number; constructor(radix: number, payload: string); } /** * Use nested class to avoid clinit on outer. * @class */ class __ParseLong { static __static_initialized: boolean; static __static_initialize(): void; /** * The number of digits (excluding minus sign and leading zeros) to * process at a time. The largest value expressible in maxDigits digits * as well as the factor radix^maxDigits must be strictly less than * 2^31. */ static maxDigitsForRadix: number[]; static maxDigitsForRadix_$LI$(): number[]; /** * A table of values radix*maxDigitsForRadix[radix]. */ static maxDigitsRadixPower: number[]; static maxDigitsRadixPower_$LI$(): number[]; /** * The largest number of digits (excluding minus sign and leading zeros) * that can fit into a long for a given radix between 2 and 36, * inclusive. */ static maxLengthForRadix: number[]; static maxLengthForRadix_$LI$(): number[]; /** * A table of floor(MAX_VALUE / maxDigitsRadixPower). */ static maxValueForRadix: number[]; static maxValueForRadix_$LI$(): number[]; static __static_initializer_0(): void; constructor(); } } } declare namespace java.net { class URL implements java.io.Serializable { jsUrl: Object; constructor(protocol?: any, host?: any, port?: any, file?: any); openStream(): java.io.InputStream; static createObjectURL(obj: any): string; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ hashCode(): number; getAuthority(): string; getContent(): any; getDefaultPort(): number; getFile(): string; getHost(): string; getPath(): string; getPort(): number; getProtocol(): string; getQuery(): string; getRef(): string; getUserInfo(): string; sameFile(other: URL): boolean; toExternalForm(): string; makeConnection(): XMLHttpRequest; /** * * @return {string} */ toString(): string; } } declare namespace java.net { class InternalJsURLFactory { static jsURLCtor: Function; static jsURLCtor_$LI$(): Function; static getJsURLConstructor(): Function; static newJsURL(...objects: any[]): URL; constructor(); } } declare namespace java.net { class InternalJsURLForShell { href: string; protocol: string; username: string; password: string; hostname: string; port: number; pathname: string; search: string; hash: string; constructor(data?: any, url?: any); } } declare namespace java.util { abstract class EventListenerProxy<T extends java.util.EventListener> implements java.util.EventListener { listener: T; constructor(listener: T); getListener(): T; } } declare namespace java.util { /** * A set known to be in ascending order. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/SortedSet.html">[Sun * docs]</a> * * @param <E> element type. * @class */ interface SortedSet<E> extends java.util.Set<E> { comparator(): java.util.Comparator<any>; first(): E; headSet(toElement: E): SortedSet<E>; last(): E; subSet(fromElement: E, toElement: E): SortedSet<E>; tailSet(fromElement: E): SortedSet<E>; } } declare namespace java.util { /** * Abstract interface for maps. * * @param <K> * key type. * @param <V> * value type. * @class */ interface Map<K, V> { clear(): any; containsKey(key: any): boolean; containsValue(value: any): boolean; entrySet(): java.util.Set<Map.Entry<K, V>>; get(key: any): V; isEmpty(): boolean; keySet(): java.util.Set<K>; put(key: K, value: V): V; putAll(t: Map<any, any>): any; remove(key: any): V; size(): number; values(): java.util.Collection<V>; merge(key: K, value: V, map: (p1: any, p2: any) => any): V; computeIfAbsent(key: K, mappingFunction: (p1: any) => any): V; getOrDefault(key: any, defaultValue: V): V; putIfAbsent(key: K, value: V): V; replaceAll(__function: (p1: any, p2: any) => any): any; } namespace Map { /** * Represents an individual map entry. * @class */ interface Entry<K, V> { getKey(): K; getValue(): V; setValue(value: V): V; } namespace Entry { /** * * Returns a comparator that compares {@link Map.Entry} by value using the given * {@link Comparator}. * * <p> * The returned comparator is serializable if the specified comparator is also * serializable. * * @param <K> * the type of the map keys * @param <V> * the type of the map values * @param {*} cmp * the value {@link Comparator} * @return {*} a comparator that compares {@link Map.Entry} by the value. * @since 1.8 */ function comparingByValue<K, V>(cmp: java.util.Comparator<any>): java.util.Comparator<java.util.Map.Entry<K, V>>; } } } declare namespace java.util { /** * A factory to create JavaScript Map instances. * @class */ class InternalJsMapFactory { static jsMapCtor: any; static jsMapCtor_$LI$(): any; static getJsMapConstructor(): any; static newJsMap<V>(): java.util.InternalJsMap<V>; constructor(); } } declare namespace java.util { /** * Incomplete and naive implementation of the BitSet utility (mainly for * compatibility/compilation purpose). * * @author Renaud Pawlak * @param {number} nbits * @class */ class BitSet implements java.lang.Cloneable, java.io.Serializable { bits: boolean[]; constructor(nbits?: any); static valueOf(longs: number[]): BitSet; flip$int(bitIndex: number): void; flip$int$int(fromIndex: number, toIndex: number): void; flip(fromIndex?: any, toIndex?: any): any; set$int(bitIndex: number): void; set$int$boolean(bitIndex: number, value: boolean): void; set$int$int(fromIndex: number, toIndex: number): void; set$int$int$boolean(fromIndex: number, toIndex: number, value: boolean): void; set(fromIndex?: any, toIndex?: any, value?: any): any; clear$int(bitIndex: number): void; clear$int$int(fromIndex: number, toIndex: number): void; clear(fromIndex?: any, toIndex?: any): any; clear$(): void; get$int(bitIndex: number): boolean; get$int$int(fromIndex: number, toIndex: number): BitSet; get(fromIndex?: any, toIndex?: any): any; length(): number; isEmpty(): boolean; cardinality(): number; and(set: BitSet): void; or(set: BitSet): void; xor(set: BitSet): void; andNot(set: BitSet): void; size(): number; equals(obj: any): boolean; clone(): any; } } declare namespace java.util { /** * See <a * href="http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html">the * official Java API doc</a> for details. * @class */ class Objects { constructor(); static compare<T>(a: T, b: T, c: java.util.Comparator<any>): number; static deepEquals(a: any, b: any): boolean; static equals(a: any, b: any): boolean; static hashCode(o: any): number; static hash(...values: any[]): number; static isNull(obj: any): boolean; static nonNull(obj: any): boolean; static requireNonNull$java_lang_Object<T>(obj: T): T; static requireNonNull$java_lang_Object$java_lang_String<T>(obj: T, message: string): T; static requireNonNull<T0 = any>(obj?: any, message?: any): any; static requireNonNull$java_lang_Object$java_util_function_Supplier<T>(obj: T, messageSupplier: () => string): T; static toString$java_lang_Object(o: any): string; static toString$java_lang_Object$java_lang_String(o: any, nullDefault: string): string; static toString(o?: any, nullDefault?: any): string; } } declare namespace java.util { /** * See <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html"> * the official Java API doc</a> for details. * * @param <T> type of the wrapped reference * @class */ class Optional<T> { static empty<T>(): Optional<T>; static of<T>(value: T): Optional<T>; static ofNullable<T>(value: T): Optional<T>; static EMPTY: Optional<any>; static EMPTY_$LI$(): Optional<any>; ref: T; constructor(ref?: any); isPresent(): boolean; get(): T; ifPresent(consumer: (p1: any) => void): void; filter(predicate: (p1: any) => boolean): Optional<T>; map<U>(mapper: (p1: any) => any): Optional<U>; flatMap<U>(mapper: (p1: any) => Optional<U>): Optional<U>; orElse(other: T): T; orElseGet(other: () => any): T; orElseThrow<X extends Error>(exceptionSupplier: () => any): T; /** * * @param {*} obj * @return {boolean} */ equals(obj: any): boolean; /** * * @return {number} */ hashCode(): number; /** * * @return {string} */ toString(): string; } } declare namespace java.util { /** * Sorted map providing additional query operations and views. * * @param <K> key type. * @param <V> value type. * @class */ interface NavigableMap<K, V> extends java.util.SortedMap<K, V> { ceilingEntry(key: K): java.util.Map.Entry<K, V>; ceilingKey(key: K): K; descendingKeySet(): java.util.NavigableSet<K>; descendingMap(): NavigableMap<K, V>; firstEntry(): java.util.Map.Entry<K, V>; floorEntry(key: K): java.util.Map.Entry<K, V>; floorKey(key: K): K; headMap(toKey?: any, inclusive?: any): any; higherEntry(key: K): java.util.Map.Entry<K, V>; higherKey(key: K): K; lastEntry(): java.util.Map.Entry<K, V>; lowerEntry(key: K): java.util.Map.Entry<K, V>; lowerKey(key: K): K; navigableKeySet(): java.util.NavigableSet<K>; pollFirstEntry(): java.util.Map.Entry<K, V>; pollLastEntry(): java.util.Map.Entry<K, V>; subMap(fromKey?: any, fromInclusive?: any, toKey?: any, toInclusive?: any): any; tailMap(fromKey?: any, inclusive?: any): any; } } declare namespace java.util { /** * See <a href="https://docs.oracle.com/javase/8/docs/api/java/util/OptionalDouble.html"> * the official Java API doc</a> for details. * @class */ class OptionalDouble { static empty(): OptionalDouble; static of(value: number): OptionalDouble; static EMPTY: OptionalDouble; static EMPTY_$LI$(): OptionalDouble; ref: number; present: boolean; constructor(value?: any); isPresent(): boolean; getAsDouble(): number; ifPresent(consumer: any): void; orElse(other: number): number; orElseGet(other: any): number; orElseThrow<X extends Error>(exceptionSupplier: () => X): number; /** * * @param {*} obj * @return {boolean} */ equals(obj: any): boolean; /** * * @return {number} */ hashCode(): number; /** * * @return {string} */ toString(): string; } } declare namespace java.util { /** * General-purpose interface for storing collections of objects. <a href= * "http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html">[Sun * docs]</a> * * @param <E> * element type * @class */ interface Collection<E> extends java.lang.Iterable<E> { add(o: E): boolean; addAll(c: Collection<any>): boolean; clear(): any; contains(o: any): boolean; containsAll(c: Collection<any>): boolean; isEmpty(): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<E>; remove(o: any): boolean; removeAll(c: Collection<any>): boolean; removeIf(filter: (p1: any) => boolean): boolean; retainAll(c: Collection<any>): boolean; size(): number; toArray<T0 = any>(a?: any): any; stream(): java.util.stream.Stream<E>; parallelStream(): java.util.stream.Stream<E>; } } declare namespace java.util { /** * Construct an Observable with zero Observers. * @class */ class Observable { changed: boolean; obs: java.util.Vector<java.util.Observer>; constructor(); /** * Adds an observer to the set of observers for this object, provided that * it is not the same as some observer already in the set. The order in * which notifications will be delivered to multiple observers is not * specified. See the class comment. * * @param {*} o * an observer to be added. * @throws NullPointerException * if the parameter o is null. */ addObserver(o: java.util.Observer): void; /** * Deletes an observer from the set of observers of this object. Passing * <CODE>null</CODE> to this method will have no effect. * * @param {*} o * the observer to be deleted. */ deleteObserver(o: java.util.Observer): void; notifyObservers$(): void; notifyObservers$java_lang_Object(arg: any): void; /** * If this object has changed, as indicated by the <code>hasChanged</code> * method, then notify all of its observers and then call the * <code>clearChanged</code> method to indicate that this object has no * longer changed. * <p> * Each observer has its <code>update</code> method called with two * arguments: this observable object and the <code>arg</code> argument. * * @param {*} arg * any object. * @see java.util.Observable#clearChanged() * @see java.util.Observable#hasChanged() * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ notifyObservers(arg?: any): any; /** * Clears the observer list so that this object no longer has any observers. */ deleteObservers(): void; /** * Marks this <tt>Observable</tt> object as having been changed; the * <tt>hasChanged</tt> method will now return <tt>true</tt>. */ setChanged(): void; /** * Indicates that this object has no longer changed, or that it has already * notified all of its observers of its most recent change, so that the * <tt>hasChanged</tt> method will now return <tt>false</tt>. This method is * called automatically by the <code>notifyObservers</code> methods. * * @see java.util.Observable#notifyObservers() * @see java.util.Observable#notifyObservers(java.lang.Object) */ clearChanged(): void; /** * Tests if this object has changed. * * @return {boolean} <code>true</code> if and only if the <code>setChanged</code> * method has been called more recently than the * <code>clearChanged</code> method on this object; * <code>false</code> otherwise. * @see java.util.Observable#clearChanged() * @see java.util.Observable#setChanged() */ hasChanged(): boolean; /** * Returns the number of observers of this <tt>Observable</tt> object. * * @return {number} the number of observers of this object. */ countObservers(): number; } } declare namespace java.util { /** * A simple wrapper around JavaScriptObject to provide {@link java.util.Map}-like semantics for any * key type. * <p> * Implementation notes: * <p> * A key's hashCode is the index in backingMap which should contain that key. Since several keys may * have the same hash, each value in hashCodeMap is actually an array containing all entries whose * keys share the same hash. * @param {java.util.AbstractHashMap} host * @class */ class InternalHashCodeMap<K, V> implements java.lang.Iterable<java.util.Map.Entry<K, V>> { forEach(action: (p1: any) => void): void; backingMap: java.util.InternalJsMap<any>; host: java.util.AbstractHashMap<K, V>; __size: number; constructor(host: java.util.AbstractHashMap<K, V>); put(key: K, value: V): V; remove(key: any): V; getEntry(key: any): java.util.Map.Entry<K, V>; findEntryInChain(key: any, chain: java.util.Map.Entry<K, V>[]): java.util.Map.Entry<K, V>; size(): number; /** * * @return {*} */ iterator(): java.util.Iterator<java.util.Map.Entry<K, V>>; getChainOrEmpty(hashCode: number): java.util.Map.Entry<K, V>[]; newEntryChain(): java.util.Map.Entry<K, V>[]; unsafeCastToArray(arr: any): java.util.Map.Entry<K, V>[]; /** * Returns hash code of the key as calculated by {@link AbstractHashMap#getHashCode(Object)} but * also handles null keys as well. * @param {*} key * @return {number} * @private */ hash(key: any): number; } namespace InternalHashCodeMap { class InternalHashCodeMap$0 implements java.util.Iterator<java.util.Map.Entry<any, any>> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; chains: java.util.InternalJsMap.Iterator<any>; itemIndex: number; chain: java.util.Map.Entry<any, any>[]; lastEntry: java.util.Map.Entry<any, any>; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): java.util.Map.Entry<any, any>; /** * */ remove(): void; constructor(__parent: any); } } } declare namespace java.util { /** * Represents a sequence of objects. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html">[Sun docs]</a> * * @param <E> element type * @class */ interface List<E> extends java.util.Collection<E> { add(index?: any, element?: any): any; addAll(index?: any, c?: any): boolean; /** * */ clear(): any; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @param {*} c * @return {boolean} */ containsAll(c: java.util.Collection<any>): boolean; get(index: number): E; indexOf(o: any): number; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<E>; lastIndexOf(o: any): number; listIterator(from?: any): java.util.ListIterator<E>; remove(index?: any): any; /** * * @param {*} c * @return {boolean} */ removeAll(c: java.util.Collection<any>): boolean; /** * * @param {*} c * @return {boolean} */ retainAll(c: java.util.Collection<any>): boolean; set(index: number, element: E): E; /** * * @return {number} */ size(): number; subList(fromIndex: number, toIndex: number): List<E>; /** * * @param {T[]} array * @return {T[]} */ toArray<T0 = any>(array?: any): any; sort(c: java.util.Comparator<any>): any; } } declare namespace java.util.stream { interface LongStream { } } declare namespace java.util.stream { interface IntStream { } namespace IntStream { function range(startInclusive: number, endExclusive: number): java.util.stream.Stream<number>; } } declare namespace java.util.stream { interface Collector<T, A, R> { supplier(): () => A; accumulator(): (p1: A, p2: T) => void; characteristics(): java.util.Set<Collector.Characteristics>; combiner(): (p1: A, p2: A) => A; finisher(): (p1: A) => R; } namespace Collector { enum Characteristics { /** * Indicates that this collector is <em>concurrent</em>, meaning that * the result container can support the accumulator function being * called concurrently with the same result container from multiple * threads. * * <p>If a {@code CONCURRENT} collector is not also {@code UNORDERED}, * then it should only be evaluated concurrently if applied to an * unordered data source. */ CONCURRENT = 0, /** * Indicates that the collection operation does not commit to preserving * the encounter order of input elements. (This might be true if the * result container has no intrinsic order, such as a {@link Set}.) */ UNORDERED = 1, /** * Indicates that the finisher function is the identity function and * can be elided. If set, it must be the case that an unchecked cast * from A to R will succeed. */ IDENTITY_FINISH = 2 } } } declare namespace java.util.stream { interface Stream<T> { filter(predicate: (p1: any) => boolean): Stream<T>; map<R>(mapper: (p1: any) => any): Stream<R>; flatMap<R>(mapper: (p1: any) => any): Stream<R>; distinct(): Stream<T>; sorted(comparator?: any): Stream<T>; peek(action: (p1: any) => void): Stream<T>; limit(maxSize: number): Stream<T>; skip(n: number): Stream<T>; forEach(action: (p1: any) => void): any; forEachOrdered(action: (p1: any) => void): any; toArray<T0 = any>(generator?: any): any; reduce(identity?: any, accumulator?: any): any; collect<R, A>(collector: java.util.stream.Collector<any, A, R>): R; min(comparator: java.util.Comparator<any>): java.util.Optional<T>; max(comparator: java.util.Comparator<any>): java.util.Optional<T>; count(): number; anyMatch(predicate: (p1: any) => boolean): boolean; allMatch(predicate: (p1: any) => boolean): boolean; noneMatch(predicate: (p1: any) => boolean): boolean; findFirst(): java.util.Optional<T>; findAny(): java.util.Optional<T>; iterator(): java.util.Iterator<T>; isParallel(): boolean; sequential(): Stream<T>; parallel(): Stream<T>; unordered(): Stream<T>; onClose(closeHandler: () => void): Stream<T>; close(): any; mapToObj<U>(mapper: (p0: number) => any): Stream<U>; } namespace Stream { function of<T>(...values: T[]): Stream<T>; } } declare namespace java.util.stream { interface DoubleStream { } } declare namespace java.util { /** * See <a href="https://docs.oracle.com/javase/8/docs/api/java/util/OptionalInt.html"> * the official Java API doc</a> for details. * @class */ class OptionalInt { static empty(): OptionalInt; static of(value: number): OptionalInt; static EMPTY: OptionalInt; static EMPTY_$LI$(): OptionalInt; ref: number; present: boolean; constructor(value?: any); isPresent(): boolean; getAsInt(): number; ifPresent(consumer: any): void; orElse(other: number): number; orElseGet(other: any): number; orElseThrow<X extends Error>(exceptionSupplier: () => X): number; /** * * @param {*} obj * @return {boolean} */ equals(obj: any): boolean; /** * * @return {number} */ hashCode(): number; /** * * @return {string} */ toString(): string; } } declare namespace java.util { /** * A collection designed for holding elements prior to processing. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Queue.html">[Sun * docs]</a> * * @param <E> element type. * @class */ interface Queue<E> extends java.util.Collection<E> { element(): E; offer(o: E): boolean; peek(): E; poll(): E; remove(o?: any): any; } } declare namespace java.util { /** * See <a href="https://docs.oracle.com/javase/8/docs/api/java/util/OptionalLong.html"> * the official Java API doc</a> for details. * @class */ class OptionalLong { static empty(): OptionalLong; static of(value: number): OptionalLong; static EMPTY: OptionalLong; static EMPTY_$LI$(): OptionalLong; ref: number; present: boolean; constructor(value?: any); isPresent(): boolean; getAsLong(): number; ifPresent(consumer: any): void; orElse(other: number): number; orElseGet(other: any): number; orElseThrow<X extends Error>(exceptionSupplier: () => X): number; /** * * @param {*} obj * @return {boolean} */ equals(obj: any): boolean; /** * * @return {number} */ hashCode(): number; /** * * @return {string} */ toString(): string; } } declare namespace java.util { /** * Available as a superclass of event objects. * @param {*} source * @class */ class EventObject { source: any; constructor(source: any); getSource(): any; } } declare namespace java.util { class InternalJsMap<V> { get(key: number): V; get(key: string): V; set(key: number, value: V): any; set(key: string, value: V): any; delete(key: number): any; delete(key: string): any; entries(): InternalJsMap.Iterator<V>; } namespace InternalJsMap { class Iterator<V> { next(): InternalJsMap.IteratorEntry<V>; } class IteratorEntry<V> { value: any[]; done: boolean; } } } declare namespace java.util { /** * Constructs a string tokenizer for the specified string. All * characters in the <code>delim</code> argument are the delimiters * for separating tokens. * <p> * If the <code>returnDelims</code> flag is <code>true</code>, then * the delimiter characters are also returned as tokens. Each * delimiter is returned as a string of length one. If the flag is * <code>false</code>, the delimiter characters are skipped and only * serve as separators between tokens. * <p> * Note that if <tt>delim</tt> is <tt>null</tt>, this constructor does * not throw an exception. However, trying to invoke other methods on the * resulting <tt>StringTokenizer</tt> may result in a * <tt>NullPointerException</tt>. * * @param {string} str a string to be parsed. * @param {string} delim the delimiters. * @param {boolean} returnDelims flag indicating whether to return the delimiters * as tokens. * @exception NullPointerException if str is <CODE>null</CODE> * @class * @author unascribed */ class StringTokenizer implements java.util.Enumeration<any> { currentPosition: number; newPosition: number; maxPosition: number; str: string; delimiters: string; retDelims: boolean; delimsChanged: boolean; /** * maxDelimCodePoint stores the value of the delimiter character with the * highest value. It is used to optimize the detection of delimiter * characters. * * It is unlikely to provide any optimization benefit in the * hasSurrogates case because most string characters will be * smaller than the limit, but we keep it so that the two code * paths remain similar. */ maxDelimCodePoint: number; /** * If delimiters include any surrogates (including surrogate * pairs), hasSurrogates is true and the tokenizer uses the * different code path. This is because String.indexOf(int) * doesn't handle unpaired surrogates as a single character. */ hasSurrogates: boolean; /** * When hasSurrogates is true, delimiters are converted to code * points and isDelimiter(int) is used to determine if the given * codepoint is a delimiter. */ delimiterCodePoints: number[]; /** * Set maxDelimCodePoint to the highest char in the delimiter set. * @private */ setMaxDelimCodePoint(): void; constructor(str?: any, delim?: any, returnDelims?: any); /** * Skips delimiters starting from the specified position. If retDelims * is false, returns the index of the first non-delimiter character at or * after startPos. If retDelims is true, startPos is returned. * @param {number} startPos * @return {number} * @private */ skipDelimiters(startPos: number): number; /** * Skips ahead from startPos and returns the index of the next delimiter * character encountered, or maxPosition if no such delimiter is found. * @param {number} startPos * @return {number} * @private */ scanToken(startPos: number): number; isDelimiter(codePoint: number): boolean; /** * Tests if there are more tokens available from this tokenizer's string. * If this method returns <tt>true</tt>, then a subsequent call to * <tt>nextToken</tt> with no argument will successfully return a token. * * @return {boolean} <code>true</code> if and only if there is at least one token * in the string after the current position; <code>false</code> * otherwise. */ hasMoreTokens(): boolean; nextToken$(): string; nextToken$java_lang_String(delim: string): string; /** * Returns the next token in this string tokenizer's string. First, * the set of characters considered to be delimiters by this * <tt>StringTokenizer</tt> object is changed to be the characters in * the string <tt>delim</tt>. Then the next token in the string * after the current position is returned. The current position is * advanced beyond the recognized token. The new delimiter set * remains the default after this call. * * @param {string} delim the new delimiters. * @return {string} the next token, after switching to the new delimiter set. * @exception NoSuchElementException if there are no more tokens in this * tokenizer's string. * @exception NullPointerException if delim is <CODE>null</CODE> */ nextToken(delim?: any): string; /** * Returns the same value as the <code>hasMoreTokens</code> * method. It exists so that this class can implement the * <code>Enumeration</code> interface. * * @return {boolean} <code>true</code> if there are more tokens; * <code>false</code> otherwise. * @see java.util.Enumeration * @see java.util.StringTokenizer#hasMoreTokens() */ hasMoreElements(): boolean; /** * Returns the same value as the <code>nextToken</code> method, * except that its declared return value is <code>Object</code> rather than * <code>String</code>. It exists so that this class can implement the * <code>Enumeration</code> interface. * * @return {*} the next token in the string. * @exception NoSuchElementException if there are no more tokens in this * tokenizer's string. * @see java.util.Enumeration * @see java.util.StringTokenizer#nextToken() */ nextElement(): any; /** * Calculates the number of times that this tokenizer's * <code>nextToken</code> method can be called before it generates an * exception. The current position is not advanced. * * @return {number} the number of tokens remaining in the string using the current * delimiter set. * @see java.util.StringTokenizer#nextToken() */ countTokens(): number; } } declare namespace java.util.regex { class Matcher implements java.util.regex.MatchResult { _pattern: java.util.regex.Pattern; text: string; starts: number[]; ends: number[]; groups: string[]; /** * The range of string that last matched the pattern. If the last * match failed then first is -1; last initially holds 0 then it * holds the index of the end of the last match (which is where the * next search starts). */ first: number; /** * The range of string that last matched the pattern. If the last * match failed then first is -1; last initially holds 0 then it * holds the index of the end of the last match (which is where the * next search starts). */ last: number; /** * The index of the last position appended in a substitution. */ lastAppendPosition: number; constructor(_pattern: java.util.regex.Pattern, text: string); hasGroups(): void; searchWith(regExp: RegExp): boolean; end$(): number; end$int(i: number): number; end$java_lang_String(string: string): number; end(string?: any): number; find$(): boolean; find$int(start: number): boolean; find(start?: any): boolean; group$(): string; group$int(i: number): string; group$java_lang_String(string: string): string; group(string?: any): string; /** * * @return {number} */ groupCount(): number; hitEnd(): boolean; lookingAt(): boolean; matches(): boolean; pattern(): java.util.regex.Pattern; regionEnd(): number; regionStart(): number; replaceAll(replacement: string): string; replaceFirst(replacement: string): string; reset$(): Matcher; reset$java_lang_CharSequence(input: any): Matcher; reset(input?: any): Matcher; start$(): number; start$int(i: number): number; start$java_lang_String(string: string): number; start(string?: any): number; toMatchResult(): java.util.regex.MatchResult; usePattern(newPattern: java.util.regex.Pattern): Matcher; } namespace Matcher { class IndexGetter { regexString: string; parenthesisStart: number[]; parenthesisEnd: number[]; starts: number[]; ends: number[]; startLastIndex: number; constructor(regexString: string, parenthesisStart: number[], parenthesisEnd: number[], starts: number[], ends: number[], startLastIndex: number); /** * * @param {def.js.String[]} args * @return {string} */ apply(args: string[]): string; } class NonCapturesToCaptures { start: number[]; ends: number[]; constructor(start: number[], ends: number[]); /** * * @param {def.js.String[]} args * @return {string} */ apply(args: string[]): string; } class FirstReplacer { replacement: string; first: boolean; constructor(replacement: string); /** * * @param {def.js.String[]} args * @return {string} */ apply(args: string[]): string; } } } declare namespace java.util.regex { class Pattern implements java.io.Serializable { static CASE_INSENSITIVE: number; static MULTILINE: number; static UNICODE_CASE: number; static UNICODE_CHARACTER_CLASS: number; regexp: RegExp; _flags: number; namedGroupsNames: java.util.Map<string, number>; constructor(regexp: RegExp, _flags: number, namedGroupsNames: java.util.Map<string, number>); static compile$java_lang_String(regexp: string): Pattern; static compile$java_lang_String$int(regexpString: string, flags: number): Pattern; static compile(regexpString?: any, flags?: any): Pattern; flags(): number; matcher(sequence: any): java.util.regex.Matcher; static matches(regex: string, input: any): boolean; pattern(): string; static quote(s: string): string; split(input: any, limit?: number): string[]; splitAsStream(input: any): java.util.stream.Stream<string>; /** * * @return {string} */ toString(): string; } namespace Pattern { class GroupNameRemover { namedGroupsNames: java.util.Map<string, number>; count: number; inBrackets: boolean; constructor(namedGroupsNames: java.util.Map<string, number>); /** * * @param {def.js.String[]} args * @return {string} */ apply(args: string[]): string; } } } declare namespace java.util.regex { interface MatchResult { start(i?: any): number; end(i?: any): number; group(i?: any): string; groupCount(): number; } } declare namespace java.util { /** * Skeletal implementation of the Collection interface. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/AbstractCollection.html">[Sun * docs]</a> * * @param <E> the element type. * @class */ abstract class AbstractCollection<E> implements java.util.Collection<E> { removeIf(filter: (p1: any) => boolean): boolean; parallelStream(): java.util.stream.Stream<any>; stream(): java.util.stream.Stream<any>; forEach(action: (p1: any) => void): void; constructor(); /** * * @param {*} o * @return {boolean} */ add(o: E): boolean; /** * * @param {*} c * @return {boolean} */ addAll(c: java.util.Collection<any>): boolean; /** * */ clear(): void; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @param {*} c * @return {boolean} */ containsAll(c: java.util.Collection<any>): boolean; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @return {*} */ abstract iterator(): java.util.Iterator<E>; /** * * @param {*} o * @return {boolean} */ remove(o: any): boolean; /** * * @param {*} c * @return {boolean} */ removeAll(c: java.util.Collection<any>): boolean; /** * * @param {*} c * @return {boolean} */ retainAll(c: java.util.Collection<any>): boolean; /** * * @return {number} */ abstract size(): number; toArray$(): any[]; toArray$java_lang_Object_A<T>(a: T[]): T[]; /** * * @param {T[]} a * @return {T[]} */ toArray<T0 = any>(a?: any): any; /** * * @return {string} */ toString(): string; advanceToFind(o: any, remove: boolean): boolean; } } declare namespace java.util { abstract class TimerTask { static VIRGIN: number; static SCHEDULED: number; static EXECUTED: number; static CANCELLED: number; state: number; nextExecutionTime: number; period: number; handle: number; constructor(); abstract run(): any; cancel(): boolean; scheduledExecutionTime(): number; } } declare namespace java.util { /** * Construct a random generator with the given {@code seed} as the initial * state. * * @param {number} seed the seed that will determine the initial state of this random * number generator. * @see #setSeed * @class */ class Random { static __static_initialized: boolean; static __static_initialize(): void; static multiplierHi: number; static multiplierLo: number; static twoToThe24: number; static twoToThe31: number; static twoToThe32: number; static twoToTheMinus24: number; static twoToTheMinus26: number; static twoToTheMinus31: number; static twoToTheMinus53: number; static twoToTheXMinus24: number[]; static twoToTheXMinus24_$LI$(): number[]; static twoToTheXMinus48: number[]; static twoToTheXMinus48_$LI$(): number[]; /** * A value used to avoid two random number generators produced at the same * time having the same seed. */ static uniqueSeed: number; static __static_initializer_0(): void; /** * The boolean value indicating if the second Gaussian number is available. */ haveNextNextGaussian: boolean; /** * The second Gaussian generated number. */ nextNextGaussian: number; /** * The high 24 bits of the 48=bit seed value. */ seedhi: number; /** * The low 24 bits of the 48=bit seed value. */ seedlo: number; constructor(seed?: any); /** * Returns the next pseudo-random, uniformly distributed {@code boolean} value * generated by this generator. * * @return {boolean} a pseudo-random, uniformly distributed boolean value. */ nextBoolean(): boolean; /** * Modifies the {@code byte} array by a random sequence of {@code byte}s * generated by this random number generator. * * @param {byte[]} buf non-null array to contain the new random {@code byte}s. * @see #next */ nextBytes(buf: number[]): void; /** * Generates a normally distributed random {@code double} number between 0.0 * inclusively and 1.0 exclusively. * * @return {number} a random {@code double} in the range [0.0 - 1.0) * @see #nextFloat */ nextDouble(): number; /** * Generates a normally distributed random {@code float} number between 0.0 * inclusively and 1.0 exclusively. * * @return {number} float a random {@code float} number between [0.0 and 1.0) * @see #nextDouble */ nextFloat(): number; /** * Pseudo-randomly generates (approximately) a normally distributed {@code * double} value with mean 0.0 and a standard deviation value of {@code 1.0} * using the <i>polar method<i> of G. E. P. Box, M. E. Muller, and G. * Marsaglia, as described by Donald E. Knuth in <i>The Art of Computer * Programming, Volume 2: Seminumerical Algorithms</i>, section 3.4.1, * subsection C, algorithm P. * * @return {number} a random {@code double} * @see #nextDouble */ nextGaussian(): number; nextInt$(): number; nextInt$int(n: number): number; /** * Returns a new pseudo-random {@code int} value which is uniformly * distributed between 0 (inclusively) and the value of {@code n} * (exclusively). * * @param {number} n the exclusive upper border of the range [0 - n). * @return {number} a random {@code int}. */ nextInt(n?: any): number; /** * Generates a uniformly distributed 64-bit integer value from the random * number sequence. * * @return {number} 64-bit random integer. * @see java.lang.Integer#MAX_VALUE * @see java.lang.Integer#MIN_VALUE * @see #next * @see #nextInt() * @see #nextInt(int) */ nextLong(): number; setSeed$long(seed: number): void; /** * Returns a pseudo-random uniformly distributed {@code int} value of the * number of bits specified by the argument {@code bits} as described by * Donald E. Knuth in <i>The Art of Computer Programming, Volume 2: * Seminumerical Algorithms</i>, section 3.2.1. * * @param {number} bits number of bits of the returned value. * @return {number} a pseudo-random generated int number. * @see #nextBytes * @see #nextDouble * @see #nextFloat * @see #nextInt() * @see #nextInt(int) * @see #nextGaussian * @see #nextLong */ next(bits: number): number; nextInternal(bits: number): number; setSeed$int$int(seedhi: number, seedlo: number): void; setSeed(seedhi?: any, seedlo?: any): any; } } declare namespace java.util { /** * See <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html"> * the official Java API doc</a> for details. * * @param <E> element type * @class */ interface Iterator<E> { hasNext(): boolean; next(): E; forEachRemaining(consumer: (p1: any) => void): any; remove(): any; } } declare namespace java.util { /** * A very simple emulation of Locale for shared-code patterns like * {@code String.toUpperCase(Locale.US)}. * <p> * Note: Any changes to this class should put into account the assumption that * was made in rest of the JRE emulation. * @class */ class Locale { static ROOT: Locale; static ROOT_$LI$(): Locale; static ENGLISH: Locale; static ENGLISH_$LI$(): Locale; static US: Locale; static US_$LI$(): Locale; static FRANCE: Locale; static FRANCE_$LI$(): Locale; static UK: Locale; static UK_$LI$(): Locale; static defaultLocale: Locale; static defaultLocale_$LI$(): Locale; /** * Returns an instance that represents the browser's default locale (not * necessarily the one defined by 'gwt.locale'). * @return {java.util.Locale} */ static getDefault(): Locale; constructor(); } namespace Locale { class RootLocale extends java.util.Locale { /** * * @return {string} */ toString(): string; constructor(); } class EnglishLocale extends java.util.Locale { /** * * @return {string} */ toString(): string; constructor(); } class FrenchLocale extends java.util.Locale { /** * * @return {string} */ toString(): string; constructor(); } class USLocale extends java.util.Locale { /** * * @return {string} */ toString(): string; constructor(); } class UKLocale extends java.util.Locale { /** * * @return {string} */ toString(): string; constructor(); } class DefaultLocale extends java.util.Locale { /** * * @return {string} */ toString(): string; constructor(); } } } declare namespace java.util.concurrent { interface Callable<V> { (): V; } } declare namespace java.util { interface Dictionary<K, V> { /** * Returns the number of entries (distinct keys) in this dictionary. * * @return {number} the number of keys in this dictionary. */ size(): number; /** * Tests if this dictionary maps no keys to value. The general contract * for the <tt>isEmpty</tt> method is that the result is true if and only * if this dictionary contains no entries. * * @return {boolean} <code>true</code> if this dictionary maps no keys to values; * <code>false</code> otherwise. */ isEmpty(): boolean; /** * Returns an enumeration of the keys in this dictionary. The general * contract for the keys method is that an <tt>Enumeration</tt> object * is returned that will generate all the keys for which this dictionary * contains entries. * * @return {*} an enumeration of the keys in this dictionary. * @see java.util.Dictionary#elements() * @see java.util.Enumeration */ keys(): java.util.Enumeration<K>; /** * Returns an enumeration of the values in this dictionary. The general * contract for the <tt>elements</tt> method is that an * <tt>Enumeration</tt> is returned that will generate all the elements * contained in entries in this dictionary. * * @return {*} an enumeration of the values in this dictionary. * @see java.util.Dictionary#keys() * @see java.util.Enumeration */ elements(): java.util.Enumeration<V>; /** * Returns the value to which the key is mapped in this dictionary. * The general contract for the <tt>isEmpty</tt> method is that if this * dictionary contains an entry for the specified key, the associated * value is returned; otherwise, <tt>null</tt> is returned. * * @return {*} the value to which the key is mapped in this dictionary; * @param {*} key a key in this dictionary. * <code>null</code> if the key is not mapped to any value in * this dictionary. * @exception NullPointerException if the <tt>key</tt> is <tt>null</tt>. * @see java.util.Dictionary#put(java.lang.Object, java.lang.Object) */ get(key: any): V; /** * Maps the specified <code>key</code> to the specified * <code>value</code> in this dictionary. Neither the key nor the * value can be <code>null</code>. * <p> * If this dictionary already contains an entry for the specified * <tt>key</tt>, the value already in this dictionary for that * <tt>key</tt> is returned, after modifying the entry to contain the * new element. <p>If this dictionary does not already have an entry * for the specified <tt>key</tt>, an entry is created for the * specified <tt>key</tt> and <tt>value</tt>, and <tt>null</tt> is * returned. * <p> * The <code>value</code> can be retrieved by calling the * <code>get</code> method with a <code>key</code> that is equal to * the original <code>key</code>. * * @param {*} key the hashtable key. * @param {*} value the value. * @return {*} the previous value to which the <code>key</code> was mapped * in this dictionary, or <code>null</code> if the key did not * have a previous mapping. * @exception NullPointerException if the <code>key</code> or * <code>value</code> is <code>null</code>. * @see java.lang.Object#equals(java.lang.Object) * @see java.util.Dictionary#get(java.lang.Object) */ put(key: K, value: V): V; /** * Removes the <code>key</code> (and its corresponding * <code>value</code>) from this dictionary. This method does nothing * if the <code>key</code> is not in this dictionary. * * @param {*} key the key that needs to be removed. * @return {*} the value to which the <code>key</code> had been mapped in this * dictionary, or <code>null</code> if the key did not have a * mapping. * @exception NullPointerException if <tt>key</tt> is <tt>null</tt>. */ remove(key: any): V; } } declare namespace java.util { /** * A collection designed for holding elements prior to processing. <a * href="http://docs.oracle.com/javase/6/docs/api/java/util/Deque.html">Deque</a> * * @param <E> element type. * @class */ interface Deque<E> extends java.util.Queue<E> { addFirst(e: E): any; addLast(e: E): any; descendingIterator(): java.util.Iterator<E>; getFirst(): E; getLast(): E; offerFirst(e: E): boolean; offerLast(e: E): boolean; peekFirst(): E; peekLast(): E; pollFirst(): E; pollLast(): E; pop(): E; push(e: E): any; removeFirst(): E; removeFirstOccurrence(o: any): boolean; removeLast(): E; removeLastOccurrence(o: any): boolean; } } declare namespace java.util { /** * An interface to generate a series of elements, one at a time. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Enumeration.html">[Sun * docs]</a> * * @param <E> the type being enumerated. * @class */ interface Enumeration<E> { hasMoreElements(): boolean; nextElement(): E; } } declare namespace java.util { /** * A tag interface that other "listener" interfaces can extend to indicate their * adherence to the observer pattern. * @class */ interface EventListener { } } declare namespace java.util { class Comparators { /** * Compares two Objects according to their <i>natural ordering</i>. * * @see java.lang.Comparable */ static NATURAL: java.util.Comparator<any>; static NATURAL_$LI$(): java.util.Comparator<any>; /** * Returns the natural Comparator. * <p> * Example: * * <pre>Comparator&lt;String&gt; compareString = Comparators.natural()</pre> * * @return {*} the natural Comparator */ static natural<T>(): java.util.Comparator<T>; } namespace Comparators { class NaturalComparator { /** * * @param {*} o1 * @param {*} o2 * @return {number} */ compare(o1: any, o2: any): number; constructor(); } } } declare namespace java.util { /** * See <a href="https://docs.oracle.com/javase/8/docs/api/java/util/PrimitiveIterator.html"> * the official Java API doc</a> for details. * * @param <T> element type * @param <C> consumer type * @class */ interface PrimitiveIterator<T, C> extends java.util.Iterator<T> { } namespace PrimitiveIterator { /** * See <a href="https://docs.oracle.com/javase/8/docs/api/java/util/PrimitiveIterator.OfDouble.html"> * the official Java API doc</a> for details. * @class */ interface OfDouble extends java.util.PrimitiveIterator<number, any> { nextDouble(): number; /** * * @return {number} */ next(): number; /** * * @param {(number) => void} consumer */ forEachRemaining(consumer?: any): any; } /** * See <a href="https://docs.oracle.com/javase/8/docs/api/java/util/PrimitiveIterator.OfInt.html"> * the official Java API doc</a> for details. * @class */ interface OfInt extends java.util.PrimitiveIterator<number, any> { nextInt(): number; /** * * @return {number} */ next(): number; /** * * @param {(number) => void} consumer */ forEachRemaining(consumer?: any): any; } /** * See <a href="https://docs.oracle.com/javase/8/docs/api/java/util/PrimitiveIterator.OfLong.html"> * the official Java API doc</a> for details. * @class */ interface OfLong extends java.util.PrimitiveIterator<number, any> { nextLong(): number; /** * * @return {number} */ next(): number; /** * * @param {(number) => void} consumer */ forEachRemaining(consumer?: any): any; } } } declare namespace java.util { interface Spliterator<T> { } } declare namespace java.util { /** * An interface used a basis for implementing custom ordering. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html">[Sun * docs]</a> * * @param <T> the type to be compared. * @class */ interface Comparator<T> { (a: T, b: T): number; } } declare namespace java.util { /** * A {@code SortedSet} with more flexible queries. * * @param <E> element type. * @class */ interface NavigableSet<E> extends java.util.SortedSet<E> { ceiling(e: E): E; descendingIterator(): java.util.Iterator<E>; descendingSet(): NavigableSet<E>; floor(e: E): E; headSet(toElement?: any, inclusive?: any): any; higher(e: E): E; lower(e: E): E; pollFirst(): E; pollLast(): E; subSet(fromElement?: any, fromInclusive?: any, toElement?: any, toInclusive?: any): any; tailSet(fromElement?: any, inclusive?: any): any; } } declare namespace java.util { /** * Represents a date and time. * @param {number} year * @param {number} month * @param {number} date * @param {number} hrs * @param {number} min * @param {number} sec * @class */ class Date implements java.lang.Cloneable, java.lang.Comparable<Date>, java.io.Serializable { static parse(s: string): number; static UTC(year: number, month: number, date: number, hrs: number, min: number, sec: number): number; /** * Ensure a number is displayed with two digits. * * @return {string} a two-character base 10 representation of the number * @param {number} number */ static padTwo(number: number): string; /** * JavaScript Date instance. */ jsdate: Object; static jsdateClass(): Object; constructor(year?: any, month?: any, date?: any, hrs?: any, min?: any, sec?: any); after(when: Date): boolean; before(when: Date): boolean; clone(): any; compareTo$java_util_Date(other: Date): number; /** * * @param {java.util.Date} other * @return {number} */ compareTo(other?: any): number; /** * * @param {*} obj * @return {boolean} */ equals(obj: any): boolean; getDate(): number; getDay(): number; getHours(): number; getMinutes(): number; getMonth(): number; getSeconds(): number; getTime(): number; getTimezoneOffset(): number; getYear(): number; /** * * @return {number} */ hashCode(): number; setDate(date: number): void; setHours(hours: number): void; setMinutes(minutes: number): void; setMonth(month: number): void; setSeconds(seconds: number): void; setTime(time: number): void; setYear(year: number): void; toGMTString(): string; toLocaleString(): string; /** * * @return {string} */ toString(): string; static ONE_HOUR_IN_MILLISECONDS: number; /** * Detects if the requested time falls into a non-existent time range due to * local time advancing into daylight savings time or is ambiguous due to * going out of daylight savings. If so, adjust accordingly. * @param {number} requestedHours * @private */ fixDaylightSavings(requestedHours: number): void; } namespace Date { /** * Encapsulates static data to avoid Date itself having a static * initializer. * @class */ class StringData { static DAYS: string[]; static DAYS_$LI$(): string[]; static MONTHS: string[]; static MONTHS_$LI$(): string[]; constructor(); } } } declare namespace java.util { /** * A map with ordering. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/SortedMap.html">[Sun * docs]</a> * * @param <K> key type. * @param <V> value type. * @class */ interface SortedMap<K, V> extends java.util.Map<K, V> { comparator(): java.util.Comparator<any>; firstKey(): K; headMap(toKey: K): SortedMap<K, V>; lastKey(): K; subMap(fromKey: K, toKey: K): SortedMap<K, V>; tailMap(fromKey: K): SortedMap<K, V>; } } declare namespace java.util { /** * Represents a set of unique objects. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Set.html">[Sun docs]</a> * * @param <E> element type. * @class */ interface Set<E> extends java.util.Collection<E> { /** * * @param {*} o * @return {boolean} */ add(o: E): boolean; /** * * @param {*} c * @return {boolean} */ addAll(c: java.util.Collection<any>): boolean; /** * */ clear(): any; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @param {*} c * @return {boolean} */ containsAll(c: java.util.Collection<any>): boolean; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<E>; /** * * @param {*} o * @return {boolean} */ remove(o: any): boolean; /** * * @param {*} c * @return {boolean} */ removeAll(c: java.util.Collection<any>): boolean; /** * * @param {*} c * @return {boolean} */ retainAll(c: java.util.Collection<any>): boolean; /** * * @return {number} */ size(): number; /** * * @param {T[]} a * @return {T[]} */ toArray<T0 = any>(a?: any): any; } } declare namespace java.util { /** * Implementation of the observer interface * @class */ interface Observer { /** * This method is called whenever the observed object is changed. An * application calls an <tt>Observable</tt> object's * <code>notifyObservers</code> method to have all the object's * observers notified of the change. * * @param {java.util.Observable} o the observable object. * @param {*} arg an argument passed to the <code>notifyObservers</code> * method. */ update(o: java.util.Observable, arg: any): any; } } declare namespace java.util.logging { /** * An emulation of the java.util.logging.Handler class. See * <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/logging/Handler.html"> * The Java API doc for details</a> * @class */ abstract class Handler { formatter: java.util.logging.Formatter; level: java.util.logging.Level; abstract close(): any; abstract flush(): any; getFormatter(): java.util.logging.Formatter; getLevel(): java.util.logging.Level; isLoggable(record: java.util.logging.LogRecord): boolean; abstract publish(record: java.util.logging.LogRecord): any; setFormatter(newFormatter: java.util.logging.Formatter): void; setLevel(newLevel: java.util.logging.Level): void; constructor(); } } declare namespace java.util.logging { /** * An emulation of the java.util.logging.LogRecord class. See * <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/logging/LogRecord.html"> * The Java API doc for details</a> * @param {java.util.logging.Level} level * @param {string} msg * @class */ class LogRecord implements java.io.Serializable { level: java.util.logging.Level; loggerName: string; msg: string; thrown: Error; millis: number; constructor(level?: any, msg?: any); getLevel(): java.util.logging.Level; getLoggerName(): string; getMessage(): string; getMillis(): number; getThrown(): Error; setLevel(newLevel: java.util.logging.Level): void; setLoggerName(newName: string): void; setMessage(newMessage: string): void; setMillis(newMillis: number): void; setThrown(newThrown: Error): void; } } declare namespace java.util.logging { /** * An emulation of the java.util.logging.LogManager class. See * <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/logging/LogManger.html"> * The Java API doc for details</a> * @class */ class LogManager { static singleton: LogManager; static getLogManager(): LogManager; loggerMap: java.util.HashMap<string, java.util.logging.Logger>; constructor(); addLogger(logger: java.util.logging.Logger): boolean; getLogger(name: string): java.util.logging.Logger; getLoggerNames(): java.util.Enumeration<string>; /** * Helper function to add a logger when we have already determined that it * does not exist. When we add a logger, we recursively add all of it's * ancestors. Since loggers do not get removed, logger creation is cheap, * and there are not usually too many loggers in an ancestry chain, * this is a simple way to ensure that the parent/child relationships are * always correctly set up. * @param {java.util.logging.Logger} logger * @private */ addLoggerAndEnsureParents(logger: java.util.logging.Logger): void; addLoggerImpl(logger: java.util.logging.Logger): void; /** * Helper function to create a logger if it does not exist since the public * APIs for getLogger and addLogger make it difficult to use those functions * for this. * @param {string} name * @return {java.util.logging.Logger} */ ensureLogger(name: string): java.util.logging.Logger; } } declare namespace java.util.logging { /** * An emulation of the java.util.logging.Formatter class. See * <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/logging/Formatter.html"> * The Java API doc for details</a> * @class */ abstract class Formatter { abstract format(record: java.util.logging.LogRecord): string; formatMessage(record: java.util.logging.LogRecord): string; } } declare namespace java.util.logging { /** * An emulation of the java.util.logging.Level class. See * <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/logging/Level.html"> * The Java API doc for details</a> * @class */ class Level implements java.io.Serializable { static ALL: Level; static ALL_$LI$(): Level; static CONFIG: Level; static CONFIG_$LI$(): Level; static FINE: Level; static FINE_$LI$(): Level; static FINER: Level; static FINER_$LI$(): Level; static FINEST: Level; static FINEST_$LI$(): Level; static INFO: Level; static INFO_$LI$(): Level; static OFF: Level; static OFF_$LI$(): Level; static SEVERE: Level; static SEVERE_$LI$(): Level; static WARNING: Level; static WARNING_$LI$(): Level; static parse(name: string): Level; constructor(); getName(): string; intValue(): number; /** * * @return {string} */ toString(): string; } namespace Level { class LevelAll extends java.util.logging.Level { /** * * @return {string} */ getName(): string; /** * * @return {number} */ intValue(): number; constructor(); } class LevelConfig extends java.util.logging.Level { /** * * @return {string} */ getName(): string; /** * * @return {number} */ intValue(): number; constructor(); } class LevelFine extends java.util.logging.Level { /** * * @return {string} */ getName(): string; /** * * @return {number} */ intValue(): number; constructor(); } class LevelFiner extends java.util.logging.Level { /** * * @return {string} */ getName(): string; /** * * @return {number} */ intValue(): number; constructor(); } class LevelFinest extends java.util.logging.Level { /** * * @return {string} */ getName(): string; /** * * @return {number} */ intValue(): number; constructor(); } class LevelInfo extends java.util.logging.Level { /** * * @return {string} */ getName(): string; /** * * @return {number} */ intValue(): number; constructor(); } class LevelOff extends java.util.logging.Level { /** * * @return {string} */ getName(): string; /** * * @return {number} */ intValue(): number; constructor(); } class LevelSevere extends java.util.logging.Level { /** * * @return {string} */ getName(): string; /** * * @return {number} */ intValue(): number; constructor(); } class LevelWarning extends java.util.logging.Level { /** * * @return {string} */ getName(): string; /** * * @return {number} */ intValue(): number; constructor(); } } } declare namespace java.util { /** * Indicates that a data structure supports constant-time random access to its * contained objects. * @class */ interface RandomAccess { } } declare namespace java.util { /** * Uses Java 1.5 ListIterator for documentation. The methods hasNext, next, and * remove are repeated to allow the specialized ListIterator documentation to be * associated with them. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/ListIterator.html">[Sun * docs]</a> * * @param <E> element type. * @class */ interface ListIterator<E> extends java.util.Iterator<E> { add(o: E): any; /** * * @return {boolean} */ hasNext(): boolean; hasPrevious(): boolean; /** * * @return {*} */ next(): E; nextIndex(): number; previous(): E; previousIndex(): number; /** * */ remove(): any; set(o: E): any; } } declare namespace java.util { /** * See <a href="https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html"> * the official Java API doc</a> for details. * @param {*} delimiter * @param {*} prefix * @param {*} suffix * @class */ class StringJoiner { delimiter: string; prefix: string; suffix: string; builder: java.lang.StringBuilder; emptyValue: string; constructor(delimiter?: any, prefix?: any, suffix?: any); add(newElement: any): StringJoiner; length(): number; merge(other: StringJoiner): StringJoiner; setEmptyValue(emptyValue: any): StringJoiner; /** * * @return {string} */ toString(): string; initBuilderOrAddDelimiter(): void; } } declare namespace java.util { /** * Basic {@link Map.Entry} implementation that implements hashCode, equals, and * toString. * @class */ abstract class AbstractMapEntry<K, V> implements java.util.Map.Entry<K, V> { /** * * @param {*} other * @return {boolean} */ equals(other: any): boolean; /** * Calculate the hash code using Sun's specified algorithm. * @return {number} */ hashCode(): number; /** * * @return {string} */ toString(): string; abstract getKey(): any; abstract getValue(): any; abstract setValue(value?: any): any; constructor(); } } declare namespace java.security { /** * Message Digest Service Provider Interface - <a * href="http://java.sun.com/j2se/1.4.2/docs/api/java/security/MessageDigestSpi.html">[Sun's * docs]</a>. * @class */ abstract class MessageDigestSpi { engineDigest$(): number[]; engineDigest$byte_A$int$int(buf: number[], offset: number, len: number): number; engineDigest(buf?: any, offset?: any, len?: any): any; engineGetDigestLength(): number; abstract engineReset(): any; engineUpdate$byte(input: number): void; engineUpdate$byte_A$int$int(input: number[], offset: number, len: number): void; engineUpdate(input?: any, offset?: any, len?: any): any; } } declare namespace java.io { /** * Provides a series of utilities to be reused between IO classes. * * TODO(chehayeb): move these checks to InternalPreconditions. * @class */ class IOUtils { static checkOffsetAndCount$byte_A$int$int(buffer: number[], byteOffset: number, byteCount: number): void; /** * Validates the offset and the byte count for the given array of bytes. * * @param {byte[]} buffer Array of bytes to be checked. * @param {number} byteOffset Starting offset in the array. * @param {number} byteCount Total number of bytes to be accessed. * @throws NullPointerException if the given reference to the buffer is null. * @throws IndexOutOfBoundsException if {@code byteOffset} is negative, {@code byteCount} is * negative or their sum exceeds the buffer length. */ static checkOffsetAndCount(buffer?: any, byteOffset?: any, byteCount?: any): any; static checkOffsetAndCount$char_A$int$int(buffer: string[], charOffset: number, charCount: number): void; static checkOffsetAndCount$int$int$int(length: number, offset: number, count: number): void; constructor(); } } declare namespace java.io { /** * JSweet implementation. * @class */ abstract class Writer implements java.lang.Appendable, java.io.Closeable, java.io.Flushable { writeBuffer: string[]; static WRITE_BUFFER_SIZE: number; lock: any; constructor(lock?: any); write$int(c: number): void; write$char_A(cbuf: string[]): void; write$char_A$int$int(cbuf: string[], off: number, len: number): void; write$java_lang_String(str: string): void; write$java_lang_String$int$int(str: string, off: number, len: number): void; write(str?: any, off?: any, len?: any): any; append$java_lang_CharSequence(csq: any): Writer; append$java_lang_CharSequence$int$int(csq: any, start: number, end: number): Writer; append(csq?: any, start?: any, end?: any): any; append$char(c: string): Writer; abstract flush(): any; abstract close(): any; } } declare namespace java.io { /** * Defines an interface for classes that can (or need to) be flushed, typically * before some output processing is considered to be finished and the object * gets closed. * @class */ interface Flushable { /** * Flushes the object by writing out any buffered data to the underlying * output. * * @throws IOException * if there are any issues writing the data. */ flush(): any; } } declare namespace java.io { /** * An {@code AutoCloseable} whose close method may throw an {@link IOException}. * @class */ interface Closeable extends java.lang.AutoCloseable { /** * Closes the object and release any system resources it holds. * * <p>Although only the first call has any effect, it is safe to call close * multiple times on the same object. This is more lenient than the * overridden {@code AutoCloseable.close()}, which may be called at most * once. */ close(): any; } } declare namespace java.io { /** * Provided for interoperability; RPC treats this interface synonymously with * {@link com.google.gwt.user.client.rpc.IsSerializable}. * The Java serialization protocol is explicitly not supported. * @class */ interface Serializable { } } declare namespace java.io { /** * This constructor does nothing. It is provided for signature * compatibility. * @class * @extends * */ abstract class InputStream implements java.io.Closeable { /** * Size of the temporary buffer used when skipping bytes with {@link skip(long)}. */ static MAX_SKIP_BUFFER_SIZE: number; constructor(); /** * Returns an estimated number of bytes that can be read or skipped without blocking for more * input. * * <p>Note that this method provides such a weak guarantee that it is not very useful in * practice. * * <p>Firstly, the guarantee is "without blocking for more input" rather than "without * blocking": a read may still block waiting for I/O to complete&nbsp;&mdash; the guarantee is * merely that it won't have to wait indefinitely for data to be written. The result of this * method should not be used as a license to do I/O on a thread that shouldn't be blocked. * * <p>Secondly, the result is a * conservative estimate and may be significantly smaller than the actual number of bytes * available. In particular, an implementation that always returns 0 would be correct. * In general, callers should only use this method if they'd be satisfied with * treating the result as a boolean yes or no answer to the question "is there definitely * data ready?". * * <p>Thirdly, the fact that a given number of bytes is "available" does not guarantee that a * read or skip will actually read or skip that many bytes: they may read or skip fewer. * * <p>It is particularly important to realize that you <i>must not</i> use this method to * size a container and assume that you can read the entirety of the stream without needing * to resize the container. Such callers should probably write everything they read to a * {@link ByteArrayOutputStream} and convert that to a byte array. Alternatively, if you're * reading from a file, {@link File#length} returns the current length of the file (though * assuming the file's length can't change may be incorrect, reading a file is inherently * racy). * * <p>The default implementation of this method in {@code InputStream} always returns 0. * Subclasses should override this method if they are able to indicate the number of bytes * available. * * @return {number} the estimated number of bytes available * @throws IOException if this stream is closed or an error occurs */ available(): number; /** * Closes this stream. Concrete implementations of this class should free * any resources during close. This implementation does nothing. * * @throws IOException * if an error occurs while closing this stream. */ close(): void; /** * Sets a mark position in this InputStream. The parameter {@code readlimit} * indicates how many bytes can be read before the mark is invalidated. * Sending {@code reset()} will reposition the stream back to the marked * position provided {@code readLimit} has not been surpassed. * <p> * This default implementation does nothing and concrete subclasses must * provide their own implementation. * * @param {number} readlimit * the number of bytes that can be read from this stream before * the mark is invalidated. * @see #markSupported() * @see #reset() */ mark(readlimit: number): void; /** * Indicates whether this stream supports the {@code mark()} and * {@code reset()} methods. The default implementation returns {@code false}. * * @return {boolean} always {@code false}. * @see #mark(int) * @see #reset() */ markSupported(): boolean; read$(): number; read$byte_A(buffer: number[]): number; read$byte_A$int$int(buffer: number[], byteOffset: number, byteCount: number): number; /** * Reads up to {@code byteCount} bytes from this stream and stores them in * the byte array {@code buffer} starting at {@code byteOffset}. * Returns the number of bytes actually read or -1 if the end of the stream * has been reached. * * @throws IndexOutOfBoundsException * if {@code byteOffset < 0 || byteCount < 0 || byteOffset + byteCount > buffer.length}. * @throws IOException * if the stream is closed or another IOException occurs. * @param {byte[]} buffer * @param {number} byteOffset * @param {number} byteCount * @return {number} */ read(buffer?: any, byteOffset?: any, byteCount?: any): number; /** * Resets this stream to the last marked location. Throws an * {@code IOException} if the number of bytes read since the mark has been * set is greater than the limit provided to {@code mark}, or if no mark * has been set. * <p> * This implementation always throws an {@code IOException} and concrete * subclasses should provide the proper implementation. * * @throws IOException * if this stream is closed or another IOException occurs. */ reset(): void; /** * Skips at most {@code byteCount} bytes in this stream. The number of actual * bytes skipped may be anywhere between 0 and {@code byteCount}. If * {@code byteCount} is negative, this method does nothing and returns 0, but * some subclasses may throw. * * <p>Note the "at most" in the description of this method: this method may * choose to skip fewer bytes than requested. Callers should <i>always</i> * check the return value. * * <p>This default implementation reads bytes into a temporary buffer. Concrete * subclasses should provide their own implementation. * * @return {number} the number of bytes actually skipped. * @throws IOException if this stream is closed or another IOException * occurs. * @param {number} byteCount */ skip(byteCount: number): number; } } declare namespace java.io { /** * JSweet implementation. * @class */ abstract class Reader implements java.io.Closeable { lock: any; constructor(lock?: any); read$(): number; read$char_A(cbuf: string[]): number; read$char_A$int$int(cbuf: string[], off: number, len: number): number; read(cbuf?: any, off?: any, len?: any): number; /** * Maximum skip-buffer size */ static maxSkipBufferSize: number; /** * Skip buffer, null until allocated */ skipBuffer: string[]; skip(n: number): number; ready(): boolean; markSupported(): boolean; mark(readAheadLimit: number): void; reset(): void; abstract close(): any; } } declare namespace java.io { /** * Default constructor. * @class */ abstract class OutputStream implements java.io.Closeable, java.io.Flushable { constructor(); /** * Closes this stream. Implementations of this method should free any * resources used by the stream. This implementation does nothing. * * @throws IOException * if an error occurs while closing this stream. */ close(): void; /** * Flushes this stream. Implementations of this method should ensure that * any buffered data is written out. This implementation does nothing. * * @throws IOException * if an error occurs while flushing this stream. */ flush(): void; write$byte_A(buffer: number[]): void; write$byte_A$int$int(buffer: number[], offset: number, count: number): void; /** * Writes {@code count} bytes from the byte array {@code buffer} starting at * position {@code offset} to this stream. * * @param {byte[]} buffer * the buffer to be written. * @param {number} offset * the start position in {@code buffer} from where to get bytes. * @param {number} count * the number of bytes from {@code buffer} to write to this * stream. * @throws IOException * if an error occurs while writing to this stream. * @throws IndexOutOfBoundsException * if {@code offset < 0} or {@code count < 0}, or if * {@code offset + count} is bigger than the length of * {@code buffer}. */ write(buffer?: any, offset?: any, count?: any): any; write$int(oneByte: number): void; } } declare namespace java.lang { } declare namespace java.lang { /** * See <a * href="http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html">the * official Java API doc</a> for details. * @class */ interface AutoCloseable { /** * Closes this resource. */ close(): any; } } declare namespace java.lang.ref { /** * This implements the reference API in a minimal way. In JavaScript, there is * no control over the reference and the GC. So this implementation's only * purpose is for compilation. * @class */ abstract class Reference<T> { referent: T; constructor(referent: T); get(): T; clear(): void; } } declare namespace java.lang { /** * Represents an error caused by an assertion failure. * @param {string} message * @param {java.lang.Throwable} cause * @class * @extends java.lang.Error */ class AssertionError extends Error { constructor(message?: any, cause?: any); } } declare namespace java.lang { /** * Allows an instance of a class implementing this interface to be used in the * foreach statement. * See <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html"> * the official Java API doc</a> for details. * * @param <T> type of returned iterator * @class */ interface Iterable<T> { iterator(): java.util.Iterator<T>; forEach(action: (p1: any) => void): any; } } declare namespace java.lang { /** * Included for hosted mode source compatibility. Partially implemented * * @skip * @param {string} className * @param {string} methodName * @param {string} fileName * @param {number} lineNumber * @class */ class StackTraceElement implements java.io.Serializable { className: string; fileName: string; lineNumber: number; methodName: string; constructor(className?: any, methodName?: any, fileName?: any, lineNumber?: any); getClassName(): string; getFileName(): string; getLineNumber(): number; getMethodName(): string; /** * * @param {*} other * @return {boolean} */ equals(other: any): boolean; /** * * @return {number} */ hashCode(): number; /** * * @return {string} */ toString(): string; } } declare namespace java.lang { /** * Constructs a {@code VirtualMachineError} with the specified * detail message and cause. <p>Note that the detail message * associated with {@code cause} is <i>not</i> automatically * incorporated in this error's detail message. * * @param {string} message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param {java.lang.Throwable} cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.8 * @class * @extends java.lang.Error * @author Frank Yellin */ abstract class VirtualMachineError extends Error { static serialVersionUID: number; constructor(message?: any, cause?: any); } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Exception.html">the * official Java API doc</a> for details. * @param {string} message * @param {java.lang.Throwable} cause * @class * @extends java.lang.Throwable */ class Exception extends Error { constructor(message?: any, cause?: any, enableSuppression?: any, writableStackTrace?: any); } } declare namespace java.lang { /** * For JRE compatibility. * @class */ class Void { constructor(); } } declare namespace java.lang { class IllegalAccessError extends Error { constructor(message?: any, cause?: any); } } declare namespace java.lang.reflect { /** * This interface makes {@link java.lang.reflect.Type} available to GWT clients. * * @see java.lang.reflect.Type * @class */ interface Type { } } declare namespace java.lang.reflect { class Array { constructor(); static newInstance(componentType: any, length: number): any; } } declare namespace java.lang { /** * Abstracts the notion of a sequence of characters. * @class */ interface CharSequence { charAt(index: number): string; length(): number; subSequence(start: number, end: number): any; } } declare namespace java.lang { } declare namespace java.lang { class NoSuchMethodError extends Error { constructor(message?: any, cause?: any); } } declare namespace java.lang { /** * An interface used a basis for implementing custom ordering. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html">[Sun * docs]</a> * * @param <T> the type to compare to. * @class */ interface Comparable<T> { compareTo(other: T): number; } } declare namespace java.lang.annotation { } declare namespace java.lang.annotation { /** * Enumerates types of declared elements in a Java program <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/annotation/ElementType.html">[Sun * docs]</a>. * @enum * @property {java.lang.annotation.ElementType} ANNOTATION_TYPE * @property {java.lang.annotation.ElementType} CONSTRUCTOR * @property {java.lang.annotation.ElementType} FIELD * @property {java.lang.annotation.ElementType} LOCAL_VARIABLE * @property {java.lang.annotation.ElementType} METHOD * @property {java.lang.annotation.ElementType} PACKAGE * @property {java.lang.annotation.ElementType} PARAMETER * @property {java.lang.annotation.ElementType} TYPE * @class */ enum ElementType { ANNOTATION_TYPE = 0, CONSTRUCTOR = 1, FIELD = 2, LOCAL_VARIABLE = 3, METHOD = 4, PACKAGE = 5, PARAMETER = 6, TYPE = 7 } } declare namespace java.lang.annotation { } declare namespace java.lang.annotation { /** * Enumerates annotation retention policies <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/annotation/RetentionPolicy.html">[Sun * docs]</a>. * @enum * @property {java.lang.annotation.RetentionPolicy} CLASS * @property {java.lang.annotation.RetentionPolicy} RUNTIME * @property {java.lang.annotation.RetentionPolicy} SOURCE * @class */ enum RetentionPolicy { CLASS = 0, RUNTIME = 1, SOURCE = 2 } } declare namespace java.lang.annotation { } declare namespace java.lang.annotation { /** * Indicates the annotation parser determined the annotation was malformed when * reading from the class file <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/annotation/AnnotationFormatError.html">[Sun * docs]</a>. * @class * @extends java.lang.Error */ class AnnotationFormatError extends Error { constructor(); } } declare namespace java.lang.annotation { } declare namespace java.lang.annotation { /** * Base interface for all annotation types <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/annotation/Annotation.html">[Sun * docs]</a>. * @class */ interface Annotation { annotationType(): any; } } declare namespace java.lang { /** * Generally unsupported. This class is provided so that the GWT compiler can * choke down class literal references. * <p> * NOTE: The code in this class is very sensitive and should keep its * dependencies upon other classes to a minimum. * * @param <T> * the type of the object * @class */ class Class<T> implements java.lang.reflect.Type { static constructors: Array<Function>; static constructors_$LI$(): Array<Function>; static classes: Array<any>; static classes_$LI$(): Array<any>; static getConstructorForClass(clazz: any): Function; static getClassForConstructor(constructor: Function): any; static mapConstructorToClass(constructor: Function, clazz: any): void; static PRIMITIVE: number; static INTERFACE: number; static ARRAY: number; static ENUM: number; /** * Create a Class object for an array. * <p> * * Arrays are not registered in the prototype table and get the class * literal explicitly at construction. * <p> * @param {java.lang.Class} leafClass * @param {number} dimensions * @return {java.lang.Class} * @private */ static getClassLiteralForArray<T>(leafClass: any, dimensions: number): any; createClassLiteralForArray(dimensions: number): any; /** * Create a Class object for a class. * * @skip * @param {string} packageName * @param {string} compoundClassName * @param {string} typeId * @param {java.lang.Class} superclass * @return {java.lang.Class} */ static createForClass<T>(packageName: string, compoundClassName: string, typeId: string, superclass: any): any; /** * Create a Class object for an enum. * * @skip * @param {string} packageName * @param {string} compoundClassName * @param {string} typeId * @param {java.lang.Class} superclass * @param {Function} enumConstantsFunc * @param {Function} enumValueOfFunc * @return {java.lang.Class} */ static createForEnum<T>(packageName: string, compoundClassName: string, typeId: string, superclass: any, enumConstantsFunc: Function, enumValueOfFunc: Function): any; /** * Create a Class object for an interface. * * @skip * @param {string} packageName * @param {string} compoundClassName * @return {java.lang.Class} */ static createForInterface<T>(packageName: string, compoundClassName: string): any; /** * Create a Class object for a primitive. * * @skip * @param {string} className * @param {string} primitiveTypeId * @return {java.lang.Class} */ static createForPrimitive(className: string, primitiveTypeId: string): any; /** * Used by {@link WebModePayloadSink} to create uninitialized instances. * @param {java.lang.Class} clazz * @return {*} */ static getPrototypeForClass(clazz: any): any; /** * Creates the class object for a type and initiliazes its fields. * @param {string} packageName * @param {string} compoundClassName * @param {string} typeId * @return {java.lang.Class} * @private */ static createClassObject<T>(packageName: string, compoundClassName: string, typeId: string): any; /** * Initiliazes {@code clazz} names from metadata. * <p> * Written in JSNI to minimize dependencies (on String.+). * @param {java.lang.Class} clazz * @private */ static initializeNames(clazz: any): void; /** * Sets the class object for primitives. * <p> * Written in JSNI to minimize dependencies (on (String)+). * @param {java.lang.Class} clazz * @param {Object} primitiveTypeId */ static synthesizePrimitiveNamesFromTypeId(clazz: any, primitiveTypeId: Object): void; enumValueOfFunc: Function; modifiers: number; componentType: any; enumConstantsFunc: Function; enumSuperclass: any; superclass: any; simpleName: string; typeName: string; canonicalName: string; packageName: string; compoundName: string; typeId: string; arrayLiterals: any[]; sequentialId: number; static nextSequentialId: number; constructor(); desiredAssertionStatus(): boolean; ensureNamesAreInitialized(): void; getCanonicalName(): string; getComponentType(): any; getEnumConstants(): T[]; getName(): string; getSimpleName(): string; getSuperclass(): any; isArray(): boolean; isEnum(): boolean; isInterface(): boolean; isPrimitive(): boolean; /** * * @return {string} */ toString(): string; /** * Used by Enum to allow getSuperclass() to be pruned. * @return {java.lang.Class} */ getEnumSuperclass(): any; } } declare namespace java.lang { class ThreadLocal<T> { value: T; initialValue(): T; get(): T; set(value: T): void; remove(): void; childValue(parentValue: T): T; constructor(); } } declare namespace java.lang { } declare namespace java.lang { /** * Indicates that a class implements <code>clone()</code>. * @class */ interface Cloneable { } } declare namespace java.lang { /** * A base class to share implementation between {@link StringBuffer} and {@link StringBuilder}. * <p> * Most methods will give expected performance results. Exception is {@link #setCharAt(int, char)}, * which is O(n), and thus should not be used many times on the same <code>StringBuffer</code>. * @param {string} string * @class */ abstract class AbstractStringBuilder { string: string; constructor(string: string); length(): number; setLength(newLength: number): void; capacity(): number; ensureCapacity(ignoredCapacity: number): void; trimToSize(): void; charAt(index: number): string; getChars(srcStart: number, srcEnd: number, dst: string[], dstStart: number): void; /** * Warning! This method is <b>much</b> slower than the JRE implementation. If you need to do * character level manipulation, you are strongly advised to use a char[] directly. * @param {number} index * @param {string} x */ setCharAt(index: number, x: string): void; subSequence(start: number, end: number): any; substring$int(begin: number): string; substring$int$int(begin: number, end: number): string; substring(begin?: any, end?: any): string; indexOf$java_lang_String(x: string): number; indexOf$java_lang_String$int(x: string, start: number): number; indexOf(x?: any, start?: any): number; lastIndexOf$java_lang_String(s: string): number; lastIndexOf$java_lang_String$int(s: string, start: number): number; lastIndexOf(s?: any, start?: any): number; /** * * @return {string} */ toString(): string; append0(x: any, start: number, end: number): void; appendCodePoint0(x: number): void; replace0(start: number, end: number, toInsert: string): void; reverse0(): void; static swap(buffer: string[], f: number, s: number): void; } } declare namespace java.lang { /** * The first-class representation of an enumeration. * * @param <E> * @class */ abstract class Enum<E extends java.lang.Enum<E>> implements java.lang.Comparable<E>, java.io.Serializable { static valueOf$java_lang_Class$java_lang_String<T extends java.lang.Enum<T>>(enumType: any, name: string): T; static valueOf<T0 = any>(enumType?: any, name?: any): any; static createValueOfMap<T extends java.lang.Enum<T>>(enumConstants: T[]): Object; static valueOf$def_js_Object$java_lang_String<T extends java.lang.Enum<T>>(map: Object, name: string): T; static get0<T extends java.lang.Enum<T>>(map: Object, name: string): T; static invokeValueOf<T extends java.lang.Enum<T>>(enumValueOfFunc: Function, name: string): T; static put0<T extends java.lang.Enum<T>>(map: Object, name: string, value: T): void; __name: string; __ordinal: number; constructor(name: string, ordinal: number); compareTo$java_lang_Enum(other: E): number; /** * * @param {java.lang.Enum} other * @return {number} */ compareTo(other?: any): number; getDeclaringClass(): any; name(): string; ordinal(): number; /** * * @return {string} */ toString(): string; } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/javase/6/docs/api/java/lang/Appendable.html">the * official Java API doc</a> for details. * @class */ interface Appendable { append(charSquence?: any, start?: any, end?: any): java.lang.Appendable; } } declare namespace java.lang { /** * Encapsulates an action for later execution. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runnable.html">[Sun * docs]</a> * * <p> * This interface is provided only for JRE compatibility. GWT does not support * multithreading. * </p> * @class */ interface Runnable { (): any; } } declare namespace java.lang { } declare namespace java.lang { } declare namespace java.beans { /** * General-purpose beans control methods. GWT only supports a limited subset of these methods. Only * the documented methods are available. * @class */ class Beans { /** * @return {boolean} <code>true</code> if we are running in the design time mode. */ static isDesignTime(): boolean; } } declare namespace java.beans { class PropertyDescriptor { getPropertyType(): any; } } declare namespace java.nio.file { class Paths { constructor(); static get(...paths: string[]): java.nio.file.Path; } } declare namespace java.nio { class ByteOrder { static BIG_ENDIAN: ByteOrder; static BIG_ENDIAN_$LI$(): ByteOrder; static LITTLE_ENDIAN: ByteOrder; static LITTLE_ENDIAN_$LI$(): ByteOrder; constructor(); /** * * @return {string} */ toString(): string; static nativeOrder(): ByteOrder; } namespace ByteOrder { class NativeInstanceHolder { static INSTANCE: java.nio.ByteOrder; static nativeOrderTester(): java.nio.ByteOrder; constructor(); } } } declare namespace java.nio { abstract class Buffer { _capacity: number; readOnly: boolean; _position: number; _limit: number; _mark: number; constructor(capacity: number, readOnly: boolean); abstract array(): any; arrayOffset(): number; capacity(): number; clear(): Buffer; flip(): Buffer; hasArray(): boolean; hasRemaining(): boolean; isDirect(): boolean; isReadOnly(): boolean; limit$(): number; limit$int(newLimit: number): Buffer; limit(newLimit?: any): any; mark(): Buffer; position$(): number; position$int(newPosition: number): Buffer; position(newPosition?: any): any; remaining(): number; reset(): Buffer; rewind(): Buffer; } } declare namespace java.nio.charset { /** * A minimal emulation of {@link Charset}. * @class */ abstract class Charset implements java.lang.Comparable<Charset> { static availableCharsets(): java.util.SortedMap<string, Charset>; static forName(charsetName: string): Charset; static createLegalCharsetNameRegex(): RegExp; __name: string; constructor(name: string, aliasesIgnored: string[]); name(): string; compareTo$java_nio_charset_Charset(that: Charset): number; /** * * @param {java.nio.charset.Charset} that * @return {number} */ compareTo(that?: any): number; /** * * @return {number} */ hashCode(): number; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {string} */ toString(): string; } namespace Charset { class AvailableCharsets { static CHARSETS: java.util.SortedMap<string, java.nio.charset.Charset>; constructor(); } } } declare namespace java.text { /** * A basic implementation for Java collators. * * @author Renaud Pawlak * @class */ class Collator { static collator: Collator; static getInstance(): Collator; /** * * @param {*} a * @param {*} b * @return {number} */ compare(a: any, b: any): number; constructor(); } } declare namespace java.text { class Normalizer { static normalize(src: any, form: Normalizer.Form): string; } namespace Normalizer { enum Form { /** * Canonical decomposition. */ NFD = 0, /** * Canonical decomposition, followed by canonical composition. */ NFC = 1, /** * Compatibility decomposition. */ NFKD = 2, /** * Compatibility decomposition, followed by canonical composition. */ NFKC = 3 } } } declare namespace java.text { /** * Create a new ParsePosition with the given initial index. * * @param {number} index initial index * @class * @author Mark Davis */ class ParsePosition { /** * Input: the place you start parsing. * <br>Output: position where the parse stopped. * This is designed to be used serially, * with each call setting index up for the next one. */ index: number; errorIndex: number; /** * Retrieve the current parse position. On input to a parse method, this * is the index of the character at which parsing will begin; on output, it * is the index of the character following the last character parsed. * * @return {number} the current parse position */ getIndex(): number; /** * Set the current parse position. * * @param {number} index the current parse position */ setIndex(index: number): void; constructor(index: number); /** * Set the index at which a parse error occurred. Formatters * should set this before returning an error code from their * parseObject method. The default value is -1 if this is not set. * * @param {number} ei the index at which an error occurred * @since 1.2 */ setErrorIndex(ei: number): void; /** * Retrieve the index at which an error occurred, or -1 if the * error index has not been set. * * @return {number} the index at which an error occurred * @since 1.2 */ getErrorIndex(): number; /** * Overrides equals * @param {*} obj * @return {boolean} */ equals(obj: any): boolean; /** * Returns a hash code for this ParsePosition. * @return {number} a hash code value for this object */ hashCode(): number; /** * Return a string representation of this ParsePosition. * @return {string} a string representation of this object */ toString(): string; } } /** * Declares equals and hashCode on JavaScript objects, for compilation. * @class */ interface Object { equals(object: Object): boolean; } declare namespace javaemul.internal.stream { /** * @author Władysław Kargul * @param {*} previous * @class * @extends javaemul.internal.stream.TerminalStreamRow */ class StreamRowEnd extends javaemul.internal.stream.TerminalStreamRow { previous: javaemul.internal.stream.StreamRow; constructor(previous: javaemul.internal.stream.StreamRow); chain(next: javaemul.internal.stream.StreamRow): void; item(a: any): boolean; } } declare namespace javaemul.internal.stream { class StreamRowAllFilter extends javaemul.internal.stream.TerminalStreamRow { predicate: any; predicateValue: boolean; attempts: number; getPredicateValue(): boolean; constructor(predicate: any); item(a: any): boolean; } } declare namespace javaemul.internal.stream { class StreamRowOnceFilter extends javaemul.internal.stream.TerminalStreamRow { predicate: any; predicateValue: boolean; firstMatch: java.util.Optional<any>; getFirstMatch(): java.util.Optional<any>; getPredicateValue(): boolean; constructor(predicate: any); item(a: any): boolean; } } declare namespace javaemul.internal.stream { class StreamRowReduce extends javaemul.internal.stream.TerminalStreamRow { result: java.util.Optional<any>; operator: any; constructor(result: java.util.Optional<any>, operator: any); getResult(): java.util.Optional<any>; item(a: any): boolean; } } declare namespace javaemul.internal.stream { class StreamRowCount extends javaemul.internal.stream.TerminalStreamRow { count: number; getCount(): number; item(a: any): boolean; constructor(); } } declare namespace javaemul.internal.stream { class StreamRowCollector extends javaemul.internal.stream.TransientStreamRow { collection: java.util.Collection<any>; constructor(collection: java.util.Collection<any>); item(a: any): boolean; end(): void; } } declare namespace javaemul.internal.stream { class StreamRowMap extends javaemul.internal.stream.TransientStreamRow { map: any; constructor(map: any); item(a: any): boolean; end(): void; } } declare namespace javaemul.internal.stream { class StreamRowFilter extends javaemul.internal.stream.TransientStreamRow { predicate: any; constructor(predicate: any); item(a: any): boolean; end(): void; } } declare namespace javaemul.internal.stream { class StreamRowFilterFlop extends javaemul.internal.stream.TransientStreamRow { predicate: any; constructor(predicate: any); item(a: any): boolean; end(): void; } } declare namespace javaemul.internal.stream { class StreamRowFlatMap extends javaemul.internal.stream.TransientStreamRow { flatMap: (p1: any) => java.util.stream.Stream<any>; constructor(flatMap: any); item(a: any): boolean; end(): void; } } declare namespace javaemul.internal { /** * Wraps a primitive <code>double</code> as an object. * @param {number} value * @class * @extends javaemul.internal.NumberHelper */ class DoubleHelper extends javaemul.internal.NumberHelper implements java.lang.Comparable<DoubleHelper> { static MAX_VALUE: number; static MIN_VALUE: number; static MIN_NORMAL: number; static MAX_EXPONENT: number; static MIN_EXPONENT: number; static NaN: number; static NEGATIVE_INFINITY: number; static POSITIVE_INFINITY: number; static SIZE: number; static POWER_512: number; static POWER_MINUS_512: number; static POWER_256: number; static POWER_MINUS_256: number; static POWER_128: number; static POWER_MINUS_128: number; static POWER_64: number; static POWER_MINUS_64: number; static POWER_52: number; static POWER_MINUS_52: number; static POWER_32: number; static POWER_MINUS_32: number; static POWER_31: number; static POWER_20: number; static POWER_MINUS_20: number; static POWER_16: number; static POWER_MINUS_16: number; static POWER_8: number; static POWER_MINUS_8: number; static POWER_4: number; static POWER_MINUS_4: number; static POWER_2: number; static POWER_MINUS_2: number; static POWER_1: number; static POWER_MINUS_1: number; static POWER_MINUS_1022: number; static compare(x: number, y: number): number; static doubleToLongBits(value: number): number; /** * @skip Here for shared implementation with Arrays.hashCode * @param {number} d * @return {number} */ static hashCode(d: number): number; static isInfinite(x: number): boolean; static isNaN(x: number): boolean; static longBitsToDouble(bits: number): number; static parseDouble(s: string): number; static toString(b: number): string; static valueOf$double(d: number): number; static valueOf$java_lang_String(s: string): number; static valueOf(s?: any): number; constructor(s?: any); /** * * @return {number} */ byteValue(): number; compareTo$javaemul_internal_DoubleHelper(b: DoubleHelper): number; /** * * @param {javaemul.internal.DoubleHelper} b * @return {number} */ compareTo(b?: any): number; /** * * @return {number} */ doubleValue(): number; static unsafeCast(instance: any): number; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ floatValue(): number; /** * Performance caution: using Double objects as map keys is not recommended. * Using double values as keys is generally a bad idea due to difficulty * determining exact equality. In addition, there is no efficient JavaScript * equivalent of <code>doubleToIntBits</code>. As a result, this method * computes a hash code by truncating the whole number portion of the * double, which may lead to poor performance for certain value sets if * Doubles are used as keys in a {@link java.util.HashMap}. * @return {number} */ hashCode(): number; /** * * @return {number} */ intValue(): number; isInfinite(): boolean; isNaN(): boolean; /** * * @return {number} */ longValue(): number; /** * * @return {number} */ shortValue(): number; /** * * @return {string} */ toString(): string; } namespace DoubleHelper { class PowersTable { static powers: number[]; static powers_$LI$(): number[]; static invPowers: number[]; static invPowers_$LI$(): number[]; constructor(); } } } declare namespace javaemul.internal { /** * Wraps a primitive <code>short</code> as an object. * @param {number} value * @class * @extends javaemul.internal.NumberHelper */ class ShortHelper extends javaemul.internal.NumberHelper implements java.lang.Comparable<ShortHelper> { static MIN_VALUE: number; static MIN_VALUE_$LI$(): number; static MAX_VALUE: number; static MAX_VALUE_$LI$(): number; static SIZE: number; static TYPE: any; static TYPE_$LI$(): any; static compare(x: number, y: number): number; static decode(s: string): number; /** * @skip Here for shared implementation with Arrays.hashCode * @param {number} s * @return {number} */ static hashCode(s: number): number; static parseShort(s: string, radix?: number): number; static reverseBytes(s: number): number; static toString(b: number): string; static valueOf$short(s: number): number; static valueOf$java_lang_String(s: string): number; static valueOf$java_lang_String$int(s: string, radix: number): number; static valueOf(s?: any, radix?: any): number; value: number; constructor(s?: any); /** * * @return {number} */ byteValue(): number; compareTo$javaemul_internal_ShortHelper(b: ShortHelper): number; /** * * @param {javaemul.internal.ShortHelper} b * @return {number} */ compareTo(b?: any): number; /** * * @return {number} */ doubleValue(): number; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ floatValue(): number; /** * * @return {number} */ hashCode(): number; /** * * @return {number} */ intValue(): number; /** * * @return {number} */ longValue(): number; /** * * @return {number} */ shortValue(): number; /** * * @return {string} */ toString(): string; } namespace ShortHelper { /** * Use nested class to avoid clinit on outer. * @class */ class BoxedValues { static boxedValues: number[]; static boxedValues_$LI$(): number[]; constructor(); } } } declare namespace javaemul.internal { /** * Wraps native <code>byte</code> as an object. * @param {number} value * @class * @extends javaemul.internal.NumberHelper */ class ByteHelper extends javaemul.internal.NumberHelper implements java.lang.Comparable<ByteHelper> { static MIN_VALUE: number; static MIN_VALUE_$LI$(): number; static MAX_VALUE: number; static MAX_VALUE_$LI$(): number; static SIZE: number; static TYPE: any; static TYPE_$LI$(): any; static compare(x: number, y: number): number; static decode(s: string): number; /** * @skip * * Here for shared implementation with Arrays.hashCode * @param {number} b * @return {number} */ static hashCode(b: number): number; static parseByte(s: string, radix?: number): number; static toString(b: number): string; static valueOf$byte(b: number): number; static valueOf$java_lang_String(s: string): number; static valueOf$java_lang_String$int(s: string, radix: number): number; static valueOf(s?: any, radix?: any): number; value: number; constructor(s?: any); /** * * @return {number} */ byteValue(): number; compareTo$javaemul_internal_ByteHelper(b: ByteHelper): number; /** * * @param {javaemul.internal.ByteHelper} b * @return {number} */ compareTo(b?: any): number; /** * * @return {number} */ doubleValue(): number; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ floatValue(): number; /** * * @return {number} */ hashCode(): number; /** * * @return {number} */ intValue(): number; /** * * @return {number} */ longValue(): number; /** * * @return {number} */ shortValue(): number; /** * * @return {string} */ toString(): string; } namespace ByteHelper { /** * Use nested class to avoid clinit on outer. * @class */ class BoxedValues { static boxedValues: number[]; static boxedValues_$LI$(): number[]; constructor(); } } } declare namespace javaemul.internal { /** * Wraps a primitive <code>float</code> as an object. * @param {number} value * @class * @extends javaemul.internal.NumberHelper */ class FloatHelper extends javaemul.internal.NumberHelper implements java.lang.Comparable<FloatHelper> { static MAX_VALUE: number; static MIN_VALUE: number; static MAX_EXPONENT: number; static MIN_EXPONENT: number; static MIN_NORMAL: number; static NaN: number; static NEGATIVE_INFINITY: number; static POSITIVE_INFINITY: number; static SIZE: number; static POWER_31_INT: number; static compare(x: number, y: number): number; static floatToIntBits(value: number): number; /** * @skip Here for shared implementation with Arrays.hashCode. * @param {number} f * @return {number} hash value of float (currently just truncated to int) */ static hashCode(f: number): number; static intBitsToFloat(bits: number): number; static isInfinite(x: number): boolean; static isNaN(x: number): boolean; static parseFloat(s: string): number; static toString(b: number): string; static valueOf$float(f: number): number; static valueOf$java_lang_String(s: string): number; static valueOf(s?: any): number; value: number; constructor(s?: any); /** * * @return {number} */ byteValue(): number; compareTo$javaemul_internal_FloatHelper(b: FloatHelper): number; /** * * @param {javaemul.internal.FloatHelper} b * @return {number} */ compareTo(b?: any): number; /** * * @return {number} */ doubleValue(): number; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ floatValue(): number; /** * Performance caution: using Float objects as map keys is not recommended. * Using floating point values as keys is generally a bad idea due to * difficulty determining exact equality. In addition, there is no efficient * JavaScript equivalent of <code>floatToIntBits</code>. As a result, this * method computes a hash code by truncating the whole number portion of the * float, which may lead to poor performance for certain value sets if * Floats are used as keys in a {@link java.util.HashMap}. * @return {number} */ hashCode(): number; /** * * @return {number} */ intValue(): number; isInfinite(): boolean; isNaN(): boolean; /** * * @return {number} */ longValue(): number; /** * * @return {number} */ shortValue(): number; /** * * @return {string} */ toString(): string; } } declare namespace javaemul.internal { /** * Wraps a primitive <code>int</code> as an object. * @param {number} value * @class * @extends javaemul.internal.NumberHelper */ class IntegerHelper extends javaemul.internal.NumberHelper implements java.lang.Comparable<IntegerHelper> { static MAX_VALUE: number; static MIN_VALUE: number; static SIZE: number; static bitCount(x: number): number; static compare(x: number, y: number): number; static decode(s: string): number; /** * @skip * * Here for shared implementation with Arrays.hashCode * @param {number} i * @return {number} */ static hashCode(i: number): number; static highestOneBit(i: number): number; static lowestOneBit(i: number): number; static numberOfLeadingZeros(i: number): number; static numberOfTrailingZeros(i: number): number; static parseInt(s: string, radix?: number): number; static reverse(i: number): number; static reverseBytes(i: number): number; static rotateLeft(i: number, distance: number): number; static rotateRight(i: number, distance: number): number; static signum(i: number): number; static toBinaryString(value: number): string; static toHexString(value: number): string; static toOctalString(value: number): string; static toString$int(value: number): string; static toString$int$int(value: number, radix: number): string; static toString(value?: any, radix?: any): string; static valueOf$int(i: number): number; static valueOf$java_lang_String(s: string): number; static valueOf$java_lang_String$int(s: string, radix: number): number; static valueOf(s?: any, radix?: any): any; static toRadixString(value: number, radix: number): string; static toUnsignedRadixString(value: number, radix: number): string; value: number; constructor(s?: any); /** * * @return {number} */ byteValue(): number; compareTo$javaemul_internal_IntegerHelper(b: IntegerHelper): number; /** * * @param {javaemul.internal.IntegerHelper} b * @return {number} */ compareTo(b?: any): number; /** * * @return {number} */ doubleValue(): number; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ floatValue(): number; /** * * @return {number} */ hashCode(): number; /** * * @return {number} */ intValue(): number; /** * * @return {number} */ longValue(): number; /** * * @return {number} */ shortValue(): number; /** * * @return {string} */ toString(): string; static getInteger(nm: string): number; } namespace IntegerHelper { /** * Use nested class to avoid clinit on outer. * @class */ class BoxedValues { static boxedValues: number[]; static boxedValues_$LI$(): number[]; constructor(); } /** * Use nested class to avoid clinit on outer. * @class */ class ReverseNibbles { /** * A fast-lookup of the reversed bits of all the nibbles 0-15. Used to * implement {@link #reverse(int)}. */ static reverseNibbles: number[]; static reverseNibbles_$LI$(): number[]; constructor(); } } } declare namespace javaemul.internal { /** * Wraps a primitive <code>long</code> as an object. * @param {number} value * @class * @extends javaemul.internal.NumberHelper */ class LongHelper extends javaemul.internal.NumberHelper implements java.lang.Comparable<LongHelper> { static MAX_VALUE: number; static MIN_VALUE: number; static SIZE: number; static bitCount(i: number): number; static compare(x: number, y: number): number; static decode(s: string): number; /** * @skip Here for shared implementation with Arrays.hashCode * @param {number} l * @return {number} */ static hashCode(l: number): number; static highestOneBit(i: number): number; static lowestOneBit(i: number): number; static numberOfLeadingZeros(i: number): number; static numberOfTrailingZeros(i: number): number; static parseLong(s: string, radix?: number): number; static reverse(i: number): number; static reverseBytes(i: number): number; static rotateLeft(i: number, distance: number): number; static rotateRight(i: number, distance: number): number; static signum(i: number): number; static toBinaryString(value: number): string; static toHexString(value: number): string; static toOctalString(value: number): string; static toString$long(value: number): string; static toString$long$int(value: number, intRadix: number): string; static toString(value?: any, intRadix?: any): string; static valueOf$long(i: number): number; static valueOf$java_lang_String(s: string): number; static valueOf$java_lang_String$int(s: string, radix: number): number; static valueOf(s?: any, radix?: any): number; static toPowerOfTwoUnsignedString(value: number, shift: number): string; value: number; constructor(s?: any); /** * * @return {number} */ byteValue(): number; compareTo$javaemul_internal_LongHelper(b: LongHelper): number; /** * * @param {javaemul.internal.LongHelper} b * @return {number} */ compareTo(b?: any): number; /** * * @return {number} */ doubleValue(): number; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ floatValue(): number; /** * * @return {number} */ hashCode(): number; /** * * @return {number} */ intValue(): number; /** * * @return {number} */ longValue(): number; /** * * @return {number} */ shortValue(): number; /** * * @return {string} */ toString(): string; } namespace LongHelper { /** * Use nested class to avoid clinit on outer. * @class */ class BoxedValues { static boxedValues: number[]; static boxedValues_$LI$(): number[]; constructor(); } } } declare namespace java.util { class Scanner implements java.util.Iterator<string>, java.io.Closeable { remove(): void; forEachRemaining(consumer: (p1: any) => void): void; static digit: string; static decimalSeparator: string; static numeral: string; static numeral_$LI$(): string; static decimalNumeral: string; static decimalNumeral_$LI$(): string; static exponent: string; static exponent_$LI$(): string; static decimal: string; static decimal_$LI$(): string; static hexFloat: string; static nonNumber: string; static signedNonNumber: string; static signedNonNumber_$LI$(): string; static booleanPattern: java.util.regex.Pattern; static booleanPattern_$LI$(): java.util.regex.Pattern; static integerPattern: java.util.regex.Pattern; static integerPattern_$LI$(): java.util.regex.Pattern; static floatPattern: java.util.regex.Pattern; static floatPattern_$LI$(): java.util.regex.Pattern; static endLinePattern: java.util.regex.Pattern; static endLinePattern_$LI$(): java.util.regex.Pattern; static whiteSpacePattern: java.util.regex.Pattern; static whiteSpacePattern_$LI$(): java.util.regex.Pattern; reader: java.io.Reader; currentDelimiter: java.util.regex.Pattern; matcher: java.util.regex.Matcher; buf: string[]; bufferFilledLength: number; currentPosition: number; nextTokenStart: number; nextDelimiterStart: number; nextDelimiterEnd: number; nextDelimiterWithPattern: java.util.regex.Pattern; defaultRadix: number; closed: boolean; constructor(string?: any); /** * */ close(): void; delimiter(): java.util.regex.Pattern; useDelimiter$java_lang_String(currentDelimiter: string): Scanner; useDelimiter(currentDelimiter?: any): Scanner; useDelimiter$java_util_regex_Pattern(currentDelimiter: java.util.regex.Pattern): Scanner; hasNext$(): boolean; searchNextTo$java_util_regex_Pattern(pattern: java.util.regex.Pattern): void; searchNextTo$java_util_regex_Pattern$boolean(pattern: java.util.regex.Pattern, canBeEmpty: boolean): void; searchNextTo(pattern?: any, canBeEmpty?: any): any; /** * * @return {string} */ next(): string; hasNext$java_util_regex_Pattern(pattern: java.util.regex.Pattern): boolean; hasNext(pattern?: any): boolean; hasNext$java_lang_String(pattern: string): boolean; radix(): number; hasNextBoolean(): boolean; nextBoolean(): boolean; hasNextByte(): boolean; nextByte(): number; hasNextDouble(): boolean; nextDouble(): number; hasNextFloat(): boolean; nextFloat(): number; hasNextInt(): boolean; nextInt(): number; hasNextLine(): boolean; nextLine(): string; hasNextLong(): boolean; nextLong(): number; hasNextShort(): boolean; nextShort(): number; reset(): Scanner; skip$java_lang_String(pattern: string): Scanner; skip(pattern?: any): Scanner; skip$java_util_regex_Pattern(pattern: java.util.regex.Pattern): Scanner; findInLine$java_lang_String(pattern: string): string; findInLine(pattern?: any): string; findInLine$java_util_regex_Pattern(pattern: java.util.regex.Pattern): string; match(): java.util.regex.MatchResult; } } declare namespace java.util { /** * Skeletal implementation of the Set interface. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/AbstractSet.html">[Sun * docs]</a> * * @param <E> the element type. * @class * @extends java.util.AbstractCollection */ abstract class AbstractSet<E> extends java.util.AbstractCollection<E> implements java.util.Set<E> { /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ hashCode(): number; /** * * @param {*} c * @return {boolean} */ removeAll(c: java.util.Collection<any>): boolean; abstract iterator(): any; abstract size(): any; constructor(); } } declare namespace java.util { /** * Skeletal implementation of the List interface. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/AbstractList.html">[Sun * docs]</a> * * @param <E> the element type. * @extends java.util.AbstractCollection * @class */ abstract class AbstractList<E> extends java.util.AbstractCollection<E> implements java.util.List<E> { sort(c: java.util.Comparator<any>): void; modCount: number; constructor(); add$java_lang_Object(obj: E): boolean; add$int$java_lang_Object(index: number, element: E): void; /** * * @param {number} index * @param {*} element */ add(index?: any, element?: any): any; addAll$int$java_util_Collection(index: number, c: java.util.Collection<any>): boolean; /** * * @param {number} index * @param {*} c * @return {boolean} */ addAll(index?: any, c?: any): boolean; /** * */ clear(): void; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @param {number} index * @return {*} */ abstract get(index: number): E; /** * * @return {number} */ hashCode(): number; /** * * @param {*} toFind * @return {number} */ indexOf(toFind: any): number; /** * * @return {*} */ iterator(): java.util.Iterator<E>; /** * * @param {*} toFind * @return {number} */ lastIndexOf(toFind: any): number; listIterator$(): java.util.ListIterator<E>; listIterator$int(from: number): java.util.ListIterator<E>; /** * * @param {number} from * @return {*} */ listIterator(from?: any): java.util.ListIterator<E>; remove$int(index: number): E; /** * * @param {number} index * @return {*} */ remove(index?: any): any; /** * * @param {number} index * @param {*} o * @return {*} */ set(index: number, o: E): E; /** * * @param {number} fromIndex * @param {number} toIndex * @return {*} */ subList(fromIndex: number, toIndex: number): java.util.List<E>; removeRange(fromIndex: number, endIndex: number): void; abstract size(): any; } namespace AbstractList { class IteratorImpl implements java.util.Iterator<any> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; i: number; last: number; constructor(__parent: any); /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): any; /** * */ remove(): void; } class SubList<E> extends java.util.AbstractList<E> { wrapped: java.util.List<E>; fromIndex: number; __size: number; constructor(wrapped: java.util.List<E>, fromIndex: number, toIndex: number); add$int$java_lang_Object(index: number, element: E): void; /** * * @param {number} index * @param {*} element */ add(index?: any, element?: any): any; /** * * @param {number} index * @return {*} */ get(index: number): E; remove$int(index: number): E; /** * * @param {number} index * @return {*} */ remove(index?: any): any; /** * * @param {number} index * @param {*} element * @return {*} */ set(index: number, element: E): E; /** * * @return {number} */ size(): number; } /** * Implementation of <code>ListIterator</code> for abstract lists. * @extends java.util.AbstractList.IteratorImpl * @class */ class ListIteratorImpl extends AbstractList.IteratorImpl implements java.util.ListIterator<any> { __parent: any; constructor(__parent: any, start?: any); /** * * @param {*} o */ add(o: any): void; /** * * @return {boolean} */ hasPrevious(): boolean; /** * * @return {number} */ nextIndex(): number; /** * * @return {*} */ previous(): any; /** * * @return {number} */ previousIndex(): number; /** * * @param {*} o */ set(o: any): void; } } } declare namespace java.util { /** * Skeletal implementation of the Queue interface. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/AbstractQueue.html">[Sun * docs]</a> * * @param <E> element type. * @extends java.util.AbstractCollection * @class */ abstract class AbstractQueue<E> extends java.util.AbstractCollection<E> implements java.util.Queue<E> { constructor(); /** * * @param {*} o * @return {boolean} */ add(o: E): boolean; /** * * @param {*} c * @return {boolean} */ addAll(c: java.util.Collection<any>): boolean; /** * */ clear(): void; /** * * @return {*} */ element(): E; /** * * @param {*} o * @return {boolean} */ abstract offer(o: E): boolean; /** * * @return {*} */ abstract peek(): E; /** * * @return {*} */ abstract poll(): E; /** * * @param {*} o * @return {boolean} */ remove(o?: any): any; remove$(): E; abstract iterator(): any; abstract size(): any; } } declare namespace java.util { /** * A {@link Deque} based on circular buffer that is implemented with an array and head/tail * pointers. Array deques have no capacity restrictions; they grow as necessary to support usage. * Null elements are prohibited. This class is likely to be faster than {@link Stack} * when used as a stack, and faster than {@link LinkedList} when used as a queue. * <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayDeque.html">ArrayDeque</a> * * @param <E> the element type. * @param {*} c * @class * @extends java.util.AbstractCollection */ class ArrayDeque<E> extends java.util.AbstractCollection<E> implements java.util.Deque<E>, java.lang.Cloneable { /** * The minimum capacity that we'll use for a newly created deque. * Must be a power of 2. */ static MIN_INITIAL_CAPACITY: number; static checkConcurrentModification(expression: boolean): void; /** * Returns best power-of-two array length to hold the given number of elements. * * @param {number} numElements the number of elements to hold * @return {number} * @private */ static nextArrayLength(numElements: number): number; /** * Returns a number that is greater than {@code num} and is a power of two. * If passed {@code num} is not positive integer or next power of two overflows then * returned value is non-positive. * E.g., if num == 32, returns 64. if num == 31, returns 32. * * @param {number} num positive integer. * @return {number} * @private */ static nextPowerOfTwo(num: number): number; /** * This field holds a JavaScript array. */ array: E[]; /** * The index of the element at the head of the deque (which is the * element that would be removed by remove() or pop()); or an * arbitrary number equal to tail if the deque is empty. */ head: number; /** * The index at which the next element would be added to the tail * of the deque (via addLast(E), add(E), or push(E)). */ tail: number; constructor(c?: any); /** * * @param {*} e * @return {boolean} */ add(e: E): boolean; /** * * @param {*} e */ addFirst(e: E): void; /** * * @param {*} e */ addLast(e: E): void; /** * */ clear(): void; clone(): any; contains$java_lang_Object(o: any): boolean; /** * * @return {*} */ descendingIterator(): java.util.Iterator<E>; /** * * @return {*} */ element(): E; /** * * @return {*} */ getFirst(): E; /** * * @return {*} */ getLast(): E; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<E>; /** * * @param {*} e * @return {boolean} */ offer(e: E): boolean; /** * * @param {*} e * @return {boolean} */ offerFirst(e: E): boolean; /** * * @param {*} e * @return {boolean} */ offerLast(e: E): boolean; /** * * @return {*} */ peek(): E; /** * * @return {*} */ peekFirst(): E; /** * * @return {*} */ peekLast(): E; /** * * @return {*} */ poll(): E; /** * * @return {*} */ pollFirst(): E; /** * * @return {*} */ pollLast(): E; /** * * @return {*} */ pop(): E; /** * * @param {*} e */ push(e: E): void; remove$(): E; remove$java_lang_Object(o: any): boolean; /** * * @return {*} */ removeFirst(): E; /** * * @param {*} o * @return {boolean} */ removeFirstOccurrence(o: any): boolean; /** * * @return {*} */ removeLast(): E; /** * * @param {*} o * @return {boolean} */ removeLastOccurrence(o: any): boolean; /** * * @return {number} */ size(): number; toArray$java_lang_Object_A<T>(out: T[]): T[]; /** * * @param {T[]} out * @return {T[]} */ toArray<T0 = any>(out?: any): any; contains$java_util_Iterator$java_lang_Object(it: java.util.Iterator<E>, o: any): boolean; contains(it?: any, o?: any): boolean; remove$java_util_Iterator$java_lang_Object(it: java.util.Iterator<E>, o: any): boolean; remove(it?: any, o?: any): any; peekFirstElement(): E; peekLastElement(): E; /** * Copies {@code count} ArrayDeque's elements to {@code dest} array. * The method is safe to use when ArrayDeque's array has been rolled over, * i.e. {@code head == tail}. * It is assumed that {@code count < size()}. * @param {java.lang.Object[]} dest * @param {number} count * @private */ copyElements(dest: any[], count: number): void; /** * Increase the capacity of this deque when full, i.e., * when head and tail have wrapped around to become equal. * @private */ ensureCapacity(): void; /** * Removes the element at the specified position in the elements array, * adjusting head and tail as necessary. This results in motion of * elements backwards or forwards in the array. * * @return {number} -1 if elements moved backwards (left-shifted); 1 if forwards (right-shifted). * @param {number} i * @private */ removeAtIndex(i: number): number; shiftLeftAtIndex(i: number): void; shiftRightAtIndex(i: number): void; } namespace ArrayDeque { class IteratorImpl implements java.util.Iterator<any> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; /** * Index of element to be returned by subsequent call to next. */ currentIndex: number; /** * Tail recorded at construction (also in remove), to stop * iterator and also to check for comodification. */ fence: number; /** * Index of element returned by most recent call to next. * Reset to -1 if element is deleted by a call to remove. */ lastIndex: number; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): any; /** * */ remove(): void; constructor(__parent: any); } class DescendingIteratorImpl implements java.util.Iterator<any> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; currentIndex: number; fence: number; lastIndex: number; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): any; /** * */ remove(): void; constructor(__parent: any); } } } declare namespace java.util { class Timer { static nextSerialNumber: number; name: string; timeouts: Array<java.util.TimerTask>; intervals: Array<java.util.TimerTask>; constructor(name?: any, daemon?: any); schedule$java_util_TimerTask$long(task: java.util.TimerTask, delay: number): void; schedule$java_util_TimerTask$java_util_Date(task: java.util.TimerTask, time: Date): void; schedule$java_util_TimerTask$long$long(task: java.util.TimerTask, delay: number, period: number): void; schedule$java_util_TimerTask$java_util_Date$long(task: java.util.TimerTask, time: Date, period: number): void; schedule(task?: any, time?: any, period?: any): any; scheduleAtFixedRate$java_util_TimerTask$long$long(task: java.util.TimerTask, delay: number, period: number): void; scheduleAtFixedRate$java_util_TimerTask$java_util_Date$long(task: java.util.TimerTask, time: Date, period: number): void; scheduleAtFixedRate(task?: any, time?: any, period?: any): any; cancel(): void; purge(): number; } namespace Timer { class Timer$0 extends java.util.TimerTask { private task; __parent: any; /** * */ run(): void; constructor(__parent: any, task: any); } } } declare namespace javaemul.internal { /** * Intrinsic string class. * @class */ class StringHelper { static CASE_INSENSITIVE_ORDER: java.util.Comparator<string>; static CASE_INSENSITIVE_ORDER_$LI$(): java.util.Comparator<string>; static copyValueOf$char_A(v: string[]): string; static copyValueOf$char_A$int$int(v: string[], offset: number, count: number): string; static copyValueOf(v?: any, offset?: any, count?: any): string; static valueOf$boolean(x: boolean): string; static valueOf$char(x: string): string; static valueOf$char_A$int$int(x: string[], offset: number, count: number): string; static valueOf(x?: any, offset?: any, count?: any): string; static fromCharCode(array: any[]): string; static valueOf$char_A(x: string[]): string; static valueOf$double(x: number): string; static valueOf$float(x: number): string; static valueOf$int(x: number): string; static valueOf$long(x: number): string; static valueOf$java_lang_Object(x: any): string; /** * This method converts Java-escaped dollar signs "\$" into * JavaScript-escaped dollar signs "$$", and removes all other lone * backslashes, which serve as escapes in Java but are passed through * literally in JavaScript. * * @skip * @param {string} replaceStr * @return {string} * @private */ static translateReplaceString(replaceStr: string): string; static compareTo(thisStr: string, otherStr: string): number; static getCharset(charsetName: string): java.nio.charset.Charset; static fromCodePoint(codePoint: number): string; static format(formatString: string, ...args: any[]): string; static join(delimiter: any, ...elements: any[]): string; constructor(); } } declare namespace java.sql { /** * An implementation of java.sql.Timestame. Derived from * http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Timestamp.html. This is * basically just regular Date decorated with a nanoseconds field. * @param {number} year * @param {number} month * @param {number} date * @param {number} hour * @param {number} minute * @param {number} second * @param {number} nano * @class * @extends java.util.Date */ class Timestamp extends java.util.Date { static valueOf(s: string): Timestamp; static padNine(value: number): string; /** * Stores the nanosecond resolution of the timestamp; must be kept in sync * with the sub-second part of Date.millis. */ nanos: number; constructor(year?: any, month?: any, date?: any, hour?: any, minute?: any, second?: any, nano?: any); after$java_sql_Timestamp(ts: Timestamp): boolean; after(ts?: any): boolean; before$java_sql_Timestamp(ts: Timestamp): boolean; before(ts?: any): boolean; compareTo$java_util_Date(o: java.util.Date): number; compareTo$java_sql_Timestamp(o: Timestamp): number; compareTo(o?: any): number; equals$java_lang_Object(ts: any): boolean; equals$java_sql_Timestamp(ts: Timestamp): boolean; equals(ts?: any): boolean; getNanos(): number; /** * * @return {number} */ getTime(): number; /** * * @return {number} */ hashCode(): number; setNanos(n: number): void; /** * * @param {number} time */ setTime(time: number): void; } } declare namespace java.sql { /** * An implementation of java.sql.Time. Derived from * http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Time.html * @param {number} hour * @param {number} minute * @param {number} second * @class * @extends java.util.Date */ class Time extends java.util.Date { static valueOf(s: string): Time; constructor(hour?: any, minute?: any, second?: any); /** * * @return {number} */ getDate(): number; /** * * @return {number} */ getDay(): number; /** * * @return {number} */ getMonth(): number; /** * * @return {number} */ getYear(): number; /** * * @param {number} i */ setDate(i: number): void; /** * * @param {number} i */ setMonth(i: number): void; /** * * @param {number} i */ setYear(i: number): void; } } declare namespace java.sql { /** * An implementation of java.sql.Date. Derived from * http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Date.html * @param {number} year * @param {number} month * @param {number} day * @class * @extends java.util.Date */ class Date extends java.util.Date { static valueOf(s: string): Date; constructor(year?: any, month?: any, day?: any); /** * * @return {number} */ getHours(): number; /** * * @return {number} */ getMinutes(): number; /** * * @return {number} */ getSeconds(): number; /** * * @param {number} i */ setHours(i: number): void; /** * * @param {number} i */ setMinutes(i: number): void; /** * * @param {number} i */ setSeconds(i: number): void; } } declare namespace java.util.logging { /** * A simple console logger used in super dev mode. * @extends java.util.logging.Handler * @class */ class SimpleConsoleLogHandler extends java.util.logging.Handler { /** * * @param {java.util.logging.LogRecord} record */ publish(record: java.util.logging.LogRecord): void; toConsoleLogLevel(level: java.util.logging.Level): string; /** * */ close(): void; /** * */ flush(): void; } } declare namespace java.util { /** * A simple wrapper around JavaScript Map for key type is string. * @param {java.util.AbstractHashMap} host * @class */ class InternalStringMap<K, V> implements java.lang.Iterable<java.util.Map.Entry<K, V>> { forEach(action: (p1: any) => void): void; backingMap: java.util.InternalJsMap<V>; host: java.util.AbstractHashMap<K, V>; size: number; /** * A mod count to track 'value' replacements in map to ensure that the * 'value' that we have in the iterator entry is guaranteed to be still * correct. This is to optimize for the common scenario where the values are * not modified during iterations where the entries are never stale. */ valueMod: number; constructor(host: java.util.AbstractHashMap<K, V>); contains(key: string): boolean; get(key: string): V; put(key: string, value: V): V; remove(key: string): V; getSize(): number; /** * * @return {*} */ iterator(): java.util.Iterator<java.util.Map.Entry<K, V>>; newMapEntry(entry: java.util.InternalJsMap.IteratorEntry<V>, lastValueMod: number): java.util.Map.Entry<K, V>; static toNullIfUndefined<T>(value: T): T; } namespace InternalStringMap { class InternalStringMap$0 implements java.util.Iterator<java.util.Map.Entry<any, any>> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; entries: java.util.InternalJsMap.Iterator<any>; current: java.util.InternalJsMap.IteratorEntry<any>; last: java.util.InternalJsMap.IteratorEntry<any>; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): java.util.Map.Entry<any, any>; /** * */ remove(): void; constructor(__parent: any); } class InternalStringMap$1 extends java.util.AbstractMapEntry<any, any> { private entry; private lastValueMod; __parent: any; /** * * @return {*} */ getKey(): any; /** * * @return {*} */ getValue(): any; /** * * @param {*} object * @return {*} */ setValue(object: any): any; constructor(__parent: any, entry: any, lastValueMod: any); } } } declare namespace java.security { /** * Message Digest algorithm - <a href= * "http://java.sun.com/j2se/1.4.2/docs/api/java/security/MessageDigest.html" * >[Sun's docs]</a>. * @extends java.security.MessageDigestSpi * @class */ abstract class MessageDigest extends java.security.MessageDigestSpi { static getInstance(algorithm: string): MessageDigest; static isEqual(digestA: number[], digestB: number[]): boolean; algorithm: string; constructor(algorithm: string); digest$(): number[]; digest$byte_A(input: number[]): number[]; digest$byte_A$int$int(buf: number[], offset: number, len: number): number; digest(buf?: any, offset?: any, len?: any): any; getAlgorithm(): string; getDigestLength(): number; reset(): void; update$byte(input: number): void; update$byte_A(input: number[]): void; update$byte_A$int$int(input: number[], offset: number, len: number): void; update(input?: any, offset?: any, len?: any): any; } namespace MessageDigest { class Md5Digest extends java.security.MessageDigest { static padding: number[]; static padding_$LI$(): number[]; /** * Converts a long to a 8-byte array using low order first. * * @param {number} n A long. * @return {byte[]} A byte[]. */ static toBytes(n: number): number[]; /** * Converts a 64-byte array into a 16-int array. * * @param {byte[]} in A byte[]. * @param {int[]} out An int[]. * @private */ static byte2int(__in: number[], out: number[]): void; static f(x: number, y: number, z: number): number; static ff(a: number, b: number, c: number, d: number, x: number, s: number, ac: number): number; static g(x: number, y: number, z: number): number; static gg(a: number, b: number, c: number, d: number, x: number, s: number, ac: number): number; static h(x: number, y: number, z: number): number; static hh(a: number, b: number, c: number, d: number, x: number, s: number, ac: number): number; static i(x: number, y: number, z: number): number; static ii(a: number, b: number, c: number, d: number, x: number, s: number, ac: number): number; /** * Converts a 4-int array into a 16-byte array. * * @param {int[]} in An int[]. * @param {byte[]} out A byte[]. * @private */ static int2byte(__in: number[], out: number[]): void; buffer: number[]; counter: number; oneByte: number[]; remainder: number; state: number[]; x: number[]; constructor(); engineDigest(buf?: any, offset?: any, len?: any): any; engineDigest$(): number[]; /** * * @return {number} */ engineGetDigestLength(): number; /** * */ engineReset(): void; engineUpdate$byte(input: number): void; engineUpdate$byte_A$int$int(input: number[], offset: number, len: number): void; /** * * @param {byte[]} input * @param {number} offset * @param {number} len */ engineUpdate(input?: any, offset?: any, len?: any): any; transform(buffer: number[]): void; } } } declare namespace java.io { /** * JSweet implementation (partial). * * TODO: actual support of charsets. * @param {java.io.OutputStream} out * @param {string} charsetName * @class * @extends java.io.Writer */ class OutputStreamWriter extends java.io.Writer { out: java.io.OutputStream; constructor(out?: any, charsetName?: any); flushBuffer(): void; write$int(c: number): void; write$char_A$int$int(cbuf: string[], off: number, len: number): void; write(cbuf?: any, off?: any, len?: any): any; write$java_lang_String$int$int(str: string, off: number, len: number): void; flush(): void; close(): void; } } declare namespace java.io { /** * Wraps an existing {@link InputStream} and performs some transformation on * the input data while it is being read. Transformations can be anything from a * simple byte-wise filtering input data to an on-the-fly compression or * decompression of the underlying stream. Input streams that wrap another input * stream and provide some additional functionality on top of it usually inherit * from this class. * * @see FilterOutputStream * @extends java.io.InputStream * @class */ class FilterInputStream extends java.io.InputStream { /** * The source input stream that is filtered. */ in: java.io.InputStream; constructor(__in: java.io.InputStream); /** * * @return {number} */ available(): number; /** * Closes this stream. This implementation closes the filtered stream. * * @throws IOException * if an error occurs while closing this stream. */ close(): void; /** * Sets a mark position in this stream. The parameter {@code readlimit} * indicates how many bytes can be read before the mark is invalidated. * Sending {@code reset()} will reposition this stream back to the marked * position, provided that {@code readlimit} has not been surpassed. * <p> * This implementation sets a mark in the filtered stream. * * @param {number} readlimit * the number of bytes that can be read from this stream before * the mark is invalidated. * @see #markSupported() * @see #reset() */ mark(readlimit: number): void; /** * Indicates whether this stream supports {@code mark()} and {@code reset()}. * This implementation returns whether or not the filtered stream supports * marking. * * @return {boolean} {@code true} if {@code mark()} and {@code reset()} are supported, * {@code false} otherwise. * @see #mark(int) * @see #reset() * @see #skip(long) */ markSupported(): boolean; /** * Reads up to {@code byteCount} bytes from this stream and stores them in * the byte array {@code buffer} starting at {@code byteOffset}. * Returns the number of bytes actually read or -1 if the end of the stream * has been reached. * * @throws IndexOutOfBoundsException * if {@code byteOffset < 0 || byteCount < 0 || byteOffset + byteCount > buffer.length}. * @throws IOException * if the stream is closed or another IOException occurs. * @param {byte[]} buffer * @param {number} byteOffset * @param {number} byteCount * @return {number} */ read(buffer?: any, byteOffset?: any, byteCount?: any): number; read$(): number; /** * Resets this stream to the last marked location. This implementation * resets the target stream. * * @throws IOException * if this stream is already closed, no mark has been set or the * mark is no longer valid because more than {@code readlimit} * bytes have been read since setting the mark. * @see #mark(int) * @see #markSupported() */ reset(): void; /** * Skips {@code byteCount} bytes in this stream. Subsequent * calls to {@code read} will not return these bytes unless {@code reset} is * used. This implementation skips {@code byteCount} bytes in the * filtered stream. * * @return {number} the number of bytes actually skipped. * @throws IOException * if this stream is closed or another IOException occurs. * @see #mark(int) * @see #reset() * @param {number} byteCount */ skip(byteCount: number): number; } } declare namespace java.io { /** * Constructs a new {@code ByteArrayInputStream} on the byte array * {@code buf} with the initial position set to {@code offset} and the * number of bytes available set to {@code offset} + {@code length}. * * @param {byte[]} buf * the byte array to stream over. * @param {number} offset * the initial position in {@code buf} to start streaming from. * @param {number} length * the number of bytes available for streaming. * @class * @extends java.io.InputStream */ class ByteArrayInputStream extends java.io.InputStream { /** * The {@code byte} array containing the bytes to stream over. */ buf: number[]; /** * The current position within the byte array. */ pos: number; /** * The current mark position. Initially set to 0 or the <code>offset</code> * parameter within the constructor. */ _mark: number; /** * The total number of bytes initially available in the byte array * {@code buf}. */ count: number; constructor(buf?: any, offset?: any, length?: any); /** * Returns the number of remaining bytes. * * @return {number} {@code count - pos} */ available(): number; /** * Closes this stream and frees resources associated with this stream. * * @throws IOException * if an I/O error occurs while closing this stream. */ close(): void; /** * Sets a mark position in this ByteArrayInputStream. The parameter * {@code readlimit} is ignored. Sending {@code reset()} will reposition the * stream back to the marked position. * * @param {number} readlimit * ignored. * @see #markSupported() * @see #reset() */ mark(readlimit: number): void; /** * Indicates whether this stream supports the {@code mark()} and * {@code reset()} methods. Returns {@code true} since this class supports * these methods. * * @return {boolean} always {@code true}. * @see #mark(int) * @see #reset() */ markSupported(): boolean; read$(): number; read$byte_A$int$int(buffer: number[], byteOffset: number, byteCount: number): number; /** * * @param {byte[]} buffer * @param {number} byteOffset * @param {number} byteCount * @return {number} */ read(buffer?: any, byteOffset?: any, byteCount?: any): number; /** * Resets this stream to the last marked location. This implementation * resets the position to either the marked position, the start position * supplied in the constructor or 0 if neither has been provided. * * @see #mark(int) */ reset(): void; /** * Skips {@code byteCount} bytes in this InputStream. Subsequent calls to * {@code read} will not return these bytes unless {@code reset} is used. * This implementation skips {@code byteCount} number of bytes in the target * stream. It does nothing and returns 0 if {@code byteCount} is negative. * * @return {number} the number of bytes actually skipped. * @param {number} byteCount */ skip(byteCount: number): number; } } declare namespace java.io { /** * JSweet implementation. * @param {java.io.Reader} in * @param {number} sz * @class * @extends java.io.Reader */ class BufferedReader extends java.io.Reader { in: java.io.Reader; cb: string[]; nChars: number; nextChar: number; static INVALIDATED: number; static UNMARKED: number; markedChar: number; readAheadLimit: number; skipLF: boolean; markedSkipLF: boolean; static defaultCharBufferSize: number; static defaultExpectedLineLength: number; constructor(__in?: any, sz?: any); ensureOpen(): void; fill(): void; read$(): number; read1(cbuf: string[], off: number, len: number): number; read$char_A$int$int(cbuf: string[], off: number, len: number): number; read(cbuf?: any, off?: any, len?: any): number; readLine$boolean(ignoreLF: boolean): string; readLine(ignoreLF?: any): string; readLine$(): string; skip(n: number): number; ready(): boolean; markSupported(): boolean; mark(readAheadLimit: number): void; reset(): void; close(): void; } } declare namespace java.io { /** * JSweet implementation. * @param {java.io.InputStream} in * @param {string} charsetName * @class * @extends java.io.Reader */ class InputStreamReader extends java.io.Reader { in: java.io.InputStream; constructor(__in?: any, charsetName?: any); read$char_A$int$int(cbuf: string[], offset: number, length: number): number; read(cbuf?: any, offset?: any, length?: any): number; ready(): boolean; close(): void; } } declare namespace java.io { class StringReader extends java.io.Reader { charArray: string[]; where: number; marked: number; markedLen: number; constructor(start: string); read$char_A$int$int(cbuf: string[], off: number, len: number): number; /** * * @param {char[]} cbuf * @param {number} off * @param {number} len * @return {number} */ read(cbuf?: any, off?: any, len?: any): number; /** * */ close(): void; /** * * @return {boolean} */ ready(): boolean; /** * * @return {boolean} */ markSupported(): boolean; /** * * @param {number} readAheadLimit */ mark(readAheadLimit: number): void; /** * */ reset(): void; } } declare namespace java.io { /** * Constructs a new {@code FilterOutputStream} with {@code out} as its * target stream. * * @param {java.io.OutputStream} out * the target stream that this stream writes to. * @class * @extends java.io.OutputStream */ class FilterOutputStream extends java.io.OutputStream { /** * The target output stream for this filter stream. */ out: java.io.OutputStream; constructor(out: java.io.OutputStream); /** * Closes this stream. This implementation closes the target stream. * * @throws IOException * if an error occurs attempting to close this stream. */ close(): void; /** * Ensures that all pending data is sent out to the target stream. This * implementation flushes the target stream. * * @throws IOException * if an error occurs attempting to flush this stream. */ flush(): void; /** * Writes {@code count} bytes from the byte array {@code buffer} starting at * position {@code offset} to this stream. * * @param {byte[]} buffer * the buffer to be written. * @param {number} offset * the start position in {@code buffer} from where to get bytes. * @param {number} count * the number of bytes from {@code buffer} to write to this * stream. * @throws IOException * if an error occurs while writing to this stream. * @throws IndexOutOfBoundsException * if {@code offset < 0} or {@code count < 0}, or if * {@code offset + count} is bigger than the length of * {@code buffer}. */ write(buffer?: any, offset?: any, count?: any): any; write$int(oneByte: number): void; } } declare namespace java.io { /** * Constructs a new {@code ByteArrayOutputStream} with a default size of * {@code size} bytes. If more than {@code size} bytes are written to this * instance, the underlying byte array will expand. * * @param {number} size * initial size for the underlying byte array, must be * non-negative. * @throws IllegalArgumentException * if {@code size} < 0. * @class * @extends java.io.OutputStream */ class ByteArrayOutputStream extends java.io.OutputStream { /** * The byte array containing the bytes written. */ buf: number[]; /** * The number of bytes written. */ count: number; constructor(size?: any); /** * Closes this stream. This releases system resources used for this stream. * * @throws IOException * if an error occurs while attempting to close this stream. */ close(): void; expand(i: number): void; /** * Resets this stream to the beginning of the underlying byte array. All * subsequent writes will overwrite any bytes previously stored in this * stream. */ reset(): void; /** * Returns the total number of bytes written to this stream so far. * * @return {number} the number of bytes written to this stream. */ size(): number; /** * Returns the contents of this ByteArrayOutputStream as a byte array. Any * changes made to the receiver after returning will not be reflected in the * byte array returned to the caller. * * @return {byte[]} this stream's current contents as a byte array. */ toByteArray(): number[]; toString$(): string; toString$int(hibyte: number): string; toString$java_lang_String(charsetName: string): string; /** * Returns the contents of this ByteArrayOutputStream as a string converted * according to the encoding declared in {@code charsetName}. * * @param {string} charsetName * a string representing the encoding to use when translating * this stream to a string. * @return {string} this stream's current contents as an encoded string. * @throws UnsupportedEncodingException * if the provided encoding is not supported. */ toString(charsetName?: any): string; write$byte_A$int$int(buffer: number[], offset: number, len: number): void; /** * Writes {@code count} bytes from the byte array {@code buffer} starting at * offset {@code index} to this stream. * * @param {byte[]} buffer * the buffer to be written. * @param {number} offset * the initial position in {@code buffer} to retrieve bytes. * @param {number} len * the number of bytes of {@code buffer} to write. * @throws NullPointerException * if {@code buffer} is {@code null}. * @throws IndexOutOfBoundsException * if {@code offset < 0} or {@code len < 0}, or if * {@code offset + len} is greater than the length of * {@code buffer}. */ write(buffer?: any, offset?: any, len?: any): any; write$int(oneByte: number): void; /** * Takes the contents of this stream and writes it to the output stream * {@code out}. * * @param {java.io.OutputStream} out * an OutputStream on which to write the contents of this stream. * @throws IOException * if an error occurs while writing to {@code out}. */ writeTo(out: java.io.OutputStream): void; } } declare namespace java.lang.ref { /** * This implements the reference API in a minimal way. In JavaScript, there is * no control over the reference and the GC. So this implementation's only * purpose is for compilation. * @param {*} referent * @class * @extends java.lang.ref.Reference */ class WeakReference<T> extends java.lang.ref.Reference<T> { constructor(referent: T); } } declare namespace java.lang { /** * Constructs an {@code InternalError} with the specified detail * message and cause. <p>Note that the detail message associated * with {@code cause} is <i>not</i> automatically incorporated in * this error's detail message. * * @param {string} message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param {java.lang.Throwable} cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.8 * @class * @extends java.lang.VirtualMachineError * @author unascribed */ class InternalError extends java.lang.VirtualMachineError { static __java_lang_InternalError_serialVersionUID: number; constructor(message?: any, cause?: any); } } declare namespace java.util { /** * Thrown when the subject of an observer cannot support additional observers. * * @param {string} message * @class * @extends java.lang.Exception */ class TooManyListenersException extends Error { constructor(message?: any); } } declare namespace java.security { /** * A generic security exception type - <a * href="http://java.sun.com/j2se/1.4.2/docs/api/java/security/GeneralSecurityException.html">[Sun's * docs]</a>. * @param {string} msg * @class * @extends java.lang.Exception */ class GeneralSecurityException extends Error { constructor(msg?: any); } } declare namespace java.io { /** * See <a * href="http://java.sun.com/javase/6/docs/api/java/io/IOException.html">the * official Java API doc</a> for details. * @param {string} message * @param {java.lang.Throwable} throwable * @class * @extends java.lang.Exception */ class IOException extends Error { constructor(message?: any, throwable?: any); } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/RuntimeException.html">the * official Java API doc</a> for details. * @param {string} message * @param {java.lang.Throwable} cause * @class * @extends java.lang.Exception */ class RuntimeException extends Error { constructor(message?: any, cause?: any, enableSuppression?: any, writableStackTrace?: any); } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/CloneNotSupportedException.html"> * the official Java API doc</a> for details. * @param {string} msg * @class * @extends java.lang.Exception */ class CloneNotSupportedException extends Error { constructor(msg?: any); } } declare namespace java.lang { /** * Constructs an <code>InterruptedException</code> with the * specified detail message. * * @param {string} s the detail message. * @class * @extends java.lang.Exception */ class InterruptedException extends Error { constructor(s?: any); } } declare namespace java.lang { class ReflectiveOperationException extends Error { constructor(s?: any); } } declare namespace java.lang { /** * See <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/NoSuchMethodException.html">the * official Java API doc</a> for details. * * This exception is never thrown by GWT or GWT's libraries, as GWT does not support reflection. It * is provided in GWT only for compatibility with user code that explicitly throws or catches it for * non-reflection purposes. * @param {string} message * @class * @extends java.lang.Exception */ class NoSuchMethodException extends Error { constructor(message?: any); } } declare namespace java.text { /** * Emulation of {@code java.text.ParseException}. * @param {string} s * @param {number} errorOffset * @class * @extends java.lang.Exception */ class ParseException extends Error { errorOffset: number; constructor(s: string, errorOffset: number); getErrorOffset(): number; } } declare namespace java.lang { class InheritableThreadLocal<T> extends java.lang.ThreadLocal<T> { childValue(parentValue: T): T; } } declare namespace java.lang { /** * A fast way to create strings using multiple appends. * * This class is an exact clone of {@link StringBuffer} except for the name. Any * change made to one should be mirrored in the other. * @param {*} s * @class * @extends java.lang.AbstractStringBuilder */ class StringBuilder extends java.lang.AbstractStringBuilder implements java.lang.CharSequence, java.lang.Appendable { constructor(s?: any); append$boolean(x: boolean): java.lang.StringBuilder; append$char(x: string): java.lang.StringBuilder; append$char_A(x: string[]): java.lang.StringBuilder; append$char_A$int$int(x: string[], start: number, len: number): java.lang.StringBuilder; append(x?: any, start?: any, len?: any): any; append$java_lang_CharSequence(x: any): java.lang.StringBuilder; append$java_lang_CharSequence$int$int(x: any, start: number, end: number): java.lang.StringBuilder; append$double(x: number): java.lang.StringBuilder; append$float(x: number): java.lang.StringBuilder; append$int(x: number): java.lang.StringBuilder; append$long(x: number): java.lang.StringBuilder; append$java_lang_Object(x: any): java.lang.StringBuilder; append$java_lang_String(x: string): java.lang.StringBuilder; append$java_lang_StringBuffer(x: java.lang.StringBuffer): java.lang.StringBuilder; appendCodePoint(x: number): java.lang.StringBuilder; delete(start: number, end: number): java.lang.StringBuilder; deleteCharAt(start: number): java.lang.StringBuilder; insert$int$boolean(index: number, x: boolean): java.lang.StringBuilder; insert$int$char(index: number, x: string): java.lang.StringBuilder; insert$int$char_A(index: number, x: string[]): java.lang.StringBuilder; insert$int$char_A$int$int(index: number, x: string[], offset: number, len: number): java.lang.StringBuilder; insert(index?: any, x?: any, offset?: any, len?: any): java.lang.StringBuilder; insert$int$java_lang_CharSequence(index: number, chars: any): java.lang.StringBuilder; insert$int$java_lang_CharSequence$int$int(index: number, chars: any, start: number, end: number): java.lang.StringBuilder; insert$int$double(index: number, x: number): java.lang.StringBuilder; insert$int$float(index: number, x: number): java.lang.StringBuilder; insert$int$int(index: number, x: number): java.lang.StringBuilder; insert$int$long(index: number, x: number): java.lang.StringBuilder; insert$int$java_lang_Object(index: number, x: any): java.lang.StringBuilder; insert$int$java_lang_String(index: number, x: string): java.lang.StringBuilder; replace(start: number, end: number, toInsert: string): java.lang.StringBuilder; reverse(): java.lang.StringBuilder; } } declare namespace java.lang { /** * A fast way to create strings using multiple appends. * * This class is an exact clone of {@link StringBuilder} except for the name. * Any change made to one should be mirrored in the other. * @param {*} s * @class * @extends java.lang.AbstractStringBuilder */ class StringBuffer extends java.lang.AbstractStringBuilder implements java.lang.CharSequence, java.lang.Appendable { constructor(s?: any); append$boolean(x: boolean): java.lang.StringBuffer; append$char(x: string): java.lang.StringBuffer; append$char_A(x: string[]): java.lang.StringBuffer; append$char_A$int$int(x: string[], start: number, len: number): java.lang.StringBuffer; append(x?: any, start?: any, len?: any): any; append$java_lang_CharSequence(x: any): java.lang.StringBuffer; append$java_lang_CharSequence$int$int(x: any, start: number, end: number): java.lang.StringBuffer; append$double(x: number): java.lang.StringBuffer; append$float(x: number): java.lang.StringBuffer; append$int(x: number): java.lang.StringBuffer; append$long(x: number): java.lang.StringBuffer; append$java_lang_Object(x: any): java.lang.StringBuffer; append$java_lang_String(x: string): java.lang.StringBuffer; append$java_lang_StringBuffer(x: java.lang.StringBuffer): java.lang.StringBuffer; appendCodePoint(x: number): java.lang.StringBuffer; delete(start: number, end: number): java.lang.StringBuffer; deleteCharAt(start: number): java.lang.StringBuffer; insert$int$boolean(index: number, x: boolean): java.lang.StringBuffer; insert$int$char(index: number, x: string): java.lang.StringBuffer; insert$int$char_A(index: number, x: string[]): java.lang.StringBuffer; insert$int$char_A$int$int(index: number, x: string[], offset: number, len: number): java.lang.StringBuffer; insert(index?: any, x?: any, offset?: any, len?: any): java.lang.StringBuffer; insert$int$java_lang_CharSequence(index: number, chars: any): java.lang.StringBuffer; insert$int$java_lang_CharSequence$int$int(index: number, chars: any, start: number, end: number): java.lang.StringBuffer; insert$int$double(index: number, x: number): java.lang.StringBuffer; insert$int$float(index: number, x: number): java.lang.StringBuffer; insert$int$int(index: number, x: number): java.lang.StringBuffer; insert$int$long(index: number, x: number): java.lang.StringBuffer; insert$int$java_lang_Object(index: number, x: any): java.lang.StringBuffer; insert$int$java_lang_String(index: number, x: string): java.lang.StringBuffer; replace(start: number, end: number, toInsert: string): java.lang.StringBuffer; reverse(): java.lang.StringBuffer; } } declare namespace java.nio { class ByteBuffer extends java.nio.Buffer implements java.lang.Comparable<ByteBuffer> { _buffer: ArrayBuffer; _array: Int8Array; _data: DataView; _order: java.nio.ByteOrder; constructor(_buffer: ArrayBuffer, readOnly: boolean); static allocate(capacity: number): ByteBuffer; /** * * @return {byte[]} */ array(): number[]; asReadOnlyBuffer(): ByteBuffer; compact(): ByteBuffer; compareTo$java_nio_ByteBuffer(byteBuffer: ByteBuffer): number; /** * * @param {java.nio.ByteBuffer} byteBuffer * @return {number} */ compareTo(byteBuffer?: any): number; duplicate(): ByteBuffer; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; get$(): number; get$byte_A(dest: number[]): ByteBuffer; get$byte_A$int$int(dest: number[], offset: number, length: number): ByteBuffer; get(dest?: any, offset?: any, length?: any): any; get$int(from: number): number; getChar$(): string; getChar$int(from: number): string; getChar(from?: any): string; getDouble$(): number; getDouble$int(from: number): number; getDouble(from?: any): number; getFloat$(): number; getFloat$int(from: number): number; getFloat(from?: any): number; getInt$(): number; getInt$int(from: number): number; getInt(from?: any): number; getLong$(): number; getLong$int(from: number): number; getLong(from?: any): number; getShort$(): number; getShort$int(from: number): number; getShort(from?: any): number; order$(): java.nio.ByteOrder; order$java_nio_ByteOrder(newOrder: java.nio.ByteOrder): ByteBuffer; order(newOrder?: any): any; put$byte(b: number): ByteBuffer; put$byte_A(src: number[]): ByteBuffer; put$byte_A$int$int(src: number[], offset: number, length: number): ByteBuffer; put(src?: any, offset?: any, length?: any): ByteBuffer; put$int$byte(to: number, b: number): ByteBuffer; putChar$char(value: string): ByteBuffer; putChar$int$char(to: number, value: string): ByteBuffer; putChar(to?: any, value?: any): ByteBuffer; putDouble$double(value: number): ByteBuffer; putDouble$int$double(to: number, value: number): ByteBuffer; putDouble(to?: any, value?: any): ByteBuffer; putFloat$float(value: number): ByteBuffer; putFloat$int$float(to: number, value: number): ByteBuffer; putFloat(to?: any, value?: any): ByteBuffer; putInt$int(value: number): ByteBuffer; putInt$int$int(to: number, value: number): ByteBuffer; putInt(to?: any, value?: any): ByteBuffer; putLong$long(value: number): ByteBuffer; putLong$int$long(to: number, value: number): ByteBuffer; putLong(to?: any, value?: any): ByteBuffer; putShort$short(value: number): ByteBuffer; putShort$int$short(to: number, value: number): ByteBuffer; putShort(to?: any, value?: any): ByteBuffer; slice(): ByteBuffer; /** * * @return {number} */ hashCode(): number; static wrap$byte_A(array: number[]): ByteBuffer; static wrap$byte_A$int$int(array: number[], offset: number, length: number): ByteBuffer; static wrap(array?: any, offset?: any, length?: any): ByteBuffer; static wrap$def_js_ArrayBuffer(array: ArrayBuffer): ByteBuffer; static wrap$def_js_ArrayBuffer$int$double(array: ArrayBuffer, offset: number, length: number): ByteBuffer; } } declare namespace javaemul.internal { /** * Provides Charset implementations. * @param {string} name * @class * @extends java.nio.charset.Charset */ abstract class EmulatedCharset extends java.nio.charset.Charset { static UTF_8: EmulatedCharset; static UTF_8_$LI$(): EmulatedCharset; static ISO_LATIN_1: EmulatedCharset; static ISO_LATIN_1_$LI$(): EmulatedCharset; static ISO_8859_1: EmulatedCharset; static ISO_8859_1_$LI$(): EmulatedCharset; constructor(name: string); abstract getBytes(string: string): number[]; abstract decodeString(bytes: number[], ofs: number, len: number): string[]; } namespace EmulatedCharset { class LatinCharset extends javaemul.internal.EmulatedCharset { constructor(name: string); /** * * @param {string} str * @return {byte[]} */ getBytes(str: string): number[]; /** * * @param {byte[]} bytes * @param {number} ofs * @param {number} len * @return {char[]} */ decodeString(bytes: number[], ofs: number, len: number): string[]; } class UtfCharset extends javaemul.internal.EmulatedCharset { constructor(name: string); /** * * @param {byte[]} bytes * @param {number} ofs * @param {number} len * @return {char[]} */ decodeString(bytes: number[], ofs: number, len: number): string[]; /** * * @param {string} str * @return {byte[]} */ getBytes(str: string): number[]; /** * Encode a single character in UTF8. * * @param {byte[]} bytes byte array to store character in * @param {number} ofs offset into byte array to store first byte * @param {number} codePoint character to encode * @return {number} number of bytes consumed by encoding the character * @throws IllegalArgumentException if codepoint >= 2^26 * @private */ encodeUtf8(bytes: number[], ofs: number, codePoint: number): number; } } } declare namespace javaemul.internal.stream { class StreamRowSortingCollector extends javaemul.internal.stream.StreamRowCollector { comparator: java.util.Comparator<any>; constructor(collection: java.util.List<any>, comparator: java.util.Comparator<any>); /** * */ end(): void; } } declare namespace java.util { /** * Skeletal implementation of the Map interface. * <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/AbstractMap.html"> * [Sun docs]</a> * * @param <K> * the key type. * @param <V> * the value type. * @class */ abstract class AbstractMap<K, V> implements java.util.Map<K, V> { getOrDefault(key: any, defaultValue: any): any; computeIfAbsent(key: any, mappingFunction: (p1: any) => any): any; replaceAll(__function: (p1: any, p2: any) => any): void; merge(key: any, value: any, map: (p1: any, p2: any) => any): any; putIfAbsent(key: any, value: any): any; constructor(); /** * */ clear(): void; /** * * @param {*} key * @return {boolean} */ containsKey(key: any): boolean; /** * * @param {*} value * @return {boolean} */ containsValue(value: any): boolean; containsEntry(entry: Map.Entry<any, any>): boolean; /** * * @return {*} */ abstract entrySet(): java.util.Set<Map.Entry<K, V>>; /** * * @param {*} obj * @return {boolean} */ equals(obj: any): boolean; /** * * @param {*} key * @return {*} */ get(key: any): V; /** * * @return {number} */ hashCode(): number; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @return {*} */ keySet(): java.util.Set<K>; /** * * @param {*} key * @param {*} value * @return {*} */ put(key: K, value: V): V; /** * * @param {*} map */ putAll(map: java.util.Map<any, any>): void; /** * * @param {*} key * @return {*} */ remove(key: any): V; /** * * @return {number} */ size(): number; toString$(): string; toString$java_util_Map_Entry(entry: Map.Entry<K, V>): string; toString(entry?: any): string; toString$java_lang_Object(o: any): string; /** * * @return {*} */ values(): java.util.Collection<V>; static getEntryKeyOrNull<K, V>(entry: Map.Entry<K, V>): K; static getEntryValueOrNull<K, V>(entry: Map.Entry<K, V>): V; implFindEntry(key: any, remove: boolean): Map.Entry<K, V>; } namespace AbstractMap { /** * Basic {@link Map.Entry} implementation used by {@link SimpleEntry} and * {@link SimpleImmutableEntry}. * @class */ abstract class AbstractEntry<K, V> implements Map.Entry<K, V> { key: K; value: V; constructor(key: K, value: V); /** * * @return {*} */ getKey(): K; /** * * @return {*} */ getValue(): V; /** * * @param {*} value * @return {*} */ setValue(value: V): V; /** * * @param {*} other * @return {boolean} */ equals(other: any): boolean; /** * Calculate the hash code using Sun's specified algorithm. * @return {number} */ hashCode(): number; /** * * @return {string} */ toString(): string; } /** * A mutable {@link Map.Entry} shared by several {@link Map} * implementations. * @param {*} key * @param {*} value * @class * @extends java.util.AbstractMap.AbstractEntry */ class SimpleEntry<K, V> extends AbstractMap.AbstractEntry<K, V> { constructor(key?: any, value?: any); } /** * An immutable {@link Map.Entry} shared by several {@link Map} * implementations. * @param {*} key * @param {*} value * @class * @extends java.util.AbstractMap.AbstractEntry */ class SimpleImmutableEntry<K, V> extends AbstractMap.AbstractEntry<K, V> { constructor(key?: any, value?: any); /** * * @param {*} value * @return {*} */ setValue(value: V): V; } class AbstractMap$0 extends java.util.AbstractSet<any> { __parent: any; /** * */ clear(): void; /** * * @param {*} key * @return {boolean} */ contains(key: any): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<any>; /** * * @param {*} key * @return {boolean} */ remove(key: any): boolean; /** * * @return {number} */ size(): number; constructor(__parent: any); } namespace AbstractMap$0 { class AbstractMap$0$0 implements java.util.Iterator<any> { private outerIter; __parent: any; forEachRemaining(consumer: (p1: any) => void): void; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): any; /** * */ remove(): void; constructor(__parent: any, outerIter: any); } } class AbstractMap$1 extends java.util.AbstractCollection<any> { __parent: any; /** * */ clear(): void; /** * * @param {*} value * @return {boolean} */ contains(value: any): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<any>; /** * * @return {number} */ size(): number; constructor(__parent: any); } namespace AbstractMap$1 { class AbstractMap$1$0 implements java.util.Iterator<any> { private outerIter; __parent: any; forEachRemaining(consumer: (p1: any) => void): void; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): any; /** * */ remove(): void; constructor(__parent: any, outerIter: any); } } } } declare namespace java.util { /** * Implements a set in terms of a hash table. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashSet.html">[Sun * docs]</a> * * @param <E> element type. * @param {number} initialCapacity * @param {number} loadFactor * @class * @extends java.util.AbstractSet */ class HashSet<E> extends java.util.AbstractSet<E> implements java.util.Set<E>, java.lang.Cloneable, java.io.Serializable { map: java.util.HashMap<E, any>; /** * Ensures that RPC will consider type parameter E to be exposed. It will be * pruned by dead code elimination. */ exposeElement: E; constructor(initialCapacity?: any, loadFactor?: any); /** * * @param {*} o * @return {boolean} */ add(o: E): boolean; /** * */ clear(): void; clone(): any; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<E>; /** * * @param {*} o * @return {boolean} */ remove(o: any): boolean; /** * * @return {number} */ size(): number; /** * * @return {string} */ toString(): string; } } declare namespace java.util { /** * A {@link java.util.Set} of {@link Enum}s. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/EnumSet.html">[Sun * docs]</a> * * @param <E> enumeration type * @extends java.util.AbstractSet * @class */ abstract class EnumSet<E extends java.lang.Enum<E>> extends java.util.AbstractSet<E> { static allOf<E extends java.lang.Enum<E>>(elementType: any): EnumSet<E>; static complementOf<E extends java.lang.Enum<E>>(other: EnumSet<E>): EnumSet<E>; static copyOf$java_util_Collection<E extends java.lang.Enum<E>>(c: java.util.Collection<E>): EnumSet<E>; static copyOf$java_util_EnumSet<E extends java.lang.Enum<E>>(s: EnumSet<E>): EnumSet<E>; static copyOf<T0 = any>(s?: any): any; static noneOf<E extends java.lang.Enum<E>>(elementType: any): EnumSet<E>; static ofOne<E extends java.lang.Enum<E>>(first: E): EnumSet<E>; static of<E extends java.lang.Enum<E>>(first: E, ...rest: E[]): EnumSet<E>; static range<E extends java.lang.Enum<E>>(from: E, to: E): EnumSet<E>; constructor(); abstract clone(): EnumSet<E>; abstract capacity(): number; } namespace EnumSet { /** * Constructs a set taking ownership of the specified set. The size must * accurately reflect the number of non-null items in set. * @param {E[]} all * @param {E[]} set * @param {number} size * @class * @extends java.util.EnumSet */ class EnumSetImpl<E extends java.lang.Enum<E>> extends java.util.EnumSet<E> { /** * All enums; reference to the class's copy; must not be modified. */ all: E[]; /** * Live enums in the set. */ set: E[]; /** * Count of enums in the set. */ __size: number; constructor(all: E[], set: E[], size: number); add$java_lang_Enum(e: E): boolean; /** * * @param {java.lang.Enum} e * @return {boolean} */ add(e?: any): boolean; /** * * @return {java.util.EnumSet} */ clone(): java.util.EnumSet<E>; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; containsEnum(e: java.lang.Enum<any>): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<E>; /** * * @param {*} o * @return {boolean} */ remove(o: any): boolean; removeEnum(e: java.lang.Enum<any>): boolean; /** * * @return {number} */ size(): number; /** * * @return {number} */ capacity(): number; } namespace EnumSetImpl { class IteratorImpl implements java.util.Iterator<any> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; i: number; last: number; constructor(__parent: any); /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {java.lang.Enum} */ next(): any; /** * */ remove(): void; findNext(): void; } } } } declare namespace java.util { /** * Implements a set using a TreeMap. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeSet.html">[Sun * docs]</a> * * @param <E> element type. * @param {*} c * @class * @extends java.util.AbstractSet */ class TreeSet<E> extends java.util.AbstractSet<E> implements java.util.NavigableSet<E>, java.io.Serializable { /** * TreeSet is stored as a TreeMap of the requested type to a constant Boolean. */ map: java.util.NavigableMap<E, boolean>; constructor(c?: any); /** * * @param {*} o * @return {boolean} */ add(o: E): boolean; /** * * @param {*} e * @return {*} */ ceiling(e: E): E; /** * */ clear(): void; /** * * @return {*} */ comparator(): java.util.Comparator<any>; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @return {*} */ descendingIterator(): java.util.Iterator<E>; /** * * @return {*} */ descendingSet(): java.util.NavigableSet<E>; /** * * @return {*} */ first(): E; /** * * @param {*} e * @return {*} */ floor(e: E): E; headSet$java_lang_Object(toElement: E): java.util.SortedSet<E>; headSet$java_lang_Object$boolean(toElement: E, inclusive: boolean): java.util.NavigableSet<E>; /** * * @param {*} toElement * @param {boolean} inclusive * @return {*} */ headSet(toElement?: any, inclusive?: any): any; /** * * @param {*} e * @return {*} */ higher(e: E): E; /** * * @return {*} */ iterator(): java.util.Iterator<E>; /** * * @return {*} */ last(): E; /** * * @param {*} e * @return {*} */ lower(e: E): E; /** * * @return {*} */ pollFirst(): E; /** * * @return {*} */ pollLast(): E; /** * * @param {*} o * @return {boolean} */ remove(o: any): boolean; /** * * @return {number} */ size(): number; subSet$java_lang_Object$boolean$java_lang_Object$boolean(fromElement: E, fromInclusive: boolean, toElement: E, toInclusive: boolean): java.util.NavigableSet<E>; /** * * @param {*} fromElement * @param {boolean} fromInclusive * @param {*} toElement * @param {boolean} toInclusive * @return {*} */ subSet(fromElement?: any, fromInclusive?: any, toElement?: any, toInclusive?: any): any; subSet$java_lang_Object$java_lang_Object(fromElement: E, toElement: E): java.util.SortedSet<E>; tailSet$java_lang_Object(fromElement: E): java.util.SortedSet<E>; tailSet$java_lang_Object$boolean(fromElement: E, inclusive: boolean): java.util.NavigableSet<E>; /** * * @param {*} fromElement * @param {boolean} inclusive * @return {*} */ tailSet(fromElement?: any, inclusive?: any): any; } } declare namespace java.util { /** * Capacity increment is ignored. * @param {number} initialCapacity * @param {number} ignoredCapacityIncrement * @class * @extends java.util.AbstractList */ class Vector<E> extends java.util.AbstractList<E> implements java.util.List<E>, java.util.RandomAccess, java.lang.Cloneable, java.io.Serializable { arrayList: java.util.ArrayList<E>; /** * Ensures that RPC will consider type parameter E to be exposed. It will be * pruned by dead code elimination. */ exposeElement: E; constructor(initialCapacity?: any, ignoredCapacityIncrement?: any); add$java_lang_Object(o: E): boolean; add$int$java_lang_Object(index: number, o: E): void; /** * * @param {number} index * @param {*} o */ add(index?: any, o?: any): any; addAll$java_util_Collection(c: java.util.Collection<any>): boolean; addAll$int$java_util_Collection(index: number, c: java.util.Collection<any>): boolean; /** * * @param {number} index * @param {*} c * @return {boolean} */ addAll(index?: any, c?: any): boolean; addElement(o: E): void; capacity(): number; /** * */ clear(): void; clone(): any; /** * * @param {*} elem * @return {boolean} */ contains(elem: any): boolean; /** * * @param {*} c * @return {boolean} */ containsAll(c: java.util.Collection<any>): boolean; copyInto(objs: any[]): void; elementAt(index: number): E; elements(): java.util.Enumeration<E>; ensureCapacity(capacity: number): void; firstElement(): E; /** * * @param {number} index * @return {*} */ get(index: number): E; indexOf$java_lang_Object(elem: any): number; indexOf$java_lang_Object$int(elem: any, index: number): number; indexOf(elem?: any, index?: any): number; insertElementAt(o: E, index: number): void; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<E>; lastElement(): E; lastIndexOf$java_lang_Object(o: any): number; lastIndexOf$java_lang_Object$int(o: any, index: number): number; lastIndexOf(o?: any, index?: any): number; remove$int(index: number): E; /** * * @param {number} index * @return {*} */ remove(index?: any): any; /** * * @param {*} c * @return {boolean} */ removeAll(c: java.util.Collection<any>): boolean; removeAllElements(): void; removeElement(o: any): boolean; removeElementAt(index: number): void; /** * * @param {number} index * @param {*} elem * @return {*} */ set(index: number, elem: E): E; setElementAt(o: E, index: number): void; setSize(size: number): void; /** * * @return {number} */ size(): number; /** * * @param {number} fromIndex * @param {number} toIndex * @return {*} */ subList(fromIndex: number, toIndex: number): java.util.List<E>; toArray$(): any[]; toArray$java_lang_Object_A<T>(a: T[]): T[]; /** * * @param {T[]} a * @return {T[]} */ toArray<T0 = any>(a?: any): any; /** * * @return {string} */ toString(): string; trimToSize(): void; /** * * @param {number} fromIndex * @param {number} endIndex */ removeRange(fromIndex: number, endIndex: number): void; static checkArrayElementIndex(index: number, size: number): void; static checkArrayIndexOutOfBounds(expression: boolean, index: number): void; } } declare namespace java.util { /** * Skeletal implementation of the List interface. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/AbstractSequentialList.html">[Sun * docs]</a> * * @param <E> element type. * @extends java.util.AbstractList * @class */ abstract class AbstractSequentialList<E> extends java.util.AbstractList<E> { constructor(); add$int$java_lang_Object(index: number, element: E): void; /** * * @param {number} index * @param {*} element */ add(index?: any, element?: any): any; addAll$int$java_util_Collection(index: number, c: java.util.Collection<any>): boolean; /** * * @param {number} index * @param {*} c * @return {boolean} */ addAll(index?: any, c?: any): boolean; /** * * @param {number} index * @return {*} */ get(index: number): E; /** * * @return {*} */ iterator(): java.util.Iterator<E>; listIterator$int(index: number): java.util.ListIterator<E>; /** * * @param {number} index * @return {*} */ listIterator(index?: any): any; remove$int(index: number): E; /** * * @param {number} index * @return {*} */ remove(index?: any): any; /** * * @param {number} index * @param {*} element * @return {*} */ set(index: number, element: E): E; /** * * @return {number} */ abstract size(): number; } } declare namespace java.util { /** * Resizeable array implementation of the List interface. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html">[Sun * docs]</a> * * <p> * This implementation differs from JDK 1.5 <code>ArrayList</code> in terms of * capacity management. There is no speed advantage to pre-allocating array * sizes in JavaScript, so this implementation does not include any of the * capacity and "growth increment" concepts in the standard ArrayList class. * Although <code>ArrayList(int)</code> accepts a value for the initial * capacity of the array, this constructor simply delegates to * <code>ArrayList()</code>. It is only present for compatibility with JDK * 1.5's API. * </p> * * @param <E> the element type. * @param {*} c * @class * @extends java.util.AbstractList */ class ArrayList<E> extends java.util.AbstractList<E> implements java.util.List<E>, java.lang.Cloneable, java.util.RandomAccess, java.io.Serializable { /** * This field holds a JavaScript array. */ array: E[]; /** * Ensures that RPC will consider type parameter E to be exposed. It will be * pruned by dead code elimination. */ exposeElement: E; constructor(c?: any); add$java_lang_Object(o: E): boolean; add$int$java_lang_Object(index: number, o: E): void; /** * * @param {number} index * @param {*} o */ add(index?: any, o?: any): any; addAll$java_util_Collection(c: java.util.Collection<any>): boolean; addAll$int$java_util_Collection(index: number, c: java.util.Collection<any>): boolean; /** * * @param {number} index * @param {*} c * @return {boolean} */ addAll(index?: any, c?: any): boolean; /** * */ clear(): void; clone(): any; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; ensureCapacity(ignored: number): void; /** * * @param {number} index * @return {*} */ get(index: number): E; indexOf$java_lang_Object(o: any): number; /** * * @return {*} */ iterator(): java.util.Iterator<E>; /** * * @return {boolean} */ isEmpty(): boolean; lastIndexOf$java_lang_Object(o: any): number; remove$int(index: number): E; /** * * @param {number} index * @return {*} */ remove(index?: any): any; remove$java_lang_Object(o: any): boolean; /** * * @param {number} index * @param {*} o * @return {*} */ set(index: number, o: E): E; /** * * @return {number} */ size(): number; toArray$(): any[]; toArray$java_lang_Object_A<T>(out: T[]): T[]; /** * * @param {T[]} out * @return {T[]} */ toArray<T0 = any>(out?: any): any; trimToSize(): void; /** * * @param {number} fromIndex * @param {number} endIndex */ removeRange(fromIndex: number, endIndex: number): void; indexOf$java_lang_Object$int(o: any, index: number): number; /** * Used by Vector. * @param {*} o * @param {number} index * @return {number} */ indexOf(o?: any, index?: any): number; lastIndexOf$java_lang_Object$int(o: any, index: number): number; /** * Used by Vector. * @param {*} o * @param {number} index * @return {number} */ lastIndexOf(o?: any, index?: any): number; setSize(newSize: number): void; } namespace ArrayList { class ArrayList$0 implements java.util.Iterator<any> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; i: number; last: number; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): any; /** * */ remove(): void; constructor(__parent: any); } } } declare namespace java.util { /** * Utility methods related to native arrays. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html">[Sun * docs]</a> * @class */ class Arrays { static asList<T>(...array: T[]): java.util.List<T>; static stream<T>(...array: T[]): java.util.stream.Stream<T>; static binarySearch$byte_A$byte(sortedArray: number[], key: number): number; static binarySearch$char_A$char(a: string[], key: string): number; static binarySearch$double_A$double(sortedArray: number[], key: number): number; static binarySearch$float_A$float(sortedArray: number[], key: number): number; static binarySearch$int_A$int(sortedArray: number[], key: number): number; static binarySearch$long_A$long(sortedArray: number[], key: number): number; static binarySearch$java_lang_Object_A$java_lang_Object(sortedArray: any[], key: any): number; static binarySearch$short_A$short(sortedArray: number[], key: number): number; static binarySearch$java_lang_Object_A$java_lang_Object$java_util_Comparator<T>(sortedArray: T[], key: T, comparator: java.util.Comparator<any>): number; /** * Perform a binary search on a sorted object array, using a user-specified * comparison function. * * @param {T[]} sortedArray object array to search * @param {*} key value to search for * @param {*} comparator comparision function, <code>null</code> indicates * <i>natural ordering</i> should be used. * @return {number} the index of an element with a matching value, or a negative number * which is the index of the next larger value (or just past the end * of the array if the searched value is larger than all elements in * the array) minus 1 (to ensure error returns are negative) * @throws ClassCastException if <code>key</code> and * <code>sortedArray</code>'s elements cannot be compared by * <code>comparator</code>. */ static binarySearch<T0 = any>(sortedArray?: any, key?: any, comparator?: any): number; static copyOf$boolean_A$int(original: boolean[], newLength: number): boolean[]; static copyOf<T0 = any>(original?: any, newLength?: any): any; static copyOf$byte_A$int(original: number[], newLength: number): number[]; static copyOf$char_A$int(original: string[], newLength: number): string[]; static copyOf$double_A$int(original: number[], newLength: number): number[]; static copyOf$float_A$int(original: number[], newLength: number): number[]; static copyOf$int_A$int(original: number[], newLength: number): number[]; static copyOf$long_A$int(original: number[], newLength: number): number[]; static copyOf$short_A$int(original: number[], newLength: number): number[]; static copyOf$java_lang_Object_A$int<T>(original: T[], newLength: number): T[]; static copyOfRange$boolean_A$int$int(original: boolean[], from: number, to: number): boolean[]; static copyOfRange<T0 = any>(original?: any, from?: any, to?: any): any; static copyOfRange$byte_A$int$int(original: number[], from: number, to: number): number[]; static copyOfRange$char_A$int$int(original: string[], from: number, to: number): string[]; static copyOfRange$double_A$int$int(original: number[], from: number, to: number): number[]; static copyOfRange$float_A$int$int(original: number[], from: number, to: number): number[]; static copyOfRange$int_A$int$int(original: number[], from: number, to: number): number[]; static copyOfRange$long_A$int$int(original: number[], from: number, to: number): number[]; static copyOfRange$short_A$int$int(original: number[], from: number, to: number): number[]; static copyOfRange$java_lang_Object_A$int$int<T>(original: T[], from: number, to: number): T[]; static deepEquals(a1: any[], a2: any[]): boolean; static deepHashCode(a: any[]): number; static deepToString$java_lang_Object_A(a: any[]): string; static equals$boolean_A$boolean_A(array1: boolean[], array2: boolean[]): boolean; static equals(array1?: any, array2?: any): boolean; static equals$byte_A$byte_A(array1: number[], array2: number[]): boolean; static equals$char_A$char_A(array1: string[], array2: string[]): boolean; static equals$double_A$double_A(array1: number[], array2: number[]): boolean; static equals$float_A$float_A(array1: number[], array2: number[]): boolean; static equals$int_A$int_A(array1: number[], array2: number[]): boolean; static equals$long_A$long_A(array1: number[], array2: number[]): boolean; static equals$java_lang_Object_A$java_lang_Object_A(array1: any[], array2: any[]): boolean; static equals$short_A$short_A(array1: number[], array2: number[]): boolean; static fill$boolean_A$boolean(a: boolean[], val: boolean): void; static fill$boolean_A$int$int$boolean(a: boolean[], fromIndex: number, toIndex: number, val: boolean): void; static fill(a?: any, fromIndex?: any, toIndex?: any, val?: any): any; static fill$byte_A$byte(a: number[], val: number): void; static fill$byte_A$int$int$byte(a: number[], fromIndex: number, toIndex: number, val: number): void; static fill$char_A$char(a: string[], val: string): void; static fill$char_A$int$int$char(a: string[], fromIndex: number, toIndex: number, val: string): void; static fill$double_A$double(a: number[], val: number): void; static fill$double_A$int$int$double(a: number[], fromIndex: number, toIndex: number, val: number): void; static fill$float_A$float(a: number[], val: number): void; static fill$float_A$int$int$float(a: number[], fromIndex: number, toIndex: number, val: number): void; static fill$int_A$int(a: number[], val: number): void; static fill$int_A$int$int$int(a: number[], fromIndex: number, toIndex: number, val: number): void; static fill$long_A$int$int$long(a: number[], fromIndex: number, toIndex: number, val: number): void; static fill$long_A$long(a: number[], val: number): void; static fill$java_lang_Object_A$int$int$java_lang_Object(a: any[], fromIndex: number, toIndex: number, val: any): void; static fill$java_lang_Object_A$java_lang_Object(a: any[], val: any): void; static fill$short_A$int$int$short(a: number[], fromIndex: number, toIndex: number, val: number): void; static fill$short_A$short(a: number[], val: number): void; static hashCode$boolean_A(a: boolean[]): number; static hashCode(a?: any): number; static hashCode$byte_A(a: number[]): number; static hashCode$char_A(a: string[]): number; static hashCode$double_A(a: number[]): number; static hashCode$float_A(a: number[]): number; static hashCode$int_A(a: number[]): number; static hashCode$long_A(a: number[]): number; static hashCode$java_lang_Object_A(a: any[]): number; static hashCode$short_A(a: number[]): number; static sort$byte_A(array: number[]): void; static sort$byte_A$int$int(array: number[], fromIndex: number, toIndex: number): void; static sort$char_A(array: string[]): void; static sort$char_A$int$int(array: string[], fromIndex: number, toIndex: number): void; static sort$double_A(array: number[]): void; static sort$double_A$int$int(array: number[], fromIndex: number, toIndex: number): void; static sort$float_A(array: number[]): void; static sort$float_A$int$int(array: number[], fromIndex: number, toIndex: number): void; static sort$int_A(array: number[]): void; static sort$int_A$int$int(array: number[], fromIndex: number, toIndex: number): void; static sort$long_A(array: number[]): void; static sort$long_A$int$int(array: number[], fromIndex: number, toIndex: number): void; static sort$java_lang_Object_A(array: any[]): void; static sort$java_lang_Object_A$int$int(x: any[], fromIndex: number, toIndex: number): void; static sort$short_A(array: number[]): void; static sort$short_A$int$int(array: number[], fromIndex: number, toIndex: number): void; static sort$java_lang_Object_A$java_util_Comparator<T>(x: T[], c: java.util.Comparator<any>): void; static sort$java_lang_Object_A$int$int$java_util_Comparator<T>(x: T[], fromIndex: number, toIndex: number, c: java.util.Comparator<any>): void; static sort<T0 = any>(x?: any, fromIndex?: any, toIndex?: any, c?: any): any; static toString$boolean_A(a: boolean[]): string; static toString(a?: any): string; static toString$byte_A(a: number[]): string; static toString$char_A(a: string[]): string; static toString$double_A(a: number[]): string; static toString$float_A(a: number[]): string; static toString$int_A(a: number[]): string; static toString$long_A(a: number[]): string; static toString$java_lang_Object_A(x: any[]): string; static toString$short_A(a: number[]): string; static deepToString$java_lang_Object_A$java_util_Set(a: any[], arraysIveSeen: java.util.Set<any[]>): string; /** * Recursive helper function for {@link Arrays#deepToString(Object[])}. * @param {java.lang.Object[]} a * @param {*} arraysIveSeen * @return {string} * @private */ static deepToString(a?: any, arraysIveSeen?: any): string; static getCopyLength(array: any, from: number, to: number): number; /** * Sort a small subsection of an array by insertion sort. * * @param {java.lang.Object[]} array array to sort * @param {number} low lower bound of range to sort * @param {number} high upper bound of range to sort * @param {*} comp comparator to use * @private */ static insertionSort(array: any[], low: number, high: number, comp: java.util.Comparator<any>): void; /** * Merge the two sorted subarrays (srcLow,srcMid] and (srcMid,srcHigh] into * dest. * * @param {java.lang.Object[]} src source array for merge * @param {number} srcLow lower bound of bottom sorted half * @param {number} srcMid upper bound of bottom sorted half & lower bound of top sorted * half * @param {number} srcHigh upper bound of top sorted half * @param {java.lang.Object[]} dest destination array for merge * @param {number} destLow lower bound of destination * @param {number} destHigh upper bound of destination * @param {*} comp comparator to use * @private */ static merge(src: any[], srcLow: number, srcMid: number, srcHigh: number, dest: any[], destLow: number, destHigh: number, comp: java.util.Comparator<any>): void; static mergeSort$java_lang_Object_A$int$int$java_util_Comparator(x: any[], fromIndex: number, toIndex: number, comp: java.util.Comparator<any>): void; static mergeSort$java_lang_Object_A$java_lang_Object_A$int$int$int$java_util_Comparator(temp: any[], array: any[], low: number, high: number, ofs: number, comp: java.util.Comparator<any>): void; /** * Recursive helper function for * {@link Arrays#mergeSort(Object[], int, int, Comparator)}. * * @param {java.lang.Object[]} temp temporary space, as large as the range of elements being * sorted. On entry, temp should contain a copy of the sort range * from array. * @param {java.lang.Object[]} array array to sort * @param {number} low lower bound of range to sort * @param {number} high upper bound of range to sort * @param {number} ofs offset to convert an array index into a temp index * @param {*} comp comparison function * @private */ static mergeSort(temp?: any, array?: any, low?: any, high?: any, ofs?: any, comp?: any): any; static nativeLongSort$java_lang_Object$java_lang_Object(array: any, compareFunction: any): void; static nativeLongSort$java_lang_Object$int$int(array: any, fromIndex: number, toIndex: number): void; /** * Sort a subset of an array of number primitives. * @param {*} array * @param {number} fromIndex * @param {number} toIndex * @private */ static nativeLongSort(array?: any, fromIndex?: any, toIndex?: any): any; static nativeNumberSort$java_lang_Object(array: any): void; static nativeNumberSort$java_lang_Object$int$int(array: any, fromIndex: number, toIndex: number): void; /** * Sort a subset of an array of number primitives. * @param {*} array * @param {number} fromIndex * @param {number} toIndex * @private */ static nativeNumberSort(array?: any, fromIndex?: any, toIndex?: any): any; } namespace Arrays { class ArrayList<E> extends java.util.AbstractList<E> implements java.util.RandomAccess, java.io.Serializable { /** * The only reason this is non-final is so that E[] (and E) will be exposed * for serialization. */ array: E[]; constructor(array: E[]); /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @param {number} index * @return {*} */ get(index: number): E; /** * * @param {number} index * @param {*} value * @return {*} */ set(index: number, value: E): E; /** * * @return {number} */ size(): number; toArray$(): any[]; toArray$java_lang_Object_A<T>(out: T[]): T[]; /** * * @param {T[]} out * @return {T[]} */ toArray<T0 = any>(out?: any): any; } } } declare namespace java.util { /** * An unbounded priority queue based on a priority heap. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html">[Sun * docs]</a> * * @param <E> element type. * @param {number} initialCapacity * @param {*} cmp * @class * @extends java.util.AbstractQueue */ class PriorityQueue<E> extends java.util.AbstractQueue<E> { static INITIAL_CAPACITY: number; static getLeftChild(node: number): number; static getParent(node: number): number; static getRightChild(node: number): number; static isLeaf(node: number, size: number): boolean; cmp: java.util.Comparator<any>; /** * A heap held in an array. heap[0] is the root of the heap (the smallest * element), the subtrees of node i are 2*i+1 (left) and 2*i+2 (right). Node i * is a leaf node if 2*i>=n. Node i's parent, if i>0, is floor((i-1)/2). */ heap: java.util.ArrayList<E>; constructor(initialCapacity?: any, cmp?: any); /** * * @param {*} c * @return {boolean} */ addAll(c: java.util.Collection<any>): boolean; /** * */ clear(): void; comparator(): java.util.Comparator<any>; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @param {*} c * @return {boolean} */ containsAll(c: java.util.Collection<any>): boolean; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<E>; /** * * @param {*} e * @return {boolean} */ offer(e: E): boolean; /** * * @return {*} */ peek(): E; /** * * @return {*} */ poll(): E; remove$java_lang_Object(o: any): boolean; /** * * @param {*} o * @return {boolean} */ remove(o?: any): any; /** * * @param {*} c * @return {boolean} */ removeAll(c: java.util.Collection<any>): boolean; /** * * @param {*} c * @return {boolean} */ retainAll(c: java.util.Collection<any>): boolean; /** * * @return {number} */ size(): number; toArray$(): any[]; toArray$java_lang_Object_A<T>(a: T[]): T[]; /** * * @param {T[]} a * @return {T[]} */ toArray<T0 = any>(a?: any): any; /** * * @return {string} */ toString(): string; /** * Make the subtree rooted at <code>node</code> a valid heap. O(n) time * * @param {number} node */ makeHeap(node: number): void; /** * Merge two subheaps into a single heap. O(log n) time * * PRECONDITION: both children of <code>node</code> are heaps * * @param {number} node the parent of the two subtrees to merge */ mergeHeaps(node: number): void; getSmallestChild(node: number, heapSize: number): number; isLeaf(node: number): boolean; removeAtIndex(index: number): void; } } declare namespace java.io { /** * @skip * @param {java.io.OutputStream} out * @class * @extends java.io.FilterOutputStream */ class PrintStream extends java.io.FilterOutputStream { constructor(out: java.io.OutputStream); print$java_lang_String(s: string): void; print(s?: any): any; println$java_lang_String(s: string): void; println(s?: any): any; print$boolean(x: boolean): void; print$char(x: string): void; print$char_A(x: string[]): void; print$double(x: number): void; print$float(x: number): void; print$int(x: number): void; print$long(x: number): void; print$java_lang_Object(x: any): void; println$(): void; println$boolean(x: boolean): void; println$char(x: string): void; println$char_A(x: string[]): void; println$double(x: number): void; println$float(x: number): void; println$int(x: number): void; println$long(x: number): void; println$java_lang_Object(x: any): void; } } declare namespace java.security { /** * A generic security exception type - <a * href="http://java.sun.com/j2se/1.4.2/docs/api/java/security/DigestException.html">[Sun's * docs]</a>. * @param {string} msg * @class * @extends java.security.GeneralSecurityException */ class DigestException extends java.security.GeneralSecurityException { constructor(msg?: any); } } declare namespace java.security { /** * A generic security exception type - <a * href="http://java.sun.com/j2se/1.4.2/docs/api/java/security/NoSuchAlgorithmException.html">[Sun's * docs]</a>. * @param {string} msg * @class * @extends java.security.GeneralSecurityException */ class NoSuchAlgorithmException extends java.security.GeneralSecurityException { constructor(msg?: any); } } declare namespace java.io { /** * A character encoding is not supported - <a * href="http://java.sun.com/javase/6/docs/api/java/io/UnsupportedEncodingException.html">[Sun's * docs]</a>. * @param {string} msg * @class * @extends java.io.IOException */ class UnsupportedEncodingException extends java.io.IOException { constructor(msg?: any); } } declare namespace javaemul.internal.stream { class StopException extends java.lang.RuntimeException { constructor(); } } declare namespace java.util { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/MissingResourceException.html">the * official Java API doc</a> for details. * @param {string} s * @param {string} className * @param {string} key * @class * @extends java.lang.RuntimeException */ class MissingResourceException extends java.lang.RuntimeException { className: string; key: string; constructor(s: string, className: string, key: string); getClassName(): string; getKey(): string; } } declare namespace java.util { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/ConcurrentModificationException.html">the * official Java API doc</a> for details. * @param {string} message * @class * @extends java.lang.RuntimeException */ class ConcurrentModificationException extends java.lang.RuntimeException { constructor(message?: any); } } declare namespace java.util { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/NoSuchElementException.html">the * official Java API doc</a> for details. * @param {string} s * @class * @extends java.lang.RuntimeException */ class NoSuchElementException extends java.lang.RuntimeException { constructor(s?: any); } } declare namespace java.util { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/EmptyStackException.html">the * official Java API doc</a> for details. * @class * @extends java.lang.RuntimeException */ class EmptyStackException extends java.lang.RuntimeException { constructor(); } } declare namespace java.io { /** * See <a * href="https://docs.oracle.com/javase/8/docs/api/java/io/UncheckedIOException.html">the * official Java API doc</a> for details. * @param {string} message * @param {java.io.IOException} cause * @class * @extends java.lang.RuntimeException */ class UncheckedIOException extends java.lang.RuntimeException { constructor(message?: any, cause?: any); /** * * @return {java.io.IOException} */ getCause(): java.io.IOException; } } declare namespace java.lang { /** * Indicates that an objet was in an invalid state during an attempted * operation. * @param {string} message * @param {java.lang.Throwable} cause * @class * @extends java.lang.RuntimeException */ class IllegalStateException extends java.lang.RuntimeException { constructor(message?: any, cause?: any); } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/NullPointerException.html">the * official Java API doc</a> for details. * @param {string} message * @class * @extends java.lang.RuntimeException */ class NullPointerException extends java.lang.RuntimeException { constructor(message?: any); createError(msg: string): any; } } declare namespace java.lang { class IllegalAccessException extends java.lang.RuntimeException { constructor(message?: any, cause?: any); } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/IllegalArgumentException.html">the * official Java API doc</a> for details. * @param {string} message * @param {java.lang.Throwable} cause * @class * @extends java.lang.RuntimeException */ class IllegalArgumentException extends java.lang.RuntimeException { constructor(message?: any, cause?: any); } } declare namespace java.lang.annotation { /** * Indicates an attempt to access an element of an annotation that has changed * since it was compiled or serialized <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/annotation/AnnotationTypeMismatchException.html">[Sun * docs]</a>. * @class * @extends java.lang.RuntimeException */ class AnnotationTypeMismatchException extends java.lang.RuntimeException { constructor(); } } declare namespace java.lang.annotation { /** * Indicates an attempt to access an element of an annotation that was added * since it was compiled or serialized <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/annotation/IncompleteAnnotationException.html">[Sun * docs]</a>. * @param {java.lang.Class} annotationType * @param {string} elementName * @class * @extends java.lang.RuntimeException */ class IncompleteAnnotationException extends java.lang.RuntimeException { __annotationType: any; __elementName: string; constructor(annotationType: any, elementName: string); annotationType(): any; elementName(): string; } } declare namespace java.lang { /** * Indicates failure to cast one type into another. * @param {string} message * @class * @extends java.lang.RuntimeException */ class ClassCastException extends java.lang.RuntimeException { constructor(message?: any); } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/NegativeArraySizeException.html">the * official Java API doc</a> for details. * @param {string} message * @class * @extends java.lang.RuntimeException */ class NegativeArraySizeException extends java.lang.RuntimeException { constructor(message?: any); } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ArrayStoreException.html">the * official Java API doc</a> for details. * @param {string} message * @class * @extends java.lang.RuntimeException */ class ArrayStoreException extends java.lang.RuntimeException { constructor(message?: any); } } declare namespace java.lang { /** * NOTE: in GWT this is only thrown for division by zero on longs and * BigInteger/BigDecimal. * <p> * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ArithmeticException.html">the * official Java API doc</a> for details. * @param {string} explanation * @class * @extends java.lang.RuntimeException */ class ArithmeticException extends java.lang.RuntimeException { constructor(explanation?: any); } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/UnsupportedOperationException.html">the * official Java API doc</a> for details. * @param {string} message * @param {java.lang.Throwable} cause * @class * @extends java.lang.RuntimeException */ class UnsupportedOperationException extends java.lang.RuntimeException { constructor(message?: any, cause?: any); } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/IndexOutOfBoundsException.html">the * official Java API doc</a> for details. * @param {string} message * @class * @extends java.lang.RuntimeException */ class IndexOutOfBoundsException extends java.lang.RuntimeException { constructor(message?: any); } } declare namespace java.nio { class BufferUnderflowException extends java.lang.RuntimeException { constructor(); } } declare namespace java.nio { class BufferOverflowException extends java.lang.RuntimeException { constructor(); } } declare namespace java.lang { class InstantiationException extends java.lang.ReflectiveOperationException { constructor(s?: any); } } declare namespace java.nio.charset { /** * Constant definitions for the standard Charsets. * @class */ class StandardCharsets { static ISO_8859_1: java.nio.charset.Charset; static ISO_8859_1_$LI$(): java.nio.charset.Charset; static UTF_8: java.nio.charset.Charset; static UTF_8_$LI$(): java.nio.charset.Charset; constructor(); } } declare namespace java.util { /** * Implementation of Map interface based on a hash table. * <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html">[Sun * docs]</a> * * @param <K> * key type * @param <V> * value type * @param {number} ignored * @param {number} alsoIgnored * @class * @extends java.util.AbstractMap */ abstract class AbstractHashMap<K, V> extends java.util.AbstractMap<K, V> { /** * A map of integral hashCodes onto entries. */ hashCodeMap: java.util.InternalHashCodeMap<K, V>; /** * A map of Strings onto values. */ stringMap: java.util.InternalStringMap<K, V>; constructor(ignored?: any, alsoIgnored?: any); /** * */ clear(): void; reset(): void; /** * * @param {*} key * @return {boolean} */ containsKey(key: any): boolean; /** * * @param {*} value * @return {boolean} */ containsValue(value: any): boolean; _containsValue(value: any, entries: java.lang.Iterable<Map.Entry<K, V>>): boolean; /** * * @return {*} */ entrySet(): java.util.Set<java.util.Map.Entry<K, V>>; /** * * @param {*} key * @return {*} */ get(key: any): V; /** * * @param {*} key * @param {*} value * @return {*} */ put(key: K, value: V): V; /** * * @param {*} key * @return {*} */ remove(key: any): V; /** * * @return {number} */ size(): number; /** * Subclasses must override to return a whether or not two keys or values * are equal. * @param {*} value1 * @param {*} value2 * @return {boolean} */ abstract _equals(value1: any, value2: any): boolean; /** * Subclasses must override to return a hash code for a given key. The key * is guaranteed to be non-null and not a String. * @param {*} key * @return {number} */ abstract getHashCode(key: any): number; /** * Returns the Map.Entry whose key is Object equal to <code>key</code>, * provided that <code>key</code>'s hash code is <code>hashCode</code>; or * <code>null</code> if no such Map.Entry exists at the specified hashCode. * @param {*} key * @return {*} * @private */ getHashValue(key: any): V; /** * Returns the value for the given key in the stringMap. Returns * <code>null</code> if the specified key does not exist. * @param {string} key * @return {*} * @private */ getStringValue(key: string): V; /** * Returns true if the a key exists in the hashCodeMap that is Object equal * to <code>key</code>, provided that <code>key</code>'s hash code is * <code>hashCode</code>. * @param {*} key * @return {boolean} * @private */ hasHashValue(key: any): boolean; /** * Returns true if the given key exists in the stringMap. * @param {string} key * @return {boolean} * @private */ hasStringValue(key: string): boolean; /** * Sets the specified key to the specified value in the hashCodeMap. Returns * the value previously at that key. Returns <code>null</code> if the * specified key did not exist. * @param {*} key * @param {*} value * @return {*} * @private */ putHashValue(key: K, value: V): V; /** * Sets the specified key to the specified value in the stringMap. Returns * the value previously at that key. Returns <code>null</code> if the * specified key did not exist. * @param {string} key * @param {*} value * @return {*} * @private */ putStringValue(key: string, value: V): V; /** * Removes the pair whose key is Object equal to <code>key</code> from * <code>hashCodeMap</code>, provided that <code>key</code>'s hash code is * <code>hashCode</code>. Returns the value that was associated with the * removed key, or null if no such key existed. * @param {*} key * @return {*} * @private */ removeHashValue(key: any): V; /** * Removes the specified key from the stringMap and returns the value that * was previously there. Returns <code>null</code> if the specified key does * not exist. * @param {string} key * @return {*} * @private */ removeStringValue(key: string): V; } namespace AbstractHashMap { class EntrySet extends java.util.AbstractSet<Map.Entry<any, any>> { __parent: any; /** * */ clear(): void; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<Map.Entry<any, any>>; /** * * @param {*} entry * @return {boolean} */ remove(entry: any): boolean; /** * * @return {number} */ size(): number; constructor(__parent: any); } /** * Iterator for <code>EntrySet</code>. * @class */ class EntrySetIterator implements java.util.Iterator<Map.Entry<any, any>> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; stringMapEntries: java.util.Iterator<Map.Entry<any, any>>; current: java.util.Iterator<Map.Entry<any, any>>; last: java.util.Iterator<Map.Entry<any, any>>; __hasNext: boolean; constructor(__parent: any); /** * * @return {boolean} */ hasNext(): boolean; computeHasNext(): boolean; /** * * @return {*} */ next(): Map.Entry<any, any>; /** * */ remove(): void; } } } declare namespace java.util { /** * A {@link java.util.Map} of {@link Enum}s. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/EnumMap.html">[Sun * docs]</a> * * @param <K> key type * @param <V> value type * @param {java.lang.Class} type * @class * @extends java.util.AbstractMap */ class EnumMap<K extends java.lang.Enum<K>, V> extends java.util.AbstractMap<K, V> { __keySet: java.util.EnumSet<K>; __values: V[]; constructor(type?: any); /** * */ clear(): void; clone(): EnumMap<K, V>; /** * * @param {*} key * @return {boolean} */ containsKey(key: any): boolean; /** * * @param {*} value * @return {boolean} */ containsValue(value: any): boolean; /** * * @return {*} */ entrySet(): java.util.Set<java.util.Map.Entry<K, V>>; /** * * @param {*} k * @return {*} */ get(k: any): V; put$java_lang_Enum$java_lang_Object(key: K, value: V): V; /** * * @param {java.lang.Enum} key * @param {*} value * @return {*} */ put(key?: any, value?: any): any; /** * * @param {*} key * @return {*} */ remove(key: any): V; /** * * @return {number} */ size(): number; /** * Returns <code>key</code> as <code>K</code>. Only runtime checks that * key is an Enum, not that it's the particular Enum K. Should only be called * when you are sure <code>key</code> is of type <code>K</code>. * @param {*} key * @return {java.lang.Enum} * @private */ asKey(key: any): K; asOrdinal(key: any): number; init$java_lang_Class(type: any): void; init(type?: any): any; init$java_util_EnumMap(m: EnumMap<K, any>): void; set(ordinal: number, value: V): V; } namespace EnumMap { class EntrySet extends java.util.AbstractSet<Map.Entry<any, any>> { __parent: any; /** * */ clear(): void; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<Map.Entry<any, any>>; /** * * @param {*} entry * @return {boolean} */ remove(entry: any): boolean; /** * * @return {number} */ size(): number; constructor(__parent: any); } class EntrySetIterator implements java.util.Iterator<Map.Entry<any, any>> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; it: java.util.Iterator<any>; key: any; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): Map.Entry<any, any>; /** * */ remove(): void; constructor(__parent: any); } class MapEntry extends java.util.AbstractMapEntry<any, any> { __parent: any; key: any; constructor(__parent: any, key: any); /** * * @return {java.lang.Enum} */ getKey(): any; /** * * @return {*} */ getValue(): any; /** * * @param {*} value * @return {*} */ setValue(value: any): any; } } } declare namespace java.util { /** * Skeletal implementation of a NavigableMap. * @extends java.util.AbstractMap * @class */ abstract class AbstractNavigableMap<K, V> extends java.util.AbstractMap<K, V> implements java.util.NavigableMap<K, V> { static copyOf<K, V>(entry: Map.Entry<K, V>): Map.Entry<K, V>; static getKeyOrNSE<K, V>(entry: Map.Entry<K, V>): K; /** * * @param {*} key * @return {*} */ ceilingEntry(key: K): Map.Entry<K, V>; /** * * @param {*} key * @return {*} */ ceilingKey(key: K): K; /** * * @param {*} k * @return {boolean} */ containsKey(k: any): boolean; /** * * @return {*} */ descendingKeySet(): java.util.NavigableSet<K>; /** * * @return {*} */ descendingMap(): java.util.NavigableMap<K, V>; /** * * @return {*} */ entrySet(): java.util.Set<Map.Entry<K, V>>; /** * * @return {*} */ firstEntry(): Map.Entry<K, V>; /** * * @return {*} */ firstKey(): K; /** * * @param {*} key * @return {*} */ floorEntry(key: K): Map.Entry<K, V>; /** * * @param {*} key * @return {*} */ floorKey(key: K): K; /** * * @param {*} k * @return {*} */ get(k: any): V; headMap(toKey?: any, inclusive?: any): any; headMap$java_lang_Object(toKey: K): java.util.SortedMap<K, V>; /** * * @param {*} key * @return {*} */ higherEntry(key: K): Map.Entry<K, V>; /** * * @param {*} key * @return {*} */ higherKey(key: K): K; /** * * @return {*} */ keySet(): java.util.Set<K>; /** * * @return {*} */ lastEntry(): Map.Entry<K, V>; /** * * @return {*} */ lastKey(): K; /** * * @param {*} key * @return {*} */ lowerEntry(key: K): Map.Entry<K, V>; /** * * @param {*} key * @return {*} */ lowerKey(key: K): K; /** * * @return {*} */ navigableKeySet(): java.util.NavigableSet<K>; /** * * @return {*} */ pollFirstEntry(): Map.Entry<K, V>; /** * * @return {*} */ pollLastEntry(): Map.Entry<K, V>; subMap(fromKey?: any, fromInclusive?: any, toKey?: any, toInclusive?: any): any; subMap$java_lang_Object$java_lang_Object(fromKey: K, toKey: K): java.util.SortedMap<K, V>; tailMap(fromKey?: any, inclusive?: any): any; tailMap$java_lang_Object(fromKey: K): java.util.SortedMap<K, V>; /** * * @param {*} entry * @return {boolean} */ containsEntry(entry: Map.Entry<any, any>): boolean; /** * Returns an iterator over the entries in this map in descending order. * @return {*} */ abstract descendingEntryIterator(): java.util.Iterator<Map.Entry<K, V>>; /** * Returns an iterator over the entries in this map in ascending order. * @return {*} */ abstract entryIterator(): java.util.Iterator<Map.Entry<K, V>>; /** * Returns the entry corresponding to the specified key. If no such entry exists returns * {@code null}. * @param {*} key * @return {*} */ abstract getEntry(key: K): Map.Entry<K, V>; /** * Returns the first entry or {@code null} if map is empty. * @return {*} */ abstract getFirstEntry(): Map.Entry<K, V>; /** * Returns the last entry or {@code null} if map is empty. * @return {*} */ abstract getLastEntry(): Map.Entry<K, V>; /** * Gets the entry corresponding to the specified key or the entry for the least key greater than * the specified key. If no such entry exists returns {@code null}. * @param {*} key * @return {*} */ abstract getCeilingEntry(key: K): Map.Entry<K, V>; /** * Gets the entry corresponding to the specified key or the entry for the greatest key less than * the specified key. If no such entry exists returns {@code null}. * @param {*} key * @return {*} */ abstract getFloorEntry(key: K): Map.Entry<K, V>; /** * Gets the entry for the least key greater than the specified key. If no such entry exists * returns {@code null}. * @param {*} key * @return {*} */ abstract getHigherEntry(key: K): Map.Entry<K, V>; /** * Returns the entry for the greatest key less than the specified key. If no such entry exists * returns {@code null}. * @param {*} key * @return {*} */ abstract getLowerEntry(key: K): Map.Entry<K, V>; /** * Remove an entry from the tree, returning whether it was found. * @param {*} entry * @return {boolean} */ abstract removeEntry(entry: Map.Entry<K, V>): boolean; pollEntry(entry: Map.Entry<K, V>): Map.Entry<K, V>; abstract comparator(): any; constructor(); } namespace AbstractNavigableMap { class DescendingMap extends java.util.AbstractNavigableMap<any, any> { __parent: any; /** * */ clear(): void; /** * * @return {*} */ comparator(): java.util.Comparator<any>; /** * * @return {*} */ descendingMap(): java.util.NavigableMap<any, any>; headMap$java_lang_Object$boolean(toKey: any, inclusive: boolean): java.util.NavigableMap<any, any>; /** * * @param {*} toKey * @param {boolean} inclusive * @return {*} */ headMap(toKey?: any, inclusive?: any): any; /** * * @param {*} key * @param {*} value * @return {*} */ put(key: any, value: any): any; /** * * @param {*} key * @return {*} */ remove(key: any): any; /** * * @return {number} */ size(): number; subMap$java_lang_Object$boolean$java_lang_Object$boolean(fromKey: any, fromInclusive: boolean, toKey: any, toInclusive: boolean): java.util.NavigableMap<any, any>; /** * * @param {*} fromKey * @param {boolean} fromInclusive * @param {*} toKey * @param {boolean} toInclusive * @return {*} */ subMap(fromKey?: any, fromInclusive?: any, toKey?: any, toInclusive?: any): any; tailMap$java_lang_Object$boolean(fromKey: any, inclusive: boolean): java.util.NavigableMap<any, any>; /** * * @param {*} fromKey * @param {boolean} inclusive * @return {*} */ tailMap(fromKey?: any, inclusive?: any): any; ascendingMap(): java.util.AbstractNavigableMap<any, any>; /** * * @return {*} */ descendingEntryIterator(): java.util.Iterator<Map.Entry<any, any>>; /** * * @return {*} */ entryIterator(): java.util.Iterator<Map.Entry<any, any>>; /** * * @param {*} key * @return {*} */ getEntry(key: any): Map.Entry<any, any>; /** * * @return {*} */ getFirstEntry(): Map.Entry<any, any>; /** * * @return {*} */ getLastEntry(): Map.Entry<any, any>; /** * * @param {*} key * @return {*} */ getCeilingEntry(key: any): Map.Entry<any, any>; /** * * @param {*} key * @return {*} */ getFloorEntry(key: any): Map.Entry<any, any>; /** * * @param {*} key * @return {*} */ getHigherEntry(key: any): Map.Entry<any, any>; /** * * @param {*} key * @return {*} */ getLowerEntry(key: any): Map.Entry<any, any>; /** * * @param {*} entry * @return {boolean} */ removeEntry(entry: Map.Entry<any, any>): boolean; constructor(__parent: any); } class EntrySet extends java.util.AbstractSet<Map.Entry<any, any>> { __parent: any; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<Map.Entry<any, any>>; /** * * @param {*} o * @return {boolean} */ remove(o: any): boolean; /** * * @return {number} */ size(): number; constructor(__parent: any); } class NavigableKeySet<K, V> extends java.util.AbstractSet<K> implements java.util.NavigableSet<K> { map: java.util.NavigableMap<K, V>; constructor(map: java.util.NavigableMap<K, V>); /** * * @param {*} k * @return {*} */ ceiling(k: K): K; /** * */ clear(): void; /** * * @return {*} */ comparator(): java.util.Comparator<any>; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @return {*} */ descendingIterator(): java.util.Iterator<K>; /** * * @return {*} */ descendingSet(): java.util.NavigableSet<K>; /** * * @return {*} */ first(): K; /** * * @param {*} k * @return {*} */ floor(k: K): K; headSet$java_lang_Object(toElement: K): java.util.SortedSet<K>; headSet$java_lang_Object$boolean(toElement: K, inclusive: boolean): java.util.NavigableSet<K>; /** * * @param {*} toElement * @param {boolean} inclusive * @return {*} */ headSet(toElement?: any, inclusive?: any): any; /** * * @param {*} k * @return {*} */ higher(k: K): K; /** * * @return {*} */ iterator(): java.util.Iterator<K>; /** * * @return {*} */ last(): K; /** * * @param {*} k * @return {*} */ lower(k: K): K; /** * * @return {*} */ pollFirst(): K; /** * * @return {*} */ pollLast(): K; /** * * @param {*} o * @return {boolean} */ remove(o: any): boolean; /** * * @return {number} */ size(): number; subSet$java_lang_Object$boolean$java_lang_Object$boolean(fromElement: K, fromInclusive: boolean, toElement: K, toInclusive: boolean): java.util.NavigableSet<K>; /** * * @param {*} fromElement * @param {boolean} fromInclusive * @param {*} toElement * @param {boolean} toInclusive * @return {*} */ subSet(fromElement?: any, fromInclusive?: any, toElement?: any, toInclusive?: any): any; subSet$java_lang_Object$java_lang_Object(fromElement: K, toElement: K): java.util.SortedSet<K>; tailSet$java_lang_Object(fromElement: K): java.util.SortedSet<K>; tailSet$java_lang_Object$boolean(fromElement: K, inclusive: boolean): java.util.NavigableSet<K>; /** * * @param {*} fromElement * @param {boolean} inclusive * @return {*} */ tailSet(fromElement?: any, inclusive?: any): any; } namespace NavigableKeySet { class NavigableKeySet$0 implements java.util.Iterator<any> { private entryIterator; __parent: any; forEachRemaining(consumer: (p1: any) => void): void; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): any; /** * */ remove(): void; constructor(__parent: any, entryIterator: any); } } } } declare namespace java.util { /** * Utility methods that operate on collections. <a href= * "http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html">[Sun * docs]</a> * @class */ class Collections { static EMPTY_LIST: java.util.List<any>; static EMPTY_LIST_$LI$(): java.util.List<any>; static EMPTY_MAP: java.util.Map<any, any>; static EMPTY_MAP_$LI$(): java.util.Map<any, any>; static EMPTY_SET: java.util.Set<any>; static EMPTY_SET_$LI$(): java.util.Set<any>; static addAll<T>(c: java.util.Collection<any>, ...a: T[]): boolean; static asLifoQueue<T>(deque: java.util.Deque<T>): java.util.Queue<T>; static binarySearch$java_util_List$java_lang_Object<T>(sortedList: java.util.List<any>, key: T): number; static binarySearch$java_util_List$java_lang_Object$java_util_Comparator<T>(sortedList: java.util.List<any>, key: T, comparator: java.util.Comparator<any>): number; /** * Perform a binary search on a sorted List, using a user-specified comparison * function. * * <p> * Note: The GWT implementation differs from the JDK implementation in that it * does not do an iterator-based binary search for Lists that do not implement * RandomAccess. * </p> * * @param {*} sortedList * List to search * @param {*} key * value to search for * @param {*} comparator * comparision function, <code>null</code> indicates <i>natural * ordering</i> should be used. * @return {number} the index of an element with a matching value, or a negative number * which is the index of the next larger value (or just past the end of * the array if the searched value is larger than all elements in the * array) minus 1 (to ensure error returns are negative) * @throws ClassCastException * if <code>key</code> and <code>sortedList</code>'s elements cannot * be compared by <code>comparator</code>. */ static binarySearch<T0 = any>(sortedList?: any, key?: any, comparator?: any): number; static copy<T>(dest: java.util.List<any>, src: java.util.List<any>): void; static disjoint(c1: java.util.Collection<any>, c2: java.util.Collection<any>): boolean; static emptyIterator<T>(): java.util.Iterator<T>; static emptyList<T>(): java.util.List<T>; static emptyListIterator<T>(): java.util.ListIterator<T>; static emptyMap<K, V>(): java.util.Map<K, V>; static emptySet<T>(): java.util.Set<T>; static enumeration<T>(c: java.util.Collection<T>): java.util.Enumeration<T>; static fill<T>(list: java.util.List<any>, obj: T): void; static frequency(c: java.util.Collection<any>, o: any): number; static list<T>(e: java.util.Enumeration<T>): java.util.ArrayList<T>; static max$java_util_Collection<T extends any & java.lang.Comparable<any>>(coll: java.util.Collection<any>): T; static max$java_util_Collection$java_util_Comparator<T>(coll: java.util.Collection<any>, comp: java.util.Comparator<any>): T; static max<T0 = any>(coll?: any, comp?: any): any; static min<T>(coll: java.util.Collection<any>, comp?: java.util.Comparator<any>): T; static newSetFromMap<E>(map: java.util.Map<E, boolean>): java.util.Set<E>; static nCopies<T>(n: number, o: T): java.util.List<T>; static replaceAll<T>(list: java.util.List<T>, oldVal: T, newVal: T): boolean; static reverse<T>(l: java.util.List<T>): void; static reverseOrder$<T>(): java.util.Comparator<T>; static reverseOrder$java_util_Comparator<T>(cmp: java.util.Comparator<T>): java.util.Comparator<T>; static reverseOrder<T0 = any>(cmp?: any): any; /** * Rotates the elements in {@code list} by the distance {@code dist} * <p> * e.g. for a given list with elements [1, 2, 3, 4, 5, 6, 7, 8, 9, 0], calling * rotate(list, 3) or rotate(list, -7) would modify the list to look like this: * [8, 9, 0, 1, 2, 3, 4, 5, 6, 7] * * @param {*} lst * the list whose elements are to be rotated. * @param {number} dist * is the distance the list is rotated. This can be any valid * integer. Negative values rotate the list backwards. */ static rotate(lst: java.util.List<any>, dist: number): void; static shuffle<T>(list: java.util.List<T>, rnd?: java.util.Random): void; static singleton<T>(o: T): java.util.Set<T>; static singletonList<T>(o: T): java.util.List<T>; static singletonMap<K, V>(key: K, value: V): java.util.Map<K, V>; static sort$java_util_List<T>(target: java.util.List<T>): void; static sort$java_util_List$java_util_Comparator<T>(target: java.util.List<T>, c: java.util.Comparator<any>): void; static sort<T0 = any>(target?: any, c?: any): any; static swap(list: java.util.List<any>, i: number, j: number): void; static unmodifiableCollection<T>(coll: java.util.Collection<any>): java.util.Collection<T>; static unmodifiableList<T>(list: java.util.List<any>): java.util.List<T>; static unmodifiableMap<K, V>(map: java.util.Map<any, any>): java.util.Map<K, V>; static unmodifiableSet<T>(set: java.util.Set<any>): java.util.Set<T>; static unmodifiableSortedMap<K, V>(map: java.util.SortedMap<K, any>): java.util.SortedMap<K, V>; static unmodifiableSortedSet<T>(set: java.util.SortedSet<any>): java.util.SortedSet<T>; static hashCode$java_lang_Iterable<T>(collection: java.lang.Iterable<T>): number; static hashCode$java_util_List<T>(list: java.util.List<T>): number; /** * Computes hash code preserving collection order (e.g. ArrayList). * @param {*} list * @return {number} */ static hashCode<T0 = any>(list?: any): number; /** * Replace contents of a list from an array. * * @param <T> * element type * @param {*} target * list to replace contents from an array * @param {java.lang.Object[]} x * an Object array which can contain only T instances * @private */ static replaceContents<T>(target: java.util.List<T>, x: any[]): void; static swapImpl$java_util_List$int$int<T>(list: java.util.List<T>, i: number, j: number): void; static swapImpl<T0 = any>(list?: any, i?: any, j?: any): any; static swapImpl$java_lang_Object_A$int$int(a: any[], i: number, j: number): void; static synchronizedList<T>(list: java.util.List<T>): java.util.List<T>; static synchronizedSet<T>(s: java.util.Set<T>): java.util.Set<T>; } namespace Collections { class LifoQueue<E> extends java.util.AbstractQueue<E> implements java.io.Serializable { deque: java.util.Deque<E>; constructor(deque: java.util.Deque<E>); /** * * @return {*} */ iterator(): java.util.Iterator<E>; /** * * @param {*} e * @return {boolean} */ offer(e: E): boolean; /** * * @return {*} */ peek(): E; /** * * @return {*} */ poll(): E; /** * * @return {number} */ size(): number; } class EmptyList extends java.util.AbstractList<any> implements java.util.RandomAccess, java.io.Serializable { /** * * @param {*} object * @return {boolean} */ contains(object: any): boolean; /** * * @param {number} location * @return {*} */ get(location: number): any; /** * * @return {*} */ iterator(): java.util.Iterator<any>; /** * * @param {number} from * @return {*} */ listIterator(from?: any): any; listIterator$(): java.util.ListIterator<any>; /** * * @return {number} */ size(): number; constructor(); } class EmptyListIterator implements java.util.ListIterator<any> { forEachRemaining(consumer: (p1: any) => void): void; static INSTANCE: Collections.EmptyListIterator; static INSTANCE_$LI$(): Collections.EmptyListIterator; /** * * @param {*} o */ add(o: any): void; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {boolean} */ hasPrevious(): boolean; /** * * @return {*} */ next(): any; /** * * @return {number} */ nextIndex(): number; /** * * @return {*} */ previous(): any; /** * * @return {number} */ previousIndex(): number; /** * */ remove(): void; /** * * @param {*} o */ set(o: any): void; constructor(); } class EmptySet extends java.util.AbstractSet<any> implements java.io.Serializable { /** * * @param {*} object * @return {boolean} */ contains(object: any): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<any>; /** * * @return {number} */ size(): number; constructor(); } class EmptyMap extends java.util.AbstractMap<any, any> implements java.io.Serializable { /** * * @param {*} key * @return {boolean} */ containsKey(key: any): boolean; /** * * @param {*} value * @return {boolean} */ containsValue(value: any): boolean; /** * * @return {*} */ entrySet(): java.util.Set<any>; /** * * @param {*} key * @return {*} */ get(key: any): any; /** * * @return {*} */ keySet(): java.util.Set<any>; /** * * @return {number} */ size(): number; /** * * @return {*} */ values(): java.util.Collection<any>; constructor(); } class ReverseComparator { static INSTANCE: Collections.ReverseComparator; static INSTANCE_$LI$(): Collections.ReverseComparator; compare$java_lang_Comparable$java_lang_Comparable(o1: java.lang.Comparable<any>, o2: java.lang.Comparable<any>): number; /** * * @param {*} o1 * @param {*} o2 * @return {number} */ compare(o1?: any, o2?: any): number; constructor(); } class SetFromMap<E> extends java.util.AbstractSet<E> implements java.io.Serializable { backingMap: java.util.Map<E, boolean>; __keySet: java.util.Set<E>; constructor(map: java.util.Map<E, boolean>); /** * * @param {*} e * @return {boolean} */ add(e: E): boolean; /** * */ clear(): void; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ hashCode(): number; /** * * @return {*} */ iterator(): java.util.Iterator<E>; /** * * @param {*} o * @return {boolean} */ remove(o: any): boolean; /** * * @return {number} */ size(): number; /** * * @return {string} */ toString(): string; /** * Lazy initialize keySet to avoid NPE after deserialization. * @return {*} * @private */ keySet(): java.util.Set<E>; } class SingletonList<E> extends java.util.AbstractList<E> implements java.io.Serializable { element: E; constructor(element: E); /** * * @param {*} item * @return {boolean} */ contains(item: any): boolean; /** * * @param {number} index * @return {*} */ get(index: number): E; /** * * @return {number} */ size(): number; } class UnmodifiableCollection<T> implements java.util.Collection<T> { removeIf(filter: (p1: any) => boolean): boolean; parallelStream(): java.util.stream.Stream<any>; stream(): java.util.stream.Stream<any>; forEach(action: (p1: any) => void): void; coll: java.util.Collection<any>; constructor(coll: java.util.Collection<any>); /** * * @param {*} o * @return {boolean} */ add(o: T): boolean; /** * * @param {*} c * @return {boolean} */ addAll(c: java.util.Collection<any>): boolean; /** * */ clear(): void; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @param {*} c * @return {boolean} */ containsAll(c: java.util.Collection<any>): boolean; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<T>; /** * * @param {*} o * @return {boolean} */ remove(o: any): boolean; /** * * @param {*} c * @return {boolean} */ removeAll(c: java.util.Collection<any>): boolean; /** * * @param {*} c * @return {boolean} */ retainAll(c: java.util.Collection<any>): boolean; /** * * @return {number} */ size(): number; toArray$(): any[]; toArray$java_lang_Object_A<E>(a: E[]): E[]; /** * * @param {E[]} a * @return {E[]} */ toArray<T0 = any>(a?: any): any; /** * * @return {string} */ toString(): string; } class UnmodifiableCollectionIterator<T> implements java.util.Iterator<T> { forEachRemaining(consumer: (p1: any) => void): void; it: java.util.Iterator<any>; constructor(it: java.util.Iterator<any>); /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): T; /** * */ remove(): void; } class RandomHolder { static rnd: java.util.Random; static rnd_$LI$(): java.util.Random; constructor(); } class UnmodifiableList<T> extends Collections.UnmodifiableCollection<T> implements java.util.List<T> { sort(c: java.util.Comparator<any>): void; list: java.util.List<any>; constructor(list: java.util.List<any>); add$int$java_lang_Object(index: number, element: T): void; /** * * @param {number} index * @param {*} element */ add(index?: any, element?: any): any; addAll$int$java_util_Collection(index: number, c: java.util.Collection<any>): boolean; /** * * @param {number} index * @param {*} c * @return {boolean} */ addAll(index?: any, c?: any): boolean; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @param {number} index * @return {*} */ get(index: number): T; /** * * @return {number} */ hashCode(): number; /** * * @param {*} o * @return {number} */ indexOf(o: any): number; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @param {*} o * @return {number} */ lastIndexOf(o: any): number; listIterator$(): java.util.ListIterator<T>; listIterator$int(from: number): java.util.ListIterator<T>; /** * * @param {number} from * @return {*} */ listIterator(from?: any): java.util.ListIterator<T>; remove$int(index: number): T; /** * * @param {number} index * @return {*} */ remove(index?: any): any; /** * * @param {number} index * @param {*} element * @return {*} */ set(index: number, element: T): T; /** * * @param {number} fromIndex * @param {number} toIndex * @return {*} */ subList(fromIndex: number, toIndex: number): java.util.List<T>; } class UnmodifiableSet<T> extends Collections.UnmodifiableCollection<T> implements java.util.Set<T> { constructor(set: java.util.Set<any>); /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {number} */ hashCode(): number; } class UnmodifiableListIterator<T> extends Collections.UnmodifiableCollectionIterator<T> implements java.util.ListIterator<T> { lit: java.util.ListIterator<any>; constructor(lit: java.util.ListIterator<any>); /** * * @param {*} o */ add(o: T): void; /** * * @return {boolean} */ hasPrevious(): boolean; /** * * @return {number} */ nextIndex(): number; /** * * @return {*} */ previous(): T; /** * * @return {number} */ previousIndex(): number; /** * * @param {*} o */ set(o: T): void; } class UnmodifiableRandomAccessList<T> extends Collections.UnmodifiableList<T> implements java.util.RandomAccess { constructor(list: java.util.List<any>); } class UnmodifiableMap<K, V> implements java.util.Map<K, V> { getOrDefault(key: any, defaultValue: any): any; computeIfAbsent(key: any, mappingFunction: (p1: any) => any): any; replaceAll(__function: (p1: any, p2: any) => any): void; merge(key: any, value: any, map: (p1: any, p2: any) => any): any; putIfAbsent(key: any, value: any): any; __entrySet: Collections.UnmodifiableSet<java.util.Map.Entry<K, V>>; __keySet: Collections.UnmodifiableSet<K>; map: java.util.Map<any, any>; __values: Collections.UnmodifiableCollection<V>; constructor(map: java.util.Map<any, any>); /** * */ clear(): void; /** * * @param {*} key * @return {boolean} */ containsKey(key: any): boolean; /** * * @param {*} val * @return {boolean} */ containsValue(val: any): boolean; /** * * @return {*} */ entrySet(): java.util.Set<java.util.Map.Entry<K, V>>; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @param {*} key * @return {*} */ get(key: any): V; /** * * @return {number} */ hashCode(): number; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @return {*} */ keySet(): java.util.Set<K>; /** * * @param {*} key * @param {*} value * @return {*} */ put(key: K, value: V): V; /** * * @param {*} t */ putAll(t: java.util.Map<any, any>): void; /** * * @param {*} key * @return {*} */ remove(key: any): V; /** * * @return {number} */ size(): number; /** * * @return {string} */ toString(): string; /** * * @return {*} */ values(): java.util.Collection<V>; } namespace UnmodifiableMap { class UnmodifiableEntrySet<K, V> extends Collections.UnmodifiableSet<java.util.Map.Entry<K, V>> { constructor(s: java.util.Set<any>); /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @param {*} o * @return {boolean} */ containsAll(o: java.util.Collection<any>): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<java.util.Map.Entry<K, V>>; toArray$(): any[]; toArray$java_lang_Object_A<T>(a: T[]): T[]; /** * * @param {T[]} a * @return {T[]} */ toArray<T0 = any>(a?: any): any; /** * Wrap an array of Map.Entries as UnmodifiableEntries. * * @param {java.lang.Object[]} array * array to wrap * @param {number} size * number of entries to wrap * @private */ wrap(array: any[], size: number): void; } namespace UnmodifiableEntrySet { class UnmodifiableEntry<K, V> implements java.util.Map.Entry<K, V> { entry: java.util.Map.Entry<any, any>; constructor(entry: java.util.Map.Entry<any, any>); /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {*} */ getKey(): K; /** * * @return {*} */ getValue(): V; /** * * @return {number} */ hashCode(): number; /** * * @param {*} value * @return {*} */ setValue(value: V): V; /** * * @return {string} */ toString(): string; } class UnmodifiableEntrySet$0 implements java.util.Iterator<java.util.Map.Entry<any, any>> { private it; __parent: any; forEachRemaining(consumer: (p1: any) => void): void; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): java.util.Map.Entry<any, any>; /** * */ remove(): void; constructor(__parent: any, it: any); } } } class UnmodifiableSortedSet<E> extends Collections.UnmodifiableSet<E> implements java.util.SortedSet<E> { sortedSet: java.util.SortedSet<E>; constructor(sortedSet: java.util.SortedSet<any>); /** * * @return {*} */ comparator(): java.util.Comparator<any>; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {*} */ first(): E; /** * * @return {number} */ hashCode(): number; /** * * @param {*} toElement * @return {*} */ headSet(toElement: E): java.util.SortedSet<E>; /** * * @return {*} */ last(): E; /** * * @param {*} fromElement * @param {*} toElement * @return {*} */ subSet(fromElement: E, toElement: E): java.util.SortedSet<E>; /** * * @param {*} fromElement * @return {*} */ tailSet(fromElement: E): java.util.SortedSet<E>; } class UnmodifiableSortedMap<K, V> extends Collections.UnmodifiableMap<K, V> implements java.util.SortedMap<K, V> { sortedMap: java.util.SortedMap<K, any>; constructor(sortedMap: java.util.SortedMap<K, any>); /** * * @return {*} */ comparator(): java.util.Comparator<any>; /** * * @param {*} o * @return {boolean} */ equals(o: any): boolean; /** * * @return {*} */ firstKey(): K; /** * * @return {number} */ hashCode(): number; /** * * @param {*} toKey * @return {*} */ headMap(toKey: K): java.util.SortedMap<K, V>; /** * * @return {*} */ lastKey(): K; /** * * @param {*} fromKey * @param {*} toKey * @return {*} */ subMap(fromKey: K, toKey: K): java.util.SortedMap<K, V>; /** * * @param {*} fromKey * @return {*} */ tailMap(fromKey: K): java.util.SortedMap<K, V>; } class Collections$0<T> implements java.util.Enumeration<T> { private it; /** * * @return {boolean} */ hasMoreElements(): boolean; /** * * @return {*} */ nextElement(): T; constructor(it: any); } } } declare namespace java.util { /** * Hash table and linked-list implementation of the Set interface with * predictable iteration order. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashSet.html">[Sun * docs]</a> * * @param <E> element type. * @param {number} ignored * @param {number} alsoIgnored * @class * @extends java.util.HashSet */ class LinkedHashSet<E> extends java.util.HashSet<E> implements java.util.Set<E>, java.lang.Cloneable { constructor(ignored?: any, alsoIgnored?: any); /** * * @return {*} */ clone(): any; } } declare namespace java.util { /** * Maintains a last-in, first-out collection of objects. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Stack.html">[Sun * docs]</a> * * @param <E> element type. * @class * @extends java.util.Vector */ class Stack<E> extends java.util.Vector<E> { /** * * @return {*} */ clone(): any; empty(): boolean; peek(): E; pop(): E; push(o: E): E; search(o: any): number; constructor(); } } declare namespace java.util { /** * Linked list implementation. * <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html"> * [Sun docs]</a> * * @param <E> * element type. * @param {*} c * @class * @extends java.util.AbstractSequentialList */ class LinkedList<E> extends java.util.AbstractSequentialList<E> implements java.lang.Cloneable, java.util.List<E>, java.util.Deque<E>, java.io.Serializable { removeIf(filter: (p1: any) => boolean): boolean; parallelStream(): java.util.stream.Stream<any>; stream(): java.util.stream.Stream<any>; sort(c: java.util.Comparator<any>): void; forEach(action: (p1: any) => void): void; /** * Ensures that RPC will consider type parameter E to be exposed. It will be * pruned by dead code elimination. */ exposeElement: E; /** * Header node - header.next is the first element of the list. */ header: LinkedList.Node<E>; /** * Tail node - tail.prev is the last element of the list. */ tail: LinkedList.Node<E>; /** * Number of nodes currently present in the list. */ __size: number; constructor(c?: any); /** * * @param {number} index * @param {*} element */ add(index?: any, element?: any): any; add$java_lang_Object(o: E): boolean; /** * * @param {*} o */ addFirst(o: E): void; /** * * @param {*} o */ addLast(o: E): void; /** * */ clear(): void; reset(): void; clone(): any; /** * * @return {*} */ descendingIterator(): java.util.Iterator<E>; /** * * @return {*} */ element(): E; /** * * @return {*} */ getFirst(): E; /** * * @return {*} */ getLast(): E; listIterator$int(index: number): java.util.ListIterator<E>; /** * * @param {number} index * @return {*} */ listIterator(index?: any): any; /** * * @param {*} o * @return {boolean} */ offer(o: E): boolean; /** * * @param {*} e * @return {boolean} */ offerFirst(e: E): boolean; /** * * @param {*} e * @return {boolean} */ offerLast(e: E): boolean; /** * * @return {*} */ peek(): E; /** * * @return {*} */ peekFirst(): E; /** * * @return {*} */ peekLast(): E; /** * * @return {*} */ poll(): E; /** * * @return {*} */ pollFirst(): E; /** * * @return {*} */ pollLast(): E; /** * * @return {*} */ pop(): E; /** * * @param {*} e */ push(e: E): void; /** * * @param {number} index * @return {*} */ remove(index?: any): any; remove$(): E; /** * * @return {*} */ removeFirst(): E; /** * * @param {*} o * @return {boolean} */ removeFirstOccurrence(o: any): boolean; /** * * @return {*} */ removeLast(): E; /** * * @param {*} o * @return {boolean} */ removeLastOccurrence(o: any): boolean; /** * * @return {number} */ size(): number; addNode(o: E, prev: LinkedList.Node<E>, next: LinkedList.Node<E>): void; removeNode(node: LinkedList.Node<E>): E; } namespace LinkedList { class DescendingIteratorImpl implements java.util.Iterator<any> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; itr: java.util.ListIterator<any>; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): any; /** * */ remove(): void; constructor(__parent: any); } /** * @param {number} index * from the beginning of the list (0 = first node) * @param {java.util.LinkedList.Node} startNode * the initial current node * @class */ class ListIteratorImpl2 implements java.util.ListIterator<any> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; /** * The index to the current position. */ currentIndex: number; /** * Current node, to be returned from next. */ currentNode: LinkedList.Node<any>; /** * The last node returned from next/previous, or null if deleted or * never called. */ lastNode: LinkedList.Node<any>; constructor(__parent: any, index: number, startNode: LinkedList.Node<any>); /** * * @param {*} o */ add(o: any): void; /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {boolean} */ hasPrevious(): boolean; /** * * @return {*} */ next(): any; /** * * @return {number} */ nextIndex(): number; /** * * @return {*} */ previous(): any; /** * * @return {number} */ previousIndex(): number; /** * */ remove(): void; /** * * @param {*} o */ set(o: any): void; } /** * Internal class representing a doubly-linked list node. * * @param <E> * element type * @class */ class Node<E> { next: LinkedList.Node<E>; prev: LinkedList.Node<E>; value: E; constructor(); } } } declare namespace java.util { class InputMismatchException extends java.util.NoSuchElementException { constructor(message?: any); } } declare namespace java.nio { class InvalidMarkException extends java.lang.IllegalStateException { constructor(); } } declare namespace java.util.regex { class PatternSyntaxException extends java.lang.IllegalArgumentException { pattern: string; constructor(desc?: any, pattern?: any, index?: any); static createSyntaxError(desc: string, index: number): Error; getIndex(): number; getDescription(): string; getPattern(): string; /** * * @return {string} */ getMessage(): string; } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/NumberFormatException.html">the * official Java API doc</a> for details. * @param {string} message * @class * @extends java.lang.IllegalArgumentException */ class NumberFormatException extends java.lang.IllegalArgumentException { static forInputString(s: string): java.lang.NumberFormatException; static forNullInputString(): java.lang.NumberFormatException; static forRadix(radix: number): java.lang.NumberFormatException; constructor(message?: any); } } declare namespace java.nio.charset { /** * GWT emulation of {@link IllegalCharsetNameException}. * @param {string} charsetName * @class * @extends java.lang.IllegalArgumentException */ class IllegalCharsetNameException extends java.lang.IllegalArgumentException { charsetName: string; constructor(charsetName: string); getCharsetName(): string; } } declare namespace java.nio.charset { /** * GWT emulation of {@link UnsupportedCharsetException}. * @param {string} charsetName * @class * @extends java.lang.IllegalArgumentException */ class UnsupportedCharsetException extends java.lang.IllegalArgumentException { charsetName: string; constructor(charsetName: string); getCharsetName(): string; } } declare namespace java.nio { class ReadOnlyBufferException extends java.lang.UnsupportedOperationException { constructor(); } } declare namespace java.lang { /** * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringIndexOfBoundsException.html">the * official Java API doc</a> for details. * @param {string} message * @class * @extends java.lang.IndexOutOfBoundsException */ class StringIndexOutOfBoundsException extends java.lang.IndexOutOfBoundsException { constructor(message?: any); } } declare namespace java.lang { /** * NOTE: in GWT this will never be thrown for normal array accesses, only for * explicit throws. * * See <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ArrayIndexOutOfBoundsException.html">the * official Java API doc</a> for details. * @param {number} index * @class * @extends java.lang.IndexOutOfBoundsException */ class ArrayIndexOutOfBoundsException extends java.lang.IndexOutOfBoundsException { constructor(msg?: any); } } declare namespace java.util { /** * Map using reference equality on keys. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/IdentityHashMap.html">[Sun * docs]</a> * * @param <K> key type * @param <V> value type * @param {number} ignored * @class * @extends java.util.AbstractHashMap */ class IdentityHashMap<K, V> extends java.util.AbstractHashMap<K, V> implements java.util.Map<K, V>, java.lang.Cloneable, java.io.Serializable { getOrDefault(key: any, defaultValue: any): any; computeIfAbsent(key: any, mappingFunction: (p1: any) => any): any; replaceAll(__function: (p1: any, p2: any) => any): void; merge(key: any, value: any, map: (p1: any, p2: any) => any): any; putIfAbsent(key: any, value: any): any; /** * Ensures that RPC will consider type parameter K to be exposed. It will be * pruned by dead code elimination. */ exposeKey: K; /** * Ensures that RPC will consider type parameter V to be exposed. It will be * pruned by dead code elimination. */ exposeValue: V; constructor(toBeCopied?: any); clone(): any; /** * * @param {*} obj * @return {boolean} */ equals(obj: any): boolean; /** * * @return {number} */ hashCode(): number; /** * * @param {*} value1 * @param {*} value2 * @return {boolean} */ _equals(value1: any, value2: any): boolean; /** * * @param {*} key * @return {number} */ getHashCode(key: any): number; } } declare namespace java.util { /** * Implementation of Map interface based on a hash table. <a * href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html">[Sun * docs]</a> * * @param <K> key type * @param <V> value type * @param {number} ignored * @param {number} alsoIgnored * @class * @extends java.util.AbstractHashMap */ class HashMap<K, V> extends java.util.AbstractHashMap<K, V> implements java.lang.Cloneable, java.io.Serializable { /** * Ensures that RPC will consider type parameter K to be exposed. It will be * pruned by dead code elimination. */ exposeKey: K; /** * Ensures that RPC will consider type parameter V to be exposed. It will be * pruned by dead code elimination. */ exposeValue: V; constructor(ignored?: any, alsoIgnored?: any); clone(): any; /** * * @param {*} value1 * @param {*} value2 * @return {boolean} */ _equals(value1: any, value2: any): boolean; /** * * @param {*} key * @return {number} */ getHashCode(key: any): number; } } declare namespace java.util { /** * Implements a TreeMap using a red-black tree. This guarantees O(log n) * performance on lookups, inserts, and deletes while maintaining linear * in-order traversal time. Null keys and values are fully supported if the * comparator supports them (the default comparator does not). * * @param <K> key type * @param <V> value type * @param {*} c * @class * @extends java.util.AbstractNavigableMap */ class TreeMap<K, V> extends java.util.AbstractNavigableMap<K, V> implements java.io.Serializable { static SubMapType_All: TreeMap.SubMapType; static SubMapType_All_$LI$(): TreeMap.SubMapType; static SubMapType_Head: TreeMap.SubMapType; static SubMapType_Head_$LI$(): TreeMap.SubMapType; static SubMapType_Range: TreeMap.SubMapType; static SubMapType_Range_$LI$(): TreeMap.SubMapType; static SubMapType_Tail: TreeMap.SubMapType; static SubMapType_Tail_$LI$(): TreeMap.SubMapType; static LEFT: number; static RIGHT: number; static otherChild(child: number): number; cmp: java.util.Comparator<any>; exposeKeyType: K; exposeValueType: V; root: TreeMap.Node<K, V>; __size: number; constructor(c?: any); /** * */ clear(): void; /** * * @return {*} */ comparator(): java.util.Comparator<any>; /** * * @return {*} */ entrySet(): java.util.Set<Map.Entry<K, V>>; headMap$java_lang_Object$boolean(toKey: K, inclusive: boolean): java.util.NavigableMap<K, V>; /** * * @param {*} toKey * @param {boolean} inclusive * @return {*} */ headMap(toKey?: any, inclusive?: any): any; /** * * @param {*} key * @param {*} value * @return {*} */ put(key: K, value: V): V; /** * * @param {*} k * @return {*} */ remove(k: any): V; /** * * @return {number} */ size(): number; subMap$java_lang_Object$boolean$java_lang_Object$boolean(fromKey: K, fromInclusive: boolean, toKey: K, toInclusive: boolean): java.util.NavigableMap<K, V>; /** * * @param {*} fromKey * @param {boolean} fromInclusive * @param {*} toKey * @param {boolean} toInclusive * @return {*} */ subMap(fromKey?: any, fromInclusive?: any, toKey?: any, toInclusive?: any): any; tailMap$java_lang_Object$boolean(fromKey: K, inclusive: boolean): java.util.NavigableMap<K, V>; /** * * @param {*} fromKey * @param {boolean} inclusive * @return {*} */ tailMap(fromKey?: any, inclusive?: any): any; /** * Returns the first node which compares greater than the given key. * * @param {*} key the key to search for * @return {java.util.TreeMap.Node} the next node, or null if there is none * @param {boolean} inclusive * @private */ getNodeAfter(key: K, inclusive: boolean): TreeMap.Node<K, V>; /** * Returns the last node which is strictly less than the given key. * * @param {*} key the key to search for * @return {java.util.TreeMap.Node} the previous node, or null if there is none * @param {boolean} inclusive * @private */ getNodeBefore(key: K, inclusive: boolean): TreeMap.Node<K, V>; assertCorrectness$(): void; /** * * @return {*} */ descendingEntryIterator(): java.util.Iterator<Map.Entry<K, V>>; /** * * @return {*} */ entryIterator(): java.util.Iterator<Map.Entry<K, V>>; assertCorrectness$java_util_TreeMap_Node$boolean(tree: TreeMap.Node<K, V>, isRed: boolean): number; /** * Internal helper function for public {@link #assertCorrectness()}. * * @param {java.util.TreeMap.Node} tree the subtree to validate. * @param {boolean} isRed true if the parent of this node is red. * @return {number} the black height of this subtree. * @throws RuntimeException if this RB-tree is not valid. * @private */ assertCorrectness(tree?: any, isRed?: any): any; /** * Finds an entry given a key and returns the node. * * @param {*} key the search key * @return {*} the node matching the key or null */ getEntry(key: K): Map.Entry<K, V>; /** * Returns the left-most node of the tree, or null if empty. * @return {*} */ getFirstEntry(): Map.Entry<K, V>; /** * Returns the right-most node of the tree, or null if empty. * @return {*} */ getLastEntry(): Map.Entry<K, V>; /** * * @param {*} key * @return {*} */ getCeilingEntry(key: K): Map.Entry<K, V>; /** * * @param {*} key * @return {*} */ getFloorEntry(key: K): Map.Entry<K, V>; /** * * @param {*} key * @return {*} */ getHigherEntry(key: K): Map.Entry<K, V>; /** * * @param {*} key * @return {*} */ getLowerEntry(key: K): Map.Entry<K, V>; /** * * @param {*} entry * @return {boolean} */ removeEntry(entry: Map.Entry<K, V>): boolean; inOrderAdd(list: java.util.List<Map.Entry<K, V>>, type: TreeMap.SubMapType, current: TreeMap.Node<K, V>, fromKey: K, fromInclusive: boolean, toKey: K, toInclusive: boolean): void; inRange(type: TreeMap.SubMapType, key: K, fromKey: K, fromInclusive: boolean, toKey: K, toInclusive: boolean): boolean; /** * Insert a node into a subtree, collecting state about the insertion. * * If the same key already exists, the value of the node is overwritten with * the value from the new node instead. * * @param {java.util.TreeMap.Node} tree subtree to insert into * @param {java.util.TreeMap.Node} newNode new node to insert * @param {java.util.TreeMap.State} state result of the insertion: state.found true if the key already * existed in the tree state.value the old value if the key existed * @return {java.util.TreeMap.Node} the new subtree root * @private */ insert(tree: TreeMap.Node<K, V>, newNode: TreeMap.Node<K, V>, state: TreeMap.State<V>): TreeMap.Node<K, V>; /** * Returns true if <code>node</code> is red. Note that null pointers are * considered black. * @param {java.util.TreeMap.Node} node * @return {boolean} * @private */ isRed(node: TreeMap.Node<K, V>): boolean; /** * Returns true if <code>a</code> is greater than or equal to <code>b</code>. * @param {*} a * @param {*} b * @param {boolean} orEqual * @return {boolean} * @private */ larger(a: K, b: K, orEqual: boolean): boolean; /** * Returns true if <code>a</code> is less than or equal to <code>b</code>. * @param {*} a * @param {*} b * @param {boolean} orEqual * @return {boolean} * @private */ smaller(a: K, b: K, orEqual: boolean): boolean; /** * Remove a key from the tree, returning whether it was found and its value. * * @param {*} key key to remove * @param {java.util.TreeMap.State} state return state, not null * @return {boolean} true if the value was found * @private */ removeWithState(key: K, state: TreeMap.State<V>): boolean; /** * replace 'node' with 'newNode' in the tree rooted at 'head'. Could have * avoided this traversal if each node maintained a parent pointer. * @param {java.util.TreeMap.Node} head * @param {java.util.TreeMap.Node} node * @param {java.util.TreeMap.Node} newNode * @private */ replaceNode(head: TreeMap.Node<K, V>, node: TreeMap.Node<K, V>, newNode: TreeMap.Node<K, V>): void; /** * Perform a double rotation, first rotating the child which will become the * root in the opposite direction, then rotating the root in the specified * direction. * * <pre> * A F * B C becomes (with rotateDirection=0) A C * D E F G B E G * D * </pre> * * @param {java.util.TreeMap.Node} tree root of the subtree to rotate * @param {number} rotateDirection the direction to rotate: 0=left, 1=right * @return {java.util.TreeMap.Node} the new root of the rotated subtree * @private */ rotateDouble(tree: TreeMap.Node<K, V>, rotateDirection: number): TreeMap.Node<K, V>; /** * Perform a single rotation, pushing the root of the subtree to the specified * direction. * * <pre> * A B * B C becomes (with rotateDirection=1) D A * D E E C * </pre> * * @param {java.util.TreeMap.Node} tree the root of the subtree to rotate * @param {number} rotateDirection the direction to rotate: 0=left rotation, 1=right * @return {java.util.TreeMap.Node} the new root of the rotated subtree * @private */ rotateSingle(tree: TreeMap.Node<K, V>, rotateDirection: number): TreeMap.Node<K, V>; } namespace TreeMap { /** * Create an iterator which may return only a restricted range. * * @param {*} fromKey the first key to return in the iterator. * @param {*} toKey the upper bound of keys to return. * @param {java.util.TreeMap.SubMapType} type * @param {boolean} fromInclusive * @param {boolean} toInclusive * @class */ class DescendingEntryIterator implements java.util.Iterator<Map.Entry<any, any>> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; iter: java.util.ListIterator<Map.Entry<any, any>>; last: Map.Entry<any, any>; constructor(__parent: any, type?: any, fromKey?: any, fromInclusive?: any, toKey?: any, toInclusive?: any); /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): Map.Entry<any, any>; /** * */ remove(): void; } /** * Create an iterator which may return only a restricted range. * * @param {*} fromKey the first key to return in the iterator. * @param {*} toKey the upper bound of keys to return. * @param {java.util.TreeMap.SubMapType} type * @param {boolean} fromInclusive * @param {boolean} toInclusive * @class */ class EntryIterator implements java.util.Iterator<Map.Entry<any, any>> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; iter: java.util.ListIterator<Map.Entry<any, any>>; last: Map.Entry<any, any>; constructor(__parent: any, type?: any, fromKey?: any, fromInclusive?: any, toKey?: any, toInclusive?: any); /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): Map.Entry<any, any>; /** * */ remove(): void; } class __java_util_TreeMap_EntrySet extends java.util.AbstractNavigableMap.EntrySet { __parent: any; /** * */ clear(): void; constructor(__parent: any); } /** * Create a node of the specified color. * * @param {*} key * @param {*} value * @param {boolean} isRed true if this should be a red node, false for black * @class * @extends java.util.AbstractMap.SimpleEntry */ class Node<K, V> extends AbstractMap.SimpleEntry<K, V> { child: TreeMap.Node<K, V>[]; isRed: boolean; constructor(key?: any, value?: any, isRed?: any); } /** * A state object which is passed down the tree for both insert and remove. * All uses make use of the done flag to indicate when no further rebalancing * of the tree is required. Remove methods use the found flag to indicate when * the desired key has been found. value is used both to return the value of a * removed node as well as to pass in a value which must match (used for * entrySet().remove(entry)), and the matchValue flag is used to request this * behavior. * * @param <V> value type * @class */ class State<V> { done: boolean; found: boolean; matchValue: boolean; value: V; /** * * @return {string} */ toString(): string; constructor(); } class SubMap extends java.util.AbstractNavigableMap<any, any> { __parent: any; fromInclusive: boolean; fromKey: any; toInclusive: boolean; toKey: any; type: TreeMap.SubMapType; constructor(__parent: any, type: TreeMap.SubMapType, fromKey: any, fromInclusive: boolean, toKey: any, toInclusive: boolean); /** * * @return {*} */ comparator(): java.util.Comparator<any>; /** * * @return {*} */ entrySet(): java.util.Set<Map.Entry<any, any>>; headMap$java_lang_Object$boolean(toKey: any, toInclusive: boolean): java.util.NavigableMap<any, any>; /** * * @param {*} toKey * @param {boolean} toInclusive * @return {*} */ headMap(toKey?: any, toInclusive?: any): any; /** * * @return {boolean} */ isEmpty(): boolean; /** * * @param {*} key * @param {*} value * @return {*} */ put(key: any, value: any): any; /** * * @param {*} k * @return {*} */ remove(k: any): any; /** * * @return {number} */ size(): number; subMap$java_lang_Object$boolean$java_lang_Object$boolean(newFromKey: any, newFromInclusive: boolean, newToKey: any, newToInclusive: boolean): java.util.NavigableMap<any, any>; /** * * @param {*} newFromKey * @param {boolean} newFromInclusive * @param {*} newToKey * @param {boolean} newToInclusive * @return {*} */ subMap(newFromKey?: any, newFromInclusive?: any, newToKey?: any, newToInclusive?: any): any; tailMap$java_lang_Object$boolean(fromKey: any, fromInclusive: boolean): java.util.NavigableMap<any, any>; /** * * @param {*} fromKey * @param {boolean} fromInclusive * @return {*} */ tailMap(fromKey?: any, fromInclusive?: any): any; /** * * @return {*} */ descendingEntryIterator(): java.util.Iterator<Map.Entry<any, any>>; /** * * @return {*} */ entryIterator(): java.util.Iterator<Map.Entry<any, any>>; /** * * @param {*} key * @return {*} */ getEntry(key: any): Map.Entry<any, any>; /** * * @return {*} */ getFirstEntry(): Map.Entry<any, any>; /** * * @return {*} */ getLastEntry(): Map.Entry<any, any>; /** * * @param {*} key * @return {*} */ getCeilingEntry(key: any): Map.Entry<any, any>; /** * * @param {*} key * @return {*} */ getFloorEntry(key: any): Map.Entry<any, any>; /** * * @param {*} key * @return {*} */ getHigherEntry(key: any): Map.Entry<any, any>; /** * * @param {*} key * @return {*} */ getLowerEntry(key: any): Map.Entry<any, any>; /** * * @param {*} entry * @return {boolean} */ removeEntry(entry: Map.Entry<any, any>): boolean; guardInRange(entry: Map.Entry<any, any>): Map.Entry<any, any>; inRange(key: any): boolean; } namespace SubMap { class SubMap$0 extends TreeMap.SubMap.EntrySet { __parent: any; /** * * @return {boolean} */ isEmpty(): boolean; constructor(__parent: any); } } class SubMapType { /** * Returns true if this submap type uses a from-key. * @return {boolean} */ fromKeyValid(): boolean; /** * Returns true if this submap type uses a to-key. * @return {boolean} */ toKeyValid(): boolean; constructor(); } class SubMapTypeHead extends TreeMap.SubMapType { /** * * @return {boolean} */ toKeyValid(): boolean; constructor(); } class SubMapTypeRange extends TreeMap.SubMapType { /** * * @return {boolean} */ fromKeyValid(): boolean; /** * * @return {boolean} */ toKeyValid(): boolean; constructor(); } class SubMapTypeTail extends TreeMap.SubMapType { /** * * @return {boolean} */ fromKeyValid(): boolean; constructor(); } } } declare namespace java.util.stream { class Collectors { static throwingMerger<T>(): (p1: T, p2: T) => T; static CH_ID: java.util.Set<java.util.stream.Collector.Characteristics>; static CH_ID_$LI$(): java.util.Set<java.util.stream.Collector.Characteristics>; static CH_NOID: java.util.Set<java.util.stream.Collector.Characteristics>; static CH_NOID_$LI$(): java.util.Set<java.util.stream.Collector.Characteristics>; static toList<T>(): java.util.stream.Collector<T, any, java.util.List<T>>; static toSet<T>(): java.util.stream.Collector<T, any, java.util.Set<T>>; static toMap$java_util_function_Function$java_util_function_Function<T, K, U>(keyMapper: (p1: any) => any, valueMapper: (p1: any) => any): java.util.stream.Collector<T, any, java.util.Map<K, U>>; static toMap$java_util_function_Function$java_util_function_Function$java_util_function_BinaryOperator<T, K, U>(keyMapper: (p1: any) => any, valueMapper: (p1: any) => any, mergeFunction: (p1: U, p2: U) => U): java.util.stream.Collector<T, any, java.util.Map<K, U>>; static toMap$java_util_function_Function$java_util_function_Function$java_util_function_BinaryOperator$java_util_function_Supplier<T, K, U, M extends java.util.Map<K, U>>(keyMapper: (p1: any) => any, valueMapper: (p1: any) => any, mergeFunction: (p1: U, p2: U) => U, mapSupplier: () => M): java.util.stream.Collector<T, any, M>; static toMap<T0 = any, T1 = any, T2 = any, T3 = any>(keyMapper?: any, valueMapper?: any, mergeFunction?: any, mapSupplier?: any): any; static mapMerger<K, V, M extends java.util.Map<K, V>>(mergeFunction: (p1: V, p2: V) => V): (p1: M, p2: M) => M; static joining$(): java.util.stream.Collector<any, any, string>; static joining$java_lang_CharSequence(delimiter: any): java.util.stream.Collector<any, any, string>; static joining$java_lang_CharSequence$java_lang_CharSequence$java_lang_CharSequence(delimiter: any, prefix: any, suffix: any): java.util.stream.Collector<any, any, string>; /** * Returns a {@code Collector} that concatenates the input elements, separated * by the specified delimiter, with the specified prefix and suffix, in * encounter order. * * @param {*} delimiter * the delimiter to be used between each element * @param {*} prefix * the sequence of characters to be used at the beginning of the * joined result * @param {*} suffix * the sequence of characters to be used at the end of the joined * result * @return {*} A {@code Collector} which concatenates CharSequence elements, * separated by the specified delimiter, in encounter order */ static joining(delimiter?: any, prefix?: any, suffix?: any): java.util.stream.Collector<any, any, string>; static groupingBy$java_util_function_Function$java_util_stream_Collector<T, K, A, D>(classifier: (p1: any) => any, downstream: java.util.stream.Collector<any, A, D>): java.util.stream.Collector<T, any, java.util.Map<K, D>>; static groupingBy$java_util_function_Function$java_util_function_Supplier$java_util_stream_Collector<T, K, D, A, M extends java.util.Map<K, D>>(classifier: (p1: any) => any, mapFactory: () => M, downstream: java.util.stream.Collector<any, A, D>): java.util.stream.Collector<T, any, M>; static groupingBy<T0 = any, T1 = any, T2 = any, T3 = any, T4 = any>(classifier?: any, mapFactory?: any, downstream?: any): any; static mapping<T, U, A, R>(mapper: (p1: any) => any, downstream: java.util.stream.Collector<any, A, R>): java.util.stream.Collector<T, any, R>; static reducing$java_lang_Object$java_util_function_BinaryOperator<T>(identity: T, op: (p1: T, p2: T) => T): java.util.stream.Collector<T, any, T>; static reducing$java_lang_Object$java_util_function_Function$java_util_function_BinaryOperator<T, U>(identity: U, mapper: (p1: any) => any, op: (p1: U, p2: U) => U): java.util.stream.Collector<T, any, U>; static reducing<T0 = any, T1 = any>(identity?: any, mapper?: any, op?: any): any; static boxSupplier<T>(identity: T): () => T[]; } namespace Collectors { class CollectorImpl<T, A, R> implements java.util.stream.Collector<T, A, R> { __supplier: () => A; __accumulator: (p1: A, p2: T) => void; __combiner: (p1: A, p2: A) => A; __characteristics: java.util.Set<Collector.Characteristics>; __finisher: (p1: A) => R; constructor(supplier?: any, accumulator?: any, combiner?: any, finisher?: any, characteristics?: any); static castingIdentity<I, R>(): (p1: I) => R; /** * * @return {*} */ accumulator(): (p1: A, p2: T) => void; /** * * @return {*} */ supplier(): () => A; /** * * @return {*} */ combiner(): (p1: A, p2: A) => A; /** * * @return {*} */ finisher(): (p1: A) => R; /** * * @return {*} */ characteristics(): java.util.Set<Collector.Characteristics>; } } } declare namespace java.util { /** * Hash table implementation of the Map interface with predictable iteration * order. <a href= * "http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html">[Sun * docs]</a> * * @param <K> * key type. * @param <V> * value type. * @param {number} ignored * @param {number} alsoIgnored * @param {boolean} accessOrder * @class * @extends java.util.HashMap */ class LinkedHashMap<K, V> extends java.util.HashMap<K, V> implements java.util.Map<K, V> { getOrDefault(key: any, defaultValue: any): any; computeIfAbsent(key: any, mappingFunction: (p1: any) => any): any; replaceAll(__function: (p1: any, p2: any) => any): void; merge(key: any, value: any, map: (p1: any, p2: any) => any): any; putIfAbsent(key: any, value: any): any; accessOrder: boolean; head: LinkedHashMap.ChainEntry; map: java.util.HashMap<K, LinkedHashMap.ChainEntry>; constructor(ignored?: any, alsoIgnored?: any, accessOrder?: any); /** * */ clear(): void; resetChainEntries(): void; /** * * @return {*} */ clone(): any; /** * * @param {*} key * @return {boolean} */ containsKey(key: any): boolean; /** * * @param {*} value * @return {boolean} */ containsValue(value: any): boolean; /** * * @return {*} */ entrySet(): java.util.Set<java.util.Map.Entry<K, V>>; /** * * @param {*} key * @return {*} */ get(key: any): V; /** * * @param {*} key * @param {*} value * @return {*} */ put(key: K, value: V): V; /** * * @param {*} key * @return {*} */ remove(key: any): V; /** * * @return {number} */ size(): number; removeEldestEntry(eldest: java.util.Map.Entry<K, V>): boolean; recordAccess(entry: LinkedHashMap.ChainEntry): void; } namespace LinkedHashMap { /** * The entry we use includes next/prev pointers for a doubly-linked circular * list with a head node. This reduces the special cases we have to deal * with in the list operations. * * Note that we duplicate the key from the underlying hash map so we can * find the eldest entry. The alternative would have been to modify HashMap * so more of the code was directly usable here, but this would have added * some overhead to HashMap, or to reimplement most of the HashMap code here * with small modifications. Paying a small storage cost only if you use * LinkedHashMap and minimizing code size seemed like a better tradeoff * @param {*} key * @param {*} value * @class * @extends java.util.AbstractMap.SimpleEntry */ class ChainEntry extends AbstractMap.SimpleEntry<any, any> { __parent: any; next: LinkedHashMap.ChainEntry; prev: LinkedHashMap.ChainEntry; constructor(__parent: any, key?: any, value?: any); /** * Add this node to the end of the chain. */ addToEnd(): void; /** * Remove this node from any list it may be a part of. */ remove(): void; } class __java_util_LinkedHashMap_EntrySet extends java.util.AbstractSet<java.util.Map.Entry<any, any>> { __parent: any; /** * */ clear(): void; /** * * @param {*} o * @return {boolean} */ contains(o: any): boolean; /** * * @return {*} */ iterator(): java.util.Iterator<java.util.Map.Entry<any, any>>; /** * * @param {*} entry * @return {boolean} */ remove(entry: any): boolean; /** * * @return {number} */ size(): number; constructor(__parent: any); } namespace __java_util_LinkedHashMap_EntrySet { class EntryIterator implements java.util.Iterator<java.util.Map.Entry<any, any>> { __parent: any; forEachRemaining(consumer: (p1: any) => void): void; last: LinkedHashMap.ChainEntry; __next: LinkedHashMap.ChainEntry; constructor(__parent: any); /** * * @return {boolean} */ hasNext(): boolean; /** * * @return {*} */ next(): java.util.Map.Entry<any, any>; /** * */ remove(): void; } } } } declare namespace java.util { class ConcurrentHashMap<K, V> extends java.util.HashMap<K, V> { constructor(); } } declare namespace java.util { class Hashtable<K, V> extends java.util.HashMap<K, V> implements java.util.Dictionary<K, V> { static serialVersionUID: number; constructor(ignored?: any, alsoIgnored?: any); keys(): java.util.Enumeration<K>; elements(): java.util.Enumeration<V>; } namespace Hashtable { class Hashtable$0 implements java.util.Enumeration<any> { private it; __parent: any; /** * * @return {boolean} */ hasMoreElements(): boolean; /** * * @return {*} */ nextElement(): any; constructor(__parent: any, it: any); } class Hashtable$1 implements java.util.Enumeration<any> { private it; __parent: any; /** * * @return {boolean} */ hasMoreElements(): boolean; /** * * @return {*} */ nextElement(): any; constructor(__parent: any, it: any); } } } declare namespace java.lang { class System { static __static_initialized: boolean; static __static_initialize(): void; static ENVIRONMENT_IS_WEB: boolean; static ENVIRONMENT_IS_WEB_$LI$(): boolean; static ENVIRONMENT_IS_WORKER: boolean; static ENVIRONMENT_IS_WORKER_$LI$(): boolean; static ENVIRONMENT_IS_NODE: boolean; static ENVIRONMENT_IS_NODE_$LI$(): boolean; static ENVIRONMENT_IS_SHELL: boolean; static ENVIRONMENT_IS_SHELL_$LI$(): boolean; static propertyMap: java.util.Map<string, string>; static propertyMap_$LI$(): java.util.Map<string, string>; static err: java.io.PrintStream; static err_$LI$(): java.io.PrintStream; static out: java.io.PrintStream; static out_$LI$(): java.io.PrintStream; static in: java.io.InputStream; static in_$LI$(): java.io.InputStream; static __static_initializer_0(): void; static arraycopy(src: any, srcOfs: number, dest: any, destOfs: number, len: number): void; static currentTimeMillis(): number; static gc(): void; static getProperty$java_lang_String(key: string): string; static getProperty$java_lang_String$java_lang_String(key: string, def: string): string; static getProperty(key?: any, def?: any): string; static identityHashCode(o: any): number; static setErr(err: java.io.PrintStream): void; static setOut(out: java.io.PrintStream): void; static lineSeparator(): string; static exit(status: number): void; } namespace System { class System$0 extends java.io.OutputStream { sep: string; toOut: string; /** * Writes {@code count} bytes from the byte array {@code buffer} starting at * position {@code offset} to this stream. * * @param {byte[]} buffer * the buffer to be written. * @param {number} offset * the start position in {@code buffer} from where to get bytes. * @param {number} count * the number of bytes from {@code buffer} to write to this * stream. * @throws IOException * if an error occurs while writing to this stream. * @throws IndexOutOfBoundsException * if {@code offset < 0} or {@code count < 0}, or if * {@code offset + count} is bigger than the length of * {@code buffer}. */ write(buffer?: any, offset?: any, count?: any): any; write$int(i: number): void; /** * */ flush(): void; constructor(); } class System$1 extends java.io.OutputStream { sep: string; toOut: string; /** * Writes {@code count} bytes from the byte array {@code buffer} starting at * position {@code offset} to this stream. * * @param {byte[]} buffer * the buffer to be written. * @param {number} offset * the start position in {@code buffer} from where to get bytes. * @param {number} count * the number of bytes from {@code buffer} to write to this * stream. * @throws IOException * if an error occurs while writing to this stream. * @throws IndexOutOfBoundsException * if {@code offset < 0} or {@code count < 0}, or if * {@code offset + count} is bigger than the length of * {@code buffer}. */ write(buffer?: any, offset?: any, count?: any): any; write$int(i: number): void; /** * */ flush(): void; constructor(); } class System$2 extends java.io.InputStream { readData: string[]; where: number; sep: string; readerFunction: () => string; /** * Reads up to {@code byteCount} bytes from this stream and stores them in * the byte array {@code buffer} starting at {@code byteOffset}. * Returns the number of bytes actually read or -1 if the end of the stream * has been reached. * * @throws IndexOutOfBoundsException * if {@code byteOffset < 0 || byteCount < 0 || byteOffset + byteCount > buffer.length}. * @throws IOException * if the stream is closed or another IOException occurs. * @param {byte[]} buffer * @param {number} byteOffset * @param {number} byteCount * @return {number} */ read(buffer?: any, byteOffset?: any, byteCount?: any): number; read$(): number; constructor(); } } } declare namespace javaemul.internal { /** * A utility class that provides utility functions to do precondition checks inside GWT-SDK. * @class */ class InternalPreconditions { static CHECKED_MODE: boolean; static CHECKED_MODE_$LI$(): boolean; static TYPE_CHECK: boolean; static TYPE_CHECK_$LI$(): boolean; static API_CHECK: boolean; static API_CHECK_$LI$(): boolean; static BOUND_CHECK: boolean; static BOUND_CHECK_$LI$(): boolean; static checkType(expression: boolean): void; static checkCriticalType(expression: boolean): void; static checkArrayType$boolean(expression: boolean): void; static checkCriticalArrayType$boolean(expression: boolean): void; static checkArrayType$boolean$java_lang_Object(expression: boolean, errorMessage: any): void; /** * Ensures the truth of an expression that verifies array type. * @param {boolean} expression * @param {*} errorMessage */ static checkArrayType(expression?: any, errorMessage?: any): any; static checkCriticalArrayType$boolean$java_lang_Object(expression: boolean, errorMessage: any): void; static checkCriticalArrayType(expression?: any, errorMessage?: any): any; static checkElement$boolean(expression: boolean): void; static checkCriticalElement$boolean(expression: boolean): void; static checkElement$boolean$java_lang_Object(expression: boolean, errorMessage: any): void; /** * Ensures the truth of an expression involving existence of an element. * @param {boolean} expression * @param {*} errorMessage */ static checkElement(expression?: any, errorMessage?: any): any; static checkCriticalElement$boolean$java_lang_Object(expression: boolean, errorMessage: any): void; /** * Ensures the truth of an expression involving existence of an element. * <p> * For cases where failing fast is pretty important and not failing early could cause bugs that * are much harder to debug. * @param {boolean} expression * @param {*} errorMessage */ static checkCriticalElement(expression?: any, errorMessage?: any): any; static checkArgument$boolean(expression: boolean): void; static checkCriticalArgument$boolean(expression: boolean): void; static checkArgument$boolean$java_lang_Object(expression: boolean, errorMessage: any): void; static checkCriticalArgument$boolean$java_lang_Object(expression: boolean, errorMessage: any): void; static checkArgument$boolean$java_lang_String$java_lang_Object_A(expression: boolean, errorMessageTemplate: string, ...errorMessageArgs: any[]): void; /** * Ensures the truth of an expression involving one or more parameters to the calling method. * @param {boolean} expression * @param {string} errorMessageTemplate * @param {java.lang.Object[]} errorMessageArgs */ static checkArgument(expression?: any, errorMessageTemplate?: any, ...errorMessageArgs: any[]): any; static checkCriticalArgument$boolean$java_lang_String$java_lang_Object_A(expression: boolean, errorMessageTemplate: string, ...errorMessageArgs: any[]): void; /** * Ensures the truth of an expression involving one or more parameters to the calling method. * <p> * For cases where failing fast is pretty important and not failing early could cause bugs that * are much harder to debug. * @param {boolean} expression * @param {string} errorMessageTemplate * @param {java.lang.Object[]} errorMessageArgs */ static checkCriticalArgument(expression?: any, errorMessageTemplate?: any, ...errorMessageArgs: any[]): any; static checkState$boolean(expression: boolean): void; /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * <p> * For cases where failing fast is pretty important and not failing early could cause bugs that * are much harder to debug. * @param {boolean} expression */ static checkCritcalState(expression: boolean): void; static checkState$boolean$java_lang_Object(expression: boolean, errorMessage: any): void; /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * @param {boolean} expression * @param {*} errorMessage */ static checkState(expression?: any, errorMessage?: any): any; /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * @param {boolean} expression * @param {*} errorMessage */ static checkCriticalState(expression: boolean, errorMessage: any): void; static checkNotNull$java_lang_Object<T>(reference: T): T; static checkCriticalNotNull$java_lang_Object<T>(reference: T): T; static checkNotNull$java_lang_Object$java_lang_Object(reference: any, errorMessage: any): void; /** * Ensures that an object reference passed as a parameter to the calling method is not null. * @param {*} reference * @param {*} errorMessage */ static checkNotNull<T0 = any>(reference?: any, errorMessage?: any): any; static checkCriticalNotNull$java_lang_Object$java_lang_Object(reference: any, errorMessage: any): void; static checkCriticalNotNull<T0 = any>(reference?: any, errorMessage?: any): any; /** * Ensures that {@code size} specifies a valid array size (i.e. non-negative). * @param {number} size */ static checkArraySize(size: number): void; static checkCriticalArraySize(size: number): void; /** * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive. * @param {number} index * @param {number} size */ static checkElementIndex(index: number, size: number): void; static checkCriticalElementIndex(index: number, size: number): void; /** * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of * size {@code size}. A position index may range from zero to {@code size}, inclusive. * @param {number} index * @param {number} size */ static checkPositionIndex(index: number, size: number): void; static checkCriticalPositionIndex(index: number, size: number): void; /** * Ensures that {@code start} and {@code end} specify a valid <i>positions</i> in an array, list * or string of size {@code size}, and are in order. A position index may range from zero to * {@code size}, inclusive. * @param {number} start * @param {number} end * @param {number} size */ static checkPositionIndexes(start: number, end: number, size: number): void; /** * Ensures that {@code start} and {@code end} specify a valid <i>positions</i> in an array, list * or string of size {@code size}, and are in order. A position index may range from zero to * {@code size}, inclusive. * @param {number} start * @param {number} end * @param {number} size */ static checkCriticalPositionIndexes(start: number, end: number, size: number): void; /** * Checks that bounds are correct. * * @throw StringIndexOutOfBoundsException if the range is not legal * @param {number} start * @param {number} end * @param {number} size */ static checkStringBounds(start: number, end: number, size: number): void; /** * Substitutes each {@code %s} in {@code template} with an argument. These are matched by * position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than * placeholders, the unmatched arguments will be appended to the end of the formatted message in * square braces. * @param {string} template * @param {java.lang.Object[]} args * @return {string} * @private */ static format(template: string, ...args: any[]): string; constructor(); } } declare namespace java.util { /** * A helper to detect concurrent modifications to collections. This is implemented as a helper * utility so that we could remove the checks easily by a flag. * @class */ class ConcurrentModificationDetector { static API_CHECK: boolean; static API_CHECK_$LI$(): boolean; static MOD_COUNT_PROPERTY: string; static structureChanged(map: any): void; static recordLastKnownStructure(host: any, iterator: java.util.Iterator<any>): void; static checkStructuralChange(host: any, iterator: java.util.Iterator<any>): void; } } declare namespace java.util.logging { /** * An emulation of the java.util.logging.Logger class. See * <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/logging/Logger.html"> * The Java API doc for details</a> * @class */ class Logger { static __static_initialized: boolean; static __static_initialize(): void; static GLOBAL_LOGGER_NAME: string; static LOGGING_ENABLED: string; static LOGGING_ENABLED_$LI$(): string; static LOGGING_WARNING: boolean; static LOGGING_WARNING_$LI$(): boolean; static LOGGING_SEVERE: boolean; static LOGGING_SEVERE_$LI$(): boolean; static LOGGING_FALSE: boolean; static LOGGING_FALSE_$LI$(): boolean; static __static_initializer_0(): void; static getGlobal(): Logger; static getLogger(name: string): Logger; static assertLoggingValues(): void; handlers: java.util.List<java.util.logging.Handler>; level: java.util.logging.Level; name: string; parent: Logger; useParentHandlers: boolean; constructor(name: string, resourceName: string); addHandler(handler: java.util.logging.Handler): void; config(msg: string): void; fine(msg: string): void; finer(msg: string): void; finest(msg: string): void; info(msg: string): void; warning(msg: string): void; severe(msg: string): void; getHandlers(): java.util.logging.Handler[]; getLevel(): java.util.logging.Level; getName(): string; getParent(): Logger; getUseParentHandlers(): boolean; isLoggable(messageLevel: java.util.logging.Level): boolean; log$java_util_logging_Level$java_lang_String(level: java.util.logging.Level, msg: string): void; log$java_util_logging_Level$java_lang_String$java_lang_Throwable(level: java.util.logging.Level, msg: string, thrown: Error): void; log(level?: any, msg?: any, thrown?: any): any; log$java_util_logging_LogRecord(record: java.util.logging.LogRecord): void; removeHandler(handler: java.util.logging.Handler): void; setLevel(newLevel: java.util.logging.Level): void; setParent(newParent: Logger): void; setUseParentHandlers(newUseParentHandlers: boolean): void; getEffectiveLevel(): java.util.logging.Level; actuallyLog$java_util_logging_Level$java_lang_String$java_lang_Throwable(level: java.util.logging.Level, msg: string, thrown: Error): void; actuallyLog(level?: any, msg?: any, thrown?: any): any; actuallyLog$java_util_logging_LogRecord(record: java.util.logging.LogRecord): void; } } declare namespace java.nio.file { class Path implements java.lang.Comparable<Path>, java.lang.Iterable<Path> { forEach(action: (p1: any) => void): void; static PATH_SEPARATOR: string; static PATH_SEPARATOR_$LI$(): string; fullPath: string; constructor(fullPath: string); compareTo$java_nio_file_Path(path: Path): number; /** * * @param {java.nio.file.Path} path * @return {number} */ compareTo(path?: any): number; isAbsolute(): boolean; getFileName(): Path; getParent(): Path; resolve$java_nio_file_Path(other: Path): Path; resolve(other?: any): Path; resolve$java_lang_String(other: string): Path; toAbsolutePath(): Path; /** * * @return {*} */ iterator(): java.util.Iterator<Path>; /** * * @return {string} */ toString(): string; } }
the_stack
import React, { ReactNode, useEffect, useState } from 'react' import { useLazyQuery } from '@apollo/client' import { useForm, Controller, ValidationRules, useFormContext, FormProvider, } from 'react-hook-form' import { useDebounce } from 'react-use' import { FormatInputValueFunction } from 'react-number-format' import { useLinkResolver } from '@island.is/web/hooks/useLinkResolver' import { InputController } from '@island.is/shared/form-fields' import { Box, GridColumn, GridContainer, GridRow, Select, Button, Option, Input, Text, LinkContext, Link, Stack, LoadingDots, } from '@island.is/island-ui/core' import { Organizations, SupportCategory } from '@island.is/api/schema' import { GET_SUPPORT_SEARCH_RESULTS_QUERY } from '@island.is/web/screens/queries' import { GetSupportSearchResultsQuery, GetSupportSearchResultsQueryVariables, SearchableContentTypes, SupportQna, } from '@island.is/web/graphql/schema' import { ModifySearchTerms } from '../../SearchInput/SearchInput' type FormState = { message: string name: string email: string category: string syslumadur: string subject: string } interface StandardFormProps { syslumenn?: Organizations['items'] supportCategories?: SupportCategory[] loading: boolean onSubmit: (formState: FormState) => Promise<void> institutionSlug: string } type CategoryId = /** * Fjölskyldumál */ | '4vQ4htPOAZvzcXBcjx06SH' /** * Skírteini */ | '7nWhQCER920RakQ7BZpEmV' /** * Andlát og dánarbú */ | '2TkJynZlamqTHdjUziXDG0' /** * Þinglýsingar, staðfestingar og skráningar */ | '6K9stHLAB2mEyGqtqjnXxf' /** * Gjöld og innheimta */ | '5u2M09Kw3p1Spva1GSuAzB' /** * Löggildingar */ | 'WrQIftmx61sHJMoIr1QRW' /** * Vottorð */ | '76Expbwtudon1Gz5lrKOit' /** * Lögráðamál */ | '4tvRkPgKP3kerbyRJDvaWF' /** * Önnur þjónusta sýslumanna */ | '4LNbNB3GvH3RcoIGpuZKhG' /** * Leyfi */ | '7HbSNTUHJReJ2GPeT1ni1C' /** * Fullnustugerðir */ | '7LkzuYSzqwM7k8fJyeRbm6' const labels = { syslumadur: 'Sýslumannsembætti', nafn: 'Nafn', email: 'Tölvupóstfang', malaflokkur: 'Málaflokkur', nafn_malsadila: 'Nafn málsaðila', kennitala_malsadila: 'Kennitala málsaðila', malsnumer: 'Málsnúmer', nafn_leyfishafa: 'Nafn leyfishafa', nafn_hins_latna: 'Nafn hins látna', kennitala_hins_latna: 'Kennitala hins látna', kennitala_arftaka: 'Kennitala arftaka', kennitala_leyfishafa: 'Kennitala leyfishafa', fastanumer_eignar: 'Fastanúmer eignar', skraningarnumer_okutaekis: 'Skráningarnúmer ökutækis', kennitala_vegna_lausafes: 'Kennitala vegna lausafés', erindi: 'Erindi', vidfangsefni: 'Viðfangsefni', phone: 'Símanúmer', } interface BasicInputProps { name: keyof typeof labels requiredMessage?: string format?: string | FormatInputValueFunction } const BasicInput = ({ name, requiredMessage, format }: BasicInputProps) => { const { errors, register } = useFormContext() return ( <InputController backgroundColor="blue" id={name} name={name} label={labels[name]} error={errors?.[name]?.message} required={!!requiredMessage} format={format} rules={{ ...(requiredMessage && { required: { value: true, message: requiredMessage, }, }), }} {...register(name)} /> ) } const MIN_SEARCH_QUERY_LENGTH = 1 export const StandardForm = ({ syslumenn, supportCategories, loading, onSubmit, institutionSlug, }: StandardFormProps) => { const useFormMethods = useForm({}) const { handleSubmit, getValues, control, errors, formState: { isSubmitting }, } = useFormMethods const { linkResolver } = useLinkResolver() const [syslumadurId, setSyslumadurId] = useState<string>('') const [subject, setSubject] = useState<string>('') const [showAllSuggestions, setShowAllSuggestions] = useState<boolean>(false) const [lastSubject, setLastSubject] = useState<string>('') const [isChangingSubject, setIsChangingSubject] = useState<boolean>(false) const [suggestions, setSuggestions] = useState<Array<SupportQna>>([]) const [categoryId, setCategoryId] = useState<string>('') const [categoryLabel, setCategoryLabel] = useState<string>('') const [addonFields, setAddonFields] = useState<ReactNode | null>() const [fetch, { loading: loadingSuggestions, called, data }] = useLazyQuery< GetSupportSearchResultsQuery, GetSupportSearchResultsQueryVariables >(GET_SUPPORT_SEARCH_RESULTS_QUERY, { onCompleted: () => { setIsChangingSubject(false) updateSuggestions() }, }) useDebounce( () => { if (!isChangingSubject) { return false } if (subject === '') { setSuggestions([]) setIsChangingSubject(false) } if (subject.length > MIN_SEARCH_QUERY_LENGTH) { const queryString = ModifySearchTerms(subject) if (subject.trim() === lastSubject.trim()) { updateSuggestions() setIsChangingSubject(false) } else { fetch({ variables: { query: { queryString, size: 10, types: [SearchableContentTypes['WebQna']], }, }, }) } setLastSubject(subject) } }, 1000, [subject], ) useEffect(() => { if (subject === '') { setSuggestions([]) setIsChangingSubject(false) } }, [subject]) const updateSuggestions = () => { setSuggestions((data?.searchResults?.items as Array<SupportQna>) || []) } useEffect(() => { let fields = null switch (categoryId as CategoryId) { case '6K9stHLAB2mEyGqtqjnXxf': fields = ( <> <GridColumn span={['12/12', '12/12', '4/12']} paddingBottom={3}> <BasicInput name="fastanumer_eignar" /> </GridColumn> <GridColumn span={['12/12', '12/12', '4/12']} paddingBottom={3}> <BasicInput name="skraningarnumer_okutaekis" /> </GridColumn> <GridColumn span={['12/12', '12/12', '4/12']} paddingBottom={3}> <BasicInput name="kennitala_vegna_lausafes" format="######-####" /> </GridColumn> </> ) break case '7HbSNTUHJReJ2GPeT1ni1C': fields = ( <> <GridColumn span="12/12" paddingBottom={3}> <BasicInput name="nafn_leyfishafa" requiredMessage="Nafn leyfishafa vantar" /> </GridColumn> <GridColumn span={['12/12', '6/12']} paddingBottom={3}> <BasicInput name="kennitala_leyfishafa" requiredMessage="Kennitala leyfishafa vantar" format="######-####" /> </GridColumn> </> ) break case '5u2M09Kw3p1Spva1GSuAzB': case '7nWhQCER920RakQ7BZpEmV': fields = ( <GridColumn span={['12/12', '6/12']} paddingBottom={3}> <BasicInput name="kennitala_malsadila" requiredMessage="Kennitala málsaðila vantar" format="######-####" /> </GridColumn> ) break case '7LkzuYSzqwM7k8fJyeRbm6': case '4tvRkPgKP3kerbyRJDvaWF': case '4vQ4htPOAZvzcXBcjx06SH': fields = ( <> <GridColumn span="12/12" paddingBottom={3}> <BasicInput name="nafn_malsadila" requiredMessage="Nafn málsaðila vantar" /> </GridColumn> <GridColumn span={['12/12', '6/12']} paddingBottom={3}> <BasicInput name="kennitala_malsadila" format="######-####" /> </GridColumn> <GridColumn span={['12/12', '6/12']} paddingBottom={3}> <BasicInput name="malsnumer" /> </GridColumn> </> ) break case '2TkJynZlamqTHdjUziXDG0': fields = ( <> <GridColumn span="12/12" paddingBottom={3}> <BasicInput name="nafn_hins_latna" requiredMessage="Nafn hins látna vantar" /> </GridColumn> <GridColumn span={['12/12', '6/12']} paddingBottom={3}> <BasicInput name="kennitala_hins_latna" format="######-####" /> </GridColumn> <GridColumn span={['12/12', '6/12']} paddingBottom={8}> <BasicInput name="malsnumer" /> </GridColumn> <GridColumn span={['12/12', '6/12']} paddingBottom={3}> <BasicInput name="kennitala_arftaka" format="######-####" /> </GridColumn> </> ) break default: break } setAddonFields( fields ? ( <GridRow marginBottom={5} marginTop={5}> {fields} </GridRow> ) : null, ) }, [categoryId]) const canSubmit = !isSubmitting const submitWithMessage = async () => { const values = getValues() let message = Object.keys(labels).reduce((message, k) => { const label = labels[k] const value = values[k] if (label && value) { message += `${label}:\n${value}\n\n` } return message }, '') message = `Málaflokkur:\n${categoryLabel}\n\n${message}` return onSubmit({ email: values.email, name: values.nafn, subject: values.vidfangsefni, syslumadur: syslumadurId || '', category: categoryId, message, }) } const isBusy = loadingSuggestions || isChangingSubject return ( <> <GridContainer> <GridRow marginTop={6}> <GridColumn span={['12/12', '12/12', '12/12', '8/12']}> <Select backgroundColor="blue" icon="chevronDown" isSearchable label={labels.malaflokkur} name="malaflokkur" onChange={({ label, value }: Option) => { setCategoryLabel(label as string) setCategoryId(value as string) }} options={supportCategories.map((x) => ({ label: x.title, value: x.id, }))} placeholder="Veldu flokk" size="md" /> </GridColumn> </GridRow> {categoryId && ( <GridRow marginTop={3}> <GridColumn span={['12/12', '12/12', '12/12', '8/12']}> <InputController backgroundColor="blue" control={control} id="vidfangsefni" name="vidfangsefni" label={labels.vidfangsefni} error={errors?.vidfangsefni?.message} onChange={(e) => { if (e?.target?.value?.length > MIN_SEARCH_QUERY_LENGTH) { setIsChangingSubject(true) } setSubject(e.target.value) }} rules={{ required: { value: true, message: 'Vinsamlegast fylltu út viðfangsefni', }, }} required /> </GridColumn> </GridRow> )} {(isBusy || !!suggestions.length) && ( <Box marginTop={3} borderLeftWidth="standard" borderColor="blue200" paddingX={3} paddingY={3} > {!!suggestions.length && ( <Text variant="h5" marginBottom={3}> Við höldum að þetta gæti hjálpað </Text> )} {isBusy ? ( <LoadingDots /> ) : suggestions.length ? ( <Stack space={2}> {suggestions .slice(0, showAllSuggestions ? 10 : 5) .map(({ title, slug, organization, category }, index) => { const organizationSlug = organization?.slug const categorySlug = category?.slug return ( <LinkContext.Provider key={index} value={{ linkRenderer: (href, children) => ( <Link href={href} color="blue600" underline="normal" > {children} </Link> ), }} > <Text key={index} variant="small" color="blue600"> <a href={`${ linkResolver('helpdesk').href }/${organizationSlug}/${categorySlug}?q=${slug}`} > {title} </a> </Text> </LinkContext.Provider> ) })} {suggestions.length > 5 && !showAllSuggestions && ( <Button onClick={() => setShowAllSuggestions(true)} variant="text" size="small" icon="arrowDown" > Sjá meira </Button> )} </Stack> ) : ( <Text variant="small">Ekkert fannst</Text> )} </Box> )} <GridRow marginBottom={called ? 0 : 20}></GridRow> </GridContainer> {called && ( <FormProvider {...useFormMethods}> <form onSubmit={handleSubmit(submitWithMessage)}> <GridContainer> <GridRow marginTop={8}> <GridColumn paddingBottom={3} span="12/12"> <Controller control={control} name="nafn" defaultValue="" rules={ { required: { value: true, message: 'Nafn vantar', }, } as ValidationRules } render={({ onChange, onBlur, value, name }) => ( <Input backgroundColor="blue" name={name} onBlur={onBlur} label={labels.nafn} value={value} hasError={errors.nafn} errorMessage={errors.nafn?.message} onChange={onChange} required /> )} /> </GridColumn> <GridColumn paddingBottom={3} span="12/12"> <Controller control={useFormMethods.control} id="phone" name="phone" defaultValue="" render={({ onChange, onBlur, value, name }) => ( <Input backgroundColor="blue" name={name} onBlur={onBlur} label={labels.phone} value={value} hasError={errors.phone} errorMessage={errors.phone?.message} onChange={onChange} /> )} /> </GridColumn> <GridColumn span={['12/12', '12/12', '12/12', '8/12']}> <GridRow> <GridColumn paddingBottom={3} span="12/12"> <Controller control={useFormMethods.control} id="email" name="email" defaultValue="" rules={{ required: { value: true, message: 'Netfang vantar', }, pattern: { value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i, message: 'Netfang er mögulega rangt skrifað', }, }} render={({ onChange, onBlur, value, name }) => ( <Input backgroundColor="blue" name={name} onBlur={onBlur} label={labels.email} value={value} hasError={errors.email} errorMessage={errors.email?.message} onChange={onChange} required /> )} /> </GridColumn> </GridRow> {addonFields} <GridRow> <GridColumn span="12/12" paddingTop={5}> <Controller control={control} id="erindi" name="erindi" defaultValue="" rules={{ required: { value: true, message: 'Erindi vantar', }, }} render={({ onChange, onBlur, value, name }) => ( <Input backgroundColor="blue" name={name} onBlur={onBlur} label={labels.erindi} value={value} hasError={errors.erindi} errorMessage={errors.erindi?.message} onChange={onChange} rows={10} textarea required /> )} /> </GridColumn> </GridRow> <GridRow marginTop={8}> <GridColumn span={['12/12', '12/12', '6/12', '6/12']} paddingBottom={3} > {institutionSlug === 'syslumenn' && ( <Controller control={control} id="syslumadur" name="syslumadur" defaultValue="" rules={{ required: { value: true, message: 'Vinsamlegast veldu sýslumannsembætti', }, }} render={({ onChange }) => ( <Select backgroundColor="blue" icon="chevronDown" isSearchable label="Þinn sýslumaður" name="syslumadur" onChange={({ label, value }: Option) => { onChange(label) setSyslumadurId(value as string) }} hasError={errors.syslumadur} errorMessage={errors.syslumadur?.message} options={syslumenn.map((x) => ({ label: x.title, value: x.id, }))} placeholder="Veldu sýslumannsembætti" size="sm" required /> )} /> )} </GridColumn> <GridColumn span={['12/12', '12/12', '6/12', '6/12']}> <Box display="flex" flexDirection="column" justifyContent="flexEnd" alignItems="flexEnd" > <Button type="submit" variant="primary" icon="arrowForward" loading={loading} disabled={!canSubmit} > Senda fyrirspurn </Button> </Box> </GridColumn> </GridRow> </GridColumn> </GridRow> </GridContainer> </form> </FormProvider> )} </> ) }
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { NodeModel } from '../../../src/diagram/objects/node-model'; import { Node } from '../../../src/diagram/objects/node'; import { ConnectorModel } from '../../../src/diagram/objects/connector-model'; import { Connector } from '../../../src/diagram/objects/connector'; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; /** * ClipBoard Command spec */ describe('Diagram Control', () => { describe('Copy and Paste a single node', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram1' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; diagram = new Diagram({ width: '900px', height: '700px', nodes: [node], }); diagram.appendTo('#diagram1'); selArray.push(diagram.nodes[0]); diagram.select(selArray); //copy the single node let object: object = diagram.copy(); //paste the single node diagram.paste(object as NodeModel[]); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation - copy and paste the single node', (done: Function) => { expect(diagram.nodes.length === 2 && diagram.nodes[1].offsetX === 110 && diagram.nodes[1].offsetY === 110 && diagram.nodes[0].offsetX === 100).toBe(true); done(); }); }); describe('Cut and Paste a single node', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram2' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; diagram = new Diagram({ width: '900px', height: '700px', nodes: [node], }); diagram.appendTo('#diagram2'); selArray.push(diagram.nodes[0]); diagram.select(selArray); //cut the single node diagram.cut(); //paste the cuted node diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation - cut and paste a single node', (done: Function) => { expect(diagram.nodes.length === 1 && diagram.nodes[0].offsetX === 100 && diagram.nodes[0].offsetY === 100).toBe(true); done(); }); }); describe('Copy and Paste a single connector', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram3' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceDecorator: { style: { fill: 'black' }, shape: 'Arrow', pivot: { x: 0, y: 0.5 } }, targetDecorator: { shape: 'Diamond', style: { fill: 'blue' }, pivot: { x: 0, y: 0.5 } }, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '900px', height: '700px', connectors: [connector1], }); diagram.appendTo('#diagram3'); selArray.push(diagram.connectors[0]); diagram.select(selArray); //copy the single connector let object: object = diagram.copy(); diagram.paste(object as ConnectorModel[]); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation - copy and paste a single connector', (done: Function) => { expect(diagram.connectors.length === 2 && diagram.connectors[0].sourcePoint.x === 200 && diagram.connectors[0].sourcePoint.y === 200 && diagram.connectors[1].sourcePoint.x === 210 && diagram.connectors[1].sourcePoint.x === 210 && diagram.connectors[0].targetPoint.x === 300 && diagram.connectors[0].targetPoint.y === 300).toBe(true); done(); }); }); describe('Cut and Paste a single connector', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram4' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceDecorator: { style: { fill: 'black' }, shape: 'Arrow', pivot: { x: 0, y: 0.5 } }, targetDecorator: { shape: 'Diamond', style: { fill: 'blue' }, pivot: { x: 0, y: 0.5 } }, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '900px', height: '700px', connectors: [connector1], }); diagram.appendTo('#diagram4'); selArray.push(diagram.connectors[0]); diagram.select(selArray); diagram.cut(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation - cut and paste a single connector', (done: Function) => { expect(diagram.connectors.length === 1 && diagram.connectors[0].sourcePoint.x === 200 && diagram.connectors[0].sourcePoint.y === 200 && diagram.connectors[0].targetPoint.x === 300 && diagram.connectors[0].targetPoint.y === 300).toBe(true); done(); }); }); describe('copy and paste the connector when it is connect with node ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram5' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 200, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceID: node.id, targetID: node1.id, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [node, node1], connectors: [connector1] }); diagram.appendTo('#diagram5'); selArray.push(diagram.connectors[0]); diagram.select(selArray); let object: object = diagram.copy(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking connector copy and paste connector when it is connect with nodes', (done: Function) => { let failure: boolean = false; expect(diagram.connectors[1].sourceID === '' && diagram.connectors[1].targetID === '' && (diagram.nodes[0] as Node).outEdges.length === 1 && (diagram.nodes[1] as Node).inEdges.length === 1).toBe(true); done(); }); }); describe('cut and paste the connector when it is connect with node ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram6' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 200, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceID: node.id, targetID: node1.id, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [node, node1], connectors: [connector1] }); diagram.appendTo('#diagram6'); selArray.push(diagram.connectors[0]); diagram.select(selArray); diagram.cut(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking connector cut and paste connector when it is connect with nodes', (done: Function) => { let failure: boolean = false; expect(diagram.connectors[0].sourceID === '' && diagram.connectors[0].targetID === '' && (diagram.nodes[0] as Node).outEdges.length === 0 && (diagram.nodes[1] as Node).inEdges.length === 0).toBe(true); done(); }); }); describe('copy and paste the node when it has out Edges ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram7' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 200, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceID: node.id, targetID: node1.id, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [node, node1], connectors: [connector1] }); diagram.appendTo('#diagram7'); selArray.push(diagram.nodes[0]); diagram.select(selArray); let object: object = diagram.copy(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking connector copy and paste node when it has out edges', (done: Function) => { let failure: boolean = false; expect(diagram.connectors[0].sourceID === 'node' && diagram.connectors[0].targetID === 'node1' && diagram.nodes.length === 3 && (diagram.nodes[0] as Node).outEdges[0] === 'connector1' && (diagram.nodes[1] as Node).inEdges[0] === 'connector1' && diagram.nodes[2].id !== diagram.nodes[0].id).toBe(true); done(); }); }); describe('cut and paste the node when it has out Edges ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram8' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 200, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceID: node.id, targetID: node1.id, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [node, node1], connectors: [connector1] }); diagram.appendTo('#diagram8'); selArray.push(diagram.nodes[0]); diagram.select(selArray); diagram.cut(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking node cut and paste node when it has out edges', (done: Function) => { expect(diagram.connectors.length === 0 && diagram.nodes.length === 2 && (diagram.nodes[0] as Node).outEdges.length === 0 && (diagram.nodes[1] as Node).inEdges.length === 0).toBe(true); done(); }); }); describe('copy and paste the two selected nodes with out edges ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram9' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 200, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceID: node.id, targetID: node1.id, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [node, node1], connectors: [connector1] }); diagram.appendTo('#diagram9'); selArray.push(diagram.nodes[0]); selArray.push(diagram.nodes[1]); diagram.select(selArray, true); let object: object = diagram.copy(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking copy and paste the two selected nodes with out edges', (done: Function) => { expect(diagram.connectors[0].sourceID === 'node' && diagram.connectors[0].targetID === 'node1' && diagram.nodes.length === 4 && (diagram.nodes[0] as Node).outEdges[0] === 'connector1' && (diagram.nodes[1] as Node).inEdges[0] === 'connector1' && (diagram.nodes[2] as Node).outEdges.length === 0 && (diagram.nodes[3] as Node).inEdges.length === 0).toBe(true); done(); }); }); describe('cut and paste the two selected nodes with out edges ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram10' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 200, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceID: node.id, targetID: node1.id, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [node, node1], connectors: [connector1] }); diagram.appendTo('#diagram10'); selArray.push(diagram.nodes[0]); selArray.push(diagram.nodes[1]); diagram.select(selArray, true); diagram.cut(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking cut and paste the two selected nodes with out edges', (done: Function) => { expect(diagram.connectors.length === 0 && diagram.nodes.length === 2 && (diagram.nodes[0] as Node).outEdges.length === 0 && (diagram.nodes[1] as Node).inEdges.length === 0 ).toBe(true); done(); }); }); describe('copy and paste two selected nodes with edges ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram11' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 200, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceID: node.id, targetID: node1.id, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [node, node1], connectors: [connector1] }); diagram.appendTo('#diagram11'); selArray.push(diagram.nodes[0]); selArray.push(diagram.nodes[1]); selArray.push(diagram.connectors[0]); diagram.select(selArray, true); let object: object = diagram.copy(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking copy and paste two selected nodes with edges', (done: Function) => { expect(diagram.connectors[0].sourceID === 'node' && diagram.connectors[0].targetID === 'node1' && diagram.nodes.length === 4 && diagram.connectors.length === 2 && (diagram.nodes[2] as Node).outEdges[0] === diagram.connectors[1].id && diagram.connectors[1].sourceID === diagram.nodes[2].id && diagram.connectors[1].targetID === diagram.nodes[3].id).toBe(true); done(); }); }); describe('cut and paste the two selected nodes with edges ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram12' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 200, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceID: node.id, targetID: node1.id, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [node, node1], connectors: [connector1] }); diagram.appendTo('#diagram12'); selArray.push(diagram.nodes[0]); selArray.push(diagram.nodes[1]); selArray.push(diagram.connectors[0]); diagram.select(selArray, true); diagram.cut(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking cut and paste the two selected nodes with edges', (done: Function) => { expect(diagram.nodes.length === 2 && diagram.connectors.length === 1 && (diagram.nodes[1] as Node).inEdges[0] === diagram.connectors[0].id && (diagram.nodes[0] as Node).outEdges[0] === diagram.connectors[0].id && diagram.connectors[0].sourceID === diagram.nodes[0].id && diagram.connectors[0].targetID === diagram.nodes[1].id).toBe(true); done(); }); }); describe('Copy and subsequent Paste of single node', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; diagram = new Diagram({ width: '900px', height: '700px', nodes: [node], }); diagram.appendTo('#diagram'); selArray.push(diagram.nodes[0]); diagram.select(selArray); let object: object = diagram.copy(); diagram.paste(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking subsequent paste of single node', (done: Function) => { expect(diagram.nodes.length === 3 && diagram.nodes[1].offsetX === 110 && diagram.nodes[1].offsetY === 110 && diagram.nodes[0].offsetX === 100 && diagram.nodes[2].offsetX === 120).toBe(true); done(); }); }); describe('Copy and Paste a single node after the original node moving', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagram0' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; diagram = new Diagram({ width: '900px', height: '700px', nodes: [node], }); diagram.appendTo('#diagram0'); selArray.push(diagram.nodes[0]); diagram.select(selArray); let object: object = diagram.copy(); diagram.nodes[0].offsetX = 200; diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking copy and paste after original node move', (done: Function) => { expect(diagram.nodes.length === 2 && diagram.nodes[1].offsetX === 110 && diagram.nodes[1].offsetY === 110 && diagram.nodes[0].offsetX === 200).toBe(true); done(); }); }); describe('Copy and subsequent Paste a single connector', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagramj' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceDecorator: { style: { fill: 'black' }, shape: 'Arrow', pivot: { x: 0, y: 0.5 } }, targetDecorator: { shape: 'Diamond', style: { fill: 'blue' }, pivot: { x: 0, y: 0.5 } }, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '900px', height: '700px', connectors: [connector1], }); diagram.appendTo('#diagramj'); selArray.push(diagram.connectors[0]); diagram.select(selArray); let object: object = diagram.copy(); diagram.paste(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking subsequent paste of single connector', (done: Function) => { expect(diagram.connectors.length === 3 && diagram.connectors[0].sourcePoint.x === 200 && diagram.connectors[0].sourcePoint.y === 200 && diagram.connectors[1].sourcePoint.x === 210 && diagram.connectors[1].sourcePoint.x === 210 && diagram.connectors[0].targetPoint.x === 300 && diagram.connectors[0].targetPoint.y === 300 && diagram.connectors[2].sourcePoint.x === 220 && diagram.connectors[2].sourcePoint.y === 220).toBe(true); done(); }); }); describe('subsequent paste two selected nodes with edges ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'dia' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 300, offsetY: 200, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 200, y: 200 }, targetPoint: { x: 300, y: 300 }, sourceID: node.id, targetID: node1.id, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '500px', height: '500px', nodes: [node, node1], connectors: [connector1] }); diagram.appendTo('#dia'); selArray.push(diagram.nodes[0]); selArray.push(diagram.nodes[1]); selArray.push(diagram.connectors[0]); diagram.select(selArray, true); let object: object = diagram.copy(); diagram.paste(); diagram.paste(); diagram.paste(); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking subsequent paste two selected nodes with edges', (done: Function) => { expect(diagram.connectors[0].sourceID === 'node' && diagram.connectors[0].targetID === 'node1' && diagram.nodes.length === 8 && diagram.connectors.length === 4 && (diagram.nodes[2] as Node).outEdges[0] === diagram.connectors[1].id && diagram.connectors[1].sourceID === diagram.nodes[2].id && diagram.connectors[1].targetID === diagram.nodes[3].id).toBe(true); done(); }); }); describe('Copy and paste with inEdges and outEdges', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagramcopyPaste' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node1: NodeModel = { id: "node1", width: 90, height: 40, annotations: [{ content: 'Start' }], offsetX: 400, offsetY: 30, shape: { type: 'Flow', shape: 'Terminator' } }; let node2: NodeModel = { id: "node2", offsetX: 400, offsetY: 100, width: 90, height: 40, annotations: [{ content: 'Design' }], shape: { type: 'Flow', shape: 'Process' } }; let node3: NodeModel = { id: "node3", offsetX: 400, offsetY: 180, width: 90, height: 40, annotations: [{ content: 'Coding' }], shape: { type: 'Flow', shape: 'Process' } }; let node4: NodeModel = { id: "node4", width: 90, height: 40, offsetX: 400, offsetY: 260, annotations: [{ content: 'Testing' }], shape: { type: 'Flow', shape: 'Process' }, }; let node5: NodeModel = { id: "node5", width: 90, height: 40, offsetX: 400, offsetY: 340, annotations: [{ content: 'Errors?' }], shape: { type: 'Flow', shape: 'Decision' }, }; let node6: NodeModel = { id: "node6", width: 90, height: 40, offsetX: 400, offsetY: 450, annotations: [{ content: 'End' }], shape: { type: 'Flow', shape: 'Terminator' }, }; let node7: NodeModel = { id: "node7", width: 110, height: 60, offsetX: 220, offsetY: 180, annotations: [{ content: 'Design Error?' }], shape: { type: 'Flow', shape: 'Decision' } }; let connector1: ConnectorModel = { id: "connector1", sourceID: node1.id, targetID: node2.id }; let connector2: ConnectorModel = { id: "connector2", sourceID: node2.id, targetID: node3.id }; let connector3: ConnectorModel = { id: "connector3", sourceID: node3.id, targetID: node4.id }; let connector4: ConnectorModel = { id: "connector4", sourceID: node4.id, targetID: node5.id }; let connector5: ConnectorModel = { id: "connector5", sourceID: node5.id, targetID: node6.id, annotations: [{ content: "No", style: { fill: 'white' } }] }; let connector6: ConnectorModel = { id: "connector6", sourceID: node5.id, targetID: node7.id, type: "Orthogonal", annotations: [{ content: "Yes", style: { fill: "white" } }] }; let connector7: ConnectorModel = { id: "connector7", sourceID: node7.id, targetID: node3.id, type: "Orthogonal", annotations: [{ content: "No", style: { fill: "white" } }] }; let connector8: ConnectorModel = { id: "connector8", sourceID: node7.id, targetID: node2.id, type: "Orthogonal", annotations: [{ content: "Yes", style: { fill: "white" } }] }; diagram = new Diagram({ width: '850px', height: '700px', nodes: [node1, node2, node3, node4, node5, node6, node7], connectors: [connector1, connector2, connector3, connector4, connector5, connector6, connector7, connector8] }); diagram.appendTo('#diagramcopyPaste'); selArray.push(diagram.nodes[1]); selArray.push(diagram.nodes[2]); selArray.push(diagram.connectors[1]); diagram.select(selArray, true); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking copy and paste two selected nodes with inEdges and outEdges', (done: Function) => { diagram.copy(); diagram.paste(); expect((diagram.connectors[8] as ConnectorModel).sourceID !== undefined && (diagram.connectors[8] as ConnectorModel).targetID !== undefined).toBe(true); done(); }); it('Checking copy and paste two selected nodes with inEdges and outEdges', (done: Function) => { diagram.undo(); diagram.selectedItems.nodes = []; diagram.selectedItems.connectors = []; let selArray: (NodeModel | ConnectorModel)[] = [diagram.nodes[6], diagram.nodes[2], diagram.connectors[6]]; diagram.select(selArray, true); diagram.copy(); diagram.paste(); expect((diagram.connectors[8] as ConnectorModel).sourceID !== undefined && (diagram.connectors[8] as ConnectorModel).targetID !== undefined).toBe(true); done(); }); }); describe('paste a node ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagramml' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node: NodeModel = { id: 'node', width: 100, height: 100, offsetX: 100, offsetY: 100, shape: { type: 'Basic', shape: 'Rectangle' }, annotations: [{ style: { strokeColor: 'black', opacity: 0.5 }, content: 'center center', height: 50, width: 50, offset: { x: 0.5, y: 0.5 }, horizontalAlignment: 'Center', verticalAlignment: 'Center', }] }; diagram = new Diagram({ width: '900px', height: '700px', nodes: [node], }); diagram.appendTo('#diagramml'); diagram.paste([{ id: "node2", width: 190, height: 100, offsetX: 500, offsetY: 100 }]); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation - copy and paste the single node', (done: Function) => { expect(diagram.nodes.length === 2 && diagram.nodes[1].offsetX === 510 && diagram.nodes[1].offsetY === 110).toBe(true); done(); }); }); describe(' Paste a connector', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'diagrammn' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let connector1: ConnectorModel = { id: 'connector1', type: 'Orthogonal', sourcePoint: { x: 100, y: 100 }, targetPoint: { x: 200, y: 200 }, sourceDecorator: { style: { fill: 'black' }, shape: 'Arrow', pivot: { x: 0, y: 0.5 } }, targetDecorator: { shape: 'Diamond', style: { fill: 'blue' }, pivot: { x: 0, y: 0.5 } }, cornerRadius: 10, style: { strokeColor: 'red', strokeWidth: 3, opacity: 3 } }; diagram = new Diagram({ width: '900px', height: '700px', connectors: [connector1], }); diagram.appendTo('#diagrammn'); diagram.paste([{ id: 'connector2', type: 'Straight', sourcePoint: { x: 300, y: 300 }, targetPoint: { x: 400, y: 400 } }]); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking diagram instance creation - copy and paste a single connector', (done: Function) => { expect(diagram.connectors.length === 2 && diagram.connectors[1].sourcePoint.x === 310 && diagram.connectors[1].sourcePoint.y === 310 && diagram.connectors[1].targetPoint.x === 410 && diagram.connectors[1].targetPoint.y === 410).toBe(true); done(); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) }); });
the_stack
import * as d3 from "d3"; import * as Typesettable from "typesettable"; import { Formatter } from "../core/formatters"; import * as Formatters from "../core/formatters"; import * as Scales from "../scales"; import * as Utils from "../utils"; import { LabelFontSizePx } from "../components/label"; import { SimpleSelection } from "../core/interfaces"; import { makeEnum } from "../utils/makeEnum"; import { Axis } from "./axis"; export const TimeInterval = makeEnum([ "second", "minute", "hour", "day", "week", "month", "year", ]); export type TimeInterval = keyof typeof TimeInterval; /** * Defines a configuration for a Time Axis tier. * For details on how ticks are generated see: https://github.com/mbostock/d3/wiki/Time-Scales#ticks */ export type TimeAxisTierConfiguration = { /** * The time unit associated with this configuration (seconds, minutes, hours, etc). */ interval: string; /** * Number of intervals between each tick. */ step: number; /** * Formatter used to format tick labels. Tick values will be passed through the formatter * before being displayed. */ formatter: Formatter; }; /** * An array of linked TimeAxisTierConfigurations. * Each configuration will be shown on a different tier. * Currently, up to two tiers are supported. */ export type TimeAxisConfiguration = TimeAxisTierConfiguration[]; /** * Possible orientations for a Time Axis. */ export const TimeAxisOrientation = makeEnum(["top", "bottom"]); export type TimeAxisOrientation = keyof typeof TimeAxisOrientation; export const TierLabelPosition = makeEnum(["between", "center"]); export type TierLabelPosition = keyof typeof TierLabelPosition; export class Time extends Axis<Date> { /** * The CSS class applied to each Time Axis tier */ public static TIME_AXIS_TIER_CLASS = "time-axis-tier"; private static _SORTED_TIME_INTERVAL_INDEX: Record<TimeInterval, number> = { [TimeInterval.second]: 0, [TimeInterval.minute]: 1, [TimeInterval.hour]: 2, [TimeInterval.day]: 3, [TimeInterval.week]: 4, [TimeInterval.month]: 5, [TimeInterval.year]: 6, }; private static _DEFAULT_TIME_AXIS_CONFIGURATIONS = (useUTC: boolean) => { const formatter = (specifier: string) => Formatters.time(specifier, useUTC); return [ [ { interval: TimeInterval.second, step: 1, formatter: formatter("%I:%M:%S %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.second, step: 5, formatter: formatter("%I:%M:%S %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.second, step: 10, formatter: formatter("%I:%M:%S %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.second, step: 15, formatter: formatter("%I:%M:%S %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.second, step: 30, formatter: formatter("%I:%M:%S %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.minute, step: 1, formatter: formatter("%I:%M %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.minute, step: 5, formatter: formatter("%I:%M %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.minute, step: 10, formatter: formatter("%I:%M %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.minute, step: 15, formatter: formatter("%I:%M %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.minute, step: 30, formatter: formatter("%I:%M %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.hour, step: 1, formatter: formatter("%I %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.hour, step: 3, formatter: formatter("%I %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.hour, step: 6, formatter: formatter("%I %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.hour, step: 12, formatter: formatter("%I %p") }, { interval: TimeInterval.day, step: 1, formatter: formatter("%B %e, %Y") }, ], [ { interval: TimeInterval.day, step: 1, formatter: formatter("%a %e") }, { interval: TimeInterval.month, step: 1, formatter: formatter("%B %Y") }, ], [ { interval: TimeInterval.day, step: 1, formatter: formatter("%e") }, { interval: TimeInterval.month, step: 1, formatter: formatter("%B %Y") }, ], [ { interval: TimeInterval.month, step: 1, formatter: formatter("%B") }, { interval: TimeInterval.year, step: 1, formatter: formatter("%Y") }, ], [ { interval: TimeInterval.month, step: 1, formatter: formatter("%b") }, { interval: TimeInterval.year, step: 1, formatter: formatter("%Y") }, ], [ { interval: TimeInterval.month, step: 3, formatter: formatter("%b") }, { interval: TimeInterval.year, step: 1, formatter: formatter("%Y") }, ], [ { interval: TimeInterval.month, step: 6, formatter: formatter("%b") }, { interval: TimeInterval.year, step: 1, formatter: formatter("%Y") }, ], [ { interval: TimeInterval.year, step: 1, formatter: formatter("%Y") }, ], [ { interval: TimeInterval.year, step: 1, formatter: formatter("%y") }, ], [ { interval: TimeInterval.year, step: 5, formatter: formatter("%Y") }, ], [ { interval: TimeInterval.year, step: 25, formatter: formatter("%Y") }, ], [ { interval: TimeInterval.year, step: 50, formatter: formatter("%Y") }, ], [ { interval: TimeInterval.year, step: 100, formatter: formatter("%Y") }, ], [ { interval: TimeInterval.year, step: 200, formatter: formatter("%Y") }, ], [ { interval: TimeInterval.year, step: 500, formatter: formatter("%Y") }, ], [ { interval: TimeInterval.year, step: 1000, formatter: formatter("%Y") }, ], ]; } private _useUTC: boolean; private _tierLabelContainers: SimpleSelection<void>[]; private _tierMarkContainers: SimpleSelection<void>[]; private _tierBaselines: SimpleSelection<void>[]; private _tierHeights: number[]; private _possibleTimeAxisConfigurations: TimeAxisConfiguration[]; private _numTiers: number; private _measurer: Typesettable.CacheMeasurer; private _maxTimeIntervalPrecision: TimeInterval = null; private _mostPreciseConfigIndex: number; private _tierLabelPositions: TierLabelPosition[] = []; private static _LONG_DATE = new Date(9999, 8, 29, 12, 59, 9999); /** * Constructs a Time Axis. * * A Time Axis is a visual representation of a Time Scale. * * @constructor * @param {Scales.Time} scale * @param {AxisOrientation} orientation Orientation of this Time Axis. Time Axes can only have "top" or "bottom" * @param {boolean} useUTC Displays date object in UTC if true, local time if false. Defaults to false. * orientations. */ constructor(scale: Scales.Time, orientation: TimeAxisOrientation, useUTC?: boolean) { super(scale, orientation); this._useUTC = useUTC; this.addClass("time-axis"); this.tickLabelPadding(5); this.axisConfigurations(Time._DEFAULT_TIME_AXIS_CONFIGURATIONS(this._useUTC)); this.annotationFormatter(Formatters.time("%a %b %d, %Y", this._useUTC)); } public tickLabelFontSize(): LabelFontSizePx; public tickLabelFontSize(fontSize: LabelFontSizePx): this; public tickLabelFontSize(fontSize?: LabelFontSizePx): LabelFontSizePx | this { if (fontSize == null) { return super.tickLabelFontSize(); } if (this._tierLabelContainers != null) { this.invalidateCache(); this._computeHeight(); this._tierLabelContainers.forEach((container) => { // clearing to remove outdated font-size classes container.attr("class", null) .classed(`${Axis.TICK_LABEL_CLASS}-container`, true) .classed(`label-${this._tickLabelFontSize}`, true); }); } return super.tickLabelFontSize(fontSize); } /** * Gets the label positions for each tier. */ public tierLabelPositions(): TierLabelPosition[]; /** * Sets the label positions for each tier. * * @param {string[]} newPositions The positions for each tier. "between" and "center" are the only supported values. * @returns {Axes.Time} The calling Time Axis. */ public tierLabelPositions(newPositions: TierLabelPosition[]): this; public tierLabelPositions(newPositions?: TierLabelPosition[]): any { if (newPositions == null) { return this._tierLabelPositions; } else { if (!newPositions.every((pos: string) => pos.toLowerCase() === "between" || pos.toLowerCase() === "center")) { throw new Error("Unsupported position for tier labels"); } this._tierLabelPositions = newPositions; this.redraw(); return this; } } /** * Gets the maximum TimeInterval precision */ public maxTimeIntervalPrecision(): TimeInterval; /** * Sets the maximum TimeInterval precision. This limits the display to not * show time intervals above this precision. For example, if this is set to * `TimeInterval.day` or `"day"` then no hours or minute ticks will be * displayed in the axis. * * @param {TimeInterval} newPrecision The new maximum precision. * @returns {Axes.Time} The calling Time Axis. */ public maxTimeIntervalPrecision(newPrecision: TimeInterval): this; public maxTimeIntervalPrecision(newPrecision?: TimeInterval): any { if (newPrecision == null) { return this._maxTimeIntervalPrecision; } else { this._maxTimeIntervalPrecision = newPrecision; this.redraw(); return this; } } /** * Returns the current `TimeAxisConfiguration` used to render the axes. * * Note that this is only valid after the axis had been rendered and the * most precise valid configuration is determined from the available space * and maximum precision constraints. * * @returns {TimeAxisConfiguration} The currently used `TimeAxisConfiguration` or `undefined`. */ public currentAxisConfiguration(): TimeAxisConfiguration { return this._possibleTimeAxisConfigurations[this._mostPreciseConfigIndex]; } /** * Gets the possible TimeAxisConfigurations. */ public axisConfigurations(): TimeAxisConfiguration[]; /** * Sets the possible TimeAxisConfigurations. * The Time Axis will choose the most precise configuration that will display in the available space. * * @param {TimeAxisConfiguration[]} configurations * @returns {Axes.Time} The calling Time Axis. */ public axisConfigurations(configurations: TimeAxisConfiguration[]): this; public axisConfigurations(configurations?: any): any { if (configurations == null) { return this._possibleTimeAxisConfigurations; } this._possibleTimeAxisConfigurations = configurations; this._numTiers = Utils.Math.max(this._possibleTimeAxisConfigurations.map((config: TimeAxisConfiguration) => config.length), 0); if (this._isAnchored) { this._setupDomElements(); } const oldLabelPositions = this.tierLabelPositions(); const newLabelPositions: TierLabelPosition[] = []; for (let i = 0; i < this._numTiers; i++) { newLabelPositions.push(oldLabelPositions[i] || "between"); } this.tierLabelPositions(newLabelPositions); this.redraw(); return this; } /** * Gets the index of the most precise TimeAxisConfiguration that will fit in the current width. */ private _getMostPreciseConfigurationIndex(): number { let mostPreciseIndex = this._possibleTimeAxisConfigurations.length; this._possibleTimeAxisConfigurations.forEach((interval: TimeAxisConfiguration, index: number) => { if (index < mostPreciseIndex && interval.every((tier: TimeAxisTierConfiguration) => this._checkTimeAxisTierConfiguration(tier))) { mostPreciseIndex = index; } }); if (mostPreciseIndex === this._possibleTimeAxisConfigurations.length) { Utils.Window.warn("zoomed out too far: could not find suitable interval to display labels"); --mostPreciseIndex; } return mostPreciseIndex; } public orientation(): TimeAxisOrientation; public orientation(orientation: TimeAxisOrientation): this; public orientation(orientation?: TimeAxisOrientation): TimeAxisOrientation | this { if (orientation && (orientation.toLowerCase() === "right" || orientation.toLowerCase() === "left")) { throw new Error(orientation + " is not a supported orientation for TimeAxis - only horizontal orientations are supported"); } return super.orientation(orientation); // maintains getter-setter functionality } protected _computeHeight() { const textHeight = this._measurer.measure().height; this._tierHeights = []; for (let i = 0; i < this._numTiers; i++) { this._tierHeights.push(textHeight + this.tickLabelPadding() + ((this._tierLabelPositions[i]) === "between" ? 0 : this._maxLabelTickLength())); } return d3.sum(this._tierHeights); } private _getIntervalLength(config: TimeAxisTierConfiguration) { const startDate = this._scale.domain()[0]; const d3Interval = Scales.Time.timeIntervalToD3Time(config.interval, this._useUTC); const endDate = d3Interval.offset(startDate, config.step); if (endDate > this._scale.domain()[1]) { // this offset is too large, so just return available width return this.width(); } // measure how much space one date can get const stepLength = Math.abs(this._scale.scale(endDate) - this._scale.scale(startDate)); return stepLength; } private _maxWidthForInterval(config: TimeAxisTierConfiguration): number { return this._measurer.measure(config.formatter(Time._LONG_DATE)).width; } /** * Check if tier configuration fits in the current width and satisfied the * max TimeInterval precision limit. */ private _checkTimeAxisTierConfiguration(config: TimeAxisTierConfiguration): boolean { // Use the sorted index to determine if the teir configuration contains a // time interval that is too precise for the maxTimeIntervalPrecision // setting (if set). if (this._maxTimeIntervalPrecision != null) { const precisionLimit = Time._SORTED_TIME_INTERVAL_INDEX[this._maxTimeIntervalPrecision]; const configPrecision = Time._SORTED_TIME_INTERVAL_INDEX[config.interval as TimeInterval]; if (precisionLimit != null && configPrecision != null && configPrecision < precisionLimit) { return false; } } const worstWidth = this._maxWidthForInterval(config) + 2 * this.tickLabelPadding(); return Math.min(this._getIntervalLength(config), this.width()) >= worstWidth; } protected _sizeFromOffer(availableWidth: number, availableHeight: number) { // Makes sure that the size it requires is a multiple of tier sizes, such that // we have no leftover tiers const size = super._sizeFromOffer(availableWidth, availableHeight); const tierHeights = this._tierHeights.reduce((prevValue, currValue, index, arr) => { return (prevValue + currValue > size.height) ? prevValue : (prevValue + currValue); }); const nonCoreHeight = this.margin() + (this.annotationsEnabled() ? this.annotationTierCount() * this._annotationTierHeight() : 0); size.height = Math.min(size.height, tierHeights + nonCoreHeight); return size; } protected _setup() { super._setup(); this._setupDomElements(); } private _setupDomElements() { this.content().selectAll("." + Time.TIME_AXIS_TIER_CLASS).remove(); this._tierLabelContainers = []; this._tierMarkContainers = []; this._tierBaselines = []; this._tickLabelContainer.remove(); this._baseline.remove(); for (let i = 0; i < this._numTiers; ++i) { const tierContainer = this.content().append("g").classed(Time.TIME_AXIS_TIER_CLASS, true); this._tierLabelContainers.push( tierContainer.append("g") .classed(`${Axis.TICK_LABEL_CLASS}-container`, true) .classed(`label-${this._tickLabelFontSize}`, true), ); this._tierMarkContainers.push(tierContainer.append("g").classed(Axis.TICK_MARK_CLASS + "-container", true)); this._tierBaselines.push(tierContainer.append("line").classed("baseline", true)); } const context = new Typesettable.SvgContext(this._tierLabelContainers[0].node() as SVGElement); this._measurer = new Typesettable.CacheMeasurer(context); } private _getTickIntervalValues(config: TimeAxisTierConfiguration): any[] { return (<Scales.Time> this._scale).tickInterval(config.interval, config.step, this._useUTC); } protected _getTickValues() { return this._possibleTimeAxisConfigurations[this._mostPreciseConfigIndex].reduce( (ticks: any[], config: TimeAxisTierConfiguration) => ticks.concat(this._getTickIntervalValues(config)), [], ); } private _cleanTiers() { for (let index = 0; index < this._tierLabelContainers.length; index++) { this._tierLabelContainers[index].selectAll("." + Axis.TICK_LABEL_CLASS).remove(); this._tierMarkContainers[index].selectAll("." + Axis.TICK_MARK_CLASS).remove(); this._tierBaselines[index].style("visibility", "hidden"); } } private _getTickValuesForConfiguration(config: TimeAxisTierConfiguration) { const tickPos = (<Scales.Time> this._scale).tickInterval(config.interval, config.step, this._useUTC); const domain = this._scale.domain(); const tickPosValues = tickPos.map((d: Date) => d.valueOf()); // can't indexOf with objects if (tickPosValues.indexOf(domain[0].valueOf()) === -1) { tickPos.unshift(domain[0]); } if (tickPosValues.indexOf(domain[1].valueOf()) === -1) { tickPos.push(domain[1]); } return tickPos; } private _renderTierLabels(container: SimpleSelection<void>, config: TimeAxisTierConfiguration, index: number) { const tickPos = this._getTickValuesForConfiguration(config); let labelPos: Date[] = []; if (this._tierLabelPositions[index] === "between" && config.step === 1) { tickPos.map((datum: any, i: any) => { if (i + 1 >= tickPos.length) { return; } labelPos.push(new Date((tickPos[i + 1].valueOf() - tickPos[i].valueOf()) / 2 + tickPos[i].valueOf())); }); } else { labelPos = tickPos; } const tickLabelsUpdate = container.selectAll("." + Axis.TICK_LABEL_CLASS).data(labelPos, (d) => String(d.valueOf())); tickLabelsUpdate.remove(); const tickLabelsEnter = tickLabelsUpdate .enter() .append("g") .classed(Axis.TICK_LABEL_CLASS, true); tickLabelsEnter.append("text"); const xTranslate = (this._tierLabelPositions[index] === "center" || config.step === 1) ? 0 : this.tickLabelPadding(); let yTranslate: number; if (this.orientation() === "bottom") { yTranslate = d3.sum(this._tierHeights.slice(0, index + 1)) - this.tickLabelPadding(); } else { if (this._tierLabelPositions[index] === "center") { yTranslate = this.height() - d3.sum(this._tierHeights.slice(0, index)) - this.tickLabelPadding() - this._maxLabelTickLength(); } else { yTranslate = this.height() - d3.sum(this._tierHeights.slice(0, index)) - this.tickLabelPadding(); } } const tickLabels = tickLabelsUpdate.merge(tickLabelsEnter); const textSelection = tickLabels.selectAll("text"); if (textSelection.size() > 0) { textSelection.attr("transform", `translate(${xTranslate},${yTranslate})`); } tickLabelsUpdate.exit().remove(); tickLabels.attr("transform", (d: any) => "translate(" + this._scale.scale(d) + ",0)"); const anchor = (this._tierLabelPositions[index] === "center" || config.step === 1) ? "middle" : "start"; tickLabels.selectAll("text").text(config.formatter).style("text-anchor", anchor); } private _renderTickMarks(tickValues: Date[], index: number) { const tickMarksUpdate = this._tierMarkContainers[index].selectAll("." + Axis.TICK_MARK_CLASS).data(tickValues); const tickMarks = tickMarksUpdate .enter() .append("line") .classed(Axis.TICK_MARK_CLASS, true) .merge(tickMarksUpdate); const attr = this._generateTickMarkAttrHash(); const offset = this._tierHeights.slice(0, index).reduce((translate: number, height: number) => translate + height, 0); if (this.orientation() === "bottom") { attr["y1"] = offset; attr["y2"] = offset + (this._tierLabelPositions[index] === "center" ? this.innerTickLength() : this._tierHeights[index]); } else { attr["y1"] = this.height() - offset; attr["y2"] = this.height() - (offset + (this._tierLabelPositions[index] === "center" ? this.innerTickLength() : this._tierHeights[index])); } tickMarks.attrs(attr); if (this.orientation() === "bottom") { attr["y1"] = offset; attr["y2"] = offset + (this._tierLabelPositions[index] === "center" ? this.endTickLength() : this._tierHeights[index]); } else { attr["y1"] = this.height() - offset; attr["y2"] = this.height() - (offset + (this._tierLabelPositions[index] === "center" ? this.endTickLength() : this._tierHeights[index])); } d3.select(tickMarks.nodes()[0]).attrs(attr); d3.select(tickMarks.nodes()[tickMarks.size() - 1]).attrs(attr); // Add end-tick classes to first and last tick for CSS customization purposes d3.select(tickMarks.nodes()[0]).classed(Axis.END_TICK_MARK_CLASS, true); d3.select(tickMarks.nodes()[tickMarks.size() - 1]).classed(Axis.END_TICK_MARK_CLASS, true); tickMarksUpdate.exit().remove(); } private _renderLabellessTickMarks(tickValues: Date[]) { const tickMarksUpdate = this._tickMarkContainer.selectAll("." + Axis.TICK_MARK_CLASS).data(tickValues); const tickMarks = tickMarksUpdate .enter() .append("line") .classed(Axis.TICK_MARK_CLASS, true) .merge(tickMarksUpdate); const attr = this._generateTickMarkAttrHash(); attr["y2"] = (this.orientation() === "bottom") ? this.tickLabelPadding() : this.height() - this.tickLabelPadding(); tickMarks.attrs(attr); tickMarksUpdate.exit().remove(); } private _generateLabellessTicks() { if (this._mostPreciseConfigIndex < 1) { return []; } return this._getTickIntervalValues(this._possibleTimeAxisConfigurations[this._mostPreciseConfigIndex - 1][0]); } public renderImmediately() { this._mostPreciseConfigIndex = this._getMostPreciseConfigurationIndex(); const tierConfigs = this._possibleTimeAxisConfigurations[this._mostPreciseConfigIndex]; this._cleanTiers(); tierConfigs.forEach((config: TimeAxisTierConfiguration, i: number) => this._renderTierLabels(this._tierLabelContainers[i], config, i), ); const tierTicks = tierConfigs.map((config: TimeAxisTierConfiguration, i: number) => this._getTickValuesForConfiguration(config), ); let baselineOffset = 0; for (let i = 0; i < Math.max(tierConfigs.length, 1); ++i) { const attr = this._generateBaselineAttrHash(); attr["y1"] += (this.orientation() === "bottom") ? baselineOffset : -baselineOffset; attr["y2"] = attr["y1"]; this._tierBaselines[i].attrs(attr).style("visibility", "inherit"); baselineOffset += this._tierHeights[i]; } let labelLessTicks: Date[] = []; const domain = this._scale.domain(); const totalLength = this._scale.scale(domain[1]) - this._scale.scale(domain[0]); if (this._getIntervalLength(tierConfigs[0]) * 1.5 >= totalLength) { labelLessTicks = this._generateLabellessTicks(); } this._renderLabellessTickMarks(labelLessTicks); this._hideOverflowingTiers(); for (let i = 0; i < tierConfigs.length; ++i) { this._renderTickMarks(tierTicks[i], i); this._hideOverlappingAndCutOffLabels(i); } if (this.annotationsEnabled()) { this._drawAnnotations(); } else { this._removeAnnotations(); } return this; } private _hideOverflowingTiers() { const availableHeight = this.height(); let usedHeight = 0; this.content() .selectAll("." + Time.TIME_AXIS_TIER_CLASS) .attr("visibility", (d: any, i: number) => { usedHeight += this._tierHeights[i]; return usedHeight <= availableHeight ? "inherit" : "hidden"; }); } private _hideOverlappingAndCutOffLabels(index: number) { const boundingBox = this.element().node().getBoundingClientRect(); const isInsideBBox = (tickBox: ClientRect) => { return ( Math.floor(boundingBox.left) <= Math.ceil(tickBox.left) && Math.floor(boundingBox.top) <= Math.ceil(tickBox.top) && Math.floor(tickBox.right) <= Math.ceil(boundingBox.left + this.width()) && Math.floor(tickBox.bottom) <= Math.ceil(boundingBox.top + this.height()) ); }; const visibleTickMarks = this._tierMarkContainers[index] .selectAll("." + Axis.TICK_MARK_CLASS) .filter(function (d: Element, i: number) { const visibility = d3.select(this).style("visibility"); return visibility === "visible" || visibility === "inherit"; }); // We use the ClientRects because x1/x2 attributes are not comparable to ClientRects of labels const visibleTickMarkRects = visibleTickMarks.nodes().map((mark: Element) => mark.getBoundingClientRect()); const visibleTickLabels = this._tierLabelContainers[index] .selectAll<SVGGElement, any>("." + Axis.TICK_LABEL_CLASS) .filter(function (d: Element, i: number) { const visibility = d3.select(this).style("visibility"); return visibility === "visible" || visibility === "inherit"; }); let lastLabelClientRect: ClientRect; visibleTickLabels.each(function (d: Element, i: number) { const clientRect = this.getBoundingClientRect(); const tickLabel = d3.select(this); const leadingTickMark = visibleTickMarkRects[i]; const trailingTickMark = visibleTickMarkRects[i + 1]; const isOverlappingLastLabel = (lastLabelClientRect != null && Utils.DOM.clientRectsOverlap(clientRect, lastLabelClientRect)); const isOverlappingLeadingTickMark = (leadingTickMark != null && Utils.DOM.clientRectsOverlap(clientRect, leadingTickMark)); const isOverlappingTrailingTickMark = (trailingTickMark != null && Utils.DOM.clientRectsOverlap(clientRect, trailingTickMark)); if (!isInsideBBox(clientRect) || isOverlappingLastLabel || isOverlappingLeadingTickMark || isOverlappingTrailingTickMark) { tickLabel.style("visibility", "hidden"); } else { lastLabelClientRect = clientRect; tickLabel.style("visibility", "inherit"); } }); } public invalidateCache() { super.invalidateCache(); if (this._measurer != null) { (this._measurer as Typesettable.CacheMeasurer).reset(); } } }
the_stack
import { Nodey, NodeyCode, NodeyOutput, NodeyCodeCell, NodeyMarkdown, NodeyCell, NodeyNotebook, NodeyRawCell, } from "../../nodey"; import { log } from "../../notebook"; import { FileManager } from "../../jupyter-hooks/file-manager"; import { History, NodeHistory, OutputHistory, CodeHistory } from ".."; import { Search } from "./search"; export type searchResult = { label: string; count: number; results: Nodey[][]; }; export class HistoryStore { readonly fileManager: FileManager; readonly history: History; private _notebookHistory: NodeHistory<NodeyNotebook>; private _codeCellStore: CodeHistory[] = []; private _markdownStore: NodeHistory<NodeyMarkdown>[] = []; private _rawCellStore: NodeHistory<NodeyRawCell>[] = []; private _outputStore: OutputHistory[] = []; private _snippetStore: NodeHistory<NodeyCode>[] = []; constructor(history: History, fileManager: FileManager) { this.history = history; this.fileManager = fileManager; } get currentNotebook(): NodeyNotebook | undefined { return this._notebookHistory?.latest; } public getNotebook(ver?: number): NodeyNotebook | undefined { return this._notebookHistory.getVersion(ver); } get cells(): NodeyCell[] { let notebook = this.currentNotebook; if (!notebook) return []; // error case only return notebook.cells.map((name) => this.get(name) as NodeyCell); } public getHistoryOf(name?: string | Nodey): NodeHistory<Nodey> | undefined { if (!name) return; // error case only let typeChar = "???"; // error case only let id: number; if (typeof name === "string") { var idVal; [typeChar, idVal] = name.split("."); id = parseInt(idVal); } else if (name instanceof Nodey) { typeChar = name.typeChar; id = name.id === undefined ? -1 : name.id; } switch (typeChar) { case "n": return this._notebookHistory; case "c": return this._codeCellStore[id]; case "o": return this._outputStore[id]; case "s": return this._snippetStore[id]; case "m": return this._markdownStore[id]; case "r": return this._rawCellStore[id]; default: console.error("nodey type not found" + name + " " + typeof name); } } getLatestOf(name: string | Nodey): Nodey | undefined { let nodeHist = this.getHistoryOf(name); if (nodeHist === undefined) // error case only console.error("No history found for " + name + " " + typeof name); else return nodeHist.latest; } getPriorVersion(name?: string | Nodey): Nodey | undefined { if (!name) return; // error case only let ver = -1; // error case only if (name instanceof Nodey) { if (name.version !== undefined) ver = name.version - 1; } else { let [, , verVal] = (name as string).split("."); ver = parseInt(verVal) - 1; } let nodeHist = this.getHistoryOf(name); if (ver > -1 && nodeHist) return nodeHist.getVersion(ver); else return; } get(name?: string): Nodey | undefined { if (!name) return; // error case only //log("attempting to find", name); let [, , verVal] = name.split("."); let ver = verVal ? parseInt(verVal) : undefined; let nodeHist = this.getHistoryOf(name); if (ver !== undefined) return nodeHist?.getVersion(ver); return nodeHist?.latest; } getOutput(nodey?: NodeyCode): OutputHistory | undefined { if (!nodey) return; let cell: NodeyCodeCell; if (nodey instanceof NodeyCodeCell) cell = nodey; else cell = this.getCellParent(nodey); let cellHistory = this.getHistoryOf(cell) as CodeHistory; let outName = cellHistory?.getOutput(cell?.version); if (outName) return this.getHistoryOf(outName) as OutputHistory; return; } // returns output that was specifically created or present in a given notebook getOutputForNotebook( nodey?: NodeyCode, relativeTo?: NodeyNotebook ): NodeyOutput | undefined { if (!nodey || !relativeTo) return; let outputHist = this.getOutput(nodey); if (!outputHist) return; let out = outputHist.find( (output) => output.created === relativeTo.created ); if (!out) { // no output was created in this notebook, so find any output that would // have been present let outBefore = outputHist.filter( (output) => output.created < relativeTo.created ); out = outBefore[outBefore.length - 1]; } return out; } getAllOutput(nodey?: NodeyCode): OutputHistory[] | undefined { if (!nodey) return; let cell: NodeyCodeCell; if (nodey instanceof NodeyCodeCell) cell = nodey; else { let parent = this.getCellParent(nodey); if (parent) cell = parent; } let cellHistory = this.getHistoryOf(cell) as CodeHistory; let outNames = cellHistory?.allOutput; return outNames?.map((name) => this.getHistoryOf(name) as OutputHistory); } public store(nodey: Nodey): void { if (nodey instanceof NodeyNotebook) { let id = 0; nodey.id = id; // if this is the first version if (!this._notebookHistory) this._notebookHistory = new NodeHistory<NodeyNotebook>(); this._notebookHistory.addVersion(nodey); } else { let store = this._getStoreFor(nodey); if (store) { let history = this._makeHistoryFor(nodey); if (history) { let id = store.push(history) - 1; nodey.id = id; store[nodey.id].addVersion(nodey); } else console.error("Failed to create new history for nodey: ", nodey); } else console.error( "Failed to find existing history store for nodey ", nodey ); } } /* * Search */ public search(query: string): searchResult[] { return Search.search( query, this.history.inspector, this._markdownStore, this._codeCellStore, this._outputStore ); } /** * newNodey and oldNodey are nodeys with two seperate histories. * This function creates a back pointer between the first version * of newNodey back to the history, version v of oldNodey. **/ public linkBackHistories(newNodey: Nodey, oldNodey: Nodey): void { let history = this.getHistoryOf(newNodey); if (history) history.addOriginPointer(oldNodey); else console.error( "Failed to link back histories between ", newNodey, " and ", oldNodey ); } private _getStoreFor(nodey: Nodey): NodeHistory<Nodey>[] | undefined { if (nodey instanceof NodeyCodeCell) return this._codeCellStore; else if (nodey instanceof NodeyMarkdown) return this._markdownStore; else if (nodey instanceof NodeyOutput) return this._outputStore; else if (nodey instanceof NodeyCode) return this._snippetStore; else if (nodey instanceof NodeyRawCell) return this._rawCellStore; } private _makeHistoryFor(nodey: Nodey) { if (nodey instanceof NodeyMarkdown || nodey instanceof NodeyRawCell) return new NodeHistory<NodeyCell>(); else if (nodey instanceof NodeyCodeCell) return new CodeHistory(); else if (nodey instanceof NodeyOutput) return new OutputHistory(this.fileManager); else if (nodey instanceof NodeyCode) return new NodeHistory<NodeyCode>(); } public registerTiedNodey(nodey: NodeyCell, forceTie: string): void { let oldNodey = this.get(forceTie) as NodeyCell; let history = this.getHistoryOf(oldNodey); if (history) { history.addVersion(nodey); nodey.id = oldNodey.id; } else { console.error( "Failed to register tied history between ", nodey.artifactName, " and ", forceTie ); } } public getCellParent(relativeTo: Nodey): NodeyCodeCell | undefined { //log("get cell parent of ", relativeTo); if (relativeTo instanceof NodeyCodeCell) return relativeTo; else if (relativeTo.parent) { const latest = this.getLatestOf(relativeTo.parent); if (latest) return this.getCellParent(latest); } } public getNotebookOf(relativeTo: Nodey): NodeyNotebook | undefined { let created = relativeTo?.created; if (created !== undefined) { // error case if undefined let event = this.history.checkpoints.get(created); if (event) { // error case if undefined let notebook_id = event.notebook; if (notebook_id !== undefined) return this.getNotebook(notebook_id); } } return; } public getForNotebook( nodeyHist: NodeHistory<Nodey>, relativeTo: number ): Nodey | undefined { const notebook = this.getNotebook(relativeTo); const nextNotebook = this.getNotebook(relativeTo + 1); const endCheck = nextNotebook?.created || notebook?.created + 1 || -1; if (nodeyHist && endCheck !== -1) { let max = -1; nodeyHist.foreach((ver) => { if (ver.created < endCheck) max = ver.version; }); return nodeyHist.getVersion(max); } } public writeToFile(): void { this.fileManager.writeToFile(); } public dump() { //TODO only for debug log(this._codeCellStore); } public toJSON(): HistoryStore.SERIALIZE { return { notebook: this._notebookHistory.toJSON(), codeCells: this._codeCellStore.map((hist) => hist.toJSON()), markdownCells: this._markdownStore.map((hist) => hist.toJSON()), rawCells: this._rawCellStore.map((hist) => hist.toJSON()), snippets: this._snippetStore.map((hist) => hist.toJSON()), output: this._outputStore.map((hist) => hist.toJSON()), }; } public fromJSON(data: HistoryStore.SERIALIZE) { this._codeCellStore = data.codeCells.map( (item: CodeHistory.SERIALIZE, id: number) => { let hist = new CodeHistory(); hist.fromJSON(item, NodeyCodeCell.fromJSON, id); return hist; } ); this._markdownStore = data.markdownCells.map( (item: NodeHistory.SERIALIZE, id: number) => { let hist = new NodeHistory<NodeyMarkdown>(); hist.fromJSON(item, NodeyMarkdown.fromJSON, id); return hist; } ); if (data.rawCells) this._rawCellStore = data.rawCells.map( (item: NodeHistory.SERIALIZE, id: number) => { let hist = new NodeHistory<NodeyRawCell>(); hist.fromJSON(item, NodeyRawCell.fromJSON, id); return hist; } ); this._snippetStore = data.snippets.map( (item: NodeHistory.SERIALIZE, id: number) => { let hist = new NodeHistory<NodeyCode>(); hist.fromJSON(item, NodeyCode.fromJSON, id); return hist; } ); this._outputStore = data.output.map( (item: NodeHistory.SERIALIZE, id: number) => { let hist = new OutputHistory(this.fileManager); hist.fromJSON(item, NodeyOutput.fromJSON, id); return hist; } ); this._notebookHistory = new NodeHistory<NodeyNotebook>(); this._notebookHistory.fromJSON( data.notebook, NodeyNotebook.fromJSON, 0 // all notebooks have an id of 0, it's a singleton ); } /* * Returns the equivalent of toJSON() for a slice of history * starting at fromVer and ending (non-inclusive) at toVer * versions of the whole notebook. * * returns null if given an invalid fromVer/toVer pair */ public slice(fromVer: number, toVer: number): HistoryStore.SERIALIZE | null { if (fromVer > toVer) return null; // error case const fromTime = this.getNotebook(fromVer)?.created; const toTime = this.getNotebook(toVer)?.created; if (!fromTime || !toTime) return null; // error case // slice all available histories let notebookList: NodeHistory.SERIALIZE = this._notebookHistory.sliceByVer( fromVer, toVer ); let codeCells = this.sliceStore(this._codeCellStore, fromTime, toTime); let markdownCells = this.sliceStore(this._markdownStore, fromTime, toTime); let rawCells = this.sliceStore(this._rawCellStore, fromTime, toTime); let output = this.sliceStore(this._outputStore, fromTime, toTime); return { notebook: notebookList, codeCells, markdownCells, rawCells, snippets: [], output, }; } // helper method private sliceStore( store: NodeHistory<Nodey>[], fromTime: number, toTime: number ): NodeHistory.SERIALIZE[] { let slice = []; store.forEach((history: NodeHistory<Nodey>) => { let data = history.sliceByTime(fromTime, toTime); if (data && data.versions.length > 0) slice.push(data); }); return slice; } } export namespace HistoryStore { export interface SERIALIZE { notebook: NodeHistory.SERIALIZE; codeCells: NodeHistory.SERIALIZE[]; markdownCells: NodeHistory.SERIALIZE[]; rawCells: NodeHistory.SERIALIZE[]; snippets: NodeHistory.SERIALIZE[]; output: NodeHistory.SERIALIZE[]; } }
the_stack
import * as assert from 'assert'; import {describe, it, before, after, afterEach} from 'mocha'; import {cls, TraceCLS, TraceCLSMechanism} from '../src/cls'; import { defaultConfig, GetHeaderFunction as HeaderGetter, OpenCensusPropagation, RequestDetails, SetHeaderFunction as HeaderSetter, } from '../src/config'; import {SpanType} from '../src/constants'; import { StackdriverTracer, StackdriverTracerComponents, StackdriverTracerConfig, } from '../src/trace-api'; import {traceWriter} from '../src/trace-writer'; import {alwaysTrace, neverTrace} from '../src/tracing-policy'; import {FORCE_NEW, TraceContext} from '../src/util'; import {TestLogger} from './logger'; import * as testTraceModule from './trace'; import {getBaseConfig, NoPropagation} from './utils'; describe('Trace Interface', () => { const logger = new TestLogger(); function createTraceAgent( config?: Partial<StackdriverTracerConfig>, components?: Partial<StackdriverTracerComponents> ): StackdriverTracer { const result = new StackdriverTracer('test'); result.enable( Object.assign(getBaseConfig(), config), Object.assign( { tracePolicy: alwaysTrace(), logger, propagation: new NoPropagation(), }, components ) ); return result; } before(() => { testTraceModule.setCLSForTest(TraceCLS); cls.create({mechanism: TraceCLSMechanism.ASYNC_LISTENER}, logger).enable(); return traceWriter .create( Object.assign( {[FORCE_NEW]: true, authOptions: {projectId: 'project-1'}}, defaultConfig ), logger ) .initialize(); }); after(() => { testTraceModule.setCLSForTest(testTraceModule.TestCLS); }); it('should correctly manage internal state', () => { const traceAPI = createTraceAgent(); assert.ok(traceAPI.isActive()); traceAPI.disable(); assert.ok(!traceAPI.isActive(), 'Being disabled sets isActive to false'); }); describe('behavior when initialized', () => { afterEach(() => { testTraceModule.clearTraceData(); }); it('should produce real child spans with createChildSpan', () => { const traceAPI = createTraceAgent(); traceAPI.runInRootSpan({name: 'root'}, rootSpan => { const childSpan = traceAPI.createChildSpan({name: 'sub'}); childSpan.addLabel('key', 'val'); childSpan.endSpan(); rootSpan.endSpan(); }); const rootSpanData = testTraceModule.getOneSpan( span => span.name === 'root' ); const childSpanData = testTraceModule.getOneSpan( span => span.name === 'sub' ); assert.strictEqual(childSpanData.parentSpanId, rootSpanData.spanId); assert.strictEqual(childSpanData.labels.key, 'val'); }); it('should produce real child spans through root span API', () => { const traceAPI = createTraceAgent(); traceAPI.runInRootSpan({name: 'root'}, rootSpan => { const childSpan = rootSpan.createChildSpan({name: 'sub'}); childSpan.addLabel('key', 'val'); childSpan.endSpan(); rootSpan.endSpan(); }); // getOneSpan asserts that only one such span exists. const rootSpanData = testTraceModule.getOneSpan( span => span.name === 'root' ); const childSpanData = testTraceModule.getOneSpan( span => span.name === 'sub' ); assert.strictEqual(childSpanData.parentSpanId, rootSpanData.spanId); assert.strictEqual(childSpanData.labels.key, 'val'); }); it('should produce real root spans with runInRootSpan', () => { const traceAPI = createTraceAgent(); const result = traceAPI.runInRootSpan({name: 'root'}, rootSpan => { rootSpan.addLabel('key', 'val'); rootSpan.endSpan(); return 'result'; }); assert.strictEqual(result, 'result'); // getOneSpan asserts that only one such span exists. const rootSpanData = testTraceModule.getOneSpan( span => span.name === 'root' ); assert.strictEqual(rootSpanData.labels.key, 'val'); }); it('should allow sequential root spans', () => { const traceAPI = createTraceAgent(); traceAPI.runInRootSpan({name: 'root1'}, rootSpan => { rootSpan.endSpan(); }); traceAPI.runInRootSpan({name: 'root2'}, rootSpan => { rootSpan.endSpan(); }); assert.strictEqual(testTraceModule.getTraces().length, 2); }); it('should not allow nested root spans', () => { const traceAPI = createTraceAgent(); traceAPI.runInRootSpan({name: 'root1'}, rootSpan => { traceAPI.runInRootSpan({name: 'root2'}, notRootSpan => { assert.strictEqual(notRootSpan.type, SpanType.UNCORRELATED); notRootSpan.endSpan(); }); rootSpan.endSpan(); }); assert.strictEqual(testTraceModule.getTraces().length, 1); }); it('should return a root span when getCurrentRootSpan is called', () => { const traceAPI = createTraceAgent(); // When a root span isn't running, return UNCORRELATED. assert.strictEqual( traceAPI.getCurrentRootSpan().type, SpanType.UNCORRELATED ); traceAPI.runInRootSpan({name: 'root'}, rootSpan => { assert.strictEqual(traceAPI.getCurrentRootSpan(), rootSpan); rootSpan.endSpan(); }); }); it('should warn when the spans per trace soft limit has been exceeded', () => { const tracer = createTraceAgent({ spansPerTraceSoftLimit: 10, spansPerTraceHardLimit: 20, }); tracer.runInRootSpan({name: 'root'}, rootSpan => { for (let i = 0; i < 10; i++) { tracer.createChildSpan({name: `span-${i}`}).endSpan(); } assert.strictEqual(logger.getNumLogsWith('warn', '[span-9]'), 1); for (let i = 0; i < 9; i++) { tracer.createChildSpan({name: `span-${i + 10}`}).endSpan(); } const child = tracer.createChildSpan({name: 'span-19'}); assert.ok(!tracer.isRealSpan(child)); assert.strictEqual(logger.getNumLogsWith('warn', '[span-19]'), 1); rootSpan.endSpan(); }); }); it('should return null context ID when one does not exist', () => { const traceAPI = createTraceAgent(); assert.strictEqual(traceAPI.getCurrentContextId(), null); }); it('should return the appropriate context ID', () => { const traceAPI = createTraceAgent(); traceAPI.runInRootSpan({name: 'root'}, rootSpan => { const id = traceAPI.getCurrentContextId(); assert.ok(rootSpan.getTraceContext()); assert.strictEqual(id, rootSpan.getTraceContext()!.traceId); rootSpan.endSpan(); // getOneTrace asserts that there is exactly one trace. testTraceModule.getOneTrace(trace => trace.traceId === id); }); }); it('should return a context ID even if in an untraced request', () => { const traceAPI = createTraceAgent({}, {tracePolicy: neverTrace()}); traceAPI.runInRootSpan({name: ''}, rootSpan => { assert.strictEqual(rootSpan.type, SpanType.UNSAMPLED); assert.notStrictEqual(traceAPI.getCurrentContextId(), null); assert.ok(rootSpan.getTraceContext()); assert.strictEqual( traceAPI.getCurrentContextId(), rootSpan.getTraceContext()!.traceId ); assert.ok(rootSpan.createChildSpan().getTraceContext()); assert.ok(traceAPI.createChildSpan().getTraceContext()); }); }); it('should return the project ID from the Trace Writer (promise api)', async () => { const traceApi = createTraceAgent(); assert.strictEqual(await traceApi.getProjectId(), 'project-1'); }); it('should return get the project ID from the Trace Writer', () => { const traceApi = createTraceAgent(); assert.strictEqual(traceApi.getWriterProjectId(), 'project-1'); }); it('should pass relevant fields to the trace policy', () => { class CaptureOptionsTracePolicy { capturedShouldTraceParam: RequestDetails | null = null; shouldTrace(options: RequestDetails) { this.capturedShouldTraceParam = options; return false; } } const tracePolicy = new CaptureOptionsTracePolicy(); const traceAPI = createTraceAgent({}, {tracePolicy}); // All params present { const rootSpanOptions = { name: 'root', url: 'foo', method: 'bar', traceContext: {traceId: '1', spanId: '2', options: 1}, }; const beforeRootSpan = Date.now(); traceAPI.runInRootSpan(rootSpanOptions, rootSpan => { assert.strictEqual(rootSpan.type, SpanType.UNSAMPLED); rootSpan.endSpan(); }); const afterRootSpan = Date.now(); assert.ok(tracePolicy.capturedShouldTraceParam); const shouldTraceParam = tracePolicy.capturedShouldTraceParam!; assert.strictEqual(shouldTraceParam.url, 'foo'); assert.strictEqual(shouldTraceParam.method, 'bar'); assert.ok(shouldTraceParam.timestamp >= beforeRootSpan); assert.ok(shouldTraceParam.timestamp <= afterRootSpan); assert.ok(shouldTraceParam.timestamp <= afterRootSpan); assert.deepStrictEqual( shouldTraceParam.traceContext, rootSpanOptions.traceContext ); assert.strictEqual(shouldTraceParam.options, rootSpanOptions); } tracePolicy.capturedShouldTraceParam = null; // Limited params present { const rootSpanOptions = {name: 'root'}; traceAPI.runInRootSpan(rootSpanOptions, rootSpan => { assert.strictEqual(rootSpan.type, SpanType.UNSAMPLED); rootSpan.endSpan(); }); assert.ok(tracePolicy.capturedShouldTraceParam); const shouldTraceParam = tracePolicy.capturedShouldTraceParam!; assert.strictEqual(shouldTraceParam.url, ''); assert.strictEqual(shouldTraceParam.method, ''); assert.strictEqual(shouldTraceParam.traceContext, null); assert.strictEqual(shouldTraceParam.options, rootSpanOptions); } }); it('should expose methods for trace context header propagation', () => { class TestPropagation implements OpenCensusPropagation { extract({getHeader}: HeaderGetter) { return {traceId: getHeader('a') as string, spanId: '0', options: 1}; } inject({setHeader}: HeaderSetter, traceContext: TraceContext) { setHeader(traceContext.traceId, 'y'); } } const propagation = new TestPropagation(); const tracer = createTraceAgent({}, {propagation}); const result = tracer.propagation.extract(s => `${s}${s}`); assert.deepStrictEqual(result, { traceId: 'aa', spanId: '0', options: 1, }); let setHeaderCalled = false; tracer.propagation.inject( (key: string, value: string) => { assert.strictEqual(key, 'x'); assert.strictEqual(value, 'y'); setHeaderCalled = true; }, {traceId: 'x', spanId: '0', options: 1} ); assert.ok(setHeaderCalled); }); it('should respect enhancedDatabaseReporting options field', () => { [true, false].forEach(enhancedDatabaseReporting => { const traceAPI = createTraceAgent({ enhancedDatabaseReporting, }); assert.strictEqual( traceAPI.enhancedDatabaseReportingEnabled(), enhancedDatabaseReporting ); }); }); it('should use incoming context to set trace ID when available', () => { // Propagate from trace context header { createTraceAgent().runInRootSpan( { name: 'root1', traceContext: {traceId: '123456', spanId: '667', options: 1}, }, rootSpan => { rootSpan.endSpan(); } ); const foundTrace = testTraceModule.getOneTrace( trace => trace.traceId === '123456' ); assert.strictEqual(foundTrace.spans.length, 1); assert.strictEqual(foundTrace.spans[0].name, 'root1'); assert.strictEqual(foundTrace.spans[0].parentSpanId, '667'); } // Generate a trace context { createTraceAgent().runInRootSpan({name: 'root2'}, rootSpan => { rootSpan.endSpan(); }); // The trace ID will not randomly be 123456 const foundTrace = testTraceModule.getOneTrace( trace => trace.traceId !== '123456' ); assert.strictEqual(foundTrace.spans.length, 1); assert.strictEqual(foundTrace.spans[0].name, 'root2'); assert.notStrictEqual(foundTrace.spans[0].parentSpanId, '667'); } }); it('should trace if no option flags are provided', () => { createTraceAgent({enhancedDatabaseReporting: false}).runInRootSpan( {name: 'root', traceContext: {traceId: '123456', spanId: '667'}}, rootSpan => { rootSpan.endSpan(); } ); const foundTrace = testTraceModule.getOneTrace( trace => trace.traceId === '123456' ); assert.strictEqual(foundTrace.spans.length, 1); }); describe('getting response trace context', () => { it('should behave as expected', () => { const fakeTraceId = 'ffeeddccbbaa99887766554433221100'; const traceApi = createTraceAgent(); const tracedContext = {traceId: fakeTraceId, spanId: '0', options: 1}; const untracedContext = { traceId: fakeTraceId, spanId: '0', options: 0, }; const unspecifiedContext = {traceId: fakeTraceId, spanId: '0'}; assert.deepStrictEqual( traceApi.getResponseTraceContext(tracedContext, true), tracedContext ); assert.deepStrictEqual( traceApi.getResponseTraceContext(tracedContext, false), untracedContext ); assert.deepStrictEqual( traceApi.getResponseTraceContext(untracedContext, true), untracedContext ); assert.deepStrictEqual( traceApi.getResponseTraceContext(untracedContext, false), untracedContext ); assert.deepStrictEqual( traceApi.getResponseTraceContext(unspecifiedContext, true), untracedContext ); assert.deepStrictEqual( traceApi.getResponseTraceContext(unspecifiedContext, false), untracedContext ); }); }); }); });
the_stack
import { __testMethods } from './SpellingDictionaryMethods'; import { createSpellingDictionary } from './createSpellingDictionary'; import { SpellingDictionaryFromTrie } from './SpellingDictionaryFromTrie'; import { Trie } from 'cspell-trie-lib'; // cSpell:ignore aple describe('Verify building Dictionary', () => { test('build from word list', async () => { const words = ['apple', 'ape', 'able', 'apple', 'banana', 'orange', 'pear', 'aim', 'approach', 'bear']; const dict = await createSpellingDictionary(words, 'words', 'test', {}); expect(dict.name).toBe('words'); expect(dict.has('apple')).toBe(true); const suggestions = dict.suggest('aple').map(({ word }) => word); expect(suggestions).toEqual(expect.arrayContaining(['apple'])); expect(suggestions).toEqual(expect.arrayContaining(['ape'])); expect(suggestions).toEqual(expect.not.arrayContaining(['banana'])); }); test('compounds from word list', async () => { const words = [ 'apple', 'apples', 'ape', 'able', 'apple', 'banana', 'orange', 'pear', 'aim', 'approach', 'bear', ]; const dict = await createSpellingDictionary(words, 'words', 'test', { useCompounds: true }); expect(dict.has('apple')).toBe(true); expect(dict.has('Apple')).toBe(true); expect(dict.has('APPLE')).toBe(true); expect(dict.has('APPLEs')).toBe(true); expect(dict.has('APPles')).toBe(true); // cspell:disable-line // cspell:ignore applebanana applebananas applebananaorange expect(dict.has('applebanana')).toBe(true); expect(dict.has('applebananaorange')).toBe(true); expect(dict.has('applebananas')).toBe(false); }); test('case-sensitive word list', async () => { const words = ['apple', 'Seattle', 'Amsterdam', 'surf', 'words', 'English', 'McGreyer']; const dict = await createSpellingDictionary(words, 'words', 'test', { caseSensitive: true, }); const ignoreCase = { ignoreCase: true }; const useCase = { ignoreCase: false }; expect(dict.has('apple', useCase)).toBe(true); expect(dict.has('Apple', ignoreCase)).toBe(true); expect(dict.has('Apple', useCase)).toBe(true); expect(dict.has('APPLE', useCase)).toBe(true); expect(dict.has('Seattle', useCase)).toBe(true); expect(dict.has('seattle', useCase)).toBe(false); expect(dict.has('English', useCase)).toBe(true); expect(dict.has('english', useCase)).toBe(false); expect(dict.has('ENGLISH', useCase)).toBe(true); expect(dict.has('McGreyer', useCase)).toBe(true); expect(dict.has('mcgreyer', useCase)).toBe(false); // cspell:disable-line // We do not support mixed case as all caps matching at this point. expect(dict.has('MCGREYER', useCase)).toBe(false); // cspell:disable-line expect(dict.has('MCGREYER', ignoreCase)).toBe(true); // cspell:disable-line }); test('Suggest Trie', () => { const words = [ 'apple', 'ape', 'able', 'apple', 'banana', 'orange', 'pear', 'aim', 'approach', 'bear', 'cattle', 'rattle', 'battle', 'rattles', 'battles', 'tattles', ]; const trie = Trie.create(words); const dict = new SpellingDictionaryFromTrie(trie, 'trie', {}); // cspell:ignore cattles const results = dict.suggest('Cattles'); const suggestions = results.map(({ word }) => word); expect(suggestions).toEqual(['cattle', 'battles', 'rattles', 'tattles', 'battle', 'rattle']); expect(suggestions).toEqual(expect.not.arrayContaining(['banana'])); }); test('build from list containing non-strings', async () => { // eslint-disable-next-line no-sparse-arrays const words = ['apple', 'ape', 'able', , 'apple', 'banana', 'orange', 5, 'pear', 'aim', 'approach', 'bear']; const dict = await createSpellingDictionary(words as string[], 'words', 'test', {}); expect(dict.name).toBe('words'); // expect(dict).toBeInstanceOf(SpellingDictionaryFromTrie); expect(dict.has('apple')).toBe(true); const suggestions = dict.suggest('aple').map(({ word }) => word); expect(suggestions).toEqual(expect.arrayContaining(['apple'])); expect(suggestions).toEqual(expect.arrayContaining(['ape'])); expect(suggestions).toEqual(expect.not.arrayContaining(['banana'])); }); type Test = [string, boolean, string[]]; // cspell:ignore café const tests: Test[] = [ ['house', false, ['house']], ['House', false, ['House', 'house']], ['café', false, ['cafe', 'café']], ['Café', false, ['Cafe', 'Café', 'cafe', 'café']], ['House', true, ['House', '~house']], ['HOUSE', true, ['HOUSE', '~house']], ['Café', true, ['Café', '~Cafe', '~cafe', '~café']], // Make sure all accent forms work. ['café'.normalize(), false, ['cafe', 'café']], ['café'.normalize('NFD'), false, ['cafe', 'café']], ['café'.normalize('NFKC'), false, ['cafe', 'café']], ['café'.normalize('NFKD'), false, ['cafe', 'café']], ]; test.each(tests)( 'wordDictionaryFormsCollector %s %o %o', (word: string, isCaseSensitive: boolean, expected: string[]) => { const collector = __testMethods.wordDictionaryFormsCollector(isCaseSensitive ? '~' : ''); expect([...collector(word)].sort()).toEqual(expected.sort()); expect([...collector(word)]).toEqual([]); } ); }); describe('Validate wordSearchForms', () => { test.each` word | isCaseSensitive | ignoreCase | expected ${'house'} | ${false} | ${false} | ${['house']} ${'House'} | ${false} | ${false} | ${['house']} ${'House'} | ${false} | ${false} | ${['house']} ${'House'} | ${true} | ${false} | ${['House', 'house']} ${'HOUSE'} | ${false} | ${false} | ${['house']} ${'HOUSE'} | ${true} | ${false} | ${['HOUSE', 'House', 'house']} ${'café'} | ${false} | ${false} | ${['café']} ${'café'} | ${true} | ${false} | ${['café']} ${'café'} | ${true} | ${true} | ${['café']} ${'Café'} | ${false} | ${false} | ${['café']} ${'Café'} | ${false} | ${true} | ${['café']} ${'Café'} | ${true} | ${false} | ${['Café', 'café']} ${'Café'} | ${true} | ${true} | ${['café']} ${'CAFÉ'} | ${false} | ${false} | ${['café']} ${'CAFÉ'} | ${false} | ${true} | ${['café']} ${'CAFÉ'} | ${true} | ${false} | ${['CAFÉ', 'Café', 'café']} ${'CAFÉ'} | ${true} | ${true} | ${['café']} ${'café'.normalize()} | ${false} | ${false} | ${['café']} ${'café'.normalize('NFD')} | ${false} | ${false} | ${['café']} ${'café'.normalize('NFKC')} | ${false} | ${false} | ${['café']} ${'café'.normalize('NFKD')} | ${false} | ${false} | ${['café']} `('$word $isCaseSensitive $ignoreCase $expected', ({ word, isCaseSensitive, ignoreCase, expected }) => { const words = __testMethods.wordSearchFormsArray(word, isCaseSensitive, ignoreCase); expect(words.sort()).toEqual(expected.sort()); }); }); describe('Verify Case Sensitive Dictionaries', () => { test.each` word | ignoreCase | expected ${'Paris'} | ${undefined} | ${true} ${'PARIS'} | ${undefined} | ${true} ${'paris'} | ${undefined} | ${true} ${'Paris'} | ${true} | ${true} ${'PARIS'} | ${true} | ${true} ${'paris'} | ${true} | ${true} ${'Paris'} | ${false} | ${true} ${'PARIS'} | ${false} | ${true} ${'paris'} | ${false} | ${false} ${'Köln'} | ${false} | ${true} ${'köln'} | ${false} | ${false} ${'KÖLN'} | ${false} | ${true} `(`Has $word Case: $ignoreCase Exp: $expected`, ({ word, ignoreCase, expected }) => { const dict = sampleDict(); expect(dict.has(word, { ignoreCase })).toBe(expected); }); // cspell:ignore kuln test.each` word | ignoreCase | expected ${'köln'} | ${false} | ${['Köln']} ${'köln'} | ${true} | ${['köln', 'koln', 'Köln']} ${'koln'} | ${true} | ${['koln', 'köln', 'Köln']} ${'kuln'} | ${false} | ${['Köln']} ${'kuln'} | ${true} | ${['koln', 'köln', 'Köln']} `('Suggestions for $word $ignoreCase $expected', ({ word, ignoreCase, expected }) => { // cspell:ignore koln const dict = sampleDict(); const sugs = dict.suggest(word, { ignoreCase }); const sugWords = sugs.map((s) => s.word); expect(sugWords).toEqual(expected); }); }); function sampleDict() { const words = sampleWords(); return createSpellingDictionary(words, 'words', 'test', { caseSensitive: true }); } // cspell:words métro Rhône Köln Düsseldorf function sampleWords() { return ` England Canada Netherlands France German China Belgium Paris Chicago Amsterdam Antwerp Brussels Rhône Cologne Köln Düsseldorf métro cafe café metro apple apples ape apes around astound profound compound table tables tabled `.split(/\s+/g); }
the_stack
import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/cr_elements/cr_input/cr_input_style_css.m.js'; import '../strings.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {Coordinate2d} from '../data/coordinate2d.js'; import {CustomMarginsOrientation} from '../data/margins.js'; import {MeasurementSystem} from '../data/measurement_system.js'; import {Size} from '../data/size.js'; import {observerDepsDefined} from '../print_preview_utils.js'; import {InputMixin} from './input_mixin.js'; /** * Radius of the margin control in pixels. Padding of control + 1 for border. */ const RADIUS_PX: number = 9; export interface PrintPreviewMarginControlElement { $: { input: HTMLInputElement; lineContainer: HTMLDivElement; line: HTMLDivElement; }; } const PrintPreviewMarginControlElementBase = I18nMixin(WebUIListenerMixin(InputMixin(PolymerElement))); export class PrintPreviewMarginControlElement extends PrintPreviewMarginControlElementBase { static get is() { return 'print-preview-margin-control'; } static get template() { return html`{__html_template__}`; } static get properties() { return { disabled: { type: Boolean, reflectToAttribute: true, observer: 'onDisabledChange_', }, side: { type: String, reflectToAttribute: true, }, invalid: { type: Boolean, reflectToAttribute: true, }, invisible: { type: Boolean, reflectToAttribute: true, observer: 'onClipSizeChange_', }, measurementSystem: Object, focused_: { type: Boolean, reflectToAttribute: true, value: false, }, positionInPts_: { type: Number, notify: true, value: 0, }, scaleTransform: { type: Number, notify: true, }, translateTransform: { type: Object, notify: true, }, pageSize: { type: Object, notify: true, }, clipSize: { type: Object, notify: true, observer: 'onClipSizeChange_', }, }; } disabled: boolean; side: CustomMarginsOrientation; invalid: boolean; invisible: boolean; measurementSystem: MeasurementSystem|null; scaleTransform: number; translateTransform: Coordinate2d; pageSize: Size; clipSize: Size|null; private focused_: boolean; private positionInPts_: number; static get observers() { return [ 'updatePosition_(positionInPts_, scaleTransform, translateTransform, ' + 'pageSize, side)', ]; } ready() { super.ready(); this.addEventListener('input-change', e => this.onInputChange_(e)); } /** @return The input element for InputBehavior. */ getInput(): HTMLInputElement { return this.$.input; } /** * @param valueInPts New value of the margin control's textbox in pts. */ setTextboxValue(valueInPts: number) { const textbox = this.$.input; const pts = textbox.value ? this.parseValueToPts_(textbox.value) : null; if (pts !== null && valueInPts === Math.round(pts)) { // If the textbox's value represents the same value in pts as the new one, // don't reset. This allows the "undo" command to work as expected, see // https://crbug.com/452844. return; } textbox.value = this.serializeValueFromPts_(valueInPts); this.resetString(); } /** @return The current position of the margin control. */ getPositionInPts(): number { return this.positionInPts_; } /** @param position The new position for the margin control. */ setPositionInPts(position: number) { this.positionInPts_ = position; } /** * @return 'true' or 'false', indicating whether the input should be * aria-hidden. */ private getAriaHidden_(): string { return this.invisible.toString(); } /** * Converts a value in pixels to points. * @param pixels Pixel value to convert. * @return Given value expressed in points. */ convertPixelsToPts(pixels: number): number { let pts; const Orientation = CustomMarginsOrientation; if (this.side === Orientation.TOP) { pts = pixels - this.translateTransform.y + RADIUS_PX; pts /= this.scaleTransform; } else if (this.side === Orientation.RIGHT) { pts = pixels - this.translateTransform.x + RADIUS_PX; pts /= this.scaleTransform; pts = this.pageSize.width - pts; } else if (this.side === Orientation.BOTTOM) { pts = pixels - this.translateTransform.y + RADIUS_PX; pts /= this.scaleTransform; pts = this.pageSize.height - pts; } else { assert(this.side === Orientation.LEFT); pts = pixels - this.translateTransform.x + RADIUS_PX; pts /= this.scaleTransform; } return pts; } /** * @param event A pointerdown event triggered by this element. * @return Whether the margin should start being dragged. */ shouldDrag(event: PointerEvent): boolean { return !this.disabled && event.button === 0 && (event.composedPath()[0] === this.$.lineContainer || event.composedPath()[0] === this.$.line); } private onDisabledChange_() { if (this.disabled) { this.focused_ = false; } } /** * @param value Value to parse to points. E.g. '3.40' or '200'. * @return Value in points represented by the input value. */ private parseValueToPts_(value: string): number|null { value = value.trim(); if (value.length === 0) { return null; } assert(this.measurementSystem); const decimal = this.measurementSystem!.decimalDelimiter; const thousands = this.measurementSystem!.thousandsDelimiter; const whole = `(?:0|[1-9]\\d*|[1-9]\\d{0,2}(?:[${thousands}]\\d{3})*)`; const fractional = `(?:[${decimal}]\\d+)`; const wholeDecimal = `(?:${whole}[${decimal}])`; const validationRegex = new RegExp( `^-?(?:${whole}${fractional}?|${fractional}|${wholeDecimal})$`); if (validationRegex.test(value)) { // Removing thousands delimiters and replacing the decimal delimiter with // the dot symbol in order to use parseFloat() properly. value = value.replace(new RegExp(`\\${thousands}`, 'g'), '') .replace(decimal, '.'); return this.measurementSystem!.convertToPoints(parseFloat(value)); } return null; } /** * @param value Value in points to serialize. * @return String representation of the value in the system's local units. */ private serializeValueFromPts_(value: number): string { assert(this.measurementSystem); value = this.measurementSystem!.convertFromPoints(value); value = this.measurementSystem!.roundValue(value); // Convert the dot symbol to the decimal delimiter for the locale. return value.toString().replace( '.', this.measurementSystem!.decimalDelimiter); } private fire_(eventName: string, detail?: any) { this.dispatchEvent( new CustomEvent(eventName, {bubbles: true, composed: true, detail})); } /** * @param e Contains the new value of the input. */ private onInputChange_(e: CustomEvent<string>) { if (e.detail === '') { return; } const value = this.parseValueToPts_(e.detail); if (value === null) { this.invalid = true; return; } this.fire_('text-change', value); } private onBlur_() { this.focused_ = false; this.resetAndUpdate(); this.fire_('text-blur', this.invalid || !this.$.input.value); } private onFocus_() { this.focused_ = true; this.fire_('text-focus'); } private updatePosition_() { if (!observerDepsDefined(Array.from(arguments))) { return; } const Orientation = CustomMarginsOrientation; let x = this.translateTransform.x; let y = this.translateTransform.y; let width: number|null = null; let height: number|null = null; if (this.side === Orientation.TOP) { y = this.scaleTransform * this.positionInPts_ + this.translateTransform.y - RADIUS_PX; width = this.scaleTransform * this.pageSize.width; } else if (this.side === Orientation.RIGHT) { x = this.scaleTransform * (this.pageSize.width - this.positionInPts_) + this.translateTransform.x - RADIUS_PX; height = this.scaleTransform * this.pageSize.height; } else if (this.side === Orientation.BOTTOM) { y = this.scaleTransform * (this.pageSize.height - this.positionInPts_) + this.translateTransform.y - RADIUS_PX; width = this.scaleTransform * this.pageSize.width; } else { x = this.scaleTransform * this.positionInPts_ + this.translateTransform.x - RADIUS_PX; height = this.scaleTransform * this.pageSize.height; } window.requestAnimationFrame(() => { this.style.left = Math.round(x) + 'px'; this.style.top = Math.round(y) + 'px'; if (width !== null) { this.style.width = Math.round(width) + 'px'; } if (height !== null) { this.style.height = Math.round(height) + 'px'; } }); this.onClipSizeChange_(); } private onClipSizeChange_() { if (!this.clipSize) { return; } window.requestAnimationFrame(() => { const offsetLeft = this.offsetLeft; const offsetTop = this.offsetTop; this.style.clip = 'rect(' + (-offsetTop) + 'px, ' + (this.clipSize!.width - offsetLeft) + 'px, ' + (this.clipSize!.height - offsetTop) + 'px, ' + (-offsetLeft) + 'px)'; }); } } declare global { interface HTMLElementTagNameMap { 'print-preview-margin-control': PrintPreviewMarginControlElement; } } customElements.define( PrintPreviewMarginControlElement.is, PrintPreviewMarginControlElement);
the_stack
import { Component, Optional, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { Params } from '@angular/router'; import { CoreSite } from '@classes/site'; import { CoreCourseModuleMainActivityComponent } from '@features/course/classes/main-activity-component'; import { CoreCourseContentsPage } from '@features/course/pages/contents/contents'; import { CoreCourse } from '@features/course/services/course'; import { IonContent } from '@ionic/angular'; import { CoreGroupInfo, CoreGroups } from '@services/groups'; import { CoreNavigator } from '@services/navigator'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreTextUtils } from '@services/utils/text'; import { CoreTimeUtils } from '@services/utils/time'; import { CoreUtils } from '@services/utils/utils'; import { Translate } from '@singletons'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { AddonModAssign, AddonModAssignAssign, AddonModAssignProvider, AddonModAssignSubmissionGradingSummary, } from '../../services/assign'; import { AddonModAssignOffline } from '../../services/assign-offline'; import { AddonModAssignAutoSyncData, AddonModAssignSync, AddonModAssignSyncProvider, AddonModAssignSyncResult, } from '../../services/assign-sync'; import { AddonModAssignModuleHandlerService } from '../../services/handlers/module'; import { AddonModAssignSubmissionComponent } from '../submission/submission'; /** * Component that displays an assignment. */ @Component({ selector: 'addon-mod-assign-index', templateUrl: 'addon-mod-assign-index.html', }) export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit, OnDestroy { @ViewChild(AddonModAssignSubmissionComponent) submissionComponent?: AddonModAssignSubmissionComponent; component = AddonModAssignProvider.COMPONENT; moduleName = 'assign'; assign?: AddonModAssignAssign; // The assign object. canViewAllSubmissions = false; // Whether the user can view all submissions. canViewOwnSubmission = false; // Whether the user can view their own submission. timeRemaining?: string; // Message about time remaining to submit. lateSubmissions?: string; // Message about late submissions. showNumbers = true; // Whether to show number of submissions with each status. summary?: AddonModAssignSubmissionGradingSummary; // The grading summary. needsGradingAvailable = false; // Whether we can see the submissions that need grading. groupInfo: CoreGroupInfo = { groups: [], separateGroups: false, visibleGroups: false, defaultGroupId: 0, }; // Status. submissionStatusSubmitted = AddonModAssignProvider.SUBMISSION_STATUS_SUBMITTED; submissionStatusDraft = AddonModAssignProvider.SUBMISSION_STATUS_DRAFT; needGrading = AddonModAssignProvider.NEED_GRADING; protected currentUserId?: number; // Current user ID. protected currentSite?: CoreSite; // Current user ID. protected syncEventName = AddonModAssignSyncProvider.AUTO_SYNCED; // Observers. protected savedObserver?: CoreEventObserver; protected submittedObserver?: CoreEventObserver; protected gradedObserver?: CoreEventObserver; constructor( protected content?: IonContent, @Optional() courseContentsPage?: CoreCourseContentsPage, ) { super('AddonModLessonIndexComponent', content, courseContentsPage); } /** * Component being initialized. */ async ngOnInit(): Promise<void> { super.ngOnInit(); this.currentUserId = CoreSites.getCurrentSiteUserId(); this.currentSite = CoreSites.getCurrentSite(); // Listen to events. this.savedObserver = CoreEvents.on( AddonModAssignProvider.SUBMISSION_SAVED_EVENT, (data) => { if (this.assign && data.assignmentId == this.assign.id && data.userId == this.currentUserId) { // Assignment submission saved, refresh data. this.showLoadingAndRefresh(true, false); } }, this.siteId, ); this.submittedObserver = CoreEvents.on( AddonModAssignProvider.SUBMITTED_FOR_GRADING_EVENT, (data) => { if (this.assign && data.assignmentId == this.assign.id && data.userId == this.currentUserId) { // Assignment submitted, check completion. CoreCourse.checkModuleCompletion(this.courseId, this.module.completiondata); // Reload data since it can have offline data now. this.showLoadingAndRefresh(true, false); } }, this.siteId, ); this.gradedObserver = CoreEvents.on(AddonModAssignProvider.GRADED_EVENT, (data) => { if (this.assign && data.assignmentId == this.assign.id && data.userId == this.currentUserId) { // Assignment graded, refresh data. this.showLoadingAndRefresh(true, false); } }, this.siteId); await this.loadContent(false, true); try { await AddonModAssign.logView(this.assign!.id, this.assign!.name); CoreCourse.checkModuleCompletion(this.courseId, this.module.completiondata); } catch { // Ignore errors. Just don't check Module completion. } if (this.canViewAllSubmissions) { // User can see all submissions, log grading view. CoreUtils.ignoreErrors(AddonModAssign.logGradingView(this.assign!.id, this.assign!.name)); } else if (this.canViewOwnSubmission) { // User can only see their own submission, log view the user submission. CoreUtils.ignoreErrors(AddonModAssign.logSubmissionView(this.assign!.id, this.assign!.name)); } } /** * Expand the description. */ expandDescription(ev?: Event): void { ev?.preventDefault(); ev?.stopPropagation(); if (this.assign && (this.description || this.assign.introattachments)) { CoreTextUtils.viewText(Translate.instant('core.description'), this.description || '', { component: this.component, componentId: this.module.id, files: this.assign.introattachments, filter: true, contextLevel: 'module', instanceId: this.module.id, courseId: this.courseId, }); } } /** * Get assignment data. * * @param refresh If it's refreshing content. * @param sync If it should try to sync. * @param showErrors If show errors to the user of hide them. * @return Promise resolved when done. */ protected async fetchContent(refresh = false, sync = false, showErrors = false): Promise<void> { // Get assignment data. try { this.assign = await AddonModAssign.getAssignment(this.courseId, this.module.id); this.dataRetrieved.emit(this.assign); this.description = this.assign.intro; if (sync) { // Try to synchronize the assign. await CoreUtils.ignoreErrors(this.syncActivity(showErrors)); } // Check if there's any offline data for this assign. this.hasOffline = await AddonModAssignOffline.hasAssignOfflineData(this.assign.id); // Get assignment submissions. const submissions = await AddonModAssign.getSubmissions(this.assign.id, { cmId: this.module.id }); const time = CoreTimeUtils.timestamp(); this.canViewAllSubmissions = submissions.canviewsubmissions; if (submissions.canviewsubmissions) { // Calculate the messages to display about time remaining and late submissions. if (this.assign.duedate > 0) { if (this.assign.duedate - time <= 0) { this.timeRemaining = Translate.instant('addon.mod_assign.assignmentisdue'); } else { this.timeRemaining = CoreTimeUtils.formatDuration(this.assign.duedate - time, 3); if (this.assign.cutoffdate) { if (this.assign.cutoffdate > time) { this.lateSubmissions = Translate.instant( 'addon.mod_assign.latesubmissionsaccepted', { $a: CoreTimeUtils.userDate(this.assign.cutoffdate * 1000) }, ); } else { this.lateSubmissions = Translate.instant('addon.mod_assign.nomoresubmissionsaccepted'); } } else { this.lateSubmissions = ''; } } } else { this.timeRemaining = ''; this.lateSubmissions = ''; } // Check if groupmode is enabled to avoid showing wrong numbers. this.groupInfo = await CoreGroups.getActivityGroupInfo(this.assign.cmid, false); this.showNumbers = (this.groupInfo.groups && this.groupInfo.groups.length == 0) || this.currentSite!.isVersionGreaterEqualThan('3.5'); await this.setGroup(CoreGroups.validateGroupId(this.group, this.groupInfo)); return; } try { // Check if the user can view their own submission. await AddonModAssign.getSubmissionStatus(this.assign.id, { cmId: this.module.id }); this.canViewOwnSubmission = true; } catch (error) { this.canViewOwnSubmission = false; if (error.errorcode !== 'nopermission') { throw error; } } } finally { this.fillContextMenu(refresh); } } /** * Set group to see the summary. * * @param groupId Group ID. * @return Resolved when done. */ async setGroup(groupId = 0): Promise<void> { this.group = groupId; const submissionStatus = await AddonModAssign.getSubmissionStatus(this.assign!.id, { groupId: this.group, cmId: this.module.id, }); this.summary = submissionStatus.gradingsummary; if (!this.summary) { this.needsGradingAvailable = false; return; } if (this.summary?.warnofungroupedusers === true) { this.summary.warnofungroupedusers = 'ungroupedusers'; } else { switch (this.summary?.warnofungroupedusers) { case AddonModAssignProvider.WARN_GROUPS_REQUIRED: this.summary.warnofungroupedusers = 'ungroupedusers'; break; case AddonModAssignProvider.WARN_GROUPS_OPTIONAL: this.summary.warnofungroupedusers = 'ungroupedusersoptional'; break; default: this.summary.warnofungroupedusers = ''; break; } } this.needsGradingAvailable = (submissionStatus.gradingsummary?.submissionsneedgradingcount || 0) > 0 && this.currentSite!.isVersionGreaterEqualThan('3.2'); } /** * Go to view a list of submissions. * * @param status Status to see. * @param hasSubmissions If the status has any submission. */ goToSubmissionList(status?: string, hasSubmissions = false): void { if (typeof status != 'undefined' && !hasSubmissions && this.showNumbers) { return; } const params: Params = { groupId: this.group || 0, moduleName: this.moduleName, }; if (typeof status != 'undefined') { params.status = status; } CoreNavigator.navigateToSitePath( AddonModAssignModuleHandlerService.PAGE_NAME + `/${this.courseId}/${this.module.id}/submission`, { params, }, ); } /** * Checks if sync has succeed from result sync data. * * @param result Data returned by the sync function. * @return If succeed or not. */ protected hasSyncSucceed(result: AddonModAssignSyncResult): boolean { if (result.updated) { this.submissionComponent?.invalidateAndRefresh(false); } return result.updated; } /** * Perform the invalidate content function. * * @return Resolved when done. */ protected async invalidateContent(): Promise<void> { const promises: Promise<void>[] = []; promises.push(AddonModAssign.invalidateAssignmentData(this.courseId)); if (this.assign) { promises.push(AddonModAssign.invalidateAllSubmissionData(this.assign.id)); if (this.canViewAllSubmissions) { promises.push(AddonModAssign.invalidateSubmissionStatusData(this.assign.id, undefined, this.group)); } } await Promise.all(promises).finally(() => { this.submissionComponent?.invalidateAndRefresh(true); }); } /** * User entered the page that contains the component. */ ionViewDidEnter(): void { super.ionViewDidEnter(); this.submissionComponent?.ionViewDidEnter(); } /** * User left the page that contains the component. */ ionViewDidLeave(): void { super.ionViewDidLeave(); this.submissionComponent?.ionViewDidLeave(); } /** * Compares sync event data with current data to check if refresh content is needed. * * @param syncEventData Data receiven on sync observer. * @return True if refresh is needed, false otherwise. */ protected isRefreshSyncNeeded(syncEventData: AddonModAssignAutoSyncData): boolean { if (this.assign && syncEventData.assignId == this.assign.id) { if (syncEventData.warnings && syncEventData.warnings.length) { // Show warnings. CoreDomUtils.showErrorModal(syncEventData.warnings[0]); } return true; } return false; } /** * Performs the sync of the activity. * * @return Promise resolved when done. */ protected sync(): Promise<AddonModAssignSyncResult> { return AddonModAssignSync.syncAssign(this.assign!.id); } /** * Component being destroyed. */ ngOnDestroy(): void { super.ngOnDestroy(); this.savedObserver?.off(); this.submittedObserver?.off(); this.gradedObserver?.off(); } }
the_stack
import { NGAExtensions } from './ngaExtensions'; import { GeoPackage } from '../geoPackage'; import { RTreeIndex } from './rtree/rtreeIndex'; import { RelatedTablesExtension } from './relatedTables'; import { TableInfo } from '../db/table/tableInfo'; import { CoreSQLUtils } from '../db/coreSQLUtils'; import { UserCustomTableReader } from '../user/custom/userCustomTableReader'; import { AlterTable } from '../db/alterTable'; import { TableMapping } from '../db/tableMapping'; import { ExtendedRelationDao } from './relatedTables/extendedRelationDao'; import { SchemaExtension } from './schema'; import { DataColumnsDao } from '../dataColumns/dataColumnsDao'; import { TableCreator } from '../db/tableCreator'; import { ConstraintParser } from '../db/table/constraintParser'; import { MetadataExtension } from './metadata'; import { MetadataReferenceDao } from '../metadata/reference/metadataReferenceDao'; import { CrsWktExtension } from './crsWkt'; export class GeoPackageExtensions { /** * Delete all table extensions for the table within the GeoPackage * * @param geoPackage GeoPackage * @param table table name */ static deleteTableExtensions(geoPackage: GeoPackage, table: string) { // Handle deleting any extensions with extra tables here NGAExtensions.deleteTableExtensions(geoPackage, table); GeoPackageExtensions.deleteRTreeSpatialIndex(geoPackage, table); GeoPackageExtensions.deleteRelatedTables(geoPackage, table); GeoPackageExtensions.deleteSchema(geoPackage, table); GeoPackageExtensions.deleteMetadata(geoPackage, table); GeoPackageExtensions.deleteExtensionForTable(geoPackage, table); } /** * Delete all extensions * @param geoPackage GeoPackage */ static deleteExtensions(geoPackage: GeoPackage) { // Handle deleting any extensions with extra tables here NGAExtensions.deleteExtensions(geoPackage); this.deleteRTreeSpatialIndexExtension(geoPackage); this.deleteRelatedTablesExtension(geoPackage); this.deleteSchemaExtension(geoPackage); this.deleteMetadataExtension(geoPackage); this.deleteCrsWktExtension(geoPackage); this.delete(geoPackage); } /** * Copy all table extensions for the table within the GeoPackage * * @param geoPackage GeoPackage * @param table table name * @param newTable new table name */ static copyTableExtensions(geoPackage: GeoPackage, table: string, newTable: string) { try { GeoPackageExtensions.copyRTreeSpatialIndex(geoPackage, table, newTable); GeoPackageExtensions.copyRelatedTables(geoPackage, table, newTable); GeoPackageExtensions.copySchema(geoPackage, table, newTable); GeoPackageExtensions.copyMetadata(geoPackage, table, newTable); // Handle copying any extensions with extra tables here NGAExtensions.copyTableExtensions(geoPackage, table, newTable); } catch (e) { console.warn( 'Failed to copy extensions for table: ' + newTable + ', copied from table: ' + table, e); } } /** * Delete the extensions for the table * @param geoPackage * @param table */ static deleteExtensionForTable(geoPackage: GeoPackage, table: string) { let extensionsDao = geoPackage.extensionDao; try { if (extensionsDao.isTableExists()) { extensionsDao.deleteByExtension(table); } } catch (SQLe) { throw new Error('Failed to delete Table extensions. GeoPackage: ' + geoPackage.name + ', Table: ' + table); } } /** * Delete the extensions * @param geoPackage */ static delete(geoPackage: GeoPackage) { let extensionsDao = geoPackage.extensionDao; try { if (extensionsDao.isTableExists()) { geoPackage.dropTable(extensionsDao.gpkgTableName); } } catch (SQLe) { throw new Error('Failed to delete all extensions. GeoPackage: ' + geoPackage.name); } } /** * Delete the RTree Spatial extension for the table * @param geoPackage GeoPackage * @param table table name */ static deleteRTreeSpatialIndex(geoPackage: GeoPackage, table: string) { let rTreeIndexExtension = GeoPackageExtensions.getRTreeIndexExtension(geoPackage); if (rTreeIndexExtension.has(table)) { rTreeIndexExtension.deleteTable(table); } } /** * Delete the RTree Spatial extension * @param geoPackage GeoPackage */ static deleteRTreeSpatialIndexExtension(geoPackage: GeoPackage) { let rTreeIndexExtension = GeoPackageExtensions.getRTreeIndexExtension(geoPackage); if (rTreeIndexExtension.has()) { rTreeIndexExtension.deleteAll(); } } /** * Copy the RTree Spatial extension for the table * @param geoPackage GeoPackage * @param table table name * @param newTable new table name */ static copyRTreeSpatialIndex(geoPackage: GeoPackage, table: string, newTable: string) { try { let rTreeIndexExtension = GeoPackageExtensions.getRTreeIndexExtension(geoPackage); if (rTreeIndexExtension.has(table)) { let geometryColumnsDao = geoPackage.geometryColumnsDao; let geometryColumns = geometryColumnsDao.queryForTableName(newTable); if (geometryColumns !== null && geometryColumns !== undefined) { let tableInfo = TableInfo.info(geoPackage.connection, newTable); if (tableInfo !== null && tableInfo !== undefined) { let pk = tableInfo.getPrimaryKey().getName(); rTreeIndexExtension.createWithParameters(newTable, geometryColumns.column_name, pk); } } } } catch (e) { console.warn( 'Failed to create RTree for table: ' + newTable + ', copied from table: ' + table, e); } } /** * Get a RTree Index Extension used only for deletions * @param geoPackage GeoPackage * @return RTree index extension */ static getRTreeIndexExtension(geoPackage: GeoPackage): RTreeIndex { return new RTreeIndex(geoPackage, null); } /** * Delete the Related Tables extensions for the table * @param geoPackage GeoPackage * @param table table name */ static deleteRelatedTables(geoPackage: GeoPackage, table: string) { let relatedTablesExtension = GeoPackageExtensions.getRelatedTableExtension(geoPackage); if (relatedTablesExtension.has()) { relatedTablesExtension.removeRelationships(table); } } /** * Delete the Related Tables extension * @param geoPackage GeoPackage */ static deleteRelatedTablesExtension(geoPackage: GeoPackage) { let relatedTablesExtension = GeoPackageExtensions.getRelatedTableExtension(geoPackage); if (relatedTablesExtension.has()) { relatedTablesExtension.removeExtension(); } } /** * Copy the Related Tables extensions for the table * @param geoPackage GeoPackage * @param table table name * @param newTable new table name */ static copyRelatedTables(geoPackage: GeoPackage, table: string, newTable: string) { try { let relatedTablesExtension = GeoPackageExtensions.getRelatedTableExtension(geoPackage); if (relatedTablesExtension.has()) { let extendedRelationsDao = relatedTablesExtension.extendedRelationDao; let extensionsDao = geoPackage.extensionDao; let extendedRelations = extendedRelationsDao.getBaseTableRelations(table); extendedRelations.forEach(extendedRelation => { let mappingTableName = extendedRelation.mapping_table_name; let extensions = extensionsDao.queryByExtensionAndTableName(RelatedTablesExtension.EXTENSION_NAME, mappingTableName); if (extensions.length > 0) { let newMappingTableName = CoreSQLUtils.createName(geoPackage.connection, mappingTableName, table, newTable); let userTable = new UserCustomTableReader(mappingTableName).readTable(geoPackage.connection); AlterTable.copyTable(geoPackage.connection, userTable, newMappingTableName); let extension = extensions[0]; extension.setTableName(newMappingTableName); extensionsDao.create(extension); let extendedRelationTableMapping = TableMapping.fromTableInfo(TableInfo.info(geoPackage.connection, ExtendedRelationDao.TABLE_NAME)); extendedRelationTableMapping.removeColumn(ExtendedRelationDao.ID); let baseTableNameColumn = extendedRelationTableMapping.getColumn(ExtendedRelationDao.BASE_TABLE_NAME); baseTableNameColumn.constantValue = newTable; baseTableNameColumn.whereValue = table; let mappingTableNameColumn = extendedRelationTableMapping.getColumn(ExtendedRelationDao.MAPPING_TABLE_NAME); mappingTableNameColumn.constantValue = newMappingTableName; mappingTableNameColumn.whereValue = mappingTableName; CoreSQLUtils.transferTableContentForTableMapping(geoPackage.connection, extendedRelationTableMapping); } }); } } catch (e) { console.warn('Failed to create Related Tables for table: ' + newTable + ', copied from table: ' + table, e); } } /** * Get a Related Table Extension used only for deletions * @param geoPackage GeoPackage * @return Related Table Extension */ static getRelatedTableExtension(geoPackage: GeoPackage): RelatedTablesExtension { return new RelatedTablesExtension(geoPackage); } /** * Delete the Schema extensions for the table * @param geoPackage GeoPackage * @param table table name */ static deleteSchema(geoPackage: GeoPackage, table: string) { let dataColumnsDao = geoPackage.dataColumnsDao; try { if (dataColumnsDao.isTableExists()) { dataColumnsDao.deleteByTableName(table); } } catch (e) { throw new Error('Failed to delete Schema extension. GeoPackage: ' + geoPackage.name + ', Table: ' + table); } } /** * Delete the Schema extension * @param geoPackage GeoPackage */ static deleteSchemaExtension(geoPackage: GeoPackage) { let schemaExtension = new SchemaExtension(geoPackage); if (schemaExtension.has()) { schemaExtension.removeExtension(); } } /** * Copy the Schema extensions for the table * @param geoPackage GeoPackage * @param table table name * @param newTable new table name */ static copySchema(geoPackage: GeoPackage, table: string, newTable: string) { try { if (geoPackage.isTable(DataColumnsDao.TABLE_NAME)) { let dataColumnsTable = new UserCustomTableReader(DataColumnsDao.TABLE_NAME).readUserCustomTable(geoPackage); let nameColumn = dataColumnsTable.getColumnWithColumnName(DataColumnsDao.COLUMN_NAME); if (nameColumn.hasConstraints()) { nameColumn.clearConstraints(); if (dataColumnsTable.hasConstraints()) { dataColumnsTable.clearConstraints(); let constraintSql = TableCreator.tableCreationScripts.data_columns[0]; let constraints = ConstraintParser.getConstraints(constraintSql); dataColumnsTable.addConstraints(constraints.getTableConstraints()); } AlterTable.alterColumnForTable(geoPackage.connection, dataColumnsTable, nameColumn); } CoreSQLUtils.transferTableContent(geoPackage.connection, DataColumnsDao.TABLE_NAME, DataColumnsDao.COLUMN_TABLE_NAME, newTable, table); } } catch (e) { console.warn( 'Failed to create Schema for table: ' + newTable + ', copied from table: ' + table, e); } } /** * Delete the Metadata extensions for the table * @param geoPackage GeoPackage * @param table table name */ static deleteMetadata(geoPackage: GeoPackage, table: string) { let metadataReferenceDao = geoPackage.metadataReferenceDao; try { if (metadataReferenceDao.isTableExists()) { metadataReferenceDao.deleteByTableName(table); } } catch (SQLe) { throw new Error('Failed to delete Metadata extension. GeoPackage: ' + geoPackage.name + ', Table: ' + table); } } /** * Delete the Metadata extension * @param geoPackage GeoPackage */ static deleteMetadataExtension(geoPackage: GeoPackage) { let metadataExtension = new MetadataExtension(geoPackage); if (metadataExtension.has()) { metadataExtension.removeExtension(); } } /** * Copy the Metadata extensions for the table * @param geoPackage GeoPackage * @param table table name * @param newTable new table name */ static copyMetadata(geoPackage: GeoPackage, table: string, newTable: string) { try { if (geoPackage.isTable(MetadataReferenceDao.TABLE_NAME)) { CoreSQLUtils.transferTableContent(geoPackage.connection, MetadataReferenceDao.TABLE_NAME, MetadataReferenceDao.COLUMN_TABLE_NAME, newTable, table); } } catch (e) { console.warn( 'Failed to create Metadata for table: ' + newTable + ', copied from table: ' + table, e); } } /** * Delete the WKT for Coordinate Reference Systems extension * @param geoPackage GeoPackage */ static deleteCrsWktExtension(geoPackage: GeoPackage) { let crsWktExtension = new CrsWktExtension(geoPackage); if (crsWktExtension.has()) { crsWktExtension.removeExtension(); } } }
the_stack
'use strict'; import { existsSync } from 'graceful-fs'; import * as recursive from 'recursive-readdir'; import * as vscode from 'vscode'; import { QuickPickItem, QuickPickOptions, window } from 'vscode'; import { insertBookmarkExternal, insertBookmarkInternal } from '../controllers/bookmark-controller'; import { getYmlTitle, hasValidWorkSpaceRootPath, ignoreFiles, insertContentToEditor, isMarkdownFileCheck, isValidEditor, isValidFileCheck, noActiveEditorMessage, postWarning, setCursorPosition, unsupportedFileMessage } from '../helper/common'; import { sendTelemetryData } from '../helper/telemetry'; import { externalLinkBuilder, internalLinkBuilder, videoLinkBuilder } from '../helper/utility'; import { linkToDocsPageByUrl } from './links/linkToDocsPageByUrl'; import { basename, extname } from 'path'; const yaml = require('js-yaml'); const telemetryCommandMedia: string = 'insertMedia'; const telemetryCommandLink: string = 'insertLink'; let commandOption: string; export function insertLinksAndMediaCommands() { const commands = [ { command: insertVideo.name, callback: insertVideo }, { command: insertURL.name, callback: insertURL }, { command: insertLink.name, callback: insertLink }, { command: selectLinkType.name, callback: selectLinkType }, { command: selectLinkTypeToolbar.name, callback: selectLinkTypeToolbar }, { command: selectMediaType.name, callback: selectMediaType } ]; return commands; } export const imageExtensions = ['.jpeg', '.jpg', '.png', '.gif', '.bmp']; export const markdownAndYmlExtensionFilter = ['.md', '.yml']; export const h1TextRegex = /\n {0,3}(#{1,6})(.*)/; export const yamlTextRegex = /^-{3}\s*\r?\n([\s\S]*?)-{3}\s*\r?\n([\s\S]*)/; export enum MediaType { Link, ImageOrVideo, GrayBorderImage } export async function insertVideo() { commandOption = 'video'; const editor = vscode.window.activeTextEditor; if (!editor) { noActiveEditorMessage(); return; } const validateInput = (urlInput: string) => { const allowedHosts = [ 'https://channel9.msdn.com', 'https://www.youtube.com/embed', 'https://www.microsoft.com/en-us/videoplayer/embed' ]; const urlLowerCase = urlInput.toLowerCase(); return allowedHosts.includes(urlLowerCase) && urlLowerCase.split('?')[0].endsWith('player') ? '' : 'https://channel9.msdn.com, https://www.youtube.com/embed or https://www.microsoft.com/en-us/videoplayer/embed are required prefixes for video URLs. Link will not be added if prefix is not present.'; }; const val = await vscode.window.showInputBox({ placeHolder: 'Enter URL; Begin typing to see the allowed video URL prefixes.', validateInput }); // If the user adds a link that doesn't include the http(s) protocol, show a warning and don't add the link. if (val === undefined) { postWarning( 'Incorrect link syntax. For YouTube videos, use the embed syntax, https://www.youtube.com/embed/<videoID>. For Channel9videos, use the player syntax, https://channel9.msdn.com/. For Red Tiger, use, https://www.microsoft.com/en-us/embed/<videoID>/player' ); return; } const contentToInsert = videoLinkBuilder(val); await insertContentToEditor(editor, contentToInsert); sendTelemetryData(telemetryCommandMedia, commandOption); } /** * Creates an external URL with the current selection. */ export async function insertURL() { commandOption = 'external'; const editor = vscode.window.activeTextEditor; if (!editor) { noActiveEditorMessage(); return; } const selection = editor.selection; const selectedText = editor.document.getText(selection); const options: vscode.InputBoxOptions = { placeHolder: 'Enter URL', validateInput: urlInput => urlInput.startsWith('http://') || urlInput.startsWith('https://') ? '' : 'http:// or https:// is required for URLs. Link will not be added if prefix is not present.' }; const linkTextOptions: vscode.InputBoxOptions = { placeHolder: 'Enter link text. If no text is entered, URL will be used.' }; const val = await vscode.window.showInputBox(options); // If the user adds a link that doesn't include the http(s) protocol, show a warning and don't add the link. if (!val) { postWarning('Incorrect link syntax. Abandoning command.'); return; } let contentToInsert = ''; if (!/^http(s)?:\/\/docs\.microsoft\.com\//.test(val)) { // if user selected text, don't prompt for alt text contentToInsert = await buildLinkForWebURL(selectedText, val, selection, linkTextOptions); } else { const choice = await pickConversionChoice(); if (choice === 'convert') { await linkToDocsPageByUrl(val); return; } else if (choice === 'insert without converting') { const docsRegexLang = new RegExp(/\/[A-Za-z]{2}-[A-Za-z]{2}\//); const urlWithoutLocal = val.replace(docsRegexLang, '/'); contentToInsert = await buildLinkForWebURL( selectedText, urlWithoutLocal, selection, linkTextOptions ); } else { return; } } insertContentToEditor(editor, contentToInsert, true); setCursorPosition( editor, selection.start.line, selection.start.character + contentToInsert.length ); sendTelemetryData(telemetryCommandLink, commandOption); } async function buildLinkForWebURL( selectedText: string, val: string, selection: vscode.Selection, linkTextOptions: vscode.InputBoxOptions ) { let contentToInsert; if (selectedText) { contentToInsert = externalLinkBuilder(val, selectedText); } // if no content is selected, prompt for alt text // no alt text: use link if (selection.isEmpty) { const altText = await window.showInputBox(linkTextOptions); if (selection.isEmpty && !altText) { contentToInsert = externalLinkBuilder(val); } if (altText) { contentToInsert = externalLinkBuilder(val, altText); } } return contentToInsert; } export async function pickConversionChoice() { const opts: QuickPickOptions = { placeHolder: 'Fully qualified links to Docs pages will be broken in isolated environments. Convert to a relative link?' }; const items: QuickPickItem[] = []; items.push({ description: '', label: 'Convert' }); items.push({ description: '', label: 'Insert without converting' }); items.push({ description: '', label: 'Cancel' }); const selection: QuickPickItem = await window.showQuickPick(items, opts); if (!selection) { return; } const selectionWithoutIcon = selection.label.toLowerCase(); switch (selectionWithoutIcon) { case 'convert': commandOption = 'convert'; return 'convert'; case 'insert without converting': commandOption = 'insert without converting'; return 'insert without converting'; case 'cancel': return ''; } } /** * Inserts a link */ export function insertLink() { const editor = vscode.window.activeTextEditor; if (!editor) { noActiveEditorMessage(); return; } const languageId = editor.document.languageId; const isMarkdown = languageId === 'markdown'; const isYaml = languageId === 'yaml'; if (!isMarkdown && !isYaml) { unsupportedFileMessage(languageId); return; } Insert(MediaType.Link, { languageId }); } /** * Triggers the insert function and passes in the true value to signify it is an art insert. */ export function insertImage() { Insert(MediaType.ImageOrVideo); } export function getFilesShowQuickPick(mediaType: MediaType, altText: string, options?: any) { const path = require('path'); const os = require('os'); const fs = require('fs'); const editor = vscode.window.activeTextEditor; if (!editor) { noActiveEditorMessage(); return; } const selection = editor.selection; let folderPath: string = ''; let selectedText = editor.document.getText(selection); const activeFileDir = path.dirname(editor.document.fileName); if (vscode.workspace.workspaceFolders) { folderPath = vscode.workspace.workspaceFolders[0].uri.fsPath; } // recursively get all the files from the root folder recursive(folderPath, ignoreFiles, (err: any, files: any) => { if (err) { vscode.window.showErrorMessage(err); throw err; } const items: vscode.QuickPickItem[] = []; files.sort(); const isArt = mediaType !== MediaType.Link; if (isArt) { files .filter((file: any) => imageExtensions.indexOf(path.extname(file.toLowerCase())) !== -1) .forEach((file: any) => { items.push({ label: path.basename(file), description: path.dirname(file) }); }); } else { files .filter( (file: any) => markdownAndYmlExtensionFilter.indexOf(path.extname(file.toLowerCase())) !== -1 ) .forEach((file: any) => { items.push({ label: path.basename(file), description: path.dirname(file) }); }); } // show the quick pick menu const selectionPick = vscode.window.showQuickPick(items); selectionPick.then(qpSelection => { if (!qpSelection) { return; } else { let result: string = ''; const altTextFileName = qpSelection.label; // Gets the H1 content as default name if unselected text. Will filter undefinition H1, non-MD file. if (!isArt && selectedText === '') { // gets the content for chosen file with utf-8 format const fullPath = path.join(qpSelection.description, qpSelection.label); let content = fs.readFileSync(fullPath, 'utf8'); // Separation yaml. const yamlMatch = content.match(yamlTextRegex); if (yamlMatch != null) { content = yamlMatch[2]; } content = '\n' + content; const linkExtension = extname(fullPath); if (linkExtension === '.md') { const match = content.match(h1TextRegex); if (match != null) { selectedText = match[2].trim(); } } if (linkExtension === '.yml') { const title = getYmlTitle(fullPath); if (title) { selectedText = title; } else { selectedText = basename(fullPath, '.yml'); } } } const languageId = options ? options.languageId : undefined; // Construct and write out links if (isArt && altText) { if (altText.length > 250) { vscode.window.showWarningMessage('Alt text exceeds 250 characters!'); } else { result = internalLinkBuilder( isArt, path.relative( activeFileDir, path.join(qpSelection.description, qpSelection.label).split('\\').join('\\\\') ), altText, languageId ); } } else if (isArt && altText === '') { result = internalLinkBuilder( isArt, path.relative( activeFileDir, path.join(qpSelection.description, qpSelection.label).split('\\').join('\\\\') ), altTextFileName, languageId ); } else if (!isArt) { result = internalLinkBuilder( isArt, path.relative( activeFileDir, path.join(qpSelection.description, qpSelection.label).split('\\').join('\\\\') ), selectedText, languageId ); } if (os.type() === 'Darwin') { if (isArt) { result = internalLinkBuilder( isArt, path.relative( activeFileDir, path.join(qpSelection.description, qpSelection.label).split('//').join('//') ), altText, languageId ); } else { result = internalLinkBuilder( isArt, path.relative( activeFileDir, path.join(qpSelection.description, qpSelection.label).split('//').join('//') ), selectedText, languageId ); } } if (!!result) { // Insert content into topic insertContentToEditor(editor, result, true); if (!isArt) { setCursorPosition( editor, selection.start.line, selection.start.character + result.length ); } } } }); }); } /** * Inserts various media types. * @param {MediaType} mediaType - the media type to insert. * @param {IOptions} [options] - optionally specifies the language identifier of the target file. */ export async function Insert(mediaType: MediaType, options?: any) { let actionType: string = Insert.name; const editor = vscode.window.activeTextEditor; if (!editor) { noActiveEditorMessage(); return; } else { const selectedText = editor.document.getText(editor.selection); // Determines the name to set in the ValidEditor check switch (mediaType) { case MediaType.ImageOrVideo: actionType = 'Art'; commandOption = 'art'; sendTelemetryData(telemetryCommandMedia, commandOption); break; case MediaType.Link: actionType = 'Link'; commandOption = 'internal'; sendTelemetryData(telemetryCommandLink, commandOption); break; } // Checks for valid environment if (!isValidEditor(editor, false, actionType)) { return; } // We have some cross-over functionality in both YAML and Markdown if (!isValidFileCheck(editor, ['markdown', 'yaml'])) { return; } if (!hasValidWorkSpaceRootPath(telemetryCommandLink)) { return; } // The active file should be used as the origin for relative links. // The path is split so the file type is not included when resolving the path. const activeFileName = editor.document.fileName; const pathDelimited = editor.document.fileName.split('.'); const activeFilePath = pathDelimited[0]; // Check to see if the active file has been saved. If it has not been saved, warn the user. // The user will still be allowed to add a link but it the relative path will not be resolved. if (!existsSync(activeFileName)) { vscode.window.showWarningMessage( `${activeFilePath} is not saved. Cannot accurately resolve path to create link.` ); return; } getFilesShowQuickPick(mediaType, selectedText, options); } } /** * Creates an entry point for creating an internal (link type) or external link (url type). */ export function selectLinkType() { const editor = vscode.window.activeTextEditor; if (!editor) { noActiveEditorMessage(); return; } else { if (!isValidEditor(editor, false, 'insert link')) { return; } if (!isMarkdownFileCheck(editor, false)) { return; } const linkTypes = ['Heading in this file', 'Heading in another file']; vscode.window.showQuickPick(linkTypes).then(qpSelection => { if (qpSelection === linkTypes[0]) { insertBookmarkInternal(); } else if (qpSelection === linkTypes[1]) { insertBookmarkExternal(); } }); } } /** * Creates an entry point for creating an internal (link type) or external link (url type). */ export function selectLinkTypeToolbar(toolbar?: boolean) { const editor = vscode.window.activeTextEditor; if (!editor) { noActiveEditorMessage(); return; } if (!isValidEditor(editor, false, 'insert link')) { return; } if (!isMarkdownFileCheck(editor, false)) { return; } const linkTypes = ['External', 'Internal', 'Bookmark in this file', 'Bookmark in another file']; vscode.window.showQuickPick(linkTypes).then(qpSelection => { if (qpSelection === linkTypes[0]) { insertURL(); } else if (qpSelection === linkTypes[1]) { Insert(MediaType.Link); } else if (qpSelection === linkTypes[2]) { insertBookmarkInternal(); } else if (qpSelection === linkTypes[3]) { insertBookmarkExternal(); } }); } /** * Creates an entry point for creating an internal (link type) or external link (url type). */ export function selectMediaType() { const editor = vscode.window.activeTextEditor; if (!editor) { noActiveEditorMessage(); return; } else { if (!isValidEditor(editor, false, 'insert media')) { return; } if (!isMarkdownFileCheck(editor, false)) { return; } const mediaTypes = ['Image', 'Video']; vscode.window.showQuickPick(mediaTypes).then(qpSelection => { if (qpSelection === mediaTypes[0]) { Insert(MediaType.ImageOrVideo); } else if (qpSelection === mediaTypes[1]) { insertVideo(); } }); } }
the_stack
jest.unmock('../../src/TestResults/match-node'); jest.unmock('../../src/TestResults/match-by-context'); jest.unmock('../test-helper'); import * as helper from '../test-helper'; import * as match from '../../src/TestResults/match-by-context'; import { TestReconciliationStateType, TestResult } from '../../src/TestResults'; import { TestAssertionStatus, ParsedNode } from 'jest-editor-support'; import { toTestResultRecord } from '../test-helper'; const reason = (m: TestResult) => m.sourceHistory[m.sourceHistory.length - 1]; describe('buildAssertionContainer', () => { it('can build and sort assertions without ancestors', () => { const a1 = helper.makeAssertion('test-1', 'KnownSuccess', [], [1, 0]); const a2 = helper.makeAssertion('test-2', 'KnownSuccess', [], [2, 0]); const a3 = helper.makeAssertion('test-3', 'KnownSuccess', [], [3, 0]); const root = match.buildAssertionContainer([a1, a3, a2]); expect(root.childContainers).toHaveLength(0); expect(root.childData).toHaveLength(3); expect(root.childData.map((n) => n.zeroBasedLine)).toEqual([1, 2, 3]); }); it('can build and sort assertions with ancestors', () => { const a1 = helper.makeAssertion('test-1', 'KnownSuccess', [], [1, 0]); const a2 = helper.makeAssertion('test-2', 'KnownSuccess', ['d-1'], [2, 0]); const a3 = helper.makeAssertion('test-3', 'KnownSuccess', ['d-1', 'd-1-1'], [3, 0]); const a4 = helper.makeAssertion('test-4', 'KnownSuccess', ['d-1'], [4, 0]); const a5 = helper.makeAssertion('test-4', 'KnownFail', ['d-2'], [5, 0]); const a6 = helper.makeAssertion('test-4', 'KnownFail', ['d-2'], [8, 0]); // ensure the assertion hierarchical integrity before building the container expect( [a1, a5, a3, a2, a4, a6].every((a) => a.fullName === a.title || a.ancestorTitles.length > 0) ).toBe(true); const root = match.buildAssertionContainer([a1, a5, a3, a2, a4, a6]); expect(root.childContainers).toHaveLength(2); expect(root.childData).toHaveLength(1); expect(root.childContainers.map((n) => [n.name, n.zeroBasedLine])).toEqual([ ['d-1', 2], ['d-2', 5], ]); expect(root.childData.map((n) => [n.name, n.zeroBasedLine])).toEqual([['test-1', 1]]); // the original assertion integrity should not be changed expect( [a1, a5, a3, a2, a4, a6].every((a) => a.fullName === a.title || a.ancestorTitles.length > 0) ).toBe(true); }); it('can group assertions with the same line', () => { const a1 = helper.makeAssertion('test-1', 'KnownSuccess', [], [2, 0]); const a2 = helper.makeAssertion('test-2', 'KnownSuccess', [], [2, 0]); const a3 = helper.makeAssertion('test-3', 'KnownSuccess', [], [2, 0]); const a4 = helper.makeAssertion('test-4', 'KnownSuccess', [], [5, 0]); const root = match.buildAssertionContainer([a1, a3, a4, a2]); expect(root.childContainers).toHaveLength(0); expect(root.childData).toHaveLength(2); expect(root.childData.map((n) => n.zeroBasedLine)).toEqual([2, 5]); const groupNode = root.childData[0]; expect(groupNode.getAll().map((n) => n.data.title)).toEqual(['test-1', 'test-3', 'test-2']); }); it('can group describe blocks with the same line', () => { const a1 = helper.makeAssertion('test-1', 'KnownSuccess', ['d-1'], [2, 0]); const a2 = helper.makeAssertion('test-1', 'KnownSuccess', ['d-2'], [2, 0]); const a3 = helper.makeAssertion('test-1', 'KnownSuccess', ['d-3'], [2, 0]); const a4 = helper.makeAssertion('test-2', 'KnownSuccess', [], [5, 0]); const root = match.buildAssertionContainer([a1, a2, a3, a4]); expect(root.childContainers).toHaveLength(1); expect(root.childData).toHaveLength(1); expect(root.childData[0]).toMatchObject({ zeroBasedLine: 5, name: 'test-2' }); const describeNode = root.childContainers[0]; expect(describeNode).toMatchObject({ zeroBasedLine: 2, name: 'd-1' }); expect(describeNode.group?.map((n) => n.name)).toEqual(['d-2', 'd-3']); }); it('create a container based on assertion ancestorTitles structure', () => { const a1 = helper.makeAssertion('test-1', 'KnownSuccess', [], [1, 0]); const a2 = helper.makeAssertion('test-2', 'KnownSuccess', ['d-1'], [10, 0]); const a3 = helper.makeAssertion('test-3', 'KnownSuccess', ['d-1', 'd-2'], [15, 0]); const a4 = helper.makeAssertion('test-4', 'KnownFail', ['d-1'], [20, 0]); const root = match.buildAssertionContainer([a4, a3, a1, a2]); expect(root.childData.map((n) => (n as any).name)).toEqual(['test-1']); expect(root.childContainers).toHaveLength(1); const d1 = root.findContainer(['d-1']); expect(d1.childContainers).toHaveLength(1); expect(d1.childData.map((n) => (n as any).name)).toEqual(['test-2', 'test-4']); const d2 = d1.findContainer(['d-2']); expect(d2.childContainers).toHaveLength(0); expect(d2.childData.map((n) => (n as any).name)).toEqual(['test-3']); }); }); describe('buildSourceContainer', () => { it('can build and sort source container without ancestors', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-2', [6, 0, 7, 0]); const t3 = helper.makeItBlock('test-3', [8, 0, 10, 0]); const sourceRoot = helper.makeRoot([t2, t1, t3]); const root = match.buildSourceContainer(sourceRoot); expect(root.childContainers).toHaveLength(0); expect(root.childData.map((n) => (n as any).name)).toEqual(['test-1', 'test-2', 'test-3']); }); it('can build and sort source container with ancestors', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-2', [6, 0, 7, 0]); const t3 = helper.makeItBlock('test-3', [8, 0, 10, 0]); const d1 = helper.makeDescribeBlock('d-1', [t2]); const d2 = helper.makeDescribeBlock('d-2', [t3]); const sourceRoot = helper.makeRoot([t1, d1, d2]); const root = match.buildSourceContainer(sourceRoot); expect(root.childContainers).toHaveLength(2); expect(root.childData).toHaveLength(1); expect(root.childData.map((n) => (n as any).name)).toEqual([t1.name]); const d1Container = root.findContainer(['d-1']); expect(d1Container?.childData).toHaveLength(1); expect(d1Container?.childContainers).toHaveLength(0); const d2Container = root.findContainer(['d-2']); expect(d2Container?.childData).toHaveLength(1); expect(d2Container?.childContainers).toHaveLength(0); }); it('lines will be converted to zeroBased', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-2', [6, 0, 7, 0]); const sourceRoot = helper.makeRoot([t2, t1]); const root = match.buildSourceContainer(sourceRoot); expect(root.childContainers).toHaveLength(0); expect(root.childData.map((n) => n.zeroBasedLine)).toEqual([0, 5]); }); it('can build and sort container from describe and it blocks', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-2', [6, 0, 7, 0]); const t3 = helper.makeItBlock('test-3', [8, 0, 10, 0]); const d1 = helper.makeDescribeBlock('d-1', [t1, t2]); const sourceRoot = helper.makeRoot([t3, d1]); const root = match.buildSourceContainer(sourceRoot); expect(root.childData.map((n) => (n as any).name)).toEqual(['test-3']); expect(root.childContainers).toHaveLength(1); const container = root.childContainers[0]; expect(container.childContainers).toHaveLength(0); expect(container.childData.map((n) => (n as any).name)).toEqual(['test-1', 'test-2']); }); it('does not group itBlocks even if they have the same start line (wrongly)', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-2', [1, 0, 7, 0]); const sourceRoot = helper.makeRoot([t1, t2]); const root = match.buildSourceContainer(sourceRoot); expect(root.childData.map((n) => (n as any).name)).toEqual(['test-1', 'test-2']); expect(root.childContainers).toHaveLength(0); }); }); describe('matchTestAssertions', () => { const mockError = jest.fn(); const mockWarn = jest.fn(); beforeEach(() => { jest.resetAllMocks(); console.error = mockError; console.warn = mockWarn; }); it('tests are matched by context position regardless name and line', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-2-${num}', [6, 0, 7, 0], { nameType: 'TemplateLiteral' }); const sourceRoot = helper.makeRoot([t2, t1]); const a1 = helper.makeAssertion('test-1', 'KnownFail', [], [0, 0]); const a2 = helper.makeAssertion('test-2-100', 'KnownSuccess', [], [7, 0]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); expect(matched).toHaveLength(2); expect(matched.map((m) => m.name)).toEqual(['test-1', 'test-2-100']); expect(matched.map((m) => m.identifier.title)).toEqual(['test-1', 'test-2-100']); expect(matched.map((m) => m.identifier.ancestorTitles)).toEqual([[], []]); expect(matched.map((m) => m.status)).toEqual(['KnownFail', 'KnownSuccess']); }); it('can match tests with the same name but in different describe blocks', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-1', [6, 0, 7, 0]); const d1 = helper.makeDescribeBlock('d-1', [t2]); const sourceRoot = helper.makeRoot([t1, d1]); const a1 = helper.makeAssertion('test-1', 'KnownFail', [], [0, 0]); const a2 = helper.makeAssertion('test-1', 'KnownSuccess', ['d-1'], [5, 0]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); expect(matched.map((m) => m.name)).toEqual(['test-1', 'd-1 test-1']); expect(matched.map((m) => m.identifier.title)).toEqual(['test-1', 'test-1']); expect(matched.map((m) => m.identifier.ancestorTitles)).toEqual([[], ['d-1']]); expect(matched.map((m) => m.status)).toEqual(['KnownFail', 'KnownSuccess']); expect(matched.map((m) => m.start.line)).toEqual([0, 5]); expect(matched.map((m) => m.end.line)).toEqual([4, 6]); }); describe(`context do not align`, () => { it('when test block is missing assertion in the same container', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const sourceRoot = helper.makeRoot([t1]); const matched = match.matchTestAssertions('a file', sourceRoot, []); expect(matched.map((m) => m.name)).toEqual(['test-1']); expect(matched.map((m) => m.status)).toEqual(['Unknown']); expect(matched.map((m) => m.start.line)).toEqual([0]); expect(matched.map((m) => m.end.line)).toEqual([4]); }); it('can still resolve by fallback to simple name match', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-2', [10, 0, 15, 0]); const sourceRoot = helper.makeRoot([t1, t2]); const a1 = helper.makeAssertion('test-1', 'KnownFail', [], [0, 0]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1]); expect(matched.map((m) => [m.name, m.status])).toEqual( expect.arrayContaining([ ['test-1', 'KnownFail'], ['test-2', 'Unknown'], ]) ); }); it('will continue match the child containers', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); // under root const t2 = helper.makeItBlock('test-2', [6, 0, 7, 0]); // under d-1 const t3 = helper.makeItBlock('test-3', [8, 0, 9, 0]); // under d-1 const t4 = helper.makeItBlock('test-4', [10, 0, 12, 0]); // under d-1-1 const d11 = helper.makeDescribeBlock('d-1-1', [t4]); const d1 = helper.makeDescribeBlock('d-1', [t2, t3, d11]); const sourceRoot = helper.makeRoot([t1, d1]); // assertion missing for 'd-1': t3 const a1 = helper.makeAssertion('test-1', 'KnownSuccess', [], [6, 0]); const a2 = helper.makeAssertion('test-2', 'KnownFail', ['d-1'], [6, 0]); const a4 = helper.makeAssertion('test-4', 'KnownSuccess', ['d-1', 'd-1-1'], [9, 0]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2, a4]); const expected = [ ['test-1', 'KnownSuccess', 'match-by-context'], ['d-1 test-2', 'KnownFail', 'match-by-name'], ['d-1 test-3', 'Unknown', 'match-failed'], ['d-1 d-1-1 test-4', 'KnownSuccess', 'match-by-context'], ]; expect(matched).toHaveLength(expected.length); expect(matched.map((m) => [m.name, m.status, reason(m)])).toEqual( expect.arrayContaining(expected) ); }); it('describe block will fail if context mismatch and name lookup failed', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); // under root const t2 = helper.makeItBlock('test-2', [6, 0, 7, 0]); // under d-1 const d1 = helper.makeDescribeBlock('d-1', [t2]); const sourceRoot = helper.makeRoot([t1, d1]); // assertion missing for t3 const a1 = helper.makeAssertion('test-1', 'KnownSuccess', [], [6, 0]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1]); expect(matched.map((m) => [m.name, m.status])).toEqual([ ['test-1', 'KnownSuccess'], ['d-1 test-2', 'Unknown'], ]); }); it('empty desecribe block', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); // under root const d11 = helper.makeDescribeBlock('d-1-1', []); const d1 = helper.makeDescribeBlock('d-1', [d11]); const sourceRoot = helper.makeRoot([d1, t1]); const a1 = helper.makeAssertion('test-1', 'KnownSuccess', [], [6, 0]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1]); expect(matched).toHaveLength(1); expect(matched.map((m) => [m.name, m.status])).toEqual([['test-1', 'KnownSuccess']]); }); }); describe('1-many (jest.each) match', () => { const createTestData = ( statusList: (TestReconciliationStateType | [TestReconciliationStateType, number])[] ): [ParsedNode, TestAssertionStatus[]] => { const t1 = helper.makeItBlock('', [12, 1, 20, 1], { nameType: 'TemplateLiteral', lastProperty: 'each', }); const sourceRoot = helper.makeRoot([t1]); // this match jest.each with 2 assertions const assertions = statusList.map((s, idx) => { let state: TestReconciliationStateType; let override: Partial<TestAssertionStatus>; if (typeof s === 'string') { state = s; override = {}; } else { state = s[0]; override = { line: s[1] }; } return helper.makeAssertion(`test-${idx}`, state, [], [11, 0], override); }); return [sourceRoot, assertions]; }; it('all assertions will be returned', () => { const [root, assertions] = createTestData([ 'KnownSuccess', ['KnownFail', 13], 'KnownSuccess', ]); const matched = match.matchTestAssertions('a file', root, assertions); expect(matched).toHaveLength(3); expect(matched.map((m) => m.status)).toEqual(['KnownSuccess', 'KnownFail', 'KnownSuccess']); expect(matched[1].status).toEqual('KnownFail'); expect(matched[1].start).toEqual({ line: 11, column: 0 }); expect(matched[1].end).toEqual({ line: 19, column: 0 }); expect(matched[1].lineNumberOfError).toEqual(12); }); describe('describe.each use case', () => { describe('1 test in describe.each', () => { it.each` t1Info | d1Info | a1Info | a2Info ${['test-1']} | ${['d-1.each $var']} | ${['test-1', ['d-1.each 1']]} | ${['test-1', ['d-1.each 2']]} ${['test-1']} | ${['d-1.each']} | ${['test-1', ['d-1.each']]} | ${['test-1', ['d-1.each']]} ${['test-${k}', { hasDynamicName: true }]} | ${['d-1.each']} | ${['test-1', ['d-1.each']]} | ${['test-1', ['d-1.each']]} ${['test-${k}', { hasDynamicName: true }]} | ${['d-1.each $var']} | ${['test-1', ['d-1.each 1']]} | ${['test-1', ['d-1.each 2']]} `('$t1Info in $d1Info', ({ t1Info, d1Info, a1Info, a2Info }) => { let [tName, override] = t1Info; const t1 = helper.makeItBlock(tName, [1, 0, 5, 0], { ...(override ?? {}) }); [tName, override] = d1Info; const d1 = helper.makeDescribeBlock(tName, [t1], { lastProperty: 'each', ...(override ?? {}), }); let [aName, ancestor] = a1Info; const a1 = helper.makeAssertion(aName, 'KnownSuccess', ancestor, [1, 0]); [aName, ancestor] = a2Info; const a2 = helper.makeAssertion(aName, 'KnownFail', ancestor, [1, 0]); const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a1.fullName, t1.start.line - 1, a1.status, ['match-by-context']], [a2.fullName, t1.start.line - 1, a2.status, ['match-by-context']], ]); // expect(matched.map((m) => extractResult(m))).toEqual( // expect.arrayContaining([ // [a1.fullName, t1.start.line - 1, a1.status, ['match-by-context']], // [a2.fullName, t1.start.line - 1, a2.status, ['match-by-context']], // ]) // ); }); }); describe('nested each tests in describe.each', () => { const t1 = helper.makeItBlock('test-1.each $count', [1, 0, 5, 0], { lastProperty: 'each' }); const d1 = helper.makeDescribeBlock('d-1.each $var', [t1], { lastProperty: 'each' }); const a1 = helper.makeAssertion('test-1.each 1', 'KnownSuccess', ['d-1.each 1'], [1, 0]); const a2 = helper.makeAssertion('test-1.each 2', 'KnownFail', ['d-1.each 1'], [1, 0]); const a3 = helper.makeAssertion('test-1.each 2', 'KnownSuccess', ['d-1.each 2'], [1, 0]); it('single nested each tests in describe.each', () => { const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2, a3]); expect(matched).toHaveLength(3); expect(matched.map((m) => [m.name, m.start.line, m.status, reason(m)])).toEqual( expect.arrayContaining([ [a1.fullName, t1.start.line - 1, a1.status, 'match-by-context'], [a2.fullName, t1.start.line - 1, a2.status, 'match-by-context'], [a3.fullName, t1.start.line - 1, a3.status, 'match-by-context'], ]) ); }); it('multiple tests in the describe.each block', () => { const t2 = helper.makeItBlock('test-2', [10, 0, 5, 0]); const t3 = helper.makeItBlock('test-3-${k}', [20, 0, 5, 0], { nameType: 'TemplateLiteral', }); const dd1 = helper.makeDescribeBlock('d-1.each $var', [t1, t2, t3], { lastProperty: 'each', }); const a4 = helper.makeAssertion('test-2', 'KnownSuccess', ['d-1.each 1'], [11, 0]); const a5 = helper.makeAssertion('test-2', 'KnownSuccess', ['d-1.each 2'], [11, 0]); const a6 = helper.makeAssertion('test-3-a', 'KnownSuccess', ['d-1.each 1'], [33, 0]); const a7 = helper.makeAssertion('test-3-b', 'KnownFail', ['d-1.each 2'], [33, 0]); const sourceRoot = helper.makeRoot([dd1]); const matched = match.matchTestAssertions('a file', sourceRoot, [ a1, a2, a3, a4, a5, a6, a7, ]); expect(matched).toHaveLength(7); expect(matched.map((m) => [m.name, m.start.line, m.status, reason(m)])).toEqual( expect.arrayContaining([ [a1.fullName, t1.start.line - 1, a1.status, 'match-by-context'], [a2.fullName, t1.start.line - 1, a2.status, 'match-by-context'], [a3.fullName, t1.start.line - 1, a3.status, 'match-by-context'], [a4.fullName, t2.start.line - 1, a4.status, 'match-by-context'], [a5.fullName, t2.start.line - 1, a5.status, 'match-by-context'], [a6.fullName, t3.start.line - 1, a6.status, 'match-by-context'], [a7.fullName, t3.start.line - 1, a7.status, 'match-by-context'], ]) ); }); }); it('1 simple test in describe.each with the same name', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const d1 = helper.makeDescribeBlock('d-1.each', [t1], { lastProperty: 'each' }); const a1 = helper.makeAssertion('test-1', 'KnownSuccess', ['d-1.each'], [1, 0]); const a2 = helper.makeAssertion('test-1', 'KnownFail', ['d-1.each'], [1, 0]); const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); expect(matched).toHaveLength(2); expect(matched.map((m) => [m.name, m.start.line, m.status, reason(m)])).toEqual( expect.arrayContaining([ [a1.fullName, t1.start.line - 1, a1.status, 'match-by-context'], [a2.fullName, t1.start.line - 1, a2.status, 'match-by-context'], ]) ); }); it('1 dynamically named test.each in describe.each', () => { const t1 = helper.makeItBlock('test-1-${x}', [1, 0, 5, 0], { nameType: 'TemplateLiteral' }); const d1 = helper.makeDescribeBlock('d-1.each $var', [t1], { lastProperty: 'each' }); const a1 = helper.makeAssertion('`test-1-x`', 'KnownSuccess', ['d-1.each 1'], [1, 0]); const a2 = helper.makeAssertion('test-1-y', 'KnownFail', ['d-1.each 2'], [1, 0]); const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); expect(matched).toHaveLength(2); expect(matched.map((m) => [m.name, m.start.line, m.status, reason(m)])).toEqual( expect.arrayContaining([ [a1.fullName, t1.start.line - 1, a1.status, 'match-by-context'], [a2.fullName, t1.start.line - 1, a2.status, 'match-by-context'], ]) ); }); it('it.each within describe.each', () => { const t1 = helper.makeItBlock('test.each $x', [1, 0, 5, 0], { lastProperty: 'each' }); const d1 = helper.makeDescribeBlock('d-1.each $var', [t1], { lastProperty: 'each' }); const a1 = helper.makeAssertion('`test.each a`', 'KnownSuccess', ['d-1.each 1'], [1, 0]); const a2 = helper.makeAssertion('test.each b', 'KnownFail', ['d-1.each 1'], [1, 0]); const a3 = helper.makeAssertion('test.each a', 'KnownSuccess', ['d-1.each 2'], [1, 0]); const a4 = helper.makeAssertion('test.each b', 'KnownSuccess', ['d-1.each 2'], [1, 0]); const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2, a3, a4]); expect(matched).toHaveLength(4); expect(matched.map((m) => [m.name, m.start.line, m.status, reason(m)])).toEqual( expect.arrayContaining([ [a1.fullName, t1.start.line - 1, a1.status, 'match-by-context'], [a2.fullName, t1.start.line - 1, a2.status, 'match-by-context'], [a3.fullName, t1.start.line - 1, a3.status, 'match-by-context'], [a4.fullName, t1.start.line - 1, a4.status, 'match-by-context'], ]) ); }); it('deeper it.each within describe.each', () => { const t1 = helper.makeItBlock('test.each $x', [1, 0, 5, 0], { lastProperty: 'each' }); const d1 = helper.makeDescribeBlock('d-1.each $var', [t1], { lastProperty: 'each' }); const d2 = helper.makeDescribeBlock('d-2', [d1]); const t2 = helper.makeItBlock('empty test', [6, 0, 7, 0]); const a1 = helper.makeAssertion('`test.each a`', 'KnownSuccess', ['d-1.each 1'], [1, 0]); const a2 = helper.makeAssertion('test.each b', 'KnownFail', ['d-1.each 1'], [1, 0]); const a3 = helper.makeAssertion('test.each a', 'KnownSuccess', ['d-1.each 2'], [1, 0]); const a4 = helper.makeAssertion('test.each b', 'KnownSuccess', ['d-1.each 2'], [1, 0]); const sourceRoot = helper.makeRoot([d2, t2]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2, a3, a4]); // expect(matched).toHaveLength(5); expect(matched.map((m) => [m.name, m.start.line, m.status, reason(m)])).toEqual( expect.arrayContaining([ [a1.fullName, t1.start.line - 1, a1.status, 'match-by-location'], [a2.fullName, t1.start.line - 1, a2.status, 'match-by-location'], [a3.fullName, t1.start.line - 1, a3.status, 'match-by-location'], [a4.fullName, t1.start.line - 1, a4.status, 'match-by-location'], [t2.name, t2.start.line - 1, 'Unknown', 'match-failed'], ]) ); }); }); }); it('test name precedence: assertion.fullName > assertion.title > testSource.name', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-2-${num}', [6, 0, 7, 0], { nameType: 'TemplateLiteral' }); const t3 = helper.makeItBlock('test-3-no-assertion', [8, 0, 10, 0]); const d1 = helper.makeDescribeBlock('d-1', [t1, t2]); const sourceRoot = helper.makeRoot([d1, t3]); const a1 = helper.makeAssertion('test-1', 'KnownFail', ['d-1'], [0, 0]); a1.fullName = undefined; const a2 = helper.makeAssertion('test-2-100', 'KnownSuccess', ['d-1'], [7, 0]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); const expected = ['test-3-no-assertion', 'test-1', 'd-1 test-2-100']; expect(matched).toHaveLength(expected.length); expect(matched.map((m) => m.name)).toEqual(expect.arrayContaining(expected)); expect(matched.map((m) => m.status)).toEqual( expect.arrayContaining(['Unknown', 'KnownFail', 'KnownSuccess']) ); }); it('duplicate name in the same block would generate error if only we can not match by context', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-1', [6, 0, 7, 0]); const sourceRoot = helper.makeRoot([t1, t2]); const a1 = helper.makeAssertion('test-1', 'KnownSuccess', undefined, [2, 0]); const a2 = helper.makeAssertion('test-1', 'KnownFail', undefined, [7, 0]); // when we can match by context let matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); expect(matched).toHaveLength(2); expect(matched.map((m) => [m.name, m.status, m.start.line, m.sourceHistory])).toEqual([ [a1.fullName, a1.status, t1.start.line - 1, expect.arrayContaining(['match-by-context'])], [a2.fullName, a2.status, t2.start.line - 1, expect.arrayContaining(['match-by-context'])], ]); // when we can not match by context matched = match.matchTestAssertions('a file', sourceRoot, [a1]); expect(matched).toHaveLength(2); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a1.fullName, t1.start.line - 1, a1.status, ['duplicate-name', 'match-by-location']], ['test-1', t2.start.line - 1, 'Unknown', ['duplicate-name', 'match-failed']], ]); }); describe('duplicate name in the describe blocks', () => { it('would be ok as long as we can match the tests within', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-2', [6, 0, 7, 0]); const d1 = helper.makeDescribeBlock('d-1', [t1]); const d2 = helper.makeDescribeBlock('d-1', [t2]); const sourceRoot = helper.makeRoot([d1, d2]); const a1 = helper.makeAssertion('test-1', 'KnownSuccess', ['d-1'], [2, 0]); const a2 = helper.makeAssertion('test-2', 'KnownFail', ['d-1'], [7, 0]); // when the test within the describe have different name: we should be able to match just fine const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); expect(matched).toHaveLength(2); expect(matched.map((m) => [m.name, m.status, m.start.line, m.sourceHistory])).toEqual([ [a1.fullName, a1.status, t1.start.line - 1, expect.arrayContaining(['match-by-name'])], [a2.fullName, a2.status, t2.start.line - 1, expect.arrayContaining(['match-by-name'])], ]); }); it('would fail the match if test within can not be resolved deterministically', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 5, 0]); const t2 = helper.makeItBlock('test-1', [6, 0, 9, 0]); const d1 = helper.makeDescribeBlock('d-1', [t1]); const d2 = helper.makeDescribeBlock('d-1', [t2]); const sourceRoot = helper.makeRoot([d1, d2]); const a1 = helper.makeAssertion('test-1', 'KnownSuccess', ['d-1'], [22, 0]); const a2 = helper.makeAssertion('test-1', 'KnownFail', ['d-1'], [27, 0]); // when the test within the describe have different name: we should be able to match just fine const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); expect(matched).toHaveLength(2); // when test within have the same name, then it will report error expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [`d-1 ${t1.name}`, t1.start.line - 1, 'Unknown', ['duplicate-name', 'match-failed']], [`d-1 ${t2.name}`, t2.start.line - 1, 'Unknown', ['duplicate-name', 'match-failed']], ]); }); }); // test.todo will generate null for location that could confuses the context matching describe('unknown location and test result reason', () => { const t1 = helper.makeItBlock('test-${i}', [1, 0, 5, 0], { nameType: 'TemplateLiteral' }); // under d-1 const t2 = helper.makeItBlock('test.todo 1', [6, 0, 7, 0]); // under d-1 const t3 = helper.makeItBlock('test.todo 2', [9, 0, 10, 0]); // under d-1 const t4 = helper.makeItBlock('test-2', [12, 0, 20, 0]); // under d-1 const t5 = helper.makeItBlock('some weird test', [22, 0, 22, 100]); // under d-2 const d1 = helper.makeDescribeBlock('d-1', [t1, t2, t3, t4]); const d2 = helper.makeDescribeBlock('d-2', [t5]); const a1 = helper.makeAssertion('test-1', 'KnownSuccess', ['d-1'], [1, 0]); const a2 = helper.makeAssertion('test.todo 1', 'Unknown', ['d-1'], undefined, { location: null, }); const a3 = helper.makeAssertion('test.todo 2', 'Unknown', ['d-1'], undefined, { location: null, }); const a4 = helper.makeAssertion('test-2', 'KnownFail', ['d-1'], [12, 0]); const a5 = helper.makeAssertion('some weird test', 'KnownFail', ['d-2'], undefined, { location: null, }); it('nodes with unknown locations can still be merged by name', () => { const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2, a3, a4]); expect(matched).toHaveLength(4); expect(matched.map((m) => [m.name, m.status, reason(m)])).toEqual( expect.arrayContaining([ [a1.fullName, a1.status, 'match-by-context'], [a2.fullName, a2.status, 'match-by-name'], [a3.fullName, a3.status, 'match-by-name'], [a4.fullName, a4.status, 'match-by-context'], ]) ); // no merge expect(matched.every((m) => !m.multiResults)).toBeTruthy(); }); it('block with only unknown location tests can still be matched by name', () => { const sourceRoot = helper.makeRoot([d1, d2]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2, a3, a4, a5]); expect(matched).toHaveLength(5); expect(matched.map((m) => [m.name, m.status, reason(m)])).toEqual( expect.arrayContaining([ [a1.fullName, a1.status, 'match-by-context'], [a2.fullName, a2.status, 'match-by-name'], [a3.fullName, a3.status, 'match-by-name'], [a4.fullName, a4.status, 'match-by-context'], [a5.fullName, a5.status, 'match-by-name'], ]) ); }); it('if unknown location test failed to match by name, they will show up as unknown and may impacted other test matching', () => { const a3Unmatched = helper.makeAssertion( 'test.todo 2 unmatched', 'KnownSuccess', ['d-1'], undefined, { location: null, } ); const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2, a4, a3Unmatched]); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a2.fullName, t2.start.line - 1, a2.status, ['match-by-name']], [a4.fullName, t4.start.line - 1, a4.status, ['match-by-name']], [a1.fullName, t1.start.line - 1, a1.status, ['match-by-location']], [`d-1 ${t3.name}`, t3.start.line - 1, 'Unknown', ['match-failed']], ]); }); it('match result reason can pass through the hierarchy', () => { const deep2 = helper.makeDescribeBlock('layer-2', [t1]); const deep1 = helper.makeDescribeBlock('layer-1', [deep2]); const matched = match.matchTestAssertions('a file', helper.makeRoot([deep1]), []); expect(matched).toHaveLength(1); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [`layer-1 layer-2 ${t1.name}`, t1.start.line - 1, 'Unknown', ['match-failed']], ]); }); }); describe('invalid grouping: do no worse than match-by-name', () => { const t0 = helper.makeItBlock('first test', [1, 0, 6, 0]); const d0 = helper.makeDescribeBlock('desc-1', [t0]); const t1 = helper.makeItBlock('test.each $a', [7, 0, 5, 0], { lastProperty: 'each' }); const d1 = helper.makeDescribeBlock('wrapper-1', [t1]); const t2 = helper.makeItBlock('test.each again $a', [10, 0, 15, 0], { lastProperty: 'each' }); // const d2 = helper.makeDescribeBlock('wrapper-2', [t2]); const t3 = helper.makeItBlock('last test', [15, 0, 27, 0]); const tTodo = helper.makeItBlock('a todo test', [30, 0, 30, 0]); const d3 = helper.makeDescribeBlock('wrapper-3', [t3, tTodo]); describe('when all tests have the same loation: i.e. they will be grouped incorrectly', () => { const a0 = helper.makeAssertion('first test', 'KnownSuccess', undefined, [1, 0]); const a1 = helper.makeAssertion('test.each 1', 'KnownSuccess', undefined, [1, 0]); const a2 = helper.makeAssertion('test.each 2', 'KnownFail', undefined, [1, 0]); // const a3 = helper.makeAssertion('test.each again 3', 'KnownSuccess', undefined, [1, 0]); const a4 = helper.makeAssertion('last test', 'KnownSuccess', undefined, [1, 0]); const a5 = helper.makeAssertion('a todo test', 'KnownTodo', undefined, undefined, { location: null, }); it('can match by name for static test names', () => { const sourceRoot = helper.makeRoot([t0, t3, tTodo]); const matched = match.matchTestAssertions('a file', sourceRoot, [a4, a0, a5]); expect(matched).toHaveLength(3); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a0.fullName, t0.start.line - 1, a0.status, ['match-by-name']], [a4.fullName, t3.start.line - 1, a4.status, ['match-by-name']], [a5.fullName, tTodo.start.line - 1, a5.status, ['match-by-name', 'invalid-location']], ]); }); describe('can skip dynamic named tests while still matching the static named ones', () => { it('simple case: no describe', () => { const sourceRoot = helper.makeRoot([t0, t1, t3, tTodo]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2, a4, a0, a5]); expect(matched).toHaveLength(4); expect(matched.map((m) => [m.name, m.start.line, m.status, reason(m)])).toEqual( expect.arrayContaining([ [a0.fullName, t0.start.line - 1, a0.status, 'match-by-name'], [t1.name, t1.start.line - 1, 'Unknown', 'match-failed'], [a4.fullName, t3.start.line - 1, a4.status, 'match-by-name'], [a5.fullName, tTodo.start.line - 1, a5.status, 'match-by-name'], ]) ); }); it('a more complex case: with desc blocks', () => { const sourceRoot = helper.makeRoot([d0, t1, t3, tTodo]); const a0d = helper.makeAssertion('first test', 'KnownSuccess', ['desc-1'], [1, 0]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2, a4, a0d, a5]); expect(matched).toHaveLength(4); expect(matched.map((m) => [m.name, m.start.line, m.status, reason(m)])).toEqual( expect.arrayContaining([ [a0d.fullName, t0.start.line - 1, a0d.status, 'match-by-context'], [t1.name, t1.start.line - 1, 'Unknown', 'match-failed'], [a4.fullName, t3.start.line - 1, a4.status, 'match-by-name'], [a5.fullName, tTodo.start.line - 1, a5.status, 'match-by-name'], ]) ); }); it('a more complex case2: with deep desc blocks and multiple tests within', () => { const dComplex = helper.makeDescribeBlock('desc-deep', [d1, t2]); const a1d = helper.makeAssertion( 'test.each 1', 'KnownSuccess', ['desc-deep', 'wrapper-1'], [1, 0] ); const a2d = helper.makeAssertion( 'test.each 2', 'KnownFail', ['desc-deep', 'wrapper-1'], [1, 0] ); const a3d = helper.makeAssertion( 'test.each again 3', 'KnownSuccess', ['desc-deep'], [1, 0] ); const a4d = helper.makeAssertion('last test', 'KnownSuccess', ['wrapper-3'], [1, 0]); const a5d = helper.makeAssertion('a todo test', 'KnownTodo', ['wrapper-3'], undefined, { location: null, }); const sourceRoot = helper.makeRoot([t0, dComplex, d3]); const matched = match.matchTestAssertions('a file', sourceRoot, [ a1d, a2d, a3d, a4d, a0, a5d, ]); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a0.fullName, t0.start.line - 1, a0.status, ['match-by-context']], [a1d.fullName, t1.start.line - 1, a1d.status, ['match-by-context']], [a2d.fullName, t1.start.line - 1, a2d.status, ['match-by-context']], [a3d.fullName, t2.start.line - 1, a3d.status, ['match-by-context']], [a4d.fullName, t3.start.line - 1, a4d.status, ['match-by-context']], [a5d.fullName, tTodo.start.line - 1, a5d.status, ['match-by-name']], ]); }); }); }); }); describe('can handle missing ancestorTitles (#715)', () => { const t1 = helper.makeItBlock('test me', [1, 0, 6, 0]); const d1 = helper.makeDescribeBlock('desc-1', [t1]); const t2 = helper.makeItBlock('test me', [10, 0, 15, 0]); const d2 = helper.makeDescribeBlock('desc-2', [t2]); it('simple 1 test in describe block', () => { const a1 = helper.makeAssertion('test me', 'KnownSuccess', undefined, [1, 0], { fullName: 'desc-1 test me', }); const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1]); expect(matched).toHaveLength(1); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a1.fullName, t1.start.line - 1, a1.status, ['match-by-name']], ]); }); it('2 test block with the same name but different describe blocks', () => { const a1 = helper.makeAssertion('test me', 'KnownSuccess', undefined, [1, 0], { fullName: 'desc-1 test me', }); const a2 = helper.makeAssertion('test me', 'KnownFail', undefined, [10, 0], { fullName: 'desc-2 test me', }); const sourceRoot = helper.makeRoot([d1, d2]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a1.fullName, t1.start.line - 1, a1.status, ['missing-ancestor-info', 'match-by-name']], [a2.fullName, t2.start.line - 1, a2.status, ['missing-ancestor-info', 'match-by-name']], ]); }); it('when test.each matched multiple assertions by full-name', () => { const t1 = helper.makeItBlock('a each test', [1, 0, 6, 0], { lastProperty: 'each' }); const d1 = helper.makeDescribeBlock('desc-1', [t1]); const a1 = helper.makeAssertion('a each test', 'KnownSuccess', undefined, [1, 0], { fullName: 'desc-1 a each test', }); const a2 = helper.makeAssertion('a each test', 'KnownFail', undefined, [1, 0], { fullName: 'desc-1 a each test', }); const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a1.fullName, t1.start.line - 1, a1.status, ['missing-ancestor-info', 'match-by-name']], [a2.fullName, t1.start.line - 1, a2.status, ['missing-ancestor-info', 'match-by-name']], ]); }); it('can still detect duplicate test names and match by location', () => { const t1 = helper.makeItBlock('a test', [1, 0, 6, 0]); const t2 = helper.makeItBlock('a test', [10, 0, 16, 0]); const d1 = helper.makeDescribeBlock('desc-1', [t1, t2]); const a1 = helper.makeAssertion('a test', 'KnownSuccess', undefined, [1, 0], { fullName: 'desc-1 a test', }); const a2 = helper.makeAssertion('a test', 'KnownFail', undefined, [10, 0], { fullName: 'desc-1 a test', }); mockError.mockClear(); const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2]); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a1.fullName, t1.start.line - 1, a1.status, ['duplicate-name', 'match-by-location']], [a2.fullName, t2.start.line - 1, a2.status, ['duplicate-name', 'match-by-location']], ]); }); }); describe('console output', () => { const t1 = helper.makeItBlock('test-1', [1, 0, 6, 0]); const t2 = helper.makeItBlock('test-2', [10, 0, 16, 0]); const d1 = helper.makeDescribeBlock('desc-1', [t1, t2]); const a1 = helper.makeAssertion('test-1', 'KnownSuccess', ['desc-1'], [1, 0]); const a3 = helper.makeAssertion('test-3', 'KnownSuccess', undefined, [15, 0]); it.each([true, false])('mismatch message is shown when verbose = %p', (verbose) => { const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a3], verbose); expect(matched).toHaveLength(2); expect(matched.map((m) => [m.name, m.sourceHistory])).toEqual( expect.arrayContaining([['desc-1 test-2', expect.arrayContaining(['match-failed'])]]) ); expect(mockWarn).toBeCalledTimes(1); const info = mockWarn.mock.calls[0][1]; expect(info.type).toEqual('report-unmatched'); expect(info.unmatchedItBlocks).toHaveLength(1); expect(info.unmatchedItBlocks).toEqual( expect.arrayContaining([expect.objectContaining({ name: 'test-2' })]) ); expect(info.unmatchedAssertions).toHaveLength(1); expect(info.unmatchedAssertions).toEqual( expect.arrayContaining([expect.objectContaining({ name: 'test-3' })]) ); }); }); describe('edge cases', () => { it('when location order is wrong but context matched', () => { // angular produces fixed wrong location that caused the order of the tests are also wrong // even though the context matched! const t1 = helper.makeItBlock('a test', [1, 0, 6, 0]); const t2 = helper.makeItBlock('a test.each %i', [10, 0, 16, 0], { lastProperty: 'each' }); const a1 = helper.makeAssertion('a test', 'KnownSuccess', undefined, [100, 0]); const a2 = helper.makeAssertion('a test.each 1 ', 'KnownFail', undefined, [10, 0]); const a3 = helper.makeAssertion('a test.each 2', 'KnownSuccess', undefined, [10, 0]); const sourceRoot = helper.makeRoot([t1, t2]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1, a2, a3]); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a1.fullName, t1.start.line - 1, a1.status, ['match-by-name']], [a2.fullName, t2.start.line - 1, a2.status, ['match-by-location']], [a3.fullName, t2.start.line - 1, a3.status, ['match-by-location']], ]); }); }); it('matched assertions would be updated with source range', () => { const getRange = (t) => ({ start: { line: t.start.line - 1, column: t.start.column - 1 }, end: { line: t.end.line - 1, column: t.end.column - 1 }, }); const t1 = helper.makeItBlock('a test $seq', [2, 5, 6, 51], { lastProperty: 'each' }); const d1 = helper.makeDescribeBlock('desc-1', [t1], { start: { line: 1, column: 3 }, end: { line: 7, column: 3 }, }); const a1 = helper.makeAssertion('a test 1', 'KnownSuccess', ['desc-1'], [3, 0]); const a2 = helper.makeAssertion('a test 2 ', 'KnownFail', ['desc-1'], [3, 0]); const sourceRoot = helper.makeRoot([d1]); const assertionRoot = match.buildAssertionContainer([a1, a2]); const matched = match.matchTestAssertions('a file', sourceRoot, assertionRoot); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a1.fullName, t1.start.line - 1, a1.status, ['match-by-context']], [a2.fullName, t1.start.line - 1, a2.status, ['match-by-context']], ]); const assertionDescribe = assertionRoot.childContainers[0]; expect(assertionDescribe.attrs.range).toEqual(getRange(d1)); expect(assertionDescribe.attrs.range).toEqual(getRange(d1)); assertionDescribe.childData.forEach((c) => expect(c.attrs.range).toEqual(getRange(t1))); }); // see https://github.com/jest-community/vscode-jest/issues/608#issuecomment-849770258 it('dynamic named describe block should work for match-by-context', () => { const t1 = helper.makeItBlock('simple test', [1, 0, 6, 0]); const d1 = helper.makeDescribeBlock('`with ${TemplateLiteral}`', [t1]); const a1 = helper.makeAssertion('simple test', 'KnownSuccess', ['with whatever'], [1, 0]); const sourceRoot = helper.makeRoot([d1]); const matched = match.matchTestAssertions('a file', sourceRoot, [a1]); expect(matched.map((m) => toTestResultRecord(m))).toMatchTestResults([ [a1.fullName, t1.start.line - 1, a1.status, ['match-by-context']], ]); }); });
the_stack
import { CSSProperties } from 'react'; import { isServerRendering } from '../_util/dom'; import { isArray } from '../_util/is'; import { TriggerProps, MouseLocationType } from './interface'; // get element's position relative to root element function getElementPosition(element: HTMLElement, elementRect: ChildRect, root?: Element) { if (!root || !element || isServerRendering) { return { left: 0, width: 0, height: 0, top: 0 }; } // safari and chrome const bodyScroll = (direction) => document.documentElement[direction] || document.body[direction]; const pageScrollTop = root === document.body ? bodyScroll('scrollTop') : (root as Element).scrollTop; const pageScrollLeft = root === document.body ? bodyScroll('scrollLeft') : (root as Element).scrollLeft; const { left, top, width, height } = elementRect; // custom container const rootLeft = root === document.body ? 0 : (root as Element).getBoundingClientRect().left; const rootTop = root === document.body ? 0 : (root as Element).getBoundingClientRect().top; const pTop = top + pageScrollTop - rootTop; const pLeft = left + pageScrollLeft - rootLeft; return { left: pLeft, top: pTop, width, height, }; } const getInsideValue = function (min, max, value) { if (value < min) { return min; } if (value > max) { return max; } return value; }; const getPopupAlign = ( propsPopupAlign: TriggerProps['popupAlign'], showArrow: boolean ): { left?: number; right?: number; bottom?: number; top?: number; horizontalOffset?: number; verticalOffset?: number; } => { let horizontalOffset = 0; let verticalOffset = 0; let resultPopupAlign = {}; if (!showArrow) { resultPopupAlign = { ...propsPopupAlign }; } else { resultPopupAlign = { left: 12, right: 12, top: 12, bottom: 12, ...propsPopupAlign, }; } for (const key in resultPopupAlign) { if (isArray(resultPopupAlign[key])) { let index = 0; // top,bottom 时候,第二个参数是纵向偏移量 if (['top', 'bottom'].indexOf(key) > -1) { index = 1; horizontalOffset = resultPopupAlign[key][0]; } else { verticalOffset = resultPopupAlign[key][1]; } resultPopupAlign[key] = resultPopupAlign[key][index]; } } return { ...resultPopupAlign, horizontalOffset, verticalOffset, }; }; type ReturnType = { style?: CSSProperties; arrowStyle?: CSSProperties; realPosition?: TriggerProps['position']; }; type ChildRect = { left: number; top: number; width: number; height: number; right: number; bottom: number; }; const getChildRect = (child, mouseLocation): ChildRect => { return mouseLocation ? { left: mouseLocation.clientX, top: mouseLocation.clientY, width: 0, height: 0, right: mouseLocation.clientX, bottom: mouseLocation.clientY, } : child.getBoundingClientRect(); }; export default ( props: TriggerProps, content: HTMLElement, child: HTMLElement, mountContainer: Element, mouseLocation: MouseLocationType ): ReturnType => { const { autoAlignPopupWidth, autoAlignPopupMinWidth, alignPoint, style: propsStyle } = props; if (!child || !content || !mountContainer) { return {}; } const style: { left?: number; top?: number } = {}; // 如果跟随鼠标,相当于鼠标位置作为 child const childRect = getChildRect(child, alignPoint && mouseLocation); const { left, top, width, height } = getElementPosition(child, childRect, mountContainer); const popupAlign = getPopupAlign(props.popupAlign, props.showArrow); const alignLeft = popupAlign.left || 0; const alignRight = popupAlign.right || 0; const alignTop = popupAlign.top || 0; const alignBottom = popupAlign.bottom || 0; // 通过props.style 传递的width优先级更高 if (autoAlignPopupWidth && propsStyle?.width === undefined) { content.style.width = `${child.offsetWidth}px`; } if (autoAlignPopupMinWidth) { content.style.minWidth = `${child.offsetWidth}px`; } let realPosition = props.position; const arrowStyle: { left?: number; top?: number } = {}; const autoPosition = (direction) => { if (!props.autoFitPosition) { return; } // document.documentElement?.clientHeight 是为了排除横向滚动条的高度影响。 const windowHeight = document.documentElement?.clientHeight || window.innerHeight; const windowWidth = document.documentElement?.clientWidth || window.innerWidth; let result = false; // 是否进行了位置调整 // 视口左侧/顶部到 popupcontainer 的距离 const boundnary = { left: left - childRect.left, top: top - childRect.top, }; const { top: styleTop = 0, left: styleLeft = 0 } = style; // 水平方向微调 if (direction === 'top' || direction === 'bottom') { if (boundnary.left > styleLeft && childRect.right > 12) { // 左边被遮挡 style.left = Math.max(boundnary.left, left - content.clientWidth); style.left = Math.max(style.left as number, left - content.clientWidth + 24); } else if ( styleLeft - boundnary.left + content.clientWidth > windowWidth && windowWidth - childRect.left > 12 ) { // 右侧被遮挡,右侧贴边。如果child在可视区内的宽度小于12,不进行位置调整 style.left = Math.max(boundnary.left, boundnary.left + windowWidth - content.clientWidth); style.left = Math.max(style.left as number, left - content.clientWidth + 24); } } // 垂直方向微调 if (direction === 'left' || direction === 'right') { if (boundnary.top > styleTop && childRect.bottom > 12) { // 上面 style.top = boundnary.top; style.top = Math.max( style.top as number, top - content.clientHeight + childRect.height / 2 ); } else if ( styleTop - boundnary.top + content.clientHeight > windowHeight && windowHeight - childRect.top > 12 ) { // 向上微调位置,如果child在可视区内的高度小于12,不进行位置调整 style.top = Math.max(boundnary.top, boundnary.top + windowHeight - content.clientHeight); style.top = Math.max( style.top as number, top - content.clientHeight + childRect.height / 2 ); } } if (direction === 'top' && boundnary.top > styleTop) { // 上面被遮挡 if (childRect.top < windowHeight - childRect.bottom) { // 放到下面 style.top = Math.min( top + height + (alignTop || 0), boundnary.top + windowHeight - content.clientHeight ); result = true; } else { // 贴顶部边界 style.top = boundnary.top; } } if (direction === 'bottom' && styleTop - boundnary.top + content.clientHeight > windowHeight) { // 下部分被遮挡 if (windowHeight - childRect.bottom < childRect.top) { // 放到上面 style.top = Math.max(top - content.clientHeight - (alignBottom || 0), boundnary.top); result = true; } else { // 贴底边界 style.top = boundnary.top + windowHeight - content.clientHeight; } } if (direction === 'left' && boundnary.left > styleLeft) { // 左边被遮挡 if (childRect.left < windowWidth - childRect.right) { // 放到右边 style.left = Math.min( width + left + alignRight, boundnary.left + windowWidth - content.clientWidth ); result = true; } else { style.left = boundnary.left; } } if (direction === 'right' && styleLeft - boundnary.left + content.clientWidth > windowWidth) { // 右边被遮挡 if (windowWidth - childRect.right < childRect.left) { // 放到左边 style.left = Math.max(left - content.clientWidth - alignLeft, boundnary.left); result = true; } else { // 贴左边界 style.left = boundnary.left + windowWidth - content.clientWidth; } } // 限制在popupContainer中,左侧最小为 0px if (style.left < 0) { style.left = 0; } else { // 限制在popupContainer中,左侧最大为 mountContainer.scrollWidth - content.clientWidth,保证弹出层在container内部 const maxLeft = mountContainer.scrollWidth - content.clientWidth; style.left = Math.min(maxLeft, style.left); } return result; }; const horizontalOffset = popupAlign.horizontalOffset || 0; const verticalOffset = popupAlign.verticalOffset || 0; switch (props.position) { case 'top': { style.top = top - content.clientHeight - alignTop; style.left = left + width / 2 - content.clientWidth / 2; autoPosition('top') && (realPosition = 'bottom'); style.left += horizontalOffset; const arrowLeft = left - Number(style.left) + width / 2; arrowStyle.left = getInsideValue(12, content.clientWidth - 12, arrowLeft); break; } case 'tl': style.top = top - content.clientHeight - alignTop; style.left = left; autoPosition('top') && (realPosition = 'bl'); style.left += horizontalOffset; let arrowLeft = left - Number(style.left) + Math.min(width / 2, 50); arrowStyle.left = getInsideValue(12, content.clientWidth - 12, arrowLeft); break; case 'tr': style.top = -content.clientHeight + top - alignTop; style.left = left + width - content.clientWidth; autoPosition('top') && (realPosition = 'br'); style.left += horizontalOffset; arrowLeft = left - Number(style.left) + Math.max(width / 2, width - 50); arrowStyle.left = getInsideValue(12, content.clientWidth - 12, arrowLeft); break; case 'bottom': { style.top = height + top + alignBottom; style.left = left + width / 2 - content.clientWidth / 2; autoPosition('bottom') && (realPosition = 'top'); style.left += horizontalOffset; const arrowLeft = left - Number(style.left) + width / 2; arrowStyle.left = getInsideValue(12, content.clientWidth - 12, arrowLeft); break; } case 'bl': style.top = height + top + alignBottom; style.left = left; autoPosition('bottom') && (realPosition = 'tl'); style.left += horizontalOffset; arrowLeft = left - Number(style.left) + Math.min(width / 2, 50); arrowStyle.left = getInsideValue(12, content.clientWidth - 12, arrowLeft); break; case 'br': style.top = height + top + alignBottom; style.left = left + width - content.clientWidth; autoPosition('bottom') && (realPosition = 'tr'); style.left += horizontalOffset; arrowLeft = left - Number(style.left) + Math.max(width / 2, width - 50); arrowStyle.left = getInsideValue(12, content.clientWidth - 12, arrowLeft); break; case 'left': { style.top = top + height / 2 - content.clientHeight / 2; style.left = left - content.clientWidth - alignLeft; autoPosition('left') && (realPosition = 'right'); style.top += verticalOffset; const arrowTop = top - Number(style.top) + height / 2; arrowStyle.top = getInsideValue(12, content.clientHeight - 12, arrowTop); break; } case 'lt': style.top = top; style.left = left - content.clientWidth - alignLeft; autoPosition('left') && (realPosition = 'rt'); style.top += verticalOffset; let arrowTop = top - Number(style.top) + Math.min(height / 2, 50); arrowStyle.top = getInsideValue(12, content.clientHeight - 12, arrowTop); break; case 'lb': style.top = top + height - content.clientHeight; style.left = left - content.clientWidth - alignLeft; autoPosition('left') && (realPosition = 'rb'); style.top += verticalOffset; arrowTop = top - Number(style.top) + Math.max(height / 2, height - 50); arrowStyle.top = getInsideValue(12, content.clientHeight - 12, arrowTop); break; case 'right': { style.top = top + height / 2 - content.clientHeight / 2; style.left = width + left + alignRight; autoPosition('right') && (realPosition = 'left'); style.top += verticalOffset; const arrowTop = top - Number(style.top) + height / 2; arrowStyle.top = getInsideValue(12, content.clientHeight - 12, arrowTop); break; } case 'rt': style.top = top; style.left = width + left + alignRight; autoPosition('right') && (realPosition = 'lt'); style.top += verticalOffset; arrowTop = top - Number(style.top) + Math.min(height / 2, 50); arrowStyle.top = getInsideValue(12, content.clientHeight - 12, arrowTop); break; case 'rb': style.top = top + height - content.clientHeight; style.left = width + left + alignRight; autoPosition('right') && (realPosition = 'lb'); style.top += verticalOffset; arrowTop = top - Number(style.top) + Math.max(height / 2, height - 50); arrowStyle.top = getInsideValue(12, content.clientHeight - 12, arrowTop); break; default: break; } return { style, arrowStyle, realPosition, }; };
the_stack
/// <reference path="ezgui.ts" /> /// <reference path="../lib/pixi.d.ts" /> /// <reference path="multistatesprite.ts" /> /// <reference path="compatibility.ts" /> module EZGUI { export class GUIObject extends EZGUI.Compatibility.GUIDisplayObjectContainer { public guiID: string; get Id(): string { return this.guiID; } set Id(val: string) { this.guiID = val; } public userData: any; public name: string; public container: PIXI.Container; public guiParent: GUISprite; constructor() { super(); this.container = new Compatibility.GUIContainer(); this.addChild(this.container); } protected setupEvents() { var __this: any = this; //var _this:any = this; __this.interactive = true; __this.pointerover = function (event) { //__this.mouseover = function (event) { //console.log('mouseover ', _this.guiID); //if PIXI 2 use event else use event.data var data = event.data || event; if (!__this.canTrigger(event, __this)) { return; } //console.log('hover ', guiObj.guiID); __this._over = true; //guiObj.setState('hover'); __this.emit('ezgui:mouseover', event, __this); } //__this.mouseout = function (event) { __this.pointerout = function (event) { //console.log('mouseout ', _this.guiID); //if PIXI 2 use event else use event.data var data = event.data || event; __this._over = false; //guiObj.setState('out'); __this.emit('ezgui:mouseout', event, __this); } //handle drag stuff //__this.mousedown = __this.touchstart = function (event: any) { __this.pointerdown = function (event: any) { //console.log('mousedown ', _this.guiID); if (!__this.canTrigger(event, __this)) { return; } var pos = utils.getRealPos(event); EZGUI.startDrag.x = pos.x; EZGUI.startDrag.y = pos.y; EZGUI.startDrag.t = Date.now(); var data = event.data || event; __this.emit('ezgui:mousedown', event, __this); //event.stopped = true; } //__this.mouseup = __this.mouseupoutside = __this.touchend = __this.touchendoutside = function (event: any) { __this.pointerup = function (event: any) { if (!__this.canTrigger(event, __this)) { return; } var data = event.data || event; __this.emit('ezgui:mouseup', event, __this); var pos = utils.getRealPos(event); if (utils.distance(pos.x, pos.y, EZGUI.startDrag.x, EZGUI.startDrag.y) <= 4) { __this.emit('ezgui:click', event, __this); if (EZGUI.focused && __this != EZGUI.focused && EZGUI.focused.emit) EZGUI.focused.emit('ezgui:blur'); EZGUI.focused = __this; EZGUI.focused.emit('ezgui:focus'); event.stopped = true; } }; __this.pointermove = function (event) { //__this.mousemove = __this.touchmove = function (event) { if (__this._over) { if (__this.canTrigger(event, __this)) { __this._over = false; __this.pointerover(event); } else { __this.pointereout(event); } } if (!__this.canTrigger(event, __this)) { return; } var data = event.data || event; __this.emit('ezgui:mousemove', event, __this); } EZGUI.Compatibility.copyPointerEvents(__this); __this.click = __this.tap = function (event) { //console.log('click', _this.guiID); //var pos = utils.getRealPos(event); //if (utils.distance(pos.x, pos.y, _this.startDrag.x, _this.startDrag.y) > 4) return; //if (guiObj.canTrigger(event, guiObj)) guiObj.emit('ezgui:click', event); } if (__this.phaserGroup) { __this.phaserGroup.inputEnabled = true; //Fix priorityID otherwise, events will not trigger on children if (EZGUI.Compatibility.isPhaser24plus) { for (var c in EZGUI.components) { var __this = EZGUI.components[c]; if (__this.phaserGroup && __this.phaserGroup.input && __this.guiParent && __this.guiParent.phaserGroup && __this.guiParent.phaserGroup.input) { __this.phaserGroup.input.priorityID = __this.guiParent.phaserGroup.input.priorityID + 1; } } } __this.phaserGroup.events.onInputOver.add(function (target, event) { __this._over = true; //console.log('ezgui:mouseover', event); __this.emit('ezgui:mouseover', event, __this); }, this); __this.phaserGroup.events.onInputOut.add(function (target, event) { __this._over = false; __this.emit('ezgui:mouseout', event, __this); //console.log('ezgui:mouseout', event); }, this); __this.phaserGroup.events.onInputDown.add(function (target, event) { if (!__this.canTrigger(event, __this)) { return; } var pos = utils.getRealPos(event); EZGUI.startDrag.x = pos.x; EZGUI.startDrag.y = pos.y; EZGUI.startDrag.t = Date.now(); __this.emit('ezgui:mousedown', event, __this); if (!__this.draggable && __this.guiParent && __this.guiParent.draggable) { __this.guiParent.emit('ezgui:mousedown', event, __this); } // //console.log('ezgui:mousedown', event); }, this); __this.phaserGroup.events.onInputUp.add(function (target, event) { //if (!_this.canTrigger(event, _this)) { // return; //} //_this.emit('ezgui:mouseup', event); __this.emit('ezgui:mouseup', event, __this); var pos = utils.getRealPos(event); if (utils.distance(pos.x, pos.y, EZGUI.startDrag.x, EZGUI.startDrag.y) <= 4) { __this.emit('ezgui:click', event, __this); if (EZGUI.focused && __this != EZGUI.focused && EZGUI.focused.emit) EZGUI.focused.emit('ezgui:blur'); EZGUI.focused = __this; EZGUI.focused.emit('ezgui:focus'); //console.log('ezgui:click', event); } if (!__this.draggable && __this.guiParent && __this.guiParent.draggable) { __this.guiParent.emit('ezgui:mouseup', event, __this); } }, this); //Phaser.GAMES[0].input.moveCallback = function (pointer, x, y) { // console.log(pointer, x, y); //} Phaser.GAMES[0].input.mouse.mouseMoveCallback = function (event) { if (__this._over) { if (__this.canTrigger(event, __this)) { __this._over = true; __this.emit('ezgui:mouseover', event, __this); } else { __this._over = false; __this.emit('ezgui:mouseout', event, __this); } } if (!__this.canTrigger(event, __this)) { return; } var data = event.data || event; __this.emit('ezgui:mousemove', event, __this); } } } public originalAddChildAt(child, index) { return super.addChildAt(child, index); } public originalAddChild(child) { return this.originalAddChildAt(child, this.children.length); } public getChildByName(name) { return this.container.getChildByName(name); }; public addChild(child) { if (child instanceof GUISprite) { //return this.container.addChild(child); (<any>child).guiParent = this; if (child.phaserGroup) return this.container.addChild(child.phaserGroup); else return this.container.addChild(child); } else { return super.addChild(child); } } public removeChild(child) { if (child instanceof GUISprite) { child.guiParent = null; if (child.phaserGroup) return this.container.removeChild(child.phaserGroup); else return this.container.removeChild(child); } else { return super.removeChild(child); } } public mouseInObj(event, guiSprite) { var data = event.data || event; var clientpos = utils.getClientXY(event); var origEvt = event; if (data.originalEvent && data.originalEvent.changedTouches && data.originalEvent.changedTouches.length > 0) { origEvt = data.originalEvent.changedTouches[0]; } else if (data.originalEvent && data.originalEvent.touches && data.originalEvent.touches.length > 0) { origEvt = data.originalEvent.touches[0]; } else { if (data.originalEvent) origEvt = data.originalEvent; } var bcr = origEvt.target.getBoundingClientRect(); var px = clientpos.x - bcr.left; var py = clientpos.y - bcr.top; var absPos = utils.getAbsPos(guiSprite); if (px < absPos.x || px > absPos.x + guiSprite.width || py < absPos.y || py > absPos.y + guiSprite.height) return false; return true; } public canTrigger(event, guiSprite) { var data = event.data || event; var clientpos = utils.getClientXY(event); var origEvt = event; if (data.originalEvent && data.originalEvent.changedTouches && data.originalEvent.changedTouches.length > 0) { origEvt = data.originalEvent.changedTouches[0]; } else if (data.originalEvent && data.originalEvent.touches && data.originalEvent.touches.length > 0) { origEvt = data.originalEvent.touches[0]; } else { if (data.originalEvent) origEvt = data.originalEvent; } if (!origEvt.target.getBoundingClientRect) return false; var bcr = origEvt.target.getBoundingClientRect(); var px = clientpos.x - bcr.left; var py = clientpos.y - bcr.top; //var absPos = utils.getAbsPos(guiSprite); //if (px < absPos.x || px > absPos.x + guiSprite.width || py < absPos.y || py > absPos.y + guiSprite.height) return false; //check if click is in visible zone var masked = utils.isMasked(px, py, guiSprite); return !masked; } public on(event, fn, context?):any { return super.on('ezgui:' + event, fn, context); //super.on('gui:' + event, cb); } public off(event, fn?, context?):any { if (EZGUI.Compatibility.PIXIVersion == 2) { if (fn == null && context == null) { (<any>this)._listeners['ezgui:' + event] = []; return; } } return super.off('ezgui:' + event, fn, context); //super.on('gui:' + event, cb); } public bindChildren(event, fn) { for (var i = 0; i < this.container.children.length; i++) { var child:any = this.container.children[i]; if (child.guiSprite) child = child.guiSprite; child.on(event, fn); } } public bindChildrenOfType(_type, event, fn) { for (var i = 0; i < this.container.children.length; i++) { var child: any = this.container.children[i]; if (child.guiSprite) child = child.guiSprite; if (child instanceof _type) child.on(event, fn); } } public unbindChildren(event, fn?) { for (var i = 0; i < this.container.children.length; i++) { var child: any = this.container.children[i]; if (child.guiSprite) child = child.guiSprite; child.off(event, fn); } } public unbindChildrenOfType(_type, event, fn?) { for (var i = 0; i < this.container.children.length; i++) { var child :any= this.container.children[i]; if (child.guiSprite) child = child.guiSprite; if (child instanceof _type) child.off(event, fn); } } public preUpdate() { } public update() { } public postUpdate() { } public destroy() { if (this.phaserGroup) { this.phaserGroup.destroy(); } if (this.parent && this.parent.removeChild) this.parent.removeChild(this); delete EZGUI.components[this.guiID]; } } //EZGUI.registerComponents(GUISprite, 'default'); }
the_stack
import { A } from '@ember/array'; import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; //@ts-ignore import { initialize as injectC3Enhancements } from '@yavin/c3/initializers/inject-c3-enhancements'; //@ts-ignore import { setupMirage } from 'ember-cli-mirage/test-support'; import NaviFactResponse from '@yavin/client/models/navi-fact-response'; import { buildTestRequest } from 'navi-core/test-support/request'; import { VisualizationModel } from 'navi-core/components/navi-visualizations/table'; import { TestContext } from 'ember-test-helpers'; const TEMPLATE = hbs` <NaviVisualizations::BarChart @model={{this.model}} @options={{this.options}} />`; /*eslint max-len: ["error", { "code": 250 }]*/ //@ts-ignore -- skip injector const metricResponse = new NaviFactResponse(null, { //prettier-ignore rows: [ { 'network.dateTime(grain=day)': '2016-05-30 00:00:00.000', uniqueIdentifier: 172933788, totalPageViews: 3669828357 }, { 'network.dateTime(grain=day)': '2016-05-31 00:00:00.000', uniqueIdentifier: 183206656, totalPageViews: 4088487125 }, { 'network.dateTime(grain=day)': '2016-06-01 00:00:00.000', uniqueIdentifier: 183380921, totalPageViews: 4024700302 }, { 'network.dateTime(grain=day)': '2016-06-02 00:00:00.000', uniqueIdentifier: 180559793, totalPageViews: 3950276031 }, { 'network.dateTime(grain=day)': '2016-06-03 00:00:00.000', uniqueIdentifier: 172724594, totalPageViews: 3697156058 } ], }); //@ts-ignore -- skip injector const dimensionReponse = new NaviFactResponse(null, { //prettier-ignore rows: [ { 'network.dateTime(grain=week)': '2016-02-15 00:00:00.000', 'age(field=id)': '-3', uniqueIdentifier: 155191081, totalPageViews: 3072620639 }, { 'network.dateTime(grain=week)': '2015-12-14 00:00:00.000', 'age(field=id)': '1', uniqueIdentifier: 55191081, totalPageViews: 2072620639 }, { 'network.dateTime(grain=week)': '2015-12-21 00:00:00.000', 'age(field=id)': '1', uniqueIdentifier: 72724594, totalPageViews: 2697156058 }, { 'network.dateTime(grain=week)': '2015-12-28 00:00:00.000', 'age(field=id)': '1', uniqueIdentifier: 83380921, totalPageViews: 3024700302 }, { 'network.dateTime(grain=week)': '2016-01-04 00:00:00.000', 'age(field=id)': '1', uniqueIdentifier: 72933788, totalPageViews: 2669828357 }, { 'network.dateTime(grain=week)': '2016-01-11 00:00:00.000', 'age(field=id)': '1', uniqueIdentifier: 83206656, totalPageViews: 3088487125 }, { 'network.dateTime(grain=week)': '2016-01-18 00:00:00.000', 'age(field=id)': '1', uniqueIdentifier: 83380921, totalPageViews: 2024700302 }, { 'network.dateTime(grain=week)': '2016-01-25 00:00:00.000', 'age(field=id)': '1', uniqueIdentifier: 80559793, totalPageViews: 2950276031 }, { 'network.dateTime(grain=week)': '2016-02-01 00:00:00.000', 'age(field=id)': '1', uniqueIdentifier: 72724594, totalPageViews: 2697156058 }, { 'network.dateTime(grain=week)': '2016-02-08 00:00:00.000', 'age(field=id)': '1', uniqueIdentifier: 52298735, totalPageViews: 2008425744 }, { 'network.dateTime(grain=week)': '2016-02-15 00:00:00.000', 'age(field=id)': '1', uniqueIdentifier: 55191081, totalPageViews: 2072620639 }, { 'network.dateTime(grain=week)': '2015-12-14 00:00:00.000', 'age(field=id)': '2', uniqueIdentifier: 55191081, totalPageViews: 2620639 }, { 'network.dateTime(grain=week)': '2015-12-21 00:00:00.000', 'age(field=id)': '2', uniqueIdentifier: 72724594, totalPageViews: 2156058 }, { 'network.dateTime(grain=week)': '2015-12-28 00:00:00.000', 'age(field=id)': '2', uniqueIdentifier: 83380921, totalPageViews: 24700302 }, { 'network.dateTime(grain=week)': '2016-01-04 00:00:00.000', 'age(field=id)': '2', uniqueIdentifier: 72933788, totalPageViews: 9828357 }, { 'network.dateTime(grain=week)': '2016-01-11 00:00:00.000', 'age(field=id)': '2', uniqueIdentifier: 83206656, totalPageViews: 88487125 }, { 'network.dateTime(grain=week)': '2016-01-18 00:00:00.000', 'age(field=id)': '2', uniqueIdentifier: 83380921, totalPageViews: 4700302 }, { 'network.dateTime(grain=week)': '2016-01-25 00:00:00.000', 'age(field=id)': '2', uniqueIdentifier: 80559793, totalPageViews: 276031 }, { 'network.dateTime(grain=week)': '2016-02-01 00:00:00.000', 'age(field=id)': '2', uniqueIdentifier: 72724594, totalPageViews: 7156058 }, { 'network.dateTime(grain=week)': '2016-02-08 00:00:00.000', 'age(field=id)': '2', uniqueIdentifier: 52298735, totalPageViews: 8425744 }, { 'network.dateTime(grain=week)': '2016-02-15 00:00:00.000', 'age(field=id)': '2', uniqueIdentifier: 55191081, totalPageViews: 72620639 }, { 'network.dateTime(grain=week)': '2015-12-14 00:00:00.000', 'age(field=id)': '3', uniqueIdentifier: 55191081, totalPageViews: 72620639 }, { 'network.dateTime(grain=week)': '2015-12-21 00:00:00.000', 'age(field=id)': '3', uniqueIdentifier: 72724594, totalPageViews: 697156058 }, { 'network.dateTime(grain=week)': '2015-12-28 00:00:00.000', 'age(field=id)': '3', uniqueIdentifier: 83380921, totalPageViews: 24700302 }, { 'network.dateTime(grain=week)': '2016-01-04 00:00:00.000', 'age(field=id)': '3', uniqueIdentifier: 72933788, totalPageViews: 669828357 }, { 'network.dateTime(grain=week)': '2016-01-11 00:00:00.000', 'age(field=id)': '3', uniqueIdentifier: 83206656, totalPageViews: 88487125 }, { 'network.dateTime(grain=week)': '2016-01-18 00:00:00.000', 'age(field=id)': '3', uniqueIdentifier: 83380921, totalPageViews: 24700302 }, { 'network.dateTime(grain=week)': '2016-01-25 00:00:00.000', 'age(field=id)': '3', uniqueIdentifier: 80559793, totalPageViews: 950276031 }, { 'network.dateTime(grain=week)': '2016-02-01 00:00:00.000', 'age(field=id)': '3', uniqueIdentifier: 72724594, totalPageViews: 697156058 }, { 'network.dateTime(grain=week)': '2016-02-08 00:00:00.000', 'age(field=id)': '3', uniqueIdentifier: 52298735, totalPageViews: 8425744 }, { 'network.dateTime(grain=week)': '2016-02-15 00:00:00.000', 'age(field=id)': '3', uniqueIdentifier: 55191081, totalPageViews: 2620639 }, { 'network.dateTime(grain=week)': '2015-12-14 00:00:00.000', 'age(field=id)': '4', uniqueIdentifier: 55191081, totalPageViews: 72620639 }, { 'network.dateTime(grain=week)': '2015-12-21 00:00:00.000', 'age(field=id)': '4', uniqueIdentifier: 72724594, totalPageViews: 97156058 }, { 'network.dateTime(grain=week)': '2015-12-28 00:00:00.000', 'age(field=id)': '4', uniqueIdentifier: 83380921, totalPageViews: 24700302 }, { 'network.dateTime(grain=week)': '2016-01-04 00:00:00.000', 'age(field=id)': '4', uniqueIdentifier: 72933788, totalPageViews: 2669828357 }, { 'network.dateTime(grain=week)': '2016-01-11 00:00:00.000', 'age(field=id)': '4', uniqueIdentifier: 83206656, totalPageViews: 88487125 }, { 'network.dateTime(grain=week)': '2016-01-18 00:00:00.000', 'age(field=id)': '4', uniqueIdentifier: 83380921, totalPageViews: 24700302 }, { 'network.dateTime(grain=week)': '2016-01-25 00:00:00.000', 'age(field=id)': '4', uniqueIdentifier: 80559793, totalPageViews: 50276031 }, { 'network.dateTime(grain=week)': '2016-02-01 00:00:00.000', 'age(field=id)': '4', uniqueIdentifier: 72724594, totalPageViews: 97156058 }, { 'network.dateTime(grain=week)': '2016-02-08 00:00:00.000', 'age(field=id)': '4', uniqueIdentifier: 52298735, totalPageViews: 8425744 }, { 'network.dateTime(grain=week)': '2016-02-15 00:00:00.000', 'age(field=id)': '4', uniqueIdentifier: 55191081, totalPageViews: 72620639 } ], }); module('Integration | Component | bar chart', function (hooks) { setupRenderingTest(hooks); setupMirage(hooks); hooks.beforeEach(async function (this: TestContext) { injectC3Enhancements(); this.set('options', { axis: { y: { series: { type: 'metric', config: {}, }, }, }, }); await this.owner.lookup('service:navi-metadata').loadMetadata(); }); test('it renders', async function (assert) { assert.expect(2); const singleMetricRequest = buildTestRequest( [{ field: 'uniqueIdentifier' }], [], { start: '2016-05-30 00:00:00.000', end: '2016-06-04 00:00:00.000' }, 'day' ); const Model: VisualizationModel = A([{ request: singleMetricRequest, response: metricResponse }]); this.set('model', Model); await render(TEMPLATE); assert.dom('.yavin-c3-chart').isVisible('The bar chart widget component is visible'); assert.dom('.c3-bar').exists({ count: 5 }, '5 bars are present on the chart'); }); test('multiple metric series', async function (assert) { assert.expect(1); const multipleMetricRequest = buildTestRequest( [{ field: 'uniqueIdentifier' }, { field: 'totalPageViews' }], [], { start: '2016-05-30 00:00:00.000', end: '2016-06-04 00:00:00.000' }, 'day' ); const Model: VisualizationModel = A([{ request: multipleMetricRequest, response: metricResponse }]); this.set('model', Model); await render(TEMPLATE); assert.dom('.c3-bar').exists({ count: 10 }, 'Ten bars are present in the bar based on the metrics in the request'); }); test('multiple dimension series', async function (assert) { assert.expect(2); this.set('options', { axis: { y: { series: { type: 'dimension', config: { metricCid: 'cid_totalPageViews', dimensions: [ { name: 'All Other', values: { cid_age: '-3' } }, { name: 'under 13', values: { cid_age: '1' } }, { name: '13 - 25', values: { cid_age: '2' } }, { name: '25 - 35', values: { cid_age: '3' } }, { name: '35 - 45', values: { cid_age: '4' } }, ], }, }, }, }, }); const dimensionRequest = buildTestRequest( [{ field: 'uniqueIdentifier' }, { cid: 'cid_totalPageViews', field: 'totalPageViews' }], [{ cid: 'cid_age', field: 'age', parameters: { field: 'id' } }], { start: '2015-12-14 00:00:00.000', end: '2016-02-22 00:00:00.000' }, 'week' ); const Model: VisualizationModel = A([{ request: dimensionRequest, response: dimensionReponse }]); this.set('model', Model); await render(TEMPLATE); assert .dom('.c3-bars') .exists({ count: 5 }, 'Five series are present in the bar chart based on the dimension series in the request'); assert .dom('.c3-bar') .exists({ count: 50 }, 'Fifty bars are present in the bar chart based on the dimension series in the request'); }); });
the_stack
import * as s from './RegulationsSearchSection.css' import React, { useEffect, useMemo, useState } from 'react' import { useRouter } from 'next/router' import { Box, Button, Checkbox, GridColumn, GridContainer, GridRow, Input, Option, Select, } from '@island.is/island-ui/core' import { useNamespaceStrict as useNamespace } from '@island.is/web/hooks' import { useShortState } from '@island.is/regulations' import { RegulationLawChapterTree, RegulationMinistry, } from '@island.is/regulations/web' import { RegulationHomeTexts } from './RegulationTexts.types' import { OptionTypeBase, ValueType } from 'react-select' import { RegulationSearchFilters, RegulationSearchKey } from './regulationUtils' import cn from 'classnames' // --------------------------------------------------------------------------- /** Icky utility function to handle the buggy typing of react-select * * See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/32553 */ const getRSValue = (option: ValueType<OptionTypeBase>) => { const opt: OptionTypeBase | undefined | null = Array.isArray(option) ? (option as Array<OptionTypeBase>)[0] : option return opt ? String(opt.value) : undefined } const emptyOption = (label?: string): Option => ({ value: '', label: label ? `– ${label} –` : '—', }) /** Looks through a list of `Option`s for one with a matching `value` * * If a match is not found it returns `null` because that's the * magic value that tricks `react-select` to show the "placeholder" value */ const findValueOption = (options: ReadonlyArray<Option>, value?: string) => { // NOTE: The returned option MUST NOT be a copy (with trimmed value, // even if it would look nicer) because react-select seems to do an // internal `===` comparison against the options list, and thus copies // will fail to appear selected in the dropdown list. return (value && options.find((opt) => opt.value === value)) || null } const yearToOption = (year: number | string): Option => { const value = String(year) return { value, label: value, } } const filterOrder: Record<RegulationSearchKey, number> = { q: 1, year: 2, yearTo: 3, rn: 4, ch: 5, iA: 6, iR: 7, page: 8, } /** Returns a copy of the original query with any falsy values filtered out */ const cleanQuery = ( query: Record<RegulationSearchKey, string | null | undefined>, ) => Object.entries(query) .sort((a, b) => { const keyA = a[0] as RegulationSearchKey const keyB = b[0] as RegulationSearchKey return (filterOrder[keyA] || 999) > (filterOrder[keyB] || 999) ? 1 : -1 }) .reduce<Record<string, string>>((newQuery, [key, value]) => { if (value) { newQuery[key] = value } return newQuery }, {}) // --------------------------------------------------------------------------- export type RegulationsSearchSectionProps = { searchFilters: RegulationSearchFilters years: ReadonlyArray<number> ministries: ReadonlyArray<RegulationMinistry> lawChapters: Readonly<RegulationLawChapterTree> texts: RegulationHomeTexts page?: number anchorRef: React.RefObject<HTMLDivElement> } export const RegulationsSearchSection = ( props: RegulationsSearchSectionProps, ) => { const filters = props.searchFilters const txt = useNamespace(props.texts) const router = useRouter() const yearOptions = useMemo(() => { return [emptyOption(txt('searchYearEmptyOption'))].concat( props.years.map(yearToOption), ) as ReadonlyArray<Option> }, [props.years]) const [yearToOptions, setYearToOptions] = useState(yearOptions) useEffect(() => { if (filters.year) { setYearToOptions( yearOptions.filter((opt) => { return opt.value === '' || Number(opt.value) > Number(filters.year) }), ) } else { setYearToOptions(yearOptions) } if (Number(filters.yearTo) <= Number(filters.year)) { doSearch('yearTo', '') } }, [yearOptions, filters.year]) useEffect(() => { doSearch('page', props.page && props.page > 1 ? String(props.page) : '') const anchorTop = (props?.anchorRef?.current?.getBoundingClientRect()?.top || 0) + window.scrollY setTimeout(() => { window.scrollTo({ top: props.page && props.page > 1 ? anchorTop - 30 : 0, behavior: 'smooth', }) }, 100) }, [props.page]) const ministryOptions = useMemo(() => { return [emptyOption(txt('searchMinistryEmptyOption'))].concat( props.ministries.map( (m): Option => ({ value: m.slug, label: m.name, }), ), ) as ReadonlyArray<Option> }, [props.ministries]) const lawChapterOptions = useMemo( () => props.lawChapters.reduce<Array<Option>>( (opts, { name, slug, subChapters }) => { opts.push({ value: slug, label: `${name}`, }) opts = opts.concat( subChapters.map(({ name, slug }) => ({ value: slug, label: '    ' + name, })), ) return opts }, [emptyOption(txt('searchChapterEmptyOption'))], ) as ReadonlyArray<Option>, [props.lawChapters], ) const doSearch = ( keyOrFilters: RegulationSearchKey | Partial<RegulationSearchFilters>, value?: string, ) => { let newFilters = typeof keyOrFilters !== 'string' ? { ...filters, ...keyOrFilters } : { ...filters, [keyOrFilters]: value } // reset page to 1 if any search params change if (keyOrFilters !== 'page') { newFilters = { ...newFilters, page: '' } } router.replace({ pathname: router.pathname, query: cleanQuery(newFilters), }) } const clearSearch = () => { setFilterValue('') router.replace({ pathname: router.pathname, query: null, }) } const clearAdvancedFields = () => { router.replace({ pathname: router.pathname, query: filterValue ? { q: filterValue } : undefined, }) } const [filterValue, setFilterValue] = useState(filters.q) useEffect(() => { setFilterValue(filters.q) }, [filters.q]) const hasAdvancedValues = !!( filters.year || filters.rn || filters.ch || filters.iA || filters.iR ) const filterHasValues = !!filterValue || hasAdvancedValues const [showAdvancedSearch, setShowAdvancedSearch] = useState( hasAdvancedValues, ) const [ advancedSearchTransitioning, setAdvancedSearchTransitioning, ] = useShortState<boolean>(undefined, 600) return ( <GridContainer> <GridRow> <GridColumn span={['1/1', '1/1', '1/1', '1/1', '10/12']} offset={['0', '0', '0', '0', '1/12']} paddingTop={2} paddingBottom={[4, 4, 4]} > <GridContainer> <GridRow alignItems="center"> <GridColumn span={['1/1', '1/1', '10/12', '10/12', '8/10']} paddingTop={0} paddingBottom={[2, 2, 0]} > <Input id="q" name="q" placeholder={txt('searchQueryLabel')} backgroundColor={['blue', 'blue', 'white']} size="md" icon="search" iconType="outline" value={filterValue} onChange={(event) => setFilterValue(event.target.value)} onKeyDown={(event) => { if (event.key === 'Enter') { doSearch('q', filterValue) } }} onBlur={() => doSearch('q', filterValue)} /> </GridColumn> <GridColumn span={['1/1', '1/1', '2/12', '2/12', '2/10']} paddingBottom={[2, 2, 0]} > <Button variant="text" icon={showAdvancedSearch ? 'chevronUp' : 'chevronDown'} onClick={() => { if (hasAdvancedValues) { clearAdvancedFields() } setShowAdvancedSearch(!showAdvancedSearch) setAdvancedSearchTransitioning(true) }} > Ítarleit </Button> </GridColumn> </GridRow> <div className={cn( s.advancedFields, advancedSearchTransitioning && s.advancedFieldsTransitioning, )} hidden={!showAdvancedSearch} > {(showAdvancedSearch || advancedSearchTransitioning) && ( <> <GridRow> <GridColumn span={['1/1', '1/1', '6/12', '5/12', '4/10']} paddingTop={[0, 0, 3]} paddingBottom={[2, 2, 0]} > <Checkbox id="regulations-search-amendments-checkbox" label={txt( 'searchIncludeAmendingLabel', 'Leita í breytingareglugerðum', )} checked={!!filters.iA} onChange={() => doSearch('iA', !filters.iA ? 'true' : '') } /> </GridColumn> <GridColumn span={['1/1', '1/1', '6/12', '5/12', '4/10']} paddingTop={[0, 0, 3]} paddingBottom={[2, 2, 0]} > <Checkbox id="regulations-search-repelled-checkbox" label={txt( 'searchIncludeRepelledLabel', 'Leita í brottföllnum reglugerðum', )} checked={!!filters.iR} onChange={() => doSearch({ iR: !filters.iR ? 'true' : '', rn: undefined, }) } /> </GridColumn> </GridRow> <GridRow> <GridColumn span={['1/1', '1/1', '6/12', '5/12', '4/10']} paddingTop={[0, 0, 4]} paddingBottom={[2, 2, 0]} > <Select name="rn" isSearchable label={txt('searchMinistryLabel', 'Ráðuneyti')} placeholder={txt( 'searchMinistryPlaceholder', 'Veldu ráðuneyti', )} value={findValueOption(ministryOptions, filters.rn)} options={ministryOptions} onChange={(option) => doSearch({ rn: getRSValue(option), iR: undefined }) } size="sm" /> </GridColumn> <GridColumn span={['1/1', '1/1', '6/12', '5/12', '4/10']} paddingTop={[0, 0, 4]} paddingBottom={[2, 2, 0]} > <Select name="ch" isSearchable label={txt('searchChapterLabel', 'Kafli í lagasafni')} placeholder={txt( 'searchChapterPlaceholder', 'Veldu kafla', )} value={findValueOption(lawChapterOptions, filters.ch)} options={lawChapterOptions} onChange={(option) => doSearch('ch', getRSValue(option)) } size="sm" /> </GridColumn> </GridRow> <GridRow> <GridColumn span={['1/1', '1/1', '4/12', '3/12', '2/10']} paddingTop={[0, 0, 4]} paddingBottom={[2, 2, 0]} > <Select name="year" isSearchable label={txt('searchYearLabel', 'Útgáfuár')} placeholder={txt('searchYearPlaceholder', 'Veldu ár')} value={findValueOption(yearOptions, filters.year)} options={yearOptions} onChange={(option) => { const year = getRSValue(option) const yearTo = !year ? undefined : filters.yearTo // clear yearTo along with year doSearch({ year, yearTo }) }} size="sm" /> </GridColumn> {filters.year && ( <GridColumn span={['1/1', '1/1', '4/12', '3/12', '2/10']} paddingTop={[0, 0, 4]} paddingBottom={[2, 2, 0]} > <Select name="yearTo" isSearchable label={txt('searchYearToLabel', 'Tímabili til')} placeholder={txt( 'searchYearToPlaceholder', 'Veldu ár', )} value={findValueOption(yearToOptions, filters.yearTo)} options={yearToOptions} onChange={(option) => doSearch('yearTo', getRSValue(option)) } size="sm" /> </GridColumn> )} </GridRow> </> )} </div> </GridContainer> <Box marginTop={2} className={s.clearSearch} hidden={!filterHasValues} > <Button icon="reload" type="button" size="small" variant="text" disabled={!filterHasValues} onClick={() => clearSearch()} > {txt('searchClearLabel')} </Button> </Box> </GridColumn> </GridRow> </GridContainer> ) }
the_stack
import test from 'ava'; import { compilerOperationAddressData, compileScript, compileScriptContents, describeExpectedInput, hexToBin, stringifyTestVector, } from '../../lib'; test('compileScript: unprovided ID', (t) => { t.deepEqual(compileScript('test', {}, { scripts: { typo: '1' } }), { errorType: 'parse', errors: [ { error: 'No script with an ID of "test" was provided in the compilation environment.', range: { endColumn: 0, endLineNumber: 0, startColumn: 0, startLineNumber: 0, }, }, ], success: false, }); }); test('compileScript: clean errors on unexpected input', (t) => { t.deepEqual(compileScript('t', {}, { scripts: { t: 'te$t' } }), { errorType: 'parse', errors: [ { error: "Encountered unexpected input while parsing script. Expected the opening parenthesis of this evaluation ('(').", range: { endColumn: 4, endLineNumber: 1, startColumn: 4, startLineNumber: 1, }, }, ], success: false, }); t.deepEqual( compileScript('t', {}, { scripts: { t: '<$(<1> <2> OP_ADD >' } }), { errorType: 'parse', errors: [ { error: "Encountered unexpected input while parsing script. Expected a binary literal ('0b...'), a double quote (\"), a hex literal ('0x...'), a single quote ('), a valid identifier, an integer literal, the closing parenthesis of this evaluation (')'), the start of a multi-line comment ('/*'), the start of a push statement ('<'), the start of a single-line comment ('//'), or the start of an evaluation ('$').", range: { endColumn: 19, endLineNumber: 1, startColumn: 19, startLineNumber: 1, }, }, ], success: false, } ); t.deepEqual(compileScript('t', {}, { scripts: { t: '"incomplete' } }), { errorType: 'parse', errors: [ { error: 'Encountered unexpected input while parsing script. Expected a closing double quote (").', range: { endColumn: 12, endLineNumber: 1, startColumn: 12, startLineNumber: 1, }, }, ], success: false, }); }); test('compileScript: empty string', (t) => { t.deepEqual(compileScript('t', {}, { scripts: { t: '' } }), { bytecode: Uint8Array.of(), parse: { end: { column: 1, line: 1, offset: 0, }, name: 'Script', start: { column: 1, line: 1, offset: 0, }, value: [], }, reduce: { bytecode: Uint8Array.of(), range: { endColumn: 1, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, script: [ { bytecode: Uint8Array.of(), range: { endColumn: 1, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, }, ], }, resolve: [ { range: { endColumn: 1, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, type: 'comment', value: '', }, ], success: true, }); }); test('compileScriptContents: empty string', (t) => { t.deepEqual( compileScriptContents({ data: {}, environment: { scripts: {} }, script: '', }), { bytecode: Uint8Array.of(), parse: { end: { column: 1, line: 1, offset: 0, }, name: 'Script', start: { column: 1, line: 1, offset: 0, }, value: [], }, reduce: { bytecode: Uint8Array.of(), range: { endColumn: 1, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, script: [ { bytecode: Uint8Array.of(), range: { endColumn: 1, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, }, ], }, resolve: [ { range: { endColumn: 1, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, type: 'comment', value: '', }, ], success: true, } ); }); test('compileScriptContents: empty script (script with space)', (t) => { t.deepEqual(compileScript('t', {}, { scripts: { t: ' ' } }), { bytecode: Uint8Array.of(), parse: { end: { column: 5, line: 1, offset: 4, }, name: 'Script', start: { column: 1, line: 1, offset: 0, }, value: [], }, reduce: { bytecode: Uint8Array.of(), range: { endColumn: 5, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, script: [ { bytecode: Uint8Array.of(), range: { endColumn: 5, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, }, ], }, resolve: [ { range: { endColumn: 5, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, type: 'comment', value: '', }, ], success: true, }); }); test('describeExpectedInput: handles EOF', (t) => { t.deepEqual( describeExpectedInput(['one thing', 'EOF']), 'Encountered unexpected input while parsing script. Expected one thing or the end of the script.' ); }); test('describeExpectedInput: handles 2 options', (t) => { t.deepEqual( describeExpectedInput(['one thing', 'another thing']), 'Encountered unexpected input while parsing script. Expected one thing or another thing.' ); }); test('compileScript parse error', (t) => { t.deepEqual(compileScript('t', {}, { scripts: { t: '$' } }), { errorType: 'parse', errors: [ { error: "Encountered unexpected input while parsing script. Expected the opening parenthesis of this evaluation ('(').", range: { endColumn: 2, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], success: false, }); }); test('compileScript: 0x51', (t) => { const result = compileScript('t', {}, { scripts: { t: '0x51' } }); t.deepEqual( result, { bytecode: Uint8Array.of(0x51), parse: { end: { column: 5, line: 1, offset: 4, }, name: 'Script', start: { column: 1, line: 1, offset: 0, }, value: [ { end: { column: 5, line: 1, offset: 4, }, name: 'HexLiteral', start: { column: 1, line: 1, offset: 0, }, value: '51', }, ], }, reduce: { bytecode: Uint8Array.of(0x51), range: { endColumn: 5, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, script: [ { bytecode: Uint8Array.of(0x51), range: { endColumn: 5, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, }, ], }, resolve: [ { literal: '51', literalType: 'HexLiteral', range: { endColumn: 5, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, type: 'bytecode', value: Uint8Array.of(0x51), }, ], success: true, }, stringifyTestVector(result) ); }); test('compileScript: <1>', (t) => { const result = compileScript('t', {}, { scripts: { t: '<1>' } }); t.deepEqual( result, { bytecode: Uint8Array.of(0x51), parse: { end: { column: 4, line: 1, offset: 3, }, name: 'Script', start: { column: 1, line: 1, offset: 0, }, value: [ { end: { column: 4, line: 1, offset: 3, }, name: 'Push', start: { column: 1, line: 1, offset: 0, }, value: { end: { column: 3, line: 1, offset: 2, }, name: 'Script', start: { column: 2, line: 1, offset: 1, }, value: [ { end: { column: 3, line: 1, offset: 2, }, name: 'BigIntLiteral', start: { column: 2, line: 1, offset: 1, }, value: '1', }, ], }, }, ], }, reduce: { bytecode: Uint8Array.of(0x51), range: { endColumn: 4, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, script: [ { bytecode: Uint8Array.of(0x51), push: { bytecode: Uint8Array.of(0x01), range: { endColumn: 3, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, script: [ { bytecode: Uint8Array.of(0x01), range: { endColumn: 3, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], }, range: { endColumn: 4, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, }, ], }, resolve: [ { range: { endColumn: 4, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, type: 'push', value: [ { literal: '1', literalType: 'BigIntLiteral', range: { endColumn: 3, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, type: 'bytecode', value: Uint8Array.of(0x01), }, ], }, ], success: true, }, stringifyTestVector(result) ); }); test('compileScript: <0xabcdef>', (t) => { const result = compileScript('t', {}, { scripts: { t: '<0xabcdef>' } }); t.deepEqual( result, { bytecode: Uint8Array.of(0x03, 0xab, 0xcd, 0xef), parse: { end: { column: 11, line: 1, offset: 10, }, name: 'Script', start: { column: 1, line: 1, offset: 0, }, value: [ { end: { column: 11, line: 1, offset: 10, }, name: 'Push', start: { column: 1, line: 1, offset: 0, }, value: { end: { column: 10, line: 1, offset: 9, }, name: 'Script', start: { column: 2, line: 1, offset: 1, }, value: [ { end: { column: 10, line: 1, offset: 9, }, name: 'HexLiteral', start: { column: 2, line: 1, offset: 1, }, value: 'abcdef', }, ], }, }, ], }, reduce: { bytecode: Uint8Array.of(0x03, 0xab, 0xcd, 0xef), range: { endColumn: 11, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, script: [ { bytecode: Uint8Array.of(0x03, 0xab, 0xcd, 0xef), push: { bytecode: Uint8Array.of(0xab, 0xcd, 0xef), range: { endColumn: 10, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, script: [ { bytecode: Uint8Array.of(0xab, 0xcd, 0xef), range: { endColumn: 10, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], }, range: { endColumn: 11, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, }, ], }, resolve: [ { range: { endColumn: 11, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, type: 'push', value: [ { literal: 'abcdef', literalType: 'HexLiteral', range: { endColumn: 10, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, type: 'bytecode', value: Uint8Array.of(0xab, 0xcd, 0xef), }, ], }, ], success: true, }, stringifyTestVector(result) ); }); test('compileScript: <"abc 👍">', (t) => { const result = compileScript('t', {}, { scripts: { t: '<"abc 👍">' } }); t.deepEqual( result, { bytecode: hexToBin('0861626320f09f918d'), parse: { end: { column: 11, line: 1, offset: 10, }, name: 'Script', start: { column: 1, line: 1, offset: 0, }, value: [ { end: { column: 11, line: 1, offset: 10, }, name: 'Push', start: { column: 1, line: 1, offset: 0, }, value: { end: { column: 10, line: 1, offset: 9, }, name: 'Script', start: { column: 2, line: 1, offset: 1, }, value: [ { end: { column: 10, line: 1, offset: 9, }, name: 'UTF8Literal', start: { column: 2, line: 1, offset: 1, }, value: 'abc 👍', }, ], }, }, ], }, reduce: { bytecode: hexToBin('0861626320f09f918d'), range: { endColumn: 11, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, script: [ { bytecode: hexToBin('0861626320f09f918d'), push: { bytecode: hexToBin('61626320f09f918d'), range: { endColumn: 10, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, script: [ { bytecode: hexToBin('61626320f09f918d'), range: { endColumn: 10, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, }, ], }, range: { endColumn: 11, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, }, ], }, resolve: [ { range: { endColumn: 11, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, type: 'push', value: [ { literal: 'abc 👍', literalType: 'UTF8Literal', range: { endColumn: 10, endLineNumber: 1, startColumn: 2, startLineNumber: 1, }, type: 'bytecode', value: hexToBin('61626320f09f918d'), }, ], }, ], success: true, }, stringifyTestVector(result) ); }); test('compileScript (no identifiers): OP_1', (t) => { t.deepEqual(compileScript('t', {}, { scripts: { t: 'OP_1' } }), { errorType: 'resolve', errors: [ { error: 'Unknown identifier "OP_1".', range: { endColumn: 5, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, }, ], parse: { end: { column: 5, line: 1, offset: 4, }, name: 'Script', start: { column: 1, line: 1, offset: 0, }, value: [ { end: { column: 5, line: 1, offset: 4, }, name: 'Identifier', start: { column: 1, line: 1, offset: 0, }, value: 'OP_1', }, ], }, resolve: [ { range: { endColumn: 5, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, type: 'error', value: 'Unknown identifier "OP_1".', }, ], success: false, }); }); test('compileScript: OP_1 OP_2 OP_ADD', (t) => { t.deepEqual( compileScript( 't', {}, { opcodes: { OP_1: Uint8Array.of(0x51), // eslint-disable-line @typescript-eslint/naming-convention OP_2: Uint8Array.of(0x52), // eslint-disable-line @typescript-eslint/naming-convention OP_ADD: Uint8Array.of(0x93), // eslint-disable-line @typescript-eslint/naming-convention }, scripts: { t: 'OP_1 OP_2 OP_ADD' }, } ), { bytecode: Uint8Array.of(0x51, 0x52, 0x93), parse: { end: { column: 17, line: 1, offset: 16, }, name: 'Script', start: { column: 1, line: 1, offset: 0, }, value: [ { end: { column: 5, line: 1, offset: 4, }, name: 'Identifier', start: { column: 1, line: 1, offset: 0, }, value: 'OP_1', }, { end: { column: 10, line: 1, offset: 9, }, name: 'Identifier', start: { column: 6, line: 1, offset: 5, }, value: 'OP_2', }, { end: { column: 17, line: 1, offset: 16, }, name: 'Identifier', start: { column: 11, line: 1, offset: 10, }, value: 'OP_ADD', }, ], }, reduce: { bytecode: Uint8Array.of(0x51, 0x52, 0x93), range: { endColumn: 17, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, script: [ { bytecode: Uint8Array.of(0x51), range: { endColumn: 5, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, }, { bytecode: Uint8Array.of(0x52), range: { endColumn: 10, endLineNumber: 1, startColumn: 6, startLineNumber: 1, }, }, { bytecode: Uint8Array.of(0x93), range: { endColumn: 17, endLineNumber: 1, startColumn: 11, startLineNumber: 1, }, }, ], }, resolve: [ { opcode: 'OP_1', range: { endColumn: 5, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, type: 'bytecode', value: Uint8Array.of(0x51), }, { opcode: 'OP_2', range: { endColumn: 10, endLineNumber: 1, startColumn: 6, startLineNumber: 1, }, type: 'bytecode', value: Uint8Array.of(0x52), }, { opcode: 'OP_ADD', range: { endColumn: 17, endLineNumber: 1, startColumn: 11, startLineNumber: 1, }, type: 'bytecode', value: Uint8Array.of(0x93), }, ], success: true, } ); }); test('compileScript: variable and script inclusion', (t) => { const comp = compileScript( 't', { bytecode: { varOp2: Uint8Array.of(0x52), }, }, { opcodes: { OP_1: Uint8Array.of(0x51), // eslint-disable-line @typescript-eslint/naming-convention OP_ADD: Uint8Array.of(0x93), // eslint-disable-line @typescript-eslint/naming-convention }, operations: { addressData: compilerOperationAddressData, }, scripts: { pushNumbers: 'OP_1 varOp2', t: 'pushNumbers OP_ADD' }, variables: { varOp2: { description: 'Gets added to OP_1', name: 'OP_2 as a variable', type: 'AddressData', }, }, } ); t.deepEqual(comp, { bytecode: Uint8Array.of(0x51, 0x52, 0x93), parse: { end: { column: 19, line: 1, offset: 18, }, name: 'Script', start: { column: 1, line: 1, offset: 0, }, value: [ { end: { column: 12, line: 1, offset: 11, }, name: 'Identifier', start: { column: 1, line: 1, offset: 0, }, value: 'pushNumbers', }, { end: { column: 19, line: 1, offset: 18, }, name: 'Identifier', start: { column: 13, line: 1, offset: 12, }, value: 'OP_ADD', }, ], }, reduce: { bytecode: Uint8Array.of(0x51, 0x52, 0x93), range: { endColumn: 19, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, script: [ { bytecode: Uint8Array.of(0x51, 0x52), range: { endColumn: 12, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, }, { bytecode: Uint8Array.of(0x93), range: { endColumn: 19, endLineNumber: 1, startColumn: 13, startLineNumber: 1, }, }, ], }, resolve: [ { range: { endColumn: 12, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, script: 'pushNumbers', source: [ { opcode: 'OP_1', range: { endColumn: 5, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, type: 'bytecode', value: Uint8Array.of(0x51), }, { range: { endColumn: 12, endLineNumber: 1, startColumn: 6, startLineNumber: 1, }, type: 'bytecode', value: Uint8Array.of(0x52), variable: 'varOp2', }, ], type: 'bytecode', value: Uint8Array.of(0x51, 0x52), }, { opcode: 'OP_ADD', range: { endColumn: 19, endLineNumber: 1, startColumn: 13, startLineNumber: 1, }, type: 'bytecode', value: Uint8Array.of(0x93), }, ], success: true, }); }); test('compileScript: comments', (t) => { t.deepEqual( compileScript( 't', {}, { scripts: { t: '// single-line\n /* multi-\nline */' } } ), { bytecode: Uint8Array.of(), parse: { end: { column: 8, line: 3, offset: 34, }, name: 'Script', start: { column: 1, line: 1, offset: 0, }, value: [ { end: { column: 15, line: 1, offset: 14, }, name: 'Comment', start: { column: 1, line: 1, offset: 0, }, value: 'single-line', }, { end: { column: 8, line: 3, offset: 34, }, name: 'Comment', start: { column: 3, line: 2, offset: 17, }, value: 'multi-\nline', }, ], }, reduce: { bytecode: Uint8Array.of(), range: { endColumn: 8, endLineNumber: 3, startColumn: 1, startLineNumber: 1, }, script: [ { bytecode: Uint8Array.of(), range: { endColumn: 15, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, }, { bytecode: Uint8Array.of(), range: { endColumn: 8, endLineNumber: 3, startColumn: 3, startLineNumber: 2, }, }, ], }, resolve: [ { range: { endColumn: 15, endLineNumber: 1, startColumn: 1, startLineNumber: 1, }, type: 'comment', value: 'single-line', }, { range: { endColumn: 8, endLineNumber: 3, startColumn: 3, startLineNumber: 2, }, type: 'comment', value: 'multi-\nline', }, ], success: true, } ); });
the_stack
import React from "react"; import * as d3 from "d3"; import style from "../hiplot.scss"; import { create_d3_scale_without_outliers, ParamDef } from "../infertypes"; import { foCreateAxisLabel, foDynamicSizeFitContent } from "../lib/svghelpers"; import { ParamType, Datapoint } from "../types"; const margin = {top: 20, right: 20, bottom: 50, left: 60}; interface BinsDrawData { bins: d3.Bin<any, any>[]; g: SVGSVGElement; draw_fn: any; }; export interface HistogramData { all: Datapoint[]; selected: Datapoint[]; }; export interface DistributionPlotData { height: number, width: number, nbins: number, axis: string, histData: HistogramData; param_def: ParamDef; animateMs: number; }; // Inspired by https://www.d3-graph-gallery.com/graph/histogram_binSize.html export class DistributionPlot extends React.Component<DistributionPlotData, {}> { /** * Supports both vertical and horizontal bar plots. * Will switch to vertical if we are plotting categorical data with too many distinct values. */ axisBottom = React.createRef<SVGSVGElement>(); axisLeft = React.createRef<SVGSVGElement>(); axisRight = React.createRef<SVGSVGElement>(); axisBottomName = React.createRef<SVGGElement>(); svgContainer = React.createRef<SVGSVGElement>(); histAll = React.createRef<SVGSVGElement>(); histSelected = React.createRef<SVGSVGElement>(); dataScale: any; isVertical() { /* Vertical: | -- | __ || | || || ... +-------------- Horizontal: | ========= | ====== | == +-------------- */ return (this.props.param_def.type != ParamType.CATEGORICAL || this.props.param_def.distinct_values.length < 3); } figureWidth() { return this.props.width - margin.left - margin.right; } figureHeight() { return this.props.height - margin.top - margin.bottom; } createDataAxis(dataScale: any, animate: boolean): void { if (this.isVertical()) { dataScale.range([0, this.figureWidth()]); d3.select(this.axisBottom.current).call(d3.axisBottom(dataScale).ticks(1 + this.props.width/50)); d3.select(this.axisBottomName.current).html(null).append(function() { return foCreateAxisLabel(this.props.param_def, null, null); }.bind(this)) .classed("distrplot_axislabel", true) .attr("x", -4) .attr("text-anchor", "end"); d3.select(this.axisBottomName.current).select(".distrplot_axislabel") .each(function(this: SVGForeignObjectElement) { foDynamicSizeFitContent(this); }); this.axisRight.current.innerHTML = ''; } else { dataScale.range([this.figureHeight(), 0]); d3.select(this.axisRight.current) .transition() .duration(animate ? this.props.animateMs : 0) .call(d3.axisRight(dataScale).ticks(1 + this.props.height/50)) .attr("text-anchor", "end"); d3.select(this.axisLeft.current) .transition() .duration(animate ? this.props.animateMs : 0) .call(d3.axisLeft(dataScale).ticks(1 + this.props.height/50)); } } createDataScaleAndAxis(): void { this.dataScale = create_d3_scale_without_outliers(this.props.param_def); this.createDataAxis(this.dataScale, false); } createHistogram(): d3.HistogramGeneratorNumber<any, any> { const me = this; const scaleCopy = this.dataScale.copy().range([0, 1]); var thresholds = []; if (this.props.param_def.type == ParamType.CATEGORICAL) { thresholds = this.props.param_def.distinct_values.map((v) => scaleCopy(v)); thresholds = thresholds.map((value, index) => index == 0 ? value : (value + thresholds[index - 1]) / 2); } else { for (var i = 1; i < this.props.nbins; ++i) { thresholds.push(i / this.props.nbins); } } var histogram = d3.histogram() .value(function(d) { return scaleCopy(d[me.props.axis]); }) .domain([0, 1]) .thresholds(thresholds); return histogram; } drawAllHistograms(animate: boolean) { const histogram = this.createHistogram(); var allHist: {selected: BinsDrawData, all: BinsDrawData} = { selected: { bins: histogram(this.props.histData.selected), g: this.histAll.current, draw_fn: this.drawHistogramRects.bind(this), }, all: { bins: histogram(this.props.histData.all), g: this.histSelected.current, draw_fn: this.drawHistogramLines.bind(this), } }; // Density axis: set max based on maximum in histogram const maxDensityHistogram = d3.max(Object.values(allHist), function(hist) { const total = d3.sum(hist.bins, (d) => d.length); if (!total) { return 0; } return d3.max(hist.bins, (d) => d.length / total); }); var densityScale = d3.scaleLinear() .domain([0, maxDensityHistogram]); var binsOrdering = allHist.all.bins.map((_, i) => i); if (this.isVertical()) { densityScale = densityScale.range([this.figureHeight(), 0]) d3.select(this.axisLeft.current) .transition() .duration(animate ? this.props.animateMs : 0) .call(d3.axisLeft(densityScale) .ticks(1 + this.props.height/50) .tickSizeInner(-(this.props.width - margin.left - margin.right)) ); } else { densityScale = densityScale.range([0, this.figureWidth()]) d3.select(this.axisBottom.current) .transition() .duration(animate ? this.props.animateMs : 0) .call(d3.axisBottom(densityScale).ticks(1 + this.props.width/50)); // Compute reordering of the bins - we want to display higher densities first. var ordered1 = Array.from(binsOrdering).sort((a, b) => allHist.selected.bins[a].length - allHist.selected.bins[b].length); ordered1.forEach(function(value, idx) { binsOrdering[value] = idx; }); // Update ticks/axis as well var domain: string[] = this.dataScale.domain(); var domainsOrdered = domain.map(function(v, idx) { return domain[ordered1[idx]]; }); this.createDataAxis(d3.scalePoint().domain(domainsOrdered).range(this.dataScale.range()), true); } // Draw all the histograms Object.values(allHist).forEach(function(v) { v.draw_fn(v, densityScale, animate, binsOrdering); }.bind(this)) } drawHistogramLines(hist: BinsDrawData, densityScale: d3.ScaleLinear<number, number>, animate: boolean, binsOrdering: number[]) { const total = d3.sum(hist.bins, (d) => d.length); const densityScaleFromLength = (d) => densityScale(total ? d.length / total : 0); const dataScale = d3.scaleLinear().range(this.dataScale.range()); var u = d3.select(hist.g).selectAll<SVGLineElement, any>("line") .data(hist.bins); const dataCoord = this.isVertical() ? "x" : "y"; const densityCoord = this.isVertical() ? "y" : "x"; u .enter() .append("line") // Add a new rect for each new elements .merge(u) // get the already existing elements as well .transition() // and apply changes to all of them .duration(animate ? this.props.animateMs : 0) .attr(`${dataCoord}1`, (d, i) => dataScale(hist.bins[binsOrdering[i]].x0) + 1) .attr(`${densityCoord}1`, (d, i) => densityScaleFromLength(d)) .attr(`${dataCoord}2`, (d, i) => dataScale(hist.bins[binsOrdering[i]].x1)) .attr(`${densityCoord}2`, (d, i) => densityScaleFromLength(d)); u .exit() .remove(); } drawHistogramRects(hist: BinsDrawData, densityScale: d3.ScaleLinear<number, number>, animate: boolean, binsOrdering: number[]) { const total = d3.sum(hist.bins, (d) => d.length); const densityScaleFromLength = (d) => densityScale(total ? d.length / total : 0); const dataScale = d3.scaleLinear().range(this.dataScale.range()); var u = d3.select(hist.g).selectAll<SVGRectElement, any>("rect") .data(hist.bins); var ut = u .enter() .append("rect") // Add a new rect for each new elements .merge(u) // get the already existing elements as well .attr("data-value-sample", function(d, i) { return d.length ? d[0][this.props.axis] : "empty"}.bind(this)) .on('mouseover', function (d, i) { d3.select(this).transition() .duration(150) .attr('opacity', '.5'); }) .on('mouseout', function (d, i) { d3.select(this).transition() .duration(150) .attr('opacity', '1'); }) .transition() // and apply changes to all of them .duration(animate ? this.props.animateMs : 0); if (this.isVertical()) { ut .attr("x", 1) .attr("transform", function(d) { return "translate(" + dataScale(d.x0) + "," + densityScaleFromLength(d) + ")"; }) .attr("width", function(d) { return dataScale(d.x1) - dataScale(d.x0) -1 ; }) .attr("height", function(d) { return this.figureHeight() - densityScaleFromLength(d); }.bind(this)); } else { ut //.attr("y", 1) .attr("transform", function(d, i) { return "translate(0," + dataScale(hist.bins[binsOrdering[i]].x1) + ")"; }) .attr("width", function(d) { return densityScaleFromLength(d); }) .attr("height", function(d, i) { const delta = Math.abs(dataScale(hist.bins[binsOrdering[i]].x1) - dataScale(hist.bins[binsOrdering[i]].x0)); return delta > 2 ? delta - 1 : delta; }.bind(this)); } u .exit() .remove(); } componentDidMount() { this.createDataScaleAndAxis(); this.drawAllHistograms(false); } componentDidUpdate(prevProps: DistributionPlotData, prevState: {}) { if (prevProps.axis != this.props.axis || prevProps.param_def != this.props.param_def || prevProps.width != this.props.width || prevProps.height != this.props.height) { this.createDataScaleAndAxis(); } if (prevProps.axis != this.props.axis || prevProps.param_def != this.props.param_def || prevProps.nbins != this.props.nbins || prevProps.histData != this.props.histData || prevProps.width != this.props.width || prevProps.height != this.props.height) { const animate = prevProps.nbins != this.props.nbins || prevProps.histData != this.props.histData; this.drawAllHistograms(animate); } } render() { const leftAxisLabel = this.isVertical() ? "Density" : this.props.axis; return (<div> <svg width={this.props.width} height={this.props.height}> <g transform={`translate(${margin.left}, 15)`} textAnchor="start" fontWeight="bold"> <text style={{stroke: "white", strokeWidth: "0.2em"}}>{leftAxisLabel}</text> <text>{leftAxisLabel}</text> </g> <g ref={this.svgContainer} className={style['distr-graph-svg']} transform={`translate(${margin.left}, ${margin.top})`}> <g className={style.histAll} ref={this.histAll}></g> <g className={style.histSelected} ref={this.histSelected}></g> <g className="axisLeft" ref={this.axisLeft}></g> <g className="axisRight" ref={this.axisRight} transform={`translate(${this.figureWidth()}, 0)`}></g> <g className="axisBottom" ref={this.axisBottom} transform={`translate(0, ${this.figureHeight()})`}></g> <g ref={this.axisBottomName} transform={`translate(${this.figureWidth()}, ${this.props.height - margin.top - 30})`} textAnchor="end" fontWeight="bold"> </g> </g> </svg> </div>); } };
the_stack
import { BotConfiguration, BotRecipe, IBlobResource, IBlobStorageService, IConnectedService, ICosmosDBResource, ICosmosDBService, IDispatchResource, IDispatchService, IEndpointService, IFileResource, IFileService, IGenericResource, IGenericService, ILuisService, IQnAService, IResource, IUrlResource, ServiceTypes } from 'botframework-config'; import * as chalk from 'chalk'; import * as program from 'commander'; import * as fsx from 'fs-extra'; import * as process from 'process'; import { spawnAsync } from './processUtils'; import { regionToLuisAuthoringRegionMap } from './utils'; export interface ExportOptions { // should resources be downloaded info folder download: boolean; // progress callback during export progress?: (service: IConnectedService, command: string, index: number, total: number) => void } program.Command.prototype.unknownOption = (flag: string): void => { console.error(chalk.default.redBright(`Unknown arguments: ${flag}`)); program.help(); }; interface IExportArgs { bot: string; folder: string; secret: string; quiet: boolean; verbose: boolean; args: string[]; } program .name('msbot export services') .description('export all of the connected services to local folder with .bot.recipe file to support cloning') .option('-f, --folder <folder>', 'path to folder to place exported resources') .option('--verbose', 'show verbose export information') .option('-q, --quiet', 'disable output') .option('-b, --bot <path>', 'path to bot file. If omitted, local folder will look for a .bot file') .option('--secret <secret>', 'bot file secret password for encrypting service secrets') .option('--prefix', 'Append [msbot] prefix to all messages') .action((cmd: program.Command, actions: program.Command) => undefined); const command: program.Command = program.parse(process.argv); const args: IExportArgs = <IExportArgs>{}; Object.assign(args, command); args.verbose = process.env.VERBOSE === 'verbose'; if (!args.bot) { BotConfiguration.loadBotFromFolder(process.cwd(), args.secret) .then(processConfiguration) .catch((reason: Error) => { console.error(chalk.default.redBright(reason.toString().split('\n')[0])); showErrorHelp(); }); } else { BotConfiguration.load(args.bot, args.secret) .then(processConfiguration) .catch((reason: Error) => { console.error(chalk.default.redBright(reason.toString().split('\n')[0])); showErrorHelp(); }); } async function processConfiguration(config: BotConfiguration): Promise<void> { if (!args.folder) { throw new Error('missing --folder argument'); } try { const recipe: BotRecipe = await exportBot(config, args.folder, { progress: (service: IConnectedService, newCommand: string, index: number, total: number): void => { if (!args.quiet) { const output: string = `exporting ${chalk.default.bold(service.name)} [${service.type}] (${index}/${total})`; if (args.verbose) { console.warn(chalk.default.bold(output)); console.log(chalk.default.italic(`${newCommand}\n`)); } else { console.warn(output); } } } }); } catch (error) { const lines: string[] = error.message.split('\n'); for (const line of lines) { // trim to copywrite symbol, help from inner process command line args is inappropriate if (line.indexOf('©') > 0) { process.exit(1); } console.error(chalk.default.redBright(line)); } } } // export the services from the bot file as resource files and recipe file async function exportBot(config: BotConfiguration, folder: string, exportOptions?: Partial<ExportOptions>): Promise<BotRecipe> { let options = Object.assign({ download: true }, exportOptions); let recipe = new BotRecipe(); await fsx.ensureDir(folder); let index = 0; for (let service of config.services) { index++; switch (service.type) { case ServiceTypes.Dispatch: { await exportLuisService(service); let dispatchResource: IDispatchResource = { type: service.type, id: service.id, name: service.name, serviceIds: (<IDispatchService>service).serviceIds }; recipe.resources.push(dispatchResource); } break; case ServiceTypes.Luis: { await exportLuisService(service); let resource: IResource = { type: service.type, id: service.id, name: service.name }; recipe.resources.push(resource); } break; case ServiceTypes.QnA: { let qnaService = <IQnAService>service; if (options.download) { let command = `qnamaker export kb --kbId ${qnaService.kbId} --environment prod --subscriptionKey ${qnaService.subscriptionKey} --hostname ${qnaService.hostname} --endpointKey ${qnaService.endpointKey}`; if (options.progress) { options.progress(service, command, index, config.services.length); } let json = ''; await spawnAsync(command, (stdout) => json += stdout, (stderr) => console.error(stderr)); // make sure it's json JSON.parse(json); await fsx.writeFile(folder + `/${qnaService.id}.qna`, json, { encoding: 'utf8' }); } else { if (options.progress) { options.progress(service, '', index, config.services.length); } } let resource: IResource = { type: service.type, id: service.id, name: service.name }; recipe.resources.push(resource); } break; case ServiceTypes.Endpoint: { if (options.progress) { options.progress(service, '', index, config.services.length); } let endpointResource: IUrlResource = { type: ServiceTypes.Endpoint, id: service.id, name: service.name, url: (<IEndpointService>service).endpoint }; recipe.resources.push(endpointResource); } break; case ServiceTypes.BlobStorage: { if (options.progress) { options.progress(service, '', index, config.services.length); } let blobResource: IBlobResource = { type: ServiceTypes.BlobStorage, id: service.id, name: service.name, container: (<IBlobStorageService>service).container || '' }; recipe.resources.push(blobResource); } break; case ServiceTypes.CosmosDB: { if (options.progress) { options.progress(service, '', index, config.services.length); } let cosmosDBResource: ICosmosDBResource = { type: ServiceTypes.CosmosDB, id: service.id, name: service.name, database: (<ICosmosDBService>service).database, collection: (<ICosmosDBService>service).collection, }; recipe.resources.push(cosmosDBResource); } break; case ServiceTypes.File: { if (options.progress) { options.progress(service, '', index, config.services.length); } let fileResource: IFileResource = { type: ServiceTypes.File, id: service.id, name: service.name, path: (<IFileService>service).path, }; recipe.resources.push(fileResource); } break; case ServiceTypes.Generic: { if (options.progress) { options.progress(service, '', index, config.services.length); } console.warn(`WARNING: Generic services cannot be cloned and all configuration data will be passed unchanged and unencrypted `); let genericService = <IGenericService>service; let genericResource: IGenericResource = { type: ServiceTypes.Generic, id: service.id, name: service.name, url: genericService.url, configuration: genericService.configuration, }; recipe.resources.push(genericResource); } break; case ServiceTypes.Bot: { if (options.progress) { options.progress(service, '', index, config.services.length); } let resource: IResource = { type: service.type, id: service.id, name: service.name }; recipe.resources.push(resource); } break; case ServiceTypes.AppInsights: { if (options.progress) { options.progress(service, '', index, config.services.length); } let resource: IResource = { type: service.type, id: service.id, name: service.name }; recipe.resources.push(resource); } break; default: if (options.progress) { options.progress(service, '', index, config.services.length); } console.warn(`WARNING: Unknown service type [${service.type}]. This service will not be exported.`); break; } } await fsx.writeFile(folder + `/bot.recipe`, JSON.stringify(recipe, null, 2), { encoding: 'utf8' }); return recipe; async function exportLuisService(service: IConnectedService) { let luisService = <ILuisService>service; if (options.download) { const luisAuthoringRegion = regionToLuisAuthoringRegionMap[luisService.region]; let command = `luis export version --region ${luisAuthoringRegion} --appId ${luisService.appId} --authoringKey ${luisService.authoringKey} --versionId "${luisService.version}"`; if (options.progress) { options.progress(service, command, index, config.services.length); } let json = ''; await spawnAsync(command, (stdout) => json += stdout, (stderr) => console.error(stderr)); // make sure it's json try { JSON.parse(json); } catch(err) { throw new Error(`${err.message || err}\n${json}`); } await fsx.writeFile(folder + `/${luisService.id}.luis`, json, { encoding: 'utf8' }); } else { if (options.progress) { options.progress(service, '', index, config.services.length); } } } } function showErrorHelp(): void { program.outputHelp((str: string) => { console.error(str); return ''; }); process.exit(1); }
the_stack
export default function makeDashboard(integrationId: string) { return { annotations: { list: [ { builtIn: 1, datasource: "-- Grafana --", enable: true, hide: true, iconColor: "rgba(0, 211, 255, 1)", name: "Annotations & Alerts", type: "dashboard" } ] }, editable: true, gnetId: null, graphTooltip: 0, iteration: 1623959942178, links: [], panels: [ { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The total number of open SQL Sessions.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 0 }, hiddenSeries: false, id: 2, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sql_conns{integration_id="${integrationId}",instance=~"$node"}`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "B" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Open SQL Sessions", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:108", format: "short", label: "connections", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:109", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The total number of SQL transactions currently open.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 8 }, hiddenSeries: false, id: 30, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sql_txns_open{integration_id="${integrationId}",instance=~"$node"}`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Open SQL Transactions", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:279", format: "short", label: "transactions", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:280", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The total number of SQL statements currently running.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 16 }, hiddenSeries: false, id: 10, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(sql_distsql_queries_active{integration_id="${integrationId}",cluster=~"$cluster",instance=~"$node"})`, interval: "", intervalFactor: 2, legendFormat: "Active Statements", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Active SQL Statements", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:184", format: "short", label: "queries", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:185", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The total amount of SQL client network traffic in bytes per second.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 24 }, hiddenSeries: false, id: 4, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(rate(sql_bytesin{integration_id="${integrationId}",instance=~"$node"}[5m]))`, instant: false, interval: "", intervalFactor: 2, legendFormat: "Bytes In", refId: "A" }, { exemplar: true, expr: `sum(rate(sql_bytesout{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Bytes Out", refId: "B" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "SQL Byte Traffic", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:260", format: "bytes", label: "byte traffic", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:261", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "A moving average of the # of SELECT, INSERT, UPDATE, and DELETE statements successfully executed per second.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 32 }, hiddenSeries: false, id: 6, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(rate(sql_select_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Selects", refId: "A" }, { exemplar: true, expr: `sum(rate(sql_update_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Updates", refId: "B" }, { exemplar: true, expr: `sum(rate(sql_insert_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Inserts", refId: "C" }, { exemplar: true, expr: `sum(rate(sql_delete_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Deletes", refId: "D" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "SQL Statements", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:336", format: "short", label: "queries", logBase: 1, max: null, min: null, show: true }, { $$hashKey: "object:337", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of statements which returned a planning or runtime error.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 40 }, hiddenSeries: false, id: 8, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(rate(sql_failure_count{integration_id="${integrationId}",cluster=~"$cluster",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Errors", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "SQL Statement Errors", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:412", format: "short", label: "errors", logBase: 1, max: "1", min: "0", show: true }, { $$hashKey: "object:413", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The total number of SQL statements that experienced contention.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 48 }, hiddenSeries: false, id: 32, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(rate(sql_distsql_contended_queries_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "Contention", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "SQL Statement Contention", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:489", format: "short", label: "queries", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:490", format: "short", label: "", logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of flows on each node contributing to currently running distributed SQL statements.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 56 }, hiddenSeries: false, id: 12, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `rate(sql_distsql_flows_active{integration_id="${integrationId}",cluster=~"$cluster",instance=~"$node"}[5m])`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Active Flows for Distributed SQL Statements", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:107", format: "short", label: "flows", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:108", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Over the last minute, this node executed 99% of queries within this time. This time does not include network latency between the node and client.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 64 }, hiddenSeries: false, id: 14, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `histogram_quantile(0.99, rate(sql_service_latency_bucket{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Service Latency: SQL, 99th percentile", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:710", format: "ns", label: "latency", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:711", format: "short", label: "", logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Over the last minute, this node executed 90% of queries within this time. This time does not include network latency between the node and client.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 72 }, hiddenSeries: false, id: 16, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `histogram_quantile(0.90, rate(sql_service_latency_bucket{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Service Latency: SQL, 90th percentile", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:934", format: "ns", label: "latency", logBase: 1, max: null, min: null, show: true }, { $$hashKey: "object:935", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The 99th percentile of latency between query requests and responses over a 1 minute period. Values are displayed individually for each node.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 80 }, hiddenSeries: false, id: 18, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `histogram_quantile(0.99,rate(exec_latency_bucket{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "KV Execution Latency: 99th percentile", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1084", format: "µs", label: "latency", logBase: 1, max: null, min: null, show: true }, { $$hashKey: "object:1085", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The 90th percentile of latency between query requests and responses over a 1 minute period. Values are displayed individually for each node.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 88 }, hiddenSeries: false, id: 20, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `histogram_quantile(0.90, rate(exec_latency_bucket{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "KV Execution Latency: 90th percentile", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1160", format: "ns", label: "latency", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1161", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The total number of transactions initiated, committed, rolled back, or aborted per second.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 96 }, hiddenSeries: false, id: 22, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum(rate(sql_txn_begin_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Begin", refId: "A" }, { exemplar: true, expr: `sum(rate(sql_txn_commit_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Commits", refId: "B" }, { exemplar: true, expr: `sum(rate( sql_txn_rollback_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Rollbacks", refId: "D" }, { exemplar: true, expr: `sum(rate(sql_txn_abort_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Aborts", refId: "C" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Transactions", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1458", format: "short", label: "latency", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1459", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The 99th percentile of total transaction time over a 1 minute period. Values are displayed individually for each node.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 104 }, hiddenSeries: false, id: 26, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `histogram_quantile(0.99,rate(sql_txn_latency_bucket{integration_id="${integrationId}"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Transaction Latency: 99th percentile", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1756", format: "µs", label: "latency", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1757", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The 90th percentile of total transaction time over a 1 minute period. Values are displayed individually for each node.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 112 }, hiddenSeries: false, id: 28, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `histogram_quantile(0.90,rate(sql_txn_latency_bucket{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Transaction Latency: 90th percentile", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1832", format: "ns", label: "latency", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1833", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The current amount of allocated SQL memory. This amount is what is compared against the node's --max-sql-memory flag.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 120 }, hiddenSeries: false, id: 34, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sql_mem_root_current{integration_id="${integrationId}",instance=~"$node"}`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "SQL Memory", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:157", format: "bytes", label: "allocation bytes", logBase: 1, max: null, min: null, show: true }, { $$hashKey: "object:158", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The total number of DDL statements per second", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 128 }, hiddenSeries: false, id: 24, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(rate(sql_ddl_count{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "DDL Statements", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Schema Changes", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1908", format: "short", label: "statements", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1909", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The total number of statements denied per second due to a [cluster setting](https://www.cockroachlabs.com/docs/v21.1/cluster-settings.html) in the format feature.statement_type.enabled = FALSE.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 136 }, hiddenSeries: false, id: 36, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `rate(sql_feature_flag_denial{integration_id="${integrationId}",instance=~"$node"}[5m])`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeRegions: [], title: "Statement Denials: Cluster Settings", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:214", format: "short", label: "statements", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:215", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } } ], refresh: false, schemaVersion: 27, style: "dark", tags: [], templating: { list: [ { allValue: "", current: { selected: false, text: "All", value: "$__all" }, datasource: "metrics", definition: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, description: null, error: null, hide: 0, includeAll: true, label: "Node", multi: false, name: "node", options: [], query: { query: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, refId: "Prometheus-node-Variable-Query" }, refresh: 1, regex: "", skipUrlSync: false, sort: 3, tagValuesQuery: "", tags: [], tagsQuery: "", type: "query", useTags: false } ] }, time: { from: "now-1h", to: "now" }, timepicker: {}, timezone: "utc", title: "CRDB Console: SQL", uid: `sql-${integrationId}`, version: 2 }; } export type Dashboard = ReturnType<typeof makeDashboard>;
the_stack
import { Component, OnInit, OnDestroy } from '@angular/core'; import {Subscription} from 'rxjs/Subscription'; import { environment } from './../../../../../environments/environment'; import {LoggerService} from '../../../../shared/services/logger.service'; import {UtilsService} from '../../../../shared/services/utils.service'; import { CommonResponseService } from '../../../../shared/services/common-response.service'; import {RefactorFieldsService} from '../../../../shared/services/refactor-fields.service'; import { FormGroup, FormControl, Validators, NgForm } from '@angular/forms'; import { FormService } from '../../../../shared/services/form.service'; import { HttpHeaders } from '@angular/common/http'; import {WorkflowService} from '../../../../core/services/workflow.service'; import { ToastObservableService } from '../../../../post-login-app/common/services/toast-observable.service'; import * as _ from 'lodash'; import {ActivatedRoute, Router} from '@angular/router'; @Component({ selector: 'app-config-management', templateUrl: './config-management.component.html', styleUrls: ['./config-management.component.css'] }) export class ConfigManagementComponent implements OnInit, OnDestroy { pageTitle: String = 'Configuration Management'; breadcrumbDetails = { breadcrumbArray: ['Admin'], breadcrumbLinks: ['policies'], breadcrumbPresent: 'Configuration' }; errorMessage = 'apiResponseError'; dataSubscription: Subscription; configPropertySubscription: Subscription; updateSubscription: Subscription; applyActive1 = -1; applyActive2 = -1; applyActive3 = -1; activeColumn = 0; editProperty= false; showPreview = false; formData; overrideFormData = []; editData: any; originalData: any; previousEditedData: any; errorValue = 0; // Reactive-forms private configManagementForm: FormGroup; public overrideFormGroup = {}; public formErrors = {}; public formGroup = {}; firstLevelIndex: any; secondLevelIndex: any; thirdLevelIndex: any; fourthLevelIndex: any; firstLevelData = {}; secondaryLevelData = {}; tertiaryLevelData = {}; applicationBreadcrumb = []; showConfBox = { 'value': false, 'modified': { 'columnIndex': 0 }, 'isConfigColumnModified': false, 'isOverridenAlreadyExist': false, 'showContinueBtn': 1, 'isEditPageCancelBtnClick': false, 'confirmDelete': false, 'resetToView': false }; editColumnIndex = -1; overiddenData = []; filterData: {}; showLoader = true; showError = false; createNew = false; transactionObj = { type: '', title: '', message: '', obj1: { type: '', title: '', message: '' } }; transactionResponse = { updatedConfig: { success: false, error: false }, createdConfig: { success: false, error: false }, deleteConfig: { success: false, error: false }, rollbackConfig: { success: false, error: false }, responseCount: 0 }; configKeys = { errorValue: 0, value: [], errorMessage: 'apiResponseError' }; configAudit = { errorValue: 0, value: [], errorMessage: 'apiResponseError' }; deletePayLoadOnhold = {}; deleteFieldInProgress = false; updateInProgress = false; deleteTransactionResponse; confirmationMessage; historyPreview: any; showHistoryPreview = false; showDropdown = false; activeHistoryTile = -1; userRemarks = ''; showUserRemarks = false; backButtonRequired: boolean; pageLevel = 0; public checkBoxSelectedCount = new Array<number>(); constructor(private router: Router, private workflowService: WorkflowService, private commonResponseService: CommonResponseService, private logger: LoggerService, private utils: UtilsService, private refactorFieldsService: RefactorFieldsService, private formService: FormService, private toastObservableService: ToastObservableService) { this.getConfigKeys(); this.updateComponent(); } ngOnInit() { this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently(this.pageLevel); } updateComponent() { /* Updates the whole component */ this.reset(); this.getHistory(); this.getData(); } reset() { this.errorValue = 0; this.firstLevelData = {}; this.secondaryLevelData = {}; this.tertiaryLevelData = {}; this.applyActive1 = -1; this.activeColumn = 0; this.editProperty = false; this.showPreview = false; this.editData = []; this.originalData = []; this.previousEditedData = []; this.applicationBreadcrumb = []; this.resetEditConfig(); this.transactionResponse = { updatedConfig: { success: false, error: false }, createdConfig: { success: false, error: false }, deleteConfig: { success: false, error: false }, rollbackConfig: { success: false, error: false }, responseCount: 0 }; this.transactionObj = { type: '', title: '', message: '', obj1: { type: '', title: '', message: '' } }; this.confirmationMessage = ''; this.deleteTransactionResponse = null; this.showHistoryPreview = false; this.activeHistoryTile = -1; this.userRemarks = ''; this.showUserRemarks = false; } navigateBack() { try { this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root); } catch (error) { this.logger.log('error', error); } } getData() { try { const configUrl = environment.getConfigProperties.url; const configMethod = environment.getConfigProperties.method; this.dataSubscription = this.commonResponseService .getData(configUrl, configMethod, {}, {}) .subscribe( response => { try { if (this.utils.checkIfAPIReturnedDataIsEmpty(response)) { this.errorValue = -1; this.errorMessage = 'noDataAvailable'; } else { this.errorValue = 1; this.filterData = response.applications; this.storeFirstLevel(this.filterData[0], 0); } } catch (e) { this.errorValue = -1; this.errorMessage = 'jsError'; this.logger.log('error', e); } }, error => { this.errorValue = -1; this.errorMessage = 'apiResponseError'; this.logger.log('error', error); }); } catch (error) { this.logger.log('error', error); } } storeFirstLevel(data, index, event?) { try { this.applyActive1 = index; if (this.editProperty) { this.showConfBox.modified = { 'columnIndex': 1 }; this.showConfBox.isConfigColumnModified = true; this.showConfBox.isOverridenAlreadyExist = false; this.confirmationMessage = this.confirmationCondition(); this.showConfBox.value = true; return; } this.activeColumn = 1; this.firstLevelIndex = index; this.firstLevelData = {}; this.secondaryLevelData = {}; this.applicationBreadcrumb = []; if (data == null || data.length === 0) { this.firstLevelData = {}; } else { this.firstLevelData = data; // remove duplicates from properties this.firstLevelData['properties'] = _.uniqBy(this.firstLevelData['properties'], 'key'); this.applicationBreadcrumb.push(this.firstLevelData['name']); } } catch (error) { this.logger.log('error', error); } } storeSecondLevel(data, index) { try { this.applyActive2 = index; if (this.editProperty) { this.showConfBox.resetToView = true; this.showConfBox.modified = { 'columnIndex': 2 }; this.showConfBox.isConfigColumnModified = true; this.showConfBox.isOverridenAlreadyExist = false; this.confirmationMessage = this.confirmationCondition(); this.showConfBox.value = true; return; } this.activeColumn = 2; this.checkBoxSelectedCount = []; this.secondLevelIndex = index; this.secondaryLevelData = {}; this.applicationBreadcrumb = []; if (data == null || data.length === 0) { this.secondaryLevelData = {}; } else { this.secondaryLevelData = data; // remove duplicates from properties this.secondaryLevelData['properties'] = _.uniqBy(this.secondaryLevelData['properties'], 'key'); this.applicationBreadcrumb.push( this.firstLevelData['name'], this.secondaryLevelData['name'] ); } } catch (error) { this.logger.log('error', error); } } storeThirdLevel(data, index) { try { this.applyActive3 = index; if (this.editProperty) { this.showConfBox.resetToView = true; this.showConfBox.modified = { 'columnIndex': 3 }; this.showConfBox.isConfigColumnModified = true; this.showConfBox.isOverridenAlreadyExist = false; this.confirmationMessage = this.confirmationCondition(); this.showConfBox.value = true; return; } this.activeColumn = 3; this.thirdLevelIndex = index; this.tertiaryLevelData = data; // remove duplicates from properties this.tertiaryLevelData['properties'] = _.uniqBy(this.tertiaryLevelData['properties'], 'key'); this.applicationBreadcrumb = []; this.applicationBreadcrumb.push( this.firstLevelData['name'], this.secondaryLevelData['name'], this.tertiaryLevelData['name'] ); } catch (error) { this.logger.log('error', error); } } buildForm(application, index) { this.originalData = JSON.parse(JSON.stringify(application)); this.editData = JSON.parse(JSON.stringify(application)); const data = application.properties; this.editColumnIndex = index; this.formData = []; this.formGroup = {}; for (let i = 0; i < data.length; i++) { let individualField = { formControlName: data[i].key, formControlDisplayName: this.refactorFieldsService.getDisplayNameForAKey( data[i].key.toLocaleLowerCase() ) || data[i].key }; if (data[i].description) { individualField = Object.assign({'metadata': data[i].description}, individualField); } this.formData.push(individualField); this.formGroup[data[i].key] = new FormControl(data[i].value, Validators.required); this.formErrors[data[i].key] = ''; } this.configManagementForm = new FormGroup ({ edit: new FormGroup(this.formGroup) }); this.configManagementForm.valueChanges.subscribe(() => { this.formErrors = this.formService.validateForm(this.configManagementForm, this.formErrors, true); }); } register(myForm: NgForm) { // mark all fields as touched if (this.configManagementForm.controls.hasOwnProperty('edit')) { const editFormGroup = this.configManagementForm['controls']['edit'] as FormGroup; this.formService.markFormGroupTouched(editFormGroup); if (editFormGroup.valid) { this.previewEditList(editFormGroup.value); } } if (this.configManagementForm.controls.hasOwnProperty('overidden')) { const overridenFormGroup = this.configManagementForm['controls']['overidden'] as FormGroup; this.formService.markFormGroupTouched(overridenFormGroup); if (overridenFormGroup.valid) { this.previewOverideList(overridenFormGroup.value); } } } previewOverideList(updatedValues) { this.overiddenData = []; const keys = Object.keys(updatedValues); for (let i = 0; i < keys.length; i++) { const obj = { key: keys[i], value: updatedValues[keys[i]] }; this.overiddenData.push(obj); } } previewEditList (updatedValues) { const modifiedValue = []; const keys = Object.keys(updatedValues); this.previousEditedData = JSON.parse(JSON.stringify(this.originalData)); this.previousEditedData.properties = []; for (let i = 0; i < this.originalData.properties.length; i++) { if (this.originalData.properties[i].key === keys[i]) { if (this.originalData.properties[i].value !== updatedValues[keys[i]]) { const obj = { key: keys[i], value: updatedValues[keys[i]], description: this.originalData.properties[i].description, oldValue: this.originalData.properties[i].value }; modifiedValue.push(obj); this.previousEditedData.properties.push(obj); } else { this.previousEditedData.properties.push(this.originalData.properties[i]); } } else { const obj = { key: keys[i], value: updatedValues[keys[i]] }; modifiedValue.push(obj); } } this.editData.properties = modifiedValue; this.showPreview = true; } backToEditedData() { this.editData = this.previousEditedData; this.showPreview = false; } UpdateProperty() { this.showUserRemarks = false; this.transactionResponse.responseCount = 0; this.errorValue = 10; if (this.editData.properties.length > 0) { this.updateEditedProperty(); } if (this.overiddenData.length > 0) { this.updateOveriddenProperty(); } } updateOveriddenProperty() { this.updateInProgress = true; const updateData = []; for (let i = 0; i < this.overiddenData.length; i++) { updateData.push({ 'application': this.editData.name, 'configKey': this.overiddenData[i]['key'], 'configValue': this.overiddenData[i]['value'] }); } const payload = { 'configProperties': updateData }; const queryParams = { 'userMessage': this.userRemarks }; this.postConfigData(payload, queryParams); } updateEditedProperty() { this.updateInProgress = true; const updateData = []; try { const url = environment.updateConfigProperties.url; const method = environment.updateConfigProperties.method; for (let i = 0; i < this.editData.properties.length; i++) { updateData.push({ 'application': this.editData.name, 'configKey': this.editData.properties[i]['key'], 'configValue': this.editData.properties[i]['value'] }); } const payload = { 'configProperties': updateData }; const queryParams = { 'userMessage': this.userRemarks }; this.dataSubscription = this.commonResponseService .getData(url, method, payload, queryParams) .subscribe( response => { try { this.transactionResponse.updatedConfig.success = true; this.transactionResponse.responseCount++; } catch (e) { this.transactionResponse.updatedConfig.error = true; this.transactionResponse.responseCount++; this.errorMessage = 'jsError'; this.logger.log('error', e); } }, error => { this.transactionResponse.updatedConfig.error = true; this.transactionResponse.responseCount++; this.errorMessage = 'apiResponseError'; this.logger.log('error', error); }); } catch (error) { this.logger.log('error', error); } } postConfigData(payload, queryParams) { try { this.errorValue = 10; const url = environment.createConfigProperties.url; const method = environment.createConfigProperties.method; this.updateSubscription = this.commonResponseService .getData(url, method, payload, queryParams) .subscribe( response => { try { this.transactionResponse.createdConfig.success = true; this.transactionResponse.responseCount++; } catch (e) { this.transactionResponse.createdConfig.error = true; this.transactionResponse.responseCount++; this.errorMessage = 'jsError'; this.logger.log('error', e); } }, error => { this.transactionResponse.createdConfig.error = true; this.transactionResponse.responseCount++; this.errorMessage = 'apiResponseError'; this.logger.log('error', error); }); } catch (error) { this.logger.log('error', error); } } cancelEdit() { this.showConfBox.isEditPageCancelBtnClick = true; this.showConfBox.isConfigColumnModified = true; this.showConfBox.resetToView = true; this.showConfBox.isOverridenAlreadyExist = false; this.confirmationMessage = this.confirmationCondition(); this.showConfBox.value = true; } resetEditConfig() { this.showPreview = false; this.editProperty = false; this.editColumnIndex = -1; this.overiddenData = []; this.overrideFormData = []; this.overrideFormGroup = {}; this.formData = []; this.showConfBox.isOverridenAlreadyExist = false; this.showConfBox.isConfigColumnModified = false; this.showConfBox.confirmDelete = false; this.showConfBox.resetToView = false; this.deletePayLoadOnhold = {}; } transactionalMessage() { if (this.updateInProgress) { if (this.transactionResponse.updatedConfig.success) { this.transactionObj.type = 'success'; this.transactionObj.title = 'Success!'; this.transactionObj.message = 'Succesfully updated configuration data for ' + this.editData.name; } else if (this.transactionResponse.updatedConfig.error) { this.transactionObj.type = 'error'; this.transactionObj.title = 'Error!'; this.transactionObj.message = 'Updating configuration data for ' + this.editData.name; } if (this.transactionResponse.createdConfig.success) { this.transactionObj.obj1.type = 'success'; this.transactionObj.obj1.title = 'Success!'; this.transactionObj.obj1.message = 'Succesfully created configuration data for ' + this.editData.name; } else if (this.transactionResponse.createdConfig.error) { this.transactionObj.obj1.type = 'error'; this.transactionObj.obj1.title = 'Error!'; this.transactionObj.obj1.message = 'Creating configuration data for ' + this.editData.name; } if (this.transactionResponse.rollbackConfig.success) { this.transactionObj.type = 'success'; this.transactionObj.title = 'Success!'; this.transactionObj.message = 'Succesfully reverted configuration data.'; } else if (this.transactionResponse.rollbackConfig.error) { this.transactionObj.type = 'error'; this.transactionObj.title = 'Error!'; this.transactionObj.message = 'Reverting configuration data.'; } } return this.transactionObj; } allMessages() { if (this.editData && this.editData.properties && this.editData.properties.length > 0 && this.overiddenData.length > 0) { if (this.transactionResponse.responseCount >= 2) { return this.transactionalMessage(); } } else { return this.transactionalMessage(); } } takeActionPostTransaction(event) { if (event === 'back') { this.errorValue = 1; this.backToEditedData(); } else { this.updateComponent(); } } confirmationCondition() { if ( this.editProperty && this.showConfBox.isOverridenAlreadyExist) { return 'This field already exist in ' + this.editData['name']; } else if (this.editProperty && this.showConfBox.isConfigColumnModified) { return 'Changes are not saved. Are you sure you want to discard your changes?'; } else if (this.editProperty && this.showConfBox.confirmDelete) { return 'Configuration removals may impact the system to come down. Are you sure you want to remove this field?'; } return ''; } continueConfirmBox() { if (this.editProperty) { // This condition if when confirmation is to ask user to reset the edit. if (this.showConfBox.resetToView) { this.resetEditConfig(); if (this.showConfBox.isEditPageCancelBtnClick) { this.showConfBox.isEditPageCancelBtnClick = false; } else { if (this.showConfBox.modified.columnIndex === 1) { this.storeFirstLevel(this.filterData[0], this.applyActive1); } else if (this.showConfBox.modified.columnIndex === 2) { this.storeSecondLevel(this.firstLevelData['children'][this.applyActive2], this.applyActive2); } else if (this.showConfBox.modified.columnIndex === 3) { this.storeThirdLevel(this.secondaryLevelData['children'][this.applyActive3], this.applyActive3); } } this.showConfBox.value = false; this.confirmationMessage = ''; } else { if (this.showConfBox.confirmDelete) { this.deleteFieldOnConfirm(this.deletePayLoadOnhold); } } } } cancelConfirmBox() { this.showConfBox.value = false; this.confirmationMessage = ''; this.showConfBox.showContinueBtn = 1; if (this.showConfBox.modified.columnIndex === 1) { this.applyActive1 = this.firstLevelIndex; } else if (this.showConfBox.modified.columnIndex === 2) { this.applyActive2 = this.secondLevelIndex; } else if (this.showConfBox.modified.columnIndex === 3) { this.applyActive3 = this.thirdLevelIndex; } } onOverride(data) { for (let i = 0; i < this.editData.properties.length; i++) { if (this.editData.properties[i].key === data.key) { this.showConfBox.isOverridenAlreadyExist = true; this.confirmationMessage = this.confirmationCondition(); this.showConfBox.value = true; this.showConfBox.showContinueBtn = -1; return; } } for (let i = 0; i < this.overrideFormData.length; i++) { if (this.overrideFormData[i].formControlName === data.key) { this.showConfBox.isOverridenAlreadyExist = true; this.confirmationMessage = this.confirmationCondition(); this.showConfBox.value = true; this.showConfBox.showContinueBtn = -1; return; } } let individualField = { formControlName: data.key, formControlDisplayName: this.refactorFieldsService.getDisplayNameForAKey( data.key.toLocaleLowerCase() ) || data.key }; if (data.description) { individualField = Object.assign({'metadata': data.description}, individualField); } this.overrideFormData.push(individualField); this.overrideFormGroup[data.key] = new FormControl(data.value, Validators.required); this.formErrors[data.key] = ''; this.configManagementForm = new FormGroup ({ edit: new FormGroup(this.formGroup), overidden: new FormGroup(this.overrideFormGroup) }); this.configManagementForm.valueChanges.subscribe(() => { this.formErrors = this.formService.validateForm(this.configManagementForm, this.formErrors, true); }); // provide toast message for overridden field this.toastObservableService.postMessage('Field added to ' + this.editData.name + ' to override ', 3); } onDelete(fieldType, input) { try { this.deletePayLoadOnhold = { 'fieldType': fieldType, 'input': input, 'payload': { 'application': this.editData.name, 'configKey': input.formControlName, 'configValue': this.configManagementForm.controls[fieldType]['controls'][input.formControlName].value } }; this.showConfBox.confirmDelete = true; this.showConfBox.isOverridenAlreadyExist = false; this.showConfBox.isConfigColumnModified = false; this.confirmationMessage = this.confirmationCondition(); this.showConfBox.value = true; } catch (error) { this.logger.log('error', 'JS Error, Error deleting field'); } } onDeleteNotSavedField(fieldType, input) { try { const childFormGroup: FormGroup = <FormGroup>this.configManagementForm.get(fieldType); childFormGroup.removeControl(input.formControlName); this.overrideFormData = this.overrideFormData.filter(item => item.formControlName !== input.formControlName); } catch (error) { this.logger.log('error', 'js error, error deleting field not saved by user'); } } deleteFieldOnConfirm(deleteObj) { const options = { headers: new HttpHeaders({ 'Content-Type': 'application/json', }), body: deleteObj['payload'] }; this.deleteFieldInProgress = true; this.commonResponseService.getData( environment.deleteConfigKey.url, environment.deleteConfigKey.method, {}, {}, options).subscribe(response => { this.transactionResponse.deleteConfig.success = true; this.deleteActionComplete(); // Success message will not be required. /*if (!this.deleteTransactionResponse) { this.deleteTransactionResponse = {}; } this.deleteTransactionResponse.type = 'success'; this.deleteTransactionResponse.title = 'Success!'; this.deleteTransactionResponse.message = 'Succesfully deleted configuration: ' + this.deletePayLoadOnhold['payload']['configKey'];*/ }, error => { this.transactionResponse.deleteConfig.error = true; if (!this.deleteTransactionResponse) { this.deleteTransactionResponse = {}; } this.deleteTransactionResponse.type = 'error'; this.deleteTransactionResponse.title = 'Error!'; this.deleteTransactionResponse.message = 'Deleting configuration ' + this.deletePayLoadOnhold['payload']['configKey']; this.logger.log('error', 'Server error deleting the field'); }); } deleteActionComplete() { this.showConfBox.value = false; this.deleteFieldInProgress = false; this.confirmationMessage = ''; this.transactionResponse.deleteConfig.success = false; this.transactionResponse.deleteConfig.error = false; this.deletePayLoadOnhold = {}; this.deleteTransactionResponse = null; this.updateComponent(); } getConfigKeys() { try { const configUrl = environment.getConfigkeys.url; const configMethod = environment.getConfigkeys.method; this.configPropertySubscription = this.commonResponseService .getData(configUrl, configMethod, {}, {}) .subscribe( response => { try { if (this.utils.checkIfAPIReturnedDataIsEmpty(response)) { this.configKeys.errorValue = -1; this.configKeys.errorMessage = 'noDataAvailable'; } else { this.configKeys.errorValue = 1; this.configKeys.value = response; } } catch (e) { this.configKeys.errorValue = -1; this.configKeys.errorMessage = 'jsError'; this.logger.log('error', e); } }, error => { this.configKeys.errorValue = -1; this.configKeys.errorMessage = 'apiResponseError'; this.logger.log('error', error); }); } catch (error) { this.logger.log('error', error); } } createNewField(newObj) { this.createNew = false; const object = { key: Object.keys(newObj)[0], value: Object.values(newObj)[0] }; this.onOverride(object); } getHistory() { try { const historyUrl = environment.auditTrailConfigProperties.url; const historyMethod = environment.auditTrailConfigProperties.method; this.configPropertySubscription = this.commonResponseService .getData(historyUrl, historyMethod, {}, {}) .subscribe( response => { try { if (this.utils.checkIfAPIReturnedDataIsEmpty(response.configPropertyAudit)) { this.configAudit.errorValue = -1; this.configAudit.errorMessage = 'noDataAvailable'; } else { this.configAudit.errorValue = 1; const configData = response.configPropertyAudit; for (let i = 0; i < configData.length; i++) { configData[i] = this.processSelectedHistoryData(configData[i]); } this.configAudit.value = configData; } } catch (e) { this.configAudit.errorValue = -1; this.configAudit.errorMessage = 'jsError'; this.logger.log('error', e); } }, error => { this.configAudit.errorValue = -1; this.configAudit.errorMessage = 'apiResponseError'; this.logger.log('error', error); }); } catch (error) { this.logger.log('error', error); } } getHistoryPreview(selectedCommit) { this.activeHistoryTile = selectedCommit.activeIndex; this.historyPreview = selectedCommit.value; this.showDropdown = false; this.showHistoryPreview = true; } historyDropdownCloseEvent(value) { this.showDropdown = value; } processSelectedHistoryData(data) { const historyArray = []; const appArray = []; const property = data.configPropertyChangeList; for (let i = 0; i < property.length; i++) { if (appArray.indexOf(property[i].application) !== -1) { const index = appArray.indexOf(property[i].application); historyArray[index].configProperties.push({ 'configKey': property[i].configKey, 'newConfigValue': property[i].newConfigValue, 'oldConfigValue': property[i].oldConfigValue }); } else { const appObj = { 'application': property[i].application, configProperties: [{ 'configKey': property[i].configKey, 'newConfigValue': property[i].newConfigValue, 'oldConfigValue': property[i].oldConfigValue }] }; historyArray.push(appObj); appArray.push(property[i].application); } } data.configPropertyChangeList = historyArray; return data; } updateRollback() { try { this.errorValue = 10; this.updateInProgress = true; const url = environment.rollbackConfigProperties.url; const method = environment.rollbackConfigProperties.method; const queryParams = { 'timestamp': this.historyPreview.auditTimeStamp, 'userMessage': this.userRemarks }; this.updateSubscription = this.commonResponseService .getData(url, method, {}, queryParams) .subscribe( response => { try { this.transactionResponse.rollbackConfig.success = true; this.transactionResponse.responseCount++; } catch (e) { this.transactionResponse.rollbackConfig.error = true; this.transactionResponse.responseCount++; this.errorMessage = 'jsError'; this.logger.log('error', e); } }, error => { this.transactionResponse.rollbackConfig.error = true; this.transactionResponse.responseCount++; this.errorMessage = 'apiResponseError'; this.logger.log('error', error); }); } catch (error) { this.logger.log('error', error); } } resetUserRemarks() { this.userRemarks = ''; } ngOnDestroy() { try { if (this.dataSubscription) { this.dataSubscription.unsubscribe(); } if (this.configPropertySubscription) { this.configPropertySubscription.unsubscribe(); } if (this.updateSubscription) { this.updateSubscription.unsubscribe(); } } catch (error) { this.logger.log('error', 'JS Error - ' + error); } } }
the_stack
import * as qlogschema from '@/data/QlogSchema'; export default class TextSequenceJSONToQlog { public static async convert( inputStream:ReadableStream ) : Promise<qlogschema.IQLog | undefined> { console.log("TextSequenceJSONToQlog: converting textsequence JSON file"); // make proper qlogschema.IQLog again when we've updated the schema to match draft-02 proper const qlogFile:any = { qlog_version: "draft-02", qlog_format: qlogschema.LogFormat.JSONSEQ, traces: new Array<qlogschema.ITrace>() } as qlogschema.IQLog; const rawJSONentries = await TextSequenceJSONToQlog.parseTextSequences( inputStream ); if ( rawJSONentries.length === 0 ) { console.error("TextSequenceJSONToQlog: no entries found in the loaded file..."); return qlogFile; } // in json-seq format, we should first have the file "header", a separate object containing the qlog metadata // and then we should have a single entry per event after that. const header = rawJSONentries.shift(); if ( header.qlog_version === undefined || header.qlog_format !== qlogschema.LogFormat.JSONSEQ || header.trace === undefined ) { console.error("TextSequenceJSONToQlog: File did not start with the proper qlog header (needs version, format and trace)! Aborting...", header); return undefined; } // copy over everything, but we'll handle trace separately below for ( const key of Object.keys(header) ) { if ( key !== "trace" ) { (qlogFile as any)[key] = header[key]; } } // json-seq files have just a single trace by definition const trace:qlogschema.ITrace = { vantage_point: { type: qlogschema.VantagePointType.unknown, }, events: [], }; // copy over everything for ( const key of Object.keys(header.trace) ) { (trace as any)[ key ] = header.trace[key]; } trace.events = rawJSONentries; // the header was removed by calling shift() above, so these should be the raw events qlogFile.traces = [ trace ]; return qlogFile as qlogschema.IQLog; } protected static async parseTextSequences( inputStream:ReadableStream ) : Promise<Array<any>> { let resolver:any = undefined; let rejecter:any = undefined; const output = new Promise<Array<any>>( (resolve, reject) => { resolver = resolve; rejecter = reject; }); const entries:Array<any> = []; const jsonStream = TextSequenceJSONToQlog.createRecordTransformer( inputStream ); const streamReader = jsonStream.getReader(); let read:any = undefined; streamReader.read().then( read = ( result:any ) => { // at the end of the stream, this function is called one last time // with result.done set and an empty result.value if ( result.done ) { resolver( entries ); return; } // use destructuring instead of concat to merge the objects, // see https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1oki entries.push( ...result.value ); // console.log("parseNDJSON: DEBUG : ", result.value.length, result.value ); streamReader.read().then( read ); } ); return output; } // this code was taken largely from the can-ndjson-stream project (https://www.npmjs.com/package/can-ndjson-stream) // that project however surfaces each object individually, which incurs quite a large message passing overhead from the transforming stream // to the reading stream. // Our custom version here instead batches all read objects from a single chunk and propagates those up in 1 time, which is much faster for our use case. // it also replaces splitting on \n by splitting on the RecordSeparator character for json-seq. Everything else is the same as NDJSON handling. // copyright notice for this function: /* The MIT License (MIT) Copyright 2017 Justin Meyer (justinbmeyer@gmail.com), Fang Lu (cc2lufang@gmail.com), Siyao Wu (wusiyao@umich.edu), Shang Jiang (mrjiangshang@gmail.com) 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. */ protected static createRecordTransformer( inputStream:ReadableStream ):ReadableStream { let is_reader:ReadableStreamReader|undefined = undefined; let cancellationRequest:boolean = false; let readRecordCount = 0; return new ReadableStream({ start: (controller) => { const reader = inputStream.getReader(); is_reader = reader; const decoder = new TextDecoder(); let data_buf = ""; reader.read().then(function processResult(result:any):any { // at the end of the stream, this function is called one last time // with result.done set and an empty result.value if (result.done) { if (cancellationRequest) { // Immediately exit return; } // try to process the last part of the file if possible data_buf = data_buf.trim(); if (data_buf.length !== 0) { ++readRecordCount; try { const data_l = JSON.parse(data_buf); controller.enqueue( [data_l] ); // need to wrap in array, since that's what calling code expects } catch (e) { console.error("TextSequenceJSONToQlog:ondone record #" + readRecordCount + " was invalid JSON. Skipping and continuing.", data_buf); // // TODO: what does this do practically? We probably want to (silently?) ignore errors? // controller.error(e); // return; } } controller.close(); return; } const data = decoder.decode(result.value, {stream: true}); data_buf += data; const records = data_buf.split("\u001E"); // \u001E is the Record Separator character const output = []; // batch results together to reduce message passing overhead console.log("TextsequenceJSONToQlog:createRecordTransformer Amount of records", records.length); for ( let i = 0; i < records.length - 1; ++i) { const r = records[i].trim(); if (r.length > 0) { ++readRecordCount; try { const data_record = JSON.parse(r); // controller.enqueue(data_record) would immediately pass the single read object on, but we batch it instead on the next line output.push( data_record ); } catch (e) { console.error("TextSequenceJSONToQlog: line #" + readRecordCount + " was invalid JSON. Skipping and continuing.", r, records.length); return; // // TODO: what does this do practically? We probably want to (silently?) ignore errors? // controller.error(e); // cancellationRequest = true; // reader.cancel(); // return; } } } data_buf = records[records.length - 1]; controller.enqueue( output ); return reader.read().then(processResult); }); }, cancel: (reason) => { console.warn("TextSequenceJSONToQlog:parseTextSequences : Cancel registered due to ", reason); cancellationRequest = true; if ( is_reader !== undefined ) { is_reader.cancel(); } }, }, // TODO: we tried to optimize a bit with this, but it doesn't seem to work (printing chunks above gives chunks of 65K, not 260K) // didn't immediately find a good solution for this though, seems like chunk-sizing APIs aren't well supported yet in browsers { highWaterMark: 4, // read up to 1 chunk of the following size size: (chunk) => { return 262144; }, }); } }
the_stack
import { Appointment } from "../Items/Appointment"; import { AppointmentType } from "../../../Enumerations/AppointmentType"; import { AttendeeCollection } from "../../../ComplexProperties/AttendeeCollection"; import { BoolPropertyDefinition } from "../../../PropertyDefinitions/BoolPropertyDefinition"; import { ComplexPropertyDefinition } from "../../../PropertyDefinitions/ComplexPropertyDefinition"; import { ContainedPropertyDefinition } from "../../../PropertyDefinitions/ContainedPropertyDefinition"; import { DateTimePropertyDefinition } from "../../../PropertyDefinitions/DateTimePropertyDefinition"; import { DeletedOccurrenceInfoCollection } from "../../../ComplexProperties/DeletedOccurrenceInfoCollection"; import { EmailAddress } from "../../../ComplexProperties/EmailAddress"; import { EnhancedLocation } from "../../../ComplexProperties/EnhancedLocation"; import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion"; import { GenericPropertyDefinition } from "../../../PropertyDefinitions/GenericPropertyDefinition"; import { IntPropertyDefinition } from "../../../PropertyDefinitions/IntPropertyDefinition"; import { ItemCollection } from "../../../ComplexProperties/ItemCollection"; import { LegacyFreeBusyStatus } from "../../../Enumerations/LegacyFreeBusyStatus"; import { MeetingResponseType } from "../../../Enumerations/MeetingResponseType"; import { MeetingTimeZonePropertyDefinition } from "../../../PropertyDefinitions/MeetingTimeZonePropertyDefinition"; import { OccurrenceInfo } from "../../../ComplexProperties/OccurrenceInfo"; import { OccurrenceInfoCollection } from "../../../ComplexProperties/OccurrenceInfoCollection"; import { OnlineMeetingSettings } from "../../../ComplexProperties/OnlineMeetingSettings"; import { PropertyDefinition } from "../../../PropertyDefinitions/PropertyDefinition"; import { PropertyDefinitionFlags } from "../../../Enumerations/PropertyDefinitionFlags"; import { RecurrencePropertyDefinition } from "../../../PropertyDefinitions/RecurrencePropertyDefinition"; import { ScopedDateTimePropertyDefinition } from "../../../PropertyDefinitions/ScopedDateTimePropertyDefinition"; import { StartTimeZonePropertyDefinition } from "../../../PropertyDefinitions/StartTimeZonePropertyDefinition"; import { StringPropertyDefinition } from "../../../PropertyDefinitions/StringPropertyDefinition"; import { TimeSpanPropertyDefinition } from "../../../PropertyDefinitions/TimeSpanPropertyDefinition"; import { TimeZonePropertyDefinition } from "../../../PropertyDefinitions/TimeZonePropertyDefinition"; import { XmlElementNames } from "../../XmlElementNames"; import { ItemSchema } from "./ItemSchema"; /** * Field URIs for Appointment. */ module FieldUris { export var Start: string = "calendar:Start"; export var End: string = "calendar:End"; export var OriginalStart: string = "calendar:OriginalStart"; export var IsAllDayEvent: string = "calendar:IsAllDayEvent"; export var LegacyFreeBusyStatus: string = "calendar:LegacyFreeBusyStatus"; export var Location: string = "calendar:Location"; export var When: string = "calendar:When"; export var IsMeeting: string = "calendar:IsMeeting"; export var IsCancelled: string = "calendar:IsCancelled"; export var IsRecurring: string = "calendar:IsRecurring"; export var MeetingRequestWasSent: string = "calendar:MeetingRequestWasSent"; export var IsResponseRequested: string = "calendar:IsResponseRequested"; export var CalendarItemType: string = "calendar:CalendarItemType"; export var MyResponseType: string = "calendar:MyResponseType"; export var Organizer: string = "calendar:Organizer"; export var RequiredAttendees: string = "calendar:RequiredAttendees"; export var OptionalAttendees: string = "calendar:OptionalAttendees"; export var Resources: string = "calendar:Resources"; export var ConflictingMeetingCount: string = "calendar:ConflictingMeetingCount"; export var AdjacentMeetingCount: string = "calendar:AdjacentMeetingCount"; export var ConflictingMeetings: string = "calendar:ConflictingMeetings"; export var AdjacentMeetings: string = "calendar:AdjacentMeetings"; export var Duration: string = "calendar:Duration"; export var TimeZone: string = "calendar:TimeZone"; export var AppointmentReplyTime: string = "calendar:AppointmentReplyTime"; export var AppointmentSequenceNumber: string = "calendar:AppointmentSequenceNumber"; export var AppointmentState: string = "calendar:AppointmentState"; export var Recurrence: string = "calendar:Recurrence"; export var FirstOccurrence: string = "calendar:FirstOccurrence"; export var LastOccurrence: string = "calendar:LastOccurrence"; export var ModifiedOccurrences: string = "calendar:ModifiedOccurrences"; export var DeletedOccurrences: string = "calendar:DeletedOccurrences"; export var MeetingTimeZone: string = "calendar:MeetingTimeZone"; export var StartTimeZone: string = "calendar:StartTimeZone"; export var EndTimeZone: string = "calendar:EndTimeZone"; export var ConferenceType: string = "calendar:ConferenceType"; export var AllowNewTimeProposal: string = "calendar:AllowNewTimeProposal"; export var IsOnlineMeeting: string = "calendar:IsOnlineMeeting"; export var MeetingWorkspaceUrl: string = "calendar:MeetingWorkspaceUrl"; export var NetShowUrl: string = "calendar:NetShowUrl"; export var Uid: string = "calendar:UID"; export var RecurrenceId: string = "calendar:RecurrenceId"; export var DateTimeStamp: string = "calendar:DateTimeStamp"; export var EnhancedLocation: string = "calendar:EnhancedLocation"; export var JoinOnlineMeetingUrl: string = "calendar:JoinOnlineMeetingUrl"; export var OnlineMeetingSettings: string = "calendar:OnlineMeetingSettings"; } /** * Represents the schema for appointment and meeting requests. */ export class AppointmentSchema extends ItemSchema { /** * Defines the **StartTimeZone** property. */ public static StartTimeZone: PropertyDefinition = new StartTimeZonePropertyDefinition( "StartTimeZone", XmlElementNames.StartTimeZone, FieldUris.StartTimeZone, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **EndTimeZone** property. */ public static EndTimeZone: PropertyDefinition = new TimeZonePropertyDefinition( "EndTimeZone", XmlElementNames.EndTimeZone, FieldUris.EndTimeZone, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2010 ); /** * Defines the **Start** property. */ public static Start: PropertyDefinition = new ScopedDateTimePropertyDefinition( "Start", XmlElementNames.Start, FieldUris.Start, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, (version: ExchangeVersion) => { return AppointmentSchema.StartTimeZone; } ); /** * Defines the **End** property. */ public static End: PropertyDefinition = new ScopedDateTimePropertyDefinition( "End", XmlElementNames.End, FieldUris.End, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, (version: ExchangeVersion) => { if (version !== ExchangeVersion.Exchange2007_SP1) { return AppointmentSchema.EndTimeZone; } return AppointmentSchema.StartTimeZone; }); /** * Defines the **OriginalStart** property. */ public static OriginalStart: PropertyDefinition = new DateTimePropertyDefinition( "OriginalStart", XmlElementNames.OriginalStart, FieldUris.OriginalStart, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsAllDayEvent** property. */ public static IsAllDayEvent: PropertyDefinition = new BoolPropertyDefinition( "IsAllDayEvent", XmlElementNames.IsAllDayEvent, FieldUris.IsAllDayEvent, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **LegacyFreeBusyStatus** property. */ public static LegacyFreeBusyStatus: PropertyDefinition = new GenericPropertyDefinition<LegacyFreeBusyStatus>( "LegacyFreeBusyStatus", XmlElementNames.LegacyFreeBusyStatus, FieldUris.LegacyFreeBusyStatus, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, LegacyFreeBusyStatus ); /** * Defines the **Location** property. */ public static Location: PropertyDefinition = new StringPropertyDefinition( "Location", XmlElementNames.Location, FieldUris.Location, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **When** property. */ public static When: PropertyDefinition = new StringPropertyDefinition( "When", XmlElementNames.When, FieldUris.When, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsMeeting** property. */ public static IsMeeting: PropertyDefinition = new BoolPropertyDefinition( "IsMeeting", XmlElementNames.IsMeeting, FieldUris.IsMeeting, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsCancelled** property. */ public static IsCancelled: PropertyDefinition = new BoolPropertyDefinition( "IsCancelled", XmlElementNames.IsCancelled, FieldUris.IsCancelled, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsRecurring** property. */ public static IsRecurring: PropertyDefinition = new BoolPropertyDefinition( "IsRecurring", XmlElementNames.IsRecurring, FieldUris.IsRecurring, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **MeetingRequestWasSent** property. */ public static MeetingRequestWasSent: PropertyDefinition = new BoolPropertyDefinition( "MeetingRequestWasSent", XmlElementNames.MeetingRequestWasSent, FieldUris.MeetingRequestWasSent, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsResponseRequested** property. */ public static IsResponseRequested: PropertyDefinition = new BoolPropertyDefinition( "IsResponseRequested", XmlElementNames.IsResponseRequested, FieldUris.IsResponseRequested, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **AppointmentType** property. */ public static AppointmentType: PropertyDefinition = new GenericPropertyDefinition<AppointmentType>( "CalendarItemType", XmlElementNames.CalendarItemType, FieldUris.CalendarItemType, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, AppointmentType ); /** * Defines the **MyResponseType** property. */ public static MyResponseType: PropertyDefinition = new GenericPropertyDefinition<MeetingResponseType>( "MyResponseType", XmlElementNames.MyResponseType, FieldUris.MyResponseType, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, MeetingResponseType ); /** * Defines the **Organizer** property. */ public static Organizer: PropertyDefinition = new ContainedPropertyDefinition<EmailAddress>( "Organizer", XmlElementNames.Organizer, FieldUris.Organizer, XmlElementNames.Mailbox, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new EmailAddress(); } ); /** * Defines the **RequiredAttendees** property. */ public static RequiredAttendees: PropertyDefinition = new ComplexPropertyDefinition<AttendeeCollection>( "RequiredAttendees", XmlElementNames.RequiredAttendees, FieldUris.RequiredAttendees, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete, ExchangeVersion.Exchange2007_SP1, () => { return new AttendeeCollection(); } ); /** * Defines the **OptionalAttendees** property. */ public static OptionalAttendees: PropertyDefinition = new ComplexPropertyDefinition<AttendeeCollection>( "OptionalAttendees", XmlElementNames.OptionalAttendees, FieldUris.OptionalAttendees, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete, ExchangeVersion.Exchange2007_SP1, () => { return new AttendeeCollection(); } ); /** * Defines the **Resources** property. */ public static Resources: PropertyDefinition = new ComplexPropertyDefinition<AttendeeCollection>( "Resources", XmlElementNames.Resources, FieldUris.Resources, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete, ExchangeVersion.Exchange2007_SP1, () => { return new AttendeeCollection(); } ); /** * Defines the **ConflictingMeetingCount** property. */ public static ConflictingMeetingCount: PropertyDefinition = new IntPropertyDefinition( "ConflictingMeetingCount", XmlElementNames.ConflictingMeetingCount, FieldUris.ConflictingMeetingCount, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **AdjacentMeetingCount** property. */ public static AdjacentMeetingCount: PropertyDefinition = new IntPropertyDefinition( "AdjacentMeetingCount", XmlElementNames.AdjacentMeetingCount, FieldUris.AdjacentMeetingCount, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ConflictingMeetings** property. */ public static ConflictingMeetings: PropertyDefinition = new ComplexPropertyDefinition<ItemCollection<Appointment>>( "ConflictingMeetings", XmlElementNames.ConflictingMeetings, FieldUris.ConflictingMeetings, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1, () => { return new ItemCollection<Appointment>(); } ); /** * Defines the **AdjacentMeetings** property. */ public static AdjacentMeetings: PropertyDefinition = new ComplexPropertyDefinition<ItemCollection<Appointment>>( "AdjacentMeetings", XmlElementNames.AdjacentMeetings, FieldUris.AdjacentMeetings, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1, () => { return new ItemCollection<Appointment>(); } ); /** * Defines the **Duration** property. */ public static Duration: PropertyDefinition = new TimeSpanPropertyDefinition( "Duration", XmlElementNames.Duration, FieldUris.Duration, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **TimeZone** property. */ public static TimeZone: PropertyDefinition = new StringPropertyDefinition( "TimeZone", XmlElementNames.TimeZone, FieldUris.TimeZone, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **AppointmentReplyTime** property. */ public static AppointmentReplyTime: PropertyDefinition = new DateTimePropertyDefinition( "AppointmentReplyTime", XmlElementNames.AppointmentReplyTime, FieldUris.AppointmentReplyTime, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **AppointmentSequenceNumber** property. */ public static AppointmentSequenceNumber: PropertyDefinition = new IntPropertyDefinition( "AppointmentSequenceNumber", XmlElementNames.AppointmentSequenceNumber, FieldUris.AppointmentSequenceNumber, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **AppointmentState** property. */ public static AppointmentState: PropertyDefinition = new IntPropertyDefinition( "AppointmentState", XmlElementNames.AppointmentState, FieldUris.AppointmentState, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Recurrence** property. */ public static Recurrence: PropertyDefinition = new RecurrencePropertyDefinition( "Recurrence", XmlElementNames.Recurrence, FieldUris.Recurrence, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **FirstOccurrence** property. */ public static FirstOccurrence: PropertyDefinition = new ComplexPropertyDefinition<OccurrenceInfo>( "FirstOccurrence", XmlElementNames.FirstOccurrence, FieldUris.FirstOccurrence, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1, () => { return new OccurrenceInfo(); } ); /** * Defines the **LastOccurrence** property. */ public static LastOccurrence: PropertyDefinition = new ComplexPropertyDefinition<OccurrenceInfo>( "LastOccurrence", XmlElementNames.LastOccurrence, FieldUris.LastOccurrence, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1, () => { return new OccurrenceInfo(); } ); /** * Defines the **ModifiedOccurrences** property. */ public static ModifiedOccurrences: PropertyDefinition = new ComplexPropertyDefinition<OccurrenceInfoCollection>( "ModifiedOccurrences", XmlElementNames.ModifiedOccurrences, FieldUris.ModifiedOccurrences, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1, () => { return new OccurrenceInfoCollection(); } ); /** * Defines the **DeletedOccurrences** property. */ public static DeletedOccurrences: PropertyDefinition = new ComplexPropertyDefinition<DeletedOccurrenceInfoCollection>( "DeletedOccurrences", XmlElementNames.DeletedOccurrences, FieldUris.DeletedOccurrences, PropertyDefinitionFlags.None, ExchangeVersion.Exchange2007_SP1, () => { return new DeletedOccurrenceInfoCollection(); } ); /** * Defines the **MeetingTimeZone** property. */ public static MeetingTimeZone: PropertyDefinition = new MeetingTimeZonePropertyDefinition( "MeetingTimeZone", XmlElementNames.MeetingTimeZone, FieldUris.MeetingTimeZone, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ConferenceType** property. */ public static ConferenceType: PropertyDefinition = new IntPropertyDefinition( "ConferenceType", XmlElementNames.ConferenceType, FieldUris.ConferenceType, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **AllowNewTimeProposal** property. */ public static AllowNewTimeProposal: PropertyDefinition = new BoolPropertyDefinition( "AllowNewTimeProposal", XmlElementNames.AllowNewTimeProposal, FieldUris.AllowNewTimeProposal, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsOnlineMeeting** property. */ public static IsOnlineMeeting: PropertyDefinition = new BoolPropertyDefinition( "IsOnlineMeeting", XmlElementNames.IsOnlineMeeting, FieldUris.IsOnlineMeeting, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **MeetingWorkspaceUrl** property. */ public static MeetingWorkspaceUrl: PropertyDefinition = new StringPropertyDefinition( "MeetingWorkspaceUrl", XmlElementNames.MeetingWorkspaceUrl, FieldUris.MeetingWorkspaceUrl, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **NetShowUrl** property. */ public static NetShowUrl: PropertyDefinition = new StringPropertyDefinition( "NetShowUrl", XmlElementNames.NetShowUrl, FieldUris.NetShowUrl, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ICalUid** property. */ public static ICalUid: PropertyDefinition = new StringPropertyDefinition( "ICalUid", XmlElementNames.Uid, FieldUris.Uid, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ICalRecurrenceId** property. */ public static ICalRecurrenceId: PropertyDefinition = new DateTimePropertyDefinition( "ICalRecurrenceId", XmlElementNames.RecurrenceId, FieldUris.RecurrenceId, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, true ); /** * Defines the **ICalDateTimeStamp** property. */ public static ICalDateTimeStamp: PropertyDefinition = new DateTimePropertyDefinition( "ICalDateTimeStamp", XmlElementNames.DateTimeStamp, FieldUris.DateTimeStamp, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, true ); /** * Defines the **EnhancedLocation** property. */ public static EnhancedLocation: PropertyDefinition = new ComplexPropertyDefinition<EnhancedLocation>( "EnhancedLocation", XmlElementNames.EnhancedLocation, FieldUris.EnhancedLocation, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, () => { return new EnhancedLocation(); } ); /** * Defines the **JoinOnlineMeetingUrl** property. */ public static JoinOnlineMeetingUrl: PropertyDefinition = new StringPropertyDefinition( "JoinOnlineMeetingUrl", XmlElementNames.JoinOnlineMeetingUrl, FieldUris.JoinOnlineMeetingUrl, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013 ); /** * Defines the **OnlineMeetingSettings** property. */ public static OnlineMeetingSettings: PropertyDefinition = new ComplexPropertyDefinition<OnlineMeetingSettings>( "OnlineMeetingSettings", XmlElementNames.OnlineMeetingSettings, FieldUris.OnlineMeetingSettings, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2013, () => { return new OnlineMeetingSettings(); } ); /** * @internal Instance of **AppointmentSchema** */ static Instance: AppointmentSchema = new AppointmentSchema(); /** * 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(AppointmentSchema, AppointmentSchema.ICalUid); this.RegisterProperty(AppointmentSchema, AppointmentSchema.ICalRecurrenceId); this.RegisterProperty(AppointmentSchema, AppointmentSchema.ICalDateTimeStamp); this.RegisterProperty(AppointmentSchema, AppointmentSchema.Start); this.RegisterProperty(AppointmentSchema, AppointmentSchema.End); this.RegisterProperty(AppointmentSchema, AppointmentSchema.OriginalStart); this.RegisterProperty(AppointmentSchema, AppointmentSchema.IsAllDayEvent); this.RegisterProperty(AppointmentSchema, AppointmentSchema.LegacyFreeBusyStatus); this.RegisterProperty(AppointmentSchema, AppointmentSchema.Location); this.RegisterProperty(AppointmentSchema, AppointmentSchema.When); this.RegisterProperty(AppointmentSchema, AppointmentSchema.IsMeeting); this.RegisterProperty(AppointmentSchema, AppointmentSchema.IsCancelled); this.RegisterProperty(AppointmentSchema, AppointmentSchema.IsRecurring); this.RegisterProperty(AppointmentSchema, AppointmentSchema.MeetingRequestWasSent); this.RegisterProperty(AppointmentSchema, AppointmentSchema.IsResponseRequested); this.RegisterProperty(AppointmentSchema, AppointmentSchema.AppointmentType); this.RegisterProperty(AppointmentSchema, AppointmentSchema.MyResponseType); this.RegisterProperty(AppointmentSchema, AppointmentSchema.Organizer); this.RegisterProperty(AppointmentSchema, AppointmentSchema.RequiredAttendees); this.RegisterProperty(AppointmentSchema, AppointmentSchema.OptionalAttendees); this.RegisterProperty(AppointmentSchema, AppointmentSchema.Resources); this.RegisterProperty(AppointmentSchema, AppointmentSchema.ConflictingMeetingCount); this.RegisterProperty(AppointmentSchema, AppointmentSchema.AdjacentMeetingCount); this.RegisterProperty(AppointmentSchema, AppointmentSchema.ConflictingMeetings); this.RegisterProperty(AppointmentSchema, AppointmentSchema.AdjacentMeetings); this.RegisterProperty(AppointmentSchema, AppointmentSchema.Duration); this.RegisterProperty(AppointmentSchema, AppointmentSchema.TimeZone); this.RegisterProperty(AppointmentSchema, AppointmentSchema.AppointmentReplyTime); this.RegisterProperty(AppointmentSchema, AppointmentSchema.AppointmentSequenceNumber); this.RegisterProperty(AppointmentSchema, AppointmentSchema.AppointmentState); this.RegisterProperty(AppointmentSchema, AppointmentSchema.Recurrence); this.RegisterProperty(AppointmentSchema, AppointmentSchema.FirstOccurrence); this.RegisterProperty(AppointmentSchema, AppointmentSchema.LastOccurrence); this.RegisterProperty(AppointmentSchema, AppointmentSchema.ModifiedOccurrences); this.RegisterProperty(AppointmentSchema, AppointmentSchema.DeletedOccurrences); this.RegisterInternalProperty(AppointmentSchema, AppointmentSchema.MeetingTimeZone); this.RegisterProperty(AppointmentSchema, AppointmentSchema.StartTimeZone); this.RegisterProperty(AppointmentSchema, AppointmentSchema.EndTimeZone); this.RegisterProperty(AppointmentSchema, AppointmentSchema.ConferenceType); this.RegisterProperty(AppointmentSchema, AppointmentSchema.AllowNewTimeProposal); this.RegisterProperty(AppointmentSchema, AppointmentSchema.IsOnlineMeeting); this.RegisterProperty(AppointmentSchema, AppointmentSchema.MeetingWorkspaceUrl); this.RegisterProperty(AppointmentSchema, AppointmentSchema.NetShowUrl); this.RegisterProperty(AppointmentSchema, AppointmentSchema.EnhancedLocation); this.RegisterProperty(AppointmentSchema, AppointmentSchema.JoinOnlineMeetingUrl); this.RegisterProperty(AppointmentSchema, AppointmentSchema.OnlineMeetingSettings); } } /** * Represents the schema for appointment and meeting requests. */ export interface AppointmentSchema { /** * Defines the **StartTimeZone** property. */ StartTimeZone: PropertyDefinition; /** * Defines the **EndTimeZone** property. */ EndTimeZone: 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 **IsResponseRequested** property. */ IsResponseRequested: 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 **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; /** * Defines the **ICalUid** property. */ ICalUid: PropertyDefinition; /** * Defines the **ICalRecurrenceId** property. */ ICalRecurrenceId: PropertyDefinition; /** * Defines the **ICalDateTimeStamp** property. */ ICalDateTimeStamp: PropertyDefinition; /** * Defines the **EnhancedLocation** property. */ EnhancedLocation: PropertyDefinition; /** * Defines the **JoinOnlineMeetingUrl** property. */ JoinOnlineMeetingUrl: PropertyDefinition; /** * Defines the **OnlineMeetingSettings** property. */ OnlineMeetingSettings: PropertyDefinition; /** * @internal Instance of **AppointmentSchema** */ Instance: AppointmentSchema; } /** * Represents the schema for appointment and meeting requests. */ export interface AppointmentSchemaStatic extends AppointmentSchema { }
the_stack
import {NvItemsIds, NvSystemIds, ZnpCommandStatus} from "../constants/common"; import {Subsystem} from "../unpi/constants"; import {Znp} from "../znp"; import * as Structs from "../structs"; import {BuiltTable} from "../structs"; /** * Adapter non-volatile memory instrumentation. This class provides interface to interact * with ZNP adapter's NV memory. Provided functionality covers basic operations from reading, * writing and deleting keys to extended table manipulation. */ export class AdapterNvMemory { public memoryAlignment: Structs.StructMemoryAlignment = null; private znp: Znp; public constructor(znp: Znp) { this.znp = znp; } /** * Initialize NV memory driver by examining target and determining memory alignment. */ public async init(): Promise<void> { /* use `ZCD_NV_NWKKEY` to determine if target platform uses memory alignment (length 21 = unaligned, length 24 = aligned) */ const rawNwkKey = await this.readItem(NvItemsIds.NWKKEY); this.memoryAlignment = rawNwkKey.length === 21 ? "unaligned" : "aligned"; } /** * Reads a variable-length item from NV memory and returns buffer object. Read can be offset as required. * * @param id NV item identifier. * @param offset Desired data offset to read from. */ public async readItem(id: NvItemsIds, offset?: number): Promise<Buffer>; /** * Reads a variable-length item from NV memory and creates a builds a requested struct. * * @param id NV item identifier. * @param offset Desired data offset to read from. * @param useStruct Struct factory to use to wrap the data in. */ public async readItem<R extends Structs.BuiltStruct, T extends R | Structs.BuiltTable<R>>(id: NvItemsIds, offset?: number, useStruct?: Structs.MemoryObjectFactory<T>): Promise<T>; public async readItem<R extends Structs.BuiltStruct, T extends R | Structs.BuiltTable<R>>(id: NvItemsIds, offset = 0, useStruct?: Structs.MemoryObjectFactory<T>): Promise<Buffer | T> { if (useStruct) { this.checkMemoryAlignmentSetup(); } const lengthResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "osalNvLength", {id})); if (!lengthResponse?.payload?.length || lengthResponse?.payload?.length === 0) { return null; } const length = lengthResponse.payload.length; const buffer = Buffer.alloc(length); while (offset < length) { const readResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "osalNvReadExt", {id, offset})); /* istanbul ignore next */ if (!readResponse) { return null; } /* istanbul ignore next */ if (readResponse.payload?.status !== 0) { throw new Error(`Received non-success status while reading NV (id=${id}, offset=${offset}, status=${readResponse.payload.status})`); } buffer.set(readResponse.payload.value, offset); offset += readResponse.payload.value.length; } if (useStruct) { // eslint-disable-next-line @typescript-eslint/no-explicit-any return (useStruct as any)(buffer, this.memoryAlignment) as T; } return buffer; } /** * Writes data to adapter NV memory. Method fails if write fails. * * @param id NV item identifier. * @param data Data to be written. * @param offset Offset within NV item to write the data. * @param autoInit Whether NV item should be automatically initialized if not present. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any public async writeItem(id: NvItemsIds, data: Buffer | Structs.SerializableMemoryObject, offset =0, autoInit = true): Promise<void> { this.checkMemoryAlignmentSetup(); const buffer = Buffer.isBuffer(data) ? data : data.serialize(this.memoryAlignment); const lengthResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "osalNvLength", {id})); const exists = lengthResponse.payload.length && lengthResponse.payload.length > 0; /* istanbul ignore next */ if (!exists) { const initLength = buffer.length > 240 ? 240 : buffer.length; if (!autoInit) { throw new Error(`Cannot write NV memory item which does not exist (id=${id})`); } const initResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "osalNvItemInit", {id, len: buffer.length, initlen: initLength, initvalue: buffer.slice(0, initLength)}, undefined, null, [ZnpCommandStatus.SUCCESS, ZnpCommandStatus.NV_ITEM_INITIALIZED])); if (initResponse.payload.status !== 0x09) { throw new Error(`Failed to initialize NV memory item (id=${id}, name=${NvItemsIds[id]}, len=${buffer.length}, status=${initResponse.payload.status})`); } } let remaining = buffer.length; while (remaining > 0) { /* istanbul ignore next */ const writeLength = remaining > 240 ? 240 : remaining; const dataOffset = buffer.length - remaining; const writeData = buffer.slice(dataOffset, dataOffset + writeLength); const writeResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "osalNvWriteExt", {id, offset: dataOffset, len: writeLength, value: writeData})); /* istanbul ignore next */ if (writeResponse.payload.status !== 0) { throw new Error(`Received non-success status while writing NV (id=${id}, offset=${offset}, status=${writeResponse.payload.status})`); } remaining -= writeLength; } } /** * Determines whether NV item is different from provided data and updates if necessary. * * @param id NV item identifier. * @param data Desired NV item value. * @param autoInit Whether NV item should be automatically initialized if not present. */ public async updateItem(id: NvItemsIds, data: Buffer, autoInit = true): Promise<void> { this.checkMemoryAlignmentSetup(); const current = await this.readItem(id); if (!current || !current.equals(data)) { await this.writeItem(id, data, 0, autoInit); } } /** * Deletes an NV memory item. * * @param id NV item identifier. */ public async deleteItem(id: NvItemsIds): Promise<void> { this.checkMemoryAlignmentSetup(); const lengthResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "osalNvLength", {id})); const exists = lengthResponse.payload.length && lengthResponse.payload.length > 0; /* istanbul ignore next */ if (exists) { const deleteResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "osalNvDelete", {id, len:lengthResponse.payload.length})); if (!deleteResponse || ![ZnpCommandStatus.SUCCESS, ZnpCommandStatus.NV_ITEM_INITIALIZED].includes(deleteResponse.payload.status)) { /* istanbul ignore next */ throw new Error(`Received non-success status while deleting NV (id=${id}, status=${deleteResponse.payload.status})`); } } } /** * Reads extended table entry (used by Z-Stack 3.x+). NV tables within newer Z-Stack releases include 16-bit `subId` * identifying table entries. * * @param sysId SimpleLink system identifier. * @param id NV item identifier. * @param subId Entry index. * @param offset Data offset to read from. */ public async readExtendedTableEntry(sysId: NvSystemIds, id: NvItemsIds, subId: number, offset?: number): Promise<Buffer>; public async readExtendedTableEntry<T extends Structs.BuiltStruct>(sysId: NvSystemIds, id: NvItemsIds, subId: number, offset?: number, useStruct?: Structs.MemoryObjectFactory<T>): Promise<T>; public async readExtendedTableEntry<T extends Structs.BuiltStruct>(sysId: NvSystemIds, id: NvItemsIds, subId: number, offset?: number, useStruct?: Structs.MemoryObjectFactory<T>): Promise<Buffer | T> { this.checkMemoryAlignmentSetup(); const lengthResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "nvLength", {sysid: sysId, itemid: id, subid: subId})); const exists = lengthResponse.payload.len && lengthResponse.payload.len > 0; if (exists) { const readResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "nvRead", {sysid: sysId, itemid: id, subid: subId, offset: offset || 0, len: lengthResponse.payload.len})); /* istanbul ignore next */ if (readResponse.payload.status !== 0) { throw new Error(`Received non-success status while reading NV extended table entry (sysId=${sysId}, id=${id}, subId=${subId}, offset=${offset}, status=${readResponse.payload.status})`); } /* istanbul ignore next */ if (useStruct) { return useStruct(readResponse.payload.value); } else { return readResponse.payload.value; } } return null; } /** * Writes extended table entry (user by Z-Stack 3.x+). NV tables within newer Z-Stack releases include 16-bit `subId` * identifying table tnreis. * * @param sysId SimpleLink system identifier. * @param id NV item identifier. * @param subId Entry index. * @param data Data to write to the table. * @param offset Offset to write at. * @param autoInit Whether non-existent entry should be automatically initialized. */ public async writeExtendedTableEntry(sysId: NvSystemIds, id: NvItemsIds, subId: number, data: Buffer, offset?: number, autoInit=true): Promise<void> { this.checkMemoryAlignmentSetup(); const lengthResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "nvLength", {sysid: sysId, itemid: id, subid: subId})); const exists = lengthResponse.payload.len && lengthResponse.payload.len > 0; /* istanbul ignore if */ if (!exists) { if (!autoInit) { throw new Error(`Cannot write NV memory extended table item which does not exist (sudId=${sysId}, id=${id}, subId=${subId})`); } const createResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "nvCreate", {sysid: sysId, itemid: id, subid: subId, len: data.length})); if (!createResponse || createResponse.payload.status !== ZnpCommandStatus.SUCCESS) { /* istanbul ignore next */ throw new Error(`Failed to crate NV memory extended table item with status (sudId=${sysId}, id=${id}, subId=${subId})`); } } const writeResponse = await this.retry(() => this.znp.request(Subsystem.SYS, "nvWrite", {sysid: sysId, itemid: id, subid: subId, offset: offset || 0, len: data.length, value: data})); /* istanbul ignore next */ if (writeResponse.payload.status !== 0) { throw new Error(`Received non-success status while writing NV extended table idem (sudId=${sysId}, id=${id}, subId=${subId}, offset=${offset}, status=${writeResponse.payload.status})`); } } /** * Reads a legacy NV table at defined index into raw `Buffer` object array. Providing maximum * length is necessary in order to prevent invalid memory access. * * @param mode Only legacy mode is supported with this signature. * @param id The item index at which the table starts. * @param maxLength Maximum number of items the table may contain. */ public async readTable(mode: "legacy", id: NvItemsIds, maxLength: number): Promise<Buffer[]>; /** * Reads a legacy table at defined index into a table structure covering struct entries. * Providing maximum length is necessary in order to prevent invalid memory access. * * @param mode Only legacy mode is supported with this signature. * @param id The item index at which the table starts. * @param maxLength Maximum number of items the table may contain. * @param useTable Table factory to spawn a table and populate with retrieved data. */ public async readTable<R extends Structs.BuiltStruct, T extends Structs.BuiltTable<R>>(mode: "legacy", id: NvItemsIds, maxLength: number, useTable?: Structs.MemoryObjectFactory<T>): Promise<T>; /** * Reads an extended (Z-Stack 3.x.0+) table into raw `Buffer` object array. * Maximum length is optional since the table boundary can be detected automatically. * * @param mode Only extended mode is supported with this signature. * @param sysId SimpleLink system identifier. * @param id Extended table NV index. * @param maxLength Maximum number of entries to load from the table. */ public async readTable(mode: "extended", sysId: NvSystemIds, id: NvItemsIds, maxLength?: number): Promise<Buffer[]>; /** * Reads an extended (Z-Stack 3.x.0+) table into a table structure covering struct entries. * Maximum length is optional since the table boundary can be detected automatically. * * @param mode Only extended mode is supported with this signature. * @param sysId SimpleLink system identifier. * @param id Extended table NV index. * @param maxLength Maximum number of entries to load from the table. * @param useTable Table factory to spawn a table and populate with retrieved data. */ public async readTable<R extends Structs.BuiltStruct, T extends Structs.BuiltTable<R>>(mode: "extended", sysId: NvSystemIds, id: NvItemsIds, maxLength?: number, useTable?: Structs.MemoryObjectFactory<T>): Promise<T>; public async readTable<R extends Structs.BuiltStruct, T extends Structs.BuiltTable<R>>(mode: "legacy" | "extended", p1: NvSystemIds | NvItemsIds, p2: NvItemsIds | number, p3?: Structs.MemoryObjectFactory<T> | number, p4?: Structs.MemoryObjectFactory<T>): Promise<Buffer[] | T> { const sysId = mode === "legacy" ? undefined : p1 as NvSystemIds; const id = (mode === "legacy" ? p1 : p2) as NvItemsIds; const maxLength = (mode === "legacy" ? p2 : p3) as number; const useTable = (mode === "legacy" ? p3 : p4) as Structs.MemoryObjectFactory<T>; const rawEntries: Buffer[] = []; let entryOffset = 0; let rawEntry = null; if (mode === "legacy") { do { rawEntry = await this.readItem(id + (entryOffset++)); if (rawEntry) { rawEntries.push(rawEntry); } } while (rawEntry !== null && entryOffset < maxLength); } else { /* istanbul ignore next */ do { rawEntry = await this.readExtendedTableEntry(sysId, id, entryOffset++); if (rawEntry) { rawEntries.push(rawEntry); } } while (rawEntry !== null && (!maxLength || entryOffset < maxLength)); } /* istanbul ignore next */ return useTable ? useTable(rawEntries) : rawEntries; } /** * Writes a struct-based table structure into a legacy NV memory position. * * @param mode Only legacy mode is supported with this signature. * @param id Start NV item index. * @param table Table structure to write to NV memory. */ public async writeTable<R extends Structs.BuiltStruct>(mode: "legacy", id: NvItemsIds, table: BuiltTable<R>): Promise<void>; /** * Writes a struct-based table structure into an extended NV memory position. * * @param mode Only extended mode is supported with this signature. * @param sysId SimpleLink system identifier. * @param id Extended table NV item index. * @param table Table structure to write to NV memory. */ public async writeTable<R extends Structs.BuiltStruct>(mode: "extended", sysId: NvSystemIds, id: NvItemsIds, table: BuiltTable<R>): Promise<void>; public async writeTable<R extends Structs.BuiltStruct>(mode: "extended" | "legacy", p1: NvSystemIds | NvItemsIds, p2: NvItemsIds | BuiltTable<R>, p3?: BuiltTable<R>): Promise<void> { this.checkMemoryAlignmentSetup(); const sysId = mode === "legacy" ? undefined : p1 as NvSystemIds; const id = (mode === "legacy" ? p1 : p2) as NvItemsIds; const table = (mode === "legacy" ? p2 : p3) as BuiltTable<R>; if (mode === "legacy") { for (const [index, entry] of table.entries.entries()) { await this.writeItem(id + index, entry.serialize(this.memoryAlignment)); } } else { for (const [index, entry] of table.entries.entries()) { await this.writeExtendedTableEntry(sysId, id, index, entry.serialize(this.memoryAlignment)); } } } /** * Internal function to prevent occasional ZNP request failures. * * *Some timeouts were present when working with SimpleLink Z-Stack 3.x.0+.* * * @param fn Function to retry. * @param retries Maximum number of retries. */ private async retry<R>(fn: (() => Promise<R>), retries = 3): Promise<R> { let i = 0; while (i < retries) { try { const result = await fn(); return result; } catch (error) { /* istanbul ignore next */ if (i >= retries) { /* istanbul ignore next */ throw error; } } /* istanbul ignore next */ i++; } } /** * Internal function used by NV manipulation methods to check for correct driver initialization. */ private checkMemoryAlignmentSetup(): void { /* istanbul ignore next */ if (this.memoryAlignment === null) { throw new Error("adapter memory alignment unknown - has nv memory driver been initialized?"); } } }
the_stack
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; import 'chrome://resources/cr_elements/cr_nav_menu_item_style.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/polymer/v3_0/paper-ripple/paper-ripple.js'; import './shared_style.js'; import './strings.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {isRTL} from 'chrome://resources/js/util.m.js'; import {html, microTask, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {changeFolderOpen, selectFolder} from './actions.js'; import {BookmarksCommandManagerElement} from './command_manager.js'; import {FOLDER_OPEN_BY_DEFAULT_DEPTH, MenuSource, ROOT_NODE_ID} from './constants.js'; import {StoreClientMixin} from './store_client_mixin.js'; import {BookmarkNode} from './types.js'; import {hasChildFolders, isShowingSearch} from './util.js'; const BookmarksFolderNodeElementBase = StoreClientMixin(PolymerElement); // Workaround because TS compiler doesn't know about scrollIntoViewIfNeeded(). type HTMLDivElementWithScroll = HTMLDivElement&{ scrollIntoViewIfNeeded: () => void; }; export interface BookmarksFolderNodeElement { $: { container: HTMLDivElementWithScroll, descendants: HTMLDivElement, } } export class BookmarksFolderNodeElement extends BookmarksFolderNodeElementBase { static get is() { return 'bookmarks-folder-node'; } static get template() { return html`{__html_template__}`; } static get properties() { return { itemId: { type: String, observer: 'updateFromStore', }, depth: { type: Number, observer: 'depthChanged_', }, isOpen: { type: Boolean, computed: 'computeIsOpen_(openState_, depth)', }, item_: Object, openState_: Boolean, selectedFolder_: String, searchActive_: Boolean, isSelectedFolder_: { type: Boolean, reflectToAttribute: true, computed: 'computeIsSelected_(itemId, selectedFolder_, searchActive_)' }, hasChildFolder_: { type: Boolean, computed: 'computeHasChildFolder_(item_.children)', }, }; } depth: number; isOpen: boolean; itemId: string; private item_: BookmarkNode; private openState_: boolean; private selectedFolder_: string; private searchActive_: boolean; private isSelectedFolder_: boolean = false; private hasChildFolder_: boolean; static get observers() { return [ 'updateAriaExpanded_(hasChildFolder_, isOpen)', 'scrollIntoViewIfNeeded_(isSelectedFolder_)', ]; } ready() { super.ready(); this.addEventListener('keydown', e => this.onKeydown_(e)); } /** @override */ connectedCallback() { super.connectedCallback(); this.watch('item_', state => { return state.nodes[this.itemId]; }); this.watch('openState_', state => { return state.folderOpenState.has(this.itemId) ? state.folderOpenState.get(this.itemId) : null; }); this.watch('selectedFolder_', state => state.selectedFolder); this.watch('searchActive_', state => { return isShowingSearch(state); }); this.updateFromStore(); } private getContainerClass_(isSelectedFolder: boolean): string { return isSelectedFolder ? 'selected' : ''; } getFocusTarget(): HTMLElement { return this.$.container; } getDropTarget(): HTMLElement { return this.$.container; } private onKeydown_(e: KeyboardEvent) { let yDirection = 0; let xDirection = 0; let handled = true; if (e.key === 'ArrowUp') { yDirection = -1; } else if (e.key === 'ArrowDown') { yDirection = 1; } else if (e.key === 'ArrowLeft') { xDirection = -1; } else if (e.key === 'ArrowRight') { xDirection = 1; } else if (e.key === ' ') { this.selectFolder_(); } else { handled = false; } if (isRTL()) { xDirection *= -1; } this.changeKeyboardSelection_( xDirection, yDirection, this.shadowRoot!.activeElement); if (!handled) { handled = BookmarksCommandManagerElement.getInstance().handleKeyEvent( e, new Set([this.itemId])); } if (!handled) { return; } e.preventDefault(); e.stopPropagation(); } private changeKeyboardSelection_( xDirection: number, yDirection: number, currentFocus: Element|null) { let newFocusFolderNode = null; const isChildFolderNodeFocused = currentFocus && (currentFocus as HTMLElement)!.tagName === 'BOOKMARKS-FOLDER-NODE'; if (xDirection === 1) { // The right arrow opens a folder if closed and goes to the first child // otherwise. if (this.hasChildFolder_) { if (!this.isOpen) { this.dispatch(changeFolderOpen(this.item_.id, true)); } else { yDirection = 1; } } } else if (xDirection === -1) { // The left arrow closes a folder if open and goes to the parent // otherwise. if (this.hasChildFolder_ && this.isOpen) { this.dispatch(changeFolderOpen(this.item_.id, false)); } else { const parentFolderNode = this.getParentFolderNode_(); if (parentFolderNode!.itemId !== ROOT_NODE_ID) { parentFolderNode!.getFocusTarget().focus(); } } } if (!yDirection) { return; } // The current node's successor is its first child when open. if (!isChildFolderNodeFocused && yDirection === 1 && this.isOpen) { const children = this.getChildFolderNodes_(); if (children.length) { newFocusFolderNode = children[0]; } } if (isChildFolderNodeFocused) { // Get the next child folder node if a child is focused. if (!newFocusFolderNode) { newFocusFolderNode = this.getNextChild_( yDirection === -1, (currentFocus! as BookmarksFolderNodeElement)); } // The first child's predecessor is this node. if (!newFocusFolderNode && yDirection === -1) { newFocusFolderNode = this; } } // If there is no newly focused node, allow the parent to handle the change. if (!newFocusFolderNode) { if (this.itemId !== ROOT_NODE_ID) { this.getParentFolderNode_()!.changeKeyboardSelection_( 0, yDirection, this); } return; } // The root node is not navigable. if (newFocusFolderNode.itemId !== ROOT_NODE_ID) { newFocusFolderNode.getFocusTarget().focus(); } } /** * Returns the next or previous visible bookmark node relative to |child|. */ private getNextChild_(reverse: boolean, child: BookmarksFolderNodeElement): BookmarksFolderNodeElement|null { let newFocus = null; const children = this.getChildFolderNodes_(); const index = children.indexOf(child); assert(index !== -1); if (reverse) { // A child node's predecessor is either the previous child's last visible // descendant, or this node, which is its immediate parent. newFocus = index === 0 ? null : children[index - 1]!.getLastVisibleDescendant_(); } else if (index < children.length - 1) { // A successor to a child is the next child. newFocus = children[index + 1]!; } return newFocus; } /** * Returns the immediate parent folder node, or null if there is none. */ private getParentFolderNode_(): BookmarksFolderNodeElement|null { let parentFolderNode = this.parentNode; while (parentFolderNode && (parentFolderNode as HTMLElement).tagName !== 'BOOKMARKS-FOLDER-NODE') { parentFolderNode = parentFolderNode.parentNode || (parentFolderNode as ShadowRoot).host; } return (parentFolderNode as BookmarksFolderNodeElement) || null; } private getLastVisibleDescendant_(): BookmarksFolderNodeElement { const children = this.getChildFolderNodes_(); if (!this.isOpen || children.length === 0) { return this; } return children.pop()!.getLastVisibleDescendant_(); } private selectFolder_() { if (!this.isSelectedFolder_) { this.dispatch(selectFolder(this.itemId, this.getState().nodes)); } } private onContextMenu_(e: MouseEvent) { e.preventDefault(); this.selectFolder_(); BookmarksCommandManagerElement.getInstance().openCommandMenuAtPosition( e.clientX, e.clientY, MenuSource.TREE, new Set([this.itemId])); } private getChildFolderNodes_(): BookmarksFolderNodeElement[] { return Array.from(this.shadowRoot!.querySelectorAll( 'bookmarks-folder-node')); } /** * Toggles whether the folder is open. */ private toggleFolder_(e: Event) { this.dispatch(changeFolderOpen(this.itemId, !this.isOpen)); e.stopPropagation(); } private preventDefault_(e: Event) { e.preventDefault(); } private computeIsSelected_( itemId: string, selectedFolder: string, searchActive: boolean): boolean { return itemId === selectedFolder && !searchActive; } private computeHasChildFolder_(): boolean { return hasChildFolders(this.itemId, this.getState().nodes); } private depthChanged_() { this.style.setProperty('--node-depth', String(this.depth)); if (this.depth === -1) { this.$.descendants.removeAttribute('role'); } } private getChildDepth_(): number { return this.depth + 1; } private isFolder_(itemId: string): boolean { return !this.getState().nodes[itemId]!.url; } private isRootFolder_(): boolean { return this.itemId === ROOT_NODE_ID; } private getTabIndex_(): string { // This returns a tab index of 0 for the cached selected folder when the // search is active, even though this node is not technically selected. This // allows the sidebar to be focusable during a search. return this.selectedFolder_ === this.itemId ? '0' : '-1'; } /** * Sets the 'aria-expanded' accessibility on nodes which need it. Note that * aria-expanded="false" is different to having the attribute be undefined. */ private updateAriaExpanded_(hasChildFolder: boolean, isOpen: boolean) { if (hasChildFolder) { this.getFocusTarget().setAttribute('aria-expanded', String(isOpen)); } else { this.getFocusTarget().removeAttribute('aria-expanded'); } } /** * Scrolls the folder node into view when the folder is selected. */ private scrollIntoViewIfNeeded_() { if (!this.isSelectedFolder_) { return; } microTask.run(() => this.$.container.scrollIntoViewIfNeeded()); } private computeIsOpen_(openState: boolean|null, depth: number): boolean { return openState != null ? openState : depth <= FOLDER_OPEN_BY_DEFAULT_DEPTH; } } declare global { interface HTMLElementTagNameMap { 'bookmarks-folder-node': BookmarksFolderNodeElement; } } customElements.define( BookmarksFolderNodeElement.is, BookmarksFolderNodeElement);
the_stack
const DATA = "<BASE64_DATA_PLACEHOLDER>"; // Standard Myanmar code point range before digits const STD_CP0 = 0x1000; const STD_CP1 = 0x103F; // Standard Myanmar code point range after digits const AFT_CP0 = 0x104A; const AFT_CP1 = 0x109F; // Extended Myanmar code point range A const EXA_CP0 = 0xAA60; const EXA_CP1 = 0xAA7F; // Extended Myanmar code point range B const EXB_CP0 = 0xA9E0; const EXB_CP1 = 0xA9FF; // Unicode space characters const SPC_CP0 = 0x2000; const SPC_CP1 = 0x200B; // Indices into Markov nodes const STD_OFFSET = 1; const AFT_OFFSET = STD_OFFSET + STD_CP1 - STD_CP0 + 1; const EXA_OFFSET = AFT_OFFSET + AFT_CP1 - AFT_CP0 + 1; const EXB_OFFSET = EXA_OFFSET + EXA_CP1 - EXA_CP0 + 1; const SPC_OFFSET = EXB_OFFSET + EXB_CP1 - EXB_CP0 + 1; const NUM_STATES = SPC_OFFSET + SPC_CP1 - SPC_CP0 + 1; /** * SSV: An ID representing which Unicode code points to include in the model: * * <p>SSV_STD_EXA_EXB_SPC - include Myanmar, Extended A, Extended B, and space-like * <p>STD_EXA_EXB - same as above but no space-like code points * * <p>"SSV" originally stands for State Set Version. */ const SSV_STD_EXA_EXB_SPC = 0; const SSV_STD_EXA_EXB = 1; const SSV_COUNT = 2; /** * Returns the index of the state in the Markov chain corresponding to the given code point. * * <p>Code points in the standard Myanmar range, Myanmar Extended A, Myanmar Extended B, and * Unicode Whitespace each have a unique state assigned to them. All other code points are mapped * to state 0. * * @param cp The code point to convert to a state index. * @return The index of the state in the Markov chain. 0 <= state < getSize() */ function getIndexForCodePoint(cp: number, ssv: number): number { if (STD_CP0 <= cp && cp <= STD_CP1) { return cp - STD_CP0 + STD_OFFSET; } if (AFT_CP0 <= cp && cp <= AFT_CP1) { return cp - AFT_CP0 + AFT_OFFSET; } if (EXA_CP0 <= cp && cp <= EXA_CP1) { return cp - EXA_CP0 + EXA_OFFSET; } if (EXB_CP0 <= cp && cp <= EXB_CP1) { return cp - EXB_CP0 + EXB_OFFSET; } if (ssv == SSV_STD_EXA_EXB_SPC && SPC_CP0 <= cp && cp <= SPC_CP1) { return cp - SPC_CP0 + SPC_OFFSET; } return 0; } function checkMagicNumberAndVersion(stream: DataView, offset: number, expectedBinaryTagLead: number, expectedBinaryTagTrail: number, expectedBinaryVersion: number): number { const binaryTagLead = stream.getUint32(offset); offset += 4; if (binaryTagLead !== expectedBinaryTagLead) { throw new Error("Unexpected magic number lead; expected " + expectedBinaryTagLead.toString(16) + " but got " + binaryTagLead.toString(16)); } const binaryTagTrail = stream.getUint32(offset); offset += 4; if (binaryTagTrail !== expectedBinaryTagTrail) { throw new Error("Unexpected magic number trail; expected " + expectedBinaryTagTrail.toString(16) + " but got " + binaryTagTrail.toString(16)); } // If expectedBinaryVersion is -1, don't check or consume it. if (expectedBinaryVersion !== -1) { const binaryVersion = stream.getUint32(offset); offset += 4; if (binaryVersion !== expectedBinaryVersion) { throw new Error("Unexpected serial version number; expected " + expectedBinaryVersion.toString(16) + " but got " + binaryVersion.toString(16)); } } return offset; } // This is different on Node vs Browser. let getArrayBuffer: () => ArrayBuffer; // @if NODEJS getArrayBuffer = () => { // Buffer is defined on Node // @ts-ignore const nodeBuffer = new Buffer(DATA, "base64"); const arrayBuffer = new ArrayBuffer(nodeBuffer.length); const u8view = new Uint8Array(arrayBuffer); for (let i = 0; i < nodeBuffer.length; i++) { u8view[i] = nodeBuffer[i]; } return arrayBuffer; }; // @endif // @if !NODEJS getArrayBuffer = () => { const binaryString = atob(DATA); const arrayBuffer = new ArrayBuffer(binaryString.length); const u8view = new Uint8Array(arrayBuffer); for (let i = 0; i < binaryString.length; i++) { u8view[i] = binaryString.charCodeAt(i); } return arrayBuffer; }; // @endif class BinaryMarkov { // JavaScript doesn't have the concept of 64-bit integers, so split the tag into two 32-bit ints. private static BINARY_TAG_LEAD = 0x424D4152; private static BINARY_TAG_TRAIL = 0x4B4F5620; // Current serial format version number, used in association with the magic number. private static BINARY_VERSION = 0; private logProbabilityDifferences: number[][]; constructor(stream: DataView, offset: number) { // @if NODEJS offset = checkMagicNumberAndVersion(stream, offset, BinaryMarkov.BINARY_TAG_LEAD, BinaryMarkov.BINARY_TAG_TRAIL, BinaryMarkov.BINARY_VERSION); // @endif // @if !NODEJS // Don't include the magic number checking code in a minified build offset += 12; // @endif const size = stream.getInt16(offset); offset += 2; const logProbabilityDifferences: number[][] = []; for (let i1 = 0; i1 < size; i1++) { logProbabilityDifferences[i1] = []; let entries = stream.getInt16(offset); offset += 2; let fallback: number; if (entries === 0) { fallback = 0.0; } else { fallback = stream.getFloat32(offset); offset += 4; } let next = -1; for (let i2 = 0; i2 < size; i2++) { if (entries > 0 && next < i2) { next = stream.getInt16(offset); offset += 2; entries--; } if (next === i2) { logProbabilityDifferences[i1][i2] = stream.getFloat32(offset); offset += 4; } else { logProbabilityDifferences[i1][i2] = fallback; } } } this.logProbabilityDifferences = logProbabilityDifferences; } getLogProbabilityDifference(i1: number, i2: number): number { return this.logProbabilityDifferences[i1][i2]; } } class ZawgyiUnicodeMarkovModel { // JavaScript doesn't have the concept of 64-bit integers, so split the tag into two 32-bit ints. private static BINARY_TAG_LEAD = 0x555A4D4F; private static BINARY_TAG_TRAIL = 0x44454C20; private classifier: BinaryMarkov; private ssv: number; constructor(stream: DataView, offset: number) { // @if NODEJS offset = checkMagicNumberAndVersion(stream, offset, ZawgyiUnicodeMarkovModel.BINARY_TAG_LEAD, ZawgyiUnicodeMarkovModel.BINARY_TAG_TRAIL, -1); // @endif // @if !NODEJS // Don't include the magic number checking code in a minified build offset += 8; // @endif const binaryVersion = stream.getUint32(offset); offset += 4; if (binaryVersion === 1) { // No SSV field this.ssv = 0; } else if (binaryVersion === 2) { this.ssv = stream.getUint32(offset); offset += 4; } else { throw new Error("Serial version: expected 1 or 2 but got " + binaryVersion.toString(16)); } this.classifier = new BinaryMarkov(stream, offset); } predict(input: string): number { // Start at the base state let prevState = 0; let totalDelta = 0.0; let seenTransition = false; for (let offset = 0; offset <= input.length; offset++) { let currState; if (offset === input.length) { currState = 0; } else { // Note: All interesting characters are in the BMP. const cp = input.charCodeAt(offset); currState = getIndexForCodePoint(cp, this.ssv); } // Ignore 0-to-0 transitions if (prevState !== 0 || currState !== 0) { const delta = this.classifier.getLogProbabilityDifference(prevState, currState); totalDelta += delta; seenTransition = true; } prevState = currState; } // Special case: if there is no signal, return -Infinity, // which will get interpreted by users as strong Unicode. // This happens when the input string contains no Myanmar-range code points. if (!seenTransition) { return Number.NEGATIVE_INFINITY; } // result = Pz/(Pu+Pz) // = exp(logPz)/(exp(logPu)+exp(logPz)) // = 1/(1+exp(logPu-logPz)) return 1.0 / (1.0 + Math.exp(totalDelta)); } } export class ZawgyiDetector { private model: ZawgyiUnicodeMarkovModel; /** Loads the model from the resource and returns a ZawgyiDetector instance. */ constructor() { // Convert the Base64 to an ArrayBuffer. const arrayBuffer = getArrayBuffer(); this.model = new ZawgyiUnicodeMarkovModel(new DataView(arrayBuffer, 0), 0); } /** * Performs detection on the given string. Returns the probability that the string is Zawgyi given * that it is either Unicode or Zawgyi. Values approaching 1 are strong Zawgyi; values approaching * 0 are strong Unicode; and values close to 0.5 are toss-ups. * * <p>If the string does not contain any Myanmar range code points, -Infinity is returned. * * @param input The string on which to run detection. * @return The probability that the string is Zawgyi (between 0 and 1), or -Infinity if the string * contains no Myanmar range code points. */ getZawgyiProbability(input: string): number { return this.model.predict(input); } }
the_stack
import MultiFormat from '@requestnetwork/multi-format'; import { IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; import Utils from '@requestnetwork/utils'; import CreateAction from '../../../src/actions/create'; import Version from '../../../src/version'; const CURRENT_VERSION = Version.currentVersion; import * as TestData from '../utils/test-data-generator'; /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('CreateAction', () => { describe('format', () => { it('can create with only the payee', async () => { const actionCreation = await CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, timestamp: TestData.arbitraryTimestamp, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); // 'action is wrong' expect(actionCreation.data.name).toBe(RequestLogicTypes.ACTION_NAME.CREATE); // 'actionCreation.data.version is wrong' expect(actionCreation.data.version).toBe(CURRENT_VERSION); // 'currency is wrong' expect(actionCreation.data.parameters.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'expectedAmount is wrong' expect(actionCreation.data.parameters.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'timestamp is wrong' expect(actionCreation.data.parameters.timestamp).toBe(TestData.arbitraryTimestamp); // 'nonce is wrong' expect(actionCreation.data.parameters.nonce).toBeUndefined(); // 'extensionsData is wrong' expect(actionCreation.data.parameters.extensionsData).toBeUndefined(); // 'payer is wrong' expect(actionCreation.data.parameters.payer).toBeUndefined(); // 'actionCreation.data.parameters.payee is wrong' expect(actionCreation.data.parameters).toHaveProperty('payee'); // 'actionCreation.data.parameters.payee.type is wrong' expect(actionCreation.data.parameters.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'actionCreation.data.parameters.payee.value is wrong' expect(actionCreation.data.parameters.payee.value).toBe(TestData.payeeRaw.address); }); it('can create with nonce', async () => { const actionCreation = await CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, nonce: 2, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, timestamp: TestData.arbitraryTimestamp, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); // 'action is wrong' expect(actionCreation.data.name).toBe(RequestLogicTypes.ACTION_NAME.CREATE); // 'actionCreation.data.version is wrong' expect(actionCreation.data.version).toBe(CURRENT_VERSION); // 'currency is wrong' expect(actionCreation.data.parameters.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'expectedAmount is wrong' expect(actionCreation.data.parameters.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'timestamp is wrong' expect(actionCreation.data.parameters.timestamp).toBe(TestData.arbitraryTimestamp); // 'nonce is wrong' expect(actionCreation.data.parameters.nonce).toBe(2); // 'extensionsData is wrong' expect(actionCreation.data.parameters.extensionsData).toBeUndefined(); // 'payer is wrong' expect(actionCreation.data.parameters.payer).toBeUndefined(); // 'actionCreation.data.parameters.payee is wrong' expect(actionCreation.data.parameters).toHaveProperty('payee'); // 'actionCreation.data.parameters.payee.type is wrong' expect(actionCreation.data.parameters.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'actionCreation.data.parameters.payee.value is wrong' expect(actionCreation.data.parameters.payee.value).toBe(TestData.payeeRaw.address); }); it('can generate timestamp if not given', async () => { const actionCreation = await CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); // 'action is wrong' expect(actionCreation.data.name).toBe(RequestLogicTypes.ACTION_NAME.CREATE); // 'actionCreation.data.version is wrong' expect(actionCreation.data.version).toBe(CURRENT_VERSION); // 'currency is wrong' expect(actionCreation.data.parameters.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'expectedAmount is wrong' expect(actionCreation.data.parameters.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'extensionsData is wrong' expect(actionCreation.data.parameters.extensionsData).toBeUndefined(); // 'payer is wrong' expect(actionCreation.data.parameters.payer).toBeUndefined(); // 'actionCreation.data.parameters.payee is wrong' expect(actionCreation.data.parameters).toHaveProperty('payee'); // 'actionCreation.data.parameters.payee.type is wrong' expect(actionCreation.data.parameters.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'actionCreation.data.parameters.payee.value is wrong' expect(actionCreation.data.parameters.payee.value).toBe(TestData.payeeRaw.address); // 'timestamp is wrong' expect(actionCreation.data.parameters.timestamp).toBeDefined(); }); it('can create with only the payer', async () => { const actionCreation = await CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payer: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payerRaw.address, }, timestamp: TestData.arbitraryTimestamp, }, TestData.payerRaw.identity, TestData.fakeSignatureProvider, ); // 'action is wrong' expect(actionCreation.data.name).toBe(RequestLogicTypes.ACTION_NAME.CREATE); // 'actionCreation.data.version is wrong' expect(actionCreation.data.version).toBe(CURRENT_VERSION); // 'currency is wrong' expect(actionCreation.data.parameters.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'expectedAmount is wrong' expect(actionCreation.data.parameters.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'extensionsData is wrong' expect(actionCreation.data.parameters.extensionsData).toBeUndefined(); // 'payee is wrong' expect(actionCreation.data.parameters.payee).toBeUndefined(); // 'actionCreation.data.parameters.payer is wrong' expect(actionCreation.data.parameters).toHaveProperty('payer'); // 'actionCreation.data.parameters.payer.type is wrong' expect(actionCreation.data.parameters.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'actionCreation.data.parameters.payer.value is wrong' expect(actionCreation.data.parameters.payer.value).toBe(TestData.payerRaw.address); }); it('can create with the payee and the payer', async () => { const actionCreation = await CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, payer: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payerRaw.address, }, timestamp: TestData.arbitraryTimestamp, }, TestData.payerRaw.identity, TestData.fakeSignatureProvider, ); // 'action is wrong' expect(actionCreation.data.name).toBe(RequestLogicTypes.ACTION_NAME.CREATE); // 'actionCreation.data.version is wrong' expect(actionCreation.data.version).toBe(CURRENT_VERSION); // 'currency is wrong' expect(actionCreation.data.parameters.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'expectedAmount is wrong' expect(actionCreation.data.parameters.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'extensionsData is wrong' expect(actionCreation.data.parameters.extensionsData).toBeUndefined(); // 'actionCreation.data.parameters.payee is wrong' expect(actionCreation.data.parameters).toHaveProperty('payee'); // 'actionCreation.data.parameters.payee.type is wrong' expect(actionCreation.data.parameters.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'actionCreation.data.parameters.payee.value is wrong' expect(actionCreation.data.parameters.payee.value).toBe(TestData.payeeRaw.address); // 'actionCreation.data.parameters.payer is wrong' expect(actionCreation.data.parameters).toHaveProperty('payer'); // 'actionCreation.data.parameters.payer.type is wrong' expect(actionCreation.data.parameters.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'actionCreation.data.parameters.payer.value is wrong' expect(actionCreation.data.parameters.payer.value).toBe(TestData.payerRaw.address); }); it('can create with the payee but the payer is a smartcontract', async () => { const actionCreation = await CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, payer: { network: 'private', type: IdentityTypes.TYPE.ETHEREUM_SMART_CONTRACT, value: TestData.payerRaw.address, } as IdentityTypes.ISmartContractIdentity, timestamp: TestData.arbitraryTimestamp, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); // 'action is wrong' expect(actionCreation.data.name).toBe(RequestLogicTypes.ACTION_NAME.CREATE); // 'actionCreation.data.version is wrong' expect(actionCreation.data.version).toBe(CURRENT_VERSION); // 'currency is wrong' expect(actionCreation.data.parameters.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'expectedAmount is wrong' expect(actionCreation.data.parameters.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'timestamp is wrong' expect(actionCreation.data.parameters.timestamp).toBe(TestData.arbitraryTimestamp); // 'nonce is wrong' expect(actionCreation.data.parameters.nonce).toBeUndefined(); // 'extensionsData is wrong' expect(actionCreation.data.parameters.extensionsData).toBeUndefined(); // 'actionCreation.data.parameters.payer is wrong' expect(actionCreation.data.parameters).toHaveProperty('payer'); // 'actionCreation.data.parameters.payer.type is wrong' expect(actionCreation.data.parameters.payer.type).toBe( IdentityTypes.TYPE.ETHEREUM_SMART_CONTRACT, ); // 'actionCreation.data.parameters.payer.value is wrong' expect(actionCreation.data.parameters.payer.value).toBe(TestData.payerRaw.address); // 'actionCreation.data.parameters.payer.network is wrong' expect(actionCreation.data.parameters.payer.network).toBe('private'); // 'actionCreation.data.parameters.payee is wrong' expect(actionCreation.data.parameters).toHaveProperty('payee'); // 'actionCreation.data.parameters.payee.type is wrong' expect(actionCreation.data.parameters.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'actionCreation.data.parameters.payee.value is wrong' expect(actionCreation.data.parameters.payee.value).toBe(TestData.payeeRaw.address); }); it('cannot create with a smartcontract', () => { expect(() => CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payee: { network: 'rinkeby', type: IdentityTypes.TYPE.ETHEREUM_SMART_CONTRACT, value: TestData.payeeRaw.address, } as IdentityTypes.ISmartContractIdentity, timestamp: TestData.arbitraryTimestamp, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ), ).toThrowError('Signer must be the payee or the payer'); }); it('cannot create without payee and payer', () => { expect(() => CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, timestamp: TestData.arbitraryTimestamp, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ), ).toThrowError('payee or PayerId must be given'); }); it('cannot create with amount as decimal', () => { expect(() => CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '0.1234', payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ), ).toThrowError('expectedAmount must be a positive integer'); }); it('cannot create with amount not a number', () => { expect(() => CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: 'NaN', payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ), ).toThrowError('expectedAmount must be a positive integer'); }); it('can format create with extensionsData', async () => { const extensionsData = [{ id: 'extension1', value: 'whatever' }]; const actionCreation = await CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, extensionsData, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, payer: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payerRaw.address, }, timestamp: TestData.arbitraryTimestamp, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); // 'action is wrong' expect(actionCreation.data.name).toBe(RequestLogicTypes.ACTION_NAME.CREATE); // 'currency is wrong' expect(actionCreation.data.parameters.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'expectedAmount is wrong' expect(actionCreation.data.parameters.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'actionCreation.data.parameters.extensionsData is wrong' expect(actionCreation.data.parameters.extensionsData).toEqual(extensionsData); // 'actionCreation.data.parameters.payee is wrong' expect(actionCreation.data.parameters).toHaveProperty('payee'); // 'actionCreation.data.parameters.payee.type is wrong' expect(actionCreation.data.parameters.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'actionCreation.data.parameters.payee.value is wrong' expect(actionCreation.data.parameters.payee.value).toBe(TestData.payeeRaw.address); // 'actionCreation.data.parameters.payer is wrong' expect(actionCreation.data.parameters).toHaveProperty('payer'); // 'actionCreation.data.parameters.payer.type is wrong' expect(actionCreation.data.parameters.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'actionCreation.data.parameters.payer.value is wrong' expect(actionCreation.data.parameters.payer.value).toBe(TestData.payerRaw.address); }); it('cannot sign with ECDSA by another', () => { expect(() => CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, payer: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payerRaw.address, }, }, TestData.otherIdRaw.identity, TestData.fakeSignatureProvider, ), ).toThrowError('Signer must be the payee or the payer'); }); it('cannot sign with ECDSA by payer if only payee given', () => { expect(() => CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, }, TestData.payerRaw.identity, TestData.fakeSignatureProvider, ), ).toThrowError('Signer must be the payee or the payer'); }); it('cannot sign with ECDSA by payee if only payer given', () => { expect(() => CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payer: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payerRaw.address, }, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ), ).toThrowError('Signer must be the payee or the payer'); }); it('can create with amount as integer or zero', async () => { let actionCreation = await CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: 10000, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); // 'expectedAmount is wrong' expect(actionCreation.data.parameters.expectedAmount).toBe('10000'); actionCreation = await CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: 0, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); // 'expectedAmount is wrong' expect(actionCreation.data.parameters.expectedAmount).toBe('0'); }); it('cannot create with amount as negative', () => { expect(() => CreateAction.format( { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '-1000', payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, }, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ), ).toThrowError('expectedAmount must be a positive integer'); }); it('does not support other identity type than "ethereumAddress" for Payee', () => { const params: any = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '1000', payee: { type: 'not_ethereumAddress', value: '0xAf083f77F1fFd54218d91491AFD06c9296EaC3ce', }, payer: TestData.payerRaw.identity, }; expect(() => CreateAction.format(params, TestData.payerRaw.identity, TestData.fakeSignatureProvider), ).toThrowError('payee: identity type not supported'); }); it('does not support other identity type than "ethereumAddress" for Payer', () => { const params: any = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '1000', payee: TestData.payeeRaw.identity, payer: { type: 'not_ethereumAddress', value: '0xAf083f77F1fFd54218d91491AFD06c9296EaC3ce', }, }; expect(() => CreateAction.format(params, TestData.payeeRaw.identity, TestData.fakeSignatureProvider), ).toThrowError('payer: identity type not supported'); }); it('does not support other identity value not ethereum for Payee', () => { const params: any = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '1000', payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: 'not valid ethereum', }, }; expect(() => CreateAction.format(params, TestData.payeeRaw.identity, TestData.fakeSignatureProvider), ).toThrowError('payee: identity value must be an ethereum address'); }); it('does not support other identity value not ethereum for Payer', () => { const params: any = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '1000', payer: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: 'not valid ethereum', }, }; expect(() => CreateAction.format(params, TestData.payeeRaw.identity, TestData.fakeSignatureProvider), ).toThrowError('payer: identity value must be an ethereum address'); }); }); describe('createRequest', () => { it('can create with only the payee', async () => { const createParams = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, timestamp: TestData.arbitraryTimestamp, }; const actionCreation = await CreateAction.format( createParams, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' expect(request.requestId).toBe( MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), ); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'state is wrong' expect(request.state).toBe(RequestLogicTypes.STATE.CREATED); // 'expectedAmount is wrong' expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'extensions is wrong' expect(request.extensions).toEqual({}); // 'request should have property creator' expect(request).toHaveProperty('creator'); // 'request.creator.type is wrong' expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.creator.value is wrong' expect(request.creator.value).toBe(TestData.payeeRaw.address); // 'request should have property payee' expect(request).toHaveProperty('payee'); if (request.payee) { // 'request.payee.type is wrong' expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payee.value is wrong' expect(request.payee.value).toBe(TestData.payeeRaw.address); } // 'payer is wrong' expect(request.payer).toBeUndefined(); // 'request.events is wrong' expect(request.events[0]).toEqual({ actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { expectedAmount: TestData.arbitraryExpectedAmount, extensionsDataLength: 0, isSignedRequest: false, }, timestamp: 2, }); // 'timestamp is wrong' expect(request.timestamp).toBe(TestData.arbitraryTimestamp); }); it('can create with nonce', async () => { const createParams = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, nonce: 3, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, timestamp: TestData.arbitraryTimestamp, }; const actionCreation = await CreateAction.format( createParams, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' expect(request.requestId).toBe( MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), ); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'state is wrong' expect(request.state).toBe(RequestLogicTypes.STATE.CREATED); // 'expectedAmount is wrong' expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'extensions is wrong' expect(request.extensions).toEqual({}); // 'request should have property creator' expect(request).toHaveProperty('creator'); // 'request.creator.type is wrong' expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.creator.value is wrong' expect(request.creator.value).toBe(TestData.payeeRaw.address); // 'request should have property payee' expect(request).toHaveProperty('payee'); if (request.payee) { // 'request.payee.type is wrong' expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payee.value is wrong' expect(request.payee.value).toBe(TestData.payeeRaw.address); } // 'payer is wrong' expect(request.payer).toBeUndefined(); // 'request.events is wrong' expect(request.events[0]).toEqual({ actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { expectedAmount: TestData.arbitraryExpectedAmount, extensionsDataLength: 0, isSignedRequest: false, }, timestamp: 2, }); // 'timestamp is wrong' expect(request.timestamp).toBe(TestData.arbitraryTimestamp); // 'nonce is wrong' expect(request.nonce).toBe(3); }); it('can create with only the payer', async () => { const createParams = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payer: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payerRaw.address, }, }; const actionCreation = await CreateAction.format( createParams, TestData.payerRaw.identity, TestData.fakeSignatureProvider, ); const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' expect(request.requestId).toBe( MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), ); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'state is wrong' expect(request.state).toBe(RequestLogicTypes.STATE.ACCEPTED); // 'expectedAmount is wrong' expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'extensions is wrong' expect(request.extensions).toEqual({}); // 'request should have property creator' expect(request).toHaveProperty('creator'); // 'request.creator.type is wrong' expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.creator.value is wrong' expect(request.creator.value).toBe(TestData.payerRaw.address); // 'request should have property payer' expect(request).toHaveProperty('payer'); if (request.payer) { // 'request.payer.type is wrong' expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payer.value is wrong' expect(request.payer.value).toBe(TestData.payerRaw.address); } // 'payee is wrong' expect(request.payee).toBeUndefined(); // 'request.events is wrong' expect(request.events[0]).toEqual({ actionSigner: TestData.payerRaw.identity, name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { expectedAmount: TestData.arbitraryExpectedAmount, extensionsDataLength: 0, isSignedRequest: false, }, timestamp: 2, }); }); it('can create with the payee and the payer', async () => { const createParams = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, payer: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payerRaw.address, }, timestamp: TestData.arbitraryTimestamp, }; const actionCreation = await CreateAction.format( createParams, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' expect(request.requestId).toBe( MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), ); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'state is wrong' expect(request.state).toBe(RequestLogicTypes.STATE.CREATED); // 'expectedAmount is wrong' expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'extensions is wrong' expect(request.extensions).toEqual({}); // 'request should have property creator' expect(request).toHaveProperty('creator'); // 'request.creator.type is wrong' expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.creator.value is wrong' expect(request.creator.value).toBe(TestData.payeeRaw.address); // 'request should have property payee' expect(request).toHaveProperty('payee'); if (request.payee) { // 'request.payee.type is wrong' expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payee.value is wrong' expect(request.payee.value).toBe(TestData.payeeRaw.address); } // 'request should have property payer' expect(request).toHaveProperty('payer'); if (request.payer) { // 'request.payer.type is wrong' expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payer.value is wrong' expect(request.payer.value).toBe(TestData.payerRaw.address); } // 'request.events is wrong' expect(request.events[0]).toEqual({ actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { expectedAmount: TestData.arbitraryExpectedAmount, extensionsDataLength: 0, isSignedRequest: false, }, timestamp: 2, }); }); it('cannot create without payee and payer', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: 'ETH', expectedAmount: TestData.arbitraryExpectedAmount, extensionsData: [{ id: 'extension1', value: 'whatever' }], }, version: CURRENT_VERSION, }, signature: TestData.fakeSignature, }; expect(() => CreateAction.createRequest(action, 2)).toThrowError( 'action.parameters.payee or action.parameters.payer must be given', ); }); it('cannot create with amount not a number', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: 'ETH', expectedAmount: 'Not a Number', extensionsData: [{ id: 'extension1', value: 'whatever' }], payee: { type: 'ethereumAddress', value: '0xAf083f77F1fFd54218d91491AFD06c9296EaC3ce', }, }, version: CURRENT_VERSION, }, signature: TestData.fakeSignature, }; expect(() => CreateAction.createRequest(action, 2)).toThrowError( 'action.parameters.expectedAmount must be a string representing a positive integer', ); }); it('cannot create with amount decimal', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: 'ETH', expectedAmount: '0.1234', extensionsData: [{ id: 'extension1', value: 'whatever' }], payee: { type: 'ethereumAddress', value: '0xAf083f77F1fFd54218d91491AFD06c9296EaC3ce', }, }, version: CURRENT_VERSION, }, signature: TestData.fakeSignature, }; expect(() => CreateAction.createRequest(action, 2)).toThrowError( 'action.parameters.expectedAmount must be a string representing a positive integer', ); }); it('cannot create with amount negative', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: 'ETH', expectedAmount: '-100000000000', extensionsData: [{ id: 'extension1', value: 'whatever' }], payee: { type: 'ethereumAddress', value: '0xAf083f77F1fFd54218d91491AFD06c9296EaC3ce', }, }, version: CURRENT_VERSION, }, signature: TestData.fakeSignature, }; expect(() => CreateAction.createRequest(action, 2)).toThrowError( 'action.parameters.expectedAmount must be a string representing a positive integer', ); }); it('can create with extensionsData', async () => { const extensionsData = [{ id: 'extension1', value: 'whatever' }]; const createParams = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, extensionsData, payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payeeRaw.address, }, payer: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: TestData.payerRaw.address, }, }; const actionCreation = await CreateAction.format( createParams, TestData.payeeRaw.identity, TestData.fakeSignatureProvider, ); const request = CreateAction.createRequest(actionCreation, 2); // 'requestId is wrong' expect(request.requestId).toBe( MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(actionCreation)), ); // 'currency is wrong' expect(request.currency).toEqual({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }); // 'state is wrong' expect(request.state).toBe(RequestLogicTypes.STATE.CREATED); // 'expectedAmount is wrong' expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount); // 'request.extensionsData is wrong' expect(request.extensionsData).toEqual(extensionsData); // 'request should have property creator' expect(request).toHaveProperty('creator'); // 'request.creator.type is wrong' expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.creator.value is wrong' expect(request.creator.value).toBe(TestData.payeeRaw.address); // 'request should have property payee' expect(request).toHaveProperty('payee'); if (request.payee) { // 'request.payee.type is wrong' expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payee.value is wrong' expect(request.payee.value).toBe(TestData.payeeRaw.address); } // 'request should have property payer' expect(request).toHaveProperty('payer'); if (request.payer) { // 'request.payer.type is wrong' expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS); // 'request.payer.value is wrong' expect(request.payer.value).toBe(TestData.payerRaw.address); } // 'request.events is wrong' expect(request.events[0]).toEqual({ actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { expectedAmount: TestData.arbitraryExpectedAmount, extensionsDataLength: 1, isSignedRequest: false, }, timestamp: 2, }); }); it('cannot create with signature by another', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: 'ETH', expectedAmount: TestData.arbitraryExpectedAmount, extensionsData: [{ id: 'extension1', value: 'whatever' }], payee: { type: 'ethereumAddress', value: '0xAf083f77F1fFd54218d91491AFD06c9296EaC3ce', }, }, version: CURRENT_VERSION, }, signature: TestData.fakeSignature, }; expect(() => CreateAction.createRequest(action, 2)).toThrowError( 'Signer must be the payee or the payer', ); }); it('does not support other identity type than "ethereumAddress" for Payee', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: 'ETH', expectedAmount: TestData.arbitraryExpectedAmount, extensionsData: [{ id: 'extension1', value: 'whatever' }], payee: { type: 'not_ethereumAddress', value: '0xAf083f77F1fFd54218d91491AFD06c9296EaC3ce', }, }, version: CURRENT_VERSION, }, signature: TestData.fakeSignature, }; expect(() => CreateAction.createRequest(action, 2)).toThrowError( 'payee: identity type not supported', ); }); it('does not support other identity type than "ethereumAddress" for Payer', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: 'ETH', expectedAmount: TestData.arbitraryExpectedAmount, extensionsData: [{ id: 'extension1', value: 'whatever' }], payer: { type: 'not_ethereumAddress', value: '0xAf083f77F1fFd54218d91491AFD06c9296EaC3ce', }, }, version: CURRENT_VERSION, }, signature: TestData.fakeSignature, }; expect(() => CreateAction.createRequest(action, 2)).toThrowError( 'payer: identity type not supported', ); }); it('does not support identity value not being an "ethereumAddress" for Payee', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: 'ETH', expectedAmount: TestData.arbitraryExpectedAmount, extensionsData: [{ id: 'extension1', value: 'whatever' }], payee: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: 'not an address', }, }, version: CURRENT_VERSION, }, signature: TestData.fakeSignature, }; expect(() => CreateAction.createRequest(action, 2)).toThrowError( 'payee: identity value must be an ethereum address', ); }); it('does not support identity value not being an "ethereumAddress" for Payer', () => { const action = { data: { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: 'ETH', expectedAmount: TestData.arbitraryExpectedAmount, extensionsData: [{ id: 'extension1', value: 'whatever' }], payer: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: 'not an address', }, }, version: CURRENT_VERSION, }, signature: TestData.fakeSignature, }; expect(() => CreateAction.createRequest(action, 2)).toThrowError( 'payer: identity value must be an ethereum address', ); }); }); });
the_stack
import crypto from '@trust/webcrypto'; import { EventEmitter } from 'events'; import * as util from 'util'; import { Role } from './Role'; import { SignalingClient, SignalingClientConfig } from './SignalingClient'; import { mockDateClass, restoreDateClass } from './internal/testUtils'; const RealWebSocket = window.WebSocket; const ENDPOINT = 'wss://endpoint.kinesisvideo.amazonaws.com'; const CHANNEL_ARN = 'arn:aws:kinesisvideo:us-west-2:123456789012:channel/testChannel/1234567890'; const CLIENT_ID = 'TestClientId'; const SDP_OFFER_OBJECT = { sdp: 'offer= true\nvideo= true', type: 'offer', }; const SDP_OFFER: RTCSessionDescription = { ...SDP_OFFER_OBJECT, toJSON: () => SDP_OFFER_OBJECT, } as any; const SDP_OFFER_VIEWER_STRING = '{"action":"SDP_OFFER","messagePayload":"eyJzZHAiOiJvZmZlcj0gdHJ1ZVxudmlkZW89IHRydWUiLCJ0eXBlIjoib2ZmZXIifQ=="}'; const SDP_OFFER_MASTER_STRING = '{"action":"SDP_OFFER","messagePayload":"eyJzZHAiOiJvZmZlcj0gdHJ1ZVxudmlkZW89IHRydWUiLCJ0eXBlIjoib2ZmZXIifQ==","recipientClientId":"TestClientId"}'; const SDP_OFFER_VIEWER_MESSAGE = '{"messageType":"SDP_OFFER","messagePayload":"eyJzZHAiOiJvZmZlcj0gdHJ1ZVxudmlkZW89IHRydWUiLCJ0eXBlIjoib2ZmZXIifQ==","senderClientId":"TestClientId"}'; const SDP_OFFER_MASTER_MESSAGE = '{"messageType":"SDP_OFFER","messagePayload":"eyJzZHAiOiJvZmZlcj0gdHJ1ZVxudmlkZW89IHRydWUiLCJ0eXBlIjoib2ZmZXIifQ=="}'; const SDP_ANSWER_OBJECT = { sdp: 'offer= true\nvideo= true', type: 'answer', }; const SDP_ANSWER: RTCSessionDescription = { ...SDP_ANSWER_OBJECT, toJSON: () => SDP_ANSWER_OBJECT, } as any; const SDP_ANSWER_VIEWER_STRING = '{"action":"SDP_ANSWER","messagePayload":"eyJzZHAiOiJvZmZlcj0gdHJ1ZVxudmlkZW89IHRydWUiLCJ0eXBlIjoiYW5zd2VyIn0="}'; const SDP_ANSWER_MASTER_STRING = '{"action":"SDP_ANSWER","messagePayload":"eyJzZHAiOiJvZmZlcj0gdHJ1ZVxudmlkZW89IHRydWUiLCJ0eXBlIjoiYW5zd2VyIn0=","recipientClientId":"TestClientId"}'; const SDP_ANSWER_VIEWER_MESSAGE = '{"messageType":"SDP_ANSWER","messagePayload":"eyJzZHAiOiJvZmZlcj0gdHJ1ZVxudmlkZW89IHRydWUiLCJ0eXBlIjoiYW5zd2VyIn0=","senderClientId":"TestClientId"}'; const SDP_ANSWER_MASTER_MESSAGE = '{"messageType":"SDP_ANSWER","messagePayload":"eyJzZHAiOiJvZmZlcj0gdHJ1ZVxudmlkZW89IHRydWUiLCJ0eXBlIjoiYW5zd2VyIn0="}'; const ICE_CANDIDATE_OBJECT = { candidate: 'upd 10.111.34.88', sdpMid: '1', sdpMLineIndex: 1, }; const ICE_CANDIDATE: RTCIceCandidate = { ...ICE_CANDIDATE_OBJECT, toJSON: () => ICE_CANDIDATE_OBJECT, } as any; const ICE_CANDIDATE_VIEWER_STRING = '{"action":"ICE_CANDIDATE","messagePayload":"eyJjYW5kaWRhdGUiOiJ1cGQgMTAuMTExLjM0Ljg4Iiwic2RwTWlkIjoiMSIsInNkcE1MaW5lSW5kZXgiOjF9"}'; const ICE_CANDIDATE_MASTER_STRING = '{"action":"ICE_CANDIDATE","messagePayload":"eyJjYW5kaWRhdGUiOiJ1cGQgMTAuMTExLjM0Ljg4Iiwic2RwTWlkIjoiMSIsInNkcE1MaW5lSW5kZXgiOjF9","recipientClientId":"TestClientId"}'; const ICE_CANDIDATE_VIEWER_MESSAGE = '{"messageType":"ICE_CANDIDATE","messagePayload":"eyJjYW5kaWRhdGUiOiJ1cGQgMTAuMTExLjM0Ljg4Iiwic2RwTWlkIjoiMSIsInNkcE1MaW5lSW5kZXgiOjF9","senderClientId":"TestClientId"}'; const ICE_CANDIDATE_MASTER_MESSAGE = '{"messageType":"ICE_CANDIDATE","messagePayload":"eyJjYW5kaWRhdGUiOiJ1cGQgMTAuMTExLjM0Ljg4Iiwic2RwTWlkIjoiMSIsInNkcE1MaW5lSW5kZXgiOjF9"}'; class MockWebSocket extends EventEmitter { static instance: MockWebSocket; public readyState: number; public send = jest.fn(); public close = jest.fn().mockImplementation(() => { if (this.readyState === RealWebSocket.CONNECTING || this.readyState === RealWebSocket.OPEN) { this.readyState = RealWebSocket.CLOSING; setTimeout(() => { if (this.readyState === RealWebSocket.CLOSING) { this.readyState = RealWebSocket.CLOSED; this.emit('close'); } }, 5); } }); public constructor() { super(); this.readyState = RealWebSocket.CONNECTING; setTimeout(() => { if (this.readyState === RealWebSocket.CONNECTING) { this.readyState = RealWebSocket.OPEN; this.emit('open'); } }, 10); MockWebSocket.instance = this; } public addEventListener(...args: any[]): void { super.addListener.apply(this, args); } public removeEventListener(...args: any[]): void { super.removeListener.apply(this, args); } } window.WebSocket = MockWebSocket as any; describe('SignalingClient', () => { let config: Partial<SignalingClientConfig>; let signer: jest.Mock; const mockDate = new Date('2020-05-01T00:00:00.000Z'); const mockClockSkewedDate = new Date('2020-05-01T00:16:40.000Z'); // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore global.crypto = crypto; // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore global.TextEncoder = util.TextEncoder; beforeEach(() => { mockDateClass(mockDate); signer = jest.fn().mockImplementation(endpoint => new Promise(resolve => resolve(endpoint))); config = { role: Role.VIEWER, clientId: CLIENT_ID, channelARN: CHANNEL_ARN, region: 'us-west-2', channelEndpoint: ENDPOINT, requestSigner: { getSignedURL: signer, }, }; }); afterEach(() => { restoreDateClass(); }); describe('constructor', () => { beforeEach(() => { delete config.requestSigner; config.credentials = { accessKeyId: 'ACCESS_KEY_ID', secretAccessKey: 'SECRET_ACCESS_KEY', sessionToken: 'SESSION_TOKEN', }; }); it('should not throw if valid viewer config provided', () => { new SignalingClient(config as SignalingClientConfig); }); it('should not throw if valid master config provided', () => { config.role = Role.MASTER; delete config.clientId; new SignalingClient(config as SignalingClientConfig); }); it('should throw if no config provided', () => { expect(() => new SignalingClient(null)).toThrow('SignalingClientConfig cannot be null'); }); it('should throw if viewer and no client id is provided', () => { config.clientId = null; expect(() => new SignalingClient(config as SignalingClientConfig)).toThrow('clientId cannot be null'); }); it('should throw if master and a client id is provided', () => { config.role = Role.MASTER; expect(() => new SignalingClient(config as SignalingClientConfig)).toThrow('clientId should be null'); }); it('should throw if ARN is not provided', () => { config.channelARN = null; expect(() => new SignalingClient(config as SignalingClientConfig)).toThrow('channelARN cannot be null'); }); it('should throw if region is not provided', () => { config.region = null; expect(() => new SignalingClient(config as SignalingClientConfig)).toThrow('region cannot be null'); }); it('should throw if channelEndpoint is not provided', () => { config.channelEndpoint = null; expect(() => new SignalingClient(config as SignalingClientConfig)).toThrow('channelEndpoint cannot be null'); }); }); describe('open', () => { it('should open a connection to the signaling server as the viewer', done => { const client = new SignalingClient(config as SignalingClientConfig); client.on('open', () => { expect(signer).toBeCalledWith( ENDPOINT, { 'X-Amz-ChannelARN': CHANNEL_ARN, 'X-Amz-ClientId': CLIENT_ID, }, mockDate, ); done(); }); client.open(); }); it('should open a connection to the signaling server as the master', done => { config.role = Role.MASTER; delete config.clientId; const client = new SignalingClient(config as SignalingClientConfig); client.on('open', () => { expect(signer).toBeCalledWith( ENDPOINT, { 'X-Amz-ChannelARN': CHANNEL_ARN, }, mockDate, ); done(); }); client.open(); }); it('should open a connection to the signaling server with clock skew adjusted date', done => { config.systemClockOffset = 1000000; const client = new SignalingClient(config as SignalingClientConfig); client.on('open', () => { expect(signer).toBeCalledWith( ENDPOINT, { 'X-Amz-ChannelARN': CHANNEL_ARN, 'X-Amz-ClientId': CLIENT_ID, }, mockClockSkewedDate, ); done(); }); client.open(); }); it('should not open a connection to the signaling server if it is closed while opening', async () => { config.requestSigner.getSignedURL = jest.fn().mockImplementation(endpoint => new Promise(resolve => setTimeout(() => resolve(endpoint), 5))); const client = new SignalingClient(config as SignalingClientConfig); client.on('open', () => { expect('Should not have fired an event').toBeFalsy(); }); client.open(); client.close(); return new Promise(resolve => setTimeout(resolve, 100)); }); it('should throw an error when making multiple open requests', () => { const client = new SignalingClient(config as SignalingClientConfig); expect(() => { client.open(); client.open(); }).toThrow('Client is already open, opening, or closing'); }); it('should emit an error event if the connection cannot be started', done => { signer.mockImplementation(endpoint => new Promise((_, reject) => reject(new Error(endpoint)))); const client = new SignalingClient(config as SignalingClientConfig); client.on('error', () => { done(); }); client.open(); }); }); describe('close', () => { it('should close an open connection', done => { const client = new SignalingClient(config as SignalingClientConfig); // Open a channel, close it, then wait for the close event. client.on('open', () => { client.close(); }); client.on('close', () => { expect(MockWebSocket.instance.close).toHaveBeenCalled(); done(); }); client.open(); }); it('should do nothing if the connection is closing', done => { const client = new SignalingClient(config as SignalingClientConfig); // Open a channel, close it, try to close it again, then wait for the close event. client.on('open', () => { client.close(); expect(() => client.close()).not.toThrow(); }); client.on('close', () => { done(); }); client.open(); }); it('should do nothing if the connection is not open', async () => { const client = new SignalingClient(config as SignalingClientConfig); // Close the client and then wait 100ms. If the close event fires, fail. client.on('close', () => { expect('Should not have fired an event').toBeFalsy(); }); client.close(); return new Promise(resolve => setTimeout(resolve, 100)); }); }); describe('sendSdpOffer', () => { it('should send the message as the viewer', done => { const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { client.sendSdpOffer(SDP_OFFER); expect(MockWebSocket.instance.send).toHaveBeenCalledWith(SDP_OFFER_VIEWER_STRING); done(); }); }); it('should send the message as the master', done => { config.role = Role.MASTER; delete config.clientId; const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { client.sendSdpOffer(SDP_OFFER, CLIENT_ID); expect(MockWebSocket.instance.send).toHaveBeenCalledWith(SDP_OFFER_MASTER_STRING); done(); }); }); it('should throw an error if the connection is not open', () => { const client = new SignalingClient(config as SignalingClientConfig); expect(() => client.sendSdpOffer(SDP_OFFER)).toThrow('Could not send message because the connection to the signaling service is not open.'); }); it('should throw an error if there is a recipient id as viewer', done => { const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { expect(() => client.sendSdpOffer(SDP_OFFER, CLIENT_ID)).toThrow( 'Unexpected recipient client id. As the VIEWER, messages must not be sent with a recipient client id.', ); done(); }); }); it('should throw an error if there is no recipient id as master', done => { config.role = Role.MASTER; delete config.clientId; const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { expect(() => client.sendSdpOffer(SDP_OFFER)).toThrow( 'Missing recipient client id. As the MASTER, all messages must be sent with a recipient client id.', ); done(); }); }); }); describe('sendSdpAnswer', () => { it('should send the message as the viewer', done => { const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { client.sendSdpAnswer(SDP_ANSWER); expect(MockWebSocket.instance.send).toHaveBeenCalledWith(SDP_ANSWER_VIEWER_STRING); done(); }); }); it('should send the message as the master', done => { config.role = Role.MASTER; delete config.clientId; const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { client.sendSdpAnswer(SDP_ANSWER, CLIENT_ID); expect(MockWebSocket.instance.send).toHaveBeenCalledWith(SDP_ANSWER_MASTER_STRING); done(); }); }); it('should throw an error if the connection is not open', () => { const client = new SignalingClient(config as SignalingClientConfig); expect(() => client.sendSdpAnswer(SDP_ANSWER)).toThrow('Could not send message because the connection to the signaling service is not open.'); }); it('should throw an error if there is a recipient id as viewer', done => { const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { expect(() => client.sendSdpAnswer(SDP_ANSWER, CLIENT_ID)).toThrow( 'Unexpected recipient client id. As the VIEWER, messages must not be sent with a recipient client id.', ); done(); }); }); it('should throw an error if there is no recipient id as master', done => { config.role = Role.MASTER; delete config.clientId; const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { expect(() => client.sendSdpAnswer(SDP_ANSWER)).toThrow( 'Missing recipient client id. As the MASTER, all messages must be sent with a recipient client id.', ); done(); }); }); }); describe('sendIceCandidate', () => { it('should send the message as the viewer', done => { const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { client.sendIceCandidate(ICE_CANDIDATE); expect(MockWebSocket.instance.send).toHaveBeenCalledWith(ICE_CANDIDATE_VIEWER_STRING); done(); }); }); it('should send the message as the master', done => { config.role = Role.MASTER; delete config.clientId; const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { client.sendIceCandidate(ICE_CANDIDATE, CLIENT_ID); expect(MockWebSocket.instance.send).toHaveBeenCalledWith(ICE_CANDIDATE_MASTER_STRING); done(); }); }); it('should throw an error if the connection is not open', () => { const client = new SignalingClient(config as SignalingClientConfig); expect(() => client.sendIceCandidate(ICE_CANDIDATE)).toThrow('Could not send message because the connection to the signaling service is not open.'); }); it('should throw an error if there is a recipient id as viewer', done => { const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { expect(() => client.sendIceCandidate(ICE_CANDIDATE, CLIENT_ID)).toThrow( 'Unexpected recipient client id. As the VIEWER, messages must not be sent with a recipient client id.', ); done(); }); }); it('should throw an error if there is no recipient id as master', done => { config.role = Role.MASTER; delete config.clientId; const client = new SignalingClient(config as SignalingClientConfig); client.open(); client.on('open', () => { expect(() => client.sendIceCandidate(ICE_CANDIDATE)).toThrow( 'Missing recipient client id. As the MASTER, all messages must be sent with a recipient client id.', ); done(); }); }); }); describe('events', () => { it('should ignore non-parsable messages from the signaling service', done => { const client = new SignalingClient(config as SignalingClientConfig); // Open a connection, receive a faulty message, and then continue to receive and process a non-faulty message. client.on('sdpOffer', () => { done(); }); client.on('open', () => { MockWebSocket.instance.emit('message', { data: 'not valid JSON' }); MockWebSocket.instance.emit('message', { data: SDP_OFFER_MASTER_MESSAGE }); }); client.open(); }); describe('sdpOffer', () => { it('should parse sdpOffer messages from the master', done => { const client = new SignalingClient(config as SignalingClientConfig); client.on('sdpOffer', (sdpOffer, senderClientId) => { expect(sdpOffer).toEqual(SDP_OFFER_OBJECT); expect(senderClientId).toBeFalsy(); done(); }); client.on('open', () => { MockWebSocket.instance.emit('message', { data: SDP_OFFER_MASTER_MESSAGE }); }); client.open(); }); it('should parse sdpOffer messages from the viewer', done => { config.role = Role.MASTER; delete config.clientId; const client = new SignalingClient(config as SignalingClientConfig); client.on('sdpOffer', (sdpOffer, senderClientId) => { expect(sdpOffer).toEqual(SDP_OFFER_OBJECT); expect(senderClientId).toEqual(CLIENT_ID); done(); }); client.on('open', () => { MockWebSocket.instance.emit('message', { data: SDP_OFFER_VIEWER_MESSAGE }); }); client.open(); }); it('should parse sdpOffer messages from the master and release pending ICE candidates', done => { const client = new SignalingClient(config as SignalingClientConfig); client.on('sdpOffer', (sdpOffer, senderClientId) => { expect(sdpOffer).toEqual(SDP_OFFER_OBJECT); expect(senderClientId).toBeFalsy(); client.on('iceCandidate', (iceCandidate, senderClientId) => { expect(iceCandidate).toEqual(ICE_CANDIDATE_OBJECT); expect(senderClientId).toBeFalsy(); done(); }); }); client.on('open', () => { MockWebSocket.instance.emit('message', { data: ICE_CANDIDATE_MASTER_MESSAGE }); MockWebSocket.instance.emit('message', { data: ICE_CANDIDATE_MASTER_MESSAGE }); MockWebSocket.instance.emit('message', { data: SDP_OFFER_MASTER_MESSAGE }); }); client.open(); }); }); describe('sdpAnswer', () => { it('should parse sdpAnswer messages from the master', done => { const client = new SignalingClient(config as SignalingClientConfig); client.on('sdpAnswer', (sdpAnswer, senderClientId) => { expect(sdpAnswer).toEqual(SDP_ANSWER_OBJECT); expect(senderClientId).toBeFalsy(); done(); }); client.on('open', () => { MockWebSocket.instance.emit('message', { data: SDP_ANSWER_MASTER_MESSAGE }); }); client.open(); }); it('should parse sdpAnswer messages from the viewer', done => { config.role = Role.MASTER; delete config.clientId; const client = new SignalingClient(config as SignalingClientConfig); client.on('sdpAnswer', (sdpAnswer, senderClientId) => { expect(sdpAnswer).toEqual(SDP_ANSWER_OBJECT); expect(senderClientId).toEqual(CLIENT_ID); done(); }); client.on('open', () => { MockWebSocket.instance.emit('message', { data: SDP_ANSWER_VIEWER_MESSAGE }); }); client.open(); }); it('should parse sdpAnswer messages from the master and release pending ICE candidates', done => { const client = new SignalingClient(config as SignalingClientConfig); client.on('sdpAnswer', (sdpAnswer, senderClientId) => { expect(sdpAnswer).toEqual(SDP_ANSWER_OBJECT); expect(senderClientId).toBeFalsy(); client.on('iceCandidate', (iceCandidate, senderClientId) => { expect(iceCandidate).toEqual(ICE_CANDIDATE_OBJECT); expect(senderClientId).toBeFalsy(); done(); }); }); client.on('open', () => { MockWebSocket.instance.emit('message', { data: ICE_CANDIDATE_MASTER_MESSAGE }); MockWebSocket.instance.emit('message', { data: ICE_CANDIDATE_MASTER_MESSAGE }); MockWebSocket.instance.emit('message', { data: SDP_ANSWER_MASTER_MESSAGE }); }); client.open(); }); }); describe('iceCandidate', () => { it('should parse iceCandidate messages from the master', done => { const client = new SignalingClient(config as SignalingClientConfig); client.on('iceCandidate', (iceCandidate, senderClientId) => { expect(iceCandidate).toEqual(ICE_CANDIDATE_OBJECT); expect(senderClientId).toBeFalsy(); done(); }); client.on('open', () => { MockWebSocket.instance.emit('message', { data: SDP_ANSWER_MASTER_MESSAGE }); MockWebSocket.instance.emit('message', { data: ICE_CANDIDATE_MASTER_MESSAGE }); }); client.open(); }); it('should parse iceCandidate messages from the viewer', done => { config.role = Role.MASTER; delete config.clientId; const client = new SignalingClient(config as SignalingClientConfig); client.on('iceCandidate', (iceCandidate, senderClientId) => { expect(iceCandidate).toEqual(ICE_CANDIDATE_OBJECT); expect(senderClientId).toEqual(CLIENT_ID); done(); }); client.on('open', () => { MockWebSocket.instance.emit('message', { data: SDP_ANSWER_VIEWER_MESSAGE }); MockWebSocket.instance.emit('message', { data: ICE_CANDIDATE_VIEWER_MESSAGE }); }); client.open(); }); }); }); });
the_stack
module txt { export enum PathFit { Rainbow, Stairstep }; export interface PathPoint{ x:number; y:number; rotation?:number; offsetX?:number; } export enum PathAlign { Center, Right, Left }; export class Path { private pathElement:SVGPathElement = null; path:string=null; start:number = 0; center:number = null; end:number = null; angles:any[] = null; flipped:boolean = false; fit:PathFit = txt.PathFit.Rainbow; align:PathAlign = txt.PathAlign.Center; length:number = null; realLength:number = null; closed:boolean = false; clockwise:boolean = true; constructor( path:string , start:number=0 , end:number=null , flipped:boolean=false , fit:PathFit=txt.PathFit.Rainbow , align:PathAlign = txt.PathAlign.Center ){ this.path = path; this.start = start; this.align = align; this.end = end; this.flipped = flipped; this.fit = fit; this.update(); } update(){ this.pathElement = <SVGPathElement>document.createElementNS( "http://www.w3.org/2000/svg" , "path" ); this.pathElement.setAttributeNS( null , "d" , this.path ); this.length = this.pathElement.getTotalLength(); this.closed = ( this.path.toLowerCase().indexOf( 'z' ) != -1 ); var pointlength = this.length / 10; var points = []; //console.log( this.pathElement ); points.push( this.getRealPathPoint( 0 ) ); points.push( this.getRealPathPoint( pointlength ) ); points.push( this.getRealPathPoint( pointlength * 2 ) ); points.push( this.getRealPathPoint( pointlength * 3 ) ); points.push( this.getRealPathPoint( pointlength * 4 ) ); points.push( this.getRealPathPoint( pointlength * 5 ) ); points.push( this.getRealPathPoint( pointlength * 6 ) ); points.push( this.getRealPathPoint( pointlength * 7 ) ); points.push( this.getRealPathPoint( pointlength * 8 ) ); points.push( this.getRealPathPoint( pointlength * 9 ) ); points.push( this.getRealPathPoint( pointlength * 10 ) ); var clock = ( points[1].x - points[0].x ) * ( points[1].y + points[0].y ) + ( points[2].x - points[1].x ) * ( points[2].y + points[1].y ) + ( points[3].x - points[2].x ) * ( points[3].y + points[2].y ) + ( points[4].x - points[3].x ) * ( points[4].y + points[3].y ) + ( points[5].x - points[4].x ) * ( points[5].y + points[4].y ) + ( points[6].x - points[5].x ) * ( points[6].y + points[5].y ) + ( points[7].x - points[6].x ) * ( points[7].y + points[6].y ) + ( points[8].x - points[7].x ) * ( points[8].y + points[7].y ) + ( points[9].x - points[8].x ) * ( points[9].y + points[8].y ) + ( points[10].x - points[9].x ) * ( points[10].y + points[9].y ); //console.log( clock ); if( clock > 0 ){ this.clockwise = false; }else{ this.clockwise = true; } if( this.end == null ){ this.end = this.length; } if( this.closed == false ){ if( this.flipped == false ){ if( this.start > this.end ){ this.realLength = this.start - this.end; this.center = this.start - this.realLength / 2; }else{ this.realLength = this.end - this.start; this.center = this.start + this.realLength / 2; } }else{ if( this.start > this.end ){ this.realLength = this.start - this.end; this.center = this.start - this.realLength / 2; }else{ this.realLength = this.end - this.start; this.center = this.start + this.realLength / 2; } } }else if( this.clockwise == false ){ if( this.flipped == false ){ if( this.start > this.end ){ this.realLength = this.start - this.end; this.center = this.end + this.realLength / 2; }else{ this.realLength = ( this.start + this.length - this.end ); this.center = this.end + this.realLength / 2; if( this.center > this.length ){ this.center = this.center - this.length; } } }else{ if( this.start > this.end ){ this.realLength = ( this.end + this.length - this.start ); this.center = this.start + this.realLength / 2; if( this.center > this.length ){ this.center = this.center - this.length; } }else{ this.realLength = this.end - this.start; this.center = this.start + this.realLength / 2; } } }else{ if( this.flipped == false ){ if( this.start > this.end ){ this.realLength = this.end + this.length - this.start; this.center = this.start + this.realLength / 2; if( this.center > this.length ){ this.center = this.center - this.length; } }else{ this.realLength = this.end - this.start; this.center = this.start + this.realLength / 2; } }else{ if( this.start > this.end ){ this.realLength = this.start - this.end; this.center = this.end + this.realLength / 2; }else{ this.realLength = this.start + this.length - this.end; this.center = this.end + this.realLength / 2; if( this.center > this.length ){ this.center = this.center - this.length; } } } } } getRealPathPoint( distance:number ):txt.PathPoint { if( distance > this.length ){ return this.pathElement.getPointAtLength( distance - this.length ); }else if( distance < 0 ){ return this.pathElement.getPointAtLength( distance + this.length ); }else{ return this.pathElement.getPointAtLength( distance ); } } getPathPoint( distance:number , characterLength:number = 0 , charOffset:number = 0 ):txt.PathPoint { distance = distance * 0.99; characterLength = characterLength * 0.99; //console.log( characterLength ); var point0:PathPoint; var point1:PathPoint; var point2:PathPoint; var position:number; var direction:boolean = true; var realStart:number = 0; if( this.closed == false ){ if( this.flipped == false ){ if( this.start > this.end ){ if( this.align == PathAlign.Left ){ realStart = this.start; }else if( this.align == PathAlign.Center ){ realStart = this.start - ( this.realLength - characterLength ) / 2; }else if( this.align == PathAlign.Right ){ realStart = this.start - this.realLength - characterLength; } position = realStart - distance; direction = false; }else{ if( this.align == PathAlign.Left ){ realStart = this.start; }else if( this.align == PathAlign.Center ){ realStart = this.start + ( this.realLength - characterLength ) / 2; }else if( this.align == PathAlign.Right ){ realStart = this.start + this.realLength - characterLength; } position = realStart + distance; } }else{ if( this.start > this.end ){ if( this.align == PathAlign.Left ){ realStart = this.start; }else if( this.align == PathAlign.Center ){ realStart = this.start - ( this.realLength - characterLength ) / 2; }else if( this.align == PathAlign.Right ){ realStart = this.start - this.realLength - characterLength; } position = realStart - distance; direction = false; }else{ if( this.align == PathAlign.Left ){ realStart = this.start; }else if( this.align == PathAlign.Center ){ realStart = this.start + ( this.realLength - characterLength ) / 2; }else if( this.align == PathAlign.Right ){ realStart = this.start + this.realLength - characterLength; } position = realStart - distance; } } }else if( this.clockwise == false ){ if( this.flipped == false ){ if( this.start > this.end ){ if( this.align == PathAlign.Left ){ realStart = this.start; }else if( this.align == PathAlign.Center ){ realStart = this.start - ( this.realLength - characterLength ) / 2; }else if( this.align == PathAlign.Right ){ realStart = this.start - this.realLength - characterLength; } position = realStart - distance; direction = false; }else{ if( this.align == PathAlign.Left ){ realStart = this.start; position = realStart - distance; }else if( this.align == PathAlign.Center ){ realStart = this.start - ( this.realLength - characterLength ) / 2; position = realStart - distance; }else if( this.align == PathAlign.Right ){ realStart = this.start - this.realLength - characterLength; position = realStart - distance; } if( position < 0 ){ position = position + this.length; } direction = false; } }else{ if( this.start > this.end ){ if( this.align == PathAlign.Left ){ realStart = this.start; position = realStart + distance; }else if( this.align == PathAlign.Center ){ realStart = this.start + ( this.realLength - characterLength ) / 2; position = realStart + distance; }else if( this.align == PathAlign.Right ){ realStart = this.start + this.realLength - characterLength; position = realStart + distance; } if( position > this.length ){ position = position - this.length; } }else{ if( this.align == PathAlign.Left ){ realStart = this.start; }else if( this.align == PathAlign.Center ){ realStart = this.start + ( this.realLength - characterLength ) / 2; }else if( this.align == PathAlign.Right ){ realStart = this.start + this.realLength - characterLength; } position = realStart + distance; } } }else{ if( this.flipped == false ){ if( this.start > this.end ){ if( this.align == PathAlign.Left ){ realStart = this.start; position = realStart - distance; }else if( this.align == PathAlign.Center ){ realStart = this.start - ( this.realLength - characterLength ) / 2; position = realStart - distance; }else if( this.align == PathAlign.Right ){ realStart = this.start - this.realLength - characterLength; position = realStart - distance; } if( position < 0 ){ position = position + this.length; } direction = false; }else{ if( this.align == PathAlign.Left ){ realStart = this.start; }else if( this.align == PathAlign.Center ){ realStart = this.start - ( this.realLength - characterLength ) / 2; }else if( this.align == PathAlign.Right ){ realStart = this.start - this.realLength - characterLength; } position = realStart - distance; direction = false; } }else{ if( this.start > this.end ){ if( this.align == PathAlign.Left ){ realStart = this.start; }else if( this.align == PathAlign.Center ){ realStart = this.start + ( this.realLength - characterLength ) / 2; }else if( this.align == PathAlign.Right ){ realStart = this.start + this.realLength - characterLength; } position = realStart + distance; }else{ if( this.align == PathAlign.Left ){ realStart = this.start; position = realStart + distance; }else if( this.align == PathAlign.Center ){ realStart = this.start + ( this.realLength - characterLength ) / 2; position = realStart + distance; }else if( this.align == PathAlign.Right ){ realStart = this.start + this.realLength - characterLength; position = realStart + distance; } if( position > this.length ){ position = position - this.length; } } } } point1 = this.getRealPathPoint( position ); var segment = this.pathElement.pathSegList.getItem( this.pathElement.getPathSegAtLength( position ) ).pathSegType; if( segment == 4 ){ if( direction ){ }else{ if( this.pathElement.getPathSegAtLength( position ) != this.pathElement.getPathSegAtLength( position - charOffset ) ){ var pp0 = this.getRealPathPoint( position ); var pp1 = this.getRealPathPoint( position - charOffset ); var ppc = this.pathElement.pathSegList.getItem( this.pathElement.getPathSegAtLength( position ) - 1 ); var d0 = Math.sqrt( Math.pow( ( pp0.x - ppc['x'] ) , 2 ) + Math.pow( ( pp0.y - ppc['y'] ) , 2 ) ); var d1 = Math.sqrt( Math.pow( ( pp1.x - ppc['x'] ) , 2 ) + Math.pow( ( pp1.y - ppc['y'] ) , 2 ) ); if( d0 > d1 ){ point1 = pp0; point2 = { x:ppc['x'], y:ppc['y'] }; var rot12 = Math.atan( ( point2.y - point1.y ) / ( point2.x - point1.x ) ) * 180 / Math.PI; if( point1.x > point2.x ){ rot12 = rot12 + 180; } if( rot12 < 0 ){ rot12 = rot12 + 360; } if( rot12 > 360 ){ rot12 = rot12 - 360; } point1.rotation = rot12; return point1; }else{ point1 = { x:ppc['x'], y:ppc['y'] }; point1.offsetX = -d0; point1['next'] = true; return point1; } } } } if( direction ){ point2 = this.getRealPathPoint( position + charOffset ); //console.log( direction , position + charOffset , this.realLength ); }else{ point2 = this.getRealPathPoint( position - charOffset ); //console.log( direction , position - charOffset , this.realLength ); } var rot12 = Math.atan( ( point2.y - point1.y ) / ( point2.x - point1.x ) ) * 180 / Math.PI; if( point1.x > point2.x ){ rot12 = rot12 + 180; } if( rot12 < 0 ){ rot12 = rot12 + 360; } if( rot12 > 360 ){ rot12 = rot12 - 360; } point1.rotation = rot12; return point1; } } }
the_stack
import { assertEq, assertDeepEq, assertOk } from '../test-helpers'; import { moment } from '../chain'; xdescribe('is valid', () => { it('array bad month', function () { assertEq(moment([2010, -1]).isValid(), false, 'month -1 invalid'); assertEq(moment([2100, 12]).isValid(), false, 'month 12 invalid'); }); it('array good month', function () { for (var i = 0; i < 12; i++) { assertEq(moment([2010, i]).isValid(), true, 'month ' + i); assertEq(moment.utc([2010, i]).isValid(), true, 'month ' + i); } }); it('Feb 29 0000 is valid', function () { // https://github.com/moment/moment/issues/3358 assertOk(moment({ year: 0, month: 1, date: 29 }).isValid(), 'Feb 29 0000 must be valid'); assertOk(moment({ year: 0, month: 1, date: 28 }).add(1, 'd').isValid(), 'Feb 28 0000 + 1 day must be valid'); }); it('array bad date', function () { var tests = [ moment([2010, 0, 0]), moment([2100, 0, 32]), moment.utc([2010, 0, 0]), moment.utc([2100, 0, 32]) ], i, m; for (i in tests) { m = tests[i]; assertEq(m.isValid(), false); } }); it('h/hh with hour > 12', function () { assertOk(moment('06/20/2014 11:51 PM', 'MM/DD/YYYY hh:mm A', true).isValid(), '11 for hh'); assertOk(moment('06/20/2014 11:51 AM', 'MM/DD/YYYY hh:mm A', true).isValid(), '11 for hh'); assertOk(moment('06/20/2014 23:51 PM', 'MM/DD/YYYY hh:mm A').isValid(), 'non-strict validity 23 for hh'); // assertOk(moment('06/20/2014 23:51 PM', 'MM/DD/YYYY hh:mm A').parsingFlags().bigHour, 'non-strict bigHour 23 for hh'); assertOk(!moment('06/20/2014 23:51 PM', 'MM/DD/YYYY hh:mm A', true).isValid(), 'validity 23 for hh'); // assertOk(moment('06/20/2014 23:51 PM', 'MM/DD/YYYY hh:mm A', true).parsingFlags().bigHour, 'bigHour 23 for hh'); }); it('array bad date leap year', function () { assertEq(moment([2010, 1, 29]).isValid(), false, '2010 feb 29'); assertEq(moment([2100, 1, 29]).isValid(), false, '2100 feb 29'); assertEq(moment([2008, 1, 30]).isValid(), false, '2008 feb 30'); assertEq(moment([2000, 1, 30]).isValid(), false, '2000 feb 30'); assertEq(moment.utc([2010, 1, 29]).isValid(), false, 'utc 2010 feb 29'); assertEq(moment.utc([2100, 1, 29]).isValid(), false, 'utc 2100 feb 29'); assertEq(moment.utc([2008, 1, 30]).isValid(), false, 'utc 2008 feb 30'); assertEq(moment.utc([2000, 1, 30]).isValid(), false, 'utc 2000 feb 30'); }); it('string + formats bad date', function () { assertEq(moment('2020-00-00', []).isValid(), false, 'invalid on empty array'); assertEq(moment('2020-00-00', ['YYYY-MM-DD', 'DD-MM-YYYY']).isValid(), false, 'invalid on all in array'); assertEq(moment('2020-00-00', ['DD-MM-YYYY', 'YYYY-MM-DD']).isValid(), false, 'invalid on all in array'); assertEq(moment('2020-01-01', ['YYYY-MM-DD', 'DD-MM-YYYY']).isValid(), true, 'valid on first'); assertEq(moment('2020-01-01', ['DD-MM-YYYY', 'YYYY-MM-DD']).isValid(), true, 'valid on last'); assertEq(moment('2020-01-01', ['YYYY-MM-DD', 'YYYY-DD-MM']).isValid(), true, 'valid on both'); assertEq(moment('2020-13-01', ['YYYY-MM-DD', 'YYYY-DD-MM']).isValid(), true, 'valid on last'); assertEq(moment('12-13-2012', ['DD-MM-YYYY', 'YYYY-MM-DD']).isValid(), false, 'month rollover'); assertEq(moment('12-13-2012', ['DD-MM-YYYY', 'DD-MM-YYYY']).isValid(), false, 'month rollover'); assertEq(moment('38-12-2012', ['DD-MM-YYYY']).isValid(), false, 'day rollover'); }); it('string nonsensical with format', function () { assertEq(moment('fail', 'MM-DD-YYYY').isValid(), false, 'string \'fail\' with format \'MM-DD-YYYY\''); assertEq(moment('xx-xx-2001', 'DD-MM-YYY').isValid(), true, 'string \'xx-xx-2001\' with format \'MM-DD-YYYY\''); }); it('string with bad month name', function () { assertEq(moment('01-Nam-2012', 'DD-MMM-YYYY').isValid(), false, '\'Nam\' is an invalid month'); assertEq(moment('01-Aug-2012', 'DD-MMM-YYYY').isValid(), true, '\'Aug\' is a valid month'); }); it('string with spaceless format', function () { assertEq(moment('10Sep2001', 'DDMMMYYYY').isValid(), true, 'Parsing 10Sep2001 should result in a valid date'); }); it('invalid string iso 8601', function () { var tests = [ '2010-00-00', '2010-01-00', '2010-01-40', '2010-01-01T24:01', // 24:00:00 is actually valid '2010-01-01T23:60', '2010-01-01T23:59:60' ], i; for (i = 0; i < tests.length; i++) { assertEq(moment(tests[i], moment.ISO_8601).isValid(), false, tests[i] + ' should be invalid'); assertEq(moment.utc(tests[i], moment.ISO_8601).isValid(), false, tests[i] + ' should be invalid'); } }); it('invalid string iso 8601 + timezone', function () { var tests = [ '2010-00-00T+00:00', '2010-01-00T+00:00', '2010-01-40T+00:00', '2010-01-40T24:01+00:00', '2010-01-40T23:60+00:00', '2010-01-40T23:59:60+00:00', '2010-01-40T23:59:59.9999+00:00', '2010-01-40T23:59:59,9999+00:00' ], i; for (i = 0; i < tests.length; i++) { assertEq(moment(tests[i], moment.ISO_8601).isValid(), false, tests[i] + ' should be invalid'); assertEq(moment.utc(tests[i], moment.ISO_8601).isValid(), false, tests[i] + ' should be invalid'); } }); it('valid string iso 8601 - not strict', function () { var tests = [ '2010-01-30 00:00:00,000Z', '20100101', '20100130', '20100130T23+00:00', '20100130T2359+0000', '20100130T235959+0000', '20100130T235959,999+0000', '20100130T235959,999-0700', '20100130T000000,000+0700', '20100130 000000,000Z' ]; for (var i = 0; i < tests.length; i++) { assertEq(moment(tests[i]).isValid(), true, tests[i] + ' should be valid in normal'); assertEq(moment.utc(tests[i]).isValid(), true, tests[i] + ' should be valid in normal'); } }); it('valid string iso 8601 + timezone', function () { var tests = [ '2010-01-01', '2010-01-30', '2010-01-30T23+00:00', '2010-01-30T23:59+00:00', '2010-01-30T23:59:59+00:00', '2010-01-30T23:59:59.999+00:00', '2010-01-30T23:59:59.999-07:00', '2010-01-30T00:00:00.000+07:00', '2010-01-30T23:59:59.999-07', '2010-01-30T00:00:00.000+07', '2010-01-30 00:00:00.000Z' ], i; for (i = 0; i < tests.length; i++) { assertEq(moment(tests[i]).isValid(), true, tests[i] + ' should be valid in normal'); assertEq(moment.utc(tests[i]).isValid(), true, tests[i] + ' should be valid in normal'); assertEq(moment(tests[i], moment.ISO_8601, true).isValid(), true, tests[i] + ' should be valid in strict'); assertEq(moment.utc(tests[i], moment.ISO_8601, true).isValid(), true, tests[i] + ' should be valid in strict'); } }); /* it('invalidAt', function () { assertEq(moment([2000, 12]).invalidAt(), 1, 'month 12 is invalid: 0-11'); assertEq(moment([2000, 1, 30]).invalidAt(), 2, '30 is not a valid february day'); assertEq(moment([2000, 1, 29, 25]).invalidAt(), 3, '25 is invalid hour'); assertEq(moment([2000, 1, 29, 24, 1]).invalidAt(), 3, '24:01 is invalid hour'); assertEq(moment([2000, 1, 29, 23, 60]).invalidAt(), 4, '60 is invalid minute'); assertEq(moment([2000, 1, 29, 23, 59, 60]).invalidAt(), 5, '60 is invalid second'); assertEq(moment([2000, 1, 29, 23, 59, 59, 1000]).invalidAt(), 6, '1000 is invalid millisecond'); assertEq(moment([2000, 1, 29, 23, 59, 59, 999]).invalidAt(), -1, '-1 if everything is fine'); }); */ it('valid Unix timestamp', function () { assertEq(moment(1371065286, 'X').isValid(), true, 'number integer'); assertEq(moment(1379066897.0, 'X').isValid(), true, 'number whole 1dp'); assertEq(moment(1379066897.7, 'X').isValid(), true, 'number 1dp'); assertEq(moment(1379066897.00, 'X').isValid(), true, 'number whole 2dp'); assertEq(moment(1379066897.07, 'X').isValid(), true, 'number 2dp'); assertEq(moment(1379066897.17, 'X').isValid(), true, 'number 2dp'); assertEq(moment(1379066897.000, 'X').isValid(), true, 'number whole 3dp'); assertEq(moment(1379066897.007, 'X').isValid(), true, 'number 3dp'); assertEq(moment(1379066897.017, 'X').isValid(), true, 'number 3dp'); assertEq(moment(1379066897.157, 'X').isValid(), true, 'number 3dp'); assertEq(moment('1371065286', 'X').isValid(), true, 'string integer'); assertEq(moment('1379066897.', 'X').isValid(), true, 'string trailing .'); assertEq(moment('1379066897.0', 'X').isValid(), true, 'string whole 1dp'); assertEq(moment('1379066897.7', 'X').isValid(), true, 'string 1dp'); assertEq(moment('1379066897.00', 'X').isValid(), true, 'string whole 2dp'); assertEq(moment('1379066897.07', 'X').isValid(), true, 'string 2dp'); assertEq(moment('1379066897.17', 'X').isValid(), true, 'string 2dp'); assertEq(moment('1379066897.000', 'X').isValid(), true, 'string whole 3dp'); assertEq(moment('1379066897.007', 'X').isValid(), true, 'string 3dp'); assertEq(moment('1379066897.017', 'X').isValid(), true, 'string 3dp'); assertEq(moment('1379066897.157', 'X').isValid(), true, 'string 3dp'); }); it('invalid Unix timestamp', function () { assertEq(moment(undefined, 'X').isValid(), false, 'undefined'); assertEq(moment('undefined', 'X').isValid(), false, 'string undefined'); try { assertEq(moment(null, 'X').isValid(), false, 'null'); } catch (e) { assertOk(true, 'null'); } assertEq(moment('null', 'X').isValid(), false, 'string null'); assertEq(moment([], 'X').isValid(), false, 'array'); assertEq(moment('{}', 'X').isValid(), false, 'object'); try { assertEq(moment('', 'X').isValid(), false, 'string empty'); } catch (e) { assertOk(true, 'string empty'); } assertEq(moment(' ', 'X').isValid(), false, 'string space'); }); it('valid Unix offset milliseconds', function () { assertEq(moment(1234567890123, 'x').isValid(), true, 'number integer'); assertEq(moment('1234567890123', 'x').isValid(), true, 'string integer'); }); it('invalid Unix offset milliseconds', function () { assertEq(moment(undefined, 'x').isValid(), false, 'undefined'); assertEq(moment('undefined', 'x').isValid(), false, 'string undefined'); try { assertEq(moment(null, 'x').isValid(), false, 'null'); } catch (e) { assertOk(true, 'null'); } assertEq(moment('null', 'x').isValid(), false, 'string null'); assertEq(moment([], 'x').isValid(), false, 'array'); assertEq(moment('{}', 'x').isValid(), false, 'object'); try { assertEq(moment('', 'x').isValid(), false, 'string empty'); } catch (e) { assertOk(true, 'string empty'); } assertEq(moment(' ', 'x').isValid(), false, 'string space'); }); it('empty', function () { assertEq(moment(null).isValid(), false, 'null'); assertEq(moment('').isValid(), false, 'empty string'); assertEq(moment(null, 'YYYY').isValid(), false, 'format + null'); assertEq(moment('', 'YYYY').isValid(), false, 'format + empty string'); assertEq(moment(' ', 'YYYY').isValid(), false, 'format + empty when trimmed'); }); it('days of the year', function () { assertEq(moment('2010 300', 'YYYY DDDD').isValid(), true, 'day 300 of year valid'); assertEq(moment('2010 365', 'YYYY DDDD').isValid(), true, 'day 365 of year valid'); assertEq(moment('2010 366', 'YYYY DDDD').isValid(), false, 'day 366 of year invalid'); assertEq(moment('2012 365', 'YYYY DDDD').isValid(), true, 'day 365 of leap year valid'); assertEq(moment('2012 366', 'YYYY DDDD').isValid(), true, 'day 366 of leap year valid'); assertEq(moment('2012 367', 'YYYY DDDD').isValid(), false, 'day 367 of leap year invalid'); }); it('24:00:00.000 is valid', function () { assertEq(moment('2014-01-01 24', 'YYYY-MM-DD HH').isValid(), true, '24 is valid'); assertEq(moment('2014-01-01 24:00', 'YYYY-MM-DD HH:mm').isValid(), true, '24:00 is valid'); assertEq(moment('2014-01-01 24:01', 'YYYY-MM-DD HH:mm').isValid(), false, '24:01 is not valid'); }); it('oddball permissiveness', function () { // https://github.com/moment/moment/issues/1128 assertOk(moment('2010-10-3199', ['MM/DD/YYYY', 'MM-DD-YYYY', 'YYYY-MM-DD']).isValid()); // https://github.com/moment/moment/issues/1122 assertOk(moment('3:25', ['h:mma', 'hh:mma', 'H:mm', 'HH:mm']).isValid()); }); it('0 hour is invalid in strict', function () { assertEq(moment('00:01', 'hh:mm', true).isValid(), false, '00 hour is invalid in strict'); assertEq(moment('00:01', 'hh:mm').isValid(), true, '00 hour is valid in normal'); assertEq(moment('0:01', 'h:mm', true).isValid(), false, '0 hour is invalid in strict'); assertEq(moment('0:01', 'h:mm').isValid(), true, '0 hour is valid in normal'); }); });
the_stack
import { createServer } from "http"; import { Server } from "socket.io"; import { Server as ServerV3 } from "socket.io-v3"; import { io as ioc } from "socket.io-client"; import { AddressInfo } from "net"; import { InMemoryStore, instrument, RedisStore } from ".."; import expect = require("expect.js"); import { createClient } from "redis"; const waitFor = (emitter: any, event: string): Promise<any> => { return new Promise((resolve) => { emitter.once(event, (...args: any[]) => { resolve(args.length === 1 ? args[0] : args); }); }); }; describe("Socket.IO Admin (server instrumentation)", () => { ([ ["v4", Server], ["v3", ServerV3], ] as [string, typeof Server][]).forEach(([version, ServerConstructor]) => { describe(`Socket.IO ${version}`, () => { let port: number, io: Server; beforeEach((done) => { const httpServer = createServer(); io = new ServerConstructor(httpServer); httpServer.listen(() => { port = (httpServer.address() as AddressInfo).port; done(); }); }); afterEach(() => { io.close(); }); it("creates an admin namespace", (done) => { instrument(io, { auth: false, }); const adminSocket = ioc(`http://localhost:${port}/admin`); adminSocket.on("connect", () => { adminSocket.disconnect(); done(); }); }); it("creates an admin namespace with custom name", (done) => { instrument(io, { auth: false, namespaceName: "/custom", }); const adminSocket = ioc(`http://localhost:${port}/custom`); adminSocket.on("connect", () => { adminSocket.disconnect(); done(); }); }); describe("authentication", () => { it("prevents anonymous connection", (done) => { instrument(io, { auth: { type: "basic", username: "admin", password: "$2b$10$nu1FHRkuxkZkqID.31gz4uQsyERZAn.m4IIruysTsHDODBtrqS5Me", // "changeit" }, }); const adminSocket = ioc(`http://localhost:${port}/admin`); adminSocket.on("connect", () => { done(new Error("should not happen")); }); adminSocket.on("connect_error", (err: any) => { expect(err.message).to.eql("invalid credentials"); adminSocket.disconnect(); done(); }); }); it("allows connection with valid credentials", (done) => { instrument(io, { auth: { type: "basic", username: "admin", password: "$2b$10$nu1FHRkuxkZkqID.31gz4uQsyERZAn.m4IIruysTsHDODBtrqS5Me", // "changeit" }, }); const adminSocket = ioc(`http://localhost:${port}/admin`, { auth: { username: "admin", password: "changeit", }, }); adminSocket.on("connect", () => { adminSocket.disconnect(); done(); }); }); it("allows connection with a valid session ID", (done) => { instrument(io, { auth: { type: "basic", username: "admin", password: "$2b$10$nu1FHRkuxkZkqID.31gz4uQsyERZAn.m4IIruysTsHDODBtrqS5Me", // "changeit" }, }); const adminSocket = ioc(`http://localhost:${port}/admin`, { reconnectionDelay: 100, auth: { username: "admin", password: "changeit", }, }); adminSocket.on("session", (sessionId) => { adminSocket.auth = { sessionId, }; adminSocket.on("connect", () => { adminSocket.disconnect(); done(); }); adminSocket.disconnect().connect(); }); }); it("prevents connection with an invalid session ID", (done) => { instrument(io, { auth: { type: "basic", username: "admin", password: "$2b$10$nu1FHRkuxkZkqID.31gz4uQsyERZAn.m4IIruysTsHDODBtrqS5Me", // "changeit" }, }); const adminSocket = ioc(`http://localhost:${port}/admin`, { auth: { sessionId: "1234", }, }); adminSocket.on("connect", () => { done(new Error("should not happen")); }); adminSocket.on("connect_error", (err: any) => { expect(err.message).to.eql("invalid credentials"); adminSocket.disconnect(); done(); }); }); }); it("returns the list of supported features", (done) => { instrument(io, { auth: false, }); const adminSocket = ioc(`http://localhost:${port}/admin`); adminSocket.on("config", (config: any) => { if (version === "v4") { expect(config.supportedFeatures).to.eql([ "EMIT", "JOIN", "LEAVE", "DISCONNECT", "MJOIN", "MLEAVE", "MDISCONNECT", ]); } else { expect(config.supportedFeatures).to.eql([ "EMIT", "JOIN", "LEAVE", "DISCONNECT", ]); } adminSocket.disconnect(); done(); }); }); it("returns an empty list of supported features when in readonly mode", (done) => { instrument(io, { auth: false, readonly: true, }); const adminSocket = ioc(`http://localhost:${port}/admin`); adminSocket.on("config", (config: any) => { expect(config.supportedFeatures).to.eql([]); adminSocket.disconnect(); done(); }); }); it("returns the list of all sockets upon connection", async () => { instrument(io, { auth: false, readonly: true, }); const clientSocket = ioc(`http://localhost:${port}`); await waitFor(clientSocket, "connect"); const adminSocket = ioc(`http://localhost:${port}/admin`, { forceNew: true, }); const sockets = await waitFor(adminSocket, "all_sockets"); expect(sockets.length).to.eql(2); sockets.forEach((socket: any) => { if (socket.nsp === "/") { expect(socket.id).to.eql(clientSocket.id); } else { expect(socket.id).to.eql(adminSocket.id); expect(socket.nsp).to.eql("/admin"); } }); clientSocket.disconnect(); adminSocket.disconnect(); }); it("emits administrative events", async () => { instrument(io, { auth: false, }); const adminSocket = ioc(`http://localhost:${port}/admin`); await waitFor(adminSocket, "connect"); const clientSocket = ioc(`http://localhost:${port}`, { forceNew: true, }); // connect const serverSocket = await waitFor(io, "connection"); const socket = await waitFor(adminSocket, "socket_connected"); expect(socket.id).to.eql(serverSocket.id); expect(socket.nsp).to.eql("/"); expect(socket.handshake).to.eql({ address: serverSocket.handshake.address, headers: serverSocket.handshake.headers, query: serverSocket.handshake.query, issued: serverSocket.handshake.issued, secure: serverSocket.handshake.secure, time: serverSocket.handshake.time, url: serverSocket.handshake.url, xdomain: serverSocket.handshake.xdomain, }); expect(socket.rooms).to.eql([...serverSocket.rooms]); // join serverSocket.join("room1"); const [nsp, room, id] = await waitFor(adminSocket, "room_joined"); expect(nsp).to.eql("/"); expect(room).to.eql("room1"); expect(id).to.eql(socket.id); // leave serverSocket.leave("room1"); const [nsp2, room2, id2] = await waitFor(adminSocket, "room_left"); expect(nsp2).to.eql("/"); expect(room2).to.eql("room1"); expect(id2).to.eql(socket.id); // disconnect serverSocket.disconnect(); const [nsp3, id3] = await waitFor(adminSocket, "socket_disconnected"); expect(nsp3).to.eql("/"); expect(id3).to.eql(socket.id); adminSocket.disconnect(); }); it("performs administrative tasks", async () => { instrument(io, { auth: false, }); const adminSocket = ioc(`http://localhost:${port}/admin`); await waitFor(adminSocket, "connect"); const clientSocket = ioc(`http://localhost:${port}`, { forceNew: true, }); const serverSocket = await waitFor(io, "connection"); await waitFor(adminSocket, "room_joined"); // emit adminSocket.emit("emit", "/", serverSocket.id, "hello", "world"); const value = await waitFor(clientSocket, "hello"); expect(value).to.eql("world"); // join adminSocket.emit("join", "/", "room1", serverSocket.id); await waitFor(adminSocket, "room_joined"); expect(serverSocket.rooms.has("room1")).to.eql(true); // leave adminSocket.emit("leave", "/", "room1", serverSocket.id); await waitFor(adminSocket, "room_left"); expect(serverSocket.rooms.has("room1")).to.eql(false); // disconnect adminSocket.emit("_disconnect", "/", false, serverSocket.id); await waitFor(clientSocket, "disconnect"); adminSocket.disconnect(); }); it("supports dynamic namespaces", async function () { // requires `socket.io>=4.1.0` with the "new_namespace" event if (version === "v3") { return this.skip(); } instrument(io, { auth: false, }); io.of(/\/dynamic-\d+/); const adminSocket = ioc(`http://localhost:${port}/admin`); await waitFor(adminSocket, "connect"); const clientSocket = ioc(`http://localhost:${port}/dynamic-101`, { forceNew: true, }); const socket = await waitFor(adminSocket, "socket_connected"); expect(socket.nsp).to.eql("/dynamic-101"); clientSocket.disconnect(); adminSocket.disconnect(); }); }); }); describe("Stores", () => { describe("InMemoryStore", () => { it("works", async () => { const store = new InMemoryStore(); store.saveSession("123"); expect(await store.doesSessionExist("123")).to.eql(true); expect(await store.doesSessionExist("456")).to.eql(false); }); }); describe("RedisStore", () => { it("works", async () => { const redisClient = createClient(); const store = new RedisStore(redisClient); store.saveSession("123"); expect(await store.doesSessionExist("123")).to.eql(true); expect(await store.doesSessionExist("456")).to.eql(false); redisClient.quit(); }); }); }); });
the_stack
// ------------------------------------------------------------------------ // Copyright (c) 2018 Alexandre Bento Freire. All rights reserved. // Licensed under the MIT License+uuid License. See License.txt for details // ------------------------------------------------------------------------ // This file was generated via gulp build-definition-files // // @WARN: Don't edit this file. // // This file contains about the compilation of all the exported types // targeted for the end-user // The source data is all information in each source code file defined between // #export-section-start: release // and #export-section-end: release // // This way the user will have access to all the public information in one file // It won't be used during the development phase. // And it's excluded in tsconfig // declare namespace ABeamer { export function downRound(v: number): int; export function sprintf( // pattern containing %d formatters format: string, // value to replace ...values): string; // ------------------------------------------------------------------------ // Server // ------------------------------------------------------------------------ export interface ServerFeatures { hasLogging: boolean; } // ------------------------------------------------------------------------ // Messages // ------------------------------------------------------------------------ export interface Localization { locale: string; charRanges?: [number, number][]; messages?: { [srcMsg: string]: string }; functionalities?: [Functionalities | string, { src: string, dst: string }[]][]; } /** * These messages will be moved messages/messages-en.ts on version 2.x */ export enum Msgs { MustNatPositive = 'The value of %p% must be a natural positive', MustNatNotNegative = 'The value of %p% must be a natural non-negative', MustBeANumber = 'The value of %p% must be a number', MustBeAString = 'The value of %p% must be textual', MustBeANumberOrExpr = 'The value of %p% must be a number or an expression', MustBeAStringOrExpr = 'The value of %p% must be textual or an expression', Unknown = 'Unknown %p%', UnknownOf = 'Unknown "%type%" %p%', UnknownType = 'Unknown type of %p%', NoEmptyField = 'Field %p% can not be empty', NoEmptySelector = 'Selector %p% can not be empty', NoCode = 'Code Handler is not allowed', OutOfScope = '%p% out of scope', ExpHasErrors = 'Expression %e% has errors: %err%', WrongNrParams = 'Function %p% has the wrong number of input parameters', WrongParamType = 'Function %p% has the wrong type in parameter: %i%', ValueTypeError = 'Value %p% must be a number or an expression', UnaryErr = 'Unary operators only support numerical values', flyover = 'flyover', task = 'task', pos = 'position', startScene = 'startScene', endScene = 'endScene', } export interface I8nParams { [name: string]: (number | string); } export function i8nMsg(msg: string, params?: I8nParams): string; export enum RoundFuncName { none, round, ceil, floor, downRound, } export type RoundFunc = (v: number) => number; export type RoundHandlerFunc = string | RoundFuncName | RoundFunc; export function parseRoundFunc(handler: RoundHandlerFunc): RoundFunc; export function parseHandler<T, TO>(handler: T, defaultHandler: T, _mapper: any, args: ABeamerArgs): TO; export function parseEnum<T>(value: T | string, mapper: any, defValue?: T | string | undefined): T; export function throwErr(msg: string): void; export function throwI8n(msg: string, params?: I8nParams): void; export function throwIf(isTrue: boolean, msg: string): void; export function throwIfI8n(isTrue: boolean, msg: string, params?: I8nParams): void; // ------------------------------------------------------------------------ // Time // ------------------------------------------------------------------------ /** * List of supported Time Units. * `%` can only be used if there is a parent time reference. */ export enum TimeUnit { f, ms, s, m, '%', } /** Time [](Code Handler) */ export type TimeFunc = (args?: ABeamerArgs) => TimeUnit | string | ExprString | number; /** Time used by the user to provide Duration and Position */ export type TimeHandler = TimeUnit | string | ExprString | number | TimeFunc; export function frame2Time(frame: uint, fps: uint, unit: TimeUnit, maxPrecision?: uint): string; export function parseTimeHandler( timeOrFrame: TimeHandler | undefined, args: ABeamerArgs, defaultTimeOrFrame: string | int, referenceFrame: int, toInt: boolean = true): int | number; // ------------------------------------------------------------------------ // Functions // ------------------------------------------------------------------------ export const enum ExFuncParamType { Any, Number, String, Array, } export interface ExFuncParam { paType?: ExFuncParamType; sValue?: string; numValue?: number; arrayValue?: number[]; } export type _CheckParamFunc = (req: ExFuncReq, paramCount: uint, paramTypes?: ExFuncParamType[]) => void; export interface ExFuncReq { args: ABeamerArgs; req?: ExFuncReq; res?: ExFuncParam; checkParams: _CheckParamFunc; } export type ExprFuncParams = ExFuncParam[]; export type ExFunction = (params: ExprFuncParams, req?: ExFuncReq) => void; // ------------------------------------------------------------------------ // Expressions // ------------------------------------------------------------------------ export type VarType = number | string | boolean | number[] | object; export interface Vars { e: number; pi: number; /** =pi/180 */ deg2rad: number; /** =180/pi */ rad2deg: number; /** Frames per second. */ fps?: uint; /** Frame output width = generated file image width. */ frameWidth?: uint; /** Frame output height = generated file image height. */ frameHeight?: uint; /** Is True, if it's teleporting. */ isTeleporting?: boolean; /** Element index of the active adapter */ elIndex?: uint; /** Number of elements inside defined by the active adapter */ elCount?: uint; /** Computed Numerical `valueStart`. */ v0?: number; /** Computed Numerical `value`. */ v1?: number; /** Computed Numerical difference `value` - `valueStart`. */ vd?: number; /** Computed Numerical value injected to the easing function. */ vt?: number; /** Computed Numerical value injected to the oscillator function. */ vot?: number; /** Computed Numerical value injected to the path function. */ vpt?: number; /** `t` used to interpolate an easing, oscillator or path via expression. */ t?: number; /** Generic value. Used in Charts. */ v?: number; /** Generic iterator. Used in Factories. */ i?: int; /** Generic number of items/points/elements. Used in Charts. */ n?: int; [name: string]: VarType; } export const enum ExprType { NotExpr, CalcOnce, CalcMany, } export type ExprResult = string | number | number[]; export type ExprString = string; export function getVars(): Vars; export function isCharacter(ch: string | undefined, pos: uint = 0): boolean; export function isDigit(ch: string): boolean; export function isCharacterOrNum(ch: string): boolean; export function isExpr(text: string): boolean; export function arrayInputHelper(params: ExprFuncParams, req: ExFuncReq, paramCount: uint | undefined, arrayLength: uint | undefined, func: (inpArray: any) => any): void; export function calcExpr(expr: string, args: ABeamerArgs): ExprResult; export function ifExprCalc(expr: string, args: ABeamerArgs): ExprResult | undefined; export function ifExprCalcNum(expr: string, defNumber: number | undefined, args: ABeamerArgs): number | undefined; export function calcStr(expr: string, args: ABeamerArgs): string; export function ifExprCalcStr(expr: string, defString: string | undefined, args: ABeamerArgs): string | undefined; export function ExprOrNumToNum(param: ExprString | number, defValue: number | undefined, args: ABeamerArgs): number | undefined; export function ExprOrStrToStr(param: ExprString | string, defValue: string | undefined, args: ABeamerArgs): string | undefined; // ------------------------------------------------------------------------ // Easings // ------------------------------------------------------------------------ /** * Defines the easing Code Handler. * * An **easing** is a interpolator runs `t` from [0, 1], where * `t=0` is the first frame and `t=1` the last frame of the animation. * This interpolator can be viewed as the speed interpolator and its the * first one in the Animation Pipeline. * Usually outputs a value from [0, 1] but other values are also possible. */ export type EasingFunc = (t: number, params: EasingParams, args?: ABeamerArgs) => number; /** * Defines the easing type, which is either string representing a predefined * easing function or a custom function (see easing function). * * The easing function interpolates from [0, 1]. */ export type EasingHandler = EasingName | string | ExprString | EasingFunc | ExprName; /** * Defines the Base parameters for every easing function. * At the moment no parameter is required, but it can change in the future. */ export type EasingParams = AnyParams; /** List of the built-in easings */ export enum EasingName { linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInSine, easeOutSine, easeInOutSine, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInElastic, easeOutElastic, easeInOutElastic, easeInBack, easeOutBack, easeInOutBack, easeInBounce, easeOutBounce, easeInOutBounce, } // ------------------------------------------------------------------------ // Oscillators // ------------------------------------------------------------------------ /** * Defines the type of a oscillator function. * An oscillator function is an interpolator that runs from [0, 1]. * Usually outputs a value from [-1, 1] but other values are also possible. * An oscillator is mostly used to rotate an element returning to the original position. */ export type OscillatorFunc = (t: number, params: OscillatorParams, args?: ABeamerArgs) => number; /** * Defines the oscillator type, which is either string representing a predefined * oscillator function or a custom function (see oscillator function) * The oscillator function interpolates from [0, 1]. */ export type OscillatorHandler = OscillatorName | number | ExprString | OscillatorFunc | EasingFunc; /** * Defines the Base parameters for every oscillator function. * At the moment no parameter is required, but it can change in the future. */ export type OscillatorParams = AnyParams; /** List of the built-in oscillators */ export enum OscillatorName { harmonic = 1000, // lower ids are for easings. damped, pulsar, } /** Oscillator parameters defined in an Animation Property. */ export interface Oscillator { /** Defines an Oscillator by Name, Expression or Code Handler */ handler: OscillatorHandler; /** Params passed to the Oscillator. Depends on the Oscillator Type */ params?: AnyParams | HarmonicOscillatorParams | DampedOscillatorParams | PulsarOscillatorParams ; } /** Function used to define what to do when a value is negative. */ export type NegativeFunc = (t: number) => number; /** * List of Negative built-in functions: * - `abs` Math.abs * - `clip` If v < 0 then v = 0 */ export enum NegativeBuiltInFuncs { none, clip, abs, } /** Params defined inside the props.oscillator.params, when `props.oscillator = 'harmonic'` */ export interface HarmonicOscillatorParams extends OscillatorParams { /** * Defines the number of full cycles (positive arc+negative arc) * contained during the `duration` period. * If `negativeHander = abs`, 1 cycle will have 2 arcs. */ cycles?: number; /** Function used to define what to do when a value is negative. */ negativeHander?: NegativeBuiltInFuncs | string | NegativeFunc; /** Allows to shift and scale the input of every oscillator. */ shift: number; // cut: number; } /** Params defined inside the props.oscillator.params, when `props.oscillator = 'damped'` */ export interface DampedOscillatorParams { frequency?: number; /** Defines how much energy the oscillator will lose from one cycle to the next. */ friction?: number; /** Function used to define what to do when a value is negative. */ negativeHander?: NegativeBuiltInFuncs | string | NegativeFunc; } /** List of the built-in pulsar type */ export enum PulsarType { normal, sine, random, positiveRandom, } /** Params defined inside the props.oscillator.params, when `props.oscillator = 'pulsar'` */ export interface PulsarOscillatorParams { /** Type of pulsar defined by ID or string. */ type?: PulsarType | string; /** The point where the pulsar reaches it's maximum value. */ midpoint?: number; /** * The amplitude around midpoint where the pulsar begins to receive value. * The pulsar starts gaining energy at `midpoint-spread`, reaches the maximum value * at `midpoint` and then decreases until reaches zero at `midpoint+spread`. */ spread?: number; } // ------------------------------------------------------------------------ // Paths // ------------------------------------------------------------------------ /** * Defines the type of a path function. * A path function is an interpolator that usually runs from [0, 1]. * An path defines a movement in the n-space. */ export type PathFunc = (t: number, params: PathParams, stage: uint, args?: ABeamerArgs) => number[]; /** * Defines the path type, which is either string representing a predefined * path function or a custom function (see path function). * The path function interpolates from [0, 1]. */ export type PathHandler = PathName | string | ExprString | PathFunc; /** List of the built-in paths */ export enum PathName { line, rect, circle, ellipse, } /** * Defines the Base parameters for every path function. * At the moment no parameter is required, but it can change in the future. */ export type PathParams = AnyParams; /** Path parameters defined in an Animation Property. */ export interface Path { /** Defines a Path by Name, Expression or Code Handler */ handler: PathHandler; /** Params passed to the Path. Depends on the Path Type */ params?: FuncParams | LinePathParams | RectPathParams | CirclePathParams | EllipsePathParams ; } export interface CenteredPathParams extends PathParams { centerX?: number | ExprString; centerY?: number | ExprString; } export interface LinePathParams extends PathParams { x0?: number | ExprString; y0?: number | ExprString; x1?: number | ExprString; y1?: number | ExprString; } export type RectPathParams = LinePathParams; export interface CirclePathParams extends CenteredPathParams { radius?: number | ExprString; } export interface EllipsePathParams extends CenteredPathParams { radiusX?: number | ExprString; radiusY?: number | ExprString; } // ------------------------------------------------------------------------ // Tasks // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Task Results // ------------------------------------------------------------------------ export const TR_EXIT = 0; export const TR_DONE = 1; export const TR_INTERACTIVE = 2; export type TaskResult = 0 | 1 | 2; // ------------------------------------------------------------------------ // Task Stage // ------------------------------------------------------------------------ export const TS_INIT = 0; export const TS_ANIME_LOOP = 1; export const TS_TELEPORT = 2; // ------------------------------------------------------------------------ // Task Interface // ------------------------------------------------------------------------ export type TaskFunc = (anime: Animation, wkTask: WorkTask, params?: AnyParams, stage?: uint, args?: ABeamerArgs) => TaskResult; export type TaskHandler = TaskName | TaskFunc; export type TaskName = string | GeneralTaskName | TextTaskName | ShapeTaskName | AttackTaskName ; export type TaskParams = AnyParams | GeneralTaskParams | TextTaskParams | ShapeTaskParams | AttackTaskParams ; /** * Parameters provided by the user during an `addAnimation`. */ export interface Task { /** Task Name, Expression or Input Function defined by the user. */ handler: TaskHandler; /** Parameters passed to the task function */ params?: TaskParams; } /** * Parameters passed to a task during the execution. */ export interface WorkTask { name: string; params: TaskParams; animeIndex: uint; } export type GeneralTaskName = /** @see TaskFactoryParams */ | 'factory' ; export type GeneralTaskParams = | FactoryTaskParams ; export type FactoryTaskAttr = string | ExprString | number | string[] | number[]; export interface FactoryTaskParams extends AnyParams { count: uint | ExprString; tag?: string; content?: FactoryTaskAttr; isContentFormatted?: boolean; attrs?: { name: string; value: FactoryTaskAttr; isFormatted?: boolean; }[]; } // ------------------------------------------------------------------------ // Flyovers // ------------------------------------------------------------------------ export interface InfoFlyoverParams { /** * Element selector from the story, it can be DOM or virtual. * @default .info-flyover */ selector?: ElSelector; /** * Text patterns supporting '${}' macros. * * Supported macros are: * * - `storyFrameNr` - current render frame within the story. * - `storyElapsedS` - number of seconds elapsed within the story. * - `storyElapsedMS` - number of milliseconds elapsed within the story. * - `storyElapsedM` - number of minutes elapsed within the story. * * @example story-frame: ${storyFrameNr} story-time: ${storyTime} * @default ${storyFrameNr} */ format?: string; /** * Maximum number of decimal digits for time macros. * @default: 4 */ maxPrecision?: int; } export interface VideoSyncFlyoverParams { /** * Element selector from the story, it can be DOM or virtual. * * @default #video */ selector?: ElSelector; /** * If it's `false`, is disabled if `isServer = true`. * * @default true */ serverRender: boolean; } /** * Generic parameters passed to a flyover function. */ export type FlyoverParams = AnyParams | InfoFlyoverParams | VideoSyncFlyoverParams; /** * Defines a function that is executed on every render step. * Use it to render elements that scene independent. */ export type FlyoverFunc = (wkFlyover: WorkFlyover, params: FlyoverParams, stage?: uint, args?: ABeamerArgs) => void; export interface WorkFlyover { name: string; params: FlyoverParams; } /** * Flyover Name, Expression or Input Function defined by the user. * in `story.addFlyover`. */ export type FlyoverHandler = string | FlyoverFunc // Displays info about frames or time | 'info' // Synchronizes a video current time with the story current render frame | 'video-sync'; // ------------------------------------------------------------------------ // Elements // ------------------------------------------------------------------------ /** * Defines the special names for [Adapter properties](#Adapter property) names. */ export type SpecialAdapterPropName = // modifies the textContent property. 'text' // same as text. It's preferable to use 'text'. | 'textContent' // modifies the innerHTML attribute. | 'html' // same as html. It's preferable to use 'html'. | 'innerHTML' // modifies outerHTML attribute. | 'outerHTML' // changes the style.display CSS property for DOM Elements/Scenes. // Uses DOM attribute `data-abeamer-display`. | 'visible' // modifies the attribute `src`. | 'src' // modifies the `classList` if it has `+` or `-` if has it starts a class. // otherwise it sets `className`. | 'class' ; /** * **Dual properties** are properties that map one animation property into 2 [](DOM properties). */ export type DualPropName = 'width-height' | 'left-top' | 'right-top' | 'left-bottom' | 'right-bottom'; /** * List of Property Names that a DOM or Virtual Element should support. */ export type ElPropName = string | 'id' | 'visible' | 'uid' | 'data-abeamer-display' ; /** * List of Property Names that a DOM or Virtual Scene should support. */ export type ScenePropName = string | 'html' | 'left' | 'top' | 'width' | 'height' /** If this value is set, it will for `Visible=true` */ | 'data-abeamer-display' ; /** * List of Property Names that a DOM or Virtual Story should support. */ export type StoryPropName = string | 'frame-width' | 'frame-height' /** clip-path is a set only. see CSS clip-story properties */ | 'clip-path' | 'fps' ; /** * Union of Property Names that a DOM or Virtual Adapter should support. */ export type PropName = string | ElPropName | ScenePropName | StoryPropName | SpecialAdapterPropName | DualPropName ; /** * Although, DOM only returns string values, a virtual Element can use * more rich data types. * e.g. DOM adapter maps a boolean `visible` into CSS display. * A virtual element can use directly booleans. */ export type PropValue = string | number | int | boolean; export enum WaitForWhat { Custom, ImageLoad, MediaSync, } export interface WaitFor { prop: PropName; value?: string | number; what?: WaitForWhat; } export type WaitForList = WaitFor[]; /** * Base interface for virtual elements such as WebGL, Canvas or Task animator. */ export interface VirtualElement { getProp(name: PropName, args?: ABeamerArgs): PropValue; setProp(name: PropName, value: PropValue, args?: ABeamerArgs): void; waitFor?(waitFor: WaitFor, onDone: DoneFunc, args?: ABeamerArgs): void; /** * Called after the frame is rendered, and before moves to the next frame. * This method is called even if no property changed. * It's an optional method, but future version might require its implementation. */ frameRendered?(args?: ABeamerArgs): void; } export type PElement = HTMLElement | VirtualElement; // ------------------------------------------------------------------------ // VirtualAnimator // ------------------------------------------------------------------------ /** * Used by plugin creators to allow their content to be animated. * A plugin can animate canvas, WebGl, svg or reduce the complexity of a CSS animation. * The story uses `uid` to manage animators. */ export interface VirtualAnimator extends VirtualElement { selector: string; } /** * It simplifies the usage of [](VirtualAnimator) by plugins. * In many cases plugins just need to receive the changing property, * in order to modify its state. * Override `animateProp` to receive the changing property. * animateProp isn't called if the property is `uid`. */ export class SimpleVirtualAnimator implements VirtualAnimator { props: AnyParams = {}; selector: string; propsChanged: boolean = false; onAnimateProp: (name: PropName, value: PropValue) => void; onAnimateProps: (args?: ABeamerArgs) => void; /** * Called after property value changed. * Use this method instead animateProps, if the rendering should be right after * each property is updated, otherwise use animateProps. */ animateProp(name: PropName, value: PropValue): void { if (this.onAnimateProp) { this.onAnimateProp(name, value); } } /** * Called after actions from the frame are rendered, and if at least one property changed. * Use this method instead animateProp, if the animation has multiple virtual properties and * each animation can be done after all are updated. */ animateProps(args?: ABeamerArgs): void { if (this.onAnimateProps) { this.onAnimateProps(args); } } getProp(name: PropName): PropValue { return this.props[name]; } setProp(name: PropName, value: PropValue): void { this.props[name] = value; if (name !== 'uid') { this.propsChanged = true; this.animateProp(name, value); } } frameRendered(args?: ABeamerArgs) { if (this.propsChanged) { this.animateProps(args); this.propsChanged = false; } } } // ------------------------------------------------------------------------ // Scene Selectors // ------------------------------------------------------------------------ /** * Base interface for virtual scenes such as WebGL, Canvas. */ export interface VirtualScene { /** * Must support `id` and `visible` attributes. */ getProp(name: PropName, args?: ABeamerArgs): string; /** * Must support `visible` and `uid` attributes. */ setProp(name: PropName, value: string, args?: ABeamerArgs): void; /** * Must call iterator for each element represented on the selector. * * @param selector CSS style selectors */ query(selector: string, iterator: (element: PElement, index: uint) => void); } /** * Scene Selector defined by the user. */ export type SceneSelector = string | JQuery | VirtualScene; // ------------------------------------------------------------------------ // Element Selector // ------------------------------------------------------------------------ /** * Defines css selectors, JQuery, meta-selectors, and Virtual selectors. * Virtual selectors start with `%`. */ export type ElSelector = JQuery // (DOM or virtual) selectors | string // list of (DOM or virtual) elements ids | string[] // list of html elements | HTMLElement[] // list of virtual elements | VirtualElement[] // An pEls containing elements | pEls ; /** * User defined function that return an Element Selector. * Doesn't supports remote rendering. */ export type ElSelectorFunc = (args?: ABeamerArgs) => ElSelector; /** * Element Selector defined by the user. */ export type ElSelectorHandler = ElSelector | ElSelectorFunc; // ------------------------------------------------------------------------ // Browser // ------------------------------------------------------------------------ export interface Browser { isMsIE: boolean; vendorPrefix: string; prefixedProps: string[]; } export const browser: Browser = { isMsIE: false, vendorPrefix: '', prefixedProps: [], }; // ------------------------------------------------------------------------ // Transitions // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Transition States // ------------------------------------------------------------------------ export const TRS_SETUP = 0; export const TRS_AT_OUT = 1; export const TRS_AT_IN = 2; export const DEFAULT_TRANSITION_DURATION = '1s'; /** * List of the built-in Transition Names. */ export enum StdTransitions { slideLeft, slideRight, slideTop, slideBottom, dissolve, } /** * Parameters passed to the Transition function. */ export interface TransitionParams { bothVisible: boolean; state?: int; frameI?: int; enterFrameI?: uint | undefined; leaveRealFrameI?: uint | undefined; frameCount?: uint; leaveFrameCount?: uint; enterFrameCount?: uint; leaveAdapter?: AbstractAdapter; enterAdapter?: AbstractAdapter; } export type TransitionFunc = (params: TransitionParams, args?: ABeamerArgs) => void; export type TransitionHandler = string | ExprString | TransitionFunc | StdTransitions; export interface Transition { handler: TransitionHandler; duration?: TimeHandler; } // ------------------------------------------------------------------------ // Plugin Manager // ------------------------------------------------------------------------ export interface AnyParams { [key: string]: any; } export interface ABeamerArgs { story?: Story; scene?: Scene; stage?: uint; /** Every time, the render is executed this value is incremented. */ renderNr?: uint; user?: AnyParams; waitMan?: WaitMan; /** If true, the internal code or plugin should dump information using `story.logFrmt`. */ isVerbose?: boolean; /** * True if it's running a supporting server program for frame storage. * * #end-user @readonly */ hasServer?: boolean; isTeleporting?: boolean; /** If true, perform type checks and other restriction checks. */ isStrict?: boolean; /* * Global variables used as variables of expressions. * `abeamer render` command-line can change these variables by passing them * as multiple `--var` parameters, * these parameters will be converted to queryString and added to url. * * ## Examples * * accessed by expressions in client library: * `valueText: 'pi*2'` * * passed by command line: * `abeamer render --var name=end-user --var value=1.2.3`. * * passed on the url: * ?var=name%3Dend-user&var=value%3D1.2.3 */ vars: Vars; } /** * Information required by each plugin creator about its own plug-in. */ export interface PluginInfo { id: string; uuid: string; author: string; email: string; copyrights?: string; jsUrls?: string[]; cssUrls?: string[]; assetsUrls?: string[]; telemetricUrl?: string[]; teleportable: boolean; } /** List of all the functionalities available to be extended by plugins. */ export enum Functionalities { easings, oscillators, paths, transitions, tasks, flyovers, functions, } // ------------------------------------------------------------------------ // Text Tasks // ------------------------------------------------------------------------ export type WrapperTaskName = /** @see #SceneTransitionTaskParams */ | 'scene-transition' /** @see #AddStillsTaskParams */ | 'add-stills' /** @see #AddFlyoverTaskParams */ | 'add-flyover' /** @see #AddVarsTaskParams */ | 'add-vars' ; export type WrapperTaskParams = | SceneTransitionTaskParams | AddStillsTaskParams | AddFlyoverTaskParams | AddVarsTaskParams ; export interface SceneTransitionTaskParams extends AnyParams { handler?: TransitionHandler; duration?: TimeHandler; } export interface AddStillsTaskParams extends AnyParams { duration: TimeHandler; } export interface AddFlyoverTaskParams extends AnyParams { handler: FlyoverHandler; params?: FlyoverParams; } /** * Adds multiple variables to `args.vars`. * Variables can be: * * - textual, numerical and arrays. * - object variables of the above types. * * ## Example * * ```typescript * tasks: [{ * handler: 'add-vars', * params: { * vars: { * prop1: 'changes the args.vars.prop1', * 'obj1.prop2': 'creates an object obj1 in vars, set prop2', * 'over.about.blue': 'creates obj over.about.sets prop blue', * }, * } * }] * ``` */ export interface AddVarsTaskParams extends AnyParams { /** * If false, it won't overwrite the previous value. * @default true */ overwrite?: boolean; /** * If true and textual value starts with `=`, it will compute the expression. * @default false */ allowExpr?: boolean; /** * Object with name: value of all the variables to add to `args.vars`. */ vars: { [varName: string]: string | ExprString | number | number[] }; } // ------------------------------------------------------------------------ // Animation Direction // ------------------------------------------------------------------------ export enum Directions { normal, reverse, alternate, 'alternate-reverse', } /* ---- Bypass Mode ---- */ export const BP_FIRST_INSIDE = 0; // this is the default bypass mode export const BP_INSIDE = 1; export const BP_ALL = 2; export type BypassMode = 0 | 1 | 2; /* ---- Function Stage ---- */ export const FS_PREPARE = 0; export const FS_TELEPORT = 1; export const FS_RUN = 2; /** Base parameters used by any Animation Function. */ export type FuncParams = AnyParams; /** Value used, if no duration is defined for an animation. */ export const DEFAULT_DURATION = '1f'; /** Value used, if no duration is defined for a fade in/out. */ export const DEFAULT_FADE_DURATION = '400ms'; /** * A ExprName is used for motion handlers, mostly for easings, to have * dynamic names. * Since an expression can be used to interpolate, by using expressions starting * with '==', it will compute immediately the expression and the output * must the motion name. * @example = 'easeIn' + iff(frameWidth < 100, 'Quad', 'Cubic') */ export type ExprName = ExprString; /** * Defines parameters used both by `Animation` and `AnimationProp`. * The `AnimationProp` overrides the parameters defined by `Animation`. * This way, an animation can have parameters for all animation properties * and some animation properties can have different parameters. * The `duration` parameter defined in the animation property * */ export interface AnimationCommonParams { /** If it's false, it will bypass the animation or property. */ enabled?: boolean; /** * A `Scene.addAnimations` runs its list of animations and properties in parallel, * and at the end of last animation it moves the position forward. * Setting the `advance`: * 1. To `true` of an animation property will move forward the position * for the next property animation, but not the animation. * The property of each element moves independently. * 2. To `true` of an animation that isn't the last one, will move forward * for the next animation within the list. * The value used with the maximum of all the elements of the all the properties * of the previous animation. * 3. To `false` of the last animation, it won't move forward at the end. */ advance?: boolean; /** * Defines the duration of the animation of a single cycle * in terms of frames, seconds, minutes or milliseconds. * The total duration is `duration*(iterationCount + 1)`. * In case of numerical values, ABeamer uses `defaultUnit` * to known what kind of unit is it. * * @see #iterationCount * * @example '1s' * @example '40ms' * @example '20%' (use only on the animation property duration) * @example '5fps' * @example 50 * @example 2.5 (use only if the DefaultUnit is 's' or 'ms') * @example (args) => '2s' (JavaScript functions aren't teleportable) * @example '=round(fps/2)' */ duration?: TimeHandler; /** * Allows to [](#off-sync) the starting point of an animation. * Use `+`, `-` for relative positions. * Prefer relative positions over absolute positions. * Use only if you need to off-sync an animation. * Overlapping property animations isn't supported. * * @example '-10fps' (starts the animation 10 frames before the expected starting point) * @example '+2ms' (starts the animation 2 milliseconds after the expected starting point * @example (args) => '4ms' (JavaScript functions aren't teleportable) */ position?: TimeHandler; /** * An **easing** is a interpolator runs `t` from [0, 1], where * `t=0` is the first frame and `t=1` the last frame of the animation. * This interpolator can be viewed as the speed interpolator and its the * first one in the Animation Pipeline. * The output value will be used to feed the [](#oscillator). * Usually outputs a value from [0, 1] but other values are also possible. * * This interpolator can be used outside physical motion (left/right/top/bottom). * In cases of textual property, such as `color`, `text`, `src`, * the easing will define how quickly those values will change * among a list defined `valueText` or by using `valueFormat`. * In this case, the `startValue` and `value` should be between [0, 1]. * Setting a `startValue` higher than `value`, * will reverse the direction of the changes. * * The easing can also be used to define the speed of the changes * of multi-parameter properties, such as `text-shadow`, by using as an input * of a `valueFormat`. * * This is the first stage of the Animation Pipeline. * The output value will be used to feed the [](#oscillator). * * ABeamer includes a list of the most common easings by * bundling the jquery.easing plugin. * More can be added via plugins. * * An easing can be defined by: * 1. Name - It will use the list of easings predefined or added via plugins. * 2. Expression - It evaluate the expression for each frame, passing the variable `t`. * 3. Code Handler - This function will receive the variable `t`. * * **WARNING** Code Handlers aren't [teleported](teleporter), * therefore it can't be used in remote rendering. * * @default 'linear' * @see easings */ easing?: EasingHandler; /** * An **oscillator** is an optional interpolator that runs `t` from [easing(0), easing(1)] * and the usually outputs a value from [-Amplitude, Amplitude] where usually * f(0) = 0 and f(1) = 0. * Its output will be generate `v = valueStart + (value - valueStart) * oscillator(easing(t))` * and then will be injected into a path as input. * * An oscillator has the following usages: * * 1. A rotational movement, where the oscillator defines the rotation and * the easing the defines the speed. * * 2. Flashing elements, where an element changes its `opacity` or `text-shadow`, * and these values oscillate between [0, 1]. * * 3. Uni-dimensional paths. Unlike paths, the oscillators have their value stored * in the Action Link, allowing to link the end value to the next animation. * * The oscillators shares the namespace with [](easings), allowing any easing function * to operate also as a oscillator. * Since the main function of an oscillator is to return to its original position * at the end of the animation cycle, when an easing is used as an oscillator the * best is to use the following: * ```json * { iterationCount: 2, * direction: alternate * } * ``` * An oscillator can be defined by: * 1. Name - It will use the list of easings and oscillator predefined or added via plugins. * 2. Expression - It evaluate the expression for each frame, passing the variable `t`. * 3. Code Handler - This function will receive the variable `t`. * * **WARNING** Code Handlers aren't [teleported](teleporter), * therefore it can't be used in remote rendering. * */ oscillator?: Oscillator; /* * An interpolator function where the input is the result of the * oscillator interpolator after the easing interpolator usually, * goes from [0, 1] and the output is an list of numbers, * representing the n-dimensions of a path. * To reverse the direction path, set `value = -1` and `valueStart = 0`. * To follow only a segment of the path, set both `value` and `valueStart`. * * Multi-dimension paths are mutual exclusive with textual `valueText`. * * Single-dimensions paths work similar to easings and oscillators. * These paths use the easing to define the speed and the path * can create post-effects such as steps. * The output of the a single-path value isn't stored in the Action Link, unlike * the oscillator. * * A multi-dimension path can be used in the following ways: * - via `valueFormat`. Allows to encode that path in a single property. * Used in `text-shadow`, `transform`. * - via dual-properties. */ path?: Path; /** * Delay of the start of the animation between 2 elements defined inside the selector. * The total duration of the animation will be: `duration+count*itemDelayDuration`. * @see itemDelayGrouping */ itemDelayDuration?: TimeHandler; /** * Applies a modulus division to the elements defined in the selector when * it relates the `itemDelayDuration`. * A `itemDelayDuration=2`, will make the odd elements to have the same * `itemDelayDuration`. */ itemDelayGrouping?: uint; /** * Applies a random changes with maximum of `itemDelayDisturbance` to the * `itemDelayDuration` for each element defined by the selector. */ itemDelayDisturbance?: TimeHandler; } // ------------------------------------------------------------------------ // AnimationProp // ------------------------------------------------------------------------ export type AnimPropValue = string | number; export type PropValueFunc = (args?: ABeamerArgs) => AnimPropValue; export type PropValueStartHandler = AnimPropValue | int | ExprString | PropValueFunc; export type PropValueHandler = PropValueStartHandler; export type ValueTextFunc = (t: number, args?: ABeamerArgs) => string; export interface AnimationProp extends AnimationCommonParams { /** * Defines the property name. The property corresponds to DOM style element * or special properties * * @see AnimationPropName */ prop: PropName; /** * Defines the starting value of an animation injected into the * Animation Pipeline (easing➝oscillator➝path|valueText➝valueFormat). * Easing interpolates from `valueStart` to `value`. * * Use only if: * 1. ABeamer can't get the value from the element property. * 2. There is no [](#Action Link) or you want to have a different start value. * 3. Handle virtual elements. * * - Always set this value CSS transforms, since ABeamer doesn't * computes the CSS transform. * - For pixels, all write text with 'px' suffix unless * is defined `valueFormat`. * - To interpolate textual values, usually set `valueStart=0`. * - It supports expressions and Code Handlers. * * **WARNING** Code Handlers aren't [teleported](teleporter), * therefore it can't be used in remote rendering. * * @example 10 * @example '4px' * @example 'true' * @example '=frameCount' * * If `valueFormat='%dpx'` * @example 4 */ valueStart?: PropValueStartHandler; /** * Defines the end numerical value into the * Animation Pipeline (easing->oscillator->path|valueText->valueFormat). * Easing interpolates from `valueStart` to `value`. * * - For pixels, use a numerical value. * - Use textual properties, usually don't need to define this value since * the default is 1. * - To have a value relative to the starting value (valueStart or computed value), * use '+value' or '-value'. * - It supports expressions and Code Handlers. * * **WARNING** Code Handlers aren't [teleported](teleporter), * therefore it can't be used in remote rendering. * * @default 1 * @example '+10' * @example 100 */ value?: PropValueHandler; /** * This event is fired before modifying an element property during rending. * Use if you need to handle virtual elements. * or if you want to manually set an element value. * If returns `false`, ABeamer won't set the element property. * * **WARNING** Events aren't [teleported](teleporter), * therefore it can't be used in remote rendering. */ onSetValue?(value: AnimPropValue, args?: ABeamerArgs): boolean; /** * Formats the value using the sprintf rules. * This is the last node in the computation pipeline. * It can format numerical values returned by the easing->oscillator, * but also each value of a path and a value returning from `valueText`. * * @example '%dpx %dpx 8px white' * @example 'rotateX(%fdeg)' * @example 'rotateX(%fdeg)' */ valueFormat?: string; /** * Provides a list of textual values, expression or function to be interpolated. * This value is computed after easing, oscillator and path interpolators and round function. * Mutual exclusive with pixels, multi-dimension paths and booleans. * * Used by textual properties such as `color`, `url`, `font-family` and `text`. */ valueText?: string[] | ExprString | ValueTextFunc; /** * **EXPERIMENTAL** Waits for the adapter to be ready to deliver an asset before * instructing the render to move to the next frame or give the server order to store the image. * Used to wait for loading images or sync with videos. * * This feature is not implemented yet..._Coming soon_ . * * @see gallery/animate-video-sync */ waitFor?: WaitForList; /** * Round function to apply after easing->oscillator->path. * If this value is not set, for pixels properties the round function will be used, * for other properties there is no default round function. */ roundFunc?: RoundFuncName; /** * Defines how many times the animation repeats itself. * Same as CSS `animation-iteration-count`. * * @see gallery/animate-loop * * @example 1 (to run twice) * @example 3 (to run 4 times) */ iterationCount?: int; /** * Defines the direction of each iteration. * Same as CSS `animation-direction`. * * @example 'alternate' * @example ABeamer.DI_ALTERNATE * @example ABeamer.DS_NORMAL */ direction?: uint | string; /** * Defines how the frames should be bypassed in case of a flush or another * forward motion outside the rendering process. * * @default BP_FIRST_INSIDE */ bypassForwardMode?: BypassMode; /** * Defines how the frames should be bypassed in case of a flush or another * backward motion outside the rendering process. * In a backward motion the first stage it's end point of animation. * * @default BP_FIRST_INSIDE */ bypassBackwardMode?: BypassMode; } /** * Definition of the animation to be sent to the render pipeline. * Used by `Scene.addAnimations`. */ export interface Animation extends AnimationCommonParams { /** * Tasks allow to build complex animations and * to avoid executing javascript code. * * @see tasks */ tasks?: Task[]; /** * css selector, JQuery, html elements, virtual selector or meta-selectors * that defines the list of elements. * If `strictMode` is `false`, the empty selectors will be gracefully bypassed. * * This field can be empty only if there is a setup task. */ selector?: ElSelectorHandler; /** * List of properties per animation. * * @see AnimationProp */ props?: AnimationProp[]; } export type Animations = Animation[]; // ------------------------------------------------------------------------ // Story // ------------------------------------------------------------------------ export type DoneFunc = () => void; export type WaitFunc = (args: ABeamerArgs, params: AnyParams, onDone: DoneFunc) => void; export interface WaitMan { addWaitFunc(func: WaitFunc, params: AnyParams): void; } export type DirectionInt = -1 | 1; export type LogType = 0 | 1 | 2; /** Scene by Object, index or name */ export type SceneHandler = Scene | uint | string; export interface StoryConfig { config: { abeamer: any; }; } export interface StoryMetadata { version?: string; author?: string; email?: string; copyrights?: string; categories?: string[]; keywords?: string[]; comments?: string[]; rating?: uint; /** ISO DateTime stamp of the creation time. */ createdDateTime?: string; /** ISO DateTime stamp of the last modified time. */ modifiedDateTime?: string; } /** Parameters passed to the story when it's created */ export interface CreateStoryParams { /** Adds automatically the default scenes. */ dontAddDefaultScenes?: boolean; /** Defines if the story is going to be teleported. */ toTeleport?: boolean; /** * Set this parameter to false, * if you need to inject html/css code into the page before the teleporting * process starts. * @default true */ toStartTeleporting?: boolean; /** * Set this value, if you need use a Virtual Story Adapter inside of the * default DOM Adapter. */ storyAdapter?: SceneAdapter; /** * Defines the log level. Use `LL_VERBOSE` for debugging. * The server can modify this mode. * Set this parameter to log during the constructor phase, * otherwise is also possible to set later via `story.logLevel`. */ logLevel?: uint; } /** * ABeamer still has to render all the previous frames * of active scene bypassing the middle frames, * but it won't be render to disk and it will bypass any unnecessary frames. */ export interface RenderFrameOptions { /** * First render frame. * If `startScene` isn't defined it will be relative to the story, otherwise is * relative to the `startScene`. * * @default 0 */ renderPos?: TimeHandler; /** * Total number of frames to render. * * **EXPERIMENTAL** Use a negative value to render backwards. * For backward rendering, ABeamer first has to consume all the frames forward, * bypassing all middle frames, only after can render backwards. * * @default the total number of frames */ renderCount?: TimeHandler; /** * First scene to be rendered. * Before start rendering the `startScene`, first, * ABeamer first has to consume all the frames until it reaches the * beginning of Scene. * Accepts by 'Scene Zero-Based Index', 'Name' or by 'Scene Object' */ startScene?: SceneHandler; /** * Last scene to be rendered. * Accepts by 'Scene Zero-Based Index', 'Name' or by 'Scene Object'. */ endScene?: SceneHandler; } export function createStory(fps?: uint, createParams?: CreateStoryParams): Story; export function createStoryFromConfig( cfgUrl: string, callback: (story: Story) => void, fps?: uint, createParams?: CreateStoryParams): void; // ------------------------------------------------------------------------ // Text Tasks // ------------------------------------------------------------------------ export type TextTaskName = /** @see #TextSplitTaskParams */ | 'text-split' /** @see #TypewriterTaskParams */ | 'typewriter' /** @see #DecipherTaskParams */ | 'decipher' ; export type TextTaskParams = | TextSplitTaskParams | TypewriterTaskParams | DecipherTaskParams ; export interface TextSplitTaskParams extends AnyParams { text?: string; splitBy?: | 'char' | 'word' ; /** * If realign is true, it sets the left property of each new element * in a way that are align side by side. * * Use it if the element position is absolute. * * Main purpose is to use with transformations. * * Valid only for DOM elements. */ realign?: boolean; } export interface TypewriterTaskParams extends TextSplitTaskParams { cursor?: boolean; cursorChar?: string; } /** * List of the directions that instruct how the text can be revealed. */ export enum RevealDir { disabled, toRight, toLeft, toCenter, } export interface DecipherTaskParams extends AnyParams { upperCharRanges?: [number, number][]; lowerCharRanges?: [number, number][]; iterations: uint; revealCharIterations?: uint; revealDirection?: RevealDir | string; text: string; } // ------------------------------------------------------------------------ // Shape Tasks // ------------------------------------------------------------------------ export enum Shapes { rectangle, line, circle, speech, } export type ShapeTaskName = 'shape'; export type ShapeTaskParams = | RectangleShapeTaskParams | LineShapeTaskParams | CircleShapeTaskParams | SpeechShapeTaskParams ; export interface BaseShapeTaskParams extends AnyParams { shape?: Shapes | string; stroke?: string; strokeWidth?: uint | ExprString; fill?: string; } export interface RectangleShapeTaskParams extends BaseShapeTaskParams { width?: uint | ExprString; height?: uint | ExprString; rx?: uint | ExprString; ry?: uint | ExprString; } export interface LineShapeTaskParams extends BaseShapeTaskParams { x?: int | ExprString; y?: int | ExprString; direction?: number | ExprString; length?: number | ExprString; } export interface CircleShapeTaskParams extends BaseShapeTaskParams { radius?: number | ExprString; } export const DEFAULT_SPEECH_START = 10; export const DEFAULT_SPEECH_WIDTH = 10; export const DEFAULT_SPEECH_HEIGHT = 10; export const DEFAULT_SPEECH_SHIFT = 0; export enum SpeechPosition { left, right, } export interface SpeechShapeTaskParams extends RectangleShapeTaskParams { speechPosition?: SpeechPosition | string; speechStart?: uint; speechWidth?: uint; speechHeight?: uint; speechShift?: int; } // ------------------------------------------------------------------------ // Attack Tasks // ------------------------------------------------------------------------ export type AttackTaskName = /** @see #ColorAttackTaskParams */ | 'color-attack' ; export type AttackTaskParams = ColorAttackTaskParams; export interface ColorAttackTaskParams extends AnyParams { /** List of colors to attack the original color. */ attack: string[]; /** * Property Name. * @default: 'color' */ prop?: string; /** * Number of times it will attack the color before returning to the original. * Expressions are supported. */ cycles?: uint | ExprString; /** Color to end the attack. If undefined, it uses the original color. */ endColor?: string; } // ------------------------------------------------------------------------ // Chart Tasks // ------------------------------------------------------------------------ export enum ChartTypes { pie, bar, area, line, marker, mixed, } export type ChartTaskName = 'chart'; export interface ExprSeries { /** * Expression that defines the series. * `v` is the variable that starts in `startValue`, increments `step`. * `n` is the number of points. */ expr: ExprString; /** * Number of points generated by the expr. * If it's undefined, but there is already a previous series it will use * the previous series nrPoints. * @default ChartDefaults.nrPoints */ nrPoints: uint; startValue?: number; step?: number; } export type SeriesData = number[] | ExprSeries; export enum ChartCaptionOrientation { horizontal, vertical, } export enum ChartCaptionPosition { top, bottom, left, right, } export enum ChartCaptionAlignment { left, center, right, } export interface ChartCaptions { fontColor?: string | ExprString; fontFamily?: string | ExprString; fontSize?: uint | ExprString; alignment?: ChartCaptionAlignment | string; position?: ChartCaptionPosition | string; orientation?: ChartCaptionOrientation | string; marginBefore?: uint | ExprString; marginAfter?: uint | ExprString; } export interface ChartLabels extends ChartCaptions { captions?: string[] | ExprString; } export type ChartLabelsX = ChartLabels; export interface ChartLegendMark { width?: uint | ExprString; height?: uint | ExprString; spacing?: uint | ExprString; } export interface ChartLegend extends ChartLabels { mark?: ChartLegendMark; } export interface ChartLabelsY extends ChartLabels { tickCount?: uint; } export enum ChartPointShape { circle, square, diamond, } export interface ChartMarkers { visible?: boolean | boolean[] | boolean[][]; shape?: (ChartPointShape | string) | (ChartPointShape | string)[] | (ChartPointShape | string)[][]; size?: uint | uint[] | uint[][]; color?: string | string[] | string[][]; } export interface ChartLine { visible?: boolean; color?: string | ExprString; width?: number | ExprString; } export interface ChartTitle extends ChartCaptions { caption: string | ExprString; } export interface ChartDefaults { labelsX: ChartLabelsX; labelsY: ChartLabelsY; legend: ChartLegend; title: ChartTitle; fillColors: string; strokeColors: string; strokeWidth: uint; markers: ChartMarkers; barWidth: uint; pointMaxHeight: uint; pointDistance: uint; seriesSpacing: uint; /** Number of Points for ExprSeries */ nrPoints: uint; } /** * Parameters for both [Axis Charts](#AxisChartTaskParams) and [Pie Charts](#PieChartTaskParams). */ export interface BaseChartTaskParams extends AnyParams { /** * Defines the type of chart. * If it's `mixed` it uses [](#chartTypes) */ chartType?: ChartTypes | string; /** * List of series of data points. * Each series much have the same number of data points. */ data: SeriesData[]; /** * Set with a unique virtual selector, to be used another `addAnimations` to animate the chart. * ### Example * ```typescript * scene.addAnimations([{ * selector: 'canvas', * tasks: [{ * handler: 'chart', * params: { * data: [[100, 200, 50, 140, 300]], * pointHeightStart: 0.1, // defined the initial value for the animation point-height property * animeSelector: 'chart-anime-02', // unique animation selector to be used by the animator * } as ABeamer.AxisChartTaskParams, * }], * }]) * .addAnimations([{ * selector: `%chart-anime-02`, // animation selector defined previously, prefixed with '%' * duration: `1s`, * props: [{ * prop: 'point-height', // property which initial value is 0.1 * value: 1, // value at the end of animation * }], * }]); * ``` */ animeSelector?: string; /** * Defines the chart title. * At the moment is only supported horizontal top or bottom titles. */ title?: string | ExprString | ChartTitle; /** * Defines the chart legend. * At the moment is only supported stacked left or right top legend. */ legend?: ChartLegend; // colors /** Interior Color used by `area`, `bar` and `pie` charts. */ fillColors?: string | string[] | string[][]; /** Outline Color used by `area`, `bar` and `pie` charts, and line color for `line` chart. */ strokeColors?: string | string[] | string[][]; strokeWidth?: uint | uint[] | uint[][]; } /** * Parameters used by Pie Charts. * Pie Charts provide the following animators: * - [angle](#PieChartTaskParams.angleStart) with initial value in angleStart. * - [dispersion](#PieChartTaskParams.dispersionStart) with initial value in dispersionStart. */ export interface PieChartTaskParams extends BaseChartTaskParams { /** * Initial angle in radians defining the zero radial line of the chart. * This parameter is animated with property `angle`. */ angleStart?: number | ExprString; /** * Initial dispersion factor defined between 0 and 1. * A dispersion defines the percentage of how much the pie circle will be used. * A value of 1 represents a full circle, and a value of 0.5, represents half circle. * This parameter is animated with property `dispersion`. */ dispersionStart?: number | ExprString; isClockwise?: boolean; } /** * Parameters used by Axis Charts, which are all except [Pie Charts](#PieChartTaskParams). * Axis Charts provide the following animators: * - [point-height](#AxisChartTaskParams.pointHeightStart) with initial value in pointHeightStart. * - [deviation](#AxisChartTaskParams.deviationStart) with initial value in deviationStart. * - [sweep](#AxisChartTaskParams.sweepStart) with initial value in sweepStart. */ export interface AxisChartTaskParams extends BaseChartTaskParams { /** * Chart Type per series. Use only if [](#chartType) is `mixed`. * @example: [ABeamer.ChartTypes.bar, ABeamer.ChartTypes.bar, ABeamer.ChartTypes.line] */ chartTypes?: (ChartTypes | string)[]; /** * Defines the X labels with complete information or just as an [](#ExprString). * If it's a ExprString, it will create one label for each point. * The iterator variable is `v`. * If it's an array, it must match the number of points in a series. * @example =2012 + v * @example { captions: ['A', 'B', 'C', 'D'] } */ labelsX?: ChartLabelsX | ExprString | string[]; /** * Defines the Y labels with complete information or just as an [](#ExprString). * If it's a ExprString, it will create one label for each point. * The iterator variable is `v`. * If it's an array, it must match the tickCount. * @example =v/1000 + 'k' * @example { captions: ['10', '20', '30', '40'] } */ labelsY?: ChartLabelsY | ExprString | string[]; // markers markers?: ChartMarkers; /** * x bar length for `bar` charts. * If it's zero, it's calculated automatically in order to fill the complete x-space. */ barWidth?: uint | ExprString; // points pointMaxHeight?: uint | ExprString; /** * x distance between two data points. * If it's zero, it's calculated automatically in order to fill the complete x-space. * If the chart includes bars charts it must be big enough to include all the bars. */ pointDistance?: uint | ExprString; /** * x space between two bars. Used only in `bar` charts. */ seriesSpacing?: uint | ExprString; // colors /** * Colors to be used in case of the data point is negative. * At the moment, it only supports `bar` charts. */ negativeFillColors?: string | string[] | string[][]; xAxis?: ChartLine; yAxis?: ChartLine; y0Line?: ChartLine; // limits maxValue?: number | ExprString; minValue?: number | ExprString; // animation pointHeightStart?: number | ExprString; deviationStart?: number | ExprString; sweepStart?: number | ExprString; } }
the_stack
export class CSSFormatter { private ch: any; private pos: number = -1; private source_text: string; private whiteRe: RegExp = /^\s+$/; // tokenizer // printer private indentSize: any; private indentString: string; private singleIndent: string; private indentLevel = 0; private nestedLevel = 0; private output: string[] = []; private print: string[] = []; // https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule private cssBeautifyNestedAtRule = { "@page": true, "@font-face": true, "@keyframes": true, // also in cssBeautifyConditionalGroupRule below "@media": true, "@supports": true, "@document": true }; private cssBeautifyConditionalGroupRule = { "@media": true, "@supports": true, "@document": true }; private next(): string { this.ch = this.source_text.charAt(++this.pos); return this.ch; } private peek(): string { return this.source_text.charAt(this.pos + 1); } private eatString(endChar: string): string { let start: number = this.pos; while (this.next()) { if (this.ch === "\\") { this.next(); this.next(); } else if (this.ch === endChar) { break; } else if (this.ch === "\n") { break; } } return this.source_text.substring(start, this.pos + 1); } private eatWhitespace(): boolean { let start = this.pos; while (this.whiteRe.test(this.peek())) { this.pos++; } return this.pos !== start; } private skipWhitespace(): boolean { let start = this.pos; do { } while (this.whiteRe.test(this.next())); return this.pos !== start + 1; } private eatComment(singleLine): string { let start = this.pos; this.next(); while (this.next()) { if (this.ch === "*" && this.peek() === "/") { this.pos++; break; } else if (singleLine && this.ch === "\n") { break; } } return this.source_text.substring(start, this.pos + 1); } private lookBack(str): boolean { return this.source_text.substring(this.pos - str.length, this.pos).toLowerCase() === str; } private isCommentOnLine(): boolean { let endOfLine = this.source_text.indexOf('\n', this.pos); if (endOfLine === -1) { return false; } let restOfLine = this.source_text.substring(this.pos, endOfLine); return restOfLine.indexOf('//') !== -1; } private indent(): void { this.indentLevel++; this.indentString += this.singleIndent; } private outdent(): void { this.indentLevel--; this.indentString = this.indentString.slice(0, -this.indentSize); } private lastCharWhitespace(): boolean { return this.whiteRe.test(this.output[this.output.length - 1]); } private newLine(keepWhitespace): void { if (!keepWhitespace) { while (this.lastCharWhitespace()) { this.output.pop(); } } if (this.output.length) { this.output.push('\n'); } if (this.indentString) { this.output.push(this.indentString); } } private singleSpace(): void { if (this.output.length && !this.lastCharWhitespace()) { this.output.push(' '); } } public css_beautify(sourceText: string, options: any): string { options = options || {}; this.source_text = sourceText; let indentSize: any = options.indent_size || 4; let indentCharacter: any = options.indent_char || ' '; let selectorSeparatorNewline: any = (options.selector_separator_newline === undefined) ? true : options.selector_separator_newline; let endWithNewline: any = (options.end_with_newline === undefined) ? false : options.end_with_newline; // compatibility if (typeof indentSize === "string") { indentSize = parseInt(indentSize, 10); } this.indentString = sourceText.match(/^[\r\n]*[\t ]*/)[0]; this.singleIndent = new Array(indentSize + 1).join(indentCharacter); this.print["{"] = (chOpenBrace: string): void => { this.singleSpace(); this.output.push(chOpenBrace); this.newLine(false); }; this.print["}"] = (chCloseBrace: string): void => { this.newLine(false); this.output.push(chCloseBrace); this.newLine(false); }; if (this.indentString) { this.output.push(this.indentString); } let insideRule = false; let enteringConditionalGroup = false; while (true) { let isAfterSpace = this.skipWhitespace(); if (!this.ch) { break; } else if (this.ch === '/' && this.peek() === '*') { /* css comment */ this.newLine(false); this.output.push(this.eatComment(true), "\n", this.indentString); let header = this.lookBack(""); if (header) { this.newLine(false); } } else if (this.ch === '/' && this.peek() === '/') { // single line comment this.output.push(this.eatComment(true), this.indentString); } else if (this.ch === '@') { // strip trailing space, if present, for hash property checks let atRule = this.eatString(" ").replace(/ $/, ''); // pass along the space we found as a separate item this.output.push(atRule, this.ch); // might be a nesting at-rule if (atRule in this.cssBeautifyNestedAtRule) { this.nestedLevel += 1; if (atRule in this.cssBeautifyConditionalGroupRule) { enteringConditionalGroup = true; } } } else if (this.ch === '{') { this.eatWhitespace(); if (this.peek() === '}') { this.next(); this.output.push(" {}"); } else { this.indent(); this.print["{"](this.ch); // when entering conditional groups, only rulesets are allowed if (enteringConditionalGroup) { enteringConditionalGroup = false; insideRule = (this.indentLevel > this.nestedLevel); } else { // otherwise, declarations are also allowed insideRule = (this.indentLevel >= this.nestedLevel); } } } else if (this.ch === '}') { this.outdent(); this.print["}"](this.ch); insideRule = false; if (this.nestedLevel) { this.nestedLevel--; } } else if (this.ch === ":") { this.eatWhitespace(); if (insideRule || enteringConditionalGroup) { // 'property: value' delimiter // which could be in a conditional group query this.output.push(this.ch, " "); } else { if (this.peek() === ":") { // pseudo-element this.next(); this.output.push("::"); } else { // pseudo-class this.output.push(this.ch); } } } else if (this.ch === '"' || this.ch === '\'') { this.output.push(this.eatString(this.ch)); } else if (this.ch === ';') { if (this.isCommentOnLine()) { let beforeComment = this.eatString('/'); let comment = this.eatComment(true); this.output.push(beforeComment, comment.substring(1, comment.length - 1), '\n', this.indentString); } else { this.output.push(this.ch, '\n', this.indentString); } } else if (this.ch === '(') { // may be a url if (this.lookBack("url")) { this.output.push(this.ch); this.eatWhitespace(); if (this.next()) { if (this.ch !== ')' && this.ch !== '"' && this.ch !== '\'') { this.output.push(this.eatString(')')); } else { this.pos--; } } } else { if (isAfterSpace) { this.singleSpace(); } this.output.push(this.ch); this.eatWhitespace(); } } else if (this.ch === ')') { this.output.push(this.ch); } else if (this.ch === ',') { this.eatWhitespace(); this.output.push(this.ch); if (!insideRule && selectorSeparatorNewline) { this.newLine(false); } else { this.singleSpace(); } } else if (this.ch === ']') { this.output.push(this.ch); } else if (this.ch === '[' || this.ch === '=') { // no whitespace before or after this.eatWhitespace(); this.output.push(this.ch); } else { if (isAfterSpace) { this.singleSpace(); } this.output.push(this.ch); } } let sweetCode = this.output.join('').replace(/[\n ]+$/, ''); // establish end_with_newline let should = endWithNewline; let actually = /\n$/.test(sweetCode); if (should && !actually) { sweetCode += "\n"; } else if (!should && actually) { sweetCode = sweetCode.slice(0, -1); } return sweetCode; } }
the_stack
import * as _ from 'lodash'; import {Component, ElementRef, HostListener, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {StringUtil} from '@common/util/string.util'; import {CommonUtil} from '@common/util/common.util'; import {EventBroadcaster} from '@common/event/event.broadcaster'; import {AbstractComponent} from '@common/component/abstract.component'; import {DerivationRule, Field, FieldFormat, FieldRole, IngestionRule, LogicalType} from '@domain/datasource/datasource'; import {Type} from '../../../../shared/datasource-metadata/domain/type'; import {DataStorageConstant} from '../../../constant/data-storage-constant'; import {ColumnSelectBoxComponent} from '../../../data-source-list/component/column-select-box.component'; import {StorageFilterSelectBoxComponent} from '../../../data-source-list/component/storage-filter-select-box.component'; @Component({ selector: 'schema-configure-create-field', templateUrl: 'schema-configure-create-field.component.html' }) export class SchemaConfigureCreateFieldComponent extends AbstractComponent implements OnInit, OnDestroy { @ViewChild('typeSelectBox') private readonly _typeSelectBox: StorageFilterSelectBoxComponent; @ViewChild('latitudeSelectBox') private readonly _latitudeSelectBox: ColumnSelectBoxComponent; @ViewChild('longitudeSelectBox') private readonly _longitudeSelectBox: ColumnSelectBoxComponent; private _originFieldList: Field[]; public readonly typeList = [ { label: this.translateService.instant('msg.storage.ui.list.geo.point'), icon: 'ddp-icon-type-point', value: Type.Logical.GEO_POINT }, // {label: this.translateService.instant('msg.storage.ui.list.geo.line'), icon: 'ddp-icon-type-line', value: Type.Logical.GEO_LINE}, // {label: this.translateService.instant('msg.storage.ui.list.geo.polygon'), icon: 'ddp-icon-type-polygon', value: Type.Logical.GEO_POLYGON}, { label: this.translateService.instant('msg.storage.ui.list.expression'), icon: 'ddp-icon-type-expression', value: Type.Logical.USER_DEFINED } ]; public selectedType = { label: this.translateService.instant('msg.storage.ui.list.geo.point'), icon: 'ddp-icon-type-point', value: Type.Logical.GEO_POINT }; // field list public latitudeFieldList: Field[]; public longitudeFieldList: Field[]; // selected field public selectedLatitudeField: Field; public selectedLongitudeField: Field; // name public fieldName: string; // expression public expression: string; // valid public isInvalidLatitudeField: boolean; public isInvalidLongitudeField: boolean; public isInvalidFieldName: boolean; public isInvalidExpression: boolean; // valid message public invalidFieldNameMessage: string; public invalidExpressionMessage: string; // flag public isShowCreateField: boolean; // constructor constructor(private broadCaster: EventBroadcaster, protected element: ElementRef, protected injector: Injector) { super(element, injector); } ngOnInit() { super.ngOnInit(); // add subscription this.subscriptions.push( this.broadCaster.on(DataStorageConstant.Datasource.BroadcastKey.DATASOURCE_CHANGED_FIELD_LIST).subscribe((fieldList) => { // change field list this.changeFieldList(fieldList); }) ); } ngOnDestroy() { super.ngOnDestroy(); } /** * Window resize * @param _event */ @HostListener('window:resize', ['$event']) public onResize(_event) { // #1925 if (this._typeSelectBox && this._typeSelectBox.isListShow) { this._typeSelectBox.isListShow = false; } else if (this._latitudeSelectBox && this._latitudeSelectBox.isListShow) { this._latitudeSelectBox.isListShow = false; } else if (this._longitudeSelectBox && this._longitudeSelectBox.isListShow) { this._longitudeSelectBox.isListShow = false; } } /** * Change field list * @param fieldList */ public changeFieldList(fieldList): void { // set origin field list (except created field) this._originFieldList = this._cloneValue(fieldList).filter(field => !Field.isCreatedField(field)); // if empty selected latitude field if (this._isEmptyValue(this.selectedLatitudeField)) { // set longitude field list this.longitudeFieldList = this._cloneValue(this._originFieldList.filter(field => !Field.isRemovedField(field) && !Field.isCreatedField(field))); } else { // if not empty selected latitude field this.selectedLatitudeField = this._originFieldList.find(field => field.originalName === this.selectedLatitudeField.originalName); // set longitude field list this._changeLongitudeFieldListExceptField(this.selectedLatitudeField); // if removed field if (Field.isRemovedField(this.selectedLatitudeField)) { this.selectedLatitudeField = undefined; } } // if empty selected longitude field if (this._isEmptyValue(this.selectedLongitudeField)) { // set latitude field list this.latitudeFieldList = this._cloneValue(this._originFieldList.filter(field => !Field.isRemovedField(field) && !Field.isCreatedField(field))); } else { // if not empty selected longitude field this.selectedLongitudeField = this._originFieldList.find(field => field.originalName === this.selectedLongitudeField.originalName); // set latitude field list this._changeLatitudeFieldListExceptField(this.selectedLongitudeField); // if removed field if (Field.isRemovedField(this.selectedLongitudeField)) { this.selectedLongitudeField = undefined; } } } /** * Open create field popup */ public openCreateFieldPopup(): void { this.isShowCreateField = true; } /** * Close create field popup */ public closeCreateFieldPopup(): void { // init view this._initView(); this.isShowCreateField = false; } /** * Check valid field name */ public checkValidFieldName(): void { // is empty if (StringUtil.isEmpty(this.fieldName)) { // set invalid message this.invalidFieldNameMessage = this.translateService.instant('msg.storage.ui.required'); // set valid error this.isInvalidFieldName = true; // return return; } // duplicated name if (this._isDuplicatedName()) { // set invalid message this.invalidFieldNameMessage = this.translateService.instant('msg.storage.ui.duplicated'); // set valid error this.isInvalidFieldName = true; // return return; } // set valid error this.isInvalidFieldName = false; } /** * Check valid expression */ public checkValidExpression(): void { // is empty string if (StringUtil.isEmpty(this.expression)) { // set invalid message this.invalidExpressionMessage = this.translateService.instant('msg.storage.ui.required'); // set valid error this.isInvalidExpression = true; // return return; } // set valid this.isInvalidExpression = false; } /** * Check valid GEO field */ public checkValidGeoField(): void { // if empty latitude column if (this._isEmptyValue(this.selectedLatitudeField)) { // set valid error this.isInvalidLatitudeField = true; } // if empty longitude column if (this._isEmptyValue(this.selectedLongitudeField)) { // set valid error this.isInvalidLongitudeField = false; } } /** * Change selected type * @param type */ public changeSelectedType(type): void { this.selectedType = type; } /** * Change selected latitude field * @param field */ public changeSelectedLatitudeField(field): void { // if empty field OR different field if (this._isEmptyValue(this.selectedLatitudeField) || this.selectedLatitudeField.originalName !== field.originalName) { this.selectedLatitudeField = field; // change longitude field list this._changeLongitudeFieldListExceptField(field); // set valid latitude field this.isInvalidLatitudeField = undefined; } } /** * Change selected longitude field * @param field */ public changeSelectedLongitudeField(field): void { // if empty field OR different field if (this._isEmptyValue(this.selectedLongitudeField) || this.selectedLongitudeField.originalName !== field.originalName) { this.selectedLongitudeField = field; // change latitude field list this._changeLatitudeFieldListExceptField(field); // set valid longitude field this.isInvalidLatitudeField = undefined; } } /** * Click create field button */ public onClickCreateField(): void { // if enable create field if (this._isEnableCreateField()) { // create field this._createField(); // close this.closeCreateFieldPopup(); } } /** * Is expression field * @returns {boolean} */ public isExpressionField(): boolean { return this.selectedType.value === Type.Logical.USER_DEFINED; } /** * Is enable crate field * @returns {boolean} * @private */ private _isEnableCreateField(): boolean { // check field name this.checkValidFieldName(); // if expression type if (this.isExpressionField()) { this.checkValidExpression(); return this._isValidFieldName() && this._isValidExpression(); } else { // if GEO types this.checkValidGeoField(); return this._isValidFieldName() && this._isValidLatitudeField() && this._isValidLongitudeField(); } } /** * Is valid field name * @returns {boolean} * @private */ private _isValidFieldName(): boolean { return this.isInvalidFieldName !== true; } /** * Is valid expression * @returns {boolean} * @private */ private _isValidExpression(): boolean { return this.isInvalidExpression !== true; } /** * Is valid latitude field * @returns {boolean} * @private */ private _isValidLatitudeField(): boolean { return this.isInvalidLatitudeField !== true; } /** * Is valid longitude field * @private */ private _isValidLongitudeField(): boolean { return this.isInvalidLongitudeField !== true; } /** * Is duplicated name * @private */ private _isDuplicatedName(): boolean { return this._originFieldList.some(field => field.name === this.fieldName.trim()); } /** * Is empty value * @param value * @returns {boolean} * @private */ private _isEmptyValue(value): boolean { return _.isNil(value); } /** * Clone value * @param value * @private */ private _cloneValue(value) { return _.cloneDeep(value); } /** * Change latitude field list except field * @param field * @private */ private _changeLatitudeFieldListExceptField(field): void { this.latitudeFieldList = this._originFieldList.filter(originField => originField.originalName !== field.originalName); } /** * Change longitude field list except field * @param field * @private */ private _changeLongitudeFieldListExceptField(field): void { this.longitudeFieldList = this._originFieldList.filter(originField => originField.originalName !== field.originalName); } /** * Create field * @private */ private _createField(): void { const field = new Field(); field.removeUIproperties(); field.originalName = CommonUtil.getUUID(); field.name = this.fieldName.trim(); field.derived = true; // TODO 추후 Type.Role.DIMENSION field.role = FieldRole.DIMENSION; field.ingestionRule = new IngestionRule(); field.derivationRule = new DerivationRule(); field.derivationRule.type = this.selectedType.value.toString().toLowerCase(); // if selected type Expression if (this.isExpressionField()) { field.type = Type.Logical.STRING; // TODO 추후 Type.Logical.STRING field.logicalType = LogicalType.STRING; field.derivationRule.expr = this.expression.trim(); } else { field.type = Type.Logical.STRUCT; // TODO 추후 Type.Logical으로 변경시 제거 필요 field.setLogicalType(this.selectedType.value); field.derivationRule.latField = this.selectedLatitudeField.originalName; field.derivationRule.lonField = this.selectedLongitudeField.originalName; field.format = new FieldFormat(); field.format.removeUnixTypeProperties(); field.format.geoCoordinateInitialize(); field.format.type = this.selectedType.value.toString().toLowerCase() } // broadcast to DATASOURCE_CREATED_FIELD this.broadCaster.broadcast(DataStorageConstant.Datasource.BroadcastKey.DATASOURCE_CREATED_FIELD, field); this._originFieldList.push(field); } /** * Init view * @private */ private _initView(): void { // input this.fieldName = undefined; this.expression = undefined; // valid this.isInvalidLatitudeField = undefined; this.isInvalidLongitudeField = undefined; this.isInvalidFieldName = undefined; this.isInvalidExpression = undefined; // selected field this.selectedLatitudeField = undefined; this.selectedLongitudeField = undefined; // init selected type this.selectedType = this.typeList[0]; } }
the_stack
import {Type} from "./type"; import {isType, Symbol, SYMBOL_FLAG_IS_TEMPLATE, SymbolKind} from "./symbol"; import {SourceRange} from "../../utils/log"; import {Scope} from "./scope"; import {addScopeToSymbol, CheckContext, linkSymbolToNode} from "../analyzer/type-checker"; import {assert} from "../../utils/assert"; /** * Author: Nidin Vinayakan */ export enum NodeKind { // Other EXTENDS, FILE, GLOBAL, IMPLEMENTS, PARAMETER, PARAMETERS, VARIABLE, IMPORT, IMPORT_FROM, // Statements BLOCK, BREAK, MODULE, IMPORTS, CLASS, CONSTANTS, CONTINUE, EMPTY, ENUM, EXPRESSIONS, EXPRESSION, FUNCTION, IF, RETURN, UNSAFE, JAVASCRIPT, START, VARIABLES, WHILE, FOR, // Expressions ALIGN_OF, BOOLEAN, CALL, CAST, DOT, HOOK, INDEX, POINTER_INDEX, ANY, INT32, INT64, FLOAT32, FLOAT64, ARRAY, GENERIC, NAME, NEW, DELETE, NULL, UNDEFINED, PARSE_ERROR, SIZE_OF, STRING, THIS, TYPE, // Unary expressions ADDRESS_OF, COMPLEMENT, DEREFERENCE, NEGATIVE, NOT, POINTER_TYPE, POSITIVE, POSTFIX_DECREMENT, POSTFIX_INCREMENT, PREFIX_DECREMENT, PREFIX_INCREMENT, // Binary expressions ADD, ASSIGN, BITWISE_AND, BITWISE_OR, BITWISE_XOR, DIVIDE, EQUAL, EXPONENT, GREATER_THAN, GREATER_THAN_EQUAL, LESS_THAN, LESS_THAN_EQUAL, LOGICAL_AND, LOGICAL_OR, MULTIPLY, NOT_EQUAL, REMAINDER, SHIFT_LEFT, SHIFT_RIGHT, SUBTRACT, //JavaScript JS_NUMBER, JS_OBJECT, JS_STRING, JS_ARRAY } export function isUnary(kind: NodeKind): boolean { return kind >= NodeKind.ADDRESS_OF && kind <= NodeKind.PREFIX_INCREMENT; } export function isUnaryPostfix(kind: NodeKind): boolean { return kind >= NodeKind.POSTFIX_DECREMENT && kind <= NodeKind.POSTFIX_INCREMENT; } export function isBinary(kind: NodeKind): boolean { return kind >= NodeKind.ADD && kind <= NodeKind.SUBTRACT; } export function invertedBinaryKind(kind: NodeKind): NodeKind { if (kind == NodeKind.EQUAL) return NodeKind.NOT_EQUAL; if (kind == NodeKind.NOT_EQUAL) return NodeKind.EQUAL; if (kind == NodeKind.GREATER_THAN) return NodeKind.LESS_THAN_EQUAL; if (kind == NodeKind.GREATER_THAN_EQUAL) return NodeKind.LESS_THAN; if (kind == NodeKind.LESS_THAN) return NodeKind.GREATER_THAN_EQUAL; if (kind == NodeKind.LESS_THAN_EQUAL) return NodeKind.GREATER_THAN; return kind; } export function isExpression(node: Node): boolean { return node.kind >= NodeKind.ALIGN_OF && node.kind <= NodeKind.SUBTRACT; } export function isCompactNodeKind(kind: NodeKind): boolean { return kind == NodeKind.CONSTANTS || kind == NodeKind.EXPRESSION || kind == NodeKind.VARIABLES; } export const NODE_FLAG_DECLARE = 1 << 0; export const NODE_FLAG_EXPORT = 1 << 1; export const NODE_FLAG_IMPORT = 1 << 2; export const NODE_FLAG_LIBRARY = 1 << 3; export const NODE_FLAG_GET = 1 << 4; export const NODE_FLAG_OPERATOR = 1 << 5; export const NODE_FLAG_POSITIVE = 1 << 6; export const NODE_FLAG_PRIVATE = 1 << 7; export const NODE_FLAG_PROTECTED = 1 << 8; export const NODE_FLAG_PUBLIC = 1 << 9; export const NODE_FLAG_SET = 1 << 10; export const NODE_FLAG_STATIC = 1 << 11; export const NODE_FLAG_UNSAFE = 1 << 12; export const NODE_FLAG_JAVASCRIPT = 1 << 13; export const NODE_FLAG_UNSIGNED_OPERATOR = 1 << 14; export const NODE_FLAG_VIRTUAL = 1 << 15; export const NODE_FLAG_START = 1 << 16; export const NODE_FLAG_ANYFUNC = 1 << 17; export const NODE_FLAG_GENERIC = 1 << 18; export class NodeFlag { flag: int32; range: SourceRange; next: NodeFlag; } export function appendFlag(first: NodeFlag, flag: int32, range: SourceRange): NodeFlag { let link = new NodeFlag(); link.flag = flag; link.range = range; // Is the list empty? if (first == null) { return link; } // Append the flag to the end of the list let secondToLast = first; while (secondToLast.next != null) { secondToLast = secondToLast.next; } secondToLast.next = link; return first; } export function allFlags(link: NodeFlag): int32 { let all = 0; while (link != null) { all = all | link.flag; link = link.next; } return all; } export function rangeForFlag(link: NodeFlag, flag: int32): SourceRange { while (link != null) { if (link.flag == flag) { return link.range; } link = link.next; } return null; } export class Node { kind: NodeKind; flags: int32; firstFlag: NodeFlag; range: SourceRange; internalRange: SourceRange; parent: Node; firstChild: Node; lastChild: Node; previousSibling: Node; nextSibling: Node; resolvedType: Type; symbol: Symbol; scope: Scope; offset: int32; returnNode: Node; constructorFunctionNode: Node; derivedNodes: Node[]; private _rawValue: any; private _hasValue: boolean; private _hasStringValue: boolean; get hasValue(): boolean { return this._hasValue; } get rawValue(): any { if (this._hasStringValue) { return `"${this._rawValue}"`; } else { return this._rawValue; } } get __internal_rawValue(): any { return this._rawValue; } set rawValue(newValue: any) { this._hasValue = true; this._rawValue = newValue; } get intValue(): int32 { let n = this._rawValue; if (Number(n) === n && n % 1 === 0) { return this._rawValue; } return null; } set intValue(newValue: int32) { this._hasValue = true; this._rawValue = newValue; } get longValue(): int64 { //TODO: Implement Int64 return this._rawValue; } set longValue(newValue: int64) { //TODO: Implement Int64 this._hasValue = true; this._rawValue = newValue; } get floatValue(): float32 { return this._rawValue; } set floatValue(newValue: float32) { this._hasValue = true; this._rawValue = newValue; } get doubleValue(): float64 { return this._rawValue; } set doubleValue(newValue: float64) { this._hasValue = true; this._rawValue = newValue; } get stringValue(): string { return this._rawValue; } set stringValue(newValue: string) { this._hasValue = true; this._hasStringValue = true; this._rawValue = newValue; } get referenceValue(): string { return this._rawValue; } set referenceValue(newValue: string) { this._hasValue = true; this._rawValue = newValue; } becomeTypeOf(node: Node, context: CheckContext): void { switch (node.resolvedType) { case context.int64Type: if (this.kind != NodeKind.NAME) { this.kind = NodeKind.INT64; } this.resolvedType = context.int64Type; break; case context.float64Type: if (this.kind != NodeKind.NAME) { this.kind = NodeKind.FLOAT64; } this.resolvedType = context.float64Type; break; } if (node.flags) { this.flags = node.flags; } } becomeValueTypeOf(symbol: Symbol, context: CheckContext): void { // let resolvedSymbol = symbol.resolvedType.pointerTo ? symbol.resolvedType.pointerTo.symbol : symbol.resolvedType.symbol; let resolvedSymbol = symbol.resolvedType.symbol; if (resolvedSymbol) { switch (symbol.resolvedType) { case context.int64Type: this.resolvedType = context.int64Type; if (this.kind == NodeKind.NULL) { this.longValue = 0; } if (this.kind != NodeKind.NAME) { this.kind = NodeKind.INT64; } break; case context.float64Type: this.resolvedType = context.float64Type; if (this.kind == NodeKind.NULL) { this.doubleValue = 0.0; } if (this.kind != NodeKind.NAME) { this.kind = NodeKind.FLOAT64; } break; } } } clone(): Node { let node: Node = new Node(); node.kind = this.kind; if (this.offset !== undefined) node.offset = this.offset; if (this.flags !== undefined) node.flags = this.flags; if (this.firstFlag !== undefined) node.firstFlag = this.firstFlag; // if(this.constructorFunctionNode) node.constructorFunctionNode = this.constructorFunctionNode; if (this.range !== undefined) node.range = this.range; if (this.internalRange !== undefined) node.internalRange = this.internalRange; if (this.hasValue) node.rawValue = this.__internal_rawValue; return node; } becomeSymbolReference(symbol: Symbol): void { this.kind = NodeKind.NAME; this.symbol = symbol; this.referenceValue = symbol.name; this.resolvedType = symbol.resolvedType; this.removeChildren(); } becomeIntegerConstant(value: int32): void { this.kind = NodeKind.INT32; this.symbol = null; this.intValue = value; this.removeChildren(); } becomeLongConstant(value: int64): void { this.kind = NodeKind.INT64; this.symbol = null; this.longValue = value; this.removeChildren(); } becomeFloatConstant(value: float32): void { this.kind = NodeKind.FLOAT32; this.symbol = null; this.floatValue = value; this.removeChildren(); } becomeDoubleConstant(value: float64): void { this.kind = NodeKind.FLOAT64; this.symbol = null; this.doubleValue = value; this.removeChildren(); } becomeBooleanConstant(value: boolean): void { this.kind = NodeKind.BOOLEAN; this.symbol = null; this.intValue = value ? 1 : 0; this.removeChildren(); } isNegativeInteger(): boolean { return this.kind == NodeKind.INT32 && this.intValue < 0; } isNonNegativeInteger(): boolean { return this.kind == NodeKind.INT32 && this.intValue >= 0; } isDeclare(): boolean { return (this.flags & NODE_FLAG_DECLARE) != 0; } isLibrary(): boolean { return (this.flags & NODE_FLAG_LIBRARY) != 0; } isVirtual(): boolean { return (this.flags & NODE_FLAG_VIRTUAL) != 0; } isExport(): boolean { return (this.flags & NODE_FLAG_EXPORT) != 0; } isImport(): boolean { return (this.flags & NODE_FLAG_IMPORT) != 0; } isExternalImport(): boolean { return this.isDeclare() && !this.isLibrary(); } isStart(): boolean { return (this.flags & NODE_FLAG_START) != 0; } isJavaScript(): boolean { return (this.flags & NODE_FLAG_JAVASCRIPT) != 0; } isStatic(): boolean { return (this.flags & NODE_FLAG_STATIC) != 0; } isAnyfunc(): boolean { return (this.flags & NODE_FLAG_ANYFUNC) != 0; } isDeclareOrJavaScript(): boolean { return (this.flags & (NODE_FLAG_DECLARE | NODE_FLAG_JAVASCRIPT)) != 0; } isDeclareOrExport(): boolean { return (this.flags & (NODE_FLAG_DECLARE | NODE_FLAG_EXPORT)) != 0; } isGet(): boolean { return (this.flags & NODE_FLAG_GET) != 0; } isSet(): boolean { return (this.flags & NODE_FLAG_SET) != 0; } isOperator(): boolean { return (this.flags & NODE_FLAG_OPERATOR) != 0; } isPositive(): boolean { return (this.flags & NODE_FLAG_POSITIVE) != 0; } isPrivate(): boolean { return (this.flags & NODE_FLAG_PRIVATE) != 0; } isUnsafe(): boolean { return (this.flags & NODE_FLAG_UNSAFE) != 0; } isGeneric(): boolean { return (this.flags & NODE_FLAG_GENERIC) != 0; } isTemplate(): boolean { return this.symbol && (this.symbol.flags & SYMBOL_FLAG_IS_TEMPLATE) != 0; } isUnsignedOperator(): boolean { return (this.flags & NODE_FLAG_UNSIGNED_OPERATOR) != 0; } childCount(): int32 { let count = 0; let child = this.firstChild; while (child != null) { count = count + 1; child = child.nextSibling; } return count; } parameterCount(): int32 { let count = 0; let child = this.firstChild; if (child.kind == NodeKind.PARAMETERS) { child = child.firstChild; while (child != null) { count = count + 1; child = child.nextSibling; } } return count; } hasParameters(): boolean { if (this.firstChild) { let child = this.firstChild; if (child.kind == NodeKind.PARAMETERS) { return child.childCount() > 0; } } return false; } createEmptyConstructor(): Node { let node = createFunction("constructor"); node.appendChild(createName(this.symbol.name)); let body = createBlock(); node.appendChild(body); let variablesNode = createVariables(); variablesNode.appendChild(createVariable("this", createType(this.resolvedType), null)); body.appendChild(variablesNode); let returnNode: Node = createReturn(createName("this")); body.appendChild(returnNode); // let symbol = new Symbol(); // symbol.kind = SymbolKind.FUNCTION_INSTANCE; // symbol.name = node.stringValue; // symbol.rename = "_ctr"; // addScopeToSymbol(symbol, this.scope); // linkSymbolToNode(symbol, node); return node; } firstInstanceFunction(): Node { let child = this.firstChild; while (child !== undefined) { if (child.kind == NodeKind.FUNCTION) { return child; } child = child.nextSibling; } return null; } appendChild(child: Node): void { child.parent = this; if (this.firstChild == null) { this.firstChild = child; this.firstChild.offset = 0; } else { child.previousSibling = this.lastChild; this.lastChild.nextSibling = child; child.offset = this.lastChild.offset + 1; } this.lastChild = child; } insertChildBefore(after: Node, before: Node): void { if (before == null) { return; } assert(before != after); assert(before.parent == null); assert(before.previousSibling == null); assert(before.nextSibling == null); assert(after == null || after.parent == this); if (after == null) { this.appendChild(before); return; } before.parent = this; before.previousSibling = after.previousSibling; before.nextSibling = after; if (after.previousSibling != null) { assert(after == after.previousSibling.nextSibling); after.previousSibling.nextSibling = before; } else { assert(after == this.firstChild); this.firstChild = before; } after.previousSibling = before; } insertChildAfter(before: Node, after: Node): void { if (after == null) { return; } assert(before != after); assert(after.parent == null); assert(after.previousSibling == null); assert(after.nextSibling == null); assert(before == null || before.parent == this); if (before == null) { this.appendChild(after); return; } after.parent = this; after.previousSibling = before; after.nextSibling = before.nextSibling; if (before.nextSibling != null) { assert(before == before.nextSibling.previousSibling); before.nextSibling.previousSibling = after; } before.nextSibling = after; } remove(): Node { assert(this.parent != null); if (this.previousSibling != null) { assert(this.previousSibling.nextSibling == this); this.previousSibling.nextSibling = this.nextSibling; } else { assert(this.parent.firstChild == this); this.parent.firstChild = this.nextSibling; } if (this.nextSibling != null) { assert(this.nextSibling.previousSibling == this); this.nextSibling.previousSibling = this.previousSibling; } else { assert(this.parent.lastChild == this); this.parent.lastChild = this.previousSibling; } this.parent = null; this.previousSibling = null; this.nextSibling = null; return this; } removeChildren(): void { while (this.lastChild != null) { this.lastChild.remove(); } } replaceWith(node: Node): void { assert(node != this); assert(this.parent != null); assert(node.parent == null); assert(node.previousSibling == null); assert(node.nextSibling == null); node.parent = this.parent; node.previousSibling = this.previousSibling; node.nextSibling = this.nextSibling; if (this.previousSibling != null) { assert(this.previousSibling.nextSibling == this); this.previousSibling.nextSibling = node; } else { assert(this.parent.firstChild == this); this.parent.firstChild = node; } if (this.nextSibling != null) { assert(this.nextSibling.previousSibling == this); this.nextSibling.previousSibling = node; } else { assert(this.parent.lastChild == this); this.parent.lastChild = node; } this.parent = null; this.previousSibling = null; this.nextSibling = null; } isType(): boolean { return this.kind == NodeKind.TYPE || this.kind == NodeKind.POINTER_TYPE || this.symbol != null && isType(this.symbol.kind); } isCallValue(): boolean { return this.parent.kind == NodeKind.CALL && this == this.parent.callValue(); } isAssignTarget(): boolean { return this.parent.kind == NodeKind.ASSIGN && this == this.parent.binaryLeft(); } withRange(range: SourceRange): Node { this.range = range; return this; } withInternalRange(range: SourceRange): Node { this.internalRange = range; return this; } functionFirstArgument(): Node { assert(this.kind == NodeKind.FUNCTION); assert(this.childCount() >= 2); let child = this.firstChild; if (child.kind == NodeKind.PARAMETERS) { child = child.nextSibling; } return child; } functionLastArgument(): Node { assert(this.kind == NodeKind.FUNCTION); assert(this.childCount() >= 2); let child = this.firstChild; if (child.kind == NodeKind.PARAMETERS) { child = child.nextSibling; } let lastArgument: Node = null; while (child != null) { let nextChild = child.nextSibling; if (nextChild.kind !== NodeKind.VARIABLE) { lastArgument = child; child = null; } else { child = nextChild; } } return lastArgument; } functionFirstArgumentIgnoringThis(): Node { assert(this.kind == NodeKind.FUNCTION); assert(this.childCount() >= 2); assert(this.symbol != null); let child = this.functionFirstArgument(); if (this.symbol.kind == SymbolKind.FUNCTION_INSTANCE) { child = child.nextSibling; } return child; } functionReturnType(): Node { assert(this.kind == NodeKind.FUNCTION); assert(this.childCount() >= 2); assert(isExpression(this.lastChild.previousSibling)); return this.lastChild.previousSibling; } constructorNode(): Node { assert(this.kind == NodeKind.NEW); assert(this.childCount() > 0); assert(this.resolvedType.symbol.node.kind == NodeKind.CLASS); return this.resolvedType.symbol.node.constructorFunctionNode; } functionBody(): Node { assert(this.kind == NodeKind.FUNCTION); assert(this.childCount() >= 2); assert(this.lastChild.kind == NodeKind.BLOCK || this.lastChild.kind == NodeKind.EMPTY); let body = this.lastChild; return body.kind == NodeKind.BLOCK ? body : null; } newType(): Node { assert(this.kind == NodeKind.NEW); assert(this.childCount() >= 1); assert(isExpression(this.firstChild)); return this.firstChild; } deleteType(): Node { assert(this.kind == NodeKind.DELETE); assert(this.childCount() >= 1); assert(isExpression(this.firstChild)); return this.firstChild; } callValue(): Node { assert(this.kind == NodeKind.CALL); assert(this.childCount() >= 1); assert(isExpression(this.firstChild)); return this.firstChild; } castValue(): Node { assert(this.kind == NodeKind.CAST); assert(this.childCount() == 2); assert(isExpression(this.firstChild)); return this.firstChild; } castType(): Node { assert(this.kind == NodeKind.CAST); assert(this.childCount() == 2); assert(isExpression(this.lastChild)); return this.lastChild; } alignOfType(): Node { assert(this.kind == NodeKind.ALIGN_OF); assert(this.childCount() == 1); assert(isExpression(this.firstChild)); return this.firstChild; } sizeOfType(): Node { assert(this.kind == NodeKind.SIZE_OF); assert(this.childCount() == 1); assert(isExpression(this.firstChild)); return this.firstChild; } dotTarget(): Node { assert(this.kind == NodeKind.DOT); assert(this.childCount() == 1); assert(isExpression(this.firstChild)); return this.firstChild; } returnValue(): Node { assert(this.kind == NodeKind.RETURN); assert(this.childCount() <= 1); assert(this.firstChild == null || isExpression(this.firstChild)); return this.firstChild; } ifReturnNode(): Node { assert(this.kind == NodeKind.IF); assert(this.firstChild !== null); assert(this.firstChild.nextSibling !== null); return this.firstChild.nextSibling.returnNode || null; } deleteValue(): Node { assert(this.kind == NodeKind.DELETE); assert(this.childCount() <= 1); assert(this.firstChild == null || isExpression(this.firstChild)); return this.firstChild; } extendsType(): Node { assert(this.kind == NodeKind.EXTENDS); assert(this.childCount() == 1); assert(isExpression(this.firstChild)); return this.firstChild; } firstGenericType(): Node { assert(this.firstChild.kind == NodeKind.PARAMETERS); assert(this.firstChild.childCount() > 0); return this.firstChild.firstChild; } variableType(): Node { assert(this.kind == NodeKind.VARIABLE); assert(this.childCount() <= 2); assert(isExpression(this.firstChild) || this.firstChild.kind == NodeKind.EMPTY); let type = this.firstChild; return type.kind != NodeKind.EMPTY ? type : null; } variableValue(): Node { assert(this.kind == NodeKind.VARIABLE); assert(this.childCount() <= 2); assert(this.firstChild.nextSibling == null || isExpression(this.firstChild.nextSibling)); return this.firstChild.nextSibling; } hasVariableValue(): boolean { assert(this.kind == NodeKind.VARIABLE); return this.firstChild != undefined && this.firstChild.nextSibling != undefined; } expressionValue(): Node { assert(this.kind == NodeKind.EXPRESSION); assert(this.childCount() == 1); assert(isExpression(this.firstChild)); return this.firstChild; } binaryLeft(): Node { assert(isBinary(this.kind)); assert(this.childCount() == 2); assert(isExpression(this.firstChild)); return this.firstChild; } binaryRight(): Node { assert(isBinary(this.kind)); assert(this.childCount() == 2); assert(isExpression(this.lastChild)); return this.lastChild; } unaryValue(): Node { assert(isUnary(this.kind)); assert(this.childCount() == 1); assert(isExpression(this.firstChild)); return this.firstChild; } pointer(): Node { assert(this.kind == NodeKind.POINTER_INDEX); assert(this.childCount() >= 1); assert(isExpression(this.firstChild)); return this.firstChild; } pointerOffset(): int32 { assert(this.firstChild); assert(this.firstChild.nextSibling); return this.firstChild.nextSibling.intValue; } forInitializationStatement(): Node { assert(this.kind == NodeKind.FOR); assert(this.childCount() == 4); return this.firstChild; } forTerminationStatement(): Node { assert(this.kind == NodeKind.FOR); assert(this.childCount() == 4); return this.firstChild.nextSibling.expressionValue(); } forUpdateStatements(): Node { assert(this.kind == NodeKind.FOR); assert(this.childCount() == 4); return this.firstChild.nextSibling.nextSibling; } forBody(): Node { assert(this.kind == NodeKind.FOR); assert(this.childCount() == 4); assert(this.lastChild.kind == NodeKind.BLOCK); return this.lastChild; } whileValue(): Node { assert(this.kind == NodeKind.WHILE); assert(this.childCount() == 2); assert(isExpression(this.firstChild)); return this.firstChild; } whileBody(): Node { assert(this.kind == NodeKind.WHILE); assert(this.childCount() == 2); assert(this.lastChild.kind == NodeKind.BLOCK); return this.lastChild; } hookValue(): Node { assert(this.kind == NodeKind.HOOK); assert(this.childCount() == 3); assert(isExpression(this.firstChild)); return this.firstChild; } hookTrue(): Node { assert(this.kind == NodeKind.HOOK); assert(this.childCount() == 3); assert(isExpression(this.firstChild.nextSibling)); return this.firstChild.nextSibling; } hookFalse(): Node { assert(this.kind == NodeKind.HOOK); assert(this.childCount() == 3); assert(isExpression(this.lastChild)); return this.lastChild; } indexTarget(): Node { assert(this.kind == NodeKind.INDEX); assert(this.childCount() >= 1); assert(isExpression(this.firstChild)); return this.firstChild; } ifValue(): Node { assert(this.kind == NodeKind.IF); assert(this.childCount() == 2 || this.childCount() == 3); assert(isExpression(this.firstChild)); return this.firstChild; } ifTrue(): Node { assert(this.kind == NodeKind.IF); assert(this.childCount() == 2 || this.childCount() == 3); assert(this.firstChild.nextSibling.kind == NodeKind.BLOCK); return this.firstChild.nextSibling; } ifFalse(): Node { assert(this.kind == NodeKind.IF); assert(this.childCount() == 2 || this.childCount() == 3); assert(this.firstChild.nextSibling.nextSibling == null || this.firstChild.nextSibling.nextSibling.kind == NodeKind.BLOCK); return this.firstChild.nextSibling.nextSibling || null; } expandCallIntoOperatorTree(): boolean { if (this.kind != NodeKind.CALL) { return false; } let value = this.callValue(); let symbol = value.symbol; if (value.kind == NodeKind.DOT && symbol.node.isOperator() && symbol.node.isDeclare()) { let binaryKind = NodeKind.NULL; if (symbol.name == "%") binaryKind = NodeKind.REMAINDER; else if (symbol.name == "&") binaryKind = NodeKind.BITWISE_AND; else if (symbol.name == "*") binaryKind = NodeKind.MULTIPLY; else if (symbol.name == "**") binaryKind = NodeKind.EXPONENT; else if (symbol.name == "/") binaryKind = NodeKind.DIVIDE; else if (symbol.name == "<") binaryKind = NodeKind.LESS_THAN; else if (symbol.name == "<<") binaryKind = NodeKind.SHIFT_LEFT; else if (symbol.name == "==") binaryKind = NodeKind.EQUAL; else if (symbol.name == ">") binaryKind = NodeKind.GREATER_THAN; else if (symbol.name == ">>") binaryKind = NodeKind.SHIFT_RIGHT; else if (symbol.name == "[]") binaryKind = NodeKind.INDEX; else if (symbol.name == "^") binaryKind = NodeKind.BITWISE_XOR; else if (symbol.name == "|") binaryKind = NodeKind.BITWISE_OR; if (binaryKind != NodeKind.NULL) { this.kind = binaryKind; value.remove(); this.insertChildBefore(this.firstChild, value.dotTarget().remove()); return true; } else if (symbol.name == "[]=") { this.kind = NodeKind.ASSIGN; let target = createIndex(value.remove().dotTarget().remove()); target.appendChild(this.firstChild.remove()); this.insertChildBefore(this.firstChild, target); return true; } } return false; } arrayLength(): Node { assert(this.kind == NodeKind.NEW); assert(this.childCount() >= 1); assert(isExpression(this.firstChild)); assert(this.firstChild.resolvedType.isArray()); return this.firstChild.nextSibling; } } export function createNew(type: Node): Node { assert(isExpression(type)); let node = new Node(); node.kind = NodeKind.NEW; node.appendChild(type); return node; } export function createDelete(value: Node): Node { assert(value == null || isExpression(value)); let node = new Node(); node.kind = NodeKind.DELETE; if (value != null) { node.appendChild(value); } return node; } export function createHook(test: Node, primary: Node, secondary: Node): Node { assert(isExpression(test)); assert(isExpression(primary)); assert(isExpression(secondary)); let node = new Node(); node.kind = NodeKind.HOOK; node.appendChild(test); node.appendChild(primary); node.appendChild(secondary); return node; } export function createIndex(target: Node): Node { assert(isExpression(target)); let node = new Node(); node.kind = NodeKind.INDEX; node.appendChild(target); return node; } export function createNull(): Node { let node = new Node(); node.kind = NodeKind.NULL; return node; } export function createUndefined(): Node { let node = new Node(); node.kind = NodeKind.UNDEFINED; return node; } export function createThis(): Node { let node = new Node(); node.kind = NodeKind.THIS; return node; } export function createAddressOf(value: Node): Node { assert(isExpression(value)); let node = new Node(); node.kind = NodeKind.ADDRESS_OF; node.appendChild(value); return node; } export function createDereference(value: Node): Node { assert(isExpression(value)); let node = new Node(); node.kind = NodeKind.DEREFERENCE; node.appendChild(value); return node; } export function createAlignOf(type: Node): Node { assert(isExpression(type)); let node = new Node(); node.kind = NodeKind.ALIGN_OF; node.appendChild(type); return node; } export function createSizeOf(type: Node): Node { assert(isExpression(type)); let node = new Node(); node.kind = NodeKind.SIZE_OF; node.appendChild(type); return node; } export function createboolean(value: boolean): Node { let node = new Node(); node.kind = NodeKind.BOOLEAN; node.intValue = value ? 1 : 0; return node; } export function createInt(value: int32): Node { let node = new Node(); node.kind = NodeKind.INT32; node.intValue = value; return node; } export function createLong(value: int64): Node { let node = new Node(); node.kind = NodeKind.INT64; node.longValue = value; return node; } export function createFloat(value: float32): Node { let node = new Node(); node.kind = NodeKind.FLOAT32; node.floatValue = value; return node; } export function createDouble(value: float64): Node { let node = new Node(); node.kind = NodeKind.FLOAT64; node.doubleValue = value; return node; } export function createString(value: string): Node { let node = new Node(); node.kind = NodeKind.STRING; node.stringValue = value; return node; } export function createArray(type: Type): Node { let node = new Node(); node.kind = NodeKind.ARRAY; node.resolvedType = type; return node; } export function createName(value: string): Node { let node = new Node(); node.kind = NodeKind.NAME; node.referenceValue = value; return node; } export function createType(type: Type): Node { assert(type != null); let node = new Node(); node.kind = NodeKind.TYPE; node.resolvedType = type; return node; } export function createAny(): Node { let node = new Node(); node.kind = NodeKind.ANY; return node; } export function createEmpty(): Node { let node = new Node(); node.kind = NodeKind.EMPTY; return node; } export function createExpression(value: Node): Node { assert(isExpression(value)); let node = new Node(); node.kind = NodeKind.EXPRESSION; node.appendChild(value); return node; } export function createBlock(): Node { let node = new Node(); node.kind = NodeKind.BLOCK; return node; } export function createModule(name: string): Node { let node = new Node(); node.kind = NodeKind.MODULE; node.stringValue = name; return node; } export function createClass(name: string): Node { let node = new Node(); node.kind = NodeKind.CLASS; node.stringValue = name; return node; } export function createEnum(name: string): Node { let node = new Node(); node.kind = NodeKind.ENUM; node.stringValue = name; return node; } export function createIf(value: Node, trueBranch: Node, falseBranch: Node): Node { assert(isExpression(value)); assert(trueBranch.kind == NodeKind.BLOCK); assert(falseBranch == null || falseBranch.kind == NodeKind.BLOCK); let node = new Node(); node.kind = NodeKind.IF; node.appendChild(value); node.appendChild(trueBranch); if (falseBranch != null) { node.appendChild(falseBranch); } return node; } export function createWhile(value: Node, body: Node): Node { assert(isExpression(value)); assert(body.kind == NodeKind.BLOCK); let node = new Node(); node.kind = NodeKind.WHILE; node.appendChild(value); node.appendChild(body); return node; } export function createFor(initializationStmt: Node, terminationStmt: Node, updateStmt: Node, body: Node): Node { // assert(isExpression(initializationStmt)); // assert(isExpression(terminationStmt)); // assert(isExpression(updateStmt)); assert(body.kind == NodeKind.BLOCK); let node = new Node(); node.kind = NodeKind.FOR; node.appendChild(initializationStmt); node.appendChild(terminationStmt); node.appendChild(updateStmt); node.appendChild(body); return node; } export function createReturn(value: Node): Node { assert(value == null || isExpression(value)); let node = new Node(); node.kind = NodeKind.RETURN; if (value != null) { node.appendChild(value); } return node; } export function createImports(): Node { let node = new Node(); node.kind = NodeKind.IMPORTS; return node; } export function createImport(name: string): Node { let node = new Node(); node.kind = NodeKind.IMPORT; node.stringValue = name; return node; } export function createImportFrom(name: string): Node { let node = new Node(); node.kind = NodeKind.IMPORT_FROM; node.stringValue = name; return node; } export function createVariables(): Node { let node = new Node(); node.kind = NodeKind.VARIABLES; return node; } export function createConstants(): Node { let node = new Node(); node.kind = NodeKind.CONSTANTS; return node; } export function createParameters(): Node { let node = new Node(); node.kind = NodeKind.PARAMETERS; return node; } export function createExtends(type: Node): Node { assert(isExpression(type)); let node = new Node(); node.kind = NodeKind.EXTENDS; node.appendChild(type); return node; } export function createImplements(): Node { let node = new Node(); node.kind = NodeKind.IMPLEMENTS; return node; } export function createParameter(name: string): Node { let node = new Node(); node.kind = NodeKind.PARAMETER; node.stringValue = name; return node; } export function createVariable(name: string, type: Node, value: Node): Node { assert(type == null || isExpression(type)); assert(value == null || isExpression(value)); let node = new Node(); node.kind = NodeKind.VARIABLE; node.stringValue = name; node.appendChild(type != null ? type : createEmpty()); if (value != null) { node.appendChild(value); } return node; } export function createFunction(name: string): Node { let node = new Node(); node.kind = NodeKind.FUNCTION; node.stringValue = name; return node; } export function createUnary(kind: NodeKind, value: Node): Node { assert(isUnary(kind)); assert(isExpression(value)); let node = new Node(); node.kind = kind; node.appendChild(value); return node; } export function createBinary(kind: NodeKind, left: Node, right: Node): Node { assert(isBinary(kind)); assert(isExpression(left)); assert(isExpression(right)); let node = new Node(); node.kind = kind; node.appendChild(left); node.appendChild(right); return node; } export function createCall(value: Node): Node { assert(isExpression(value)); let node = new Node(); node.kind = NodeKind.CALL; node.appendChild(value); return node; } export function createCast(value: Node, type: Node): Node { assert(isExpression(value)); assert(isExpression(type)); let node = new Node(); node.kind = NodeKind.CAST; node.appendChild(value); node.appendChild(type); return node; } export function createDot(value: Node, name: string): Node { assert(isExpression(value)); let node = new Node(); node.kind = NodeKind.DOT; node.stringValue = name; node.appendChild(value); return node; } export function createSymbolReference(symbol: Symbol): Node { let node = createName(symbol.name); node.symbol = symbol; node.resolvedType = symbol.resolvedType; return node; } export function createMemberReference(value: Node, symbol: Symbol): Node { let node = createDot(value, symbol.name); node.symbol = symbol; node.resolvedType = symbol.resolvedType; return node; } export function createParseError(): Node { let node = new Node(); node.kind = NodeKind.PARSE_ERROR; return node; } //JavaScript export function createJSNumber(): Node { let node = new Node(); node.kind = NodeKind.JS_NUMBER; return node; } export function createJSObject(): Node { let node = new Node(); node.kind = NodeKind.JS_OBJECT; return node; } export function createJSString(): Node { let node = new Node(); node.kind = NodeKind.JS_STRING; return node; } export function createJSArray(): Node { let node = new Node(); node.kind = NodeKind.JS_ARRAY; return node; }
the_stack
import { Array } from "@siteimprove/alfa-array"; import { Callback } from "@siteimprove/alfa-callback"; import { Collection } from "@siteimprove/alfa-collection"; import { Comparable, Comparer, Comparison } from "@siteimprove/alfa-comparable"; import { Hash } from "@siteimprove/alfa-hash"; import { Iterable } from "@siteimprove/alfa-iterable"; import { Serializable } from "@siteimprove/alfa-json"; import { Map } from "@siteimprove/alfa-map"; import { Mapper } from "@siteimprove/alfa-mapper"; import { None, Option } from "@siteimprove/alfa-option"; import { Predicate } from "@siteimprove/alfa-predicate"; import { Reducer } from "@siteimprove/alfa-reducer"; import { Refinement } from "@siteimprove/alfa-refinement"; import { Set } from "@siteimprove/alfa-set"; import { Branch, Empty, Leaf, Node } from "./node"; const { not } = Predicate; const { compareComparable } = Comparable; /** * @public */ export class List<T> implements Collection.Indexed<T> { public static of<T>(...values: Array<T>): List<T> { const size = values.length; // Fast path: The values fit within the tail. if (size <= Node.Capacity) { return new List(Empty, Leaf.of(values), 0, size); } return values.reduce((list, value) => list._push(value), List.empty<T>()); } private static _empty = new List<never>(Empty, Empty, 0, 0); public static empty<T = never>(): List<T> { return this._empty; } private readonly _head: Empty | Leaf<T> | Branch<T>; private readonly _tail: Empty | Leaf<T>; private readonly _shift: number; private readonly _size: number; private constructor( head: Empty | Leaf<T> | Branch<T>, tail: Empty | Leaf<T>, shift: number, size: number ) { this._head = head; this._tail = tail; this._shift = shift; this._size = size; } public get size(): number { return this._size; } public isEmpty(): this is List<never> { return this._tail.isEmpty(); } public forEach(callback: Callback<T, void, [index: number]>): void { Iterable.forEach(this, callback); } public map<U>(mapper: Mapper<T, U, [index: number]>): List<U> { let index = 0; const tail = (this._tail as Node<T>).map((value) => mapper(value, index++)); const head = (this._head as Node<T>).map((value) => mapper(value, index++)); return new List( head as Empty | Leaf<U> | Branch<U>, tail as Empty | Leaf<U>, this._shift, this._size ); } public apply<U>(mapper: List<Mapper<T, U>>): List<U> { return mapper.flatMap((mapper) => this.map(mapper)); } public flatMap<U>(mapper: Mapper<T, List<U>, [index: number]>): List<U> { return this.reduce( (list, value, index) => list.concat(mapper(value, index)), List.empty<U>() ); } public flatten<T>(this: List<List<T>>): List<T> { return this.flatMap((list) => list); } public reduce<U>(reducer: Reducer<T, U, [index: number]>, accumulator: U): U { return Iterable.reduce(this, reducer, accumulator); } public reduceWhile<U>( predicate: Predicate<T, [index: number]>, reducer: Reducer<T, U, [index: number]>, accumulator: U ): U { return Iterable.reduceWhile(this, predicate, reducer, accumulator); } public reduceUntil<U>( predicate: Predicate<T, [index: number]>, reducer: Reducer<T, U, [index: number]>, accumulator: U ): U { return Iterable.reduceUntil(this, predicate, reducer, accumulator); } public filter<U extends T>( refinement: Refinement<T, U, [index: number]> ): List<U>; public filter(predicate: Predicate<T, [index: number]>): List<T>; public filter(predicate: Predicate<T, [index: number]>): List<T> { return List.from(Iterable.filter(this, predicate)); } public reject<U extends T>( refinement: Refinement<T, U, [index: number]> ): List<Exclude<T, U>>; public reject(predicate: Predicate<T, [index: number]>): List<T>; public reject(predicate: Predicate<T, [index: number]>): List<T> { return this.filter(not(predicate)); } public find<U extends T>( refinement: Refinement<T, U, [index: number]> ): Option<U>; public find(predicate: Predicate<T, [index: number]>): Option<T>; public find(predicate: Predicate<T, [index: number]>): Option<T> { return Iterable.find(this, predicate); } public includes(value: T): boolean { return Iterable.includes(this, value); } public collect<U>(mapper: Mapper<T, Option<U>, [index: number]>): List<U> { return List.from(Iterable.collect(this, mapper)); } public collectFirst<U>( mapper: Mapper<T, Option<U>, [index: number]> ): Option<U> { return Iterable.collectFirst(this, mapper); } public some(predicate: Predicate<T, [index: number]>): boolean { return Iterable.some(this, predicate); } public none(predicate: Predicate<T, [index: number]>): boolean { return Iterable.none(this, predicate); } public every(predicate: Predicate<T, [index: number]>): boolean { return Iterable.every(this, predicate); } public count(predicate: Predicate<T, [index: number]>): number { return Iterable.count(this, predicate); } public distinct(): List<T> { let seen = Set.empty<T>(); let list = List.empty<T>(); for (const value of this) { if (seen.has(value)) { continue; } seen = seen.add(value); list = list.append(value); } return list; } public get(index: number): Option<T> { if (index < 0 || index >= this._size || this._tail.isEmpty()) { return None; } const offset = this._size - this._tail.values.length; let value: Option<T>; if (index < offset) { value = this._head.get(index, this._shift - Node.Bits); } else { value = this._tail.get(index - offset); } return value; } public has(index: number): boolean { return index >= 0 && index < this._size; } public set(index: number, value: T): List<T> { if (index < 0 || index >= this._size || this._tail.isEmpty()) { return this; } const offset = this._size - this._tail.values.length; let head = this._head; let tail = this._tail; if (index < offset) { if (head.isEmpty()) { return this; } head = head.set(index, value, this._shift); if (head === this._head) { return this; } } else { tail = tail.set(index - offset, value); if (tail === this._tail) { return this; } } return new List(head, tail, this._shift, this._size); } public insert(index: number, value: T): List<T> { if (index < 0 || index > this.size) { return this; } if (index === 0) { return this.prepend(value); } if (index === this.size) { return this.append(value); } return List.from( Iterable.concat( Iterable.take(this, index), Iterable.from([value]), Iterable.skip(this, index) ) ); } public append(value: T): List<T> { return this._push(value); } public prepend(value: T): List<T> { return List.of(value).concat(this); } public concat(iterable: Iterable<T>): List<T> { return Iterable.reduce<T, List<T>>( iterable, (list, value) => list._push(value), this ); } public subtract(iterable: Iterable<T>): List<T> { return List.from(Iterable.subtract(this, iterable)); } public intersect(iterable: Iterable<T>): List<T> { return List.from(Iterable.intersect(this, iterable)); } public zip<U>(iterable: Iterable<U>): List<[T, U]> { return List.from(Iterable.zip(this, iterable)); } public first(): Option<T> { return this._tail.isEmpty() ? None : Option.of(this._tail.values[0]); } public last(): Option<T> { return Iterable.last(this); } public take(count: number): List<T> { return List.from(Iterable.take(this, count)); } public takeWhile<U extends T>( refinement: Refinement<T, U, [index: number]> ): List<U>; public takeWhile(predicate: Predicate<T, [index: number]>): List<T>; public takeWhile(predicate: Predicate<T, [index: number]>): List<T> { return List.from(Iterable.takeWhile(this, predicate)); } public takeUntil(predicate: Predicate<T, [index: number]>): List<T> { return this.takeWhile(not(predicate)); } public takeLast(count: number = 1): List<T> { return List.from(Iterable.takeLast(this, count)); } public takeLastWhile<U extends T>( refinement: Refinement<T, U, [index: number]> ): List<U>; public takeLastWhile(predicate: Predicate<T, [index: number]>): List<T>; public takeLastWhile(predicate: Predicate<T, [index: number]>): List<T> { return List.from(Iterable.takeLastWhile(this, predicate)); } public takeLastUntil(predicate: Predicate<T, [index: number]>): List<T> { return this.takeLastWhile(not(predicate)); } public skip(count: number): List<T> { return List.from(Iterable.skip(this, count)); } public skipWhile(predicate: Predicate<T, [index: number]>): List<T> { return List.from(Iterable.skipWhile(this, predicate)); } public skipUntil(predicate: Predicate<T, [index: number]>): List<T> { return this.skipWhile(not(predicate)); } public skipLast(count: number = 1): List<T> { let list: List<T> = this; while (count-- > 0) { list = list._pop(); } return list; } public skipLastWhile(predicate: Predicate<T, [index: number]>): List<T> { return List.from(Iterable.skipLastWhile(this, predicate)); } public skipLastUntil(predicate: Predicate<T, [index: number]>): List<T> { return this.skipLastWhile(not(predicate)); } public trim(predicate: Predicate<T, [index: number]>): List<T> { return this.trimLeading(predicate).trimTrailing(predicate); } public trimLeading(predicate: Predicate<T, [index: number]>): List<T> { return this.skipWhile(predicate); } public trimTrailing(predicate: Predicate<T, [index: number]>): List<T> { return this.skipLastWhile(predicate); } public rest(): List<T> { return this.skip(1); } public slice(start: number, end?: number): List<T> { return List.from(Iterable.slice(this, start, end)); } public reverse(): List<T> { return List.from(Iterable.reverse(this)); } public join(separator: string): string { return Iterable.join(this, separator); } public sort<T extends Comparable<T>>(this: List<T>): List<T> { return this.sortWith(compareComparable); } public sortWith(comparer: Comparer<T>): List<T> { return List.from(Iterable.sortWith(this, comparer)); } public compare<T>( this: List<Comparable<T>>, iterable: Iterable<T> ): Comparison { return this.compareWith(iterable, compareComparable); } public compareWith<U = T>( iterable: Iterable<U>, comparer: Comparer<T, U, [index: number]> ): Comparison { return Iterable.compareWith(this, iterable, comparer); } public groupBy<K>(grouper: Mapper<T, K>): Map<K, List<T>> { return this.reduce((groups, value) => { const group = grouper(value); return groups.set( group, groups .get(group) .getOrElse(() => List.empty<T>()) ._push(value) ); }, Map.empty<K, List<T>>()); } public equals<T>(value: List<T>): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof List && value._size === this._size && value._head.equals(this._head) && value._tail.equals(this._tail) ); } public hash(hash: Hash): void { for (const value of this) { hash.writeUnknown(value); } hash.writeUint32(this._size); } public *[Symbol.iterator](): Iterator<T> { yield* this._head; yield* this._tail; } public toArray(): Array<T> { return [...this]; } public toJSON(): List.JSON<T> { return this.toArray().map((value) => Serializable.toJSON(value)); } public toString(): string { const values = this.join(", "); return `List [${values === "" ? "" : ` ${values} `}]`; } private _push(value: T): List<T> { // If no tail exists yet, this means that the list is empty. We therefore // create a new tail with the pushed value. As the current list is empty, // it won't have a head. As such, there's no need to pass the head along. // // In: List { head: Empty, tail: Empty } // Out: List { head: Empty, tail: Leaf(value) } // if (this._tail.isEmpty()) { return new List(Empty, Leaf.of([value]), 0, 1); } // If the tail has capacity for another value, we concatenate the pushed // value onto the current tail. The current list may or may not have a head, // so we pass the head along as-is. // // In: List { head, tail } // Out: List { head, tail: Leaf(...tail, value) } // if (this._tail.hasCapacity()) { return new List( this._head, Leaf.of([...this._tail.values, value]), this._shift, this._size + 1 ); } // If the tail does not have capacity for another value, we need to add it // to the head to make room for a new tail. If the current list does not // have a head, we use the current tail as the new head and create a new // tail with the pushed value. // // In: List { head: Empty, tail } // Out: List { head: tail, tail: Leaf(value) } // if (this._head.isEmpty()) { return new List( this._tail, Leaf.of([value]), this._shift + Node.Bits, this._size + 1 ); } const index = this._size - Node.Capacity; let head = this._head; let shift = this._shift; // If the head has overflown, we need to split it which in turn increases // the depth of the list. if (head.isLeaf() || index === Node.overflow(shift)) { head = Branch.of([head]); shift += Node.Bits; } else { head = head.clone(); } let prev = head; let level = shift - Node.Bits; // We now add the tail to the head in order to make room for a new tail. while (level > 0) { const i = Node.fragment(index, level); level -= Node.Bits; const next = prev.nodes[i] as Branch<T> | undefined; if (next === undefined) { if (level === 0) { prev.nodes[i] = this._tail; } else { prev.nodes[i] = prev = Branch.empty<T>(); } } else { prev.nodes[i] = prev = next.clone(); } } // With the current tail inserted into the new head, we can now make a new // tail with the pushed value. Do note that the spread syntax is only used // for illustrative purposes here; the tail is actually inserted in the // rightmost branch of the head. // // In: List { head, tail } // Out: List { head: Branch(...head, ...tail), tail: Leaf(value) } // return new List(head, Leaf.of([value]), shift, this._size + 1); } private _pop(): List<T> { // If the list has no tail then it is empty. We therefore return the list // itself as the pop has no effect. if (this._tail.isEmpty()) { return this; } // If the list has a size of 1 then the result of the popping its last // element will be an empty list. // // In: List { head: Empty, tail: Leaf(value) } // Out: List { head: Empty, tail: Empty } // if (this._size === 1) { return List.empty(); } // If the tail has more than one element, it will have a non-zero size after // popping the last element. We can therefore get away with removing the // last element from the tail and reuse the head. // // In: List { head, tail: Leaf(...tail, value) } // Out: List { head, tail } // if (this._tail.values.length > 1) { return new List( this._head, Leaf.of(this._tail.values.slice(0, this._tail.values.length - 1)), this._shift, this._size - 1 ); } if (this._head.isLeaf() || this._head.isEmpty()) { return new List( Empty, this._head, this._shift - Node.Bits, this._size - 1 ); } let head: Leaf<T> | Branch<T> = this._head.clone(); let tail = this._tail; let shift = this._shift; const index = this._size - Node.Capacity - 1; let prev = head; let level = shift - Node.Bits; // We now remove the rightmost leaf of the head as this will be used as the // new tail. while (level > 0) { const fragment = Node.fragment(index, level); level -= Node.Bits; const next = prev.nodes[fragment]; // Once we reach the rightmost leaf node, remove it as it will be used as // the new tail. if (next.isLeaf()) { prev.nodes.pop(); tail = next; } else { prev = prev.nodes[fragment] = next.clone(); } } // If the head has underflown, we unwrap its first child and use that as the // new head which in turn decreases the depth of the list. If the head is a // leaf node, we instead set the new head to null. if (index === Node.underflow(shift)) { head = head.nodes[0]; shift -= Node.Bits; } // With the rightmost branch of the head removed, we can now use it as the // new tail and discard the old. Do note that the spread syntax is only used // for illustrative purposes here; the tail is actually removed from the // rightmost branch of the head. // // In: List { head: Branch(...head, tail), tail: Leaf(value) } // Out: List { head, tail } // return new List(head, tail, shift, this._size - 1); } } /** * @public */ export namespace List { export type JSON<T> = Collection.Indexed.JSON<T>; export function isList<T>(value: Iterable<T>): value is List<T>; export function isList<T>(value: unknown): value is List<T>; export function isList<T>(value: unknown): value is List<T> { return value instanceof List; } export function from<T>(iterable: Iterable<T>): List<T> { if (isList(iterable)) { return iterable; } if (Array.isArray(iterable)) { return fromArray(iterable); } return fromIterable(iterable); } export function fromArray<T>(array: ReadonlyArray<T>): List<T> { const size = array.length; // Fast path: The array fits within the tail. if (size <= Node.Capacity) { return List.of(...array); } return Array.reduce( array, (list, value) => list.append(value), List.empty() ); } export function fromIterable<T>(iterable: Iterable<T>): List<T> { return Iterable.reduce( iterable, (list, value) => list.append(value), List.empty() ); } }
the_stack
import type {Mutable, Proto, ObserverType} from "@swim/util"; import type {FastenerOwner, FastenerFlags} from "../fastener/Fastener"; import type {AnyComponent, Component} from "./Component"; import {ComponentRelationInit, ComponentRelationClass, ComponentRelation} from "./ComponentRelation"; /** @internal */ export type ComponentSetType<F extends ComponentSet<any, any>> = F extends ComponentSet<any, infer C> ? C : never; /** @public */ export interface ComponentSetInit<C extends Component = Component> extends ComponentRelationInit<C> { extends?: {prototype: ComponentSet<any, any>} | string | boolean | null; key?(component: C): string | undefined; compare?(a: C, b: C): number; sorted?: boolean; willSort?(parent: Component | null): void; didSort?(parent: Component | null): void; sortChildren?(parent: Component): void; compareChildren?(a: Component, b: Component): number; } /** @public */ export type ComponentSetDescriptor<O = unknown, C extends Component = Component, I = {}> = ThisType<ComponentSet<O, C> & I> & ComponentSetInit<C> & Partial<I>; /** @public */ export interface ComponentSetClass<F extends ComponentSet<any, any> = ComponentSet<any, any>> extends ComponentRelationClass<F> { /** @internal */ readonly SortedFlag: FastenerFlags; /** @internal @override */ readonly FlagShift: number; /** @internal @override */ readonly FlagMask: FastenerFlags; } /** @public */ export interface ComponentSetFactory<F extends ComponentSet<any, any> = ComponentSet<any, any>> extends ComponentSetClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): ComponentSetFactory<F> & I; define<O, C extends Component = Component>(className: string, descriptor: ComponentSetDescriptor<O, C>): ComponentSetFactory<ComponentSet<any, C>>; define<O, C extends Component = Component>(className: string, descriptor: {observes: boolean} & ComponentSetDescriptor<O, C, ObserverType<C>>): ComponentSetFactory<ComponentSet<any, C>>; define<O, C extends Component = Component, I = {}>(className: string, descriptor: {implements: unknown} & ComponentSetDescriptor<O, C, I>): ComponentSetFactory<ComponentSet<any, C> & I>; define<O, C extends Component = Component, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & ComponentSetDescriptor<O, C, I & ObserverType<C>>): ComponentSetFactory<ComponentSet<any, C> & I>; <O, C extends Component = Component>(descriptor: ComponentSetDescriptor<O, C>): PropertyDecorator; <O, C extends Component = Component>(descriptor: {observes: boolean} & ComponentSetDescriptor<O, C, ObserverType<C>>): PropertyDecorator; <O, C extends Component = Component, I = {}>(descriptor: {implements: unknown} & ComponentSetDescriptor<O, C, I>): PropertyDecorator; <O, C extends Component = Component, I = {}>(descriptor: {implements: unknown; observes: boolean} & ComponentSetDescriptor<O, C, I & ObserverType<C>>): PropertyDecorator; } /** @public */ export interface ComponentSet<O = unknown, C extends Component = Component> extends ComponentRelation<O, C> { (component: AnyComponent<C>): O; /** @override */ get fastenerType(): Proto<ComponentSet<any, any>>; /** @internal */ readonly components: {readonly [componentId: number]: C | undefined}; readonly componentCount: number; hasComponent(component: Component): boolean; addComponent(component?: AnyComponent<C>, target?: Component | null, key?: string): C; attachComponent(component?: AnyComponent<C>, target?: Component | null): C; detachComponent(component: C): C | null; insertComponent(parent?: Component | null, component?: AnyComponent<C>, target?: Component | null, key?: string): C; removeComponent(component: C): C | null; deleteComponent(component: C): C | null; /** @internal @override */ bindComponent(component: Component, target: Component | null): void; /** @internal @override */ unbindComponent(component: Component): void; /** @override */ detectComponent(component: Component): C | null; /** @internal @protected */ key(component: C): string | undefined; get sorted(): boolean; /** @internal */ initSorted(sorted: boolean): void; sort(sorted?: boolean): this; /** @protected */ willSort(parent: Component | null): void; /** @protected */ onSort(parent: Component | null): void; /** @protected */ didSort(parent: Component | null): void; /** @internal @protected */ sortChildren(parent: Component): void; /** @internal */ compareChildren(a: Component, b: Component): number; /** @internal @protected */ compare(a: C, b: C): number; } /** @public */ export const ComponentSet = (function (_super: typeof ComponentRelation) { const ComponentSet: ComponentSetFactory = _super.extend("ComponentSet"); Object.defineProperty(ComponentSet.prototype, "fastenerType", { get: function (this: ComponentSet): Proto<ComponentSet<any, any>> { return ComponentSet; }, configurable: true, }); ComponentSet.prototype.hasComponent = function (this: ComponentSet, component: Component): boolean { return this.components[component.uid] !== void 0; }; ComponentSet.prototype.addComponent = function <C extends Component>(this: ComponentSet<unknown, C>, newComponent?: AnyComponent<C>, target?: Component | null, key?: string): C { if (newComponent !== void 0 && newComponent !== null) { newComponent = this.fromAny(newComponent); } else { newComponent = this.createComponent(); } if (target === void 0) { target = null; } let parent: Component | null; if (this.binds && (parent = this.parentComponent, parent !== null)) { if (key === void 0) { key = this.key(newComponent); } this.insertChild(parent, newComponent, target, key); } const components = this.components as {[comtrollerId: number]: C | undefined}; if (components[newComponent.uid] === void 0) { this.willAttachComponent(newComponent, target); components[newComponent.uid] = newComponent; (this as Mutable<typeof this>).componentCount += 1; this.onAttachComponent(newComponent, target); this.initComponent(newComponent); this.didAttachComponent(newComponent, target); } return newComponent; }; ComponentSet.prototype.attachComponent = function <C extends Component>(this: ComponentSet<unknown, C>, newComponent?: AnyComponent<C>, target?: Component | null): C { if (newComponent !== void 0 && newComponent !== null) { newComponent = this.fromAny(newComponent); } else { newComponent = this.createComponent(); } const components = this.components as {[comtrollerId: number]: C | undefined}; if (components[newComponent.uid] === void 0) { if (target === void 0) { target = null; } this.willAttachComponent(newComponent, target); components[newComponent.uid] = newComponent; (this as Mutable<typeof this>).componentCount += 1; this.onAttachComponent(newComponent, target); this.initComponent(newComponent); this.didAttachComponent(newComponent, target); } return newComponent; }; ComponentSet.prototype.detachComponent = function <C extends Component>(this: ComponentSet<unknown, C>, oldComponent: C): C | null { const components = this.components as {[comtrollerId: number]: C | undefined}; if (components[oldComponent.uid] !== void 0) { this.willDetachComponent(oldComponent); (this as Mutable<typeof this>).componentCount -= 1; delete components[oldComponent.uid]; this.onDetachComponent(oldComponent); this.deinitComponent(oldComponent); this.didDetachComponent(oldComponent); return oldComponent; } return null; }; ComponentSet.prototype.insertComponent = function <C extends Component>(this: ComponentSet<unknown, C>, parent?: Component | null, newComponent?: AnyComponent<C>, target?: Component | null, key?: string): C { if (newComponent !== void 0 && newComponent !== null) { newComponent = this.fromAny(newComponent); } else { newComponent = this.createComponent(); } if (parent === void 0 || parent === null) { parent = this.parentComponent; } if (target === void 0) { target = null; } if (key === void 0) { key = this.key(newComponent); } if (parent !== null && (newComponent.parent !== parent || newComponent.key !== key)) { this.insertChild(parent, newComponent, target, key); } const components = this.components as {[comtrollerId: number]: C | undefined}; if (components[newComponent.uid] === void 0) { this.willAttachComponent(newComponent, target); components[newComponent.uid] = newComponent; (this as Mutable<typeof this>).componentCount += 1; this.onAttachComponent(newComponent, target); this.initComponent(newComponent); this.didAttachComponent(newComponent, target); } return newComponent; }; ComponentSet.prototype.removeComponent = function <C extends Component>(this: ComponentSet<unknown, C>, component: C): C | null { if (this.hasComponent(component)) { component.remove(); return component; } return null; }; ComponentSet.prototype.deleteComponent = function <C extends Component>(this: ComponentSet<unknown, C>, component: C): C | null { const oldComponent = this.detachComponent(component); if (oldComponent !== null) { oldComponent.remove(); } return oldComponent; }; ComponentSet.prototype.bindComponent = function <C extends Component>(this: ComponentSet<unknown, C>, component: Component, target: Component | null): void { if (this.binds) { const newComponent = this.detectComponent(component); const components = this.components as {[comtrollerId: number]: C | undefined}; if (newComponent !== null && components[newComponent.uid] === void 0) { this.willAttachComponent(newComponent, target); components[newComponent.uid] = newComponent; (this as Mutable<typeof this>).componentCount += 1; this.onAttachComponent(newComponent, target); this.initComponent(newComponent); this.didAttachComponent(newComponent, target); } } }; ComponentSet.prototype.unbindComponent = function <C extends Component>(this: ComponentSet<unknown, C>, component: Component): void { if (this.binds) { const oldComponent = this.detectComponent(component); const components = this.components as {[comtrollerId: number]: C | undefined}; if (oldComponent !== null && components[oldComponent.uid] !== void 0) { this.willDetachComponent(oldComponent); (this as Mutable<typeof this>).componentCount -= 1; delete components[oldComponent.uid]; this.onDetachComponent(oldComponent); this.deinitComponent(oldComponent); this.didDetachComponent(oldComponent); } } }; ComponentSet.prototype.detectComponent = function <C extends Component>(this: ComponentSet<unknown, C>, component: Component): C | null { if (typeof this.type === "function" && component instanceof this.type) { return component as C; } return null; }; ComponentSet.prototype.key = function <C extends Component>(this: ComponentSet<unknown, C>, component: C): string | undefined { return void 0; }; Object.defineProperty(ComponentSet.prototype, "sorted", { get(this: ComponentSet): boolean { return (this.flags & ComponentSet.SortedFlag) !== 0; }, configurable: true, }); ComponentSet.prototype.initInherits = function (this: ComponentSet, sorted: boolean): void { if (sorted) { (this as Mutable<typeof this>).flags = this.flags | ComponentSet.SortedFlag; } else { (this as Mutable<typeof this>).flags = this.flags & ~ComponentSet.SortedFlag; } }; ComponentSet.prototype.sort = function (this: ComponentSet, sorted?: boolean): typeof this { if (sorted === void 0) { sorted = true; } const flags = this.flags; if (sorted && (flags & ComponentSet.SortedFlag) === 0) { const parent = this.parentComponent; this.willSort(parent); this.setFlags(flags | ComponentSet.SortedFlag); this.onSort(parent); this.didSort(parent); } else if (!sorted && (flags & ComponentSet.SortedFlag) !== 0) { this.setFlags(flags & ~ComponentSet.SortedFlag); } return this; }; ComponentSet.prototype.willSort = function (this: ComponentSet, parent: Component | null): void { // hook }; ComponentSet.prototype.onSort = function (this: ComponentSet, parent: Component | null): void { if (parent !== null) { this.sortChildren(parent); } }; ComponentSet.prototype.didSort = function (this: ComponentSet, parent: Component | null): void { // hook }; ComponentSet.prototype.sortChildren = function <C extends Component>(this: ComponentSet<unknown, C>, parent: Component): void { parent.sortChildren(this.compareChildren.bind(this)); }; ComponentSet.prototype.compareChildren = function <C extends Component>(this: ComponentSet<unknown, C>, a: Component, b: Component): number { const components = this.components; const x = components[a.uid]; const y = components[b.uid]; if (x !== void 0 && y !== void 0) { return this.compare(x, y); } else { return x !== void 0 ? 1 : y !== void 0 ? -1 : 0; } }; ComponentSet.prototype.compare = function <C extends Component>(this: ComponentSet<unknown, C>, a: C, b: C): number { return a.uid < b.uid ? -1 : a.uid > b.uid ? 1 : 0; }; ComponentSet.construct = function <F extends ComponentSet<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { if (fastener === null) { fastener = function (newComponent: AnyComponent<ComponentSetType<F>>): FastenerOwner<F> { fastener!.addComponent(newComponent); return fastener!.owner; } as F; delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name Object.setPrototypeOf(fastener, fastenerClass.prototype); } fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).components = {}; (fastener as Mutable<typeof fastener>).componentCount = 0; return fastener; }; ComponentSet.define = function <O, C extends Component>(className: string, descriptor: ComponentSetDescriptor<O, C>): ComponentSetFactory<ComponentSet<any, C>> { let superClass = descriptor.extends as ComponentSetFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const sorted = descriptor.sorted; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.sorted; if (superClass === void 0 || superClass === null) { superClass = this; } const fastenerClass = superClass.extend(className, descriptor); fastenerClass.construct = function (fastenerClass: {prototype: ComponentSet<any, any>}, fastener: ComponentSet<O, C> | null, owner: O): ComponentSet<O, C> { fastener = superClass!.construct(fastenerClass, fastener, owner); if (affinity !== void 0) { fastener.initAffinity(affinity); } if (inherits !== void 0) { fastener.initInherits(inherits); } if (sorted !== void 0) { fastener.initSorted(sorted); } return fastener; }; return fastenerClass; }; (ComponentSet as Mutable<typeof ComponentSet>).SortedFlag = 1 << (_super.FlagShift + 0); (ComponentSet as Mutable<typeof ComponentSet>).FlagShift = _super.FlagShift + 1; (ComponentSet as Mutable<typeof ComponentSet>).FlagMask = (1 << ComponentSet.FlagShift) - 1; return ComponentSet; })(ComponentRelation);
the_stack
* @packageDocumentation * @module std */ //================================================================ import { IForwardIterator } from "../iterator/IForwardIterator"; import { IBidirectionalIterator } from "../iterator/IBidirectionalIterator"; import { IRandomAccessIterator } from "../iterator/IRandomAccessIterator"; import { IPointer } from "../functional/IPointer"; import { UnaryPredicator } from "../internal/functional/UnaryPredicator"; import { BinaryPredicator } from "../internal/functional/BinaryPredicator"; import { General } from "../internal/functional/General"; import { Writeonly } from "../internal/functional/Writeonly"; import { equal_to } from "../functional/comparators"; import { randint } from "./random"; import { advance } from "../iterator/global"; type UnaryOperatorInferrer< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<OutputIterator>, OutputIterator>>> = (val: IPointer.ValueType<InputIterator>) => IPointer.ValueType<OutputIterator>; type BinaryOperatorInferrer< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator2>, InputIterator2>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<OutputIterator>, OutputIterator>>> = (x: IPointer.ValueType<InputIterator1>, y: IPointer.ValueType<InputIterator2>) => IPointer.ValueType<OutputIterator>; /* ========================================================= MODIFIERS (MODIFYING SEQUENCE) - FILL - REMOVE - REPLACE & SWAP - RE-ARRANGEMENT ============================================================ FILL --------------------------------------------------------- */ /** * Copy elements in range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param output Output iterator of the first position. * * @return Output Iterator of the last position by advancing. */ export function copy< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator>, OutputIterator>>> (first: InputIterator, last: InputIterator, output: OutputIterator): OutputIterator { for (; !first.equals(last); first = first.next()) { output.value = first.value; output = output.next(); } return output; } /** * Copy *n* elements. * * @param first Input iteartor of the first position. * @param n Number of elements to copy. * @param output Output iterator of the first position. * * @return Output Iterator of the last position by advancing. */ export function copy_n< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator>, OutputIterator>>> (first: InputIterator, n: number, output: OutputIterator): OutputIterator { for (let i: number = 0; i < n; ++i) { output.value = first.value; first = first.next(); output = output.next(); } return output; } /** * Copy specific elements by a condition. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param output Output iterator of the first position. * @param pred A function predicates the specific condition. * * @return Output Iterator of the last position by advancing. */ export function copy_if< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator>, OutputIterator>>> ( first: InputIterator, last: InputIterator, output: OutputIterator, pred: UnaryPredicator<IPointer.ValueType<InputIterator>> ): OutputIterator { for (; !first.equals(last); first = first.next()) { if (!pred(first.value)) continue; output.value = first.value; output = output.next(); } return output; } /** * Copy elements reversely. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param output Output iterator of the first position. * * @return Output Iterator of the last position by advancing. */ export function copy_backward< InputIterator extends Readonly<IBidirectionalIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IBidirectionalIterator<IPointer.ValueType<InputIterator>, OutputIterator>>> ( first: InputIterator, last: InputIterator, output: OutputIterator ): OutputIterator { last = last.prev(); while (!last.equals(first)) { last = last.prev(); output = output.prev(); output.value = last.value; } return output; } /** * Fill range elements * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param val The value to fill. * * @return Output Iterator of the last position by advancing. */ export function fill<ForwardIterator extends Writeonly<IForwardIterator<IPointer.ValueType<ForwardIterator>, ForwardIterator>>> ( first: ForwardIterator, last: ForwardIterator, val: IPointer.ValueType<ForwardIterator> ): void { for (; !first.equals(last); first = first.next()) first.value = val; } /** * Fill *n* elements. * * @param first Input iteartor of the first position. * @param n Number of elements to fill. * @param val The value to fill. * * @return Output Iterator of the last position by advancing. */ export function fill_n<OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<OutputIterator>, OutputIterator>>> ( first: OutputIterator, n: number, val: IPointer.ValueType<OutputIterator> ): OutputIterator { for (let i: number = 0; i < n; ++i) { first.value = val; first = first.next(); } return first; } /** * Transform elements. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param output Output iterator of the first position. * @param op Unary function determines the transform. * * @return Output Iterator of the last position by advancing. */ export function transform< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<OutputIterator>, OutputIterator>>> ( first: InputIterator, last: InputIterator, result: OutputIterator, op: UnaryOperatorInferrer<InputIterator, OutputIterator> ): OutputIterator; /** * Transform elements. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param output Output iterator of the first position. * @param op Binary function determines the transform. * * @return Output Iterator of the last position by advancing. */ export function transform< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator2>, InputIterator2>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<OutputIterator>, OutputIterator>>> ( first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, result: OutputIterator, op: BinaryOperatorInferrer<InputIterator1, InputIterator2, OutputIterator> ): OutputIterator; export function transform(...args: any[]): any { if (args.length === 4) return (_Unary_transform as Function)(...args); else // args: #5 return (_Binary_transform as Function)(...args); } function _Unary_transform< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<OutputIterator>, OutputIterator>>> ( first: InputIterator, last: InputIterator, result: OutputIterator, op: UnaryOperatorInferrer<InputIterator, OutputIterator> ): OutputIterator { for (; !first.equals(last); first = first.next()) { result.value = op(first.value); result = result.next(); } return result; } function _Binary_transform< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator2>, InputIterator2>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<OutputIterator>, OutputIterator>>> ( first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, result: OutputIterator, binary_op: BinaryOperatorInferrer<InputIterator1, InputIterator2, OutputIterator> ): OutputIterator { while (!first1.equals(last1)) { result.value = binary_op(first1.value, first2.value); first1 = first1.next(); first2 = first2.next(); result = result.next(); } return result; } /** * Generate range elements. * * @param first Forward iteartor of the first position. * @param last Forward iterator of the last position. * @param gen The generator function. */ export function generate<ForwardIterator extends Writeonly<IForwardIterator<IPointer.ValueType<ForwardIterator>, ForwardIterator>>> ( first: ForwardIterator, last: ForwardIterator, gen: () => IPointer.ValueType<ForwardIterator> ): void { for (; !first.equals(last); first = first.next()) first.value = gen(); } /** * Generate *n* elements. * * @param first Forward iteartor of the first position. * @param n Number of elements to generate. * @param gen The generator function. * * @return Forward Iterator to the last position by advancing. */ export function generate_n<ForwardIterator extends Writeonly<IForwardIterator<IPointer.ValueType<ForwardIterator>, ForwardIterator>>> ( first: ForwardIterator, n: number, gen: () => IPointer.ValueType<ForwardIterator> ): ForwardIterator { while (n-- > 0) { first.value = gen(); first = first.next(); } return first; } /* --------------------------------------------------------- REMOVE --------------------------------------------------------- */ /** * Test whether elements are unique in sorted range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param pred A binary function predicates two arguments are equal. Default is {@link equal_to}. * * @returns Whether unique or not. */ export function is_unique<InputIterator extends General<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, pred: BinaryPredicator<IPointer.ValueType<InputIterator>> = equal_to ): boolean { if (first.equals(last)) return true; let next: InputIterator = first.next(); for (; !next.equals(last); next = next.next()) { if (pred(first.value, next.value) === true) return false; first = first.next(); } return true; } /** * Remove duplicated elements in sorted range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param pred A binary function predicates two arguments are equal. Default is {@link equal_to}. * * @return Input iterator to the last element not removed. */ export function unique<InputIterator extends General<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, pred: BinaryPredicator<IPointer.ValueType<InputIterator>> = equal_to ): InputIterator { if (first.equals(last)) return last; let ret: InputIterator = first; for (first = first.next(); !first.equals(last); first = first.next()) if (!pred(ret.value, first.value)) { ret = ret.next(); ret.value = first.value; } return ret.next(); } /** * Copy elements in range without duplicates. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param output Output iterator of the last position. * @param pred A binary function predicates two arguments are equal. Default is {@link equal_to}. * * @return Output Iterator of the last position by advancing. */ export function unique_copy< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator>, OutputIterator>>> ( first: InputIterator, last: InputIterator, output: OutputIterator, pred: BinaryPredicator<IPointer.ValueType<InputIterator>> = equal_to ): OutputIterator { if (first.equals(last)) return output; output.value = first.value; first = first.next(); for (; !first.equals(last); first = first.next()) if (!pred(first.value, output.value)) { output = output.next(); output.value = first.value; } return output.next(); } /** * Remove specific value in range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param val The specific value to remove. * * @return Iterator tho the last element not removed. */ export function remove<InputIterator extends General<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, val: IPointer.ValueType<InputIterator> ): InputIterator { return remove_if(first, last, elem => equal_to(elem, val)); } /** * Remove elements in range by a condition. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param pred An unary function predicates remove. * * @return Iterator tho the last element not removed. */ export function remove_if<InputIterator extends General<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, pred: UnaryPredicator<IPointer.ValueType<InputIterator>> ): InputIterator { let ret: InputIterator = first; while (!first.equals(last)) { if (!pred(first.value)) { ret.value = first.value; ret = ret.next(); } first = first.next(); } return ret; } /** * Copy range removing specific value. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param output Output iterator of the last position. * @param val The condition predicates remove. * * @return Output Iterator of the last position by advancing. */ export function remove_copy< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator>, OutputIterator>>> ( first: InputIterator, last: InputIterator, output: OutputIterator, val: IPointer.ValueType<InputIterator> ): OutputIterator { return remove_copy_if(first, last, output, elem => equal_to(elem, val)); } /** * Copy range removing elements by a condition. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param output Output iterator of the last position. * @param pred An unary function predicates remove. * * @return Output Iterator of the last position by advancing. */ export function remove_copy_if< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator>, OutputIterator>>> ( first: InputIterator, last: InputIterator, output: OutputIterator, pred: UnaryPredicator<IPointer.ValueType<InputIterator>> ): OutputIterator { for (; !first.equals(last); first = first.next()) { if (pred(first.value)) continue; output.value = first.value; output = output.next(); } return output; } /* --------------------------------------------------------- REPLACE & SWAP --------------------------------------------------------- */ /** * Replace specific value in range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param old_val Specific value to change * @param new_val Specific value to be changed. */ export function replace<InputIterator extends General<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, old_val: IPointer.ValueType<InputIterator>, new_val: IPointer.ValueType<InputIterator> ): void { return replace_if(first, last, elem => equal_to(elem, old_val), new_val); } /** * Replace specific condition in range. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param pred An unary function predicates the change. * @param new_val Specific value to be changed. */ export function replace_if<InputIterator extends General<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> ( first: InputIterator, last: InputIterator, pred: UnaryPredicator<IPointer.ValueType<InputIterator>>, new_val: IPointer.ValueType<InputIterator> ): void { for (let it = first; !it.equals(last); it = it.next()) if (pred(it.value) === true) it.value = new_val; } /** * Copy range replacing specific value. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param output Output iterator of the first position. * @param old_val Specific value to change * @param new_val Specific value to be changed. * * @return Output Iterator of the last position by advancing. */ export function replace_copy< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator>, OutputIterator>>> ( first: InputIterator, last: InputIterator, output: OutputIterator, old_val: IPointer.ValueType<InputIterator>, new_val: IPointer.ValueType<InputIterator> ): OutputIterator { return replace_copy_if(first, last, output, elem => equal_to(elem, old_val), new_val); } /** * Copy range replacing specfic condition. * * @param first Input iteartor of the first position. * @param last Input iterator of the last position. * @param output Output iterator of the first position. * @param pred An unary function predicates the change. * @param new_val Specific value to be changed. * * @return Output Iterator of the last position by advancing. */ export function replace_copy_if< InputIterator extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator>, OutputIterator>>> ( first: InputIterator, last: InputIterator, result: OutputIterator, pred: UnaryPredicator<IPointer.ValueType<InputIterator>>, new_val: IPointer.ValueType<InputIterator> ): OutputIterator { for (; !first.equals(last); first = first.next()) { if (pred(first.value)) result.value = new_val; else result.value = first.value; result = result.next(); } return result; } /** * Swap values of two iterators. * * @param x Forward iterator to swap its value. * @param y Forward iterator to swap its value. */ export function iter_swap< ForwardIterator1 extends General<IForwardIterator<IPointer.ValueType<ForwardIterator1>, ForwardIterator1>>, ForwardIterator2 extends General<IForwardIterator<IPointer.ValueType<ForwardIterator1>, ForwardIterator2>>> (x: ForwardIterator1, y: ForwardIterator2): void { [x.value, y.value] = [y.value, x.value]; } /** * Swap values of two ranges. * * @param first1 Forward iteartor of the first position of the 1st range. * @param last1 Forward iterator of the last position of the 1st range. * @param first2 Forward iterator of the first position of the 2nd range. * * @return Forward Iterator of the last position of the 2nd range by advancing. */ export function swap_ranges< ForwardIterator1 extends General<IForwardIterator<IPointer.ValueType<ForwardIterator1>, ForwardIterator1>>, ForwardIterator2 extends General<IForwardIterator<IPointer.ValueType<ForwardIterator1>, ForwardIterator2>>> (first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2): ForwardIterator2 { for (; !first1.equals(last1); first1 = first1.next()) { iter_swap(first1, first2); first2 = first2.next(); } return first2; } /* --------------------------------------------------------- RE-ARRANGEMENT --------------------------------------------------------- */ /** * Reverse elements in range. * * @param first Bidirectional iterator of the first position. * @param last Bidirectional iterator of the last position. */ export function reverse<BidirectionalIterator extends General<IBidirectionalIterator<IPointer.ValueType<BidirectionalIterator>, BidirectionalIterator>>> (first: BidirectionalIterator, last: BidirectionalIterator): void { // first !== last && first !== --last while (first.equals(last) === false && first.equals((last = last.prev())) === false) { iter_swap(first, last); first = first.next(); } } /** * Copy reversed elements in range. * * @param first Bidirectional iterator of the first position. * @param last Bidirectional iterator of the last position. * @param output Output iterator of the first position. * * @return Output Iterator of the last position by advancing. */ export function reverse_copy< BidirectionalIterator extends Readonly<IBidirectionalIterator<IPointer.ValueType<BidirectionalIterator>, BidirectionalIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<BidirectionalIterator>, OutputIterator>>> ( first: BidirectionalIterator, last: BidirectionalIterator, output: OutputIterator ): OutputIterator { while (!last.equals(first)) { last = last.prev(); output.value = last.value; output = output.next(); } return output; } export function shift_left<ForwardIterator extends General<IForwardIterator<IPointer.ValueType<ForwardIterator>, ForwardIterator>>> (first: ForwardIterator, last: ForwardIterator, n: number): ForwardIterator { const mid = advance(first, n); return copy(mid, last, first); } export function shift_right<ForwardIterator extends General<IBidirectionalIterator<IPointer.ValueType<ForwardIterator>, ForwardIterator>>> (first: ForwardIterator, last: ForwardIterator, n: number): ForwardIterator { const mid = advance(last, -n); return copy_backward(first, mid, last); } /** * Rotate elements in range. * * @param first Input iteartor of the first position. * @param middle Input iteartor of the initial position of the right side. * @param last Input iteartor of the last position. * * @return Input iterator of the final position in the left side; *middle*. */ export function rotate<InputIterator extends General<IForwardIterator<IPointer.ValueType<InputIterator>, InputIterator>>> (first: InputIterator, middle: InputIterator, last: InputIterator): InputIterator { while (!first.equals(middle) && !middle.equals(last)) { iter_swap(first, middle); first = first.next(); middle = middle.next(); } return first; } /** * Copy rotated elements in range. * * @param first Input iteartor of the first position. * @param middle Input iteartor of the initial position of the right side. * @param last Input iteartor of the last position. * @param output Output iterator of the last position. * * @return Output Iterator of the last position by advancing. */ export function rotate_copy< ForwardIterator extends Readonly<IForwardIterator<IPointer.ValueType<ForwardIterator>, ForwardIterator>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<ForwardIterator>, OutputIterator>>> ( first: ForwardIterator, middle: ForwardIterator, last: ForwardIterator, output: OutputIterator ): OutputIterator { output = copy(middle, last, output); return copy(first, middle, output); } /** * Shuffle elements in range. * * @param first Random access iteartor of the first position. * @param last Random access iteartor of the last position. */ export function shuffle<RandomAccessIterator extends General<IRandomAccessIterator<IPointer.ValueType<RandomAccessIterator>, RandomAccessIterator>>> (first: RandomAccessIterator, last: RandomAccessIterator): void { for (let it = first; !it.equals(last); it = it.next()) { const rand_index: number = randint(first.index(), last.index() - 1); if (it.index() !== rand_index) iter_swap(it, first.advance(rand_index)); } }
the_stack
import { Component, IterableDiffers, ElementRef, KeyValueDiffers, ChangeDetectorRef, Input, Renderer2, OnInit } from '@angular/core'; import { IgControlBase } from '../igcontrolbase/igcontrolbase'; @Component({ selector: 'ig-map', template: '<ng-content></ng-content>', inputs: ['widgetId', 'options', 'changeDetectionInterval', 'disabled', 'create', 'width', 'height', 'dataSource', 'dataSourceUrl', 'dataSourceType', 'responseDataKey', 'autoMarginWidth', 'autoMarginHeight', 'crosshairVisibility', 'crosshairPoint', 'plotAreaBackground', 'defaultInteraction', 'dragModifier', 'panModifier', 'previewRect', 'windowRect', 'zoomable', 'windowScale', 'windowResponse', 'windowRectMinWidth', 'windowPositionHorizontal', 'windowPositionVertical', 'circleMarkerTemplate', 'triangleMarkerTemplate', 'pyramidMarkerTemplate', 'squareMarkerTemplate', 'diamondMarkerTemplate', 'pentagonMarkerTemplate', 'hexagonMarkerTemplate', 'tetragramMarkerTemplate', 'pentagramMarkerTemplate', 'hexagramMarkerTemplate', 'overviewPlusDetailPaneBackgroundImageUri', 'useTiledZooming', 'preferHigherResolutionTiles', 'zoomTileCacheSize', 'backgroundContent', 'series', 'theme'], outputs: ['tooltipShowing', 'tooltipShown', 'tooltipHiding', 'tooltipHidden', 'browserNotSupported', 'seriesCursorMouseMove', 'seriesMouseLeftButtonDown', 'seriesMouseLeftButtonUp', 'seriesMouseMove', 'seriesMouseEnter', 'seriesMouseLeave', 'windowRectChanged', 'gridAreaRectChanged', 'refreshCompleted', 'triangulationStatusChanged'] }) export class IgMapComponent extends IgControlBase<IgMap> implements OnInit { constructor(el: ElementRef, renderer: Renderer2, differs: IterableDiffers, kvalDiffers: KeyValueDiffers, cdr: ChangeDetectorRef) { super(el, renderer, differs, kvalDiffers, cdr); } @Input() public set dataSource(value: any) { this._dataSource = value; const map = jQuery(this._el).data(this._widgetName); if (map) { jQuery(this._el)[this._widgetName]('option', 'dataSource', this._dataSource); } } private _dataSource: any; public option(): void { return; } ngOnInit() { if (this._dataSource === null || this._dataSource === undefined) { this._dataSource = this.options.dataSource; } if (!this.options.dataSource && this._dataSource) { this.options.dataSource = this._dataSource; } super.ngOnInit(); } /** * Destroys the widget. */ /* istanbul ignore next */ public destroy(): void { return; } /** * Returns the ID of parent element holding the map. */ /* istanbul ignore next */ public id(): string { return; } /** * Exports the map to a PNG image. * * @param width The width of the image. * @param height The height of the image. */ /* istanbul ignore next */ public exportImage(width?: object, height?: object): object { return; } /** * Notify the map that styles it draws colors from may have been updated. */ /* istanbul ignore next */ public styleUpdated(): object { return; } /** * Resets the zoom level of the map to default. */ /* istanbul ignore next */ public resetZoom(): object { return; } /** * Adds a new item to the data source and notifies the map. * * @param item The item that we want to add to the data source. * @param targetName The name of the series bound to the data source. */ /* istanbul ignore next */ public addItem(item: object, targetName: string): void { return; } /** * Inserts a new item to the data source and notifies the map. * * @param item the new item that we want to insert in the data source. * @param index The index in the data source where the new item will be inserted. * @param targetName The name of the series bound to the data source. */ /* istanbul ignore next */ public insertItem(item: object, index: number, targetName: string): void { return; } /** * Deletes an item from the data source and notifies the map. * * @param index The index in the data source from where the item will be been removed. * @param targetName The name of the series bound to the data source. */ /* istanbul ignore next */ public removeItem(index: number, targetName: string): void { return; } /** * Updates an item in the data source and notifies the map. * * @param index The index of the item in the data source that we want to change. * @param item The new item object that will be set in the data source. * @param targetName The name of the series bound to the data source. */ /* istanbul ignore next */ public setItem(index: number, item: object, targetName: string): void { return; } /** * Notifies the the map that an item has been set in an associated data source. * * @param dataSource The data source in which the change happened. * @param index The index in the items source that has been changed. * @param newItem the new item that has been set in the collection. * @param oldItem the old item that has been overwritten in the collection. */ /* istanbul ignore next */ public notifySetItem(dataSource: object, index: number, newItem: object, oldItem: object): object { return; } /** * Notifies the the map that the items have been cleared from an associated data source. * It's not necessary to notify more than one target of a change if they share the same items source. * * @param dataSource The data source in which the change happened. */ /* istanbul ignore next */ public notifyClearItems(dataSource: object): object { return; } /** * Notifies the the target series that an item has been inserted at the specified index in its data source. * It's not necessary to notify more than one target of a change if they share the same items source. * * @param dataSource The data source in which the change happened. * @param index The index in the items source where the new item has been inserted. * @param newItem the new item that has been set in the collection. */ /* istanbul ignore next */ public notifyInsertItem(dataSource: object, index: number, newItem: object): object { return; } /** * Notifies the the target series that an item has been removed from the specified index in its data source. * It's not necessary to notify more than one target of a change if they share the same items source. * * @param dataSource The data source in which the change happened. * @param index The index in the items source from where the old item has been removed. * @param oldItem the old item that has been removed from the collection. */ /* istanbul ignore next */ public notifyRemoveItem(dataSource: object, index: number, oldItem: object): object { return; } /** * Notifies the target series or axis that it should scroll the requested data item into view. * * @param targetName The name of the series or axis notify. * @param item The data item to bring into view, if possible. */ /* istanbul ignore next */ public scrollIntoView(targetName: string, item: object): object { return; } /** * Either xAxis or yAxis (longitude or latitude) that it should scale the requested value into map space from axis space. * For example you can use this method if you want to find where longitude 50 stands scaled to map's width. * * @param targetName Either xAxis or yAxis to notify. * @param unscaledValue The value in axis space to translate into map space. */ /* istanbul ignore next */ public scaleValue(targetName: string, unscaledValue: number): number { return; } /** * Either xAxis or yAxis (longitude or latitude) that it should unscale the requested value into axis space from map space. * For example you can use this method if you want to find what is the longitude unscaled from 0 width of the map. * * @param targetName Either xAxis or yAxis to notify. * @param scaledValue The value in map space to translate into axis space. */ /* istanbul ignore next */ public unscaleValue(targetName: string, scaledValue: number): number { return; } /** * Manually starts a tiled zoom if one isn't already running. */ /* istanbul ignore next */ public startTiledZoomingIfNecessary(): void { return; } /** * Manually ends a tiled zoom if one is running. */ /* istanbul ignore next */ public endTiledZoomingIfRunning(): void { return; } /** * Clears the tile zoom tile cache so that new tiles will be generated. Only applies if the viewer is using a tile based zoom.. */ /* istanbul ignore next */ public clearTileZoomCache(): void { return; } /** * Forces any pending deferred work to render on the map before continuing */ /* istanbul ignore next */ public flush(): void { return; } /** * Exports visual data from the map to aid in unit testing */ /* istanbul ignore next */ public exportVisualData(): void { return; } /** * Gets the actual minimum value of the target xAxis or yAxis * * @param targetName target name */ /* istanbul ignore next */ public getActualMinimumValue(targetName: object): void { return; } /** * Gets the actual maximum value of the target xAxis or yAxis * * @param targetName target name */ /* istanbul ignore next */ public getActualMaximumValue(targetName: object): void { return; } /** * Notifies the map that the container was resized */ /* istanbul ignore next */ public notifyContainerResized(): void { return; } /** * Zoom in to the geographic region specified, when possible (may need to wait fior map to be initialized). * * @param rect The geographic area rectangle. */ /* istanbul ignore next */ public zoomToGeographic(rect: object): object { return; } /** * Given the current plot area of the control and a geographic region, get the WindowRect that would encompass that geographic region. * * @param rect The geographic area rectangle. */ /* istanbul ignore next */ public getGeographicFromZoom(rect: object): object { return; } /** * Given the current plot area of the control and a geographic region, get the WindowRect that would encompass that geographic region. * * @param rect The geographic area rectangle. */ /* istanbul ignore next */ public getZoomFromGeographic(rect: object): object { return; } /** * Creates a print preview page with the map, hiding all other elements on the page. */ /* istanbul ignore next */ public print(): void { return; } /** * Indicates that a series should render, even though no option has been modified that would normally cause it to refresh. * * @param targetName The name of the series to render. * @param animate Whether the change should be animated, if possible. */ /* istanbul ignore next */ public renderSeries(targetName: string, animate: boolean): void { return; }}
the_stack
import * as vscode from "vscode"; import { executeCommand, ExpectedDocument, groupTestsByParentName } from "../utils"; suite("./test/suite/commands/seek-word-edge.md", function () { // Set up document. let document: vscode.TextDocument, editor: vscode.TextEditor; this.beforeAll(async () => { document = await vscode.workspace.openTextDocument(); editor = await vscode.window.showTextDocument(document); editor.options.insertSpaces = true; editor.options.tabSize = 2; await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); }); this.afterAll(async () => { await executeCommand("workbench.action.closeActiveEditor"); }); test("1 > word-start-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox |^ 0 `); // Perform all operations. await executeCommand("dance.seek.word.backward"); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:8:1", 6, String.raw` the quick brown fox |^ 0 `); }); test("1 > word-start-4", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox |^ 0 `); // Perform all operations. await executeCommand("dance.seek.word", { count: 4 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:20:1", 6, String.raw` the quick brown fox ^^^ 0 `); }); test("1 > word-start-4 > word-start", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox ^^^ 0 `); // Perform all operations. await executeCommand("dance.seek.word"); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:30:1", 6, String.raw` the quick brown fox ^^^ 0 `); }); test("1 > word-start-4 > word-start > x", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox ^^^ 0 `); // Perform all operations. await executeCommand("dance.seek.word"); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:42:1", 6, String.raw` the quick brown fox ^^^ 0 `); }); test("1 > word-start-4 > word-start-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox ^^^ 0 `); // Perform all operations. await executeCommand("dance.seek.word.backward"); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:54:1", 6, String.raw` the quick brown fox |^^ 0 `); }); test("1 > word-start-4 > word-start-backward-2", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox ^^^ 0 `); // Perform all operations. await executeCommand("dance.seek.word.backward", { count: 2 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:64:1", 6, String.raw` the quick brown fox |^^^^^ 0 `); }); test("1 > word-start-4 > word-start-backward-5", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox ^^^ 0 `); // Perform all operations. await executeCommand("dance.seek.word.backward", { count: 5 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:74:1", 6, String.raw` the quick brown fox |^^^ 0 `); }); test("1 > word-start-5", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox |^ 0 `); // Perform all operations. await executeCommand("dance.seek.word", { count: 5 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:86:1", 6, String.raw` the quick brown fox ^^^ 0 `); }); test("2 > word-start-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` foo bar ^ 0 baz `); // Perform all operations. await executeCommand("dance.seek.word.backward"); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:106:1", 6, String.raw` foo bar |^^ 0 baz `); }); test("3 > word-start-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox |^^^ 0 |^ 1 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek.word.backward"); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:127:1", 6, String.raw` the quick brown fox |^^ 0 `); }); test("3 > word-start-backward-9", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox |^^^ 0 |^ 1 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek.word.backward", { count: 9 }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:139:1", 6, String.raw` the quick brown fox |^^^ 0 `); }); test("3 > word-end-4", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox |^^^ 0 |^ 1 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek.wordEnd", { count: 4 }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:151:1", 6, String.raw` the quick brown fox ^^^^ 0 `); }); test("3 > word-end-5", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` the quick brown fox |^^^ 0 |^ 1 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek.wordEnd", { count: 5 }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:163:1", 6, String.raw` the quick brown fox ^^^^ 0 `); }); test("4 > word-start-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` there is a blank line before me |^^^^ 0 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek.word.backward"); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:185:1", 6, String.raw` ^ 0 there is a blank line before me ^ 0 `); }); test("4 > word-start-backward > x", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` ^ 0 there is a blank line before me ^ 0 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek.word.backward"); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:200:1", 6, String.raw` ^ 0 there is a blank line before me ^ 0 `); }); test("4 > word-start-backward-4", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` there is a blank line before me |^^^^ 0 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek.word.backward", { count: 9 }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:214:1", 6, String.raw` ^ 0 there is a blank line before me ^ 0 `); }); test("5 > word-start-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` there are two blank lines before me |^^^^ 0 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek.word.backward"); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:239:1", 6, String.raw` ^ 0 ^ 0 there are two blank lines before me `); }); test("5 > word-start-backward > x", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` ^ 0 ^ 0 there are two blank lines before me `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek.word.backward"); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:255:1", 6, String.raw` ^ 0 ^ 0 there are two blank lines before me `); }); test("5 > word-start-backward-9", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` there are two blank lines before me |^^^^ 0 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.seek.word.backward", { count: 9 }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-word-edge.md:270:1", 6, String.raw` ^ 0 ^ 0 there are two blank lines before me `); }); groupTestsByParentName(this); });
the_stack
import * as React from 'react'; import { Input } from '@fluentui/react-input'; import { Label } from '@fluentui/react-label'; import { Button } from '@fluentui/react-button'; import { Scenario } from './utils'; import { useForm, Controller, OnSubmit } from 'react-hook-form'; import { usePubSub, PubSubProvider, Handler } from '@cactuslab/usepubsub'; const regexes = { onlyNameChars: /^[A-Za-zÀ-ÖØ-öø-ÿěščřžďťňůĚŠČŘŽĎŤŇŮ -]*$/, // eslint-disable-next-line @fluentui/max-len startsAndEndsWithLetter: /^(([A-Za-zÀ-ÖØ-öø-ÿěščřžďťňůĚŠČŘŽĎŤŇŮ][A-Za-zÀ-ÖØ-öø-ÿěščřžďťňůĚŠČŘŽĎŤŇŮ -]*[A-Za-zÀ-ÖØ-öø-ÿěščřžďťňůĚŠČŘŽĎŤŇŮ])|[A-Za-zÀ-ÖØ-öø-ÿěščřžďťňůĚŠČŘŽĎŤŇŮ])?$/, noWhitespace: /^\S*$/, hasNumber: /^\S*[0-9]\S*$/, hasLowercaseLetter: /^\S*[a-z]\S*$/, hasUppercaseLetter: /^\S*[A-Z]\S*$/, hasSpecialChar: /^\S*[^0-9a-zA-ZÀ-ÖØ-öø-ÿěščřžďťňůĚŠČŘŽĎŤŇŮ\s]\S*$/, }; interface FormInputs { fullName: string; nickname: string; password: string; } interface FormValidation { subscribe: (channel: string, handler: Handler) => () => void; unsubscribe: (channel: string, handler: Handler) => void; } interface ValidationMessageProps { id: string; formValidation: FormValidation; } const ValidationMessage: React.FC<ValidationMessageProps> = ({ id, formValidation, children }) => { const [isAlerting, setIsAlerting] = React.useState(true); const alert = React.useCallback(() => { setIsAlerting(false); setTimeout(() => setIsAlerting(true), 200); }, [setIsAlerting]); React.useEffect(() => { formValidation.subscribe(id, alert); return () => formValidation.unsubscribe(id, alert); }, [formValidation, alert, id]); return ( <div role={isAlerting ? 'alert' : undefined} style={{ color: isAlerting ? 'red' : 'green' }} id={`${id}Errors`}> {children} </div> ); }; const useFormValidation = ( handleSubmit: (callback: OnSubmit<FormInputs>) => (e?: React.BaseSyntheticEvent) => Promise<void>, ) => { const pubSub = usePubSub(); const isSubmitting = React.useRef(false); const wrappedHandleSubmit = React.useCallback( (callback: OnSubmit<FormInputs>) => { const handler = handleSubmit(callback); return async (e: React.BaseSyntheticEvent) => { isSubmitting.current = true; const result = await handler(e); isSubmitting.current = false; return result; }; }, [isSubmitting, handleSubmit], ); const onFieldValidated = React.useCallback( (field: string) => { if (!isSubmitting.current) { pubSub.publish(field, 'validate'); } return true; }, [isSubmitting, pubSub], ); const notifyFormFieldError = React.useCallback( (field: string) => { pubSub.publish(field, 'validate'); return true; }, [pubSub], ); return { subscribe: pubSub.subscribe, unsubscribe: pubSub.unsubscribe, onFieldValidated, handleSubmit: wrappedHandleSubmit, notifyFormFieldError, }; }; const RegistrationFormInputsAccessibility = () => { const { control, handleSubmit, errors, formState } = useForm<FormInputs>({ validateCriteriaMode: 'all', mode: 'onBlur', reValidateMode: 'onBlur', }); const formValidation = useFormValidation(handleSubmit); const [isPasswordVisible, setIsPasswordVisible] = React.useState(false); const [isSubmittedAndValid, setIsSubmittedAndValid] = React.useState(false); React.useEffect(() => { // If the form is submitted and has errors, focus the first error fiel, otherwise do nothing if (!formState.isSubmitting || formState.isValid) { return; } const firstErrorName = Object.keys(errors)[0] as keyof FormInputs; const firstErrorField = document.getElementById(firstErrorName); setTimeout(() => formValidation.notifyFormFieldError(firstErrorName), 200); if (firstErrorField) { firstErrorField.focus(); } }, [errors, formState, formValidation]); React.useEffect(() => { if (isSubmittedAndValid) { document.getElementById('validMessage')?.focus(); } }, [isSubmittedAndValid]); const onSubmit = (data: FormInputs, event?: React.BaseSyntheticEvent) => { event?.preventDefault(); if (formState.isValid) { setIsSubmittedAndValid(true); } }; const onShowPasswordChange = (event: React.ChangeEvent) => { setIsPasswordVisible(!isPasswordVisible); }; return ( <Scenario pageTitle="Registration form inputs"> <h2>Registration form</h2> {!isSubmittedAndValid ? ( <form onSubmit={formValidation.handleSubmit(onSubmit)}> <Label htmlFor="fullName">Full name:</Label> <Controller name="fullName" control={control} as={ <Input type="text" id="fullName" name="fullName" aria-required="true" aria-invalid={!!errors.fullName} aria-describedby="fullNameErrors" /> } rules={{ required: true, minLength: 2, maxLength: 50, validate: { onlyNameChars: value => regexes.onlyNameChars.test(value), startsAndEndsWithLetter: value => regexes.startsAndEndsWithLetter.test(value), always: () => { if (!formState.isSubmitting) { formValidation.onFieldValidated('fullName'); } return true; }, }, }} /> {errors.fullName?.types && ( <ValidationMessage id="fullName" formValidation={formValidation}> {'required' in errors.fullName.types ? ( <p>Full name is required.</p> ) : ( <> <p>Full name is invalid. It must:</p> <ul> {('minLength' in errors.fullName.types || 'maxLength' in errors.fullName.types) && ( <li>Have between 2 and 50 characters.</li> )} {'onlyNameChars' in errors.fullName.types && ( <li>Contain only lowercase or uppercase letters, spaces or hyphens.</li> )} {'startsAndEndsWithLetter' in errors.fullName.types && <li>Start and end wit letter.</li>} </ul> </> )} </ValidationMessage> )} <Label htmlFor="nickname">Nickname:</Label> <Controller name="nickname" control={control} as={ <Input type="text" id="nickname" name="nickname" aria-invalid={!!errors.nickname} aria-describedby="nicknameErrors" /> } rules={{ minLength: 2, maxLength: 20, validate: { onlyNameChars: value => regexes.onlyNameChars.test(value), startsAndEndsWithLetter: value => regexes.startsAndEndsWithLetter.test(value), always: () => { if (!formState.isSubmitting) { formValidation.onFieldValidated('nickname'); } return true; }, }, }} /> {errors.nickname?.types && ( <ValidationMessage id="nickname" formValidation={formValidation}> <p>Nickname is invalid. It must:</p> <ul> {('minLength' in errors.nickname.types || 'maxLength' in errors.nickname.types) && ( <li>Have between 2 and 20 characters.</li> )} {'onlyNameChars' in errors.nickname.types && ( <li>Contain only lowercase or uppercase letters, spaces or hyphens.</li> )} {'startsAndEndsWithLetter' in errors.nickname.types && <li>Start and end wit letter.</li>} </ul> </ValidationMessage> )} <Label htmlFor="password">Password:</Label> <Controller name="password" control={control} as={ <Input type={isPasswordVisible ? 'text' : 'password'} id="password" name="password" aria-required="true" aria-invalid={!!errors.password} aria-describedby="passwordErrors" /> } rules={{ required: true, minLength: 8, maxLength: 20, validate: { hasLowercaseLetter: value => regexes.hasLowercaseLetter.test(value), hasUppercaseLetter: value => regexes.hasUppercaseLetter.test(value), hasNumber: value => regexes.hasNumber.test(value), hasSpecialChar: value => regexes.hasSpecialChar.test(value), noWhitespace: value => regexes.noWhitespace.test(value), always: () => { if (!formState.isSubmitting) { formValidation.onFieldValidated('password'); } return true; }, }, }} /> <Label htmlFor="showPassword">Show password</Label> <input type="checkbox" id="showPassword" name="showPassword" onChange={onShowPasswordChange} /> {errors.password?.types && ( <ValidationMessage id="password" formValidation={formValidation}> {'required' in errors.password.types ? ( <p>Password is required.</p> ) : ( <> <p>Password is invalid. It must:</p> <ul> {('minLength' in errors.password.types || 'maxLength' in errors.password.types) && ( <li>Have between 8 and 20 characters.</li> )} {('hasLowercaseLetter' in errors.password.types || 'hasUppercaseLetter' in errors.password.types || 'hasSpecialChar' in errors.password.types || 'hasNumber' in errors.password.types || 'noWhiteSpace' in errors.password.types) && ( <li> Contain at least one lower case letter, upper case letter, number, special character and no spaces. </li> )} </ul> </> )} </ValidationMessage> )} <Button type="submit">Register</Button> </form> ) : ( <p id="validMessage" role="alert" tabIndex={0}> The form is valid and would have been submitted. </p> )} </Scenario> ); }; export const RegistrationFormInputsAccessibilityScenario = () => ( <PubSubProvider> <RegistrationFormInputsAccessibility /> </PubSubProvider> ); export default { title: 'Accessibility Scenarios/ Registration form inputs', id: 'input-accessibility-scenario', };
the_stack
import { Compare, Plot } from "@tonejs/plot"; import { expect } from "chai"; import { BasicTests, testAudioContext } from "test/helper/Basic"; import { atTime, Offline } from "test/helper/Offline"; import { SCHEDULE_RAMP_AFTER_SET_TARGET } from "test/helper/Supports"; import { BPM, Decibels, Frequency, Positive, Seconds, Time, Unit, UnitName } from "Tone/core/type/Units"; import { Signal } from "Tone/signal/Signal"; import { getContext } from "../Global"; import { Param } from "./Param"; import { connect } from "./ToneAudioNode"; const audioContext = getContext(); describe("Param", () => { BasicTests(Param, { context: testAudioContext, param: testAudioContext.createOscillator().frequency, }); context("constructor", () => { it("can be created and disposed", async () => { await Offline(context => { const param = new Param<"time">({ context, param: context.createConstantSource().offset, units: "time", }); expect(param.getValueAtTime(0)).to.equal(1); param.dispose(); }); }); it("can pass in a value", async () => { await Offline(context => { const param = new Param({ context, param: context.createConstantSource().offset, value: 1.1, }); expect(param.getValueAtTime(0)).to.equal(1.1); param.dispose(); }); }); it("requires a param in the constructor", () => { expect(() => { const param = new Param({ value: 1.1, }); }).throws(Error); }); }); context("Scheduling Curves", () => { const sampleRate = 11025; function matchesOutputCurve(param, outBuffer): void { outBuffer.toArray()[0].forEach((sample, index) => { try { expect(param.getValueAtTime(index / sampleRate)).to.be.closeTo(sample, 0.1); } catch (e) { throw e; } }); } if (SCHEDULE_RAMP_AFTER_SET_TARGET) { it("correctly handles setTargetAtTime followed by a ramp", async () => { let param; // this fails on FF const testBuffer = await Offline(context => { const source = context.createConstantSource(); source.connect(context.rawContext.destination); source.start(0); param = new Param({ context, param: source.offset, }); param.setTargetAtTime(2, 0.5, 0.1); expect(param.getValueAtTime(0.6)).to.be.closeTo(1.6, 0.1); param.linearRampToValueAtTime(0.5, 0.7); expect(param.getValueAtTime(0.6)).to.be.closeTo(0.75, 0.1); }, 1.5, 1, sampleRate); document.body.appendChild(await Plot.signal(testBuffer)); matchesOutputCurve(param, testBuffer); }); it("schedules a value curve", async () => { let param; const testBuffer = await Offline(context => { const source = context.createConstantSource(); source.connect(context.rawContext.destination); source.start(0); param = new Param({ context, param: source.offset, units: "number", value: 0, }); param.setValueCurveAtTime([0, 0.5, 0, 1, 1.5], 0.1, 0.8, 0.5); expect(param.getValueAtTime(0.91)).to.be.closeTo(0.75, 0.01); }, 1, 1, sampleRate); document.body.appendChild(await Plot.signal(testBuffer)); matchesOutputCurve(param, testBuffer); }); it("a mixture of scheduling curves", async () => { let param; const testBuffer = await Offline(context => { const source = context.createConstantSource(); source.connect(context.rawContext.destination); source.start(0); param = new Param({ context, param: source.offset, value: 0.1, }); param.setValueAtTime(0, 0); param.setValueAtTime(1, 0.1); param.linearRampToValueAtTime(3, 0.2); param.exponentialRampToValueAtTime(0.01, 0.3); param.setTargetAtTime(-1, 0.35, 0.2); param.cancelAndHoldAtTime(0.6); param.rampTo(1.1, 0.2, 0.7); param.exponentialRampTo(0, 0.1, 0.85); param.setValueAtTime(0, 1); param.linearRampTo(1, 0.2, 1); param.targetRampTo(0, 0.1, 1.1); param.setValueAtTime(4, 1.2); param.cancelScheduledValues(1.2); param.linearRampToValueAtTime(1, 1.3); }, 1.5, 1, sampleRate); document.body.appendChild(await Plot.signal(testBuffer)); matchesOutputCurve(param, testBuffer); }); it.skip("can cancel and hold", async () => { let param; const testBuffer = await Offline(context => { const source = context.createConstantSource(); source.connect(context.rawContext.destination); source.start(0); param = new Param({ context, param: source.offset, value: 0.1, }); param.setValueAtTime(0, 0); param.setValueAtTime(1, 0.2); param.cancelAndHoldAtTime(0.1); param.linearRampToValueAtTime(1, 0.3); param.cancelAndHoldAtTime(0.2); expect(param.getValueAtTime(0.2)).to.be.closeTo(0.5, 0.001); param.exponentialRampToValueAtTime(0, 0.4); param.cancelAndHoldAtTime(0.25); expect(param.getValueAtTime(0.25)).to.be.closeTo(0.033, 0.001); param.setTargetAtTime(1, 0.3, 0.1); param.cancelAndHoldAtTime(0.4); expect(param.getValueAtTime(0.4)).to.be.closeTo(0.644, 0.001); param.setValueAtTime(0, 0.45); param.setValueAtTime(1, 0.48); param.cancelAndHoldAtTime(0.45); expect(param.getValueAtTime(0.45)).to.be.closeTo(0, 0.001); }, 0.5, 1, sampleRate); matchesOutputCurve(param, testBuffer); // document.body.appendChild(await Plot.signal(testBuffer)); }); // it ("matches known values", async () => { // await Compare.toFile(context => { // const source = context.createConstantSource(); // source.connect(context.rawContext.destination); // source.start(0); // const param = new Param({ // context, // param: source.offset, // value: 0.1, // }); // param.setValueAtTime(0, 0); // param.setValueAtTime(1, 0.2); // param.cancelAndHoldAtTime(0.1); // param.linearRampToValueAtTime(1, 0.3); // param.cancelAndHoldAtTime(0.2); // param.exponentialRampToValueAtTime(0, 0.4); // param.cancelAndHoldAtTime(0.25); // param.setTargetAtTime(1, 0.3, 0.1); // param.cancelAndHoldAtTime(0.4); // }, "/base/test/audio/param/curve_0.wav", 0.01, 0.5, 1, 11025); // }); } }); context("Units", () => { it("throws an error with invalid values", () => { const osc = audioContext.createOscillator(); const param = new Param<"frequency">({ context: audioContext, param: osc.frequency, units: "frequency", }); expect(() => { // @ts-ignore expect(param.setValueAtTime("bad", "bad")); }).to.throw(Error); expect(() => { // @ts-ignore expect(param.linearRampToValueAtTime("bad", "bad")); }).to.throw(Error); expect(() => { // @ts-ignore expect(param.exponentialRampToValueAtTime("bad", "bad")); }).to.throw(Error); expect(() => { // @ts-ignore expect(param.setTargetAtTime("bad", "bad", 0.1)); }).to.throw(Error); expect(() => { // @ts-ignore expect(param.cancelScheduledValues("bad")); }).to.throw(Error); param.dispose(); }); it("can be created with specific units", () => { const gain = audioContext.createGain(); const param = new Param<"bpm">({ context: audioContext, param: gain.gain, units: "bpm", }); expect(param.units).to.equal("bpm"); param.dispose(); }); it("can evaluate the given units", () => { const gain = audioContext.createGain(); const param = new Param<"decibels">({ context: audioContext, param: gain.gain, units: "decibels", }); param.value = 0.5; expect(param.value).to.be.closeTo(0.5, 0.001); param.dispose(); }); it("can be forced to not convert", async () => { const testBuffer = await Offline(context => { const source = context.createConstantSource(); source.connect(context.rawContext.destination); source.start(0); const param = new Param({ context, convert: false, param: source.offset, units: "decibels", }); param.value = -10; expect(param.value).to.be.closeTo(-10, 0.01); }, 0.001, 1); expect(testBuffer.getValueAtTime(0)).to.be.closeTo(-10, 0.01); }); }); context("apply", () => { it("can apply a scheduled curve", () => { let sig; return Offline(context => { const signal = new Signal(); sig = signal; signal.setValueAtTime(0, 0); signal.linearRampToValueAtTime(0.5, 0.1); signal.exponentialRampToValueAtTime(0.2, 0.5); signal.linearRampToValueAtTime(4, 2); signal.cancelScheduledValues(1); signal.setTargetAtTime(4, 1, 0.1); const source = context.createConstantSource(); source.start(0); connect(source, context.destination); return atTime(0.4, () => { signal.apply(source.offset); }); }, 2).then(async buffer => { for (let time = 0.41; time < 2; time += 0.1) { expect(buffer.getValueAtTime(time)).to.be.closeTo(sig.getValueAtTime(time), 0.01); } // document.body.appendChild(await Plot.signal(buffer)); }); }); it("can apply a scheduled curve that starts with a setTargetAtTime", () => { let sig; return Offline(context => { const signal = new Signal(); sig = signal; signal.setTargetAtTime(2, 0, 0.2); const source = context.createConstantSource(); source.start(0); connect(source, context.destination); return atTime(0.4, () => { signal.apply(source.offset); }); }, 2).then(async buffer => { for (let time = 0.41; time < 2; time += 0.1) { expect(buffer.getValueAtTime(time)).to.be.closeTo(sig.getValueAtTime(time), 0.05); } // document.body.appendChild(await Plot.signal(buffer)); }); }); it("can apply a scheduled curve that starts with a setTargetAtTime and then schedules other things", () => { let sig; return Offline(context => { const signal = new Signal(); sig = signal; signal.setTargetAtTime(2, 0, 0.2); signal.setValueAtTime(1, 0.8); signal.linearRampToValueAtTime(0, 2); const source = context.createConstantSource(); source.start(0); connect(source, context.destination); return atTime(0.4, () => { signal.apply(source.offset); }); }, 2).then(async buffer => { for (let time = 0.41; time < 2; time += 0.1) { expect(buffer.getValueAtTime(time)).to.be.closeTo(sig.getValueAtTime(time), 0.05); } // document.body.appendChild(await Plot.signal(buffer)); }); }); it("can set the param if the Param is marked as swappable", () => { return Offline(context => { const constSource = context.createConstantSource(); const param = new Param({ swappable: true, param: constSource.offset, }); param.setValueAtTime(0.1, 0.1); param.setValueAtTime(0.2, 0.2); param.setValueAtTime(0.3, 0.3); const constSource2 = context.createConstantSource(); constSource2.start(0); param.setParam(constSource2.offset); connect(constSource2, context.destination); }, 0.5).then(buffer => { expect(buffer.getValueAtTime(0.1)).to.be.closeTo(0.1, 0.001); expect(buffer.getValueAtTime(0.2)).to.be.closeTo(0.2, 0.001); expect(buffer.getValueAtTime(0.3)).to.be.closeTo(0.3, 0.001); }); }); it("throws an error if the param is not set to swappable", () => { return Offline(context => { const constSource = context.createConstantSource(); const param = new Param({ param: constSource.offset, }); const constSource2 = context.createConstantSource(); expect(() => { param.setParam(constSource2.offset); }).to.throw(Error); }, 0.5); }); }); context("Unit Conversions", () => { function testUnitConversion(units: UnitName, inputValue: any, inputVerification: number, outputValue: number): void { it(`converts to ${units}`, async () => { const testBuffer = await Offline(context => { const source = context.createConstantSource(); source.connect(context.rawContext.destination); source.start(0); const param = new Param({ context, param: source.offset, units, }); param.value = inputValue; expect(param.value).to.be.closeTo(inputVerification, 0.01); }, 0.001, 1); expect(testBuffer.getValueAtTime(0)).to.be.closeTo(outputValue, 0.01); }); } testUnitConversion("number", 3, 3, 3); testUnitConversion("decibels", -10, -10, 0.31); testUnitConversion("decibels", -20, -20, 0.1); testUnitConversion("decibels", -100, -100, 0); testUnitConversion("gain", 1.2, 1.2, 1.2); testUnitConversion("positive", 1.5, 1.5, 1.5); testUnitConversion("positive", 0, 0, 0); testUnitConversion("time", 2, 2, 2); testUnitConversion("time", 0, 0, 0); testUnitConversion("frequency", 20, 20, 20); testUnitConversion("frequency", 0.1, 0.1, 0.1); testUnitConversion("normalRange", 0, 0, 0); testUnitConversion("normalRange", 0.5, 0.5, 0.5); testUnitConversion("normalRange", 1.5, 1, 1); testUnitConversion("audioRange", -1, -1, -1); testUnitConversion("audioRange", 0.5, 0.5, 0.5); testUnitConversion("audioRange", 1, 1, 1); }); context("min/maxValue", () => { function testMinMaxValue(units: UnitName, min, max): void { it(`has proper min/max for ${units}`, () => { const source = audioContext.createConstantSource(); source.connect(audioContext.rawContext.destination); const param = new Param({ context: audioContext, param: source.offset, units, }); expect(param.minValue).to.be.equal(min); expect(param.maxValue).to.be.equal(max); }); } // number, decibels, normalRange, audioRange, gain // positive, time, frequency, transportTime, ticks, bpm, degrees, samples, hertz const rangeMax = 3.4028234663852886e+38; testMinMaxValue("number", -rangeMax, rangeMax); testMinMaxValue("decibels", -Infinity, rangeMax); testMinMaxValue("normalRange", 0, 1); testMinMaxValue("audioRange", -1, 1); testMinMaxValue("gain", -rangeMax, rangeMax); testMinMaxValue("positive", 0, rangeMax); testMinMaxValue("time", 0, rangeMax); testMinMaxValue("frequency", 0, rangeMax); testMinMaxValue("transportTime", 0, rangeMax); testMinMaxValue("ticks", 0, rangeMax); testMinMaxValue("bpm", 0, rangeMax); testMinMaxValue("degrees", -rangeMax, rangeMax); testMinMaxValue("samples", 0, rangeMax); testMinMaxValue("hertz", 0, rangeMax); it("can pass in a min and max value", () => { const source = audioContext.createConstantSource(); source.connect(audioContext.rawContext.destination); const param = new Param({ context: audioContext, param: source.offset, minValue: 0.3, maxValue: 0.5, }); expect(param.minValue).to.be.equal(0.3); expect(param.maxValue).to.be.equal(0.5); }); }); context("defaultValue", () => { it("has the right default value for default units", () => { const source = audioContext.createConstantSource(); source.connect(audioContext.rawContext.destination); const param = new Param({ context: audioContext, param: source.offset, }); expect(param.defaultValue).to.be.equal(1); }); it("has the right default value for default decibels", () => { const source = audioContext.createConstantSource(); source.connect(audioContext.rawContext.destination); const param = new Param({ context: audioContext, param: source.offset, units: "decibels", }); expect(param.defaultValue).to.be.equal(0); }); }); // const allSchedulingMethods = ['setValueAtTime', 'linearRampToValueAtTime', 'exponentialRampToValueAtTime'] context("setValueAtTime", () => { function testSetValueAtTime(units: UnitName, value0, value1, value2): void { it(`can schedule value with units ${units}`, async () => { const testBuffer = await Offline(context => { const source = context.createConstantSource(); source.connect(context.rawContext.destination); source.start(0); const param = new Param({ context, param: source.offset, units, }); param.setValueAtTime(value0, 0); param.setValueAtTime(value1, 0.01); param.setValueAtTime(value2, 0.02); expect(param.getValueAtTime(0)).to.be.closeTo(value0, 0.01); expect(param.getValueAtTime(0.01)).to.be.closeTo(value1, 0.01); expect(param.getValueAtTime(0.02)).to.be.closeTo(value2, 0.01); }, 0.022, 1); expect(testBuffer.getValueAtTime(0)).to.be.closeTo(0, 0.01); expect(testBuffer.getValueAtTime(0.011)).to.be.closeTo(1, 0.01); expect(testBuffer.getValueAtTime(0.021)).to.be.closeTo(0.5, 0.01); }); } const allUnits: UnitName[] = ["number", "decibels", "normalRange", "audioRange", "gain", "positive", "time", "frequency", "transportTime", "ticks", "bpm", "degrees", "samples", "hertz"]; allUnits.forEach(unit => { if (unit === "decibels") { testSetValueAtTime(unit, -100, 0, -6); } else { testSetValueAtTime(unit, 0, 1, 0.5); } }); }); ["linearRampToValueAtTime", "exponentialRampToValueAtTime"].forEach(method => { context(method, () => { function testRampToValueAtTime(units: UnitName, value0, value1, value2): void { it(`can schedule value with units ${units}`, async () => { const testBuffer = await Offline(context => { const source = context.createConstantSource(); source.connect(context.rawContext.destination); source.start(0); const param = new Param({ context, param: source.offset, units, }); param.setValueAtTime(value0, 0); param[method](value1, 0.01); param[method](value2, 0.02); expect(param.getValueAtTime(0)).to.be.closeTo(value0, 0.01); expect(param.getValueAtTime(0.01)).to.be.closeTo(value1, 0.01); expect(param.getValueAtTime(0.02)).to.be.closeTo(value2, 0.01); }, 0.022, 1); expect(testBuffer.getValueAtTime(0)).to.be.closeTo(1, 0.01); expect(testBuffer.getValueAtTime(0.01)).to.be.closeTo(0.7, 0.01); expect(testBuffer.getValueAtTime(0.02)).to.be.closeTo(0, 0.01); }); } const allUnits: UnitName[] = ["number", "decibels", "normalRange", "audioRange", "gain", "positive", "time", "frequency", "transportTime", "ticks", "bpm", "degrees", "samples", "hertz"]; allUnits.forEach(unit => { if (unit === "decibels") { testRampToValueAtTime(unit, 0, -3, -100); } else { testRampToValueAtTime(unit, 1, 0.7, 0); } }); }); }); ["linearRampTo", "exponentialRampTo", "rampTo", "targetRampTo"].forEach(method => { context(method, () => { function testRampToValueAtTime(units: UnitName, value0, value1, value2): void { it(`can schedule value with units ${units}`, async () => { const testBuffer = await Offline(context => { const source = context.createConstantSource(); source.connect(context.rawContext.destination); source.start(0); const param = new Param({ context, param: source.offset, units, value: value0, }); param[method](value1, 0.009, 0); param[method](value2, 0.01, 0.01); expect(param.getValueAtTime(0)).to.be.closeTo(value0, 0.02); expect(param.getValueAtTime(0.01)).to.be.closeTo(value1, 0.02); if (units !== "decibels") { expect(param.getValueAtTime(0.025)).to.be.closeTo(value2, 0.01); } }, 0.021, 1); // document.body.appendChild(await Plot.signal(testBuffer)); expect(testBuffer.getValueAtTime(0)).to.be.closeTo(1, 0.01); expect(testBuffer.getValueAtTime(0.01)).to.be.closeTo(0.7, 0.01); expect(testBuffer.getValueAtTime(0.02)).to.be.closeTo(0, 0.01); }); } const allUnits: UnitName[] = ["number", "decibels", "normalRange", "audioRange", "gain", "positive", "time", "frequency", "transportTime", "ticks", "bpm", "degrees", "samples", "hertz"]; allUnits.forEach(unit => { if (unit === "decibels") { testRampToValueAtTime(unit, 0, -3, -100); } else { testRampToValueAtTime(unit, 1, 0.7, 0); } }); }); }); });
the_stack
import { CellPosition, toCursor } from "app/client/components/CellPosition"; import { Disposable, dom, Emitter, Holder, IDisposable, IDisposableOwner, IDomArgs, MultiHolder, styled, TagElem } from "grainjs"; import { GristDoc } from "app/client/components/GristDoc"; import { ITooltipControl, showTooltip, tooltipCloseButton } from "app/client/ui/tooltips"; import { FieldEditorStateEvent } from "app/client/widgets/FieldEditor"; import { colors, testId } from "app/client/ui2018/cssVars"; import { cssLink } from "app/client/ui2018/links"; /** * Component that keeps track of editor's state (draft value). If user hits an escape button * by accident, this component will provide a way to continue the work. * Each editor can report its current state, that will be remembered and restored * when user whishes to continue his work. * Each document can have only one draft at a particular time, that * is cleared when changes occur on any other cell or the cursor navigates await from a cell. * * This component is built as a plugin for GristDoc. GristDoc, FieldBuilder, FieldEditor were just * extended in order to provide some public interface that this objects plugs into. * To disable the drafts, just simple remove it from GristDoc. */ export class Drafts extends Disposable { constructor( doc: GristDoc ) { super(); // Here are all the parts that play some role in this feature // Cursor will navigate the cursor on a view to a proper cell const cursor: Cursor = CursorAdapter.create(this, doc); // Storage will remember last draft const storage: Storage = StorageAdapter.create(this); // Notification will show notification with button to undo discard const notification: Notification = NotificationAdapter.create(this, doc); // Tooltip will hover above the editor and offer to continue from last edit const tooltip: Tooltip = TooltipAdapter.create(this, doc); // Editor will restore its previous state and inform about keyboard events const editor: Editor = EditorAdapter.create(this, doc); // Here is the main use case describing how parts are connected const when = makeWhen(this); // When user cancels the editor when(editor.cellCancelled, (ev: StateChanged) => { // if the state of the editor hasn't changed if (!ev.modified) { // close the tooltip and notification tooltip.close(); notification.close(); // don't store the draft - we assume that user // actually wanted to discard the draft by pressing // escape again return; } // Show notification notification.showUndoDiscard(); // Save draft in memory storage.save(ev); // Make sure that tooltip is not visible tooltip.close(); }); // When user clicks notification to continue with the draft when(notification.pressed, async () => { // if the draft is there const draft = storage.get(); if (draft) { // restore the position of a cell await cursor.goToCell(draft.position); // activate the editor await editor.activate(); // and restore last draft editor.setState(draft.state); } // We don't need the draft any more. // If user presses escape one more time it will be crated // once again storage.clear(); // Close the notification notification.close(); // tooltip is not visible here, and will be shown // when editor is activated }); // When user doesn't do anything while the notification is visible // remove the draft when it disappears when(notification.disappeared, () => { storage.clear(); }); // When editor is activated (user typed something or double clicked a cell) when(editor.activated, (pos: CellPosition) => { // if there was a draft for a cell if (storage.hasDraftFor(pos)) { // show tooltip to continue with a draft tooltip.showContinueDraft(); } // make sure that notification is not visible notification.close(); }); // When editor is modified, close tooltip after some time when(editor.cellModified, (_: StateChanged) => { tooltip.scheduleClose(); }); // When user saves a cell when(editor.cellSaved, (_: StateChanged) => { // just close everything and clear draft storage.clear(); tooltip.close(); notification.close(); }); // When a user clicks a tooltip to continue with a draft when(tooltip.click, () => { const draft = storage.get(); // if there was a draft if (draft) { // restore the draft editor.setState(draft.state); } // close the tooltip tooltip.close(); }); } } /////////////////////////////////////////////////////////// // Roles definition that abstract the way this feature interacts with Grist /** * Cursor role can navigate the cursor to a proper cell */ interface Cursor { goToCell(pos: CellPosition): Promise<void>; } /** * Editor role represents active editor that is attached to a cell. */ interface Editor { // Occurs when user triggers the save operation (by the enter key, clicking away) cellSaved: TypedEmitter<StateChanged>; // Occurs when user triggers the save operation (by the enter key, clicking away) cellModified: TypedEmitter<StateChanged>; // Occurs when user typed something on a cell or double clicked it activated: TypedEmitter<CellPosition>; // Occurs when user cancels the edit (mainly by the escape key or by icon on mobile) cellCancelled: TypedEmitter<StateChanged>; // Editor can restore its state setState(state: any): void; // Editor can be shown up to the user on active cell activate(): Promise<void>; } /** * Notification that is shown to the user on the right bottom corner */ interface Notification { // Occurs when user clicked the notification pressed: Signal; // Occurs when notification disappears with no action from a user disappeared: Signal; // Notification can be closed if it is visible close(): void; // Show notification to the user, to inform him that he can continue with the draft showUndoDiscard(): void; } /** * Storage abstraction. Is responsible for storing latest * draft (position and state) */ interface Storage { // Retrieves latest draft data get(): State | null; // Stores latest draft data save(ev: State): void; // Checks if there is draft data at the position hasDraftFor(position: CellPosition): boolean; // Removes draft data clear(): void; } /** * Tooltip role is responsible for showing tooltip over active field editor with an information * that the drafts is available, and a button to continue with the draft */ interface Tooltip { // Occurs when user clicks the button on the tooltip - so he wants // to continue with the draft click: Signal; // Show tooltip over active cell editor showContinueDraft(): void; // Close tooltip close(): void; // Close tooltip after some time scheduleClose(): void; } /** * Schema of the information that is stored in the storage. */ interface State { // State of the editor state: any; // Cell position where the draft was created position: CellPosition; } /** * Event that is emitted when editor state has changed */ interface StateChanged extends State { modified: boolean; } /////////////////////////////////////////////////////////// // Here are all the adapters for the roles above. They // abstract the way this feature interacts with the GristDoc class CursorAdapter extends Disposable implements Cursor { constructor(private _doc: GristDoc) { super(); } public async goToCell(pos: CellPosition): Promise<void> { await this._doc.recursiveMoveToCursorPos(toCursor(pos, this._doc.docModel), true); } } class StorageAdapter extends Disposable implements Storage { private _memory: State | null; public get(): State | null { return this._memory; } public save(ev: State) { this._memory = ev; } public hasDraftFor(position: CellPosition): boolean { const item = this._memory; if (item && CellPosition.equals(item.position, position)) { return true; } return false; } public clear(): void { this._memory = null; } } class NotificationAdapter extends Disposable implements Notification { public readonly pressed: Signal; public readonly disappeared: Signal; private _hadAction = false; private _holder = Holder.create(this); constructor(private _doc: GristDoc) { super(); this.pressed = this.autoDispose(new Emitter()); this.disappeared = this.autoDispose(new Emitter()); } public close(): void { this._hadAction = true; this._holder.clear(); } public showUndoDiscard() { const notifier = this._doc.app.topAppModel.notifier; const notification = notifier.createUserMessage("Undo discard", { message: () => discardNotification( dom.on("click", () => { this._hadAction = true; this.pressed.emit(); }) ) }); notification.onDispose(() => { if (!this._hadAction) { this.disappeared.emit(); } }); this._holder.autoDispose(notification); this._hadAction = false; } } class TooltipAdapter extends Disposable implements Tooltip { public readonly click: Signal; // there can be only one tooltip at a time private _tooltip: ITooltipControl | null = null; private _scheduled = false; constructor(private _doc: GristDoc) { super(); this.click = this.autoDispose(new Emitter()); // make sure that the tooltip is closed when this object gets disposed this.onDispose(() => { this.close(); }); } public scheduleClose(): void { if (this._tooltip && !this._scheduled) { this._scheduled = true; const origClose = this._tooltip.close; this._tooltip.close = () => { clearTimeout(timer); origClose(); }; const timer = setTimeout(this._tooltip.close, 6000); } } public showContinueDraft(): void { // close tooltip if there was a previous one this.close(); // get the editor dom const editorDom = this._doc.activeEditor.get()?.getDom(); if (!editorDom) { return; } // attach the tooltip this._tooltip = showTooltip( editorDom, cellTooltip(() => this.click.emit())); } public close(): void { this._scheduled = false; this._tooltip?.close(); this._tooltip = null; } } class EditorAdapter extends Disposable implements Editor { public readonly cellSaved: TypedEmitter<StateChanged> = this.autoDispose(new Emitter()); public readonly cellModified: TypedEmitter<StateChanged> = this.autoDispose(new Emitter()); public readonly activated: TypedEmitter<CellPosition> = this.autoDispose(new Emitter()); public readonly cellCancelled: TypedEmitter<StateChanged> = this.autoDispose(new Emitter()); private _holder = Holder.create<MultiHolder>(this); constructor(private _doc: GristDoc) { super(); // observe active editor this.autoDispose(_doc.activeEditor.addListener((editor) => { if (!editor) { return; } // when the editor is created we assume that it is visible to the user this.activated.emit(editor.cellPosition()); // Auto dispose the previous MultiHolder along with all the previous listeners, and create a // new MultiHolder for the new ones. const mholder = MultiHolder.create(this._holder); mholder.autoDispose(editor.changeEmitter.addListener((e: FieldEditorStateEvent) => { this.cellModified.emit({ position: e.position, state: e.currentState, modified: e.wasModified }); })); // when user presses escape mholder.autoDispose(editor.cancelEmitter.addListener((e: FieldEditorStateEvent) => { this.cellCancelled.emit({ position: e.position, state: e.currentState, modified: e.wasModified }); })); // when user presses enter to save the value mholder.autoDispose(editor.saveEmitter.addListener((e: FieldEditorStateEvent) => { this.cellSaved.emit({ position: e.position, state: e.currentState, modified: e.wasModified }); })); })); } public setState(state: any): void { // rebuild active editor with a state from a draft this._doc.activeEditor.get()?.rebuildEditor(undefined, Number.POSITIVE_INFINITY, state); } public async activate() { // open up the editor at current position await this._doc.activateEditorAtCursor({}); } } /////////////////////////////////////////////////////////// // Ui components // Cell tooltip to restore the draft - it is visible over active editor const styledTooltip = styled('div', ` display: flex; align-items: center; --icon-color: ${colors.lightGreen}; & > .${cssLink.className} { margin-left: 8px; } `); function cellTooltip(clb: () => any) { return function (ctl: ITooltipControl) { return styledTooltip( cssLink('Restore last edit', dom.on('mousedown', (ev) => { ev.preventDefault(); ctl.close(); clb(); }), testId('draft-tooltip'), ), tooltipCloseButton(ctl), ); }; } // Discard notification dom const styledNotification = styled('div', ` cursor: pointer; color: ${colors.lightGreen}; &:hover { text-decoration: underline; } `); function discardNotification(...args: IDomArgs<TagElem<"div">>) { return styledNotification( "Undo Discard", testId("draft-notification"), ...args ); } /////////////////////////////////////////////////////////// // Internal implementations - not relevant to main use case // helper method to listen to the Emitter and dispose the listener with a parent function makeWhen(owner: IDisposableOwner) { return function <T extends EmitterType<any>>(emitter: T, handler: EmitterHandler<T>) { owner.autoDispose(emitter.addListener(handler as any)); }; } // Default emitter is not typed, this augments the Emitter interface interface TypedEmitter<T> { emit(item: T): void; addListener(clb: (e: T) => any): IDisposable; } interface Signal { emit(): void; addListener(clb: () => any): IDisposable; } type EmitterType<T> = T extends TypedEmitter<infer E> ? TypedEmitter<E> : Signal; type EmitterHandler<T> = T extends TypedEmitter<infer E> ? ((e: E) => any) : () => any;
the_stack
import * as babelTypes from 'babel-types'; export type coreTypes = babelTypes.ArrayExpression | babelTypes.AssignmentExpression | babelTypes.BinaryExpression | babelTypes.Directive | babelTypes.DirectiveLiteral | babelTypes.BlockStatement | babelTypes.BreakStatement | babelTypes.CallExpression | babelTypes.CatchClause | babelTypes.ConditionalExpression | babelTypes.ContinueStatement | babelTypes.DebuggerStatement | babelTypes.DoWhileStatement | babelTypes.EmptyStatement | babelTypes.ExpressionStatement | babelTypes.File | babelTypes.ForInStatement | babelTypes.ForStatement | babelTypes.FunctionDeclaration | babelTypes.FunctionExpression | babelTypes.Identifier | babelTypes.IfStatement | babelTypes.LabeledStatement | babelTypes.StringLiteral | babelTypes.NumericLiteral | babelTypes.NullLiteral | babelTypes.BooleanLiteral | babelTypes.RegExpLiteral | babelTypes.LogicalExpression | babelTypes.MemberExpression | babelTypes.NewExpression | babelTypes.Program | babelTypes.ObjectExpression | babelTypes.ObjectMethod | babelTypes.ObjectProperty | babelTypes.RestElement | babelTypes.ReturnStatement | babelTypes.SequenceExpression | babelTypes.SwitchCase | babelTypes.SwitchStatement | babelTypes.ThisExpression | babelTypes.ThrowStatement | babelTypes.TryStatement | babelTypes.UnaryExpression | babelTypes.UpdateExpression | babelTypes.VariableDeclaration | babelTypes.VariableDeclarator | babelTypes.WhileStatement | babelTypes.WithStatement; export type es2015Types = babelTypes.AssignmentPattern | babelTypes.ArrayPattern | babelTypes.ArrowFunctionExpression | babelTypes.ClassBody | babelTypes.ClassDeclaration | babelTypes.ClassExpression | babelTypes.ExportAllDeclaration | babelTypes.ExportDefaultDeclaration | babelTypes.ExportNamedDeclaration | babelTypes.ExportSpecifier | babelTypes.ForOfStatement | babelTypes.ImportDeclaration | babelTypes.ImportDefaultSpecifier | babelTypes.ImportNamespaceSpecifier | babelTypes.ImportSpecifier | babelTypes.MetaProperty | babelTypes.ClassMethod | babelTypes.ObjectPattern | babelTypes.SpreadElement | babelTypes.Super | babelTypes.TaggedTemplateExpression | babelTypes.TemplateElement | babelTypes.TemplateLiteral | babelTypes.YieldExpression | babelTypes.AwaitExpression | babelTypes.BindExpression | babelTypes.ClassProperty | babelTypes.Decorator | babelTypes.DoExpression | babelTypes.ExportDefaultSpecifier | babelTypes.ExportNamespaceSpecifier; export type flowTypes = babelTypes.AnyTypeAnnotation | babelTypes.ArrayTypeAnnotation | babelTypes.BooleanTypeAnnotation | babelTypes.BooleanLiteralTypeAnnotation | babelTypes.NullLiteralTypeAnnotation | babelTypes.ClassImplements | babelTypes.DeclareClass | babelTypes.DeclareFunction | babelTypes.DeclareInterface | babelTypes.DeclareModule | babelTypes.DeclareTypeAlias | babelTypes.DeclareVariable | babelTypes.FunctionTypeAnnotation | babelTypes.FunctionTypeParam | babelTypes.GenericTypeAnnotation | babelTypes.InterfaceExtends | babelTypes.InterfaceDeclaration | babelTypes.IntersectionTypeAnnotation | babelTypes.MixedTypeAnnotation | babelTypes.NullableTypeAnnotation | babelTypes.NumberTypeAnnotation | babelTypes.ObjectTypeAnnotation | babelTypes.ObjectTypeCallProperty | babelTypes.ObjectTypeIndexer | babelTypes.ObjectTypeProperty | babelTypes.QualifiedTypeIdentifier | babelTypes.StringLiteralTypeAnnotation | babelTypes.StringTypeAnnotation | babelTypes.ThisTypeAnnotation | babelTypes.TupleTypeAnnotation | babelTypes.TypeofTypeAnnotation | babelTypes.TypeAlias | babelTypes.TypeAnnotation | babelTypes.TypeCastExpression | babelTypes.TypeParameterDeclaration | babelTypes.TypeParameterInstantiation | babelTypes.UnionTypeAnnotation | babelTypes.VoidTypeAnnotation; export type jsxTypes = babelTypes.JSXAttribute | babelTypes.JSXClosingElement | babelTypes.JSXElement | babelTypes.JSXEmptyExpression | babelTypes.JSXExpressionContainer | babelTypes.JSXIdentifier | babelTypes.JSXMemberExpression | babelTypes.JSXNamespacedName | babelTypes.JSXOpeningElement | babelTypes.JSXSpreadAttribute | babelTypes.JSXText; export type miscTypes = babelTypes.Noop | babelTypes.ParenthesizedExpression; export type NodeTypes = coreTypes | es2015Types | flowTypes | jsxTypes | miscTypes; export interface coreVisitors<V> { ArrayExpression?: V | undefined; AssignmentExpression?: V | undefined; BinaryExpression?: V | undefined; Directive?: V | undefined; DirectiveLiteral?: V | undefined; BlockStatement?: V | undefined; BreakStatement?: V | undefined; CallExpression?: V | undefined; CatchClause?: V | undefined; ConditionalExpression?: V | undefined; ContinueStatement?: V | undefined; DebuggerStatement?: V | undefined; DoWhileStatement?: V | undefined; EmptyStatement?: V | undefined; ExpressionStatement?: V | undefined; File?: V | undefined; ForInStatement?: V | undefined; ForStatement?: V | undefined; FunctionDeclaration?: V | undefined; FunctionExpression?: V | undefined; Identifier?: V | undefined; IfStatement?: V | undefined; LabeledStatement?: V | undefined; StringLiteral?: V | undefined; NumericLiteral?: V | undefined; NullLiteral?: V | undefined; BooleanLiteral?: V | undefined; RegExpLiteral?: V | undefined; LogicalExpression?: V | undefined; MemberExpression?: V | undefined; NewExpression?: V | undefined; Program?: V | undefined; ObjectExpression?: V | undefined; ObjectMethod?: V | undefined; ObjectProperty?: V | undefined; RestElement?: V | undefined; ReturnStatement?: V | undefined; SequenceExpression?: V | undefined; SwitchCase?: V | undefined; SwitchStatement?: V | undefined; ThisExpression?: V | undefined; ThrowStatement?: V | undefined; TryStatement?: V | undefined; UnaryExpression?: V | undefined; UpdateExpression?: V | undefined; VariableDeclaration?: V | undefined; VariableDeclarator?: V | undefined; WhileStatement?: V | undefined; WithStatement?: V | undefined; } export interface es2015Visitors<V> { AssignmentPattern?: V | undefined; ArrayPattern?: V | undefined; ArrowFunctionExpression?: V | undefined; ClassBody?: V | undefined; ClassDeclaration?: V | undefined; ClassExpression?: V | undefined; ExportAllDeclaration?: V | undefined; ExportDefaultDeclaration?: V | undefined; ExportNamedDeclaration?: V | undefined; ExportSpecifier?: V | undefined; ForOfStatement?: V | undefined; ImportDeclaration?: V | undefined; ImportDefaultSpecifier?: V | undefined; ImportNamespaceSpecifier?: V | undefined; ImportSpecifier?: V | undefined; MetaProperty?: V | undefined; ClassMethod?: V | undefined; ObjectPattern?: V | undefined; SpreadElement?: V | undefined; Super?: V | undefined; TaggedTemplateExpression?: V | undefined; TemplateElement?: V | undefined; TemplateLiteral?: V | undefined; YieldExpression?: V | undefined; AwaitExpression?: V | undefined; BindExpression?: V | undefined; ClassProperty?: V | undefined; Decorator?: V | undefined; DoExpression?: V | undefined; ExportDefaultSpecifier?: V | undefined; ExportNamespaceSpecifier?: V | undefined; } export interface flowVisitors<V> { AnyTypeAnnotation?: V | undefined; ArrayTypeAnnotation?: V | undefined; BooleanTypeAnnotation?: V | undefined; BooleanLiteralTypeAnnotation?: V | undefined; NullLiteralTypeAnnotation?: V | undefined; ClassImplements?: V | undefined; DeclareClass?: V | undefined; DeclareFunction?: V | undefined; DeclareInterface?: V | undefined; DeclareModule?: V | undefined; DeclareTypeAlias?: V | undefined; DeclareVariable?: V | undefined; FunctionTypeAnnotation?: V | undefined; FunctionTypeParam?: V | undefined; GenericTypeAnnotation?: V | undefined; InterfaceExtends?: V | undefined; InterfaceDeclaration?: V | undefined; IntersectionTypeAnnotation?: V | undefined; MixedTypeAnnotation?: V | undefined; NullableTypeAnnotation?: V | undefined; NumberTypeAnnotation?: V | undefined; ObjectTypeAnnotation?: V | undefined; ObjectTypeCallProperty?: V | undefined; ObjectTypeIndexer?: V | undefined; ObjectTypeProperty?: V | undefined; QualifiedTypeIdentifier?: V | undefined; StringLiteralTypeAnnotation?: V | undefined; StringTypeAnnotation?: V | undefined; ThisTypeAnnotation?: V | undefined; TupleTypeAnnotation?: V | undefined; TypeofTypeAnnotation?: V | undefined; TypeAlias?: V | undefined; TypeAnnotation?: V | undefined; TypeCastExpression?: V | undefined; TypeParameterDeclaration?: V | undefined; TypeParameterInstantiation?: V | undefined; UnionTypeAnnotation?: V | undefined; VoidTypeAnnotation?: V | undefined; } export interface jsxVisitors<V> { JSXAttribute?: V | undefined; JSXClosingElement?: V | undefined; JSXElement?: V | undefined; JSXEmptyExpression?: V | undefined; JSXExpressionContainer?: V | undefined; JSXIdentifier?: V | undefined; JSXMemberExpression?: V | undefined; JSXNamespacedName?: V | undefined; JSXOpeningElement?: V | undefined; JSXSpreadAttribute?: V | undefined; JSXText?: V | undefined; } export interface miscVisitors<V> { Noop?: V | undefined; ParenthesizedExpression?: V | undefined; } export interface visitors<V> extends coreVisitors<V>, es2015Visitors<V>, flowVisitors<V>, jsxVisitors<V>, miscVisitors<V> { } export type Visitor = (commentBlock: NodeTypes, state: any) => void; export type SimpleVisitor = (node: NodeTypes, state: any) => void; export type AncestorVisitor = (node: NodeTypes, state: any, ancestors: babelTypes.Node[]) => void; export type AncestorStatelessVisitor = (node: NodeTypes, state: any, ancestors: babelTypes.Node[]) => void; export type RecursiveVisitor = (node: NodeTypes, state: any, next: (node: babelTypes.Node) => void) => void; export function simple(node: NodeTypes, visitors: visitors<SimpleVisitor>, state: any): void; export function ancestor(node: NodeTypes, visitors: visitors<AncestorVisitor>, state: any): void; export function recursive(node: NodeTypes, visitors: visitors<RecursiveVisitor>, state: any): void;
the_stack
import * as fs from 'fs'; import * as path from 'path'; import * as crypto from 'crypto'; import { execSync } from 'child_process'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { Diagnostic, DiagnosticSeverity, DiagnosticTag, ProposedFeatures, Range, TextEdit, Files, DocumentFilter, DocumentFormattingRegistrationOptions, Disposable, DocumentFormattingRequest, TextDocuments } from 'vscode-languageserver/node'; import { URI } from 'vscode-uri'; import { ProbeFailedParams, ProbeFailedRequest, NoESLintLibraryRequest, Status, ShowOutputChannel, NoConfigRequest } from './shared/customMessages'; import { ConfigurationSettings, DirectoryItem, ESLintSeverity, ModeEnum, ModeItem, PackageManagers, RuleCustomization, RuleSeverity, Validate } from './shared/settings'; import * as Is from './is'; import { LRUCache } from './linkedMap'; import { isUNC, normalizeDriveLetter, normalizePath } from './paths'; import LanguageDefaults from './languageDefaults'; /** * ESLint specific settings for a text document. */ export type TextDocumentSettings = Omit<ConfigurationSettings, 'workingDirectory'> & { silent: boolean; workingDirectory: DirectoryItem | undefined; library: ESLintModule | undefined; resolvedGlobalPackageManagerPath: string | undefined; }; export namespace TextDocumentSettings { export function hasLibrary(settings: TextDocumentSettings): settings is (TextDocumentSettings & { library: ESLintModule }) { return settings.library !== undefined; } } /** * A special error thrown by the ESLint library */ export interface ESLintError extends Error { messageTemplate?: string; messageData?: { pluginName?: string; }; } export namespace ESLintError { export function isNoConfigFound(error: any): boolean { const candidate = error as ESLintError; return candidate.messageTemplate === 'no-config-found' || candidate.message === 'No ESLint configuration found.'; } } type ESLintAutoFixEdit = { range: [number, number]; text: string; }; type ESLintSuggestionResult = { desc: string; fix: ESLintAutoFixEdit; }; type ESLintProblem = { line: number; column: number; endLine?: number; endColumn?: number; severity: number; ruleId: string; message: string; fix?: ESLintAutoFixEdit; suggestions?: ESLintSuggestionResult[] }; type ESLintDocumentReport = { filePath: string; errorCount: number; warningCount: number; messages: ESLintProblem[]; output?: string; }; type ESLintReport = { errorCount: number; warningCount: number; results: ESLintDocumentReport[]; }; export type CLIOptions = { cwd?: string; fixTypes?: string[]; fix?: boolean; }; export type SeverityConf = 0 | 1 | 2 | 'off' | 'warn' | 'error'; export type RuleConf = SeverityConf | [SeverityConf, ...any[]]; export type ConfigData = { rules?: Record<string, RuleConf>; }; export type ESLintClassOptions = { cwd?: string; fixTypes?: string[]; fix?: boolean; overrideConfig?: ConfigData; overrideConfigFile?: string | null; }; export type RuleMetaData = { docs?: { url?: string; }; type?: string; }; export namespace RuleMetaData { const handled: Set<string> = new Set(); const ruleId2Meta: Map<string, RuleMetaData> = new Map(); export function capture(eslint: ESLintClass, reports: ESLintDocumentReport[]): void { let rulesMetaData: Record<string, RuleMetaData> | undefined; if (eslint.isCLIEngine) { const toHandle = reports.filter(report => !handled.has(report.filePath)); if (toHandle.length === 0) { return; } rulesMetaData = typeof eslint.getRulesMetaForResults === 'function' ? eslint.getRulesMetaForResults(toHandle) : undefined; toHandle.forEach(report => handled.add(report.filePath)); } else { rulesMetaData = typeof eslint.getRulesMetaForResults === 'function' ? eslint.getRulesMetaForResults(reports) : undefined; } if (rulesMetaData === undefined) { return undefined; } Object.entries(rulesMetaData).forEach(([key, meta]) => { if (ruleId2Meta.has(key)) { return; } if (meta && meta.docs && Is.string(meta.docs.url)) { ruleId2Meta.set(key, meta); } }); } export function clear(): void { handled.clear(); ruleId2Meta.clear(); } export function getUrl(ruleId: string): string | undefined { return ruleId2Meta.get(ruleId)?.docs?.url; } export function getType(ruleId: string): string | undefined { return ruleId2Meta.get(ruleId)?.type; } export function hasRuleId(ruleId: string): boolean { return ruleId2Meta.has(ruleId); } } export type ParserOptions = { parser?: string; }; export type ESLintConfig = { env: Record<string, boolean>; extends: string | string[]; // globals: Record<string, GlobalConf>; ignorePatterns: string | string[]; noInlineConfig: boolean; // overrides: OverrideConfigData[]; parser: string | null; parserOptions?: ParserOptions; plugins: string[]; processor: string; reportUnusedDisableDirectives: boolean | undefined; root: boolean; rules: Record<string, RuleConf>; settings: object; }; export type Problem = { label: string; documentVersion: number; ruleId: string; line: number; diagnostic: Diagnostic; edit?: ESLintAutoFixEdit; suggestions?: ESLintSuggestionResult[]; }; export namespace Problem { export function isFixable(problem: Problem): problem is FixableProblem { return problem.edit !== undefined; } export function hasSuggestions(problem: Problem): problem is SuggestionsProblem { return problem.suggestions !== undefined; } } export type FixableProblem = Problem & { edit: ESLintAutoFixEdit; }; export namespace FixableProblem { export function createTextEdit(document: TextDocument, editInfo: FixableProblem): TextEdit { return TextEdit.replace(Range.create(document.positionAt(editInfo.edit.range[0]), document.positionAt(editInfo.edit.range[1])), editInfo.edit.text || ''); } } export type SuggestionsProblem = Problem & { suggestions: ESLintSuggestionResult[]; }; export namespace SuggestionsProblem { export function createTextEdit(document: TextDocument, suggestion: ESLintSuggestionResult): TextEdit { return TextEdit.replace(Range.create(document.positionAt(suggestion.fix.range[0]), document.positionAt(suggestion.fix.range[1])), suggestion.fix.text || ''); } } interface ESLintClass { // https://eslint.org/docs/developer-guide/nodejs-api#-eslintlinttextcode-options lintText(content: string, options: {filePath?: string, warnIgnored?: boolean}): Promise<ESLintDocumentReport[]>; // https://eslint.org/docs/developer-guide/nodejs-api#-eslintispathignoredfilepath isPathIgnored(path: string): Promise<boolean>; // https://eslint.org/docs/developer-guide/nodejs-api#-eslintgetrulesmetaforresultsresults getRulesMetaForResults?(results: ESLintDocumentReport[]): Record<string, RuleMetaData> | undefined /* for ESLintClassEmulator */; // https://eslint.org/docs/developer-guide/nodejs-api#-eslintcalculateconfigforfilefilepath calculateConfigForFile(path: string): Promise<ESLintConfig | undefined /* for ESLintClassEmulator */>; // Whether it is the old CLI Engine isCLIEngine?: boolean; } interface ESLintClassConstructor { new(options: ESLintClassOptions): ESLintClass; } interface CLIEngineConstructor { new(options: CLIOptions): CLIEngine; } /** * A loaded ESLint npm module. */ export type ESLintModule = { // version < 7.0 ESLint: undefined; CLIEngine: CLIEngineConstructor; } | { // 7.0 <= version < 8.0 ESLint: ESLintClassConstructor; CLIEngine: CLIEngineConstructor; } | { // 8.0 <= version. ESLint: ESLintClassConstructor; CLIEngine: undefined; }; export namespace ESLintModule { export function hasESLintClass(value: ESLintModule): value is { ESLint: ESLintClassConstructor; CLIEngine: undefined; } { return value.ESLint !== undefined; } export function hasCLIEngine(value: ESLintModule): value is { ESLint: undefined; CLIEngine: CLIEngineConstructor; } { return value.CLIEngine !== undefined; } } // { meta: { docs: [Object], schema: [Array] }, create: [Function: create] } type RuleData = { meta?: RuleMetaData; }; namespace RuleData { export function hasMetaType(value: RuleMetaData | undefined): value is RuleMetaData & { type: string; } { return value !== undefined && value.type !== undefined; } } interface CLIEngine { executeOnText(content: string, file?: string, warn?: boolean): ESLintReport; isPathIgnored(path: string): boolean; // This is only available from v4.15.0 forward getRules?(): Map<string, RuleData>; getConfigForFile?(path: string): ESLintConfig; } namespace CLIEngine { export function hasRule(value: CLIEngine): value is CLIEngine & { getRules(): Map<string, RuleData> } { return value.getRules !== undefined; } } /** * ESLint class emulator using CLI Engine. */ class ESLintClassEmulator implements ESLintClass { private cli: CLIEngine; constructor(cli: CLIEngine) { this.cli = cli; } get isCLIEngine(): boolean { return true; } async lintText(content: string, options: { filePath?: string | undefined; warnIgnored?: boolean | undefined; }): Promise<ESLintDocumentReport[]> { return this.cli.executeOnText(content, options.filePath, options.warnIgnored).results; } async isPathIgnored(path: string): Promise<boolean> { return this.cli.isPathIgnored(path); } getRulesMetaForResults(_results: ESLintDocumentReport[]): Record<string, RuleMetaData> | undefined { if (!CLIEngine.hasRule(this.cli)) { return undefined; } const rules: Record<string, RuleMetaData> = {}; for (const [name, rule] of this.cli.getRules()) { if (rule.meta !== undefined) { rules[name] = rule.meta; } } return rules; } async calculateConfigForFile(path: string): Promise<ESLintConfig | undefined> { return typeof this.cli.getConfigForFile === 'function' ? this.cli.getConfigForFile(path) : undefined; } } /** * Class for dealing with Fixes. */ export class Fixes { constructor(private edits: Map<string, Problem>) { } public static overlaps(a: FixableProblem | undefined, b: FixableProblem): boolean { return a !== undefined && a.edit.range[1] > b.edit.range[0]; } public static sameRange(a: FixableProblem, b: FixableProblem): boolean { return a.edit.range[0] === b.edit.range[0] && a.edit.range[1] === b.edit.range[1]; } public isEmpty(): boolean { return this.edits.size === 0; } public getDocumentVersion(): number { if (this.isEmpty()) { throw new Error('No edits recorded.'); } return this.edits.values().next().value.documentVersion; } public getScoped(diagnostics: Diagnostic[]): Problem[] { const result: Problem[] = []; for (const diagnostic of diagnostics) { const key = Diagnostics.computeKey(diagnostic); const editInfo = this.edits.get(key); if (editInfo) { result.push(editInfo); } } return result; } public getAllSorted(): FixableProblem[] { const result: FixableProblem[] = []; for (const value of this.edits.values()) { if (Problem.isFixable(value)) { result.push(value); } } return result.sort((a, b) => { const d0 = a.edit.range[0] - b.edit.range[0]; if (d0 !== 0) { return d0; } // Both edits have now the same start offset. // Length of a and length of b const al = a.edit.range[1] - a.edit.range[0]; const bl = b.edit.range[1] - b.edit.range[0]; // Both has the same start offset and length. if (al === bl) { return 0; } if (al === 0) { return -1; } if (bl === 0) { return 1; } return al - bl; }); } public getApplicable(): FixableProblem[] { const sorted = this.getAllSorted(); if (sorted.length <= 1) { return sorted; } const result: FixableProblem[] = []; let last: FixableProblem = sorted[0]; result.push(last); for (let i = 1; i < sorted.length; i++) { let current = sorted[i]; if (!Fixes.overlaps(last, current) && !Fixes.sameRange(last, current)) { result.push(current); last = current; } } return result; } } export type SaveRuleConfigItem = { offRules: Set<string>, onRules: Set<string>}; /** * Manages the special save rule configurations done in the VS Code settings. */ export namespace SaveRuleConfigs { export let inferFilePath: (documentOrUri: string | TextDocument | URI | undefined) => string | undefined; const saveRuleConfigCache = new LRUCache<string, SaveRuleConfigItem | null>(128); export async function get(uri: string, settings: TextDocumentSettings & { library: ESLintModule }): Promise<SaveRuleConfigItem | undefined> { const filePath = inferFilePath(uri); let result = saveRuleConfigCache.get(uri); if (filePath === undefined || result === null) { return undefined; } if (result !== undefined) { return result; } const rules = settings.codeActionOnSave.rules; result = await ESLint.withClass(async (eslint) => { if (rules === undefined || eslint.isCLIEngine) { return undefined; } const config = await eslint.calculateConfigForFile(filePath); if (config === undefined || config.rules === undefined || config.rules.length === 0) { return undefined; } const offRules: Set<string> = new Set(); const onRules: Set<string> = new Set(); if (rules.length === 0) { Object.keys(config.rules).forEach(ruleId => offRules.add(ruleId)); } else { for (const ruleId of Object.keys(config.rules)) { if (isOff(ruleId, rules)) { offRules.add(ruleId); } else { onRules.add(ruleId); } } } return offRules.size > 0 ? { offRules, onRules } : undefined; }, settings); if (result === undefined || result === null) { saveRuleConfigCache.set(uri, null); return undefined; } else { saveRuleConfigCache.set(uri, result); return result; } } export function remove(key: string): boolean { return saveRuleConfigCache.delete(key); } export function clear(): void { saveRuleConfigCache.clear(); } function isOff(ruleId: string, matchers: string[]): boolean { for (const matcher of matchers) { if (matcher.startsWith('!') && new RegExp(`^${matcher.slice(1).replace(/\*/g, '.*')}$`, 'g').test(ruleId)) { return true; } else if (new RegExp(`^${matcher.replace(/\*/g, '.*')}$`, 'g').test(ruleId)) { return false; } } return true; } } /** * Manages rule serverity overrides done using VS Code settings. */ export namespace RuleSeverities { const ruleSeverityCache = new LRUCache<string, RuleSeverity | null>(1024); export function getOverride(ruleId: string, customizations: RuleCustomization[]): RuleSeverity | undefined { let result: RuleSeverity | undefined | null = ruleSeverityCache.get(ruleId); if (result === null) { return undefined; } if (result !== undefined) { return result; } for (const customization of customizations) { if (asteriskMatches(customization.rule, ruleId)) { result = customization.severity; } } if (result === undefined) { ruleSeverityCache.set(ruleId, null); return undefined; } ruleSeverityCache.set(ruleId, result); return result; } export function clear(): void { ruleSeverityCache.clear(); } function asteriskMatches(matcher: string, ruleId: string): boolean { return matcher.startsWith('!') ? !(new RegExp(`^${matcher.slice(1).replace(/\*/g, '.*')}$`, 'g').test(ruleId)) : new RegExp(`^${matcher.replace(/\*/g, '.*')}$`, 'g').test(ruleId); } } /** * Creates LSP Diagnostis and captures code action information. */ namespace Diagnostics { export function computeKey(diagnostic: Diagnostic): string { const range = diagnostic.range; let message: string | undefined; if (diagnostic.message) { const hash = crypto.createHash('md5'); hash.update(diagnostic.message); message = hash.digest('base64'); } return `[${range.start.line},${range.start.character},${range.end.line},${range.end.character}]-${diagnostic.code}-${message ?? ''}`; } export function create(settings: TextDocumentSettings, problem: ESLintProblem): [Diagnostic, RuleSeverity | undefined] { const message = problem.message; const startLine = typeof problem.line !== 'number' || Number.isNaN(problem.line) ? 0 : Math.max(0, problem.line - 1); const startChar = typeof problem.column !== 'number' || Number.isNaN(problem.column) ? 0 : Math.max(0, problem.column - 1); const endLine = typeof problem.endLine !== 'number' || Number.isNaN(problem.endLine) ? startLine : Math.max(0, problem.endLine - 1); const endChar = typeof problem.endColumn !== 'number' || Number.isNaN(problem.endColumn) ? startChar : Math.max(0, problem.endColumn - 1); const override = RuleSeverities.getOverride(problem.ruleId, settings.rulesCustomizations); const result: Diagnostic = { message: message, severity: convertSeverityToDiagnosticWithOverride(problem.severity, override), source: 'eslint', range: { start: { line: startLine, character: startChar }, end: { line: endLine, character: endChar } } }; if (problem.ruleId) { const url = RuleMetaData.getUrl(problem.ruleId); result.code = problem.ruleId; if (url !== undefined) { result.codeDescription = { href: url }; } if (problem.ruleId === 'no-unused-vars') { result.tags = [DiagnosticTag.Unnecessary]; } } return [result, override]; } function adjustSeverityForOverride(severity: number | RuleSeverity, severityOverride?: RuleSeverity) { switch (severityOverride) { case RuleSeverity.off: case RuleSeverity.info: case RuleSeverity.warn: case RuleSeverity.error: return severityOverride; case RuleSeverity.downgrade: switch (convertSeverityToDiagnostic(severity)) { case DiagnosticSeverity.Error: return RuleSeverity.warn; case DiagnosticSeverity.Warning: case DiagnosticSeverity.Information: return RuleSeverity.info; } case RuleSeverity.upgrade: switch (convertSeverityToDiagnostic(severity)) { case DiagnosticSeverity.Information: return RuleSeverity.warn; case DiagnosticSeverity.Warning: case DiagnosticSeverity.Error: return RuleSeverity.error; } default: return severity; } } function convertSeverityToDiagnostic(severity: number | RuleSeverity) { // RuleSeverity concerns an overridden rule. A number is direct from ESLint. switch (severity) { // Eslint 1 is warning case 1: case RuleSeverity.warn: return DiagnosticSeverity.Warning; case 2: case RuleSeverity.error: return DiagnosticSeverity.Error; case RuleSeverity.info: return DiagnosticSeverity.Information; default: return DiagnosticSeverity.Error; } } function convertSeverityToDiagnosticWithOverride(severity: number | RuleSeverity, severityOverride: RuleSeverity | undefined): DiagnosticSeverity { return convertSeverityToDiagnostic(adjustSeverityForOverride(severity, severityOverride)); } } /** * Capture information necessary to compute code actions. */ export namespace CodeActions { const codeActions: Map<string, Map<string, Problem>> = new Map<string, Map<string, Problem>>(); export function get(uri: string): Map<string, Problem> | undefined { return codeActions.get(uri); } export function set(uri: string, value: Map<string, Problem>): void { codeActions.set(uri, value); } export function remove(uri: string): boolean { return codeActions.delete(uri); } export function record(document: TextDocument, diagnostic: Diagnostic, problem: ESLintProblem): void { if (!problem.ruleId) { return; } const uri = document.uri; let edits: Map<string, Problem> | undefined = CodeActions.get(uri); if (edits === undefined) { edits = new Map<string, Problem>(); CodeActions.set(uri, edits); } edits.set(Diagnostics.computeKey(diagnostic), { label: `Fix this ${problem.ruleId} problem`, documentVersion: document.version, ruleId: problem.ruleId, line: problem.line, diagnostic: diagnostic, edit: problem.fix, suggestions: problem.suggestions }); } } /** * Wrapper round the ESLint npm module. */ export namespace ESLint { let connection: ProposedFeatures.Connection; let documents: TextDocuments<TextDocument>; let inferFilePath: (documentOrUri: string | TextDocument | URI | undefined) => string | undefined; let loadNodeModule: <T>(moduleName: string) => T | undefined; const languageId2ParserRegExp: Map<string, RegExp[]> = function createLanguageId2ParserRegExp() { const result = new Map<string, RegExp[]>(); const typescript = /\/@typescript-eslint\/parser\//; const babelESLint = /\/babel-eslint\/lib\/index.js$/; result.set('typescript', [typescript, babelESLint]); result.set('typescriptreact', [typescript, babelESLint]); const angular = /\/@angular-eslint\/template-parser\//; result.set('html', [angular]); return result; }(); const languageId2ParserOptions: Map<string, { regExps: RegExp[]; parsers: Set<string>; parserRegExps?: RegExp[] }> = function createLanguageId2ParserOptionsRegExp() { const result = new Map<string, { regExps: RegExp[]; parsers: Set<string>; parserRegExps?: RegExp[] }>(); const vue = /vue-eslint-parser\/.*\.js$/; const typescriptEslintParser = /@typescript-eslint\/parser\/.*\.js$/; result.set('typescript', { regExps: [vue], parsers: new Set<string>(['@typescript-eslint/parser']), parserRegExps: [typescriptEslintParser] }); return result; }(); const languageId2PluginName: Map<string, string> = new Map([ ['html', 'html'], ['vue', 'vue'], ['markdown', 'markdown'] ]); const defaultLanguageIds: Set<string> = new Set([ 'javascript', 'javascriptreact' ]); const projectFolderIndicators: [string, boolean][] = [ [ 'package.json', true ], [ '.eslintignore', true], [ '.eslintrc', false ], [ '.eslintrc.json', false ], [ '.eslintrc.js', false ], [ '.eslintrc.yaml', false ], [ '.eslintrc.yml', false ] ]; const path2Library: Map<string, ESLintModule> = new Map<string, ESLintModule>(); const document2Settings: Map<string, Promise<TextDocumentSettings>> = new Map<string, Promise<TextDocumentSettings>>(); const formatterRegistrations: Map<string, Promise<Disposable>> = new Map(); export function initialize($connection: ProposedFeatures.Connection, $documents: TextDocuments<TextDocument>, $inferFilePath: (documentOrUri: string | TextDocument | URI | undefined) => string | undefined, $loadNodeModule: <T>(moduleName: string) => T | undefined) { connection = $connection; documents = $documents; inferFilePath = $inferFilePath; loadNodeModule = $loadNodeModule; } export function removeSettings(key: string): boolean { return document2Settings.delete(key); } export function clearSettings(): void { document2Settings.clear(); } export function unregisterAsFormatter(document: TextDocument): void { const unregister = formatterRegistrations.get(document.uri); if (unregister !== undefined) { void unregister.then(disposable => disposable.dispose()); formatterRegistrations.delete(document.uri); } } export function clearFormatters(): void { for (const unregistration of formatterRegistrations.values()) { void unregistration.then(disposable => disposable.dispose()); } formatterRegistrations.clear(); } export function resolveSettings(document: TextDocument): Promise<TextDocumentSettings> { const uri = document.uri; let resultPromise = document2Settings.get(uri); if (resultPromise) { return resultPromise; } resultPromise = connection.workspace.getConfiguration({ scopeUri: uri, section: '' }).then((configuration: ConfigurationSettings) => { const settings: TextDocumentSettings = Object.assign( {}, configuration, { silent: false, library: undefined, resolvedGlobalPackageManagerPath: undefined }, { workingDirectory: undefined} ); if (settings.validate === Validate.off) { return settings; } settings.resolvedGlobalPackageManagerPath = GlobalPaths.get(settings.packageManager); const filePath = inferFilePath(document); const workspaceFolderPath = settings.workspaceFolder !== undefined ? inferFilePath(settings.workspaceFolder.uri) : undefined; const hasUserDefinedWorkingDirectories: boolean = configuration.workingDirectory !== undefined; const workingDirectoryConfig = configuration.workingDirectory ?? { mode: ModeEnum.location }; if (ModeItem.is(workingDirectoryConfig)) { let candidate: string | undefined; if (workingDirectoryConfig.mode === ModeEnum.location) { if (workspaceFolderPath !== undefined) { candidate = workspaceFolderPath; } else if (filePath !== undefined && !isUNC(filePath)) { candidate = path.dirname(filePath); } } else if (workingDirectoryConfig.mode === ModeEnum.auto) { if (workspaceFolderPath !== undefined) { candidate = findWorkingDirectory(workspaceFolderPath, filePath); } else if (filePath !== undefined && !isUNC(filePath)) { candidate = path.dirname(filePath); } } if (candidate !== undefined && fs.existsSync(candidate)) { settings.workingDirectory = { directory: candidate }; } } else { settings.workingDirectory = workingDirectoryConfig; } let promise: Promise<string>; let nodePath: string | undefined; if (settings.nodePath !== null) { nodePath = settings.nodePath; if (!path.isAbsolute(nodePath) && workspaceFolderPath !== undefined) { nodePath = path.join(workspaceFolderPath, nodePath); } } let moduleResolveWorkingDirectory: string | undefined; if (!hasUserDefinedWorkingDirectories && filePath !== undefined) { moduleResolveWorkingDirectory = path.dirname(filePath); } if (moduleResolveWorkingDirectory === undefined && settings.workingDirectory !== undefined && !settings.workingDirectory['!cwd']) { moduleResolveWorkingDirectory = settings.workingDirectory.directory; } if (nodePath !== undefined) { promise = Files.resolve('eslint', nodePath, nodePath, trace).then<string, string>(undefined, () => { return Files.resolve('eslint', settings.resolvedGlobalPackageManagerPath, moduleResolveWorkingDirectory, trace); }); } else { promise = Files.resolve('eslint', settings.resolvedGlobalPackageManagerPath, moduleResolveWorkingDirectory, trace); } settings.silent = settings.validate === Validate.probe; return promise.then(async (libraryPath) => { let library = path2Library.get(libraryPath); if (library === undefined) { library = loadNodeModule(libraryPath); if (library === undefined) { settings.validate = Validate.off; if (!settings.silent) { connection.console.error(`Failed to load eslint library from ${libraryPath}. See output panel for more information.`); } } else if (library.CLIEngine === undefined && library.ESLint === undefined) { settings.validate = Validate.off; connection.console.error(`The eslint library loaded from ${libraryPath} doesn\'t neither exports a CLIEngine nor an ESLint class. You need at least eslint@1.0.0`); } else { connection.console.info(`ESLint library loaded from: ${libraryPath}`); settings.library = library; path2Library.set(libraryPath, library); } } else { settings.library = library; } if (settings.validate === Validate.probe && TextDocumentSettings.hasLibrary(settings)) { settings.validate = Validate.off; let filePath = ESLint.getFilePath(document, settings); if (filePath !== undefined) { const parserRegExps = languageId2ParserRegExp.get(document.languageId); const pluginName = languageId2PluginName.get(document.languageId); const parserOptions = languageId2ParserOptions.get(document.languageId); if (defaultLanguageIds.has(document.languageId)) { settings.validate = Validate.on; } else if (parserRegExps !== undefined || pluginName !== undefined || parserOptions !== undefined) { const eslintConfig: ESLintConfig | undefined = await ESLint.withClass((eslintClass) => { try { return eslintClass.calculateConfigForFile(filePath!); } catch (err) { return undefined; } }, settings); if (eslintConfig !== undefined) { const parser: string | undefined = eslintConfig.parser !== null ? normalizePath(eslintConfig.parser) : undefined; if (parser !== undefined) { if (parserRegExps !== undefined) { for (const regExp of parserRegExps) { if (regExp.test(parser)) { settings.validate = Validate.on; break; } } } if (settings.validate !== Validate.on && parserOptions !== undefined && typeof eslintConfig.parserOptions?.parser === 'string') { const eslintConfigParserOptionsParser = normalizePath(eslintConfig.parserOptions.parser); for (const regExp of parserOptions.regExps) { if (regExp.test(parser) && ( parserOptions.parsers.has(eslintConfig.parserOptions.parser) || parserOptions.parserRegExps !== undefined && parserOptions.parserRegExps.some(parserRegExp => parserRegExp.test(eslintConfigParserOptionsParser)) )) { settings.validate = Validate.on; break; } } } } if (settings.validate !== Validate.on && Array.isArray(eslintConfig.plugins) && eslintConfig.plugins.length > 0 && pluginName !== undefined) { for (const name of eslintConfig.plugins) { if (name === pluginName) { settings.validate = Validate.on; break; } } } } } } if (settings.validate === Validate.off) { const params: ProbeFailedParams = { textDocument: { uri: document.uri } }; void connection.sendRequest(ProbeFailedRequest.type, params); } } if (settings.format && settings.validate === Validate.on && TextDocumentSettings.hasLibrary(settings)) { const Uri = URI.parse(uri); const isFile = Uri.scheme === 'file'; let pattern: string = isFile ? Uri.fsPath.replace(/\\/g, '/') : Uri.fsPath; pattern = pattern.replace(/[\[\]\{\}]/g, '?'); const filter: DocumentFilter = { scheme: Uri.scheme, pattern: pattern }; const options: DocumentFormattingRegistrationOptions = { documentSelector: [filter] }; if (!isFile) { formatterRegistrations.set(uri, connection.client.register(DocumentFormattingRequest.type, options)); } else { const filePath = inferFilePath(uri)!; await ESLint.withClass(async (eslintClass) => { if (!await eslintClass.isPathIgnored(filePath)) { formatterRegistrations.set(uri, connection.client.register(DocumentFormattingRequest.type, options)); } }, settings); } } return settings; }, () => { settings.validate = Validate.off; if (!settings.silent) { void connection.sendRequest(NoESLintLibraryRequest.type, { source: { uri: document.uri } }); } return settings; }); }); document2Settings.set(uri, resultPromise); return resultPromise; } export function newClass(library: ESLintModule, newOptions: ESLintClassOptions | CLIOptions, useESLintClass: boolean): ESLintClass { if (ESLintModule.hasESLintClass(library) && useESLintClass) { return new library.ESLint(newOptions); } if (ESLintModule.hasCLIEngine(library)) { return new ESLintClassEmulator(new library.CLIEngine(newOptions)); } return new library.ESLint(newOptions); } export function withClass<T>(func: (eslintClass: ESLintClass) => T, settings: TextDocumentSettings & { library: ESLintModule }, options?: ESLintClassOptions | CLIOptions): T { const newOptions: ESLintClassOptions | CLIOptions = options === undefined ? Object.assign(Object.create(null), settings.options) : Object.assign(Object.create(null), settings.options, options); const cwd = process.cwd(); try { if (settings.workingDirectory) { // A lot of libs are sensitive to drive letter casing and assume a // capital drive letter. Make sure we support that correctly. const newCWD = normalizeDriveLetter(settings.workingDirectory.directory); newOptions.cwd = newCWD; if (settings.workingDirectory['!cwd'] !== true && fs.existsSync(newCWD)) { process.chdir(newCWD); } } const eslintClass = newClass(settings.library, newOptions, settings.useESLintClass); return func(eslintClass); } finally { if (cwd !== process.cwd()) { process.chdir(cwd); } } } export function getFilePath(document: TextDocument | undefined, settings: TextDocumentSettings): string | undefined { if (document === undefined) { return undefined; } const uri = URI.parse(document.uri); if (uri.scheme === 'untitled') { if (settings.workspaceFolder !== undefined) { const ext = LanguageDefaults.getExtension(document.languageId); const workspacePath = inferFilePath(settings.workspaceFolder.uri); if (workspacePath !== undefined && ext !== undefined) { return path.join(workspacePath, `test.${ext}`); } } return undefined; } else { return inferFilePath(uri); } } const validFixTypes = new Set<string>(['problem', 'suggestion', 'layout']); export async function validate(document: TextDocument, settings: TextDocumentSettings & { library: ESLintModule }): Promise<Diagnostic[]> { const newOptions: CLIOptions = Object.assign(Object.create(null), settings.options); let fixTypes: Set<string> | undefined = undefined; if (Array.isArray(newOptions.fixTypes) && newOptions.fixTypes.length > 0) { fixTypes = new Set(); for (const item of newOptions.fixTypes) { if (validFixTypes.has(item)) { fixTypes.add(item); } } if (fixTypes.size === 0) { fixTypes = undefined; } } const content = document.getText(); const uri = document.uri; const file = getFilePath(document, settings); return withClass(async (eslintClass) => { CodeActions.remove(uri); const reportResults: ESLintDocumentReport[] = await eslintClass.lintText(content, { filePath: file, warnIgnored: settings.onIgnoredFiles !== ESLintSeverity.off }); RuleMetaData.capture(eslintClass, reportResults); const diagnostics: Diagnostic[] = []; if (reportResults && Array.isArray(reportResults) && reportResults.length > 0) { const docReport = reportResults[0]; if (docReport.messages && Array.isArray(docReport.messages)) { docReport.messages.forEach((problem) => { if (problem) { const [diagnostic, override] = Diagnostics.create(settings, problem); if (!(override === RuleSeverity.off || (settings.quiet && diagnostic.severity === DiagnosticSeverity.Warning))) { diagnostics.push(diagnostic); } if (fixTypes !== undefined && problem.ruleId !== undefined && problem.fix !== undefined) { const type = RuleMetaData.getType(problem.ruleId); if (type !== undefined && fixTypes.has(type)) { CodeActions.record(document, diagnostic, problem); } } else { CodeActions.record(document, diagnostic, problem); } } }); } } return diagnostics; }, settings); } function trace(message: string, verbose?: string): void { connection.tracer.log(message, verbose); } /** * Global paths for the different package managers */ namespace GlobalPaths { const globalPaths: Record<string, { cache: string | undefined; get(): string | undefined; }> = { yarn: { cache: undefined, get(): string | undefined { return Files.resolveGlobalYarnPath(trace); } }, npm: { cache: undefined, get(): string | undefined { return Files.resolveGlobalNodePath(trace); } }, pnpm: { cache: undefined, get(): string { const pnpmPath = execSync('pnpm root -g').toString().trim(); return pnpmPath; } } }; export function get(packageManager: PackageManagers): string | undefined { const pm = globalPaths[packageManager]; if (pm) { if (pm.cache === undefined) { pm.cache = pm.get(); } return pm.cache; } return undefined; } } export function findWorkingDirectory(workspaceFolder: string, file: string | undefined): string | undefined { if (file === undefined || isUNC(file)) { return workspaceFolder; } // Don't probe for something in node modules folder. if (file.indexOf(`${path.sep}node_modules${path.sep}`) !== -1) { return workspaceFolder; } let result: string = workspaceFolder; let directory: string | undefined = path.dirname(file); outer: while (directory !== undefined && directory.startsWith(workspaceFolder)) { for (const item of projectFolderIndicators) { if (fs.existsSync(path.join(directory, item[0]))) { result = directory; if (item[1]) { break outer; } else { break; } } } const parent = path.dirname(directory); directory = parent !== directory ? parent : undefined; } return result; } export namespace ErrorHandlers { export const single: ((error: any, document: TextDocument, library: ESLintModule) => Status | undefined)[] = [ tryHandleNoConfig, tryHandleConfigError, tryHandleMissingModule, showErrorMessage ]; export function getMessage(err: any, document: TextDocument): string { let result: string | undefined = undefined; if (typeof err.message === 'string' || err.message instanceof String) { result = <string>err.message; result = result.replace(/\r?\n/g, ' '); if (/^CLI: /.test(result)) { result = result.substr(5); } } else { result = `An unknown error occurred while validating document: ${document.uri}`; } return result; } const noConfigReported: Map<string, ESLintModule> = new Map<string, ESLintModule>(); export function clearNoConfigRepoerted(): void { noConfigReported.clear(); } function tryHandleNoConfig(error: any, document: TextDocument, library: ESLintModule): Status | undefined { if (!ESLintError.isNoConfigFound(error)) { return undefined; } if (!noConfigReported.has(document.uri)) { connection.sendRequest( NoConfigRequest.type, { message: getMessage(error, document), document: { uri: document.uri } } ).then(undefined, () => { }); noConfigReported.set(document.uri, library); } return Status.warn; } const configErrorReported: Map<string, ESLintModule> = new Map<string, ESLintModule>(); export function getConfigErrorReported(key: string): ESLintModule | undefined { return configErrorReported.get(key); } export function removeConfigErrorReported(key: string): boolean { return configErrorReported.delete(key); } function tryHandleConfigError(error: any, document: TextDocument, library: ESLintModule): Status | undefined { if (!error.message) { return undefined; } function handleFileName(filename: string): Status { if (!configErrorReported.has(filename)) { connection.console.error(getMessage(error, document)); if (!documents.get(URI.file(filename).toString())) { connection.window.showInformationMessage(getMessage(error, document)); } configErrorReported.set(filename, library); } return Status.warn; } let matches = /Cannot read config file:\s+(.*)\nError:\s+(.*)/.exec(error.message); if (matches && matches.length === 3) { return handleFileName(matches[1]); } matches = /(.*):\n\s*Configuration for rule \"(.*)\" is /.exec(error.message); if (matches && matches.length === 3) { return handleFileName(matches[1]); } matches = /Cannot find module '([^']*)'\nReferenced from:\s+(.*)/.exec(error.message); if (matches && matches.length === 3) { return handleFileName(matches[2]); } return undefined; } const missingModuleReported: Map<string, ESLintModule> = new Map<string, ESLintModule>(); export function clearMissingModuleReported(): void { missingModuleReported.clear(); } function tryHandleMissingModule(error: any, document: TextDocument, library: ESLintModule): Status | undefined { if (!error.message) { return undefined; } function handleMissingModule(plugin: string, module: string, error: ESLintError): Status { if (!missingModuleReported.has(plugin)) { const fsPath = inferFilePath(document); missingModuleReported.set(plugin, library); if (error.messageTemplate === 'plugin-missing') { connection.console.error([ '', `${error.message.toString()}`, `Happened while validating ${fsPath ? fsPath : document.uri}`, `This can happen for a couple of reasons:`, `1. The plugin name is spelled incorrectly in an ESLint configuration file (e.g. .eslintrc).`, `2. If ESLint is installed globally, then make sure ${module} is installed globally as well.`, `3. If ESLint is installed locally, then ${module} isn't installed correctly.`, '', `Consider running eslint --debug ${fsPath ? fsPath : document.uri} from a terminal to obtain a trace about the configuration files used.` ].join('\n')); } else { connection.console.error([ `${error.message.toString()}`, `Happened while validating ${fsPath ? fsPath : document.uri}` ].join('\n')); } } return Status.warn; } const matches = /Failed to load plugin (.*): Cannot find module (.*)/.exec(error.message); if (matches && matches.length === 3) { return handleMissingModule(matches[1], matches[2], error); } return undefined; } const ignoredErrors: Set<string> = new Set(); function showErrorMessage(error: any, document: TextDocument): Status { const errorMessage = `ESLint: ${getMessage(error, document)}. Please see the 'ESLint' output channel for details.`; const actions = [ { title: 'Open Output', id: 1}, { title: 'Ignore for this Session', id: 2} ]; if (!ignoredErrors.has(errorMessage)) { void connection.window.showErrorMessage(errorMessage, ...actions).then((value) => { if (value !== undefined) { if (value.id === 1) { void connection.sendNotification(ShowOutputChannel.type); } else if (value.id === 2) { ignoredErrors.add(errorMessage); } } }); } else { connection.console.error(errorMessage); } if (Is.string(error.stack)) { connection.console.error('ESLint stack trace:'); connection.console.error(error.stack); } return Status.error; } } }
the_stack
import CommonUtils from "../../utils/CommonUtils"; import { BlockRegData } from "../Define/BlockDef"; import { BlockPort } from "../Define/Port"; export default { register, packageName: 'Array', version: 1, } function register() { //#region 创建数组 let CreateArray = new BlockRegData("9C432A9B-25DD-49D1-C504-16B9A207C3EC", "创建数组", '创建一个数组', '', '数组') CreateArray.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'IN0', paramType: 'any', name: '元素0', portAnyFlexable: { flexable: true } }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'ARRAY', paramType: 'any', paramSetType: 'array', name: '数组', description: '创建的数组实例', portAnyFlexable: { flexable: true } } ]; CreateArray.portAnyFlexables = { flexable: { setResultToData: 'opType' } }; CreateArray.settings.parametersChangeSettings.userCanAddInputParameter = true; CreateArray.callbacks.onCreate = (block) => { if(!CommonUtils.isDefined(block.data['opType'])) block.data['opType'] = 'any'; }; CreateArray.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let array = new Array<any>(); Object.keys(block.inputPorts).forEach((key) => { let port = (<BlockPort>block.inputPorts[key]); if(!port.paramType.isExecute()) { let v = block.getInputParamValue(port); if(CommonUtils.isDefinedAndNotNull(v)) array.push(v); } }); block.setOutputParamValue('ARRAY', array); block.activeOutputPort('OUT'); } }; CreateArray.callbacks.onUserAddPort = (block, direction, type) => { block.data['portCount'] = typeof block.data['portCount'] == 'number' ? block.data['portCount'] + 1 : block.inputPortCount; return { guid: 'IN' + block.data['portCount'], direction: 'input', paramType: block.data['opType'], name: '元素' + block.data['portCount'], portAnyFlexable: { flexable: true } } }; //#endregion //#region 清空数组 let EmptyArray = new BlockRegData("2B376B16-32E0-2D5E-080F-144586F6DC65", "清空数组", '清空一个数组,移除所有元素', '', '数组'); EmptyArray.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; EmptyArray.portAnyFlexables = { flexable: {} }; EmptyArray.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let array = <Array<any>>block.getInputParamValue('INARRAY'); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } array.empty(); block.setOutputParamValue('OUTARRAY', array); block.activeOutputPort('OUT'); } }; //#endregion //#region 获取 let ArrayGetItem = new BlockRegData("B19B4F6D-86DC-23C2-4430-8E5720E8927A", "获取", '获取数组指定索引的元素', '', '数组'); ArrayGetItem.ports = [ { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'ININDEX', paramType: 'number', name: '索引', description: '要获取的索引位置,如果为负值,则索引从末尾开始', }, { direction: 'input', guid: 'INISREF', paramType: 'boolean', name: '复制?', description: '如果复制为真,那么将会拷贝数组元素的一个副本,\n对此元素的更改不会在返回数组中。如果复制\n为假,那么对此元素的修改将会体现在数组中。', }, { direction: 'output', guid: 'OUTITEM', paramType: 'any', name: '元素', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayGetItem.portAnyFlexables = { flexable: {} }; ArrayGetItem.callbacks.onPortParamRequest = (block, port, context) => { let array = <Array<any>>block.getInputParamValue('INARRAY', context); let index = <number>block.getInputParamValue('ININDEX', context); let ref = <boolean>block.getInputParamValue('INISREF', context); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } if(!CommonUtils.isDefinedAndNotNull(index)) { block.throwError('输入索引参数不能为空', block.getPortByGUID('ININDEX'), 'error', true); return; } switch(port.guid) { case 'OUTITEM': return ref ? CommonUtils.clone(array[index]) : array[index], context case 'OUTARRAY': return array; } }; //#endregion //#region 插入 let ArrayInsert = new BlockRegData("56F43FA6-3FFE-0421-37D3-BDC28174FC98", "插入", '将元素插入数组指定索引', '', '数组'); ArrayInsert.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INITEM', name: '元素', description: '要插入的元素', paramType: 'any', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'ININDEX', name: '索引', description: '要插入的索引位置,如果为负值,则索引从末尾开始', paramType: 'number', }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTARRLEN', paramType: 'number', name: '数组长度', description: '修改之后的数组长度', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayInsert.portAnyFlexables = { flexable: {} }; ArrayInsert.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let array = <Array<any>>block.getInputParamValue('INARRAY'); let index = <number>block.getInputParamValue('ININDEX'); let item = <number>block.getInputParamValue('INITEM'); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } if(!index || index < 0) index = array.length - 1; array.splice(index, 2, item); block.setOutputParamValue('OUTARRAY', array); block.setOutputParamValue('OUTARRLEN', array.length); block.activeOutputPort('OUT'); } }; //#endregion //#region 添加 let ArrayAdd = new BlockRegData("71BC8260-2BF4-6E58-70CC-6154518958A0", "添加", '将元素添加至数组末尾', '', '数组'); ArrayAdd.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INITEM', name: '元素', description: '要插入的元素', paramType: 'any', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTARRLEN', paramType: 'number', name: '数组长度', description: '修改之后的数组长度', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayAdd.portAnyFlexables = { flexable: {} }; ArrayAdd.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let array = <Array<any>>block.getInputParamValue('INARRAY'); let item = <number>block.getInputParamValue('INITEM'); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } if(!CommonUtils.isDefinedAndNotNull(item)) { block.throwError('输入参数不能为空', block.getPortByGUID('INITEM'), 'error', true); return; } array.push(item); block.setOutputParamValue('OUTARRAY', array); block.setOutputParamValue('OUTARRLEN', array.length); block.activeOutputPort('OUT'); } }; //#endregion //#region 添加唯一 let ArrayAddOnce = new BlockRegData("56942A7E-D747-1F59-7297-EBF1DDE8572E", "添加唯一", '将元素添加至数组,如果元素已经在数组中,则不会添加', '', '数组'); ArrayAddOnce.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INITEM', name: '元素', description: '要插入的元素', paramType: 'any', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTARRLEN', paramType: 'number', name: '数组长度', description: '修改之后的数组长度', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayAddOnce.portAnyFlexables = { flexable: {} }; ArrayAddOnce.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let array = <Array<any>>block.getInputParamValue('INARRAY'); let item = <number>block.getInputParamValue('INITEM'); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } if(!CommonUtils.isDefinedAndNotNull(item)) { block.throwError('输入参数不能为空', block.getPortByGUID('INITEM'), 'error', true); return; } array.addOnce(item); block.setOutputParamValue('OUTARRAY', array); block.setOutputParamValue('OUTARRLEN', array.length); block.activeOutputPort('OUT'); } } //#endregion //#region 包含 let ArrayContains = new BlockRegData("55B1D5F5-CED3-0E91-70B4-BFCF71F1E5D6", "包含", '检查数组是否包含某个元素', '', '数组'); ArrayContains.ports = [ { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INITEM', paramType: 'number', name: '元素', description: '要检查的元素', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUTCONTAINS', paramType: 'boolean', name: '包含?', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayContains.portAnyFlexables = { flexable: {} }; ArrayContains.callbacks.onPortParamRequest = (block, port, context) => { let array = <Array<any>>block.getInputParamValue('INARRAY', context); if(port.guid == 'OUTARRAY') return array; else if(port.guid == 'OUTCONTAINS') { let item = block.getInputParamValue('INITEM', context); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } return array.contains(item); } }; //#endregion //#region 查找元素 let ArrayFind = new BlockRegData("AE91FCFC-1697-70F8-9304-6E39031EF284", "查找元素", '在数组中查找某个元素,返回它的第一个索引', '', '数组'); ArrayFind.ports = [ { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INITEM', paramType: 'number', name: '元素', description: '要检查的元素', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUTINDEX', paramType: 'boolean', name: '索引', description: '返回这个元素在此数组中的索引位置,如果没有找到,则返回-1', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayFind.portAnyFlexables = { flexable: {} }; ArrayFind.callbacks.onPortParamRequest = (block, port, context) => { let array = <Array<any>>block.getInputParamValue('INARRAY', context); if(port.guid == 'OUTARRAY') return array; if(port.guid == 'OUTINDEX') { let item = block.getInputParamValue('INITEM', context); let index = array.indexOf(item); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } return index; } }; //#endregion //#region 反向查找元素 let ArrayFindReverse = new BlockRegData("15BF61B9-F974-6700-7CD2-661F31842E96", "反向查找元素", '在数组中查找某个元素,返回它的最后一个索引', '', '数组'); ArrayFindReverse.ports = [ { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INITEM', paramType: 'number', name: '元素', description: '要检查的元素', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUTINDEX', paramType: 'boolean', name: '索引', description: '返回这个元素在此数组中的索引位置,如果没有找到,则返回-1', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayFindReverse.portAnyFlexables = { flexable: {} }; ArrayFindReverse.callbacks.onPortParamRequest = (block, port, context) => { let array = <Array<any>>block.getInputParamValue('INARRAY', context); if(port.guid == 'OUTARRAY') return array; if(port.guid == 'OUTINDEX') { let item = block.getInputParamValue('INITEM', context); let index = array.lastIndexOf(item); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } return index; } }; //#endregion //#region 为有效索引 let ArrayIndexValid = new BlockRegData("C874AEB3-B16B-B10E-8D40-65186840D8D0", "为有效索引", '测试一个索引数字在数组中是否有效', '', '数组'); ArrayIndexValid.ports = [ { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', }, { direction: 'input', guid: 'ININDEX', paramType: 'number', name: '索引', description: '想要测试有效的索引', }, { direction: 'output', guid: 'OUTVALID', paramType: 'boolean', name: '是否有效', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayIndexValid.callbacks.onPortParamRequest = (block, port, context) => { let array = <Array<any>>block.getInputParamValue('INARRAY', context); if(port.guid == 'OUTARRAY') return array; if(port.guid == 'OUTVALID') { let index = block.getInputParamValue('ININDEX', context); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } return index >= 0 && index < array.length; } }; //#endregion //#region 最后一个索引 let ArrayLastIndex = new BlockRegData("169EA221-5EB0-B42E-83BD-3C9AA9C48E91", "最后一个索引", '获取数组中的最后一个索引', '', '数组'); ArrayLastIndex.ports = [ { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', }, { direction: 'output', guid: 'OUTVALIDINDEX', paramType: 'number', name: '索引', description: '数组的最后一个有效索引', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayLastIndex.callbacks.onPortParamRequest = (block, port, context) => { let array = <Array<any>>block.getInputParamValue('INARRAY', context); if(port.guid == 'OUTARRAY') return array; if(port.guid == 'OUTVALIDINDEX') { if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } return array.length - 1; } }; //#endregion //#region 移除元素 let ArrayRemove = new BlockRegData("F0BC5166-7E22-1D90-AD2F-7E1C61DC498E", "移除元素", '移除数组中的一个元素', '', '数组'); ArrayRemove.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INITEM', name: '元素', description: '要移除的元素', paramType: 'any', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTRMED', paramType: 'boolean', description: '如果元素不在数组中,返回假,如果在数组中并且被移除,返回真', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayRemove.portAnyFlexables = { flexable: {} }; ArrayRemove.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let array = <Array<any>>block.getInputParamValue('INARRAY'); let item = <number>block.getInputParamValue('INITEM'); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } block.setOutputParamValue('OUTRMED', array.remove(item)); block.setOutputParamValue('OUTARRAY', array); block.activeOutputPort('OUT'); } }; //#endregion //#region 按索引移除元素 let ArrayRemoveIndex = new BlockRegData("BAF8135D-886B-4FD2-F683-06DAA67C5A0A", "按索引移除元素", '按索引移除数组中的一个元素', '', '数组'); ArrayRemoveIndex.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', }, { direction: 'input', guid: 'ININDEX', name: '索引', description: '要移除的索引位置,如果为负值,则索引从末尾开始', paramType: 'number', }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTARRLEN', paramType: 'boolean', description: '如果索引在数组中并且元素被移除,返回真', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayRemoveIndex.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let array = <Array<any>>block.getInputParamValue('INARRAY'); let index = <number>block.getInputParamValue('ININDEX'); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } if(index < 0) index = array.length - 1; block.setOutputParamValue('OUTARRLEN', array.remove(index)); block.setOutputParamValue('OUTARRAY', array); block.activeOutputPort('OUT'); } }; //#endregion //#region 交换数组元素 let ArraySwap = new BlockRegData("A087E766-18FD-F466-6EC2-A89A581E668F", "交换数组元素", '交换数组中的两个元素', '', '数组'); ArraySwap.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', }, { direction: 'input', guid: 'ININDEX1', description: '一个待切换的索引位置,如果为负值,则索引从末尾开始', paramType: 'number', }, { direction: 'input', guid: 'ININDEX2', description: '另一个待切换的索引位置,如果为负值,则索引从末尾开始', paramType: 'number', }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayRemoveIndex.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let array = <Array<any>>block.getInputParamValue('INARRAY'); let index2 = <number>block.getInputParamValue('ININDEX2'); let index1 = <number>block.getInputParamValue('ININDEX1'); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } if(!CommonUtils.isDefinedAndNotNull(index2)) { block.throwError('输入索引2参数不能为空', block.getPortByGUID('ININDEX2'), 'error', true); return; } if(!CommonUtils.isDefinedAndNotNull(index1)) { block.throwError('输入索引1参数不能为空', block.getPortByGUID('ININDEX1'), 'error', true); return; } CommonUtils.swapItems(array, index1, index2); block.setOutputParamValue('OUTARRAY', array); block.activeOutputPort('OUT'); } }; //#endregion //#region 数组长度 let ArrayLength = new BlockRegData("6DC6FBF7-A154-C666-B78B-06DE7DD96D02", "数组长度", '获取一个数组的长度', '', '数组'); ArrayLength.ports = [ { direction: 'input', guid: 'INARRAY', paramType: 'any', paramSetType: 'array', }, { direction: 'output', guid: 'OUTLEN', paramType: 'number', description: '数组的元素个数', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArrayLength.callbacks.onPortParamRequest = (block, port, context) => { let array = <Array<any>>block.getInputParamValue('INARRAY', context); if(port.guid == 'OUTARRAY') return array; if(port.guid == 'OUTLEN') { let array = <Array<any>>block.getInputParamValue('INARRAY', context); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } return array.length; } }; //#endregion //#region 重设长度 let ArraySetLength = new BlockRegData("B0FD037C-0EE9-E104-8B60-CD1270F759E9", "重设长度", '重新设置一个数组的长度', '', '数组'); ArraySetLength.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INARRAY', name: '数组', paramType: 'any', paramSetType: 'array', }, { direction: 'input', guid: 'INSIZE', description: '数组的新长度', paramType: 'number', }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } } ]; ArraySetLength.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let array = <Array<any>>block.getInputParamValue('INARRAY'); let len = <number>block.getInputParamValue('INSIZE'); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } if(!CommonUtils.isDefinedAndNotNull(len)) { block.throwError('输入数组的新长度参数不能为空', block.getPortByGUID('INSIZE'), 'error', true); return; } array.length = len; block.setOutputParamValue('OUTARRAY', array); block.activeOutputPort('OUT'); } }; //#endregion //#region 数组合并 let ArrayContact = new BlockRegData("E9681FF2-A9C9-3E4F-2FBE-D77BB75A2E54", "数组合并", '合并两个数组', '', '数组'); ArrayContact.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INARRAY', paramType: 'any', paramSetType: 'array', description: '一个待合并的数组', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INARRAY2', paramType: 'any', paramSetType: 'array', description: '另一个待合并的数组', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'input', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', description: '返回合并后的数组', }, ]; ArrayContact.portAnyFlexables = { flexable: {} }; ArrayContact.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let array = <Array<any>>block.getInputParamValue('INARRAY'); let array2 = <Array<any>>block.getInputParamValue('INARRAY2'); if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } if(!CommonUtils.isDefinedAndNotNull(array2)) { block.throwError('输入数组2参数不能为空', block.getPortByGUID('INARRA2Y'), 'error', true); return; } block.setOutputParamValue('OUTARRAY', array.concat(array2)); block.activeOutputPort('OUT'); } }; //#endregion //#region For Each Loop let ArrayForeach = new BlockRegData("284C7F0E-3105-9E59-06B8-9BF809519396", "For Each Loop(数组)", '遍历循环指定的数组', '', '数组'); ArrayForeach.baseInfo.logo = require('../../assets/images/BlockIcon/loop.svg'); ArrayForeach.ports = [ { name: "进入", direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { name: "数组", description: '要遍历的数组', direction: 'input', guid: 'ARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true }, }, { name: "终止", description: '终止遍历循环', direction: 'input', guid: 'BREAK', paramType: 'execute', }, { guid: 'LOOPBODY', paramType: 'execute', direction: 'output', name: '循环体', }, { guid: 'ELEMENT', paramType: 'number', direction: 'output', name: '当前元素', portAnyFlexable: { flexable: true }, }, { guid: 'INDEX', paramType: 'number', direction: 'output', name: '当前索引', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true } }, { guid: 'EXIT', paramType: 'execute', direction: 'output', name: '循环结束' }, ]; ArrayForeach.portAnyFlexables = { flexable: {} }; ArrayForeach.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { var variables = block.variables(); variables['breakActived'] = false; let INDEX = block.getPortByGUID('INDEX'); let ELEMENT = block.getPortByGUID('ELEMENT'); let EXIT = block.getPortByGUID('EXIT'); let LOOPBODY = block.getPortByGUID('LOOPBODY'); let array = <Array<any>>block.getInputParamValue('ARRAY'); let breakActived = variables['breakActived']; if(!CommonUtils.isDefinedAndNotNull(array)) { block.throwError('输入数组参数不能为空', block.getPortByGUID('INARRAY'), 'error', true); return; } for(let i = 0, len = array.length; i < len; i++) { block.setOutputParamValue(ELEMENT, array[i]); block.setOutputParamValue(INDEX, i); block.activeOutputPort(LOOPBODY); breakActived = variables['breakActived']; if(breakActived) break; } block.setOutputParamValue('OUTARRAY', array); block.activeOutputPort(EXIT); }else if(port.guid == 'BREAK') { var variables = block.variables(); variables['breakActived'] = true; } }; //#endregion return [ CreateArray, EmptyArray, ArrayGetItem, ArrayInsert, ArrayAdd, ArrayAddOnce, ArrayContains, ArrayFind, ArrayFindReverse, ArrayIndexValid, ArrayLastIndex, ArrayRemove, ArrayRemoveIndex, ArraySwap, ArrayLength, ArrayContact, ArraySetLength, ArrayForeach, ]; }
the_stack
import _debug from 'debug' import { PubTrackEvent as PubTrackEvt, TrackKind } from '../SocketEvent' import { WebWorker } from '../webworker' import { config } from '../window' const debug = _debug('peercalls') const { peerId } = config interface EncryptStreamEvent { type: 'encrypt' readable: ReadableStream<RTCEncodedFrame> writable: WritableStream<RTCEncodedFrame> } interface DecryptStreamEvent { type: 'decrypt' streamId: string kind: TrackKind peerId: string streams?: RTCInsertableStreams } interface PasswordEvent { type: 'password' password: string } interface PubTrackEvent { type: 'pubTrack' pubTrackEvent: PubTrackEvt } interface InitEvent { type: 'init' peerId: string url: string } type PostMessageEvent = EncryptStreamEvent | DecryptStreamEvent | PubTrackEvent | PasswordEvent | InitEvent export type EncryptionWorker = WebWorker<PostMessageEvent, void> export interface DecryptParams { receiver: RTCRtpReceiver kind: TrackKind streamId: string peerId: string } interface WorkerParams { peerId: string url: string } const workerFunc = () => (self: EncryptionWorker) => { const params: WorkerParams = { url: '', peerId: '', } const tagLength = 128 const ivByteLength = 16 interface DecryptContext { key?: CryptoKey streamProps: StreamProps peerId: string password: string } interface EncryptContext { key?: CryptoKey password: string } interface Context { password: string decryptContextByStreamKey: Record<StreamKey, DecryptContext> encryptContext: EncryptContext } const frameTypeToCryptoOffset = { key: 10, delta: 3, empty: 1, undefined: 1, } type StreamKey = string interface StreamProps { streamId: string kind: TrackKind } function newStreamKey(params: StreamProps): StreamKey { const { streamId, kind } = params return (streamId + ':' + kind) as StreamKey } const context: Context = { password: '', decryptContextByStreamKey: {}, encryptContext: { password: '', }, } function createKey(password: string, url: string, peerId: string) { const urlBytes = new TextEncoder().encode(url) const peerIdBytes = new TextEncoder().encode(peerId) const salt = new Uint8Array( urlBytes.byteLength + 1 + peerIdBytes.byteLength, ) salt.set(urlBytes) salt.set(peerIdBytes, urlBytes.byteLength + 1) return crypto.subtle.importKey( 'raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveKey', 'deriveBits'], ) .then(passwordKey => crypto.subtle.deriveKey( { name: 'PBKDF2', salt, iterations: 150000, hash: 'SHA-1', }, passwordKey, { name: 'AES-GCM', length: 256, }, false, [ 'encrypt', 'decrypt' ], )) } function updateDecryptContext( streamProps: StreamProps, peerId: string, ) { const { password } = context const { url } = params const streamKey = newStreamKey(streamProps) let c = context.decryptContextByStreamKey[streamKey] // Check if everything is already configured as it should be if (c && c.peerId === peerId && c.password === password) { return } c = context.decryptContextByStreamKey[streamKey] = { peerId, password, streamProps, } if (!password) { c.key = undefined return } return createKey(password, url, peerId) .then(key => { // Ensure there was no context update in the meantime. This can happen // if metadata has changed, or a user has left and another one who just // joined got assigned the same key. if (context.decryptContextByStreamKey[streamKey] === c) { context.decryptContextByStreamKey[streamKey].key = key } }) } function updateEncryptContext() { const { password } = context const { url, peerId } = params if (context.encryptContext && context.encryptContext.password === password) { return Promise.resolve() } if (!password) { context.encryptContext.key = undefined return Promise.resolve() } context.encryptContext.password = password return createKey(password, url, peerId) .then(key => { // Ensure password has not been changed in the meantime. if (context.encryptContext.password === password) { context.encryptContext.key = key } }) } function isVideoFrame(frame: unknown): frame is RTCEncodedVideoFrame { // cannot use typeof here because TypeScript converts it into a function // and this function call fails. return !!frame && !!(frame as {type: RTCEncodedVideoFrameType}).type } function getCryptoOffset<T extends RTCEncodedFrame>(frame: T): number { if (isVideoFrame(frame)) { return frameTypeToCryptoOffset[frame.type] } return frameTypeToCryptoOffset.undefined } function encrypt<T extends RTCEncodedFrame>( frame: T, controller: TransformStreamDefaultController<T>, ) { const { key } = context.encryptContext if (!key) { // Encryption key has not yet been created. if (!context.password) { // Only enqueue the unencrypted frame when there is no password set. // If a key was set, but the key creation is in process, we should not // leaking unencrypted frames. controller.enqueue(frame) } return } const iv = new Uint8Array(ivByteLength) crypto.getRandomValues(iv) const cryptoOffset = getCryptoOffset(frame) const additionalData = new Uint8Array(frame.data, 0, cryptoOffset) const dataToEncrypt = new Uint8Array(frame.data, cryptoOffset) return crypto.subtle.encrypt( { name: 'AES-GCM', iv, additionalData, tagLength, }, key, dataToEncrypt, ) .then(encryptedData => { const newData = new Uint8Array( additionalData.length + encryptedData.byteLength + iv.byteLength, ) let offset = 0 newData.set(additionalData, offset) offset += additionalData.byteLength newData.set(new Uint8Array(encryptedData), offset) offset += encryptedData.byteLength newData.set(iv, offset) offset += iv.byteLength frame.data = newData.buffer controller.enqueue(frame) }) } function decrypt<T extends RTCEncodedFrame>( streamProps: StreamProps, frame: T, controller: TransformStreamDefaultController<T>, ) { const streamKey = newStreamKey(streamProps) const ctx = context.decryptContextByStreamKey[streamKey] if (!ctx) { controller.enqueue(frame) return } if (!ctx.key) { controller.enqueue(frame) return } const { key } = ctx return Promise.resolve().then(() => { const cryptoOffset = getCryptoOffset(frame) let offset = 0 const additionalData = new Uint8Array(frame.data, offset, cryptoOffset) offset += additionalData.byteLength const encryptedData = new Uint8Array( frame.data, offset, frame.data.byteLength - offset - ivByteLength) offset += encryptedData.byteLength const iv = new Uint8Array(frame.data, offset) return crypto.subtle.decrypt( { name: 'AES-GCM', iv, additionalData, tagLength, }, key, encryptedData, ) .then(decryptedData => { const data = new Uint8Array( additionalData.byteLength + decryptedData.byteLength) data.set(additionalData) data.set(new Uint8Array(decryptedData), additionalData.byteLength) frame.data = data.buffer }) }) .catch(err => { // Decryption with invalid key will throw errors. }) .finally(() => { // TODO perhaps it would be wiser not to show unencrypted streams when // password is set to ensure users are aware that a receiving stream is // not encrypted. Or at least show some kind of warning. controller.enqueue(frame) }) } function handlePubTrackEvent(msg: PubTrackEvent) { const { pubTrackEvent } = msg const { kind, peerId, trackId: { streamId } } = pubTrackEvent const streamProps = { kind, streamId } const streamKey = newStreamKey(streamProps) // We use peerId becaues the peerId is the source of the track and the only // one who might use the insertable streams. switch (pubTrackEvent.type) { case 1: // Pub return updateDecryptContext(streamProps, peerId) case 2: // Unpub delete context.decryptContextByStreamKey[streamKey] break } } function handlePassword(msg: PasswordEvent) { context.password = msg.password // Regenerate all keys updateEncryptContext() .then(() => Promise.all( Object.keys(context.decryptContextByStreamKey).map(streamKey => { const decryptContext = context.decryptContextByStreamKey[streamKey] const { streamProps } = decryptContext return updateDecryptContext(streamProps, decryptContext.peerId) }), )) } function handleEncrypt(msg: EncryptStreamEvent) { msg.readable .pipeThrough(new TransformStream({ transform: (frame, ctrl) => encrypt(frame, ctrl), })) .pipeTo(msg.writable) return updateEncryptContext() } function handleDecrypt(msg: DecryptStreamEvent) { if (msg.streams) { msg.streams.readable .pipeThrough(new TransformStream({ transform: (frame, ctrl) => decrypt(msg, frame, ctrl), })) .pipeTo(msg.streams.writable) } return updateDecryptContext(msg, msg.peerId) } self.onmessage = event => { const msg = event.data switch (msg.type) { case 'init': params.url = msg.url params.peerId = msg.peerId console.log('InsertableStreams worker initialized', params.url) break case 'password': return handlePassword(msg) case 'pubTrack': return handlePubTrackEvent(msg) case 'encrypt': return handleEncrypt(msg) case 'decrypt': return handleDecrypt(msg) } } } export class InsertableStreamsCodec { protected worker?: Worker protected readonly workerBlobURL?: string protected sendersReceivers = new Set<RTCRtpSender | RTCRtpReceiver>() constructor() { if (!( typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function' )) { return } this.workerBlobURL = URL.createObjectURL( new Blob( ['(', workerFunc.toString(), ')()(self)'], {type: 'application/javascript'}, ), ) if ( !( typeof RTCRtpSender !== 'undefined' && typeof RTCRtpSender.prototype.createEncodedStreams === 'function' && typeof RTCRtpReceiver !== 'undefined' && typeof RTCRtpReceiver.prototype.createEncodedStreams === 'function' ) ) { debug('Environment does not support insertable streams') return } const initMsg: InitEvent = { type: 'init', url: location.href, peerId, } try { this.worker = new Worker(this.workerBlobURL) this.postMessage(initMsg, []) } catch (err) { debug('Error creating insertable streams worker: %s', err) } } private postMessage( message: PostMessageEvent, transfers: Transferable[], ): boolean { if (!this.worker) { return false } this.worker.postMessage(message, transfers) return true } setPassword(password: string): boolean { const message: PasswordEvent = { type: 'password', password: password, } return this.postMessage(message, []) } postPubTrackEvent(pubTrackEvent: PubTrackEvt) { const message: PubTrackEvent = { type: 'pubTrack', pubTrackEvent, } return this.postMessage(message, []) } getEncodedStreams( senderOrReceiver: RTCRtpSender | RTCRtpReceiver, ): RTCInsertableStreams | null { if (typeof senderOrReceiver.createEncodedStreams !== 'function') { return null } try { return senderOrReceiver.createEncodedStreams!() } catch (err) { debug('Could not get encoded streams: %s', err) return null } } encrypt(sender: RTCRtpSender): boolean { if (!this.worker) { return false } if (this.sendersReceivers.has(sender)) { // This sender has already been seen (transceiver reuse). return true } this.sendersReceivers.add(sender) const streams = this.getEncodedStreams(sender) if (!streams) { return false } const message: EncryptStreamEvent = { type: 'encrypt', readable: streams.readable, writable: streams.writable, } this.worker.postMessage(message, [ streams.readable, streams.writable, ] as unknown as Transferable[]) return true } decrypt(params: DecryptParams): boolean { if (!this.worker) { return false } let streams: RTCInsertableStreams | undefined const transferables: Transferable[] = [] // Encoded streams can only be requested once so the following prevents // an error during transceiver reuse in the case of the same sender being // assigned a different track. if (!this.sendersReceivers.has(params.receiver)) { const encodedStreams = this.getEncodedStreams(params.receiver) if (!encodedStreams) { return false } streams = { readable: encodedStreams.readable, writable: encodedStreams.writable, } transferables.push(streams.readable as unknown as Transferable) transferables.push(streams.writable as unknown as Transferable) this.sendersReceivers.add(params.receiver) } const message: DecryptStreamEvent = { type: 'decrypt', streamId: params.streamId, kind: params.kind, peerId: params.peerId, streams, } this.worker.postMessage(message, transferables) return true } } export const insertableStreamsCodec = new InsertableStreamsCodec()
the_stack
import { Storage } from '../storage/Storage' import { Logger } from '../utils/Logger' import { ExposedPromise } from '../utils/exposed-promise' import { MatrixClientStore } from './MatrixClientStore' import { MatrixHttpClient } from './MatrixHttpClient' import { MatrixRoom, MatrixRoomStatus } from './models/MatrixRoom' import { MatrixRoomService } from './services/MatrixRoomService' import { MatrixUserService } from './services/MatrixUserService' import { MatrixEventService } from './services/MatrixEventService' import { MatrixSyncResponse } from './models/api/MatrixSync' import { MatrixClientEventEmitter } from './MatrixClientEventEmitter' import { MatrixClientEventType, MatrixClientEvent } from './models/MatrixClientEvent' const logger = new Logger('MatrixClient') interface MatrixClientOptions { baseUrl: string storage: Storage } interface MatrixLoginConfig { id: string password: string deviceId: string } const IMMEDIATE_POLLING_RETRIES = 3 const RETRY_INTERVAL = 5000 /** * The matrix client used to connect to the matrix network */ export class MatrixClient { private isActive: boolean = true private _isReady: ExposedPromise<void> = new ExposedPromise() constructor( private readonly store: MatrixClientStore, private readonly eventEmitter: MatrixClientEventEmitter, private readonly userService: MatrixUserService, private readonly roomService: MatrixRoomService, private readonly eventService: MatrixEventService, private readonly httpClient: MatrixHttpClient ) { this.store.onStateChanged((oldState, newState, stateChange) => { this.eventEmitter.onStateChanged(oldState, newState, stateChange) }, 'rooms') } /** * Create a matrix client based on the options provided * * @param config */ public static create(config: MatrixClientOptions): MatrixClient { const store = new MatrixClientStore(config.storage) const eventEmitter = new MatrixClientEventEmitter() const httpClient = new MatrixHttpClient(config.baseUrl) const accountService = new MatrixUserService(httpClient) const roomService = new MatrixRoomService(httpClient) const eventService = new MatrixEventService(httpClient) return new MatrixClient( store, eventEmitter, accountService, roomService, eventService, httpClient ) } /** * Return all the rooms we are currently part of */ public get joinedRooms(): Promise<MatrixRoom[]> { return new Promise(async (resolve) => { await this.isConnected() resolve( Object.values(this.store.get('rooms')).filter( (room) => room.status === MatrixRoomStatus.JOINED ) ) }) } /** * Return all the rooms to which we have received invitations */ public get invitedRooms(): Promise<MatrixRoom[]> { return new Promise(async (resolve) => { await this.isConnected() resolve( Object.values(this.store.get('rooms')).filter( (room) => room.status === MatrixRoomStatus.INVITED ) ) }) } /** * Return all the rooms that we left */ public get leftRooms(): Promise<MatrixRoom[]> { return new Promise(async (resolve) => { await this.isConnected() resolve( Object.values(this.store.get('rooms')).filter( (room) => room.status === MatrixRoomStatus.LEFT ) ) }) } /** * Initiate the connection to the matrix node and log in * * @param user */ public async start(user: MatrixLoginConfig): Promise<void> { const response = await this.userService.login(user.id, user.password, user.deviceId) await this.store.update({ accessToken: response.access_token }) const initialPollingResult = new Promise<void>(async (resolve, reject) => { await this.poll( 0, async (pollingResponse: MatrixSyncResponse) => { if (!this.store.get('isRunning')) { resolve() } await this.store.update({ isRunning: true, syncToken: pollingResponse.next_batch, pollingTimeout: 30000, pollingRetries: 0, rooms: MatrixRoom.fromSync(pollingResponse.rooms) }) }, async (error) => { if (!this.store.get('isRunning')) { reject(error) } await this.store.update({ isRunning: false, pollingRetries: this.store.get('pollingRetries') + 1 }) } ) }) initialPollingResult .then(() => { this._isReady.resolve() }) .catch(console.error) return initialPollingResult } public async isConnected(): Promise<void> { return this._isReady.promise } /** * Stop all running requests */ public async stop(): Promise<void> { logger.log(`MATRIX CLIENT STOPPED`) this.isActive = false this._isReady = new ExposedPromise() return this.httpClient.cancelAllRequests() } /** * Subscribe to new matrix events * * @param event * @param listener */ public subscribe<T extends MatrixClientEventType>( event: T, listener: (event: MatrixClientEvent<T>) => void ): void { this.eventEmitter.on(event, listener) } /** * Unsubscribe from matrix events * * @param event * @param listener */ public unsubscribe( event: MatrixClientEventType, listener: (event: MatrixClientEvent<any>) => void ): void { if (listener) { this.eventEmitter.removeListener(event, listener) } } /** * Unsubscribe from all matrix events of this type * * @param event * @param listener */ public unsubscribeAll(event: MatrixClientEventType): void { this.eventEmitter.removeAllListeners(event) } public async getRoomById(id: string): Promise<MatrixRoom> { await this.isConnected() return this.store.getRoom(id) } /** * Create a private room with the supplied members * * @param members Members that will be in the room */ public async createTrustedPrivateRoom(...members: string[]): Promise<string> { await this.isConnected() return this.requiresAuthorization('createRoom', async (accessToken) => { const response = await this.roomService.createRoom(accessToken, { room_version: '5', invite: members, preset: 'public_chat', is_direct: true }) return response.room_id }) } /** * Invite user to rooms * * @param user The user to be invited * @param roomsOrIds The rooms the user will be invited to */ public async inviteToRooms(user: string, ...roomsOrIds: string[] | MatrixRoom[]): Promise<void> { await this.isConnected() await this.requiresAuthorization('invite', (accessToken) => Promise.all( (roomsOrIds as any[]).map((roomOrId) => { const room = this.store.getRoom(roomOrId) this.roomService .inviteToRoom(accessToken, user, room) .catch((error) => logger.warn('inviteToRooms', error)) }) ) ) } /** * Join rooms * * @param roomsOrIds */ public async joinRooms(...roomsOrIds: string[] | MatrixRoom[]): Promise<void> { await this.isConnected() await this.requiresAuthorization('join', (accessToken) => Promise.all( (roomsOrIds as any[]).map((roomOrId) => { const room = this.store.getRoom(roomOrId) return this.roomService.joinRoom(accessToken, room) }) ) ) } /** * Send a text message * * @param roomOrId * @param message */ public async sendTextMessage(roomId: string, message: string): Promise<void> { await this.isConnected() await this.requiresAuthorization('send', async (accessToken) => { const txnId = await this.createTxnId() return this.eventService.sendMessage( accessToken, roomId, { msgtype: 'm.text', body: message }, txnId ) }) } /** * Poll the server to get the latest data and get notified of changes * * @param interval * @param onSyncSuccess * @param onSyncError */ private async poll( interval: number, onSyncSuccess: (response: MatrixSyncResponse) => void, onSyncError: (error: unknown) => void ): Promise<void> { const store = this.store const sync = this.sync.bind(this) const pollSync = async ( resolve: (value?: void | PromiseLike<void> | undefined) => void, reject: (reason?: any) => void ): Promise<void> => { let syncingRetries: number = 0 try { const response = await sync() onSyncSuccess(response) } catch (error) { onSyncError(error) syncingRetries = store.get('pollingRetries') // console.warn('Could not sync:', error) if (this.isActive) { logger.log(`Retry syncing... ${syncingRetries} retries so far`) } } finally { if (this.isActive) { setTimeout( async () => { await pollSync(resolve, reject) }, syncingRetries > IMMEDIATE_POLLING_RETRIES ? RETRY_INTERVAL + interval : interval ) } else { reject(new Error(`Syncing stopped manually.`)) } } } return new Promise(pollSync) } /** * Get state from server */ private async sync(): Promise<MatrixSyncResponse> { return this.requiresAuthorization('sync', async (accessToken) => this.eventService.sync(accessToken, { pollingTimeout: this.store.get('pollingTimeout'), syncToken: this.store.get('syncToken') }) ) } /** * A helper method that makes sure an access token is provided * * @param name * @param action */ private async requiresAuthorization<T>( name: string, action: (accessToken: string) => Promise<T> ): Promise<T> { const storedToken: string | undefined = this.store.get('accessToken') if (!storedToken) { return Promise.reject(`${name} requires authorization but no access token has been provided.`) } return action(storedToken) } /** * Create a transaction ID */ private async createTxnId(): Promise<string> { const timestamp = new Date().getTime() const counter = this.store.get('txnNo') await this.store.update({ txnNo: counter + 1 }) return `m${timestamp}.${counter}` } }
the_stack
import assert from 'assert' import { parseArgv } from './cli' describe('CLI', () => { describe('parseArgv', () => { describe('input', () => { it('--input', () => { const argv = ['', '', '--input', 'sample.svg'] const options = parseArgv(argv) assert.strictEqual(options.input, 'sample.svg') }) it('-i', () => { const argv = ['', '', '-i', 'sample.svg'] const options = parseArgv(argv) assert.strictEqual(options.input, 'sample.svg') }) }) describe('output', () => { it('--output', () => { const argv = ['', '', '--output', './'] const options = parseArgv(argv) assert.strictEqual(options.output, './') }) it('-o', () => { const argv = ['', '', '-o', './'] const options = parseArgv(argv) assert.strictEqual(options.output, './') }) }) describe('icon', () => { it('Defaults', () => { const argv = ['', '', '-i', 'sample.svg'] const options = parseArgv(argv) assert.deepStrictEqual(options.icon, { report: false, icns: {}, ico: {}, favicon: {} }) }) }) describe('icon.ico', () => { it('--ico', () => { const argv = ['', '', '--ico'] const options = parseArgv(argv) assert.deepStrictEqual(options.icon, { report: false, ico: {} }) }) it('--ico-name', () => { const argv = ['', '', '--ico', '--ico-name', 'sample'] const options = parseArgv(argv) assert.deepStrictEqual(options.icon, { report: false, ico: { name: 'sample' } }) }) it('--ico-sizes', () => { const argv = ['', '', '--ico', '--ico-sizes', '24,32'] const options = parseArgv(argv) assert.deepStrictEqual(options.icon, { report: false, ico: { sizes: [24, 32] } }) }) }) describe('icon.icns', () => { it('--icns', () => { const argv = ['', '', '--icns'] const options = parseArgv(argv) assert.deepStrictEqual(options.icon, { report: false, icns: {} }) }) it('--icns-name', () => { const argv = ['', '', '--icns', '--icns-name', 'sample'] const options = parseArgv(argv) assert.deepStrictEqual(options.icon, { report: false, icns: { name: 'sample' } }) }) it('--icns-sizes', () => { const argv = ['', '', '--icns', '--icns-sizes', '24,32'] const options = parseArgv(argv) assert.deepStrictEqual(options.icon, { report: false, icns: { sizes: [24, 32] } }) }) }) describe('icon.favicon', () => { it('--favicon', () => { const argv = ['', '', '--favicon'] const options = parseArgv(argv) assert.deepStrictEqual(options.icon, { report: false, favicon: {} }) }) it('--favicon-name', () => { const argv = ['', '', '--favicon', '--favicon-name', 'sample'] const options = parseArgv(argv) assert.deepStrictEqual(options.icon, { report: false, favicon: { name: 'sample' } }) }) it('--favicon-png-sizes', () => { const argv = ['', '', '--favicon', '--favicon-png-sizes', '24,32'] const options = parseArgv(argv) assert.deepStrictEqual(options.icon, { report: false, favicon: { pngSizes: [24, 32] } }) }) it('--favicon-ico-sizes', () => { const argv = ['', '', '--favicon', '--favicon-ico-sizes', '24,32'] const options = parseArgv(argv) assert.deepStrictEqual(options.icon, { report: false, favicon: { icoSizes: [24, 32] } }) }) }) }) }) /* import assert from 'assert' import Path from 'path' describe('CLI', () => { const Module = Rewire('./cli.js') describe('parse', () => { const parse = Module.__get__('parse') it('Empty arguments', () => { const options = parse([]) assert(options.help) }) it('parse: -h --help', () => { let options = parse(['-h']) assert(options.help) options = parse(['--help']) assert(options.help) }) it('-v --version', () => { let options = parse(['-v']) assert(options.version) options = parse(['--version']) assert(options.version) }) it('-i SVGFILE -o DESTDIR', () => { const argv = ['-i', './test/data/sample.svg', '-o', './test'] const options = parse(argv) let expected = Path.resolve(argv[1]) assert(options.input === expected) expected = Path.resolve(argv[3]) assert(options.output === expected) assert(options.report === undefined) }) it('-i PNGDIR -o DESTDIR -r', () => { const argv = ['-i', './test/data', '-o', './test', '-r'] const options = parse(argv) let expected = Path.resolve(argv[1]) assert(options.input === expected) expected = Path.resolve(argv[3]) assert(options.output === expected) assert(options.report === true) }) it('Default images', () => { const argv = ['-i', './test/data', '-o', './test'] const options = parse(argv) assert(options.ico !== undefined) assert(options.icns !== undefined) assert(options.favicon !== undefined) }) describe('--ico', () => { it('Full options', () => { const argv = [ '-i', './test/data', '-o', './test', '--ico', 'name=foo', 'sizes=16,32' ] const options = parse(argv) const expected = { name: 'foo', sizes: [16, 32] } assert.deepStrictEqual(options.ico, expected) }) it('name', () => { const argv = ['-i', './test/data', '-o', './test', '--ico', 'name=foo'] const options = parse(argv) const expected = { name: 'foo' } assert.deepStrictEqual(options.ico, expected) }) it('sizes', () => { const argv = [ '-i', './test/data', '-o', './test', '--ico', 'sizes=16,32' ] const options = parse(argv) const expected = { sizes: [16, 32] } assert.deepStrictEqual(options.ico, expected) }) it('Without options', () => { const argv = ['-i', './test/data', '-o', './test', '--ico'] const options = parse(argv) assert(options.ico !== undefined) assert(options.icns === undefined) assert(options.favicon === undefined) }) }) describe('--icns', () => { it('Full options', () => { const argv = [ '-i', './test/data', '-o', './test', '--icns', 'name=foo', 'sizes=16,32' ] const options = parse(argv) const expected = { name: 'foo', sizes: [16, 32] } assert.deepStrictEqual(options.icns, expected) }) it('name', () => { const argv = ['-i', './test/data', '-o', './test', '--icns', 'name=foo'] const options = parse(argv) const expected = { name: 'foo' } assert.deepStrictEqual(options.icns, expected) }) it('sizes', () => { const argv = [ '-i', './test/data', '-o', './test', '--icns', 'sizes=16,32' ] const options = parse(argv) const expected = { sizes: [16, 32] } assert.deepStrictEqual(options.icns, expected) }) it('Without options', () => { const argv = ['-i', './test/data', '-o', './test', '--icns'] const options = parse(argv) assert(options.ico === undefined) assert(options.icns !== undefined) assert(options.favicon === undefined) }) }) describe('--favicon', () => { it('Full options', () => { const argv = [ '-i', './test/data', '-o', './test', '--favicon', 'ico=24,48', 'name=icon-', 'sizes=16,32' ] const options = parse(argv) const expected = { ico: [24, 48], name: 'icon-', sizes: [16, 32] } assert.deepStrictEqual(options.favicon, expected) }) it('ico', () => { const argv = [ '-i', './test/data', '-o', './test', '--favicon', 'ico=24,48' ] const options = parse(argv) const expected = { ico: [24, 48] } assert.deepStrictEqual(options.favicon, expected) }) it('name', () => { const argv = [ '-i', './test/data', '-o', './test', '--favicon', 'name=icon-' ] const options = parse(argv) const expected = { name: 'icon-' } assert.deepStrictEqual(options.favicon, expected) }) it('sizes', () => { const argv = [ '-i', './test/data', '-o', './test', '--favicon', 'sizes=16,32' ] const options = parse(argv) const expected = { sizes: [16, 32] } assert.deepStrictEqual(options.favicon, expected) }) it('Without options', () => { const argv = ['-i', './test/data', '-o', './test', '--favicon'] const options = parse(argv) assert(options.ico === undefined) assert(options.icns === undefined) assert(options.favicon !== undefined) }) }) }) describe('parseArgOption', () => { const parseArgOption = Module.__get__('parseArgOption') it('key=value', () => { const actual = parseArgOption('name=foo') const expected = { name: 'name', value: 'foo' } assert.deepStrictEqual(actual, expected) }) it('value', () => { const actual = parseArgOption('value') const expected = 'value' assert(actual === expected) }) }) }) */
the_stack
import {Sparkline, ISparklineLoadedEventArgs, SparklineTooltip} from '../../src/sparkline/index'; import {removeElement, getIdElement} from '../../src/sparkline/utils/helper'; import {createElement} from '@syncfusion/ej2-base'; import { MouseEvents } from './events.spec'; import {profile , inMB, getMemoryProfile} from '../common.spec'; Sparkline.Inject(SparklineTooltip); describe('Sparkline data source combination spec', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); let trigger: MouseEvents = new MouseEvents(); let element: Element; let sparkline: Sparkline; let id: string = 'spark-container'; let ele: Element; let d: string[]; beforeAll(() => { element = createElement('div', { id: id }); (element as HTMLDivElement).style.width = '400px'; (element as HTMLDivElement).style.height = '100px'; document.body.appendChild(element); sparkline = new Sparkline({ height: '200', width: '600', lineWidth: 2, fill: '#6404c4', containerArea: { border: { color: '#09ac09', width: 2 }, background: '#f3eeee' }, tooltipSettings: { visible: true, format: '${xDate} : ${yval}', trackLineSettings: { visible: true, color: 'red', width: 2 } }, dataSource: [ {xDate: new Date(2017, 1, 1), x: 0, xval: 'God Hand', yval: 2900 }, {xDate: new Date(2017, 1, 2), x: 1, xval: 'God of War', yval: 3900 }, {xDate: new Date(2017, 1, 3), x: 2, xval: 'Uncharted', yval: 3500 }, {xDate: new Date(2017, 1, 4), x: 3, xval: 'Yazuka', yval: 3800 }, {xDate: new Date(2017, 1, 5), x: 4, xval: 'GTA V', yval: 2500 }, {xDate: new Date(2017, 1, 6), x: 5, xval: 'Tomb Rider', yval: 3200 }, {xDate: new Date(2017, 1, 7), x: 6, xval: 'Sleeping Dogs', yval: 1800 }, {xDate: new Date(2017, 1, 8), x: 7, xval: 'Final Fantasy', yval: 5000 }, ], yName: 'yval', xName: 'x' }); }); afterAll(() => { sparkline.destroy(); removeElement(id); }); it('Sparkline height and width parent size priority checking', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_sparkline_line'); expect(ele.getAttribute('stroke')).toBe('#6404c4'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(28); ele = getIdElement(id + '_SparklineBorder'); d = ele.getAttribute('d').split(' '); let x: number = Number(d[1]); let y: number = Number(d[2]); let width: number = Number(d[9]) - x; let height: number = Number(d[18]) - y; expect(height).toBe(198); expect(width).toBe(598); }; sparkline.appendTo('#' + id); }); it('Sparkline datetime value type checking', () => { sparkline.loaded = () => { /* null function */}; sparkline.fill = '#f76c36'; sparkline.xName = 'xDate'; sparkline.valueType = 'DateTime'; sparkline.dataBind(); ele = getIdElement(id + '_sparkline_line'); trigger.mousemoveEvent(ele, 0, 0, 300, 100); expect(ele.getAttribute('stroke')).toBe('#f76c36'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(28); ele = getIdElement(id + '_sparkline_tooltip_div_text'); expect(ele.firstChild.textContent).toBe('Sat Feb 04 2017 '); expect(ele.lastChild.textContent).toBe(' 3800'); ele = getIdElement(id); trigger.mouseLeaveEvent(ele); }); it('Sparkline category value type checking', () => { sparkline.fill = '#07e22c'; sparkline.xName = 'xval'; sparkline.valueType = 'Category'; sparkline.tooltipSettings.format = '${xval} : ${yval}'; sparkline.dataBind(); ele = getIdElement(id + '_sparkline_line'); trigger.mousemoveEvent(ele, 0, 0, 300, 100); expect(ele.getAttribute('stroke')).toBe('#07e22c'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(28); ele = getIdElement(id + '_sparkline_tooltip_div_text'); expect(ele.firstChild.textContent).toBe('Yazuka '); expect(ele.lastChild.textContent).toBe(' 3800'); ele = getIdElement(id); trigger.mouseLeaveEvent(ele); }); it('Sparkline category value type x values same checking', () => { sparkline.dataSource = [ { xval: 'God Hand', yval: 2900 }, { xval: 'God of War', yval: 3900 }, { xval: 'Uncharted', yval: 3500 }, { xval: 'Yazuka', yval: 3800 }, { xval: 'GTA V', yval: 2500 }, { xval: 'Tomb Rider', yval: 3200 }, { xval: 'Sleeping Dogs', yval: 1800 }, { xval: 'Final Fantasy', yval: 5000 }, { xval: 'Uncharted', yval: 2900 }, ]; sparkline.fill = '#244af0'; sparkline.dataBind(); ele = getIdElement(id + '_sparkline_line'); expect(ele.getAttribute('stroke')).toBe('#244af0'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(31); expect(d[10]).toBe('174'); expect(d[13]).toBe('174'); expect(d[10]).toBe(d[13]); }); it('Sparkline category value type min X and max X checking', () => { expect(d[1]).toBe('5'); expect(d[28]).toBe('595'); }); it('Sparkline category value type min Y and max Y checking', () => { expect(d[26]).toBe('195'); expect(d[29]).toBe('5'); }); it('Sparkline category value type random point location checking', () => { expect(d[16]).toBe('258'); expect(d[17]).toBe('76'); }); it('Sparkline category value type y values negative checking', () => { sparkline.dataSource = [ { xval: 'God Hand', yval: -2900 }, { xval: 'God of War', yval: -3900 }, { xval: 'Uncharted', yval: -3500 }, { xval: 'Yazuka', yval: -3800 }, { xval: 'GTA V', yval: -2500 }, { xval: 'Tomb Rider', yval: -3200 }, { xval: 'Sleeping Dogs', yval: -1800 }, { xval: 'Final Fantasy', yval: -5000 }, ]; sparkline.fill = '#e915de'; sparkline.dataBind(); ele = getIdElement(id + '_sparkline_line'); expect(ele.getAttribute('stroke')).toBe('#e915de'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(28); }); it('Sparkline category value type y values negative min X and max X checking', () => { expect(d[1]).toBe('5'); expect(d[25]).toBe('595'); }); it('Sparkline category value type y values negative min Y and max Y checking', () => { expect(d[23]).toBe('5'); expect(d[26]).toBe('195'); }); it('Sparkline category value type y values negative random point location checking', () => { expect(d[16]).toBe('342'); expect(d[17]).toBe('47'); }); it('Sparkline category value type y values positive and negative checking', () => { sparkline.dataSource = [ { xval: 'God Hand', yval: -2900 }, { xval: 'God of War', yval: -3900 }, { xval: 'Uncharted', yval: 3500 }, { xval: 'Yazuka', yval: -3800 }, { xval: 'GTA V', yval: 2500 }, { xval: 'Tomb Rider', yval: -3200 }, { xval: 'Sleeping Dogs', yval: 1800 }, { xval: 'Final Fantasy', yval: -5000 }, ]; sparkline.fill = '#f78d15'; sparkline.dataBind(); ele = getIdElement(id + '_sparkline_line'); expect(ele.getAttribute('stroke')).toBe('#f78d15'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(28); }); it('Sparkline category value type y values positive and negative min X and max X checking', () => { expect(d[1]).toBe('5'); expect(d[25]).toBe('595'); }); it('Sparkline category value type y values positive and negative min Y and max Y checking', () => { expect(d[11]).toBe('5'); expect(d[26]).toBe('195'); }); it('Sparkline category value type y values positive and negative random point location checking', () => { expect(d[19]).toBe('426'); expect(d[20]).toBe('155'); }); it('Sparkline Date time axis value type checking with shuffled and same x values points', () => { sparkline.dataSource = [ {xDate: new Date(2017, 1, 1), yval: 2314585481 }, {xDate: new Date(2017, 5, 2), yval: 3905235430 }, {xDate: new Date(2017, 7, 3), yval: 4124124321 }, {xDate: new Date(2017, 9, 4), yval: 3804563235 }, {xDate: new Date(2017, 3, 5), yval: 6234234652 }, {xDate: new Date(2017, 6, 6), yval: 6343534513 }, {xDate: new Date(2017, 2, 7), yval: 5235435523 }, {xDate: new Date(2017, 8, 8), yval: 5013551546 }, {xDate: new Date(2017, 7, 3), yval: 3013551546 }, ]; sparkline.fill = '#f78d15'; sparkline.valueType = 'DateTime'; sparkline.xName = 'xDate'; sparkline.dataBind(); ele = getIdElement(id + '_sparkline_line'); expect(ele.getAttribute('stroke')).toBe('#f78d15'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(31); expect(d[19]).toBe(d[22]); expect(d[19]).toBe('446'); expect(d[20]).toBe('110'); expect(d[22]).toBe('446'); expect(d[23]).toBe('162'); }); it('Sparkline Date time axis value type checking min X and max X checking', () => { expect(d[1]).toBe('5'); expect(d[28]).toBe('595'); }); it('Sparkline Date time axis value type checking min Y and max Y checking', () => { expect(d[2]).toBe('195'); expect(d[17]).toBe('5'); }); it('Sparkline Date time axis value type checking random point location checking', () => { expect(d[10]).toBe('157'); expect(d[11]).toBe('10'); }); it('Sparkline Date time axis value type checking with all points are same x value points', () => { sparkline.dataSource = [ {xDate: new Date(2000, 5, 10), yval: 3145481 }, {xDate: new Date(2000, 5, 10), yval: 9055430 }, {xDate: new Date(2000, 5, 10), yval: 1244321 }, {xDate: new Date(2000, 5, 10), yval: 8043235 }, {xDate: new Date(2000, 5, 10), yval: 2344652 }, {xDate: new Date(2000, 5, 10), yval: 3434513 }, {xDate: new Date(2000, 5, 10), yval: 2355523 }, {xDate: new Date(2000, 5, 10), yval: 4131546 }, {xDate: new Date(2000, 5, 10), yval: 7131546 }, ]; sparkline.fill = '#12f7f7'; sparkline.dataBind(); ele = getIdElement(id + '_sparkline_line'); expect(ele.getAttribute('stroke')).toBe('#12f7f7'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(31); for (let i: number = 1; i < 31; i += 3) { expect(d[i]).toBe('300'); } }); it('Sparkline Date time axis value type checking with single point', () => { sparkline.dataSource = [ {xDate: new Date(2000, 5, 10), yval: 8043235 } ]; sparkline.fill = '#4fc04f'; sparkline.dataBind(); ele = getIdElement(id + '_sparkline_line'); expect(ele.getAttribute('stroke')).toBe('#4fc04f'); d = ele.getAttribute('d').split(' '); expect(d.length).toBe(7); expect(d[1]).toBe('300'); expect(d[2]).toBe('10'); expect(d[4]).toBe('300'); expect(d[5]).toBe('10'); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import {applyEdits, Edit, isPositionInsideRange, makeParseLoader, SourceRange, Warning} from 'polymer-analyzer'; import {Linter, registry, Rule} from 'polymer-linter'; import {CodeActionParams, Command, Diagnostic, DiagnosticSeverity, IConnection, TextDocuments, TextEdit, WorkspaceEdit} from 'vscode-languageserver'; import AnalyzerSynchronizer, {LsAnalyzer} from './analyzer-synchronizer'; import {applyEditCommandName} from './commands'; import AnalyzerLSPConverter from './converter'; import Settings from './settings'; import {Handler} from './util'; import minimatch = require('minimatch'); import {IMinimatch} from 'minimatch'; /** * Handles publishing diagnostics and code actions on those diagnostics. */ export default class DiagnosticGenerator extends Handler { private linter: Linter; private warningCodesToFilterOut: ReadonlySet<string> = new Set<string>(); private fileGlobsToFilterOut: ReadonlyArray<IMinimatch> = []; constructor( private analyzer: LsAnalyzer, private converter: AnalyzerLSPConverter, protected connection: IConnection, private settings: Settings, analyzerSynchronizer: AnalyzerSynchronizer, private documents: TextDocuments) { super(); this.updateLinter(); connection.onDidCloseTextDocument((event) => { if (!settings.analyzeWholePackage) { // If the user hasn't asked for whole-package analysis then it's // annoying to see warnings for files that aren't open, and in any // case, we'll never update those diagnostics while the file is closed. connection.sendDiagnostics( {diagnostics: [], uri: event.textDocument.uri}); } }); settings.projectConfigChangeStream.listen(() => { this.updateLinter(); }); this.disposables.push(analyzerSynchronizer.analysisChanges.listen(() => { this.reportWarnings(); })); settings.changeStream.listen(({newer, older}) => { if (newer.analyzeWholePackage !== older.analyzeWholePackage) { // When we switch this setting we want to be sure that we'll clear out // warnings that were reported with the old setting but not the new // one. if (newer.analyzeWholePackage) { this.urisReportedWarningsFor = new Set(this.documents.keys()); } else { for (const uri of this.urisReportedWarningsFor) { this.connection.sendDiagnostics({uri, diagnostics: []}); } } this.reportWarnings(); } }); this.connection.onCodeAction(async(req) => { return this.handleErrors(this.getCodeActions(req), []); }); this.connection.onWillSaveTextDocumentWaitUntil(async(req) => { if (this.settings.fixOnSave) { return this.handleErrors( this.getFixesForFile(req.textDocument.uri), []); } return []; }); } async getAllFixes(): Promise<WorkspaceEdit> { const {warnings, analysis} = await this.linter.lintPackage(); const fixes = []; for (const warning of warnings) { if (warning.fix) { fixes.push(warning.fix); } } // Don't apply conflicting edits to the workspace. const parseLoader = makeParseLoader(this.analyzer, analysis); const {appliedEdits} = await applyEdits(fixes, parseLoader); return this.converter.editsToWorkspaceEdit(appliedEdits); } private async getFixesForFile(uri: string): Promise<TextEdit[]> { const {warnings, analysis} = await this.linter.lint([uri]); const edits: Edit[] = []; for (const warning of warnings) { if (!warning.fix) { continue; } // A fix can touch multiple files. We can only update this document // though, so skip any fixes that touch others. if (warning.fix.some(repl => repl.range.file !== uri)) { continue; } edits.push(warning.fix); } const {appliedEdits} = await applyEdits(edits, makeParseLoader(this.analyzer, analysis)); const textEdits: TextEdit[] = []; for (const appliedEdit of appliedEdits) { for (const replacement of appliedEdit) { textEdits.push(TextEdit.replace( this.converter.convertPRangeToL(replacement.range), replacement.replacementText)); } } return textEdits; } private updateLinter() { let rules: Iterable<Rule> = new Set(); const projectConfig = this.settings.projectConfig; let configDiagnostic = this.settings.projectConfigDiagnostic; if (projectConfig.lint) { const lintConfig = projectConfig.lint; if (lintConfig.rules) { try { rules = registry.getRules(lintConfig.rules); } catch (e) { configDiagnostic = { code: 'linter-registry-error', message: e && e.message || '' + e, severity: DiagnosticSeverity.Error, source: 'polymer-ide', range: {start: {line: 0, character: 0}, end: {line: 0, character: 0}} }; } } this.warningCodesToFilterOut = new Set(lintConfig.ignoreWarnings); this.fileGlobsToFilterOut = (lintConfig.filesToIgnore || []).map(glob => new minimatch.Minimatch(glob, {})); } const polymerJsonDiagnostics = []; if (configDiagnostic) { polymerJsonDiagnostics.push(configDiagnostic); } this.connection.sendDiagnostics({ uri: this.converter.getUriForLocalPath('polymer.json'), diagnostics: polymerJsonDiagnostics }); const linter = new Linter(rules, this.analyzer); this.linter = linter; this.reportWarnings(); } /** * Used so that if we don't have any warnings to report for a file on the * next go around we can remember to send an empty array. */ private urisReportedWarningsFor = new Set<string>(); private async reportWarnings(): Promise<void> { if (this.settings.analyzeWholePackage) { return this.reportPackageWarnings( (await this.linter.lintPackage()).warnings); } else { return this.reportWarningsForOpenFiles(); } } private async reportWarningsForOpenFiles() { const openURIs = this.documents.keys(); const paths = openURIs.map(uri => this.converter.getWorkspacePathToFile({uri})) .filter( path => !this.fileGlobsToFilterOut.some(glob => glob.match(path))); const {warnings} = await this.linter.lint(paths); const diagnosticsByUri = new Map(openURIs.map((k): [string, Diagnostic[]] => [k, []])); for (const warning of this.filterWarnings(warnings)) { const diagnostic = this.converter.convertWarningToDiagnostic(warning); let diagnostics = diagnosticsByUri.get(warning.sourceRange.file) || []; diagnostics.push(diagnostic); diagnosticsByUri.set(warning.sourceRange.file, diagnostics); } // These diagnostics are reported elsewhere. diagnosticsByUri.delete(this.converter.getUriForLocalPath('polymer.json')); for (const [uri, diagnostics] of diagnosticsByUri) { this.connection.sendDiagnostics({uri, diagnostics}); } } private filterWarnings(warnings: ReadonlyArray<Warning>): ReadonlyArray<Warning> { return warnings.filter( w => !(this.warningCodesToFilterOut.has(w.code) || this.fileGlobsToFilterOut.some( glob => glob.match(this.converter.getWorkspacePathToFile( {uri: w.sourceRange.file}))))); } /** * Report the given warnings for the package implicitly defined by the * workspace. * * This is pulled out into its own non-async function to document and maintain * the invariant that there must not be an await between the initial read of * urisReportedWarningsFor and the write of it at the end. */ private reportPackageWarnings(warnings: ReadonlyArray<Warning>) { const reportedLastTime = new Set(this.urisReportedWarningsFor); this.urisReportedWarningsFor = new Set<string>(); const diagnosticsByUri = new Map<string, Diagnostic[]>(); for (const warning of this.filterWarnings(warnings)) { const uri = warning.sourceRange.file; reportedLastTime.delete(uri); this.urisReportedWarningsFor.add(uri); let diagnostics = diagnosticsByUri.get(uri); if (!diagnostics) { diagnostics = []; diagnosticsByUri.set(uri, diagnostics); } diagnostics.push(this.converter.convertWarningToDiagnostic(warning)); } diagnosticsByUri.delete(this.converter.getUriForLocalPath('polymer.json')); for (const [uri, diagnostics] of diagnosticsByUri) { this.connection.sendDiagnostics({uri, diagnostics}); } for (const uriWithNoWarnings of reportedLastTime) { this.connection.sendDiagnostics( {uri: uriWithNoWarnings, diagnostics: []}); } this.urisReportedWarningsFor = new Set(diagnosticsByUri.keys()); } private async getCodeActions(req: CodeActionParams) { const commands: Command[] = []; if (req.context.diagnostics.length === 0) { // Currently we only support code actions on Warnings, // so we can early-exit in the case where there aren't any. return commands; } const {warnings} = await this.linter.lint([req.textDocument.uri]); const requestedRange = this.converter.convertLRangeToP(req.range, req.textDocument); if (requestedRange === undefined) { return commands; } for (const warning of warnings) { if ((!warning.fix && (!warning.actions || warning.actions.length === 0)) || !isRangeInside(warning.sourceRange, requestedRange)) { continue; } if (warning.fix) { commands.push(this.createApplyEditCommand( `Quick fix the '${warning.code}' warning`, warning.fix)); } if (warning.actions) { for (const action of warning.actions) { if (action.kind !== 'edit') { continue; } commands.push(this.createApplyEditCommand( // Take up to the first newline. action.description.split('\n')[0], action.edit)); } } } return commands; } private createApplyEditCommand(title: string, edit: Edit): Command { return Command.create( title, applyEditCommandName, this.converter.editToWorkspaceEdit(edit)); } } function isRangeInside(inner: SourceRange, outer: SourceRange) { return isPositionInsideRange(inner.start, outer, true) && isPositionInsideRange(inner.end, outer, true); }
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 Resource class. * @constructor * The resource definition. * * @member {string} [id] Resource ID. * @member {string} [name] Resource name. * @member {string} [type] Resource type. */ export interface Resource extends BaseResource { readonly id?: string; readonly name?: string; readonly type?: string; } /** * @class * Initializes a new instance of the TrackedResource class. * @constructor * Definition of resource. * * @member {string} location Resource location. * @member {object} [tags] Resource tags. */ export interface TrackedResource extends Resource { location: string; tags?: { [propertyName: string]: string }; } /** * @class * Initializes a new instance of the ResourceNamespacePatch class. * @constructor * Definition of resource. * * @member {object} [tags] Resource tags. */ export interface ResourceNamespacePatch extends Resource { tags?: { [propertyName: string]: string }; } /** * @class * Initializes a new instance of the HybridConnection class. * @constructor * Description of hybrid connection resource. * * @member {date} [createdAt] The time the hybrid connection was created. * @member {date} [updatedAt] The time the namespace was updated. * @member {number} [listenerCount] The number of listeners for this hybrid * connection. Note that min : 1 and max:25 are supported. * @member {boolean} [requiresClientAuthorization] Returns true if client * authorization is needed for this hybrid connection; otherwise, false. * @member {string} [userMetadata] The usermetadata is a placeholder to store * user-defined string data for the hybrid connection endpoint. For example, it * can be used to store descriptive data, such as a list of teams and their * contact information. Also, user-defined configuration settings can be * stored. */ export interface HybridConnection extends Resource { readonly createdAt?: Date; readonly updatedAt?: Date; readonly listenerCount?: number; requiresClientAuthorization?: boolean; userMetadata?: string; } /** * @class * Initializes a new instance of the WcfRelay class. * @constructor * Description of the WCF relay resource. * * @member {boolean} [isDynamic] Returns true if the relay is dynamic; * otherwise, false. * @member {date} [createdAt] The time the WCF relay was created. * @member {date} [updatedAt] The time the namespace was updated. * @member {number} [listenerCount] The number of listeners for this relay. * Note that min :1 and max:25 are supported. * @member {string} [relayType] WCF relay type. Possible values include: * 'NetTcp', 'Http' * @member {boolean} [requiresClientAuthorization] Returns true if client * authorization is needed for this relay; otherwise, false. * @member {boolean} [requiresTransportSecurity] Returns true if transport * security is needed for this relay; otherwise, false. * @member {string} [userMetadata] The usermetadata is a placeholder to store * user-defined string data for the WCF Relay endpoint. For example, it can be * used to store descriptive data, such as list of teams and their contact * information. Also, user-defined configuration settings can be stored. */ export interface WcfRelay extends Resource { readonly isDynamic?: boolean; readonly createdAt?: Date; readonly updatedAt?: Date; readonly listenerCount?: number; relayType?: string; requiresClientAuthorization?: boolean; requiresTransportSecurity?: boolean; userMetadata?: string; } /** * @class * Initializes a new instance of the Sku class. * @constructor * SKU of the namespace. * * @member {string} [tier] The tier of this SKU. Possible values include: * 'Standard' */ export interface Sku { tier?: string; } /** * @class * Initializes a new instance of the RelayNamespace class. * @constructor * Description of a namespace resource. * * @member {object} [sku] SKU of the namespace. * @member {string} [sku.tier] The tier of this SKU. Possible values include: * 'Standard' * @member {string} [provisioningState] Possible values include: 'Created', * 'Succeeded', 'Deleted', 'Failed', 'Updating', 'Unknown' * @member {date} [createdAt] The time the namespace was created. * @member {date} [updatedAt] The time the namespace was updated. * @member {string} [serviceBusEndpoint] Endpoint you can use to perform * Service Bus operations. * @member {string} [metricId] Identifier for Azure Insights metrics. */ export interface RelayNamespace extends TrackedResource { sku?: Sku; readonly provisioningState?: string; readonly createdAt?: Date; readonly updatedAt?: Date; readonly serviceBusEndpoint?: string; readonly metricId?: string; } /** * @class * Initializes a new instance of the RelayUpdateParameters class. * @constructor * Description of a namespace resource. * * @member {object} [sku] SKU of the namespace. * @member {string} [sku.tier] The tier of this SKU. Possible values include: * 'Standard' * @member {string} [provisioningState] Possible values include: 'Created', * 'Succeeded', 'Deleted', 'Failed', 'Updating', 'Unknown' * @member {date} [createdAt] The time the namespace was created. * @member {date} [updatedAt] The time the namespace was updated. * @member {string} [serviceBusEndpoint] Endpoint you can use to perform * Service Bus operations. * @member {string} [metricId] Identifier for Azure Insights metrics. */ export interface RelayUpdateParameters extends ResourceNamespacePatch { sku?: Sku; readonly provisioningState?: string; readonly createdAt?: Date; readonly updatedAt?: Date; readonly serviceBusEndpoint?: string; readonly metricId?: string; } /** * @class * Initializes a new instance of the AuthorizationRule class. * @constructor * Description of a namespace authorization rule. * * @member {array} [rights] The rights associated with the rule. */ export interface AuthorizationRule extends Resource { rights?: string[]; } /** * @class * Initializes a new instance of the AccessKeys class. * @constructor * Namespace/Relay Connection String * * @member {string} [primaryConnectionString] Primary connection string of the * created namespace authorization rule. * @member {string} [secondaryConnectionString] Secondary connection string of * the created namespace authorization rule. * @member {string} [primaryKey] A base64-encoded 256-bit primary key for * signing and validating the SAS token. * @member {string} [secondaryKey] A base64-encoded 256-bit secondary key for * signing and validating the SAS token. * @member {string} [keyName] A string that describes the authorization rule. */ export interface AccessKeys { primaryConnectionString?: string; secondaryConnectionString?: string; primaryKey?: string; secondaryKey?: string; keyName?: string; } /** * @class * Initializes a new instance of the RegenerateAccessKeyParameters class. * @constructor * Parameters supplied to the regenerate authorization rule operation, * specifies which key neeeds to be reset. * * @member {string} keyType The access key to regenerate. Possible values * include: 'PrimaryKey', 'SecondaryKey' * @member {string} [key] Optional. If the key value is provided, this is set * to key type, or autogenerated key value set for key type. */ export interface RegenerateAccessKeyParameters { keyType: string; key?: string; } /** * @class * Initializes a new instance of the CheckNameAvailability class. * @constructor * Description of the check name availability request properties. * * @member {string} name The namespace name to check for availability. The * namespace name can contain only letters, numbers, and hyphens. The namespace * must start with a letter, and it must end with a letter or number. */ export interface CheckNameAvailability { name: string; } /** * @class * Initializes a new instance of the CheckNameAvailabilityResult class. * @constructor * Description of the check name availability request properties. * * @member {string} [message] The detailed info regarding the reason associated * with the namespace. * @member {boolean} [nameAvailable] Value indicating namespace is available. * Returns true if the namespace is available; otherwise, false. * @member {string} [reason] The reason for unavailability of a namespace. * Possible values include: 'None', 'InvalidName', 'SubscriptionIsDisabled', * 'NameInUse', 'NameInLockdown', 'TooManyNamespaceInCurrentSubscription' */ export interface CheckNameAvailabilityResult { readonly message?: string; nameAvailable?: boolean; reason?: string; } /** * @class * Initializes a new instance of the OperationDisplay class. * @constructor * The object that represents the operation. * * @member {string} [provider] Service provider: Relay. * @member {string} [resource] Resource on which the operation is performed: * Invoice, etc. * @member {string} [operation] Operation type: Read, write, delete, etc. */ export interface OperationDisplay { readonly provider?: string; readonly resource?: string; readonly operation?: string; } /** * @class * Initializes a new instance of the Operation class. * @constructor * A Relay REST API operation. * * @member {string} [name] Operation name: {provider}/{resource}/{operation} * @member {object} [display] The object that represents the operation. * @member {string} [display.provider] Service provider: Relay. * @member {string} [display.resource] Resource on which the operation is * performed: Invoice, etc. * @member {string} [display.operation] Operation type: Read, write, delete, * etc. */ export interface Operation { readonly name?: string; display?: OperationDisplay; } /** * @class * Initializes a new instance of the ErrorResponse class. * @constructor * Error reponse indicates Relay service is not able to process the incoming * request. The reason is provided in the error message. * * @member {string} [code] Error code. * @member {string} [message] Error message indicating why the operation * failed. */ export interface ErrorResponse { code?: string; message?: string; } /** * @class * Initializes a new instance of the OperationListResult class. * @constructor * Result of the request to list Relay operations. It contains a list of * operations and a URL link to get the next set of results. * * @member {string} [nextLink] URL to get the next set of operation list * results if there are any. */ export interface OperationListResult extends Array<Operation> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the RelayNamespaceListResult class. * @constructor * The response from the list namespace operation. * * @member {string} [nextLink] Link to the next set of results. Not empty if * value contains incomplete list of namespaces. */ export interface RelayNamespaceListResult extends Array<RelayNamespace> { nextLink?: string; } /** * @class * Initializes a new instance of the AuthorizationRuleListResult class. * @constructor * The response from the list namespace operation. * * @member {string} [nextLink] Link to the next set of results. Not empty if * value contains incomplete list of authorization rules. */ export interface AuthorizationRuleListResult extends Array<AuthorizationRule> { nextLink?: string; } /** * @class * Initializes a new instance of the HybridConnectionListResult class. * @constructor * The response of the list hybrid connection operation. * * @member {string} [nextLink] Link to the next set of results. Not empty if * value contains incomplete list hybrid connection operation. */ export interface HybridConnectionListResult extends Array<HybridConnection> { nextLink?: string; } /** * @class * Initializes a new instance of the WcfRelaysListResult class. * @constructor * The response of the list WCF relay operation. * * @member {string} [nextLink] Link to the next set of results. Not empty if * value contains incomplete list of WCF relays. */ export interface WcfRelaysListResult extends Array<WcfRelay> { nextLink?: string; }
the_stack
interface glMatrix { EPSILON: number; ARRAY_TYPE: Float32Array | Array<number>; RANDOM: () => number; setMatrixArrayType<T>(type: T): void; toRadian(a: number): number; } declare var glMatrix: glMatrix; interface vec2 { create(): Float32Array; clone(a: Float32Array): Float32Array; fromValues(x: number, y: number): Float32Array; copy(out: Float32Array, a: Float32Array): Float32Array; set(out: Float32Array, x: number, y: number): Float32Array; add(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; subtract(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; sub(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; multiply(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; mul(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; divide(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; div(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; min(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; max(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; scale(out: Float32Array, a: Float32Array, b: number): Float32Array; scaleAndAdd(out: Float32Array, a: Float32Array, b: Float32Array, scale: number): Float32Array; distance(a: Float32Array, b: Float32Array): number; dist(a: Float32Array, b: Float32Array): number; squaredDistance(a: Float32Array, b: Float32Array): number; sqrDist(a: Float32Array, b: Float32Array): number; length(a: Float32Array): number; len(a: Float32Array): number; squaredLength(a: Float32Array): number; sqrLen(a: Float32Array): number; negate(out: Float32Array, a: Float32Array): Float32Array; inverse(out: Float32Array, a: Float32Array): Float32Array; normalize(out: Float32Array, a: Float32Array): Float32Array; dot(a: Float32Array, b: Float32Array): number; cross(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; lerp(out: Float32Array, a: Float32Array, b: Float32Array, t: number): Float32Array; random(out: Float32Array, scale: number): Float32Array; transformMat2(out: Float32Array, a: Float32Array, m: Float32Array): Float32Array; transformMat2d(out: Float32Array, a: Float32Array, m: Float32Array): Float32Array; transformMat3(out: Float32Array, a: Float32Array, m: Float32Array): Float32Array; transformMat4(out: Float32Array, a: Float32Array, m: Float32Array): Float32Array; forEach<T>(a: Float32Array[], stride: number, offset: number, count: number, fn: (a: Float32Array, b: Float32Array, arg: T) => void, arg: T): Float32Array[]; str(a: Float32Array): string; } declare var vec2: vec2; interface vec3 { create(): Float32Array; clone(a: Float32Array): Float32Array; fromValues(x: number, y: number, z: number): Float32Array; copy(out: Float32Array, a: Float32Array): Float32Array; set(out: Float32Array, x: number, y: number, z: number): Float32Array; add(out: Float32Array, a: Float32Array, b: any): Float32Array; subtract(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; sub(out: Float32Array, a: Float32Array, b: any): Float32Array; multiply(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; mul(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; divide(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; div(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; min(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; max(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; scale(out: Float32Array, a: Float32Array, b: number): Float32Array; scaleAndAdd(out: Float32Array, a: Float32Array, b: Float32Array, scale: number): Float32Array; distance(a: Float32Array, b: Float32Array): number; dist(a: Float32Array, b: Float32Array): number; squaredDistance(a: Float32Array, b: Float32Array): number; sqrDist(a: Float32Array, b: Float32Array): number; length(a: Float32Array): number; len(a: Float32Array): number; squaredLength(a: Float32Array): number; sqrLen(a: Float32Array): number; negate(out: Float32Array, a: Float32Array): Float32Array; inverse(out: Float32Array, a: Float32Array): Float32Array; normalize(out: Float32Array, a: Float32Array): Float32Array; dot(a: Float32Array, b: Float32Array): number; cross(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; lerp(out: Float32Array, a: Float32Array, b: Float32Array, t: number): Float32Array; hermite(out: Float32Array, a: Float32Array, b: Float32Array, c: Float32Array, d: Float32Array, t: number): Float32Array; bezier(out: Float32Array, a: Float32Array, b: Float32Array, c: Float32Array, d: Float32Array, t: number): Float32Array; random(out: Float32Array, scale: number): Float32Array; transformMat4(out: Float32Array, a: Float32Array, m: Float32Array): Float32Array; transformMat3(out: Float32Array, a: Float32Array, m: Float32Array): Float32Array; transformQuat(out: Float32Array, a: Float32Array, q: Float32Array): Float32Array; rotateX(out: Float32Array, a: Float32Array, b: Float32Array, c: number): Float32Array; rotateY(out: Float32Array, a: Float32Array, b: Float32Array, c: number): Float32Array; rotateZ(out: Float32Array, a: Float32Array, b: Float32Array, c: number): Float32Array; forEach<T>(a: Float32Array[], stride: number, offset: number, count: number, fn: (a: Float32Array, b: Float32Array, arg: T) => void, arg: T): Float32Array[]; angle(a: Float32Array, b: Float32Array): number; str(a: Float32Array): string; } declare var vec3: vec3; interface vec4 { create(): Float32Array; clone(a: Float32Array): Float32Array; fromValues(x: number, y: number, z: number, w: number): Float32Array; copy(out: Float32Array, a: Float32Array): Float32Array; set(out: Float32Array, x: number, y: number, z: number, w: number): Float32Array; add(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; subtract(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; sub(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; multiply(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; mul(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; divide(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; div(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; min(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; max(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; scale(out: Float32Array, a: Float32Array, b: number): Float32Array; scaleAndAdd(out: Float32Array, a: Float32Array, b: Float32Array, scale: number): Float32Array; distance(a: Float32Array, b: Float32Array): number; dist(a: Float32Array, b: Float32Array): number; squaredDistance(a: Float32Array, b: Float32Array): number; sqrDist(a: Float32Array, b: Float32Array): number; length(a: Float32Array): number; len(a: Float32Array): number; squaredLength(a: Float32Array): number; sqrLen(a: Float32Array): number; negate(out: Float32Array, a: Float32Array): Float32Array; inverse(out: Float32Array, a: Float32Array): Float32Array; normalize(out: Float32Array, a: Float32Array): Float32Array; dot(a: Float32Array, b: Float32Array): number; lerp(out: Float32Array, a: Float32Array, b: Float32Array, t: number): Float32Array; random(out: Float32Array, scale: number): Float32Array; transformMat4(out: Float32Array, a: Float32Array, m: Float32Array): Float32Array; transformQuat(out: Float32Array, a: Float32Array, q: Float32Array): Float32Array; forEach<T>(a: Float32Array[], stride: number, offset: number, count: number, fn: (a: Float32Array, b: Float32Array, arg: T) => void, arg: T): Float32Array[]; str(a: Float32Array): string; } declare var vec4: vec4; interface mat2 { create(): Float32Array; clone(a: Float32Array): Float32Array; copy(out: Float32Array, a: Float32Array): Float32Array; identity(out: Float32Array): Float32Array; transpose(out: Float32Array, a: Float32Array): Float32Array; invert(out: Float32Array, a: Float32Array): Float32Array; adjoint(out: Float32Array, a: Float32Array): Float32Array; determinant(a: Float32Array): number; multiply(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; mul(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; rotate(out: Float32Array, a: Float32Array, rad: number): Float32Array; scale(out: Float32Array, a: Float32Array, v: Float32Array): Float32Array; fromRotation(out: Float32Array, rad: number): Float32Array; fromScaling(out: Float32Array, v: Float32Array): Float32Array; str(a: Float32Array): string; frob(a: Float32Array): number; LDU(L: Float32Array, D: Float32Array, U: Float32Array, a: Float32Array): Float32Array[]; } declare var mat2: mat2; interface mat2d { create(): Float32Array; clone(a: Float32Array): Float32Array; copy(out: Float32Array, a: Float32Array): Float32Array; identity(out: Float32Array): Float32Array; invert(out: Float32Array, a: Float32Array): Float32Array; determinant(a: Float32Array): number; multiply(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; mul(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; rotate(out: Float32Array, a: Float32Array, rad: number): Float32Array; scale(out: Float32Array, a: Float32Array, v: Float32Array): Float32Array; translate(out: Float32Array, a: Float32Array, v: Float32Array): Float32Array; fromRotation(out: Float32Array, rad: number): Float32Array; fromScaling(out: Float32Array, v: Float32Array): Float32Array; fromTranslation(out: Float32Array, v: Float32Array): Float32Array; str(a: Float32Array): string; frob(a: Float32Array): number; } declare var mat2d: mat2d; interface mat3 { create(): Float32Array; fromMat4(out: Float32Array, a: Float32Array): Float32Array; clone(a: Float32Array): Float32Array; copy(out: Float32Array, a: Float32Array): Float32Array; identity(out: Float32Array): Float32Array; transpose(out: Float32Array, a: Float32Array): Float32Array; invert(out: Float32Array, a: Float32Array): Float32Array; adjoint(out: Float32Array, a: Float32Array): Float32Array; determinant(a: Float32Array): number; multiply(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; mul(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; translate(out: Float32Array, a: Float32Array, v: Float32Array): Float32Array; rotate(out: Float32Array, a: Float32Array, rad: number): Float32Array; scale(out: Float32Array, a: Float32Array, v: Float32Array): Float32Array; fromTranslation(out: Float32Array, v: Float32Array): Float32Array; fromRotation(out: Float32Array, rad: number): Float32Array; fromScaling(out: Float32Array, v: Float32Array): Float32Array; fromMat2d(out: Float32Array, a: Float32Array): Float32Array; fromQuat(out: Float32Array, q: Float32Array): Float32Array; normalFromMat4(out: Float32Array, a: Float32Array): Float32Array; str(a: Float32Array): string; frob(a: Float32Array): number; } declare var mat3: mat3; interface mat4 { create(): Float32Array; clone(a: Float32Array): Float32Array; copy(out: Float32Array, a: Float32Array): Float32Array; identity(out: Float32Array): Float32Array; transpose(out: Float32Array, a: Float32Array): Float32Array; invert(out: Float32Array, a: Float32Array): Float32Array; adjoint(out: Float32Array, a: Float32Array): Float32Array; determinant(a: Float32Array): number; multiply(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; mul(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; translate(out: Float32Array, a: Float32Array, v: any): Float32Array; scale(out: Float32Array, a: Float32Array, v: Float32Array): Float32Array; rotate(out: Float32Array, a: Float32Array, rad: number, axis: Float32Array): Float32Array; rotateX(out: Float32Array, a: Float32Array, rad: number): Float32Array; rotateY(out: Float32Array, a: Float32Array, rad: number): Float32Array; rotateZ(out: Float32Array, a: Float32Array, rad: number): Float32Array; fromTranslation(out: Float32Array, v: Float32Array): Float32Array; fromScaling(out: Float32Array, v: Float32Array): Float32Array; fromRotation(out: Float32Array, rad: number, axis: Float32Array): Float32Array; fromXRotation(out: Float32Array, rad: number): Float32Array; fromYRotation(out: Float32Array, rad: number): Float32Array; fromZRotation(out: Float32Array, rad: number): Float32Array; fromRotationTranslation(out: Float32Array, q: Float32Array, v: Float32Array): Float32Array; fromRotationTranslationScale(out: Float32Array, q: Float32Array, v: Float32Array, s: Float32Array): Float32Array; fromRotationTranslationScaleOrigin(out: Float32Array, q: Float32Array, v: Float32Array, s: Float32Array, o: Float32Array): Float32Array; fromQuat(out: Float32Array, q: Float32Array): Float32Array; frustum(out: Float32Array, left: number, right: number, bottom: number, top: number, near: number, far: number): Float32Array; perspective(out: Float32Array, fovy: number, aspect: number, near: number, far: number): Float32Array; perspectiveFromFieldOfView(out: Float32Array, fov: number, near: number, far: number): Float32Array; ortho(out: Float32Array, left: number, right: number, bottom: number, top: number, near: number, far: number): Float32Array; lookAt(out: Float32Array, eye: Float32Array, center: Float32Array, up: Float32Array): Float32Array; str(a: Float32Array): string; frob(a: Float32Array): number; } declare var mat4: mat4; interface quat { create(): Float32Array; rotationTo(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; setAxes(out: Float32Array, view: Float32Array, right: Float32Array, up: Float32Array): Float32Array; clone(a: Float32Array): Float32Array; fromValues(x: number, y: number, z: number, w: number): Float32Array; copy(out: Float32Array, a: Float32Array): Float32Array; set(out: Float32Array, x: number, y: number, z: number, w: number): Float32Array; identity(out: Float32Array): Float32Array; setAxisAngle(out: Float32Array, axis: Float32Array, rad: number): Float32Array; add(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; multiply(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; mul(out: Float32Array, a: Float32Array, b: Float32Array): Float32Array; scale(out: Float32Array, a: Float32Array, b: number): Float32Array; rotateX(out: Float32Array, a: Float32Array, rad: number): Float32Array; rotateY(out: Float32Array, a: Float32Array, rad: number): Float32Array; rotateZ(out: Float32Array, a: Float32Array, rad: number): Float32Array; calculateW(out: Float32Array, a: Float32Array): Float32Array; dot(a: Float32Array, b: Float32Array): number; lerp(out: Float32Array, a: Float32Array, b: Float32Array, t: number): Float32Array; slerp(out: Float32Array, a: Float32Array, b: Float32Array, t: number): Float32Array; sqlerp(out: Float32Array, a: Float32Array, b: Float32Array, c: Float32Array, d: Float32Array, t: number): Float32Array; invert(out: Float32Array, a: Float32Array): Float32Array; conjugate(out: Float32Array, a: Float32Array): Float32Array; length(a: Float32Array): number; len(a: Float32Array): number; squaredLength(a: Float32Array): number; sqrLen(a: Float32Array): number; normalize(out: Float32Array, a: Float32Array): Float32Array; fromMat3(out: Float32Array, m: Float32Array): Float32Array; str(a: Float32Array): string; } declare var quat: quat;
the_stack
import ParamTypeServiceInstance from "../../sevices/ParamTypeService"; import DebugWorkProviderInstance from "../WorkProvider/DebugWorkProvider"; import CommonUtils from "../../utils/CommonUtils"; import StringUtils from "../../utils/StringUtils"; import CanvasUtils from "../../utils/CanvasUtils"; import logger from "../../utils/Logger"; import { BlockGraphDocunment, BlockGraphVariable } from "../Define/BlockDocunment"; import { BlockParameterEnumRegData, BlockParameterTypeConverterData, BlockRegData } from "../Define/BlockDef"; import { BlockPort } from "../Define/Port"; import { BlockEditor } from "../Editor/BlockEditor"; import { Block } from "../Define/Block"; import { BlockRunContextData } from "../Runner/BlockRunContextData"; import { BlockParameterType, cloneParameterTypeFromString, createParameterTypeFromString } from "../Define/BlockParameterType"; import { Vector2 } from "../Vector2"; import { Rect } from "../Rect"; import BlockRegister from "./Utils/BlockRegister"; import BlockServiceInstance from "@/sevices/BlockService"; export default { register, getScriptBaseBlockIn() { return blockIn; }, getScriptBaseBlockOut() { return blockOut; }, getScriptBaseGraphIn() { return graphIn; }, getScriptBaseGraphOut() { return graphOut; }, getScriptBaseGraphCall() { return graphCall; }, getScriptBaseVariableGet() { return variableGet; }, getScriptBaseVariableSet() { return variableSet; }, getScriptBaseCommentBlock() { return commentBlock; }, getScriptBaseConvertBlock() { return convertBlock; }, packageName: 'Base', version: 1, } function register() { //注册转换方法 registerBaseConverters(); return registerScriptBase().concat( registerScriptGraphBase(), registerScriptVariableBase(), registerDebugBase(), registerTypeBase(), registerLoadLib(), registerCommentBlock(), registerConvertBlock(), registerConnBlock(), ); } function registerBaseConverters() { let anyStringConverter = (v : any) => { return '' + v }; ParamTypeServiceInstance.registerTypeCoverter({ fromType: createParameterTypeFromString('number'), toType: createParameterTypeFromString('string'), allowSetType: 'variable', converter: anyStringConverter }); ParamTypeServiceInstance.registerTypeCoverter({ fromType: createParameterTypeFromString('bigint'), toType: createParameterTypeFromString('string'), allowSetType: 'variable', converter: anyStringConverter }); ParamTypeServiceInstance.registerTypeCoverter({ fromType: createParameterTypeFromString('boolean'), toType: createParameterTypeFromString('string'), allowSetType: 'variable', converter: anyStringConverter }); ParamTypeServiceInstance.registerTypeCoverter({ fromType: createParameterTypeFromString('object'), toType: createParameterTypeFromString('string'), allowSetType: 'variable', converter: anyStringConverter }); ParamTypeServiceInstance.registerTypeCoverter({ fromType: createParameterTypeFromString('string'), toType: createParameterTypeFromString('number'), allowSetType: 'variable', converter: (v) => parseFloat(v) }); ParamTypeServiceInstance.registerTypeCoverter({ fromType: createParameterTypeFromString('string'), toType: createParameterTypeFromString('boolean'), allowSetType: 'variable', converter: (v : string) => !StringUtils.isNullOrEmpty(v) && (v.toLowerCase() == 'true') }); ParamTypeServiceInstance.registerTypeCoverter({ fromType: createParameterTypeFromString('any'), toType: createParameterTypeFromString('string'), allowSetType: 'variable', converter: (v : any) => v + '' }); } let blockIn : BlockRegData; let blockOut : BlockRegData; let graphIn : BlockRegData; let graphOut : BlockRegData; let graphCall : BlockRegData; let variableGet : BlockRegData; let variableSet : BlockRegData; let commentBlock : BlockRegData; let convertBlock : BlockRegData; function registerScriptBase() { blockIn = new BlockRegData('0324C0EC-CE44-05B8-A62D-0ECE0D19DC9F', '脚本入口', '脚本在这里开始运行'); blockOut = new BlockRegData('77885802-92C8-569B-1E7F-48938943A549', '脚本出口', '调用此单元结束整个脚本的运行'); //运行库平台 //============================== let blockPlatform = new BlockRegData("522E5C4D-16E1-9D48-1916-19830B6F5B35", "运行库平台", "获取当前流图所在的运行库的平台", 'imengyu', '基础'); blockPlatform.blockStyle.logoBackground = 'title:运行库平台'; blockPlatform.blockStyle.minWidth = '140px'; blockPlatform.baseInfo.logo = require('../../assets/images/BlockIcon/switch.svg'); blockPlatform.baseInfo.version = '2.0'; blockPlatform.ports = [ { direction: 'output', guid: 'OUT', paramType: 'BasePlatformType', }, ]; blockPlatform.callbacks.onPortParamRequest = (block, port) => { return BlockServiceInstance.getCurrentPlatform(); }; blockPlatform.blockStyle.titleBakgroundColor = "rgba(255,20,147,0.6)"; blockPlatform.blockStyle.smallTitle = true; blockPlatform.blockStyle.noTitle = true; blockPlatform.blockStyle.hideLogo = true; //延时 //============================== let blockDelay = new BlockRegData("6C01D858-CF4D-D9EF-C18E-DE5DAE400702", "延时", '延迟流程图的运行', '基础', '基础'); blockDelay.baseInfo.version = '2.0'; blockDelay.baseInfo.logo = require('../../assets/images/BlockIcon/clock.svg'); blockDelay.ports = [ { name: "", description: '', direction: 'input', guid: 'IN', defaultConnectPort: false, paramType: 'execute', }, { direction: 'output', guid: 'OUT', executeInNewContext: true, defaultConnectPort: false, paramType: 'execute', }, { name: "时长", description: '延迟时长(毫秒)', direction: 'input', guid: 'TIME', paramType: 'number', paramDefaultValue: 1000, defaultConnectPort: false, }, ]; blockDelay.callbacks.onCreate = (block) => {}; blockDelay.callbacks.onPortExecuteIn = (block, port) => { let v = block.getInputParamValue('TIME'); let context = block.currentRunningContext; context.markContexInUse(); setTimeout(() => { block.activeOutputPortInNewContext('OUT'); context.unsetContexInUse(); }, v ? v : 1000); }; blockDelay.blockStyle.titleBakgroundColor = "rgba(120,200,254,0.6)"; blockDelay.blockStyle.logoRight = blockDelay.baseInfo.logo; //延时 //============================== let blockTimer = new BlockRegData("713EDD7E-8C92-099F-5CD7-A7E10FF77060", "定时器", '定时器用于定时执行某些任务', '基础', '基础'); blockTimer.baseInfo.version = '2.0'; blockTimer.baseInfo.logo = require('../../assets/images/BlockIcon/clock2.svg'); blockTimer.ports = [ { name: '开始', description: '开始定时器', direction: 'input', guid: 'START', defaultConnectPort: true, paramType: 'execute', }, { name: '停止', description: '停止定时器', direction: 'input', guid: 'STOP', defaultConnectPort: false, forceNoCycleDetection: true, paramType: 'execute', }, { direction: 'output', guid: 'OUT', executeInNewContext: true, defaultConnectPort: false, paramType: 'execute', }, { name: "时长", description: '周期时长(毫秒)', direction: 'input', guid: 'TIME', paramType: 'number', paramDefaultValue: 2000, defaultConnectPort: false, }, ]; blockTimer.callbacks.onCreate = (block) => {}; blockTimer.callbacks.onPortExecuteIn = (block, port) => { let context = block.currentRunningContext; let variables = block.variables(); switch(port.guid) { case 'START': { let v = block.getInputParamValue('TIME'); context.markContexInUse(); variables['intervalId'] = setInterval(() => { block.activeOutputPortInNewContext('OUT'); }, v ? v : 1000); break; } case 'STOP': { let id = variables['intervalId']; if(id) { context.unsetContexInUse(); clearInterval(id); variables['intervalId'] = undefined; } break; } } }; blockTimer.blockStyle.titleBakgroundColor = "rgba(120,200,254,0.6)"; blockTimer.blockStyle.logoRight = blockDelay.baseInfo.logo; //脚本出口 //============================== blockIn.baseInfo.author = 'imengyu'; blockIn.baseInfo.category = '基础/脚本'; blockIn.baseInfo.version = '2.0'; blockIn.baseInfo.logo = require('../../assets/images/BlockIcon/entry_go.svg'); blockIn.ports = [ { name: "脚本开始", direction: 'output', guid: 'START', defaultConnectPort: true, paramType: 'execute', }, ] blockIn.callbacks.onAddCheck = (blockRegData, graph) => { if(!graph.isMainGraph) return '只能在主图表中添加脚本开始单元'; return null; }; blockIn.settings.oneBlockOnly = true; blockIn.type = 'base'; blockIn.blockStyle.titleBakgroundColor = "rgba(25,25,112,0.6)"; //脚本入口 //============================== blockOut.baseInfo.author = 'imengyu'; blockOut.baseInfo.category = '基础/脚本'; blockOut.baseInfo.version = '2.0'; blockOut.baseInfo.logo = require('../../assets/images/BlockIcon/entry_exit.svg'); blockOut.ports = [ { name: "结束脚本", direction: 'input', guid: 'END', defaultConnectPort: false, paramType: 'execute', }, ] blockOut.callbacks.onPortExecuteIn = (block, port) => block.currentRunner.notifyEnd(block.currentRunningContext); blockOut.type = 'base'; blockOut.blockStyle.titleBakgroundColor = "rgba(112,30,133,0.6)"; return [ blockIn, blockOut, blockDelay, blockPlatform ]; } function registerScriptVariableBase() { variableGet = new BlockRegData("886A9FB9-095C-0708-B347-D2AEC6C59F05", "获取变量"); variableSet = new BlockRegData("1CD2A867-30A6-11CB-AC7F-47B524D3063D", "设置变量"); //获取变量 variableGet.baseInfo.author = 'imengyu'; variableGet.baseInfo.description = "获取变量的值"; variableGet.baseInfo.category = '基础'; variableGet.baseInfo.version = '2.0'; variableGet.type = 'base'; variableGet.callbacks.onCreate = (block) => { if(CommonUtils.isNullOrEmpty(block.options['variable'])) return; //添加端口 let variable = block.currentGraph.findGraphVariable(block.options['variable']); let port : BlockPort = null; block.data['variableReal'] = variable; block.data['portGuid'] = StringUtils.strToHexCharCode(block.options['variable'], false); if(variable != null) { port = block.addPort({ guid: block.data['portGuid'], direction: 'output', paramType: variable.type, paramDictionaryKeyType: variable.dictionaryKeyType, paramSetType: variable.setType, paramRefPassing: true, paramStatic: true, name: block.options['variable'], }, false, variable.defaultValue); block.data['variable_canuse'] = true; } }; variableGet.callbacks.onEditorCreate = (block) => { if(block.data['variable_canuse']) { let port = block.getPortByGUID(block.data['portGuid']); let variable = block.currentGraph.findGraphVariable(block.options['variable']); block.name = '获取变量 ' + variable.name + ' 的值'; block.blockStyleSettings.titleBakgroundColor = CanvasUtils.colorStrWithAlpha(ParamTypeServiceInstance.getTypeColor(variable.type.toString()), 0.3); block.data['onVariableRemove'] = block.editor.editorEvents.onVariableRemove.addListener(null, (graph, variable) => { if(graph == block.currentGraph && variable.name == block.options['variable']) block.editor.deleteBlock(block, true); }); block.data['onVariableUpdate'] = block.editor.editorEvents.onVariableUpdate.addListener(null, (graph, variableOldName, variable) => { if(graph == block.currentGraph && (variable.name == block.options['variable'] || variableOldName == block.options['variable'])) { block.options['variable'] = variable.name; port.paramType.set(variable.type); port.paramDefaultValue = variable.defaultValue; port.paramDictionaryKeyType.set(variable.dictionaryKeyType); port.paramSetType = variable.setType; port.name = variable.name; block.updatePort(port); } }); } else block.addBottomTip('icon-error-', '变量丢失,请重新添加', 'text-warning', true); }; variableGet.callbacks.onPortParamRequest = (block, port, context) => { let variableReal = <BlockGraphVariable>block.data['variableReal']; return variableReal.get(context); }; variableGet.callbacks.onDestroy = (block) => { let variable = block.currentGraph.findGraphVariable(block.options['variable']); if(variable != null) { if(block.isEditorBlock) { let blockEditor = (<BlockEditor>block); blockEditor.editor.editorEvents.onVariableUpdate.removeListener(<number>block.data['onVariableUpdate']); blockEditor.editor.editorEvents.onVariableRemove.removeListener(<number>block.data['onVariableRemove']); } } }; variableGet.blockStyle.titleBakgroundColor = "rgba(250,250,250,0.6)"; variableGet.blockStyle.noTitle = true; variableGet.settings.hideInAddPanel = true; //设置变量 variableSet.baseInfo.author = 'imengyu'; variableSet.baseInfo.description = "设置变量值"; variableSet.baseInfo.category = '基础'; variableSet.baseInfo.version = '2.0'; variableSet.type = 'base'; variableSet.ports = [ { guid: 'PI0', paramType: 'execute', direction: 'input' }, { guid: 'PO0', paramType: 'execute', direction: 'output' }, ]; variableSet.callbacks.onCreate = (block) => { //添加端口 let variable = block.currentGraph.findGraphVariable(block.options['variable']); let portOut : BlockPort = null; let portInGuid = StringUtils.strToHexCharCode(block.options['variable'] + '_I', false); let portOutGuid = StringUtils.strToHexCharCode(block.options['variable'] + '_O', false); block.data['variableReal'] = variable; block.data['portInGuid'] = portInGuid; block.data['portOutGuid'] = portOutGuid; if(variable != null) { block.addPort({ guid: portInGuid, direction: 'input', paramType: variable.type, paramDefaultValue: variable.defaultValue, paramDictionaryKeyType: variable.dictionaryKeyType, paramSetType: variable.setType, }, false, variable.defaultValue); portOut = block.addPort({ guid: portOutGuid, direction: 'output', paramType: variable.type, paramDictionaryKeyType: variable.dictionaryKeyType, paramSetType: variable.setType, paramRefPassing: true, name: block.options['variable'], }, false, variable.defaultValue); } block.data['variable_canuse'] = true; }; variableSet.callbacks.onEditorCreate = (block) => { if(block.data['variable_canuse']) { let portIn = block.getPortByGUID(block.data['portInGuid']); let portOut = block.getPortByGUID(block.data['portOutGuid']); let variable = block.currentGraph.findGraphVariable(block.options['variable']); block.name = '设置 ' + variable.name; block.blockStyleSettings.titleBakgroundColor = CanvasUtils.colorStrWithAlpha(ParamTypeServiceInstance.getTypeColor(variable.type.toString()), 0.3); block.data['onVariableRemove'] = block.editor.editorEvents.onVariableRemove.addListener(null, (graph, variable) => { if(graph == block.currentGraph && variable.name == block.options['variable']) block.editor.deleteBlock(block, true); }); block.data['onVariableUpdate'] = block.editor.editorEvents.onVariableUpdate.addListener(null, (graph, variableOldName, variable) => { if(graph == block.currentGraph && (variable.name == block.options['variable'] || variableOldName == block.options['variable'])) { block.options['variable'] = variable.name portIn.paramType.set(variable.type); portIn.paramDefaultValue = variable.defaultValue; portIn.paramDictionaryKeyType.set(variable.dictionaryKeyType); portIn.paramSetType = variable.setType; block.updatePort(portIn); portOut.paramType.set(variable.type); portOut.paramDefaultValue = variable.defaultValue; portOut.paramDictionaryKeyType.set(variable.dictionaryKeyType); portOut.name = variable.name; portOut.paramSetType = variable.setType; block.updatePort(portOut); block.name = '设置变量 ' + variable.name + ' 的值'; block.blockStyleSettings.titleBakgroundColor = CanvasUtils.colorStrWithAlpha(ParamTypeServiceInstance.getTypeColor(variable.type.toString()), 0.3); block.updateContent(); } }); } else block.addBottomTip('icon-error-', '变量丢失,请重新添加', 'text-warning', true); }; variableSet.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'PI0') { let variableReal = <BlockGraphVariable>block.data['variableReal']; if(variableReal != null) { let val = block.getInputParamValue(block.data['portInGuid']); variableReal.set(block.currentRunningContext, val); }else { logger.error(block.getName(),'变量 ' + block.options['variable'] + ' 未找到!'); } block.activeOutputPort('PO0'); } }; variableSet.callbacks.onPortParamRequest = (block, port, context) => { let variableReal = <BlockGraphVariable>block.data['variableReal']; let variable = variableReal.get(context || block.currentRunningContext); port.updateOnputValue(context, variable); return variable }; variableSet.callbacks.onDestroy = (block) => { let variable = block.currentGraph.findGraphVariable(block.options['variable']); if(variable != null) { if(block.isEditorBlock) { let blockEditor = (<BlockEditor>block); blockEditor.editor.editorEvents.onVariableUpdate.removeListener(<number>blockEditor.data['onVariableUpdate']); blockEditor.editor.editorEvents.onVariableRemove.removeListener(<number>blockEditor.data['onVariableRemove']); } } }; variableSet.blockStyle.minWidth = '180px'; variableSet.settings.hideInAddPanel = true; return [ variableSet, variableGet ] } function registerScriptGraphBase() { graphIn = new BlockRegData("CC4BE0CB-AA1D-7FD9-DF29-71701BE69254", "输入", '输入此图表', 'imengyu', '基础/脚本'); graphOut = new BlockRegData("6BA2899B-BD12-1E0B-D958-EB5C8C698319", "输出", '从此图表输出', 'imengyu', '基础/脚本'); graphCall = new BlockRegData("9EA376CE-492D-7EDD-4531-9B043CBAC707", "调用", '调用子图表', 'imengyu', '基础/脚本'); //输入 //=============================================================== graphIn.baseInfo.version = '2.0'; graphIn.baseInfo.logo = require('../../assets/images/BlockIcon/entry_go.svg'); graphIn.type = 'base'; graphIn.callbacks.onCreate = (block) => { block.currentGraph.inputPorts.forEach(element => block.addPort(element, false, element.paramDefaultValue, 'output')); }; graphIn.callbacks.onEditorCreate = (block) => { block.data['onGraphPortAdd'] = block.editor.editorEvents.onGraphPortAdd.addListener(null, (graph, port) => { port.paramRefPassing = true; if(graph == block.currentGraph && port.direction == 'input') block.addPort(port, false, port.paramDefaultValue, 'output'); }); block.data['onGraphPortRemove'] = block.editor.editorEvents.onGraphPortRemove.addListener(null, (graph, port) => { if(graph == block.currentGraph && port.direction == 'input') block.deletePort(port.guid); }); block.data['onGraphPortUpdate'] = block.editor.editorEvents.onGraphPortUpdate.addListener(null, (graph, port) => { if(graph == block.currentGraph && port.direction == 'input') { let portReal = block.getPortByGUID(port.guid); portReal.name = port.name; portReal.paramType = typeof port.paramType === 'string' ? createParameterTypeFromString(port.paramType) : <BlockParameterType>cloneParameterTypeFromString(port.paramType); portReal.paramDictionaryKeyType = typeof port.paramDictionaryKeyType === 'string' ? createParameterTypeFromString(port.paramDictionaryKeyType) : <BlockParameterType>cloneParameterTypeFromString(port.paramDictionaryKeyType); portReal.paramDefaultValue = port.paramDefaultValue; portReal.paramSetType = port.paramSetType; portReal.paramRefPassing = true; block.updatePort(portReal) } }); block.data['onGraphPortMoveDown'] = block.editor.editorEvents.onGraphPortMoveDown.addListener(null, (graph, port) => { if(graph == block.currentGraph && port.direction == 'input') block.movePortElementUpOrDown(block.getPortByGUID(port.guid), 'down'); }); block.data['onGraphPortMoveUp'] = block.editor.editorEvents.onGraphPortMoveUp.addListener(null, (graph, port) => { if(graph == block.currentGraph && port.direction == 'input') block.movePortElementUpOrDown(block.getPortByGUID(port.guid), 'up'); }); }; graphIn.callbacks.onDestroy = (block) => { if(block.isEditorBlock) { let blockEditor = (<BlockEditor>block); blockEditor.editor.editorEvents.onGraphPortAdd.removeListener(<number>blockEditor.data['onGraphPortAdd']); blockEditor.editor.editorEvents.onGraphPortRemove.removeListener(<number>blockEditor.data['onGraphPortRemove']); blockEditor.editor.editorEvents.onGraphPortUpdate.removeListener(<number>blockEditor.data['onGraphPortUpdate']); blockEditor.editor.editorEvents.onGraphPortMoveDown.removeListener(<number>blockEditor.data['onGraphPortMoveDown']); blockEditor.editor.editorEvents.onGraphPortMoveUp.removeListener(<number>blockEditor.data['onGraphPortMoveUp']); } }; graphIn.callbacks.onAddCheck = (b, graph) => { if(graph.isMainGraph) return '主图表不能有输入输出'; return null; }; graphIn.callbacks.onPortParamRequest = (block, port, context) => { //子上下文请求父上下文 let outerBlock = context.outerBlock; if(outerBlock == null) { logger.error(block.getName(), 'graphIn.onPortParamRequest.' + port.guid + ': Bad context ' + context + ' .'); return; } let outerPort = outerBlock.getPortByGUID(port.guid); let val = outerPort.rquestInputValue(context.getUpperParentContext()); port.updateOnputValue(context, val); return val; }; graphIn.settings.oneBlockOnly = true; graphIn.blockStyle.titleBakgroundColor = "rgba(250,250,250,0.6)"; //输出 //=============================================================== graphOut.baseInfo.version = '2.0'; graphOut.baseInfo.logo = require('../../assets/images/BlockIcon/entry_exit.svg'); graphOut.type = 'base'; graphOut.callbacks.onCreate = (block) => { block.currentGraph.outputPorts.forEach(element => block.addPort(element, false, element.paramDefaultValue, 'input')); }; graphOut.callbacks.onAddCheck = (b, graph) => { if(graph.isMainGraph) return '主图表不能有输入输出'; return null; }; graphOut.callbacks.onEditorCreate = (block) => { block.data['onGraphPortAdd'] = block.editor.editorEvents.onGraphPortAdd.addListener(null, (graph, port) => { if(graph == block.currentGraph && port.direction == 'output') block.addPort(port, false, port.paramDefaultValue, 'input'); }); block.data['onGraphPortRemove'] = block.editor.editorEvents.onGraphPortRemove.addListener(null, (graph, port) => { if(graph == block.currentGraph && port.direction == 'output') block.deletePort(port.guid); }); block.data['onGraphPortUpdate'] = block.editor.editorEvents.onGraphPortUpdate.addListener(null, (graph, port) => { if(graph == block.currentGraph && port.direction == 'output') { let portReal = block.getPortByGUID(port.guid); portReal.name = port.name; portReal.paramType = typeof port.paramType === 'string' ? createParameterTypeFromString(port.paramType) : <BlockParameterType>cloneParameterTypeFromString(port.paramType); portReal.paramDictionaryKeyType = typeof port.paramDictionaryKeyType === 'string' ? createParameterTypeFromString(port.paramDictionaryKeyType) : <BlockParameterType>cloneParameterTypeFromString(port.paramDictionaryKeyType); portReal.paramDefaultValue = port.paramDefaultValue; portReal.paramSetType = port.paramSetType; block.updatePort(portReal); } }); block.data['onGraphPortMoveDown'] = block.editor.editorEvents.onGraphPortMoveDown.addListener(null, (graph, port) => { if(graph == block.currentGraph && port.direction == 'output') block.movePortElementUpOrDown(block.getPortByGUID(port.guid), 'down'); }); block.data['onGraphPortMoveUp'] = block.editor.editorEvents.onGraphPortMoveUp.addListener(null, (graph, port) => { if(graph == block.currentGraph && port.direction == 'output') block.movePortElementUpOrDown(block.getPortByGUID(port.guid), 'up'); }); }; graphOut.callbacks.onPortExecuteIn = (block, port) => { //离开图表后恢复上下文 //---------------------------- let context = block.currentRunningContext; let outerBlock = context.outerBlock; if(outerBlock == null) { logger.error(block.getName(), 'leavePort.' + port.guid + ': Bad context ' + context + ' .'); return; } //获取父上下文 let parentContext = context.getUpperParentContext(); if(parentContext == null) { logger.error(block.getName(), 'leavePort: Bad context has emerged, in port: ' + block.guid + '-' + port.guid); return null; } //更新父上下文的所有输出端口 outerBlock.allPorts.forEach((port) => { if(port.direction == 'output' && !port.paramType.isExecute()) { let outerPort = outerBlock.getPortByGUID(port.guid); let val = outerPort.rquestInputValue(context); port.updateOnputValue(parentContext, val); } }); block.currentRunner.destroyGraphStack(context, block.currentGraph);//离开图表当前上下文数据无效了,清空 (<Array<any>>outerBlock.data['currentRunningContexts']).remove(context);//从图表正在运行的上下文中移除 //回到父上下文 outerBlock.currentRunningContext = parentContext; //激活外部单元 outerBlock.activeOutputPort(port.guid); }; graphOut.callbacks.onDestroy = (block) => { if(block.isEditorBlock) { let blockEditor = (<BlockEditor>block); blockEditor.editor.editorEvents.onGraphPortAdd.removeListener(<number>blockEditor.data['onGraphPortAdd']); blockEditor.editor.editorEvents.onGraphPortRemove.removeListener(<number>blockEditor.data['onGraphPortRemove']); blockEditor.editor.editorEvents.onGraphPortUpdate.removeListener(<number>blockEditor.data['onGraphPortUpdate']); blockEditor.editor.editorEvents.onGraphPortMoveDown.removeListener(<number>blockEditor.data['onGraphPortMoveDown']); blockEditor.editor.editorEvents.onGraphPortMoveUp.removeListener(<number>blockEditor.data['onGraphPortMoveUp']); } }; graphOut.settings.oneBlockOnly = true; graphOut.blockStyle.titleBakgroundColor = "rgba(250,250,250,0.6)"; //调用 //=============================================================== graphCall.baseInfo.version = '2.0'; graphCall.type = 'normal'; graphCall.callbacks.onCreate = (block) => { let currentGraph : BlockGraphDocunment = block.options['graph'] == block.currentGraph.name ? block.currentGraph : block.currentGraph.findChildGraph(block.options['graph']); block.data['currentGraph'] = currentGraph; if(currentGraph == null) return; currentGraph.inputPorts.forEach(element => block.addPort(element, false, element.paramDefaultValue, 'input')); currentGraph.outputPorts.forEach(element => block.addPort(element, false, element.paramDefaultValue, 'output')); block.data['currentRunningContexts'] = []; block.data['inBlock'] = currentGraph.getOneBlockByGUID(graphIn.guid); block.data['outBlock'] = currentGraph.getOneBlockByGUID(graphOut.guid); }; graphCall.callbacks.onEditorCreate = (block) => { let currentGraph = (<BlockGraphDocunment>block.data['currentGraph']); if(currentGraph == null) { block.addBottomTip('icon-error-1','没有找到子图表 ' + block.options['graph'],'text-warning'); return; } block.blockMenuSettings.items = [ { label: '编辑 ' + currentGraph.name, onClick: () => block.editor.openGraph(currentGraph) } ]; block.el.addEventListener('dblclick', (e : MouseEvent) => { if(e.button == 0) block.editor.openGraph(currentGraph); }); block.name = '调用子图表 ' + currentGraph.name; block.description = '调用一个子图表,并返回值\n' + currentGraph.name + '\n' + currentGraph.comment; block.data['onGraphPortAdd'] = block.editor.editorEvents.onGraphPortAdd.addListener(null, (graph, port) => { if(graph == currentGraph) block.addPort(port, false, port.paramDefaultValue, 'input'); }); block.data['onGraphPortRemove'] = block.editor.editorEvents.onGraphPortRemove.addListener(null, (graph, port) => { if(graph == currentGraph) block.deletePort(port.guid); }); block.data['onGraphPortUpdate'] = block.editor.editorEvents.onGraphPortUpdate.addListener(null, (graph, port) => { if(graph == currentGraph) { let portReal = block.getPortByGUID(port.guid); portReal.paramType = typeof port.paramType === 'string' ? createParameterTypeFromString(port.paramType) : <BlockParameterType>cloneParameterTypeFromString(port.paramType); portReal.paramDictionaryKeyType = typeof port.paramDictionaryKeyType === 'string' ? createParameterTypeFromString(port.paramDictionaryKeyType) : <BlockParameterType>cloneParameterTypeFromString(port.paramDictionaryKeyType); portReal.paramDefaultValue = port.paramDefaultValue; portReal.paramSetType = port.paramSetType; block.updatePort(portReal); } }); block.data['onGraphPortMoveDown'] = block.editor.editorEvents.onGraphPortMoveDown.addListener(null, (graph, port) => { if(graph == currentGraph) block.movePortElementUpOrDown(block.getPortByGUID(port.guid), 'down'); }); block.data['onGraphPortMoveUp'] = block.editor.editorEvents.onGraphPortMoveUp.addListener(null, (graph, port) => { if(graph == currentGraph) block.movePortElementUpOrDown(block.getPortByGUID(port.guid), 'up'); }); block.data['onGraphUpdate'] = block.editor.editorEvents.onGraphUpdate.addListener(null, (graph) => { if(graph == currentGraph) { block.name = '调用子图表 ' + currentGraph.name; block.description = '调用一个子图表,并返回值\n' + currentGraph.name + '\n' + currentGraph.comment; } }); block.data['onGraphDelete'] = block.editor.editorEvents.onGraphDelete.addListener(null, (graph) => { if(graph == currentGraph) block.editor.deleteBlock(block, true); }); }; graphCall.callbacks.onPortExecuteIn = (block, port) => { //进入图表新建上下文 let currentGraph = (<BlockGraphDocunment>block.data['currentGraph']); if(currentGraph != null) { let inBlock = block.data['inBlock']; if(inBlock == null) { logger.error(block.getName(), 'graph.call: Call graph ' + currentGraph.name + ' failed because it does not contain an entry unit.', { srcBlock: block, srcPort: port }); //提示 if(block.isEditorBlock) { if(block.data['currentGraphErrTip']) (<BlockEditor>block).deleteBottomTip(block.data['currentGraphErrTip']); block.data['currentGraphErrTip'] = (<BlockEditor>block).addBottomTip('icon-error-1','子图表 ' + block.options['graph'] + ' 没有入口!','text-warning'); } return; } let inPort = inBlock.getPortByGUID(port.guid); if(inPort == null) { logger.error(block.getName(), 'graph.call: Call graph ' + currentGraph.name + ' -> ' + port.guid + ' failed.', { srcBlock: block, srcPort: port }); return; } //新建上下文 let runner = block.currentRunner; let newContext = runner.push(inPort, block.currentRunningContext, 'activator'); newContext.graph = currentGraph; newContext.outerBlock = block; runner.prepareGraphVariables(newContext, currentGraph); runner.prepareGraphStack(newContext, currentGraph); runner.prepareAllBlockRun(newContext, currentGraph); //stackCalls block.currentRunningContext.stackCalls.push({ block: null, port: null, childContext: newContext }); //添加到集合 (<Array<any>>block.data['currentRunningContexts']).push(newContext); } }; graphCall.callbacks.onPortParamRequest = (block, port, context) => { //父上下文请求子上下文 let outBlock = block.data['outBlock']; if(outBlock == null) { logger.error(block.getName(), 'graph.onPortParamRequest: Request graph param failed because it does not contain an output unit.', { srcBlock: block, srcPort: port }); return undefined; } //子端口数据更新到父端口 let currentRunningContexts = (<Array<BlockRunContextData>>block.data['currentRunningContexts']); for(let i = 0; i < currentRunningContexts.length; i++) { if(currentRunningContexts[i].parentContext == context) { let outerPort = outBlock.getPortByGUID(port.guid); let val = outerPort.rquestInputValue(currentRunningContexts[i]); port.updateOnputValue(context, val); return val; } } return undefined; }; graphCall.callbacks.onDestroy = (block) => { if(block.isEditorBlock) { let blockEditor = (<BlockEditor>block); blockEditor.editor.editorEvents.onGraphPortAdd.removeListener(<number>blockEditor.data['onGraphPortAdd']); blockEditor.editor.editorEvents.onGraphPortRemove.removeListener(<number>blockEditor.data['onGraphPortRemove']); blockEditor.editor.editorEvents.onGraphPortUpdate.removeListener(<number>blockEditor.data['onGraphPortUpdate']); blockEditor.editor.editorEvents.onGraphPortMoveDown.removeListener(<number>blockEditor.data['onGraphPortMoveDown']); blockEditor.editor.editorEvents.onGraphPortMoveUp.removeListener(<number>blockEditor.data['onGraphPortMoveUp']); blockEditor.editor.editorEvents.onGraphDelete.removeListener(<number>blockEditor.data['onGraphDelete']); } }; graphCall.blockStyle.titleBakgroundColor = "rgba(250,250,250,0.6)"; graphCall.settings.hideInAddPanel = true; return [ graphIn, graphOut, graphCall ] } function registerDebugBase() { ParamTypeServiceInstance.registerCustomType(new BlockParameterEnumRegData("DebugLogLevel", [ 'log','info','warn','error' ], '#F7C709')); ParamTypeServiceInstance.registerCustomType(new BlockParameterEnumRegData("BasePlatformType", [ 'all','electron','nodejs','cnative' ], '#8552a1')); let blockDebug = new BlockRegData("4B6EA737-9702-A383-A268-AADC332038DF", "输出日志", '输出调试日志至控制台', '基础', '基础/调试'); let blockModal = new BlockRegData("CB1FB757-631D-8A95-0AB1-3CB28CB04FBC", "信息对话框(Alert)", '显示一个对话框', '基础', '基础/调试'); let blockConfirm = new BlockRegData("84AB5443-1998-B4FB-773A-5F41F364BB7A", "确认对话框(Confirm)", '显示一个确认对话框,用户可选择确认或取消', '基础', '基础/调试'); let blockTrace = new BlockRegData("31B04B93-FE15-4D35-B673-BDBEA8597547", "追踪(Trace)", '在控制台中打印当前执行的代码在堆栈中的调用路径', '基础', '基础/调试'); let blockAssert = new BlockRegData("F726A2CE-2285-A9D7-9252-9FC3EEAC7BDC", "断言(Assert)", '检查一个条件,如果条件不满足则抛出异常并终止流图的运行', '基础', '基础/调试'); //Assert //=================== blockAssert.baseInfo.logo = require('../../assets/images/BlockIcon/warning.svg'); blockAssert.baseInfo.version = '2.0'; blockAssert.ports = [ { direction: 'input', name: '进入', guid: 'IN', paramType: 'execute', }, { direction: 'input', name: '判断条件', guid: 'CONDITION', paramRefPassing: true, paramType: 'boolean', }, { direction: 'input', name: '抛出错误', description: '是否在条件为 false 时抛出错误并终止运行', guid: 'THROWERR', paramType: 'boolean', }, { direction: 'output', name: '成功', guid: 'SUCCESS', defaultConnectPort: false, paramType: 'execute', }, { direction: 'output', name: '失败', guid: 'FAILED', defaultConnectPort: false, paramType: 'execute', }, ]; blockAssert.callbacks.onPortExecuteIn = (block, port) => { let con = block.getInputParamValue('CONDITION'); let throwError = block.getInputParamValue('THROWERR'); if(con) block.activeOutputPort('SUCCESS'); else { if(throwError) block.throwError('条件断言失败!', port, 'error', true); else { block.throwError('条件断言失败!', port, 'warning', false); block.activeOutputPort('FAILED'); } } }; blockAssert.callbacks.onCreateCustomEditor = null; blockAssert.blockStyle.titleBakgroundColor = "rgba(120,200,254,0.6)"; //追踪 //=================== blockTrace.baseInfo.logo = require('../../assets/images/BlockIcon/trace.svg'); blockTrace.baseInfo.version = '2.0'; blockTrace.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, ]; blockTrace.callbacks.onPortExecuteIn = (block, port) => { //打印调用堆栈 logger.log(block.getName(), block.currentRunningContext.runner.mainContext.printCallStack(true)); block.activeOutputPort('OUT'); }; blockTrace.callbacks.onCreateCustomEditor = null; blockTrace.blockStyle.titleBakgroundColor = "rgba(120,200,254,0.6)"; //输出日志 //=================== blockDebug.baseInfo.version = '2.0'; blockDebug.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: false, paramType: 'execute', }, { direction: 'output', guid: 'OUT', defaultConnectPort: false, paramType: 'execute', }, { name: "标签", description: '可以定义一个输出标签,方便查找', direction: 'input', guid: 'TAG', paramType: 'string', paramDefaultValue: null, defaultConnectPort: false, }, { name: "输出", direction: 'input', guid: 'PRINT', paramType: 'any', paramDefaultValue: null, defaultConnectPort: false, }, { name: "等级", direction: 'input', guid: 'LEVEL', paramType: new BlockParameterType('enum', 'DebugLogLevel'), paramDefaultValue: 'log', defaultConnectPort: false, }, ]; blockDebug.callbacks.onCreate = (block) => { }; blockDebug.callbacks.onPortExecuteIn = (block, port) => { let paramInput = block.getInputParamValue('PRINT'); let paramLevel = block.getInputParamValue('LEVEL'); let paramTag = block.getInputParamValue('TAG'); let tag = CommonUtils.isNullOrEmpty(paramTag) ? block.getName() : paramTag; switch(paramLevel) { case 'log': logger.log(tag, paramInput, { srcBlock: block, srcPort: port }); break; case 'info': logger.info(tag, paramInput, { srcBlock: block, srcPort: port }); break; case 'warn': logger.warning(tag, paramInput, { srcBlock: block, srcPort: port }); break; case 'error': logger.error(tag, paramInput, { srcBlock: block, srcPort: port }); break; default: block.throwError('未知等级 ' + paramLevel + ',日志没有输出', port, 'warning'); break; } block.activeOutputPort('OUT'); }; blockDebug.callbacks.onCreateCustomEditor = null; blockDebug.callbacks.onCreate = (block : Block) => { let type = block.options['type']; if(!StringUtils.isNullOrEmpty(type)) { block.changePortParamType(block.getPortByGUID('PRINT'), undefined, type); } }; blockDebug.blockMenu.items.push({ label: '集合类型', children: [ { label: '变量', onClick: function() { this.changePortParamType(this.getPortByGUID('PRINT'), undefined, 'variable'); this.options['type'] = 'variable'; } }, { label: '数组', onClick: function() { this.changePortParamType(this.getPortByGUID('PRINT'), undefined, 'array'); this.options['type'] = 'array'; } }, { label: '集合', onClick: function() { this.changePortParamType(this.getPortByGUID('PRINT'), undefined, 'set'); this.options['type'] = 'set'; } }, { label: '映射', onClick: function() { this.changePortParamType(this.getPortByGUID('PRINT'), undefined, 'dictionary'); this.options['type'] = 'dictionary'; } }, ] }, { label: '重置输出类型', onClick: function() { this.changePortParamType(this.getPortByGUID('PRINT'), 'any', 'variable'); this.options['type'] = 'variable'; } }) blockDebug.blockStyle.titleBakgroundColor = "rgba(120,200,254,0.6)"; //显示一个信息对话框 //=================== blockModal.baseInfo.version = '2.0'; blockModal.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: false, paramType: 'execute', }, { direction: 'output', guid: 'OUT', executeInNewContext: true, defaultConnectPort: false, paramType: 'execute', }, { name: "标题", direction: 'input', guid: 'TITLE', paramType: 'string', defaultConnectPort: false, }, { name: "文字", direction: 'input', guid: 'TEXT', paramType: 'string', defaultConnectPort: false, }, { name: "等级", direction: 'input', guid: 'LEVEL', paramType: new BlockParameterType('enum', 'DebugLogLevel'), paramDefaultValue: 'log', defaultConnectPort: false, }, ]; blockModal.callbacks.onCreate = (block) => { }; blockModal.callbacks.onPortExecuteIn = (block, port) => { let paramText = block.getInputParamValue('TEXT'); let paramTitle = block.getInputParamValue('TITLE'); let paramLevel = block.getInputParamValue('LEVEL'); let context = block.currentRunningContext; context.markContexInUse(); DebugWorkProviderInstance.ModalProvider(<string>paramLevel, <string>paramTitle, <string>paramText, () => { context.unsetContexInUse(); block.activeOutputPortInNewContext('OUT'); }); }; blockModal.callbacks.onCreateCustomEditor = null; blockModal.blockStyle.titleBakgroundColor = "rgba(120,200,254,0.6)"; //显示一个确认对话框 //==================== blockConfirm.baseInfo.author = 'imengyu'; blockConfirm.baseInfo.description = ""; blockConfirm.baseInfo.category = '基础/调试'; blockConfirm.baseInfo.version = '2.0'; blockConfirm.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { name: "点击确认", description: '用户点击了确认按钮', direction: 'output', guid: 'OUTCON', executeInNewContext: true, defaultConnectPort: false, paramType: 'execute', }, { name: "点击取消", description: '用户点击了取消按钮', executeInNewContext: true, paramType: 'execute', direction: 'output', guid: 'OUTCAN', defaultConnectPort: false, }, { name: "标题", direction: 'input', guid: 'TITLE', paramType: 'string', defaultConnectPort: false, }, { name: "文字", direction: 'input', guid: 'TEXT', paramType: 'string', defaultConnectPort: false, }, ]; blockConfirm.callbacks.onCreate = (block) => { }; blockConfirm.callbacks.onPortExecuteIn = (block, port) => { let context = block.currentRunningContext; context.markContexInUse(); DebugWorkProviderInstance.ConfirmModalProvider(<string>block.getInputParamValue('TITLE'), <string>block.getInputParamValue('TEXT'), () => { block.activeOutputPortInNewContext('OUTCON'); context.unsetContexInUse(); }, () => { block.activeOutputPortInNewContext('OUTCAN'); context.unsetContexInUse(); }); }; blockConfirm.callbacks.onCreateCustomEditor = null; blockConfirm.blockStyle.titleBakgroundColor = "rgba(120,200,254,0.6)"; return [ blockDebug, blockConfirm, blockModal, blockAssert, blockTrace ] } function registerTypeBase() { let typeRequest = (block : Block, port : BlockPort, context : BlockRunContextData) => { let val = block.getInputParamValue('IN', context); port.updateOnputValue(context, val); return val; }; let blocks = []; let block = new BlockRegData("A81899CF-766B-F511-B179-90A81BBB088B", "字符串", "字符串 string 类型参数", 'imengyu', '基础/类型'); block.baseInfo.logo = require('../../assets/images/BlockIcon/string.svg'); block.baseInfo.version = '2.0'; block.ports = [ { direction: 'input', guid: 'IN', paramType: 'string', }, { direction: 'output', guid: 'OUT', paramType: 'string', }, ]; block.callbacks.onPortParamRequest = typeRequest; block.blockStyle.titleBakgroundColor = "rgba(255,20,147,0.6)"; block.blockStyle.smallTitle = true; block.blockStyle.noTitle = true; block.blockStyle.hideLogo = true; blocks.push(block); block = new BlockRegData("EE8345CE-14FB-3CE5-C5CD-30CF3A102DE5", "数字", "数字 number 类型参数", 'imengyu', '基础/类型'); block.baseInfo.logo = require('../../assets/images/BlockIcon/number.svg'); block.baseInfo.version = '2.0'; block.ports = [ { direction: 'input', guid: 'IN', paramType: 'number', paramDefaultValue: 0, }, { direction: 'output', guid: 'OUT', paramType: 'number', }, ]; block.callbacks.onPortParamRequest = typeRequest; block.blockStyle.titleBakgroundColor = "rgba(158,258,68,0.6)"; block.blockStyle.smallTitle = true; block.blockStyle.noTitle = true; block.blockStyle.hideLogo = true; blocks.push(block); block = new BlockRegData("90833609-8CF7-2324-A4C0-781344701C06", "布尔值", "布尔 boolean 类型参数", 'imengyu', '基础/类型'); block.baseInfo.logo = require('../../assets/images/BlockIcon/boolean.svg'); block.baseInfo.version = '2.0'; block.ports = [ { direction: 'input', guid: 'IN', paramType: 'boolean', paramDefaultValue: true, }, { direction: 'output', guid: 'OUT', paramType: 'boolean', }, ]; block.callbacks.onPortParamRequest = typeRequest; block.blockStyle.titleBakgroundColor = "rgba(180,0,0,0.6)"; block.blockStyle.smallTitle = true; block.blockStyle.noTitle = true; block.blockStyle.hideLogo = true; blocks.push(block); block = new BlockRegData("6CE4CA4F-E2F9-AD97-3F83-1B60289C9290", "BigInt", "BigInt 类型参数", 'imengyu', '基础/类型'); block.baseInfo.logo = require('../../assets/images/BlockIcon/bigint.svg'); block.baseInfo.version = '2.0'; block.ports = [ { direction: 'input', guid: 'IN', paramType: 'bigint', paramDefaultValue: 0, }, { direction: 'output', guid: 'OUT', paramType: 'bigint', }, ]; block.callbacks.onPortParamRequest = typeRequest; block.blockStyle.titleBakgroundColor = "rgba(0,168,243,0.5)"; block.blockStyle.smallTitle = true; block.blockStyle.noTitle = true; block.blockStyle.hideLogo = true; blocks.push(block); let reloadSelectBlockPorts = function(block : Block) { let type = block.options['opType']; block.changePortParamType(block.getPortByGUID('PIN'), createParameterTypeFromString(type), 'variable'); block.changePortParamType(block.getPortByGUID('POUT'), createParameterTypeFromString(type), 'variable'); } block = new BlockRegData("27284141-843F-E9AC-AE51-52AC14DF80CD", "类型变量参数", "类型变量参数单元。该单元带执行,其会开辟栈空间用以存储参数", 'imengyu', '基础/类型'); block.baseInfo.logo = require('../../assets/images/BlockIcon/circle.svg'); block.ports = [ { direction: 'input', guid: 'IN', paramType: 'execute', }, { direction: 'input', guid: 'PIN', paramType: 'any', portAnyFlexable: { flexable: true } }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'POUT', paramType: 'any', portAnyFlexable: { flexable: true } }, ]; block.portAnyFlexables = { flexable: {} }; block.callbacks.onCreate = (block) => { if(typeof block.options['opType'] == 'undefined') block.options['opType'] = 'any'; reloadSelectBlockPorts(block); }; block.callbacks.onCreateCustomEditor = (parentEle, block : BlockEditor, regData) => { let el = document.createElement('div'); let typeSelector = document.createElement('input'); typeSelector.value = ParamTypeServiceInstance.getTypeNameForUserMapping(block.options['opType']); typeSelector.type = 'text'; typeSelector.style.width = '111px'; typeSelector.readOnly = true; typeSelector.onclick = (e) => { block.editor.chooseType(new Vector2(e.x, e.y), (type, isBaseType) => { if(block.options['opType'] != type.name) { block.options['opType'] = type.name; typeSelector.value = ParamTypeServiceInstance.getTypeNameForUserMapping(type.name); reloadSelectBlockPorts(block); } }, false) }; el.innerText = '类型:'; el.style.whiteSpace = 'nowrap'; el.appendChild(typeSelector); parentEle.appendChild(el); }; block.callbacks.onPortExecuteIn = (block, port) => { if(port.guid === 'IN') block.setOutputParamValue('POUT', block.getInputParamValue('PIN')); }; blocks.push(block); return blocks; } function registerLoadLib() { let blocks = []; let block = new BlockRegData("A76128DC-F4E4-69D4-F232-A4E226183B34", "加载库", "加载附加函数库", 'imengyu', '基础'); block.baseInfo.logo = require('../../assets/images/BlockIcon/module.svg'); block.baseInfo.version = '2.0'; block.ports = [ { direction: 'input', guid: 'IN', paramType: 'execute', }, { direction: 'input', guid: 'LIBNAME', name: '库的包名', description: '指定要加载的库包名', paramType: 'string', paramRequired: true, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'LOAD-SUCCESS', paramType: 'boolean', name: '加载成功?', }, { direction: 'output', guid: 'ALREDAY-LOADED', paramType: 'boolean', name: '调用之前已加载?', }, { direction: 'output', guid: 'LIB-INFO', paramType: 'object', name: '库信息实体', }, ]; block.callbacks.onPortExecuteIn = (block, port) => { let libName = block.getInputParamValue('LIBNAME'); if(StringUtils.isNullOrEmpty(libName)) block.throwError('库的包名 必须提供 !', port, "error", true); else { let pack = BlockRegister.isPackRegister(libName); if(pack) { block.setOutputParamValue('ALREDAY-LOADED', true); block.setOutputParamValue('LIB-INFO', pack); block.activeOutputPort('OUT'); } else { block.setOutputParamValue('ALREDAY-LOADED', false); try{ let pack = __ORIGINAL_NODEJS_REQUIRE__(libName); if(pack) { BlockRegister.registerPack(pack); block.setOutputParamValue('LOAD-SUCCESS', true); block.setOutputParamValue('LIB-INFO', BlockRegister.isPackRegister(libName)); } else { block.throwError(`Pack ${libName} load failed : func not return anything!`, port, 'warning', false); block.setOutputParamValue('LOAD-SUCCESS', false); block.setOutputParamValue('LIB-INFO', null); } } catch(e) { block.throwError(`Pack ${libName} load failed : Error ${e}`, port, 'warning', false); block.setOutputParamValue('LOAD-SUCCESS', false); block.setOutputParamValue('LIB-INFO', null); } block.activeOutputPort('OUT'); } } }; block.blockStyle.logoBackground = require('../../assets/images/BlockIcon/module-big.svg'); block.blockStyle.smallTitle = true; block.blockStyle.noTitle = true; block.blockStyle.hideLogo = true; blocks.push(block); return blocks; } function registerCommentBlock() { let block = new BlockRegData("088C2A25-192D-42E7-D31B-B5E9FB7C68DD", "文档注释", "", 'imengyu', ''); block.baseInfo.logo = require('../../assets/images/BlockIcon/info.svg'); block.baseInfo.description = '在这个单元里面添加你的代码注释,拖动右下角可以调整大小'; block.ports = []; block.blockStyle.minHeight = '100px'; block.callbacks.onCreateCustomEditor = (parentEle, block) => { var input = document.createElement('textarea'); input.value = block.options['content'] ? block.options['content'] : ''; input.classList.add('custom-editor'); input.classList.add('comment-editor'); input.style.width = (typeof block.options['width'] === 'number' ? block.options['width'] : 210) + 'px'; input.style.height = (typeof block.options['height'] === 'number' ? block.options['height'] : 122) + 'px'; input.onchange = () => { block.options['content'] = input.value; block.editor.markFileChanged(); }; input.oncontextmenu = (e) => { block.editor.showInputRightMenu(new Vector2(e.x, e.y), <HTMLInputElement>e.target); e.stopPropagation(); e.preventDefault(); }; block.data['input-control'] = input; parentEle.appendChild(input); }; block.blockStyle.noComment = true; block.callbacks.onSave = (block) => { var input = <HTMLInputElement>block.data['input-control']; block.options['width'] = input.offsetWidth; block.options['height'] = input.offsetHeight; block.options['content'] = input.value; }; commentBlock = new BlockRegData("24AA3DF0-49D9-84D9-8138-534505C33327", "注释块", "", 'imengyu', ''); commentBlock.baseInfo.logo = require('../../assets/images/BlockIcon/info2.svg'); commentBlock.baseInfo.description = ''; commentBlock.ports = []; commentBlock.blockStyle.minHeight = '100px'; commentBlock.blockStyle.userCanResize = true; commentBlock.blockStyle.noTooltip = true; commentBlock.blockStyle.noComment = true; commentBlock.blockStyle.hideLogo = true; commentBlock.blockStyle.noTitle = true; commentBlock.blockStyle.layer = 'background'; commentBlock.callbacks.onCreateCustomEditor = (parentEle, block) => { let blockEle = <HTMLDivElement>parentEle.parentNode; blockEle.classList.add('flow-block-comment-block'); blockEle.style.minWidth = '250px'; blockEle.style.minHeight = '150px'; let ele = document.createElement('div'); let input = document.createElement('input'); let span = document.createElement('span'); input.value = block.options['comment'] ? block.options['comment'] : '注释'; input.onchange = () => { block.options['comment'] = input.value; span.innerText = input.value; }; input.style.display = 'none'; input.onkeypress = (e) => { if(e.key == 'Enter') input.onblur(undefined); }; input.onblur = () => { input.style.display = 'none'; span.style.display = 'block'; }; span.onclick = () => { if(block.selected && !block.isLastMovedBlock()) { span.style.display = 'none'; input.style.display = 'block'; input.focus(); } }; span.innerText = input.value; ele.classList.add('comment-block-title'); ele.appendChild(input); ele.appendChild(span); parentEle.appendChild(ele); }; commentBlock.callbacks.onCreate = (block) => { block.data['list'] = []; block.data['rect'] = new Rect(); block.data['mouseDownPos'] = { x: 0, y: 0 }; block.data['mouseDown'] = false; }; commentBlock.callbacks.onDestroy = (block) => { block.data['list'] = undefined; }; commentBlock.callbacks.onBlockMouseEvent = (block: BlockEditor, event: "move" | "down" | "up", e: MouseEvent) => { let list = block.data['list'] as Array<BlockEditor>; let rect = block.data['rect'] as Rect; let mouseDownPos = block.data['mouseDownPos'] as { x: number, y: number}; if(event === 'down') { block.data['mouseDown'] = true; mouseDownPos.x = e.x; mouseDownPos.y = e.y; //保存鼠标按下时区域内的所有单元 rect.Set(block.getRect()); list.empty(); block.editor.getBlocksInRect(rect).forEach((v) => { if(v != block) { v.updateLastPos(); list.push(v); } }); } else if(event === 'move') { if(block.data['mouseDown'] && block.getCurrentSizeType() == 0) { //移动包括在注释内的单元 let zoom = 1 / block.editor.getViewZoom(); let offX = e.x - mouseDownPos.x, offY = e.y - mouseDownPos.y; list.forEach((v) => { v.position.x = v.getLastPos().x + (offX * zoom); v.position.y = v.getLastPos().y + (offY * zoom); v.setPos(); }) } } else if(event === 'up') { if(block.data['mouseDown']) block.data['mouseDown'] = false; } return false; }; return [ block, commentBlock ]; } function registerConvertBlock() { let block = new BlockRegData("8C7DA763-05C1-61AF-DCD2-174CB6C2C279", "转换器", "", 'imengyu', '基础/转换'); block.baseInfo.logo = require('../../assets/images/BlockIcon/convert.svg'); block.baseInfo.description = ''; block.ports = [ { guid: 'INPUT', paramType: 'any', direction: 'input', defaultConnectPort: true, }, { guid: 'OUTPUT', paramType: 'any', direction: 'output' }, ]; block.type = 'base'; block.blockStyle.titleBakgroundColor = "rgba(250,250,250,0.6)"; block.blockStyle.noTitle = true; block.blockStyle.minWidth = '0px'; block.settings.hideInAddPanel = true; block.callbacks.onCreate = (block : Block) => { if(!StringUtils.isNullOrEmpty(block.options['coverterFrom']) && !StringUtils.isNullOrEmpty(block.options['coverterTo'])) block.data['coverter'] = ParamTypeServiceInstance.getTypeCoverter( createParameterTypeFromString(block.options['coverterFrom']), createParameterTypeFromString(block.options['coverterTo'])); let coverter = <BlockParameterTypeConverterData>block.data['coverter']; if(coverter) { let fromPort = block.getPortByGUID('INPUT'); let toPort = block.getPortByGUID('OUTPUT'); block.changePortParamType(fromPort, coverter.fromType, coverter.allowSetType); block.changePortParamType(toPort, coverter.toType, coverter.allowSetType); block.regData.baseInfo.description = '转换 ' + ParamTypeServiceInstance.getTypeNameForUserMapping(coverter.fromType) + ' 至 ' + ParamTypeServiceInstance.getTypeNameForUserMapping(coverter.toType); } }; block.callbacks.onPortParamRequest = (block: Block, port: BlockPort, context: BlockRunContextData) => { let coverter = <BlockParameterTypeConverterData>block.data['coverter']; if(coverter) { let input = block.getInputParamValue('INPUT', context); return coverter.converter(input); } else { block.throwError('转换器没有设置转换方法,请删除之后重新添加', port, 'error'); return undefined; } }; convertBlock = block; let parseFloatBlock = new BlockRegData("6A644C89-F7FA-E615-6342-D7E747710DD6", "parseFloat", '转换为浮点数', 'imengyu', '基础/转换'); parseFloatBlock.baseInfo.logo = require('../../assets/images/BlockIcon/convert-number.svg'); parseFloatBlock.ports = [ { guid: 'INPUT', paramType: 'any', direction: 'input', description: '要转换的变量', defaultConnectPort: true, }, { guid: 'OUTPUT', paramType: 'number', description: '转为的浮点数', direction: 'output' }, ]; parseFloatBlock.type = 'base'; parseFloatBlock.blockStyle.titleBakgroundColor = "rgba(250,250,250,0.6)"; parseFloatBlock.blockStyle.noTitle = true; parseFloatBlock.blockStyle.logoBackground = 'title:parseInt'; parseFloatBlock.blockStyle.minWidth = '130px'; parseFloatBlock.callbacks.onPortParamRequest = (block: Block, port: BlockPort, context: BlockRunContextData) => { let input = block.getInputParamValue('INPUT', context); return parseFloat(input); }; let parseIntBlock = new BlockRegData("824AB4F0-7C8F-A12F-6CA6-87266464BD6E", "parseInt", '转换为整数', 'imengyu', '基础/转换'); parseIntBlock.baseInfo.logo = require('../../assets/images/BlockIcon/convert-number-2.svg'); parseIntBlock.ports = [ { guid: 'INPUT', paramType: 'any', direction: 'input', description: '要转换的变量', defaultConnectPort: true, }, { guid: 'OUTPUT', paramType: 'number', description: '转为的整数', direction: 'output' }, ]; parseIntBlock.type = 'base'; parseIntBlock.blockStyle.logoBackground = 'title:parseInt'; parseIntBlock.blockStyle.titleBakgroundColor = "rgba(250,250,250,0.6)"; parseIntBlock.blockStyle.noTitle = true; parseIntBlock.blockStyle.minWidth = '130px'; parseIntBlock.callbacks.onPortParamRequest = (block: Block, port: BlockPort, context: BlockRunContextData) => { let input = block.getInputParamValue('INPUT', context); return parseInt(input); }; return [ block, parseFloatBlock, parseIntBlock ]; } function registerConnBlock() { let block = new BlockRegData("8A94A788-ED4E-E521-5BC2-4D69B59BAB80", "数据延长线", "", 'imengyu', ''); block.baseInfo.logo = require('../../assets/images/BlockIcon/convert.svg'); block.baseInfo.description = ''; block.ports = [ { guid: 'INPUT', paramType: 'any', paramRefPassing: true, direction: 'input', portAnyFlexable: { flexable: true }, defaultConnectPort: true, }, { guid: 'OUTPUT', paramType: 'any', paramRefPassing: true, portAnyFlexable: { flexable: true }, direction: 'output' }, ]; block.portAnyFlexables = { flexable: {} }; block.blockStyle.noTitle = true; block.blockStyle.noComment = true; block.blockStyle.minWidth = '0px'; block.callbacks.onPortParamRequest = (block: Block, port: BlockPort, context: BlockRunContextData) => { return block.getInputParamValue('INPUT', context); }; block.callbacks.onCreate = (block : Block) => { let type = block.options['type']; if(!StringUtils.isNullOrEmpty(type)) { block.changePortParamType(block.getPortByGUID('INPUT'), undefined, type); block.changePortParamType(block.getPortByGUID('OUTPUT'), undefined, type); } }; block.blockMenu.items.push({ label: '集合类型', children: [ { label: '变量', onClick: function() { this.changePortParamType(this.getPortByGUID('INPUT'), undefined, 'variable'); this.changePortParamType(this.getPortByGUID('OUTPUT'), undefined, 'variable'); this.options['type'] = 'variable'; } }, { label: '数组', onClick: function() { this.changePortParamType(this.getPortByGUID('INPUT'), undefined, 'array'); this.changePortParamType(this.getPortByGUID('OUTPUT'), undefined, 'array'); this.options['type'] = 'array'; } }, { label: '集合', onClick: function() { this.changePortParamType(this.getPortByGUID('INPUT'), undefined, 'set'); this.changePortParamType(this.getPortByGUID('OUTPUT'), undefined, 'set'); this.options['type'] = 'set'; } }, { label: '映射', onClick: function() { this.changePortParamType(this.getPortByGUID('INPUT'), undefined, 'dictionary'); this.changePortParamType(this.getPortByGUID('OUTPUT'), undefined, 'dictionary'); this.options['type'] = 'dictionary'; } }, ] }) block.callbacks.onEditorCreate = (block) => { block.el.classList.add('flow-block-extended-line'); } return [ block ]; }
the_stack
import { VexFlowTests, TestOptions } from './vexflow_test_helpers'; import { Articulation } from 'articulation'; import { Beam } from 'beam'; import { Flow } from 'flow'; import { Formatter } from 'formatter'; import { ContextBuilder } from 'renderer'; import { Stave } from 'stave'; import { Barline, BarlineType } from 'stavebarline'; import { StaveNote } from 'stavenote'; import { TabNote } from 'tabnote'; import { TabStave } from 'tabstave'; import { Voice } from 'voice'; const ArticulationTests = { Start(): void { QUnit.module('Articulation'); const run = VexFlowTests.runTests; run('Articulation - Staccato/Staccatissimo', drawArticulations, { sym1: 'a.', sym2: 'av' }); run('Articulation - Accent/Tenuto', drawArticulations, { sym1: 'a>', sym2: 'a-' }); run('Articulation - Marcato/L.H. Pizzicato', drawArticulations, { sym1: 'a^', sym2: 'a+' }); run('Articulation - Snap Pizzicato/Fermata', drawArticulations, { sym1: 'ao', sym2: 'ao' }); run('Articulation - Up-stroke/Down-Stroke', drawArticulations, { sym1: 'a|', sym2: 'am' }); run('Articulation - Fermata Above/Below', drawFermata, { sym1: 'a@a', sym2: 'a@u' }); run('Articulation - Inline/Multiple', drawArticulations2, { sym1: 'a.', sym2: 'a.' }); run('TabNote Articulation', tabNotes, { sym1: 'a.', sym2: 'a.' }); }, }; function drawArticulations(options: TestOptions, contextBuilder: ContextBuilder): void { const sym1 = options.params.sym1; const sym2 = options.params.sym2; expect(0); // Get the rendering context const ctx = contextBuilder(options.elementId, 625, 195); // bar 1 const staveBar1 = new Stave(10, 30, 125); staveBar1.setContext(ctx).draw(); const notesBar1 = [ new StaveNote({ keys: ['a/3'], duration: 'q', stem_direction: 1 }), new StaveNote({ keys: ['a/4'], duration: 'q', stem_direction: 1 }), new StaveNote({ keys: ['c/4'], duration: 'q', stem_direction: 1 }), new StaveNote({ keys: ['a/4'], duration: 'q', stem_direction: 1 }), ]; notesBar1[0].addArticulation(0, new Articulation(sym1).setPosition(4)); notesBar1[1].addArticulation(0, new Articulation(sym1).setPosition(4)); notesBar1[2].addArticulation(0, new Articulation(sym1).setPosition(3)); notesBar1[3].addArticulation(0, new Articulation(sym1).setPosition(3)); // Helper function to justify and draw a 4/4 voice Formatter.FormatAndDraw(ctx, staveBar1, notesBar1); // bar 2 - juxtaposing second bar next to first bar const staveBar2 = new Stave(staveBar1.getWidth() + staveBar1.getX(), staveBar1.getY(), 125); staveBar2.setEndBarType(Barline.type.DOUBLE); staveBar2.setContext(ctx).draw(); const notesBar2 = [ new StaveNote({ keys: ['c/5'], duration: 'q', stem_direction: -1 }), new StaveNote({ keys: ['a/5'], duration: 'q', stem_direction: -1 }), new StaveNote({ keys: ['c/5'], duration: 'q', stem_direction: -1 }), new StaveNote({ keys: ['a/5'], duration: 'q', stem_direction: -1 }), ]; notesBar2[0].addArticulation(0, new Articulation(sym1).setPosition(3)); notesBar2[1].addArticulation(0, new Articulation(sym1).setPosition(3)); notesBar2[2].addArticulation(0, new Articulation(sym1).setPosition(4)); notesBar2[3].addArticulation(0, new Articulation(sym1).setPosition(4)); // Helper function to justify and draw a 4/4 voice Formatter.FormatAndDraw(ctx, staveBar2, notesBar2); // bar 3 - juxtaposing second bar next to first bar const staveBar3 = new Stave(staveBar2.getWidth() + staveBar2.getX(), staveBar2.getY(), 125); staveBar3.setContext(ctx).draw(); const notesBar3 = [ new StaveNote({ keys: ['c/4'], duration: 'q', stem_direction: 1 }), new StaveNote({ keys: ['c/5'], duration: 'q', stem_direction: 1 }), new StaveNote({ keys: ['c/4'], duration: 'q', stem_direction: 1 }), new StaveNote({ keys: ['a/4'], duration: 'q', stem_direction: 1 }), ]; notesBar3[0].addArticulation(0, new Articulation(sym2).setPosition(4)); notesBar3[1].addArticulation(0, new Articulation(sym2).setPosition(4)); notesBar3[2].addArticulation(0, new Articulation(sym2).setPosition(3)); notesBar3[3].addArticulation(0, new Articulation(sym2).setPosition(3)); // Helper function to justify and draw a 4/4 voice Formatter.FormatAndDraw(ctx, staveBar3, notesBar3); // bar 4 - juxtaposing second bar next to first bar const staveBar4 = new Stave(staveBar3.getWidth() + staveBar3.getX(), staveBar3.getY(), 125); staveBar4.setEndBarType(BarlineType.END); staveBar4.setContext(ctx).draw(); const notesBar4 = [ new StaveNote({ keys: ['a/4'], duration: 'q', stem_direction: -1 }), new StaveNote({ keys: ['a/5'], duration: 'q', stem_direction: -1 }), new StaveNote({ keys: ['c/5'], duration: 'q', stem_direction: -1 }), new StaveNote({ keys: ['a/5'], duration: 'q', stem_direction: -1 }), ]; notesBar4[0].addArticulation(0, new Articulation(sym2).setPosition(3)); notesBar4[1].addArticulation(0, new Articulation(sym2).setPosition(3)); notesBar4[2].addArticulation(0, new Articulation(sym2).setPosition(4)); notesBar4[3].addArticulation(0, new Articulation(sym2).setPosition(4)); // Helper function to justify and draw a 4/4 voice Formatter.FormatAndDraw(ctx, staveBar4, notesBar4); } function drawFermata(options: TestOptions, contextBuilder: ContextBuilder): void { const sym1 = options.params.sym1; const sym2 = options.params.sym2; expect(0); // Get the rendering context const ctx = contextBuilder(options.elementId, 400, 200); // bar 1 const staveBar1 = new Stave(50, 30, 150); staveBar1.setContext(ctx).draw(); const notesBar1 = [ new StaveNote({ keys: ['c/4'], duration: 'q', stem_direction: 1 }), new StaveNote({ keys: ['a/4'], duration: 'q', stem_direction: 1 }), new StaveNote({ keys: ['c/4'], duration: 'q', stem_direction: -1 }), new StaveNote({ keys: ['a/4'], duration: 'q', stem_direction: -1 }), ]; notesBar1[0].addArticulation(0, new Articulation(sym1).setPosition(3)); notesBar1[1].addArticulation(0, new Articulation(sym1).setPosition(3)); notesBar1[2].addArticulation(0, new Articulation(sym2).setPosition(4)); notesBar1[3].addArticulation(0, new Articulation(sym2).setPosition(4)); // Helper function to justify and draw a 4/4 voice Formatter.FormatAndDraw(ctx, staveBar1, notesBar1); // bar 2 - juxtaposing second bar next to first bar const staveBar2 = new Stave(staveBar1.getWidth() + staveBar1.getX(), staveBar1.getY(), 150); staveBar2.setEndBarType(Barline.type.DOUBLE); staveBar2.setContext(ctx).draw(); const notesBar2 = [ new StaveNote({ keys: ['c/5'], duration: 'q', stem_direction: 1 }), new StaveNote({ keys: ['a/5'], duration: 'q', stem_direction: 1 }), new StaveNote({ keys: ['c/5'], duration: 'q', stem_direction: -1 }), new StaveNote({ keys: ['a/5'], duration: 'q', stem_direction: -1 }), ]; notesBar2[0].addArticulation(0, new Articulation(sym1).setPosition(3)); notesBar2[1].addArticulation(0, new Articulation(sym1).setPosition(3)); notesBar2[2].addArticulation(0, new Articulation(sym2).setPosition(4)); notesBar2[3].addArticulation(0, new Articulation(sym2).setPosition(4)); // Helper function to justify and draw a 4/4 voice Formatter.FormatAndDraw(ctx, staveBar2, notesBar2); } function drawArticulations2(options: TestOptions, contextBuilder: ContextBuilder): void { expect(0); // Get the rendering context const ctx = contextBuilder(options.elementId, 1000, 200); // bar 1 const staveBar1 = new Stave(10, 30, 350); staveBar1.setContext(ctx).draw(); const notesBar1 = [ new StaveNote({ keys: ['c/4'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['d/4'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['e/4'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['f/4'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['g/4'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['a/4'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['b/4'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['c/5'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['d/5'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['e/5'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['f/5'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['g/5'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['a/5'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['b/5'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['c/6'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['d/6'], duration: '16', stem_direction: -1 }), ]; let i; for (i = 0; i < 16; i++) { notesBar1[i].addArticulation(0, new Articulation('a.').setPosition(4)); notesBar1[i].addArticulation(0, new Articulation('a>').setPosition(4)); if (i === 15) { notesBar1[i].addArticulation(0, new Articulation('a@u').setPosition(4)); } } const beam1 = new Beam(notesBar1.slice(0, 8)); const beam2 = new Beam(notesBar1.slice(8, 16)); // Helper function to justify and draw a 4/4 voice Formatter.FormatAndDraw(ctx, staveBar1, notesBar1); beam1.setContext(ctx).draw(); beam2.setContext(ctx).draw(); // bar 2 - juxtaposing second bar next to first bar const staveBar2 = new Stave(staveBar1.getWidth() + staveBar1.getX(), staveBar1.getY(), 350); staveBar2.setContext(ctx).draw(); const notesBar2 = [ new StaveNote({ keys: ['f/3'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['g/3'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['a/3'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['b/3'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['c/4'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['d/4'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['e/4'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['f/4'], duration: '16', stem_direction: 1 }), new StaveNote({ keys: ['g/4'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['a/4'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['b/4'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['c/5'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['d/5'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['e/5'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['f/5'], duration: '16', stem_direction: -1 }), new StaveNote({ keys: ['g/5'], duration: '16', stem_direction: -1 }), ]; for (i = 0; i < 16; i++) { notesBar2[i].addArticulation(0, new Articulation('a-').setPosition(3)); notesBar2[i].addArticulation(0, new Articulation('a^').setPosition(3)); if (i === 15) { notesBar2[i].addArticulation(0, new Articulation('a@u').setPosition(4)); } } const beam3 = new Beam(notesBar2.slice(0, 8)); const beam4 = new Beam(notesBar2.slice(8, 16)); // Helper function to justify and draw a 4/4 voice Formatter.FormatAndDraw(ctx, staveBar2, notesBar2); beam3.setContext(ctx).draw(); beam4.setContext(ctx).draw(); // bar 3 - juxtaposing second bar next to first bar const staveBar3 = new Stave(staveBar2.getWidth() + staveBar2.getX(), staveBar2.getY(), 75); staveBar3.setContext(ctx).draw(); const notesBar3 = [new StaveNote({ keys: ['c/4'], duration: 'w', stem_direction: 1 })]; notesBar3[0].addArticulation(0, new Articulation('a-').setPosition(3)); notesBar3[0].addArticulation(0, new Articulation('a>').setPosition(3)); notesBar3[0].addArticulation(0, new Articulation('a@a').setPosition(3)); // Helper function to justify and draw a 4/4 voice Formatter.FormatAndDraw(ctx, staveBar3, notesBar3); // bar 4 - juxtaposing second bar next to first bar const staveBar4 = new Stave(staveBar3.getWidth() + staveBar3.getX(), staveBar3.getY(), 150); staveBar4.setEndBarType(Barline.type.END); staveBar4.setContext(ctx).draw(); const notesBar4 = [ new StaveNote({ keys: ['c/5'], duration: 'q', stem_direction: -1 }), new StaveNote({ keys: ['a/5'], duration: 'q', stem_direction: -1 }), new StaveNote({ keys: ['c/5'], duration: 'q', stem_direction: -1 }), new StaveNote({ keys: ['a/5'], duration: 'q', stem_direction: -1 }), ]; for (i = 0; i < 4; i++) { let position1 = 3; if (i > 1) { position1 = 4; } notesBar4[i].addArticulation(0, new Articulation('a-').setPosition(position1)); } // Helper function to justify and draw a 4/4 voice Formatter.FormatAndDraw(ctx, staveBar4, notesBar4); } function tabNotes(options: TestOptions, contextBuilder: ContextBuilder): void { const ctx = contextBuilder(options.elementId, 600, 200); ctx.font = '10pt Arial'; const stave = new TabStave(10, 10, 550); stave.setContext(ctx); stave.draw(); const specs = [ { positions: [ { str: 3, fret: 6 }, { str: 4, fret: 25 }, ], duration: '8', }, { positions: [ { str: 2, fret: 10 }, { str: 5, fret: 12 }, ], duration: '8', }, { positions: [ { str: 1, fret: 6 }, { str: 3, fret: 5 }, ], duration: '8', }, { positions: [ { str: 1, fret: 6 }, { str: 3, fret: 5 }, ], duration: '8', }, ]; const notes1 = specs.map((noteSpec) => { const tabNote = new TabNote(noteSpec); tabNote.render_options.draw_stem = true; return tabNote; }); const notes2 = specs.map((noteSpec) => { const tabNote = new TabNote(noteSpec); tabNote.render_options.draw_stem = true; tabNote.setStemDirection(-1); return tabNote; }); const notes3 = specs.map((noteSpec) => new TabNote(noteSpec)); notes1[0].addModifier(new Articulation('a>').setPosition(3), 0); // U notes1[1].addModifier(new Articulation('a>').setPosition(4), 0); // D notes1[2].addModifier(new Articulation('a.').setPosition(3), 0); // U notes1[3].addModifier(new Articulation('a.').setPosition(4), 0); // D notes2[0].addModifier(new Articulation('a>').setPosition(3), 0); notes2[1].addModifier(new Articulation('a>').setPosition(4), 0); notes2[2].addModifier(new Articulation('a.').setPosition(3), 0); notes2[3].addModifier(new Articulation('a.').setPosition(4), 0); notes3[0].addModifier(new Articulation('a>').setPosition(3), 0); notes3[1].addModifier(new Articulation('a>').setPosition(4), 0); notes3[2].addModifier(new Articulation('a.').setPosition(3), 0); notes3[3].addModifier(new Articulation('a.').setPosition(4), 0); const voice = new Voice(Flow.TIME4_4).setMode(Voice.Mode.SOFT); voice.addTickables(notes1); voice.addTickables(notes2); voice.addTickables(notes3); new Formatter().joinVoices([voice]).formatToStave([voice], stave); voice.draw(ctx, stave); ok(true, 'TabNotes successfully drawn'); } export { ArticulationTests };
the_stack
import { UserLockedAfterFailedAttemptsEvent } from "./../events"; import { SecurityService, IFieldMap, UserId } from "@bluelibs/security-bundle"; import { IPasswordBundleConfig, IPasswordService, IPasswordAuthenticationStrategyCreationOptions, IPasswordValidationOptions, IPasswordAuthenticationStrategy, IHasherService, } from "../defs"; import * as ms from "ms"; import { Inject, Service, EventManager } from "@bluelibs/core"; import { BUNDLE_CONFIG_TOKEN, HASHER_SERVICE_TOKEN } from "../constants"; import { PasswordInvalidEvent, PasswordResetRequestedEvent, PasswordResetWithTokenEvent, } from "../events"; import { PasswordAuthenticationStrategyAttachedEvent, PasswordValidatedEvent, } from "../events"; import { CooldownException, PasswordResetExpiredException, ResetPasswordInvalidTokenException, UsernameAlreadyExistsException, } from "../exceptions"; @Service() export class PasswordService implements IPasswordService { public readonly method: string = "password"; constructor( protected readonly securityService: SecurityService, protected readonly eventManager: EventManager, @Inject(BUNDLE_CONFIG_TOKEN) protected readonly config: IPasswordBundleConfig, @Inject(HASHER_SERVICE_TOKEN) protected readonly hasherService: IHasherService ) {} /** * @returns The userId * @param username */ async findUserIdByUsername( username: string, fields?: IFieldMap ): Promise<UserId> { const result = await this.securityService.findThroughAuthenticationStrategy<IPasswordAuthenticationStrategy>( this.method, { username, }, fields ); return result?.userId; } async attach( userId: UserId, options: IPasswordAuthenticationStrategyCreationOptions ): Promise<void> { const usernameExists = await this.usernameExists(options.username); if (usernameExists) { throw new UsernameAlreadyExistsException({ username: options.username }); } const salt = this.hasherService.generateSalt(); const passwordHash = this.hasherService.getHashedPassword( options.password, salt ); const data: any = { salt, passwordHash, username: options.username, lastSuccessfulPasswordValidationAt: null, resetPasswordVerificationToken: null, resetPasswordRequestedAt: null, currentFailedLoginAttempts: 0, lastFailedLoginAttemptAt: null, }; if (options.email) { data.email = options.email; } await this.updateData(userId, data); await this.eventManager.emit( new PasswordAuthenticationStrategyAttachedEvent({ userId }) ); } async isPasswordValid( userId: UserId, password: string, options: IPasswordValidationOptions = { failedAuthenticationAttemptsProcessing: true, } ): Promise<boolean> { const methodData = await this.getData(userId, { passwordHash: 1, salt: 1, currentFailedLoginAttempts: 1, lastFailedLoginAttemptAt: 1, }); if (options.failedAuthenticationAttemptsProcessing) { // This will throw if it should be cooled down and method will no longer continue await this.checkIfInCooldown( userId, methodData.currentFailedLoginAttempts, methodData.lastFailedLoginAttemptAt ); } const isValid = methodData.passwordHash === this.hasherService.getHashedPassword(password, methodData.salt); if (isValid) { await this.eventManager.emit(new PasswordValidatedEvent({ userId })); } else { await this.eventManager.emit(new PasswordInvalidEvent({ userId })); } if (options.failedAuthenticationAttemptsProcessing) { // non-blocking this.processAuthenticationResult(isValid, userId, methodData); } return isValid; } /** * Authentication failed, so we are processing exactly that */ protected async processAuthenticationResult( isValid: boolean, userId: UserId, methodData: Partial<IPasswordAuthenticationStrategy> ) { if (isValid) { await this.updateData(userId, { currentFailedLoginAttempts: 0, lastFailedLoginAttemptAt: null, }); } else { const failedAttempts = methodData.currentFailedLoginAttempts + 1; // Increment failed login attempts await this.updateData(userId, { currentFailedLoginAttempts: failedAttempts, lastFailedLoginAttemptAt: new Date(), }); if ( failedAttempts >= this.config.failedAuthenticationAttempts.lockAfter ) { await this.eventManager.emit( new UserLockedAfterFailedAttemptsEvent({ userId, failedAttempts, }) ); } } } /** * This simply checks if cooldown period of failed login attempts has passed and there are enough login attempts * Throws an error if not ok, resets currentFailedLoginAttempts */ protected async checkIfInCooldown( userId: UserId, currentFailedLoginAttempts: number, lastFailedLoginAttemptAt: Date ): Promise<void> { const { cooldown, lockAfter } = this.config.failedAuthenticationAttempts; if (currentFailedLoginAttempts >= lockAfter) { // We need to check if in the meanwhile we've cooled down if (lastFailedLoginAttemptAt) { if (lastFailedLoginAttemptAt.getTime() + ms(cooldown) < Date.now()) { // it's ok, cooldown passed await this.updateData(userId, { currentFailedLoginAttempts: 0, }); } else { throw new CooldownException({ context: "login", }); } } } } async createTokenForPasswordReset(userId: UserId): Promise<string> { // We need to check if there have been any requests in the past X time const isEligible = await this.isEligibleForPasswordResetRequest(userId); if (!isEligible) { throw new CooldownException({ context: "reset-password", }); } const token = this.hasherService.generateToken(); await this.updateData(userId, { resetPasswordVerificationToken: token, resetPasswordRequestedAt: new Date(), }); await this.eventManager.emit( new PasswordResetRequestedEvent({ userId, token, }) ); return token; } async isResetPasswordTokenValid( userId: UserId, token: string ): Promise<boolean> { const result = await this.getData(userId, { resetPasswordVerificationToken: 1, resetPasswordRequestedAt: 1, }); if (!result?.resetPasswordRequestedAt) return false; if ( result.resetPasswordRequestedAt.getTime() + ms(this.config.resetPassword.expiresAfter) < Date.now() ) { throw new PasswordResetExpiredException(); } if (result.resetPasswordVerificationToken) { return result.resetPasswordVerificationToken === token; } return false; } async resetPassword( userId: UserId, token: string, newPassword: string ): Promise<void> { if (await this.isResetPasswordTokenValid(userId, token)) { await this.setPassword(userId, newPassword); await this.updateData(userId, { resetPasswordVerificationToken: null, resetPasswordRequestedAt: null, }); await this.eventManager.emit( new PasswordResetWithTokenEvent({ userId, token, }) ); } else { throw new ResetPasswordInvalidTokenException(); } } /** * Sets the password for the user based on its salt * @param userId * @param password */ async setPassword(userId: UserId, password: string): Promise<void> { const user = await this.getData(userId, { salt: 1, }); const passwordHash = this.hasherService.getHashedPassword( password, user.salt ); await this.updateData(userId, { passwordHash, }); } /** * Sets the username for the user * @param userId * @param username */ async setUsername(userId: UserId, username: string): Promise<void> { await this.updateData(userId, { username, }); } /** * Helper method to get data easier * @param userId * @param fields */ async getData( userId, fields?: IFieldMap ): Promise<Partial<IPasswordAuthenticationStrategy>> { return this.securityService.getAuthenticationStrategyData<IPasswordAuthenticationStrategy>( userId, this.method, fields ); } /** * Checks if there is already an username attached with this information * * @param username * @param exceptUserId You can also except certain users, like for example when you are updating certain user data * @returns */ async usernameExists( username: string, exceptUserId?: UserId ): Promise<boolean> { if (exceptUserId) { const result = await this.securityService.findThroughAuthenticationStrategy( this.method, { username, } ); if (!result) { return false; } if (result.userId.toString() === exceptUserId.toString()) { return false; } else { return true; } } else { const result = await this.securityService.findThroughAuthenticationStrategy( this.method, { username, } ); return Boolean(result); } } /** * Helper method to easily update the password data * @param userId * @param data */ async updateData( userId, data: Partial<IPasswordAuthenticationStrategy> ): Promise<void> { if (data.username) { const alreadyExists = await this.usernameExists(data.username, userId); if (alreadyExists) { throw new UsernameAlreadyExistsException({ username: data.username }); } } await this.securityService.updateAuthenticationStrategyData<IPasswordAuthenticationStrategy>( userId, this.method, data ); } /** * Check if he hasn't requested the password too often * @param userId */ protected async isEligibleForPasswordResetRequest( userId: UserId ): Promise<boolean> { const methodData = await this.getData(userId, { resetPasswordRequestedAt: 1, }); // Has been cleared or never requested. if (!methodData.resetPasswordRequestedAt) { return true; } return ( Date.now() - ms(this.config.resetPassword.cooldown) > methodData.resetPasswordRequestedAt.getTime() ); } }
the_stack
import { tuple } from "@adpt/utils"; import { WithRequiredT } from "type-ops"; import { defaultDomain, defaultOfficialRepo, defaultTag, parseFamiliar, parseName, parsePathTag, parseReference, validate, } from "./image-ref-parse"; import { ImageIdString, ImageNameString, NameTagString, RegistryString, RepoDigestString } from "./types"; /** * The most basic components that make up a {@link docker.ImageRef}. * All other properties of a {@link docker.ImageRef} can be computed from * these. * @remarks * See also {@link docker.ImageRef} for more information on references. * @public */ export interface ImageRefData { /** * Image digest in the form `algorithm:hex` * @example * sha256:04696b491e0cc3c58a75bace8941c14c924b9f313b03ce5029ebbc040ed9dcd9 */ digest?: string; /** * Docker host string to contact the Docker daemon where this image is * located. * * @remarks * This should be in the same format that Docker expects for the `DOCKER_HOST` * environment variable. The special string `default` can also be used, * which will use the current value of the `DOCKER_HOST` environment variable, * if it is set and will otherwise use the default named pipe on Windows * (`npipe:///./pipe/docker_engine`) and the default socket on other * systems (`unix:///var/run/docker.sock`). * @example * tcp://localhost:2375 */ dockerHost?: "default" | string; /** * Hostname and optional port number of the container image registry where * this image is located. * @example * docker.io * @example * localhost:5000 */ domain?: RegistryString; /** * Image content ID in the form `algorithm:hex` * @example * sha256:199e537da3a86126cd6eb114bd0b13ab178dc291bbb6ea4a4a3aa257b2366b71 */ id?: ImageIdString; /** * The image repo path. * @example * google/cloud-sdk */ path?: string; /** * Image tag * @example * latest */ tag?: string; } const imageRefDataKeys = tuple( "digest", "dockerHost", "domain", "id", "path", "tag", ); /** * The type of an image reference indicates how the image can be * accessed, currently either through a Docker host (daemon) or directly to a * container registry via its API. * * @remarks * If not enough information is present to access and uniquely identify a * container image, the type is `incomplete`. * @public */ export type ImageRefType = "incomplete" | "registry" | "dockerhost"; /** * An immutable reference to a container image, including all information * known about the image. * * @remarks * This type is the base type for an image reference and is allowed to * contain partial or incomplete information about a container image. * It can include both information about how to access the image and * also information about the image itself. * * Many of the properties of {@link docker.ImageRef} are related to the * container image reference string used by Docker and other container-based * systems. A container image reference string is a structured string * containing multiple components. The most basic components are illustrated * below, using the example image reference string * `"my.registry:5000/a/repo/path:sometag@sha256:899a03e9816e5283edba63d"`. * * NOTE: The length of the `digest` has been shortened for formatting * purposes. * * ``` * "my.registry:5000/a/repo/path:sometag@sha256:899a03e9816e5283edba63d" * | domain | path | tag | digest | * ``` * * To aid in correct formatting, {@link docker.ImageRef} and related types and * classes also provide helper properties that combine these basic components * into combinations that are often useful, such as `name`, which is the * `domain` and `path` combined with a `/`. * * Many tools, such as the Docker UI, also accept a shortened form of a string * reference, called the `familiar` form. An example of a familiar reference is * `ubuntu`. In this form, only the `path` component is required. When * components of the reference are left out, default values are assumed. The * default `domain` is `docker.io` and the default `tag` is `latest`. * Additionally, if the `domain` is `docker.io` and there are no `/` characters * in the `path`, `library/` is prepended to the path. So `ubuntu` is the * familiar form for the complete reference `docker.io/library/ubuntu:latest`. * * An {@link docker.ImageRef} is designed to hold as much information about * an image as may be available and therefore some properties that are * not known will be `undefined`. * * See also {@link docker.MutableImageRef}, which can be used to parse * reference strings and construct or modify image references. * @public */ export interface ImageRef extends Readonly<ImageRefData> { /** * The complete string reference for this image in familiar form, which * leaves out certain fields from the reference when they are set to * default values. * @remarks * This reference form is the form typically used in the Docker UI. * If the ImageRef is not complete, familiar will return `undefined`, as * the correct familiar representation cannot be determined. * @example * mysql * @example * gcr.io/my-project/image:1.0.1 */ readonly familiar?: string; /** * The image name, which is comprised of the optional domain and * the (non-optional) path. Will be `undefined` if there is no `path`. * @example * gcr.io/my-project/image */ readonly name?: string; /** * The image name (including any registry) and image tag. Returns undefined * if either path or tag are not set. * If nameTag is set to a string that does not contain a tag (i.e. does * not include a ":"), the default tag of `latest` will be set. * To set nameTag without defaulting to `latest`, call the class method * `setNameTag` with the parameter `useDefaultTag` set to `false`. * @example * gcr.io/my-project/image:1.0.1 */ readonly nameTag?: string; /** * The image path (not including any registry) and image tag. Returns * undefined if either `path` or `tag` are not set. * @example * my-project/image:1.0.1 */ readonly pathTag?: string; /** * The best (most specific and complete) string reference for this image, * given the information available in this {@link docker.ImageRef}. */ readonly ref: string; /** * An alias for `domain`. */ readonly registry?: string; /** * The best remote reference available for this image in either * `domain/path@digest` format or `domain/path:tag` format. * @remarks * Returns `registryDigest` if it is set, otherwise returns `registryTag`. * If no remote reference is available, returns undefined. * @example * gcr.io/my-project/image\@sha256:899a03e9816e5283edba63d71ea528cd83576b28a7586cf617ce78af5526f209 * @example * gcr.io/my-project/image:1.0.1 */ readonly registryRef?: string; /** * The remote digest reference in `domain/path@digest` form. * @remarks * Undefined if any of `domain`, `path`, or `digest` are unset. * @example * gcr.io/my-project/image\@sha256:899a03e9816e5283edba63d71ea528cd83576b28a7586cf617ce78af5526f209 */ readonly registryDigest?: string; /** * The remote tag reference in `domain/path:tag` form. * @remarks * Undefined if any of `domain`, `path`, or `tag` are unset. * @example * gcr.io/my-project/image:1.0.1 */ readonly registryTag?: string; /** * The type of an image reference indicates how the image can be * accessed, either through a Docker host (daemon) or directly to a * container registry. * * @remarks * A reference is a valid `dockerhost` type ref when it contains a valid * dockerHost string and either: * - A valid image id or * - A valid path and either a valid tag or digest. * * A reference is a valid `registry` type ref when it contains a valid * domain, path, and either a tag or a digest. * * If not enough information is present to access and uniquely identify a * container image, the type is `incomplete`. */ readonly type: ImageRefType; } const imageRefKeys = tuple( "digest", "dockerHost", "domain", "familiar", "id", "name", "nameTag", "path", "pathTag", "ref", "registry", "registryRef", "registryDigest", "registryTag", "tag", "type", ); /** * Helper type that augments a base type to indicate that the `id` field * is present and has a valid image ID. * @public */ export type WithId<T> = T & { id: ImageIdString }; /** * Type guard for determining whether a given object has a non-null `id` * property. * @public */ export function hasId<T extends { id?: ImageIdString }>(o: T): o is WithId<T> { return hasProperty(o, "id"); } /** * A mutable reference to a container image that can be used to parse, * construct, and modify an image reference, as well as to hold information * about the image and how to access it. * * @remarks * This class can be used to parse strings that contain complete or partial * container image references. It can also be used to construct an image * reference from scratch, from individual component parts, or from another * reference, then to correctly format the reference or its components for * use with various tools. * * To parse and normalize a "familiar" image reference, like is typically * seen in the Docker UI: * ```ts * const ref = mutableImageRef("redis", true); * console.log(ref.tag); // => "latest" * console.log(ref.registryRef); // => "docker.io/library/redis:latest" * ``` * * To construct a reference to an image present on the local Docker daemon * that has an image ID: * ```ts * const ref = mutableImageRef({ * dockerHost: "default", * path: "myimage", * tag: "just-built", * id: "sha256:04696b491e0cc3c58a75bace8941c14c924b9f313b03ce5029ebbc040ed9dcd9", * }); * ``` * * To convert a `MutableImageRef` to an immutable plain object `ImageRef`, * use the `freeze` method. * @public */ export class MutableImageRef implements ImageRef { _digest?: string; _dockerHost?: string; _domain?: string; _id?: ImageIdString; _path?: string; _tag?: string; constructor(ref: ImageNameString, normalize?: boolean); constructor(info?: ImageRefData | undefined); constructor(info?: ImageRefData | ImageNameString | undefined, normalize = false) { if (!info) return; if (typeof info === "string") { const ref = normalize ? parseFamiliar(info) : parseReference(info); this.name = ref.name; if (ref.tag) this._tag = ref.tag; if (ref.digest) this._digest = ref.digest; return; } if (info.dockerHost && info.domain) { throw new Error(`Cannot specify both 'dockerHost' and 'domain' when creating an image reference`); } if (info.digest) this.digest = info.digest; if (info.dockerHost) this.dockerHost = info.dockerHost; if (info.domain) this.domain = info.domain; if (info.id) this.id = info.id; if (info.path) this.path = info.path; if (info.tag) this.tag = info.tag; } freeze(): ImageRef { const ret: any = {}; for (const k of imageRefKeys) { if (this[k] !== undefined) ret[k] = this[k]; } return Object.freeze(ret); } toData(): ImageRefData { const ret: ImageRefData = {}; for (const k of imageRefDataKeys) { if (this[k] !== undefined) ret[k] = this[k]; } return ret; } toJSON() { return this.toData(); } /** * The digest string for this image in its associated registry and repo * in the form `algorithm:hex`. */ get digest(): string | undefined { return this._digest; } set digest(digest: string | undefined) { if (digest == null) delete this._digest; else this._digest = validate("digest", digest); } get dockerHost(): string | undefined { return this._dockerHost; } set dockerHost(dockerHost: string | undefined) { if (!dockerHost) delete this._dockerHost; else this._dockerHost = dockerHost; } /** * The hostname and optional port of the image registry for this image. */ get domain(): string | undefined { return this._domain; } set domain(domain: string | undefined) { if (domain == null) delete this._domain; else this._domain = validate("domain", domain); } /** * The complete string reference for this image in familiar form, which * leaves out certain fields from the reference when they are set to * default values. * @remarks * This reference form is the form typically used in the Docker UI. * If the ImageRef is not complete, familiar will return `undefined`, as * the correct familiar representation cannot be determined. */ get familiar(): string | undefined { if (this.registryDigest) return this.registryDigest; if (this.type === "incomplete") return undefined; let path = this._path!; if (!path) return undefined; const domain = !this._domain || this._domain === defaultDomain ? "" : `${this._domain}/`; if (this._domain === defaultDomain && path.startsWith(`${defaultOfficialRepo}/`)) { path = path.slice(`${defaultOfficialRepo}/`.length); } const tag = !this._tag || this._tag === defaultTag ? "" : `:${this._tag}`; const digest = this._digest && !tag ? `@${this._digest}` : ""; return domain + path + tag + digest; } /** * The content ID of the image in `algorithm:hex` format. */ get id(): ImageIdString | undefined { return this._id; } set id(id: ImageIdString | undefined) { if (id == null) delete this._id; else this._id = validate("id", id); } /** * The image name, which is comprised of the optional domain and * the (non-optional) path. */ get name(): string | undefined { if (!this._path) return undefined; return this._domain ? `${this._domain}/${this._path}` : this._path; } set name(name: string | undefined) { if (name == null) { delete this._domain; delete this._path; } else { const parsed = parseName(name); if (parsed.domain) this._domain = parsed.domain; this._path = parsed.path; } } /** * The image name (including any registry) and image tag. Returns undefined * if either path or tag are not set. * If nameTag is set to a string that does not contain a tag (i.e. does * not include a ":"), the default tag of `latest` will be set. * To set nameTag without defaulting to `latest`, call the class method * `setNameTag` with the parameter `useDefaultTag` set to `false`. */ get nameTag(): NameTagString | undefined { if (!this.name || !this.tag) return undefined; return `${this.name}:${this.tag}`; } set nameTag(nt: NameTagString | undefined) { this.setNameTag(nt); } /** * Method to set the image name and image tag which also allows choice * of default behavior when `nameTag` does not contain a tag string. */ setNameTag(nameTag: NameTagString | undefined, useDefaultTag = true) { if (nameTag == null) { this.name = undefined; this.tag = undefined; } else { const ref = parseReference(nameTag); if (ref.digest) { throw new Error(`Invalid container image nameTag '${nameTag}'`); } this.name = ref.name; let tag = ref.tag; if (!tag && useDefaultTag) tag = defaultTag; this._tag = tag; } } /** * The image repo path. */ get path(): string | undefined { return this._path; } set path(path: string | undefined) { if (path == null) delete this._path; else this._path = validate("path", path); } /** * The image path (not including any registry) and image tag. Returns * undefined if either path or tag are not set. * If pathTag is set to a string that does not contain a tag (i.e. does * not include a ":"), the default tag of `latest` will be set. * To set pathTag without defaulting to `latest`, call the class method * `setPathTag` with the parameter `useDefaultTag` set to `false`. */ get pathTag(): string | undefined { if (!this.path || !this.tag) return undefined; return `${this.path}:${this.tag}`; } set pathTag(pathTag: string | undefined) { this.setPathTag(pathTag); } /** * Method to set the image path and image tag which also allows choice * of default behavior when `pathTag` does not contain a tag string. */ setPathTag(pathTag: string | undefined, useDefaultTag = true) { if (pathTag == null) { this.path = undefined; this.tag = undefined; } else { const pt = parsePathTag(pathTag); this.path = pt.path; let tag = pt.tag; if (!tag && useDefaultTag) tag = defaultTag; this._tag = tag; } } get ref(): string { return this.registryRef || this.nameTag || this.name || this.path || this.id || "INVALIDREF"; } /** * Alias for domain */ get registry(): string | undefined { return this.domain; } /** * The best remote reference available for this image in either * `domain/path@digest` format or `domain/path:tag` format. * @remarks * Returns `registryDigest` if it is set, otherwise returns `registryTag`. * If no remote reference is available, returns undefined. */ get registryRef(): ImageNameString | undefined { return this.registryDigest || this.registryTag; } /** * The remote digest reference in `domain/path@digest` form. * @remarks * Undefined if any of `domain`, `path`, or `digest` are unset. */ get registryDigest(): RepoDigestString | undefined { if (!this._domain || !this._path || !this._digest) return undefined; return `${this.name}@${this._digest}`; } set registryDigest(rd: RepoDigestString | undefined) { if (rd == null) { this.name = undefined; // use setter delete this._digest; } else { const ref = parseReference(rd); if (ref.tag) { throw new Error(`Invalid container image registryDigest '${rd}': must not contain tag`); } this.name = ref.name; this._digest = ref.digest; } } /** * The remote tag reference in `domain/path:tag` form. * @remarks * Undefined if any of `domain`, `path`, or `tag` are unset. */ get registryTag(): NameTagString | undefined { if (!this.domain) return undefined; return this.nameTag; } set registryTag(rt: NameTagString | undefined) { if (rt == null) { this.name = undefined; this.tag = undefined; } else { const ref = parseReference(rt); if (ref.digest) { throw new Error(`Invalid container image registryTag '${rt}': must not contain digest`); } this.name = ref.name; this.tag = ref.tag; } } /** * The image tag. */ get tag(): string | undefined { return this._tag; } set tag(tag: string | undefined) { if (tag == null) delete this._tag; else this._tag = validate("tag", tag); } /** * The type of an image reference indicates how the image can be * accessed, either through a Docker host (daemon) or directly to a * container registry. * * @remarks * A reference is a valid `dockerhost` type ref when it contains a valid * dockerHost string and either: * - A valid image id or * - A valid path and either a valid tag or digest. * * A reference is a valid `registry` type ref when it contains a valid * domain, path, and either a tag or a digest. * * If not enough information is present to access and uniquely identify a * container image, the type is `incomplete`. */ get type(): ImageRefType { if (this._dockerHost) { return this._id || (this._path && (this._tag || this._digest)) ? "dockerhost" : "incomplete"; } return this._domain && this._path && (this._tag || this._digest) ? "registry" : "incomplete"; } } /** * Factory function for creating a {@link docker.MutableImageRef}. * @remarks * Can also be used to clone an existing {@link docker.MutableImageRef} or * to create a mutable version of an existing {@link docker.ImageRef}. * @public */ export function mutableImageRef(ref: ImageNameString, normalize?: boolean): MutableImageRef; /** * Factory function for creating a {@link docker.MutableImageRef}. * @remarks * Can also be used to clone an existing {@link docker.MutableImageRef} or * to create a mutable version of an existing {@link docker.ImageRef}. * @public */ export function mutableImageRef(info?: ImageRefData): MutableImageRef; export function mutableImageRef(info?: ImageRefData | ImageNameString, normalize = false): MutableImageRef { return new MutableImageRef(info as any, normalize); } /** * Factory function for creating a {@link docker.ImageRef} or cloning an * existing one. * @public */ export function imageRef(ref: ImageNameString, normalize?: boolean): ImageRef; /** * Factory function for creating a {@link docker.ImageRef} or cloning an * existing one. * @public */ export function imageRef(info?: ImageRefData): ImageRef; export function imageRef(info?: ImageRefData | ImageNameString, normalize = false): ImageRef { const mutable = new MutableImageRef(info as any, normalize); return mutable.freeze(); } /** * A more specific type of {@link docker.ImageRef} that contains sufficient * information to uniquely identify an image on a container registry. * @public */ export interface ImageRefRegistry { readonly digest?: string; readonly domain: string; readonly familiar: string; readonly id?: ImageIdString; readonly name: string; readonly nameTag?: string; readonly path: string; readonly pathTag?: string; readonly ref: string; readonly registry: string; readonly registryRef: string; readonly registryDigest?: string; readonly registryTag?: string; readonly tag?: string; readonly type: "registry"; } /** * A type guard for determining whether a {@link docker.ImageRef} is a * {@link docker.ImageRefRegistry}. * @public */ export function isImageRefRegistry(ref: ImageRef): ref is ImageRefRegistry { return ref.type === "registry"; } /** * A type guard for determining whether a {@link docker.ImageRef} is a * {@link docker.ImageRefRegistry} that has the `id` property set. * @public */ export function isImageRefRegistryWithId(ref: ImageRef): ref is WithId<ImageRefRegistry> { return ref.type === "registry" && typeof ref.id === "string"; } /** * A more specific type of {@link docker.ImageRef} that contains sufficient * information to uniquely identify an image on a specific Docker host * (daemon). * @public */ export interface ImageRefDockerHost { readonly digest?: string; readonly dockerHost: string; readonly domain?: string; readonly familiar: string; readonly id?: ImageIdString; readonly name: string; readonly nameTag?: string; readonly path: string; readonly pathTag?: string; readonly ref: string; readonly registry?: string; readonly registryRef?: string; readonly registryDigest?: string; readonly registryTag?: string; readonly tag?: string; readonly type: "dockerhost"; } /** * A type guard for determining whether a {@link docker.ImageRef} is a * {@link docker.ImageRefDockerHost}. * @public */ export function isImageRefDockerhost(ref: ImageRef): ref is ImageRefDockerHost { return ref.type === "dockerhost"; } /** * A type guard for determining whether a {@link docker.ImageRef} is a * {@link docker.ImageRefDockerHost} that has the `id` property set. * @public */ export function isImageRefDockerhostWithId(ref: ImageRef): ref is WithId<ImageRefDockerHost> { return ref.type === "dockerhost" && typeof ref.id === "string"; } /** * A type guard for asserting whether an object has a property that is not * undefined. * @public */ function hasProperty<T extends object, K extends keyof T>(o: T, k: K): o is T & WithRequiredT<T, K> { return o[k] !== undefined; }
the_stack
import { DebugFlags, UseOnigurumaFindOptions } from '../debug'; import type { LineTokens, StateStack } from './grammar'; import { disposeOnigString, FindOption, IOnigCaptureIndex, OnigString } from '../onigLib'; import { BeginEndRule, BeginWhileRule, CaptureRule, CompiledRule, endRuleId, MatchRule, Rule, RuleId, whileRuleId } from '../rule'; import { performanceNow } from '../utils'; import type { AttributedScopeStack, Grammar, Injection } from './grammar'; class TokenizeStringResult { constructor( public readonly stack: StateStack, public readonly stoppedEarly: boolean ) { } } /** * Tokenize a string * @param grammar * @param lineText * @param isFirstLine * @param linePos * @param stack * @param lineTokens * @param checkWhileConditions * @param timeLimit Use `0` to indicate no time limit * @returns the StackElement or StackElement.TIME_LIMIT_REACHED if the time limit has been reached */ export function _tokenizeString( grammar: Grammar, lineText: OnigString, isFirstLine: boolean, linePos: number, stack: StateStack, lineTokens: LineTokens, checkWhileConditions: boolean, timeLimit: number ): TokenizeStringResult { const lineLength = lineText.content.length; let STOP = false; let anchorPosition = -1; if (checkWhileConditions) { const whileCheckResult = _checkWhileConditions( grammar, lineText, isFirstLine, linePos, stack, lineTokens ); stack = whileCheckResult.stack; linePos = whileCheckResult.linePos; isFirstLine = whileCheckResult.isFirstLine; anchorPosition = whileCheckResult.anchorPosition; } const startTime = Date.now(); while (!STOP) { if (timeLimit !== 0) { const elapsedTime = Date.now() - startTime; if (elapsedTime > timeLimit) { return new TokenizeStringResult(stack, true); } } scanNext(); // potentially modifies linePos && anchorPosition } return new TokenizeStringResult(stack, false); function scanNext(): void { if (DebugFlags.InDebugMode) { console.log(""); console.log( `@@scanNext ${linePos}: |${lineText.content .substr(linePos) .replace(/\n$/, "\\n")}|` ); } const r = matchRuleOrInjections( grammar, lineText, isFirstLine, linePos, stack, anchorPosition ); if (!r) { if (DebugFlags.InDebugMode) { console.log(" no more matches."); } // No match lineTokens.produce(stack, lineLength); STOP = true; return; } const captureIndices: IOnigCaptureIndex[] = r.captureIndices; const matchedRuleId = r.matchedRuleId; const hasAdvanced = captureIndices && captureIndices.length > 0 ? captureIndices[0].end > linePos : false; if (matchedRuleId === endRuleId) { // We matched the `end` for this rule => pop it const poppedRule = <BeginEndRule>stack.getRule(grammar); if (DebugFlags.InDebugMode) { console.log( " popping " + poppedRule.debugName + " - " + poppedRule.debugEndRegExp ); } lineTokens.produce(stack, captureIndices[0].start); stack = stack.withContentNameScopesList(stack.nameScopesList); handleCaptures( grammar, lineText, isFirstLine, stack, lineTokens, poppedRule.endCaptures, captureIndices ); lineTokens.produce(stack, captureIndices[0].end); // pop const popped = stack; stack = stack.parent!; anchorPosition = popped.getAnchorPos(); if (!hasAdvanced && popped.getEnterPos() === linePos) { // Grammar pushed & popped a rule without advancing if (DebugFlags.InDebugMode) { console.error( "[1] - Grammar is in an endless loop - Grammar pushed & popped a rule without advancing" ); } // See https://github.com/Microsoft/vscode-textmate/issues/12 // Let's assume this was a mistake by the grammar author and the intent was to continue in this state stack = popped; lineTokens.produce(stack, lineLength); STOP = true; return; } } else { // We matched a rule! const _rule = grammar.getRule(matchedRuleId); lineTokens.produce(stack, captureIndices[0].start); const beforePush = stack; // push it on the stack rule const scopeName = _rule.getName(lineText.content, captureIndices); const nameScopesList = stack.contentNameScopesList.pushAttributed( scopeName, grammar ); stack = stack.push( matchedRuleId, linePos, anchorPosition, captureIndices[0].end === lineLength, null, nameScopesList, nameScopesList ); if (_rule instanceof BeginEndRule) { const pushedRule = _rule; if (DebugFlags.InDebugMode) { console.log( " pushing " + pushedRule.debugName + " - " + pushedRule.debugBeginRegExp ); } handleCaptures( grammar, lineText, isFirstLine, stack, lineTokens, pushedRule.beginCaptures, captureIndices ); lineTokens.produce(stack, captureIndices[0].end); anchorPosition = captureIndices[0].end; const contentName = pushedRule.getContentName( lineText.content, captureIndices ); const contentNameScopesList = nameScopesList.pushAttributed( contentName, grammar ); stack = stack.withContentNameScopesList(contentNameScopesList); if (pushedRule.endHasBackReferences) { stack = stack.withEndRule( pushedRule.getEndWithResolvedBackReferences( lineText.content, captureIndices ) ); } if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) { // Grammar pushed the same rule without advancing if (DebugFlags.InDebugMode) { console.error( "[2] - Grammar is in an endless loop - Grammar pushed the same rule without advancing" ); } stack = stack.pop()!; lineTokens.produce(stack, lineLength); STOP = true; return; } } else if (_rule instanceof BeginWhileRule) { const pushedRule = <BeginWhileRule>_rule; if (DebugFlags.InDebugMode) { console.log(" pushing " + pushedRule.debugName); } handleCaptures( grammar, lineText, isFirstLine, stack, lineTokens, pushedRule.beginCaptures, captureIndices ); lineTokens.produce(stack, captureIndices[0].end); anchorPosition = captureIndices[0].end; const contentName = pushedRule.getContentName( lineText.content, captureIndices ); const contentNameScopesList = nameScopesList.pushAttributed( contentName, grammar ); stack = stack.withContentNameScopesList(contentNameScopesList); if (pushedRule.whileHasBackReferences) { stack = stack.withEndRule( pushedRule.getWhileWithResolvedBackReferences( lineText.content, captureIndices ) ); } if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) { // Grammar pushed the same rule without advancing if (DebugFlags.InDebugMode) { console.error( "[3] - Grammar is in an endless loop - Grammar pushed the same rule without advancing" ); } stack = stack.pop()!; lineTokens.produce(stack, lineLength); STOP = true; return; } } else { const matchingRule = <MatchRule>_rule; if (DebugFlags.InDebugMode) { console.log( " matched " + matchingRule.debugName + " - " + matchingRule.debugMatchRegExp ); } handleCaptures( grammar, lineText, isFirstLine, stack, lineTokens, matchingRule.captures, captureIndices ); lineTokens.produce(stack, captureIndices[0].end); // pop rule immediately since it is a MatchRule stack = stack.pop()!; if (!hasAdvanced) { // Grammar is not advancing, nor is it pushing/popping if (DebugFlags.InDebugMode) { console.error( "[4] - Grammar is in an endless loop - Grammar is not advancing, nor is it pushing/popping" ); } stack = stack.safePop(); lineTokens.produce(stack, lineLength); STOP = true; return; } } } if (captureIndices[0].end > linePos) { // Advance stream linePos = captureIndices[0].end; isFirstLine = false; } } } /** * Walk the stack from bottom to top, and check each while condition in this order. * If any fails, cut off the entire stack above the failed while condition. While conditions * may also advance the linePosition. */ function _checkWhileConditions(grammar: Grammar, lineText: OnigString, isFirstLine: boolean, linePos: number, stack: StateStack, lineTokens: LineTokens): IWhileCheckResult { let anchorPosition = (stack.beginRuleCapturedEOL ? 0 : -1); interface IWhileStack { readonly stack: StateStack; readonly rule: BeginWhileRule; } const whileRules: IWhileStack[] = []; for (let node: StateStack | null = stack; node; node = node.pop()) { const nodeRule = node.getRule(grammar); if (nodeRule instanceof BeginWhileRule) { whileRules.push({ rule: nodeRule, stack: node }); } } for (let whileRule = whileRules.pop(); whileRule; whileRule = whileRules.pop()) { const { ruleScanner, findOptions } = prepareRuleWhileSearch(whileRule.rule, grammar, whileRule.stack.endRule, isFirstLine, linePos === anchorPosition); const r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions); if (DebugFlags.InDebugMode) { console.log(' scanning for while rule'); console.log(ruleScanner.toString()); } if (r) { const matchedRuleId = r.ruleId; if (matchedRuleId !== whileRuleId) { // we shouldn't end up here stack = whileRule.stack.pop()!; break; } if (r.captureIndices && r.captureIndices.length) { lineTokens.produce(whileRule.stack, r.captureIndices[0].start); handleCaptures(grammar, lineText, isFirstLine, whileRule.stack, lineTokens, whileRule.rule.whileCaptures, r.captureIndices); lineTokens.produce(whileRule.stack, r.captureIndices[0].end); anchorPosition = r.captureIndices[0].end; if (r.captureIndices[0].end > linePos) { linePos = r.captureIndices[0].end; isFirstLine = false; } } } else { if (DebugFlags.InDebugMode) { console.log(' popping ' + whileRule.rule.debugName + ' - ' + whileRule.rule.debugWhileRegExp); } stack = whileRule.stack.pop()!; break; } } return { stack: stack, linePos: linePos, anchorPosition: anchorPosition, isFirstLine: isFirstLine }; } interface IWhileCheckResult { readonly stack: StateStack; readonly linePos: number; readonly anchorPosition: number; readonly isFirstLine: boolean; } function matchRuleOrInjections(grammar: Grammar, lineText: OnigString, isFirstLine: boolean, linePos: number, stack: StateStack, anchorPosition: number): IMatchResult | null { // Look for normal grammar rule const matchResult = matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition); // Look for injected rules const injections = grammar.getInjections(); if (injections.length === 0) { // No injections whatsoever => early return return matchResult; } const injectionResult = matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition); if (!injectionResult) { // No injections matched => early return return matchResult; } if (!matchResult) { // Only injections matched => early return return injectionResult; } // Decide if `matchResult` or `injectionResult` should win const matchResultScore = matchResult.captureIndices[0].start; const injectionResultScore = injectionResult.captureIndices[0].start; if (injectionResultScore < matchResultScore || (injectionResult.priorityMatch && injectionResultScore === matchResultScore)) { // injection won! return injectionResult; } return matchResult; } interface IMatchResult { readonly captureIndices: IOnigCaptureIndex[]; readonly matchedRuleId: RuleId | typeof endRuleId; } function matchRule(grammar: Grammar, lineText: OnigString, isFirstLine: boolean, linePos: number, stack: StateStack, anchorPosition: number): IMatchResult | null { const rule = stack.getRule(grammar); const { ruleScanner, findOptions } = prepareRuleSearch(rule, grammar, stack.endRule, isFirstLine, linePos === anchorPosition); let perfStart = 0; if (DebugFlags.InDebugMode) { perfStart = performanceNow(); } const r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions); if (DebugFlags.InDebugMode) { const elapsedMillis = performanceNow() - perfStart; if (elapsedMillis > 5) { console.warn(`Rule ${rule.debugName} (${rule.id}) matching took ${elapsedMillis} against '${lineText}'`); } console.log(` scanning for (linePos: ${linePos}, anchorPosition: ${anchorPosition})`); console.log(ruleScanner.toString()); if (r) { console.log(`matched rule id: ${r.ruleId} from ${r.captureIndices[0].start} to ${r.captureIndices[0].end}`); } } if (r) { return { captureIndices: r.captureIndices, matchedRuleId: r.ruleId }; } return null; } function matchInjections(injections: Injection[], grammar: Grammar, lineText: OnigString, isFirstLine: boolean, linePos: number, stack: StateStack, anchorPosition: number): IMatchInjectionsResult | null { // The lower the better let bestMatchRating = Number.MAX_VALUE; let bestMatchCaptureIndices: IOnigCaptureIndex[] | null = null; let bestMatchRuleId: RuleId | typeof endRuleId; let bestMatchResultPriority: number = 0; const scopes = stack.contentNameScopesList.getScopeNames(); for (let i = 0, len = injections.length; i < len; i++) { const injection = injections[i]; if (!injection.matcher(scopes)) { // injection selector doesn't match stack continue; } const rule = grammar.getRule(injection.ruleId); const { ruleScanner, findOptions } = prepareRuleSearch(rule, grammar, null, isFirstLine, linePos === anchorPosition); const matchResult = ruleScanner.findNextMatchSync(lineText, linePos, findOptions); if (!matchResult) { continue; } if (DebugFlags.InDebugMode) { console.log(` matched injection: ${injection.debugSelector}`); console.log(ruleScanner.toString()); } const matchRating = matchResult.captureIndices[0].start; if (matchRating >= bestMatchRating) { // Injections are sorted by priority, so the previous injection had a better or equal priority continue; } bestMatchRating = matchRating; bestMatchCaptureIndices = matchResult.captureIndices; bestMatchRuleId = matchResult.ruleId; bestMatchResultPriority = injection.priority; if (bestMatchRating === linePos) { // No more need to look at the rest of the injections. break; } } if (bestMatchCaptureIndices) { return { priorityMatch: bestMatchResultPriority === -1, captureIndices: bestMatchCaptureIndices, matchedRuleId: bestMatchRuleId! }; } return null; } interface IMatchInjectionsResult { readonly priorityMatch: boolean; readonly captureIndices: IOnigCaptureIndex[]; readonly matchedRuleId: RuleId | typeof endRuleId; } function prepareRuleSearch(rule: Rule, grammar: Grammar, endRegexSource: string | null, allowA: boolean, allowG: boolean): { ruleScanner: CompiledRule; findOptions: number; } { if (UseOnigurumaFindOptions) { const ruleScanner = rule.compile(grammar, endRegexSource); const findOptions = getFindOptions(allowA, allowG); return { ruleScanner, findOptions }; } const ruleScanner = rule.compileAG(grammar, endRegexSource, allowA, allowG); return { ruleScanner, findOptions: FindOption.None }; } function prepareRuleWhileSearch(rule: BeginWhileRule, grammar: Grammar, endRegexSource: string | null, allowA: boolean, allowG: boolean): { ruleScanner: CompiledRule<RuleId | typeof whileRuleId>; findOptions: number; } { if (UseOnigurumaFindOptions) { const ruleScanner = rule.compileWhile(grammar, endRegexSource); const findOptions = getFindOptions(allowA, allowG); return { ruleScanner, findOptions }; } const ruleScanner = rule.compileWhileAG(grammar, endRegexSource, allowA, allowG); return { ruleScanner, findOptions: FindOption.None }; } function getFindOptions(allowA: boolean, allowG: boolean): number { let options = FindOption.None; if (!allowA) { options |= FindOption.NotBeginString; } if (!allowG) { options |= FindOption.NotBeginPosition; } return options; } function handleCaptures(grammar: Grammar, lineText: OnigString, isFirstLine: boolean, stack: StateStack, lineTokens: LineTokens, captures: (CaptureRule | null)[], captureIndices: IOnigCaptureIndex[]): void { if (captures.length === 0) { return; } const lineTextContent = lineText.content; const len = Math.min(captures.length, captureIndices.length); const localStack: LocalStackElement[] = []; const maxEnd = captureIndices[0].end; for (let i = 0; i < len; i++) { const captureRule = captures[i]; if (captureRule === null) { // Not interested continue; } const captureIndex = captureIndices[i]; if (captureIndex.length === 0) { // Nothing really captured continue; } if (captureIndex.start > maxEnd) { // Capture going beyond consumed string break; } // pop captures while needed while (localStack.length > 0 && localStack[localStack.length - 1].endPos <= captureIndex.start) { // pop! lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos); localStack.pop(); } if (localStack.length > 0) { lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, captureIndex.start); } else { lineTokens.produce(stack, captureIndex.start); } if (captureRule.retokenizeCapturedWithRuleId) { // the capture requires additional matching const scopeName = captureRule.getName(lineTextContent, captureIndices); const nameScopesList = stack.contentNameScopesList.pushAttributed(scopeName, grammar); const contentName = captureRule.getContentName(lineTextContent, captureIndices); const contentNameScopesList = nameScopesList.pushAttributed(contentName, grammar); const stackClone = stack.push(captureRule.retokenizeCapturedWithRuleId, captureIndex.start, -1, false, null, nameScopesList, contentNameScopesList); const onigSubStr = grammar.createOnigString(lineTextContent.substring(0, captureIndex.end)); _tokenizeString(grammar, onigSubStr, (isFirstLine && captureIndex.start === 0), captureIndex.start, stackClone, lineTokens, false, /* no time limit */0); disposeOnigString(onigSubStr); continue; } const captureRuleScopeName = captureRule.getName(lineTextContent, captureIndices); if (captureRuleScopeName !== null) { // push const base = localStack.length > 0 ? localStack[localStack.length - 1].scopes : stack.contentNameScopesList; const captureRuleScopesList = base.pushAttributed(captureRuleScopeName, grammar); localStack.push(new LocalStackElement(captureRuleScopesList, captureIndex.end)); } } while (localStack.length > 0) { // pop! lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos); localStack.pop(); } } export class LocalStackElement { public readonly scopes: AttributedScopeStack; public readonly endPos: number; constructor(scopes: AttributedScopeStack, endPos: number) { this.scopes = scopes; this.endPos = endPos; } }
the_stack
import * as util from 'util'; import * as path from 'path'; import { Logger } from '@salesforce/core'; import { WorkspaceFileState, toReadableState } from './workspaceFileState'; import { AggregateSourceElement } from './aggregateSourceElement'; import { AggregateSourceElements } from './aggregateSourceElements'; import { MetadataTypeFactory } from './metadataTypeFactory'; import { replaceForwardSlashes } from './sourcePathUtil'; import MetadataRegistry = require('./metadataRegistry'); interface ComponentFailure { changed: boolean; componentType: string; created: boolean; createdDate: Date; deleted: boolean; fileName: string; fullName: string; problem: string; problemType: string; success: boolean; columnNumber?: number; lineNumber?: number; } const _createRowsForConflictStatus = function ( rows, createDisplayRowData, outpuFileInfo, projectPath, thisSelf, isStatus ) { const row = createDisplayRowData(outpuFileInfo, thisSelf.trimParentFromPath(projectPath, outpuFileInfo.filePath)); if (isStatus && outpuFileInfo.isConflict) { row.state += ' (Conflict)'; } rows.push(row); }; const _getState = function (state, deleteSupported) { const calcState = state ? state : WorkspaceFileState.DELETED; return !deleteSupported && calcState === WorkspaceFileState.DELETED ? `${toReadableState(WorkspaceFileState.DELETED)} (local file)` : toReadableState(calcState); }; const _getFullNameFromDeleteFailure = function (failure) { /* * Note the weird fullName behavior in the mdapi deploy file property. * Fortunately we can recover the fullName from the error message text! */ const noComponentFoundRegex = new RegExp(`No ${failure.componentType} named: (.+) found$`); const matches = noComponentFoundRegex.exec(failure.problem); return matches !== null ? matches[1] : null; }; const _getSourceElement = function ( componentFailure: ComponentFailure, aggregateSourceElements: AggregateSourceElements, metadataRegistry: MetadataRegistry ) { const failureMetadataType = MetadataTypeFactory.getMetadataTypeFromMetadataName( componentFailure.componentType, metadataRegistry ); if (failureMetadataType) { let fullName = componentFailure.fullName; if (fullName === 'destructiveChanges.xml') { fullName = _getFullNameFromDeleteFailure(componentFailure); } else { componentFailure.fileName = replaceForwardSlashes(componentFailure.fileName); // fix windows specific file separators fullName = failureMetadataType.getAggregateFullNameFromComponentFailure(componentFailure); } const sourceElementKey = AggregateSourceElement.getKeyFromMetadataNameAndFullName( failureMetadataType.getAggregateMetadataName(), fullName ); return aggregateSourceElements.findSourceElementByKey(sourceElementKey); } return null; }; const _parseComponentFailure = function ( componentFailure: ComponentFailure, sourceElements: AggregateSourceElements, metadataRegistry: MetadataRegistry, logger: Logger ) { let aggregateSourceElement; let filePath; let fullName; try { // see if we can map the error to a local sourceElement aggregateSourceElement = _getSourceElement(componentFailure, sourceElements, metadataRegistry); if (!util.isNullOrUndefined(aggregateSourceElement)) { const componentMetadataType = MetadataTypeFactory.getMetadataTypeFromMetadataName( componentFailure.componentType, metadataRegistry ); fullName = componentMetadataType.getWorkspaceFullNameFromComponentFailure(componentFailure); // does the error reference the -meta file or the content file? const componentFailureIsInMetadataFile = componentMetadataType.componentFailureIsInMetadataFile( componentFailure.fileName ); if (componentFailureIsInMetadataFile) { filePath = aggregateSourceElement.getMetadataWorkspacePathsForTypeAndFullName( componentFailure.componentType, fullName )[0]; } else { // the file we are looking for is a content file const matchingPaths = aggregateSourceElement.getContentWorkspacePathsForTypeAndFullName( componentFailure.componentType, fullName ); if (matchingPaths.length > 0) { filePath = componentMetadataType.getComponentFailureWorkspaceContentPath( aggregateSourceElement.getMetadataFilePath(), matchingPaths ); } } if (!filePath) { filePath = aggregateSourceElement.getMetadataFilePath(); } } else { filePath = ''; } } catch (e) { if (logger) { logger.debug(e); } } return { columnNumber: componentFailure.columnNumber, lineNumber: componentFailure.lineNumber, error: componentFailure.problem, fullName, type: componentFailure.componentType, filePath, problemType: componentFailure.problemType, }; }; const self = { getDeployFailures( resp, aggregateSourceElements: AggregateSourceElements, metadataRegistry: MetadataRegistry, logger?: Logger ) { const deployFailures = []; // look into component details assemble deployment failure message if (resp.details && resp.details.componentFailures) { if (Array.isArray(resp.details.componentFailures)) { // Array of failures for (let i = 0, len = resp.details.componentFailures.length; i < len; i++) { const comp = resp.details.componentFailures[i]; deployFailures.push(_parseComponentFailure(comp, aggregateSourceElements, metadataRegistry, logger)); } } else { // Single failure const comp = resp.details.componentFailures; deployFailures.push(_parseComponentFailure(comp, aggregateSourceElements, metadataRegistry, logger)); } } else if (!util.isNullOrUndefined(resp.ErrorMsg)) { deployFailures.push({ error: resp.ErrorMsg }); } else { deployFailures.push({ error: 'Unknown' }); } return deployFailures; }, getFullNameFromDeleteFailure(failure) { return _getFullNameFromDeleteFailure(failure); }, /** * report formatting for retrieve failures. * * @param resp - the result of toolingRetrieve * @param detailProperty - the name of the property with the deploy details. Defaults to 'DeployDetails'. * @returns {string} represents reported deployment errors * @private */ getRetrieveFailureMessage(resp, messages) { let msg = ''; if (!util.isNullOrUndefined(resp.messages)) { if (resp.messages instanceof Array && resp.messages.length > 0) { for (let i = 0, len = resp.messages.length; i < len; ++i) { msg += resp.messages[i].problem; if (i < len - 1) { msg += '\n'; } } } else { msg = resp.messages.problem; } } else if (!util.isNullOrUndefined(resp.errorMessage)) { msg = resp.errorMessage; } else if (util.isNullOrUndefined(resp.fileProperties) || !Array.isArray(resp.fileProperties)) { msg = messages.getMessage('mdapiPullCommandNoDataReturned'); } else { msg = 'Unknown'; } return msg; }, /** * helper method used by the sync commands to retrieve status of a container async request. * * @param force - the force api * @param api - scratch org api * @param sobjectId - id of the container async request * @param messages - L10N access obeject * @param callback - callback that resolves a value once the ContainerAsyncRequest is complete. * @param resolve - outer promise resolve function * @param reject - outer promise reject handler * @returns {Promise} */ retrieveContainerStatus(force, api, sobjectId, messages, callback, resolve, reject) { return force.toolingRetrieve(api, 'ContainerAsyncRequest', sobjectId).then((resp) => { switch (resp.State) { case 'Completed': return resolve(callback()); case 'Failed': { const deployFailed = new Error(resp.ErrorMsg); deployFailed.name = 'ContainerDeployFailed'; return reject(deployFailed); } case 'Invalidated': { const invalidatedError = // @todo re-label message new Error(messages.getMessage('pushCommandAsyncRequestInvalidated')); invalidatedError.name = 'ContainerDeployInvalidated'; return reject(invalidatedError); } default: { let deployErrMsg = messages.getMessage('pushCommandAsyncRequestUnexpected'); const respError = resp.ErrorMsg; if (!util.isNullOrUndefined(respError)) { deployErrMsg += ` ${respError}.`; } const deployError = new Error(deployErrMsg); deployError.name = 'ContainerDeployError'; return reject(deployError); } } }); }, /** * Removes a parent path to make a relative path. * * @param parent - the parent path (usually a project directory) * @param elementPath - the full path that contains the parent. * @returns {*} */ trimParentFromPath(parent, elementPath) { if (util.isNullOrUndefined(elementPath) || elementPath.indexOf(parent) !== 0) { return null; } if (util.isNullOrUndefined(parent)) { return null; } const trimmedParent = parent.trim(); if (trimmedParent.length < 1) { return null; } let newParent = trimmedParent; if (!parent.endsWith(path.sep)) { newParent = `${trimmedParent}${path.sep}`; } const paths = elementPath.trim().split(newParent); const element = paths[paths.length - 1]; // handle the case where both the parent and elementPath are the same. if (element === elementPath) { return ''; } return element; }, // Return table column metadata. Changesets commands do not display state info since it doesn't apply. getColumnMetaInfo(messages, withoutState?) { const stateCol = withoutState ? [] : [{ key: 'state', label: messages.getMessage('stateTableColumn') }]; const columns = [ { key: 'fullName', label: messages.getMessage('fullNameTableColumn') }, { key: 'type', label: messages.getMessage('typeTableColumn') }, { key: 'filePath', label: messages.getMessage('workspacePathTableColumn'), }, ]; return [...stateCol, ...columns]; }, createDeployFailureRow(rows, failure, projectPath) { if (!util.isNullOrUndefined(failure.filePath)) { if (failure.filePath === '') { failure.filePath = 'N/A'; } else { failure.filePath = self.trimParentFromPath(projectPath, failure.filePath); } } const columnNumber = failure.columnNumber || 0; // sometimes we only get the line number if (failure.lineNumber) { failure.error += ` (${failure.lineNumber}:${columnNumber})`; } rows.push(failure); }, createConflictRows(rows, conflictFileInfo, projectPath) { const _createDisplayRowData = (fileInfo, filePath) => ({ state: 'Conflict', fullName: fileInfo.fullName, type: fileInfo.type, filePath, }); _createRowsForConflictStatus(rows, _createDisplayRowData, conflictFileInfo, projectPath, self, false); }, createStatusLocalRows(rows, outputFileInfo, projectPath) { const _createDisplayRowData = (fileInfo, filePath) => ({ state: `Local ${_getState(fileInfo.state, fileInfo.deleteSupported)}`, fullName: fileInfo.fullName, type: fileInfo.type, filePath, }); _createRowsForConflictStatus(rows, _createDisplayRowData, outputFileInfo, projectPath, self, true); }, // displays a row based on information pulled from a SourceMember row createStatusRemoteRows(rows, sourceMember, projectPath) { const _createDisplayRowData = (sm, filePath) => ({ state: `Remote ${toReadableState(sm.state)}`, fullName: sm.fullName, type: sm.type, filePath, }); _createRowsForConflictStatus(rows, _createDisplayRowData, sourceMember, projectPath, self, true); }, createDisplayRows(rows, outputFileInfo, projectPath) { if (util.isNullOrUndefined(rows)) { const error = new Error('Row collection not specified.'); error['name'] = 'MissingRowCollection'; throw error; } if (util.isNullOrUndefined(outputFileInfo)) { const error = new Error('Output file info not found.'); error['name'] = 'SourceElementNotFound'; throw error; } if (util.isNullOrUndefined(projectPath)) { const error = new Error("Can't display row without the projectPath"); error['name'] = 'MissingProjectPathForDisplay'; throw error; } const _createDisplayRowData = (element, filePath) => ({ state: _getState(element.state, element.deleteSupported), fullName: element.fullName, type: element.type, filePath, }); const filePath = outputFileInfo.filePath; rows.push(_createDisplayRowData(outputFileInfo, self.trimParentFromPath(projectPath, filePath))); }, }; export = self;
the_stack
import * as coreHttp from "@azure/core-http"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { StorageClientContext } from "../storageClientContext"; import { ShareCreateOptionalParams, ShareCreateResponse, ShareGetPropertiesOptionalParams, ShareGetPropertiesResponse, ShareDeleteOptionalParams, ShareDeleteResponse, ShareAcquireLeaseOptionalParams, ShareAcquireLeaseResponse, ShareReleaseLeaseOptionalParams, ShareReleaseLeaseResponse, ShareChangeLeaseOptionalParams, ShareChangeLeaseResponse, ShareRenewLeaseOptionalParams, ShareRenewLeaseResponse, ShareBreakLeaseOptionalParams, ShareBreakLeaseResponse, ShareCreateSnapshotOptionalParams, ShareCreateSnapshotResponse, SharePermission, ShareCreatePermissionOptionalParams, ShareCreatePermissionResponse, ShareGetPermissionOptionalParams, ShareGetPermissionResponse, ShareSetPropertiesOptionalParams, ShareSetPropertiesResponse, ShareSetMetadataOptionalParams, ShareSetMetadataResponse, ShareGetAccessPolicyOptionalParams, ShareGetAccessPolicyResponse, ShareSetAccessPolicyOptionalParams, ShareSetAccessPolicyResponse, ShareGetStatisticsOptionalParams, ShareGetStatisticsResponse, ShareRestoreOptionalParams, ShareRestoreResponse } from "../models"; /** Class representing a Share. */ export class Share { private readonly client: StorageClientContext; /** * Initialize a new instance of the class Share class. * @param client Reference to the service client */ constructor(client: StorageClientContext) { this.client = client; } /** * Creates a new share under the specified account. If the share with the same name already exists, the * operation fails. * @param options The options parameters. */ create(options?: ShareCreateOptionalParams): Promise<ShareCreateResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, createOperationSpec ) as Promise<ShareCreateResponse>; } /** * Returns all user-defined metadata and system properties for the specified share or share snapshot. * The data returned does not include the share's list of files. * @param options The options parameters. */ getProperties( options?: ShareGetPropertiesOptionalParams ): Promise<ShareGetPropertiesResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, getPropertiesOperationSpec ) as Promise<ShareGetPropertiesResponse>; } /** * Operation marks the specified share or share snapshot for deletion. The share or share snapshot and * any files contained within it are later deleted during garbage collection. * @param options The options parameters. */ delete(options?: ShareDeleteOptionalParams): Promise<ShareDeleteResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, deleteOperationSpec ) as Promise<ShareDeleteResponse>; } /** * The Lease Share operation establishes and manages a lock on a share, or the specified snapshot for * set and delete share operations. * @param options The options parameters. */ acquireLease( options?: ShareAcquireLeaseOptionalParams ): Promise<ShareAcquireLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, acquireLeaseOperationSpec ) as Promise<ShareAcquireLeaseResponse>; } /** * The Lease Share operation establishes and manages a lock on a share, or the specified snapshot for * set and delete share operations. * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ releaseLease( leaseId: string, options?: ShareReleaseLeaseOptionalParams ): Promise<ShareReleaseLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, releaseLeaseOperationSpec ) as Promise<ShareReleaseLeaseResponse>; } /** * The Lease Share operation establishes and manages a lock on a share, or the specified snapshot for * set and delete share operations. * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ changeLease( leaseId: string, options?: ShareChangeLeaseOptionalParams ): Promise<ShareChangeLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, changeLeaseOperationSpec ) as Promise<ShareChangeLeaseResponse>; } /** * The Lease Share operation establishes and manages a lock on a share, or the specified snapshot for * set and delete share operations. * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ renewLease( leaseId: string, options?: ShareRenewLeaseOptionalParams ): Promise<ShareRenewLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, renewLeaseOperationSpec ) as Promise<ShareRenewLeaseResponse>; } /** * The Lease Share operation establishes and manages a lock on a share, or the specified snapshot for * set and delete share operations. * @param options The options parameters. */ breakLease( options?: ShareBreakLeaseOptionalParams ): Promise<ShareBreakLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, breakLeaseOperationSpec ) as Promise<ShareBreakLeaseResponse>; } /** * Creates a read-only snapshot of a share. * @param options The options parameters. */ createSnapshot( options?: ShareCreateSnapshotOptionalParams ): Promise<ShareCreateSnapshotResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, createSnapshotOperationSpec ) as Promise<ShareCreateSnapshotResponse>; } /** * Create a permission (a security descriptor). * @param sharePermission A permission (a security descriptor) at the share level. * @param options The options parameters. */ createPermission( sharePermission: SharePermission, options?: ShareCreatePermissionOptionalParams ): Promise<ShareCreatePermissionResponse> { const operationArguments: coreHttp.OperationArguments = { sharePermission, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, createPermissionOperationSpec ) as Promise<ShareCreatePermissionResponse>; } /** * Returns the permission (security descriptor) for a given key * @param filePermissionKey Key of the permission to be set for the directory/file. * @param options The options parameters. */ getPermission( filePermissionKey: string, options?: ShareGetPermissionOptionalParams ): Promise<ShareGetPermissionResponse> { const operationArguments: coreHttp.OperationArguments = { filePermissionKey, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, getPermissionOperationSpec ) as Promise<ShareGetPermissionResponse>; } /** * Sets properties for the specified share. * @param options The options parameters. */ setProperties( options?: ShareSetPropertiesOptionalParams ): Promise<ShareSetPropertiesResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, setPropertiesOperationSpec ) as Promise<ShareSetPropertiesResponse>; } /** * Sets one or more user-defined name-value pairs for the specified share. * @param options The options parameters. */ setMetadata( options?: ShareSetMetadataOptionalParams ): Promise<ShareSetMetadataResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, setMetadataOperationSpec ) as Promise<ShareSetMetadataResponse>; } /** * Returns information about stored access policies specified on the share. * @param options The options parameters. */ getAccessPolicy( options?: ShareGetAccessPolicyOptionalParams ): Promise<ShareGetAccessPolicyResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, getAccessPolicyOperationSpec ) as Promise<ShareGetAccessPolicyResponse>; } /** * Sets a stored access policy for use with shared access signatures. * @param options The options parameters. */ setAccessPolicy( options?: ShareSetAccessPolicyOptionalParams ): Promise<ShareSetAccessPolicyResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, setAccessPolicyOperationSpec ) as Promise<ShareSetAccessPolicyResponse>; } /** * Retrieves statistics related to the share. * @param options The options parameters. */ getStatistics( options?: ShareGetStatisticsOptionalParams ): Promise<ShareGetStatisticsResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, getStatisticsOperationSpec ) as Promise<ShareGetStatisticsResponse>; } /** * Restores a previously deleted Share. * @param options The options parameters. */ restore(options?: ShareRestoreOptionalParams): Promise<ShareRestoreResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, restoreOperationSpec ) as Promise<ShareRestoreResponse>; } } // Operation Specifications const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true); const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); const createOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.ShareCreateHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareCreateExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.restype1], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.metadata, Parameters.quota, Parameters.accessTier, Parameters.enabledProtocols, Parameters.rootSquash ], isXML: true, serializer: xmlSerializer }; const getPropertiesOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "GET", responses: { 200: { headersMapper: Mappers.ShareGetPropertiesHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareGetPropertiesExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.shareSnapshot ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId ], isXML: true, serializer: xmlSerializer }; const deleteOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "DELETE", responses: { 202: { headersMapper: Mappers.ShareDeleteHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareDeleteExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.shareSnapshot ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId, Parameters.deleteSnapshots ], isXML: true, serializer: xmlSerializer }; const acquireLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.ShareAcquireLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareAcquireLeaseExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.shareSnapshot, Parameters.comp2 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.action, Parameters.duration, Parameters.proposedLeaseId, Parameters.requestId ], isXML: true, serializer: xmlSerializer }; const releaseLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ShareReleaseLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareReleaseLeaseExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.shareSnapshot, Parameters.comp2 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.requestId, Parameters.action1, Parameters.leaseId1 ], isXML: true, serializer: xmlSerializer }; const changeLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ShareChangeLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareChangeLeaseExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.shareSnapshot, Parameters.comp2 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.proposedLeaseId, Parameters.requestId, Parameters.leaseId1, Parameters.action2 ], isXML: true, serializer: xmlSerializer }; const renewLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ShareRenewLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareRenewLeaseExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.shareSnapshot, Parameters.comp2 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.requestId, Parameters.leaseId1, Parameters.action3 ], isXML: true, serializer: xmlSerializer }; const breakLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 202: { headersMapper: Mappers.ShareBreakLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareBreakLeaseExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.shareSnapshot, Parameters.comp2 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId, Parameters.requestId, Parameters.action4, Parameters.breakPeriod ], isXML: true, serializer: xmlSerializer }; const createSnapshotOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.ShareCreateSnapshotHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareCreateSnapshotExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.comp3 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.metadata ], isXML: true, serializer: xmlSerializer }; const createPermissionOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.ShareCreatePermissionHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareCreatePermissionExceptionHeaders } }, requestBody: Parameters.sharePermission, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.comp4 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.contentType, Parameters.accept, Parameters.version ], isXML: false, contentType: "application/xml; charset=utf-8", serializer: xmlSerializer }; const getPermissionOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SharePermission, headersMapper: Mappers.ShareGetPermissionHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareGetPermissionExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.comp4 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept2, Parameters.filePermissionKey ], serializer }; const setPropertiesOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ShareSetPropertiesHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareSetPropertiesExceptionHeaders } }, queryParameters: [ Parameters.comp, Parameters.timeoutInSeconds, Parameters.restype1 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.quota, Parameters.accessTier, Parameters.rootSquash, Parameters.leaseId ], isXML: true, serializer: xmlSerializer }; const setMetadataOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ShareSetMetadataHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareSetMetadataExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.comp5 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.metadata, Parameters.leaseId ], isXML: true, serializer: xmlSerializer }; const getAccessPolicyOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Composite", className: "SignedIdentifier" } } }, serializedName: "SignedIdentifiers", xmlName: "SignedIdentifiers", xmlIsWrapped: true, xmlElementName: "SignedIdentifier" }, headersMapper: Mappers.ShareGetAccessPolicyHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareGetAccessPolicyExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.comp6 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId ], isXML: true, serializer: xmlSerializer }; const setAccessPolicyOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.ShareSetAccessPolicyHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareSetAccessPolicyExceptionHeaders } }, requestBody: Parameters.shareAcl, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.comp6 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.contentType, Parameters.accept, Parameters.version, Parameters.leaseId ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer }; const getStatisticsOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ShareStats, headersMapper: Mappers.ShareGetStatisticsHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareGetStatisticsExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.comp7 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId ], isXML: true, serializer: xmlSerializer }; const restoreOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.ShareRestoreHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.ShareRestoreExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.restype1, Parameters.comp8 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.requestId, Parameters.deletedShareName, Parameters.deletedShareVersion ], isXML: true, serializer: xmlSerializer };
the_stack
import { bootstrap } from "../Bootstrap"; bootstrap(); import { of as observableOf, zip as observableZip, Observable, Subject, } from "rxjs"; import { take, first, skip } from "rxjs/operators"; import { MockCreator } from "../helper/MockCreator"; import { ImageHelper } from "../helper/ImageHelper"; import { StateServiceMockCreator } from "../helper/StateServiceMockCreator"; import { FrameHelper } from "../helper/FrameHelper"; import { Image } from "../../src/graph/Image"; import { APIWrapper } from "../../src/api/APIWrapper"; import { ImageEnt } from "../../src/api/ents/ImageEnt"; import { Graph } from "../../src/graph/Graph"; import { GraphMode } from "../../src/graph/GraphMode"; import { GraphService } from "../../src/graph/GraphService"; import { NavigationEdgeStatus } from "../../src/graph/interfaces/NavigationEdgeStatus"; import { ImageCache } from "../../src/graph/ImageCache"; import { Sequence } from "../../src/graph/Sequence"; import { IAnimationState } from "../../src/state/interfaces/IAnimationState"; import { AnimationFrame } from "../../src/state/interfaces/AnimationFrame"; import { State } from "../../src/state/State"; import { StateService } from "../../src/state/StateService"; import { PlayService } from "../../src/viewer/PlayService"; import { NavigationDirection } from "../../src/graph/edge/NavigationDirection"; import { DataProvider } from "../helper/ProviderHelper"; describe("PlayService.ctor", () => { it("should be defined when constructed", () => { const api: APIWrapper = new APIWrapper(new DataProvider()); const graphService: GraphService = new GraphService(new Graph(api)); const stateService: StateService = new StateService(State.Traversing); const playService: PlayService = new PlayService(graphService, stateService); expect(playService).toBeDefined(); }); it("should emit default values", (done: () => void) => { const api: APIWrapper = new APIWrapper(new DataProvider()); const graphService: GraphService = new GraphService(new Graph(api)); const stateService: StateService = new StateService(State.Traversing); const playService: PlayService = new PlayService(graphService, stateService); observableZip( playService.direction$, playService.playing$, playService.speed$).pipe( first()) .subscribe( ([d, p, s]: [NavigationDirection, boolean, number]): void => { expect(d).toBe(NavigationDirection.Next); expect(p).toBe(false); expect(s).toBe(0.5); done(); }); }); }); describe("PlayService.playing", () => { it("should be playing after calling play", (done: () => void) => { const api: APIWrapper = new APIWrapper(new DataProvider()); const graphService: GraphService = new GraphService(new Graph(api)); const stateService: StateService = new StateService(State.Traversing); const playService: PlayService = new PlayService(graphService, stateService); playService.play(); expect(playService.playing).toBe(true); playService.playing$ .subscribe( (playing: boolean): void => { expect(playing).toBe(true); done(); }); }); it("should not be playing after calling stop", (done: () => void) => { const api: APIWrapper = new APIWrapper(new DataProvider()); const graphService: GraphService = new GraphService(new Graph(api)); const stateService: StateService = new StateService(State.Traversing); const playService: PlayService = new PlayService(graphService, stateService); playService.play(); const setGraphModeSpy: jasmine.Spy = spyOn(graphService, "setGraphMode").and.stub(); const cutImagesSpy: jasmine.Spy = spyOn(stateService, "cutImages").and.stub(); const setSpeedSpy: jasmine.Spy = spyOn(stateService, "setSpeed").and.stub(); playService.stop(); expect(setGraphModeSpy.calls.count()).toBe(1); expect(setGraphModeSpy.calls.argsFor(0)[0]).toBe(GraphMode.Spatial); expect(cutImagesSpy.calls.count()).toBe(1); expect(setSpeedSpy.calls.count()).toBe(1); expect(setSpeedSpy.calls.argsFor(0)[0]).toBe(1); expect(playService.playing).toBe(false); playService.playing$ .subscribe( (playing: boolean): void => { expect(playing).toBe(false); done(); }); }); }); describe("PlayService.speed$", () => { it("should emit when changing speed", (done: () => void) => { const api: APIWrapper = new APIWrapper(new DataProvider()); const graphService: GraphService = new GraphService(new Graph(api)); const stateService: StateService = new StateService(State.Traversing); const playService: PlayService = new PlayService(graphService, stateService); playService.speed$.pipe( skip(1)) .subscribe( (speed: number): void => { expect(speed).toBe(0); done(); }); playService.setSpeed(0); }); it("should not emit when setting current speed", () => { const api: APIWrapper = new APIWrapper(new DataProvider()); const graphService: GraphService = new GraphService(new Graph(api)); const stateService: StateService = new StateService(State.Traversing); const playService: PlayService = new PlayService(graphService, stateService); playService.setSpeed(1); let speedEmitCount: number = 0; let firstEmit: boolean = true; playService.speed$.pipe( skip(1)) .subscribe( (speed: number): void => { speedEmitCount++; if (firstEmit) { expect(speed).toBe(0); firstEmit = false; } else { expect(speed).toBe(1); } }); playService.setSpeed(0); playService.setSpeed(0); playService.setSpeed(1); playService.setSpeed(1); expect(speedEmitCount).toBe(2); }); it("should clamp speed values to 0, 1 interval", (done: () => void) => { const api: APIWrapper = new APIWrapper(new DataProvider()); const graphService: GraphService = new GraphService(new Graph(api)); const stateService: StateService = new StateService(State.Traversing); const playService: PlayService = new PlayService(graphService, stateService); let firstEmit: boolean = true; playService.speed$.pipe( skip(1)) .subscribe( (speed: number): void => { if (firstEmit) { expect(speed).toBe(0); firstEmit = false; } else { expect(speed).toBe(1); done(); } }); playService.setSpeed(-1); playService.setSpeed(2); }); }); let createState: () => IAnimationState = (): IAnimationState => { return { alpha: 0, camera: null, currentCamera: null, currentIndex: 0, currentImage: null, currentTransform: null, lastImage: null, motionless: false, imagesAhead: 0, previousImage: null, previousTransform: null, reference: null, state: State.Traversing, trajectory: null, zoom: 0, }; }; describe("PlayService.play", () => { let imageHelper: ImageHelper; let api: APIWrapper; let graphService: GraphService; let stateService: StateService; beforeEach(() => { imageHelper = new ImageHelper(); api = new APIWrapper(new DataProvider()); graphService = new GraphService(new Graph(api)); stateService = new StateServiceMockCreator().create(); }); it("should set graph mode when passing speed threshold", () => { const playService: PlayService = new PlayService(graphService, stateService); const setGraphModeSpy: jasmine.Spy = spyOn(graphService, "setGraphMode").and.stub(); playService.setSpeed(0); playService.play(); playService.setSpeed(1); playService.setSpeed(0); expect(setGraphModeSpy.calls.count()).toBe(3); expect(setGraphModeSpy.calls.argsFor(0)[0]).toBe(GraphMode.Spatial); expect(setGraphModeSpy.calls.argsFor(1)[0]).toBe(GraphMode.Sequence); expect(setGraphModeSpy.calls.argsFor(2)[0]).toBe(GraphMode.Spatial); }); it("should stop immediately if image does not have an edge in current direction and no bridge", () => { const playService: PlayService = new PlayService(graphService, stateService); const stopSpy: jasmine.Spy = spyOn(playService, "stop").and.callThrough(); spyOn(graphService, "cacheSequence$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheSequenceImages$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheBoundingBox$").and.returnValue(observableOf([])); playService.setDirection(NavigationDirection.Next); playService.play(); const frame: AnimationFrame = new FrameHelper().createFrame(); frame.state.currentImage.initializeCache(new ImageCache(undefined)); (<Subject<AnimationFrame>>stateService.currentState$).next(frame); frame.state.currentImage.cacheSequenceEdges([]); expect(stopSpy.calls.count()).toBe(1); }); it("should stop if earth mode is emitted", () => { const playService: PlayService = new PlayService(graphService, stateService); const stopSpy: jasmine.Spy = spyOn(playService, "stop").and.callThrough(); spyOn(graphService, "cacheSequence$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheSequenceImages$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheBoundingBox$").and.returnValue(observableOf([])); playService.setDirection(NavigationDirection.Next); playService.play(); (<Subject<State>>stateService.state$).next(State.Earth); expect(stopSpy.calls.count()).toBe(1); }); it("should stop if error occurs", () => { spyOn(console, "error").and.stub(); const playService: PlayService = new PlayService(graphService, stateService); const stopSpy: jasmine.Spy = spyOn(playService, "stop").and.callThrough(); spyOn(graphService, "cacheSequence$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheSequenceImages$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheBoundingBox$").and.returnValue(new Subject<Image[]>()); playService.setDirection(NavigationDirection.Next); playService.play(); const frame: AnimationFrame = new FrameHelper().createFrame(); const image: Image = frame.state.currentImage; const sequenceEdgesSubject: Subject<NavigationEdgeStatus> = new Subject<NavigationEdgeStatus>(); new MockCreator().mockProperty(image, "sequenceEdges$", sequenceEdgesSubject); (<Subject<AnimationFrame>>stateService.currentState$).next(frame); sequenceEdgesSubject.error(new Error()); expect(stopSpy.calls.count()).toBe(1); }); it("should emit in correct order if stopping immediately", (done: () => void) => { const playService: PlayService = new PlayService(graphService, stateService); spyOn(graphService, "cacheSequence$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheSequenceImages$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheBoundingBox$").and.returnValue(observableOf([])); playService.setDirection(NavigationDirection.Next); let firstEmit: boolean = true; playService.playing$.pipe( skip(1), take(2)) .subscribe( (playing: boolean): void => { expect(playing).toBe(playService.playing); if (firstEmit) { expect(playing).toBe(true); firstEmit = false; } else { expect(playing).toBe(false); done(); } }); playService.play(); const frame: AnimationFrame = new FrameHelper().createFrame(); frame.state.currentImage.initializeCache(new ImageCache(undefined)); (<Subject<AnimationFrame>>stateService.currentState$).next(frame); frame.state.currentImage.cacheSequenceEdges([]); }); it("should not stop if images are not cached", () => { const playService: PlayService = new PlayService(graphService, stateService); const stopSpy: jasmine.Spy = spyOn(playService, "stop").and.callThrough(); spyOn(graphService, "cacheSequence$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheSequenceImages$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheBoundingBox$").and.returnValue(observableOf([])); playService.setDirection(NavigationDirection.Next); playService.play(); const frame: AnimationFrame = new FrameHelper().createFrame(); const image: Image = frame.state.currentImage; image.initializeCache(new ImageCache(undefined)); const sequenceEdgesSubject: Subject<NavigationEdgeStatus> = new Subject<NavigationEdgeStatus>(); new MockCreator().mockProperty(image, "sequenceEdges$", sequenceEdgesSubject); (<Subject<AnimationFrame>>stateService.currentState$).next(frame); sequenceEdgesSubject.next({ cached: false, edges: [] }); expect(stopSpy.calls.count()).toBe(0); sequenceEdgesSubject.next({ cached: true, edges: [] }); expect(stopSpy.calls.count()).toBe(1); }); it("should stop if no more images", () => { const playService: PlayService = new PlayService(graphService, stateService); const stopSpy: jasmine.Spy = spyOn(playService, "stop").and.callThrough(); spyOn(graphService, "cacheSequence$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheSequenceImages$").and.returnValue(new Subject<Sequence>()); playService.setDirection(NavigationDirection.Next); playService.play(); const frame: AnimationFrame = new FrameHelper().createFrame(); const image: Image = frame.state.currentImage; image.initializeCache(new ImageCache(undefined)); const sequenceEdgesSubject: Subject<NavigationEdgeStatus> = new Subject<NavigationEdgeStatus>(); const prevFullImage: ImageEnt = new ImageHelper().createImageEnt(); prevFullImage.captured_at = -1; const prevImage: Image = new Image(prevFullImage); prevImage.makeComplete(prevFullImage); frame.state.trajectory.splice(0, 0, prevImage); frame.state.currentIndex = 1; new MockCreator().mockProperty(image, "sequenceEdges$", sequenceEdgesSubject); (<Subject<AnimationFrame>>stateService.currentState$).next(frame); sequenceEdgesSubject.next({ cached: false, edges: [] }); expect(stopSpy.calls.count()).toBe(0); sequenceEdgesSubject.next({ cached: true, edges: [] }); expect(stopSpy.calls.count()).toBe(1); }); it("should append image when cached", () => { const playService: PlayService = new PlayService(graphService, stateService); const appendImagesSpy: jasmine.Spy = <jasmine.Spy>stateService.appendImagess; appendImagesSpy.and.callThrough(); const cacheImageSpy: jasmine.Spy = spyOn(graphService, "cacheImage$"); const cacheImageSubject: Subject<Image> = new Subject<Image>(); cacheImageSpy.and.returnValue(cacheImageSubject); spyOn(graphService, "cacheSequence$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheSequenceImages$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheBoundingBox$").and.returnValue(new Subject<Image[]>()); playService.setDirection(NavigationDirection.Next); playService.play(); const frame: AnimationFrame = new FrameHelper().createFrame(); const image: Image = frame.state.currentImage; image.initializeCache(new ImageCache(undefined)); const sequenceEdgesSubject: Subject<NavigationEdgeStatus> = new Subject<NavigationEdgeStatus>(); new MockCreator().mockProperty(image, "sequenceEdges$", sequenceEdgesSubject); (<Subject<AnimationFrame>>stateService.currentState$).next(frame); const fullToImage: ImageEnt = imageHelper.createImageEnt(); fullToImage.id = "toKey"; const toImage: Image = new Image(fullToImage); sequenceEdgesSubject.next({ cached: true, edges: [{ data: { direction: NavigationDirection.Next, worldMotionAzimuth: 0 }, source: image.id, target: toImage.id, }], }); cacheImageSubject.next(toImage); expect(cacheImageSpy.calls.count()).toBe(1); expect(cacheImageSpy.calls.argsFor(0)[0]).toBe(toImage.id); expect(appendImagesSpy.calls.count()).toBe(1); expect(appendImagesSpy.calls.argsFor(0)[0].length).toBe(1); expect(appendImagesSpy.calls.argsFor(0)[0][0].id).toBe(toImage.id); }); it("should stop on image caching error", () => { spyOn(console, "error").and.stub(); const playService: PlayService = new PlayService(graphService, stateService); const appendImagesSpy: jasmine.Spy = <jasmine.Spy>stateService.appendImagess; appendImagesSpy.and.callThrough(); const cacheImageSpy: jasmine.Spy = spyOn(graphService, "cacheImage$"); const cacheImageSubject: Subject<Image> = new Subject<Image>(); cacheImageSpy.and.returnValue(cacheImageSubject); const stopSpy: jasmine.Spy = spyOn(playService, "stop").and.callThrough(); spyOn(graphService, "cacheSequence$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheSequenceImages$").and.returnValue(new Subject<Sequence>()); spyOn(graphService, "cacheBoundingBox$").and.returnValue(new Subject<Image[]>()); playService.setDirection(NavigationDirection.Next); playService.play(); const frame: AnimationFrame = new FrameHelper().createFrame(); const image: Image = frame.state.currentImage; image.initializeCache(new ImageCache(undefined)); const sequenceEdgesSubject: Subject<NavigationEdgeStatus> = new Subject<NavigationEdgeStatus>(); new MockCreator().mockProperty(image, "sequenceEdges$", sequenceEdgesSubject); (<Subject<AnimationFrame>>stateService.currentState$).next(frame); const fullToImage: ImageEnt = imageHelper.createImageEnt(); fullToImage.id = "toKey"; const toImage: Image = new Image(fullToImage); sequenceEdgesSubject.next({ cached: true, edges: [{ data: { direction: NavigationDirection.Next, worldMotionAzimuth: 0 }, source: image.id, target: toImage.id, }], }); cacheImageSubject.error(new Error()); expect(cacheImageSpy.calls.count()).toBe(1); expect(cacheImageSpy.calls.argsFor(0)[0]).toBe(toImage.id); expect(appendImagesSpy.calls.count()).toBe(0); expect(stopSpy.calls.count()).toBe(1); }); it("should cache sequence when in spatial graph mode", () => { const playService: PlayService = new PlayService(graphService, stateService); playService.setDirection(NavigationDirection.Next); // Set speed to zero so that graph mode is set to spatial when calling play playService.setSpeed(0); const cacheSequenceSpy: jasmine.Spy = spyOn(graphService, "cacheSequence$"); cacheSequenceSpy.and.returnValue(new Subject<Sequence>()); const cacheSequenceImagesSpy: jasmine.Spy = spyOn(graphService, "cacheSequenceImages$"); cacheSequenceImagesSpy.and.returnValue(new Subject<Sequence>()); playService.play(); const currentImage: Image = imageHelper.createImage(); new MockCreator().mockProperty(currentImage, "sequenceEdges$", new Subject<NavigationEdgeStatus>()); const currentImageSubject: Subject<Image> = <Subject<Image>>stateService.currentImage$; currentImageSubject.next(currentImage); expect(cacheSequenceSpy.calls.count()).toBe(1); expect(cacheSequenceSpy.calls.argsFor(0)[0]).toBe(currentImage.sequenceId); expect(cacheSequenceImagesSpy.calls.count()).toBe(0); playService.stop(); }); it("should cache sequence images when in sequence graph mode", () => { const playService: PlayService = new PlayService(graphService, stateService); playService.setDirection(NavigationDirection.Next); // Set speed to one so that graph mode is set to sequence when calling play playService.setSpeed(1); const cacheSequenceSpy: jasmine.Spy = spyOn(graphService, "cacheSequence$"); cacheSequenceSpy.and.returnValue(new Subject<Sequence>()); const cacheSequenceImagesSpy: jasmine.Spy = spyOn(graphService, "cacheSequenceImages$"); cacheSequenceImagesSpy.and.returnValue(new Subject<Sequence>()); playService.play(); const currentImage: Image = imageHelper.createImage(); new MockCreator().mockProperty(currentImage, "sequenceEdges$", new Subject<NavigationEdgeStatus>()); const currentImageSubject: Subject<Image> = <Subject<Image>>stateService.currentImage$; currentImageSubject.next(currentImage); expect(cacheSequenceSpy.calls.count()).toBe(0); expect(cacheSequenceImagesSpy.calls.count()).toBe(1); expect(cacheSequenceImagesSpy.calls.argsFor(0)[0]).toBe(currentImage.sequenceId); playService.stop(); }); it("should not pre-cache if current image is last sequence image", () => { graphService.setGraphMode(GraphMode.Spatial); const playService: PlayService = new PlayService(graphService, stateService); playService.setDirection(NavigationDirection.Next); const cacheSequenceSubject: Subject<Sequence> = new Subject<Sequence>(); spyOn(graphService, "cacheSequence$").and.returnValue(cacheSequenceSubject); playService.play(); const sequenceKey: string = "sequenceId"; const currentFullImage: ImageEnt = new ImageHelper().createImageEnt(); currentFullImage.sequence.id = sequenceKey; currentFullImage.id = "image0"; const currentImage: Image = new Image(currentFullImage); new MockCreator().mockProperty(currentImage, "sequenceEdges$", new Subject<NavigationEdgeStatus>()); const prevImageKey: string = "image1"; const currentImageSubject: Subject<Image> = <Subject<Image>>stateService.currentImage$; currentImageSubject.next(currentImage); const sequence: Sequence = new Sequence({ id: sequenceKey, image_ids: [prevImageKey, currentImage.id] }); cacheSequenceSubject.next(sequence); const cacheImageSpy: jasmine.Spy = spyOn(graphService, "cacheImage$"); const cacheImageSubject: Subject<Image> = new Subject<Image>(); cacheImageSpy.and.returnValue(cacheImageSubject); const state: IAnimationState = createState(); state.trajectory = [currentImage]; state.lastImage = currentImage; state.currentImage = currentImage; state.imagesAhead = 0; (<Subject<AnimationFrame>>stateService.currentState$).next({ fps: 60, id: 0, state: state }); expect(cacheImageSpy.calls.count()).toBe(0); playService.stop(); }); it("should pre-cache one trajectory image", () => { graphService.setGraphMode(GraphMode.Spatial); const playService: PlayService = new PlayService(graphService, stateService); playService.setDirection(NavigationDirection.Next); const cacheSequenceSubject: Subject<Sequence> = new Subject<Sequence>(); spyOn(graphService, "cacheSequence$").and.returnValue(cacheSequenceSubject); playService.play(); const sequenceKey: string = "sequenceId"; const currentFullImage: ImageEnt = new ImageHelper().createImageEnt(); currentFullImage.sequence.id = sequenceKey; currentFullImage.id = "image0"; const currentImage: Image = new Image(currentFullImage); new MockCreator().mockProperty(currentImage, "sequenceEdges$", new Subject<NavigationEdgeStatus>()); const nextImageKey: string = "image1"; const currentImageSubject: Subject<Image> = <Subject<Image>>stateService.currentImage$; currentImageSubject.next(currentImage); const sequence: Sequence = new Sequence({ id: sequenceKey, image_ids: [currentImage.id, nextImageKey] }); cacheSequenceSubject.next(sequence); const cacheImageSpy: jasmine.Spy = spyOn(graphService, "cacheImage$"); const cacheImageSubject: Subject<Image> = new Subject<Image>(); cacheImageSpy.and.returnValue(cacheImageSubject); const state: IAnimationState = createState(); state.trajectory = [currentImage]; state.lastImage = currentImage; state.currentImage = currentImage; state.imagesAhead = 0; const currentStateSubject$: Subject<AnimationFrame> = <Subject<AnimationFrame>>stateService.currentState$; currentStateSubject$.next({ fps: 60, id: 0, state: state }); cacheImageSubject.next(new ImageHelper().createImage()); expect(cacheImageSpy.calls.count()).toBe(1); expect(cacheImageSpy.calls.argsFor(0)[0]).toBe(nextImageKey); playService.stop(); }); it("should pre-cache one trajectory image in prev direction", () => { graphService.setGraphMode(GraphMode.Spatial); const playService: PlayService = new PlayService(graphService, stateService); playService.setDirection(NavigationDirection.Prev); const cacheSequenceSubject: Subject<Sequence> = new Subject<Sequence>(); spyOn(graphService, "cacheSequence$").and.returnValue(cacheSequenceSubject); playService.play(); const sequenceKey: string = "sequenceId"; const currentFullImage: ImageEnt = new ImageHelper().createImageEnt(); currentFullImage.sequence.id = sequenceKey; currentFullImage.id = "image0"; const currentImage: Image = new Image(currentFullImage); new MockCreator().mockProperty(currentImage, "sequenceEdges$", new Subject<NavigationEdgeStatus>()); const prevImageKey: string = "image1"; const currentImageSubject: Subject<Image> = <Subject<Image>>stateService.currentImage$; currentImageSubject.next(currentImage); const sequence: Sequence = new Sequence({ id: sequenceKey, image_ids: [prevImageKey, currentImage.id] }); cacheSequenceSubject.next(sequence); const cacheImageSpy: jasmine.Spy = spyOn(graphService, "cacheImage$"); const cacheImageSubject: Subject<Image> = new Subject<Image>(); cacheImageSpy.and.returnValue(cacheImageSubject); const state: IAnimationState = createState(); state.trajectory = [currentImage]; state.lastImage = currentImage; state.currentImage = currentImage; state.imagesAhead = 0; const currentStateSubject$: Subject<AnimationFrame> = <Subject<AnimationFrame>>stateService.currentState$; currentStateSubject$.next({ fps: 60, id: 0, state: state }); cacheImageSubject.next(new ImageHelper().createImage()); expect(cacheImageSpy.calls.count()).toBe(1); expect(cacheImageSpy.calls.argsFor(0)[0]).toBe(prevImageKey); // Sequence should not have changed because of internal reversing expect(sequence.imageIds[0]).toBe(prevImageKey); expect(sequence.imageIds[1]).toBe(currentImage.id); playService.stop(); }); it("should not pre-cache the same image twice", () => { graphService.setGraphMode(GraphMode.Spatial); const playService: PlayService = new PlayService(graphService, stateService); playService.setDirection(NavigationDirection.Next); const cacheSequenceSubject: Subject<Sequence> = new Subject<Sequence>(); spyOn(graphService, "cacheSequence$").and.returnValue(cacheSequenceSubject); playService.play(); const sequenceKey: string = "sequenceId"; const currentFullImage: ImageEnt = new ImageHelper().createImageEnt(); currentFullImage.sequence.id = sequenceKey; currentFullImage.id = "image0"; const currentImage: Image = new Image(currentFullImage); currentImage.makeComplete(currentFullImage); new MockCreator().mockProperty(currentImage, "sequenceEdges$", new Subject<NavigationEdgeStatus>()); const nextImageKey: string = "image1"; const currentImageSubject: Subject<Image> = <Subject<Image>>stateService.currentImage$; currentImageSubject.next(currentImage); const sequence: Sequence = new Sequence({ id: sequenceKey, image_ids: [currentImage.id, nextImageKey] }); cacheSequenceSubject.next(sequence); const cacheImageSpy: jasmine.Spy = spyOn(graphService, "cacheImage$"); const cacheImageSubject: Subject<Image> = new Subject<Image>(); cacheImageSpy.and.returnValue(cacheImageSubject); const state: IAnimationState = createState(); state.trajectory = [currentImage]; state.lastImage = currentImage; state.currentImage = currentImage; state.imagesAhead = 0; const currentStateSubject$: Subject<AnimationFrame> = <Subject<AnimationFrame>>stateService.currentState$; currentStateSubject$.next({ fps: 60, id: 0, state: state }); const nextFullImage: ImageEnt = new ImageHelper().createImageEnt(); nextFullImage.sequence.id = sequenceKey; nextFullImage.id = nextImageKey; const nextImage: Image = new Image(nextFullImage); nextImage.makeComplete(nextFullImage); cacheImageSubject.next(nextImage); expect(cacheImageSpy.calls.count()).toBe(1); expect(cacheImageSpy.calls.argsFor(0)[0]).toBe(nextImageKey); currentStateSubject$.next({ fps: 60, id: 0, state: state }); expect(cacheImageSpy.calls.count()).toBe(1); playService.stop(); }); it("should not pre-cache if all sequence images in trajectory", () => { graphService.setGraphMode(GraphMode.Spatial); const playService: PlayService = new PlayService(graphService, stateService); playService.setDirection(NavigationDirection.Next); const cacheSequenceSubject: Subject<Sequence> = new Subject<Sequence>(); spyOn(graphService, "cacheSequence$").and.returnValue(cacheSequenceSubject); playService.play(); const sequenceKey: string = "sequenceId"; const currentFullImage: ImageEnt = new ImageHelper().createImageEnt(); currentFullImage.sequence.id = sequenceKey; currentFullImage.id = "image0"; const currentImage: Image = new Image(currentFullImage); currentImage.makeComplete(currentFullImage); new MockCreator().mockProperty(currentImage, "sequenceEdges$", new Subject<NavigationEdgeStatus>()); const nextImageKey: string = "image1"; const nextFullImage: ImageEnt = new ImageHelper().createImageEnt(); nextFullImage.sequence.id = sequenceKey; nextFullImage.id = nextImageKey; const nextImage: Image = new Image(nextFullImage); nextImage.makeComplete(nextFullImage); new MockCreator().mockProperty(nextImage, "sequenceEdges$", new Subject<NavigationEdgeStatus>()); const currentImageSubject: Subject<Image> = <Subject<Image>>stateService.currentImage$; currentImageSubject.next(currentImage); const sequence: Sequence = new Sequence({ id: sequenceKey, image_ids: [currentImage.id, nextImageKey] }); cacheSequenceSubject.next(sequence); const cacheImageSpy: jasmine.Spy = spyOn(graphService, "cacheImage$"); const cacheImageSubject: Subject<Image> = new Subject<Image>(); cacheImageSpy.and.returnValue(cacheImageSubject); const state: IAnimationState = createState(); state.trajectory = [currentImage, nextImage]; state.lastImage = nextImage; state.currentImage = currentImage; state.imagesAhead = 0; const currentStateSubject$: Subject<AnimationFrame> = <Subject<AnimationFrame>>stateService.currentState$; currentStateSubject$.next({ fps: 60, id: 0, state: state }); expect(cacheImageSpy.calls.count()).toBe(0); playService.stop(); }); it("should pre-cache up to specified images ahead", () => { graphService.setGraphMode(GraphMode.Spatial); const playService: PlayService = new PlayService(graphService, stateService); playService.setDirection(NavigationDirection.Next); // Zero speed means max ten images ahead playService.setSpeed(0); const cacheSequenceSubject: Subject<Sequence> = new Subject<Sequence>(); spyOn(graphService, "cacheSequence$").and.returnValue(cacheSequenceSubject); playService.play(); const sequenceKey: string = "sequenceId"; const currentFullImage: ImageEnt = new ImageHelper().createImageEnt(); currentFullImage.sequence.id = sequenceKey; currentFullImage.id = "currentImageKey"; const currentImage: Image = new Image(currentFullImage); currentImage.makeComplete(currentFullImage); new MockCreator().mockProperty(currentImage, "sequenceEdges$", new Subject<NavigationEdgeStatus>()); const sequence: Sequence = new Sequence({ id: sequenceKey, image_ids: [currentImage.id] }); const sequenceImages: Image[] = []; for (let i: number = 0; i < 20; i++) { const sequenceImageKey: string = `image${i}`; const sequenceFullImage: ImageEnt = new ImageHelper().createImageEnt(); sequenceFullImage.sequence.id = sequenceKey; sequenceFullImage.id = sequenceImageKey; const sequenceImage: Image = new Image(sequenceFullImage); sequenceImage.makeComplete(sequenceFullImage); new MockCreator().mockProperty(sequenceImage, "sequenceEdges$", new Subject<NavigationEdgeStatus>()); sequence.imageIds.push(sequenceImage.id); sequenceImages.push(sequenceImage); } const currentImageSubject: Subject<Image> = <Subject<Image>>stateService.currentImage$; currentImageSubject.next(currentImage); cacheSequenceSubject.next(sequence); const cacheImageSpy: jasmine.Spy = spyOn(graphService, "cacheImage$").and.callFake( (key: string): Observable<Image> => { const fullImage: ImageEnt = new ImageHelper().createImageEnt(); fullImage.sequence.id = sequenceKey; fullImage.id = key; const image: Image = new Image(fullImage); image.makeComplete(fullImage); return observableOf(image); }); const state: IAnimationState = createState(); state.trajectory = [currentImage]; state.lastImage = currentImage; state.currentImage = currentImage; state.currentIndex = 0; state.imagesAhead = 0; // Cache ten images immediately const currentStateSubject$: Subject<AnimationFrame> = <Subject<AnimationFrame>>stateService.currentState$; currentStateSubject$.next({ fps: 60, id: 0, state: state }); let cachedCount: number = 10; expect(cacheImageSpy.calls.count()).toBe(cachedCount); // Add one image to trajectory before current image has moved state.trajectory = state.trajectory.concat(sequenceImages.splice(0, 1)); state.lastImage = state.trajectory[state.trajectory.length - 1]; state.imagesAhead = 1; currentStateSubject$.next({ fps: 60, id: 0, state: state }); // No new images should be cached expect(cacheImageSpy.calls.count()).toBe(cachedCount); // Current image has moved one step in trajectory to the last image, images ahead // is zero and one new image should be cached state.currentIndex += 1; state.currentImage = state.trajectory[state.currentIndex]; state.imagesAhead = 0; currentStateSubject$.next({ fps: 60, id: 0, state: state }); cachedCount += 1; expect(cacheImageSpy.calls.count()).toBe(cachedCount); // Add 5 images to trajectory and move current image 3 steps state.trajectory = state.trajectory.concat(sequenceImages.splice(0, 5)); state.currentIndex += 3; state.currentImage = state.trajectory[state.currentIndex]; state.lastImage = state.trajectory[state.trajectory.length - 1]; state.imagesAhead = 2; currentStateSubject$.next({ fps: 60, id: 0, state: state }); // Three new images should be cached cachedCount += 3; expect(cacheImageSpy.calls.count()).toBe(cachedCount); // Add all 14 images cached so far to trajectory and move current image to last // trajectory image state.trajectory = state.trajectory.concat(sequenceImages.splice(0, 8)); state.currentIndex = state.trajectory.length - 1; expect(state.currentIndex).toBe(14); state.currentImage = state.trajectory[state.currentIndex]; state.lastImage = state.trajectory[state.trajectory.length - 1]; state.imagesAhead = 0; currentStateSubject$.next({ fps: 60, id: 0, state: state }); // Six last images should be cached cachedCount += 6; expect(cacheImageSpy.calls.count()).toBe(cachedCount); currentStateSubject$.next({ fps: 60, id: 0, state: state }); // No new images should be cached expect(cacheImageSpy.calls.count()).toBe(cachedCount); // Add all remaining images to trajectory and move current image one step state.trajectory = state.trajectory.concat(sequenceImages.splice(0, sequenceImages.length)); state.currentIndex += 1; state.currentImage = state.trajectory[state.currentIndex]; state.lastImage = state.trajectory[state.trajectory.length - 1]; state.imagesAhead = 5; currentStateSubject$.next({ fps: 60, id: 0, state: state }); // No new images should be cached expect(cacheImageSpy.calls.count()).toBe(cachedCount); // Move current image to last trajectory image state.trajectory = state.trajectory.concat(sequenceImages.splice(0, sequenceImages.length)); state.currentIndex = state.trajectory.length - 1; state.currentImage = state.trajectory[state.currentIndex]; state.lastImage = state.trajectory[state.trajectory.length - 1]; state.imagesAhead = 0; currentStateSubject$.next({ fps: 60, id: 0, state: state }); // No new images should be cached expect(cacheImageSpy.calls.count()).toBe(20); for (let i: number = 0; i < 20; i++) { expect(cacheImageSpy.calls.argsFor(i)[0]).toBe(sequence.imageIds[i + 1]); } playService.stop(); }); });
the_stack
import { Loki } from "../../src/loki"; import { Collection } from "../../src/collection"; import { Doc } from "../../../common/types"; describe("collection", () => { interface CL { a: number; b: number; } it("works", () => { class SubclassedCollection extends Collection { constructor(name: string, options: any = {}) { super(name, options); } extendedMethod() { return this.name.toUpperCase(); } } const coll = new SubclassedCollection("users", {}); expect(coll !== null).toBe(true); expect("users".toUpperCase()).toEqual(coll.extendedMethod()); coll.insert({ name: "joe" }); expect(coll.count()).toEqual(1); }); it("lokimap works", function () { const db = new Loki("test.db"); let coll = db.addCollection("coll"); coll.insert([{a: 3, b: 3}, {a: 6, b: 7}, {a: 1, b: 2}, {a: 7, b: 8}, {a: 6, b: 4}]); expect(Object.keys(coll._lokimap).length).toEqual(5); let result = coll.find(); for (let doc of result) { let lmdoc = coll._lokimap[doc.$loki]; expect(lmdoc["a"]).toEqual(doc["a"]); expect(lmdoc["b"]).toEqual(doc["b"]); } }); it("collection rename works", function () { const db = new Loki("test.db"); db.addCollection("coll1"); let result = db.getCollection("coll1"); expect(result.name).toEqual("coll1"); db.renameCollection("coll1", "coll2"); result = db.getCollection("coll1"); expect(result).toBeNull(); result = db.getCollection("coll2"); expect(result.name).toEqual("coll2"); }); it("add existing collection name works", function () { const db = new Loki("test.db"); const coll1 = db.addCollection("coll1"); const coll2 = db.addCollection("coll1"); expect(coll1).toEqual(coll2); }); it("findAndUpdate works", () => { const db = new Loki("test.db"); const coll = db.addCollection<CL>("testcoll"); coll.insert([{a: 3, b: 3}, {a: 6, b: 7}, {a: 1, b: 2}, {a: 7, b: 8}, {a: 6, b: 4}]); coll.findAndUpdate({a: 6}, (obj: CL) => { obj.b += 1; return obj; }); const result = coll.chain().find({a: 6}).simplesort("b").data(); expect(result.length).toEqual(2); expect(result[0].b).toEqual(5); expect(result[1].b).toEqual(8); }); it("findAndRemove works", () => { const db = new Loki("test.db"); const coll = db.addCollection<CL>("testcoll"); coll.insert([{a: 3, b: 3}, {a: 6, b: 7}, {a: 1, b: 2}, {a: 7, b: 8}, {a: 6, b: 4}]); coll.findAndRemove({a: 6}); expect(coll.count()).toEqual(3); const result = coll.chain().find().simplesort("b").data(); expect(result.length).toEqual(3); expect(result[0].b).toEqual(2); expect(result[1].b).toEqual(3); expect(result[2].b).toEqual(8); }); it("removeWhere works", () => { const db = new Loki("test.db"); const coll = db.addCollection<CL>("testcoll"); coll.insert([{a: 3, b: 3}, {a: 6, b: 7}, {a: 1, b: 2}, {a: 7, b: 8}, {a: 6, b: 4}]); coll.removeWhere((obj: CL) => obj.a === 6); expect(coll.count()).toEqual(3); const result = coll.chain().find().simplesort("b").data(); expect(result.length).toEqual(3); expect(result[0].b).toEqual(2); expect(result[1].b).toEqual(3); expect(result[2].b).toEqual(8); }); it("updateWhere works", () => { const db = new Loki("test.db"); const coll = db.addCollection<CL>("testcoll"); coll.insert([{a: 3, b: 3}, {a: 6, b: 7}, {a: 1, b: 2}, {a: 7, b: 8}, {a: 6, b: 4}]); // guess we need to return object for this to work coll.updateWhere((fobj: CL) => fobj.a === 6, (obj: Doc<CL>) => { obj.b += 1; return obj; }); const result = coll.chain().find({a: 6}).simplesort("b").data(); expect(result.length).toEqual(2); expect(result[0].b).toEqual(5); expect(result[1].b).toEqual(8); }); // coll.mode(property) should return single value of property which occurs most in collection // if more than one value 'ties' it will just pick one it("mode works", () => { const db = new Loki("test.db"); const coll = db.addCollection<CL>("testcoll"); coll.insert([{a: 3, b: 3}, {a: 6, b: 7}, {a: 1, b: 2}, {a: 7, b: 8}, {a: 6, b: 4}]); expect(coll.mode("a")).toEqual(6); }); it("single inserts emit with meta when async listeners false", () => { const db = new Loki("test.db"); const coll = db.addCollection<CL>("testcoll"); // listen for insert events to validate objects coll.on("insert", (obj: Doc<CL>) => { expect(obj.hasOwnProperty("a")).toEqual(true); expect([3, 6, 1, 7, 5].indexOf(obj.a)).toBeGreaterThan(-1); switch (obj.a) { case 3: expect(obj.b).toEqual(3); break; case 6: expect(obj.b).toEqual(7); break; case 1: expect(obj.b).toEqual(2); break; case 7: expect(obj.b).toEqual(8); break; case 5: expect(obj.b).toEqual(4); break; } expect(obj.hasOwnProperty("$loki")).toEqual(true); expect(obj.hasOwnProperty("meta")).toEqual(true); expect(obj.meta.hasOwnProperty("revision")).toEqual(true); expect(obj.meta.hasOwnProperty("created")).toEqual(true); expect(obj.meta.hasOwnProperty("version")).toEqual(true); expect(obj.meta.revision).toEqual(0); expect(obj.meta.version).toEqual(0); expect(obj.meta.created).toBeGreaterThan(0); }); coll.insert({a: 3, b: 3}); coll.insert({a: 6, b: 7}); coll.insert({a: 1, b: 2}); coll.insert({a: 7, b: 8}); coll.insert({a: 5, b: 4}); }); it("single inserts (with clone) emit meta and return instances correctly", () => { const db = new Loki("test.db"); const coll = db.addCollection<CL>("testcoll", {clone: true}); // listen for insert events to validate objects coll.on("insert", (obj: Doc<CL>) => { expect(obj.hasOwnProperty("a")).toEqual(true); expect([3, 6, 1, 7, 5].indexOf(obj.a)).toBeGreaterThan(-1); switch (obj.a) { case 3: expect(obj.b).toEqual(3); break; case 6: expect(obj.b).toEqual(7); break; case 1: expect(obj.b).toEqual(2); break; case 7: expect(obj.b).toEqual(8); break; case 5: expect(obj.b).toEqual(4); break; } expect(obj.hasOwnProperty("$loki")).toEqual(true); expect(obj.hasOwnProperty("meta")).toEqual(true); expect(obj.meta.hasOwnProperty("revision")).toEqual(true); expect(obj.meta.hasOwnProperty("created")).toEqual(true); expect(obj.meta.hasOwnProperty("version")).toEqual(true); expect(obj.meta.revision).toEqual(0); expect(obj.meta.version).toEqual(0); expect(obj.meta.created).toBeGreaterThan(0); }); const i1 = coll.insert({a: 3, b: 3}); coll.insert({a: 6, b: 7}); coll.insert({a: 1, b: 2}); coll.insert({a: 7, b: 8}); coll.insert({a: 5, b: 4}); // verify that the objects returned from an insert are clones by tampering with values i1.b = 9; const result = coll.findOne({a: 3}); expect(result.b).toEqual(3); }); it("batch inserts emit with meta", () => { const db = new Loki("test.db"); const coll = db.addCollection<CL>("testcoll"); // listen for insert events to validate objects coll.on("insert", (objs: Doc<CL>[]) => { expect(Array.isArray(objs)).toEqual(true); expect(objs.length).toEqual(5); expect(objs[0].b).toEqual(3); expect(objs[1].b).toEqual(7); expect(objs[2].b).toEqual(2); expect(objs[3].b).toEqual(8); expect(objs[4].b).toEqual(4); expect(objs[0].hasOwnProperty("$loki")).toEqual(true); expect(objs[1].hasOwnProperty("$loki")).toEqual(true); expect(objs[2].hasOwnProperty("$loki")).toEqual(true); expect(objs[3].hasOwnProperty("$loki")).toEqual(true); expect(objs[4].hasOwnProperty("$loki")).toEqual(true); expect(objs[0].hasOwnProperty("meta")).toEqual(true); expect(objs[1].hasOwnProperty("meta")).toEqual(true); expect(objs[2].hasOwnProperty("meta")).toEqual(true); expect(objs[3].hasOwnProperty("meta")).toEqual(true); expect(objs[4].hasOwnProperty("meta")).toEqual(true); expect(objs[0].meta.hasOwnProperty("revision")).toEqual(true); expect(objs[0].meta.hasOwnProperty("created")).toEqual(true); expect(objs[0].meta.hasOwnProperty("version")).toEqual(true); expect(objs[0].meta.revision).toEqual(0); expect(objs[0].meta.version).toEqual(0); expect(objs[0].meta.created).toBeGreaterThan(0); }); coll.insert([{a: 3, b: 3}, {a: 6, b: 7}, {a: 1, b: 2}, {a: 7, b: 8}, {a: 5, b: 4}]); }); it("batch inserts emit with meta and return clones", () => { const db = new Loki("test.db"); const coll = db.addCollection<CL>("testcoll", {clone: true}); // listen for insert events to validate objects coll.on("insert", (objs: Doc<CL>[]) => { expect(Array.isArray(objs)).toEqual(true); expect(objs.length).toEqual(5); expect(objs[0].b).toEqual(3); expect(objs[1].b).toEqual(7); expect(objs[2].b).toEqual(2); expect(objs[3].b).toEqual(8); expect(objs[4].b).toEqual(4); expect(objs[0].hasOwnProperty("$loki")).toEqual(true); expect(objs[1].hasOwnProperty("$loki")).toEqual(true); expect(objs[2].hasOwnProperty("$loki")).toEqual(true); expect(objs[3].hasOwnProperty("$loki")).toEqual(true); expect(objs[4].hasOwnProperty("$loki")).toEqual(true); expect(objs[0].hasOwnProperty("meta")).toEqual(true); expect(objs[1].hasOwnProperty("meta")).toEqual(true); expect(objs[2].hasOwnProperty("meta")).toEqual(true); expect(objs[3].hasOwnProperty("meta")).toEqual(true); expect(objs[4].hasOwnProperty("meta")).toEqual(true); expect(objs[0].meta.hasOwnProperty("revision")).toEqual(true); expect(objs[0].meta.hasOwnProperty("created")).toEqual(true); expect(objs[0].meta.hasOwnProperty("version")).toEqual(true); expect(objs[0].meta.revision).toEqual(0); expect(objs[0].meta.version).toEqual(0); expect(objs[0].meta.created).toBeGreaterThan(0); }); const obj1 = {a: 3, b: 3}; const result = coll.insert([obj1, {a: 6, b: 7}, {a: 1, b: 2}, {a: 7, b: 8}, {a: 5, b: 4}]); expect(Array.isArray(result)).toEqual(true); // tamper original (after insert) obj1.b = 99; // returned values should have been clones of original expect(result[0].b).toEqual(3); // internal data references should have benn clones of original const obj = coll.findOne({a: 3}); expect(obj.b).toEqual(3); }); });
the_stack
import {Area, OutputArea, LabContainer} from './areas'; import {Editor, EditorTheme} from './editor'; import {fetchBlob, DownloadRequest, DownloadResponse} from './comms'; import {getElemsByClass, getElemById, getElemsByTag} from './dom-utils'; import {Resource, ResourceList} from './resource'; import {ServerWorker} from './server'; import {RunProgram, CheckOutput} from './server-types'; import * as Strings from './strings'; interface EditorView { readonly header: HTMLButtonElement; readonly editor: Editor; } type EditorMap = Map<string, EditorView>; /** * Defines the widget behavior * * @export * @class Widget */ class Widget { // model object private readonly name: string; private readonly main: string; private readonly server: string; private readonly id: string; private readonly shadowFiles: ResourceList = []; // view objects protected readonly container: HTMLDivElement; protected readonly outputArea: OutputArea; public readonly viewMap: EditorMap = new Map(); // other object private readonly editor: Editor; /** * Creates an instance of Widget and attaches logic to DOM * * @param {HTMLDivElement} elem - the container for the widget * @param {(EditorMap | undefined)} dep - The view of widgets with the same * name on the current page */ constructor(elem: HTMLDivElement, dep: EditorMap | undefined) { this.server = elem.dataset.url as string; this.container = elem; // Read attributes from container object to initialize members this.id = this.container.id; this.name = elem.dataset.name as string; this.main = elem.dataset.main as string; // add widget dependencies from up page to the EditorView if (dep) { // Shallow copy the dep map into our map for (const [k, v] of dep.entries()) { this.viewMap.set(k, v); } } // Initialize editor const edDiv = this.getElem('editor') as HTMLDivElement; this.editor = new Editor(edDiv); // Parse files const files = getElemsByClass(this.container, 'file'); // Check to make sure we have files in the widget if (files.length == 0) { throw Error('Malformed widget: No files present.'); } for (const file of files) { const basename = file.dataset.basename as string; const content = file.textContent ? file.textContent : ''; this.editor.addSession(basename, content); } // Parse shadow files const shadowFiles = getElemsByClass(this.container, 'shadow-file'); for (const file of shadowFiles) { const a: Resource = { basename: file.dataset.basename as string, contents: file.textContent ? file.textContent : '', }; this.shadowFiles.push(a); } // Setup editor tabs const tab = this.getElem('tab'); const headers = getElemsByTag(tab, 'button'); for (const h of headers) { const basename = h.textContent ? h.textContent : ''; const newView: EditorView = { header: this.getElem('tab', basename) as HTMLButtonElement, editor: this.editor, }; h.addEventListener('click', () => { for (const i of headers) { i.classList.remove('active'); } h.classList.add('active'); this.editor.setSession(basename); }); this.viewMap.set(basename, newView); } // simulate click on the first tab to show it headers[0].click(); // attach button logic const buttonGroup = this.getElem('button-group'); const buttons = getElemsByTag(buttonGroup, 'button'); for (const btn of buttons) { const mode = btn.dataset.mode as string; btn.addEventListener('click', async () => { await this.buttonCB(mode); }); } // attach handlers to the settings bar items const tabSetting = this.getElem('settings-bar', 'tab-setting') as HTMLInputElement; tabSetting.checked = true; tabSetting.addEventListener('change', () => { // TODO: figure out how to do this // if (tabSetting.checked) { // for (const t of this.viewMap.values()) { // t.header.style.display = 'block'; // if (t.content.classList.contains('active')) { // t.content.style.display = 'block'; // } else { // t.content.style.display = 'none'; // } // } // } else { // for (const t of this.viewMap.values()) { // t.header.style.display = 'none'; // t.content.style.display = 'block'; // } // } }); const themeSetting = this.getElem('settings-bar', 'theme-setting') as HTMLInputElement; themeSetting.addEventListener('change', () => { let theme = EditorTheme.Light; if (themeSetting.checked) { theme = EditorTheme.Dark; } for (const t of this.viewMap.values()) { t.editor.setTheme(theme); } }); const resetButton = this.getElem('settings-bar', 'reset-btn') as HTMLButtonElement; resetButton.addEventListener('click', () => { if (window.confirm(Strings.RESET_CONFIRM_MSG)) { this.resetEditors(); } }); const dlButton = this.getElem('settings-bar', 'download-btn'); dlButton.addEventListener('click', async () => { try { const blob = await this.downloadExample(); const objURL: string = URL.createObjectURL(blob.blob); const a = document.createElement('a'); a.setAttribute('href', objURL); a.setAttribute('download', blob.filename); document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(objURL); } catch (error) { this.outputArea.reset(); this.outputArea.addError(Strings.MACHINE_BUSY_LABEL); console.error('Error:', error); } }); // grab reference to output area in the HTML and construct area const outputArea = this.getElem('output-area') as HTMLDivElement; this.outputArea = new OutputArea(outputArea); } /** * Collect resources from the current view * * @return {ResourceList} return the widget resources */ protected collectResources(): ResourceList { const ret: ResourceList = []; // get files from view for (const [basename, view] of this.viewMap) { const r: Resource = { basename: basename, contents: view.editor.getSessionContent(basename), }; ret.push(r); } // add shadow files for (const sf of this.shadowFiles) { ret.push(sf); } // TODO: add cli contents to files return ret; } /** * Construct the server address string * * @param {string} url - the url suffix * @return {string} - the full constructed url */ private serverAddress(url: string): string { return this.server + '/' + url + '/'; } /** * Gets an element by its id inside the current widget layout * * The ids inside the widget are in the form: * <widget number>.<item>.<sub item> * * This function will prepend the widget number to the args passed in. * An example would be: * * this.getElem('foo', 'bar) would return an element with the ID * <widget number>.foo.bar * * @protected * @param {...Array<string>} args - The list of args to append * @return {HTMLElement} - The element with the ID */ protected getElem(...args: Array<string>): HTMLElement { const fullId = [this.id].concat(args).join('.'); return getElemById(fullId); } /** * The main callback for the widget buttons * * @param {string} mode - the mode of the button that triggered the event * @param {boolean} lab - specifies if this is a lab widget */ protected async buttonCB(mode: string, lab = false): Promise<void> { this.outputArea.reset(); // Clear any annotations added from previous button click for (const t of this.viewMap.values()) { t.editor.clearGutterAnnotation(); } this.outputArea.add(['output_info', 'console_output'], Strings.CONSOLE_OUTPUT_LABEL + ':'); this.outputArea.showSpinner(true); const files = this.collectResources(); const serverData: RunProgram.TS = { files: files, main: this.main, mode: mode, switches: JSON.parse(this.container.dataset.switches as string), name: this.name, lab: lab, }; const worker = new ServerWorker(this.server, (data: CheckOutput.FS): number => { return this.processCheckOutput(data); }); try { await worker.request(serverData, 'run_program'); } catch (error) { this.outputArea.addError(Strings.MACHINE_BUSY_LABEL); console.error('Error:', error); } finally { this.outputArea.showSpinner(false); } } /** * The download example callback * * @private * @return {Promise<DownloadResponse>} - A promise of the dl response */ private async downloadExample(): Promise<DownloadResponse> { const files = this.collectResources(); const serverData: DownloadRequest = { files: files, switches: JSON.parse(this.container.dataset.switches as string), name: this.name, }; return fetchBlob(serverData, this.serverAddress('download')); } /** * Returns the correct Area to place data in * * @param {number} ref - should be null for Widget * @return {Area} the area to place returned data */ protected getHomeArea(ref: number): Area { if (ref != null) { throw new Error('Malformed data packet has ref in non-lab.'); } return this.outputArea; } /** * Handle the msg data coming back from server * * @param {CheckOutput.RunMsg} msg - the returned msg * @param {Area} homeArea - the area to place the rendered msg */ protected handleMsgType(msg: CheckOutput.RunMsg, homeArea: Area): void { switch (msg.type) { case 'console': { homeArea.addConsole(msg.data); break; } case 'internal_error': msg.data += ' ' + Strings.INTERNAL_ERROR_MESSAGE; // Intentional: fall through case 'stderr': case 'stdout': { // Split multiline messages into single lines for processing const outMsgList = msg.data.split(/\r?\n/); for (const outMsg of outMsgList) { const ctRegex = /^([a-zA-Z._0-9-]+):(\d+):(\d+):(.+)$/m; const rtRegex = /^raised .+ : ([a-zA-Z._0-9-]+):(\d+) (.+)$/m; const ctMatchFound = outMsg.match(ctRegex); const rtMatchFound = outMsg.match(rtRegex); // Lines that contain a sloc are clickable: const cb = (basename: string, row: number, col: number, view: EditorView): void => { if (window.getSelection()?.toString() == '') { view.header.scrollIntoView(true); view.header.click(); // Jump to corresponding line view.editor.gotoLine(basename, row, col); } }; if (ctMatchFound?.length == 5) { const basename = ctMatchFound[1]; const view = this.viewMap.get(basename); const row = parseInt(ctMatchFound[2]); const col = parseInt(ctMatchFound[3]); if (!view) { throw Error('Basename not found: ' + basename); } if (ctMatchFound[4].indexOf(' info:') === 0) { homeArea.addInfo(outMsg, () => { cb(basename, row, col, view); }); view.editor.setGutterAnnotation(basename, row, col, outMsg, 'info'); } else { if (ctMatchFound[4].indexOf(' warning:') === 0) { view.editor.setGutterAnnotation(basename, row, col, outMsg, 'warning'); } else { view.editor.setGutterAnnotation(basename, row, col, outMsg, 'error'); } homeArea.addMsg(outMsg, () => { cb(basename, row, col, view); }); } } else if (rtMatchFound?.length == 4) { const basename = rtMatchFound[1]; const view = this.viewMap.get(basename); const row = parseInt(rtMatchFound[2]); const col = 1; if (!view) { throw Error('Basename not found: ' + basename); } homeArea.addMsg(outMsg, () => { cb(basename, row, col, view); }); view.editor.setGutterAnnotation(basename, row, col, outMsg, 'error'); } else { homeArea.addLine(outMsg); } } break; } default: { homeArea.addLine(msg.data); throw new Error('Unhandled msg type.'); } } } /** * Process the output from "check_output" ajax request * @param {CheckOutput.FS} data - The data from check_output * @return {number} the number of lines read by this function */ private processCheckOutput(data: CheckOutput.FS): number { let readLines = 0; for (const ol of data.output) { const homeArea = this.getHomeArea(ol.ref); readLines++; this.handleMsgType(ol.msg, homeArea); } if (data.completed) { if (data.status != 0) { this.outputArea.addError(Strings.EXIT_STATUS_LABEL + ': ' + data.status); } } return readLines; } /** * Reset the editors, outputArea */ protected resetEditors(): void { this.outputArea.reset(); for (const t of this.viewMap.values()) { t.editor.reset(); } } } /** * The LabWidget class * @extends Widget */ export class LabWidget extends Widget { private readonly labContainer: LabContainer; /** * Creates an instance of LabWidget and attaches logic to DOM * * @param {HTMLDivElement} elem - the container for the widget * @param {(EditorMap | undefined)} dep - The view of widgets with the same * name on the current page */ constructor(elem: HTMLDivElement, dep: EditorMap | undefined) { super(elem, dep); const labArea = this.getElem('lab-area') as HTMLDivElement; this.labContainer = new LabContainer(labArea); } /** * The main callback for the widget buttons * @param {string} mode - the mode of the button that triggered the event * @param {boolean} lab - specifies that this is a lab */ protected async buttonCB(mode: string, lab = true): Promise<void> { this.labContainer.reset(); await super.buttonCB(mode, lab); this.labContainer.sort(); } /** * Returns the correct Area to place data in * @param {number} ref - if not null, the lab ref * @return {Area} the area to place returned data */ protected getHomeArea(ref: number): Area { if (ref != null) { return this.labContainer.getLabArea(ref); } return this.outputArea; } /** * Handle the msg data coming back from server * @param {CheckOutput.RunMsg} msg - the returned msg * @param {Area} homeArea - the area to place the rendered msg */ protected handleMsgType(msg: CheckOutput.RunMsg, homeArea: Area): void { switch (msg.type) { case 'lab': { const result = this.labContainer.processResults( (msg.data as unknown) as CheckOutput.LabOutput); this.outputArea.addLabStatus(result); break; } default: { super.handleMsgType(msg, homeArea); } } } /** * Reset the editors, outputArea, and labContainer */ protected resetEditors(): void { super.resetEditors(); this.labContainer.reset(); } } type WidgetMap = Map<string, EditorMap> type WidgetLike = Widget | LabWidget; /** * Entrypoint for widget creation * * @export * @param {Array<HTMLDivElement>} widgets - The collection of widgets * found on the page */ export function widgetFactory(widgets: Array<HTMLDivElement>): void { const widgetList: WidgetMap = new Map(); for (const element of widgets) { try { let widget: WidgetLike; // Get data from element const name = element.dataset.name as string; const lab = element.dataset.lab as string; const depList = widgetList.get(name); if (lab === 'True') { widget = new LabWidget(element, depList); } else { widget = new Widget(element, depList); } // reset the view for this widget with the newly computed view widgetList.set(name, widget.viewMap); } catch (error) { // an error has occured parsing the widget console.error('Error:', error); // clear the offending element to remove any processing that was done element.innerHTML = ''; // add an error message to the page in its place const errorDiv = document.createElement('div'); errorDiv.innerHTML = '<p>An error has occured processing this widget.' + Strings.INTERNAL_ERROR_MESSAGE + '</p>'; element.appendChild(errorDiv); } } }
the_stack
module android.widget { import DataSetObserver = android.database.DataSetObserver; import Rect = android.graphics.Rect; import SparseArray = android.util.SparseArray; import View = android.view.View; import ViewGroup = android.view.ViewGroup; import Integer = java.lang.Integer; import System = java.lang.System; import Adapter = android.widget.Adapter; import AdapterView = android.widget.AdapterView; import ArrayAdapter = android.widget.ArrayAdapter; import Spinner = android.widget.Spinner; import SpinnerAdapter = android.widget.SpinnerAdapter; import Context = android.content.Context; import AttrBinder = androidui.attr.AttrBinder; /** * An abstract base class for spinner widgets. SDK users will probably not * need to use this class. * * @attr ref android.R.styleable#AbsSpinner_entries */ export abstract class AbsSpinner extends AdapterView<SpinnerAdapter> { mAdapter:SpinnerAdapter; mHeightMeasureSpec:number = 0; mWidthMeasureSpec:number = 0; mSelectionLeftPadding:number = 0; mSelectionTopPadding:number = 0; mSelectionRightPadding:number = 0; mSelectionBottomPadding:number = 0; mSpinnerPadding:Rect = new Rect(); mRecycler:AbsSpinner.RecycleBin = new AbsSpinner.RecycleBin(this); private mDataSetObserver:DataSetObserver; /** Temporary frame to hold a child View's frame rectangle */ private mTouchFrame:Rect; constructor(context:Context, bindElement?:HTMLElement, defStyle?:Map<string, string>) { super(context, bindElement, defStyle); this.initAbsSpinner(); const a = context.obtainStyledAttributes(bindElement, defStyle); const entries = a.getTextArray('entries'); if (entries != null) { const adapter = new ArrayAdapter<string>(context, R.layout.simple_spinner_item, entries); adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item); this.setAdapter(adapter); } a.recycle(); } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('entries', { setter(v:AbsSpinner, value:any, attrBinder:AttrBinder) { let entries:string[] = attrBinder.parseStringArray(value); if (entries != null) { let adapter: ArrayAdapter<string> = new ArrayAdapter<string>(v.getContext(), R.layout.simple_spinner_item, entries); adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item); v.setAdapter(adapter); } } }); } /** * Common code for different constructor flavors */ private initAbsSpinner():void { this.setFocusable(true); this.setWillNotDraw(false); } /** * The Adapter is used to provide the data which backs this Spinner. * It also provides methods to transform spinner items based on their position * relative to the selected item. * @param adapter The SpinnerAdapter to use for this Spinner */ setAdapter(adapter:SpinnerAdapter):void { if (null != this.mAdapter) { this.mAdapter.unregisterDataSetObserver(this.mDataSetObserver); this.resetList(); } this.mAdapter = adapter; this.mOldSelectedPosition = AbsSpinner.INVALID_POSITION; this.mOldSelectedRowId = AbsSpinner.INVALID_ROW_ID; if (this.mAdapter != null) { this.mOldItemCount = this.mItemCount; this.mItemCount = this.mAdapter.getCount(); this.checkFocus(); this.mDataSetObserver = new AdapterView.AdapterDataSetObserver(this); this.mAdapter.registerDataSetObserver(this.mDataSetObserver); let position:number = this.mItemCount > 0 ? 0 : AbsSpinner.INVALID_POSITION; this.setSelectedPositionInt(position); this.setNextSelectedPositionInt(position); if (this.mItemCount == 0) { // Nothing selected this.checkSelectionChanged(); } } else { this.checkFocus(); this.resetList(); // Nothing selected this.checkSelectionChanged(); } this.requestLayout(); } /** * Clear out all children from the list */ resetList():void { this.mDataChanged = false; this.mNeedSync = false; this.removeAllViewsInLayout(); this.mOldSelectedPosition = AbsSpinner.INVALID_POSITION; this.mOldSelectedRowId = AbsSpinner.INVALID_ROW_ID; this.setSelectedPositionInt(AbsSpinner.INVALID_POSITION); this.setNextSelectedPositionInt(AbsSpinner.INVALID_POSITION); this.invalidate(); } /** * @see android.view.View#measure(int, int) * * Figure out the dimensions of this Spinner. The width comes from * the widthMeasureSpec as Spinnners can't have their width set to * UNSPECIFIED. The height is based on the height of the selected item * plus padding. */ protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void { let widthMode:number = View.MeasureSpec.getMode(widthMeasureSpec); let widthSize:number; let heightSize:number; this.mSpinnerPadding.left = this.mPaddingLeft > this.mSelectionLeftPadding ? this.mPaddingLeft : this.mSelectionLeftPadding; this.mSpinnerPadding.top = this.mPaddingTop > this.mSelectionTopPadding ? this.mPaddingTop : this.mSelectionTopPadding; this.mSpinnerPadding.right = this.mPaddingRight > this.mSelectionRightPadding ? this.mPaddingRight : this.mSelectionRightPadding; this.mSpinnerPadding.bottom = this.mPaddingBottom > this.mSelectionBottomPadding ? this.mPaddingBottom : this.mSelectionBottomPadding; if (this.mDataChanged) { this.handleDataChanged(); } let preferredHeight:number = 0; let preferredWidth:number = 0; let needsMeasuring:boolean = true; let selectedPosition:number = this.getSelectedItemPosition(); if (selectedPosition >= 0 && this.mAdapter != null && selectedPosition < this.mAdapter.getCount()) { // Try looking in the recycler. (Maybe we were measured once already) let view:View = this.mRecycler.get(selectedPosition); if (view == null) { // Make a new one view = this.mAdapter.getView(selectedPosition, null, this); //if (view.getImportantForAccessibility() == AbsSpinner.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { // view.setImportantForAccessibility(AbsSpinner.IMPORTANT_FOR_ACCESSIBILITY_YES); //} } if (view != null) { // Put in recycler for re-measuring and/or layout this.mRecycler.put(selectedPosition, view); if (view.getLayoutParams() == null) { this.mBlockLayoutRequests = true; view.setLayoutParams(this.generateDefaultLayoutParams()); this.mBlockLayoutRequests = false; } this.measureChild(view, widthMeasureSpec, heightMeasureSpec); preferredHeight = this.getChildHeight(view) + this.mSpinnerPadding.top + this.mSpinnerPadding.bottom; preferredWidth = this.getChildWidth(view) + this.mSpinnerPadding.left + this.mSpinnerPadding.right; needsMeasuring = false; } } if (needsMeasuring) { // No views -- just use padding preferredHeight = this.mSpinnerPadding.top + this.mSpinnerPadding.bottom; if (widthMode == View.MeasureSpec.UNSPECIFIED) { preferredWidth = this.mSpinnerPadding.left + this.mSpinnerPadding.right; } } preferredHeight = Math.max(preferredHeight, this.getSuggestedMinimumHeight()); preferredWidth = Math.max(preferredWidth, this.getSuggestedMinimumWidth()); heightSize = AbsSpinner.resolveSizeAndState(preferredHeight, heightMeasureSpec, 0); widthSize = AbsSpinner.resolveSizeAndState(preferredWidth, widthMeasureSpec, 0); this.setMeasuredDimension(widthSize, heightSize); this.mHeightMeasureSpec = heightMeasureSpec; this.mWidthMeasureSpec = widthMeasureSpec; } getChildHeight(child:View):number { return child.getMeasuredHeight(); } getChildWidth(child:View):number { return child.getMeasuredWidth(); } protected generateDefaultLayoutParams():ViewGroup.LayoutParams { return new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } recycleAllViews():void { const childCount:number = this.getChildCount(); const recycleBin:AbsSpinner.RecycleBin = this.mRecycler; const position:number = this.mFirstPosition; // All views go in recycler for (let i:number = 0; i < childCount; i++) { let v:View = this.getChildAt(i); let index:number = position + i; recycleBin.put(index, v); } } /** * Jump directly to a specific item in the adapter data. */ setSelection(position:number, animate?:boolean):void { if(arguments.length === 1){ this.setNextSelectedPositionInt(position); this.requestLayout(); this.invalidate(); }else { // Animate only if requested position is already on screen somewhere let shouldAnimate:boolean = animate && this.mFirstPosition <= position && position <= this.mFirstPosition + this.getChildCount() - 1; this.setSelectionInt(position, shouldAnimate); } } /** * Makes the item at the supplied position selected. * * @param position Position to select * @param animate Should the transition be animated * */ setSelectionInt(position:number, animate:boolean):void { if (position != this.mOldSelectedPosition) { this.mBlockLayoutRequests = true; let delta:number = position - this.mSelectedPosition; this.setNextSelectedPositionInt(position); this.layoutSpinner(delta, animate); this.mBlockLayoutRequests = false; } } abstract layoutSpinner(delta:number, animate:boolean):void; getSelectedView():View { if (this.mItemCount > 0 && this.mSelectedPosition >= 0) { return this.getChildAt(this.mSelectedPosition - this.mFirstPosition); } else { return null; } } /** * Override to prevent spamming ourselves with layout requests * as we place views * * @see android.view.View#requestLayout() */ requestLayout():void { if (!this.mBlockLayoutRequests) { super.requestLayout(); } } getAdapter():SpinnerAdapter { return this.mAdapter; } getCount():number { return this.mItemCount; } /** * Maps a point to a position in the list. * * @param x X in local coordinate * @param y Y in local coordinate * @return The position of the item which contains the specified point, or * {@link #INVALID_POSITION} if the point does not intersect an item. */ pointToPosition(x:number, y:number):number { let frame:Rect = this.mTouchFrame; if (frame == null) { this.mTouchFrame = new Rect(); frame = this.mTouchFrame; } const count:number = this.getChildCount(); for (let i:number = count - 1; i >= 0; i--) { let child:View = this.getChildAt(i); if (child.getVisibility() == View.VISIBLE) { child.getHitRect(frame); if (frame.contains(x, y)) { return this.mFirstPosition + i; } } } return AbsSpinner.INVALID_POSITION; } //onSaveInstanceState():Parcelable { // let superState:Parcelable = super.onSaveInstanceState(); // let ss:AbsSpinner.SavedState = new AbsSpinner.SavedState(superState); // ss.selectedId = this.getSelectedItemId(); // if (ss.selectedId >= 0) { // ss.position = this.getSelectedItemPosition(); // } else { // ss.position = AbsSpinner.INVALID_POSITION; // } // return ss; //} // //onRestoreInstanceState(state:Parcelable):void { // let ss:AbsSpinner.SavedState = <AbsSpinner.SavedState> state; // super.onRestoreInstanceState(ss.getSuperState()); // if (ss.selectedId >= 0) { // this.mDataChanged = true; // this.mNeedSync = true; // this.mSyncRowId = ss.selectedId; // this.mSyncPosition = ss.position; // this.mSyncMode = AbsSpinner.SYNC_SELECTED_POSITION; // this.requestLayout(); // } //} // // // //onInitializeAccessibilityEvent(event:AccessibilityEvent):void { // super.onInitializeAccessibilityEvent(event); // event.setClassName(AbsSpinner.class.getName()); //} // //onInitializeAccessibilityNodeInfo(info:AccessibilityNodeInfo):void { // super.onInitializeAccessibilityNodeInfo(info); // info.setClassName(AbsSpinner.class.getName()); //} } export module AbsSpinner{ //export class SavedState extends View.BaseSavedState { // // selectedId:number = 0; // // position:number = 0; // // /** // * Constructor called from {@link AbsSpinner#onSaveInstanceState()} // */ // constructor( superState:Parcelable) { // super(superState); // } // // /** // * Constructor called from {@link #CREATOR} // */ // constructor( _in:Parcel) { // super(_in); // this.selectedId = _in.readLong(); // this.position = _in.readInt(); // } // // writeToParcel(out:Parcel, flags:number):void { // super.writeToParcel(out, flags); // out.writeLong(this.selectedId); // out.writeInt(this.position); // } // // toString():string { // return "AbsSpinner.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " selectedId=" + this.selectedId + " position=" + this.position + "}"; // } // // static CREATOR:Parcelable.Creator<SavedState> = (()=>{ // const inner_this=this; // class _Inner extends Parcelable.Creator<SavedState> { // // createFromParcel(_in:Parcel):SavedState { // return new SavedState(_in); // } // // newArray(size:number):SavedState[] { // return new Array<SavedState>(size); // } // } // return new _Inner(); // })(); //} export class RecycleBin { _AbsSpinner_this:AbsSpinner; constructor(arg:AbsSpinner){ this._AbsSpinner_this = arg; } private mScrapHeap:SparseArray<View> = new SparseArray<View>(); put(position:number, v:View):void { this.mScrapHeap.put(position, v); } get(position:number):View { // System.out.print("Looking for " + position); let result:View = this.mScrapHeap.get(position); if (result != null) { // System.out.println(" HIT"); this.mScrapHeap.delete(position); } else { // System.out.println(" MISS"); } return result; } clear():void { const scrapHeap:SparseArray<View> = this.mScrapHeap; const count:number = scrapHeap.size(); for (let i:number = 0; i < count; i++) { const view:View = scrapHeap.valueAt(i); if (view != null) { this._AbsSpinner_this.removeDetachedView(view, true); } } scrapHeap.clear(); } } } }
the_stack
import { IterableChanges, IterableChangeRecord } from '@angular/core'; import { FastIterableDiffer, FastIterableDifferFactory } from './fast-iterable-differ'; import { stringify } from './utils'; class ItemWithId { constructor(private id: string) { } toString() { return `{id: ${this.id}}`; } } class ComplexItem { constructor(private id: string, private color: string) { } toString() { return `{id: ${this.id}, color: ${this.color}}`; } } describe('FastIterableDiffer', () => { let differ: FastIterableDiffer<any>; beforeEach(() => { differ = new FastIterableDiffer((index, item) => item); }); it('should support only array', () => { const f = new FastIterableDifferFactory(); expect(f.supports([])).toBe(true); expect(f.supports(new Set())).toBe(false); expect(f.supports(new Map())).toBe(false); expect(f.supports(null)).toBe(false); }); it('should detect additions', () => { const l: any[] = []; differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: [] })); l.push('a'); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['a[null->0]'], additions: ['a[null->0]'], })); l.push('b'); differ.check(l); expect(iterableDifferToString(differ)) .toEqual(iterableChangesAsString( { collection: ['a', 'b[null->1]'], previous: ['a'], additions: ['b[null->1]'] })); }); it('should support changing the reference', () => { let l = [0]; differ.check(l); l = [1, 0]; differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['1[null->0]', '0[0->1]'], previous: ['0[0->1]'], additions: ['1[null->0]'], moves: ['0[0->1]'], })); l = [2, 1, 0]; differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['2[null->0]', '1[0->1]', '0[1->2]'], previous: ['1[0->1]', '0[1->2]'], additions: ['2[null->0]'], moves: ['1[0->1]', '0[1->2]'], })); }); it('should handle swapping element', () => { const l = [1, 2]; differ.check(l); l.length = 0; l.push(2); l.push(1); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['2[1->0]', '1[0->1]'], previous: ['1[0->1]', '2[1->0]'], moves: ['2[1->0]', '1[0->1]'], })); }); // https://github.com/krausest/js-framework-benchmark/pull/389 it('should handle swapping internal and trailing elements', () => { const l = [1, 2, 3, 4, 5, 6]; differ.check(l); const a = l[1]; l[1] = l[5]; l[5] = a; differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['1', '6[5->1]', '3', '4', '5', '2[1->5]'], previous: ['1', '2[1->5]', '3', '4', '5', '6[5->1]'], moves: ['6[5->1]', '2[1->5]'], })); }); it('should handle incremental swapping element', () => { const l = ['a', 'b', 'c']; differ.check(l); l.splice(1, 1); l.splice(0, 0, 'b'); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['b[1->0]', 'a[0->1]', 'c'], previous: ['a[0->1]', 'b[1->0]', 'c'], moves: ['b[1->0]', 'a[0->1]'], })); l.splice(1, 1); l.push('a'); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['b', 'c[2->1]', 'a[1->2]'], previous: ['b', 'a[1->2]', 'c[2->1]'], moves: ['c[2->1]', 'a[1->2]'], })); }); it('should detect changes in list', () => { const l: any[] = []; differ.check(l); l.push('a'); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['a[null->0]'], additions: ['a[null->0]'], })); l.push('b'); differ.check(l); expect(iterableDifferToString(differ)) .toEqual(iterableChangesAsString( { collection: ['a', 'b[null->1]'], previous: ['a'], additions: ['b[null->1]'] })); l.push('c'); l.push('d'); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['a', 'b', 'c[null->2]', 'd[null->3]'], previous: ['a', 'b'], additions: ['c[null->2]', 'd[null->3]'], })); l.splice(2, 1); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['a', 'b', 'd[3->2]'], previous: ['a', 'b', 'c[2->null]', 'd[3->2]'], moves: ['d[3->2]'], removals: ['c[2->null]'], })); l.length = 0; l.push('d'); l.push('c'); l.push('b'); l.push('a'); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['d[2->0]', 'c[null->1]', 'b[1->2]', 'a[0->3]'], previous: ['a[0->3]', 'b[1->2]', 'd[2->0]'], additions: ['c[null->1]'], moves: ['d[2->0]', 'b[1->2]', 'a[0->3]'], })); }); it('should ignore [NaN] != [NaN]', () => { const l = [NaN]; differ.check(l); differ.check(l); expect(iterableDifferToString(differ)) .toEqual(iterableChangesAsString({ collection: [NaN], previous: [NaN] })); }); it('should detect [NaN] moves', () => { const l: any[] = [NaN, NaN]; differ.check(l); l.unshift('foo'); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['foo[null->0]', 'NaN[0->1]', 'NaN[1->2]'], previous: ['NaN[0->1]', 'NaN[1->2]'], additions: ['foo[null->0]'], moves: ['NaN[0->1]', 'NaN[1->2]'], })); }); it('should remove and add same item', () => { const l = ['a', 'b', 'c']; differ.check(l); l.splice(1, 1); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['a', 'c[2->1]'], previous: ['a', 'b[1->null]', 'c[2->1]'], moves: ['c[2->1]'], removals: ['b[1->null]'], })); l.splice(1, 0, 'b'); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['a', 'b[null->1]', 'c[1->2]'], previous: ['a', 'c[1->2]'], additions: ['b[null->1]'], moves: ['c[1->2]'], })); }); it('should support duplicates', () => { differ = new FastIterableDiffer(); const l = ['a', 'a', 'a', 'b', 'b']; differ.check(l); l.splice(0, 1); differ.check(l); // expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ // collection: ['a', 'a', 'b[3->2]', 'b[4->3]'], // previous: ['a', 'a', 'a[2->null]', 'b[3->2]', 'b[4->3]'], // moves: ['b[3->2]', 'b[4->3]'], // removals: ['a[2->null]'], // })); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['a', 'a', 'b', 'b'], previous: ['a', 'a', 'a', 'b', 'b[4->null]'], removals: ['b[4->null]'], identityChanges: ['b'], })); }); it('should support insertions/moves', () => { differ = new FastIterableDiffer(); const l = ['a', 'a', 'b', 'b']; differ.check(l); l.splice(0, 0, 'b'); differ.check(l); // expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ // collection: ['b[2->0]', 'a[0->1]', 'a[1->2]', 'b', 'b[null->4]'], // previous: ['a[0->1]', 'a[1->2]', 'b[2->0]', 'b'], // additions: ['b[null->4]'], // moves: ['b[2->0]', 'a[0->1]', 'a[1->2]'], // })); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['b', 'a', 'a', 'b', 'b[null->4]'], previous: ['a', 'a', 'b', 'b'], additions: ['b[null->4]'], identityChanges: ['b', 'a'], })); }); it('should not report unnecessary moves', () => { const l = ['a', 'b', 'c']; differ.check(l); l.length = 0; l.push('b'); l.push('a'); l.push('c'); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['b[1->0]', 'a[0->1]', 'c'], previous: ['a[0->1]', 'b[1->0]', 'c'], moves: ['b[1->0]', 'a[0->1]'], })); }); // https://github.com/angular/angular/issues/17852 it('support re-insertion', () => { differ = new FastIterableDiffer(); const l = ['a', '*', '*', 'd', '-', '-', '-', 'e']; differ.check(l); l[1] = 'b'; l[5] = 'c'; differ.check(l); // expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ // collection: ['a', 'b[null->1]', '*[1->2]', 'd', '-', 'c[null->5]', '-[5->6]', 'e'], // previous: ['a', '*[1->2]', '*[2->null]', 'd', '-', '-[5->6]', '-[6->null]', 'e'], // additions: ['b[null->1]', 'c[null->5]'], // moves: ['*[1->2]', '-[5->6]'], // removals: ['*[2->null]', '-[6->null]'], // })); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['a', 'b', '*', 'd', '-', 'c', '-', 'e'], previous: ['a', '*', '*', 'd', '-', '-', '-', 'e'], identityChanges: ['b', 'c'], })); }); describe('forEachOperation', () => { function stringifyItemChange(record: any, p: number | null, c: number | null, originalIndex: number) { const suffix = originalIndex == null ? '' : ' [o=' + originalIndex + ']'; const value = record.item; if (record.currentIndex == null) { return `REMOVE ${value} (${p} -> VOID)${suffix}`; } else if (record.previousIndex == null) { return `INSERT ${value} (VOID -> ${c})${suffix}`; } else { return `MOVE ${value} (${p} -> ${c})${suffix}`; } } function modifyArrayUsingOperation( arr: number[], endData: any[], prev: number | null, next: number | null, value: number) { if (prev == null) { arr.splice(next!, 0, value); } else if (next == null) { value = arr[prev]; arr.splice(prev, 1); } else { value = arr[prev]; arr.splice(prev, 1); arr.splice(next, 0, value); } return value; } it('should trigger a series of insert/move/remove changes for inputs that have been diffed', () => { const startData = [0, 1, 2, 3, 4, 5]; const endData = [6, 2, 7, 0, 4, 8]; differ = differ.diff(startData)!; differ = differ.diff(endData)!; const operations: string[] = []; differ.forEachOperation((record: any, prev: number | null, next: number | null) => { modifyArrayUsingOperation(startData, endData, prev, next, record.item); operations.push(stringifyItemChange(record, prev, next, record.previousIndex)); }); // expect(operations).toEqual([ // 'INSERT 6 (VOID -> 0)', 'MOVE 2 (3 -> 1) [o=2]', 'INSERT 7 (VOID -> 2)', // 'REMOVE 1 (4 -> VOID) [o=1]', 'REMOVE 3 (4 -> VOID) [o=3]', // 'REMOVE 5 (5 -> VOID) [o=5]', 'INSERT 8 (VOID -> 5)', // ]); expect(operations).toEqual([ 'REMOVE 1 (1 -> VOID) [o=1]', 'REMOVE 3 (2 -> VOID) [o=3]', 'REMOVE 5 (3 -> VOID) [o=5]', 'INSERT 8 (VOID -> 3)', 'INSERT 7 (VOID -> 0)', 'MOVE 2 (2 -> 0) [o=2]', 'INSERT 6 (VOID -> 0)', ]); expect(startData).toEqual(endData); }); it('should consider inserting/removing/moving items with respect to items that have not moved at all', () => { const startData = [0, 1, 2, 3]; const endData = [2, 1]; differ = differ.diff(startData)!; differ = differ.diff(endData)!; const operations: string[] = []; differ.forEachOperation((record: any, prev: number | null, next: number | null) => { modifyArrayUsingOperation(startData, endData, prev, next, record.item); operations.push(stringifyItemChange(record, prev, next, record.previousIndex)); }); // expect(operations).toEqual([ // 'REMOVE 3 (3 -> VOID) [o=3]', // 'REMOVE 0 (0 -> VOID) [o=0]', // 'MOVE 2 (1 -> 0) [o=2]', // ]); expect(operations).toEqual([ 'REMOVE 0 (0 -> VOID) [o=0]', 'REMOVE 3 (2 -> VOID) [o=3]', 'MOVE 2 (1 -> 0) [o=2]', ]); expect(startData).toEqual(endData); }); it('should be able to manage operations within a criss/cross of move operations', () => { const startData = [1, 2, 3, 4, 5, 6]; const endData = [3, 6, 4, 9, 1, 2]; differ = differ.diff(startData)!; differ = differ.diff(endData)!; const operations: string[] = []; differ.forEachOperation((record: any, prev: number | null, next: number | null) => { modifyArrayUsingOperation(startData, endData, prev, next, record.item); operations.push(stringifyItemChange(record, prev, next, record.previousIndex)); }); // expect(operations).toEqual([ // 'REMOVE 5 (4 -> VOID) [o=4]', // 'MOVE 3 (2 -> 0) [o=2]', // 'MOVE 6 (4 -> 1) [o=5]', // 'MOVE 4 (3 -> 2) [o=3]', // 'INSERT 9 (VOID -> 3)', // ]); expect(operations).toEqual([ 'REMOVE 5 (4 -> VOID) [o=4]', 'INSERT 9 (VOID -> 0)', 'MOVE 4 (4 -> 0) [o=3]', 'MOVE 6 (5 -> 0) [o=5]', 'MOVE 3 (5 -> 0) [o=2]', ]); expect(startData).toEqual(endData); }); it('should skip moves for multiple nodes that have not moved', () => { const startData = [0, 1, 2, 3, 4]; const endData = [4, 1, 2, 3, 0, 5]; differ = differ.diff(startData)!; differ = differ.diff(endData)!; const operations: string[] = []; differ.forEachOperation((record: any, prev: number | null, next: number | null) => { modifyArrayUsingOperation(startData, endData, prev, next, record.item); operations.push(stringifyItemChange(record, prev, next, record.previousIndex)); }); // expect(operations).toEqual([ // 'MOVE 4 (4 -> 0) [o=4]', // 'MOVE 1 (2 -> 1) [o=1]', // 'MOVE 2 (3 -> 2) [o=2]', // 'MOVE 3 (4 -> 3) [o=3]', // 'INSERT 5 (VOID -> 5)', // ]); expect(operations).toEqual([ 'INSERT 5 (VOID -> 5)', 'MOVE 0 (0 -> 4) [o=0]', 'MOVE 4 (3 -> 0) [o=4]', ]); expect(startData).toEqual(endData); }); it('should not fail', () => { const startData = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; const endData = [10, 11, 1, 5, 7, 8, 0, 5, 3, 6]; differ = differ.diff(startData)!; differ = differ.diff(endData)!; const operations: string[] = []; differ.forEachOperation((record: any, prev: number | null, next: number | null) => { modifyArrayUsingOperation(startData, endData, prev, next, record.item); operations.push(stringifyItemChange(record, prev, next, record.previousIndex)); }); // expect(operations).toEqual([ // 'MOVE 10 (10 -> 0) [o=10]', 'MOVE 11 (11 -> 1) [o=11]', 'MOVE 1 (3 -> 2) [o=1]', // 'MOVE 5 (7 -> 3) [o=5]', 'MOVE 7 (9 -> 4) [o=7]', 'MOVE 8 (10 -> 5) [o=8]', // 'REMOVE 2 (7 -> VOID) [o=2]', 'INSERT 5 (VOID -> 7)', 'REMOVE 4 (9 -> VOID) [o=4]', // 'REMOVE 9 (10 -> VOID) [o=9]', // ]); expect(operations).toEqual([ 'REMOVE 2 (2 -> VOID) [o=2]', 'REMOVE 4 (3 -> VOID) [o=4]', 'REMOVE 9 (7 -> VOID) [o=9]', 'MOVE 5 (3 -> 2) [o=5]', 'MOVE 8 (6 -> 0) [o=8]', 'MOVE 7 (6 -> 0) [o=7]', 'INSERT 5 (VOID -> 0)', 'MOVE 1 (4 -> 0) [o=1]', 'MOVE 11 (9 -> 0) [o=11]', 'MOVE 10 (9 -> 0) [o=10]', ]); expect(startData).toEqual(endData); }); it('should trigger nothing when the list is completely full of replaced items that are tracked by the index', () => { differ = new FastIterableDiffer((index: number) => index); const startData = [1, 2, 3, 4]; const endData = [5, 6, 7, 8]; differ.diff(startData); differ.diff(endData); const operations: string[] = []; differ.forEachOperation((record: any, prev: number | null, next: number | null) => { modifyArrayUsingOperation(startData, endData, prev, next, record.item); operations.push(stringifyItemChange(record, prev, next, record.previousIndex)); }); expect(operations).toEqual([]); }); }); describe('diff', () => { it('should return self when there is a change', () => { expect(differ.diff(['a', 'b'])).toBe(differ); }); it('should return null when there is no change', () => { differ.diff(['a', 'b']); expect(differ.diff(['a', 'b'])).toEqual(null); }); it('should treat null as an empty list', () => { differ.diff(['a', 'b']); expect(iterableDifferToString(differ.diff(null!)!)).toEqual(iterableChangesAsString({ previous: ['a[0->null]', 'b[1->null]'], removals: ['a[0->null]', 'b[1->null]'], })); }); it('should throw when given an invalid collection', () => { expect(() => differ.diff('invalid' as any)).toThrowError(/Error trying to diff 'invalid'/); }); }); }); describe('trackBy function by id', () => { let differ: any; const trackByItemId = (index: number, item: any): any => item.id; const buildItemList = (list: string[]) => list.map((val) => new ItemWithId(val)); beforeEach(() => { differ = new FastIterableDiffer(trackByItemId); }); it('should treat the collection as dirty if identity changes', () => { differ.diff(buildItemList(['a'])); expect(differ.diff(buildItemList(['a']))).toBe(differ); }); it('should treat seen records as identity changes, not additions', () => { let l = buildItemList(['a', 'b', 'c']); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`], additions: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`], })); l = buildItemList(['a', 'b', 'c']); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: [`{id: a}`, `{id: b}`, `{id: c}`], identityChanges: [`{id: a}`, `{id: b}`, `{id: c}`], previous: [`{id: a}`, `{id: b}`, `{id: c}`], })); }); it('should have updated properties in identity change collection', () => { let l = [new ComplexItem('a', 'blue'), new ComplexItem('b', 'yellow')]; differ.check(l); l = [new ComplexItem('a', 'orange'), new ComplexItem('b', 'red')]; differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: [`{id: a, color: orange}`, `{id: b, color: red}`], identityChanges: [`{id: a, color: orange}`, `{id: b, color: red}`], // previous: [`{id: a, color: orange}`, `{id: b, color: red}`], previous: [`{id: a, color: blue}`, `{id: b, color: yellow}`], })); }); it('should track moves normally', () => { let l = buildItemList(['a', 'b', 'c']); differ.check(l); l = buildItemList(['b', 'a', 'c']); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'], // identityChanges: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'], identityChanges: ['{id: c}', '{id: a}[0->1]', '{id: b}[1->0]'], previous: ['{id: a}[0->1]', '{id: b}[1->0]', '{id: c}'], moves: ['{id: b}[1->0]', '{id: a}[0->1]'], })); }); it('should track duplicate reinsertion normally', () => { let l = buildItemList(['a', 'a']); differ.check(l); l = buildItemList(['b', 'a', 'a']); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['{id: b}[null->0]', '{id: a}[0->1]', '{id: a}[1->2]'], // identityChanges: ['{id: a}[0->1]', '{id: a}[1->2]'], identityChanges: ['{id: a}[1->2]', '{id: a}[0->1]'], previous: ['{id: a}[0->1]', '{id: a}[1->2]'], moves: ['{id: a}[0->1]', '{id: a}[1->2]'], additions: ['{id: b}[null->0]'], })); }); it('should track removals normally', () => { const l = buildItemList(['a', 'b', 'c']); differ.check(l); l.splice(2, 1); differ.check(l); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['{id: a}', '{id: b}'], previous: ['{id: a}', '{id: b}', '{id: c}[2->null]'], removals: ['{id: c}[2->null]'], })); }); }); describe('trackBy function by index', () => { let differ: FastIterableDiffer<string>; const trackByIndex = (index: number, item: any): number => index; beforeEach(() => { differ = new FastIterableDiffer(trackByIndex); }); it('should track removals normally', () => { differ.diff(['a', 'b', 'c', 'd']); differ.diff(['e', 'f', 'g', 'h']); differ.diff(['e', 'f', 'h']); expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({ collection: ['e', 'f', 'h'], // previous: ['e', 'f', 'h', 'h[3->null]'], previous: ['e', 'f', 'g', 'h[3->null]'], removals: ['h[3->null]'], identityChanges: ['h'], })); }); }); function iterableDifferToString<V>(iterableChanges: IterableChanges<V>) { const collection: string[] = []; iterableChanges.forEachItem((record: IterableChangeRecord<V>) => collection.push(icrAsString(record))); const previous: string[] = []; iterableChanges.forEachPreviousItem((record: IterableChangeRecord<V>) => previous.push(icrAsString(record))); const additions: string[] = []; iterableChanges.forEachAddedItem((record: IterableChangeRecord<V>) => additions.push(icrAsString(record))); const moves: string[] = []; iterableChanges.forEachMovedItem((record: IterableChangeRecord<V>) => moves.push(icrAsString(record))); const removals: string[] = []; iterableChanges.forEachRemovedItem((record: IterableChangeRecord<V>) => removals.push(icrAsString(record))); const identityChanges: string[] = []; iterableChanges.forEachIdentityChange((record: IterableChangeRecord<V>) => identityChanges.push(icrAsString(record))); return iterableChangesAsString({ collection, previous, additions, moves, removals, identityChanges, }); } function icrAsString<V>(icr: IterableChangeRecord<V>): string { return icr.previousIndex === icr.currentIndex ? stringify(icr.item) : stringify(icr.item) + '[' + stringify(icr.previousIndex) + '->' + stringify(icr.currentIndex) + ']'; } function iterableChangesAsString({ collection = [] as any, previous = [] as any, additions = [] as any, moves = [] as any, removals = [] as any, identityChanges = [] as any }): string { return ( 'collection: ' + collection.join(', ') + '\n' + 'previous: ' + previous.join(', ') + '\n' + 'additions: ' + additions.join(', ') + '\n' + 'moves: ' + moves.join(', ') + '\n' + 'removals: ' + removals.join(', ') + '\n' + 'identityChanges: ' + identityChanges.join(', ') + '\n' ); }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type AuctionResultsForArtistsYouFollowContainerPaginationQueryVariables = { first: number; after?: string | null | undefined; }; export type AuctionResultsForArtistsYouFollowContainerPaginationQueryResponse = { readonly me: { readonly " $fragmentRefs": FragmentRefs<"AuctionResultsForArtistsYouFollow_me">; } | null; }; export type AuctionResultsForArtistsYouFollowContainerPaginationQuery = { readonly response: AuctionResultsForArtistsYouFollowContainerPaginationQueryResponse; readonly variables: AuctionResultsForArtistsYouFollowContainerPaginationQueryVariables; }; /* query AuctionResultsForArtistsYouFollowContainerPaginationQuery( $first: Int! $after: String ) { me { ...AuctionResultsForArtistsYouFollow_me_2HEEH6 id } } fragment AuctionResultListItem_auctionResult on AuctionResult { currency dateText id internalID artist { name id } images { thumbnail { url(version: "square140") height width aspectRatio } } estimate { low } mediumText organization boughtIn performance { mid } priceRealized { cents display displayUSD } saleDate title } fragment AuctionResultsForArtistsYouFollow_me_2HEEH6 on Me { auctionResultsByFollowedArtists(first: $first, after: $after) { totalCount edges { node { saleDate internalID artistID ...AuctionResultListItem_auctionResult id __typename } cursor } pageInfo { endCursor hasNextPage } } } */ const node: ConcreteRequest = (function(){ var v0 = { "defaultValue": null, "kind": "LocalArgument", "name": "after" }, v1 = { "defaultValue": null, "kind": "LocalArgument", "name": "first" }, v2 = [ { "kind": "Variable", "name": "after", "variableName": "after" }, { "kind": "Variable", "name": "first", "variableName": "first" } ], v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }; return { "fragment": { "argumentDefinitions": [ (v0/*: any*/), (v1/*: any*/) ], "kind": "Fragment", "metadata": null, "name": "AuctionResultsForArtistsYouFollowContainerPaginationQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "args": (v2/*: any*/), "kind": "FragmentSpread", "name": "AuctionResultsForArtistsYouFollow_me" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [ (v1/*: any*/), (v0/*: any*/) ], "kind": "Operation", "name": "AuctionResultsForArtistsYouFollowContainerPaginationQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": null, "args": (v2/*: any*/), "concreteType": "AuctionResultConnection", "kind": "LinkedField", "name": "auctionResultsByFollowedArtists", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "totalCount", "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionResultEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "AuctionResult", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "saleDate", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "artistID", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "currency", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "dateText", "storageKey": null }, (v3/*: any*/), { "alias": null, "args": null, "concreteType": "Artist", "kind": "LinkedField", "name": "artist", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, (v3/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionLotImages", "kind": "LinkedField", "name": "images", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "thumbnail", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "square140" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"square140\")" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "height", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "width", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "aspectRatio", "storageKey": null } ], "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionLotEstimate", "kind": "LinkedField", "name": "estimate", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "low", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "mediumText", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "organization", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "boughtIn", "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionLotPerformance", "kind": "LinkedField", "name": "performance", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "mid", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionResultPriceRealized", "kind": "LinkedField", "name": "priceRealized", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "cents", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "displayUSD", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "cursor", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "PageInfo", "kind": "LinkedField", "name": "pageInfo", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "endCursor", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "hasNextPage", "storageKey": null } ], "storageKey": null } ], "storageKey": null }, { "alias": null, "args": (v2/*: any*/), "filters": null, "handle": "connection", "key": "AuctionResultsForArtistsYouFollowContainer_auctionResultsByFollowedArtists", "kind": "LinkedHandle", "name": "auctionResultsByFollowedArtists" }, (v3/*: any*/) ], "storageKey": null } ] }, "params": { "id": "668914f9579e091f9e0db4b244aed0bf", "metadata": {}, "name": "AuctionResultsForArtistsYouFollowContainerPaginationQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '30aa21994425545c2b04109083da75eb'; export default node;
the_stack
import * as THREE from 'three'; import { getRandom, getHtmlColor } from '../utils/lba'; import { SpriteType } from './data/spriteType'; import SampleType from './data/sampleType'; import { loadSprite } from './scenery/isometric/sprites'; import { clone } from 'lodash'; import { MAX_LIFE } from './GameState'; import Scene from './Scene'; import Game from './Game'; import { Time } from '../datatypes'; import { getParams } from '../params'; import { loadInventoryModel } from '../model/inventory'; // import { createBoundingBox } from '../utils/rendering'; export const ExtraFlag = { TIME_OUT: 1 << 0, FLY: 1 << 1, END_OBJ: 1 << 2, END_COL: 1 << 3, STOP_COL: 1 << 4, TAKABLE: 1 << 5, FLASH: 1 << 6, AIM: 1 << 7, IMPACT: 1 << 8, TIME_IN: 1 << 10, WAIT_NO_COL: 1 << 13, BONUS: 1 << 14, DART: 1 << 16, }; interface ExtraProps { bonus: number; flags: { hasCollisions: boolean; hasCollisionFloor: boolean; hasCollisionBricks: boolean; canFall: boolean; isVisible: boolean; isSprite: boolean; }; } interface ExtraState { isVisible: boolean; isTouchingGround: boolean; isTouchingFloor: boolean; isDead: boolean; isColliding: boolean; distFromGround: number; distFromFloor: number; } interface ExtraPhysics { position: THREE.Vector3; orientation: THREE.Quaternion; temp: { position: THREE.Vector3, angle: number, destAngle: number direction: THREE.Vector3, velocity: THREE.Vector3, }; } let indexCount = 0; const ACTOR_BOX = new THREE.Box3(); const EXTRA_BOX = new THREE.Box3(); const INTERSECTION = new THREE.Box3(); const DIFF = new THREE.Vector3(); const TOUCH_GROUND = new THREE.Vector3(0, 0.1, 0); const Z_AXIS = new THREE.Vector3(0, 0, 1); const TRAJECTORY = new THREE.Vector3(); const TRAJECTORY_EULER = new THREE.Euler(); const TRAJECTORY_ROT = new THREE.Quaternion(); const G = new THREE.Object3D(); const P = new THREE.Vector3(0, 0, 0); export default class Extra { readonly type = 'extra'; readonly game: Game; readonly index: number; readonly physics: ExtraPhysics; readonly props: ExtraProps; readonly isSprite: boolean; readonly lifeTime: number; readonly baseTime: Time; readonly sound: any; readonly spriteIndex?: SpriteType; readonly modelIndex?: number; model?: any; info: number; time: Time; flags: number; state: ExtraState; threeObject?: THREE.Object3D; spawnTime: number; speed: number; weight: number; throwAngle: number; hitStrength: number; hasCollidedWithActor: boolean; throwBy: number = -1; targetActor: number = -1; /** * This is used to add data meant to be looked * at in the inspector for debugging purposes. */ dbg: any = {}; static async bonus( game: Game, scene: Scene, position: THREE.Vector3, destAngle: number, spriteIndex: number, bonus: number, time: Time, ): Promise<Extra> { const extra = new Extra(game, position, destAngle, time, spriteIndex, bonus); await extra.loadMesh(scene); extra.flags |= ExtraFlag.BONUS; extra.init(THREE.MathUtils.degToRad(75), 40, 15); // lbaToDegrees(720) extra.playSample(extra.sound, SampleType.BONUS_FOUND); scene.addExtra(extra); return extra; } static async throw( game: Game, scene: Scene, position: THREE.Vector3, destAngle: number, throwAngle: number, spriteIndex: number, bonus: number, time: Time, speed: number, weight: number, strength: number, ): Promise<Extra> { const extra = new Extra(game, position, destAngle, time, spriteIndex, bonus); await extra.loadMesh(scene); extra.flags = ExtraFlag.END_OBJ | ExtraFlag.END_COL | ExtraFlag.IMPACT | ExtraFlag.TIME_IN; extra.hitStrength = strength; extra.init(throwAngle, speed, weight); scene.addExtra(extra); return extra; } static async throwObject( throwBy: number, game: Game, scene: Scene, position: THREE.Vector3, destAngle: number, throwAngle: number, modelIndex: number, time: Time, speed: number, weight: number, strength: number, ): Promise<Extra> { const extra = new Extra(game, position, destAngle, time, null, null, modelIndex); await extra.loadMesh(scene); extra.throwBy = throwBy; extra.flags = ExtraFlag.END_OBJ | ExtraFlag.END_COL | ExtraFlag.IMPACT | ExtraFlag.TIME_IN; extra.hitStrength = strength; extra.init(throwAngle, speed, weight); scene.addExtra(extra); return extra; } static async throwAiming( throwBy: number, game: Game, scene: Scene, position: THREE.Vector3, destAngle: number, spriteIndex: number, time: Time, targetActor: number, speed: number, strength: number, ): Promise<Extra> { const extra = new Extra(game, position, destAngle, time, spriteIndex, null, null); await extra.loadMesh(scene); extra.throwBy = throwBy; extra.targetActor = targetActor; extra.flags = ExtraFlag.END_OBJ | ExtraFlag.END_COL | ExtraFlag.IMPACT | ExtraFlag.TIME_IN | ExtraFlag.AIM; extra.hitStrength = strength; extra.init(destAngle, speed, 1); scene.addExtra(extra); return extra; } private constructor( game: Game, position: THREE.Vector3, angle: number, time: Time, spriteIndex?: number, bonus?: number, modelIndex?: number, ) { this.game = game; this.index = indexCount; indexCount += 1; this.physics = { position, orientation: new THREE.Quaternion(), temp: { position: position.clone(), angle, destAngle: angle, direction: position.clone(), velocity: position.clone(), } }; const euler = new THREE.Euler(0, angle, 0, 'XZY'); this.physics.orientation.setFromEuler(euler); this.isSprite = spriteIndex !== null; this.modelIndex = modelIndex; this.hasCollidedWithActor = false; this.flags = ExtraFlag.STOP_COL | ExtraFlag.WAIT_NO_COL | ExtraFlag.BONUS | ExtraFlag.TAKABLE | ExtraFlag.TIME_IN; this.props = { bonus, flags: { hasCollisions: true, hasCollisionFloor: true, hasCollisionBricks: true, canFall: true, isVisible: true, isSprite: true, } }; this.model = { boundingBox: new THREE.Box3( new THREE.Vector3(-0.1, -0.1, -0.1), new THREE.Vector3(0.1, 0.1, 0.1), ), }; this.state = { isVisible: true, isTouchingGround: false, isTouchingFloor: false, isDead: false, isColliding: false, distFromGround: 0, distFromFloor: 0, }; this.spriteIndex = spriteIndex; this.spawnTime = 0; this.lifeTime = 20; // 20 seconds this.info = bonus; this.hitStrength = 0; this.time = time; this.baseTime = time; this.spawnTime = time.elapsed; this.speed = 0; this.weight = 0; if (game.getState().config.positionalAudio) { const audio = game.getAudioManager(); this.sound = audio.createSamplePositionalAudio(); } } private async loadMesh(scene: Scene) { this.threeObject = new THREE.Object3D(); this.threeObject.position.copy(this.physics.position); TRAJECTORY_EULER.setFromQuaternion(this.physics.orientation, 'YXZ'); TRAJECTORY_EULER.y += Math.PI / 2; this.threeObject.quaternion.setFromEuler(TRAJECTORY_EULER); let obj = null; if (this.isSprite) { obj = await loadSprite( this.spriteIndex, scene.props.ambience, false, true, scene.is3DCam ); } else { obj = await loadInventoryModel( {}, this.modelIndex, scene.scenery.props.envInfo, scene.props.ambience ); } // // Debug Bounding Box // obj.boundingBoxDebugMesh = createBoundingBox( // obj.boundingBox, // new THREE.Vector3(1, 0, 0) // ); // obj.boundingBoxDebugMesh.name = 'BoundingBox'; // this.threeObject.add(obj.boundingBoxDebugMesh); this.threeObject.add(obj.threeObject ?? obj.mesh); this.threeObject.name = `extra_${this.props.bonus}`; this.threeObject.visible = this.state.isVisible; this.model = obj; if (scene.game.getState().config.positionalAudio) { this.threeObject.add(this.sound); } } private init(angle, speed, _weight) { this.flags |= ExtraFlag.FLY; this.time = this.baseTime; this.speed = speed; this.weight = _weight; this.throwAngle = angle; if (!((this.flags & ExtraFlag.AIM) === ExtraFlag.AIM)) { this.doTrajectory(this.time); } } playSample(sound: any, index: number) { const audio = this.game.getAudioManager(); if (this.game.getState().config.positionalAudio) { audio.playSound(sound, index); return; } audio.playSample(index); } stopSample(sound: any, index: number) { const audio = this.game.getAudioManager(); if (this.game.getState().config.positionalAudio) { audio.stopSound(sound, index); return; } audio.stopSample(index); } doTrajectory(time) { const ts = (time.elapsed - this.spawnTime) * 0.002; const gravity = 0.9 * Math.pow(1.275, this.weight) * 1000; const x = this.speed * ts * Math.cos(this.throwAngle); const y = this.speed * ts * Math.sin(this.throwAngle) - (0.5 * gravity * ts * ts); TRAJECTORY.set(x, y, 0); TRAJECTORY_EULER.set(0, this.physics.temp.angle, 0, 'XZY'); TRAJECTORY.applyEuler(TRAJECTORY_EULER); this.physics.position.add(TRAJECTORY); this.threeObject.position.copy(this.physics.position); this.threeObject.quaternion.copy( TRAJECTORY_ROT.setFromUnitVectors( Z_AXIS, TRAJECTORY.normalize(), ), ); } doAiming(scene, time) { const delta = this.speed * time.delta * 0.001; const aimingActor = scene.actors[this.targetActor]; const bb = aimingActor.getBoundingBox(); const halfHeight = (bb.max.y - bb.min.y) * 0.5; const position = aimingActor.physics.position.clone(); position.y += halfHeight; G.position.set(0, 0, 0); P.set(0, 0, 0); P.subVectors(position, this.physics.position).normalize(); G.translateOnAxis(P, delta); this.threeObject.position.add(G.position); this.physics.position.copy(this.threeObject.position); } update(game: Game, scene: Scene, time: Time) { let hitActor = null; if (time.elapsed - this.spawnTime > this.lifeTime && this.spriteIndex !== SpriteType.KEY) { this.flags |= ExtraFlag.TIME_OUT; } if ((this.flags & ExtraFlag.FLY) === ExtraFlag.FLY) { if ((this.flags & ExtraFlag.AIM) === ExtraFlag.AIM) { this.doAiming(scene, time); } else { this.doTrajectory(time); } } if (this.model && !((this.flags & ExtraFlag.FLY) === ExtraFlag.FLY) || ((this.flags & ExtraFlag.IMPACT) === ExtraFlag.IMPACT)) { EXTRA_BOX.copy(this.model.boundingBox); EXTRA_BOX.translate(this.physics.position); DIFF.set(0, 1 / 128, 0); EXTRA_BOX.translate(DIFF); for (let i = 0; i < scene.actors.length; i += 1) { const a = scene.actors[i]; if ((a.model === null && a.sprite === null) || i === this.throwBy || a.state.isDead || !(a.props.flags.hasCollisions || a.props.flags.isSprite)) { continue; } const boundingBox = a.getBoundingBox(); INTERSECTION.copy(boundingBox); if (a.model) { INTERSECTION.translate(a.physics.position); } else { INTERSECTION.applyMatrix4(a.threeObject.matrixWorld); } DIFF.set(0, 1 / 128, 0); INTERSECTION.translate(DIFF); ACTOR_BOX.copy(INTERSECTION); if (ACTOR_BOX.intersectsBox(EXTRA_BOX)) { hitActor = a; break; } } } // Only Twinsen can collect extras such as keys, but we allow other actors // to collect extras like life points. let shouldCollect = false; if (hitActor && hitActor.index === 0) { shouldCollect = true; if (((this.flags & ExtraFlag.BONUS) === ExtraFlag.BONUS)) { const { hero } = game.getState(); switch (this.spriteIndex) { case SpriteType.LIFE: hero.life += this.info * 5; if (hero.life > MAX_LIFE) { hero.life = MAX_LIFE; } break; case SpriteType.MAGIC: hero.magic += this.info; if (hero.magic > (hero.magicball.level + 1) * 20) { hero.magic = (hero.magicball.level + 1) * 20; } break; case SpriteType.KEY: hero.keys += 1; this.info = 1; break; case SpriteType.MONEY: case SpriteType.KASHES: hero.money += this.info; break; } } if (((this.flags & ExtraFlag.IMPACT) === ExtraFlag.IMPACT)) { hitActor.hit(-1, this.hitStrength); // check hitBy is correct } } else if (hitActor) { switch (this.spriteIndex) { case SpriteType.LIFE: hitActor.props.life += this.info * 5; shouldCollect = true; break; } } if (this.props.flags.hasCollisions && time.elapsed - this.spawnTime > 0.5) { const isTouchingGroud = scene.scenery.physics.processCollisions(scene, this, time); if (isTouchingGroud) { this.physics.position.add(TOUCH_GROUND); this.threeObject.position.copy(this.physics.position); this.flags &= ~ExtraFlag.FLY; if ((this.flags & ExtraFlag.IMPACT) === ExtraFlag.IMPACT) { scene.removeExtra(this); } } if (this.state.isColliding && (this.flags & ExtraFlag.DART) === ExtraFlag.DART) { this.flags &= ~ExtraFlag.FLY; } } if (shouldCollect || (this.flags & ExtraFlag.TIME_OUT) === ExtraFlag.TIME_OUT && !((this.flags & ExtraFlag.DART) === ExtraFlag.DART)) { if (this.info && shouldCollect) { this.collect(game, scene); } scene.removeExtra(this); } } private collect(game: Game, scene: Scene) { this.stopSample(this.sound, SampleType.BONUS_FOUND); this.playSample(this.sound, SampleType.BONUS_COLLECTED); const itrjId = `extra_${this.index}_${this.info}`; const interjections = clone(game.getUiState().interjections); interjections[itrjId] = { scene: scene.index, obj: this, color: getHtmlColor(scene.props.palette, (10 * 16) + 12), value: this.info, }; game.setUiState({interjections}); setTimeout(() => { const interjectionsCopy = clone(game.getUiState().interjections); delete interjectionsCopy[itrjId]; game.setUiState({interjections: interjectionsCopy}); }, 1000); } collectKey(game: Game, scene: Scene) { game.getState().hero.keys += 1; this.info = 1; this.collect(game, scene); scene.removeExtra(this); } } export function getBonus(type): SpriteType { const isLBA1 = getParams().game === 'lba1'; const bonus = []; for (let b = 0; b < 5; b += 1) { if (type & (1 << (b + 4))) { bonus.push(b); } } // TODO validate per chapter bonus let spriteIndex = bonus[getRandom(0, bonus.length - 1)]; spriteIndex += 3; if (!isLBA1 && spriteIndex === 3) { spriteIndex = SpriteType.KASHES; // TODO if planet Zeelich then increment // spriteIndex += 1 } return spriteIndex; }
the_stack
import { CoreFile } from '@services/file'; import { CoreFilepool } from '@services/filepool'; import { CoreSites } from '@services/sites'; import { CoreMimetypeUtils } from '@services/utils/mimetype'; import { CoreTextUtils } from '@services/utils/text'; import { CoreUtils } from '@services/utils/utils'; import { CoreH5PCore, CoreH5PDependencyAsset, CoreH5PContentDependencyData, CoreH5PDependenciesFiles, CoreH5PLibraryBasicData, CoreH5PContentMainLibraryData, } from './core'; import { CONTENTS_LIBRARIES_TABLE_NAME, CONTENT_TABLE_NAME, CoreH5PLibraryCachedAssetsDBRecord } from '../services/database/h5p'; import { CoreH5PLibraryBeingSaved } from './storage'; /** * Equivalent to Moodle's implementation of H5PFileStorage. */ export class CoreH5PFileStorage { static readonly CACHED_ASSETS_FOLDER_NAME = 'cachedassets'; /** * Will concatenate all JavaScrips and Stylesheets into two files in order to improve page performance. * * @param files A set of all the assets required for content to display. * @param key Hashed key for cached asset. * @param folderName Name of the folder of the H5P package. * @param siteId The site ID. * @return Promise resolved when done. */ async cacheAssets(files: CoreH5PDependenciesFiles, key: string, folderName: string, siteId: string): Promise<void> { const cachedAssetsPath = this.getCachedAssetsFolderPath(folderName, siteId); // Treat each type in the assets. await Promise.all(Object.keys(files).map(async (type) => { const assets: CoreH5PDependencyAsset[] = files[type]; if (!assets || !assets.length) { return; } // Create new file for cached assets. const fileName = key + '.' + (type == 'scripts' ? 'js' : 'css'); const path = CoreTextUtils.concatenatePaths(cachedAssetsPath, fileName); // Store concatenated content. const content = await this.concatenateFiles(assets, type); await CoreFile.writeFile(path, content); // Now update the files data. files[type] = [ { path: CoreTextUtils.concatenatePaths(CoreH5PFileStorage.CACHED_ASSETS_FOLDER_NAME, fileName), version: '', }, ]; })); } /** * Adds all files of a type into one file. * * @param assets A list of files. * @param type The type of files in assets. Either 'scripts' or 'styles' * @return Promise resolved with all of the files content in one string. */ protected async concatenateFiles(assets: CoreH5PDependencyAsset[], type: string): Promise<string> { const basePath = CoreFile.convertFileSrc(CoreFile.getBasePathInstant()); let content = ''; for (const i in assets) { const asset = assets[i]; let fileContent = await CoreFile.readFile(asset.path); if (type == 'scripts') { // No need to treat scripts, just append the content. content += fileContent + ';\n'; continue; } // Rewrite relative URLs used inside stylesheets. const matches = fileContent.match(/url\(['"]?([^"')]+)['"]?\)/ig); const assetPath = asset.path.replace(/(^\/|\/$)/g, ''); // Path without start/end slashes. const treated = {}; if (matches && matches.length) { matches.forEach((match) => { let url = match.replace(/(url\(['"]?|['"]?\)$)/ig, ''); if (treated[url] || url.match(/^(data:|([a-z0-9]+:)?\/)/i)) { return; // Not relative or already treated, skip. } const pathSplit = assetPath.split('/'); treated[url] = url; /* Find "../" in the URL. If it exists, we have to remove "../" and switch the last folder in the filepath for the first folder in the url. */ if (url.match(/^\.\.\//)) { // Split and remove empty values. const urlSplit = url.split('/').filter((i) => i); // Remove the file name from the asset path. pathSplit.pop(); // Remove the first element from the file URL: ../ . urlSplit.shift(); // Put the url's first folder into the asset path. pathSplit[pathSplit.length - 1] = urlSplit[0]; urlSplit.shift(); // Create the new URL and replace it in the file contents. url = pathSplit.join('/') + '/' + urlSplit.join('/'); } else { pathSplit[pathSplit.length - 1] = url; // Put the whole path to the end of the asset path. url = pathSplit.join('/'); } fileContent = fileContent.replace( new RegExp(CoreTextUtils.escapeForRegex(match), 'g'), 'url("' + CoreTextUtils.concatenatePaths(basePath, url) + '")', ); }); } content += fileContent + '\n'; } return content; } /** * Delete cached assets from file system. * * @param libraryId Library identifier. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async deleteCachedAssets(removedEntries: CoreH5PLibraryCachedAssetsDBRecord[], siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); const promises: Promise<void>[] = []; removedEntries.forEach((entry) => { const cachedAssetsFolder = this.getCachedAssetsFolderPath(entry.foldername, site.getId()); ['js', 'css'].forEach((type) => { const path = CoreTextUtils.concatenatePaths(cachedAssetsFolder, entry.hash + '.' + type); promises.push(CoreFile.removeFile(path)); }); }); // Ignore errors, maybe there's no cached asset of some type. await CoreUtils.ignoreErrors(CoreUtils.allPromises(promises)); } /** * Deletes a content folder from the file system. * * @param folderName Folder name of the content. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async deleteContentFolder(folderName: string, siteId: string): Promise<void> { await CoreFile.removeDir(this.getContentFolderPath(folderName, siteId)); } /** * Delete content indexes from filesystem. * * @param folderName Name of the folder of the H5P package. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async deleteContentIndex(folderName: string, siteId: string): Promise<void> { await CoreFile.removeFile(this.getContentIndexPath(folderName, siteId)); } /** * Delete content indexes from filesystem. * * @param libraryId Library identifier. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async deleteContentIndexesForLibrary(libraryId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); const db = site.getDb(); // Get the folder names of all the packages that use this library. const query = 'SELECT DISTINCT hc.foldername ' + 'FROM ' + CONTENTS_LIBRARIES_TABLE_NAME + ' hcl ' + 'JOIN ' + CONTENT_TABLE_NAME + ' hc ON hcl.h5pid = hc.id ' + 'WHERE hcl.libraryid = ?'; const queryArgs = [libraryId]; const result = await db.execute(query, queryArgs); await Array.from(result.rows).map(async (entry: {foldername: string}) => { try { // Delete the index.html. await this.deleteContentIndex(entry.foldername, site.getId()); } catch (error) { // Ignore errors. } }); } /** * Deletes a library from the file system. * * @param libraryData The library data. * @param siteId Site ID. * @param folderName Folder name. If not provided, it will be calculated. * @return Promise resolved when done. */ async deleteLibraryFolder( libraryData: CoreH5PLibraryBasicData | CoreH5PContentMainLibraryData, siteId: string, folderName?: string, ): Promise<void> { await CoreFile.removeDir(this.getLibraryFolderPath(libraryData, siteId, folderName)); } /** * Will check if there are cache assets available for content. * * @param key Hashed key for cached asset * @return Promise resolved with the files. */ async getCachedAssets(key: string): Promise<{scripts?: CoreH5PDependencyAsset[]; styles?: CoreH5PDependencyAsset[]} | null> { // Get JS and CSS cached assets if they exist. const results = await Promise.all([ this.getCachedAsset(key, '.js'), this.getCachedAsset(key, '.css'), ]); const files = { scripts: results[0], styles: results[1], }; return files.scripts || files.styles ? files : null; } /** * Check if a cached asset file exists and, if so, return its data. * * @param key Key of the cached asset. * @param extension Extension of the file to get. * @return Promise resolved with the list of assets (only one), undefined if not found. */ protected async getCachedAsset(key: string, extension: string): Promise<CoreH5PDependencyAsset[] | undefined> { try { const path = CoreTextUtils.concatenatePaths(CoreH5PFileStorage.CACHED_ASSETS_FOLDER_NAME, key + extension); const size = await CoreFile.getFileSize(path); if (size > 0) { return [ { path: path, version: '', }, ]; } } catch (error) { // Not found, nothing to do. } } /** * Get relative path to a content cached assets. * * @param folderName Name of the folder of the content the assets belong to. * @param siteId Site ID. * @return Path. */ getCachedAssetsFolderPath(folderName: string, siteId: string): string { return CoreTextUtils.concatenatePaths( this.getContentFolderPath(folderName, siteId), CoreH5PFileStorage.CACHED_ASSETS_FOLDER_NAME, ); } /** * Get a content folder name given the package URL. * * @param fileUrl Package URL. * @param siteId Site ID. * @return Promise resolved with the folder name. */ async getContentFolderNameByUrl(fileUrl: string, siteId: string): Promise<string> { const path = await CoreFilepool.getFilePathByUrl(siteId, fileUrl); const fileAndDir = CoreFile.getFileAndDirectoryFromPath(path); return CoreMimetypeUtils.removeExtension(fileAndDir.name); } /** * Get a package content path. * * @param folderName Name of the folder of the H5P package. * @param siteId The site ID. * @return Folder path. */ getContentFolderPath(folderName: string, siteId: string): string { return CoreTextUtils.concatenatePaths( this.getExternalH5PFolderPath(siteId), 'packages/' + folderName + '/content', ); } /** * Get the content index file. * * @param fileUrl URL of the H5P package. * @param siteId The site ID. If not defined, current site. * @return Promise resolved with the file URL if exists, rejected otherwise. */ async getContentIndexFileUrl(fileUrl: string, siteId?: string): Promise<string> { siteId = siteId || CoreSites.getCurrentSiteId(); const folderName = await this.getContentFolderNameByUrl(fileUrl, siteId); const file = await CoreFile.getFile(this.getContentIndexPath(folderName, siteId)); return file.toURL(); } /** * Get the path to a content index. * * @param folderName Name of the folder of the H5P package. * @param siteId The site ID. * @return Folder path. */ getContentIndexPath(folderName: string, siteId: string): string { return CoreTextUtils.concatenatePaths(this.getContentFolderPath(folderName, siteId), 'index.html'); } /** * Get the path to the folder that contains the H5P core libraries. * * @return Folder path. */ getCoreH5PPath(): string { return CoreTextUtils.concatenatePaths(CoreFile.getWWWPath(), '/assets/lib/h5p/'); } /** * Get the path to the dependency. * * @param dependency Dependency library. * @return The path to the dependency library */ getDependencyPath(dependency: CoreH5PContentDependencyData): string { return 'libraries/' + dependency.machineName + '-' + dependency.majorVersion + '.' + dependency.minorVersion; } /** * Get path to the folder containing H5P files extracted from packages. * * @param siteId The site ID. * @return Folder path. */ getExternalH5PFolderPath(siteId: string): string { return CoreTextUtils.concatenatePaths(CoreFile.getSiteFolder(siteId), 'h5p'); } /** * Get libraries folder path. * * @param siteId The site ID. * @return Folder path. */ getLibrariesFolderPath(siteId: string): string { return CoreTextUtils.concatenatePaths(this.getExternalH5PFolderPath(siteId), 'libraries'); } /** * Get a library's folder path. * * @param libraryData The library data. * @param siteId The site ID. * @param folderName Folder name. If not provided, it will be calculated. * @return Folder path. */ getLibraryFolderPath( libraryData: CoreH5PLibraryBasicData | CoreH5PContentMainLibraryData, siteId: string, folderName?: string, ): string { if (!folderName) { folderName = CoreH5PCore.libraryToString(libraryData, true); } return CoreTextUtils.concatenatePaths(this.getLibrariesFolderPath(siteId), folderName); } /** * Save the content in filesystem. * * @param contentPath Path to the current content folder (tmp). * @param folderName Name to put to the content folder. * @param siteId Site ID. * @return Promise resolved when done. */ async saveContent(contentPath: string, folderName: string, siteId: string): Promise<void> { const folderPath = this.getContentFolderPath(folderName, siteId); // Delete existing content for this package. await CoreUtils.ignoreErrors(CoreFile.removeDir(folderPath)); // Copy the new one. await CoreFile.moveDir(contentPath, folderPath); } /** * Save a library in filesystem. * * @param libraryData Library data. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async saveLibrary(libraryData: CoreH5PLibraryBeingSaved, siteId?: string): Promise<void> { siteId = siteId || CoreSites.getCurrentSiteId(); const folderPath = this.getLibraryFolderPath(libraryData, siteId); // Delete existing library version. try { await CoreFile.removeDir(folderPath); } catch (error) { // Ignore errors, maybe it doesn't exist. } if (libraryData.uploadDirectory) { // Copy the new one. await CoreFile.moveDir(libraryData.uploadDirectory, folderPath, true); } } }
the_stack
import { map, mergeMap } from 'rxjs/operators'; import { SchemaFormat } from './interface'; import { CoreSchemaRegistry, SchemaValidationException } from './registry'; import { addUndefinedDefaults } from './transforms'; describe('CoreSchemaRegistry', () => { it('works asynchronously', (done) => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); const data: any = {}; registry .compile({ properties: { bool: { type: 'boolean' }, str: { type: 'string', default: 'someString' }, obj: { properties: { num: { type: 'number' }, other: { type: 'number', default: 0 }, }, }, tslint: { $ref: 'https://json.schemastore.org/npm-link-up#', }, }, }) .pipe( mergeMap((validator) => validator(data)), map((result) => { expect(result.success).toBe(true); expect(data.obj.num).toBeUndefined(); expect(data.tslint).not.toBeUndefined(); }), ) .toPromise() .then(done, done.fail); }); it('supports pre transforms', (done) => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); const data = {}; registry.addPreTransform((data, ptr) => { if (ptr == '/') { return { str: 'string' }; } return data; }); registry .compile({ properties: { bool: { type: 'boolean' }, str: { type: 'string', default: 'someString' }, obj: { properties: { num: { type: 'number' }, other: { type: 'number', default: 0 }, }, }, }, }) .pipe( mergeMap((validator) => validator(data)), map((result) => { const data = result.data as any; expect(result.success).toBe(true); expect(data.str).toBe('string'); expect(data.obj.num).toBeUndefined(); }), ) .toPromise() .then(done, done.fail); }); it('supports local references', (done) => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); const data = { numbers: { one: 1 } }; registry .compile({ properties: { numbers: { type: 'object', additionalProperties: { '$ref': '#/definitions/myRef' }, }, }, definitions: { myRef: { type: 'integer' }, }, }) .pipe( mergeMap((validator) => validator(data)), map((result) => { expect(result.success).toBe(true); expect(data.numbers.one).not.toBeUndefined(); }), ) .toPromise() .then(done, done.fail); }); it('fails on invalid additionalProperties', (done) => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); const data = { notNum: 'foo' }; registry .compile({ properties: { num: { type: 'number' }, }, additionalProperties: false, }) .pipe( mergeMap((validator) => validator(data)), map((result) => { expect(result.success).toBe(false); expect(result.errors && result.errors[0].message).toContain( 'must NOT have additional properties', ); }), ) .toPromise() .then(done, done.fail); }); it('fails on invalid enum value', (done) => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); const data = { packageManager: 'foo' }; registry .compile({ properties: { packageManager: { type: 'string', enum: ['npm', 'yarn', 'pnpm', 'cnpm'] }, }, additionalProperties: false, }) .pipe( mergeMap((validator) => validator(data)), map((result) => { expect(result.success).toBe(false); expect(new SchemaValidationException(result.errors).message).toContain( `Data path "/packageManager" must be equal to one of the allowed values. Allowed values are: "npm", "yarn", "pnpm", "cnpm".`, ); }), ) .toPromise() .then(done, done.fail); }); it('fails on invalid additionalProperties async', (done) => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); const data = { notNum: 'foo' }; registry .compile({ $async: true, properties: { num: { type: 'number' }, }, additionalProperties: false, }) .pipe( mergeMap((validator) => validator(data)), map((result) => { expect(result.success).toBe(false); expect(result.errors?.[0].message).toContain('must NOT have additional properties'); expect(result.errors?.[0].keyword).toBe('additionalProperties'); }), ) .toPromise() .then(done, done.fail); }); it('supports sync format', (done) => { const registry = new CoreSchemaRegistry(); const data = { str: 'hotdog' }; const format = { name: 'is-hotdog', formatter: { validate: (str: string) => str === 'hotdog', }, }; registry.addFormat(format); registry .compile({ properties: { str: { type: 'string', format: 'is-hotdog' }, }, }) .pipe( mergeMap((validator) => validator(data)), map((result) => { expect(result.success).toBe(true); }), ) .toPromise() .then(done, done.fail); }); it('supports async format', (done) => { const registry = new CoreSchemaRegistry(); const data = { str: 'hotdog' }; const format: SchemaFormat = { name: 'is-hotdog', formatter: { async: true, validate: async (str: string) => str === 'hotdog', }, }; registry.addFormat(format); registry .compile({ $async: true, properties: { str: { type: 'string', format: 'is-hotdog' }, }, }) .pipe( mergeMap((validator) => validator(data)), map((result) => { expect(result.success).toBe(true); }), ) .toPromise() .then(done, done.fail); }); it('shows dataPath and message on error', async () => { const registry = new CoreSchemaRegistry(); const data = { hotdot: 'hotdog', banana: 'banana' }; const format: SchemaFormat = { name: 'is-hotdog', formatter: { async: false, validate: (str: string) => str === 'hotdog', }, }; registry.addFormat(format); await registry .compile({ properties: { hotdot: { type: 'string', format: 'is-hotdog' }, banana: { type: 'string', format: 'is-hotdog' }, }, }) .pipe( mergeMap((validator) => validator(data)), map((result) => { expect(result.success).toBe(false); expect(result.errors && result.errors[0]).toBeTruthy(); expect(result.errors && result.errors[0].keyword).toBe('format'); expect(result.errors && result.errors[0].instancePath).toBe('/banana'); expect(result.errors && (result.errors[0].params as any).format).toBe('is-hotdog'); }), ) .toPromise(); }); it('supports smart defaults', (done) => { const registry = new CoreSchemaRegistry(); const data: any = { arr: [{}], }; registry.addSmartDefaultProvider('test', (schema) => { expect(schema).toEqual({ $source: 'test', }); return true; }); registry.addSmartDefaultProvider('test2', (schema) => { expect(schema).toEqual({ $source: 'test2', blue: 'yep', }); return schema['blue']; }); registry.addSmartDefaultProvider('test3', () => { return [1, 2, 3]; }); registry .compile({ properties: { bool: { $ref: '#/definitions/example', }, arr: { items: { properties: { 'test': { $ref: '#/definitions/other', }, }, }, }, arr2: { $ref: '#/definitions/test3', }, obj: { properties: { deep: { properties: { arr: { $ref: '#/definitions/test3', }, }, }, }, }, }, definitions: { example: { type: 'boolean', $default: { $source: 'test', }, }, other: { type: 'string', $default: { $source: 'test2', blue: 'yep', }, }, test3: { type: 'array', $default: { $source: 'test3', }, }, }, }) .pipe( mergeMap((validator) => validator(data)), map((result) => { expect(result.success).toBe(true); expect(data.bool).toBe(true); expect(data.arr[0].test).toBe('yep'); expect(data.arr2).toEqual([1, 2, 3]); expect(data.obj.deep.arr).toEqual([1, 2, 3]); }), ) .toPromise() .then(done, done.fail); }); it('works with true as a schema and post-transforms', async () => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); const data = { a: 1, b: 2 }; const validate = await registry.compile(true).toPromise(); const result = await validate(data).toPromise(); expect(result.success).toBe(true); expect(result.data).toBe(data); }); it('adds deprecated options usage', (done) => { const registry = new CoreSchemaRegistry(); const deprecatedMessages: string[] = []; registry.useXDeprecatedProvider((m) => deprecatedMessages.push(m)); const data = { foo: true, bar: true, bat: true, }; registry .compile({ properties: { foo: { type: 'boolean', 'x-deprecated': 'Use bar instead.' }, bar: { type: 'boolean', 'x-deprecated': true }, buz: { type: 'boolean', 'x-deprecated': true }, bat: { type: 'boolean', 'x-deprecated': false }, }, }) .pipe( mergeMap((validator) => validator(data)), map((result) => { expect(deprecatedMessages.length).toBe(2); expect(deprecatedMessages[0]).toBe('Option "foo" is deprecated: Use bar instead.'); expect(deprecatedMessages[1]).toBe('Option "bar" is deprecated.'); expect(result.success).toBe(true, result.errors); }), ) .toPromise() .then(done, done.fail); }); });
the_stack
import AnchoredOperationModel from '../../lib/core/models/AnchoredOperationModel'; import CreateOperation from '../../lib/core/versions/latest/CreateOperation'; import DeactivateOperation from '../../lib/core/versions/latest/DeactivateOperation'; import DidState from '../../lib/core/models/DidState'; import Document from '../utils/Document'; import DocumentComposer from '../../lib/core/versions/latest/DocumentComposer'; import DocumentModel from '../../lib/core/versions/latest/models/DocumentModel'; import ErrorCode from '../../lib/core/versions/latest/ErrorCode'; import IOperationProcessor from '../../lib/core/interfaces/IOperationProcessor'; import IOperationStore from '../../lib/core/interfaces/IOperationStore'; import IVersionManager from '../../lib/core/interfaces/IVersionManager'; import JsObject from '../../lib/core/versions/latest/util/JsObject'; import Jwk from '../../lib/core/versions/latest/util/Jwk'; import JwkEs256k from '../../lib/core/models/JwkEs256k'; import Logger from '../../lib/common/Logger'; import MockOperationStore from '../mocks/MockOperationStore'; import MockVersionManager from '../mocks/MockVersionManager'; import Multihash from '../../lib/core/versions/latest/Multihash'; import OperationGenerator from '../generators/OperationGenerator'; import OperationProcessor from '../../lib/core/versions/latest/OperationProcessor'; import OperationType from '../../lib/core/enums/OperationType'; import PatchAction from '../../lib/core/versions/latest/PatchAction'; import PublicKeyModel from '../../lib/core/versions/latest/models/PublicKeyModel'; import RecoverOperation from '../../lib/core/versions/latest/RecoverOperation'; import Resolver from '../../lib/core/Resolver'; import SidetreeError from '../../lib/common/SidetreeError'; import UpdateOperation from '../../lib/core/versions/latest/UpdateOperation'; async function createUpdateSequence ( didUniqueSuffix: string, createOp: AnchoredOperationModel, numberOfUpdates: number, privateKey: any): Promise<AnchoredOperationModel[]> { const ops = new Array(createOp); let currentUpdateKey = Jwk.getEs256kPublicKey(privateKey); let currentPrivateKey = privateKey; for (let i = 0; i < numberOfUpdates; ++i) { const [nextUpdateKey, nextPrivateKey] = await OperationGenerator.generateKeyPair('updateKey'); const nextUpdateCommitmentHash = Multihash.canonicalizeThenDoubleHashThenEncode(nextUpdateKey.publicKeyJwk); const patches = [ { action: PatchAction.RemoveServices, ids: ['serviceId' + (i - 1)] }, { action: PatchAction.AddServices, services: OperationGenerator.generateServices(['serviceId' + i]) } ]; const updateOperationRequest = await OperationGenerator.createUpdateOperationRequest( didUniqueSuffix, currentUpdateKey, currentPrivateKey, nextUpdateCommitmentHash, patches ); // Now that the update payload is created, update the update reveal for the next operation generation to use. currentUpdateKey = nextUpdateKey.publicKeyJwk; currentPrivateKey = nextPrivateKey; const operationBuffer = Buffer.from(JSON.stringify(updateOperationRequest)); const updateOp: AnchoredOperationModel = { type: OperationType.Update, didUniqueSuffix, operationBuffer, transactionTime: i + 1, transactionNumber: i + 1, operationIndex: 0 }; ops.push(updateOp); } return ops; } function getFactorial (n: number): number { let factorial = 1; for (let i = 2; i <= n; ++i) { factorial *= i; } return factorial; } // Return a permutation of a given size with a specified index among // all possible permutations. For example, there are 5! = 120 permutations // of size 5, so by passing index values 0..119 we can enumerate all // permutations function getPermutation (size: number, index: number): Array<number> { const permutation: Array<number> = []; for (let i = 0; i < size; ++i) { permutation.push(i); } for (let i = 0; i < size; ++i) { const j = i + Math.floor(index / getFactorial(size - i - 1)); index = index % getFactorial(size - i - 1); const t = permutation[i]; permutation[i] = permutation[j]; permutation[j] = t; } return permutation; } function validateDocumentAfterUpdates (document: DocumentModel | undefined, numberOfUpdates: number) { expect(document).toBeDefined(); expect(document!.services![0].id).toEqual('serviceId' + (numberOfUpdates - 1)); } describe('OperationProcessor', async () => { let resolver: Resolver; let operationStore: IOperationStore; let versionManager: IVersionManager; let operationProcessor: IOperationProcessor; let createOp: AnchoredOperationModel; let recoveryPublicKey: JwkEs256k; let recoveryPrivateKey: JwkEs256k; let signingKeyId: string; let signingPublicKey: PublicKeyModel; let signingPrivateKey: JwkEs256k; let didUniqueSuffix: string; beforeEach(async () => { operationStore = new MockOperationStore(); operationProcessor = new OperationProcessor(); versionManager = new MockVersionManager(); spyOn(versionManager, 'getOperationProcessor').and.returnValue(operationProcessor); resolver = new Resolver(versionManager, operationStore); // Generate a unique key-pair used for each test. signingKeyId = 'signingKey'; [recoveryPublicKey, recoveryPrivateKey] = await Jwk.generateEs256kKeyPair(); [signingPublicKey, signingPrivateKey] = await OperationGenerator.generateKeyPair(signingKeyId); const services = OperationGenerator.generateServices(['serviceId0']); const createOperationBuffer = await OperationGenerator.generateCreateOperationBuffer( recoveryPublicKey, signingPublicKey, services ); const createOperation = await CreateOperation.parse(createOperationBuffer); createOp = OperationGenerator.createAnchoredOperationModelFromOperationModel(createOperation, 0, 0, 0); didUniqueSuffix = createOp.didUniqueSuffix; }); it('should return a DID Document for resolve(did) for a registered DID', async () => { await operationStore.insertOrReplace([createOp]); const didState = await resolver.resolve(didUniqueSuffix); expect(didState).toBeDefined(); const document = didState!.document; const signingKey = Document.getPublicKey(document, signingKeyId); expect(signingKey).toBeDefined(); }); it('should ignore a duplicate create operation', async () => { await operationStore.insertOrReplace([createOp]); // Insert a duplicate create op with a different transaction time. const duplicateOperation = await CreateOperation.parse(createOp.operationBuffer); const duplicateNamedAnchoredCreateOperationModel = OperationGenerator.createAnchoredOperationModelFromOperationModel(duplicateOperation, 1, 1, 0); await operationStore.insertOrReplace([duplicateNamedAnchoredCreateOperationModel]); const didState = await resolver.resolve(didUniqueSuffix); expect(didState).toBeDefined(); const document = didState!.document; const signingKey = Document.getPublicKey(document, signingKeyId); expect(signingKey).toBeDefined(); }); it('should process update to remove a public key correctly', async () => { await operationStore.insertOrReplace([createOp]); const patches = [ { action: PatchAction.RemovePublicKeys, ids: [signingKeyId] } ]; const nextUpdateCommitmentHash = 'EiD_UnusedNextUpdateCommitmentHash_AAAAAAAAAAA'; const updateOperationRequest = await OperationGenerator.createUpdateOperationRequest( didUniqueSuffix, signingPublicKey.publicKeyJwk, signingPrivateKey, nextUpdateCommitmentHash, patches ); const operationBuffer = Buffer.from(JSON.stringify(updateOperationRequest)); const updateOp: AnchoredOperationModel = { type: OperationType.Update, didUniqueSuffix, operationBuffer, transactionTime: 1, transactionNumber: 1, operationIndex: 0 }; await operationStore.insertOrReplace([updateOp]); const didState = await resolver.resolve(didUniqueSuffix); expect(didState).toBeDefined(); const document = didState!.document; const signingKey = Document.getPublicKey(document, signingKeyId); expect(signingKey).not.toBeDefined(); // if update above went through, new key would be added. }); it('should process updates correctly', async () => { const numberOfUpdates = 10; const ops = await createUpdateSequence(didUniqueSuffix, createOp, numberOfUpdates, signingPrivateKey); await operationStore.insertOrReplace(ops); const didState = await resolver.resolve(didUniqueSuffix); expect(didState).toBeDefined(); validateDocumentAfterUpdates(didState!.document, numberOfUpdates); }); it('should correctly process updates in reverse order', async () => { const numberOfUpdates = 10; const ops = await createUpdateSequence(didUniqueSuffix, createOp, numberOfUpdates, signingPrivateKey); for (let i = numberOfUpdates; i >= 0; --i) { await operationStore.insertOrReplace([ops[i]]); } const didState = await resolver.resolve(didUniqueSuffix); expect(didState).toBeDefined(); validateDocumentAfterUpdates(didState!.document, numberOfUpdates); }); it('should correctly process updates in every (5! = 120) order', async () => { const numberOfUpdates = 4; const ops = await createUpdateSequence(didUniqueSuffix, createOp, numberOfUpdates, signingPrivateKey); const numberOfOps = ops.length; const numberOfPermutations = getFactorial(numberOfOps); for (let i = 0; i < numberOfPermutations; ++i) { const permutation = getPermutation(numberOfOps, i); operationStore = new MockOperationStore(); resolver = new Resolver(versionManager, operationStore); const permutedOps = permutation.map(i => ops[i]); await operationStore.insertOrReplace(permutedOps); const didState = await resolver.resolve(didUniqueSuffix); expect(didState).toBeDefined(); validateDocumentAfterUpdates(didState!.document, numberOfUpdates); } }); it('should process deactivate operation correctly.', async () => { const numberOfUpdates = 10; const ops = await createUpdateSequence(didUniqueSuffix, createOp, numberOfUpdates, signingPrivateKey); await operationStore.insertOrReplace(ops); const didState = await resolver.resolve(didUniqueSuffix); expect(didState).toBeDefined(); validateDocumentAfterUpdates(didState!.document, numberOfUpdates); const deactivateOperationData = await OperationGenerator.createDeactivateOperation(didUniqueSuffix, recoveryPrivateKey); const anchoredDeactivateOperation = OperationGenerator.createAnchoredOperationModelFromOperationModel( deactivateOperationData.deactivateOperation, numberOfUpdates + 1, numberOfUpdates + 1, 0); await operationStore.insertOrReplace([anchoredDeactivateOperation]); const deactivatedDidState = await resolver.resolve(didUniqueSuffix); expect(deactivatedDidState).toBeDefined(); expect(deactivatedDidState!.nextRecoveryCommitmentHash).toBeUndefined(); expect(deactivatedDidState!.nextUpdateCommitmentHash).toBeUndefined(); expect(deactivatedDidState!.lastOperationTransactionNumber).toEqual(numberOfUpdates + 1); }); it('should ignore a deactivate operation of a non-existent did', async () => { const deactivateOperationData = await OperationGenerator.createDeactivateOperation(didUniqueSuffix, recoveryPrivateKey); const anchoredDeactivateOperation = OperationGenerator.createAnchoredOperationModelFromOperationModel(deactivateOperationData.deactivateOperation, 1, 1, 0); await operationStore.insertOrReplace([anchoredDeactivateOperation]); const didDocumentAfterDeactivate = await resolver.resolve(didUniqueSuffix); expect(didDocumentAfterDeactivate).toBeUndefined(); }); it('should ignore a deactivate operation with invalid signature', async () => { await operationStore.insertOrReplace([createOp]); // Intentionally signing with signing (wrong) key. const deactivateOperationData = await OperationGenerator.createDeactivateOperation(didUniqueSuffix, signingPrivateKey); const anchoredDeactivateOperation = OperationGenerator.createAnchoredOperationModelFromOperationModel(deactivateOperationData.deactivateOperation, 1, 1, 0); await operationStore.insertOrReplace([anchoredDeactivateOperation]); const didState = await resolver.resolve(didUniqueSuffix); expect(didState).toBeDefined(); const document = didState!.document; const signingKey = Document.getPublicKey(document, signingKeyId); expect(signingKey).toBeDefined(); }); it('should ignore updates to DID that is not created', async () => { const numberOfUpdates = 10; const ops = await createUpdateSequence(didUniqueSuffix, createOp, numberOfUpdates, signingPrivateKey); // elide i = 0, the create operation for (let i = 1; i < ops.length; ++i) { await operationStore.insertOrReplace([ops[i]]); } const didDocument = await resolver.resolve(didUniqueSuffix); expect(didDocument).toBeUndefined(); }); it('should ignore update operation with the incorrect updateKey', async () => { await operationStore.insertOrReplace([createOp]); const [anyPublicKey] = await OperationGenerator.generateKeyPair(`additionalKey`); const [invalidKey] = await OperationGenerator.generateKeyPair('invalidKey'); const updateOperationRequest = await OperationGenerator.createUpdateOperationRequestForAddingAKey( didUniqueSuffix, invalidKey.publicKeyJwk, signingPrivateKey, anyPublicKey, OperationGenerator.generateRandomHash() ); // Generate operation with an invalid key const updateOperationBuffer = Buffer.from(JSON.stringify(updateOperationRequest)); const updateOperation = await UpdateOperation.parse(updateOperationBuffer); const anchoredUpdateOperation = OperationGenerator.createAnchoredOperationModelFromOperationModel(updateOperation, 1, 1, 0); await operationStore.insertOrReplace([anchoredUpdateOperation]); const didState = await resolver.resolve(didUniqueSuffix); expect(didState).toBeDefined(); const document = didState!.document; const newKey = Document.getPublicKey(document, 'additionalKey'); expect(newKey).not.toBeDefined(); // if update above went through, new key would be added. }); it('should ignore update operation with an invalid signature', async () => { await operationStore.insertOrReplace([createOp]); const [, anyIncorrectSigningPrivateKey] = await OperationGenerator.generateKeyPair('key1'); const [anyPublicKey] = await OperationGenerator.generateKeyPair(`additionalKey`); const updateOperationRequest = await OperationGenerator.createUpdateOperationRequestForAddingAKey( didUniqueSuffix, signingPublicKey.publicKeyJwk, anyIncorrectSigningPrivateKey, anyPublicKey, OperationGenerator.generateRandomHash() ); const updateOperationBuffer = Buffer.from(JSON.stringify(updateOperationRequest)); const updateOperation = await UpdateOperation.parse(updateOperationBuffer); const anchoredUpdateOperation = OperationGenerator.createAnchoredOperationModelFromOperationModel(updateOperation, 1, 1, 0); await operationStore.insertOrReplace([anchoredUpdateOperation]); const didState = await resolver.resolve(didUniqueSuffix); expect(didState).toBeDefined(); const document = didState!.document; const newKey = Document.getPublicKey(document, 'new-key'); expect(newKey).not.toBeDefined(); // if update above went through, new key would be added. }); it('should resolve as undefined if all operation of a DID is rolled back.', async () => { const numberOfUpdates = 10; const ops = await createUpdateSequence(didUniqueSuffix, createOp, numberOfUpdates, signingPrivateKey); await operationStore.insertOrReplace(ops); const didState = await resolver.resolve(didUniqueSuffix); expect(didState).toBeDefined(); validateDocumentAfterUpdates(didState!.document, numberOfUpdates); // rollback await operationStore.delete(); const didDocumentAfterRollback = await resolver.resolve(didUniqueSuffix); expect(didDocumentAfterRollback).toBeUndefined(); }); describe('apply()', () => { let recoveryPublicKey: JwkEs256k; let recoveryPrivateKey: JwkEs256k; let signingPublicKey: PublicKeyModel; let signingPrivateKey: JwkEs256k; let namedAnchoredCreateOperationModel: AnchoredOperationModel; let didState: DidState | undefined; let nextRecoveryCommitmentHash: string; let verifyEncodedMultihashForContentSpy: jasmine.Spy; // Create a DID before each test. beforeEach(async () => { verifyEncodedMultihashForContentSpy = spyOn(Multihash, 'verifyEncodedMultihashForContent'); verifyEncodedMultihashForContentSpy.and.callThrough(); // MUST reset the DID state back to `undefined` for each test. didState = undefined; // Generate key(s) and service(s) to be included in the DID Document. [recoveryPublicKey, recoveryPrivateKey] = await Jwk.generateEs256kKeyPair(); [signingPublicKey, signingPrivateKey] = await OperationGenerator.generateKeyPair('signingKey'); nextRecoveryCommitmentHash = Multihash.canonicalizeThenDoubleHashThenEncode(recoveryPublicKey); const services = OperationGenerator.generateServices(['dummyHubUri']); // Create the initial create operation. const createOperationBuffer = await OperationGenerator.generateCreateOperationBuffer( recoveryPublicKey, signingPublicKey, services ); const createOperation = await CreateOperation.parse(createOperationBuffer); namedAnchoredCreateOperationModel = { type: OperationType.Create, didUniqueSuffix: createOperation.didUniqueSuffix, operationBuffer: createOperationBuffer, transactionNumber: 1, transactionTime: 1, operationIndex: 1 }; // Apply the initial create operation. didState = await operationProcessor.apply(namedAnchoredCreateOperationModel, didState); // Sanity check the create operation. expect(didState).toBeDefined(); expect(didState!.document).toBeDefined(); }); it('should return `undefined` if operation of unknown type is given.', async () => { // Create a non-create operation. const anyDid = OperationGenerator.generateRandomHash(); const [, anyRecoveryPrivateKey] = await OperationGenerator.generateKeyPair('anyRecoveryKey'); const deactivateOperationData = await OperationGenerator.createDeactivateOperation(anyDid, anyRecoveryPrivateKey); const anchoredDeactivateOperation = OperationGenerator.createAnchoredOperationModelFromOperationModel(deactivateOperationData.deactivateOperation, 1, 1, 1); const newDidState = await operationProcessor.apply(anchoredDeactivateOperation, undefined); expect(newDidState).toBeUndefined(); }); it('should throw if operation of unknown type is given.', async () => { const createOperationData = await OperationGenerator.generateAnchoredCreateOperation({ transactionTime: 2, transactionNumber: 2, operationIndex: 2 }); const anchoredOperationModel = createOperationData.anchoredOperationModel; (anchoredOperationModel.type as any) = 'UnknownType'; // Intentionally setting type to be an unknown type. await expectAsync(operationProcessor.apply(createOperationData.anchoredOperationModel, didState)) .toBeRejectedWith(new SidetreeError(ErrorCode.OperationProcessorUnknownOperationType)); }); it('should continue if logging of an invalid operation application throws for unexpected reason', async () => { const createOperationData = await OperationGenerator.generateAnchoredCreateOperation({ transactionTime: 2, transactionNumber: 2, operationIndex: 2 }); // Simulating the logging of invalid operation throws an error. spyOn(Logger, 'info').and.callFake( (data: string) => { if (data.startsWith('Ignored invalid operation')) { throw new Error('An error message.'); } } ); const newDidState = await operationProcessor.apply(createOperationData.anchoredOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toBeDefined(); expect(newDidState!.nextRecoveryCommitmentHash).toEqual(nextRecoveryCommitmentHash); }); describe('applyCreateOperation()', () => { it('should not apply the create operation if a DID state already exists.', async () => { const createOperationData = await OperationGenerator.generateAnchoredCreateOperation({ transactionTime: 2, transactionNumber: 2, operationIndex: 2 }); const newDidState = await operationProcessor.apply(createOperationData.anchoredOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toBeDefined(); expect(newDidState!.nextRecoveryCommitmentHash).toEqual(nextRecoveryCommitmentHash); }); it('should apply the create operation with { } as document if encoded data and suffix data do not match', async () => { verifyEncodedMultihashForContentSpy.and.returnValue(false); const createOperationData = await OperationGenerator.generateAnchoredCreateOperation({ transactionTime: 1, transactionNumber: 1, operationIndex: 1 }); const newDidState = await operationProcessor.apply(createOperationData.anchoredOperationModel, undefined); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toEqual({ }); expect(newDidState!.nextRecoveryCommitmentHash).toEqual(createOperationData.operationRequest.suffixData.recoveryCommitment); }); it('should apply the create operation with { } as document if delta does not exist', async () => { const createOperationData = await OperationGenerator.generateAnchoredCreateOperation({ transactionTime: 1, transactionNumber: 1, operationIndex: 1 }); spyOn(CreateOperation, 'parse').and.returnValue({ delta: undefined, suffixData: { recoveryCommitment: 'commitment' } } as any); // delta is undefined const newDidState = await operationProcessor.apply(createOperationData.anchoredOperationModel, undefined); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toEqual({ }); expect(newDidState!.nextRecoveryCommitmentHash).toEqual('commitment'); }); it('should apply the create operation with { } and advance update commitment as document if delta cannot be applied', async () => { const createOperationData = await OperationGenerator.generateAnchoredCreateOperation({ transactionTime: 1, transactionNumber: 1, operationIndex: 1 }); spyOn(DocumentComposer, 'applyPatches').and.throwError('Expected test error'); const newDidState = await operationProcessor.apply(createOperationData.anchoredOperationModel, undefined); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toEqual({ }); expect(newDidState!.nextRecoveryCommitmentHash).toEqual(createOperationData.operationRequest.suffixData.recoveryCommitment); // advance update commitment expect(newDidState!.nextUpdateCommitmentHash).toEqual(createOperationData.operationRequest.delta.updateCommitment); }); it('should apply the create operation with { } and undefined update commitment as document if delta is undefined', async () => { const createOperationData = await OperationGenerator.generateAnchoredCreateOperation({ transactionTime: 1, transactionNumber: 1, operationIndex: 1 }); // modify parse to make delta undefined const parsedOperation = await CreateOperation.parse(createOperationData.anchoredOperationModel.operationBuffer); (parsedOperation.delta as any) = undefined; spyOn(CreateOperation, 'parse').and.returnValue(Promise.resolve(parsedOperation)); const newDidState = await operationProcessor.apply(createOperationData.anchoredOperationModel, undefined); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toEqual({ }); expect(newDidState!.nextRecoveryCommitmentHash).toEqual(createOperationData.operationRequest.suffixData.recoveryCommitment); // update commitment is undefined expect(newDidState!.nextUpdateCommitmentHash).toBeUndefined(); }); }); describe('applyUpdateOperation()', () => { it('should not apply update operation if update key and commitment are not pairs.', async () => { // Create an update using the create operation generated in `beforeEach()`. const [additionalKey] = await OperationGenerator.generateKeyPair(`new-key1`); const updateOperationRequest = await OperationGenerator.createUpdateOperationRequestForAddingAKey( didUniqueSuffix, (await Jwk.generateEs256kKeyPair())[0], // this is a random bad key signingPrivateKey, additionalKey, OperationGenerator.generateRandomHash() ); const operationBuffer = Buffer.from(JSON.stringify(updateOperationRequest)); const anchoredUpdateOperationModel: AnchoredOperationModel = { type: OperationType.Update, didUniqueSuffix, operationBuffer, transactionTime: 2, transactionNumber: 2, operationIndex: 2 }; const newDidState = await operationProcessor.apply(anchoredUpdateOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toBeDefined(); // The count of public keys should remain 1, not 2. expect(newDidState!.document.publicKeys.length).toEqual(1); }); it('should not apply update operation if signature is invalid.', async () => { // Create an update using the create operation generated in `beforeEach()`. const [additionalKey] = await OperationGenerator.generateKeyPair(`new-key1`); const updateOperationRequest = await OperationGenerator.createUpdateOperationRequestForAddingAKey( didUniqueSuffix, signingPublicKey.publicKeyJwk, recoveryPrivateKey, // NOTE: Using recovery private key to generate an invalid signature. additionalKey, OperationGenerator.generateRandomHash() ); const operationBuffer = Buffer.from(JSON.stringify(updateOperationRequest)); const anchoredUpdateOperationModel: AnchoredOperationModel = { type: OperationType.Update, didUniqueSuffix, operationBuffer, transactionTime: 2, transactionNumber: 2, operationIndex: 2 }; const newDidState = await operationProcessor.apply(anchoredUpdateOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toBeDefined(); // The count of public signing keys should remain 1, not 2. expect(newDidState!.document.publicKeys.length).toEqual(1); }); it('should not apply update operation if updateKey is invalid', async () => { // Create an update using the create operation generated in `beforeEach()`. const [additionalKey] = await OperationGenerator.generateKeyPair(`new-key1`); const [invalidUpdateKey] = await OperationGenerator.generateKeyPair('invalid'); const updateOperationRequest = await OperationGenerator.createUpdateOperationRequestForAddingAKey( didUniqueSuffix, invalidUpdateKey.publicKeyJwk, signingPrivateKey, additionalKey, OperationGenerator.generateRandomHash() ); const operationBuffer = Buffer.from(JSON.stringify(updateOperationRequest)); const anchoredUpdateOperationModel: AnchoredOperationModel = { type: OperationType.Update, didUniqueSuffix, operationBuffer, transactionTime: 2, transactionNumber: 2, operationIndex: 2 }; const newDidState = await operationProcessor.apply(anchoredUpdateOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toBeDefined(); // The count of public keys should remain 1, not 2. expect(newDidState!.document.publicKeys.length).toEqual(1); }); it('should not apply update operation if delta is undefined', async () => { // Create an update using the create operation generated in `beforeEach()`. const [additionalKey] = await OperationGenerator.generateKeyPair(`new-key1`); const updateOperationRequest = await OperationGenerator.createUpdateOperationRequestForAddingAKey( didUniqueSuffix, signingPublicKey.publicKeyJwk, signingPrivateKey, additionalKey, OperationGenerator.generateRandomHash() ); const operationBuffer = Buffer.from(JSON.stringify(updateOperationRequest)); const anchoredUpdateOperationModel: AnchoredOperationModel = { type: OperationType.Update, didUniqueSuffix, operationBuffer, transactionTime: 2, transactionNumber: 2, operationIndex: 2 }; const modifiedUpdateOperation = await UpdateOperation.parse(anchoredUpdateOperationModel.operationBuffer); // set to undefined to satisfy the test condition of it being undefined (modifiedUpdateOperation.delta as any) = undefined; // mock the function to return the modified result spyOn(UpdateOperation, 'parse').and.returnValue(Promise.resolve(modifiedUpdateOperation)); const newDidState = await operationProcessor.apply(anchoredUpdateOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toBeDefined(); // The count of public keys should remain 1, not 2. expect(newDidState!.document.publicKeys.length).toEqual(1); }); it('should not apply update operation if delta does not match delta hash', async () => { // Create an update using the create operation generated in `beforeEach()`. const [additionalKey] = await OperationGenerator.generateKeyPair(`new-key1`); const updateOperationRequest = await OperationGenerator.createUpdateOperationRequestForAddingAKey( didUniqueSuffix, signingPublicKey.publicKeyJwk, signingPrivateKey, additionalKey, OperationGenerator.generateRandomHash() ); const operationBuffer = Buffer.from(JSON.stringify(updateOperationRequest)); const anchoredUpdateOperationModel: AnchoredOperationModel = { type: OperationType.Update, didUniqueSuffix, operationBuffer, transactionTime: 2, transactionNumber: 2, operationIndex: 2 }; const modifiedUpdateOperation = await UpdateOperation.parse(anchoredUpdateOperationModel.operationBuffer); // set to empty object to satisfy the test condition of not matching delta hash (modifiedUpdateOperation.delta as any) = {}; // mock the function to return the modified result spyOn(UpdateOperation, 'parse').and.returnValue(Promise.resolve(modifiedUpdateOperation)); const newDidState = await operationProcessor.apply(anchoredUpdateOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toBeDefined(); // The count of public keys should remain 1, not 2. expect(newDidState!.document.publicKeys.length).toEqual(1); }); it('should treat update a success and increment update commitment if any patch failed to apply.', async () => { // Create an update using the create operation generated in `beforeEach()`. const [additionalKey] = await OperationGenerator.generateKeyPair(`new-key1`); const nextUpdateCommitment = OperationGenerator.generateRandomHash(); const updateOperationRequest = await OperationGenerator.createUpdateOperationRequestForAddingAKey( didUniqueSuffix, signingPublicKey.publicKeyJwk, signingPrivateKey, additionalKey, nextUpdateCommitment ); const operationBuffer = Buffer.from(JSON.stringify(updateOperationRequest)); const anchoredUpdateOperationModel: AnchoredOperationModel = { type: OperationType.Update, didUniqueSuffix, operationBuffer, transactionTime: 2, transactionNumber: 2, operationIndex: 2 }; // Intentionally modifying the document before failing update patches to test original document is not modified. spyOn(DocumentComposer, 'applyPatches').and.callFake((document, _patch) => { document.publicKeys = []; throw new Error('any error'); }); // The expected outcome of patch application failure (but all integrity checks including schema checks are passed )is: // 1. Operation is considered successful. // 2. Update commitment is updated/incremented. // 3. DID document state remains the unchanged (same as prior to the patches being applied). const deepCopyOriginalDocument = JsObject.deepCopyObject(didState!.document); const newDidState = await operationProcessor.apply(anchoredUpdateOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(2); expect(newDidState!.nextUpdateCommitmentHash).toEqual(nextUpdateCommitment); // Expect the DID document to be unchanged. expect(newDidState!.document).toEqual(deepCopyOriginalDocument); }); }); describe('applyRecoverOperation()', () => { it('should not apply if recovery key hash is invalid.', async () => { const operationData = await OperationGenerator.generateRecoverOperation({ didUniqueSuffix, recoveryPrivateKey: signingPrivateKey // Intentionally an incorrect recovery key. }); const anchoredRecoverOperationModel = OperationGenerator.createAnchoredOperationModelFromOperationModel(operationData.recoverOperation, 2, 2, 2); const newDidState = await operationProcessor.apply(anchoredRecoverOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); // Verify that the recovery commitment is still the same as prior to the application of the recover operation. expect(newDidState!.nextRecoveryCommitmentHash).toEqual(nextRecoveryCommitmentHash); }); it('should not apply if recovery signature is invalid.', async () => { const operationData = await OperationGenerator.generateRecoverOperation({ didUniqueSuffix, recoveryPrivateKey }); const anchoredRecoverOperationModel = OperationGenerator.createAnchoredOperationModelFromOperationModel(operationData.recoverOperation, 2, 2, 2); const modifiedResult = await RecoverOperation.parse(anchoredRecoverOperationModel.operationBuffer); // modify the result to make signature validation fail spyOn(modifiedResult.signedDataJws, 'verifySignature').and.returnValue(Promise.resolve(false)); // mock updateOperation parse to return the modified result spyOn(RecoverOperation, 'parse').and.returnValue(Promise.resolve(modifiedResult)); const newDidState = await operationProcessor.apply(anchoredRecoverOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(1); // Verify that the recovery commitment is still the same as prior to the application of the recover operation. expect(newDidState!.nextRecoveryCommitmentHash).toEqual(nextRecoveryCommitmentHash); }); it('should apply successfully with resultant document being { } and advanced commit reveal when document composer fails to apply patches.', async () => { const document = { }; const [anyNewRecoveryPublicKey] = await Jwk.generateEs256kKeyPair(); const newUpdateCommitment = OperationGenerator.generateRandomHash(); const recoverOperationRequest = await OperationGenerator.createRecoverOperationRequest( didUniqueSuffix, recoveryPrivateKey, anyNewRecoveryPublicKey, newUpdateCommitment, document ); const recoverOperation = await RecoverOperation.parse(Buffer.from(JSON.stringify(recoverOperationRequest))); const anchoredRecoverOperationModel = OperationGenerator.createAnchoredOperationModelFromOperationModel(recoverOperation, 2, 2, 2); spyOn(DocumentComposer, 'applyPatches').and.throwError('Expected test error'); const newDidState = await operationProcessor.apply(anchoredRecoverOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(2); expect(newDidState!.document).toEqual({ }); const expectedNewRecoveryCommitment = Multihash.canonicalizeThenDoubleHashThenEncode(anyNewRecoveryPublicKey); expect(newDidState!.nextRecoveryCommitmentHash).toEqual(expectedNewRecoveryCommitment); expect(newDidState!.nextUpdateCommitmentHash).toEqual(newUpdateCommitment); }); it('should still apply successfully with resultant document being { } if new document is in some unexpected format.', async () => { const document = 'unexpected document format'; const [anyNewRecoveryPublicKey] = await Jwk.generateEs256kKeyPair(); const unusedNextUpdateCommitment = OperationGenerator.generateRandomHash(); const recoverOperationRequest = await OperationGenerator.createRecoverOperationRequest( didUniqueSuffix, recoveryPrivateKey, anyNewRecoveryPublicKey, unusedNextUpdateCommitment, document ); const recoverOperation = await RecoverOperation.parse(Buffer.from(JSON.stringify(recoverOperationRequest))); const anchoredRecoverOperationModel = OperationGenerator.createAnchoredOperationModelFromOperationModel(recoverOperation, 2, 2, 2); const newDidState = await operationProcessor.apply(anchoredRecoverOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(2); expect(newDidState!.document).toEqual({ }); const expectedNewRecoveryCommitment = Multihash.canonicalizeThenDoubleHashThenEncode(anyNewRecoveryPublicKey); expect(newDidState!.nextRecoveryCommitmentHash).toEqual(expectedNewRecoveryCommitment); }); it('should still apply successfully with resultant document being { } if delta hash mismatch.', async () => { const document = { publicKeys: [] }; const [anyNewRecoveryPublicKey] = await Jwk.generateEs256kKeyPair(); const unusedNextUpdateCommitment = OperationGenerator.generateRandomHash(); const recoverOperationRequest = await OperationGenerator.createRecoverOperationRequest( didUniqueSuffix, recoveryPrivateKey, anyNewRecoveryPublicKey, unusedNextUpdateCommitment, document ); const recoverOperation = await RecoverOperation.parse(Buffer.from(JSON.stringify(recoverOperationRequest))); const anchoredRecoverOperationModel = OperationGenerator.createAnchoredOperationModelFromOperationModel(recoverOperation, 2, 2, 2); verifyEncodedMultihashForContentSpy.and.callFake((_content, expectedHash) => { if (expectedHash === recoverOperation.signedData.deltaHash) { // Intentionally failing recovery delta operation hash check. return false; } else { return true; } }); const newDidState = await operationProcessor.apply(anchoredRecoverOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(2); expect(newDidState!.document).toEqual({ }); const expectedNewRecoveryCommitment = Multihash.canonicalizeThenDoubleHashThenEncode(anyNewRecoveryPublicKey); expect(newDidState!.nextRecoveryCommitmentHash).toEqual(expectedNewRecoveryCommitment); }); it('should still apply successfully with resultant document being { } and update commitment not advanced if delta is undefined', async () => { const document = { publicKeys: [] }; const [anyNewRecoveryPublicKey] = await Jwk.generateEs256kKeyPair(); const unusedNextUpdateCommitment = OperationGenerator.generateRandomHash(); const recoverOperationRequest = await OperationGenerator.createRecoverOperationRequest( didUniqueSuffix, recoveryPrivateKey, anyNewRecoveryPublicKey, unusedNextUpdateCommitment, document ); const recoverOperation = await RecoverOperation.parse(Buffer.from(JSON.stringify(recoverOperationRequest))); const anchoredRecoverOperationModel = OperationGenerator.createAnchoredOperationModelFromOperationModel(recoverOperation, 2, 2, 2); // mock to make delta undefined const parsedRecoveryOperation = await RecoverOperation.parse(anchoredRecoverOperationModel.operationBuffer); (parsedRecoveryOperation.delta as any) = undefined; spyOn(RecoverOperation, 'parse').and.returnValue(Promise.resolve(parsedRecoveryOperation)); const newDidState = await operationProcessor.apply(anchoredRecoverOperationModel, didState); expect(newDidState!.lastOperationTransactionNumber).toEqual(2); expect(newDidState!.document).toEqual({ }); const expectedNewRecoveryCommitment = Multihash.canonicalizeThenDoubleHashThenEncode(anyNewRecoveryPublicKey); expect(newDidState!.nextRecoveryCommitmentHash).toEqual(expectedNewRecoveryCommitment); expect(newDidState!.nextUpdateCommitmentHash).toBeUndefined(); }); }); describe('applyDeactivateOperation()', () => { it('should not apply if calculated recovery key hash is invalid.', async () => { // Creating and signing a deactivate operation using an invalid/incorrect recovery key. const [, anyIncorrectRecoveryPrivateKey] = await Jwk.generateEs256kKeyPair(); const deactivateOperationData = await OperationGenerator.createDeactivateOperation(didUniqueSuffix, anyIncorrectRecoveryPrivateKey); const deactivateOperation = await DeactivateOperation.parse(deactivateOperationData.operationBuffer); const anchoredDeactivateOperationModel = OperationGenerator.createAnchoredOperationModelFromOperationModel(deactivateOperation, 2, 2, 2); const newDidState = await operationProcessor.apply(anchoredDeactivateOperationModel, didState); // Expecting resulting DID state to still be the same as prior to attempting to apply the invalid deactivate operation. expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toBeDefined(); expect(newDidState!.document.publicKeys.length).toEqual(1); expect(newDidState!.nextUpdateCommitmentHash).toEqual(didState!.nextUpdateCommitmentHash); }); it('should not apply if signature is invalid.', async () => { // Creating and signing a deactivate operation using an invalid/incorrect recovery key. const deactivateOperationData = await OperationGenerator.createDeactivateOperation(didUniqueSuffix, recoveryPrivateKey); const deactivateOperation = await DeactivateOperation.parse(deactivateOperationData.operationBuffer); const anchoredDeactivateOperationModel = OperationGenerator.createAnchoredOperationModelFromOperationModel(deactivateOperation, 2, 2, 2); // Mock to make signature validation fail const modifiedResult = await DeactivateOperation.parse(anchoredDeactivateOperationModel.operationBuffer); spyOn(modifiedResult.signedDataJws, 'verifySignature').and.returnValue(Promise.resolve(false)); spyOn(DeactivateOperation, 'parse').and.returnValue(Promise.resolve(modifiedResult)); const newDidState = await operationProcessor.apply(anchoredDeactivateOperationModel, didState); // Expecting resulting DID state to still be the same as prior to attempting to apply the invalid deactivate operation. expect(newDidState!.lastOperationTransactionNumber).toEqual(1); expect(newDidState!.document).toBeDefined(); expect(newDidState!.document.publicKeys.length).toEqual(1); expect(newDidState!.nextUpdateCommitmentHash).toEqual(didState!.nextUpdateCommitmentHash); }); }); }); describe('getMultihashRevealValue()', () => { it('should throw if a create operation is given.', async () => { const createOperationData = await OperationGenerator.generateAnchoredCreateOperation({ transactionTime: 1, transactionNumber: 1, operationIndex: 1 }); await expectAsync(operationProcessor.getMultihashRevealValue(createOperationData.anchoredOperationModel)) .toBeRejectedWith(new SidetreeError(ErrorCode.OperationProcessorCreateOperationDoesNotHaveRevealValue)); }); }); });
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class WorkDocs extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: WorkDocs.Types.ClientConfiguration) config: Config & WorkDocs.Types.ClientConfiguration; /** * Aborts the upload of the specified document version that was previously initiated by InitiateDocumentVersionUpload. The client should make this call only when it no longer intends to upload the document version, or fails to do so. */ abortDocumentVersionUpload(params: WorkDocs.Types.AbortDocumentVersionUploadRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Aborts the upload of the specified document version that was previously initiated by InitiateDocumentVersionUpload. The client should make this call only when it no longer intends to upload the document version, or fails to do so. */ abortDocumentVersionUpload(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Activates the specified user. Only active users can access Amazon WorkDocs. */ activateUser(params: WorkDocs.Types.ActivateUserRequest, callback?: (err: AWSError, data: WorkDocs.Types.ActivateUserResponse) => void): Request<WorkDocs.Types.ActivateUserResponse, AWSError>; /** * Activates the specified user. Only active users can access Amazon WorkDocs. */ activateUser(callback?: (err: AWSError, data: WorkDocs.Types.ActivateUserResponse) => void): Request<WorkDocs.Types.ActivateUserResponse, AWSError>; /** * Creates a set of permissions for the specified folder or document. The resource permissions are overwritten if the principals already have different permissions. */ addResourcePermissions(params: WorkDocs.Types.AddResourcePermissionsRequest, callback?: (err: AWSError, data: WorkDocs.Types.AddResourcePermissionsResponse) => void): Request<WorkDocs.Types.AddResourcePermissionsResponse, AWSError>; /** * Creates a set of permissions for the specified folder or document. The resource permissions are overwritten if the principals already have different permissions. */ addResourcePermissions(callback?: (err: AWSError, data: WorkDocs.Types.AddResourcePermissionsResponse) => void): Request<WorkDocs.Types.AddResourcePermissionsResponse, AWSError>; /** * Adds a new comment to the specified document version. */ createComment(params: WorkDocs.Types.CreateCommentRequest, callback?: (err: AWSError, data: WorkDocs.Types.CreateCommentResponse) => void): Request<WorkDocs.Types.CreateCommentResponse, AWSError>; /** * Adds a new comment to the specified document version. */ createComment(callback?: (err: AWSError, data: WorkDocs.Types.CreateCommentResponse) => void): Request<WorkDocs.Types.CreateCommentResponse, AWSError>; /** * Adds one or more custom properties to the specified resource (a folder, document, or version). */ createCustomMetadata(params: WorkDocs.Types.CreateCustomMetadataRequest, callback?: (err: AWSError, data: WorkDocs.Types.CreateCustomMetadataResponse) => void): Request<WorkDocs.Types.CreateCustomMetadataResponse, AWSError>; /** * Adds one or more custom properties to the specified resource (a folder, document, or version). */ createCustomMetadata(callback?: (err: AWSError, data: WorkDocs.Types.CreateCustomMetadataResponse) => void): Request<WorkDocs.Types.CreateCustomMetadataResponse, AWSError>; /** * Creates a folder with the specified name and parent folder. */ createFolder(params: WorkDocs.Types.CreateFolderRequest, callback?: (err: AWSError, data: WorkDocs.Types.CreateFolderResponse) => void): Request<WorkDocs.Types.CreateFolderResponse, AWSError>; /** * Creates a folder with the specified name and parent folder. */ createFolder(callback?: (err: AWSError, data: WorkDocs.Types.CreateFolderResponse) => void): Request<WorkDocs.Types.CreateFolderResponse, AWSError>; /** * Adds the specified list of labels to the given resource (a document or folder) */ createLabels(params: WorkDocs.Types.CreateLabelsRequest, callback?: (err: AWSError, data: WorkDocs.Types.CreateLabelsResponse) => void): Request<WorkDocs.Types.CreateLabelsResponse, AWSError>; /** * Adds the specified list of labels to the given resource (a document or folder) */ createLabels(callback?: (err: AWSError, data: WorkDocs.Types.CreateLabelsResponse) => void): Request<WorkDocs.Types.CreateLabelsResponse, AWSError>; /** * Configure Amazon WorkDocs to use Amazon SNS notifications. The endpoint receives a confirmation message, and must confirm the subscription. For more information, see Subscribe to Notifications in the Amazon WorkDocs Developer Guide. */ createNotificationSubscription(params: WorkDocs.Types.CreateNotificationSubscriptionRequest, callback?: (err: AWSError, data: WorkDocs.Types.CreateNotificationSubscriptionResponse) => void): Request<WorkDocs.Types.CreateNotificationSubscriptionResponse, AWSError>; /** * Configure Amazon WorkDocs to use Amazon SNS notifications. The endpoint receives a confirmation message, and must confirm the subscription. For more information, see Subscribe to Notifications in the Amazon WorkDocs Developer Guide. */ createNotificationSubscription(callback?: (err: AWSError, data: WorkDocs.Types.CreateNotificationSubscriptionResponse) => void): Request<WorkDocs.Types.CreateNotificationSubscriptionResponse, AWSError>; /** * Creates a user in a Simple AD or Microsoft AD directory. The status of a newly created user is "ACTIVE". New users can access Amazon WorkDocs. */ createUser(params: WorkDocs.Types.CreateUserRequest, callback?: (err: AWSError, data: WorkDocs.Types.CreateUserResponse) => void): Request<WorkDocs.Types.CreateUserResponse, AWSError>; /** * Creates a user in a Simple AD or Microsoft AD directory. The status of a newly created user is "ACTIVE". New users can access Amazon WorkDocs. */ createUser(callback?: (err: AWSError, data: WorkDocs.Types.CreateUserResponse) => void): Request<WorkDocs.Types.CreateUserResponse, AWSError>; /** * Deactivates the specified user, which revokes the user's access to Amazon WorkDocs. */ deactivateUser(params: WorkDocs.Types.DeactivateUserRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deactivates the specified user, which revokes the user's access to Amazon WorkDocs. */ deactivateUser(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified comment from the document version. */ deleteComment(params: WorkDocs.Types.DeleteCommentRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified comment from the document version. */ deleteComment(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes custom metadata from the specified resource. */ deleteCustomMetadata(params: WorkDocs.Types.DeleteCustomMetadataRequest, callback?: (err: AWSError, data: WorkDocs.Types.DeleteCustomMetadataResponse) => void): Request<WorkDocs.Types.DeleteCustomMetadataResponse, AWSError>; /** * Deletes custom metadata from the specified resource. */ deleteCustomMetadata(callback?: (err: AWSError, data: WorkDocs.Types.DeleteCustomMetadataResponse) => void): Request<WorkDocs.Types.DeleteCustomMetadataResponse, AWSError>; /** * Permanently deletes the specified document and its associated metadata. */ deleteDocument(params: WorkDocs.Types.DeleteDocumentRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Permanently deletes the specified document and its associated metadata. */ deleteDocument(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Permanently deletes the specified folder and its contents. */ deleteFolder(params: WorkDocs.Types.DeleteFolderRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Permanently deletes the specified folder and its contents. */ deleteFolder(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the contents of the specified folder. */ deleteFolderContents(params: WorkDocs.Types.DeleteFolderContentsRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the contents of the specified folder. */ deleteFolderContents(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified list of labels from a resource. */ deleteLabels(params: WorkDocs.Types.DeleteLabelsRequest, callback?: (err: AWSError, data: WorkDocs.Types.DeleteLabelsResponse) => void): Request<WorkDocs.Types.DeleteLabelsResponse, AWSError>; /** * Deletes the specified list of labels from a resource. */ deleteLabels(callback?: (err: AWSError, data: WorkDocs.Types.DeleteLabelsResponse) => void): Request<WorkDocs.Types.DeleteLabelsResponse, AWSError>; /** * Deletes the specified subscription from the specified organization. */ deleteNotificationSubscription(params: WorkDocs.Types.DeleteNotificationSubscriptionRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified subscription from the specified organization. */ deleteNotificationSubscription(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified user from a Simple AD or Microsoft AD directory. */ deleteUser(params: WorkDocs.Types.DeleteUserRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes the specified user from a Simple AD or Microsoft AD directory. */ deleteUser(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Describes the user activities in a specified time period. */ describeActivities(params: WorkDocs.Types.DescribeActivitiesRequest, callback?: (err: AWSError, data: WorkDocs.Types.DescribeActivitiesResponse) => void): Request<WorkDocs.Types.DescribeActivitiesResponse, AWSError>; /** * Describes the user activities in a specified time period. */ describeActivities(callback?: (err: AWSError, data: WorkDocs.Types.DescribeActivitiesResponse) => void): Request<WorkDocs.Types.DescribeActivitiesResponse, AWSError>; /** * List all the comments for the specified document version. */ describeComments(params: WorkDocs.Types.DescribeCommentsRequest, callback?: (err: AWSError, data: WorkDocs.Types.DescribeCommentsResponse) => void): Request<WorkDocs.Types.DescribeCommentsResponse, AWSError>; /** * List all the comments for the specified document version. */ describeComments(callback?: (err: AWSError, data: WorkDocs.Types.DescribeCommentsResponse) => void): Request<WorkDocs.Types.DescribeCommentsResponse, AWSError>; /** * Retrieves the document versions for the specified document. By default, only active versions are returned. */ describeDocumentVersions(params: WorkDocs.Types.DescribeDocumentVersionsRequest, callback?: (err: AWSError, data: WorkDocs.Types.DescribeDocumentVersionsResponse) => void): Request<WorkDocs.Types.DescribeDocumentVersionsResponse, AWSError>; /** * Retrieves the document versions for the specified document. By default, only active versions are returned. */ describeDocumentVersions(callback?: (err: AWSError, data: WorkDocs.Types.DescribeDocumentVersionsResponse) => void): Request<WorkDocs.Types.DescribeDocumentVersionsResponse, AWSError>; /** * Describes the contents of the specified folder, including its documents and subfolders. By default, Amazon WorkDocs returns the first 100 active document and folder metadata items. If there are more results, the response includes a marker that you can use to request the next set of results. You can also request initialized documents. */ describeFolderContents(params: WorkDocs.Types.DescribeFolderContentsRequest, callback?: (err: AWSError, data: WorkDocs.Types.DescribeFolderContentsResponse) => void): Request<WorkDocs.Types.DescribeFolderContentsResponse, AWSError>; /** * Describes the contents of the specified folder, including its documents and subfolders. By default, Amazon WorkDocs returns the first 100 active document and folder metadata items. If there are more results, the response includes a marker that you can use to request the next set of results. You can also request initialized documents. */ describeFolderContents(callback?: (err: AWSError, data: WorkDocs.Types.DescribeFolderContentsResponse) => void): Request<WorkDocs.Types.DescribeFolderContentsResponse, AWSError>; /** * Describes the groups specified by the query. Groups are defined by the underlying Active Directory. */ describeGroups(params: WorkDocs.Types.DescribeGroupsRequest, callback?: (err: AWSError, data: WorkDocs.Types.DescribeGroupsResponse) => void): Request<WorkDocs.Types.DescribeGroupsResponse, AWSError>; /** * Describes the groups specified by the query. Groups are defined by the underlying Active Directory. */ describeGroups(callback?: (err: AWSError, data: WorkDocs.Types.DescribeGroupsResponse) => void): Request<WorkDocs.Types.DescribeGroupsResponse, AWSError>; /** * Lists the specified notification subscriptions. */ describeNotificationSubscriptions(params: WorkDocs.Types.DescribeNotificationSubscriptionsRequest, callback?: (err: AWSError, data: WorkDocs.Types.DescribeNotificationSubscriptionsResponse) => void): Request<WorkDocs.Types.DescribeNotificationSubscriptionsResponse, AWSError>; /** * Lists the specified notification subscriptions. */ describeNotificationSubscriptions(callback?: (err: AWSError, data: WorkDocs.Types.DescribeNotificationSubscriptionsResponse) => void): Request<WorkDocs.Types.DescribeNotificationSubscriptionsResponse, AWSError>; /** * Describes the permissions of a specified resource. */ describeResourcePermissions(params: WorkDocs.Types.DescribeResourcePermissionsRequest, callback?: (err: AWSError, data: WorkDocs.Types.DescribeResourcePermissionsResponse) => void): Request<WorkDocs.Types.DescribeResourcePermissionsResponse, AWSError>; /** * Describes the permissions of a specified resource. */ describeResourcePermissions(callback?: (err: AWSError, data: WorkDocs.Types.DescribeResourcePermissionsResponse) => void): Request<WorkDocs.Types.DescribeResourcePermissionsResponse, AWSError>; /** * Describes the current user's special folders; the RootFolder and the RecycleBin. RootFolder is the root of user's files and folders and RecycleBin is the root of recycled items. This is not a valid action for SigV4 (administrative API) clients. This action requires an authentication token. To get an authentication token, register an application with Amazon WorkDocs. For more information, see Authentication and Access Control for User Applications in the Amazon WorkDocs Developer Guide. */ describeRootFolders(params: WorkDocs.Types.DescribeRootFoldersRequest, callback?: (err: AWSError, data: WorkDocs.Types.DescribeRootFoldersResponse) => void): Request<WorkDocs.Types.DescribeRootFoldersResponse, AWSError>; /** * Describes the current user's special folders; the RootFolder and the RecycleBin. RootFolder is the root of user's files and folders and RecycleBin is the root of recycled items. This is not a valid action for SigV4 (administrative API) clients. This action requires an authentication token. To get an authentication token, register an application with Amazon WorkDocs. For more information, see Authentication and Access Control for User Applications in the Amazon WorkDocs Developer Guide. */ describeRootFolders(callback?: (err: AWSError, data: WorkDocs.Types.DescribeRootFoldersResponse) => void): Request<WorkDocs.Types.DescribeRootFoldersResponse, AWSError>; /** * Describes the specified users. You can describe all users or filter the results (for example, by status or organization). By default, Amazon WorkDocs returns the first 24 active or pending users. If there are more results, the response includes a marker that you can use to request the next set of results. */ describeUsers(params: WorkDocs.Types.DescribeUsersRequest, callback?: (err: AWSError, data: WorkDocs.Types.DescribeUsersResponse) => void): Request<WorkDocs.Types.DescribeUsersResponse, AWSError>; /** * Describes the specified users. You can describe all users or filter the results (for example, by status or organization). By default, Amazon WorkDocs returns the first 24 active or pending users. If there are more results, the response includes a marker that you can use to request the next set of results. */ describeUsers(callback?: (err: AWSError, data: WorkDocs.Types.DescribeUsersResponse) => void): Request<WorkDocs.Types.DescribeUsersResponse, AWSError>; /** * Retrieves details of the current user for whom the authentication token was generated. This is not a valid action for SigV4 (administrative API) clients. This action requires an authentication token. To get an authentication token, register an application with Amazon WorkDocs. For more information, see Authentication and Access Control for User Applications in the Amazon WorkDocs Developer Guide. */ getCurrentUser(params: WorkDocs.Types.GetCurrentUserRequest, callback?: (err: AWSError, data: WorkDocs.Types.GetCurrentUserResponse) => void): Request<WorkDocs.Types.GetCurrentUserResponse, AWSError>; /** * Retrieves details of the current user for whom the authentication token was generated. This is not a valid action for SigV4 (administrative API) clients. This action requires an authentication token. To get an authentication token, register an application with Amazon WorkDocs. For more information, see Authentication and Access Control for User Applications in the Amazon WorkDocs Developer Guide. */ getCurrentUser(callback?: (err: AWSError, data: WorkDocs.Types.GetCurrentUserResponse) => void): Request<WorkDocs.Types.GetCurrentUserResponse, AWSError>; /** * Retrieves details of a document. */ getDocument(params: WorkDocs.Types.GetDocumentRequest, callback?: (err: AWSError, data: WorkDocs.Types.GetDocumentResponse) => void): Request<WorkDocs.Types.GetDocumentResponse, AWSError>; /** * Retrieves details of a document. */ getDocument(callback?: (err: AWSError, data: WorkDocs.Types.GetDocumentResponse) => void): Request<WorkDocs.Types.GetDocumentResponse, AWSError>; /** * Retrieves the path information (the hierarchy from the root folder) for the requested document. By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the requested document and only includes the IDs of the parent folders in the path. You can limit the maximum number of levels. You can also request the names of the parent folders. */ getDocumentPath(params: WorkDocs.Types.GetDocumentPathRequest, callback?: (err: AWSError, data: WorkDocs.Types.GetDocumentPathResponse) => void): Request<WorkDocs.Types.GetDocumentPathResponse, AWSError>; /** * Retrieves the path information (the hierarchy from the root folder) for the requested document. By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the requested document and only includes the IDs of the parent folders in the path. You can limit the maximum number of levels. You can also request the names of the parent folders. */ getDocumentPath(callback?: (err: AWSError, data: WorkDocs.Types.GetDocumentPathResponse) => void): Request<WorkDocs.Types.GetDocumentPathResponse, AWSError>; /** * Retrieves version metadata for the specified document. */ getDocumentVersion(params: WorkDocs.Types.GetDocumentVersionRequest, callback?: (err: AWSError, data: WorkDocs.Types.GetDocumentVersionResponse) => void): Request<WorkDocs.Types.GetDocumentVersionResponse, AWSError>; /** * Retrieves version metadata for the specified document. */ getDocumentVersion(callback?: (err: AWSError, data: WorkDocs.Types.GetDocumentVersionResponse) => void): Request<WorkDocs.Types.GetDocumentVersionResponse, AWSError>; /** * Retrieves the metadata of the specified folder. */ getFolder(params: WorkDocs.Types.GetFolderRequest, callback?: (err: AWSError, data: WorkDocs.Types.GetFolderResponse) => void): Request<WorkDocs.Types.GetFolderResponse, AWSError>; /** * Retrieves the metadata of the specified folder. */ getFolder(callback?: (err: AWSError, data: WorkDocs.Types.GetFolderResponse) => void): Request<WorkDocs.Types.GetFolderResponse, AWSError>; /** * Retrieves the path information (the hierarchy from the root folder) for the specified folder. By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the requested folder and only includes the IDs of the parent folders in the path. You can limit the maximum number of levels. You can also request the parent folder names. */ getFolderPath(params: WorkDocs.Types.GetFolderPathRequest, callback?: (err: AWSError, data: WorkDocs.Types.GetFolderPathResponse) => void): Request<WorkDocs.Types.GetFolderPathResponse, AWSError>; /** * Retrieves the path information (the hierarchy from the root folder) for the specified folder. By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the requested folder and only includes the IDs of the parent folders in the path. You can limit the maximum number of levels. You can also request the parent folder names. */ getFolderPath(callback?: (err: AWSError, data: WorkDocs.Types.GetFolderPathResponse) => void): Request<WorkDocs.Types.GetFolderPathResponse, AWSError>; /** * Retrieves a collection of resources, including folders and documents. The only CollectionType supported is SHARED_WITH_ME. */ getResources(params: WorkDocs.Types.GetResourcesRequest, callback?: (err: AWSError, data: WorkDocs.Types.GetResourcesResponse) => void): Request<WorkDocs.Types.GetResourcesResponse, AWSError>; /** * Retrieves a collection of resources, including folders and documents. The only CollectionType supported is SHARED_WITH_ME. */ getResources(callback?: (err: AWSError, data: WorkDocs.Types.GetResourcesResponse) => void): Request<WorkDocs.Types.GetResourcesResponse, AWSError>; /** * Creates a new document object and version object. The client specifies the parent folder ID and name of the document to upload. The ID is optionally specified when creating a new version of an existing document. This is the first step to upload a document. Next, upload the document to the URL returned from the call, and then call UpdateDocumentVersion. To cancel the document upload, call AbortDocumentVersionUpload. */ initiateDocumentVersionUpload(params: WorkDocs.Types.InitiateDocumentVersionUploadRequest, callback?: (err: AWSError, data: WorkDocs.Types.InitiateDocumentVersionUploadResponse) => void): Request<WorkDocs.Types.InitiateDocumentVersionUploadResponse, AWSError>; /** * Creates a new document object and version object. The client specifies the parent folder ID and name of the document to upload. The ID is optionally specified when creating a new version of an existing document. This is the first step to upload a document. Next, upload the document to the URL returned from the call, and then call UpdateDocumentVersion. To cancel the document upload, call AbortDocumentVersionUpload. */ initiateDocumentVersionUpload(callback?: (err: AWSError, data: WorkDocs.Types.InitiateDocumentVersionUploadResponse) => void): Request<WorkDocs.Types.InitiateDocumentVersionUploadResponse, AWSError>; /** * Removes all the permissions from the specified resource. */ removeAllResourcePermissions(params: WorkDocs.Types.RemoveAllResourcePermissionsRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes all the permissions from the specified resource. */ removeAllResourcePermissions(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes the permission for the specified principal from the specified resource. */ removeResourcePermission(params: WorkDocs.Types.RemoveResourcePermissionRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes the permission for the specified principal from the specified resource. */ removeResourcePermission(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates the specified attributes of a document. The user must have access to both the document and its parent folder, if applicable. */ updateDocument(params: WorkDocs.Types.UpdateDocumentRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates the specified attributes of a document. The user must have access to both the document and its parent folder, if applicable. */ updateDocument(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Changes the status of the document version to ACTIVE. Amazon WorkDocs also sets its document container to ACTIVE. This is the last step in a document upload, after the client uploads the document to an S3-presigned URL returned by InitiateDocumentVersionUpload. */ updateDocumentVersion(params: WorkDocs.Types.UpdateDocumentVersionRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Changes the status of the document version to ACTIVE. Amazon WorkDocs also sets its document container to ACTIVE. This is the last step in a document upload, after the client uploads the document to an S3-presigned URL returned by InitiateDocumentVersionUpload. */ updateDocumentVersion(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates the specified attributes of the specified folder. The user must have access to both the folder and its parent folder, if applicable. */ updateFolder(params: WorkDocs.Types.UpdateFolderRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates the specified attributes of the specified folder. The user must have access to both the folder and its parent folder, if applicable. */ updateFolder(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates the specified attributes of the specified user, and grants or revokes administrative privileges to the Amazon WorkDocs site. */ updateUser(params: WorkDocs.Types.UpdateUserRequest, callback?: (err: AWSError, data: WorkDocs.Types.UpdateUserResponse) => void): Request<WorkDocs.Types.UpdateUserResponse, AWSError>; /** * Updates the specified attributes of the specified user, and grants or revokes administrative privileges to the Amazon WorkDocs site. */ updateUser(callback?: (err: AWSError, data: WorkDocs.Types.UpdateUserResponse) => void): Request<WorkDocs.Types.UpdateUserResponse, AWSError>; } declare namespace WorkDocs { export interface AbortDocumentVersionUploadRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ DocumentId: ResourceIdType; /** * The ID of the version. */ VersionId: DocumentVersionIdType; } export interface ActivateUserRequest { /** * The ID of the user. */ UserId: IdType; /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; } export interface ActivateUserResponse { /** * The user information. */ User?: User; } export interface Activity { /** * The activity type. */ Type?: ActivityType; /** * The timestamp when the action was performed. */ TimeStamp?: TimestampType; /** * Indicates whether an activity is indirect or direct. An indirect activity results from a direct activity performed on a parent resource. For example, sharing a parent folder (the direct activity) shares all of the subfolders and documents within the parent folder (the indirect activity). */ IsIndirectActivity?: BooleanType; /** * The ID of the organization. */ OrganizationId?: IdType; /** * The user who performed the action. */ Initiator?: UserMetadata; /** * The list of users or groups impacted by this action. This is an optional field and is filled for the following sharing activities: DOCUMENT_SHARED, DOCUMENT_SHARED, DOCUMENT_UNSHARED, FOLDER_SHARED, FOLDER_UNSHARED. */ Participants?: Participants; /** * The metadata of the resource involved in the user action. */ ResourceMetadata?: ResourceMetadata; /** * The original parent of the resource. This is an optional field and is filled for move activities. */ OriginalParent?: ResourceMetadata; /** * Metadata of the commenting activity. This is an optional field and is filled for commenting activities. */ CommentMetadata?: CommentMetadata; } export type ActivityNamesFilterType = string; export type ActivityType = "DOCUMENT_CHECKED_IN"|"DOCUMENT_CHECKED_OUT"|"DOCUMENT_RENAMED"|"DOCUMENT_VERSION_UPLOADED"|"DOCUMENT_VERSION_DELETED"|"DOCUMENT_VERSION_VIEWED"|"DOCUMENT_VERSION_DOWNLOADED"|"DOCUMENT_RECYCLED"|"DOCUMENT_RESTORED"|"DOCUMENT_REVERTED"|"DOCUMENT_SHARED"|"DOCUMENT_UNSHARED"|"DOCUMENT_SHARE_PERMISSION_CHANGED"|"DOCUMENT_SHAREABLE_LINK_CREATED"|"DOCUMENT_SHAREABLE_LINK_REMOVED"|"DOCUMENT_SHAREABLE_LINK_PERMISSION_CHANGED"|"DOCUMENT_MOVED"|"DOCUMENT_COMMENT_ADDED"|"DOCUMENT_COMMENT_DELETED"|"DOCUMENT_ANNOTATION_ADDED"|"DOCUMENT_ANNOTATION_DELETED"|"FOLDER_CREATED"|"FOLDER_DELETED"|"FOLDER_RENAMED"|"FOLDER_RECYCLED"|"FOLDER_RESTORED"|"FOLDER_SHARED"|"FOLDER_UNSHARED"|"FOLDER_SHARE_PERMISSION_CHANGED"|"FOLDER_SHAREABLE_LINK_CREATED"|"FOLDER_SHAREABLE_LINK_REMOVED"|"FOLDER_SHAREABLE_LINK_PERMISSION_CHANGED"|"FOLDER_MOVED"|string; export interface AddResourcePermissionsRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the resource. */ ResourceId: ResourceIdType; /** * The users, groups, or organization being granted permission. */ Principals: SharePrincipalList; /** * The notification options. */ NotificationOptions?: NotificationOptions; } export interface AddResourcePermissionsResponse { /** * The share results. */ ShareResults?: ShareResultsList; } export type AuthenticationHeaderType = string; export type BooleanEnumType = "TRUE"|"FALSE"|string; export type BooleanType = boolean; export interface Comment { /** * The ID of the comment. */ CommentId: CommentIdType; /** * The ID of the parent comment. */ ParentId?: CommentIdType; /** * The ID of the root comment in the thread. */ ThreadId?: CommentIdType; /** * The text of the comment. */ Text?: CommentTextType; /** * The details of the user who made the comment. */ Contributor?: User; /** * The time that the comment was created. */ CreatedTimestamp?: TimestampType; /** * The status of the comment. */ Status?: CommentStatusType; /** * The visibility of the comment. Options are either PRIVATE, where the comment is visible only to the comment author and document owner and co-owners, or PUBLIC, where the comment is visible to document owners, co-owners, and contributors. */ Visibility?: CommentVisibilityType; /** * If the comment is a reply to another user's comment, this field contains the user ID of the user being replied to. */ RecipientId?: IdType; } export type CommentIdType = string; export type CommentList = Comment[]; export interface CommentMetadata { /** * The ID of the comment. */ CommentId?: CommentIdType; /** * The user who made the comment. */ Contributor?: User; /** * The timestamp that the comment was created. */ CreatedTimestamp?: TimestampType; /** * The status of the comment. */ CommentStatus?: CommentStatusType; /** * The ID of the user being replied to. */ RecipientId?: IdType; } export type CommentStatusType = "DRAFT"|"PUBLISHED"|"DELETED"|string; export type CommentTextType = string; export type CommentVisibilityType = "PUBLIC"|"PRIVATE"|string; export interface CreateCommentRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ DocumentId: ResourceIdType; /** * The ID of the document version. */ VersionId: DocumentVersionIdType; /** * The ID of the parent comment. */ ParentId?: CommentIdType; /** * The ID of the root comment in the thread. */ ThreadId?: CommentIdType; /** * The text of the comment. */ Text: CommentTextType; /** * The visibility of the comment. Options are either PRIVATE, where the comment is visible only to the comment author and document owner and co-owners, or PUBLIC, where the comment is visible to document owners, co-owners, and contributors. */ Visibility?: CommentVisibilityType; /** * Set this parameter to TRUE to send an email out to the document collaborators after the comment is created. */ NotifyCollaborators?: BooleanType; } export interface CreateCommentResponse { /** * The comment that has been created. */ Comment?: Comment; } export interface CreateCustomMetadataRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the resource. */ ResourceId: ResourceIdType; /** * The ID of the version, if the custom metadata is being added to a document version. */ VersionId?: DocumentVersionIdType; /** * Custom metadata in the form of name-value pairs. */ CustomMetadata: CustomMetadataMap; } export interface CreateCustomMetadataResponse { } export interface CreateFolderRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The name of the new folder. */ Name?: ResourceNameType; /** * The ID of the parent folder. */ ParentFolderId: ResourceIdType; } export interface CreateFolderResponse { /** * The metadata of the folder. */ Metadata?: FolderMetadata; } export interface CreateLabelsRequest { /** * The ID of the resource. */ ResourceId: ResourceIdType; /** * List of labels to add to the resource. */ Labels: SharedLabels; /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; } export interface CreateLabelsResponse { } export interface CreateNotificationSubscriptionRequest { /** * The ID of the organization. */ OrganizationId: IdType; /** * The endpoint to receive the notifications. If the protocol is HTTPS, the endpoint is a URL that begins with https. */ Endpoint: SubscriptionEndPointType; /** * The protocol to use. The supported value is https, which delivers JSON-encoded messages using HTTPS POST. */ Protocol: SubscriptionProtocolType; /** * The notification type. */ SubscriptionType: SubscriptionType; } export interface CreateNotificationSubscriptionResponse { /** * The subscription. */ Subscription?: Subscription; } export interface CreateUserRequest { /** * The ID of the organization. */ OrganizationId?: IdType; /** * The login name of the user. */ Username: UsernameType; /** * The email address of the user. */ EmailAddress?: EmailAddressType; /** * The given name of the user. */ GivenName: UserAttributeValueType; /** * The surname of the user. */ Surname: UserAttributeValueType; /** * The password of the user. */ Password: PasswordType; /** * The time zone ID of the user. */ TimeZoneId?: TimeZoneIdType; /** * The amount of storage for the user. */ StorageRule?: StorageRuleType; /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; } export interface CreateUserResponse { /** * The user information. */ User?: User; } export type CustomMetadataKeyList = CustomMetadataKeyType[]; export type CustomMetadataKeyType = string; export type CustomMetadataMap = {[key: string]: CustomMetadataValueType}; export type CustomMetadataValueType = string; export interface DeactivateUserRequest { /** * The ID of the user. */ UserId: IdType; /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; } export interface DeleteCommentRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ DocumentId: ResourceIdType; /** * The ID of the document version. */ VersionId: DocumentVersionIdType; /** * The ID of the comment. */ CommentId: CommentIdType; } export interface DeleteCustomMetadataRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the resource, either a document or folder. */ ResourceId: ResourceIdType; /** * The ID of the version, if the custom metadata is being deleted from a document version. */ VersionId?: DocumentVersionIdType; /** * List of properties to remove. */ Keys?: CustomMetadataKeyList; /** * Flag to indicate removal of all custom metadata properties from the specified resource. */ DeleteAll?: BooleanType; } export interface DeleteCustomMetadataResponse { } export interface DeleteDocumentRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ DocumentId: ResourceIdType; } export interface DeleteFolderContentsRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the folder. */ FolderId: ResourceIdType; } export interface DeleteFolderRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the folder. */ FolderId: ResourceIdType; } export interface DeleteLabelsRequest { /** * The ID of the resource. */ ResourceId: ResourceIdType; /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * List of labels to delete from the resource. */ Labels?: SharedLabels; /** * Flag to request removal of all labels from the specified resource. */ DeleteAll?: BooleanType; } export interface DeleteLabelsResponse { } export interface DeleteNotificationSubscriptionRequest { /** * The ID of the subscription. */ SubscriptionId: IdType; /** * The ID of the organization. */ OrganizationId: IdType; } export interface DeleteUserRequest { /** * Amazon WorkDocs authentication token. Do not set this field when using administrative API actions, as in accessing the API using AWS credentials. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the user. */ UserId: IdType; } export interface DescribeActivitiesRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The timestamp that determines the starting time of the activities. The response includes the activities performed after the specified timestamp. */ StartTime?: TimestampType; /** * The timestamp that determines the end time of the activities. The response includes the activities performed before the specified timestamp. */ EndTime?: TimestampType; /** * The ID of the organization. This is a mandatory parameter when using administrative API (SigV4) requests. */ OrganizationId?: IdType; /** * Specifies which activity types to include in the response. If this field is left empty, all activity types are returned. */ ActivityTypes?: ActivityNamesFilterType; /** * The document or folder ID for which to describe activity types. */ ResourceId?: IdType; /** * The ID of the user who performed the action. The response includes activities pertaining to this user. This is an optional parameter and is only applicable for administrative API (SigV4) requests. */ UserId?: IdType; /** * Includes indirect activities. An indirect activity results from a direct activity performed on a parent resource. For example, sharing a parent folder (the direct activity) shares all of the subfolders and documents within the parent folder (the indirect activity). */ IncludeIndirectActivities?: BooleanType; /** * The maximum number of items to return. */ Limit?: LimitType; /** * The marker for the next set of results. */ Marker?: MarkerType; } export interface DescribeActivitiesResponse { /** * The list of activities for the specified user and time period. */ UserActivities?: UserActivities; /** * The marker for the next set of results. */ Marker?: MarkerType; } export interface DescribeCommentsRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ DocumentId: ResourceIdType; /** * The ID of the document version. */ VersionId: DocumentVersionIdType; /** * The maximum number of items to return. */ Limit?: LimitType; /** * The marker for the next set of results. This marker was received from a previous call. */ Marker?: MarkerType; } export interface DescribeCommentsResponse { /** * The list of comments for the specified document version. */ Comments?: CommentList; /** * The marker for the next set of results. This marker was received from a previous call. */ Marker?: MarkerType; } export interface DescribeDocumentVersionsRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ DocumentId: ResourceIdType; /** * The marker for the next set of results. (You received this marker from a previous call.) */ Marker?: PageMarkerType; /** * The maximum number of versions to return with this call. */ Limit?: LimitType; /** * A comma-separated list of values. Specify "INITIALIZED" to include incomplete versions. */ Include?: FieldNamesType; /** * Specify "SOURCE" to include initialized versions and a URL for the source document. */ Fields?: FieldNamesType; } export interface DescribeDocumentVersionsResponse { /** * The document versions. */ DocumentVersions?: DocumentVersionMetadataList; /** * The marker to use when requesting the next set of results. If there are no additional results, the string is empty. */ Marker?: PageMarkerType; } export interface DescribeFolderContentsRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the folder. */ FolderId: ResourceIdType; /** * The sorting criteria. */ Sort?: ResourceSortType; /** * The order for the contents of the folder. */ Order?: OrderType; /** * The maximum number of items to return with this call. */ Limit?: LimitType; /** * The marker for the next set of results. This marker was received from a previous call. */ Marker?: PageMarkerType; /** * The type of items. */ Type?: FolderContentType; /** * The contents to include. Specify "INITIALIZED" to include initialized documents. */ Include?: FieldNamesType; } export interface DescribeFolderContentsResponse { /** * The subfolders in the specified folder. */ Folders?: FolderMetadataList; /** * The documents in the specified folder. */ Documents?: DocumentMetadataList; /** * The marker to use when requesting the next set of results. If there are no additional results, the string is empty. */ Marker?: PageMarkerType; } export interface DescribeGroupsRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * A query to describe groups by group name. */ SearchQuery: SearchQueryType; /** * The ID of the organization. */ OrganizationId?: IdType; /** * The marker for the next set of results. (You received this marker from a previous call.) */ Marker?: MarkerType; /** * The maximum number of items to return with this call. */ Limit?: PositiveIntegerType; } export interface DescribeGroupsResponse { /** * The list of groups. */ Groups?: GroupMetadataList; /** * The marker to use when requesting the next set of results. If there are no additional results, the string is empty. */ Marker?: MarkerType; } export interface DescribeNotificationSubscriptionsRequest { /** * The ID of the organization. */ OrganizationId: IdType; /** * The marker for the next set of results. (You received this marker from a previous call.) */ Marker?: PageMarkerType; /** * The maximum number of items to return with this call. */ Limit?: LimitType; } export interface DescribeNotificationSubscriptionsResponse { /** * The subscriptions. */ Subscriptions?: SubscriptionList; /** * The marker to use when requesting the next set of results. If there are no additional results, the string is empty. */ Marker?: PageMarkerType; } export interface DescribeResourcePermissionsRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the resource. */ ResourceId: ResourceIdType; /** * The ID of the principal to filter permissions by. */ PrincipalId?: IdType; /** * The maximum number of items to return with this call. */ Limit?: LimitType; /** * The marker for the next set of results. (You received this marker from a previous call) */ Marker?: PageMarkerType; } export interface DescribeResourcePermissionsResponse { /** * The principals. */ Principals?: PrincipalList; /** * The marker to use when requesting the next set of results. If there are no additional results, the string is empty. */ Marker?: PageMarkerType; } export interface DescribeRootFoldersRequest { /** * Amazon WorkDocs authentication token. */ AuthenticationToken: AuthenticationHeaderType; /** * The maximum number of items to return. */ Limit?: LimitType; /** * The marker for the next set of results. (You received this marker from a previous call.) */ Marker?: PageMarkerType; } export interface DescribeRootFoldersResponse { /** * The user's special folders. */ Folders?: FolderMetadataList; /** * The marker for the next set of results. */ Marker?: PageMarkerType; } export interface DescribeUsersRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the organization. */ OrganizationId?: IdType; /** * The IDs of the users. */ UserIds?: UserIdsType; /** * A query to filter users by user name. */ Query?: SearchQueryType; /** * The state of the users. Specify "ALL" to include inactive users. */ Include?: UserFilterType; /** * The order for the results. */ Order?: OrderType; /** * The sorting criteria. */ Sort?: UserSortType; /** * The marker for the next set of results. (You received this marker from a previous call.) */ Marker?: PageMarkerType; /** * The maximum number of items to return. */ Limit?: LimitType; /** * A comma-separated list of values. Specify "STORAGE_METADATA" to include the user storage quota and utilization information. */ Fields?: FieldNamesType; } export interface DescribeUsersResponse { /** * The users. */ Users?: OrganizationUserList; /** * The total number of users included in the results. */ TotalNumberOfUsers?: SizeType; /** * The marker to use when requesting the next set of results. If there are no additional results, the string is empty. */ Marker?: PageMarkerType; } export type DocumentContentType = string; export interface DocumentMetadata { /** * The ID of the document. */ Id?: ResourceIdType; /** * The ID of the creator. */ CreatorId?: IdType; /** * The ID of the parent folder. */ ParentFolderId?: ResourceIdType; /** * The time when the document was created. */ CreatedTimestamp?: TimestampType; /** * The time when the document was updated. */ ModifiedTimestamp?: TimestampType; /** * The latest version of the document. */ LatestVersionMetadata?: DocumentVersionMetadata; /** * The resource state. */ ResourceState?: ResourceStateType; /** * List of labels on the document. */ Labels?: SharedLabels; } export type DocumentMetadataList = DocumentMetadata[]; export type DocumentSourceType = "ORIGINAL"|"WITH_COMMENTS"|string; export type DocumentSourceUrlMap = {[key: string]: UrlType}; export type DocumentStatusType = "INITIALIZED"|"ACTIVE"|string; export type DocumentThumbnailType = "SMALL"|"SMALL_HQ"|"LARGE"|string; export type DocumentThumbnailUrlMap = {[key: string]: UrlType}; export type DocumentVersionIdType = string; export interface DocumentVersionMetadata { /** * The ID of the version. */ Id?: DocumentVersionIdType; /** * The name of the version. */ Name?: ResourceNameType; /** * The content type of the document. */ ContentType?: DocumentContentType; /** * The size of the document, in bytes. */ Size?: SizeType; /** * The signature of the document. */ Signature?: HashType; /** * The status of the document. */ Status?: DocumentStatusType; /** * The timestamp when the document was first uploaded. */ CreatedTimestamp?: TimestampType; /** * The timestamp when the document was last uploaded. */ ModifiedTimestamp?: TimestampType; /** * The timestamp when the content of the document was originally created. */ ContentCreatedTimestamp?: TimestampType; /** * The timestamp when the content of the document was modified. */ ContentModifiedTimestamp?: TimestampType; /** * The ID of the creator. */ CreatorId?: IdType; /** * The thumbnail of the document. */ Thumbnail?: DocumentThumbnailUrlMap; /** * The source of the document. */ Source?: DocumentSourceUrlMap; } export type DocumentVersionMetadataList = DocumentVersionMetadata[]; export type DocumentVersionStatus = "ACTIVE"|string; export type EmailAddressType = string; export type FieldNamesType = string; export type FolderContentType = "ALL"|"DOCUMENT"|"FOLDER"|string; export interface FolderMetadata { /** * The ID of the folder. */ Id?: ResourceIdType; /** * The name of the folder. */ Name?: ResourceNameType; /** * The ID of the creator. */ CreatorId?: IdType; /** * The ID of the parent folder. */ ParentFolderId?: ResourceIdType; /** * The time when the folder was created. */ CreatedTimestamp?: TimestampType; /** * The time when the folder was updated. */ ModifiedTimestamp?: TimestampType; /** * The resource state of the folder. */ ResourceState?: ResourceStateType; /** * The unique identifier created from the subfolders and documents of the folder. */ Signature?: HashType; /** * List of labels on the folder. */ Labels?: SharedLabels; /** * The size of the folder metadata. */ Size?: SizeType; /** * The size of the latest version of the folder metadata. */ LatestVersionSize?: SizeType; } export type FolderMetadataList = FolderMetadata[]; export interface GetCurrentUserRequest { /** * Amazon WorkDocs authentication token. */ AuthenticationToken: AuthenticationHeaderType; } export interface GetCurrentUserResponse { /** * Metadata of the user. */ User?: User; } export interface GetDocumentPathRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ DocumentId: IdType; /** * The maximum number of levels in the hierarchy to return. */ Limit?: LimitType; /** * A comma-separated list of values. Specify NAME to include the names of the parent folders. */ Fields?: FieldNamesType; /** * This value is not supported. */ Marker?: PageMarkerType; } export interface GetDocumentPathResponse { /** * The path information. */ Path?: ResourcePath; } export interface GetDocumentRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ DocumentId: ResourceIdType; /** * Set this to TRUE to include custom metadata in the response. */ IncludeCustomMetadata?: BooleanType; } export interface GetDocumentResponse { /** * The metadata details of the document. */ Metadata?: DocumentMetadata; /** * The custom metadata on the document. */ CustomMetadata?: CustomMetadataMap; } export interface GetDocumentVersionRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ DocumentId: ResourceIdType; /** * The version ID of the document. */ VersionId: DocumentVersionIdType; /** * A comma-separated list of values. Specify "SOURCE" to include a URL for the source document. */ Fields?: FieldNamesType; /** * Set this to TRUE to include custom metadata in the response. */ IncludeCustomMetadata?: BooleanType; } export interface GetDocumentVersionResponse { /** * The version metadata. */ Metadata?: DocumentVersionMetadata; /** * The custom metadata on the document version. */ CustomMetadata?: CustomMetadataMap; } export interface GetFolderPathRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the folder. */ FolderId: IdType; /** * The maximum number of levels in the hierarchy to return. */ Limit?: LimitType; /** * A comma-separated list of values. Specify "NAME" to include the names of the parent folders. */ Fields?: FieldNamesType; /** * This value is not supported. */ Marker?: PageMarkerType; } export interface GetFolderPathResponse { /** * The path information. */ Path?: ResourcePath; } export interface GetFolderRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the folder. */ FolderId: ResourceIdType; /** * Set to TRUE to include custom metadata in the response. */ IncludeCustomMetadata?: BooleanType; } export interface GetFolderResponse { /** * The metadata of the folder. */ Metadata?: FolderMetadata; /** * The custom metadata on the folder. */ CustomMetadata?: CustomMetadataMap; } export interface GetResourcesRequest { /** * The Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The user ID for the resource collection. This is a required field for accessing the API operation using IAM credentials. */ UserId?: IdType; /** * The collection type. */ CollectionType?: ResourceCollectionType; /** * The maximum number of resources to return. */ Limit?: LimitType; /** * The marker for the next set of results. This marker was received from a previous call. */ Marker?: PageMarkerType; } export interface GetResourcesResponse { /** * The folders in the specified folder. */ Folders?: FolderMetadataList; /** * The documents in the specified collection. */ Documents?: DocumentMetadataList; /** * The marker to use when requesting the next set of results. If there are no additional results, the string is empty. */ Marker?: PageMarkerType; } export interface GroupMetadata { /** * The ID of the user group. */ Id?: IdType; /** * The name of the group. */ Name?: GroupNameType; } export type GroupMetadataList = GroupMetadata[]; export type GroupNameType = string; export type HashType = string; export type HeaderNameType = string; export type HeaderValueType = string; export type IdType = string; export interface InitiateDocumentVersionUploadRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ Id?: ResourceIdType; /** * The name of the document. */ Name?: ResourceNameType; /** * The timestamp when the content of the document was originally created. */ ContentCreatedTimestamp?: TimestampType; /** * The timestamp when the content of the document was modified. */ ContentModifiedTimestamp?: TimestampType; /** * The content type of the document. */ ContentType?: DocumentContentType; /** * The size of the document, in bytes. */ DocumentSizeInBytes?: SizeType; /** * The ID of the parent folder. */ ParentFolderId: ResourceIdType; } export interface InitiateDocumentVersionUploadResponse { /** * The document metadata. */ Metadata?: DocumentMetadata; /** * The upload metadata. */ UploadMetadata?: UploadMetadata; } export type LimitType = number; export type LocaleType = "en"|"fr"|"ko"|"de"|"es"|"ja"|"ru"|"zh_CN"|"zh_TW"|"pt_BR"|"default"|string; export type MarkerType = string; export type MessageType = string; export interface NotificationOptions { /** * Boolean value to indicate an email notification should be sent to the receipients. */ SendEmail?: BooleanType; /** * Text value to be included in the email body. */ EmailMessage?: MessageType; } export type OrderType = "ASCENDING"|"DESCENDING"|string; export type OrganizationUserList = User[]; export type PageMarkerType = string; export interface Participants { /** * The list of users. */ Users?: UserMetadataList; /** * The list of user groups. */ Groups?: GroupMetadataList; } export type PasswordType = string; export interface PermissionInfo { /** * The role of the user. */ Role?: RoleType; /** * The type of permissions. */ Type?: RolePermissionType; } export type PermissionInfoList = PermissionInfo[]; export type PositiveIntegerType = number; export type PositiveSizeType = number; export interface Principal { /** * The ID of the resource. */ Id?: IdType; /** * The type of resource. */ Type?: PrincipalType; /** * The permission information for the resource. */ Roles?: PermissionInfoList; } export type PrincipalList = Principal[]; export type PrincipalType = "USER"|"GROUP"|"INVITE"|"ANONYMOUS"|"ORGANIZATION"|string; export interface RemoveAllResourcePermissionsRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the resource. */ ResourceId: ResourceIdType; } export interface RemoveResourcePermissionRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the resource. */ ResourceId: ResourceIdType; /** * The principal ID of the resource. */ PrincipalId: IdType; /** * The principal type of the resource. */ PrincipalType?: PrincipalType; } export type ResourceCollectionType = "SHARED_WITH_ME"|string; export type ResourceIdType = string; export interface ResourceMetadata { /** * The type of resource. */ Type?: ResourceType; /** * The name of the resource. */ Name?: ResourceNameType; /** * The original name of the resource before a rename operation. */ OriginalName?: ResourceNameType; /** * The ID of the resource. */ Id?: ResourceIdType; /** * The version ID of the resource. This is an optional field and is filled for action on document version. */ VersionId?: DocumentVersionIdType; /** * The owner of the resource. */ Owner?: UserMetadata; /** * The parent ID of the resource before a rename operation. */ ParentId?: ResourceIdType; } export type ResourceNameType = string; export interface ResourcePath { /** * The components of the resource path. */ Components?: ResourcePathComponentList; } export interface ResourcePathComponent { /** * The ID of the resource path. */ Id?: IdType; /** * The name of the resource path. */ Name?: ResourceNameType; } export type ResourcePathComponentList = ResourcePathComponent[]; export type ResourceSortType = "DATE"|"NAME"|string; export type ResourceStateType = "ACTIVE"|"RESTORING"|"RECYCLING"|"RECYCLED"|string; export type ResourceType = "FOLDER"|"DOCUMENT"|string; export type RolePermissionType = "DIRECT"|"INHERITED"|string; export type RoleType = "VIEWER"|"CONTRIBUTOR"|"OWNER"|"COOWNER"|string; export type SearchQueryType = string; export interface SharePrincipal { /** * The ID of the recipient. */ Id: IdType; /** * The type of the recipient. */ Type: PrincipalType; /** * The role of the recipient. */ Role: RoleType; } export type SharePrincipalList = SharePrincipal[]; export interface ShareResult { /** * The ID of the principal. */ PrincipalId?: IdType; /** * The ID of the invited user. */ InviteePrincipalId?: IdType; /** * The role. */ Role?: RoleType; /** * The status. */ Status?: ShareStatusType; /** * The ID of the resource that was shared. */ ShareId?: ResourceIdType; /** * The status message. */ StatusMessage?: MessageType; } export type ShareResultsList = ShareResult[]; export type ShareStatusType = "SUCCESS"|"FAILURE"|string; export type SharedLabel = string; export type SharedLabels = SharedLabel[]; export type SignedHeaderMap = {[key: string]: HeaderValueType}; export type SizeType = number; export interface StorageRuleType { /** * The amount of storage allocated, in bytes. */ StorageAllocatedInBytes?: PositiveSizeType; /** * The type of storage. */ StorageType?: StorageType; } export type StorageType = "UNLIMITED"|"QUOTA"|string; export interface Subscription { /** * The ID of the subscription. */ SubscriptionId?: IdType; /** * The endpoint of the subscription. */ EndPoint?: SubscriptionEndPointType; /** * The protocol of the subscription. */ Protocol?: SubscriptionProtocolType; } export type SubscriptionEndPointType = string; export type SubscriptionList = Subscription[]; export type SubscriptionProtocolType = "HTTPS"|string; export type SubscriptionType = "ALL"|string; export type TimeZoneIdType = string; export type TimestampType = Date; export interface UpdateDocumentRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ DocumentId: ResourceIdType; /** * The name of the document. */ Name?: ResourceNameType; /** * The ID of the parent folder. */ ParentFolderId?: ResourceIdType; /** * The resource state of the document. Only ACTIVE and RECYCLED are supported. */ ResourceState?: ResourceStateType; } export interface UpdateDocumentVersionRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the document. */ DocumentId: ResourceIdType; /** * The version ID of the document. */ VersionId: DocumentVersionIdType; /** * The status of the version. */ VersionStatus?: DocumentVersionStatus; } export interface UpdateFolderRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the folder. */ FolderId: ResourceIdType; /** * The name of the folder. */ Name?: ResourceNameType; /** * The ID of the parent folder. */ ParentFolderId?: ResourceIdType; /** * The resource state of the folder. Only ACTIVE and RECYCLED are accepted values from the API. */ ResourceState?: ResourceStateType; } export interface UpdateUserRequest { /** * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API. */ AuthenticationToken?: AuthenticationHeaderType; /** * The ID of the user. */ UserId: IdType; /** * The given name of the user. */ GivenName?: UserAttributeValueType; /** * The surname of the user. */ Surname?: UserAttributeValueType; /** * The type of the user. */ Type?: UserType; /** * The amount of storage for the user. */ StorageRule?: StorageRuleType; /** * The time zone ID of the user. */ TimeZoneId?: TimeZoneIdType; /** * The locale of the user. */ Locale?: LocaleType; /** * Boolean value to determine whether the user is granted Poweruser privileges. */ GrantPoweruserPrivileges?: BooleanEnumType; } export interface UpdateUserResponse { /** * The user information. */ User?: User; } export interface UploadMetadata { /** * The URL of the upload. */ UploadUrl?: UrlType; /** * The signed headers. */ SignedHeaders?: SignedHeaderMap; } export type UrlType = string; export interface User { /** * The ID of the user. */ Id?: IdType; /** * The login name of the user. */ Username?: UsernameType; /** * The email address of the user. */ EmailAddress?: EmailAddressType; /** * The given name of the user. */ GivenName?: UserAttributeValueType; /** * The surname of the user. */ Surname?: UserAttributeValueType; /** * The ID of the organization. */ OrganizationId?: IdType; /** * The ID of the root folder. */ RootFolderId?: ResourceIdType; /** * The ID of the recycle bin folder. */ RecycleBinFolderId?: ResourceIdType; /** * The status of the user. */ Status?: UserStatusType; /** * The type of user. */ Type?: UserType; /** * The time when the user was created. */ CreatedTimestamp?: TimestampType; /** * The time when the user was modified. */ ModifiedTimestamp?: TimestampType; /** * The time zone ID of the user. */ TimeZoneId?: TimeZoneIdType; /** * The locale of the user. */ Locale?: LocaleType; /** * The storage for the user. */ Storage?: UserStorageMetadata; } export type UserActivities = Activity[]; export type UserAttributeValueType = string; export type UserFilterType = "ALL"|"ACTIVE_PENDING"|string; export type UserIdsType = string; export interface UserMetadata { /** * The ID of the user. */ Id?: IdType; /** * The name of the user. */ Username?: UsernameType; /** * The given name of the user before a rename operation. */ GivenName?: UserAttributeValueType; /** * The surname of the user. */ Surname?: UserAttributeValueType; /** * The email address of the user. */ EmailAddress?: EmailAddressType; } export type UserMetadataList = UserMetadata[]; export type UserSortType = "USER_NAME"|"FULL_NAME"|"STORAGE_LIMIT"|"USER_STATUS"|"STORAGE_USED"|string; export type UserStatusType = "ACTIVE"|"INACTIVE"|"PENDING"|string; export interface UserStorageMetadata { /** * The amount of storage used, in bytes. */ StorageUtilizedInBytes?: SizeType; /** * The storage for a user. */ StorageRule?: StorageRuleType; } export type UserType = "USER"|"ADMIN"|"POWERUSER"|"MINIMALUSER"|"WORKSPACESUSER"|string; export type UsernameType = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2016-05-01"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the WorkDocs client. */ export import Types = WorkDocs; } export = WorkDocs;
the_stack
export function sortBy<T>(arr: T[], keys: Array<keyof T>): T[] { return arr.slice().sort((a, b) => { for (let i = 0; i < keys.length; i++) { const key = keys[i]; if (a[key] < b[key]) return -1; else if (a[key] > b[key]) return 1; } return 0; }); } /** * Take out the first N items of an array */ export function take<T>(arr: T[], n: number): T[] { return arr.slice(0, n); } /** * Get the first element of an array */ export function head<T>(arr: T[]): T | undefined { return arr[0]; } /** * Get multiple object or array value by paths. Example path: `a[0].b.c` */ export function at( source: Record<string, unknown> | any[], paths: string[] | string, ) { const out = []; if (typeof paths === "string") { paths = [paths]; } for (let i = 0; i < paths.length; i++) { const path = paths[i]; const parts = path.split(/[.[\]]/g); let haystack: any = source; let found = true; for (let i = 0; i < parts.length; i++) { const part = parts[i]; if (part === "") continue; if (!(part in haystack)) { found = false; break; } haystack = haystack[part]; } if (found) { out.push(haystack); } } return out; } /** * Return item by path or default value if not present */ export function get<T = any>( source: Record<string, unknown> | any[], path: string | Array<string | number>, defaultValue?: T, ): T | undefined { if (Array.isArray(path)) { path = path.join("."); } const parts = path.split(/[.[\]]/g); let haystack: any = source; for (let i = 0; i < parts.length; i++) { const part = parts[i]; if (part === "") continue; if (!(part in haystack)) return defaultValue; haystack = haystack[part]; } return haystack; } /** * Check if an item is in an object by path */ export function has( source: Record<string, unknown> | any[], path: string | Array<string | number>, ) { const empty = "__tlodash_not_found"; return get(source, path, empty) !== empty; } /** * Check if a collection (Array, Map, Set, Object) is empty */ export function isEmpty(v: any) { if (Array.isArray(v)) { return v.length === 0; } else if (v instanceof Set || v instanceof Map) { return v.size === 0; } else if (v !== null && typeof v === "object") { return Object.keys(v).length === 0; } return true; } /** * Pick values out of an object by predicate and return them in a new object */ export function pickBy<T extends Record<string, unknown>>( obj: T, predicate: <K extends keyof T>(value: T[K], key: K) => boolean, ) { const out: Partial<T> = {}; Object.keys(obj).forEach(key => { if (predicate((obj as any)[key], key)) { (out as any)[key] = obj[key]; } }); return out; } /** * Loop over a collection and call the callback on each item */ export function forEach<T>( value: T, callback: (value: any, index: number | string, collection: T) => void, ) { if (Array.isArray(value)) { value.forEach(callback as any); } else if (value instanceof Set || value instanceof Map) { value.forEach(callback as any); } else if (value !== null && typeof value === "object") { Object.keys(value).forEach(key => { callback((value as any)[key], key, value); }); } } /** * Convert string to kebab case */ export function kebabCase(input: string) { let out = input .replace(/[-._\s]+/g, "-") .replace(/[A-Z0-9]/, "-$&") .replace(/[-]{2,}/, ""); if (out[0] === "-") { out = out.slice(1); } if (out[out.length - 1] === "-") { out = out.slice(0, -1); } return out.toLowerCase(); } /** * Get index of an item in an array */ export function indexOf<T>(arr: T[], value: T, startIndex = 0) { if (startIndex === 0) return arr.indexOf(value); for (let i = startIndex; i < arr.length; i++) { if (arr[i] === value) return i; } return -1; } /** * Flatten an array by a single level */ export function flatten(arr: any[]): any[] { return arr.reduce((acc, val) => acc.concat(val), []); } /** * Remove falsy values from array */ export function compact(arr: unknown[]) { return arr.filter(x => !!x); } /** Used to generate unique IDs. */ const idCounter: Record<string, number> = {}; /** * Generates a unique ID */ export function uniqueId(prefix = "$smoldash$") { const id = (idCounter[prefix] = (idCounter[prefix] || 0) + 1); return "" + (prefix === "$smoldash$" ? "" : prefix) + id; } // eslint-disable-next-line @typescript-eslint/ban-types export function once<T extends (...args: any[]) => any>(fn: T): T { let result: ReturnType<T>; let called = false; return function once_wrapped(this: any, ...args: any[]) { if (!called) { called = true; result = fn.apply(this, args); } return result; } as any; } /** * Create a duplicate free version of an array */ export function uniq<T>(arr: T[]): T[] { if (!Array.isArray(arr)) return []; return Array.from(new Set(arr).values()); } /** * Create a duplicate free version of an array by a user iteratee */ export function uniqBy<T, R = any>(arr: T[], iteratee: R | ((v: T) => R)) { if (!Array.isArray(arr)) return []; const seen = new Map<R, T>(); const type = typeof iteratee; arr.forEach(item => { let key: any = iteratee; if (type === "string" && item !== null && typeof item === "object") { key = (item as any)[iteratee]; } else if (type === "function") { key = (iteratee as any)(item); } if (!seen.has(key)) { seen.set(key, item); } }); return Array.from(seen.values()); } export type AnyFunction = (...args: any[]) => any; /** * Pass the result of the first function to the next one. */ export function flow(...fns: AnyFunction[]) { return function (this: any, ...args: any[]) { let result = fns[0].apply(this, args); for (let i = 1; i < fns.length; i++) { result = fns[i].call(this, result); } return result; }; } /** * Shallow clone of a value */ export function clone<T>(value: T): T { if (Array.isArray(value)) { return value.slice() as any; } else if (value instanceof RegExp) { return new RegExp(value.source, value.flags) as any; } else if (value instanceof Set) { return new Set(value) as any; } else if (value instanceof Map) { return new Map(value) as any; } else if (value instanceof Date) { return new Date(value) as any; } else if (typeof value === "object" && value !== null) { return { ...value }; } return value; } /** * Deeply clone a value */ export function cloneDeep<T>(value: T): T { if (Array.isArray(value)) { return value.slice().map(cloneDeep) as any; } else if (value instanceof RegExp) { return new RegExp(value.source, value.flags) as any; } else if (value instanceof Set) { const out = new Set(); value.forEach(v => out.add(cloneDeep(v))); return out as any; } else if (value instanceof Map) { const out = new Map(); value.forEach((v, k) => out.set(k, cloneDeep(v))); return out as any; } else if (value instanceof Date) { return new Date(value) as any; } else if (typeof value === "object" && value !== null) { const out: Record<string, any> = {}; for (const k in value) { out[k] = cloneDeep(value[k]); } return out as any; } return value; } /** * Deeply merge multiple objects */ export function merge(...objs: Record<string, any>[]): Record<string, any> { const a = objs[0] as any; for (let i = 1; i < objs.length; i++) { const b = objs[i] as any; for (const k in b) { if ( a[k] !== null && b[k] !== null && typeof a[k] === "object" && typeof b[k] === "object" ) { merge(a[k], b[k]); } else { a[k] = b[k]; } } } return objs[0]; } const createPredicate = <T>( predicate: | string | [string, any] | Record<string, any> | ((item: T) => boolean) = x => !!x, ): ((item: T) => boolean) | undefined => { let fn; if (typeof predicate === "string") { fn = (item: T) => !!(item as any)[predicate]; } else if (Array.isArray(predicate)) { fn = (item: T) => (item as any)[predicate[0]] === predicate[1]; } else if (typeof predicate === "object") { fn = (item: T) => { return Object.keys(predicate).every( v => !(v in predicate) || (item as any)[v] === predicate[v], ); }; } else if (typeof predicate === "function") { fn = predicate; } return fn; }; /** * Iterate the collection and return the index of the element where the predicate returns true */ export function findIndex<T>( collection: T[], predicate: | string | [string, any] | Record<string, any> | ((item: T) => boolean) = x => !!x, fromIndex = 0, ): number { if (!Array.isArray(collection)) return -1; const fn = createPredicate(predicate); for (let i = fromIndex; i < collection.length; i++) { if ((fn as any)(collection[i], i, collection)) { return i; } } return -1; } /** * Iterate the collection and return the element where the predicate returns true */ export function find<T>( collection: T[], predicate: | string | [string, any] | Record<string, any> | ((item: T) => boolean) = x => !!x, fromIndex = 0, ): T | undefined { const index = findIndex(collection, predicate, fromIndex); return index < 0 ? undefined : collection[index]; } /** * Iterate the collection and return the elements where the predicate returns true */ export function filter<T>( collection: T[], predicate: | string | [string, any] | Record<string, any> | ((item: T) => boolean) = x => !!x, ): T[] { if (!Array.isArray(collection)) return []; return collection.filter(createPredicate(predicate) as any); } /** * Iterate the collection and return true if predicate returns true for at least one element */ export function some<T>( collection: T[], predicate: | string | [string, any] | Record<string, any> | ((item: T) => boolean) = x => !!x, ): boolean { return findIndex(collection, predicate) > -1; } /** * Iterate the collection and return true if predicate returns true for all elements */ export function every<T>( collection: T[], predicate: | string | [string, any] | Record<string, any> | ((item: T) => boolean) = x => !!x, ): boolean { const fn = createPredicate(predicate); // if we find one element which does not satisfy predicate, then return false return findIndex(collection, item => !(fn as any)(item)) < 0; } /** * Returns new collection with each element as result of it being called on iteratee function */ // overloaded signatures export function map<T, K extends keyof T>(collection: T[], iteratee: K): T[K][]; export function map<T, Out>( collection: T[], iteratee?: (item: T, index: number, collection: T[]) => Out, ): Out[]; export function map<T, Out>( collection: T[], iteratee: string | ((item: T, index: number, collection: T[]) => Out) = x => (x as unknown) as Out, ): Out[] { if (!Array.isArray(collection)) return []; let fn; if (typeof iteratee === "string") { fn = (item: T) => item[iteratee as keyof T]; } else if (typeof iteratee === "function") { fn = iteratee; } return collection.map(fn as any); } /** * Shallowly compare to values */ export function isEqual<T>(a: T, b: T): boolean { if (a === null || b === null) { return a === b; } else if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; } else if (a instanceof RegExp && b instanceof RegExp) { return "" + a === "" + b; } else if (a instanceof Set && b instanceof Set) { if (a.size !== b.size) return false; for (const v of a.values()) { if (!b.has(v)) return false; } return true; } else if (a instanceof Map && b instanceof Map) { if (a.size !== b.size) return false; for (const [k, v] of a.entries()) { if (!b.has(k)) return false; if (b.get(k) !== v) return false; } return true; } else if (a instanceof Date && b instanceof Date) { return +a === +b; } else if (typeof a === "object" && typeof b === "object") { for (const i in a) if (!(i in b)) return false; for (const i in b) if (a[i] !== b[i]) return false; return true; } return a === b; } /** * Generate a range of numbers */ export function range(start: number, end?: number, step = 1) { if (typeof end === "undefined") { end = start; start = 0; } const result = []; for (let i = start; i < end; i += step) { result.push(i); } return result; } /** * Creates object to items in collection using keys from iteratee */ export function keyBy<T, K extends keyof T, MapKey extends string | number>( collection: T[], iteratee: K | ((item: T, index: number, collection: T[]) => MapKey), ): { [key in MapKey]: T } { if (!Array.isArray(collection)) return {} as { [key in MapKey]: T }; let fn: (item: T, index: number, collection: T[]) => MapKey; if (typeof iteratee === "string") { fn = (item: T) => (item[(iteratee as unknown) as keyof T] as unknown) as MapKey; } else if (typeof iteratee === "function") { fn = iteratee; } return collection.reduce((accumulator, item, index) => { const key = fn(item, index, collection); accumulator[key] = item; return accumulator; }, {} as { [key in MapKey]: T }); } /** * Creates object to items in collection using keys from iteratee */ export function groupBy<T, K extends keyof T, MapKey extends string | number>( collection: T[], iteratee: K | ((item: T, index: number, collection: T[]) => MapKey), ): { [key in MapKey]: T[] } { if (!Array.isArray(collection)) return {} as { [key in MapKey]: T[] }; let fn: (item: T, index: number, collection: T[]) => MapKey; if (typeof iteratee === "string") { fn = (item: T) => (item[(iteratee as unknown) as keyof T] as unknown) as MapKey; } else if (typeof iteratee === "function") { fn = iteratee; } return collection.reduce((accumulator, item, index) => { const key = fn(item, index, collection); if (!accumulator[key]) accumulator[key] = []; accumulator[key].push(item); return accumulator; }, {} as { [key in MapKey]: T[] }); }
the_stack
import * as angular from 'angular'; import * as _ from "underscore"; import {AccessControlService} from '../../../services/AccessControlService'; import { RegisterTemplateServiceFactory } from '../../services/RegisterTemplateServiceFactory'; import { EntityAccessControlService } from '../../shared/entity-access-control/EntityAccessControlService'; import {HomeController} from '../../../main/HomeController'; const moduleName = require('feed-mgr/feeds/edit-feed/module-name'); import '../../../plugin/template-table-option/define-table/define-table-feed-details.html'; var FeedUploadFileDialogController = function ($scope:any, $mdDialog:any, $http:any, RestUrlService:any , FileUpload:any, feedId:any){ var self = this; $scope.uploading = false; $scope.uploadFiles = null; /** * Upload file */ $scope.doUpload = function() { $scope.uploading = true; $scope.errorMessage = ''; var uploadUrl = RestUrlService.UPLOAD_FILE_FEED_URL(feedId); var params = {}; var successFn = function (response:any) { $scope.uploading = false; $mdDialog.hide('Upload successfully submitted.'); } var errorFn = function (data:any) { $scope.uploading = false; $scope.errorMessage = 'Failed to submit file.'; } FileUpload.uploadFileToUrl($scope.uploadFiles, uploadUrl, successFn, errorFn, params); }; $scope.hide = function() { $mdDialog.hide(); }; $scope.cancel = function() { $mdDialog.cancel(); }; }; export class controller { cardWidth:any; allowAdmin:any; allowChangePermissions:any; allowEdit:any; allowExport:any; allowStart:any; allowSlaAccess:any; feedId:any; selectedTabIndex:any; loadingFeedData:any; model:any; loadMessage:any; uploadFile:any; uploading:any; uploadAllowed:any; errorLoadingFeed:any; isNiFiRunning:any; newSla:any; cloneFeed:any; confirmDeleteFeed:any; deleteFeed:any; showFeedUploadDialog:any; showAccessControlDialog:any; openFeedMenu:any; enableFeed:any; disableFeed:any; onCategoryClick:any; onTableClick:any; addSla:any; updateMenuOptions:any; gotoFeedStats:any; gotoFeedDetails:any; shouldIndexingOptionsBeDisabled:any; shouldIndexingOptionsBeEnabled:any; findAndReplaceString:any; disabling:any; enabling:any; exportFeedUrl:any; feedNavigationLinks:any; feedNavigationLink:any; startFeed:any; startingFeed:any; /** * * Displays the details for a feed. * * @param $scope * @param $q * @param $transition$.params() * @param $mdDialog * @param $mdToast * @param $http * @param $state * @param {AccessControlService} AccessControlService the access control service * @param RestUrlService * @param FeedService * @param RegisterTemplateService * @param StateService */ constructor (private $scope:any, private $q:any, private $transition$:any, private $mdDialog:any, private $mdToast:any , private $http:any, private $state:any, private accessControlService:AccessControlService, private RestUrlService:any , private FeedService:any, private registerTemplateService:RegisterTemplateServiceFactory, private StateService:any , private SideNavService:any, private FileUpload:any, private ConfigurationService:any , private EntityAccessControlDialogService:any, private entityAccessControlService:EntityAccessControlService, private UiComponentsService:any , private AngularModuleExtensionService:any, private DatasourcesService:any) { var SLA_INDEX = 3; var self = this; /** * Flag to indicate style of page * if true it will fit the card to the 980px width * if false it will make it go 100% width * @type {boolean} */ self.cardWidth = true; /** * Indicates if admin operations are allowed. * @type {boolean} */ self.allowAdmin = false; /** * Allow the Changing of this feeds permissions * @type {boolean} */ self.allowChangePermissions = false; /** * Indicates if edit operations are allowed. * @type {boolean} */ self.allowEdit = false; /** * Indicates if export operations are allowed. * @type {boolean} */ self.allowExport = false; /** * Indicates if starting a feed is allowed. * @type {boolean} */ self.allowStart = false; /** * Alow user to access the sla tab * @type {boolean} */ self.allowSlaAccess = false; this.feedId = null; this.selectedTabIndex = 0; this.loadingFeedData = false; this.model = FeedService.editFeedModel = {}; this.model.loaded = false; this.loadMessage = '' this.uploadFile = null; this.uploading = false; this.uploadAllowed = false; this.feedNavigationLinks = AngularModuleExtensionService.getFeedNavigation(); /** * flag to indicate the feed could not be loaded * @type {boolean} */ this.errorLoadingFeed = false; /** flag to indicate if we get a valid connection back from NiFi. Initially to true. it will be rechecked on load **/ this.isNiFiRunning = true; var requestedTabIndex = $transition$.params().tabIndex; $scope.$watch(function() { return self.selectedTabIndex; }, function(newVal:any) { //reset display of feed versions FeedService.resetVersionFeedModel(); //Make the Lineage tab fit without side nav //open side nav if we are not navigating between lineage links if (newVal == 2 || (requestedTabIndex != undefined && requestedTabIndex == 2)) { SideNavService.hideSideNav(); self.cardWidth = false; requestedTabIndex = 0; } else { SideNavService.showSideNav(); self.cardWidth = true; } }) /** * flag to indicate if the SLA page should be set to empty new form rather than the list * Used for when the "Add SLA" button is clicked * @type {boolean} */ this.newSla = false; var init = function() { self.feedId = $transition$.params().feedId; self.exportFeedUrl = RestUrlService.ADMIN_EXPORT_FEED_URL+"/"+self.feedId loadFeed(requestedTabIndex); nifiRunningCheck(); }; this.cloneFeed = ()=>{ StateService.FeedManager().Feed().navigateToCloneFeed(this.model.feedName); } /** * Displays a confirmation dialog for deleting the feed. */ this.confirmDeleteFeed = function() { if(self.allowAdmin) { // Verify there are no dependent feeds if (angular.isArray(self.model.usedByFeeds) && self.model.usedByFeeds.length > 0) { var list = "<ul>"; list += _.map(self.model.usedByFeeds, function (feed:any) { return "<li>" + _.escape(feed.feedName) + "</li>"; }); list += "</ul>"; var alert = $mdDialog.alert() .parent($("body")) .clickOutsideToClose(true) .title("Feed is referenced") .htmlContent("This feed is referenced by other feeds and cannot be deleted. The following feeds should be deleted first: " + list) .ariaLabel("feed is referenced") .ok("Got it!"); $mdDialog.show(alert); return; } // Display delete dialog var $dialogScope = $scope.$new(); $dialogScope.dialog = $mdDialog; $dialogScope.vm = self; $mdDialog.show({ escapeToClose: false, fullscreen: true, parent: angular.element(document.body), scope: $dialogScope, templateUrl: "js/feed-mgr/feeds/edit-feed/feed-details-delete-dialog.html" }); } }; /** * Permanently deletes this feed. */ this.deleteFeed = function() { // Update model state self.model.state = "DELETED"; // Delete the feed var successFn = function() { $state.go("feeds"); }; var errorFn = function(response:any) { // Update model state self.model.state = "DISABLED"; // Display error message var msg = "<p>The feed cannot be deleted at this time.</p><p>"; msg += angular.isString(response.data.message) ? _.escape(response.data.message) : "Please try again later."; msg += "</p>"; $mdDialog.hide(); $mdDialog.show( $mdDialog.alert() .ariaLabel("Error deleting feed") .clickOutsideToClose(true) .htmlContent(msg) .ok("Got it!") .parent(document.body) .title("Error deleting feed") ); }; $http.delete(RestUrlService.GET_FEEDS_URL + "/" + self.feedId).then(successFn, errorFn); }; this.feedNavigationLink = function(link:any) { var feedId = self.feedId; var feedName = self.model.systemCategoryName + "." + self.model.systemFeedName; $state.go(link.sref,{feedId:feedId,feedName:feedName,model:self.model}); } this.showFeedUploadDialog = function() { $mdDialog.show({ controller: 'FeedUploadFileDialogController', escapeToClose: false, fullscreen: true, parent: angular.element(document.body), templateUrl: "js/feed-mgr/feeds/edit-feed/feed-details-upload-dialog.html", locals: {feedId: self.feedId} }).then(function(msg:any) { $mdToast.show( $mdToast.simple() .textContent('File uploaded.') .hideDelay(3000) ); }); } this.showAccessControlDialog = function(){ function onCancel(){ } function onSave(){ } EntityAccessControlDialogService.showAccessControlDialog(self.model,"feed",self.model.feedName,onSave,onCancel); } this.openFeedMenu = function($mdOpenMenu:any, ev:any) { $mdOpenMenu(ev); }; /** * Enables this feed. */ this.enableFeed = function() { if(!self.enabling && self.allowEdit) { self.enabling = true; $http.post(RestUrlService.ENABLE_FEED_URL(self.feedId)).then(function (response:any) { self.model.state = response.data.state; FeedService.updateEditModelStateIcon(); self.enabling = false; }, function () { $mdDialog.show( $mdDialog.alert() .clickOutsideToClose(true) .title("NiFi Error") .textContent("The feed could not be enabled.") .ariaLabel("Cannot enable feed.") .ok("OK") ); self.enabling = false; }); } }; /** * Disables this feed. */ this.disableFeed = function() { if(!self.disabling && self.allowEdit) { self.disabling = true; $http.post(RestUrlService.DISABLE_FEED_URL(self.feedId)).then(function (response:any) { self.model.state = response.data.state; FeedService.updateEditModelStateIcon(); self.disabling = false; }, function () { $mdDialog.show( $mdDialog.alert() .clickOutsideToClose(true) .title("NiFi Error") .textContent("The feed could not be disabled.") .ariaLabel("Cannot disable feed.") .ok("OK") ); self.disabling = false; }); } }; /** * Starts this feed. */ this.startFeed = function() { if (!self.startingFeed && self.allowStart) { self.startingFeed = true; $http.post(RestUrlService.START_FEED_URL(self.feedId)).then(function (response:any) { let msg = "Feed started"; if(response && response.data && response.data.message) { msg = response.data.message; } $mdToast.show( $mdToast.simple() .textContent(msg) .hideDelay(3000) ); self.startingFeed = false; }, function (response : any) { let msg = "The feed could not be started."; if(response && response.data && response.data.message) { msg +="<br/><br/>"+response.data.message; } console.error("Unable to start the feed ",response); $mdDialog.show( $mdDialog.alert() .clickOutsideToClose(true) .title("Error starting the feed") .htmlContent(msg) .ariaLabel("Cannot start feed.") .ok("OK") ); self.startingFeed = false; }); } }; function mergeTemplateProperties(feed:any) { var successFn = function(response:any) { return response; } var errorFn = function(err:any) { } var promise = $http({ url: RestUrlService.MERGE_FEED_WITH_TEMPLATE(feed.id), method: "POST", data: angular.toJson(feed), headers: { 'Content-Type': 'application/json; charset=UTF-8' } }).then(successFn, errorFn); return promise; } /** * Navigates to the category details page for this feed's category. * * An error is displayed if the user does not have permissions to access categories. */ this.onCategoryClick = function() { accessControlService.getUserAllowedActions() .then(function(actionSet:any) { if (accessControlService.hasAction(AccessControlService.CATEGORIES_ACCESS, actionSet.actions)) { StateService.FeedManager().Category().navigateToCategoryDetails(self.model.category.id); } else { $mdDialog.show( $mdDialog.alert() .clickOutsideToClose(true) .title("Access Denied") .textContent("You do not have permissions to access categories.") .ariaLabel("Access denied for categories") .ok("OK") ); } }); }; this.onTableClick = function() { StateService.FeedManager().Table().navigateToTable(DatasourcesService.getHiveDatasource().id,self.model.category.systemName, self.model.table.tableSchema.name); } this.addSla = function() { self.selectedTabIndex = SLA_INDEX; self.newSla = true; } this.updateMenuOptions = function() { self.uploadAllowed=false; var model = self.model; if (model && model.inputProcessor && model.inputProcessor.allProperties.length > 0) { angular.forEach(model.inputProcessor.allProperties, function (property) { if (property.processorType == 'org.apache.nifi.processors.standard.GetFile') { self.uploadAllowed = true; return; } }); } } function loadFeed(tabIndex:any) { self.errorLoadingFeed = false; self.loadingFeedData = true; self.model.loaded = false; self.loadMessage = ''; var successFn = (response:any) => { if (response.data) { var promises = { feedPromise: mergeTemplateProperties(response.data), processorTemplatesPromise: UiComponentsService.getProcessorTemplates() }; $q.all(promises).then((result:any) => { //deal with the feed data var updatedFeedResponse = result.feedPromise; //merge in the template properties //this will update teh self.model as they point to the same object if (updatedFeedResponse == undefined || updatedFeedResponse.data == undefined) { self.loadingFeedData = false; var loadMessage = 'Unable to load Feed Details. Please ensure that Apache Nifi is up and running and then refresh this page.'; self.loadMessage = loadMessage; $mdDialog.show( $mdDialog.alert() // .parent(angular.element(document.querySelector('#popupContainer'))) .clickOutsideToClose(true) .title('Unable to load Feed Details') .textContent(loadMessage) .ariaLabel('Unable to load Feed Details') .ok('Got it!') ); } else { self.model.loaded = true; FeedService.updateFeed(updatedFeedResponse.data); if (tabIndex != null && tabIndex != undefined && tabIndex != self.selectedTabIndex) { self.selectedTabIndex = tabIndex; } self.registerTemplateService.initializeProperties(updatedFeedResponse.data.registeredTemplate,'edit',[]); self.model.inputProcessors = self.registerTemplateService.removeNonUserEditableProperties(updatedFeedResponse.data.registeredTemplate.inputProcessors,true); //sort them by name self.model.inputProcessors = _.sortBy(self.model.inputProcessors,'name') self.model.inputProcessor = _.find(self.model.inputProcessors,function(processor){ return angular.isDefined(self.model.inputProcessorName) && self.model.inputProcessorName != null ? self.model.inputProcessorType == processor.type && self.model.inputProcessorName.toLowerCase() == processor.name.toLowerCase() : self.model.inputProcessorType == processor.type; }); if(angular.isUndefined(self.model.inputProcessor)){ self.model.inputProcessor = _.find(self.model.inputProcessors,function(processor){ return self.model.inputProcessorType == processor.type; }); } self.model.nonInputProcessors = self.registerTemplateService.removeNonUserEditableProperties(updatedFeedResponse.data.registeredTemplate.nonInputProcessors,false); self.updateMenuOptions(); self.loadingFeedData = false; self.model.isStream = updatedFeedResponse.data.registeredTemplate.stream; FeedService.updateEditModelStateIcon(); var entityAccessControlled = accessControlService.isEntityAccessControlled(); //Apply the entity access permissions var requests = { entityEditAccess: !entityAccessControlled || FeedService.hasEntityAccess(EntityAccessControlService.ENTITY_ACCESS.FEED.EDIT_FEED_DETAILS, self.model), entityExportAccess: !entityAccessControlled || FeedService.hasEntityAccess(EntityAccessControlService.ENTITY_ACCESS.FEED.EXPORT, self.model), entityStartAccess: !entityAccessControlled || FeedService.hasEntityAccess(EntityAccessControlService.ENTITY_ACCESS.FEED.START, self.model), entityPermissionAccess: !entityAccessControlled || FeedService.hasEntityAccess(EntityAccessControlService.ENTITY_ACCESS.FEED.CHANGE_FEED_PERMISSIONS, self.model), functionalAccess: accessControlService.getUserAllowedActions() }; $q.all(requests).then(function (response:any) { var allowEditAccess = accessControlService.hasAction(AccessControlService.FEEDS_EDIT, response.functionalAccess.actions); var allowAdminAccess = accessControlService.hasAction(AccessControlService.FEEDS_ADMIN, response.functionalAccess.actions); var slaAccess = accessControlService.hasAction(AccessControlService.SLA_ACCESS, response.functionalAccess.actions); var allowExport = accessControlService.hasAction(AccessControlService.FEEDS_EXPORT, response.functionalAccess.actions); var allowStart = accessControlService.hasAction(AccessControlService.FEEDS_EDIT, response.functionalAccess.actions); self.allowEdit = response.entityEditAccess && allowEditAccess; self.allowChangePermissions = entityAccessControlled && response.entityPermissionAccess && allowEditAccess; self.allowAdmin = allowAdminAccess; self.allowSlaAccess = slaAccess; self.allowExport = response.entityExportAccess && allowExport; self.allowStart = response.entityStartAccess && allowStart; }); } },function(err:any){ //handle err self.loadingFeedData = false; }); } else { errorFn(" The feed was not found.") } } var errorFn = function(err:any) { self.loadingFeedData = false; self.errorLoadingFeed = true; var message = angular.isDefined(err) && angular.isString(err) ? err : ''; $mdDialog.show( $mdDialog.alert() .parent(angular.element(document.querySelector('body'))) .clickOutsideToClose(true) .title('Error loading feed') .textContent('Error loading feed. '+message) .ariaLabel('Error loading feed') .ok('Got it!') //.targetEvent(ev) ); } var promise = $http.get(RestUrlService.GET_FEEDS_URL + "/" + self.feedId); promise.then(successFn, errorFn); return promise; } function nifiRunningCheck(){ var promise = $http.get(RestUrlService.IS_NIFI_RUNNING_URL); promise.then(function(response:any) { self.isNiFiRunning =response.data; }, function(err:any) { self.isNiFiRunning = false; }); } this.gotoFeedStats = function (ev:any) { ev.preventDefault(); ev.stopPropagation(); var feedName = self.model.systemCategoryName + "." + self.model.systemFeedName; StateService.OpsManager().Feed().navigateToFeedStats(feedName); }; this.gotoFeedDetails = function (ev:any) { ev.preventDefault(); ev.stopPropagation(); var feedName = self.model.systemCategoryName + "." + self.model.systemFeedName; StateService.OpsManager().Feed().navigateToFeedDetails(feedName); }; this.shouldIndexingOptionsBeDisabled = function() { return ((self.model.historyReindexingStatus === 'IN_PROGRESS') || (self.model.historyReindexingStatus === 'DIRTY')); }; this.shouldIndexingOptionsBeEnabled = () => { return !this.shouldIndexingOptionsBeDisabled(); }; this.findAndReplaceString = function(str:any, findStr:any, replacementStr:any) { var i = 0; if(angular.isUndefined(str) || angular.isUndefined(findStr)){ return ''; } else { var strLength = str.length; for (i; i < strLength; i++) { str = str.replace(findStr, replacementStr); } return str; } }; init(); }; } angular.module(moduleName).filter('capitalizeFirstLetterOfEachWord', function() { return function(str:any) { return (!!str) ? str.split(' ') .map(function(word:any) { return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase(); }) .join(' ') : ''; } }); // angular.module(moduleName).component('FeedDetailsController', { // controller: controller, // controllerAs: "vm", // templateUrl: require('./feed-details.html'), // }); angular.module(moduleName).controller('FeedDetailsController', ["$scope","$q","$transition$","$mdDialog","$mdToast","$http","$state","AccessControlService","RestUrlService","FeedService","RegisterTemplateService","StateService","SideNavService","FileUpload","ConfigurationService","EntityAccessControlDialogService","EntityAccessControlService","UiComponentsService","AngularModuleExtensionService","DatasourcesService",controller]); angular.module(moduleName).controller('FeedUploadFileDialogController',["$scope","$mdDialog","$http","RestUrlService","FileUpload","feedId",FeedUploadFileDialogController]); const module = angular.module(moduleName); export default module;
the_stack
import Fuse = require('fuse.js'); import preact = require("preact"); const { h, Component } = preact; type DocItem = { display_html: string name: string module: string link: string } function loadJSON(path: string, success: (json: DocItem[]) => void, error: (xhr: XMLHttpRequest) => void) { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { if (success) { try { success(JSON.parse(xhr.responseText)); } catch (exc) { error(xhr); } } } else { if (error) { error(xhr); } } } }; xhr.open("GET", path, true); xhr.send(); } // -------------------------------------------------------------------------- // class PageMenuButton extends Component<any, any> { render(props: { title: string, onClick: () => void }) { function onClick(e: Event) { e.preventDefault(); props.onClick(); } return <li><a href="#" onClick={onClick}>{props.title}</a></li>; } } function addSearchPageMenuButton(action: () => void) { const pageMenu = document.querySelector('#page-menu') as HTMLUListElement; const dummy = document.createElement('li'); pageMenu.insertBefore(dummy, pageMenu.firstChild); preact.render(<PageMenuButton onClick={action} title="Quick Jump" />, pageMenu, dummy); } // -------------------------------------------------------------------------- // function take<T>(n: number, arr: T[]) { if (arr.length <= n) { return arr; } return arr.slice(0, n); } type FuseResult<T> = { score: number item: T } type ResultsInModule = { module: string, totalScore: number, items: FuseResult<DocItem>[] } type QuickJumpProps = { baseUrl: string showHideTrigger: (action: () => void) => void } type QuickJumpState = { searchString: string isVisible: boolean expanded: { [moduleName: string]: true } activeLinkIndex: number moduleResults: ResultsInModule[] failedLoading?: boolean fuse: Fuse<DocItem> } class QuickJump extends Component<QuickJumpProps, QuickJumpState> { private linkIndex: number = 0; private focusPlease: boolean = false; private navigatedByKeyboard: boolean = false; private activeLink: undefined | HTMLAnchorElement; private activeLinkAction: undefined | (() => void); private input: undefined | HTMLInputElement; private searchResults: undefined | Element; componentWillMount() { this.setState({ searchString: '', isVisible: false, expanded: {}, activeLinkIndex: -1, moduleResults: [] }); loadJSON(this.props.baseUrl + "/doc-index.json", (data) => { this.setState({ fuse: new Fuse(data, { threshold: 0.25, caseSensitive: true, includeScore: true, tokenize: true, keys: [ { name: "name", weight: 0.7 }, { name: "module", weight: 0.3 } ] }), moduleResults: [] }); }, (err) => { if (console) { console.error("could not load 'doc-index.json' for searching", err); } this.setState({ failedLoading: true }); }); document.addEventListener('mousedown', this.hide.bind(this)); document.addEventListener('keydown', (e) => { if (this.state.isVisible) { if (e.key === 'Escape') { this.hide(); } else if (e.key === 'ArrowUp' || (e.key === 'k' && e.ctrlKey)) { e.preventDefault(); this.navigateLinks(-1); } else if (e.key === 'ArrowDown' || (e.key === 'j' && e.ctrlKey)) { e.preventDefault(); this.navigateLinks(+1); } else if (e.key === 'Enter' && this.state.activeLinkIndex >= 0) { this.followActiveLink(); } } if (e.key === 's' && (e.target as HTMLElement).tagName.toLowerCase() !== 'input') { e.preventDefault(); this.show(); } }) } hide() { this.setState({ isVisible: false, searchString: '' }); } show() { if (!this.state.isVisible) { this.focusPlease = true; this.setState({ isVisible: true, activeLinkIndex: -1 }); } } toggleVisibility() { if (this.state.isVisible) { this.hide(); } else { this.show(); } } navigateLinks(change: number) { const newActiveLinkIndex = Math.max(-1, Math.min(this.linkIndex-1, this.state.activeLinkIndex + change)); this.navigatedByKeyboard = true; this.setState({ activeLinkIndex: newActiveLinkIndex }); } followActiveLink() { if (!this.activeLinkAction) { return; } this.activeLinkAction(); } updateResults() { const searchString = (this.input && this.input.value) || ''; const results: FuseResult<DocItem>[] = this.state.fuse.search(searchString) as any as FuseResult<DocItem>[]; const resultsByModule: { [name: string]: FuseResult<DocItem>[] } = {}; results.forEach((result) => { const moduleName = result.item.module; const resultsInModule = resultsByModule[moduleName] || (resultsByModule[moduleName] = []); resultsInModule.push(result); }); const moduleResults: ResultsInModule[] = []; for (const moduleName in resultsByModule) { const items = resultsByModule[moduleName]; let sumOfInverseScores = 0; items.forEach((item) => { sumOfInverseScores += 1/item.score; }); moduleResults.push({ module: moduleName, totalScore: 1/sumOfInverseScores, items: items }); } moduleResults.sort((a, b) => a.totalScore - b.totalScore); this.setState({ searchString: searchString, isVisible: true, moduleResults: moduleResults }); } componentDidUpdate() { if (this.searchResults && this.activeLink && this.navigatedByKeyboard) { const rect = this.activeLink.getClientRects()[0]; const searchResultsTop = this.searchResults.getClientRects()[0].top; if (rect.bottom > window.innerHeight) { this.searchResults.scrollTop += rect.bottom - window.innerHeight + 80; } else if (rect.top < searchResultsTop) { this.searchResults.scrollTop -= searchResultsTop - rect.top + 80; } } if (this.focusPlease && this.input) { this.input.focus(); } this.navigatedByKeyboard = false; this.focusPlease = false; } componentDidMount() { this.props.showHideTrigger(this.toggleVisibility.bind(this)); } render(props: any, state: QuickJumpState) { if (state.failedLoading) { const usingFileProtocol = window.location.protocol == 'file:'; return <div id="search" class={state.isVisible ? '' : 'hidden'}> <div id="search-results"> <p class="error">Failed to load file 'doc-index.json' containing definitions in this package.</p> {usingFileProtocol ? <p class="error"> To use quick jump, load this page with HTTP (from a local static file web server) instead of using the <code>file://</code> protocol. (For security reasons, it is not possible to fetch auxiliary files using JS in a HTML page opened with <code>file://</code>.) </p> : [] } </div> </div>; } this.linkIndex = 0; const stopPropagation = (e: Event) => { e.stopPropagation(); }; const onMouseOver = (e: MouseEvent) => { let target: null | Element = e.target as Element; while (target && typeof target.getAttribute === 'function') { const linkIndexString = target.getAttribute('data-link-index'); if (typeof linkIndexString == 'string') { const linkIndex = parseInt(linkIndexString, 10); this.setState({ activeLinkIndex: linkIndex }); break; } target = target.parentNode as null | Element; } }; const items = take(10, state.moduleResults).map((r) => this.renderResultsInModule(r)); return <div id="search" class={state.isVisible ? '' : 'hidden'}> <div id="search-form" onMouseDown={stopPropagation}> <input placeholder="Search in package by name" ref={(input) => { this.input = input as undefined | HTMLInputElement; }} onFocus={this.show.bind(this)} onClick={this.show.bind(this)} onInput={this.updateResults.bind(this)} /> </div> <div id="search-results" ref={(el) => { this.searchResults = el; }} onMouseDown={stopPropagation} onMouseOver={onMouseOver}> {state.searchString === '' ? [<IntroMsg />, <KeyboardShortcuts />] : items.length == 0 ? <NoResultsMsg searchString={state.searchString} /> : <ul>{items}</ul>} </div> </div>; } renderResultsInModule(resultsInModule: ResultsInModule): JSX.Element { const items = resultsInModule.items; const moduleName = resultsInModule.module; const showAll = this.state.expanded[moduleName] || items.length <= 10; const visibleItems = showAll ? items : take(8, items); const expand = () => { const newExpanded = Object.assign({}, this.state.expanded); newExpanded[moduleName] = true; this.setState({ expanded: newExpanded }); }; const renderItem = (item: DocItem) => { return <li class="search-result"> {this.navigationLink(this.props.baseUrl + "/" + item.link, {}, <DocHtml html={item.display_html} /> )} </li>; }; return <li class="search-module"> <h4>{moduleName}</h4> <ul> {visibleItems.map((item) => renderItem(item.item))} {showAll ? [] : <li class="more-results"> {this.actionLink(expand, {}, "show " + (items.length - visibleItems.length) + " more results from this module")} </li>} </ul> </li>; } navigationLink(href: string, attrs: JSX.HTMLAttributes&JSX.SVGAttributes&{[propName: string]: any}, ...children: (JSX.Element|JSX.Element[]|string)[]) { const fullAttrs = Object.assign({ href: href, onClick: this.hide.bind(this) }, attrs); const action = () => { window.location.href = href; this.hide(); }; return this.menuLink(fullAttrs, action, ...children); } actionLink(callback: () => void, attrs: JSX.HTMLAttributes&JSX.SVGAttributes&{[propName: string]: any}, ...children: (JSX.Element|JSX.Element[]|string)[]) { const onClick = (e: Event) => { e.preventDefault(); callback(); }; const fullAttrs = Object.assign({ href: '#', onClick: onClick }, attrs); return this.menuLink(fullAttrs, callback, ...children); } menuLink(attrs: JSX.HTMLAttributes&JSX.SVGAttributes&{[propName: string]: any}, action: () => void, ...children: (JSX.Element|JSX.Element[]|string)[]) { const linkIndex = this.linkIndex; if (linkIndex === this.state.activeLinkIndex) { attrs['class'] = (attrs['class'] ? attrs['class'] + ' ' : '') + 'active-link'; attrs.ref = (link?: Element) => { if (link) this.activeLink = link as HTMLAnchorElement; }; this.activeLinkAction = action; } const newAttrs = Object.assign({ 'data-link-index': linkIndex }, attrs); this.linkIndex += 1; return h('a', newAttrs, ...children); } } class DocHtml extends Component<{ html: string }, {}> { shouldComponentUpdate(newProps: { html: string }) { return this.props.html !== newProps.html; } render(props: { html: string }) { return <div dangerouslySetInnerHTML={{__html: props.html}} />; } }; function KeyboardShortcuts() { return <table class="keyboard-shortcuts"> <tr> <th>Key</th> <th>Shortcut</th> </tr> <tr> <td><span class="key">s</span></td> <td>Open this search box</td> </tr> <tr> <td><span class="key">esc</span></td> <td>Close this search box</td> </tr> <tr> <td> <span class="key">↓</span>, <span class="key">ctrl</span> + <span class="key">j</span> </td> <td>Move down in search results</td> </tr> <tr> <td> <span class="key">↑</span>, <span class="key">ctrl</span> + <span class="key">k</span> </td> <td>Move up in search results</td> </tr> <tr> <td><span class="key">↵</span></td> <td>Go to active search result</td> </tr> </table>; } function IntroMsg() { return <p>You can find any exported type, constructor, class, function or pattern defined in this package by (approximate) name.</p>; } function NoResultsMsg(props: { searchString: string }) { const messages = [ <p> Your search for '{props.searchString}' produced the following list of results: <code>[]</code>. </p>, <p> <code>Nothing</code> matches your query for '{props.searchString}'. </p>, <p> <code> Left "no matches for '{props.searchString}'" :: Either String (NonEmpty SearchResult) </code> </p> ]; return messages[(props.searchString || 'a').charCodeAt(0) % messages.length]; } export function init(docBaseUrl?: string, showHide?: (action: () => void) => void) { preact.render( <QuickJump baseUrl={docBaseUrl || "."} showHideTrigger={showHide || addSearchPageMenuButton} />, document.body ); } // export to global object (window as any).quickNav = { init: init };
the_stack
import {createMouseEvent, emitEvent} from '../../../testing/dom/events'; import {verifyDefaultAdapter} from '../../../testing/helpers/foundation'; import {setUpFoundationTest, setUpMdcTestEnvironment} from '../../../testing/helpers/setup'; import {MDCTooltipAdapter} from '../adapter'; import {AnchorBoundaryType, attributes, CssClasses, numbers, PositionWithCaret, XPosition, YPosition} from '../constants'; import {MDCTooltipFoundation} from '../foundation'; const ESC_EVENTS = [ {type: 'keydown', key: 'Escape', target: {}} as KeyboardEvent, {type: 'keydown', keyCode: 27, target: {}} as KeyboardEvent, ]; const CARET_WIDTH = 24; const CARET_HEIGHT = 32; const RICH_TOOLTIP_WIDTH = '300px'; const RICH_TOOLTIP_HEIGHT = '140px'; const CARET_POSITION_STYLES = new Map([ [ PositionWithCaret.ABOVE_START, { yAlignment: 'bottom', xAlignment: 'left', yAxisPx: '0', xAxisPx: `${numbers.CARET_INDENTATION}px`, rotation: 35, skew: 20, scaleX: 0.9396926207859084, xTransformOrigin: `${numbers.CARET_INDENTATION}px`, yTransformOrigin: RICH_TOOLTIP_HEIGHT, } ], [ PositionWithCaret.ABOVE_CENTER, { yAlignment: 'bottom', xAlignment: 'left', yAxisPx: '0', xAxisPx: `calc((${RICH_TOOLTIP_WIDTH} - ${ CARET_WIDTH / numbers.ANIMATION_SCALE}px) / 2)`, rotation: 35, skew: 20, scaleX: 0.9396926207859084, xTransformOrigin: `calc((${RICH_TOOLTIP_WIDTH} - ${ CARET_WIDTH / numbers.ANIMATION_SCALE}px) / 2)`, yTransformOrigin: RICH_TOOLTIP_HEIGHT, } ], [ PositionWithCaret.ABOVE_END, { yAlignment: 'bottom', xAlignment: 'right', yAxisPx: '0', xAxisPx: `${numbers.CARET_INDENTATION}px`, rotation: -35, skew: -20, scaleX: 0.9396926207859084, xTransformOrigin: `calc(${RICH_TOOLTIP_WIDTH} - ${numbers.CARET_INDENTATION}px)`, yTransformOrigin: RICH_TOOLTIP_HEIGHT, } ], [ PositionWithCaret.TOP_SIDE_START, { yAlignment: 'top', xAlignment: 'right', yAxisPx: `${numbers.CARET_INDENTATION}px`, xAxisPx: '0', rotation: -55, skew: 20, scaleX: 0.9396926207859084, xTransformOrigin: RICH_TOOLTIP_WIDTH, yTransformOrigin: `${numbers.CARET_INDENTATION}px`, } ], [ PositionWithCaret.CENTER_SIDE_START, { yAlignment: 'top', xAlignment: 'right', yAxisPx: `calc((${RICH_TOOLTIP_HEIGHT} - ${ CARET_WIDTH / numbers.ANIMATION_SCALE}px) / 2)`, xAxisPx: '0', rotation: -55, skew: 20, scaleX: 0.9396926207859084, xTransformOrigin: RICH_TOOLTIP_WIDTH, yTransformOrigin: `calc((${RICH_TOOLTIP_HEIGHT} - ${ CARET_WIDTH / numbers.ANIMATION_SCALE}px) / 2)`, } ], [ PositionWithCaret.BOTTOM_SIDE_START, { yAlignment: 'bottom', xAlignment: 'right', yAxisPx: `${numbers.CARET_INDENTATION}px`, xAxisPx: '0', rotation: 55, skew: -20, scaleX: 0.9396926207859084, xTransformOrigin: RICH_TOOLTIP_WIDTH, yTransformOrigin: `calc(${RICH_TOOLTIP_HEIGHT} - ${numbers.CARET_INDENTATION}px)`, } ], [ PositionWithCaret.TOP_SIDE_END, { yAlignment: 'top', xAlignment: 'left', yAxisPx: `${numbers.CARET_INDENTATION}px`, xAxisPx: '0', rotation: 55, skew: -20, scaleX: 0.9396926207859084, xTransformOrigin: 0, yTransformOrigin: `${numbers.CARET_INDENTATION}px`, } ], [ PositionWithCaret.CENTER_SIDE_END, { yAlignment: 'top', xAlignment: 'left', yAxisPx: `calc((${RICH_TOOLTIP_HEIGHT} - ${ CARET_WIDTH / numbers.ANIMATION_SCALE}px) / 2)`, xAxisPx: '0', rotation: 55, skew: -20, scaleX: 0.9396926207859084, xTransformOrigin: 0, yTransformOrigin: `calc((${RICH_TOOLTIP_HEIGHT} - ${ CARET_WIDTH / numbers.ANIMATION_SCALE}px) / 2)`, } ], [ PositionWithCaret.BOTTOM_SIDE_END, { yAlignment: 'bottom', xAlignment: 'left', yAxisPx: `${numbers.CARET_INDENTATION}px`, xAxisPx: '0', rotation: -55, skew: 20, scaleX: 0.9396926207859084, xTransformOrigin: 0, yTransformOrigin: `calc(${RICH_TOOLTIP_HEIGHT} - ${numbers.CARET_INDENTATION}px)`, } ], [ PositionWithCaret.BELOW_START, { yAlignment: 'top', xAlignment: 'left', yAxisPx: '0', xAxisPx: `${numbers.CARET_INDENTATION}px`, rotation: -35, skew: -20, scaleX: 0.9396926207859084, xTransformOrigin: `${numbers.CARET_INDENTATION}px`, yTransformOrigin: 0, } ], [ PositionWithCaret.BELOW_CENTER, { yAlignment: 'top', xAlignment: 'left', yAxisPx: '0', xAxisPx: `calc((${RICH_TOOLTIP_WIDTH} - ${ CARET_WIDTH / numbers.ANIMATION_SCALE}px) / 2)`, rotation: -35, skew: -20, scaleX: 0.9396926207859084, xTransformOrigin: `calc((${RICH_TOOLTIP_WIDTH} - ${ CARET_WIDTH / numbers.ANIMATION_SCALE}px) / 2)`, yTransformOrigin: 0, } ], [ PositionWithCaret.BELOW_END, { yAlignment: 'top', xAlignment: 'right', yAxisPx: '0', xAxisPx: `${numbers.CARET_INDENTATION}px`, rotation: 35, skew: 20, scaleX: 0.9396926207859084, xTransformOrigin: `calc(${RICH_TOOLTIP_WIDTH} - ${numbers.CARET_INDENTATION}px)`, yTransformOrigin: 0, } ] ]); const CARET_POSITION_STYLES_RTL = new Map([ [ PositionWithCaret.BELOW_START, { yAlignment: 'top', xAlignment: 'right', yAxisPx: '0', xAxisPx: `${numbers.CARET_INDENTATION}px`, rotation: 35, skew: 20, scaleX: 0.9396926207859084, xTransformOrigin: `calc(${RICH_TOOLTIP_WIDTH} - ${numbers.CARET_INDENTATION}px)`, yTransformOrigin: 0, } ], ]); // Constant for the animationFrame mock found in setUpMdcTestEnvironment const ANIMATION_FRAME = 1; // This function assumes that the foundation has already been initialized for // interactive rich tooltips. If isRich and isInteractive have not been // initialized, the checks for interactive rich tooltips will not be called. function expectTooltipToHaveBeenShown( foundation: MDCTooltipFoundation, mockAdapter: jasmine.SpyObj<MDCTooltipAdapter>) { if (foundation.isRich() && foundation['interactiveTooltip']) { expect(mockAdapter.setAnchorAttribute) .toHaveBeenCalledWith('aria-expanded', 'true'); } expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.SHOWING); } // This function assumes that the foundation has already been initialized for // interactive rich tooltips. If isRich and isInteractive have not been // initialized, the checks for interactive rich tooltips will not be called. function expectTooltipToHaveBeenHidden( foundation: MDCTooltipFoundation, mockAdapter: jasmine.SpyObj<MDCTooltipAdapter>) { if (foundation.isRich() && foundation['interactiveTooltip']) { expect(mockAdapter.setAnchorAttribute) .toHaveBeenCalledWith('aria-expanded', 'false'); } expect(mockAdapter.setAttribute).toHaveBeenCalledWith('aria-hidden', 'true'); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.SHOWN); } // This function assumes that the foundation has already been initialized for // interactive rich tooltips. If isRich and isInteractive have not been // initialized, the checks for interactive rich tooltips will not be called. function expectTooltipNotToHaveBeenHidden( foundation: MDCTooltipFoundation, mockAdapter: jasmine.SpyObj<MDCTooltipAdapter>) { if (foundation.isRich() && foundation['interactiveTooltip']) { expect(mockAdapter.setAnchorAttribute) .not.toHaveBeenCalledWith('aria-expanded', 'false'); } expect(mockAdapter.setAttribute) .not.toHaveBeenCalledWith('aria-hidden', 'true'); expect(mockAdapter.addClass).not.toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass) .not.toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); expect(mockAdapter.removeClass).not.toHaveBeenCalledWith(CssClasses.SHOWN); } function setUpFoundationTestForRichTooltip( tooltipFoundation: typeof MDCTooltipFoundation, {isInteractive, isPersistent, hasCaret}: {isInteractive?: boolean, isPersistent?: boolean, hasCaret?: boolean} = {}) { const {foundation, mockAdapter} = setUpFoundationTest(tooltipFoundation); mockAdapter.hasClass.withArgs(CssClasses.RICH).and.returnValue(true); mockAdapter.getAttribute.withArgs(attributes.PERSISTENT) .and.returnValue(isPersistent ? 'true' : 'false'); mockAdapter.getAnchorAttribute.withArgs(attributes.ARIA_EXPANDED) .and.returnValue(isInteractive ? 'false' : null); mockAdapter.getAnchorAttribute.withArgs(attributes.ARIA_HASPOPUP) .and.returnValue(isInteractive ? 'dialog' : 'false'); mockAdapter.getAttribute.withArgs(attributes.HAS_CARET) .and.returnValue(hasCaret ? 'true' : 'false'); foundation.init(); return {foundation, mockAdapter}; } describe('MDCTooltipFoundation', () => { setUpMdcTestEnvironment(); it('default adapter returns a complete adapter implementation', () => { verifyDefaultAdapter(MDCTooltipFoundation, [ 'getAttribute', 'setAttribute', 'removeAttribute', 'addClass', 'hasClass', 'removeClass', 'getComputedStyleProperty', 'setStyleProperty', 'setSurfaceAnimationStyleProperty', 'getViewportWidth', 'getViewportHeight', 'getTooltipSize', 'getAnchorBoundingRect', 'getParentBoundingRect', 'getAnchorAttribute', 'setAnchorAttribute', 'isRTL', 'anchorContainsElement', 'tooltipContainsElement', 'focusAnchorElement', 'registerEventHandler', 'deregisterEventHandler', 'registerAnchorEventHandler', 'deregisterAnchorEventHandler', 'registerDocumentEventHandler', 'deregisterDocumentEventHandler', 'registerWindowEventHandler', 'deregisterWindowEventHandler', 'notifyHidden', 'getTooltipCaretBoundingRect', 'setTooltipCaretStyle', 'clearTooltipCaretStyles', 'getActiveElement', ]); }); it('#isRich returns false for plain tooltip', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.hasClass.withArgs(CssClasses.RICH).and.returnValue(false); foundation.init(); expect(foundation.isRich()).toBeFalse(); }); it('#isRich returns true for rich tooltip', () => { const {foundation} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); expect(foundation.isRich()).toBeTrue(); }); it('#isPersistent returns false for default rich tooltip', () => { const {foundation} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); expect(foundation.isPersistent()).toBeFalse(); }); it('#isPersistent returns true for persistent rich tooltip', () => { const {foundation} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); expect(foundation.isPersistent()).toBeTrue(); }); it('#isShown returns true if the tooltip is currently shown', () => { const {foundation} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); expect(foundation.isShown()).toBeTrue(); }); it('#isShown returns false if the tooltip is currently hidden', () => { const {foundation} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.hide(); expect(foundation.isShown()).toBeFalse(); }); it('#show modifies tooltip element so it is shown', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.SHOWING); }); it('#show does not set aria-expanded="true" on anchor element for non-interactive rich tooltip', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); expect(mockAdapter.setAnchorAttribute) .not.toHaveBeenCalledWith('aria-expanded', 'true'); }); it('#show sets aria-expanded="true" on anchor element for interactive rich tooltip', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isInteractive: true}); foundation.show(); expect(mockAdapter.setAnchorAttribute) .toHaveBeenCalledWith('aria-expanded', 'true'); }); it('#show adds SHOWN and SHOWN_TRANSITION class after rAF', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); expect(mockAdapter.addClass).not.toHaveBeenCalledWith(CssClasses.SHOWN); expect(mockAdapter.addClass) .not.toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); jasmine.clock().tick(1); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.SHOWN); expect(mockAdapter.addClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); }); it('#hide cancels a pending rAF', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.hide(); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.SHOWING); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); jasmine.clock().tick(1); expect(mockAdapter.addClass).not.toHaveBeenCalledWith(CssClasses.SHOWN); expect(mockAdapter.addClass) .not.toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); }); it('#show registers mouseenter event listener on the tooltip for rich tooltip', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); expect(mockAdapter.registerEventHandler) .toHaveBeenCalledWith('mouseenter', jasmine.any(Function)); }); it('#show registers mouseleave event listener on the tooltip for rich tooltip', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); expect(mockAdapter.registerEventHandler) .toHaveBeenCalledWith('mouseleave', jasmine.any(Function)); }); it('#hide deregisters mouseenter event listeners on the tooltip for rich tooltip', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); foundation.hide(); expect(mockAdapter.deregisterEventHandler) .toHaveBeenCalledWith('mouseenter', jasmine.any(Function)); }); it('#hide deregisters mouseleave event listeners on the tooltip for rich tooltip', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); foundation.hide(); expect(mockAdapter.deregisterEventHandler) .toHaveBeenCalledWith('mouseleave', jasmine.any(Function)); }); it('#show registers blur event listener on the anchor element', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); expect(mockAdapter.registerAnchorEventHandler) .toHaveBeenCalledWith('blur', jasmine.any(Function)); }); it('#show registers click and keydown event listeners on the document', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); expect(mockAdapter.registerDocumentEventHandler) .toHaveBeenCalledWith('click', jasmine.any(Function)); expect(mockAdapter.registerDocumentEventHandler) .toHaveBeenCalledWith('keydown', jasmine.any(Function)); }); it('#hide deregisters blur event listeners on the anchor', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.hide(); expect(mockAdapter.deregisterAnchorEventHandler) .toHaveBeenCalledWith('blur', jasmine.any(Function)); }); it('#hide deregisters click and keydown event listeners on the document', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.hide(); expect(mockAdapter.deregisterDocumentEventHandler) .toHaveBeenCalledWith('click', jasmine.any(Function)); expect(mockAdapter.deregisterDocumentEventHandler) .toHaveBeenCalledWith('keydown', jasmine.any(Function)); }); it('#show registers scroll and resize event listeners on the window', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); expect(mockAdapter.registerWindowEventHandler) .toHaveBeenCalledWith('scroll', jasmine.any(Function)); expect(mockAdapter.registerWindowEventHandler) .toHaveBeenCalledWith('resize', jasmine.any(Function)); }); it('#hide deregisters scroll and resize event listeners on the window', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.hide(); expect(mockAdapter.deregisterWindowEventHandler) .toHaveBeenCalledWith('scroll', jasmine.any(Function)); expect(mockAdapter.deregisterWindowEventHandler) .toHaveBeenCalledWith('resize', jasmine.any(Function)); }); it('#hide modifies tooltip element so it is hidden', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.hide(); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.SHOWN); }); it('#show only performs an action if tooltip is hidden', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.show(); expect(mockAdapter.addClass).toHaveBeenCalledTimes(1); }); it('#show cancels a pending hideTimeout', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.handleAnchorMouseLeave(); expect((foundation as any).hideTimeout).not.toEqual(null); foundation.show(); expect((foundation as any).hideTimeout).toEqual(null); jasmine.clock().tick(numbers.HIDE_DELAY_MS); expect(mockAdapter.addClass).not.toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass) .not.toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); }); it('#hide only performs an action if tooltip is shown', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.hide(); expect(mockAdapter.setAttribute).not.toHaveBeenCalled(); expect(mockAdapter.removeClass).not.toHaveBeenCalled(); }); it('#handleTransitionEnd removes the SHOWING, SHOWING_TRANSITION, HIDE, and HIDE_TRANSITION classes', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleTransitionEnd(); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.SHOWING); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); }); it('#handleTransitionEnd after #hide sends notification that tooltip has been hidden', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.hasClass.and.returnValue(true); foundation.show(); foundation.hide(); foundation.handleTransitionEnd(); expect(mockAdapter.hasClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.SHOWING); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); expect(mockAdapter.notifyHidden).toHaveBeenCalled(); }); it('#handleTransitionEnd after #show does not send notification that tooltip has been hidden', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.handleTransitionEnd(); expect(mockAdapter.hasClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.SHOWING); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); expect(mockAdapter.notifyHidden).not.toHaveBeenCalled(); }); it('clears any in-progress animations befores starting a show animation', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); jasmine.clock().tick(1); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.SHOWN); expect(mockAdapter.addClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); }); it('clears any in-progress animations befores starting a hide animation', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.hide(); jasmine.clock().tick(1); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); }); for (const evt of ESC_EVENTS) { it(`#handleKeydown(${evt}) hides tooltip`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.handleKeydown(evt); expect((foundation as any).hideTimeout).toEqual(null); expect(mockAdapter.setAttribute) .toHaveBeenCalledWith('aria-hidden', 'true'); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.SHOWN); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); expect(mockAdapter.deregisterDocumentEventHandler) .toHaveBeenCalledWith('click', jasmine.any(Function)); expect(mockAdapter.deregisterDocumentEventHandler) .toHaveBeenCalledWith('keydown', jasmine.any(Function)); }); } it('#handleKeydown does not hide the tooltip if the ESCAPE key was not pressed', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.hide = jasmine.createSpy('hide'); foundation.show(); foundation.handleKeydown( {type: 'keydown', key: 'Space'} as KeyboardEvent); expectTooltipNotToHaveBeenHidden(foundation, mockAdapter); }); it('#handleKeydown does not restore focus to the anchorElement if the activeElement is not a HTMLElement', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getActiveElement.and.returnValue(null); foundation.handleKeydown( {type: 'keydown', key: 'Escape'} as KeyboardEvent); expect(mockAdapter.focusAnchorElement).not.toHaveBeenCalled(); }); it('#handleKeydown does not restore focus to the anchorElement if the activeElement is not within tooltip', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.tooltipContainsElement.and.returnValue(false); document.body.focus(); foundation.handleKeydown( {type: 'keydown', key: 'Escape'} as KeyboardEvent); expect(mockAdapter.focusAnchorElement).not.toHaveBeenCalled(); }); it('#handleKeydown restores focus to the anchorElement if the activeElement was within tooltip', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); const activeElement = document.createElement('div'); mockAdapter.getActiveElement.and.returnValue(activeElement); mockAdapter.tooltipContainsElement.and.returnValue(true); document.body.focus(); foundation.handleKeydown( {type: 'keydown', key: 'Escape'} as KeyboardEvent); expect(mockAdapter.tooltipContainsElement) .toHaveBeenCalledWith(activeElement); expect(mockAdapter.focusAnchorElement).toHaveBeenCalled(); }); it('#handleDocumentClick hides the tooltip immediately for plain tooltips', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); const mockClickEvent = createMouseEvent('click'); foundation.show(); foundation.handleDocumentClick(mockClickEvent); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it('#handleDocumentClick hides the tooltip immediately for default rich tooltips', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); const mockClickEvent = createMouseEvent('click'); foundation.show(); foundation.handleDocumentClick(mockClickEvent); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it('#handleDocumentClick hides the tooltip immediately for persistent rich tooltips if there is no event target', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); const mockClickEvent = createMouseEvent('click'); foundation.show(); foundation.handleDocumentClick(mockClickEvent); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it('#handleDocumentClick hides the tooltip immediately for persistent rich tooltips if event target is not HTMLElement', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); const mockClickEvent = { ...createMouseEvent('click'), target: 'not an HTMLElement' } as unknown as MouseEvent; foundation.show(); foundation.handleDocumentClick(mockClickEvent); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it('#handleDocumentClick hides the tooltip immediately for persistent rich tooltips if event target is not within anchorElement or tooltipElement', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); mockAdapter.anchorContainsElement.and.returnValue(false); mockAdapter.tooltipContainsElement.and.returnValue(false); const mockClickEvent = { ...createMouseEvent('click'), target: document.createElement('div') }; foundation.show(); foundation.handleDocumentClick(mockClickEvent); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it('#handleDocumentClick does not hide the tooltip for persistent rich tooltips if event target is within anchorElement', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); mockAdapter.anchorContainsElement.and.returnValue(true); mockAdapter.tooltipContainsElement.and.returnValue(false); const mockClickEvent = { ...createMouseEvent('click'), target: document.createElement('div') }; foundation.show(); foundation.handleDocumentClick(mockClickEvent); expectTooltipNotToHaveBeenHidden(foundation, mockAdapter); }); it('#handleDocumentClick does not hide the tooltip for persistent rich tooltips if event target is within tooltipElement', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); mockAdapter.anchorContainsElement.and.returnValue(false); mockAdapter.tooltipContainsElement.and.returnValue(true); const mockClickEvent = { ...createMouseEvent('click'), target: document.createElement('div') }; foundation.show(); foundation.handleDocumentClick(mockClickEvent); expectTooltipNotToHaveBeenHidden(foundation, mockAdapter); }); it(`#handleAnchorMouseLeave hides the tooltip after a ${ numbers.HIDE_DELAY_MS}ms delay`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); foundation.handleAnchorMouseLeave(); expect((foundation as any).hideTimeout).not.toEqual(null); jasmine.clock().tick(numbers.HIDE_DELAY_MS); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it('#handleAnchorMouseLeave does not clear showTimeout after #handleAnchorMouseEnter is called', () => { const {foundation} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorMouseLeave(); jasmine.clock().tick(numbers.HIDE_DELAY_MS / 2); foundation.handleAnchorMouseEnter(); jasmine.clock().tick(numbers.HIDE_DELAY_MS / 2); expect((foundation as any).showTimeout).not.toEqual(null); }); it(`#handleAnchorBlur hides the tooltip immediately for plain tooltips`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); (foundation as any).handleAnchorBlur(); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it(`#handleAnchorBlur hides the tooltip immediately when focus changes to non-HTMLElement related target for default rich tooltips`, () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); (foundation as any).handleAnchorBlur({}); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it(`#handleAnchorBlur hides the tooltip immediately when focus changes to related target not within tooltip for default rich tooltips`, () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); mockAdapter.tooltipContainsElement.and.returnValue(false); const mockFocusEvent = {relatedTarget: document.createElement('div')}; foundation.show(); (foundation as any).handleAnchorBlur(mockFocusEvent); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it(`#handleAnchorBlur doesn't hide the tooltip when focus changes to related target not within tooltip for default rich tooltips`, () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); mockAdapter.tooltipContainsElement.and.returnValue(true); const mockFocusEvent = {relatedTarget: document.createElement('div')}; foundation.show(); (foundation as any).handleAnchorBlur(mockFocusEvent); expectTooltipNotToHaveBeenHidden(foundation, mockAdapter); }); it(`#handleAnchorBlur hides the tooltip immediately when focus changes to non-HTMLElement related target for persistent rich tooltips`, () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); foundation.show(); (foundation as any).handleAnchorBlur({}); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it(`#handleAnchorBlur hides the tooltip immediately when focus changes to related target not within tooltip for persistent rich tooltips`, () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); mockAdapter.tooltipContainsElement.and.returnValue(false); const mockFocusEvent = {relatedTarget: document.createElement('div')}; foundation.show(); (foundation as any).handleAnchorBlur(mockFocusEvent); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it(`#handleAnchorBlur doesn't hide the tooltip when focus changes to related target within tooltip for persistent rich tooltips`, () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); mockAdapter.tooltipContainsElement.and.returnValue(true); const mockFocusEvent = {relatedTarget: document.createElement('div')}; foundation.show(); (foundation as any).handleAnchorBlur(mockFocusEvent); expectTooltipNotToHaveBeenHidden(foundation, mockAdapter); }); it(`#handleDocumentClick hides the tooltip immediately`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); const mockClickEvent = createMouseEvent('click'); foundation.show(); foundation.handleDocumentClick(mockClickEvent); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it(`#handleAnchorMouseEnter shows the tooltip after a ${ numbers.SHOW_DELAY_MS}ms delay`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorMouseEnter(); expect((foundation as any).showTimeout).not.toEqual(null); jasmine.clock().tick(numbers.SHOW_DELAY_MS); expectTooltipToHaveBeenShown(foundation, mockAdapter); }); it('#handleAnchorMouseEnter clears any pending hideTimeout', () => { const {foundation} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorMouseLeave(); expect((foundation as any).hideTimeout).not.toEqual(null); foundation.handleAnchorMouseEnter(); expect((foundation as any).hideTimeout).toEqual(null); }); it(`#handleAnchorFocus shows the tooltip after a ${ numbers.SHOW_DELAY_MS}ms delay if relatedTarget is not a HTMLElement`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorFocus({relatedTarget: null} as FocusEvent); expect((foundation as any).showTimeout).not.toEqual(null); jasmine.clock().tick(numbers.SHOW_DELAY_MS); expectTooltipToHaveBeenShown(foundation, mockAdapter); }); it(`#handleAnchorFocus shows the tooltip if the relatedTarget is not within tooltip`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.tooltipContainsElement.and.returnValue(false); foundation.handleAnchorFocus( {relatedTarget: document.createElement('div')} as unknown as FocusEvent); expect((foundation as any).showTimeout).not.toEqual(null); jasmine.clock().tick(numbers.SHOW_DELAY_MS); expectTooltipToHaveBeenShown(foundation, mockAdapter); }); it(`#handleAnchorFocus doesn't show the tooltip if the relatedTarget is within tooltip`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.tooltipContainsElement.and.returnValue(true); foundation.handleAnchorFocus( {relatedTarget: document.createElement('div')} as unknown as FocusEvent); expect((foundation as any).showTimeout).toEqual(null); jasmine.clock().tick(numbers.SHOW_DELAY_MS); expect(mockAdapter.removeAttribute) .not.toHaveBeenCalledWith('aria-hidden'); expect(mockAdapter.removeClass) .not.toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass) .not.toHaveBeenCalledWith(CssClasses.SHOWING); }); it(`#handleAnchorClick shows the tooltip immediately when tooltip is hidden for persistent rich tooltips`, () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); expect(foundation.isShown()).toBeFalse(); foundation.handleAnchorClick(); expectTooltipToHaveBeenShown(foundation, mockAdapter); }); it(`#handleAnchorClick hides the tooltip immediately when tooltip is shown for persistent rich tooltips`, () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); foundation.show(); foundation.handleAnchorClick(); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it(`#handleTooltipMouseEnter shows plain tooltips immediately`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); (foundation as any).handleTooltipMouseEnter(); expectTooltipToHaveBeenShown(foundation, mockAdapter); }); it(`#handleTooltipMouseLeave hides plain tooltips after a ${ numbers.HIDE_DELAY_MS}ms delay`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); (foundation as any).handleTooltipMouseLeave(); expect((foundation as any).hideTimeout).not.toEqual(null); jasmine.clock().tick(numbers.HIDE_DELAY_MS); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it('#handleTooltipMouseLeave clears any pending showTimeout for plain tooltips', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorMouseEnter(); expect((foundation as any).showTimeout).not.toEqual(null); (foundation as any).handleTooltipMouseLeave(); expect((foundation as any).showTimeout).toEqual(null); jasmine.clock().tick(numbers.SHOW_DELAY_MS); expect(mockAdapter.removeAttribute) .not.toHaveBeenCalledWith('aria-hidden'); expect(mockAdapter.removeClass) .not.toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass) .not.toHaveBeenCalledWith(CssClasses.SHOWING); }); it(`#handleTooltipMouseEnter shows rich tooltips immediately`, () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); (foundation as any).handleTooltipMouseEnter(); expectTooltipToHaveBeenShown(foundation, mockAdapter); }); it(`#handleTooltipMouseLeave hides rich tooltips after a ${ numbers.HIDE_DELAY_MS}ms delay`, () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); (foundation as any).handleTooltipMouseLeave(); expect((foundation as any).hideTimeout).not.toEqual(null); jasmine.clock().tick(numbers.HIDE_DELAY_MS); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it('#handleTooltipMouseLeave clears any pending showTimeout for rich tooltips', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.handleAnchorMouseEnter(); expect((foundation as any).showTimeout).not.toEqual(null); (foundation as any).handleTooltipMouseLeave(); expect((foundation as any).showTimeout).toEqual(null); jasmine.clock().tick(numbers.SHOW_DELAY_MS); expect(mockAdapter.removeAttribute) .not.toHaveBeenCalledWith('aria-hidden'); expect(mockAdapter.removeClass) .not.toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass) .not.toHaveBeenCalledWith(CssClasses.SHOWING); }); it('#handleRichTooltipFocusOut hides the tooltip immediately if there is no related target', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); (foundation as any).handleRichTooltipFocusOut({}); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it('#handleRichTooltipFocusOut leaves tooltip open if related target is null and tooltip is interactive', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isInteractive: true}); foundation.show(); (foundation as any).handleRichTooltipFocusOut({relatedTarget: null}); expectTooltipNotToHaveBeenHidden(foundation, mockAdapter); }); it('#handleRichTooltipFocusOut hides the tooltip immediately if related target is null and tooltip is not interactive', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); (foundation as any).handleRichTooltipFocusOut({relatedTarget: null}); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it('#handleRichTooltipFocusOut hides the tooltip immediately if related target is not within the anchor or the tooltip', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); mockAdapter.anchorContainsElement.and.returnValue(false); mockAdapter.tooltipContainsElement.and.returnValue(false); (foundation as any).handleRichTooltipFocusOut({ relatedTarget: document.createElement('div') }); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); it('#handleRichTooltipFocusOut does not hide the tooltip if related target is within the anchor', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); mockAdapter.anchorContainsElement.and.returnValue(true); mockAdapter.tooltipContainsElement.and.returnValue(false); (foundation as any).handleRichTooltipFocusOut({ relatedTarget: document.createElement('div') }); expectTooltipNotToHaveBeenHidden(foundation, mockAdapter); }); it('#handleRichTooltipFocusOut does not hide the tooltip if related target is within the tooltip', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.show(); mockAdapter.anchorContainsElement.and.returnValue(false); mockAdapter.tooltipContainsElement.and.returnValue(true); (foundation as any).handleRichTooltipFocusOut({ relatedTarget: document.createElement('div') }); expectTooltipNotToHaveBeenHidden(foundation, mockAdapter); }); it(`does not re-animate a tooltip already shown in the dom (from focus)`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorFocus({relatedTarget: null} as FocusEvent); jasmine.clock().tick(numbers.SHOW_DELAY_MS); foundation.handleAnchorMouseLeave(); jasmine.clock().tick(numbers.HIDE_DELAY_MS / 2); foundation.handleAnchorFocus({relatedTarget: null} as FocusEvent); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); expect(mockAdapter.removeClass).toHaveBeenCalledTimes(3); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.SHOWING); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.SHOWN); expect(mockAdapter.addClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); expect(mockAdapter.addClass).toHaveBeenCalledTimes(3); }); it(`does not re-animate a tooltip already shown in the dom (from mouseenter)`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorMouseEnter(); jasmine.clock().tick(numbers.SHOW_DELAY_MS); foundation.handleAnchorMouseLeave(); jasmine.clock().tick(numbers.HIDE_DELAY_MS / 2); foundation.handleAnchorMouseEnter(); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); expect(mockAdapter.removeClass).toHaveBeenCalledTimes(3); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.SHOWING); expect(mockAdapter.addClass).toHaveBeenCalledWith(CssClasses.SHOWN); expect(mockAdapter.addClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); expect(mockAdapter.addClass).toHaveBeenCalledTimes(3); }); it('#handleAnchorMouseLeave clears any pending showTimeout', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorMouseEnter(); expect((foundation as any).showTimeout).not.toEqual(null); foundation.handleAnchorMouseLeave(); expect((foundation as any).showTimeout).toEqual(null); jasmine.clock().tick(numbers.SHOW_DELAY_MS); expect(mockAdapter.removeAttribute).not.toHaveBeenCalledWith('aria-hidden'); expect(mockAdapter.removeClass).not.toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass).not.toHaveBeenCalledWith(CssClasses.SHOWING); }); it('#handleTooltipMouseEnter keeps tooltip visible', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.handleAnchorMouseLeave(); expect((foundation as any).hideTimeout).not.toEqual(null); (foundation as any).handleTooltipMouseEnter(); expect((foundation as any).hideTimeout).toEqual(null); expect(mockAdapter.setAttribute) .not.toHaveBeenCalledWith('aria-hidden', 'true'); expect(foundation.isShown()).toBeTrue(); }); it('#hide clears any pending showTimeout', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorMouseEnter(); expect((foundation as any).showTimeout).not.toEqual(null); foundation.hide(); expect((foundation as any).showTimeout).toEqual(null); jasmine.clock().tick(numbers.SHOW_DELAY_MS); expect(mockAdapter.removeAttribute).not.toHaveBeenCalledWith('aria-hidden'); expect(mockAdapter.removeClass).not.toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass).not.toHaveBeenCalledWith(CssClasses.SHOWING); }); it(`#handleAnchorTouchstart shows a tooltip if the user long-presses for ${ numbers.SHOW_DELAY_MS}ms`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorTouchstart(); jasmine.clock().tick(numbers.SHOW_DELAY_MS); expectTooltipToHaveBeenShown(foundation, mockAdapter); }); it(`#handleAnchorTouchstart adds event handler for "contextmenu" event`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorTouchstart(); expect(mockAdapter.registerWindowEventHandler) .toHaveBeenCalledWith('contextmenu', jasmine.any(Function)); }); it(`#handleAnchorTouchend clears any pending showTimeout`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorTouchstart(); expect((foundation as any).showTimeout).not.toEqual(null); foundation.handleAnchorTouchend(); expect((foundation as any).showTimeout).toEqual(null); jasmine.clock().tick(numbers.SHOW_DELAY_MS); expect(mockAdapter.removeAttribute).not.toHaveBeenCalledWith('aria-hidden'); expect(mockAdapter.removeClass).not.toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.addClass).not.toHaveBeenCalledWith(CssClasses.SHOWING); }); it(`#handleAnchorTouchend removes event handler for "contextmenu" event if tooltip is not shown`, () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorTouchstart(); foundation.handleAnchorTouchend(); expect(mockAdapter.registerWindowEventHandler) .toHaveBeenCalledWith('contextmenu', jasmine.any(Function)); expect(mockAdapter.deregisterWindowEventHandler) .toHaveBeenCalledWith('contextmenu', jasmine.any(Function)); }); it('#hide deregisters "contextmenu" event listeners on the window', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorTouchstart(); jasmine.clock().tick(numbers.SHOW_DELAY_MS); foundation.hide(); expect(mockAdapter.deregisterWindowEventHandler) .toHaveBeenCalledWith('contextmenu', jasmine.any(Function)); }); it('properly calculates tooltip position (START alignment)', () => { const anchorHeight = 35; const expectedTooltipHeight = anchorHeight + numbers.BOUNDED_ANCHOR_GAP; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue({ top: 0, bottom: anchorHeight, left: 32, right: 82, width: 50, height: anchorHeight }); mockAdapter.getTooltipSize.and.returnValue({width: 100, height: 30}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipHeight}px`); expect(mockAdapter.setStyleProperty).toHaveBeenCalledWith('left', `32px`); }); it('properly sets tooltip transform origin (left top)', () => { const anchorHeight = 35; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue({ top: 0, bottom: anchorHeight, left: 32, right: 82, width: 50, height: anchorHeight }); mockAdapter.getTooltipSize.and.returnValue({width: 100, height: 30}); foundation.show(); expect(mockAdapter.setSurfaceAnimationStyleProperty) .toHaveBeenCalledWith('transform-origin', 'left top'); }); it('properly calculates tooltip position (END alignment)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 400, right: 450, width: 50, height: 35}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP; const tooltipSize = {width: 100, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(480); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty).toHaveBeenCalledWith('left', `350px`); }); it('properly sets tooltip transform origin (right top)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 400, right: 450, width: 50, height: 35}; const tooltipSize = {width: 100, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(480); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.show(); expect(mockAdapter.setSurfaceAnimationStyleProperty) .toHaveBeenCalledWith('transform-origin', 'right top'); }); it('properly calculates tooltip position (CENTER alignment)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 0, right: 200, width: 200, height: 35}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP; const tooltipSize = {width: 40, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty).toHaveBeenCalledWith('left', `80px`); }); it('properly sets tooltip transform origin (center top)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 0, right: 200, width: 200, height: 35}; const tooltipSize = {width: 40, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.show(); expect(mockAdapter.setSurfaceAnimationStyleProperty) .toHaveBeenCalledWith('transform-origin', 'center top'); }); it('properly calculates tooltip position with an UNBOUNDED anchor', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 0, width: 200, height: 35} as ClientRect; const expectedTooltipTop = anchorBoundingRect.height + numbers.UNBOUNDED_ANCHOR_GAP; const tooltipSize = {width: 40, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.setAnchorBoundaryType(AnchorBoundaryType.UNBOUNDED); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty).toHaveBeenCalledWith('left', `80px`); }); it('sets width of rich tooltip after positioning', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); const testWidth = '50px'; mockAdapter.getComputedStyleProperty.and.returnValue(testWidth); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('width', testWidth); }); it('properly calculates rich tooltip position (START alignment)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 100, right: 150, width: 50, height: 35}; const parentBoundingRect = {top: 5, bottom: 35, left: 0, right: 50, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP - parentBoundingRect.top; const expectedTooltipLeft = anchorBoundingRect.left - tooltipSize.width - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(150); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly sets rich tooltip transform origin (right top)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 100, right: 150, width: 50, height: 35}; const parentBoundingRect = {top: 5, bottom: 35, left: 0, right: 50, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(150); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.show(); expect(mockAdapter.setSurfaceAnimationStyleProperty) .toHaveBeenCalledWith('transform-origin', 'right top'); }); it('properly calculates rich tooltip position (END alignment)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 0, right: 50, width: 50, height: 35}; const parentBoundingRect = {top: 5, bottom: 35, left: 0, right: 50, width: 50, height: 30}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP - parentBoundingRect.top; const expectedTooltipLeft = anchorBoundingRect.right - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(150); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates rich tooltip transform origin (left top)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 0, right: 50, width: 50, height: 35}; const parentBoundingRect = {top: 5, bottom: 35, left: 0, right: 50, width: 50, height: 30}; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(150); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); foundation.show(); expect(mockAdapter.setSurfaceAnimationStyleProperty) .toHaveBeenCalledWith('transform-origin', 'left top'); }); it('allows users to specify the tooltip position for plain tooltips (START alignment instead of CENTER)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 32, right: 232, width: 200, height: 35}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP; const tooltipSize = {width: 40, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.setTooltipPosition({xPos: XPosition.START}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `32px`); }); it('ignores user specification if positioning violates threshold for plain tooltips (CENTER alignment instead of START)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 0, right: 200, width: 200, height: 35}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP; const tooltipSize = {width: 40, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.setTooltipPosition({xPos: XPosition.START}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `80px`); }); it('allows users to specify the tooltip position for plain tooltips (END alignment instead of START)', () => { const anchorHeight = 35; const expectedTooltipHeight = anchorHeight + numbers.BOUNDED_ANCHOR_GAP; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue({ top: 0, bottom: anchorHeight, left: 0, right: 100, width: 100, height: anchorHeight }); mockAdapter.getTooltipSize.and.returnValue({width: 50, height: 30}); foundation.setTooltipPosition({xPos: XPosition.END}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipHeight}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `50px`); }); it('allows users to specify the tooltip position for rich tooltips (END alignment instead of START)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 132, right: 232, width: 100, height: 35}; const parentBoundingRect = {top: 5, bottom: 35, left: 0, right: 50, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP - parentBoundingRect.top; const expectedTooltipLeft = anchorBoundingRect.left - tooltipSize.width - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.setTooltipPosition({xPos: XPosition.START}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('ignores user specification if positioning violates threshold for rich tooltips (END alignment instead of START)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 0, right: 200, width: 200, height: 35}; const parentBoundingRect = {top: 5, bottom: 35, left: 0, right: 50, width: 50, height: 30}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP - parentBoundingRect.top; const expectedTooltipLeft = anchorBoundingRect.right - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); foundation.setTooltipPosition({xPos: XPosition.START}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('ignores user specification if positioning is not supported for rich tooltips (END alignment instead of CENTER)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 0, right: 100, width: 100, height: 35}; const parentBoundingRect = {top: 5, bottom: 35, left: 0, right: 50, width: 50, height: 30}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP - parentBoundingRect.top; const expectedTooltipLeft = anchorBoundingRect.right - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); foundation.setTooltipPosition({xPos: XPosition.CENTER}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates START tooltip position in RTL', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 0, right: 100, width: 100, height: 35}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP; const tooltipSize = {width: 50, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.isRTL.and.returnValue(true); foundation.setTooltipPosition({xPos: XPosition.START}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty).toHaveBeenCalledWith('left', `50px`); }); it('properly calculates "right top" transform origin in RTL', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 0, right: 100, width: 100, height: 35}; const tooltipSize = {width: 50, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.isRTL.and.returnValue(true); foundation.setTooltipPosition({xPos: XPosition.START}); foundation.show(); expect(mockAdapter.setSurfaceAnimationStyleProperty) .toHaveBeenCalledWith('transform-origin', 'right top'); }); it('properly calculates END tooltip position in RTL', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 32, right: 132, width: 100, height: 35}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP; const tooltipSize = {width: 50, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.isRTL.and.returnValue(true); foundation.setTooltipPosition({xPos: XPosition.END}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty).toHaveBeenCalledWith('left', `32px`); }); it('properly calculates "left top" transform origin in RTL', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 32, right: 132, width: 100, height: 35}; const tooltipSize = {width: 50, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.isRTL.and.returnValue(true); foundation.setTooltipPosition({xPos: XPosition.END}); foundation.show(); expect(mockAdapter.setSurfaceAnimationStyleProperty) .toHaveBeenCalledWith('transform-origin', 'left top'); }); it('positions tooltip within viewport if threshold cannot be maintained (x-axis)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 450, right: 500, width: 50, height: 35}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP; const tooltipSize = {width: 100, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `400px`); }); it('allows users to specify a position within viewport if threshold cannot be maintained (START alignment instead of CENTER)', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 10, right: 60, width: 50, height: 35}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP; const tooltipSize = {width: 60, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.setTooltipPosition({xPos: XPosition.START}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `10px`); }); it('properly calculates tooltip y-position (ABOVE alignment)', () => { const anchorBoundingRect = {top: 100, bottom: 125, left: 10, right: 60, width: 50, height: 25}; const tooltipSize = {width: 60, height: 20}; const expectedTooltipTop = anchorBoundingRect.top - (numbers.BOUNDED_ANCHOR_GAP + tooltipSize.height); const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getViewportHeight.and.returnValue(300); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.setTooltipPosition({yPos: YPosition.ABOVE}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); }); it('properly calculates tooltip transform origin (left bottom)', () => { const anchorBoundingRect = {top: 100, bottom: 125, left: 10, right: 60, width: 50, height: 25}; const tooltipSize = {width: 60, height: 20}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getViewportHeight.and.returnValue(300); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.setTooltipPosition({yPos: YPosition.ABOVE}); foundation.show(); expect(mockAdapter.setSurfaceAnimationStyleProperty) .toHaveBeenCalledWith('transform-origin', 'left bottom'); }); it('properly calculates tooltip y-position (BELOW alignment)', () => { const anchorBoundingRect = {top: 100, bottom: 125, left: 10, right: 60, width: 50, height: 25}; const tooltipSize = {width: 60, height: 20}; const expectedTooltipTop = anchorBoundingRect.bottom + numbers.BOUNDED_ANCHOR_GAP; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getViewportHeight.and.returnValue(300); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.setTooltipPosition({yPos: YPosition.BELOW}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); }); it('positions tooltip within viewport if threshold cannot be maintained (y-axis)', () => { const anchorBoundingRect = {top: 0, bottom: 30, left: 450, right: 500, width: 50} as ClientRect; const expectedTooltipTop = anchorBoundingRect.bottom + numbers.BOUNDED_ANCHOR_GAP; const tooltipSize = {width: 100, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportHeight.and.returnValue(70); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); }); it('ignores user specification if positioning violates threshold (BELOW alignment instead of ABOVE)', () => { const anchorBoundingRect = {top: 40, bottom: 70, left: 450, right: 500, width: 50} as ClientRect; const tooltipSize = {width: 100, height: 30}; const expectedTooltipTop = anchorBoundingRect.bottom + numbers.BOUNDED_ANCHOR_GAP; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportHeight.and.returnValue(140); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.setTooltipPosition({yPos: YPosition.ABOVE}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); }); it('allows users to specify a position within viewport if threshold cannot be maintained (ABOVE alignment instead of BELOW)', () => { const anchorBoundingRect = {top: 40, bottom: 70, left: 450, right: 500, width: 50} as ClientRect; const tooltipSize = {width: 100, height: 30}; const expectedTooltipTop = anchorBoundingRect.top - (numbers.BOUNDED_ANCHOR_GAP + tooltipSize.height); const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportHeight.and.returnValue(110); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.setTooltipPosition({yPos: YPosition.ABOVE}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); }); it('#destroy clears showTimeout', () => { const {foundation} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorMouseEnter(); foundation.destroy(); expect((foundation as any).showTimeout).toEqual(null); }); it('#destroy clears requestAnimationFrame from show', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.show(); expect(foundation['frameId']).not.toEqual(null); foundation.destroy(); jasmine.clock().tick(ANIMATION_FRAME); expect(foundation['frameId']).toEqual(null); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); // 1 call from show and 5 calls from destroy expect(mockAdapter.removeClass).toHaveBeenCalledTimes(6); expect(mockAdapter.addClass).not.toHaveBeenCalledWith(CssClasses.SHOWN); expect(mockAdapter.addClass) .not.toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); }); it('#destroy clears hideTimeout', () => { const {foundation} = setUpFoundationTest(MDCTooltipFoundation); foundation.handleAnchorMouseLeave(); foundation.destroy(); expect((foundation as any).hideTimeout).toEqual(null); }); it('#destroy removes tooltip classes', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.destroy(); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.SHOWN); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.SHOWING_TRANSITION); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.SHOWING); expect(mockAdapter.removeClass).toHaveBeenCalledWith(CssClasses.HIDE); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(CssClasses.HIDE_TRANSITION); }); it('#destroy cancels all animation frame requests', () => { const {foundation} = setUpFoundationTest(MDCTooltipFoundation); (foundation as any).handleWindowChangeEvent(); foundation.destroy(); expect(foundation['animFrame']['rafIDs'].size).toEqual(0); }); it('#destroy removes the event listeners for plain tooltips', () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.destroy(); expect(mockAdapter.deregisterEventHandler) .toHaveBeenCalledWith('mouseenter', jasmine.any(Function)); expect(mockAdapter.deregisterEventHandler) .toHaveBeenCalledWith('mouseleave', jasmine.any(Function)); expect(mockAdapter.deregisterEventHandler) .not.toHaveBeenCalledWith('focusout', jasmine.any(Function)); expect(mockAdapter.deregisterDocumentEventHandler) .toHaveBeenCalledWith('click', jasmine.any(Function)); expect(mockAdapter.deregisterDocumentEventHandler) .toHaveBeenCalledWith('keydown', jasmine.any(Function)); expect(mockAdapter.deregisterWindowEventHandler) .toHaveBeenCalledWith('scroll', jasmine.any(Function)); expect(mockAdapter.deregisterWindowEventHandler) .toHaveBeenCalledWith('resize', jasmine.any(Function)); expect(mockAdapter.deregisterAnchorEventHandler) .toHaveBeenCalledWith('blur', jasmine.any(Function)); }); it('#destroy removes the event listeners for default rich tooltips', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip(MDCTooltipFoundation); foundation.destroy(); expect(mockAdapter.deregisterEventHandler) .toHaveBeenCalledWith('focusout', jasmine.any(Function)); expect(mockAdapter.deregisterEventHandler) .toHaveBeenCalledWith('mouseenter', jasmine.any(Function)); expect(mockAdapter.deregisterEventHandler) .toHaveBeenCalledWith('mouseleave', jasmine.any(Function)); expect(mockAdapter.deregisterDocumentEventHandler) .toHaveBeenCalledWith('click', jasmine.any(Function)); expect(mockAdapter.deregisterDocumentEventHandler) .toHaveBeenCalledWith('keydown', jasmine.any(Function)); expect(mockAdapter.deregisterWindowEventHandler) .toHaveBeenCalledWith('scroll', jasmine.any(Function)); expect(mockAdapter.deregisterWindowEventHandler) .toHaveBeenCalledWith('resize', jasmine.any(Function)); }); it('#destroy removes the event listeners for persistent rich tooltips', () => { const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); foundation.destroy(); expect(mockAdapter.deregisterEventHandler) .toHaveBeenCalledWith('focusout', jasmine.any(Function)); expect(mockAdapter.deregisterEventHandler) .not.toHaveBeenCalledWith('mouseenter', jasmine.any(Function)); expect(mockAdapter.deregisterEventHandler) .not.toHaveBeenCalledWith('mouseleave', jasmine.any(Function)); expect(mockAdapter.deregisterDocumentEventHandler) .toHaveBeenCalledWith('click', jasmine.any(Function)); expect(mockAdapter.deregisterDocumentEventHandler) .toHaveBeenCalledWith('keydown', jasmine.any(Function)); expect(mockAdapter.deregisterWindowEventHandler) .toHaveBeenCalledWith('scroll', jasmine.any(Function)); expect(mockAdapter.deregisterWindowEventHandler) .toHaveBeenCalledWith('resize', jasmine.any(Function)); }); it('recalculates position of tooltip if anchor position changes', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 0, right: 200, width: 200, height: 35}; const expectedTooltipTop = anchorBoundingRect.height + numbers.BOUNDED_ANCHOR_GAP; const expectedTooltipLeft = 80; const tooltipSize = {width: 40, height: 30}; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); mockAdapter.getViewportWidth.and.returnValue(500); mockAdapter.getViewportHeight.and.returnValue(500); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.registerWindowEventHandler.and.callFake( (ev: string, handler: EventListener) => { window.addEventListener(ev, handler); }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); const yPositionDiff = 50; const xPositionDiff = 20; const newAnchorBoundingRect = { top: anchorBoundingRect.top + yPositionDiff, bottom: anchorBoundingRect.bottom + yPositionDiff, left: anchorBoundingRect.left + xPositionDiff, right: anchorBoundingRect.right + xPositionDiff, width: anchorBoundingRect.width, height: anchorBoundingRect.height, }; mockAdapter.getAnchorBoundingRect.and.returnValue(newAnchorBoundingRect); emitEvent(window, 'resize'); jasmine.clock().tick(1); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop + yPositionDiff}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith( 'left', `${expectedTooltipLeft + xPositionDiff}px`); }); it('#show registers additional user-specified scroll handlers', () => { const scrollableAncestor = document.createElement('div'); scrollableAncestor.setAttribute('id', 'scrollable'); document.body.appendChild(scrollableAncestor); const {foundation} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); (foundation as any).repositionTooltipOnAnchorMove = jasmine.createSpy('repositionTooltipOnAnchorMove'); foundation.attachScrollHandler((evt, handler) => { scrollableAncestor.addEventListener(evt, handler); }); foundation.show(); emitEvent(scrollableAncestor, 'scroll'); jasmine.clock().tick(1); expect((foundation as any).repositionTooltipOnAnchorMove) .toHaveBeenCalled(); }); it('#hide deregisters additional user-specified scroll handlers', () => { const scrollableAncestor = document.createElement('div'); scrollableAncestor.setAttribute('id', 'scrollable'); document.body.appendChild(scrollableAncestor); const {foundation} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); (foundation as any).repositionTooltipOnAnchorMove = jasmine.createSpy('repositionTooltipOnAnchorMove'); foundation.attachScrollHandler((evt, handler) => { scrollableAncestor.addEventListener(evt, handler); }); foundation.removeScrollHandler((evt, handler) => { scrollableAncestor.removeEventListener(evt, handler); }); foundation.show(); foundation.hide(); emitEvent(scrollableAncestor, 'scroll'); jasmine.clock().tick(1); expect((foundation as any).repositionTooltipOnAnchorMove) .not.toHaveBeenCalled(); }); it('recalculates position of tooltip if user specified ancestor is scrolled', () => { const anchorBoundingRect = {top: 0, bottom: 35, left: 200, right: 250}; const parentBoundingRect = {top: 5, bottom: 35, left: 100, right: 150}; const tooltipSize = {width: 40, height: 30}; const scrollableAncestor = document.createElement('div'); scrollableAncestor.setAttribute('id', 'scrollable'); document.body.appendChild(scrollableAncestor); const expectedTooltipTop = anchorBoundingRect.bottom + numbers.BOUNDED_ANCHOR_GAP - parentBoundingRect.top; const expectedTooltipLeft = anchorBoundingRect.right - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {isPersistent: true}); mockAdapter.getViewportWidth.and.returnValue(300); mockAdapter.getViewportHeight.and.returnValue(150); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); foundation.attachScrollHandler((evt, handler) => { scrollableAncestor.addEventListener(evt, handler); }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); // "Scroll" tooltip to the bottom of the page -- tooltip position flips // from BELOW to ABOVE const yPositionDiff = 150; const xPositionDiff = 20; const newAnchorBoundingRect = { top: anchorBoundingRect.top + yPositionDiff, bottom: anchorBoundingRect.bottom + yPositionDiff, left: anchorBoundingRect.left + xPositionDiff, right: anchorBoundingRect.right + xPositionDiff, }; const newParentBoundingRect = { top: parentBoundingRect.top + yPositionDiff, bottom: parentBoundingRect.bottom + yPositionDiff, left: parentBoundingRect.left + xPositionDiff, right: parentBoundingRect.right + xPositionDiff, }; mockAdapter.getAnchorBoundingRect.and.returnValue(newAnchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(newParentBoundingRect); emitEvent(scrollableAncestor, 'scroll'); jasmine.clock().tick(1); const newExpectedTooltipTop = (newAnchorBoundingRect.top - (numbers.BOUNDED_ANCHOR_GAP + tooltipSize.height)) - newParentBoundingRect.top; expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${newExpectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); for (const pos of CARET_POSITION_STYLES.keys()) { it(`correctly positions a ${pos} aligned caret`, () => { const anchorBoundingRect = {top: 200, bottom: 235, left: 350, right: 400, width: 50, height: 35}; const tooltipSize = {width: 300, height: 150}; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.isRTL.and.returnValue(false); mockAdapter.getComputedStyleProperty.withArgs('width').and.returnValue( RICH_TOOLTIP_WIDTH); mockAdapter.getComputedStyleProperty.withArgs('height').and.returnValue( RICH_TOOLTIP_HEIGHT); mockAdapter.getTooltipCaretBoundingRect.and.returnValue( {width: CARET_WIDTH, height: CARET_HEIGHT}); foundation.setTooltipPosition({withCaretPos: pos}); foundation.show(); const styleValues = CARET_POSITION_STYLES.get(pos)!; expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith(styleValues.yAlignment, styleValues.yAxisPx); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith(styleValues.xAlignment, styleValues.xAxisPx); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith( 'transform', `rotate(${styleValues.rotation}deg) skewY(${ styleValues.skew}deg) scaleX(${styleValues.scaleX})`); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith( 'transform-origin', `${styleValues.xAlignment} ${styleValues.yAlignment}`); expect(mockAdapter.setSurfaceAnimationStyleProperty) .toHaveBeenCalledWith( 'transform-origin', `${styleValues.xTransformOrigin} ${ styleValues.yTransformOrigin}`); }); } it('properly calculates tooltip with caret position (ABOVE_START)', () => { const anchorBoundingRect = {top: 200, bottom: 235, left: 350, right: 400, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipTop = (anchorBoundingRect.top - (numbers.BOUNDED_ANCHOR_GAP + tooltipSize.height + CARET_HEIGHT / 2)) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.left + anchorBoundingRect.width / 2 - (numbers.CARET_INDENTATION + CARET_WIDTH / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret position (ABOVE_CENTER)', () => { const anchorBoundingRect = {top: 200, left: 10, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipTop = (anchorBoundingRect.top - (numbers.BOUNDED_ANCHOR_GAP + tooltipSize.height + CARET_HEIGHT / 2)) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.left + anchorBoundingRect.width / 2 - (tooltipSize.width / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret position (ABOVE_END)', () => { const anchorBoundingRect = {top: 200, left: 0, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipTop = (anchorBoundingRect.top - (numbers.BOUNDED_ANCHOR_GAP + tooltipSize.height + CARET_HEIGHT / 2)) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.left + anchorBoundingRect.width / 2 - (tooltipSize.width - numbers.CARET_INDENTATION - CARET_WIDTH / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret position (BELOW_START)', () => { const anchorBoundingRect = {bottom: 35, left: 40, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipTop = (anchorBoundingRect.bottom + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.left + anchorBoundingRect.width / 2 - (numbers.CARET_INDENTATION + CARET_WIDTH / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(90); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret position (BELOW_CENTER)', () => { const anchorBoundingRect = {bottom: 35, left: 10, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipTop = (anchorBoundingRect.bottom + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.left + anchorBoundingRect.width / 2 - (tooltipSize.width / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(90); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret position (BELOW_END)', () => { const anchorBoundingRect = {bottom: 35, left: 0, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipTop = (anchorBoundingRect.bottom + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.left + anchorBoundingRect.width / 2 - (tooltipSize.width - numbers.CARET_INDENTATION - CARET_WIDTH / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(90); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret position (TOP_SIDE_START)', () => { const anchorBoundingRect = {top: 50, bottom: 85, left: 350, right: 400, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 50}; const expectedTooltipTop = (anchorBoundingRect.top + anchorBoundingRect.height / 2 - (numbers.CARET_INDENTATION + CARET_WIDTH / 2)) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.left - (tooltipSize.width + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret position (CENTER_SIDE_START)', () => { const anchorBoundingRect = {top: 25, left: 350, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 50}; const expectedTooltipTop = (anchorBoundingRect.top + anchorBoundingRect.height / 2 - tooltipSize.height / 2) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.left - (tooltipSize.width + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret position (BOTTOM_SIDE_START)', () => { const anchorBoundingRect = {top: 20, left: 350, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 60}; const expectedTooltipTop = (anchorBoundingRect.top + anchorBoundingRect.height / 2 - (tooltipSize.height - numbers.CARET_INDENTATION - CARET_WIDTH / 2)) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.left - (tooltipSize.width + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(105); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret position (TOP_SIDE_END)', () => { const anchorBoundingRect = {top: 50, right: 35, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 60}; const expectedTooltipTop = (anchorBoundingRect.top + anchorBoundingRect.height / 2 - (numbers.CARET_INDENTATION + CARET_WIDTH / 2)) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.right + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(95); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret position (CENTER_SIDE_END)', () => { const anchorBoundingRect = {top: 22, right: 35, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 60}; const expectedTooltipTop = (anchorBoundingRect.top + anchorBoundingRect.height / 2 - tooltipSize.height / 2) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.right + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(95); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.isRTL.and.returnValue(false); mockAdapter.getComputedStyleProperty.withArgs('width').and.returnValue( RICH_TOOLTIP_WIDTH); mockAdapter.getComputedStyleProperty.withArgs('height').and.returnValue( RICH_TOOLTIP_HEIGHT); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret position (BOTTOM_SIDE_END)', () => { const anchorBoundingRect = {top: 20, right: 35, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 60}; const expectedTooltipTop = (anchorBoundingRect.top + anchorBoundingRect.height / 2 - (tooltipSize.height - numbers.CARET_INDENTATION - CARET_WIDTH / 2)) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.right + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(95); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret SIDE_END position in RTL', () => { const anchorBoundingRect = {top: 200, left: 350, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipLeft = (anchorBoundingRect.left - (tooltipSize.width + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.isRTL.and.returnValue(true); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.setTooltipPosition( {withCaretPos: PositionWithCaret.BOTTOM_SIDE_END}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret SIDE_START position in RTL', () => { const anchorBoundingRect = {top: 200, right: 400, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipLeft = (anchorBoundingRect.right + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.isRTL.and.returnValue(true); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.setTooltipPosition( {withCaretPos: PositionWithCaret.BOTTOM_SIDE_START}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret START position in RTL', () => { const anchorBoundingRect = {top: 200, left: 350, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipLeft = (anchorBoundingRect.left + anchorBoundingRect.width / 2 - (tooltipSize.width - numbers.CARET_INDENTATION - CARET_WIDTH / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.isRTL.and.returnValue(true); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.setTooltipPosition( {withCaretPos: PositionWithCaret.ABOVE_START}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('properly calculates tooltip with caret END position in RTL', () => { const anchorBoundingRect = {top: 200, left: 350, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipLeft = (anchorBoundingRect.left + anchorBoundingRect.width / 2 - (numbers.CARET_INDENTATION + CARET_WIDTH / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.isRTL.and.returnValue(true); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.setTooltipPosition({withCaretPos: PositionWithCaret.ABOVE_END}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('allows users to specify the position for tooltips with carets (TOP_SIDE_START instead of ABOVE_START)', () => { const anchorBoundingRect = {top: 200, left: 350, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipTop = (anchorBoundingRect.top + anchorBoundingRect.height / 2 - (numbers.CARET_INDENTATION + CARET_WIDTH / 2)) - parentBoundingRect.top; const expectedTooltipLeft = (anchorBoundingRect.left - (tooltipSize.width + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2)) - parentBoundingRect.left; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(850); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.setTooltipPosition( {withCaretPos: PositionWithCaret.TOP_SIDE_START}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); }); it('ignores user specification if positioning violates threshold for tooltips with caret (BELOW alignment instead of ABOVE)', () => { const anchorBoundingRect = {bottom: 35, left: 40, width: 50, height: 35}; const parentBoundingRect = {top: 5, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const expectedTooltipTop = (anchorBoundingRect.bottom + numbers.BOUNDED_ANCHOR_GAP + CARET_HEIGHT / 2) - parentBoundingRect.top; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(90); mockAdapter.getViewportHeight.and.returnValue(800); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); foundation.setTooltipPosition( {withCaretPos: PositionWithCaret.ABOVE_START}); foundation.show(); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); }); it('handles positioning for tooltip with caret when all possible positions are invalid (BELOW_END)', () => { const anchorBoundingRect = {top: -135, left: -40, width: 50, height: 35}; const parentBoundingRect = {top: 0, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(50); mockAdapter.getViewportHeight.and.returnValue(50); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.isRTL.and.returnValue(false); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); mockAdapter.getComputedStyleProperty.withArgs('width').and.returnValue( RICH_TOOLTIP_WIDTH); mockAdapter.getComputedStyleProperty.withArgs('height').and.returnValue( RICH_TOOLTIP_HEIGHT); foundation.setTooltipPosition( {withCaretPos: PositionWithCaret.ABOVE_START}); foundation.show(); const expectedTooltipTop = numbers.MIN_VIEWPORT_TOOLTIP_THRESHOLD + CARET_HEIGHT / 2; const expectedTooltipLeft = numbers.MIN_VIEWPORT_TOOLTIP_THRESHOLD + CARET_HEIGHT / 2; expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); // Verify caret is styled for BELOW_END tooltip position const styleValues = CARET_POSITION_STYLES.get(PositionWithCaret.BELOW_END)!; expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith(styleValues.yAlignment, styleValues.yAxisPx); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith(styleValues.xAlignment, styleValues.xAxisPx); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith( 'transform', `rotate(${styleValues.rotation}deg) skewY(${ styleValues.skew}deg) scaleX(${styleValues.scaleX})`); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith( 'transform-origin', `${styleValues.xAlignment} ${styleValues.yAlignment}`); }); it('handles positioning for tooltip with caret when all possible positions are invalid (ABOVE_START)', () => { const anchorBoundingRect = {top: 135, left: 100, width: 50, height: 35}; const parentBoundingRect = {top: 0, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const viewportWidth = 50; const viewportHeight = 50; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.getViewportWidth.and.returnValue(viewportWidth); mockAdapter.getViewportHeight.and.returnValue(viewportHeight); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.isRTL.and.returnValue(false); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); mockAdapter.getComputedStyleProperty.withArgs('width').and.returnValue( RICH_TOOLTIP_WIDTH); mockAdapter.getComputedStyleProperty.withArgs('height').and.returnValue( RICH_TOOLTIP_HEIGHT); foundation.show(); const expectedTooltipTop = viewportHeight - (tooltipSize.height + numbers.MIN_VIEWPORT_TOOLTIP_THRESHOLD + CARET_HEIGHT / 2); const expectedTooltipLeft = viewportWidth - (tooltipSize.width + numbers.MIN_VIEWPORT_TOOLTIP_THRESHOLD + CARET_HEIGHT / 2); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); // Verify caret is styled for ABOVE_START tooltip position const styleValues = CARET_POSITION_STYLES.get(PositionWithCaret.ABOVE_START)!; expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith(styleValues.yAlignment, styleValues.yAxisPx); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith(styleValues.xAlignment, styleValues.xAxisPx); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith( 'transform', `rotate(${styleValues.rotation}deg) skewY(${ styleValues.skew}deg) scaleX(${styleValues.scaleX})`); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith( 'transform-origin', `${styleValues.xAlignment} ${styleValues.yAlignment}`); }); it('handles positioning for tooltip with caret when all possible positions are invalid (in RTL)', () => { const anchorBoundingRect = {top: -135, left: -40, width: 50, height: 35}; const parentBoundingRect = {top: 0, left: 0, width: 50, height: 30}; const tooltipSize = {width: 40, height: 30}; const {foundation, mockAdapter} = setUpFoundationTestForRichTooltip( MDCTooltipFoundation, {hasCaret: true}); mockAdapter.isRTL.and.returnValue(true); mockAdapter.getViewportWidth.and.returnValue(50); mockAdapter.getViewportHeight.and.returnValue(50); mockAdapter.getTooltipSize.and.returnValue(tooltipSize); mockAdapter.getAnchorBoundingRect.and.returnValue(anchorBoundingRect); mockAdapter.getParentBoundingRect.and.returnValue(parentBoundingRect); mockAdapter.getTooltipCaretBoundingRect.and.returnValue({ width: CARET_WIDTH * numbers.ANIMATION_SCALE, height: CARET_HEIGHT * numbers.ANIMATION_SCALE }); mockAdapter.getComputedStyleProperty.withArgs('width').and.returnValue( RICH_TOOLTIP_WIDTH); mockAdapter.getComputedStyleProperty.withArgs('height').and.returnValue( RICH_TOOLTIP_HEIGHT); foundation.setTooltipPosition( {withCaretPos: PositionWithCaret.ABOVE_START}); foundation.show(); const expectedTooltipTop = numbers.MIN_VIEWPORT_TOOLTIP_THRESHOLD + CARET_HEIGHT / 2; const expectedTooltipLeft = numbers.MIN_VIEWPORT_TOOLTIP_THRESHOLD + CARET_HEIGHT / 2; expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('top', `${expectedTooltipTop}px`); expect(mockAdapter.setStyleProperty) .toHaveBeenCalledWith('left', `${expectedTooltipLeft}px`); // Verify caret is styled for BELOW_START tooltip position const styleValues = CARET_POSITION_STYLES_RTL.get(PositionWithCaret.BELOW_START)!; expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith(styleValues.yAlignment, styleValues.yAxisPx); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith(styleValues.xAlignment, styleValues.xAxisPx); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith( 'transform', `rotate(${styleValues.rotation}deg) skewY(${ styleValues.skew}deg) scaleX(${styleValues.scaleX})`); expect(mockAdapter.setTooltipCaretStyle) .toHaveBeenCalledWith( 'transform-origin', `${styleValues.xAlignment} ${styleValues.yAlignment}`); expect(mockAdapter.setSurfaceAnimationStyleProperty) .toHaveBeenCalledWith( 'transform-origin', `${styleValues.xTransformOrigin} ${ styleValues.yTransformOrigin}`); }); it(`#setShowDelay allows users to configure the delay prior to showing a tooltip`, () => { const extraDelayMs = 20; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.setShowDelay(numbers.SHOW_DELAY_MS + extraDelayMs); foundation.handleAnchorMouseEnter(); expect((foundation as any).showTimeout).not.toEqual(null); jasmine.clock().tick(numbers.SHOW_DELAY_MS); expect((foundation as any).showTimeout).not.toEqual(null); jasmine.clock().tick(extraDelayMs); expectTooltipToHaveBeenShown(foundation, mockAdapter); }); it(`#setHideDelay allows users to configure the delay prior to hiding a tooltip`, () => { const extraDelayMs = 20; const {foundation, mockAdapter} = setUpFoundationTest(MDCTooltipFoundation); foundation.setHideDelay(numbers.HIDE_DELAY_MS + extraDelayMs); foundation.show(); foundation.handleAnchorMouseLeave(); expect((foundation as any).hideTimeout).not.toEqual(null); jasmine.clock().tick(numbers.HIDE_DELAY_MS); expect((foundation as any).hideTimeout).not.toEqual(null); jasmine.clock().tick(extraDelayMs); expectTooltipToHaveBeenHidden(foundation, mockAdapter); }); });
the_stack
import { ContextMenuCreateProperties, BrowserTabsQueryInfo } from "../background/sharedTypes"; declare global { namespace _browser.runtime { function getManifest(): _chrome.runtime.Manifest; } namespace _browser.storage { interface Get { <S extends CRM.StorageLocal|CRM.SettingsStorage = CRM.StorageLocal|CRM.SettingsStorage>(): Promise<S>; <S extends CRM.StorageLocal|CRM.SettingsStorage, K extends keyof S>(keys: K): Promise<S>; <S extends CRM.StorageLocal|CRM.SettingsStorage, K extends keyof S>(keys: K[]): Promise<S>; } } } namespace BrowserAPINS { interface AllBrowserAPIsWindow extends Window { browser: typeof _browser; chrome: typeof _chrome; StyleMedia?: any; } // Chrome uses callback-style APIs under the "chrome" global // ^ Same for opera ^ // Edge uses callback-style APIs under the "browser" global // and an as good as empty "chrome" global (pls edge...) // Firefox uses promise-based APIs under the "browser" global // and callback-style APIs under the (probably temporary) "chrome" global // So if browser is Edge, use "browser", otherwise use "chrome" if available // to ensure always always getting callback-style APIs const apisWindow = window as unknown as AllBrowserAPIsWindow; const __srcBrowser: typeof _chrome = apisWindow.StyleMedia ? (apisWindow.browser as any) : apisWindow.chrome; function checkReject(reject: (err: _chrome.runtime.LastError) => void) { const lastError = __srcBrowser.runtime.lastError; if (lastError) { reject(lastError); return true; } return false; } type ChromeCallbackHandler<T> = { (...args: any[]): void; __resolve(value: T): void; __reject(err: any): void; __stack: Error; }; class CustomError extends Error { constructor({ message }: _chrome.runtime.LastError, { stack }: Error) { super(message); this.stack = stack; this.message = message; } } function createCallback<T>(stackSrc: Error, prom: { resolve: (result: T) => void; reject: (reason: any) => void; }): ChromeCallbackHandler<T> { const { resolve, reject } = prom; const fn = ((...args: any[]) => { const lastError = __srcBrowser.runtime.lastError; if (lastError) { reject(new CustomError(lastError, stackSrc)); } else { resolve(args[0]); } }) as Partial<ChromeCallbackHandler<T>>; fn.__resolve = resolve; fn.__reject = reject; fn.__stack = stackSrc; return fn as ChromeCallbackHandler<T>; } function createPromise<T>(callback: (handler: ChromeCallbackHandler<T>) => void) { return new Promise<T>((resolve, reject) => { callback(createCallback(new Error(), { resolve, reject })); }); } function genStoragePolyfill(type: 'local' | 'sync') { return { set(keys: any) { return createPromise<void>((handler) => { __srcBrowser.storage[type].set(keys, handler); }); }, remove(keys: string | string[]) { return createPromise<void>((handler) => { if (Array.isArray(keys)) { Promise.all(keys.map((key) => { return new Promise((resolveMapped) => { __srcBrowser.storage[type].remove(key, () => { checkReject(handler.__reject) || resolveMapped(null); }); }); })).then(handler); } else { __srcBrowser.storage[type].remove(keys, handler); } }); }, clear(): Promise<void> { return createPromise<void>((handler) => { __srcBrowser.storage[type].clear(handler); }); } }; } const browserAPIExists = 'browser' in window; const chromeAPIExists = 'chrome' in window; export function isBrowserAPISupported(api: 'browser' | 'chrome'): boolean { if (api === 'browser') { return browserAPIExists; } else if (api === 'chrome') { return chromeAPIExists; } else if (typeof location === 'undefined' || typeof location.host === 'undefined') { return false; } else { throw new Error('Unsupported browser API support queried'); } } interface MultiBrowserWindow extends Window { opr?: { addons?: any; }; opera?: any; InstallTrigger?: any; StyleMedia?: any; } let _browserUserAgent: 'chrome' | 'firefox' | 'edge' | 'opera' | 'node' = null; function getBrowserUserAgent() { const win = window as MultiBrowserWindow; const isOpera = (!!win.opr && !!win.opr.addons) || !!win.opera || navigator.userAgent.indexOf(' OPR/') >= 0; if (typeof win.InstallTrigger !== 'undefined') { return 'firefox'; } if (win.StyleMedia) { return 'edge'; } if (!isOpera && isBrowserAPISupported('chrome')) { return 'chrome'; } if (isOpera) { return 'opera'; } if (typeof location === 'undefined' || typeof location.host === 'undefined') { return 'node'; } throw new Error('Unsupported browser'); } export function getBrowser() { if (_browserUserAgent) { return _browserUserAgent; } return (_browserUserAgent = getBrowserUserAgent()); } export function getSrc() { return __srcBrowser; } function isDevOptionsPage() { return location.href.indexOf('backgroun') === -1; } function isDevBackgroundPage() { return __srcBrowser.runtime.getManifest().short_name.indexOf('dev') > -1; } function areStringsEqual(a: string | number, b: string | number): boolean { return (a + '') === (b + ''); } function findItemWithId<T extends { id: string | number; children?: T[]; }>(arr: T[], idToFind: number | string, fn: (item: T, index: number, parent: T[]) => void) { for (let i = 0; i < arr.length; i++) { const item = arr[i]; const { id, children } = item; if (areStringsEqual(id, idToFind)) { fn(item, i, arr); return true; } if (children && findItemWithId(children, idToFind, fn)) { return true; } } return false; } interface ChromeLastCall { api: string; args: any[]; } interface ContextMenuItem { id: number; createProperties: ContextMenuCreateProperties; currentProperties: ContextMenuCreateProperties; children: ContextMenuItem[]; } type ContextMenu = ContextMenuItem[]; type ActiveTabs = { type: 'create' | 'update'; data: any; id?: TabId; }[]; interface ExecutedScript { id: TabId; code: string; } type ExecutedScripts = ExecutedScript[]; let loggingEnabled: boolean = false; export function resetLogData() { testData._lastSpecialCall = null; testData._currentContextMenu = []; testData._activeTabs = []; testData._executedScripts = []; testData._fakeTabs = {}; testData._activatedBackgroundPages = []; testData._tabUpdateListeners = []; } export function enableLogging() { if (!loggingEnabled) { resetLogData(); } loggingEnabled = true; } export function isLoggingEnabled() { return loggingEnabled; } export function disableLogging() { loggingEnabled = false; testData._lastSpecialCall = null; testData._currentContextMenu = null; testData._activeTabs = null; testData._executedScripts = null; testData._fakeTabs = null; testData._activatedBackgroundPages = null; testData._tabUpdateListeners = null; } const testData: { _lastSpecialCall: ChromeLastCall; _currentContextMenu: ContextMenu; _activeTabs: ActiveTabs; _executedScripts: ExecutedScripts; _activatedBackgroundPages: CRM.GenericNodeId[]; _tabUpdateListeners: ((id: TabId, updateData: { status?: 'loading' | 'complete'; url?: string; pinned?: boolean; audible?: boolean; discarded?: boolean; autoDiscardable?: boolean; mutedInfo?: any; favIconUrl?: string; title?: string; }, tab: _browser.tabs.Tab) => void)[]; _clearExecutedScripts: () => void; _fakeTabs: { [id: number]: { id: TabId; title: string; url: string; }; [id: string]: { id: TabId; title: string; url: string; }; }; } = { _lastSpecialCall: null, _currentContextMenu: null, _activeTabs: null, _executedScripts: null, _fakeTabs: null, _activatedBackgroundPages: null, _tabUpdateListeners: null, _clearExecutedScripts: function () { while (testData._executedScripts.pop()) { } } }; export function getTestData() { if (!isDevOptionsPage() && !isDevBackgroundPage()) { return undefined; } return testData; } export function getDownloadAPI() { return __srcBrowser.downloads ? { download(options: { url: string; filename?: string; conflictAction?: string; saveAs?: boolean; method?: string; headers?: { [key: string]: string; }; body?: string; }) { if (loggingEnabled) { testData._lastSpecialCall = { api: 'downloads.download', args: [options] }; } return createPromise<number>((handler) => { __srcBrowser.downloads.download(options as any, handler); }); } } : void 0 } export const polyfill = !__srcBrowser ? {} : { commands: __srcBrowser.commands ? { getAll() { return createPromise<_browser.commands.Command[]>((handler) => { __srcBrowser.commands.getAll(handler); }); }, onCommand: __srcBrowser.commands.onCommand as Listener<string> } : void 0, contextMenus: __srcBrowser.contextMenus ? { create(createProperties: { type?: _browser.contextMenus.ItemType; id?: string; title?: string; checked?: boolean; command?: "_execute_browser_action" | "_execute_page_action" | "_execute_sidebar_action"; contexts?: _browser.contextMenus.ContextType[]; onclick?: (info: _browser.contextMenus.OnClickData, tab: _browser.tabs.Tab) => void; parentId?: number | string; documentUrlPatterns?: string[]; targetUrlPatterns?: string[]; enabled?: boolean; }, callback?: () => void): Promise<number | string> { const id = __srcBrowser.contextMenus.create(createProperties as any, () => { if (!callback) { return; } if (__srcBrowser.runtime.lastError) { polyfill.runtime.lastError = __srcBrowser.runtime.lastError.message; callback(); polyfill.runtime.lastError = null; } else { callback(); } }); const testNode: ContextMenuItem = { id, createProperties, currentProperties: createProperties, children: [] }; if (loggingEnabled) { if (createProperties.parentId) { findItemWithId(testData._currentContextMenu, createProperties.parentId, (parent) => { parent.children.push(testNode); }); } else { testData._currentContextMenu.push(testNode); } } return Promise.resolve(id); }, update(id: number | string, updateProperties: { type?: _browser.contextMenus.ItemType; title?: string; checked?: boolean; contexts?: _browser.contextMenus.ContextType[]; onclick?: (info: _browser.contextMenus.OnClickData, tab: _browser.tabs.Tab) => void; parentId?: number | string; documentUrlPatterns?: string[]; targetUrlPatterns?: string[]; enabled?: boolean; }) { if (loggingEnabled) { findItemWithId(testData._currentContextMenu, id, (item) => { var currentProperties = item.currentProperties; for (var key in updateProperties) { (currentProperties as any)[key] = updateProperties[key as keyof typeof updateProperties]; } }); } return createPromise<void>((handler) => { __srcBrowser.contextMenus.update(id + '', updateProperties, () => { if (__srcBrowser.runtime.lastError) { //Try the other method __srcBrowser.contextMenus.update(~~id, updateProperties, handler); } else { handler(); } }); }); }, remove(id: string | number) { if (loggingEnabled) { findItemWithId(testData._currentContextMenu, id, (_item, index, parent) => { parent.splice(index, 1); }); } return createPromise<void>((handler) => { __srcBrowser.contextMenus.remove(id + '', () => { if (__srcBrowser.runtime.lastError) { //Try the other method __srcBrowser.contextMenus.remove(~~id, handler); } else { handler(); } }); }); }, removeAll() { if (loggingEnabled) { while (testData._currentContextMenu.length) { testData._currentContextMenu.pop(); } } return createPromise<void>((handler) => { //Does not follow the spec but currently all browsers implement this behavior const retVal: any = __srcBrowser.contextMenus.removeAll(() => { //Edge throws an error if other extensions are active... ignore that // see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/17799250/ if (getBrowser() === 'edge' && __srcBrowser.runtime.lastError) { handler.__resolve(undefined); } if (__srcBrowser.runtime.lastError) { handler.__reject(new CustomError(__srcBrowser.runtime.lastError, handler.__stack)); } else { handler.__resolve(undefined); } }); if (retVal && typeof window !== 'undefined' && window.Promise && retVal instanceof window.Promise) { retVal.then(handler.__resolve, handler.__reject); } }); } } : void 0, downloads: getDownloadAPI(), extension: __srcBrowser.extension ? { isAllowedFileSchemeAccess(): Promise<boolean> { return createPromise<boolean>((handler) => { __srcBrowser.extension.isAllowedFileSchemeAccess(handler); }); } } : void 0, i18n: __srcBrowser.i18n ? { getAcceptLanguages(): Promise<string[]> { return createPromise<string[]>((handler) => { __srcBrowser.i18n.getAcceptLanguages(handler); }); }, getMessage(messageName: string, substitutions?: any): string { return __srcBrowser.i18n.getMessage(messageName, substitutions); }, getUILanguage(): string { return __srcBrowser.i18n.getUILanguage(); } } : void 0, notifications: __srcBrowser.notifications ? { onClicked: __srcBrowser.notifications.onClicked as Listener<string>, onClosed: __srcBrowser.notifications.onClosed as Listener<string> } : void 0, permissions: __srcBrowser.permissions ? { contains(permissions: _browser.permissions.Permissions) { return createPromise<boolean>((handler) => { __srcBrowser.permissions.contains(permissions, handler); }); }, getAll() { return createPromise<_browser.permissions.Permissions>((handler) => { __srcBrowser.permissions.getAll(handler); }); }, request(permissions: _browser.permissions.Permissions) { return createPromise<boolean>((handler) => { __srcBrowser.permissions.request(permissions, handler); }); }, remove(permissions: _browser.permissions.Permissions) { return createPromise<boolean>((handler) => { __srcBrowser.permissions.remove(permissions, handler); }); } } : void 0, runtime: __srcBrowser.runtime ? { connect(extensionIdOrConnectInfo?: string, connectInfo?: { name?: string; includeTlsChannelId?: boolean; }): _browser.runtime.Port { if (connectInfo) { return __srcBrowser.runtime.connect(extensionIdOrConnectInfo, connectInfo) as any; } else if (extensionIdOrConnectInfo) { return __srcBrowser.runtime.connect(extensionIdOrConnectInfo) as any; } else { return __srcBrowser.runtime.connect() as any; } }, getBackgroundPage() { return createPromise<Window>((handler) => { __srcBrowser.runtime.getBackgroundPage(handler); }); }, getManifest() { return Promise.resolve(__srcBrowser.runtime.getManifest()); }, getURL(path: string) { return __srcBrowser.runtime.getURL(path); }, getPlatformInfo() { return createPromise<_browser.runtime.PlatformInfo>((handler) => { __srcBrowser.runtime.getPlatformInfo(handler); }); }, openOptionsPage() { return createPromise<void>((handler) => { if (BrowserAPINS.getBrowser() === 'edge') { polyfill.tabs.create({ url: polyfill.runtime.getURL('html/options.html') }).then(() => { handler(); }); } else { __srcBrowser.runtime.openOptionsPage(handler); } }); }, reload() { return Promise.resolve(__srcBrowser.runtime.reload()); }, sendMessage<U>(extensionIdOrmessage: string | { [key: string]: any; [key: number]: any; }, optionsOrMessage?: { [key: string]: any; [key: number]: any; } | { includeTlsChannelId?: boolean; toProxyScript?: boolean; }, options?: { includeTlsChannelId?: boolean; toProxyScript?: boolean; }) { return createPromise<U | void>((handler) => { if (options) { __srcBrowser.runtime.sendMessage(extensionIdOrmessage as string, optionsOrMessage, options, handler); } else if (optionsOrMessage) { //extensionId, message or message, options __srcBrowser.runtime.sendMessage(extensionIdOrmessage, optionsOrMessage, handler); } else { __srcBrowser.runtime.sendMessage(extensionIdOrmessage, handler); } }); }, onInstalled: (__srcBrowser.runtime.onInstalled as any) as Listener<{ reason: _browser.runtime.OnInstalledReason; previousVersion?: string; id?: string; }>, onConnectExternal: (__srcBrowser.runtime.onConnectExternal as any) as Listener<_browser.runtime.Port>, onConnect: (__srcBrowser.runtime.onConnect as any) as Listener<_browser.runtime.Port>, onMessage: (__srcBrowser.runtime.onMessage as any) as EvListener<_browser.runtime.onMessageEvent>, lastError: null as string | null, id: __srcBrowser.runtime.id } : void 0, storage: __srcBrowser.storage ? { local: { ...genStoragePolyfill('local'), ...{ get<T = CRM.StorageLocal>(keys?: string | string[] | null): Promise<T> { return createPromise<T>((handler) => { if (keys) { __srcBrowser.storage.local.get(keys, handler); } else { __srcBrowser.storage.local.get(handler); } }); }, } }, sync: { ...genStoragePolyfill('sync'), ...{ get<T = CRM.SettingsStorage>(keys?: string | string[] | null): Promise<T> { return createPromise<T>((handler) => { if (keys) { __srcBrowser.storage.sync.get(keys, handler); } else { __srcBrowser.storage.sync.get(handler); } }); }, } }, onChanged: __srcBrowser.storage.onChanged as EvListener<(changes: _browser.storage.ChangeDict, areaName: _browser.storage.StorageName) => void> } : void 0, tabs: __srcBrowser.tabs ? { create(createProperties: { active?: boolean; cookieStoreId?: string; index?: number; openerTabId?: TabId; pinned?: boolean; // deprecated: selected: boolean, url?: string; windowId?: number; }) { return createPromise<_browser.tabs.Tab>((handler) => { __srcBrowser.tabs.create(createProperties, (tab) => { const { id } = tab; if (loggingEnabled) { testData._activeTabs.push({ type: 'create', data: createProperties, id }); } handler(tab); }); }); }, get(tabId: TabId) { return createPromise<_browser.tabs.Tab>((handler) => { __srcBrowser.tabs.get(tabId, handler); }); }, getCurrent() { return createPromise<_browser.tabs.Tab>((handler) => { __srcBrowser.tabs.getCurrent(handler); }); }, captureVisibleTab(windowIdOrOptions?: number | _browser.extensionTypes.ImageDetails, options?: _browser.extensionTypes.ImageDetails) { return createPromise<string>((handler) => { if (options) { __srcBrowser.tabs.captureVisibleTab(windowIdOrOptions as number, options, handler); } else if (windowIdOrOptions) { __srcBrowser.tabs.captureVisibleTab(windowIdOrOptions as _browser.extensionTypes.ImageDetails, handler); } else { __srcBrowser.tabs.captureVisibleTab(handler); } }); }, async update(tabIdOrOptions: TabId | { active?: boolean; // unsupported: autoDiscardable?: boolean, // unsupported: highlighted?: boolean, loadReplace?: boolean; muted?: boolean; openerTabId?: TabId; pinned?: boolean; // deprecated: selected?: boolean, url?: string; }, options?: { active?: boolean; // unsupported: autoDiscardable?: boolean, // unsupported: highlighted?: boolean, loadReplace?: boolean; muted?: boolean; openerTabId?: TabId; pinned?: boolean; // deprecated: selected?: boolean, url?: string; }) { return createPromise<_browser.tabs.Tab>(async (handler) => { if (!options) { __srcBrowser.tabs.update(tabIdOrOptions as { active?: boolean; // unsupported: autoDiscardable?: boolean, // unsupported: highlighted?: boolean, loadReplace?: boolean; muted?: boolean; openerTabId?: TabId; pinned?: boolean; // deprecated: selected?: boolean, url?: string; }, handler); } else { __srcBrowser.tabs.update(tabIdOrOptions as TabId, options, handler); } if (loggingEnabled) { testData._activeTabs.push({ type: 'create', data: typeof tabIdOrOptions === 'number' ? options : tabIdOrOptions, id: typeof tabIdOrOptions === 'number' ? tabIdOrOptions : undefined }); } }); }, query(queryInfo: BrowserTabsQueryInfo) { return createPromise<_browser.tabs.Tab[]>((handler) => { __srcBrowser.tabs.query(queryInfo, handler); }); }, executeScript(tabIdOrDetails: TabId | _browser.extensionTypes.InjectDetails, details?: _browser.extensionTypes.InjectDetails) { return createPromise<any[]>(async (handler) => { if (!details) { __srcBrowser.tabs.executeScript(tabIdOrDetails as _browser.extensionTypes.InjectDetails, handler); } else { __srcBrowser.tabs.executeScript(tabIdOrDetails as TabId, details, handler); } const settings = typeof tabIdOrDetails === 'number' ? details : tabIdOrDetails; if (settings.code) { let id: TabId = undefined; if (typeof tabIdOrDetails === 'number') { id = tabIdOrDetails; } else { const currentTab = await browserAPI.tabs.getCurrent(); if (currentTab) { id = currentTab.id; } } if (loggingEnabled) { testData._executedScripts.push({ id, code: settings.code }); } } }); }, sendMessage<R>(tabId: TabId, message: any, _options?: { frameId: number; }) { return createPromise<void | R>(({ __resolve, __reject }) => { __srcBrowser.tabs.sendMessage(tabId, message, (response?: R) => { checkReject(__reject) || __resolve(response); }); }); }, onUpdated: (__srcBrowser.tabs.onUpdated as any) as EvListener<(tabId: number, changeInfo: { audible?: boolean; discarded?: boolean; favIconUrl?: string; mutedInfo?: _browser.tabs.MutedInfo; pinned?: boolean; status?: string; title?: string; url?: string; }, tab: _browser.tabs.Tab) => void>, onRemoved: (__srcBrowser.tabs.onRemoved as any) as EvListener<(tabId: number, removeInfo: { windowId: number; isWindowClosing: boolean; }) => void>, onHighlighted: (__srcBrowser.tabs.onHighlighted as any) as Listener<{ windowId: number; tabIds: number[]; }> } : void 0, webRequest: __srcBrowser.webRequest ? { onBeforeRequest: (__srcBrowser.webRequest.onBeforeRequest as any) as _browser.webRequest.ReqListener<{ requestId: string; url: string; method: string; frameId: number; parentFrameId: number; requestBody?: { error?: string; formData?: { [key: string]: string[]; }; raw?: _browser.webRequest.UploadData[]; }; tabId: TabId; type: _browser.webRequest.ResourceType; timeStamp: number; originUrl: string; }, "blocking" | "requestBody"> } : void 0 }; } declare global { interface Window { browserAPI: typeof BrowserAPI.polyfill & { __isProxied: boolean; }; BrowserAPI: typeof BrowserAPINS; BrowserAPINS: typeof BrowserAPINS; BrowserAPIInstances: typeof BrowserAPINS[]; __isVirtual?: boolean; } } window.BrowserAPIInstances = window.BrowserAPIInstances || []; window.BrowserAPIInstances.push(BrowserAPINS); if (!window.browserAPI || window.__isVirtual) { // Force override of window.browser if browser is edge or if no "browser" // global exists already. Basically equal to // window.browser = BrowserAPI.polyfill || window.browser & // if getBrowser() === 'edge': window.browser = BrowserAPI.polyfill window.BrowserAPINS = window.BrowserAPI = BrowserAPINS; window.browserAPI = (BrowserAPINS.getBrowser() === 'edge' || !(window as any).browser) ? {...BrowserAPINS.polyfill as typeof BrowserAPI.polyfill, ...{ __isProxied: true }} : (window as any).browser; type MenusBrowserAPI = typeof BrowserAPI.polyfill & { menus?: (typeof BrowserAPI.polyfill)['contextMenus'] }; const menusBrowserAPI = window.browserAPI as MenusBrowserAPI; if (!menusBrowserAPI.contextMenus) { menusBrowserAPI.contextMenus = menusBrowserAPI.menus; } else if (!menusBrowserAPI.menus) { menusBrowserAPI.menus = menusBrowserAPI.contextMenus; } } const BrowserAPI = window.BrowserAPINS; const browserAPI = window.browserAPI as typeof BrowserAPI.polyfill; declare global { type browserAPI = typeof BrowserAPI.polyfill; type BrowserAPI = typeof BrowserAPINS; }
the_stack
import { Hash, Preimage, SendTransaction, SwapAbortTransaction, SwapClaimTransaction, SwapIdBytes, SwapOfferTransaction, UnsignedTransaction, } from "@iov/bcp"; import { decodeAccountConfiguration, decodeAccountMsgFee, decodeAmount, decodeBlockchainAddress, decodeChainAddressPair, decodeParticipants, decodeRawProposalOption, decodeVoteOption, } from "./decodeobjects"; import { asIntegerNumber, decodeNumericId, ensure } from "./decodinghelpers"; import * as codecImpl from "./generated/codecimpl"; import { AddAccountCertificateTx, BnsdTxMsg, CreateEscrowTx, CreateMultisignatureTx, CreateProposalTx, DeleteAccountCertificateTx, DeleteAccountTx, DeleteAllAccountsTx, DeleteDomainTx, RegisterAccountTx, RegisterDomainTx, RegisterUsernameTx, ReleaseEscrowTx, RenewAccountTx, RenewDomainTx, ReplaceAccountMsgFeesTx, ReplaceAccountTargetsTx, ReturnEscrowTx, TransferAccountTx, TransferDomainTx, TransferUsernameTx, UpdateAccountConfigurationTx, UpdateEscrowPartiesTx, UpdateMultisignatureTx, UpdateTargetsOfUsernameTx, VoteTx, } from "./types"; import { addressPrefix, encodeBnsAddress } from "./util"; // Token sends function decodeSendTransaction(base: UnsignedTransaction, msg: codecImpl.cash.ISendMsg): SendTransaction { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bcp/send", sender: encodeBnsAddress(prefix, ensure(msg.source, "source")), recipient: encodeBnsAddress(prefix, ensure(msg.destination, "destination")), amount: decodeAmount(ensure(msg.amount)), memo: msg.memo || undefined, }; } // Atomic swaps function decodeSwapOfferTx(base: UnsignedTransaction, msg: codecImpl.aswap.ICreateMsg): SwapOfferTransaction { const hash = ensure(msg.preimageHash, "preimageHash"); if (hash.length !== 32) { throw new Error("Hash must be 32 bytes (sha256)"); } const prefix = addressPrefix(base.chainId); const parsed = { ...base, kind: "bcp/swap_offer" as const, hash: hash as Hash, sender: encodeBnsAddress(prefix, ensure(msg.source, "source")), recipient: encodeBnsAddress(prefix, ensure(msg.destination, "destination")), timeout: { timestamp: asIntegerNumber(ensure(msg.timeout, "timeout")) }, amounts: (msg.amount || []).map(decodeAmount), }; return msg.memo ? { ...parsed, memo: msg.memo } : parsed; } function decodeSwapClaimTx( base: UnsignedTransaction, msg: codecImpl.aswap.IReleaseMsg, ): SwapClaimTransaction { return { ...base, kind: "bcp/swap_claim", swapId: { data: ensure(msg.swapId) as SwapIdBytes, }, preimage: ensure(msg.preimage) as Preimage, }; } function decodeSwapAbortTransaction( base: UnsignedTransaction, msg: codecImpl.aswap.IReturnMsg, ): SwapAbortTransaction { return { ...base, kind: "bcp/swap_abort", swapId: { data: ensure(msg.swapId) as SwapIdBytes, }, }; } // Usernames function decodeRegisterUsernameTx( base: UnsignedTransaction, msg: codecImpl.username.IRegisterTokenMsg, ): RegisterUsernameTx { const targets = ensure(msg.targets, "targets").map(decodeChainAddressPair); return { ...base, kind: "bns/register_username", username: ensure(msg.username, "username"), targets: targets, }; } function decodeUpdateTargetsOfUsernameTx( base: UnsignedTransaction, msg: codecImpl.username.IChangeTokenTargetsMsg, ): UpdateTargetsOfUsernameTx { const targets = ensure(msg.newTargets, "newTargets").map(decodeChainAddressPair); return { ...base, kind: "bns/update_targets_of_username", username: ensure(msg.username, "username"), targets: targets, }; } function decodeTransferUsernameTx( base: UnsignedTransaction, msg: codecImpl.username.ITransferTokenMsg, ): TransferUsernameTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/transfer_username", username: ensure(msg.username, "username"), newOwner: encodeBnsAddress(prefix, ensure(msg.newOwner, "newOwner")), }; } // Accounts function decodeUpdateAccountConfigurationTx( base: UnsignedTransaction, msg: codecImpl.account.IUpdateConfigurationMsg, ): UpdateAccountConfigurationTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/update_account_configuration", configuration: decodeAccountConfiguration(prefix, ensure(msg.patch, "patch")), }; } function decodeRegisterDomainTx( base: UnsignedTransaction, msg: codecImpl.account.IRegisterDomainMsg, ): RegisterDomainTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/register_domain", domain: ensure(msg.domain, "domain"), admin: encodeBnsAddress(prefix, ensure(msg.admin, "admin")), hasSuperuser: ensure(msg.hasSuperuser, "hasSuperuser"), broker: encodeBnsAddress(prefix, ensure(msg.broker, "broker")) || undefined, msgFees: ensure(msg.msgFees, "msgFees").map(decodeAccountMsgFee), accountRenew: asIntegerNumber(ensure(msg.accountRenew, "accountRenew")), }; } function decodeTransferDomainTx( base: UnsignedTransaction, msg: codecImpl.account.ITransferDomainMsg, ): TransferDomainTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/transfer_domain", domain: ensure(msg.domain, "domain"), newAdmin: encodeBnsAddress(prefix, ensure(msg.newAdmin, "newAdmin")), }; } function decodeRenewDomainTx( base: UnsignedTransaction, msg: codecImpl.account.IRenewDomainMsg, ): RenewDomainTx { return { ...base, kind: "bns/renew_domain", domain: ensure(msg.domain, "domain"), }; } function decodeDeleteDomainTx( base: UnsignedTransaction, msg: codecImpl.account.IDeleteDomainMsg, ): DeleteDomainTx { return { ...base, kind: "bns/delete_domain", domain: ensure(msg.domain, "domain"), }; } function decodeRegisterAccountTx( base: UnsignedTransaction, msg: codecImpl.account.IRegisterAccountMsg, ): RegisterAccountTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/register_account", domain: ensure(msg.domain, "domain"), name: ensure(msg.name, "name"), owner: encodeBnsAddress(prefix, ensure(msg.owner, "owner")), targets: ensure(msg.targets, "targets").map(decodeBlockchainAddress), broker: encodeBnsAddress(prefix, ensure(msg.broker, "broker")) || undefined, }; } function decodeTransferAccountTx( base: UnsignedTransaction, msg: codecImpl.account.ITransferAccountMsg, ): TransferAccountTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/transfer_account", domain: ensure(msg.domain, "domain"), name: ensure(msg.name, "name"), newOwner: encodeBnsAddress(prefix, ensure(msg.newOwner, "newOwner")), }; } function decodeReplaceAccountTargetsTx( base: UnsignedTransaction, msg: codecImpl.account.IReplaceAccountTargetsMsg, ): ReplaceAccountTargetsTx { return { ...base, kind: "bns/replace_account_targets", domain: ensure(msg.domain, "domain"), name: ensure(msg.name, "name"), newTargets: ensure(msg.newTargets, "newTargets").map(decodeBlockchainAddress), }; } function decodeDeleteAccountTx( base: UnsignedTransaction, msg: codecImpl.account.IDeleteAccountMsg, ): DeleteAccountTx { return { ...base, kind: "bns/delete_account", domain: ensure(msg.domain, "domain"), name: ensure(msg.name, "name"), }; } function decodeDeleteAllAccountsTx( base: UnsignedTransaction, msg: codecImpl.account.IFlushDomainMsg, ): DeleteAllAccountsTx { return { ...base, kind: "bns/delete_all_accounts", domain: ensure(msg.domain, "domain"), }; } function decodeRenewAccountTx( base: UnsignedTransaction, msg: codecImpl.account.IRenewAccountMsg, ): RenewAccountTx { return { ...base, kind: "bns/renew_account", domain: ensure(msg.domain, "domain"), name: ensure(msg.name, "name"), }; } function decodeAddAccountCertificateTx( base: UnsignedTransaction, msg: codecImpl.account.IAddAccountCertificateMsg, ): AddAccountCertificateTx { return { ...base, kind: "bns/add_account_certificate", domain: ensure(msg.domain, "domain"), name: ensure(msg.name, "name"), certificate: ensure(msg.certificate, "certificate"), }; } function decodeReplaceAccountMsgFeesTx( base: UnsignedTransaction, msg: codecImpl.account.IReplaceAccountMsgFeesMsg, ): ReplaceAccountMsgFeesTx { return { ...base, kind: "bns/replace_account_msg_fees", domain: ensure(msg.domain, "domain"), newMsgFees: ensure(msg.newMsgFees, "newMsgFees").map(decodeAccountMsgFee), }; } function decodeDeleteAccountCertificateTx( base: UnsignedTransaction, msg: codecImpl.account.IDeleteAccountCertificateMsg, ): DeleteAccountCertificateTx { return { ...base, kind: "bns/delete_account_certificate", domain: ensure(msg.domain, "domain"), name: ensure(msg.name, "name"), certificateHash: ensure(msg.certificateHash, "certificateHash"), }; } // Multisignature contracts function decodeCreateMultisignatureTx( base: UnsignedTransaction, msg: codecImpl.multisig.ICreateMsg, ): CreateMultisignatureTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/create_multisignature_contract", participants: decodeParticipants(prefix, msg.participants), activationThreshold: ensure(msg.activationThreshold, "activationThreshold"), adminThreshold: ensure(msg.adminThreshold, "adminThreshold"), }; } function decodeUpdateMultisignatureTx( base: UnsignedTransaction, msg: codecImpl.multisig.IUpdateMsg, ): UpdateMultisignatureTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/update_multisignature_contract", contractId: decodeNumericId(ensure(msg.contractId, "contractId")), participants: decodeParticipants(prefix, msg.participants), activationThreshold: ensure(msg.activationThreshold, "activationThreshold"), adminThreshold: ensure(msg.adminThreshold, "adminThreshold"), }; } // Escrows function decodeCreateEscrowTx(base: UnsignedTransaction, msg: codecImpl.escrow.ICreateMsg): CreateEscrowTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/create_escrow", sender: encodeBnsAddress(prefix, ensure(msg.source, "source")), arbiter: encodeBnsAddress(prefix, ensure(msg.arbiter, "arbiter")), recipient: encodeBnsAddress(prefix, ensure(msg.destination, "destination")), amounts: ensure(msg.amount, "amount").map(decodeAmount), timeout: { timestamp: asIntegerNumber(ensure(msg.timeout, "timeout")) }, memo: msg.memo !== null ? msg.memo : undefined, }; } function decodeReleaseEscrowTx( base: UnsignedTransaction, msg: codecImpl.escrow.IReleaseMsg, ): ReleaseEscrowTx { return { ...base, kind: "bns/release_escrow", escrowId: decodeNumericId(ensure(msg.escrowId, "escrowId")), amounts: ensure(msg.amount, "amount").map(decodeAmount), }; } function decodeReturnEscrowTx(base: UnsignedTransaction, msg: codecImpl.escrow.IReturnMsg): ReturnEscrowTx { return { ...base, kind: "bns/return_escrow", escrowId: decodeNumericId(ensure(msg.escrowId, "escrowId")), }; } function decodeUpdateEscrowPartiesTx( base: UnsignedTransaction, msg: codecImpl.escrow.IUpdatePartiesMsg, ): UpdateEscrowPartiesTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/update_escrow_parties", escrowId: decodeNumericId(ensure(msg.escrowId, "escrowId")), sender: msg.source ? encodeBnsAddress(prefix, msg.source) : undefined, arbiter: msg.arbiter ? encodeBnsAddress(prefix, msg.arbiter) : undefined, recipient: msg.destination ? encodeBnsAddress(prefix, msg.destination) : undefined, }; } // Governance function decodeCreateProposalTx( base: UnsignedTransaction, msg: codecImpl.gov.ICreateProposalMsg, ): CreateProposalTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/create_proposal", title: ensure(msg.title, "title"), action: decodeRawProposalOption(prefix, ensure(msg.rawOption, "rawOption")), description: ensure(msg.description, "description"), electionRuleId: decodeNumericId(ensure(msg.electionRuleId, "electionRuleId")), startTime: asIntegerNumber(ensure(msg.startTime, "startTime")), author: encodeBnsAddress(prefix, ensure(msg.author, "author")), }; } function decodeVoteTx(base: UnsignedTransaction, msg: codecImpl.gov.IVoteMsg): VoteTx { const prefix = addressPrefix(base.chainId); return { ...base, kind: "bns/vote", proposalId: decodeNumericId(ensure(msg.proposalId, "proposalId")), selection: decodeVoteOption(ensure(msg.selected, "selected")), voter: msg.voter ? encodeBnsAddress(prefix, msg.voter) : null, }; } export function decodeMsg(base: UnsignedTransaction, tx: BnsdTxMsg): UnsignedTransaction { // Token sends if (tx.cashSendMsg) return decodeSendTransaction(base, tx.cashSendMsg); // Atomic swaps if (tx.aswapCreateMsg) return decodeSwapOfferTx(base, tx.aswapCreateMsg); if (tx.aswapReleaseMsg) return decodeSwapClaimTx(base, tx.aswapReleaseMsg); if (tx.aswapReturnMsg) return decodeSwapAbortTransaction(base, tx.aswapReturnMsg); // Usernames if (tx.usernameRegisterTokenMsg) return decodeRegisterUsernameTx(base, tx.usernameRegisterTokenMsg); if (tx.usernameChangeTokenTargetsMsg) { return decodeUpdateTargetsOfUsernameTx(base, tx.usernameChangeTokenTargetsMsg); } if (tx.usernameTransferTokenMsg) return decodeTransferUsernameTx(base, tx.usernameTransferTokenMsg); // Accounts if (tx.accountUpdateConfigurationMsg) { return decodeUpdateAccountConfigurationTx(base, tx.accountUpdateConfigurationMsg); } if (tx.accountRegisterDomainMsg) return decodeRegisterDomainTx(base, tx.accountRegisterDomainMsg); if (tx.accountTransferDomainMsg) return decodeTransferDomainTx(base, tx.accountTransferDomainMsg); if (tx.accountRenewDomainMsg) return decodeRenewDomainTx(base, tx.accountRenewDomainMsg); if (tx.accountDeleteDomainMsg) return decodeDeleteDomainTx(base, tx.accountDeleteDomainMsg); if (tx.accountRegisterAccountMsg) return decodeRegisterAccountTx(base, tx.accountRegisterAccountMsg); if (tx.accountTransferAccountMsg) return decodeTransferAccountTx(base, tx.accountTransferAccountMsg); if (tx.accountReplaceAccountTargetsMsg) { return decodeReplaceAccountTargetsTx(base, tx.accountReplaceAccountTargetsMsg); } if (tx.accountDeleteAccountMsg) return decodeDeleteAccountTx(base, tx.accountDeleteAccountMsg); if (tx.accountFlushDomainMsg) return decodeDeleteAllAccountsTx(base, tx.accountFlushDomainMsg); if (tx.accountRenewAccountMsg) return decodeRenewAccountTx(base, tx.accountRenewAccountMsg); if (tx.accountAddAccountCertificateMsg) { return decodeAddAccountCertificateTx(base, tx.accountAddAccountCertificateMsg); } if (tx.accountReplaceAccountMsgFeesMsg) { return decodeReplaceAccountMsgFeesTx(base, tx.accountReplaceAccountMsgFeesMsg); } if (tx.accountDeleteAccountCertificateMsg) { return decodeDeleteAccountCertificateTx(base, tx.accountDeleteAccountCertificateMsg); } // Multisignature contracts if (tx.multisigCreateMsg) return decodeCreateMultisignatureTx(base, tx.multisigCreateMsg); if (tx.multisigUpdateMsg) return decodeUpdateMultisignatureTx(base, tx.multisigUpdateMsg); // Escrows if (tx.escrowCreateMsg) return decodeCreateEscrowTx(base, tx.escrowCreateMsg); if (tx.escrowReleaseMsg) return decodeReleaseEscrowTx(base, tx.escrowReleaseMsg); if (tx.escrowReturnMsg) return decodeReturnEscrowTx(base, tx.escrowReturnMsg); if (tx.escrowUpdatePartiesMsg) return decodeUpdateEscrowPartiesTx(base, tx.escrowUpdatePartiesMsg); // Governance if (tx.govCreateProposalMsg) return decodeCreateProposalTx(base, tx.govCreateProposalMsg); if (tx.govVoteMsg) return decodeVoteTx(base, tx.govVoteMsg); throw new Error("unknown message type in transaction"); }
the_stack
import { Parser, UnitProps } from "@itwin/core-quantity"; import { assert } from "chai"; import { LocalUnitFormatProvider } from "../quantity-formatting/LocalUnitFormatProvider"; import { OverrideFormatEntry, QuantityFormatter, QuantityType, QuantityTypeArg } from "../quantity-formatting/QuantityFormatter"; import { BearingQuantityType } from "./BearingQuantityType"; function withinTolerance(x: number, y: number, tolerance?: number): boolean { const tol: number = undefined !== tolerance ? tolerance : 0.1e-6; const z = x - y; return z >= -tol && z <= tol; } /** setup a local storage mock that contains a unit system and QuantityType.Length override format */ const storageMock = () => { const storage: { [key: string]: any } = { "quantityTypeFormat#user#q:QuantityTypeEnumValue-1": `{"metric":{"type":"Decimal","precision":2,"roundFactor":0,"showSignOption":"OnlyNegative","formatTraits":["keepSingleZero","showUnitLabel"],"decimalSeparator":".","thousandSeparator":",","uomSeparator":" ","stationSeparator":"+","composite":{"spacer":"","includeZero":true,"units":[{"name":"Units.CM","label":"cm"}]}}}`, "unitsystem#user": "metric", }; return { setItem: (key: string, value: string) => { storage[key] = value || ""; }, getItem: (key: string) => { return key in storage ? storage[key] : null; }, removeItem: (key: string) => { delete storage[key]; }, get length() { return Object.keys(storage).length; }, key: (i: number) => { const keys = Object.keys(storage); return keys[i] || null; }, }; }; describe("Quantity formatter", async () => { let quantityFormatter: QuantityFormatter; const propertyDescriptorToRestore = Object.getOwnPropertyDescriptor(window, "localStorage")!; const myLocalStorage = storageMock(); before(async () => { Object.defineProperty(window, "localStorage", { get: () => myLocalStorage, }); }); beforeEach(async () => { quantityFormatter = new QuantityFormatter(); await quantityFormatter.onInitialized(); }); after(async () => { // restore the overriden property getter Object.defineProperty(window, "localStorage", propertyDescriptorToRestore); }); it("Length should honor overrides from LocalUnitFormatProvider", async () => { // set the units settings provider that will set the QuantityFormatter to "metric" and provide overrides to display "cm" await quantityFormatter.setUnitFormattingSettingsProvider(new LocalUnitFormatProvider(quantityFormatter, false)); const expected = `12345.6 cm`; const newFormatterSpec = quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Length); assert(newFormatterSpec !== undefined); const actual = quantityFormatter.formatQuantity(123.456, newFormatterSpec); assert.equal(actual, expected); }); it("Save overrides to localStorage", async () => { const overrideLengthAndCoordinateEntry = { metric: { composite: { includeZero: true, spacer: " ", units: [{ label: "mm", name: "Units.MM" }], }, formatTraits: ["keepSingleZero", "showUnitLabel"], precision: 4, type: "Decimal", }, }; // set the units settings provider that will set the QuantityFormatter to "metric" and provide overrides to display "cm" await quantityFormatter.setUnitFormattingSettingsProvider(new LocalUnitFormatProvider(quantityFormatter, false)); let expected = `12345.6 cm`; let newFormatterSpec = quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Length); assert(newFormatterSpec !== undefined); let actual = quantityFormatter.formatQuantity(123.456, newFormatterSpec); assert.equal(actual, expected); // update the overrides to display "mm" expected = `123456 mm`; await quantityFormatter.setOverrideFormats(QuantityType.Length, overrideLengthAndCoordinateEntry); const storedOverride = JSON.parse(localStorage.getItem("quantityTypeFormat#user#q:QuantityTypeEnumValue-1")!) as OverrideFormatEntry; assert(storedOverride.metric?.composite?.units[0].label === "mm"); assert(storedOverride.metric?.composite?.units[0].name === "Units.MM"); newFormatterSpec = quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Length); actual = quantityFormatter.formatQuantity(123.456, newFormatterSpec); assert.equal(actual, expected); // now delete the overrides to restore to default of "m" expected = `123.456 m`; await quantityFormatter.clearOverrideFormats(QuantityType.Length); newFormatterSpec = quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Length); actual = quantityFormatter.formatQuantity(123.456, newFormatterSpec); assert.equal(actual, expected); assert(localStorage.getItem("quantityTypeFormat#user#q:QuantityTypeEnumValue-1") === null); }); it("Length should be cached during onInitialized processing", async () => { const expected = `405'-0 1/2"`; const newFormatterSpec = quantityFormatter.findFormatterSpecByQuantityType(QuantityType.Length); assert(newFormatterSpec !== undefined); const actual = quantityFormatter.formatQuantity(123.456, newFormatterSpec); assert.equal(actual, expected); }); it("Length format spec retrieved asynchronously", async () => { const expected = `405'-0 1/2"`; const newFormatterSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Length); const actual = quantityFormatter.formatQuantity(123.456, newFormatterSpec); assert.equal(actual, expected); }); it("Set and use length override format", async () => { const overrideLengthAndCoordinateEntry = { metric: { composite: { includeZero: true, spacer: " ", units: [{ label: "cm", name: "Units.CM" }], }, formatTraits: ["keepSingleZero", "showUnitLabel"], precision: 4, type: "Decimal", }, imperial: { composite: { includeZero: true, spacer: " ", units: [{ label: "in", name: "Units.IN" }], }, formatTraits: ["keepSingleZero", "showUnitLabel"], precision: 4, type: "Decimal", }, }; const metricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Length, false); const metricFormattedValue = quantityFormatter.formatQuantity(1.5, metricFormatSpec); assert.equal(metricFormattedValue, "1.5 m"); const imperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Length, true); const imperialFormattedValue = quantityFormatter.formatQuantity(1.5, imperialFormatSpec); assert.equal(imperialFormattedValue, `4'-11"`); await quantityFormatter.setOverrideFormats(QuantityType.Length, overrideLengthAndCoordinateEntry); const overrideMetricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Length, false); const overrideMetricFormattedValue = quantityFormatter.formatQuantity(1.5, overrideMetricFormatSpec); assert.equal(overrideMetricFormattedValue, "150 cm"); const overrideImperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Length, true); const overrideImperialFormattedValue = quantityFormatter.formatQuantity(1.5, overrideImperialFormatSpec); assert.equal(overrideImperialFormattedValue, "59.0551 in"); quantityFormatter.addAlternateLabels("Units.FT", "shoe", "sock"); const alternateLabels = quantityFormatter.alternateUnitLabelsProvider.getAlternateUnitLabels({ name: "Units.FT" } as UnitProps); assert(!!alternateLabels); assert(alternateLabels.includes("shoe")); assert(alternateLabels.includes("sock")); const overrideImperialParserSpec = await quantityFormatter.getParserSpecByQuantityType(QuantityType.Length, true); const overrideValueInMeters1 = quantityFormatter.parseToQuantityValue(`48"`, overrideImperialParserSpec); const overrideValueInMeters2 = quantityFormatter.parseToQuantityValue(`48 in`, overrideImperialParserSpec); const overrideValueInMeters3 = quantityFormatter.parseToQuantityValue(`4 ft`, overrideImperialParserSpec); const overrideValueInMeters4 = quantityFormatter.parseToQuantityValue(`4 shoe`, overrideImperialParserSpec); const overrideValueInMeters5 = quantityFormatter.parseToQuantityValue(`4 sock`, overrideImperialParserSpec); assert(Parser.isParsedQuantity(overrideValueInMeters1)); assert(Parser.isParsedQuantity(overrideValueInMeters2)); assert(Parser.isParsedQuantity(overrideValueInMeters3)); assert(Parser.isParsedQuantity(overrideValueInMeters4)); assert(Parser.isParsedQuantity(overrideValueInMeters5)); if (Parser.isParsedQuantity(overrideValueInMeters1) && Parser.isParsedQuantity(overrideValueInMeters2) && Parser.isParsedQuantity(overrideValueInMeters3) && Parser.isParsedQuantity(overrideValueInMeters4) && Parser.isParsedQuantity(overrideValueInMeters5)) { assert(withinTolerance(overrideValueInMeters1.value, 1.2192)); assert(withinTolerance(overrideValueInMeters1.value, overrideValueInMeters2.value)); assert(withinTolerance(overrideValueInMeters3.value, overrideValueInMeters2.value)); assert(withinTolerance(overrideValueInMeters4.value, overrideValueInMeters5.value)); } }); it("Set and use coordinate and length overrides format (Survey Feet) - deprecate way", async () => { const overrideLengthAndCoordinateEntry = { metric: { composite: { includeZero: true, spacer: " ", units: [{ label: "m", name: "Units.M" }], }, formatTraits: ["keepSingleZero", "showUnitLabel"], precision: 4, type: "Decimal", }, imperial: { composite: { includeZero: true, spacer: " ", units: [{ label: "ft (US Survey)", name: "Units.US_SURVEY_FT" }], }, formatTraits: ["keepSingleZero", "showUnitLabel"], precision: 4, type: "Decimal", }, }; // deprecated way of passing in useImperial let metricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate, false); let metricFormattedValue = quantityFormatter.formatQuantity(100000.0, metricFormatSpec); assert.equal(metricFormattedValue, "100000 m"); let imperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate, true); let imperialFormattedValue = quantityFormatter.formatQuantity(100000.0, imperialFormatSpec); assert.equal(imperialFormattedValue, "328083.99 ft"); await quantityFormatter.setOverrideFormats(QuantityType.Length, overrideLengthAndCoordinateEntry); await quantityFormatter.setOverrideFormats(QuantityType.Coordinate, overrideLengthAndCoordinateEntry); let overrideMetricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Length, false); let overrideMetricFormattedValue = quantityFormatter.formatQuantity(100000.0, overrideMetricFormatSpec); assert.equal(overrideMetricFormattedValue, "100000 m"); overrideMetricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate, false); overrideMetricFormattedValue = quantityFormatter.formatQuantity(100000.0, overrideMetricFormatSpec); assert.equal(overrideMetricFormattedValue, "100000 m"); let overrideImperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Length, true); let overrideImperialFormattedValue = quantityFormatter.formatQuantity(100000.0, overrideImperialFormatSpec); assert.equal(overrideImperialFormattedValue, "328083.3333 ft (US Survey)"); overrideImperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate, true); overrideImperialFormattedValue = quantityFormatter.formatQuantity(100000.0, overrideImperialFormatSpec); assert.equal(overrideImperialFormattedValue, "328083.3333 ft (US Survey)"); let overrideImperialParserSpec = await quantityFormatter.getParserSpecByQuantityType(QuantityType.Length, true); let overrideValueInMeters1 = quantityFormatter.parseToQuantityValue("328083.333333333 ft (US Survey)", overrideImperialParserSpec); let overrideValueInMeters2 = quantityFormatter.parseToQuantityValue("328083.333333333", overrideImperialParserSpec); assert(Parser.isParsedQuantity(overrideValueInMeters1)); assert(Parser.isParsedQuantity(overrideValueInMeters2)); if (Parser.isParsedQuantity(overrideValueInMeters1) && Parser.isParsedQuantity(overrideValueInMeters2)) { assert(withinTolerance(overrideValueInMeters1.value, 100000)); assert(withinTolerance(overrideValueInMeters1.value, overrideValueInMeters2.value)); } overrideImperialParserSpec = await quantityFormatter.getParserSpecByQuantityType(QuantityType.Coordinate, true); overrideValueInMeters1 = quantityFormatter.parseToQuantityValue("328083.333333333 ft (US Survey)", overrideImperialParserSpec); overrideValueInMeters2 = quantityFormatter.parseToQuantityValue("328083.333333333", overrideImperialParserSpec); assert(Parser.isParsedQuantity(overrideValueInMeters1)); assert(Parser.isParsedQuantity(overrideValueInMeters2)); if (Parser.isParsedQuantity(overrideValueInMeters1) && Parser.isParsedQuantity(overrideValueInMeters2)) { assert(withinTolerance(overrideValueInMeters1.value, 100000)); assert(withinTolerance(overrideValueInMeters1.value, overrideValueInMeters2.value)); } await quantityFormatter.clearAllOverrideFormats(); metricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate, false); metricFormattedValue = quantityFormatter.formatQuantity(100000.0, metricFormatSpec); assert.equal(metricFormattedValue, "100000 m"); imperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate, true); imperialFormattedValue = quantityFormatter.formatQuantity(100000.0, imperialFormatSpec); assert.equal(imperialFormattedValue, "328083.99 ft"); }); it("Set and use coordinate and length overrides format (Survey Feet)", async () => { const overrideLengthAndCoordinateEntry = { metric: { composite: { includeZero: true, spacer: " ", units: [{ label: "m", name: "Units.M" }], }, formatTraits: ["keepSingleZero", "showUnitLabel"], precision: 4, type: "Decimal", }, imperial: { composite: { includeZero: true, spacer: " ", units: [{ label: "ft (US Survey)", name: "Units.US_SURVEY_FT" }], }, formatTraits: ["keepSingleZero", "showUnitLabel"], precision: 4, type: "Decimal", }, }; await quantityFormatter.setActiveUnitSystem("metric"); let metricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate); let metricFormattedValue = quantityFormatter.formatQuantity(100000.0, metricFormatSpec); assert.equal(metricFormattedValue, "100000 m"); await quantityFormatter.setActiveUnitSystem("imperial"); let imperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate); let imperialFormattedValue = quantityFormatter.formatQuantity(100000.0, imperialFormatSpec); assert.equal(imperialFormattedValue, "328083.99 ft"); await quantityFormatter.setOverrideFormats(QuantityType.Length, overrideLengthAndCoordinateEntry); await quantityFormatter.setOverrideFormats(QuantityType.Coordinate, overrideLengthAndCoordinateEntry); await quantityFormatter.setActiveUnitSystem("metric"); let overrideMetricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Length); let overrideMetricFormattedValue = quantityFormatter.formatQuantity(100000.0, overrideMetricFormatSpec); assert.equal(overrideMetricFormattedValue, "100000 m"); overrideMetricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate); overrideMetricFormattedValue = quantityFormatter.formatQuantity(100000.0, overrideMetricFormatSpec); assert.equal(overrideMetricFormattedValue, "100000 m"); await quantityFormatter.setActiveUnitSystem("imperial"); let overrideImperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Length); let overrideImperialFormattedValue = quantityFormatter.formatQuantity(100000.0, overrideImperialFormatSpec); assert.equal(overrideImperialFormattedValue, "328083.3333 ft (US Survey)"); overrideImperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate); overrideImperialFormattedValue = quantityFormatter.formatQuantity(100000.0, overrideImperialFormatSpec); assert.equal(overrideImperialFormattedValue, "328083.3333 ft (US Survey)"); let overrideImperialParserSpec = await quantityFormatter.getParserSpecByQuantityType(QuantityType.Length); let overrideValueInMeters1 = quantityFormatter.parseToQuantityValue("328083.333333333 ft (US Survey)", overrideImperialParserSpec); let overrideValueInMeters2 = quantityFormatter.parseToQuantityValue("328083.333333333", overrideImperialParserSpec); assert(Parser.isParsedQuantity(overrideValueInMeters1)); assert(Parser.isParsedQuantity(overrideValueInMeters2)); if (Parser.isParsedQuantity(overrideValueInMeters1) && Parser.isParsedQuantity(overrideValueInMeters2)) { assert(withinTolerance(overrideValueInMeters1.value, 100000)); assert(withinTolerance(overrideValueInMeters1.value, overrideValueInMeters2.value)); } overrideImperialParserSpec = await quantityFormatter.getParserSpecByQuantityType(QuantityType.Coordinate); overrideValueInMeters1 = quantityFormatter.parseToQuantityValue("328083.333333333 ft (US Survey)", overrideImperialParserSpec); overrideValueInMeters2 = quantityFormatter.parseToQuantityValue("328083.333333333", overrideImperialParserSpec); assert(Parser.isParsedQuantity(overrideValueInMeters1)); assert(Parser.isParsedQuantity(overrideValueInMeters2)); if (Parser.isParsedQuantity(overrideValueInMeters1) && Parser.isParsedQuantity(overrideValueInMeters2)) { assert(withinTolerance(overrideValueInMeters1.value, 100000)); assert(withinTolerance(overrideValueInMeters1.value, overrideValueInMeters2.value)); } await quantityFormatter.clearAllOverrideFormats(); imperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate); imperialFormattedValue = quantityFormatter.formatQuantity(100000.0, imperialFormatSpec); assert.equal(imperialFormattedValue, "328083.99 ft"); await quantityFormatter.setActiveUnitSystem("metric"); metricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Coordinate); metricFormattedValue = quantityFormatter.formatQuantity(100000.0, metricFormatSpec); assert.equal(metricFormattedValue, "100000 m"); }); it("Set and use area overrides format (Survey Feet)", async () => { const overrideEntry = { metric: { composite: { includeZero: true, spacer: " ", units: [{ label: "m²", name: "Units.SQ_M" }], }, formatTraits: ["keepSingleZero", "showUnitLabel"], precision: 4, type: "Decimal", }, imperial: { composite: { includeZero: true, spacer: " ", units: [{ label: "ft² (US Survey)", name: "Units.SQ_US_SURVEY_FT" }], }, formatTraits: ["keepSingleZero", "showUnitLabel"], precision: 4, type: "Decimal", }, }; let metricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Area, false); let metricFormattedValue = quantityFormatter.formatQuantity(100000.0, metricFormatSpec); assert.equal(metricFormattedValue, "100000 m²"); let imperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Area, true); let imperialFormattedValue = quantityFormatter.formatQuantity(100000.0, imperialFormatSpec); assert.equal(imperialFormattedValue, "1076391.0417 ft²"); await quantityFormatter.setOverrideFormats(QuantityType.Area, overrideEntry); const overrideMetricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Area, false); const overrideMetricFormattedValue = quantityFormatter.formatQuantity(100000.0, overrideMetricFormatSpec); assert.equal(overrideMetricFormattedValue, "100000 m²"); const overrideImperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Area, true); const overrideImperialFormattedValue = quantityFormatter.formatQuantity(100000.0, overrideImperialFormatSpec); assert.equal(overrideImperialFormattedValue, "1076386.7361 ft² (US Survey)"); const overrideImperialParserSpec = await quantityFormatter.getParserSpecByQuantityType(QuantityType.Area, true); const overrideValueInMeters1 = quantityFormatter.parseToQuantityValue("1076386.7361", overrideImperialParserSpec); const overrideValueInMeters2 = quantityFormatter.parseToQuantityValue("1076386.7361 sussf", overrideImperialParserSpec); // eslint-disable-next-line no-console // console.log(`overrideValueInMeters1=${JSON.stringify(overrideValueInMeters1)}`); assert(Parser.isParsedQuantity(overrideValueInMeters1)); assert(Parser.isParsedQuantity(overrideValueInMeters2)); if (Parser.isParsedQuantity(overrideValueInMeters1) && Parser.isParsedQuantity(overrideValueInMeters2)) { assert(withinTolerance(overrideValueInMeters1.value, 100000, 1.0e-5)); assert(withinTolerance(overrideValueInMeters1.value, overrideValueInMeters2.value)); } await quantityFormatter.clearOverrideFormats(QuantityType.Area); metricFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Area, false); metricFormattedValue = quantityFormatter.formatQuantity(100000.0, metricFormatSpec); assert.equal(metricFormattedValue, "100000 m²"); imperialFormatSpec = await quantityFormatter.getFormatterSpecByQuantityType(QuantityType.Area, true); imperialFormattedValue = quantityFormatter.formatQuantity(100000.0, imperialFormatSpec); assert.equal(imperialFormattedValue, "1076391.0417 ft²"); }); describe("Test native unit conversions", async () => { async function testUnitConversion(magnitude: number, fromUnitName: string, expectedValue: number, toUnitName: string, tolerance?: number) { const fromUnit = await quantityFormatter.findUnitByName(fromUnitName); const toUnit = await quantityFormatter.findUnitByName(toUnitName); const unitConversion = await quantityFormatter.getConversion(fromUnit, toUnit); const convertedValue = (magnitude * unitConversion.factor) + unitConversion.offset; assert(withinTolerance(convertedValue, expectedValue, tolerance), `Expected ${expectedValue} ${toUnitName}, got ${convertedValue} ${toUnitName}`); } it("UnitConversionTests, USCustomaryLengths", async () => { // Conversion tests where expected value is taken directly out of http://www.nist.gov/pml/wmd/pubs/upload/hb44-15-web-final.pdf, Appendix C. Section 4, Page C-8 // Directly from exact values in tables await testUnitConversion(1.0, "Units.MILE", 63360, "Units.IN"); await testUnitConversion(1.0, "Units.MILE", 5280, "Units.FT"); await testUnitConversion(1.0, "Units.MILE", 1760, "Units.YRD"); await testUnitConversion(1.0, "Units.MILE", 80, "Units.CHAIN"); await testUnitConversion(1.0, "Units.IN", 2.54, "Units.CM"); await testUnitConversion(1.0, "Units.FT", 30.48, "Units.CM"); await testUnitConversion(1.0, "Units.YRD", 91.44, "Units.CM"); await testUnitConversion(1.0, "Units.CHAIN", 66.0 * 30.48, "Units.CM"); await testUnitConversion(1.0, "Units.MILE", 160934.4, "Units.CM"); }); it("UnitConversionTests, UsSurveyLengths", async () => { // Conversion tests where expected value is taken directly out of http://www.nist.gov/pml/wmd/pubs/upload/hb44-15-web-final.pdf, Appendix C. Section 4, Page C-8 // Exact values from document used for these conversions await testUnitConversion(1.0, "Units.FT", 0.999998, "Units.US_SURVEY_FT"); await testUnitConversion(1.0, "Units.FT", 0.0254 * 39.37, "Units.US_SURVEY_FT"); await testUnitConversion(1.0, "Units.US_SURVEY_FT", 1.0 / 0.999998, "Units.FT"); await testUnitConversion(1.0, "Units.US_SURVEY_FT", 1200.0 / 3937.0, "Units.M"); await testUnitConversion(1.0, "Units.M", 3937.0 / 1200.0, "Units.US_SURVEY_FT"); await testUnitConversion(1.0, "Units.US_SURVEY_MILE", 5280.0 * 1200.0 / 3937.0, "Units.M"); await testUnitConversion(1.0, "Units.US_SURVEY_MILE", 1.0 / 0.999998, "Units.MILE"); await testUnitConversion(1.0, "Units.MILE", 0.999998, "Units.US_SURVEY_MILE"); await testUnitConversion(1.0, "Units.M", 3937.0 / 1200.0 / 5280.0, "Units.US_SURVEY_MILE"); await testUnitConversion(1.0, "Units.US_SURVEY_FT", 1.0 / 66.0, "Units.US_SURVEY_CHAIN"); await testUnitConversion(1.0, "Units.M", 39.37, "Units.US_SURVEY_IN"); await testUnitConversion(12.0, "Units.US_SURVEY_IN", 1200.0 / 3937.0, "Units.M"); // Directly from exact values in tables await testUnitConversion(1.0, "Units.US_SURVEY_MILE", 63360, "Units.US_SURVEY_IN"); await testUnitConversion(1.0, "Units.US_SURVEY_MILE", 5280, "Units.US_SURVEY_FT"); await testUnitConversion(1.0, "Units.US_SURVEY_MILE", 1760, "Units.US_SURVEY_YRD"); await testUnitConversion(1.0, "Units.US_SURVEY_MILE", 80, "Units.US_SURVEY_CHAIN", 1.0e-6); // Exact values do not exist in document await testUnitConversion(1.0, "Units.US_SURVEY_FT", 0.3048006, "Units.M"); await testUnitConversion(1.0, "Units.US_SURVEY_CHAIN", 20.11684, "Units.M"); await testUnitConversion(1.0, "Units.US_SURVEY_YRD", 3.0 * 0.3048006, "Units.M"); await testUnitConversion(1.0, "Units.US_SURVEY_MILE", 1609.347, "Units.M", 1.0e-3); }); }); }); describe("Test Custom QuantityType", async () => { let quantityFormatter: QuantityFormatter; beforeEach(async () => { quantityFormatter = new QuantityFormatter(); await quantityFormatter.onInitialized(); }); it("QuantityFormatter should handle unit system changes properly", async () => { const persistenceUnit = await quantityFormatter.findUnitByName("Units.RAD"); const quantityTypeDefinition = new BearingQuantityType(persistenceUnit); let wasRegistered = await quantityFormatter.registerQuantityType(quantityTypeDefinition); assert.equal(wasRegistered, true); // only allow a single registration wasRegistered = await quantityFormatter.registerQuantityType(quantityTypeDefinition); assert.equal(wasRegistered, false); const formatterSpec = await quantityFormatter.getFormatterSpecByQuantityType("Bearing"); assert.isDefined(formatterSpec); const rad45 = Math.PI / 4; const formattedAngle = formatterSpec!.applyFormatting(rad45); assert.equal(formattedAngle, `N 45°0'0" E`); const parserSpec = await quantityFormatter.getParserSpecByQuantityType("Bearing"); assert.isDefined(parserSpec); const parsedRadians = parserSpec!.parseToQuantityValue("n45e"); assert(Parser.isParsedQuantity(parsedRadians)); if (Parser.isParsedQuantity(parsedRadians)) assert.equal(parsedRadians.value, rad45); }); }); describe("Test Formatted Quantities", async () => { let quantityFormatter: QuantityFormatter; beforeEach(async () => { quantityFormatter = new QuantityFormatter(); await quantityFormatter.onInitialized(); }); async function testFormatting(type: QuantityTypeArg, magnitude: number, expectedValue: string) { const formatterSpec = await quantityFormatter.getFormatterSpecByQuantityType(type); const formattedValue = quantityFormatter.formatQuantity(magnitude, formatterSpec); // console.log(`Type=${type} formatted value=${formattedValue}`); // eslint-disable-line no-console assert.equal(formattedValue, expectedValue); } it("QuantityFormatter should handle unit system changes properly", async () => { assert.isTrue(quantityFormatter.activeUnitSystem === "imperial"); await testFormatting(QuantityType.Length, 1000.0, `3280'-10 1/8"`); await testFormatting(QuantityType.Angle, Math.PI / 2, `90°0'0"`); await testFormatting(QuantityType.Area, 1000.0, "10763.9104 ft²"); await testFormatting(QuantityType.Coordinate, 1000.0, "3280.84 ft"); await testFormatting(QuantityType.LatLong, Math.PI, `180°0'0"`); await testFormatting(QuantityType.LatLong, 0.2645, `15°9'17.0412"`); await testFormatting(QuantityType.LengthEngineering, 1000.0, "3280.8399 ft"); await testFormatting(QuantityType.LengthSurvey, 1000.0, "3280.8333 ft (US Survey)"); await testFormatting(QuantityType.Stationing, 1000.0, "32+80.84"); await testFormatting(QuantityType.Volume, 1000.0, "35314.6662 ft³"); await quantityFormatter.setActiveUnitSystem("metric"); await testFormatting(QuantityType.Length, 1000.0, `1000 m`); await testFormatting(QuantityType.Angle, Math.PI / 2, `90°`); await testFormatting(QuantityType.Area, 1000.0, "1000 m²"); await testFormatting(QuantityType.Coordinate, 1000.0, "1000 m"); await testFormatting(QuantityType.LatLong, Math.PI, `180°0'0"`); await testFormatting(QuantityType.LengthEngineering, 1000.0, "1000 m"); await testFormatting(QuantityType.LengthSurvey, 1000.0, "1000 m"); await testFormatting(QuantityType.Stationing, 1000.0, "1+000.00"); await testFormatting(QuantityType.Stationing, 15918.01, "15+918.01"); await testFormatting(QuantityType.Volume, 1000.0, "1000 m³"); await quantityFormatter.setActiveUnitSystem("usCustomary"); await testFormatting(QuantityType.Length, 1000.0, `3280'-10 1/8"`); await testFormatting(QuantityType.Angle, Math.PI / 2, `90°0'0"`); await testFormatting(QuantityType.Area, 1000.0, "10763.9104 ft²"); await testFormatting(QuantityType.Coordinate, 1000.0, "3280.84 ft"); await testFormatting(QuantityType.LatLong, Math.PI, `180°0'0"`); await testFormatting(QuantityType.LengthEngineering, 1000.0, "3280.8399 ft"); await testFormatting(QuantityType.LengthSurvey, 1000.0, "3280.8333 ft"); await testFormatting(QuantityType.Stationing, 1000.0, "32+80.84"); await testFormatting(QuantityType.Volume, 1000.0, "35314.6662 ft³"); await quantityFormatter.setActiveUnitSystem("usSurvey"); await testFormatting(QuantityType.Length, 1000.0, `3280.8333 ft`); await testFormatting(QuantityType.Angle, Math.PI / 2, `90°0'0"`); await testFormatting(QuantityType.Area, 1000.0, "10763.8674 ft²"); await testFormatting(QuantityType.Coordinate, 1000.0, "3280.83 ft"); await testFormatting(QuantityType.LatLong, Math.PI, `180°0'0"`); await testFormatting(QuantityType.LengthEngineering, 1000.0, "3280.8333 ft"); await testFormatting(QuantityType.LengthSurvey, 1000.0, "3280.8333 ft"); await testFormatting(QuantityType.Stationing, 1000.0, "32+80.83"); await testFormatting(QuantityType.Volume, 1000.0, "35314.4548 ft³"); }); });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { VirtualMachineRunCommands } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ComputeManagementClient } from "../computeManagementClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { RunCommandDocumentBase, VirtualMachineRunCommandsListNextOptionalParams, VirtualMachineRunCommandsListOptionalParams, VirtualMachineRunCommand, VirtualMachineRunCommandsListByVirtualMachineNextOptionalParams, VirtualMachineRunCommandsListByVirtualMachineOptionalParams, VirtualMachineRunCommandsListResponse, VirtualMachineRunCommandsGetOptionalParams, VirtualMachineRunCommandsGetResponse, VirtualMachineRunCommandsCreateOrUpdateOptionalParams, VirtualMachineRunCommandsCreateOrUpdateResponse, VirtualMachineRunCommandUpdate, VirtualMachineRunCommandsUpdateOptionalParams, VirtualMachineRunCommandsUpdateResponse, VirtualMachineRunCommandsDeleteOptionalParams, VirtualMachineRunCommandsGetByVirtualMachineOptionalParams, VirtualMachineRunCommandsGetByVirtualMachineResponse, VirtualMachineRunCommandsListByVirtualMachineResponse, VirtualMachineRunCommandsListNextResponse, VirtualMachineRunCommandsListByVirtualMachineNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing VirtualMachineRunCommands operations. */ export class VirtualMachineRunCommandsImpl implements VirtualMachineRunCommands { private readonly client: ComputeManagementClient; /** * Initialize a new instance of the class VirtualMachineRunCommands class. * @param client Reference to the service client */ constructor(client: ComputeManagementClient) { this.client = client; } /** * Lists all available run commands for a subscription in a location. * @param location The location upon which run commands is queried. * @param options The options parameters. */ public list( location: string, options?: VirtualMachineRunCommandsListOptionalParams ): PagedAsyncIterableIterator<RunCommandDocumentBase> { const iter = this.listPagingAll(location, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(location, options); } }; } private async *listPagingPage( location: string, options?: VirtualMachineRunCommandsListOptionalParams ): AsyncIterableIterator<RunCommandDocumentBase[]> { let result = await this._list(location, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext(location, continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( location: string, options?: VirtualMachineRunCommandsListOptionalParams ): AsyncIterableIterator<RunCommandDocumentBase> { for await (const page of this.listPagingPage(location, options)) { yield* page; } } /** * The operation to get all run commands of a Virtual Machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine containing the run command. * @param options The options parameters. */ public listByVirtualMachine( resourceGroupName: string, vmName: string, options?: VirtualMachineRunCommandsListByVirtualMachineOptionalParams ): PagedAsyncIterableIterator<VirtualMachineRunCommand> { const iter = this.listByVirtualMachinePagingAll( resourceGroupName, vmName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByVirtualMachinePagingPage( resourceGroupName, vmName, options ); } }; } private async *listByVirtualMachinePagingPage( resourceGroupName: string, vmName: string, options?: VirtualMachineRunCommandsListByVirtualMachineOptionalParams ): AsyncIterableIterator<VirtualMachineRunCommand[]> { let result = await this._listByVirtualMachine( resourceGroupName, vmName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByVirtualMachineNext( resourceGroupName, vmName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByVirtualMachinePagingAll( resourceGroupName: string, vmName: string, options?: VirtualMachineRunCommandsListByVirtualMachineOptionalParams ): AsyncIterableIterator<VirtualMachineRunCommand> { for await (const page of this.listByVirtualMachinePagingPage( resourceGroupName, vmName, options )) { yield* page; } } /** * Lists all available run commands for a subscription in a location. * @param location The location upon which run commands is queried. * @param options The options parameters. */ private _list( location: string, options?: VirtualMachineRunCommandsListOptionalParams ): Promise<VirtualMachineRunCommandsListResponse> { return this.client.sendOperationRequest( { location, options }, listOperationSpec ); } /** * Gets specific run command for a subscription in a location. * @param location The location upon which run commands is queried. * @param commandId The command id. * @param options The options parameters. */ get( location: string, commandId: string, options?: VirtualMachineRunCommandsGetOptionalParams ): Promise<VirtualMachineRunCommandsGetResponse> { return this.client.sendOperationRequest( { location, commandId, options }, getOperationSpec ); } /** * The operation to create or update the run command. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine where the run command should be created or updated. * @param runCommandName The name of the virtual machine run command. * @param runCommand Parameters supplied to the Create Virtual Machine RunCommand operation. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, vmName: string, runCommandName: string, runCommand: VirtualMachineRunCommand, options?: VirtualMachineRunCommandsCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<VirtualMachineRunCommandsCreateOrUpdateResponse>, VirtualMachineRunCommandsCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<VirtualMachineRunCommandsCreateOrUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, vmName, runCommandName, runCommand, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * The operation to create or update the run command. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine where the run command should be created or updated. * @param runCommandName The name of the virtual machine run command. * @param runCommand Parameters supplied to the Create Virtual Machine RunCommand operation. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, vmName: string, runCommandName: string, runCommand: VirtualMachineRunCommand, options?: VirtualMachineRunCommandsCreateOrUpdateOptionalParams ): Promise<VirtualMachineRunCommandsCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, vmName, runCommandName, runCommand, options ); return poller.pollUntilDone(); } /** * The operation to update the run command. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine where the run command should be updated. * @param runCommandName The name of the virtual machine run command. * @param runCommand Parameters supplied to the Update Virtual Machine RunCommand operation. * @param options The options parameters. */ async beginUpdate( resourceGroupName: string, vmName: string, runCommandName: string, runCommand: VirtualMachineRunCommandUpdate, options?: VirtualMachineRunCommandsUpdateOptionalParams ): Promise< PollerLike< PollOperationState<VirtualMachineRunCommandsUpdateResponse>, VirtualMachineRunCommandsUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<VirtualMachineRunCommandsUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, vmName, runCommandName, runCommand, options }, updateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * The operation to update the run command. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine where the run command should be updated. * @param runCommandName The name of the virtual machine run command. * @param runCommand Parameters supplied to the Update Virtual Machine RunCommand operation. * @param options The options parameters. */ async beginUpdateAndWait( resourceGroupName: string, vmName: string, runCommandName: string, runCommand: VirtualMachineRunCommandUpdate, options?: VirtualMachineRunCommandsUpdateOptionalParams ): Promise<VirtualMachineRunCommandsUpdateResponse> { const poller = await this.beginUpdate( resourceGroupName, vmName, runCommandName, runCommand, options ); return poller.pollUntilDone(); } /** * The operation to delete the run command. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine where the run command should be deleted. * @param runCommandName The name of the virtual machine run command. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, vmName: string, runCommandName: string, options?: VirtualMachineRunCommandsDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, vmName, runCommandName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * The operation to delete the run command. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine where the run command should be deleted. * @param runCommandName The name of the virtual machine run command. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, vmName: string, runCommandName: string, options?: VirtualMachineRunCommandsDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, vmName, runCommandName, options ); return poller.pollUntilDone(); } /** * The operation to get the run command. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine containing the run command. * @param runCommandName The name of the virtual machine run command. * @param options The options parameters. */ getByVirtualMachine( resourceGroupName: string, vmName: string, runCommandName: string, options?: VirtualMachineRunCommandsGetByVirtualMachineOptionalParams ): Promise<VirtualMachineRunCommandsGetByVirtualMachineResponse> { return this.client.sendOperationRequest( { resourceGroupName, vmName, runCommandName, options }, getByVirtualMachineOperationSpec ); } /** * The operation to get all run commands of a Virtual Machine. * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine containing the run command. * @param options The options parameters. */ private _listByVirtualMachine( resourceGroupName: string, vmName: string, options?: VirtualMachineRunCommandsListByVirtualMachineOptionalParams ): Promise<VirtualMachineRunCommandsListByVirtualMachineResponse> { return this.client.sendOperationRequest( { resourceGroupName, vmName, options }, listByVirtualMachineOperationSpec ); } /** * ListNext * @param location The location upon which run commands is queried. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( location: string, nextLink: string, options?: VirtualMachineRunCommandsListNextOptionalParams ): Promise<VirtualMachineRunCommandsListNextResponse> { return this.client.sendOperationRequest( { location, nextLink, options }, listNextOperationSpec ); } /** * ListByVirtualMachineNext * @param resourceGroupName The name of the resource group. * @param vmName The name of the virtual machine containing the run command. * @param nextLink The nextLink from the previous successful call to the ListByVirtualMachine method. * @param options The options parameters. */ private _listByVirtualMachineNext( resourceGroupName: string, vmName: string, nextLink: string, options?: VirtualMachineRunCommandsListByVirtualMachineNextOptionalParams ): Promise<VirtualMachineRunCommandsListByVirtualMachineNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, vmName, nextLink, options }, listByVirtualMachineNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.RunCommandListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.location1 ], headerParameters: [Parameters.accept1], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/runCommands/{commandId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.RunCommandDocument } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.location1, Parameters.commandId ], headerParameters: [Parameters.accept1], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.VirtualMachineRunCommand }, 201: { bodyMapper: Mappers.VirtualMachineRunCommand }, 202: { bodyMapper: Mappers.VirtualMachineRunCommand }, 204: { bodyMapper: Mappers.VirtualMachineRunCommand }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.runCommand, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.vmName, Parameters.runCommandName ], headerParameters: [Parameters.contentType, Parameters.accept1], mediaType: "json", serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.VirtualMachineRunCommand }, 201: { bodyMapper: Mappers.VirtualMachineRunCommand }, 202: { bodyMapper: Mappers.VirtualMachineRunCommand }, 204: { bodyMapper: Mappers.VirtualMachineRunCommand }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.runCommand1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.vmName, Parameters.runCommandName ], headerParameters: [Parameters.contentType, Parameters.accept1], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.vmName, Parameters.runCommandName ], headerParameters: [Parameters.accept1], serializer }; const getByVirtualMachineOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.VirtualMachineRunCommand }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.expand], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.vmName, Parameters.runCommandName ], headerParameters: [Parameters.accept1], serializer }; const listByVirtualMachineOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.VirtualMachineRunCommandsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.expand], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.vmName ], headerParameters: [Parameters.accept1], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.RunCommandListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.nextLink, Parameters.location1 ], headerParameters: [Parameters.accept1], serializer }; const listByVirtualMachineNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.VirtualMachineRunCommandsListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.expand], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink, Parameters.vmName ], headerParameters: [Parameters.accept1], serializer };
the_stack
import { DI, IContainer, Registration } from '@aurelia/kernel'; import { StandardConfiguration, Aurelia as $Aurelia, IPlatform, IAppRoot, CustomElementType, CustomElement, IHydratedParentController } from '@aurelia/runtime-html'; import { BrowserPlatform } from '@aurelia/platform-browser'; import type { ISinglePageApp, IEnhancementConfig } from '@aurelia/runtime-html'; export const PLATFORM = BrowserPlatform.getOrCreate(globalThis); export { IPlatform }; function createContainer(): IContainer { return DI.createContainer() .register( Registration.instance(IPlatform, PLATFORM), StandardConfiguration, ); } export class Aurelia extends $Aurelia { public constructor(container: IContainer = createContainer()) { super(container); } public static start(root: IAppRoot | undefined): void | Promise<void> { return new Aurelia().start(root); } public static app(config: ISinglePageApp | unknown): Omit<Aurelia, 'register' | 'app' | 'enhance'> { return new Aurelia().app(config); } public static enhance<T extends unknown>(config: IEnhancementConfig<T>, parentController?: IHydratedParentController): ReturnType<$Aurelia['enhance']> { return new Aurelia().enhance(config, parentController); } public static register(...params: readonly unknown[]): Aurelia { return new Aurelia().register(...params); } public app(config: ISinglePageApp | unknown): Omit<this, 'register' | 'app' | 'enhance'> { if (CustomElement.isType(config as CustomElementType)) { // Default to custom element element name const definition = CustomElement.getDefinition(config as CustomElementType); let host = document.querySelector(definition.name); if (host === null) { // When no target is found, default to body. // For example, when user forgot to write <my-app></my-app> in html. host = document.body; } return super.app({ host: host as HTMLElement, component: config as CustomElementType }); } return super.app(config as ISinglePageApp); } } export default Aurelia; export { Interceptor, // RetryConfiguration, // RetryableRequest, // ValidInterceptorMethodName, json, // retryStrategy, // RetryInterceptor, HttpClientConfiguration, HttpClient, IHttpClient, } from '@aurelia/fetch-client'; export { all, DI, IContainer, // IDefaultableInterfaceSymbol, // IFactory, inject, IRegistration, IRegistry, IResolver, IServiceLocator, Key, lazy, optional, // RegisterSelf, Registration, // ResolveCallback, singleton, transient, // Injectable, // InterfaceSymbol, InstanceProvider, Resolved, // Transformer, Class, Constructable, ConstructableClass, // Diff, IDisposable, // IFrameRequestCallback, IIndexable, // IPerformance, // ITimerHandler, // IWindowOrWorkerGlobalScope, // KnownKeys, // NoInfer, // Omit, // OptionalKnownKeys, // OptionalValuesOf, // Overwrite, // Param0, // Param1, // Param2, // Param3, // Pick2, // Pick3, // Primitive, // Public, // Purify, // RequiredKnownKeys, // RequiredValuesOf, // StrictPrimitive, // Unwrap, // ValuesOf, // Writable, // IfEquals, // ReadonlyKeys, // WritableKeys, // metadata, Metadata, // IConsoleLike, ColorOptions, // ILogConfig, // ILogEvent, // ILogEventFactory, // ISink, ILogger, // LogConfig, // DefaultLogEvent, // DefaultLogEventFactory, // DefaultLogger, ConsoleSink, LoggerConfiguration, // relativeToFile, // join, // parseQueryString, // IQueryParams, emptyArray, emptyObject, noop, // ITraceInfo, // ITraceWriter, // ILiveLoggingOptions, LogLevel, // IResourceDefinition, // IResourceDescriptions, // IResourceKind, // IResourceType, // ResourceDescription, // ResourcePartDescription, // fromAnnotationOrDefinitionOrTypeOrDefault, // fromAnnotationOrTypeOrDefault, // fromDefinitionOrDefault, EventAggregator, IEventAggregator, isArrayIndex, camelCase, kebabCase, pascalCase, toArray, // nextId, // resetId, // compareNumber, // mergeDistinct, // isNumberOrBigInt, // isStringOrDate, bound, // mergeArrays, // mergeObjects, // firstDefined, // getPrototypeChain, } from '@aurelia/kernel'; export { RouterOptions, IRouter, IRouterEvents, Router, RouteNode, route, Route, RouteConfig, IRouteContext, IRouteViewModel, NavigationInstruction, Routeable, Params, RouterConfiguration, RouterRegistration, } from '@aurelia/router'; export { // CallFunctionExpression, // connects, // observes, // callsFunction, // hasAncestor, // isAssignable, // isLeftHandSide, // isPrimary, // isResource, // hasBind, // hasUnbind, // isLiteral, // arePureLiterals, // isPureLiteral, // CustomExpression, // BindingBehaviorExpression, // ValueConverterExpression, // AssignExpression, // ConditionalExpression, // AccessThisExpression, // AccessScopeExpression, // AccessMemberExpression, // AccessKeyedExpression, // CallScopeExpression, // CallMemberExpression, // BinaryExpression, // UnaryExpression, // PrimitiveLiteralExpression, // HtmlLiteralExpression, // ArrayLiteralExpression, // ObjectLiteralExpression, // TemplateExpression, // TaggedTemplateExpression, // ArrayBindingPattern, // ObjectBindingPattern, // BindingIdentifier, // ForOfStatement, // Interpolation, // AnyBindingExpression, // IsPrimary, // IsLiteral, // IsLeftHandSide, // IsUnary, // IsBinary, // IsConditional, // IsAssign, // IsValueConverter, // IsBindingBehavior, // IsAssignable, // IsExpression, // IsExpressionOrStatement, // Connects, // Observes, // CallsFunction, // IsResource, // HasBind, // HasUnbind, // HasAncestor, // IVisitor, // IExpression, // IAccessKeyedExpression, // IAccessMemberExpression, // IAccessScopeExpression, // IAccessThisExpression, // IArrayBindingPattern, // IArrayLiteralExpression, // IAssignExpression, // IBinaryExpression, // IBindingBehaviorExpression, // IBindingIdentifier, // ICallFunctionExpression, // ICallMemberExpression, // ICallScopeExpression, // IConditionalExpression, // ForOfStatement, // IHtmlLiteralExpression, // Interpolation, // IObjectBindingPattern, // IObjectLiteralExpression, // IPrimitiveLiteralExpression, // ITaggedTemplateExpression, // ITemplateExpression, // IUnaryExpression, // IValueConverterExpression, // BinaryOperator, // BindingIdentifierOrPattern, // UnaryOperator, // PropertyBinding, // CallBinding, // IObserverLocatorBasedConnectable, // IConnectableBinding, // connectable, // IExpressionParser, // ExpressionType, // MultiInterpolationBinding, // InterpolationBinding, // LetBinding, // RefBinding, // ArrayObserver, // enableArrayObservation, // disableArrayObservation, // applyMutationsToIndices, // synchronizeIndices, // MapObserver, // enableMapObservation, // disableMapObservation, // SetObserver, // enableSetObservation, // disableSetObservation, // BindingContext, // OverrideContext, // CollectionLengthObserver, // CollectionSizeObserver, // IDirtyChecker, // DirtyCheckProperty, // DirtyCheckSettings, ComputedObserver, ComputedWatcher, ExpressionWatcher, Watch, watch, // IObjectObservationAdapter, IObserverLocator, // ITargetObserverLocator, // ITargetAccessorLocator, // getCollectionObserver, // ObserverLocator, // PrimitiveObserver, // PropertyAccessor, // BindableObserver, // SetterObserver, ISignaler, subscriberCollection, bindingBehavior, BindingBehavior, BindingBehaviorInstance, // PartialBindingBehaviorDefinition, // BindingBehaviorKind, // BindingBehaviorDecorator, // BindingBehaviorInstance, // BindingBehaviorType, // BindingModeBehavior, // OneTimeBindingBehavior, // ToViewBindingBehavior, // FromViewBindingBehavior, // TwoWayBindingBehavior, // DebounceBindingBehavior, // SignalableBinding, // SignalBindingBehavior, // ThrottleBindingBehavior, customAttribute, // CustomAttributeDecorator, CustomAttribute, // CustomAttributeDefinition // CustomAttributeKind, // CustomAttributeType, // PartialCustomAttributeDefinition, templateController, // FrequentMutations, // InfrequentMutations, // ObserveShallow, // If, // Else, // Repeat, // Replaceable, // With, containerless, customElement, CustomElement, // CustomElementDecorator, // CustomElementKind, // CustomElementType, // CustomElementDefinition, // PartialCustomElementDefinition, // IElementProjector, // IProjectorLocator, useShadowDOM, ValueConverter, // ValueConverterDefinition, // PartialValueConverterDefinition, // ValueConverterKind, // ValueConverterDecorator, ValueConverterInstance, // ValueConverterType, valueConverter, // ISanitizer, // SanitizeValueConverter, // ViewValueConverter, // Clock, // IClock, // IClockSettings, // ITask, // TaskQueue, // QueueTaskOptions, // Task, // TaskAbortError, // TaskCallback, // TaskQueue, AppTask, TaskQueuePriority, // TaskStatus, // QueueTaskTargetOptions, bindable, PartialBindableDefinition, // BindableDefinition, Bindable, // PartialChildrenDefinition, // ChildrenDefinition, // Children, children, // These exports are temporary until we have a proper way to unit test them Controller, ViewFactory, // IViewLocator, // ViewLocator, // view, // Views, // Aurelia, // Replaced by quick-start wrapper // IDOMInitializer, // ISinglePageApp, IAppRoot, IWorkTracker, // IfRegistration, // ElseRegistration, // RepeatRegistration, // ReplaceableRegistration, // WithRegistration, // SanitizeValueConverterRegistration, // DebounceBindingBehaviorRegistration, // OneTimeBindingBehaviorRegistration, // ToViewBindingBehaviorRegistration, // FromViewBindingBehaviorRegistration, // SignalBindingBehaviorRegistration, // ThrottleBindingBehaviorRegistration, // TwoWayBindingBehaviorRegistration, // RefBindingRendererRegistration, // CallBindingRendererRegistration, // CustomAttributeRendererRegistration, // CustomElementRendererRegistration, // InterpolationBindingRendererRegistration, // IteratorBindingRendererRegistration, // LetElementRendererRegistration, // PropertyBindingRendererRegistration, // SetPropertyRendererRegistration, // TemplateControllerRendererRegistration, // DefaultResources as RuntimeDefaultResources, // IObserverLocatorRegistration, // IRendererRegistration, // RuntimeConfiguration, // AttributeInstruction, // ICallBindingInstruction, // IHydrateAttributeInstruction, // IHydrateElementInstruction, // IHydrateLetElementInstruction, // IHydrateTemplateController, // IInterpolationInstruction, // IIteratorBindingInstruction, // ILetBindingInstruction, // IInstructionRow, // InstructionTypeName, // IPropertyBindingInstruction, // IRefBindingInstruction, // ISetPropertyInstruction, // isInstruction, // IInstruction, // NodeInstruction, // IInstruction, // InstructionType, // PartialCustomElementDefinitionParts, alias, registerAliases, // DOM, should expose the one exported in runtime-html INode, IEventTarget, IRenderLocation, // NodeSequence, // INodeSequence, // INodeSequenceFactory, BindingMode, // ExpressionKind, // Hooks, LifecycleFlags, // State, // CallBindingInstruction, // HydrateAttributeInstruction, // HydrateElementInstruction, // HydrateTemplateController, // InterpolationInstruction, // IteratorBindingInstruction, // LetBindingInstruction, // HydrateLetElementInstruction, // RefBindingInstruction, // SetPropertyInstruction, // ViewModelKind, // IBinding, // IViewModel, ICustomAttributeViewModel, ICustomElementViewModel, // IController, // IContainer, // IViewCache, // IViewFactory, // MountStrategy, // AccessorOrObserver, // Collection, // CollectionKind, // DelegationStrategy, // IAccessor, // IBindingContext, // ICollectionChangeTracker, // ICollectionObserver, // ICollectionSubscriber, IndexMap, // IObservable, // IObservedArray, // IObservedMap, // IObservedSet, // IOverrideContext, // Scope, // ISubscribable, // ISubscriberCollection, // ObservedCollection, // CollectionObserver, // ICollectionSubscriberCollection, // ICollectionSubscribable, // ISubscriber, // isIndexMap, // copyIndexMap, // cloneIndexMap, // createIndexMap, renderer, // DefaultBindingLanguage as JitDefaultBindingLanguage, // JitConfiguration, // Access, // Precedence, // Char, // These exports are temporary until we have a proper way to unit test them // parseExpression, // BindableInfo, // ElementInfo, // AttrInfo, // AnySymbol, // BindingSymbol, // CustomAttributeSymbol, // CustomElementSymbol, // ElementSymbol, // LetElementSymbol, // NodeSymbol, // ParentNodeSymbol, // PlainAttributeSymbol, // PlainElementSymbol, // ReplacePartSymbol, // ResourceAttributeSymbol, // SymbolFlags, // SymbolWithBindings, // SymbolWithMarker, // SymbolWithTemplate, // TemplateControllerSymbol, // TextSymbol IAurelia, // Listener, // AttributeBinding, // AttributeNSAccessor, // IInputElement, // CheckedObserver, // ClassAttributeAccessor, // DataAttributeAccessor, // ElementPropertyAccessor, // IManagedEvent, // ListenerTracker, // DelegateOrCaptureSubscription, // TriggerSubscription, // IElementConfiguration, // IEventDelegator, // IEventSubscriber, // IEventTargetWithLookups, // EventSubscriber, // EventSubscription, // EventDelegator, NodeObserverLocator, // TargetAccessorLocator, // TargetObserverLocator, // ISelectElement, // IOptionElement, // SelectValueObserver, // StyleAttributeAccessor, // ISVGAnalyzer, // ValueAttributeObserver, // AttrBindingBehavior, // SelfableBinding, // SelfBindingBehavior, // UpdateTriggerBindingBehavior, // UpdateTriggerableBinding, // UpdateTriggerableObserver, // Focus, // Portal, // PortalTarget, // PortalLifecycleCallback, // Subject, // Compose, IAuSlotsInfo, AuSlotsInfo, // IProjectorLocatorRegistration, // ITargetAccessorLocatorRegistration, // ITargetObserverLocatorRegistration, // ITemplateFactoryRegistration, // DefaultComponents as RuntimeHtmlDefaultComponents, // CompiledTemplate, // ChildrenObserver, // IRenderer, // IInstructionTypeClassifier, // IRenderingEngine, // ITemplate, ITemplateCompiler, // ITemplateFactory, ITemplateCompilerHooks, TemplateCompilerHooks, templateCompilerHooks, // RenderContext // AttrSyntax, // IAttributeParser, attributePattern, // AttributePatternDefinition, IAttributePattern, // IAttributePatternHandler, // Interpretation, // ISyntaxInterpreter, IAttrMapper, // AtPrefixedTriggerAttributePattern, // ColonPrefixedBindAttributePattern, // DotSeparatedAttributePattern, // RefAttributePattern, bindingCommand, // BindingCommand, BindingCommandInstance, // BindingCommandDefinition, // BindingCommandKind, // BindingCommandType, // CallBindingCommand, // DefaultBindingCommand, // ForBindingCommand, // FromViewBindingCommand, // OneTimeBindingCommand, // ToViewBindingCommand, // TwoWayBindingCommand, IEnhancementConfig, IHydratedParentController, // IExpressionParserRegistration, // DefaultComponents as JitDefaultComponents, // RefAttributePatternRegistration, // DotSeparatedAttributePatternRegistration, // DefaultBindingSyntax, // AtPrefixedTriggerAttributePatternRegistration, // ColonPrefixedBindAttributePatternRegistration, ShortHandBindingSyntax, // CallBindingCommandRegistration, // DefaultBindingCommandRegistration, // ForBindingCommandRegistration, // FromViewBindingCommandRegistration, // OneTimeBindingCommandRegistration, // ToViewBindingCommandRegistration, // TwoWayBindingCommandRegistration, // AttrBindingBehaviorRegistration, // SelfBindingBehaviorRegistration, // UpdateTriggerBindingBehaviorRegistration, // ComposeRegistration, // DefaultResources as RuntimeHtmlDefaultResources, // AttributeBindingRendererRegistration, // ListenerBindingRendererRegistration, // SetAttributeRendererRegistration, // SetClassAttributeRendererRegistration, // SetStyleAttributeRendererRegistration, // StylePropertyBindingRendererRegistration, // TextBindingRendererRegistration, // DefaultRenderers, // StandardConfiguration, createElement, // RenderPlan, // AttributeInstruction, // IInstructionRow, // NodeInstruction, // IInstruction, // InstructionType, // IAttributeBindingInstruction, // IListenerBindingInstruction, // ISetAttributeInstruction, // isInstruction, // IStylePropertyBindingInstruction, // ITextBindingInstruction, // NodeSequenceFactory, // FragmentNodeSequence, // AttributeBindingInstruction, // SetAttributeInstruction, // SetClassAttributeInstruction, // SetStyleAttributeInstruction, // StylePropertyBindingInstruction, // TextBindingInstruction, // ContainerlessProjector, // HostProjector, // HTMLProjectorLocator, // ShadowDOMProjector, StyleConfiguration, // styles, IShadowDOMConfiguration, // CSSModulesProcessorRegistry, cssModules, // ShadowDOMRegistry, // IShadowDOMStyleFactory, shadowCSS, // AdoptedStyleSheetsStyles, // StyleElementStyles, // IShadowDOMStyles, // IShadowDOMGlobalStyles // IAttrSyntaxTransformer, // TriggerBindingCommand, // DelegateBindingCommand, // CaptureBindingCommand, // AttrBindingCommand, // ClassBindingCommand, // StyleBindingCommand, // ITemplateCompilerRegistration, // ITemplateElementFactoryRegistration, // IAttrSyntaxTransformerRegistation, // DefaultComponents as JitHtmlDefaultComponents, // TriggerBindingCommandRegistration, // DelegateBindingCommandRegistration, // CaptureBindingCommandRegistration, // AttrBindingCommandRegistration, // ClassBindingCommandRegistration, // StyleBindingCommandRegistration, // DefaultBindingLanguage as JitHtmlDefaultBindingLanguage, // StandardConfiguration, // stringifyDOM, // stringifyInstructions, // stringifyTemplateDefinition, // TemplateBinder, // ITemplateElementFactory, ILifecycleHooks, LifecycleHook, LifecycleHooks, lifecycleHooks, // -------- dialog plugin ------------- // configurations DialogConfiguration, DialogConfigurationProvider, DialogDefaultConfiguration, // enums DialogActionKey, DialogMouseEventType, DialogDeactivationStatuses, // settings IDialogSettings, IDialogGlobalSettings, IDialogLoadedSettings, // main interfaces IDialogService, IDialogController, IDialogDomRenderer, IDialogDom, // dialog results DialogError, DialogOpenPromise, DialogOpenResult, DialogCancelError, DialogCloseError, DialogCloseResult, // default impls DialogService, DialogController, DefaultDialogDom, DefaultDialogDomRenderer, DefaultDialogGlobalSettings, // implementable for applications IDialogCustomElementViewModel, IDialogComponent, IDialogComponentActivate, IDialogComponentCanActivate, IDialogComponentDeactivate, IDialogComponentCanDeactivate, // -------- dialog plugin end ------------- // -------- wc plugin ------------- IWcElementRegistry, WebComponentViewModelClass, WcCustomElementRegistry, // -------- wc plugin end ------------- } from '@aurelia/runtime-html';
the_stack
import BN from 'bn.js' import debug from 'debug' import { ethers } from 'ethers' import { LocalAddress, CryptoUtils, Address, Contracts } from '.' import { Coin, LoomCoinTransferGateway } from './contracts' import { IWithdrawalReceipt } from './contracts/transfer-gateway' import { sleep, parseSigs } from './helpers' import { getMetamaskSigner } from './solidity-helpers' import { CrossChainUser, CrossChainUserParams, CrossChainUserConstructorParams } from './crosschain-user' const log = debug('gateway-user') const coinMultiplier = new BN(10).pow(new BN(18)) import { ERC20 } from './mainnet-contracts/ERC20' import { ERC20Factory } from './mainnet-contracts/ERC20Factory' import { EthereumGatewayV2Factory } from './mainnet-contracts/EthereumGatewayV2Factory' import { EthereumGatewayV1Factory } from './mainnet-contracts/EthereumGatewayV1Factory' import { EthereumGatewayV2 as EthereumGatewayV2Contract } from './mainnet-contracts/EthereumGatewayV2' import { ValidatorManagerV2Factory } from './mainnet-contracts/ValidatorManagerV2Factory' import { ValidatorManagerV2 as ValidatorManagerContractV2 } from './mainnet-contracts/ValidatorManagerV2' const ERC20Prefix = '\x10Withdraw ERC20:\n' const V2_GATEWAYS = ['asia1', 'test-z-us-1', 'extdev-plasma-us1'] export type GatewayVersion = 1 | 2 export interface EthereumContracts { gateway: EthereumGatewayV2Contract loomToken: ERC20 vmc?: ValidatorManagerContractV2 } export interface GatewayUserParams extends CrossChainUserParams { gatewayAddress: string version: GatewayVersion } export interface GatewayUserConstructorParams extends CrossChainUserConstructorParams { gateway: EthereumGatewayV2Contract loomToken: ERC20 vmc?: ValidatorManagerContractV2 dappchainGateway: Contracts.LoomCoinTransferGateway dappchainLoom: Contracts.Coin version: GatewayVersion } /** * @deprecated Will be removed in loom-js v2.0.0 */ export class GatewayUser extends CrossChainUser { private _ethereumGateway: EthereumGatewayV2Contract private _ethereumLoom: ERC20 private _ethereumVMC?: ValidatorManagerContractV2 private _dappchainGateway: Contracts.LoomCoinTransferGateway private _dappchainLoom: Contracts.Coin private _version: GatewayVersion static async createGatewayOfflineUserAsync(params: GatewayUserParams): Promise<GatewayUser> { const provider = new ethers.providers.JsonRpcProvider(params.ethEndpoint) const wallet = new ethers.Wallet(params.ethereumPrivateKey!, provider) return GatewayUser.createGatewayUserAsync({ wallet, ...params }) } static async createGatewayMetamaskUserAsync(params: GatewayUserParams): Promise<GatewayUser> { const wallet = getMetamaskSigner(params.web3!.currentProvider) return GatewayUser.createGatewayUserAsync({ wallet, ...params }) } static async getContracts( wallet: ethers.Signer, gatewayAddress: string, version?: GatewayVersion ): Promise<EthereumContracts> { let gateway: any switch (version) { case 2: gateway = EthereumGatewayV2Factory.connect(gatewayAddress, wallet) break case 1: gateway = EthereumGatewayV1Factory.connect(gatewayAddress, wallet) break default: throw new Error('Invalid Ethereum Gateway version ' + version) } const loomAddress = await gateway.functions.loomAddress() const loomToken = ERC20Factory.connect(loomAddress, wallet) let vmc if (version === 2) { const vmcAddress = await gateway.functions.vmc() vmc = ValidatorManagerV2Factory.connect(vmcAddress, wallet) } return { gateway: gateway as EthereumGatewayV2Contract, loomToken: loomToken as ERC20, vmc: vmc as ValidatorManagerContractV2 } } private static getGatewayVersion(endpoint: string, version?: GatewayVersion): GatewayVersion { // If no gateway version is provided, pick based on the chain URL prefix let retVersion: GatewayVersion = 1 if (typeof version === undefined) { const chainName = endpoint.split('.')[0] for (let chainPrefix of V2_GATEWAYS) { if (chainName.indexOf(chainPrefix) != -1) { retVersion = 2 } } } return retVersion } static async createEthSignMetamaskGatewayUserAsync( params: GatewayUserParams ): Promise<GatewayUser> { const gwVersion = GatewayUser.getGatewayVersion(params.dappchainEndpoint, params.version) let crosschain = await CrossChainUser.createEthSignMetamaskCrossChainUserAsync(params) const dappchainEthAddress = new Address( 'eth', LocalAddress.fromHexString(crosschain.ethAddress) ) const dappchainLoom = await Coin.createAsync(crosschain.client, dappchainEthAddress) const dappchainGateway = await LoomCoinTransferGateway.createAsync( crosschain.client, dappchainEthAddress ) const { gateway, loomToken, vmc } = await GatewayUser.getContracts( crosschain.wallet, params.gatewayAddress, params.version ) return new GatewayUser({ wallet: crosschain.wallet, client: crosschain.client, loomAddress: crosschain.loomAddress, ethAddress: crosschain.ethAddress, gateway, loomToken, vmc, dappchainGateway, dappchainLoom, version: gwVersion! }) } static async createGatewayUserAsync(params: GatewayUserParams): Promise<GatewayUser> { const gwVersion = GatewayUser.getGatewayVersion(params.dappchainEndpoint, params.version) let crosschain = await CrossChainUser.createCrossChainUserAsync(params) const dappchainLoom = await Coin.createAsync(crosschain.client, crosschain.loomAddress) const dappchainGateway = await LoomCoinTransferGateway.createAsync( crosschain.client, crosschain.loomAddress ) const { gateway, loomToken, vmc } = await GatewayUser.getContracts( crosschain.wallet, params.gatewayAddress, params.version ) return new GatewayUser({ wallet: crosschain.wallet, client: crosschain.client, loomAddress: crosschain.loomAddress, ethAddress: crosschain.ethAddress, gateway, loomToken, vmc, dappchainGateway, dappchainLoom, addressMapper: crosschain.addressMapper, version: gwVersion }) } constructor(params: GatewayUserConstructorParams) { super(params) this._version = params.version // Set ethereum contracts // @ts-ignore this._ethereumGateway = params.gateway // @ts-ignore this._ethereumLoom = params.loomToken // @ts-ignore this._ethereumVMC = params.vmc // Set dappchain contracts this._dappchainGateway = params.dappchainGateway this._dappchainLoom = params.dappchainLoom this._dappchainGateway = params.dappchainGateway } get ethereumVMC(): ValidatorManagerContractV2 | undefined { return this._ethereumVMC } get ethereumGateway(): EthereumGatewayV2Contract { return this._ethereumGateway } get ethereumLoom(): ERC20 { return this._ethereumLoom } get dappchainLoom(): Contracts.Coin { return this._dappchainLoom } get dappchainGateway(): Contracts.LoomCoinTransferGateway { return this._dappchainGateway } /** * Deposits funds from mainnet to the gateway */ async depositAsync(amount: BN): Promise<ethers.ContractTransaction> { let currentApproval = await this._ethereumLoom.functions.allowance( await this.ethAddress, this._ethereumGateway.address ) let currentApprovalBN = new BN(currentApproval.toString()) log('Current approval:', currentApproval) if (amount.gt(currentApprovalBN)) { let tx = await this._ethereumLoom.functions.approve( this._ethereumGateway.address, amount.sub(currentApprovalBN).toString() ) await tx.wait() log('Approved an extra', amount.sub(currentApprovalBN)) } return this._ethereumGateway.functions.depositERC20( amount.toString(), this._ethereumLoom.address ) } /** * Withdraw funds from the gateway to mainnet */ async withdrawAsync(amount: BN): Promise<ethers.ContractTransaction> { const sig = await this.depositCoinToDAppChainGatewayAsync(amount) return this.withdrawCoinFromDAppChainGatewayAsync(amount, sig) } async resumeWithdrawalAsync() { const receipt = await this.getPendingWithdrawalReceiptAsync() if (receipt === null) { log('No pending receipt') return } const signature = CryptoUtils.bytesToHexAddr(receipt.oracleSignature) const amount = receipt.tokenAmount! return this.withdrawCoinFromDAppChainGatewayAsync(amount, signature) } async getPendingWithdrawalReceiptAsync(): Promise<IWithdrawalReceipt | null> { return this._dappchainGateway.withdrawalReceiptAsync(this.loomAddress) } /** * Retrieves the DAppChain LoomCoin balance of a user * @param address The address to check the balance of. If not provided, it will check the user's balance */ async getDAppChainBalanceAsync(address?: string): Promise<BN> { const addr = address ? this.prefixAddress(address) : this.loomAddress const balance = await this._dappchainLoom.getBalanceOfAsync(addr) return balance } /** * Deposits an amount of LOOM tokens to the dappchain gateway and return a signature which can be used to withdraw the same amount from the mainnet gateway. * * @param amount The amount that will be deposited to the DAppChain Gateway (and will be possible to withdraw from the mainnet) */ private async depositCoinToDAppChainGatewayAsync(amount: BN): Promise<string> { let pendingReceipt = await this.getPendingWithdrawalReceiptAsync() let signature: Uint8Array if (pendingReceipt === null) { await this._dappchainLoom.approveAsync(this._dappchainGateway.address, amount) const ethereumAddressStr = await this.ethAddress const ethereumAddress = Address.fromString(`eth:${ethereumAddressStr}`) const _ethereumLoomCoinAddress = Address.fromString(`eth:${this._ethereumLoom.address}`) await this._dappchainGateway.withdrawLoomCoinAsync( amount, _ethereumLoomCoinAddress, ethereumAddress ) log(`${amount.div(coinMultiplier).toString()} tokens deposited to DAppChain Gateway...`) while (pendingReceipt === null || pendingReceipt.oracleSignature.length === 0) { pendingReceipt = await this.getPendingWithdrawalReceiptAsync() await sleep(2000) } } signature = pendingReceipt.oracleSignature return CryptoUtils.bytesToHexAddr(signature) } async getUnclaimedLoomTokensAsync(owner?: string): Promise<BN> { const address = owner ? Address.fromString(`eth:${owner}`) : Address.fromString(`eth:${this.ethAddress}`) const tokens = await this._dappchainGateway.getUnclaimedTokensAsync(address) const unclaimedLoomTokens = tokens.filter( t => t.tokenContract.local.toString() === this.ethereumLoom.address ) // There is only 1 LOOM token and there's only 1 balance for it: // All other parameters of UnclaimedToken are for ERC721(x) tokens. let amount if (unclaimedLoomTokens.length === 0) { // no unclaimed tokens amount = new BN(0) } else { // if the amounts array was set const amounts = unclaimedLoomTokens[0].tokenAmounts! amount = amounts ? amounts[0] : new BN(0) } return amount } private async withdrawCoinFromDAppChainGatewayAsync( amount: BN, sig: string ): Promise<ethers.ContractTransaction> { if (this._version === 2 && this._ethereumVMC !== undefined) { const hash = await this.createWithdrawalHash(amount) const validators = await this._ethereumVMC!.functions.getValidators() const { vs, rs, ss, valIndexes } = parseSigs(sig, hash, validators) return this._ethereumGateway.functions.withdrawERC20( amount.toString(), this._ethereumLoom.address, valIndexes, vs, rs, ss ) } // @ts-ignore return this._ethereumGateway.functions.withdrawERC20( amount.toString(), sig, this._ethereumLoom.address ) } private async createWithdrawalHash(amount: BN): Promise<string> { let nonce = await this.ethereumGateway.functions.nonces(this.ethAddress) let amountHashed = ethers.utils.solidityKeccak256( ['uint256', 'address'], [amount.toString(), this.ethereumLoom.address] ) const msg = ethers.utils.solidityKeccak256( ['string', 'address', 'uint256', 'address', 'bytes32'], [ERC20Prefix, this.ethAddress, nonce, this.ethereumGateway.address, amountHashed] ) return msg } /** * Helper function to prefix an address with the chainId to get chainId:address format */ prefixAddress(address: string) { return Address.fromString(`${this.client.chainId}:${address}`) } }
the_stack
import { Either } from './Either' import { Eq } from './Eq' import { identity } from './function' import { Magma } from './Magma' import { Monoid } from './Monoid' import { Option } from './Option' import { Ord } from './Ord' import { Predicate } from './Predicate' import * as RS from './ReadonlySet' import { Refinement } from './Refinement' import { Semigroup } from './Semigroup' import { separated, Separated } from './Separated' import { Show } from './Show' /** * @category instances * @since 2.0.0 */ export const getShow: <A>(S: Show<A>) => Show<Set<A>> = RS.getShow /** * @category instances * @since 2.0.0 */ export const getEq: <A>(E: Eq<A>) => Eq<Set<A>> = RS.getEq /** * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F<A>) => F<B>` whose argument and return types * use the type constructor `F` to represent some computational context. * * @category combinators * @since 2.0.0 */ export function map<B>(E: Eq<B>): <A>(f: (x: A) => B) => (set: Set<A>) => Set<B> { const elemE = elem(E) return (f) => (set) => { const r = new Set<B>() set.forEach((e) => { const v = f(e) if (!elemE(v, r)) { r.add(v) } }) return r } } /** * Composes computations in sequence, using the return value of one computation to determine the next computation. * * @category combinators * @since 2.0.0 */ export function chain<B>(E: Eq<B>): <A>(f: (x: A) => Set<B>) => (set: Set<A>) => Set<B> { const elemE = elem(E) return (f) => (set) => { const r = new Set<B>() set.forEach((e) => { f(e).forEach((e) => { if (!elemE(e, r)) { r.add(e) } }) }) return r } } interface Next<A> { readonly done?: boolean readonly value: A } /** * @category combinators * @since 2.0.0 */ export function filter<A, B extends A>(refinement: Refinement<A, B>): (set: Set<A>) => Set<B> export function filter<A>(predicate: Predicate<A>): <B extends A>(set: Set<B>) => Set<B> export function filter<A>(predicate: Predicate<A>): (set: Set<A>) => Set<A> export function filter<A>(predicate: Predicate<A>): (set: Set<A>) => Set<A> { return (set: Set<A>) => { const values = set.values() let e: Next<A> const r = new Set<A>() // tslint:disable-next-line: strict-boolean-expressions while (!(e = values.next()).done) { const a = e.value if (predicate(a)) { r.add(a) } } return r } } /** * @since 2.0.0 */ export function partition<A, B extends A>(refinement: Refinement<A, B>): (set: Set<A>) => Separated<Set<A>, Set<B>> export function partition<A>(predicate: Predicate<A>): <B extends A>(set: Set<B>) => Separated<Set<B>, Set<B>> export function partition<A>(predicate: Predicate<A>): (set: Set<A>) => Separated<Set<A>, Set<A>> export function partition<A>(predicate: Predicate<A>): (set: Set<A>) => Separated<Set<A>, Set<A>> { return (set: Set<A>) => { const values = set.values() let e: Next<A> const right = new Set<A>() const left = new Set<A>() // tslint:disable-next-line: strict-boolean-expressions while (!(e = values.next()).done) { const a = e.value if (predicate(a)) { right.add(a) } else { left.add(a) } } return separated(left, right) } } // TODO: remove non-curried overloading in v3 /** * Form the union of two sets * * @category combinators * @since 2.0.0 */ export function union<A>( E: Eq<A> ): { (that: Set<A>): (me: Set<A>) => Set<A> (me: Set<A>, that: Set<A>): Set<A> } export function union<A>(E: Eq<A>): (me: Set<A>, that?: Set<A>) => Set<A> | ((me: Set<A>) => Set<A>) { const elemE = elem(E) return (me, that?) => { if (that === undefined) { const unionE = union(E) return (that) => unionE(me, that) } if (isEmpty(me)) { return that } if (isEmpty(that)) { return me } const r = new Set(me) that.forEach((e) => { if (!elemE(e, r)) { r.add(e) } }) return r } } // TODO: remove non-curried overloading in v3 /** * The set of elements which are in both the first and second set * * @category combinators * @since 2.0.0 */ export function intersection<A>( E: Eq<A> ): { (that: Set<A>): (me: Set<A>) => Set<A> (me: Set<A>, that: Set<A>): Set<A> } export function intersection<A>(E: Eq<A>): (me: Set<A>, that?: Set<A>) => Set<A> | ((that: Set<A>) => Set<A>) { const elemE = elem(E) return (me, that?) => { if (that === undefined) { const intersectionE = intersection(E) return (that) => intersectionE(that, me) } if (isEmpty(me) || isEmpty(that)) { return new Set() } const r = new Set<A>() me.forEach((e) => { if (elemE(e, that)) { r.add(e) } }) return r } } /** * @since 2.0.0 */ export function partitionMap<B, C>( EB: Eq<B>, EC: Eq<C> ): <A>(f: (a: A) => Either<B, C>) => (set: Set<A>) => Separated<Set<B>, Set<C>> { return <A>(f: (a: A) => Either<B, C>) => (set: Set<A>) => { const values = set.values() let e: Next<A> const left = new Set<B>() const right = new Set<C>() const hasB = elem(EB) const hasC = elem(EC) // tslint:disable-next-line: strict-boolean-expressions while (!(e = values.next()).done) { const v = f(e.value) switch (v._tag) { case 'Left': if (!hasB(v.left, left)) { left.add(v.left) } break case 'Right': if (!hasC(v.right, right)) { right.add(v.right) } break } } return separated(left, right) } } // TODO: remove non-curried overloading in v3 /** * Form the set difference (`x` - `y`) * * @example * import { difference } from 'fp-ts/Set' * import * as N from 'fp-ts/number' * import { pipe } from 'fp-ts/function' * * assert.deepStrictEqual(pipe(new Set([1, 2]), difference(N.Eq)(new Set([1, 3]))), new Set([2])) * * @category combinators * @since 2.0.0 */ export function difference<A>( E: Eq<A> ): { (that: Set<A>): (me: Set<A>) => Set<A> (me: Set<A>, that: Set<A>): Set<A> } export function difference<A>(E: Eq<A>): (me: Set<A>, that?: Set<A>) => Set<A> | ((me: Set<A>) => Set<A>) { const elemE = elem(E) return (me, that?) => { if (that === undefined) { const differenceE = difference(E) return (that) => differenceE(that, me) } return filter((a: A) => !elemE(a, that))(me) } } /** * @category instances * @since 2.11.0 */ export const getUnionSemigroup = <A>(E: Eq<A>): Semigroup<Set<A>> => ({ concat: union(E) }) /** * @category instances * @since 2.0.0 */ export const getUnionMonoid = <A>(E: Eq<A>): Monoid<Set<A>> => ({ concat: getUnionSemigroup(E).concat, empty: new Set() }) /** * @category instances * @since 2.0.0 */ export const getIntersectionSemigroup = <A>(E: Eq<A>): Semigroup<Set<A>> => ({ concat: intersection(E) }) /** * @category instances * @since 2.11.0 */ export const getDifferenceMagma = <A>(E: Eq<A>): Magma<Set<A>> => ({ concat: difference(E) }) /** * @since 2.0.0 */ export const reduce: <A>(O: Ord<A>) => <B>(b: B, f: (b: B, a: A) => B) => (fa: Set<A>) => B = RS.reduce /** * @since 2.0.0 */ export const foldMap: <A, M>(O: Ord<A>, M: Monoid<M>) => (f: (a: A) => M) => (fa: Set<A>) => M = RS.foldMap /** * @since 2.11.0 */ export const reduceRight: <A>(O: Ord<A>) => <B>(b: B, f: (a: A, b: B) => B) => (fa: Set<A>) => B = RS.reduceRight /** * Create a set with one element * * @category constructors * @since 2.0.0 */ export const singleton = <A>(a: A): Set<A> => new Set([a]) /** * Insert a value into a set * * @category combinators * @since 2.0.0 */ export function insert<A>(E: Eq<A>): (a: A) => (set: Set<A>) => Set<A> { const elemE = elem(E) return (a) => (set) => { if (!elemE(a)(set)) { const r = new Set(set) r.add(a) return r } else { return set } } } /** * Delete a value from a set * * @category combinators * @since 2.0.0 */ export const remove = <A>(E: Eq<A>) => (a: A) => (set: Set<A>): Set<A> => filter((ax: A) => !E.equals(a, ax))(set) /** * Checks an element is a member of a set; * If yes, removes the value from the set * If no, inserts the value to the set * * @category combinators * @since 2.5.0 */ export const toggle = <A>(E: Eq<A>): ((a: A) => (set: Set<A>) => Set<A>) => { const elemE = elem(E) const removeE = remove(E) const insertE = insert(E) return (a) => (set) => (elemE(a, set) ? removeE : insertE)(a)(set) } /** * Create a set from an array * * @category constructors * @since 2.0.0 */ export const fromArray = <A>(E: Eq<A>) => (as: Array<A>): Set<A> => { const len = as.length const out = new Set<A>() const has = elem(E) for (let i = 0; i < len; i++) { const a = as[i] if (!has(a, out)) { out.add(a) } } return out } /** * @category combinators * @since 2.0.0 */ export const compact = <A>(E: Eq<A>): ((fa: Set<Option<A>>) => Set<A>) => filterMap(E)(identity) /** * @since 2.0.0 */ export function separate<E, A>(EE: Eq<E>, EA: Eq<A>): (fa: Set<Either<E, A>>) => Separated<Set<E>, Set<A>> { return (fa) => { const elemEE = elem(EE) const elemEA = elem(EA) const left: Set<E> = new Set() const right: Set<A> = new Set() fa.forEach((e) => { switch (e._tag) { case 'Left': if (!elemEE(e.left, left)) { left.add(e.left) } break case 'Right': if (!elemEA(e.right, right)) { right.add(e.right) } break } }) return separated(left, right) } } /** * @category combinators * @since 2.0.0 */ export function filterMap<B>(E: Eq<B>): <A>(f: (a: A) => Option<B>) => (fa: Set<A>) => Set<B> { const elemE = elem(E) return (f) => (fa) => { const r: Set<B> = new Set() fa.forEach((a) => { const ob = f(a) if (ob._tag === 'Some' && !elemE(ob.value, r)) { r.add(ob.value) } }) return r } } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.0.0 */ export const empty: Set<never> = new Set() /** * Test whether a `Set` is empty. * * @since 2.10.0 */ export const isEmpty = <A>(set: Set<A>): boolean => set.size === 0 /** * Calculate the number of elements in a `Set`. * * @since 2.10.0 */ export const size = <A>(set: Set<A>): number => set.size /** * @since 2.0.0 */ export const some: <A>(predicate: Predicate<A>) => (set: Set<A>) => boolean = RS.some /** * @since 2.0.0 */ export const every: <A>(predicate: Predicate<A>) => (set: Set<A>) => boolean = RS.every /** * @since 2.10.0 */ export const isSubset: <A>(E: Eq<A>) => (that: Set<A>) => (me: Set<A>) => boolean = RS.isSubset // TODO: remove non-curried overloading in v3 /** * Test if a value is a member of a set * * @since 2.0.0 */ export const elem: <A>( E: Eq<A> ) => { (a: A): (set: Set<A>) => boolean (a: A, set: Set<A>): boolean } = RS.elem /** * Get a sorted `Array` of the values contained in a `Set`. * * @since 2.0.0 */ export const toArray = <A>(O: Ord<A>) => (set: Set<A>): Array<A> => { const out: Array<A> = [] set.forEach((e) => out.push(e)) return out.sort(O.compare) } // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- /** * Use [`isSubset`](#issubset) instead. * * @since 2.0.0 * @deprecated */ export const subset: <A>( E: Eq<A> ) => { (that: Set<A>): (me: Set<A>) => boolean (me: Set<A>, that: Set<A>): boolean } = RS.isSubset
the_stack
import '../../../test/common-test-setup-karma'; import './gr-change-list'; import {GrChangeList} from './gr-change-list'; import {GerritNav} from '../../core/gr-navigation/gr-navigation'; import { pressKey, query, queryAll, queryAndAssert, stubFlags, } from '../../../test/test-utils'; import {YOUR_TURN} from '../../core/gr-navigation/gr-navigation'; import {Key} from '../../../utils/dom-util'; import {TimeFormat} from '../../../constants/constants'; import {AccountId, NumericChangeId} from '../../../types/common'; import { createChange, createServerInfo, } from '../../../test/test-data-generators'; import {GrChangeListItem} from '../gr-change-list-item/gr-change-list-item'; const basicFixture = fixtureFromElement('gr-change-list'); suite('gr-change-list basic tests', () => { let element: GrChangeList; setup(() => { element = basicFixture.instantiate(); }); suite('test show change number not logged in', () => { setup(async () => { element = basicFixture.instantiate(); element.account = undefined; element.preferences = undefined; element.config = createServerInfo(); await element.updateComplete; }); test('show number disabled', () => { assert.isFalse(element.showNumber); }); }); suite('test show change number preference enabled', () => { setup(async () => { element = basicFixture.instantiate(); element.preferences = { legacycid_in_change_table: true, time_format: TimeFormat.HHMM_12, change_table: [], }; element.account = {_account_id: 1001 as AccountId}; element.config = createServerInfo(); await element.updateComplete; }); test('show number enabled', () => { assert.isTrue(element.showNumber); }); }); suite('test show change number preference disabled', () => { setup(async () => { element = basicFixture.instantiate(); // legacycid_in_change_table is not set when false. element.preferences = { time_format: TimeFormat.HHMM_12, change_table: [], }; element.account = {_account_id: 1001 as AccountId}; element.config = createServerInfo(); await element.updateComplete; }); test('show number disabled', () => { assert.isFalse(element.showNumber); }); }); test('computed fields', () => { assert.equal( element.computeLabelNames([ { results: [ {...createChange(), _number: 0 as NumericChangeId, labels: {}}, ], }, ]).length, 0 ); assert.equal( element.computeLabelNames([ { results: [ { ...createChange(), _number: 0 as NumericChangeId, labels: {Verified: {approved: {}}}, }, { ...createChange(), _number: 1 as NumericChangeId, labels: { Verified: {approved: {}}, 'Code-Review': {approved: {}}, }, }, { ...createChange(), _number: 2 as NumericChangeId, labels: { Verified: {approved: {}}, 'Library-Compliance': {approved: {}}, }, }, ], }, ]).length, 3 ); assert.equal(element.computeLabelShortcut('Code-Review'), 'CR'); assert.equal(element.computeLabelShortcut('Verified'), 'V'); assert.equal(element.computeLabelShortcut('Library-Compliance'), 'LC'); assert.equal(element.computeLabelShortcut('PolyGerrit-Review'), 'PR'); assert.equal(element.computeLabelShortcut('polygerrit-review'), 'PR'); assert.equal( element.computeLabelShortcut('Invalid-Prolog-Rules-Label-Name--Verified'), 'V' ); assert.equal(element.computeLabelShortcut('Some-Special-Label-7'), 'SSL7'); assert.equal( element.computeLabelShortcut('--Too----many----dashes---'), 'TMD' ); assert.equal( element.computeLabelShortcut( 'Really-rather-entirely-too-long-of-a-label-name' ), 'RRETL' ); }); test('colspans', async () => { element.sections = [{results: [{...createChange()}]}]; await element.updateComplete; const tdItemCount = queryAll<HTMLTableElement>(element, 'td').length; element.visibleChangeTableColumns = []; const labelNames: string[] | undefined = []; assert.equal( tdItemCount, element.computeColspan({results: [{...createChange()}]}, labelNames) ); }); test('keyboard shortcuts', async () => { sinon.stub(element, 'computeLabelNames'); element.sections = [{results: new Array(1)}, {results: new Array(2)}]; element.selectedIndex = 0; element.changes = [ {...createChange(), _number: 0 as NumericChangeId}, {...createChange(), _number: 1 as NumericChangeId}, {...createChange(), _number: 2 as NumericChangeId}, ]; await element.updateComplete; const elementItems = queryAll<GrChangeListItem>( element, 'gr-change-list-item' ); assert.equal(elementItems.length, 3); assert.isTrue(elementItems[0].hasAttribute('selected')); pressKey(element, 'j'); await element.updateComplete; assert.equal(element.selectedIndex, 1); assert.isTrue(elementItems[1].hasAttribute('selected')); pressKey(element, 'j'); await element.updateComplete; assert.equal(element.selectedIndex, 2); assert.isTrue(elementItems[2].hasAttribute('selected')); const navStub = sinon.stub(GerritNav, 'navigateToChange'); assert.equal(element.selectedIndex, 2); pressKey(element, Key.ENTER); await element.updateComplete; assert.deepEqual( navStub.lastCall.args[0], {...createChange(), _number: 2 as NumericChangeId}, 'Should navigate to /c/2/' ); pressKey(element, 'k'); await element.updateComplete; assert.equal(element.selectedIndex, 1); pressKey(element, Key.ENTER); await element.updateComplete; assert.deepEqual( navStub.lastCall.args[0], {...createChange(), _number: 1 as NumericChangeId}, 'Should navigate to /c/1/' ); pressKey(element, 'k'); pressKey(element, 'k'); pressKey(element, 'k'); assert.equal(element.selectedIndex, 0); }); test('no changes', async () => { element.changes = []; await element.updateComplete; const listItems = queryAll<GrChangeListItem>( element, 'gr-change-list-item' ); assert.equal(listItems.length, 0); const noChangesMsg = queryAndAssert<HTMLTableRowElement>( element, '.noChanges' ); assert.ok(noChangesMsg); }); test('empty sections', async () => { element.sections = [{results: []}, {results: []}]; await element.updateComplete; const listItems = queryAll<GrChangeListItem>( element, 'gr-change-list-item' ); assert.equal(listItems.length, 0); const noChangesMsg = queryAll<HTMLTableRowElement>(element, '.noChanges'); assert.equal(noChangesMsg.length, 2); }); suite('empty section', () => { test('not shown on empty non-outgoing sections', () => { const section = {name: 'test', query: 'test', results: []}; assert.isTrue(element.isEmpty(section)); assert.equal(element.getSpecialEmptySlot(section), ''); }); test('shown on empty outgoing sections', () => { const section = { name: 'test', query: 'test', results: [], isOutgoing: true, }; assert.isTrue(element.isEmpty(section)); assert.equal(element.getSpecialEmptySlot(section), 'empty-outgoing'); }); test('shown on empty outgoing sections', () => { const section = {name: YOUR_TURN.name, query: 'test', results: []}; assert.isTrue(element.isEmpty(section)); assert.equal(element.getSpecialEmptySlot(section), 'empty-your-turn'); }); test('not shown on non-empty outgoing sections', () => { const section = { name: 'test', query: 'test', isOutgoing: true, results: [ { ...createChange(), _number: 0 as NumericChangeId, labels: {Verified: {approved: {}}}, }, ], }; assert.isFalse(element.isEmpty(section)); }); }); suite('empty column preference', () => { let element: GrChangeList; setup(async () => { stubFlags('isEnabled').returns(true); element = basicFixture.instantiate(); element.sections = [{results: [{...createChange()}]}]; element.account = {_account_id: 1001 as AccountId}; element.preferences = { legacycid_in_change_table: true, time_format: TimeFormat.HHMM_12, change_table: [], }; element.config = createServerInfo(); await element.updateComplete; }); test('show number enabled', () => { assert.isTrue(element.showNumber); }); test('all columns visible', () => { for (const column of element.changeTableColumns!) { const elementClass = '.' + column.trim().toLowerCase(); assert.isFalse( queryAndAssert<HTMLElement>(element, elementClass)!.hidden ); } }); }); suite('full column preference', () => { let element: GrChangeList; setup(async () => { stubFlags('isEnabled').returns(true); element = basicFixture.instantiate(); element.sections = [{results: [{...createChange()}]}]; element.account = {_account_id: 1001 as AccountId}; element.preferences = { legacycid_in_change_table: true, time_format: TimeFormat.HHMM_12, change_table: [ 'Subject', 'Status', 'Owner', 'Reviewers', 'Comments', 'Repo', 'Branch', 'Updated', 'Size', ' Status ', ], }; element.config = createServerInfo(); await element.updateComplete; }); test('all columns visible', () => { for (const column of element.changeTableColumns!) { const elementClass = '.' + column.trim().toLowerCase(); assert.isFalse( queryAndAssert<HTMLElement>(element, elementClass).hidden ); } }); }); suite('partial column preference', () => { let element: GrChangeList; setup(async () => { stubFlags('isEnabled').returns(true); element = basicFixture.instantiate(); element.sections = [{results: [{...createChange()}]}]; element.account = {_account_id: 1001 as AccountId}; element.preferences = { legacycid_in_change_table: true, time_format: TimeFormat.HHMM_12, change_table: [ 'Subject', 'Status', 'Owner', 'Reviewers', 'Comments', 'Branch', 'Updated', 'Size', ' Status ', ], }; element.config = createServerInfo(); await element.updateComplete; }); test('all columns except repo visible', () => { for (const column of element.changeTableColumns!) { const elementClass = '.' + column.trim().toLowerCase(); if (column === 'Repo') { assert.isNotOk(query<HTMLElement>(element, elementClass)); } else { assert.isOk(queryAndAssert<HTMLElement>(element, elementClass)); } } }); }); test('obsolete column in preferences not visible', () => { assert.isTrue(element._isColumnEnabled('Subject')); assert.isFalse(element._isColumnEnabled('Assignee')); }); suite('random column does not exist', () => { let element: GrChangeList; /* This would only exist if somebody manually updated the config file. */ setup(async () => { element = basicFixture.instantiate(); element.account = {_account_id: 1001 as AccountId}; element.preferences = { legacycid_in_change_table: true, time_format: TimeFormat.HHMM_12, change_table: ['Bad'], }; await element.updateComplete; }); test('bad column does not exist', () => { assert.isNotOk(query<HTMLElement>(element, '.bad')); }); }); suite('dashboard queries', () => { let element: GrChangeList; setup(() => { element = basicFixture.instantiate(); }); teardown(() => { sinon.restore(); }); test('query without age and limit unchanged', () => { const query = 'status:closed owner:me'; assert.deepEqual(element.processQuery(query), query); }); test('query with age and limit', () => { const query = 'status:closed age:1week limit:10 owner:me'; const expectedQuery = 'status:closed owner:me'; assert.deepEqual(element.processQuery(query), expectedQuery); }); test('query with age', () => { const query = 'status:closed age:1week owner:me'; const expectedQuery = 'status:closed owner:me'; assert.deepEqual(element.processQuery(query), expectedQuery); }); test('query with limit', () => { const query = 'status:closed limit:10 owner:me'; const expectedQuery = 'status:closed owner:me'; assert.deepEqual(element.processQuery(query), expectedQuery); }); test('query with age as value and not key', () => { const query = 'status:closed random:age'; const expectedQuery = 'status:closed random:age'; assert.deepEqual(element.processQuery(query), expectedQuery); }); test('query with limit as value and not key', () => { const query = 'status:closed random:limit'; const expectedQuery = 'status:closed random:limit'; assert.deepEqual(element.processQuery(query), expectedQuery); }); test('query with -age key', () => { const query = 'status:closed -age:1week'; const expectedQuery = 'status:closed'; assert.deepEqual(element.processQuery(query), expectedQuery); }); }); suite('gr-change-list sections', () => { let element: GrChangeList; setup(() => { element = basicFixture.instantiate(); }); test('keyboard shortcuts', async () => { element.selectedIndex = 0; element.sections = [ { results: [ {...createChange(), _number: 0 as NumericChangeId}, {...createChange(), _number: 1 as NumericChangeId}, {...createChange(), _number: 2 as NumericChangeId}, ], }, { results: [ {...createChange(), _number: 3 as NumericChangeId}, {...createChange(), _number: 4 as NumericChangeId}, {...createChange(), _number: 5 as NumericChangeId}, ], }, { results: [ {...createChange(), _number: 6 as NumericChangeId}, {...createChange(), _number: 7 as NumericChangeId}, {...createChange(), _number: 8 as NumericChangeId}, ], }, ]; await element.updateComplete; const elementItems = queryAll<GrChangeListItem>( element, 'gr-change-list-item' ); assert.equal(elementItems.length, 9); pressKey(element, 'j'); assert.equal(element.selectedIndex, 1); pressKey(element, 'j'); const navStub = sinon.stub(GerritNav, 'navigateToChange'); assert.equal(element.selectedIndex, 2); pressKey(element, Key.ENTER); assert.deepEqual( navStub.lastCall.args[0], {...createChange(), _number: 2 as NumericChangeId}, 'Should navigate to /c/2/' ); pressKey(element, 'k'); assert.equal(element.selectedIndex, 1); pressKey(element, Key.ENTER); assert.deepEqual( navStub.lastCall.args[0], {...createChange(), _number: 1 as NumericChangeId}, 'Should navigate to /c/1/' ); pressKey(element, 'j'); pressKey(element, 'j'); pressKey(element, 'j'); assert.equal(element.selectedIndex, 4); pressKey(element, Key.ENTER); assert.deepEqual( navStub.lastCall.args[0], {...createChange(), _number: 4 as NumericChangeId}, 'Should navigate to /c/4/' ); }); test('computeItemAbsoluteIndex', () => { sinon.stub(element, 'computeLabelNames'); element.sections = [ {results: new Array(1)}, {results: new Array(2)}, {results: new Array(3)}, ]; assert.equal(element.computeItemAbsoluteIndex(0, 0), 0); // Out of range but no matter. assert.equal(element.computeItemAbsoluteIndex(0, 1), 1); assert.equal(element.computeItemAbsoluteIndex(1, 0), 1); assert.equal(element.computeItemAbsoluteIndex(1, 1), 2); assert.equal(element.computeItemAbsoluteIndex(1, 2), 3); assert.equal(element.computeItemAbsoluteIndex(2, 0), 3); assert.equal(element.computeItemAbsoluteIndex(3, 0), 6); }); }); });
the_stack
import * as vscode from "vscode"; import * as fs from "fs"; import * as path from "path"; import Utils from "./utils"; import * as nls from "vscode-nls"; import { inputConnectionParameters } from "./inputConnectionParameters"; import { inputAuthenticationParameters } from "./inputAuthenticationParameters"; import { ResponseError } from "vscode-languageclient"; import serverProvider, { ServerItem, EnvSection } from "./serverItemProvider"; import { ConnTypeIds, sendValidationRequest, IValidationInfo, sendDisconnectRequest, ITokenInfo, sendConnectRequest, sendAuthenticateRequest, IAuthenticationInfo, sendReconnectRequest, IReconnectInfo, ENABLE_CODE_PAGE, } from "./protocolMessages"; let localize = nls.loadMessageBundle(); const compile = require("template-literal"); const localizeHTML = { "tds.webview.newServer.title": localize( "tds.webview.newServer.title", "New Server" ), "tds.webview.newServer.name": localize( "tds.webview.newServer.name", "Server Name" ), "tds.webview.newServer.address": localize( "tds.webview.newServer.address", "Address" ), "tds.webview.newServer.port": localize("tds.webview.newServer.port", "Port"), "tds.webview.newServer.save": localize("tds.webview.newServer.save", "Save"), "tds.webview.newServer.saveClose": localize( "tds.webview.newServer.saveClose", "Save/Close" ), "tds.webview.newServer.secure": localize( "tds.webview.newServer.secure", "Secure(SSL)" ), "tds.webview.dir.include": localize( "tds.webview.dir.include", "Includes directory" ), "tds.webview.dir.include2": localize( "tds.webview.dir.include2", "Allow multiple directories" ), }; export class ServersExplorer { constructor(context: vscode.ExtensionContext) { let currentPanel: vscode.WebviewPanel | undefined = undefined; vscode.commands.registerCommand("totvs-developer-studio.add", () => { if (vscode.workspace.workspaceFolders === undefined) { vscode.window.showErrorMessage("No folder opened."); return; } if (currentPanel) { currentPanel.reveal(); } else { currentPanel = vscode.window.createWebviewPanel( "totvs-developer-studio.add", localize("tds.webview.newServer.title", "New Server"), vscode.ViewColumn.One, { enableScripts: true, localResourceRoots: [ vscode.Uri.file( path.join(context.extensionPath, "src", "server") ), ], retainContextWhenHidden: true, } ); currentPanel.webview.html = getWebViewContent(context, localizeHTML); currentPanel.onDidDispose( () => { currentPanel = undefined; }, null, context.subscriptions ); currentPanel.webview.onDidReceiveMessage( (message) => { switch (message.command) { case "checkDir": let checkedDir = Utils.checkDir(message.selectedDir); currentPanel.webview.postMessage({ command: "checkedDir", checkedDir: checkedDir, }); break; case "saveServer": if (message.serverName && message.port && message.address) { const serverId = createServer( message.serverType, message.serverName, message.port, message.address, 0, "", true, message.includes ); if (serverId !== undefined) { sendValidationRequest(message.address, message.port).then( (validInfoNode: IValidationInfo) => { Utils.updateBuildVersion( serverId, validInfoNode.build, validInfoNode.secure ); return; }, (err: ResponseError<object>) => { vscode.window.showErrorMessage(err.message); } ); } } else { vscode.window.showErrorMessage( localize( "tds.webview.serversView.addServerFail", "Add Server Fail. Name, port and Address are need" ) ); } if (currentPanel) { if (message.close) { currentPanel.dispose(); } } } }, undefined, context.subscriptions ); } }); vscode.commands.registerCommand("totvs-developer-studio.config", () => { if (vscode.workspace.workspaceFolders === undefined) { vscode.window.showErrorMessage("No folder opened."); return; } const servers = Utils.getServerConfigFile(); if (servers) { vscode.window.showTextDocument(vscode.Uri.file(servers)); } }); // check if there is an open folder if (vscode.workspace.workspaceFolders === undefined) { vscode.window.showErrorMessage("No folder opened."); return; } const options: vscode.TreeViewOptions<ServerItem | EnvSection> = { treeDataProvider: serverProvider, }; vscode.window.createTreeView("totvs_server", options); vscode.window.registerTreeDataProvider("totvs_server", serverProvider); vscode.commands.registerCommand( "totvs-developer-studio.connect", (serverItem: ServerItem) => { let ix = serverProvider.localServerItems.indexOf(serverItem); if (ix >= 0) { //Verifica se ha um buildVersion cadastrado. if (serverItem.buildVersion) { inputConnectionParameters( context, serverItem, ConnTypeIds.CONNT_DEBUGGER, false ); } else { //Há build no servidor. vscode.window.setStatusBarMessage( `Validando servidor [${serverItem.name}]`, sendValidationRequest(serverItem.address, serverItem.port).then( (validationInfo: IValidationInfo) => { //retornou uma versao valida no servidor. const updated = Utils.updateBuildVersion( serverItem.id, validationInfo.build, validationInfo.secure ); serverItem.buildVersion = validationInfo.build; if (updated) { //continua a autenticacao. inputConnectionParameters( context, serverItem, ConnTypeIds.CONNT_DEBUGGER, false ); } return; }, (err: ResponseError<object>) => { vscode.window.showErrorMessage(err.message); } ) ); } } } ); vscode.commands.registerCommand( "totvs-developer-studio.reconnect", (serverItem: ServerItem) => { let ix = serverProvider.localServerItems.indexOf(serverItem); if (ix >= 0) { //Verifica se ha um buildVersion cadastrado. if (serverItem.buildVersion) { inputConnectionParameters( context, serverItem, ConnTypeIds.CONNT_DEBUGGER, true ); } else { vscode.window.showErrorMessage( localize( "tds.webview.serversView.couldNotReconn", "Could not reconnect to server" ) ); } } } ); vscode.commands.registerCommand( "totvs-developer-studio.disconnect", (serverItem: ServerItem) => { if (serverItem.isConnected) { vscode.window.setStatusBarMessage( `Desconectando do servidor [${serverItem.name}]`, sendDisconnectRequest(serverItem).then( (ti: ITokenInfo) => { if (!ti.sucess) { serverProvider.connectedServerItem = undefined; } executeCommand("_totvs-developer-studio.clearMonitorPanel"); }, (err: ResponseError<object>) => { serverProvider.connectedServerItem = undefined; handleError(err); } ) ); } else { vscode.window.showInformationMessage( localize( "tds.webview.serversView.alreadyConn", "Server is already disconnected" ) ); serverProvider.connectedServerItem = undefined; } } ); vscode.commands.registerCommand( "totvs-developer-studio.selectenv", (environment: EnvSection) => { inputConnectionParameters( context, environment, ConnTypeIds.CONNT_DEBUGGER, true ); } ); vscode.commands.registerCommand( "totvs-developer-studio.delete", (serverItem: ServerItem) => { let ix = serverProvider.localServerItems.indexOf(serverItem); if (ix >= 0) { Utils.deleteServer(serverItem.id); } } ); vscode.commands.registerCommand( "totvs-developer-studio.delete.environment", (environmentItem: EnvSection) => { Utils.deleteEnvironmentServer(environmentItem); } ); vscode.commands.registerCommand( "totvs-developer-studio.rename", (serverItem: ServerItem) => { let ix = serverProvider.localServerItems.indexOf(serverItem); if (ix >= 0) { vscode.window .showInputBox({ placeHolder: localize( "tds.webview.serversView.renameServer", "Rename the server" ), value: (typeof serverItem.label === "string")?serverItem.label:(serverItem.label as vscode.TreeItemLabel).label, }) .then((newName: string) => { Utils.updateServerName(serverItem.id, newName); }); } } ); function createServer( typeServer: string, serverName: string, port: number, address: string, secure: number, buildVersion: string, showSucess: boolean, includes: string[] ): string | undefined { const serverId = Utils.createNewServer( typeServer, serverName, port, address, buildVersion, secure, includes ); if (serverId !== undefined && showSucess) { vscode.window.showInformationMessage( localize("tds.webview.serversView.serverSaved", "Saved server ") + serverName ); } return serverId; } function getWebViewContent(context, localizeHTML) { const htmlOnDiskPath = vscode.Uri.file( path.join(context.extensionPath, "src", "server", "addServer.html") ); const cssOniskPath = vscode.Uri.file( path.join(context.extensionPath, "resources", "css", "form.css") ); const htmlContent = fs.readFileSync( htmlOnDiskPath.with({ scheme: "vscode-resource" }).fsPath ); const cssContent = fs.readFileSync( cssOniskPath.with({ scheme: "vscode-resource" }).fsPath ); let runTemplate = compile(htmlContent); return runTemplate({ css: cssContent, localize: localizeHTML }); } } } function doFinishConnectProcess( serverItem: ServerItem, token: string, environment: string ) { Utils.saveConnectionToken(serverItem.id, token, environment); Utils.saveSelectServer( serverItem.id, token, serverItem.name, environment, serverItem.username ); if (serverProvider !== undefined) { serverItem.environment = environment; serverItem.token = token; serverProvider.connectedServerItem = serverItem; } runCommandUpdateMonitor(); //let isSafeRPO = serverItem.isSafeRPO; // this is not working returning => undefined let isSafeRPO = serverItem.buildVersion.localeCompare('7.00.191205P') > 0; // custom context tds-vscode.isSafeRPO vscode.commands.executeCommand('setContext', 'tds-vscode.isSafeRPO', isSafeRPO); } /* * O comando é registrado na tela do monitor, portanto, caso ela nao sido aberta, o comando nao existira, entao faz a busca antes de mais nada. * Segundo a documentacao, comandos que começam com "_" sao tratados com internos. * doc: https://vshaxe.github.io/vscode-extern/VscodeCommands.html */ function executeCommand(commandId: string) { return vscode.commands.getCommands(false).then((commands: string[]) => { let index = commands.indexOf(commandId); if(index > -1) { vscode.commands.executeCommand(commandId); } }); } function runCommandUpdateMonitor() { executeCommand("_totvs-developer-studio.updateMonitorPanel"); } export function connectServer( serverItem: ServerItem, environment: string, connType: ConnTypeIds ) { if (serverItem.isConnected && serverItem.environment === environment) { vscode.window.showInformationMessage( localize( "tds.webview.serversView.alreadyConn", "The server selected is already connected." ) ); } else { if (serverProvider.connectedServerItem !== undefined) { vscode.commands.executeCommand( "totvs-developer-studio.disconnect", serverProvider.connectedServerItem ); } vscode.window.setStatusBarMessage( `Conectando-se ao servidor [${serverItem.name}]`, sendConnectRequest(serverItem, environment, connType).then( (result: ITokenInfo) => { if (result.sucess) { if (result.needAuthentication) { serverItem.token = result.token; inputAuthenticationParameters(serverItem, environment); } else { doFinishConnectProcess(serverItem, result.token, environment); } } return result.sucess; }, (error) => { vscode.window.showErrorMessage(error); } ) ); } } export function authenticate( serverItem: ServerItem, environment: string, username: string, password: string ) { const enconding: string = vscode.env.language === "ru" ? ENABLE_CODE_PAGE.CP1251 : ENABLE_CODE_PAGE.CP1252; vscode.window.setStatusBarMessage( `Autenticando usuário [${username}] no servidor [${serverItem.name}]`, sendAuthenticateRequest( serverItem, environment, username, password, enconding ) .then( (result: IAuthenticationInfo) => { let token: string = result.token; return result.sucess ? token : ""; }, (error: any) => { vscode.window.showErrorMessage(error); } ) .then((token: string) => { if (token) { serverItem.username = username; doFinishConnectProcess(serverItem, token, environment); } }) ); } function doReconnect( serverItem: ServerItem, environment: string, connType: ConnTypeIds ): Thenable<boolean> { const token = Utils.getSavedTokens(serverItem.id, environment); if (token) { return sendReconnectRequest(serverItem, token, connType).then( (ri: IReconnectInfo) => { if (ri.sucess) { doFinishConnectProcess(serverItem, ri.token, environment); } return ri.sucess; } ); } else { return Promise.resolve(false); } } export function reconnectServer( serverItem: ServerItem, environment: string, connType: ConnTypeIds ) { const connectedServerItem = serverProvider.connectedServerItem; if (connectedServerItem !== undefined) { async () => await vscode.commands.executeCommand( "totvs-developer-studio.disconnect", connectedServerItem ); } vscode.window.setStatusBarMessage( `$(loading) Reconectando-se ao servidor [${serverItem.name}]`, doReconnect(serverItem, environment, connType) ); } export function reconnectLastServer() { const servers = Utils.getServersConfig(); if (servers.lastConnectedServer && servers.configurations) { servers.configurations.forEach((element) => { if (element.id === servers.lastConnectedServer) { reconnectServer( element, element.environment, ConnTypeIds.CONNT_DEBUGGER ); } }); } } class NodeError { code: number; message: string; } function handleError(nodeError: NodeError) { vscode.window.showErrorMessage(nodeError.code + ": " + nodeError.message); }
the_stack
import { ComponentInstance } from '../component' import { Ref, isRef, isReactive, ComputedRef } from '../reactivity' import { assert, logError, noopFn, warn, isFunction, isObject, isArray, isPlainObject, isSet, isMap, } from '../utils' import { defineComponentInstance } from '../utils/helper' import { getVueConstructor } from '../runtimeContext' import { WatcherPreFlushQueueKey, WatcherPostFlushQueueKey, } from '../utils/symbols' import { getCurrentScopeVM } from './effectScope' export type WatchEffect = (onInvalidate: InvalidateCbRegistrator) => void export type WatchSource<T = any> = Ref<T> | ComputedRef<T> | (() => T) export type WatchCallback<V = any, OV = any> = ( value: V, oldValue: OV, onInvalidate: InvalidateCbRegistrator ) => any type MapSources<T> = { [K in keyof T]: T[K] extends WatchSource<infer V> ? V : never } type MapOldSources<T, Immediate> = { [K in keyof T]: T[K] extends WatchSource<infer V> ? Immediate extends true ? V | undefined : V : never } export interface WatchOptionsBase { flush?: FlushMode // onTrack?: ReactiveEffectOptions['onTrack']; // onTrigger?: ReactiveEffectOptions['onTrigger']; } type InvalidateCbRegistrator = (cb: () => void) => void export type FlushMode = 'pre' | 'post' | 'sync' export interface WatchOptions<Immediate = boolean> extends WatchOptionsBase { immediate?: Immediate deep?: boolean } export interface VueWatcher { lazy: boolean get(): any teardown(): void run(): void value: any } export type WatchStopHandle = () => void let fallbackVM: ComponentInstance function flushPreQueue(this: any) { flushQueue(this, WatcherPreFlushQueueKey) } function flushPostQueue(this: any) { flushQueue(this, WatcherPostFlushQueueKey) } function hasWatchEnv(vm: any) { return vm[WatcherPreFlushQueueKey] !== undefined } function installWatchEnv(vm: any) { vm[WatcherPreFlushQueueKey] = [] vm[WatcherPostFlushQueueKey] = [] vm.$on('hook:beforeUpdate', flushPreQueue) vm.$on('hook:updated', flushPostQueue) } function getWatcherOption(options?: Partial<WatchOptions>): WatchOptions { return { ...{ immediate: false, deep: false, flush: 'pre', }, ...options, } } function getWatchEffectOption(options?: Partial<WatchOptions>): WatchOptions { return { ...{ flush: 'pre', }, ...options, } } function getWatcherVM() { let vm = getCurrentScopeVM() if (!vm) { if (!fallbackVM) { fallbackVM = defineComponentInstance(getVueConstructor()) } vm = fallbackVM } else if (!hasWatchEnv(vm)) { installWatchEnv(vm) } return vm } function flushQueue(vm: any, key: any) { const queue = vm[key] for (let index = 0; index < queue.length; index++) { queue[index]() } queue.length = 0 } function queueFlushJob( vm: any, fn: () => void, mode: Exclude<FlushMode, 'sync'> ) { // flush all when beforeUpdate and updated are not fired const fallbackFlush = () => { vm.$nextTick(() => { if (vm[WatcherPreFlushQueueKey].length) { flushQueue(vm, WatcherPreFlushQueueKey) } if (vm[WatcherPostFlushQueueKey].length) { flushQueue(vm, WatcherPostFlushQueueKey) } }) } switch (mode) { case 'pre': fallbackFlush() vm[WatcherPreFlushQueueKey].push(fn) break case 'post': fallbackFlush() vm[WatcherPostFlushQueueKey].push(fn) break default: assert( false, `flush must be one of ["post", "pre", "sync"], but got ${mode}` ) break } } function createVueWatcher( vm: ComponentInstance, getter: () => any, callback: (n: any, o: any) => any, options: { deep: boolean sync: boolean immediateInvokeCallback?: boolean noRun?: boolean before?: () => void } ): VueWatcher { const index = vm._watchers.length // @ts-ignore: use undocumented options vm.$watch(getter, callback, { immediate: options.immediateInvokeCallback, deep: options.deep, lazy: options.noRun, sync: options.sync, before: options.before, }) return vm._watchers[index] } // We have to monkeypatch the teardown function so Vue will run // runCleanup() when it tears down the watcher on unmounted. function patchWatcherTeardown(watcher: VueWatcher, runCleanup: () => void) { const _teardown = watcher.teardown watcher.teardown = function (...args) { _teardown.apply(watcher, args) runCleanup() } } function createWatcher( vm: ComponentInstance, source: WatchSource<unknown> | WatchSource<unknown>[] | WatchEffect, cb: WatchCallback<any> | null, options: WatchOptions ): () => void { if (__DEV__ && !cb) { if (options.immediate !== undefined) { warn( `watch() "immediate" option is only respected when using the ` + `watch(source, callback, options?) signature.` ) } if (options.deep !== undefined) { warn( `watch() "deep" option is only respected when using the ` + `watch(source, callback, options?) signature.` ) } } const flushMode = options.flush const isSync = flushMode === 'sync' let cleanup: (() => void) | null const registerCleanup: InvalidateCbRegistrator = (fn: () => void) => { cleanup = () => { try { fn() } catch ( // FIXME: remove any error: any ) { logError(error, vm, 'onCleanup()') } } } // cleanup before running getter again const runCleanup = () => { if (cleanup) { cleanup() cleanup = null } } const createScheduler = <T extends Function>(fn: T): T => { if ( isSync || /* without a current active instance, ignore pre|post mode */ vm === fallbackVM ) { return fn } return ((...args: any[]) => queueFlushJob( vm, () => { fn(...args) }, flushMode as 'pre' | 'post' )) as unknown as T } // effect watch if (cb === null) { let running = false const getter = () => { // preventing the watch callback being call in the same execution if (running) { return } try { running = true ;(source as WatchEffect)(registerCleanup) } finally { running = false } } const watcher = createVueWatcher(vm, getter, noopFn, { deep: options.deep || false, sync: isSync, before: runCleanup, }) patchWatcherTeardown(watcher, runCleanup) // enable the watcher update watcher.lazy = false const originGet = watcher.get.bind(watcher) // always run watchEffect watcher.get = createScheduler(originGet) return () => { watcher.teardown() } } let deep = options.deep let isMultiSource = false let getter: () => any if (isRef(source)) { getter = () => source.value } else if (isReactive(source)) { getter = () => source deep = true } else if (isArray(source)) { isMultiSource = true getter = () => source.map((s) => { if (isRef(s)) { return s.value } else if (isReactive(s)) { return traverse(s) } else if (isFunction(s)) { return s() } else { __DEV__ && warn( `Invalid watch source: ${JSON.stringify(s)}. A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.`, vm ) return noopFn } }) } else if (isFunction(source)) { getter = source as () => any } else { getter = noopFn __DEV__ && warn( `Invalid watch source: ${JSON.stringify(source)}. A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.`, vm ) } if (deep) { const baseGetter = getter getter = () => traverse(baseGetter()) } const applyCb = (n: any, o: any) => { if ( !deep && isMultiSource && n.every((v: any, i: number) => Object.is(v, o[i])) ) return // cleanup before running cb again runCleanup() return cb(n, o, registerCleanup) } let callback = createScheduler(applyCb) if (options.immediate) { const originalCallback = callback // `shiftCallback` is used to handle the first sync effect run. // The subsequent callbacks will redirect to `callback`. let shiftCallback = (n: any, o: any) => { shiftCallback = originalCallback // o is undefined on the first call return applyCb(n, isArray(n) ? [] : o) } callback = (n: any, o: any) => { return shiftCallback(n, o) } } // @ts-ignore: use undocumented option "sync" const stop = vm.$watch(getter, callback, { immediate: options.immediate, deep: deep, sync: isSync, }) // Once again, we have to hack the watcher for proper teardown const watcher = vm._watchers[vm._watchers.length - 1] // if the return value is reactive and deep:true // watch for changes, this might happen when new key is added if (isReactive(watcher.value) && watcher.value.__ob__?.dep && deep) { watcher.value.__ob__.dep.addSub({ update() { // this will force the source to be revaluated and the callback // executed if needed watcher.run() }, }) } patchWatcherTeardown(watcher, runCleanup) return () => { stop() } } export function watchEffect( effect: WatchEffect, options?: WatchOptionsBase ): WatchStopHandle { const opts = getWatchEffectOption(options) const vm = getWatcherVM() return createWatcher(vm, effect, null, opts) } export function watchPostEffect(effect: WatchEffect) { return watchEffect(effect, { flush: 'post' }) } export function watchSyncEffect(effect: WatchEffect) { return watchEffect(effect, { flush: 'sync' }) } // overload #1: array of multiple sources + cb // Readonly constraint helps the callback to correctly infer value types based // on position in the source array. Otherwise the values will get a union type // of all possible value types. export function watch< T extends Readonly<WatchSource<unknown>[]>, Immediate extends Readonly<boolean> = false >( sources: T, cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>, options?: WatchOptions<Immediate> ): WatchStopHandle // overload #2: single source + cb export function watch<T, Immediate extends Readonly<boolean> = false>( source: WatchSource<T>, cb: WatchCallback<T, Immediate extends true ? T | undefined : T>, options?: WatchOptions<Immediate> ): WatchStopHandle // overload #3: watching reactive object w/ cb export function watch< T extends object, Immediate extends Readonly<boolean> = false >( source: T, cb: WatchCallback<T, Immediate extends true ? T | undefined : T>, options?: WatchOptions<Immediate> ): WatchStopHandle // implementation export function watch<T = any>( source: WatchSource<T> | WatchSource<T>[], cb: WatchCallback<T>, options?: WatchOptions ): WatchStopHandle { let callback: WatchCallback<unknown> | null = null if (isFunction(cb)) { // source watch callback = cb as WatchCallback<unknown> } else { // effect watch if (__DEV__) { warn( `\`watch(fn, options?)\` signature has been moved to a separate API. ` + `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` + `supports \`watch(source, cb, options?) signature.` ) } options = cb as Partial<WatchOptions> callback = null } const opts = getWatcherOption(options) const vm = getWatcherVM() return createWatcher(vm, source, callback, opts) } function traverse(value: unknown, seen: Set<unknown> = new Set()) { if (!isObject(value) || seen.has(value)) { return value } seen.add(value) if (isRef(value)) { traverse(value.value, seen) } else if (isArray(value)) { for (let i = 0; i < value.length; i++) { traverse(value[i], seen) } } else if (isSet(value) || isMap(value)) { value.forEach((v: any) => { traverse(v, seen) }) } else if (isPlainObject(value)) { for (const key in value) { traverse(value[key], seen) } } return value }
the_stack
import { Rule, RuleResult, RuleFail, RuleContext, RulePotential, RuleManual, RulePass } from "../../../api/IEngine"; import { DOMUtil } from "../../../dom/DOMUtil"; import { DOMWalker } from "../../../dom/DOMWalker"; import { FragmentUtil } from "../util/fragment"; import { RPTUtil, NodeWalker } from "../util/legacy"; let a11yRulesInput: Rule[] = [ { /** * Description: Trigger if an input isn't labeled or titled * Origin: WCAG 2.0 Technique H44, H65, H91 */ id: "WCAG20_Input_ExplicitLabel", context: "aria:button,aria:checkbox,aria:combobox,aria:listbox,aria:menuitemcheckbox" +",aria:menuitemradio,aria:radio,aria:searchbox,aria:slider,aria:spinbutton" +",aria:switch,aria:textbox,aria:progressbar,dom:input[type=file],dom:output", // the datalist element do not require any explicit or implicit label, might need to exclude it from the scope of the rules run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; // JCH - NO OUT OF SCOPE hidden in context /* removed the check role= presentation since according to latest native host semantics https://www.w3.org/TR/html-aria/#docconformance table, these two roles are not applicable to the elements are in the scope of this role if (RPTUtil.hasRole(ruleContext, "presentation") || RPTUtil.hasRole(ruleContext, "none")) return RulePass(1); */ if (ruleContext.getAttribute("aria-hidden")) { return null; } // Determine the input type let passed = true; let nodeName = ruleContext.nodeName.toLowerCase(); let type = "text"; if (nodeName == "input" && ruleContext.hasAttribute("type")) { type = ruleContext.getAttribute("type").toLowerCase(); } else if (nodeName === "button" || RPTUtil.hasRoleInSemantics(ruleContext, "button")) { type = "buttonelem"; } if (nodeName == "input" && type == "") { type = "text"; } if (type === "image") { // Handled by WCAG20_Input_ExplicitLabelImage return null; } let POF = -1; let textTypes = [ "text", "file", "password", "checkbox", "radio", "search", "tel", "url", "email", //HTML 5. Note: type = "hidden" doesn't require text "date", "number", "range", //HTML 5. type = "image" is checked in g10. "time", "color" ] let buttonTypes = [ "button", "reset", "submit" ] let buttonTypesWithDefaults = ["reset", "submit"]; // 'submit' and 'reset' have visible defaults. if (textTypes.indexOf(type) !== -1) { // If type is in the list // Get only the non-hidden labels for element, in the case that an label is hidden then it is a violation // Note: label[for] does not work for ARIA-defined inputs let labelElem = ruleContext.hasAttribute("role") ? null : RPTUtil.getLabelForElementHidden(ruleContext, true); let hasLabelElemContent = false; if (labelElem) { if (RPTUtil.hasInnerContentHidden(labelElem)) { hasLabelElemContent = true; } else if ((labelElem.getAttribute("aria-label") || "").trim().length > 0) { hasLabelElemContent = true; } else if (labelElem.hasAttribute("aria-labelledby")) { let labelledByElem = FragmentUtil.getById(labelElem, labelElem.getAttribute('aria-labelledby')); if (labelledByElem && RPTUtil.hasInnerContent(labelledByElem)) { hasLabelElemContent = true; } } } passed = (!!labelElem && hasLabelElemContent) || (!labelElem && RPTUtil.attributeNonEmpty(ruleContext, "title") || RPTUtil.attributeNonEmpty(ruleContext, "placeholder")) || RPTUtil.getAriaLabel(ruleContext).trim().length > 0 || RPTUtil.hasImplicitLabel(ruleContext); if (!passed) POF = 2 + textTypes.indexOf(type); } else if (buttonTypes.indexOf(type) !== -1) { // If type is a button if (buttonTypesWithDefaults.indexOf(type) !== -1 && !ruleContext.hasAttribute("value")) { // 'submit' and 'reset' have visible defaults so pass if there is no 'value' attribute passed = true; } else { passed = RPTUtil.attributeNonEmpty(ruleContext, "value") || RPTUtil.hasAriaLabel(ruleContext) || RPTUtil.attributeNonEmpty(ruleContext, "title"); if (!passed) POF = 2 + textTypes.length + buttonTypes.indexOf(type); } } else if (type == "buttonelem") { // If I am an image and I have alt text - accessibility-web-engine#269 let bAlt = false; if (ruleContext.nodeName.toLowerCase() === "img" && ruleContext.hasAttribute("alt")) { let alt = ruleContext.getAttribute("alt"); if (alt.trim().length === 0) { bAlt = false; } else { bAlt = true; } }; passed = RPTUtil.hasInnerContentHidden(ruleContext) || RPTUtil.hasAriaLabel(ruleContext) || bAlt || RPTUtil.attributeNonEmpty(ruleContext, "title"); if (!passed) POF = 2 + textTypes.length + buttonTypes.length + 1; } // Rpt_Aria_ValidIdRef determines if the aria-labelledby id points to a valid element if (!passed && (buttonTypes.indexOf(type) !== -1)) { if (ruleContext.hasAttribute("class") && ruleContext.getAttribute("class") == "dijitOffScreen" && DOMUtil.parentElement(ruleContext).hasAttribute("widgetid")) { // Special handling for dijit buttons let labelId = DOMUtil.parentElement(ruleContext).getAttribute("widgetid") + "_label"; let label = FragmentUtil.getById(ruleContext, labelId); if (label != null) { passed = RPTUtil.hasInnerContentHidden(label); // This means I failed above also if (!passed) POF = 2 + textTypes.length + buttonTypes.length + 4 + buttonTypes.indexOf(type); } } } if (!passed && nodeName == "optgroup") { passed = RPTUtil.attributeNonEmpty(ruleContext, "label"); if (!passed) POF = 2 + textTypes.length + buttonTypes.length + 2; } if (!passed && nodeName == "option") { // Is a non-empty value attribute also enough for an option element? passed = RPTUtil.attributeNonEmpty(ruleContext, "label") || ruleContext.innerHTML.trim().length > 0; if (!passed) POF = 2 + textTypes.length + buttonTypes.length + 3; } if (passed) { return RulePass("Pass_0"); } else if (ruleContext.hasAttribute("role") && ruleContext.getAttribute("role").trim().length > 0) { return RuleFail("Fail_2", ruleContext.getAttribute("role").split(" ")); } else { return RuleFail("Fail_1", [nodeName]); } } }, { /** * Description: Trigger if an image input does not have alt. * Origin: WCAG 2.0 Technique H91 */ id: "WCAG20_Input_ExplicitLabelImage", context: "dom:input", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { // See https://www.w3.org/WAI/WCAG21/Techniques/failures/F65 const ruleContext = context["dom"].node as Element; if (!ruleContext.hasAttribute("type") || ruleContext.getAttribute("type").toLowerCase() != "image") { return null; } if (RPTUtil.attributeNonEmpty(ruleContext, "alt")) { return RulePass("Pass_0"); } else if (RPTUtil.hasAriaLabel(ruleContext)) { return RulePass("Pass_1"); } else if (ruleContext.hasAttribute("title") && ruleContext.getAttribute("title").length > 0) { return RulePass("Pass_2"); } return RuleFail("Fail"); } }, { /** * Description: Trigger if the label is supposed to be before the input, but is not. * Origin: WCAG 2.0 Technique H44 */ id: "WCAG20_Input_LabelBefore", context: "dom:input, dom:textarea, dom:select", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; if (ruleContext.nodeName.toLowerCase() == "input" && ruleContext.hasAttribute("type")) { let type = ruleContext.getAttribute("type").toLowerCase(); if (type != "text" && type != "file" && type != "password") { return null; } } // Get only the non-hidden labels for element let labelElem = RPTUtil.getLabelForElementHidden(ruleContext, true); if (labelElem == null || !RPTUtil.hasInnerContentHidden(labelElem)) { // Due to dependency, label must be done via title - this rule doesn't apply return null; } let value = RPTUtil.compareNodeOrder(labelElem, ruleContext); if (value == -2) { // input nested in label let passed = false; let walkNode = ruleContext.previousSibling; while (!passed && walkNode != null) { passed = ((walkNode.nodeName.toLowerCase() == "#text" && walkNode.nodeValue.trim().length > 0) || (walkNode.nodeName.toLowerCase() == "span" && walkNode.textContent.trim().length > 0)); walkNode = walkNode.previousSibling; } if (!passed) { // Input nested in label and text after input return RuleFail("Fail_1"); } } else { if (value != -1) { // label is after input return RuleFail("Fail_2"); } } // Haven't returned yet, then I pass return RulePass("Pass_0"); } }, { /** * Description: Trigger if the label is supposed to be after the input, but is not. * Origin: WCAG 2.0 Technique H44 */ id: "WCAG20_Input_LabelAfter", context: "dom:input", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; let type = ""; if (ruleContext.hasAttribute("type")) type = ruleContext.getAttribute("type").toLowerCase(); if (type != "checkbox" && type != "radio") { return null; } // Get only the non-hidden labels for element let labelElem = RPTUtil.getLabelForElementHidden(ruleContext, true); if (labelElem === null || !RPTUtil.hasInnerContentHidden(labelElem)) { // Due to dependency, label must be done via title - this rule doesn't apply return null; } let value = RPTUtil.compareNodeOrder(labelElem, ruleContext); let passed; if (value === -2) { // input nested in label passed = false; let walkNode = new NodeWalker(labelElem); walkNode.node = ruleContext; while (!passed && walkNode.nextNode()) { passed = ((walkNode.node.nodeName.toLowerCase() === "#text" && walkNode.node.nodeValue.trim().length > 0) || (walkNode.node.nodeName.toLowerCase() === "span" && walkNode.node.textContent.trim().length > 0)); } if (!passed) { // Input nested in label and text before input return RuleFail("Fail_1"); } } else { if (value != 1) { // label is before input return RuleFail("Fail_2"); } } return RulePass("Pass_0"); } }, { /** * Description: Trigger if non-radio/chk inputs are not in a fieldset * Origin: WCAG 2.0 Technique H71 */ id: "WCAG20_Input_InFieldSet", context: "dom:input, dom:textarea, dom:select", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; // Don't trigger for other input types or if we're in a fieldset if (ruleContext.nodeName.toLowerCase() == "input" && ruleContext.hasAttribute("type")) { let type = ruleContext.getAttribute("type").toLowerCase(); if (type != "text" && type != "file" && type != "password") return RulePass("Pass_0"); } if (RPTUtil.getAncestor(ruleContext, "fieldset") != null) return RulePass("Pass_0"); // No fieldset - see if this input is all by itself - no need to group single inputs let parent = RPTUtil.getAncestor(ruleContext, ["form", "body"]); let checkTypes = ["input", "textarea", "select"]; let passed = true; for (let i = 0; passed && i < checkTypes.length; ++i) { let controls = parent.getElementsByTagName(checkTypes[i]); for (let j = 0; passed && j < controls.length; ++j) { // Check if the node should be skipped or not based on the Check Hidden Content setting and if the node isVisible or // not. if (RPTUtil.shouldNodeBeSkippedHidden(controls[j])) { continue; } // Note that textareas and selects will be called type='text' let type = controls[j].hasAttribute("type") ? controls[j].getAttribute("type").toLowerCase() : "text"; // Only fail if this is another control in the form and its type is another text-like input passed = controls[j] == ruleContext || (type != "text" && type != "password" && type != "file"); } } if (passed) return RulePass("Pass_0"); if (!passed) return RulePotential("Potential_1"); } }, { /** * Description: Trigger if a radio/checkbox with same name is not grouped * (e.g., in a fieldset, with role = "group", etc.) * Origin: WCAG 2.0 Technique H71, H91 * * Failures: * 0a. radio not in fieldset, group or radiogroup - AND I find another radio or check with the same 'name' attribute- AND I'm not in a table * 0b. checkbox not in fieldset or group - AND I find another radio or check with the same 'name' attribute - AND I'm not in a table * 1. radio or checkbox missing a name [IGNORE?] * 2. radio or checkbox has the same "name" attribute as another radio or checkbox in a separate fieldset, group or radiogroup * 3. am in table and some combination of the above */ id: "WCAG20_Input_RadioChkInFieldSet", context: "dom:input", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; if (context["aria"].role === 'none' || context["aria"].role === 'presentation') return null; const getGroup = (e : Element) => { let retVal = RPTUtil.getAncestor(e, "fieldset") || RPTUtil.getAncestorWithRole(e, "radiogroup") || RPTUtil.getAncestorWithRole(e, "group") || RPTUtil.getAncestorWithRole(e, "grid") || RPTUtil.getAncestorWithRole(e, "table"); if (!retVal) { retVal = RPTUtil.getAncestor(e, "table"); if (retVal && !RPTUtil.isDataTable(retVal)) { retVal = null; } } return retVal; } // Only radio buttons and checkboxes are in scope let ctxType = ruleContext.hasAttribute("type") ? ruleContext.getAttribute("type").toLowerCase() : "text"; if (ctxType !== "checkbox" && ctxType !== "radio") { return null; } // Determine which form we're in (if any) to determine our scope let ctxForm = RPTUtil.getAncestorWithRole(ruleContext, "form") || RPTUtil.getAncestor(ruleContext, "html") || ruleContext.ownerDocument.documentElement; // Get data about all of the visible checkboxes and radios in the scope of this form // and cache it for all of the other inputs in this scope let formCache = RPTUtil.getCache(ctxForm, "WCAG20_Input_RadioChkInFieldSet", null); if (!formCache) { formCache = { checkboxByName: {}, radiosByName: {}, nameToGroup: { }, numCheckboxes: 0, numRadios: 0 } // Get all of the checkboxes in the form or body (but not nested in something else and not hidden) // And get a mapping of these checkboxes to let cWalker = new DOMWalker(ctxForm, false, ctxForm); let checkboxQ = []; let radiosQ = []; while (cWalker.nextNode()) { if (!cWalker.bEndTag && cWalker.node.nodeType === 1 && cWalker.node.nodeName.toLowerCase() === "input" && RPTUtil.isNodeVisible(cWalker.node)) { let type = (cWalker.node as Element).getAttribute("type"); if (type === "checkbox") { checkboxQ.push(cWalker.node); } else if (type === "radio") { radiosQ.push(cWalker.node); } } } // let checkboxQ = ctxForm.querySelectorAll("input[type=checkbox]"); for (let idx=0; idx<checkboxQ.length; ++idx) { const cb = checkboxQ[idx]; if ((RPTUtil.getAncestorWithRole(cb, "form") || RPTUtil.getAncestor(ruleContext, "html") || ruleContext.ownerDocument.documentElement) === ctxForm && !RPTUtil.shouldNodeBeSkippedHidden(cb)) { const name = cb.getAttribute("name") || ""; (formCache.checkboxByName[name] = formCache.checkboxByName[name] || []).push(cb); formCache.nameToGroup[name] = formCache.nameToGroup[name] || getGroup(cb); ++formCache.numCheckboxes; } } // Get all of the radios in the form or body (but not nested in something else and not hidden) // let radiosQ = ctxForm.querySelectorAll("input[type=radio]"); for (let idx=0; idx<radiosQ.length; ++idx) { const r = radiosQ[idx]; const radCtx = (RPTUtil.getAncestorWithRole(r, "form") || RPTUtil.getAncestor(ruleContext, "html") || ruleContext.ownerDocument.documentElement); if (radCtx === ctxForm && !RPTUtil.shouldNodeBeSkippedHidden(r)) { const name = r.getAttribute("name") || ""; (formCache.radiosByName[name] = formCache.radiosByName[name] || []).push(r); formCache.nameToGroup[name] = formCache.nameToGroup[name] || getGroup(r); ++formCache.numRadios; } } RPTUtil.setCache(ctxForm, "WCAG20_Input_RadioChkInFieldSet", formCache); } ///////////// Calculated everything, now check the various cases const ctxName = ruleContext.getAttribute("name"); const ctxGroup = getGroup(ruleContext); ctxType = ctxType === "radio" ? "Radio" : "Checkbox"; if (!ctxName || ctxName === "") { // First process cases where the control is not named if (ctxType === "Radio") { // Radios without names don't act like groups, so don't enforce grouping if (ctxGroup === null) { return RulePass("Pass_RadioNoName", [ctxType]); } else { return RulePass("Pass_Grouped", [ctxType]); } } else { // Must be an unnamed checkbox if (ctxGroup === null) { if ((formCache.checkboxByName[""] || []).length > 1) { return RulePotential("Potential_UnnamedCheckbox", [ctxType]); } else { return RulePass("Pass_LoneNogroup", [ctxType]); } } else { return RulePass("Pass_Grouped", [ctxType]); } } } else { // Considering a named checkbox const numRadiosWithName = (formCache.radiosByName[ctxName] || []).length; const numCheckboxesWithName = (formCache.checkboxByName[ctxName] || []).length; // Capitalize the input type for messages if (numRadiosWithName > 0 && numCheckboxesWithName > 0) { // We have a naming mismatch between different controls return RuleFail("Fail_ControlNameMismatch", [ctxType, ctxType === "checkbox"?"radio":"checkbox", ctxName]); } else if (ctxType === "Radio" && (formCache.numRadios === 1 || numRadiosWithName === 1) || ctxType === "Checkbox" && formCache.numCheckboxes === 1) { // This is a lone control (either only control of this type on the page, or a radio button without any others by that name) // We pass this control in all cases if (ctxGroup === null) { return RulePass("Pass_LoneNogroup", [ctxType]); } else { return RulePass("Pass_Grouped", [ctxType]); } } else if (ctxType === "Checkbox" && formCache.numCheckboxes > 1 && numCheckboxesWithName === 1) { // We have only one checkbox with this name, but there are other checkboxes in the form. // If we're not grouped, ask them to examine it if (ctxGroup === null) { return RulePotential("Potential_LoneCheckbox", [ctxType]); } else { return RulePass("Pass_Grouped", [ctxType]); } } else { // We share a name with another similar control. Are we grouped together? if (ctxGroup === null) { if (formCache.nameToGroup[ctxName] !== null) { // We're not grouped, but some control with the same name is in a group return RuleFail("Fail_NotGroupedOtherGrouped", [ctxType, ctxName]); } else { // None of us are grouped return RuleFail("Fail_NotGroupedOtherNotGrouped", [ctxType, ctxName]) } } else if (formCache.nameToGroup[ctxName] !== ctxGroup) { // We're not in the main group with the others return RuleFail("Fail_NotSameGroup", [ctxType, ctxName]); } else { // We're all grouped up! return RulePass("Pass_Grouped", [ctxType]); } } } } }, { /** * Description: Triggers if input has an onchange event handler * Origin: WCAG 2.0 Technique G13 */ id: "WCAG20_Input_HasOnchange", context: "dom:input, dom:textarea, dom:select", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; if (ruleContext.nodeName.toLowerCase() == "input" && ruleContext.hasAttribute("type")) { let type = ruleContext.getAttribute("type").toLowerCase(); if (type != "text" && type != "file" && type != "password" && type != "checkbox" && type != "radio") return RulePass("Pass_0"); } let passed = !ruleContext.hasAttribute("onchange"); if (passed) return RulePass("Pass_0"); if (!passed) return RulePotential("Potential_1"); } }, { /** * Description: Triggers if input has a HTML 5 required property: HAAC, G1124 */ id: "HAAC_Input_HasRequired", context: "dom:input, dom:textarea, dom:select", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; let passed = true; if (ruleContext.hasAttribute("required")) { passed = false; } if (passed) return RulePass("Pass_0"); if (!passed) return RulePotential("Potential_1"); } }, { /** * Description: Triggers if placeholder is used as a replacement of label * * Origin: HTML 5 - per Richard Schwerdtfeger's requirements. g1145 */ id: "HAAC_Input_Placeholder", context: "dom:input[placeholder], dom:textarea[placeholder]", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; if (ruleContext.hasAttribute("type")) { let type = ruleContext.getAttribute("type").toLowerCase(); if (type == "hidden" || type == "button") { return RulePass("Pass_0"); } } if (ruleContext.hasAttribute("hidden")) { let hidden = ruleContext.getAttribute("hidden"); if (hidden == "" || hidden.toLowerCase() == "hidden") { // when hidden is empty in the element, "" is returned, same as it has a value of "". return RulePass("Pass_0"); } } if (ruleContext.hasAttribute("aria-label")) { return RulePotential("Potential_1"); } if (ruleContext.hasAttribute("aria-labelledby") && ruleContext.hasAttribute("id")) { let id = ruleContext.getAttribute("id").trim(); let refIds = ruleContext.getAttribute("aria-labelledby").trim().split(/\s+/); // separated by one or more white spaces if (!refIds.includes(id)) { return RulePass("Pass_0"); } else { return RulePotential("Potential_2"); } } return RulePass("Pass_0"); } }, { /** * Description: Checks that the HTML autocomplete attribute has a correct value. * The rule applies to any HTML input, select and textarea element with a non-empty HTML autocomplete attribute except when one of the following is true: * - The element is not visible on the page, not included in the accessibility tree, and not focusable * - The element is an input element with a type property of hidden, button, submit or reset * - The element has a disabled or aria-disabled="true" attribute * - The element has tabindex="-1" and has a semantic role that is not a widget. (Disabled for now) * Origin: WCAG 2.1 Success Criterion 1.3.5 (Identify Input Purpose) */ id: "WCAG21_Input_Autocomplete", context: "dom:input[autocomplete], dom:textarea[autocomplete], dom:select[autocomplete]", run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const cache = { "tokensOnOff": ["on", "off"], "tokenOptionalSection": "section-", "tokensOptionalPurpose": ["shipping", "billing"], "tokensMandatoryGroup1_password": ["new-password", "current-password"], "tokensMandatoryGroup1_multiline": ["street-address"], "tokensMandatoryGroup1_month": ["cc-exp"], "tokensMandatoryGroup1_numeric": ["cc-exp-month", "cc-exp-year", "transaction-amount", "bday-day", "bday-month", "bday-year"], "tokensMandatoryGroup1_date": ["bday"], "tokensMandatoryGroup1_url": ["url", "photo"], "tokensMandatoryGroup1_text": ["name", "honorific-prefix", "given-name", "additional-name", "family-name", "honorific-suffix", "nickname", "username", "organization-title", "organization", "address-line1", "address-line2", "address-line3", "address-level4", "address-level3", "address-level2", "address-level1", "country", "country-name", "postal-code", "cc-name", "cc-given-name", "cc-additional-name", "cc-family-name", "cc-number", "cc-csc", "cc-type", "transaction-currency", "language", "sex"], "tokensMandatoryGroup1_all": ["name", "honorific-prefix", "given-name", "additional-name", "family-name", "honorific-suffix", "nickname", "username", "new-password", "current-password", "organization-title", "organization", "street-address", "address-line1", "address-line2", "address-line3", "address-level4", "address-level3", "address-level2", "address-level1", "country", "country-name", "postal-code", "cc-name", "cc-given-name", "cc-additional-name", "cc-family-name", "cc-number", "cc-exp", "cc-exp-month", "cc-exp-year", "cc-csc", "cc-type", "transaction-currency", "transaction-amount", "language", "bday", "bday-day", "bday-month", "bday-year", "sex", "url", "photo"], "tokensOptionalGroup2": ["home", "work", "mobile", "fax", "pager"], "tokensMandatoryGroup2_tel": ["tel"], "tokensMandatoryGroup2_email": ["email"], "tokensMandatoryGroup2_url": ["impp"], "tokensMandatoryGroup2_text": ["tel-country-code", "tel-national", "tel-area-code", "tel-local", "tel-local-prefix", "tel-local-suffix", "tel-extension"], "tokensMandatoryGroup2_all": ["tel", "tel-country-code", "tel-national", "tel-area-code", "tel-local", "tel-local-prefix", "tel-local-suffix", "tel-extension", "email", "impp"] } const ruleContext = context["dom"].node as Element; let foundMandatoryToken = false; let nodeName = ruleContext.nodeName.toLowerCase(); if (!RPTUtil.isNodeVisible(ruleContext) || RPTUtil.isNodeDisabled(ruleContext)) { return null; } let type = ruleContext.hasAttribute("type") ? ruleContext.getAttribute("type").trim().toLowerCase() : "text"; let autocompleteAttr = ruleContext.getAttribute("autocomplete").trim().toLowerCase(); let tokens = autocompleteAttr.split(/\s+/); if (tokens.length === 0 || autocompleteAttr.length === 0) { return null; } let tokensMandatoryGroup1 = []; let tokensMandatoryGroup2 = []; if (nodeName === "textarea" || nodeName === "select") { // accept all tokens tokensMandatoryGroup1 = cache.tokensMandatoryGroup1_all; tokensMandatoryGroup2 = cache.tokensMandatoryGroup2_all; } else if (nodeName === "input") { // handle the various 'input' types switch (type) { // Disable check for input type=hidden for now based on scrum discussion /* case "hidden": // accept all tokens tokensMandatoryGroup1 = cache.tokensMandatoryGroup1_all; tokensMandatoryGroup2 = cache.tokensMandatoryGroup2_all; break; */ case "text": case "search": tokensMandatoryGroup1 = cache.tokensMandatoryGroup1_text.concat(cache.tokensMandatoryGroup1_password, cache.tokensMandatoryGroup1_url, cache.tokensMandatoryGroup1_numeric, cache.tokensMandatoryGroup1_month, cache.tokensMandatoryGroup1_date); tokensMandatoryGroup2 = cache.tokensMandatoryGroup2_all; break; case "password": tokensMandatoryGroup1 = cache.tokensMandatoryGroup1_password; break; case "url": tokensMandatoryGroup1 = cache.tokensMandatoryGroup1_url; tokensMandatoryGroup2 = cache.tokensMandatoryGroup2_url; break; case "email": tokensMandatoryGroup2 = cache.tokensMandatoryGroup2_email; break; case "tel": tokensMandatoryGroup2 = cache.tokensMandatoryGroup2_tel; break; case "number": tokensMandatoryGroup1 = cache.tokensMandatoryGroup1_numeric; break; case "month": tokensMandatoryGroup1 = cache.tokensMandatoryGroup1_month; break; case "date": tokensMandatoryGroup1 = cache.tokensMandatoryGroup1_date; break; default: // unsupported type for this rule. return null; } } else { // should never get here. return null; } // Disable check for input type=hidden for now based on scrum discussion let autofillMantle = /* (nodeName==="input" && type==="hidden") ? "anchor" : */ "expectation"; if (autofillMantle === "expectation") { // check on|off for expectation mantle. if (tokens.includes("on") || tokens.includes("off")) { // on|off should be the only token if (tokens.length === 1) { return RulePass(1); } else { return RuleFail(2); } } } // check detail autofill tokens let currIndex = 0; // check optional 'section-*' tokens if (tokens[currIndex].startsWith(cache.tokenOptionalSection) && tokens[currIndex].length > 8) { currIndex++; // consume token } // check optional 'shipping|billing' tokens if (tokens.length > currIndex && cache.tokensOptionalPurpose.includes(tokens[currIndex])) { currIndex++; // consume token } // check either mandatory group 1 or 2 tokens if (tokens.length > currIndex) { // check mandatory group 1 if (tokensMandatoryGroup1.includes(tokens[currIndex])) { foundMandatoryToken = true; currIndex++; } else { // check optional tokens for group 2 if (cache.tokensOptionalGroup2.includes(tokens[currIndex])) { currIndex++; } // check mandatory group 2 if (tokensMandatoryGroup2.includes(tokens[currIndex])) { foundMandatoryToken = true; currIndex++; } } } // Only pass if we have seen either of the mandatory groups and all tokens have been consumed if (foundMandatoryToken && tokens.length === currIndex) { return RulePass("Pass_0"); } else { return RuleFail("Fail_1"); } } }, { /** * Description: Trigger if an input does not have a visible label * Origin: WCAG 2.0 Success Criterion 3.3.2 */ id: "WCAG20_Input_VisibleLabel", context: "aria:button,aria:checkbox,aria:combobox,aria:listbox,aria:menuitemcheckbox" +",aria:menuitemradio,aria:radio,aria:searchbox,aria:slider,aria:spinbutton" +",aria:switch,aria:textbox,aria:progressbar,dom:input[type=file],dom:output", dependencies: ["WCAG20_Input_ExplicitLabel"], run: (context: RuleContext, options?: {}): RuleResult | RuleResult[] => { const ruleContext = context["dom"].node as Element; let nodeName = ruleContext.nodeName.toLowerCase(); if (!RPTUtil.isNodeVisible(ruleContext) || RPTUtil.isNodeDisabled(ruleContext)) { return null; } // when in a combobox, only look at the input textbox. if (RPTUtil.getAncestorWithRole(ruleContext, "combobox") && !(RPTUtil.hasRoleInSemantics(ruleContext, "textbox") || RPTUtil.hasRoleInSemantics(ruleContext, "searchbox") || nodeName === "input" || (nodeName === "select" && RPTUtil.hasRoleInSemantics(ruleContext, "combobox")))) { return null; } // avoid diagnosing the popup list of a combobox. let rolesToCheck = ["listbox", "tree", "grid", "dialog"]; for (let j = 0; j < rolesToCheck.length; j++) { if (RPTUtil.hasRoleInSemantics(ruleContext, rolesToCheck[j])) { let comboboxes = RPTUtil.getElementsByRoleHidden(ruleContext.ownerDocument, "combobox", true, true); for (let k = 0; k < comboboxes.length; k++) { let combobox = comboboxes[k]; let aria_owns = RPTUtil.getElementAttribute(combobox, "aria-owns"); if (aria_owns) { let owns = RPTUtil.normalizeSpacing(aria_owns.trim()).split(" "); for (let i = 0; i < owns.length; i++) { let owned = FragmentUtil.getById(ruleContext, owns[i]); if (owned === ruleContext) { return null; } } } } } } // Determine the input type let passed = true; let type = "text"; if (nodeName == "input" && ruleContext.hasAttribute("type")) { type = ruleContext.getAttribute("type").toLowerCase(); } else if (nodeName === "button" || RPTUtil.hasRoleInSemantics(ruleContext, "button")) { type = "buttonelem"; } if (nodeName == "input" && type == "") { type = "text"; } let textTypes = ["text", "file", "password", "checkbox", "radio", "search", "tel", "url", "email", "date", "number", "range", "time", "color", "month", "week", "datetime-local"]; let buttonTypes = ["button", "reset", "submit"]; let buttonTypesWithDefaults = ["reset", "submit"]; // 'submit' and 'reset' have visible defaults. if (textTypes.indexOf(type) !== -1) { // If type is in the list // Get only the non-hidden labels for element, in the case that an label is hidden then it is a violation let labelElem = RPTUtil.getLabelForElementHidden(ruleContext, true); passed = (labelElem != null && RPTUtil.hasInnerContentHidden(labelElem)) || RPTUtil.hasImplicitLabel(ruleContext) || type === "file"; // input type=file has a visible default. } else if (buttonTypes.indexOf(type) !== -1 || type == "buttonelem") { // Buttons are not in scope for this success criteria (IBMa/equal-access#204) return null; } // check if there is a visible label pointed to by the aria-labelledby attribute. if (!passed && RPTUtil.attributeNonEmpty(ruleContext, "aria-labelledby")) { let theLabel = ruleContext.getAttribute("aria-labelledby"); let labelValues = theLabel.split(/\s+/); for (let j = 0; j < labelValues.length; ++j) { let elementById = FragmentUtil.getById(ruleContext, labelValues[j]); if (elementById && RPTUtil.isNodeVisible(elementById) && RPTUtil.hasInnerContentHidden(elementById)) { passed = true; break; } } } if (!passed && nodeName == "optgroup") { passed = RPTUtil.attributeNonEmpty(ruleContext, "label"); } if (!passed && nodeName == "option") { passed = RPTUtil.attributeNonEmpty(ruleContext, "label") || ruleContext.innerHTML.trim().length > 0; } // One last check for roles that support name from content if (!passed) { // list from https://www.w3.org/TR/wai-aria-1.1/#namefromcontent let rolesWithNameFromContent = ["button", "cell", "checkbox", "columnheader", "gridcell", "heading", "link", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "row", "rowgroup", "rowheader", "switch", "tab", "tooltip",/*"tree",*/"treeitem"]; //get attribute roles as well as implicit roles. let roles = RPTUtil.getRoles(ruleContext, true); for (let i = 0; i < roles.length; i++) { if (rolesWithNameFromContent.indexOf(roles[i]) !== -1) { passed = RPTUtil.hasInnerContentHidden(ruleContext); break; } } } // Determine if this is referenced by a combobox. If so, the label belongs to the combobox let id = ruleContext.getAttribute("id"); if (id && id.trim().length > 0) { if (ruleContext.ownerDocument.querySelector(`*[aria-controls='${id}'][role='combobox']`)) { return null; } } if (passed) { return RulePass("Pass_0"); } else { return RulePotential("Potential_1"); } } } ] export { a11yRulesInput }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [bugbust](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsbugbust.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Bugbust extends PolicyStatement { public servicePrefix = 'bugbust'; /** * Statement provider for service [bugbust](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsbugbust.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to create a BugBust event * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * Dependent actions: * - iam:CreateServiceLinkedRole * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toCreateEvent() { return this.to('CreateEvent'); } /** * Grants permission to evaluate checked-in profiling groups * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toEvaluateProfilingGroups() { return this.to('EvaluateProfilingGroups'); } /** * Grants permission to view customer details about an event * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toGetEvent() { return this.to('GetEvent'); } /** * Grants permission to view the status of a BugBust player's attempt to join a BugBust event * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toGetJoinEventStatus() { return this.to('GetJoinEventStatus'); } /** * Grants permission to join an event * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toJoinEvent() { return this.to('JoinEvent'); } /** * Grants permission to view the bugs that were imported into an event for players to work on * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * Dependent actions: * - codeguru-reviewer:DescribeCodeReview * - codeguru-reviewer:ListRecommendations * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toListBugs() { return this.to('ListBugs'); } /** * Grants permission to view the participants of an event * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toListEventParticipants() { return this.to('ListEventParticipants'); } /** * Grants permission to view the scores of an event's players * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toListEventScores() { return this.to('ListEventScores'); } /** * Grants permission to List BugBust events * * Access Level: List * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toListEvents() { return this.to('ListEvents'); } /** * Grants permission to view the profiling groups that were imported into an event for players to work on * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toListProfilingGroups() { return this.to('ListProfilingGroups'); } /** * Grants permission to view the pull requests used by players to submit fixes to their claimed bugs in an event * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toListPullRequests() { return this.to('ListPullRequests'); } /** * Grants permission to lists tag for a Bugbust resource * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to tag a Bugbust resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to untag a Bugbust resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update a BugBust event * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * Dependent actions: * - codeguru-profiler:DescribeProfilingGroup * - codeguru-profiler:ListProfilingGroups * - codeguru-reviewer:DescribeCodeReview * - codeguru-reviewer:ListCodeReviews * - codeguru-reviewer:ListRecommendations * - codeguru-reviewer:TagResource * - codeguru-reviewer:UnTagResource * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toUpdateEvent() { return this.to('UpdateEvent'); } /** * Grants permission to update a work item as claimed or unclaimed (bug or profiling group) * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toUpdateWorkItem() { return this.to('UpdateWorkItem'); } /** * Grants permission to update an event's work item (bug or profiling group) * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/auth-and-access-control-permissions-reference.html */ public toUpdateWorkItemAdmin() { return this.to('UpdateWorkItemAdmin'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateEvent", "EvaluateProfilingGroups", "JoinEvent", "UpdateEvent", "UpdateWorkItem", "UpdateWorkItemAdmin" ], "Read": [ "GetEvent", "GetJoinEventStatus", "ListBugs", "ListEventParticipants", "ListEventScores", "ListProfilingGroups", "ListPullRequests", "ListTagsForResource" ], "List": [ "ListEvents" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type codereview to the statement * * https://docs.aws.amazon.com/codeguru/latest/profiler-ug/API_CodeReview.html * * @param resourceId - Identifier for the resourceId. * @param codeReviewId - Identifier for the codeReviewId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onCodereview(resourceId: string, codeReviewId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:codeguru-reviewer:${Region}:${Account}:association:${ResourceId}:codereview:${CodeReviewId}'; arn = arn.replace('${ResourceId}', resourceId); arn = arn.replace('${CodeReviewId}', codeReviewId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type ProfilingGroup to the statement * * https://docs.aws.amazon.com/codeguru/latest/profiler-api/working-with-profiling-groups.html * * @param profilingGroupName - Identifier for the profilingGroupName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onProfilingGroup(profilingGroupName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:codeguru-profiler:${Region}:${Account}:profilingGroup/${ProfilingGroupName}'; arn = arn.replace('${ProfilingGroupName}', profilingGroupName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type Event to the statement * * https://docs.aws.amazon.com/codeguru/latest/bugbust-ug/event-managing.html * * @param eventId - Identifier for the eventId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onEvent(eventId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:bugbust:${Region}:${Account}:events/${EventId}'; arn = arn.replace('${EventId}', eventId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
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 Resource class. * @constructor * An Azure resource. * * @member {string} [id] The resource ID. * @member {string} [name] The name of the resource. * @member {string} [type] The type of the resource. * @member {string} location The location of the resource. This cannot be * changed after the resource is created. * @member {object} [tags] The tags of the resource. */ export interface Resource extends BaseResource { readonly id?: string; readonly name?: string; readonly type?: string; location: string; tags?: { [propertyName: string]: string }; } /** * @class * Initializes a new instance of the Workspace class. * @constructor * An object that represents a machine learning team account workspace. * * @member {string} [description] The description of this workspace. * @member {string} [accountId] The immutable id of the team account which * contains this workspace. * @member {string} [workspaceId] The immutable id of this workspace. * @member {string} friendlyName The friendly name for this workspace. This * will be the workspace name in the arm id when the workspace object gets * created * @member {date} [creationDate] The creation date of the machine learning * workspace in ISO8601 format. * @member {string} [provisioningState] The current deployment state of team * account workspace resource. The provisioningState is to indicate states for * resource provisioning. Possible values include: 'Creating', 'Succeeded', * 'Updating', 'Deleting', 'Failed' */ export interface Workspace extends Resource { description?: string; readonly accountId?: string; readonly workspaceId?: string; friendlyName: string; readonly creationDate?: Date; readonly provisioningState?: string; } /** * @class * Initializes a new instance of the WorkspaceUpdateParameters class. * @constructor * The parameters for updating a machine learning team account workspace. * * @member {object} [tags] The resource tags for the machine learning team * account workspace. * @member {string} [friendlyName] Friendly name of this workspace. * @member {string} [description] Description for this workspace. */ export interface WorkspaceUpdateParameters { tags?: { [propertyName: string]: string }; friendlyName?: string; description?: string; } /** * @class * Initializes a new instance of the Project class. * @constructor * An object that represents a machine learning project. * * @member {string} [description] The description of this project. * @member {string} [accountId] The immutable id of the team account which * contains this project. * @member {string} [workspaceId] The immutable id of the workspace which * contains this project. * @member {string} [projectId] The immutable id of this project. * @member {string} [gitrepo] The reference to git repo for this project. * @member {string} friendlyName The friendly name for this project. * @member {date} [creationDate] The creation date of the project in ISO8601 * format. * @member {string} [provisioningState] The current deployment state of project * resource. The provisioningState is to indicate states for resource * provisioning. Possible values include: 'Creating', 'Succeeded', 'Updating', * 'Deleting', 'Failed' */ export interface Project extends Resource { description?: string; readonly accountId?: string; readonly workspaceId?: string; readonly projectId?: string; gitrepo?: string; friendlyName: string; readonly creationDate?: Date; readonly provisioningState?: string; } /** * @class * Initializes a new instance of the ProjectUpdateParameters class. * @constructor * The parameters for updating a machine learning project. * * @member {object} [tags] The resource tags for the machine learning project. * @member {string} [friendlyName] The friendly name for this project. * @member {string} [description] The description of this project. * @member {string} [gitrepo] The reference to git repo for this project. */ export interface ProjectUpdateParameters { tags?: { [propertyName: string]: string }; friendlyName?: string; description?: string; gitrepo?: string; } /** * @class * Initializes a new instance of the ErrorResponse class. * @constructor * The error response send when an operation fails. * * @member {string} code error code * @member {string} message error message */ export interface ErrorResponse { code: string; message: string; } /** * @class * Initializes a new instance of the StorageAccountProperties class. * @constructor * The properties of a storage account for a machine learning team account. * * @member {string} storageAccountId The fully qualified arm Id of the storage * account. * @member {string} accessKey The access key to the storage account. */ export interface StorageAccountProperties { storageAccountId: string; accessKey: string; } /** * @class * Initializes a new instance of the Account class. * @constructor * An object that represents a machine learning team account. * * @member {string} vsoAccountId The fully qualified arm id of the vso account * to be used for this team account. * @member {string} [accountId] The immutable id associated with this team * account. * @member {string} [description] The description of this workspace. * @member {string} [friendlyName] The friendly name for this workspace. This * will be the workspace name in the arm id when the workspace object gets * created * @member {string} keyVaultId The fully qualified arm id of the user key * vault. * @member {string} [seats] The no of users/seats who can access this team * account. This property defines the charge on the team account. * @member {string} [discoveryUri] The uri for this machine learning team * account. * @member {date} [creationDate] The creation date of the machine learning team * account in ISO8601 format. * @member {object} storageAccount The properties of the storage account for * the machine learning team account. * @member {string} [storageAccount.storageAccountId] The fully qualified arm * Id of the storage account. * @member {string} [storageAccount.accessKey] The access key to the storage * account. * @member {string} [provisioningState] The current deployment state of team * account resource. The provisioningState is to indicate states for resource * provisioning. Possible values include: 'Creating', 'Succeeded', 'Updating', * 'Deleting', 'Failed' */ export interface Account extends Resource { vsoAccountId: string; readonly accountId?: string; description?: string; friendlyName?: string; keyVaultId: string; seats?: string; readonly discoveryUri?: string; readonly creationDate?: Date; storageAccount: StorageAccountProperties; readonly provisioningState?: string; } /** * @class * Initializes a new instance of the AccountUpdateParameters class. * @constructor * The parameters for updating a machine learning team account. * * @member {object} [tags] The resource tags for the machine learning team * account. * @member {string} [description] The description of this workspace. * @member {string} [friendlyName] The friendly name for this workspace. This * will be the workspace name in the arm id when the workspace object gets * created * @member {string} [seats] The no of users/seats who can access this team * account. This property defines the charge on the team account. * @member {string} [storageAccountKey] The key for storage account associated * with this team account */ export interface AccountUpdateParameters { tags?: { [propertyName: string]: string }; description?: string; friendlyName?: string; seats?: string; storageAccountKey?: string; } /** * @class * Initializes a new instance of the OperationDisplay class. * @constructor * Display name of operation * * @member {string} [provider] The resource provider name: * Microsoft.MachineLearningExperimentation * @member {string} [resource] The resource on which the operation is * performed. * @member {string} [operation] The operation that users can perform. * @member {string} [description] The description for the operation. */ export interface OperationDisplay { provider?: string; resource?: string; operation?: string; description?: string; } /** * @class * Initializes a new instance of the Operation class. * @constructor * Azure Machine Learning team account REST API operation * * @member {string} [name] Operation name: {provider}/{resource}/{operation} * @member {object} [display] Display name of operation * @member {string} [display.provider] The resource provider name: * Microsoft.MachineLearningExperimentation * @member {string} [display.resource] The resource on which the operation is * performed. * @member {string} [display.operation] The operation that users can perform. * @member {string} [display.description] The description for the operation. */ export interface Operation { name?: string; display?: OperationDisplay; } /** * @class * Initializes a new instance of the OperationListResult class. * @constructor * An array of operations supported by the resource provider. * */ export interface OperationListResult extends Array<Operation> { } /** * @class * Initializes a new instance of the AccountListResult class. * @constructor * The result of a request to list machine learning team accounts. * * @member {string} [nextLink] The URI that can be used to request the next * list of machine learning team accounts. */ export interface AccountListResult extends Array<Account> { nextLink?: string; } /** * @class * Initializes a new instance of the WorkspaceListResult class. * @constructor * The result of a request to list machine learning team account workspaces. * * @member {string} [nextLink] The URI that can be used to request the next * list of machine learning workspaces. */ export interface WorkspaceListResult extends Array<Workspace> { nextLink?: string; } /** * @class * Initializes a new instance of the ProjectListResult class. * @constructor * The result of a request to list projects. * * @member {string} [nextLink] The URI that can be used to request the next * list of projects. */ export interface ProjectListResult extends Array<Project> { nextLink?: string; }
the_stack
import { ILogPayload, Logger, LoggerOutputAreaModel, LogLevel } from '@jupyterlab/logconsole'; import { RenderMimeRegistry } from '@jupyterlab/rendermime'; import { ISignal, Signal } from '@lumino/signaling'; class SignalLogger<SENDER, ARGS> { constructor(signal: ISignal<SENDER, ARGS>) { signal.connect(this.slot, this); } slot(sender: SENDER, args: ARGS) { this.args.push(args); } dispose() { Signal.disconnectAll(this); } args: ARGS[] = []; } describe('LoggerOutputAreaModel', () => { let model: LoggerOutputAreaModel; beforeEach(() => { model = new LoggerOutputAreaModel({ maxLength: 10 }); }); afterEach(() => { model.dispose(); }); describe('#constructor()', () => { it('should create an LoggerOutputAreaModel', () => { expect(model).toBeInstanceOf(LoggerOutputAreaModel); }); it('should set the max length', async () => { const model = new LoggerOutputAreaModel({ maxLength: 10 }); expect(model.maxLength).toEqual(10); model.dispose(); }); }); describe('#maxLength', () => { it('should set the maximum number of messages in the first-in first-out queue', () => { for (let i = 0; i < 12; i++) { model.add({ output_type: 'display_data', data: { 'text/plain': i.toString() }, timestamp: Date.now(), level: 'info' }); } expect(model.length).toEqual(10); expect(model.get(0).data['text/plain']).toEqual('2'); }); it('setting maxLength should immediately apply and trim the message list', () => { for (let i = 0; i < 12; i++) { model.add({ output_type: 'display_data', data: { 'text/plain': i.toString() }, timestamp: Date.now(), level: 'info' }); } expect(model.maxLength).toEqual(10); expect(model.length).toEqual(10); model.maxLength = 5; expect(model.maxLength).toEqual(5); expect(model.length).toEqual(5); expect(model.get(0).data['text/plain']).toEqual('7'); }); }); }); describe('Logger', () => { let logger: Logger; beforeEach(() => { logger = new Logger({ source: 'test source', maxLength: 10 }); }); afterEach(() => { logger.dispose(); }); describe('#constructor()', () => { it('should create a Logger with initial properties', () => { expect(logger).toBeInstanceOf(Logger); expect(logger.source).toEqual('test source'); expect(logger.maxLength).toEqual(10); }); }); describe('#maxLength', () => { it('should set the maximum number of messages in the first-in first-out queue', () => { for (let i = 0; i < 12; i++) { logger.log({ type: 'text', data: i.toString(), level: 'critical' }); } expect(logger.length).toEqual(10); expect(logger.outputAreaModel.get(0).data['text/plain']).toEqual('2'); }); it('setting maxLength should immediately apply and trim the message list', () => { for (let i = 0; i < 12; i++) { logger.log({ type: 'text', data: i.toString(), level: 'critical' }); } const model = logger.outputAreaModel; expect(logger.maxLength).toEqual(10); expect(logger.length).toEqual(10); logger.maxLength = 5; expect(logger.maxLength).toEqual(5); expect(logger.length).toEqual(5); expect(model.get(0).data['text/plain']).toEqual('7'); }); }); describe('#level', () => { const levels: LogLevel[] = [ 'critical', 'error', 'warning', 'info', 'debug' ]; it('should default to "warning"', () => { expect(logger.level).toEqual('warning'); }); it.each(levels)('filters for messages: %s', (level: LogLevel) => { logger.level = level; const messages: ILogPayload[] = levels.map(level => ({ type: 'text', data: level, level })); messages.forEach(m => logger.log({ ...m })); const logged: string[] = []; for (let i = 0; i < logger.length; i++) { const msg = logger.outputAreaModel.get(i); logged.push(msg.level); } const shouldInclude = levels.slice(0, levels.indexOf(level) + 1); const shouldExclude = levels.slice(levels.indexOf(level) + 1); shouldInclude.forEach(x => { expect(logged).toContain(x); }); shouldExclude.forEach(x => { expect(logged).not.toContain(x); }); }); it('logs a "metadata" level text message if changed', () => { logger.level = 'info'; const msg = logger.outputAreaModel.get(0); expect(msg.level).toBe('metadata'); expect(msg.data['text/plain']).toContain('info'); }); it('emits a stateChanged signal when changing', () => { const s = new SignalLogger(logger.stateChanged); logger.level = 'info'; expect(s.args).toEqual([ { name: 'level', oldValue: 'warning', newValue: 'info' } ]); s.dispose(); }); it('setting to its current value has no effect', () => { const s = new SignalLogger(logger.stateChanged); logger.level = logger.level; // eslint-disable-line expect(s.args.length).toBe(0); expect(logger.length).toBe(0); s.dispose(); }); }); describe('#length', () => { it('records how many messages are stored', () => { logger.log({ type: 'text', data: 'message 1', level: 'warning' }); logger.log({ type: 'text', data: 'message 2', level: 'warning' }); expect(logger.length).toBe(2); logger.clear(); expect(logger.length).toBe(0); }); it('may be less than the messages logged if messages were combined', () => { logger.log({ type: 'output', data: { output_type: 'stream', name: 'stdout', text: 'message 1' }, level: 'critical' }); logger.log({ type: 'output', data: { output_type: 'stream', name: 'stdout', text: 'message 2' }, level: 'critical' }); expect(logger.length).toBe(1); }); }); describe('#rendermime', () => { it('initially is null', () => { expect(logger.rendermime).toBe(null); }); it('sets the rendermime attribute', () => { const value = new RenderMimeRegistry(); logger.rendermime = value; expect(logger.rendermime).toBe(value); }); it('emits a stateChanged signal when changed', () => { const oldValue = (logger.rendermime = new RenderMimeRegistry()); const newValue = oldValue.clone(); const s = new SignalLogger(logger.stateChanged); logger.rendermime = newValue; expect(s.args).toEqual([{ name: 'rendermime', oldValue, newValue }]); s.dispose(); }); it('setting to current value has no effect', () => { logger.rendermime = new RenderMimeRegistry(); const s = new SignalLogger(logger.stateChanged); logger.rendermime = logger.rendermime; // eslint-disable-line expect(s.args).toEqual([]); s.dispose(); }); }); describe('#version', () => { it('starts at zero', () => { expect(logger.version).toBe(0); }); it('increments every time a message is logged', () => { logger.log({ type: 'text', data: 'message 1', level: 'warning' }); logger.log({ type: 'text', data: 'message 2', level: 'warning' }); expect(logger.version).toBe(2); }); it('increments even if messages are combined', () => { logger.log({ type: 'output', data: { output_type: 'stream', name: 'stdout', text: 'message 1' }, level: 'critical' }); logger.log({ type: 'output', data: { output_type: 'stream', name: 'stdout', text: 'message 2' }, level: 'critical' }); expect(logger.length).toBe(1); expect(logger.version).toBe(2); }); it('does not increment on clearing messages', () => { logger.log({ type: 'text', data: 'message 1', level: 'warning' }); logger.log({ type: 'text', data: 'message 2', level: 'warning' }); expect(logger.version).toBe(2); logger.clear(); expect(logger.length).toBe(0); expect(logger.version).toBe(2); }); }); describe('#log()', () => { it('logs text messages', () => { logger.log({ type: 'text', data: 'message', level: 'warning' }); expect(logger.length).toBe(1); }); it('logs html messages', () => { logger.log({ type: 'html', data: 'message', level: 'warning' }); expect(logger.length).toBe(1); }); it('logs output stream messages', () => { logger.log({ type: 'output', data: { output_type: 'stream', name: 'stdout', text: 'message' }, level: 'warning' }); expect(logger.length).toBe(1); }); it('logs display_data messages', () => { logger.log({ type: 'output', data: { output_type: 'display_data', data: { 'text/plain': 'message' } }, level: 'warning' }); expect(logger.length).toBe(1); }); it('logs execute_result messages', () => { logger.log({ type: 'output', data: { output_type: 'execute_result', data: { 'text/plain': 'message', execution_count: 5 } }, level: 'warning' }); expect(logger.length).toBe(1); }); it('logs error messages', () => { logger.log({ type: 'output', data: { output_type: 'error', ename: 'Error', evalue: 'Error', traceback: ['level 1', 'level 2'] }, level: 'warning' }); expect(logger.length).toBe(1); }); it('emits an "append" content changed signal', () => { const s = new SignalLogger(logger.contentChanged); logger.log({ type: 'text', data: 'message 1', level: 'warning' }); expect(s.args).toEqual(['append']); s.dispose(); }); it('emits an "append" content changed signal and log outputs', () => { const s = new SignalLogger(logger.contentChanged); logger.log({ type: 'output', data: { output_type: 'stream', name: 'stdout', text: 'message 1' }, level: 'critical' }); logger.log({ type: 'output', data: { output_type: 'stream', name: 'stdout', text: 'message 2' }, level: 'critical' }); expect(s.args).toEqual(['append', 'append']); expect(logger.length).toBe(1); s.dispose(); }); it('adds a timestamp to the message', () => { const before = Date.now(); logger.log({ type: 'text', data: 'message 1', level: 'warning' }); const after = Date.now(); const msgTime = logger.outputAreaModel.get(0).timestamp.getTime(); expect(msgTime).toBeGreaterThanOrEqual(before); expect(msgTime).toBeLessThanOrEqual(after); }); }); describe('#clear()', () => { it('clears messages', () => { logger.log({ type: 'text', data: 'message 1', level: 'warning' }); logger.log({ type: 'text', data: 'message 2', level: 'warning' }); expect(logger.length).toBe(2); logger.clear(); expect(logger.length).toBe(0); }); it('emits a "clear" content changed signal', () => { const s = new SignalLogger(logger.contentChanged); logger.log({ type: 'text', data: 'message 1', level: 'warning' }); logger.clear(); expect(s.args).toEqual(['append', 'clear']); s.dispose(); }); }); describe('#checkpoint()', () => { it('adds a metadata message to the message list', () => { logger.checkpoint(); expect(logger.outputAreaModel.get(0).level).toBe('metadata'); }); it('emits an "append" content changed signal', () => { const s = new SignalLogger(logger.contentChanged); logger.checkpoint(); expect(s.args).toEqual(['append']); s.dispose(); }); }); });
the_stack
'use strict'; import { localize } from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import { TPromise } from 'vs/base/common/winjs.base'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { Action } from 'vs/base/common/actions'; import { isPromiseCanceledError, create as createError } from 'vs/base/common/errors'; import * as mime from 'vs/base/common/mime'; import * as paths from 'vs/base/common/paths'; import { EventEmitter } from 'vs/base/common/eventEmitter'; import { EditorInput } from 'vs/workbench/common/editor'; import { IFileStatus, IGitServiceError, GitErrorCodes, Status, StatusType, AutoFetcherState, IGitConfiguration, IAutoFetcher, ServiceEvents, ServiceState, IModel, IGitOperation, IRawGitService, IGitService, IGitCredentialScope, RawServiceState, ServiceOperations, IPushOptions, ICommit, IRawStatus } from 'vs/workbench/parts/git/common/git'; import { Model } from 'vs/workbench/parts/git/common/gitModel'; import { NativeGitIndexStringEditorInput, GitIndexDiffEditorInput, GitWorkingTreeDiffEditorInput, GitDiffEditorInput } from 'vs/workbench/parts/git/browser/gitEditorInputs'; import { GitOperation } from 'vs/workbench/parts/git/browser/gitOperations'; import { EventType as WorkbenchFileEventType, TextFileChangeEvent } from 'vs/workbench/parts/files/common/files'; import { IFileService, EventType as FileEventType, FileChangesEvent, FileChangeType } from 'vs/platform/files/common/files'; import { ThrottledDelayer, PeriodThrottledDelayer } from 'vs/base/common/async'; import severity from 'vs/base/common/severity'; import { IOutputService } from 'vs/workbench/parts/output/common/output'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IEventService } from 'vs/platform/event/common/event'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IMessageService, CloseAction } from 'vs/platform/message/common/message'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import URI from 'vs/base/common/uri'; import * as semver from 'semver'; import { shell } from 'electron'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import Event from 'vs/base/common/event'; import { domEvent } from 'vs/base/browser/event'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; function toReadablePath(path: string): string { if (!platform.isWindows) { return path; } return path.replace(/\//g, '\\'); } class EditorInputCache { private gitService: GitService; private fileService: IFileService; private eventService: IEventService; private instantiationService: IInstantiationService; private editorService: IWorkbenchEditorService; private editorGroupService: IEditorGroupService; private contextService: IWorkspaceContextService; private cache: { [key: string]: TPromise<EditorInput> }; private toDispose: IDisposable[]; constructor(gitService: GitService, @IInstantiationService instantiationService: IInstantiationService, @IFileService fileService: IFileService, @IEventService eventService: IEventService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IEditorGroupService editorGroupService: IEditorGroupService, @IWorkspaceContextService contextService: IWorkspaceContextService ) { this.instantiationService = instantiationService; this.fileService = fileService; this.eventService = eventService; this.editorService = editorService; this.editorGroupService = editorGroupService; this.contextService = contextService; this.gitService = gitService; this.cache = {}; this.toDispose = []; this.toDispose.push(this.gitService.getModel().addListener2('fileStatus:dispose', (fileStatus: IFileStatus) => this.onFileStatusDispose(fileStatus))); } getInput(status: IFileStatus): TPromise<EditorInput> { var result = this.cache[status.getId()]; if (result) { return result; } result = this.createInput(status); this.cache[status.getId()] = result; return result; } private createInput(status: IFileStatus): TPromise<EditorInput> { return TPromise.join<EditorInput>([this.createLeftInput(status), this.createRightInput(status)]).then((result) => { var leftInput = result[0]; var rightInput = result[1]; var fileSegment: string; var folderSegment: string; if (status.getStatus() === Status.INDEX_RENAMED) { let pathComponents = status.getRename().split('/'); fileSegment = pathComponents[pathComponents.length - 1]; folderSegment = toReadablePath(pathComponents.slice(0, pathComponents.length - 1).join('/')); } else { let pathComponents = status.getPathComponents(); fileSegment = pathComponents[pathComponents.length - 1]; folderSegment = toReadablePath(pathComponents.slice(0, pathComponents.length - 1).join('/')); } if (!leftInput) { if (!rightInput) { var error = new Error(localize('cantOpen', "Can't open this git resource.")); (<IGitServiceError>error).gitErrorCode = GitErrorCodes.CantOpenResource; return TPromise.wrapError(error); } return TPromise.as(rightInput); } switch (status.getStatus()) { case Status.INDEX_MODIFIED: return TPromise.as(new GitIndexDiffEditorInput(localize('gitIndexChanges', "{0} (index) ↔ {1}", fileSegment, fileSegment), localize('gitIndexChangesDesc', "{0} - Changes on index", folderSegment), leftInput, rightInput, status)); case Status.INDEX_RENAMED: return TPromise.as(new GitIndexDiffEditorInput(localize('gitIndexChangesRenamed', "{0} ← {1}", status.getRename(), status.getPath()), localize('gitIndexChangesRenamedDesc', "{0} - Renamed - Changes on index", folderSegment), leftInput, rightInput, status)); case Status.MODIFIED: return TPromise.as(new GitWorkingTreeDiffEditorInput(localize('workingTreeChanges', "{0} (HEAD) ↔ {1}", fileSegment, fileSegment), localize('workingTreeChangesDesc', "{0} - Changes on working tree", folderSegment), leftInput, rightInput, status)); default: return TPromise.as(new GitDiffEditorInput(localize('gitMergeChanges', "{0} (merge) ↔ {1}", fileSegment, fileSegment), localize('gitMergeChangesDesc', "{0} - Merge changes", folderSegment), leftInput, rightInput, status)); } }).then((editorInput: EditorInput) => { editorInput.addOneTimeDisposableListener('dispose', () => { delete this.cache[status.getId()]; }); return editorInput; }, (errs) => { return TPromise.wrapError(Array.isArray(errs) ? errs[0] || errs[1] : errs); }); } private createLeftInput(status: IFileStatus): TPromise<EditorInput> { var path = status.getPath(); var model = this.gitService.getModel(); switch (status.getStatus()) { case Status.INDEX_MODIFIED: case Status.INDEX_RENAMED: return this.gitService.show(path, status, 'HEAD', status.getMimetype()); case Status.MODIFIED: var indexStatus = model.getStatus().find(path, StatusType.INDEX); if (indexStatus && indexStatus.getStatus() === Status.INDEX_RENAMED) { return this.gitService.show(indexStatus.getRename(), status, '~', status.getMimetype()); } if (indexStatus) { return this.gitService.show(path, status, '~', status.getMimetype()); } return this.gitService.show(path, status, 'HEAD', status.getMimetype()); default: return TPromise.as(null); } } private createRightInput(status: IFileStatus): TPromise<EditorInput> { const model = this.gitService.getModel(); const path = status.getPath(); let resource = URI.file(paths.join(model.getRepositoryRoot(), path)); switch (status.getStatus()) { case Status.INDEX_MODIFIED: case Status.INDEX_ADDED: case Status.INDEX_COPIED: return this.gitService.show(path, status, '~', status.getMimetype()); case Status.INDEX_RENAMED: return this.gitService.show(status.getRename(), status, '~', status.getMimetype()); case Status.INDEX_DELETED: case Status.DELETED: return this.gitService.show(path, status, 'HEAD', status.getMimetype()); case Status.MODIFIED: case Status.UNTRACKED: case Status.IGNORED: var indexStatus = model.getStatus().find(path, StatusType.INDEX); if (indexStatus && indexStatus.getStatus() === Status.INDEX_RENAMED) { resource = URI.file(paths.join(model.getRepositoryRoot(), indexStatus.getRename())); } return this.editorService.createInput({ resource }); case Status.BOTH_MODIFIED: return this.editorService.createInput({ resource }); default: return TPromise.as(null); } } private onFileStatusDispose(fileStatus: IFileStatus): void { var id = fileStatus.getId(); var editorInputPromise = this.cache[id]; if (editorInputPromise) { editorInputPromise.done((editorInput) => { this.eventuallyDispose(editorInput); }); } } /** * If the disposed status is the same as this input's status, we must try to dispose the input. * But we should not do it while the input is still open. This method will eventually call dispose * when the editor input goes out of the visible editors. */ private eventuallyDispose(editorInput: EditorInput): void { if (!this.maybeDispose(editorInput)) { var listener = this.editorGroupService.onEditorsChanged(() => { if (this.maybeDispose(editorInput)) { listener.dispose(); } }); } } private maybeDispose(editorInput: EditorInput): boolean { if (!editorInput.isDirty() && !this.editorService.getVisibleEditors().some((editor) => editor.input && editor.input.matches(editorInput))) { editorInput.dispose(); return true; } return false; } dispose(): void { Object.keys(this.cache).forEach(key => { this.cache[key].done((editorInput) => { editorInput.dispose(); }); delete this.cache[key]; }); this.toDispose = dispose(this.toDispose); } } export class AutoFetcher implements IAutoFetcher, IDisposable { private static MIN_TIMEOUT = 2 * 60 * 1000; // every two minutes private static MAX_TIMEOUT = 5 * 60 * 1000; // every five minutes private _state: AutoFetcherState; private gitService: GitService; private eventService: IEventService; private messageService: IMessageService; private configurationService: IConfigurationService; private instantiationService: IInstantiationService; private currentRequest: TPromise<void>; private timeout: number; private toDispose: IDisposable[]; private gitServiceStateDisposable: IDisposable; constructor(gitService: GitService, // gitService passed as argument, not by injection @IEventService eventService: IEventService, @IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IConfigurationService configurationService: IConfigurationService, @IInstantiationService instantiationService: IInstantiationService ) { this._state = AutoFetcherState.Disabled; this.gitService = gitService; this.eventService = eventService; this.messageService = messageService; this.configurationService = configurationService; this.instantiationService = instantiationService; this.currentRequest = null; this.timeout = AutoFetcher.MIN_TIMEOUT; this.toDispose = []; this.toDispose.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfiguration(e.config.git))); this.onConfiguration(configurationService.getConfiguration<IGitConfiguration>('git')); } get state(): AutoFetcherState { return this._state; } private onConfiguration(config: IGitConfiguration): void { if (config.autofetch === false) { this.disable(); } else { this.enable(); } } enable(): void { if (this._state !== AutoFetcherState.Disabled) { return; } this.gitServiceStateDisposable = this.gitService.addListener2(ServiceEvents.STATE_CHANGED, (e) => this.onGitServiceStateChange(e)); this._state = AutoFetcherState.Active; this.onGitServiceStateChange(this.gitService.getState()); } disable(): void { if (this.gitServiceStateDisposable) { this.gitServiceStateDisposable.dispose(); this.gitServiceStateDisposable = null; } this.deactivate(); this._state = AutoFetcherState.Disabled; } private onGitServiceStateChange(state: ServiceState): void { if (state === ServiceState.OK) { this.activate(); } else { this.deactivate(); } } activate(): void { if (this.currentRequest) { this.currentRequest.cancel(); } this._state = AutoFetcherState.Active; this.loop(); } deactivate(): void { if (!this.currentRequest) { return; } this._state = AutoFetcherState.Inactive; this.currentRequest.cancel(); this.currentRequest = null; } private loop(): void { this._state = AutoFetcherState.Fetching; const remotes = this.gitService.getModel().getRemotes(); if (remotes.length === 0) { this.timeout = AutoFetcher.MIN_TIMEOUT; this.currentRequest = TPromise.as(null); } else { this.currentRequest = this.gitService.fetch().then(() => { this.timeout = AutoFetcher.MIN_TIMEOUT; }, (err) => { if (isPromiseCanceledError(err)) { return TPromise.wrapError(err); } else if (err.gitErrorCode === GitErrorCodes.AuthenticationFailed) { return TPromise.wrapError(err); } else { this.timeout = Math.min(Math.round(this.timeout * 1.2), AutoFetcher.MAX_TIMEOUT); // backoff } }); } this.currentRequest.then(() => { this._state = AutoFetcherState.Active; this.currentRequest = TPromise.timeout(this.timeout); return this.currentRequest; }).then(() => this.loop(), (err) => this.deactivate()); } dispose(): void { this.disable(); } } interface IGitCredentialRequest { guid: string; scope: IGitCredentialScope; } const IgnoreOldGitStorageKey = 'settings.workspace.git.ignoreOld'; export class GitService extends EventEmitter implements IGitService { _serviceBrand: any; private eventService: IEventService; private contextService: IWorkspaceContextService; private messageService: IMessageService; private instantiationService: IInstantiationService; private editorService: IWorkbenchEditorService; private lifecycleService: ILifecycleService; private outputService: IOutputService; protected raw: IRawGitService; private state: ServiceState; private operations: IGitOperation[]; private model: IModel; private inputCache: EditorInputCache; private toDispose: IDisposable[]; private needsRefresh: boolean; private statusDelayer: ThrottledDelayer<IModel>; private reactiveStatusDelayer: PeriodThrottledDelayer<IModel>; private autoFetcher: AutoFetcher; private isStatusPending = false; private isFocused = true; private _allowHugeRepositories: boolean; get allowHugeRepositories(): boolean { return this._allowHugeRepositories; } set allowHugeRepositories(value: boolean) { this._allowHugeRepositories = value; if (value && this.state === ServiceState.Huge) { this.transition(ServiceState.OK); } } get onOutput(): Event<string> { return this.raw.onOutput; } constructor( raw: IRawGitService, @IInstantiationService instantiationService: IInstantiationService, @IEventService eventService: IEventService, @IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IOutputService outputService: IOutputService, @IWorkspaceContextService contextService: IWorkspaceContextService, @ILifecycleService lifecycleService: ILifecycleService, @IStorageService storageService: IStorageService, @IConfigurationService private configurationService: IConfigurationService ) { super(); this.instantiationService = instantiationService; this.eventService = eventService; this.messageService = messageService; this.editorService = editorService; this.outputService = outputService; this.contextService = contextService; this.lifecycleService = lifecycleService; this.raw = raw; this.state = ServiceState.NotInitialized; this.operations = []; this.model = new Model(); this.toDispose = []; this.needsRefresh = false; this.statusDelayer = new ThrottledDelayer<IModel>(500); this.reactiveStatusDelayer = new PeriodThrottledDelayer<IModel>(500, 10000); this.autoFetcher = this.instantiationService.createInstance(AutoFetcher, this); this._allowHugeRepositories = false; this.registerListeners(); this.inputCache = this.instantiationService.createInstance(EditorInputCache, this); this.triggerAutoStatus(true); // trigger initial status if (!storageService.getBoolean(IgnoreOldGitStorageKey, StorageScope.GLOBAL, false)) { this.raw.serviceState().done(state => { if (state !== RawServiceState.OK) { return; } return this.raw.getVersion().then(version => { version = version || ''; version = version.replace(/^(\d+\.\d+\.\d+).*$/, '$1'); version = semver.valid(version); if (version && semver.satisfies(version, '<2.0.0')) { messageService.show(severity.Warning, { message: localize('updateGit', "You seem to have git {0} installed. Code works best with git >=2.0.0.", version), actions: [ CloseAction, new Action('neverShowAgain', localize('neverShowAgain', "Don't show again"), null, true, () => { storageService.store(IgnoreOldGitStorageKey, true, StorageScope.GLOBAL); return null; }), new Action('downloadLatest', localize('download', "Download"), '', true, () => { shell.openExternal('https://git-scm.com/'); return null; }) ] }); } }); }); } } private registerListeners(): void { this.toDispose.push(this.eventService.addListener2(FileEventType.FILE_CHANGES, (e) => this.onFileChanges(e))); this.toDispose.push(this.eventService.addListener2(WorkbenchFileEventType.FILE_SAVED, (e) => this.onTextFileChange(e))); this.toDispose.push(this.eventService.addListener2(WorkbenchFileEventType.FILE_REVERTED, (e) => this.onTextFileChange(e))); this.toDispose.push(this.configurationService.onDidUpdateConfiguration(() => { if (this._allowHugeRepositories) { return; } const config = this.configurationService.getConfiguration<IGitConfiguration>('git'); this._allowHugeRepositories = config.allowLargeRepositories; if (this._allowHugeRepositories) { this.triggerAutoStatus(); } })); this.lifecycleService.onShutdown(this.dispose, this); const focusEvent = domEvent(window, 'focus'); this.toDispose.push(focusEvent(() => { this.isFocused = true; if (this.isStatusPending) { this.triggerAutoStatus(); } })); const blurEvent = domEvent(window, 'blur'); this.toDispose.push(blurEvent(() => this.isFocused = false)); } private onTextFileChange(e: TextFileChangeEvent): void { var shouldTriggerStatus = paths.basename(e.resource.fsPath) === '.gitignore'; if (!shouldTriggerStatus) { return; } this.triggerAutoStatus(); } private onFileChanges(e: FileChangesEvent): void { var isIdle = this.isIdle(); var shouldTriggerStatus = e.changes.some(c => { var workspacePath = this.contextService.toWorkspaceRelativePath(c.resource); if (!workspacePath) { return false; // ignore out of workspace files } // for .gitindex, the service must be idle if ('.git/index' === workspacePath) { return isIdle; } // for anything other that .git* if (!/^\.git/.test(workspacePath)) { return true; } // added or deleted .git folder if (workspacePath === '.git') { return c.type === FileChangeType.ADDED || c.type === FileChangeType.DELETED; } return ['.git/index.lock', '.git/FETCH_HEAD', '.gitignore', '.gitmodules'].indexOf(workspacePath) === -1; }); if (!shouldTriggerStatus) { return; } this.triggerAutoStatus(); } private onGitServiceOperationEnd(e: { operation: IGitOperation; }): void { if (e.operation.id === ServiceOperations.COMMAND) { this.triggerAutoStatus(); } } getState(): ServiceState { return this.state; } getModel(): IModel { return this.model; } status(): TPromise<IModel> { return this.statusDelayer.trigger(() => this._status()); } private _status(): TPromise<IModel> { const config = this.configurationService.getConfiguration<IGitConfiguration>('git'); if (this._allowHugeRepositories || config.allowLargeRepositories) { return this.run(ServiceOperations.STATUS, () => this.raw.status()); } if (this.state === ServiceState.Huge) { return TPromise.as(this.model); } return this.raw.statusCount().then(count => { if (count > 5000 && !this._allowHugeRepositories) { this.transition(ServiceState.Huge); return TPromise.as(this.model); } return this.run(ServiceOperations.STATUS, () => this.raw.status()); }); } private triggerAutoStatus(force = false): void { this.isStatusPending = true; if (!this.isFocused && !force) { return; } this.isStatusPending = false; const config = this.configurationService.getConfiguration<IGitConfiguration>('git'); if (!config.autorefresh) { return; } this.reactiveStatusDelayer.trigger(() => this.status()).done(null, e => { if (isPromiseCanceledError(e)) { return; } this.messageService.show(severity.Error, e); }); } init(): TPromise<IModel> { return this.run(ServiceOperations.INIT, () => this.raw.init()); } add(files?: IFileStatus[]): TPromise<IModel> { return this.run(ServiceOperations.ADD, () => this.raw.add(GitService.toPaths(files))); } stage(filePath: string, content: string): TPromise<IModel> { return this.run(ServiceOperations.STAGE, () => this.raw.stage(filePath, content)); } branch(name: string, checkout: boolean = false): TPromise<IModel> { return this.run(ServiceOperations.BRANCH, () => this.raw.branch(name, checkout)); } checkout(treeish: string = '', files: IFileStatus[] = null): TPromise<IModel> { return this.run(ServiceOperations.CHECKOUT, () => this.raw.checkout(treeish, GitService.toPaths(files))); } clean(files: IFileStatus[]): TPromise<IModel> { return this.run(ServiceOperations.CLEAN, () => this.raw.clean(files.map((s) => s.getPath()))); } undo(): TPromise<IModel> { return this.run(ServiceOperations.UNDO, () => this.raw.undo()); } reset(treeish: string, hard?: boolean): TPromise<IModel> { return this.run(ServiceOperations.RESET, () => this.raw.reset(treeish, hard)); } revertFiles(treeish: string, files?: IFileStatus[]): TPromise<IModel> { return this.run(ServiceOperations.REVERT, () => this.raw.revertFiles(treeish, (files || []).map((s) => s.getPath()))); } fetch(): TPromise<IModel> { return this.run(ServiceOperations.BACKGROUND_FETCH, () => this.raw.fetch()); } pull(rebase?: boolean): TPromise<IModel> { return this.run(ServiceOperations.PULL, () => this.raw.pull(rebase)); } push(remote?: string, name?: string, options?: IPushOptions): TPromise<IModel> { return this.run(ServiceOperations.PUSH, () => this.raw.push(remote, name, options)); } sync(rebase?: boolean): TPromise<IModel> { const head = this.model.getHEAD(); const isAhead = head && head.upstream && !!head.ahead; if (!isAhead) { return this.run(ServiceOperations.SYNC, () => this.raw.pull(rebase)); } else { return this.run(ServiceOperations.SYNC, () => this.raw.sync()); } } commit(message: string, amend: boolean = false, stage: boolean = false, signoff: boolean = false): TPromise<IModel> { return this.run(ServiceOperations.COMMIT, () => this.raw.commit(message, amend, stage, signoff)); } getCommitTemplate(): TPromise<string> { return this.raw.getCommitTemplate(); } getCommit(ref: string): TPromise<ICommit> { return this.raw.getCommit(ref); } detectMimetypes(path: string, treeish: string = '~'): TPromise<string[]> { return this.raw.detectMimetypes(path, treeish); } private run(operationId: string, fn: () => TPromise<IRawStatus>): TPromise<IModel> { return this.raw.serviceState().then(state => { if (state === RawServiceState.GitNotFound) { this.transition(ServiceState.NoGit); return TPromise.as(null); } else if (state === RawServiceState.Disabled) { this.transition(ServiceState.Disabled); return TPromise.as(null); } else { return this._run(operationId, fn); } }); } private _run(operationId: string, fn: () => TPromise<IRawStatus>): TPromise<IModel> { var operation = new GitOperation(operationId, fn); this.operations.push(operation); this.emit(ServiceEvents.OPERATION_START, operation); this.emit(ServiceEvents.OPERATION, operation); var onDone = (error: any = null) => { var index = this.operations.indexOf(operation); if (index > -1) { this.operations.splice(index, 1); } var e = { operation: operation, error: error }; this.emit(ServiceEvents.OPERATION_END, e); this.onGitServiceOperationEnd(e); this.emit(ServiceEvents.OPERATION, operation); }; return operation.run().then((status: IRawStatus) => { this.model.update(status); onDone(); if (status) { this.transition(status.state === null || status.state === undefined ? ServiceState.OK : status.state); } else { this.transition(ServiceState.NotARepo); } return this.model; }, (e) => { onDone(e); if (isPromiseCanceledError(e)) { return TPromise.wrapError(e); } var gitErrorCode: string = e.gitErrorCode || null; if (gitErrorCode === GitErrorCodes.NotAtRepositoryRoot) { this.transition(ServiceState.NotAtRepoRoot); return TPromise.as(this.model); } this.emit(ServiceEvents.ERROR, e); this.transition(ServiceState.OK); if (gitErrorCode === GitErrorCodes.NoUserNameConfigured || gitErrorCode === GitErrorCodes.NoUserEmailConfigured) { this.messageService.show(severity.Warning, localize('configureUsernameEmail', "Please configure your git user name and e-mail.")); return TPromise.as(null); } else if (gitErrorCode === GitErrorCodes.BadConfigFile) { this.messageService.show(severity.Error, localize('badConfigFile', "Git {0}", e.message)); return TPromise.as(null); } else if (gitErrorCode === GitErrorCodes.UnmergedChanges) { this.messageService.show(severity.Warning, localize('unmergedChanges', "You should first resolve the unmerged changes before committing your changes.")); return TPromise.as(null); } var error: Error; var showOutputAction = new Action('show.gitOutput', localize('showOutput', "Show Output"), null, true, () => this.outputService.getChannel('Git').show()); var cancelAction = new Action('close.message', localize('cancel', "Cancel"), null, true, () => TPromise.as(true)); error = createError( localize('checkNativeConsole', "There was an issue running a git operation. Please review the output or use a console to check the state of your repository."), { actions: [showOutputAction, cancelAction] } ); (<any>error).gitErrorCode = gitErrorCode; return TPromise.wrapError(error); }); } private transition(state: ServiceState): void { var oldState = this.state; this.state = state; if (state !== oldState) { this.emit(ServiceEvents.STATE_CHANGED, state); } } buffer(path: string, treeish: string = '~'): TPromise<string> { return this.raw.show(path, treeish); } show(path: string, status: IFileStatus, treeish: string = '~', mimetype: string = 'text/plain'): TPromise<EditorInput> { return this.detectMimetypes(path, treeish).then((mimetypes: string[]) => { var pathComponents = status.getPathComponents(); var fileSegment = pathComponents[pathComponents.length - 1]; var folderSegment = toReadablePath(pathComponents.slice(0, pathComponents.length - 1).join('/')); var label: string; var description: string; if (treeish === '~') { label = localize('changesFromIndex', "{0} (index)", fileSegment); description = localize('changesFromIndexDesc', "{0} - Changes on index", folderSegment); } else { label = localize('changesFromTree', "{0} ({1})", fileSegment, treeish); description = localize('changesFromTreeDesc', "{0} - Changes on {1}", folderSegment, treeish); } if (mime.isUnspecific(mimetypes)) { mimetypes = mime.guessMimeTypes(path); // guess from path if our detection did not yield results } // Binary: our story is weak here for binary files on the index. Since we run natively, we do not have a way currently // to e.g. show images as binary inside the renderer because images need to be served through a URL to show. We could revisit this by // allowing to use data URLs for resource inputs to render them. However, this would mean potentially loading a large file into memory // // Our solution now is to detect binary files and immediately return an input that is flagged as binary unknown mime type. if (mime.isBinaryMime(mime.guessMimeTypes(path)) || mimetypes.indexOf(mime.MIME_BINARY) >= 0) { return TPromise.wrapError(new Error('The resource seems to be binary and cannot be displayed')); } // Text return TPromise.as(this.instantiationService.createInstance(NativeGitIndexStringEditorInput, label, description, mimetypes.join(', '), status, path, treeish)); }); } getInput(status: IFileStatus): TPromise<EditorInput> { return this.inputCache.getInput(status).then(null, (err) => { if (err.gitErrorCode = GitErrorCodes.CantOpenResource) { this.messageService.show(severity.Warning, localize('cantOpenResource', "Can't open this git resource.")); return TPromise.as(null); } return TPromise.wrapError(err); }); } isInitialized(): boolean { return this.state === ServiceState.OK; } isIdle(): boolean { return this.isInitialized() && !this.operations.some(op => op.id !== ServiceOperations.BACKGROUND_FETCH); } getRunningOperations(): IGitOperation[] { return this.operations; } getAutoFetcher(): IAutoFetcher { return this.autoFetcher; } private static toPaths(files: IFileStatus[]): string[] { if (!files) { return null; } return files.map((status) => { /* In the case that a file was renamed in the index and (changed || deleted) in the working tree, we must use its new name, running the checkout command. */ switch (status.getStatus()) { case Status.MODIFIED: case Status.DELETED: if (status.getRename()) { return status.getRename(); } default: return status.getPath(); } }); } dispose(): void { this.emit(ServiceEvents.DISPOSE); if (this.model) { this.model.dispose(); this.model = null; } super.dispose(); } }
the_stack
import * as React from 'react'; import { useId, useControllableValue, useConst, useSetTimeout } from '@fluentui/react-hooks'; import { KeyCodes, css, getRTL, getRTLSafeKeyCode, on, classNamesFunction, getNativeProps, divProperties, } from '@fluentui/utilities'; import type { ISliderProps, ISliderStyleProps, ISliderStyles } from './Slider.types'; import type { ILabelProps } from '../Label/index'; export const ONKEYDOWN_TIMEOUT_DURATION = 1000; interface ISliderInternalState { onKeyDownTimer: number; /** For a ranged slider, whether the thumb currently being dragged is the lower value one. */ isAdjustingLowerValue: boolean; /** Allows access to the latest `value` inside reused callbacks (to avoid stale capture issues) */ latestValue: number; /** Allows access to the latest `lowerValue` inside reused callbacks (to avoid stale capture issues) */ latestLowerValue: number; /** * Whether the user is currently dragging the thumb and it's between step intervals. * (If true, and `props.snapToStep` is falsy, transition animations will be disabled.) */ isBetweenSteps?: boolean; } const getClassNames = classNamesFunction<ISliderStyleProps, ISliderStyles>(); type Dimension = 'height' | 'width'; type Position = 'bottom' | 'left' | 'right'; type PositionOrDimension = Dimension | Position; /** All the possible event types for a change event */ type ChangeEvent = Parameters<Required<ISliderProps>['onChange']>[2]; /** All the possible event types for a change event that's dragging the slider (mouse or touch) */ type DragChangeEvent = React.MouseEvent | React.TouchEvent | MouseEvent | TouchEvent; const getSlotStyleFn = (sty: PositionOrDimension) => { return (value: number) => { return { [sty]: `${value}%`, }; }; }; const getPercent = (value: number, sliderMin: number, sliderMax: number) => { return sliderMax === sliderMin ? 0 : ((value - sliderMin) / (sliderMax - sliderMin)) * 100; }; const useComponentRef = ( props: ISliderProps, thumb: React.RefObject<HTMLSpanElement>, value: number | undefined, range: [number, number] | undefined, ) => { React.useImperativeHandle( props.componentRef, () => ({ get value() { return value; }, get range() { return range; }, focus() { if (thumb.current) { thumb.current.focus(); } }, }), [thumb, value, range], ); }; export const useSlider = (props: ISliderProps, ref: React.Ref<HTMLDivElement>) => { const { step = 1, className, disabled = false, label, max = 10, min = 0, showValue = true, buttonProps = {}, vertical = false, snapToStep, valueFormat, styles, theme, originFromZero, 'aria-labelledby': ariaLabelledBy, 'aria-label': ariaLabel, ranged, onChange, onChanged, } = props; const disposables = React.useRef<(() => void)[]>([]); const { setTimeout, clearTimeout } = useSetTimeout(); const sliderLine = React.useRef<HTMLDivElement>(null); // Casting here is necessary because useControllableValue expects the event for the change callback // to extend React.SyntheticEvent, when in fact for Slider, the event could be either a React event // or a native browser event depending on the context. const [unclampedValue, setValue] = useControllableValue(props.value, props.defaultValue, (ev: any, v) => onChange?.(v!, ranged ? [internalState.latestLowerValue, v!] : undefined, ev), ) as [number | undefined, (v: number | undefined, ev: ChangeEvent) => void]; const [unclampedLowerValue, setLowerValue] = useControllableValue( props.lowerValue, props.defaultLowerValue, (ev: any, lv) => onChange?.(internalState.latestValue, [lv!, internalState.latestValue], ev), ) as [number | undefined, (v: number | undefined, ev: ChangeEvent) => void]; // Ensure that value is always a number and is clamped by min/max. const value = Math.max(min, Math.min(max, unclampedValue || 0)); const lowerValue = Math.max(min, Math.min(value, unclampedLowerValue || 0)); const internalState = useConst<ISliderInternalState>({ onKeyDownTimer: -1, isAdjustingLowerValue: false, latestValue: value, latestLowerValue: lowerValue, }); // On each render, update this saved value used by callbacks. (This should be safe even if render // is called multiple times, because an event handler or timeout callback will only run once.) internalState.latestValue = value; internalState.latestLowerValue = lowerValue; const id = useId('Slider', props.id || buttonProps?.id); const classNames = getClassNames(styles, { className, disabled, vertical, showTransitions: !snapToStep && !internalState.isBetweenSteps, showValue, ranged, theme: theme!, }); const steps = (max - min) / step; const clearOnKeyDownTimer = (): void => { clearTimeout(internalState.onKeyDownTimer); internalState.onKeyDownTimer = -1; }; const setOnKeyDownTimer = (event: React.KeyboardEvent) => { clearOnKeyDownTimer(); if (onChanged) { internalState.onKeyDownTimer = setTimeout(() => { onChanged( event, internalState.latestValue, ranged ? [internalState.latestLowerValue, internalState.latestValue] : undefined, ); }, ONKEYDOWN_TIMEOUT_DURATION); } }; const getAriaValueText = (valueProps: number | undefined): string | undefined => { const { ariaValueText } = props; if (valueProps !== undefined) { return ariaValueText ? ariaValueText(valueProps) : valueProps.toString(); } return undefined; }; /** * Update `value` or `lowerValue`, including clamping between min/max and rounding to * appropriate precision. * @param newValue - New current value of the slider, possibly rounded to a whole step. * @param newUnroundedValue - Like `newValue` but without the rounding to a step. If this is * provided and not equal to `newValue`, `internalState.isBetweenSteps` will be set, which * may cause thumb movement animations to be disabled. */ const updateValue = (ev: any, newValue: number, newUnroundedValue?: number): void => { newValue = Math.min(max, Math.max(min, newValue)); newUnroundedValue = newUnroundedValue !== undefined ? Math.min(max, Math.max(min, newUnroundedValue)) : undefined; let numDec = 0; if (isFinite(step)) { while (Math.round(step * Math.pow(10, numDec)) / Math.pow(10, numDec) !== step) { numDec++; } } // Make sure value has correct number of decimal places based on number of decimals in step const roundedValue = parseFloat(newValue.toFixed(numDec)); internalState.isBetweenSteps = newUnroundedValue !== undefined && newUnroundedValue !== roundedValue; if (ranged) { // decided which thumb value to change if ( internalState.isAdjustingLowerValue && (originFromZero ? roundedValue <= 0 : roundedValue <= internalState.latestValue) ) { setLowerValue(roundedValue, ev); } else if ( !internalState.isAdjustingLowerValue && (originFromZero ? roundedValue >= 0 : roundedValue >= internalState.latestLowerValue) ) { setValue(roundedValue, ev); } } else { setValue(roundedValue, ev); } }; const onKeyDown = (event: React.KeyboardEvent): void => { let newCurrentValue = internalState.isAdjustingLowerValue ? internalState.latestLowerValue : internalState.latestValue; let diff = 0; // eslint-disable-next-line deprecation/deprecation switch (event.which) { case getRTLSafeKeyCode(KeyCodes.left, props.theme): case KeyCodes.down: diff = -step; clearOnKeyDownTimer(); setOnKeyDownTimer(event); break; case getRTLSafeKeyCode(KeyCodes.right, props.theme): case KeyCodes.up: diff = step; clearOnKeyDownTimer(); setOnKeyDownTimer(event); break; case KeyCodes.home: newCurrentValue = min; clearOnKeyDownTimer(); setOnKeyDownTimer(event); break; case KeyCodes.end: newCurrentValue = max; clearOnKeyDownTimer(); setOnKeyDownTimer(event); break; default: return; } updateValue(event, newCurrentValue + diff); event.preventDefault(); event.stopPropagation(); }; const getPosition = (event: DragChangeEvent, verticalProp: boolean | undefined): number => { let currentPosition = 0; switch (event.type) { case 'mousedown': case 'mousemove': currentPosition = !verticalProp ? (event as MouseEvent).clientX : (event as MouseEvent).clientY; break; case 'touchstart': case 'touchmove': currentPosition = !verticalProp ? (event as TouchEvent).touches[0].clientX : (event as TouchEvent).touches[0].clientY; break; } return currentPosition; }; const calculateCurrentSteps = (event: DragChangeEvent) => { const sliderPositionRect: ClientRect = sliderLine.current!.getBoundingClientRect(); const sliderLength: number = !props.vertical ? sliderPositionRect.width : sliderPositionRect.height; const stepLength: number = sliderLength / steps; let currentSteps: number; let distance: number; if (!props.vertical) { const left = getPosition(event, props.vertical); distance = getRTL(props.theme) ? sliderPositionRect.right - left : left - sliderPositionRect.left; currentSteps = distance / stepLength; } else { const bottom = getPosition(event, props.vertical); distance = sliderPositionRect.bottom - bottom; currentSteps = distance / stepLength; } return currentSteps; }; const onMouseMoveOrTouchMove = (event: DragChangeEvent, suppressEventCancelation?: boolean): void => { const currentSteps = calculateCurrentSteps(event); const newUnroundedValue = min + step * currentSteps; const newCurrentValue = min + step * Math.round(currentSteps); updateValue(event, newCurrentValue, newUnroundedValue); if (!suppressEventCancelation) { event.preventDefault(); event.stopPropagation(); } }; const onMouseDownOrTouchStart = (event: React.MouseEvent | React.TouchEvent): void => { if (ranged) { const currentSteps = calculateCurrentSteps(event); const newValue = min + step * currentSteps; internalState.isAdjustingLowerValue = newValue <= internalState.latestLowerValue || newValue - internalState.latestLowerValue <= internalState.latestValue - newValue; } if (event.type === 'mousedown') { disposables.current.push( on(window, 'mousemove', onMouseMoveOrTouchMove as (ev: Event) => void, true), on(window, 'mouseup', onMouseUpOrTouchEnd, true), ); } else if (event.type === 'touchstart') { disposables.current.push( on(window, 'touchmove', onMouseMoveOrTouchMove as (ev: Event) => void, true), on(window, 'touchend', onMouseUpOrTouchEnd, true), ); } onMouseMoveOrTouchMove(event, true); }; const onMouseUpOrTouchEnd = (event: MouseEvent | TouchEvent): void => { // Done adjusting, so clear this value internalState.isBetweenSteps = undefined; onChanged?.( event, internalState.latestValue, ranged ? [internalState.latestLowerValue, internalState.latestValue] : undefined, ); disposeListeners(); }; const onThumbFocus = (event: React.FocusEvent): void => { internalState.isAdjustingLowerValue = event.target === lowerValueThumbRef.current; }; const disposeListeners = (): void => { disposables.current.forEach(dispose => dispose()); disposables.current = []; }; const lowerValueThumbRef = React.useRef<HTMLElement>(null); const thumbRef = React.useRef<HTMLElement>(null); useComponentRef( props, ranged && !vertical ? lowerValueThumbRef : thumbRef, value, ranged ? [lowerValue, value] : undefined, ); const getPositionStyles = getSlotStyleFn(vertical ? 'bottom' : getRTL(props.theme) ? 'right' : 'left'); const getTrackStyles = getSlotStyleFn(vertical ? 'height' : 'width'); const originValue = originFromZero ? 0 : min; const valuePercent = getPercent(value, min, max); const lowerValuePercent = getPercent(lowerValue, min, max); const originPercentOfLine = getPercent(originValue, min, max); const activeSectionWidth = ranged ? valuePercent - lowerValuePercent : Math.abs(originPercentOfLine - valuePercent); const topSectionWidth = Math.min(100 - valuePercent, 100 - originPercentOfLine); const bottomSectionWidth = ranged ? lowerValuePercent : Math.min(valuePercent, originPercentOfLine); const rootProps: React.HTMLAttributes<HTMLDivElement> & React.RefAttributes<HTMLDivElement> = { className: classNames.root, ref: ref, }; const labelProps: ILabelProps = { className: classNames.titleLabel, children: label, disabled, htmlFor: ariaLabel ? undefined : id, }; const valueLabelProps: ILabelProps | undefined = showValue ? { className: classNames.valueLabel, children: valueFormat ? valueFormat(value) : value, disabled, htmlFor: disabled ? id : undefined, } : undefined; const lowerValueLabelProps: ILabelProps | undefined = ranged && showValue ? { className: classNames.valueLabel, children: valueFormat ? valueFormat(lowerValue) : lowerValue, disabled, } : undefined; const zeroTickProps: React.HTMLAttributes<HTMLElement> | undefined = originFromZero ? { className: classNames.zeroTick, style: getPositionStyles(originPercentOfLine), } : undefined; const trackActiveProps: React.HTMLAttributes<HTMLElement> = { className: css(classNames.lineContainer, classNames.activeSection), style: getTrackStyles(activeSectionWidth), }; const trackTopInactiveProps: React.HTMLAttributes<HTMLElement> = { className: css(classNames.lineContainer, classNames.inactiveSection), style: getTrackStyles(topSectionWidth), }; const trackBottomInactiveProps: React.HTMLAttributes<HTMLElement> = { className: css(classNames.lineContainer, classNames.inactiveSection), style: getTrackStyles(bottomSectionWidth), }; const sliderProps: React.HTMLAttributes<HTMLElement> = { 'aria-disabled': disabled, role: 'slider', tabIndex: disabled ? undefined : 0, ...({ 'data-is-focusable': !disabled } as any), }; const sliderBoxProps: React.HTMLAttributes<HTMLElement> = { id, className: css(classNames.slideBox, buttonProps.className), ...(!disabled && { onMouseDown: onMouseDownOrTouchStart, onTouchStart: onMouseDownOrTouchStart, onKeyDown: onKeyDown, }), ...(buttonProps && getNativeProps<React.HTMLAttributes<HTMLDivElement>>(buttonProps, divProperties, ['id', 'className'])), ...(!ranged && { ...sliderProps, 'aria-valuemin': min, 'aria-valuemax': max, 'aria-valuenow': value, 'aria-valuetext': getAriaValueText(value), 'aria-label': ariaLabel || label, 'aria-labelledby': ariaLabelledBy, }), }; const onFocusProp = disabled ? {} : { onFocus: onThumbFocus }; const thumbProps: React.HTMLAttributes<HTMLElement> & React.RefAttributes<HTMLElement> = { ref: thumbRef, className: classNames.thumb, style: getPositionStyles(valuePercent), ...(ranged && { ...sliderProps, ...onFocusProp, id: `max-${id}`, 'aria-valuemin': lowerValue, 'aria-valuemax': max, 'aria-valuenow': value, 'aria-valuetext': getAriaValueText(value), 'aria-label': `max ${ariaLabel || label}`, }), }; const lowerValueThumbProps: | (React.HTMLAttributes<HTMLElement> & React.RefAttributes<HTMLElement>) | undefined = ranged ? { ref: lowerValueThumbRef, className: classNames.thumb, style: getPositionStyles(lowerValuePercent), ...sliderProps, ...onFocusProp, id: `min-${id}`, 'aria-valuemin': min, 'aria-valuemax': value, 'aria-valuenow': lowerValue, 'aria-valuetext': getAriaValueText(lowerValue), 'aria-label': `min ${ariaLabel || label}`, } : undefined; const containerProps: React.HTMLAttributes<HTMLElement> = { className: classNames.container, }; const sliderLineProps: React.HTMLAttributes<HTMLDivElement> & React.RefAttributes<HTMLDivElement> = { ref: sliderLine, className: classNames.line, }; return { root: rootProps, label: labelProps, sliderBox: sliderBoxProps, container: containerProps, valueLabel: valueLabelProps, lowerValueLabel: lowerValueLabelProps, thumb: thumbProps, lowerValueThumb: lowerValueThumbProps, zeroTick: zeroTickProps, activeTrack: trackActiveProps, topInactiveTrack: trackTopInactiveProps, bottomInactiveTrack: trackBottomInactiveProps, sliderLine: sliderLineProps, }; };
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const timeEntryOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'timeEntry', ], }, }, options: [ { name: 'Create', value: 'create', description: 'Create a time entry', }, { name: 'Delete', value: 'delete', description: 'Delete a time entry', }, { name: 'Get', value: 'get', description: 'Get a time entry', }, { name: 'Get All', value: 'getAll', description: 'Get all time entries', }, { name: 'Start', value: 'start', description: 'Start a time entry', }, { name: 'Stop', value: 'stop', description: 'Stop the current running timer', }, { name: 'Update', value: 'update', description: 'Update a time Entry', }, ], default: 'create', description: 'The operation to perform.', }, ]; export const timeEntryFields: INodeProperties[] = [ /* -------------------------------------------------------------------------- */ /* timeEntry:getAll */ /* -------------------------------------------------------------------------- */ { displayName: 'Team ID', name: 'team', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'getAll', ], }, }, typeOptions: { loadOptionsMethod: 'getTeams', }, required: true, }, { displayName: 'Return All', name: 'returnAll', type: 'boolean', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'getAll', ], }, }, default: false, description: 'If all results should be returned or only up to a given limit.', }, { displayName: 'Limit', name: 'limit', type: 'number', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'getAll', ], returnAll: [ false, ], }, }, typeOptions: { minValue: 1, maxValue: 10, }, default: 5, description: 'How many results to return.', }, { displayName: 'Filters', name: 'filters', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'getAll', ], }, }, options: [ { displayName: 'End Date', name: 'end_date', type: 'dateTime', default: '', }, { displayName: 'Start Date', name: 'start_date', type: 'dateTime', default: '', }, ], }, /* -------------------------------------------------------------------------- */ /* timeEntry:get */ /* -------------------------------------------------------------------------- */ { displayName: 'Team ID', name: 'team', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'get', ], }, }, typeOptions: { loadOptionsMethod: 'getTeams', }, required: true, }, { displayName: 'Running', name: 'running', type: 'boolean', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'get', ], }, }, default: false, description: 'When set to true it will return just the current running time entry', }, { displayName: 'Time Entry ID', name: 'timeEntry', type: 'string', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'get', ], running: [ false, ], }, }, required: true, }, /* -------------------------------------------------------------------------- */ /* timeEntry:create */ /* -------------------------------------------------------------------------- */ { displayName: 'Team ID', name: 'team', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'create', ], }, }, typeOptions: { loadOptionsMethod: 'getTeams', }, required: true, }, { displayName: 'Space ID', name: 'space', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'create', ], }, }, typeOptions: { loadOptionsMethod: 'getSpaces', loadOptionsDependsOn: [ 'team', ], }, required: true, }, { displayName: 'Folderless List', name: 'folderless', type: 'boolean', default: false, displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'create', ], }, }, required: true, }, { displayName: 'Folder ID', name: 'folder', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'create', ], folderless: [ false, ], }, }, typeOptions: { loadOptionsMethod: 'getFolders', loadOptionsDependsOn: [ 'space', ], }, required: true, }, { displayName: 'List ID', name: 'list', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'create', ], folderless: [ true, ], }, }, typeOptions: { loadOptionsMethod: 'getFolderlessLists', loadOptionsDependsOn: [ 'space', ], }, required: true, }, { displayName: 'List ID', name: 'list', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'create', ], folderless: [ false, ], }, }, typeOptions: { loadOptionsMethod: 'getLists', loadOptionsDependsOn: [ 'folder', ], }, required: true, }, { displayName: 'Start', name: 'start', type: 'dateTime', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'create', ], }, }, required: true, default: '', }, { displayName: 'Duration (minutes)', name: 'duration', type: 'number', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'create', ], }, }, default: 0, required: true, description: 'Duration in minutes', }, { displayName: 'Task ID', name: 'task', type: 'options', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'create', ], }, }, typeOptions: { loadOptionsMethod: 'getTasks', loadOptionsDependsOn: [ 'list', ], }, default: '', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'create', ], }, }, options: [ { displayName: 'Assignee IDs', name: 'assignee', type: 'options', typeOptions: { loadOptionsMethod: 'getAssignees', loadOptionsDependsOn: [ 'list', ], }, default: [], }, { displayName: 'Billable', name: 'billable', type: 'boolean', default: true, }, { displayName: 'Description', name: 'description', type: 'string', default: '', description: 'Description of the time entry', }, { displayName: 'Tags IDs', name: 'tags', type: 'multiOptions', typeOptions: { loadOptionsDependsOn: [ 'team', ], loadOptionsMethod: 'getTimeEntryTags', }, default: [], }, ], }, /* -------------------------------------------------------------------------- */ /* timeEntry:start */ /* -------------------------------------------------------------------------- */ { displayName: 'Team ID', name: 'team', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'start', ], }, }, typeOptions: { loadOptionsMethod: 'getTeams', }, required: true, }, { displayName: 'Task ID', name: 'task', type: 'string', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'start', ], }, }, required: true, }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'start', ], }, }, options: [ { displayName: 'Billable', name: 'billable', type: 'boolean', default: true, }, { displayName: 'Description', name: 'description', type: 'string', default: '', description: 'Description of the time entry', }, ], }, /* -------------------------------------------------------------------------- */ /* timeEntry:stop */ /* -------------------------------------------------------------------------- */ { displayName: 'Team ID', name: 'team', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'stop', ], }, }, typeOptions: { loadOptionsMethod: 'getTeams', }, required: true, }, /* -------------------------------------------------------------------------- */ /* timeEntry:delete */ /* -------------------------------------------------------------------------- */ { displayName: 'Team ID', name: 'team', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'delete', ], }, }, typeOptions: { loadOptionsMethod: 'getTeams', }, required: true, }, { displayName: 'Time Entry ID', name: 'timeEntry', type: 'string', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'delete', ], }, }, required: true, }, /* -------------------------------------------------------------------------- */ /* timeEntry:update */ /* -------------------------------------------------------------------------- */ { displayName: 'Team ID', name: 'team', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'update', ], }, }, typeOptions: { loadOptionsMethod: 'getTeams', }, required: true, }, { displayName: 'Space ID', name: 'space', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'update', ], }, }, typeOptions: { loadOptionsMethod: 'getSpaces', loadOptionsDependsOn: [ 'team', ], }, required: true, }, { displayName: 'Folderless List', name: 'folderless', type: 'boolean', default: false, displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'update', ], }, }, required: true, }, { displayName: 'Folder ID', name: 'folder', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'update', ], folderless: [ false, ], }, }, typeOptions: { loadOptionsMethod: 'getFolders', loadOptionsDependsOn: [ 'space', ], }, required: true, }, { displayName: 'List ID', name: 'list', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'update', ], folderless: [ true, ], }, }, typeOptions: { loadOptionsMethod: 'getFolderlessLists', loadOptionsDependsOn: [ 'space', ], }, required: true, }, { displayName: 'List ID', name: 'list', type: 'options', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'update', ], folderless: [ false, ], }, }, typeOptions: { loadOptionsMethod: 'getLists', loadOptionsDependsOn: [ 'folder', ], }, required: true, }, { displayName: 'Archived', name: 'archived', type: 'boolean', default: false, displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'update', ], }, }, required: true, }, { displayName: 'Time Entry ID', name: 'timeEntry', type: 'string', default: '', displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'update', ], }, }, required: true, }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'timeEntry', ], operation: [ 'update', ], }, }, options: [ { displayName: 'Assignee IDs', name: 'assignee', type: 'options', typeOptions: { loadOptionsMethod: 'getAssignees', loadOptionsDependsOn: [ 'list', ], }, default: [], }, { displayName: 'Billable', name: 'billable', type: 'boolean', default: true, }, { displayName: 'Description', name: 'description', type: 'string', default: '', description: 'Description of the time entry', }, { displayName: 'Duration (minutes)', name: 'duration', type: 'number', default: 0, description: 'Duration in minutes', }, { displayName: 'Start', name: 'start', type: 'dateTime', default: '', }, { displayName: 'Tags IDs', name: 'tags', type: 'multiOptions', typeOptions: { loadOptionsDependsOn: [ 'spaceId', ], loadOptionsMethod: 'getTags', }, default: [], }, { displayName: 'Task ID', name: 'task', type: 'options', typeOptions: { loadOptionsMethod: 'getTasks', loadOptionsDependsOn: [ 'archived', 'list', ], }, default: '', }, ], }, ];
the_stack
import XEUtils from 'xe-utils' import { browse, hasClass, getAbsolutePos, addClass, removeClass, getEventTargetNode } from '../../tools/dom' import { VxeGlobalHooksHandles, TableKeyboardPrivateMethods } from '../../../types/all' function getTargetOffset (target: any, container: any) { let offsetTop = 0 let offsetLeft = 0 const triggerCheckboxLabel = !browse.firefox && hasClass(target, 'vxe-checkbox--label') if (triggerCheckboxLabel) { const checkboxLabelStyle = getComputedStyle(target) offsetTop -= XEUtils.toNumber(checkboxLabelStyle.paddingTop) offsetLeft -= XEUtils.toNumber(checkboxLabelStyle.paddingLeft) } while (target && target !== container) { offsetTop += target.offsetTop offsetLeft += target.offsetLeft target = target.offsetParent if (triggerCheckboxLabel) { const checkboxStyle = getComputedStyle(target) offsetTop -= XEUtils.toNumber(checkboxStyle.paddingTop) offsetLeft -= XEUtils.toNumber(checkboxStyle.paddingLeft) } } return { offsetTop, offsetLeft } } const tableKeyboardHook: VxeGlobalHooksHandles.HookOptions = { setupTable ($xetable) { const { props, reactData, internalData } = $xetable const { refElem } = $xetable.getRefMaps() const { computeEditOpts, computeCheckboxOpts, computeMouseOpts, computeTreeOpts } = $xetable.getComputeMaps() function getCheckboxRangeRows (params: any, targetTrElem: any, moveRange: any) { let countHeight = 0 let rangeRows = [] const isDown = moveRange > 0 const moveSize = moveRange > 0 ? moveRange : (Math.abs(moveRange) + targetTrElem.offsetHeight) const { scrollYLoad } = reactData const { afterFullData, scrollYStore } = internalData if (scrollYLoad) { const _rowIndex = $xetable.getVTRowIndex(params.row) if (isDown) { rangeRows = afterFullData.slice(_rowIndex, _rowIndex + Math.ceil(moveSize / scrollYStore.rowHeight)) } else { rangeRows = afterFullData.slice(_rowIndex - Math.floor(moveSize / scrollYStore.rowHeight) + 1, _rowIndex + 1) } } else { const siblingProp = isDown ? 'next' : 'previous' while (targetTrElem && countHeight < moveSize) { const rowNodeRest = $xetable.getRowNode(targetTrElem) if (rowNodeRest) { rangeRows.push(rowNodeRest.item) countHeight += targetTrElem.offsetHeight targetTrElem = targetTrElem[`${siblingProp}ElementSibling`] } } } return rangeRows } const handleCheckboxRangeEvent = (evnt: any, params: any) => { const { column, cell } = params if (column.type === 'checkbox') { const el = refElem.value const { elemStore } = internalData const disX = evnt.clientX const disY = evnt.clientY const bodyWrapperRef = elemStore[`${column.fixed || 'main'}-body-wrapper`] || elemStore['main-body-wrapper'] const bodyWrapperElem = bodyWrapperRef ? bodyWrapperRef.value : null if (!bodyWrapperElem) { return } const checkboxRangeElem = bodyWrapperElem.querySelector('.vxe-table--checkbox-range') as HTMLElement const domMousemove = document.onmousemove const domMouseup = document.onmouseup const trElem = cell.parentNode const selectRecords = $xetable.getCheckboxRecords() let lastRangeRows = [] const marginSize = 1 const offsetRest = getTargetOffset(evnt.target, bodyWrapperElem) const startTop = offsetRest.offsetTop + evnt.offsetY const startLeft = offsetRest.offsetLeft + evnt.offsetX const startScrollTop = bodyWrapperElem.scrollTop const rowHeight = trElem.offsetHeight let mouseScrollTimeout: any = null let isMouseScrollDown: any = false let mouseScrollSpaceSize = 1 const triggerEvent = (type: 'change' | 'start' | 'end', evnt: MouseEvent) => { $xetable.dispatchEvent(`checkbox-range-${type}` as 'checkbox-range-change' | 'checkbox-range-start' | 'checkbox-range-end', { records: $xetable.getCheckboxRecords(), reserves: $xetable.getCheckboxReserveRecords() }, evnt) } const handleChecked = (evnt: MouseEvent) => { const { clientX, clientY } = evnt const offsetLeft = clientX - disX const offsetTop = clientY - disY + (bodyWrapperElem.scrollTop - startScrollTop) let rangeHeight = Math.abs(offsetTop) let rangeWidth = Math.abs(offsetLeft) let rangeTop = startTop let rangeLeft = startLeft if (offsetTop < marginSize) { // 向上 rangeTop += offsetTop if (rangeTop < marginSize) { rangeTop = marginSize rangeHeight = startTop } } else { // 向下 rangeHeight = Math.min(rangeHeight, bodyWrapperElem.scrollHeight - startTop - marginSize) } if (offsetLeft < marginSize) { // 向左 rangeLeft += offsetLeft if (rangeWidth > startLeft) { rangeLeft = marginSize rangeWidth = startLeft } } else { // 向右 rangeWidth = Math.min(rangeWidth, bodyWrapperElem.clientWidth - startLeft - marginSize) } checkboxRangeElem.style.height = `${rangeHeight}px` checkboxRangeElem.style.width = `${rangeWidth}px` checkboxRangeElem.style.left = `${rangeLeft}px` checkboxRangeElem.style.top = `${rangeTop}px` checkboxRangeElem.style.display = 'block' const rangeRows = getCheckboxRangeRows(params, trElem, offsetTop < marginSize ? -rangeHeight : rangeHeight) // 至少滑动 10px 才能有效匹配 if (rangeHeight > 10 && rangeRows.length !== lastRangeRows.length) { lastRangeRows = rangeRows if (evnt.ctrlKey) { rangeRows.forEach((row: any) => { $xetable.handleSelectRow({ row }, selectRecords.indexOf(row) === -1) }) } else { $xetable.setAllCheckboxRow(false) $xetable.setCheckboxRow(rangeRows, true) } triggerEvent('change', evnt) } } // 停止鼠标滚动 const stopMouseScroll = () => { clearTimeout(mouseScrollTimeout) mouseScrollTimeout = null } // 开始鼠标滚动 const startMouseScroll = (evnt: MouseEvent) => { stopMouseScroll() mouseScrollTimeout = setTimeout(() => { if (mouseScrollTimeout) { const { scrollLeft, scrollTop, clientHeight, scrollHeight } = bodyWrapperElem const topSize = Math.ceil(mouseScrollSpaceSize * 50 / rowHeight) if (isMouseScrollDown) { if (scrollTop + clientHeight < scrollHeight) { $xetable.scrollTo(scrollLeft, scrollTop + topSize) startMouseScroll(evnt) handleChecked(evnt) } else { stopMouseScroll() } } else { if (scrollTop) { $xetable.scrollTo(scrollLeft, scrollTop - topSize) startMouseScroll(evnt) handleChecked(evnt) } else { stopMouseScroll() } } } }, 50) } addClass(el, 'drag--range') document.onmousemove = evnt => { evnt.preventDefault() evnt.stopPropagation() const { clientY } = evnt const { boundingTop } = getAbsolutePos(bodyWrapperElem) // 如果超过可视区,触发滚动 if (clientY < boundingTop) { isMouseScrollDown = false mouseScrollSpaceSize = boundingTop - clientY if (!mouseScrollTimeout) { startMouseScroll(evnt) } } else if (clientY > boundingTop + bodyWrapperElem.clientHeight) { isMouseScrollDown = true mouseScrollSpaceSize = clientY - boundingTop - bodyWrapperElem.clientHeight if (!mouseScrollTimeout) { startMouseScroll(evnt) } } else if (mouseScrollTimeout) { stopMouseScroll() } handleChecked(evnt) } document.onmouseup = (evnt) => { stopMouseScroll() removeClass(el, 'drag--range') checkboxRangeElem.removeAttribute('style') document.onmousemove = domMousemove document.onmouseup = domMouseup triggerEvent('end', evnt) } triggerEvent('start', evnt) } } const handleCellMousedownEvent = (evnt: any, params: any) => { const { editConfig, checkboxConfig, mouseConfig } = props const checkboxOpts = computeCheckboxOpts.value const mouseOpts = computeMouseOpts.value const editOpts = computeEditOpts.value if (mouseConfig && mouseOpts.area && $xetable.handleCellAreaEvent) { return $xetable.handleCellAreaEvent(evnt, params) } else { if (checkboxConfig && checkboxOpts.range) { handleCheckboxRangeEvent(evnt, params) } if (mouseConfig && mouseOpts.selected) { if (!editConfig || editOpts.mode === 'cell') { $xetable.handleSelected(params, evnt) } } } } const keyboardMethods: TableKeyboardPrivateMethods = { // 处理 Tab 键移动 moveTabSelected (args, isLeft, evnt) { const { editConfig } = props const { afterFullData, visibleColumn } = internalData const editOpts = computeEditOpts.value let targetRow let targetRowIndex: any let targetColumnIndex: any const params = Object.assign({}, args) const _rowIndex = $xetable.getVTRowIndex(params.row) const _columnIndex = $xetable.getVTColumnIndex(params.column) evnt.preventDefault() if (isLeft) { // 向左 if (_columnIndex <= 0) { // 如果已经是第一列,则移动到上一行 if (_rowIndex > 0) { targetRowIndex = _rowIndex - 1 targetRow = afterFullData[targetRowIndex] targetColumnIndex = visibleColumn.length - 1 } } else { targetColumnIndex = _columnIndex - 1 } } else { if (_columnIndex >= visibleColumn.length - 1) { // 如果已经是第一列,则移动到上一行 if (_rowIndex < afterFullData.length - 1) { targetRowIndex = _rowIndex + 1 targetRow = afterFullData[targetRowIndex] targetColumnIndex = 0 } } else { targetColumnIndex = _columnIndex + 1 } } const targetColumn = visibleColumn[targetColumnIndex] if (targetColumn) { if (targetRow) { params.rowIndex = targetRowIndex params.row = targetRow } else { params.rowIndex = _rowIndex } params.columnIndex = targetColumnIndex params.column = targetColumn params.cell = $xetable.getCell(params.row, params.column) if (editConfig) { if (editOpts.trigger === 'click' || editOpts.trigger === 'dblclick') { if (editOpts.mode === 'row') { $xetable.handleActived(params, evnt) } else { $xetable.scrollToRow(params.row, params.column) .then(() => $xetable.handleSelected(params, evnt)) } } } else { $xetable.scrollToRow(params.row, params.column) .then(() => $xetable.handleSelected(params, evnt)) } } }, // 处理当前行方向键移动 moveCurrentRow (isUpArrow, isDwArrow, evnt) { const { treeConfig } = props const { currentRow } = reactData const { afterFullData } = internalData const treeOpts = computeTreeOpts.value let targetRow evnt.preventDefault() if (currentRow) { if (treeConfig) { const { index, items } = XEUtils.findTree(afterFullData, item => item === currentRow, treeOpts) if (isUpArrow && index > 0) { targetRow = items[index - 1] } else if (isDwArrow && index < items.length - 1) { targetRow = items[index + 1] } } else { const _rowIndex = $xetable.getVTRowIndex(currentRow) if (isUpArrow && _rowIndex > 0) { targetRow = afterFullData[_rowIndex - 1] } else if (isDwArrow && _rowIndex < afterFullData.length - 1) { targetRow = afterFullData[_rowIndex + 1] } } } else { targetRow = afterFullData[0] } if (targetRow) { const params = { $table: $xetable, row: targetRow, rowIndex: $xetable.getRowIndex(targetRow), $rowIndex: $xetable.getVMRowIndex(targetRow) } $xetable.scrollToRow(targetRow) .then(() => $xetable.triggerCurrentRowEvent(evnt, params)) } }, // 处理可编辑方向键移动 moveSelected (args, isLeftArrow, isUpArrow, isRightArrow, isDwArrow, evnt) { const { afterFullData, visibleColumn } = internalData const params = Object.assign({}, args) const _rowIndex = $xetable.getVTRowIndex(params.row) const _columnIndex = $xetable.getVTColumnIndex(params.column) evnt.preventDefault() if (isUpArrow && _rowIndex > 0) { // 移动到上一行 params.rowIndex = _rowIndex - 1 params.row = afterFullData[params.rowIndex] } else if (isDwArrow && _rowIndex < afterFullData.length - 1) { // 移动到下一行 params.rowIndex = _rowIndex + 1 params.row = afterFullData[params.rowIndex] } else if (isLeftArrow && _columnIndex) { // 移动到左侧单元格 params.columnIndex = _columnIndex - 1 params.column = visibleColumn[params.columnIndex] } else if (isRightArrow && _columnIndex < visibleColumn.length - 1) { // 移动到右侧单元格 params.columnIndex = _columnIndex + 1 params.column = visibleColumn[params.columnIndex] } $xetable.scrollToRow(params.row, params.column).then(() => { params.cell = $xetable.getCell(params.row, params.column) $xetable.handleSelected(params, evnt) }) }, /** * 表头单元格按下事件 */ triggerHeaderCellMousedownEvent (evnt, params) { const { mouseConfig } = props const mouseOpts = computeMouseOpts.value if (mouseConfig && mouseOpts.area && $xetable.handleHeaderCellAreaEvent) { const cell = evnt.currentTarget const triggerSort = getEventTargetNode(evnt, cell, 'vxe-cell--sort').flag const triggerFilter = getEventTargetNode(evnt, cell, 'vxe-cell--filter').flag $xetable.handleHeaderCellAreaEvent(evnt, Object.assign({ cell, triggerSort, triggerFilter }, params)) } $xetable.focus() if ($xetable.closeMenu) { $xetable.closeMenu() } }, /** * 单元格按下事件 */ triggerCellMousedownEvent (evnt, params) { const cell = evnt.currentTarget params.cell = cell handleCellMousedownEvent(evnt, params) $xetable.focus() $xetable.closeFilter() if ($xetable.closeMenu) { $xetable.closeMenu() } } } return keyboardMethods } } export default tableKeyboardHook
the_stack
import * as ts from 'typescript'; // tslint:disable-next-line:max-line-length import {DocClass, DocExtraType, DocFunction, DocFunctionParam, DocHeading, Docs, DocSubheading} from './view'; // Mirrors the info argument to @doc in decorators.ts. export interface DocInfo { heading: string; subheading: string; namespace?: string; subclasses?: string[]; useDocsFrom?: string; configParamIndices?: number[]; } export function getDocDecoratorOrAnnotation( checker: ts.TypeChecker, node: ts.MethodDeclaration|ts.ClassDeclaration|ts.FunctionDeclaration, annotationName: string): DocInfo { let docInfo: DocInfo; // Try to parse decorators. if (node.decorators != null) { docInfo = parseDocDecorators(node.decorators, annotationName); } else { // Try to parse the jsdoc annotation. const jsdoc = getJsdoc(checker, node, annotationName); if (jsdoc != null) { docInfo = convertDocStringToDocInfoObject(`${jsdoc}`); } } return docInfo; } /** * Parses the @doc annotation and returns the typed DocInfo object. */ export function parseDocDecorators( decorators: ts.NodeArray<ts.Decorator>, decoratorName: string): DocInfo { let docInfo: DocInfo = null; decorators.map(decorator => { const decoratorStr = decorator.getText(); if (decoratorStr.startsWith('@' + decoratorName)) { const decoratorConfigStr = decoratorStr.substring(decoratorName.length + 1); docInfo = convertDocStringToDocInfoObject(decoratorConfigStr); if (docInfo.subheading == null) { docInfo.subheading = ''; } } }); return docInfo; } /** * Converts a JSOL object (JavaScript object notation) to a parsed JSON DocInfo * object. * * e.g. * {heading: 'hello'} => {"heading": "hello"} */ function convertDocStringToDocInfoObject(docString: string): DocInfo { const jsonString = docString.replace(/([a-zA-Z0-9]+):/g, '"$1":').replace(/\'/g, '"'); return JSON.parse(jsonString); } export function addSubclassMethods( docHeadings: DocHeading[], subclassMethodMap: {[subclass: string]: DocFunction[]}) { const subclasses = Object.keys(subclassMethodMap); subclasses.forEach(subclass => { const methods = subclassMethodMap[subclass]; // Find the class. for (let i = 0; i < docHeadings.length; i++) { const heading = docHeadings[i]; for (let j = 0; j < heading.subheadings.length; j++) { const subheading = heading.subheadings[j]; if (subheading.symbols == null) { throw new Error( `Subheading '${subheading.name}' has no symbols. ` + `Please remove it from the predefined docHeadings, or ` + `add methods to the subheading in the code with @doc.`); } for (let k = 0; k < subheading.symbols.length; k++) { const symbol = subheading.symbols[k]; if (symbol['isClass'] != null && symbol.symbolName === subclass) { const classSymbol = symbol as DocClass; methods.forEach(method => classSymbol.methods.push(method)); } } } } }); } export function unpackConfigParams( docHeadings: DocHeading[], configInterfaceParamMap: {[interfaceName: string]: DocFunctionParam[]}) { foreachDocFunction(docHeadings, docFunction => { const params = []; for (let i = 0; i < docFunction.parameters.length; i++) { const configParamName = docFunction.parameters[i].name; params.push(docFunction.parameters[i]); let configParams = configInterfaceParamMap[docFunction.parameters[i].type]; if (configParams != null) { configParams.forEach( configParam => { // Deep copy the configParam. params.push(JSON.parse(JSON.stringify(configParam)))}); docFunction.parameters[i].type = 'Object'; } // If config params is null, we don't have an interface defined for // this type so we should not try to unpack it. } docFunction.parameters = params; }); } export function unpackExtraTypesInClasses( docHeadings: DocHeading[], configInterfaceParamMap: {[interfaceName: string]: DocFunctionParam[]}) { foreachDocClass(docHeadings, docClass => { if (docClass.extraTypes) { docClass.extraTypes.forEach(extraType => { const params = configInterfaceParamMap[extraType.symbol]; if (params != null) { extraType.params = params; } }); } }); } export function unpackReturnTypes( docHeadings: DocHeading[], configInterfaceParamMap: {[interfaceName: string]: DocFunctionParam[]}) { foreachDocFunction(docHeadings, docFunction => { if (docFunction.unpackedReturnTypes) { for (const returnType of docFunction.unpackedReturnTypes) { const params = configInterfaceParamMap[returnType.symbol]; if (params != null) { returnType.params = params; } } } }); } export function replaceUseDocsFromDocStrings( docHeadings: DocHeading[], globalSymbolDocMap: {[symbolName: string]: {docs: string, params: DocFunctionParam[]}}) { foreachDocFunction(docHeadings, docFunction => { if (docFunction.docInfo.useDocsFrom != null && globalSymbolDocMap[docFunction.docInfo.useDocsFrom] != null) { docFunction.documentation = globalSymbolDocMap[docFunction.docInfo.useDocsFrom].docs; const params = globalSymbolDocMap[docFunction.docInfo.useDocsFrom].params || []; // Replace params from useDocsFrom only when param names line up. for (let i = 0; i < docFunction.parameters.length; i++) { params.forEach(param => { if (param.name === docFunction.parameters[i].name) { docFunction.parameters[i] = param; } }); } } }); } // Parse the file info, github URL and filename from a node. export function getFileInfo( node: ts.Node, sourceFile: ts.SourceFile, repoPath: string, srcRoot: string, githubRoot: string): {displayFilename: string, githubUrl: string} { // Line numbers are 0-indexed. const startLine = sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1; const endLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1; const fileName = sourceFile.fileName.substring(repoPath.length + '/'.length); const displayFilename = fileName.substring(srcRoot.length) + '#' + startLine; const githubUrl = `${githubRoot}/${fileName}#L${startLine}-L${endLine}`; return {displayFilename, githubUrl}; } // Given a newly seen docInfo from a @doc annotation, fill in headings / // subheadings and return the subheading. export function fillHeadingsAndGetSubheading( docInfo: DocInfo, docHeadings: DocHeading[]): DocSubheading { // Find the heading. let heading: DocHeading; for (let i = 0; i < docHeadings.length; i++) { if (docHeadings[i].name === docInfo.heading) { heading = docHeadings[i]; } } if (heading == null) { heading = {name: docInfo.heading, description: '', subheadings: []}; docHeadings.push(heading); } // Find the subheading. let subheading: DocSubheading; for (let i = 0; i < heading.subheadings.length; i++) { if (heading.subheadings[i].name === docInfo.subheading) { subheading = heading.subheadings[i]; } } if (subheading == null) { subheading = {name: docInfo.subheading, symbols: []}; heading.subheadings.push(subheading); } if (subheading.symbols == null) { subheading.symbols = []; } return subheading; } export function computeStatistics(docs: Docs): {headingsCount: number, subheadingsCount: number, methodCount: number} { let subheadingsCount = 0; let methodCount = 0; for (let i = 0; i < docs.headings.length; i++) { const heading = docs.headings[i]; subheadingsCount += heading.subheadings.length; for (let j = 0; j < heading.subheadings.length; j++) { methodCount += heading.subheadings[j].symbols.length; } } return {headingsCount: docs.headings.length, subheadingsCount, methodCount}; } // Sorts the doc headings. export function sortMethods( docs: Docs, pins: {[heading: string]: {[subheading: string]: string[]}}) { const docHeadings = docs.headings; // Sort the methods by name. for (let i = 0; i < docHeadings.length; i++) { const heading = docHeadings[i]; for (let j = 0; j < heading.subheadings.length; j++) { const subheading = heading.subheadings[j]; if (subheading.symbols == null) { subheading.symbols = []; } // Pin the symbols in order of the pins. const pinnedSymbols = []; if (pins[heading.name] != null && pins[heading.name][subheading.name] != null) { const pin = pins[heading.name][subheading.name]; pin.forEach(pinnedSymbolName => { // Loop backwards so we remove symbols. for (let k = subheading.symbols.length - 1; k >= 0; k--) { const symbol = subheading.symbols[k]; if (symbol.symbolName === pinnedSymbolName) { pinnedSymbols.push(symbol); subheading.symbols.splice(k, 1); } } }); } // Sort non-pinned symbols by name. subheading.symbols.sort((a, b) => { if (a.symbolName < b.symbolName) { return -1; } else if (a.symbolName > b.symbolName) { return 1; } return 0; }); subheading.symbols = pinnedSymbols.concat(subheading.symbols); } } } export function kind(node: ts.Node): string { const keys = Object.keys(ts.SyntaxKind); for (let i = 0; i < keys.length; i++) { if (ts.SyntaxKind[keys[i]] === node.kind) { return keys[i]; } } return null; } export function isStatic(node: ts.MethodDeclaration): boolean { let isStatic = false; node.forEachChild(child => { if (child.kind === ts.SyntaxKind.StaticKeyword) { isStatic = true; } }); return isStatic; } /** * Finds a jsdoc tag by a given tag name for a symbol. e.g. @docalias number[] * => number[]. */ export function getJsdoc( checker: ts.TypeChecker, node: ts.InterfaceDeclaration|ts.TypeAliasDeclaration|ts.ClassDeclaration| ts.EnumDeclaration|ts.FunctionDeclaration|ts.MethodDeclaration, tag: string): string { const symbol = checker.getSymbolAtLocation(node.name); const docs = symbol.getDocumentationComment(checker); const tags = symbol.getJsDocTags(); for (let i = 0; i < tags.length; i++) { const jsdocTag = tags[i]; if (jsdocTag.name === tag) { return jsdocTag.text != null ? jsdocTag.text.trim() : ''; } } return null; } /** * Converts a function parameter symbol to its string type value. */ export function parameterTypeToString( checker: ts.TypeChecker, symbol: ts.Symbol, identifierGenericMap: {[identifier: string]: string}): string { // Look for type nodes that aren't null and get the full text of the type // node, falling back to using the checker to serialize the type. let typeStr; const valueDeclaration = symbol.valueDeclaration; if (valueDeclaration == null) { // See bug https://github.com/microsoft/TypeScript/issues/24706 // value declaration is not optional but is sometimes undefined. // Fall back to using the checkers method for converting the type to a // string. typeStr = checker.typeToString( checker.getTypeOfSymbolAtLocation(symbol, valueDeclaration)); } else { valueDeclaration.forEachChild(child => { if (ts.isTypeNode(child) && child.kind !== ts.SyntaxKind.NullKeyword) { typeStr = child.getText(); } }); if (typeStr == null) { // Fall back to using the checkers method for converting the type to a // string. typeStr = checker.typeToString( checker.getTypeOfSymbolAtLocation(symbol, valueDeclaration)); } } return sanitizeTypeString(typeStr, identifierGenericMap); } /** * Sanitizes a type string by removing generics and replacing generics. * e.g. Tensor<R> => Tensor * e.g. T => Tensor */ export function sanitizeTypeString( typeString: string, identifierGenericMap: {[identifier: string]: string}) { // If the return type is part of the generic map, use the mapped // type. For example, <T extends Tensor> will replace "T" with // "Tensor". Object.keys(identifierGenericMap).forEach(identifier => { const re = new RegExp('\\b' + identifier + '\\b', 'g'); typeString = typeString.replace(re, identifierGenericMap[identifier]); }); // Remove generics except Promise generics. typeString = typeString.replace(/(?<!Promise)(<.+?>)/, ''); return typeString; } /** * Computes a mapping of identifier to their generic type. For example: * method<T extends Tensor>() {} * In this example, this method will return {'T': 'Tensor'}. */ export function getIdentifierGenericMap(node: ts.MethodDeclaration| ts.FunctionDeclaration): {[generic: string]: string} { const identifierGenericMap = {}; node.forEachChild(child => { // TypeParameterDeclarations look like <T extends Tensor|NamedTensorMap>. if (ts.isTypeParameterDeclaration(child)) { let identifier; let generic; child.forEachChild(cc => { // Type nodes are "Tensor|NamedTensorMap" // Identifier nodes are "T". if (ts.isTypeNode(cc)) { generic = cc.getText(); } else if (ts.isIdentifier(cc)) { identifier = cc.getText(); } }); if (identifier != null && generic != null) { identifierGenericMap[identifier] = generic; } } }); return identifierGenericMap; } /** * Iterate over all functions in the docs. */ export function foreachDocFunction( docHeadings: DocHeading[], fn: (docFunction: DocFunction) => void) { docHeadings.forEach(heading => { if (heading.subheadings == null) { return; } heading.subheadings.forEach(subheading => { if (subheading.symbols == null) { return; } subheading.symbols.forEach(untypedSymbol => { if (untypedSymbol['isClass']) { const symbol = untypedSymbol as DocClass; symbol.methods.forEach(method => { fn(method); }); } else { fn(untypedSymbol as DocFunction); } }); }); }); } /** * Iterate over all classes in the docs. */ export function foreachDocClass( docHeadings: DocHeading[], fn: (docClass: DocClass) => void) { docHeadings.forEach(heading => { if (heading.subheadings == null) { return; } heading.subheadings.forEach(subheading => { if (subheading.symbols == null) { return; } subheading.symbols.forEach(untypedSymbol => { if (untypedSymbol['isClass']) { fn(untypedSymbol as DocClass); } }); }); }); } /** * Replace all types with their aliases. e.g. ShapeMap[R2] => number[] */ export function replaceDocTypeAliases( docHeadings: DocHeading[], docTypeAliases: {[type: string]: string}) { foreachDocFunction(docHeadings, docFunction => { docFunction.parameters.forEach(param => { param.type = replaceDocTypeAlias(param.type, docTypeAliases); }); docFunction.returnType = replaceDocTypeAlias(docFunction.returnType, docTypeAliases); }); } export function replaceDocTypeAlias( docTypeString: string, docTypeAliases: {[type: string]: string}): string { Object.keys(docTypeAliases).forEach(type => { if (docTypeString.indexOf(type) !== -1) { const re = new RegExp('\\b' + type + '\\b(\\[.+\\])?', 'g'); docTypeString = docTypeString.replace(re, docTypeAliases[type]); } }); return docTypeString; } export function inlineTypes( docHeadings: DocHeading[], types: {[typeName: string]: string}) { Object.keys(types).forEach(typeName => { const re = getSymbolReplaceRegex(typeName, false /** isMarkdown */); foreachDocFunction(docHeadings, docFunction => { docFunction.parameters.forEach(param => { param.type = param.type.replace(re, types[typeName]); }); }); foreachDocClass(docHeadings, docClass => { if (docClass.extraTypes) { docClass.extraTypes.forEach(extraType => { if (extraType.params) { extraType.params.forEach(param => { param.type = param.type.replace(re, types[typeName]); }); } }); } }); foreachDocFunction(docHeadings, foreachDocFunction => { if (foreachDocFunction.unpackedReturnTypes) { foreachDocFunction.unpackedReturnTypes.forEach(returnType => { if (returnType.params) { returnType.params.forEach(param => { param.type = param.type.replace(re, types[typeName]); }); } }); } }); }); } export interface SymbolAndUrl { // How the symbol should be referred to in other locations in docs. referenceName: string; // The name of the symbol, no namespaces. symbolName: string; url: string; type: 'function'|'class'|'method'; toplevelNamespace?: string; } /** * Adds markdown links for reference symbols in documentation, parameter * types, and return types. Uses @doclink aliases to link displayed symbols to * another symbol's documentation. */ export function linkSymbols( docs: Docs, symbols: SymbolAndUrl[], toplevelNamespace: string, docLinkAliases: {[symbolName: string]: string}) { // Find all the symbols. docs.headings.forEach(heading => { heading.subheadings.forEach(subheading => { subheading.symbols.forEach(symbol => { const namespace = (symbol.namespace != null && symbol.namespace != '' ? symbol.namespace + '.' : ''); if (toplevelNamespace.length > 0) { symbol.displayName = toplevelNamespace + '.' + namespace + symbol.symbolName; } else { symbol.displayName = namespace + symbol.symbolName } const referenceName = namespace + symbol.symbolName; symbol.urlHash = (symbol['isClass'] ? 'class:' : '') + referenceName; symbols.push({ referenceName, symbolName: symbol.symbolName, url: '#' + symbol.urlHash, type: symbol['isClass'] != null ? 'class' : 'function', toplevelNamespace }); if (symbol['isClass'] != null) { const docClass = symbol as DocClass; docClass.methods.forEach(method => { method.urlHash = docClass.displayName + '.' + method.symbolName; symbols.push({ referenceName: referenceName + '.' + method.symbolName, symbolName: method.symbolName, url: '#' + method.urlHash, type: 'method', toplevelNamespace }); }); } }); }); }); // Add new doc link alias symbols. Object.keys(docLinkAliases).forEach(docLinkAlias => { // Find the symbol so we can find the url hash. symbols.forEach(symbol => { if (symbol.symbolName === docLinkAliases[docLinkAlias]) { symbols.push({ symbolName: docLinkAlias, referenceName: docLinkAlias, url: symbol.url, type: symbol.type, toplevelNamespace: symbol.toplevelNamespace }); } }); }); // Replace class documentation with links. docs.headings.forEach(heading => { heading.subheadings.forEach(subheading => { subheading.symbols.forEach(symbol => { if (symbol['isClass']) { symbol.documentation = replaceSymbolsWithLinks( symbol.documentation, symbols, true /** isMarkdown */); const classSymbol = symbol as DocClass; if (classSymbol.inheritsFrom != null) { classSymbol.inheritsFrom = replaceSymbolsWithLinks( classSymbol.inheritsFrom, symbols, false /** isMarkdown */, true /** replaceFromSymbolName */); } } }); }); }); foreachDocFunction(docs.headings, method => { method.documentation = replaceSymbolsWithLinks( method.documentation, symbols, true /** isMarkdown */); // Since automatic types do not have namespaces, we must replace using // just the symbol names. method.returnType = replaceSymbolsWithLinks( method.returnType, symbols, false /** isMarkdown */, true /** replaceFromSymbolName */); method.parameters.forEach(param => { param.documentation = replaceSymbolsWithLinks( param.documentation, symbols, true /** isMarkdown */); param.type = replaceSymbolsWithLinks( param.type, symbols, false /** isMarkdown */, true /** replaceFromSymbolName */); }); }); } /** * Replaces symbols wrapped in backticks with links to the documentation for * that symbol. * * @param input The input string to replace over. Can be markdown, a type, or * any other documentation string. * @param symbolsAndUrls The symbols and URLs used to make replacements. * @param isMarkdown Whether the input is markdown. When using markdown input, * we expect replace the symbol wrapped in backticks. When not using markdown * input, we just replace any symbols wrapped by word boundaries. * @param replaceFromSymbolName Whether to replace from the just the symbol name * (no "tf" or namespace prefix) or the fully qualified reference name (with the * "tf" and namespace prefixes). */ function replaceSymbolsWithLinks( input: string, symbolsAndUrls: SymbolAndUrl[], isMarkdown: boolean, replaceFromSymbolName = false): string { symbolsAndUrls.forEach(symbolAndUrl => { let symbolName: string; if (replaceFromSymbolName) { symbolName = symbolAndUrl.symbolName; } else { if (symbolAndUrl.toplevelNamespace != null) { symbolName = symbolAndUrl.toplevelNamespace + '.' + symbolAndUrl.referenceName; } else { symbolName = symbolAndUrl.referenceName; } } const re = getSymbolReplaceRegex(symbolName, isMarkdown); let displayText = (symbolAndUrl.toplevelNamespace != null ? symbolAndUrl.toplevelNamespace + '.' : '') + symbolAndUrl.referenceName; if (symbolAndUrl.type === 'function' || symbolAndUrl.type === 'method') { displayText += '()'; } input = input.replace(re, `[${displayText}](${symbolAndUrl.url})`); }); return input; } function getSymbolReplaceRegex(symbolName: string, isMarkdown: boolean) { const wrapper = isMarkdown ? '\`' : '\\b(?![\'\:])'; const re = new RegExp(wrapper + symbolName + wrapper, 'g'); return re; } export function hasSpreadOperator(symbol: ts.Symbol) { return symbol.valueDeclaration != null && symbol.valueDeclaration.getText().startsWith('...'); } /** * In typescript 3.x ts.displayPartsToString(symbol.getDocumentationComment()) * will not strip * from the start of a comment line in a code fence * e.g. * ```js * // the stars at the * // start of these lines * // will be part of the output *``` * This function will strip * at the start of lines of the input string */ export function removeStarsFromCommentString(input: string) { if (input != null) { const lines = input.split('\n'); const regex = /^(\s*\*\s?)/; const stripped = lines.map(l => l.replace(regex, '')); return stripped.join('\n'); } return input; }
the_stack
import { ProjectSyncMetadataModel } from "@plasmicapp/code-merger"; import axios, { AxiosError } from "axios"; import socketio from "socket.io-client"; import { AuthConfig, CodeConfig, DEFAULT_HOST, ImagesConfig, StyleConfig, } from "./utils/config-utils"; import { HandledError } from "./utils/error"; import { Metadata } from "./utils/get-context"; export class AppServerError extends Error { constructor(message: string) { super(message); } } export interface ComponentBundle { renderModule: string; skeletonModule: string; cssRules: string; renderModuleFileName: string; skeletonModuleFileName: string; cssFileName: string; componentName: string; id: string; scheme: string; nameInIdToUuid: Array<[string, string]>; isPage: boolean; plumeType?: string; } export interface GlobalVariantBundle { id: string; name: string; contextModule: string; contextFileName: string; } export interface JsBundleTheme { themeFileName: string; themeModule: string; bundleName: string; } export interface ProjectMetaBundle { projectId: string; projectName: string; cssFileName: string; cssRules: string; jsBundleThemes?: JsBundleTheme[]; } export interface IconBundle { id: string; name: string; module: string; fileName: string; } export interface ImageBundle { id: string; name: string; blob: string; fileName: string; } export interface ProjectVersionMeta { projectId: string; projectApiToken: string; version: string; projectName: string; componentIds: string[]; dependencies: { [projectId: string]: string; }; indirect: boolean; } export interface VersionResolution { projects: ProjectVersionMeta[]; dependencies: ProjectVersionMeta[]; conflicts: ProjectVersionMeta[]; } export interface RequiredPackages { "@plasmicapp/loader": string; "@plasmicapp/cli": string; "@plasmicapp/react-web": string; "@plasmicapp/react-web-runtime": string; } export interface ProjectBundle { components: ComponentBundle[]; codeComponentMetas: CodeComponentMeta[]; projectConfig: ProjectMetaBundle; globalVariants: GlobalVariantBundle[]; usedTokens: StyleTokensMap; iconAssets: IconBundle[]; imageAssets: ImageBundle[]; checksums: ChecksumBundle; usedNpmPackages: string[]; externalCssImports: string[]; } export type ProjectMeta = Omit<ProjectBundle, "projectConfig">; export interface StyleConfigResponse { defaultStyleCssFileName: string; defaultStyleCssRules: string; } export interface StyleTokensMap { props: { name: string; type: string; value: string | number; meta: { projectId: string; id: string; }; }[]; global: { meta: { source: "plasmic.app"; }; }; } export interface ChecksumBundle { // List of checksums as [ComponentBundle.id, checksum] renderModuleChecksums: Array<[string, string]>; // List of checksums as [ComponentBundle.id, checksum] cssRulesChecksums: Array<[string, string]>; // List of checksums as [imageBundle.id, checksum] imageChecksums: Array<[string, string]>; // List of checksums as [IconBundle.id, checksum] iconChecksums: Array<[string, string]>; // List of checksums as [GlobalVariant.id, checksum] globalVariantChecksums: Array<[string, string]>; // Checksum of projectCss file projectCssChecksum: string; } export interface CodeComponentMeta { id: string; // component uuid name: string; importPath: string; } export interface ProjectIconsResponse { version: string; icons: IconBundle[]; } export interface ProjectIdAndToken { projectId: string; projectApiToken?: string; } export class PlasmicApi { constructor(private auth: AuthConfig) {} async genStyleConfig(styleOpts?: StyleConfig): Promise<StyleConfigResponse> { const result = await this.post( `${this.codegenHost}/api/v1/code/style-config`, styleOpts ); return result.data as StyleConfigResponse; } /** * Sync resolution - Given a fuzzy idea of what the user wants, * (i.e. a versionRange and component names), * ask the server for the exact references for a later call to `projectComponents` * - For components specified in the parameters - the server will return the latest version that satisfies the versionRange * - Any conflicting versions will be returned in `conflicts`, and should cause the client's sync to abort * @param projects * @param recursive */ async resolveSync( projects: { projectId: string; versionRange?: string; componentIdOrNames: readonly string[] | undefined; projectApiToken?: string; }[], recursive?: boolean ): Promise<VersionResolution> { const resp: any = await this.post( `${this.codegenHost}/api/v1/code/resolve-sync`, { projects, recursive, } ); const versionResolution = resp.data as VersionResolution; return { ...versionResolution }; } async getCurrentUser() { return await axios.get(`${this.studioHost}/api/v1/auth/self`, { headers: this.makeHeaders(), }); } async requiredPackages(): Promise<RequiredPackages> { const resp = await this.post( `${this.codegenHost}/api/v1/code/required-packages` ); return { ...resp.data } as RequiredPackages; } /** * Code-gen endpoint. * This will fetch components at an exact specified version. * If you don't know what version should be used, call `resolveSync` first. * @param projectId * @param cliVersion * @param reactWebVersion * @param newCompScheme * @param existingCompScheme * @param componentIdOrNames * @param version */ async projectComponents( projectId: string, opts: { platform: string; newCompScheme: "blackbox" | "direct"; // The list of existing components as [componentUuid, codeScheme] existingCompScheme: Array<[string, "blackbox" | "direct"]>; componentIdOrNames: readonly string[] | undefined; version: string; imageOpts: ImagesConfig; stylesOpts: StyleConfig; codeOpts: CodeConfig; checksums: ChecksumBundle; indirect: boolean; metadata?: Metadata; } ): Promise<ProjectBundle> { const result = await this.post( `${this.codegenHost}/api/v1/projects/${projectId}/code/components`, { ...opts, } ); return result.data as ProjectBundle; } async uploadBundle( projectId: string, bundleName: string, bundleJs: string, css: string[], metaJson: string, genModulePath: string | undefined, genCssPaths: string[], pkgVersion: string | undefined, extraPropMetaJson: string | undefined, themeProviderWrapper: string | undefined, themeModule: string | undefined ): Promise<StyleTokensMap> { const result = await this.post( `${this.codegenHost}/api/v1/projects/${projectId}/jsbundle/upload`, { projectId, bundleName, bundleJs, css, metaJson, genModulePath, genCssPaths, pkgVersion, extraPropMetaJson, themeProviderWrapper, themeModule, } ); return result.data as StyleTokensMap; } async projectStyleTokens( projectId: string, versionRange?: string ): Promise<StyleTokensMap> { const result = await this.post( `${this.codegenHost}/api/v1/projects/${projectId}/code/tokens`, { versionRange } ); return result.data as StyleTokensMap; } async projectIcons( projectId: string, versionRange?: string, iconIds?: string[] ): Promise<ProjectIconsResponse> { const result = await this.post( `${this.codegenHost}/api/v1/projects/${projectId}/code/icons`, { versionRange, iconIds } ); return result.data as ProjectIconsResponse; } async projectSyncMetadata( projectId: string, revision: number, rethrowAppError: boolean ): Promise<ProjectSyncMetadataModel> { const result = await this.post( `${this.codegenHost}/api/v1/projects/${projectId}/code/project-sync-metadata`, { revision }, rethrowAppError ); return ProjectSyncMetadataModel.fromJson(result.data); } connectSocket(): SocketIOClient.Socket { const socket = socketio.connect(this.studioHost, { path: `/api/v1/socket`, transportOptions: { polling: { extraHeaders: this.makeHeaders(), }, }, }); return socket; } // If rethrowAppError is true, we will throw an exception with the error // message private async post(url: string, data?: any, rethrowAppError?: boolean) { try { return await axios.post( url, { projectIdsAndTokens: this.projectIdsAndTokens, ...data }, { headers: this.makeHeaders(), } ); } catch (e) { const error = e as AxiosError; const errorMsg = this.makeErrorMessage(error); if (rethrowAppError) { throw new AppServerError(errorMsg); } if (!errorMsg) { throw e; } throw new HandledError(errorMsg); } } private makeErrorMessage(error: AxiosError) { const response = error.response; if (!response) { return undefined; } if (response.status === 403) { return `Incorrect Plasmic credentials; please check your .plasmic.auth file or your project API tokens.`; } if (response.data?.error?.message) { return response.data.error.message; } else if (response.data) { return `Error: request failed with status code ${response.status}. The response is ${response.data}`; } else { return undefined; } } private makeHeaders() { const headers: Record<string, string> = { "x-plasmic-api-user": this.auth.user, "x-plasmic-api-token": this.auth.token, }; if (this.auth.basicAuthUser && this.auth.basicAuthPassword) { const authString = Buffer.from( `${this.auth.basicAuthUser}:${this.auth.basicAuthPassword}` ).toString("base64"); headers["Authorization"] = `Basic ${authString}`; } return headers; } private projectIdsAndTokens?: ProjectIdAndToken[]; attachProjectIdsAndTokens(idsAndTokens: ProjectIdAndToken[]) { this.projectIdsAndTokens = idsAndTokens; } private get studioHost() { return this.auth.host; } private get codegenHost() { if (!this.auth.host || this.auth.host === DEFAULT_HOST) { return "https://codegen.plasmic.app"; } else { return this.auth.host; } } }
the_stack
import * as $protobuf from 'protobufjs' /** Properties of a Metric. */ export interface IMetric { /** Metric xAdvance */ xAdvance?: number | null /** Metric xOffset */ xOffset?: number | null /** Metric yOffset */ yOffset?: number | null } /** Represents a Metric. */ export class Metric implements IMetric { /** * Constructs a new Metric. * @param [properties] Properties to set */ constructor(properties?: IMetric) /** Metric xAdvance. */ public xAdvance: number /** Metric xOffset. */ public xOffset: number /** Metric yOffset. */ public yOffset: number /** * Creates a new Metric instance using the specified properties. * @param [properties] Properties to set * @returns Metric instance */ public static create(properties?: IMetric): Metric /** * Encodes the specified Metric message. Does not implicitly {@link Metric.verify|verify} messages. * @param message Metric message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IMetric, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified Metric message, length delimited. Does not implicitly {@link Metric.verify|verify} messages. * @param message Metric message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IMetric, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a Metric message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Metric * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): Metric /** * Decodes a Metric message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Metric * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Metric /** * Verifies a Metric message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a Metric message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Metric */ public static fromObject(object: { [k: string]: any }): Metric /** * Creates a plain object from a Metric message. Also converts values to other types if specified. * @param message Metric * @param [options] Conversion options * @returns Plain object */ public static toObject( message: Metric, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this Metric to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of a GradientColor. */ export interface IGradientColor { /** GradientColor id */ id?: number | null /** GradientColor offset */ offset?: number | null /** GradientColor color */ color?: string | null } /** Represents a GradientColor. */ export class GradientColor implements IGradientColor { /** * Constructs a new GradientColor. * @param [properties] Properties to set */ constructor(properties?: IGradientColor) /** GradientColor id. */ public id: number /** GradientColor offset. */ public offset: number /** GradientColor color. */ public color: string /** * Creates a new GradientColor instance using the specified properties. * @param [properties] Properties to set * @returns GradientColor instance */ public static create(properties?: IGradientColor): GradientColor /** * Encodes the specified GradientColor message. Does not implicitly {@link GradientColor.verify|verify} messages. * @param message GradientColor message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IGradientColor, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified GradientColor message, length delimited. Does not implicitly {@link GradientColor.verify|verify} messages. * @param message GradientColor message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IGradientColor, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a GradientColor message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GradientColor * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): GradientColor /** * Decodes a GradientColor message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GradientColor * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited( reader: $protobuf.Reader | Uint8Array, ): GradientColor /** * Verifies a GradientColor message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a GradientColor message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GradientColor */ public static fromObject(object: { [k: string]: any }): GradientColor /** * Creates a plain object from a GradientColor message. Also converts values to other types if specified. * @param message GradientColor * @param [options] Conversion options * @returns Plain object */ public static toObject( message: GradientColor, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this GradientColor to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of a Gradient. */ export interface IGradient { /** Gradient type */ type?: number | null /** Gradient angle */ angle?: number | null /** Gradient palette */ palette?: IGradientColor[] | null } /** Represents a Gradient. */ export class Gradient implements IGradient { /** * Constructs a new Gradient. * @param [properties] Properties to set */ constructor(properties?: IGradient) /** Gradient type. */ public type: number /** Gradient angle. */ public angle: number /** Gradient palette. */ public palette: IGradientColor[] /** * Creates a new Gradient instance using the specified properties. * @param [properties] Properties to set * @returns Gradient instance */ public static create(properties?: IGradient): Gradient /** * Encodes the specified Gradient message. Does not implicitly {@link Gradient.verify|verify} messages. * @param message Gradient message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IGradient, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified Gradient message, length delimited. Does not implicitly {@link Gradient.verify|verify} messages. * @param message Gradient message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IGradient, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a Gradient message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Gradient * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): Gradient /** * Decodes a Gradient message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Gradient * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Gradient /** * Verifies a Gradient message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a Gradient message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Gradient */ public static fromObject(object: { [k: string]: any }): Gradient /** * Creates a plain object from a Gradient message. Also converts values to other types if specified. * @param message Gradient * @param [options] Conversion options * @returns Plain object */ public static toObject( message: Gradient, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this Gradient to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of a PatternTexture. */ export interface IPatternTexture { /** PatternTexture buffer */ buffer?: Uint8Array | null /** PatternTexture scale */ scale?: number | null /** PatternTexture repetition */ repetition?: string | null } /** Represents a PatternTexture. */ export class PatternTexture implements IPatternTexture { /** * Constructs a new PatternTexture. * @param [properties] Properties to set */ constructor(properties?: IPatternTexture) /** PatternTexture buffer. */ public buffer: Uint8Array /** PatternTexture scale. */ public scale: number /** PatternTexture repetition. */ public repetition: string /** * Creates a new PatternTexture instance using the specified properties. * @param [properties] Properties to set * @returns PatternTexture instance */ public static create(properties?: IPatternTexture): PatternTexture /** * Encodes the specified PatternTexture message. Does not implicitly {@link PatternTexture.verify|verify} messages. * @param message PatternTexture message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IPatternTexture, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified PatternTexture message, length delimited. Does not implicitly {@link PatternTexture.verify|verify} messages. * @param message PatternTexture message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IPatternTexture, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a PatternTexture message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PatternTexture * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): PatternTexture /** * Decodes a PatternTexture message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PatternTexture * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited( reader: $protobuf.Reader | Uint8Array, ): PatternTexture /** * Verifies a PatternTexture message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a PatternTexture message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PatternTexture */ public static fromObject(object: { [k: string]: any }): PatternTexture /** * Creates a plain object from a PatternTexture message. Also converts values to other types if specified. * @param message PatternTexture * @param [options] Conversion options * @returns Plain object */ public static toObject( message: PatternTexture, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this PatternTexture to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of a Fill. */ export interface IFill { /** Fill type */ type?: number | null /** Fill color */ color?: string | null /** Fill gradient */ gradient?: IGradient | null /** Fill patternTexture */ patternTexture?: IPatternTexture | null /** Fill width */ width?: number | null /** Fill lineCap */ lineCap?: string | null /** Fill lineJoin */ lineJoin?: string | null } /** Represents a Fill. */ export class Fill implements IFill { /** * Constructs a new Fill. * @param [properties] Properties to set */ constructor(properties?: IFill) /** Fill type. */ public type: number /** Fill color. */ public color: string /** Fill gradient. */ public gradient?: IGradient | null /** Fill patternTexture. */ public patternTexture?: IPatternTexture | null /** Fill width. */ public width: number /** Fill lineCap. */ public lineCap: string /** Fill lineJoin. */ public lineJoin: string /** * Creates a new Fill instance using the specified properties. * @param [properties] Properties to set * @returns Fill instance */ public static create(properties?: IFill): Fill /** * Encodes the specified Fill message. Does not implicitly {@link Fill.verify|verify} messages. * @param message Fill message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IFill, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified Fill message, length delimited. Does not implicitly {@link Fill.verify|verify} messages. * @param message Fill message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IFill, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a Fill message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Fill * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): Fill /** * Decodes a Fill message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Fill * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Fill /** * Verifies a Fill message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a Fill message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Fill */ public static fromObject(object: { [k: string]: any }): Fill /** * Creates a plain object from a Fill message. Also converts values to other types if specified. * @param message Fill * @param [options] Conversion options * @returns Plain object */ public static toObject( message: Fill, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this Fill to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of a Font. */ export interface IFont { /** Font font */ font?: Uint8Array | null /** Font family */ family?: string | null /** Font size */ size?: number | null /** Font lineHeight */ lineHeight?: number | null } /** Represents a Font. */ export class Font implements IFont { /** * Constructs a new Font. * @param [properties] Properties to set */ constructor(properties?: IFont) /** Font font. */ public font: Uint8Array /** Font family. */ public family: string /** Font size. */ public size: number /** Font lineHeight. */ public lineHeight: number /** * Creates a new Font instance using the specified properties. * @param [properties] Properties to set * @returns Font instance */ public static create(properties?: IFont): Font /** * Encodes the specified Font message. Does not implicitly {@link Font.verify|verify} messages. * @param message Font message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IFont, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified Font message, length delimited. Does not implicitly {@link Font.verify|verify} messages. * @param message Font message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IFont, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a Font message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Font * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): Font /** * Decodes a Font message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Font * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Font /** * Verifies a Font message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a Font message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Font */ public static fromObject(object: { [k: string]: any }): Font /** * Creates a plain object from a Font message. Also converts values to other types if specified. * @param message Font * @param [options] Conversion options * @returns Plain object */ public static toObject( message: Font, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this Font to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of a GlyphFont. */ export interface IGlyphFont { /** GlyphFont letter */ letter?: string | null /** GlyphFont adjustMetric */ adjustMetric?: IMetric | null /** GlyphFont kerning */ kerning?: { [k: string]: number } | null } /** Represents a GlyphFont. */ export class GlyphFont implements IGlyphFont { /** * Constructs a new GlyphFont. * @param [properties] Properties to set */ constructor(properties?: IGlyphFont) /** GlyphFont letter. */ public letter: string /** GlyphFont adjustMetric. */ public adjustMetric?: IMetric | null /** GlyphFont kerning. */ public kerning: { [k: string]: number } /** * Creates a new GlyphFont instance using the specified properties. * @param [properties] Properties to set * @returns GlyphFont instance */ public static create(properties?: IGlyphFont): GlyphFont /** * Encodes the specified GlyphFont message. Does not implicitly {@link GlyphFont.verify|verify} messages. * @param message GlyphFont message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IGlyphFont, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified GlyphFont message, length delimited. Does not implicitly {@link GlyphFont.verify|verify} messages. * @param message GlyphFont message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IGlyphFont, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a GlyphFont message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GlyphFont * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): GlyphFont /** * Decodes a GlyphFont message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GlyphFont * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited( reader: $protobuf.Reader | Uint8Array, ): GlyphFont /** * Verifies a GlyphFont message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a GlyphFont message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GlyphFont */ public static fromObject(object: { [k: string]: any }): GlyphFont /** * Creates a plain object from a GlyphFont message. Also converts values to other types if specified. * @param message GlyphFont * @param [options] Conversion options * @returns Plain object */ public static toObject( message: GlyphFont, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this GlyphFont to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of a GlyphImage. */ export interface IGlyphImage { /** GlyphImage letter */ letter?: string | null /** GlyphImage adjustMetric */ adjustMetric?: IMetric | null /** GlyphImage buffer */ buffer?: Uint8Array | null /** GlyphImage fileName */ fileName?: string | null /** GlyphImage fileType */ fileType?: string | null /** GlyphImage selected */ selected?: boolean | null /** GlyphImage kerning */ kerning?: { [k: string]: number } | null } /** Represents a GlyphImage. */ export class GlyphImage implements IGlyphImage { /** * Constructs a new GlyphImage. * @param [properties] Properties to set */ constructor(properties?: IGlyphImage) /** GlyphImage letter. */ public letter: string /** GlyphImage adjustMetric. */ public adjustMetric?: IMetric | null /** GlyphImage buffer. */ public buffer: Uint8Array /** GlyphImage fileName. */ public fileName: string /** GlyphImage fileType. */ public fileType: string /** GlyphImage selected. */ public selected: boolean /** GlyphImage kerning. */ public kerning: { [k: string]: number } /** * Creates a new GlyphImage instance using the specified properties. * @param [properties] Properties to set * @returns GlyphImage instance */ public static create(properties?: IGlyphImage): GlyphImage /** * Encodes the specified GlyphImage message. Does not implicitly {@link GlyphImage.verify|verify} messages. * @param message GlyphImage message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IGlyphImage, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified GlyphImage message, length delimited. Does not implicitly {@link GlyphImage.verify|verify} messages. * @param message GlyphImage message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IGlyphImage, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a GlyphImage message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GlyphImage * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): GlyphImage /** * Decodes a GlyphImage message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GlyphImage * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited( reader: $protobuf.Reader | Uint8Array, ): GlyphImage /** * Verifies a GlyphImage message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a GlyphImage message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GlyphImage */ public static fromObject(object: { [k: string]: any }): GlyphImage /** * Creates a plain object from a GlyphImage message. Also converts values to other types if specified. * @param message GlyphImage * @param [options] Conversion options * @returns Plain object */ public static toObject( message: GlyphImage, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this GlyphImage to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of a Layout. */ export interface ILayout { /** Layout padding */ padding?: number | null /** Layout spacing */ spacing?: number | null /** Layout power */ power?: boolean | null } /** Represents a Layout. */ export class Layout implements ILayout { /** * Constructs a new Layout. * @param [properties] Properties to set */ constructor(properties?: ILayout) /** Layout padding. */ public padding: number /** Layout spacing. */ public spacing: number /** Layout power. */ public power: boolean /** * Creates a new Layout instance using the specified properties. * @param [properties] Properties to set * @returns Layout instance */ public static create(properties?: ILayout): Layout /** * Encodes the specified Layout message. Does not implicitly {@link Layout.verify|verify} messages. * @param message Layout message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: ILayout, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified Layout message, length delimited. Does not implicitly {@link Layout.verify|verify} messages. * @param message Layout message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: ILayout, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a Layout message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Layout * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): Layout /** * Decodes a Layout message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Layout * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Layout /** * Verifies a Layout message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a Layout message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Layout */ public static fromObject(object: { [k: string]: any }): Layout /** * Creates a plain object from a Layout message. Also converts values to other types if specified. * @param message Layout * @param [options] Conversion options * @returns Plain object */ public static toObject( message: Layout, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this Layout to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of a Shadow. */ export interface IShadow { /** Shadow color */ color?: string | null /** Shadow blur */ blur?: number | null /** Shadow offsetX */ offsetX?: number | null /** Shadow offsetY */ offsetY?: number | null } /** Represents a Shadow. */ export class Shadow implements IShadow { /** * Constructs a new Shadow. * @param [properties] Properties to set */ constructor(properties?: IShadow) /** Shadow color. */ public color: string /** Shadow blur. */ public blur: number /** Shadow offsetX. */ public offsetX: number /** Shadow offsetY. */ public offsetY: number /** * Creates a new Shadow instance using the specified properties. * @param [properties] Properties to set * @returns Shadow instance */ public static create(properties?: IShadow): Shadow /** * Encodes the specified Shadow message. Does not implicitly {@link Shadow.verify|verify} messages. * @param message Shadow message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IShadow, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified Shadow message, length delimited. Does not implicitly {@link Shadow.verify|verify} messages. * @param message Shadow message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IShadow, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a Shadow message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Shadow * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): Shadow /** * Decodes a Shadow message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Shadow * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Shadow /** * Verifies a Shadow message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a Shadow message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Shadow */ public static fromObject(object: { [k: string]: any }): Shadow /** * Creates a plain object from a Shadow message. Also converts values to other types if specified. * @param message Shadow * @param [options] Conversion options * @returns Plain object */ public static toObject( message: Shadow, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this Shadow to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of a Style. */ export interface IStyle { /** Style font */ font?: IFont | null /** Style fill */ fill?: IFill | null /** Style useStroke */ useStroke?: boolean | null /** Style stroke */ stroke?: IFill | null /** Style useShadow */ useShadow?: boolean | null /** Style shadow */ shadow?: IShadow | null /** Style bgColor */ bgColor?: string | null } /** Represents a Style. */ export class Style implements IStyle { /** * Constructs a new Style. * @param [properties] Properties to set */ constructor(properties?: IStyle) /** Style font. */ public font?: IFont | null /** Style fill. */ public fill?: IFill | null /** Style useStroke. */ public useStroke: boolean /** Style stroke. */ public stroke?: IFill | null /** Style useShadow. */ public useShadow: boolean /** Style shadow. */ public shadow?: IShadow | null /** Style bgColor. */ public bgColor: string /** * Creates a new Style instance using the specified properties. * @param [properties] Properties to set * @returns Style instance */ public static create(properties?: IStyle): Style /** * Encodes the specified Style message. Does not implicitly {@link Style.verify|verify} messages. * @param message Style message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IStyle, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified Style message, length delimited. Does not implicitly {@link Style.verify|verify} messages. * @param message Style message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IStyle, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a Style message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Style * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): Style /** * Decodes a Style message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Style * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Style /** * Verifies a Style message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a Style message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Style */ public static fromObject(object: { [k: string]: any }): Style /** * Creates a plain object from a Style message. Also converts values to other types if specified. * @param message Style * @param [options] Conversion options * @returns Plain object */ public static toObject( message: Style, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this Style to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of an Ui. */ export interface IUi { /** Ui previewText */ previewText?: string | null } /** Represents an Ui. */ export class Ui implements IUi { /** * Constructs a new Ui. * @param [properties] Properties to set */ constructor(properties?: IUi) /** Ui previewText. */ public previewText: string /** * Creates a new Ui instance using the specified properties. * @param [properties] Properties to set * @returns Ui instance */ public static create(properties?: IUi): Ui /** * Encodes the specified Ui message. Does not implicitly {@link Ui.verify|verify} messages. * @param message Ui message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IUi, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified Ui message, length delimited. Does not implicitly {@link Ui.verify|verify} messages. * @param message Ui message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IUi, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes an Ui message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Ui * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): Ui /** * Decodes an Ui message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Ui * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Ui /** * Verifies an Ui message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates an Ui message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Ui */ public static fromObject(object: { [k: string]: any }): Ui /** * Creates a plain object from an Ui message. Also converts values to other types if specified. * @param message Ui * @param [options] Conversion options * @returns Plain object */ public static toObject( message: Ui, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this Ui to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } } /** Properties of a Project. */ export interface IProject { /** Project id */ id?: number | Long | null /** Project name */ name?: string | null /** Project text */ text?: string | null /** Project glyphs */ glyphs?: { [k: string]: IGlyphFont } | null /** Project glyphImages */ glyphImages?: IGlyphImage[] | null /** Project style */ style?: IStyle | null /** Project layout */ layout?: ILayout | null /** Project globalAdjustMetric */ globalAdjustMetric?: IMetric | null /** Project ui */ ui?: IUi | null } /** Represents a Project. */ export class Project implements IProject { /** * Constructs a new Project. * @param [properties] Properties to set */ constructor(properties?: IProject) /** Project id. */ public id: number | Long /** Project name. */ public name: string /** Project text. */ public text: string /** Project glyphs. */ public glyphs: { [k: string]: IGlyphFont } /** Project glyphImages. */ public glyphImages: IGlyphImage[] /** Project style. */ public style?: IStyle | null /** Project layout. */ public layout?: ILayout | null /** Project globalAdjustMetric. */ public globalAdjustMetric?: IMetric | null /** Project ui. */ public ui?: IUi | null /** * Creates a new Project instance using the specified properties. * @param [properties] Properties to set * @returns Project instance */ public static create(properties?: IProject): Project /** * Encodes the specified Project message. Does not implicitly {@link Project.verify|verify} messages. * @param message Project message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode( message: IProject, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Encodes the specified Project message, length delimited. Does not implicitly {@link Project.verify|verify} messages. * @param message Project message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited( message: IProject, writer?: $protobuf.Writer, ): $protobuf.Writer /** * Decodes a Project message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Project * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( reader: $protobuf.Reader | Uint8Array, length?: number, ): Project /** * Decodes a Project message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Project * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Project /** * Verifies a Project message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): string | null /** * Creates a Project message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Project */ public static fromObject(object: { [k: string]: any }): Project /** * Creates a plain object from a Project message. Also converts values to other types if specified. * @param message Project * @param [options] Conversion options * @returns Plain object */ public static toObject( message: Project, options?: $protobuf.IConversionOptions, ): { [k: string]: any } /** * Converts this Project to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any } }
the_stack