text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
* @fileoverview Implements the a base mixin for CommonMsubsup, CommonMunderover * and their relatives. (Since munderover can become msubsup * when movablelimits is set, munderover needs to be able to * do the same thing as msubsup in some cases.) * * @author dpvc@mathjax.org (Davide Cervone) */ import {AnyWrapper, WrapperConstructor, Constructor, AnyWrapperClass} from '../Wrapper.js'; import {CommonMo} from './mo.js'; import {CommonMunderover} from './munderover.js'; import {MmlMsubsup} from '../../../core/MmlTree/MmlNodes/msubsup.js'; import {MmlMo} from '../../../core/MmlTree/MmlNodes/mo.js'; import {BBox} from '../../../util/BBox.js'; import {DIRECTION} from '../FontData.js'; /*****************************************************************/ /** * The CommonScriptbase interface * * @template W The child-node Wrapper class */ export interface CommonScriptbase<W extends AnyWrapper> extends AnyWrapper { /** * The core mi or mo of the base (or the base itself if there isn't one) */ readonly baseCore: W; /** * The base element's wrapper */ readonly baseChild: W; /** * The relative scaling of the base compared to the munderover/msubsup */ readonly baseScale: number; /** * The italic correction of the base (if any) */ readonly baseIc: number; /** * True if base italic correction should be removed (msub and msubsup or mathaccents) */ readonly baseRemoveIc: boolean; /** * True if the base is a single character */ readonly baseIsChar: boolean; /** * True if the base has an accent under or over */ readonly baseHasAccentOver: boolean; readonly baseHasAccentUnder: boolean; /** * True if this is an overline or underline */ readonly isLineAbove: boolean; readonly isLineBelow: boolean; /** * True if this is an msup with script that is a math accent */ readonly isMathAccent: boolean; /** * The script element's wrapper (overridden in subclasses) */ readonly scriptChild: W; /***************************************************************************/ /* * Methods for information about the core element for the base */ /** * @return {W} The wrapper for the base core mi or mo (or whatever) */ getBaseCore(): W; /** * @return {W} The base fence item or null */ getSemanticBase(): W; /** * Recursively retrieves an element for a given fencepointer. * * @param {W} fence The potential fence. * @param {string} id The fencepointer id. * @return {W} The original fence the scripts belong to. */ getBaseFence(fence: W, id: string): W; /** * @return {number} The scaling factor for the base core relative to the munderover/msubsup */ getBaseScale(): number; /** * The base's italic correction (properly scaled) */ getBaseIc(): number; /** * An adjusted italic correction (for slightly better results) */ getAdjustedIc(): number; /** * @return {boolean} True if the base is an mi, mn, or mo (not a largeop) consisting of * a single unstretched character */ isCharBase(): boolean; /** * Determine if the under- and overscripts are under- or overlines. */ checkLineAccents(): void; /** * @param {W} script The script node to check for being a line */ isLineAccent(script: W): boolean; /***************************************************************************/ /* * Methods for sub-sup nodes */ /** * @return {number} The base child's width without the base italic correction (if not needed) */ getBaseWidth(): number; /** * Get the shift for the script (implemented in subclasses) * * @return {number[]} The horizontal and vertical offsets for the script */ getOffset(): number[]; /** * @param {number} n The value to use if the base isn't a (non-large-op, unstretched) char * @return {number} Either n or 0 */ baseCharZero(n: number): number; /** * Get the shift for a subscript (TeXBook Appendix G 18ab) * * @return {number} The vertical offset for the script */ getV(): number; /** * Get the shift for a superscript (TeXBook Appendix G 18acd) * * @return {number} The vertical offset for the script */ getU(): number; /***************************************************************************/ /* * Methods for under-over nodes */ /** * @return {boolean} True if the base has movablelimits (needed by munderover) */ hasMovableLimits(): boolean; /** * Get the separation and offset for overscripts (TeXBoox Appendix G 13, 13a) * * @param {BBox} basebox The bounding box of the base * @param {BBox} overbox The bounding box of the overscript * @return {number[]} The separation between their boxes, and the offset of the overscript */ getOverKU(basebox: BBox, overbox: BBox): number[]; /** * Get the separation and offset for underscripts (TeXBoox Appendix G 13, 13a) * * @param {BBox} basebox The bounding box of the base * @param {BBox} underbox The bounding box of the underscript * @return {number[]} The separation between their boxes, and the offset of the underscript */ getUnderKV(basebox: BBox, underbox: BBox): number[]; /** * @param {BBox[]} boxes The bounding boxes whose offsets are to be computed * @param {number[]=} delta The initial x offsets of the boxes * @return {number[]} The actual offsets needed to center the boxes in the stack */ getDeltaW(boxes: BBox[], delta?: number[]): number[]; /** * @param {boolean=} noskew Whether to ignore the skew amount * @return {number} The offset for under and over */ getDelta(noskew?: boolean): number; /** * Handle horizontal stretching of children to match greatest width * of all children */ stretchChildren(): void; } export interface CommonScriptbaseClass extends AnyWrapperClass { /** * Set to true for munderover/munder/mover/msup (Appendix G 13) */ useIC: boolean; } /** * Shorthand for the CommonScriptbase constructor * * @template W The child-node Wrapper class */ export type ScriptbaseConstructor<W extends AnyWrapper> = Constructor<CommonScriptbase<W>>; /*****************************************************************/ /** * A base class for msup/msub/msubsup and munder/mover/munderover * wrapper mixin implementations * * @template W The child-node Wrapper class * @template T The Wrapper class constructor type */ export function CommonScriptbaseMixin< W extends AnyWrapper, T extends WrapperConstructor >(Base: T): ScriptbaseConstructor<W> & T { return class extends Base { /** * Set to false for msubsup/msub (Appendix G 13) */ public static useIC: boolean = true; /** * The core mi or mo of the base (or the base itself if there isn't one) */ public baseCore: W; /** * The base element's wrapper */ public baseScale: number = 1; /** * The relative scaling of the base compared to the munderover/msubsup */ public baseIc: number = 0; /** * True if base italic correction should be removed (msub and msubsup or mathaccents) */ public baseRemoveIc: boolean = false; /** * True if the base is a single character */ public baseIsChar: boolean = false; /** * True if the base has an accent under or over */ public baseHasAccentOver: boolean = null; public baseHasAccentUnder: boolean = null; /** * True if this is an overline or underline */ public isLineAbove: boolean = false; public isLineBelow: boolean = false; /** * True if this is an msup with script that is a math accent */ public isMathAccent: boolean = false; /** * @return {W} The base element's wrapper */ public get baseChild(): W { return this.childNodes[(this.node as MmlMsubsup).base]; } /** * @return {W} The script element's wrapper (overridden in subclasses) */ public get scriptChild(): W { return this.childNodes[1]; } /** * @override */ constructor(...args: any[]) { super(...args); // // Find the base core // const core = this.baseCore = this.getBaseCore(); if (!core) return; // // Get information about the base element // this.setBaseAccentsFor(core); this.baseScale = this.getBaseScale(); this.baseIc = this.getBaseIc(); this.baseIsChar = this.isCharBase(); // // Determine if we are setting a mathaccent // this.isMathAccent = this.baseIsChar && (this.scriptChild && !!this.scriptChild.coreMO().node.getProperty('mathaccent')) as boolean; // // Check for overline/underline accents // this.checkLineAccents(); // // Check if the base is a mi or mo that needs italic correction removed // this.baseRemoveIc = !this.isLineAbove && !this.isLineBelow && (!(this.constructor as CommonScriptbaseClass).useIC || this.isMathAccent); } /***************************************************************************/ /* * Methods for information about the core element for the base */ /** * @return {W} The wrapper for the base core mi or mo (or whatever) */ public getBaseCore(): W { let core = this.getSemanticBase() || this.childNodes[0]; while (core && ((core.childNodes.length === 1 && (core.node.isKind('mrow') || core.node.isKind('TeXAtom') || core.node.isKind('mstyle') || core.node.isKind('mpadded') || core.node.isKind('mphantom') || core.node.isKind('semantics'))) || (core.node.isKind('munderover') && core.isMathAccent))) { this.setBaseAccentsFor(core); core = core.childNodes[0]; } if (!core) { this.baseHasAccentOver = this.baseHasAccentUnder = false; } return core || this.childNodes[0]; } /** * @param {W} core The element to check for accents */ public setBaseAccentsFor(core: W) { if (core.node.isKind('munderover')) { if (this.baseHasAccentOver === null) { this.baseHasAccentOver = !!core.node.attributes.get('accent'); } if (this.baseHasAccentUnder === null) { this.baseHasAccentUnder = !!core.node.attributes.get('accentunder'); } } } /** * @return {W} The base fence item or null */ public getSemanticBase(): W { let fence = this.node.attributes.getExplicit('data-semantic-fencepointer') as string; return this.getBaseFence(this.baseChild, fence); } /** * Recursively retrieves an element for a given fencepointer. * * @param {W} fence The potential fence. * @param {string} id The fencepointer id. * @return {W} The original fence the scripts belong to. */ public getBaseFence(fence: W, id: string): W { if (!fence || !fence.node.attributes || !id) { return null; } if (fence.node.attributes.getExplicit('data-semantic-id') === id) { return fence; } for (const child of fence.childNodes) { const result = this.getBaseFence(child, id); if (result) { return result; } } return null; } /** * @return {number} The scaling factor for the base core relative to the munderover/msubsup */ public getBaseScale(): number { let child = this.baseCore as any; let scale = 1; while (child && child !== this) { const bbox = child.getBBox(); scale *= bbox.rscale; child = child.parent; } return scale; } /** * The base's italic correction (properly scaled) */ public getBaseIc(): number { return this.baseCore.getBBox().ic * this.baseScale; } /** * An adjusted italic correction (for slightly better results) */ public getAdjustedIc(): number { const bbox = this.baseCore.getBBox(); return (bbox.ic ? 1.05 * bbox.ic + .05 : 0) * this.baseScale; } /** * @return {boolean} True if the base is an mi, mn, or mo consisting of a single character */ public isCharBase(): boolean { let base = this.baseCore; return (((base.node.isKind('mo') && (base as any).size === null) || base.node.isKind('mi') || base.node.isKind('mn')) && base.bbox.rscale === 1 && Array.from(base.getText()).length === 1); } /** * Determine if the under- and overscripts are under- or overlines. */ public checkLineAccents() { if (!this.node.isKind('munderover')) return; if (this.node.isKind('mover')) { this.isLineAbove = this.isLineAccent(this.scriptChild); } else if (this.node.isKind('munder')) { this.isLineBelow = this.isLineAccent(this.scriptChild); } else { const mml = this as unknown as CommonMunderover<W>; this.isLineAbove = this.isLineAccent(mml.overChild); this.isLineBelow = this.isLineAccent(mml.underChild); } } /** * @param {W} script The script node to check for being a line * @return {boolean} True if the script is U+2015 */ public isLineAccent(script: W): boolean { const node = script.coreMO().node; return (node.isToken && (node as MmlMo).getText() === '\u2015'); } /***************************************************************************/ /* * Methods for sub-sup nodes */ /** * @return {number} The base child's width without the base italic correction (if not needed) */ public getBaseWidth(): number { const bbox = this.baseChild.getBBox(); return bbox.w * bbox.rscale - (this.baseRemoveIc ? this.baseIc : 0) + this.font.params.extra_ic; } /** * This gives the common bbox for msub and msup. It is overridden * for all the others (msubsup, munder, mover, munderover). * * @override */ public computeBBox(bbox: BBox, recompute: boolean = false) { const w = this.getBaseWidth(); const [x, y] = this.getOffset(); bbox.append(this.baseChild.getBBox()); bbox.combine(this.scriptChild.getBBox(), w + x, y); bbox.w += this.font.params.scriptspace; bbox.clean(); this.setChildPWidths(recompute); } /** * Get the shift for the script (implemented in subclasses) * * @return {[number, number]} The horizontal and vertical offsets for the script */ public getOffset(): [number, number] { return [0, 0]; } /** * @param {number} n The value to use if the base isn't a (non-large-op, unstretched) char * @return {number} Either n or 0 */ public baseCharZero(n: number): number { const largeop = !!this.baseCore.node.attributes.get('largeop'); const scale = this.baseScale; return (this.baseIsChar && !largeop && scale === 1 ? 0 : n); } /** * Get the shift for a subscript (TeXBook Appendix G 18ab) * * @return {number} The vertical offset for the script */ public getV(): number { const bbox = this.baseCore.getBBox(); const sbox = this.scriptChild.getBBox(); const tex = this.font.params; const subscriptshift = this.length2em(this.node.attributes.get('subscriptshift'), tex.sub1); return Math.max( this.baseCharZero(bbox.d * this.baseScale + tex.sub_drop * sbox.rscale), subscriptshift, sbox.h * sbox.rscale - (4 / 5) * tex.x_height ); } /** * Get the shift for a superscript (TeXBook Appendix G 18acd) * * @return {number} The vertical offset for the script */ public getU(): number { const bbox = this.baseCore.getBBox(); const sbox = this.scriptChild.getBBox(); const tex = this.font.params; const attr = this.node.attributes.getList('displaystyle', 'superscriptshift'); const prime = this.node.getProperty('texprimestyle'); const p = prime ? tex.sup3 : (attr.displaystyle ? tex.sup1 : tex.sup2); const superscriptshift = this.length2em(attr.superscriptshift, p); return Math.max( this.baseCharZero(bbox.h * this.baseScale - tex.sup_drop * sbox.rscale), superscriptshift, sbox.d * sbox.rscale + (1 / 4) * tex.x_height ); } /***************************************************************************/ /* * Methods for under-over nodes */ /** * @return {boolean} True if the base has movablelimits (needed by munderover) */ public hasMovableLimits(): boolean { const display = this.node.attributes.get('displaystyle'); const mo = this.baseChild.coreMO().node; return (!display && !!mo.attributes.get('movablelimits')); } /** * Get the separation and offset for overscripts (TeXBoox Appendix G 13, 13a) * * @param {BBox} basebox The bounding box of the base * @param {BBox} overbox The bounding box of the overscript * @return {[number, number]} The separation between their boxes, and the offset of the overscript */ public getOverKU(basebox: BBox, overbox: BBox): [number, number] { const accent = this.node.attributes.get('accent') as boolean; const tex = this.font.params; const d = overbox.d * overbox.rscale; const t = tex.rule_thickness * tex.separation_factor; const delta = (this.baseHasAccentOver ? t : 0); const T = (this.isLineAbove ? 3 * tex.rule_thickness : t); const k = (accent ? T : Math.max(tex.big_op_spacing1, tex.big_op_spacing3 - Math.max(0, d))) - delta; return [k, basebox.h * basebox.rscale + k + d]; } /** * Get the separation and offset for underscripts (TeXBoox Appendix G 13, 13a) * * @param {BBox} basebox The bounding box of the base * @param {BBox} underbox The bounding box of the underscript * @return {[number, number]} The separation between their boxes, and the offset of the underscript */ public getUnderKV(basebox: BBox, underbox: BBox): [number, number] { const accent = this.node.attributes.get('accentunder') as boolean; const tex = this.font.params; const h = underbox.h * underbox.rscale; const t = tex.rule_thickness * tex.separation_factor; const delta = (this.baseHasAccentUnder ? t : 0); const T = (this.isLineBelow ? 3 * tex.rule_thickness : t); const k = (accent ? T : Math.max(tex.big_op_spacing2, tex.big_op_spacing4 - h)) - delta; return [k, -(basebox.d * basebox.rscale + k + h)]; } /** * @param {BBox[]} boxes The bounding boxes whose offsets are to be computed * @param {number[]=} delta The initial x offsets of the boxes * @return {number[]} The actual offsets needed to center the boxes in the stack */ public getDeltaW(boxes: BBox[], delta: number[] = [0, 0, 0]): number[] { const align = this.node.attributes.get('align'); const widths = boxes.map(box => box.w * box.rscale); widths[0] -= (this.baseRemoveIc && !this.baseCore.node.attributes.get('largeop') ? this.baseIc : 0); const w = Math.max(...widths); const dw = [] as number[]; let m = 0; for (const i of widths.keys()) { dw[i] = (align === 'center' ? (w - widths[i]) / 2 : align === 'right' ? w - widths[i] : 0) + delta[i]; if (dw[i] < m) { m = -dw[i]; } } if (m) { for (const i of dw.keys()) { dw[i] += m; } } [1, 2].map(i => dw[i] += (boxes[i] ? boxes[i].dx * boxes[0].scale : 0)); return dw; } /** * @param {boolean=} noskew Whether to ignore the skew amount * @return {number} The offset for under and over */ public getDelta(noskew: boolean = false): number { const accent = this.node.attributes.get('accent'); const {sk, ic} = this.baseCore.getBBox(); return ((accent && !noskew ? sk : 0) + this.font.skewIcFactor * ic) * this.baseScale; } /** * Handle horizontal stretching of children to match greatest width * of all children */ public stretchChildren() { let stretchy: AnyWrapper[] = []; // // Locate and count the stretchy children // for (const child of this.childNodes) { if (child.canStretch(DIRECTION.Horizontal)) { stretchy.push(child); } } let count = stretchy.length; let nodeCount = this.childNodes.length; if (count && nodeCount > 1) { let W = 0; // // If all the children are stretchy, find the largest one, // otherwise, find the width of the non-stretchy children. // let all = (count > 1 && count === nodeCount); for (const child of this.childNodes) { const noStretch = (child.stretch.dir === DIRECTION.None); if (all || noStretch) { const {w, rscale} = child.getBBox(noStretch); if (w * rscale > W) W = w * rscale; } } // // Stretch the stretchable children // for (const child of stretchy) { (child.coreMO() as CommonMo).getStretchedVariant([W / child.bbox.rscale]); } } } }; }
the_stack
import {NiFiExecutionNodeConfiguration} from "../../../../../model/nifi-execution-node-configuration"; import {NiFiTimerUnit} from "../../../../../model/nifi-timer-unit"; import {AbstractControl, FormControl, FormGroup, ValidatorFn, Validators} from "@angular/forms"; import {Component, Input, OnDestroy, OnInit, ViewContainerRef} from "@angular/core"; import {Feed} from "../../../../../model/feed/feed.model"; import {NiFiClusterStatus} from "../../../../../model/nifi-cluster-status"; import {TdDialogService} from "@covalent/core/dialogs"; import {NiFiService} from "../../../../../services/NiFiService"; import {FeedConstants} from "../../../../../services/FeedConstants"; import * as _ from "underscore"; import {FeedPreconditionDialogService} from "../../../../../shared/feed-precondition/feed-precondition-dialog-service"; import {CloneUtil} from "../../../../../../common/utils/clone-util"; @Component({ selector: "feed-schedule", templateUrl: "./feed-schedule.component.html" }) export class FeedScheduleComponent implements OnInit, OnDestroy{ @Input() public feed:Feed; @Input() public editable:boolean; @Input() public parentForm:FormGroup; public scheduleForm:FormGroup; /** * All possible schedule strategies * @type {*[]} */ allScheduleStrategies: any = []; /** * Array of strategies filtered for this feed * @type {any[]} */ scheduleStrategies: any[] = []; /** * Indicates that NiFi is clustered. * @type {boolean} */ isClustered: boolean = false; /** * Indicates that NiFi supports the execution node property. * @type {boolean} */ supportsExecutionNode: boolean = false; /** * copy of the preconditions that will be modified and applied back to the feed on save */ preconditions:any[]; /** * NiFi Timer Units * @type {NiFiTimerUnit[]} */ public nifiTimerUnits: NiFiTimerUnit[] = [ {value: 'days', description: 'Days'}, {value: 'hrs', description: 'Hours'}, {value: 'min', description: 'Minutes'}, {value: 'sec', description: 'Seconds'} ]; /** * NiFi Execution Node Configuration * @type {NiFiExecutionNodeConfiguration[]} */ public nifiExecutionNodeConfigurations: NiFiExecutionNodeConfiguration[] = [ {value: 'ALL', description: 'All nodes'}, {value: 'PRIMARY', description: 'Primary node'}, ]; constructor( private nifiService: NiFiService, private dialogService: TdDialogService, private preconditionDialogService: FeedPreconditionDialogService, private _viewContainerRef:ViewContainerRef) { this.scheduleForm = new FormGroup({}); this.allScheduleStrategies = Object.keys(FeedConstants.SCHEDULE_STRATEGIES).map(key => FeedConstants.SCHEDULE_STRATEGIES[key]) let cronExpressionValue = FeedConstants.DEFAULT_CRON; let cronExpressionControl = new FormControl(cronExpressionValue, [Validators.required]); this.scheduleForm.registerControl("cronExpression", cronExpressionControl); } ngOnInit(){ this.detectNiFiClusterStatus(); if(this.parentForm){ this.parentForm.registerControl("scheduleForm",this.scheduleForm); } this.preconditions = this.feed.schedule.preconditions != undefined ? this.feed.schedule.preconditions : []; this.initializFormControls(); this.updateScheduleStrategies(); } ngOnDestroy() { } /** * Check for the form control value and set it to the incoming value if present * @param {string} formControlName * @param value * @return {boolean} true if the control exists and was set, false if not */ private checkAndSetValue(formControlName:string,value:any):boolean { let control = this.scheduleForm.get(formControlName); if(control) { control.setValue(value); } return control != undefined; } /** * Check if the given control and validationKey has an error * @param {string} name * @param {string} check * @return {boolean} */ hasError(name:string,check:string){ let control = this.scheduleForm.get(name); if(control){ return control.hasError(check); } else { return false; } } private initializFormControls(){ if(!this.checkAndSetValue("scheduleStrategy",this.feed.schedule.schedulingStrategy)) { let scheduleStrategyControl = new FormControl(this.feed.schedule.schedulingStrategy, [Validators.required]); scheduleStrategyControl.valueChanges.subscribe(value => { this.registerFormControls(); }) this.scheduleForm.registerControl("scheduleStrategy", scheduleStrategyControl); } this.registerFormControls(); } /** * register form controls with the feed values */ private registerFormControls(){ let cronExpressionValue = FeedConstants.DEFAULT_CRON; let timerAmountValue = 5; let timerUnitsValue = 'min'; if (this.feed.schedule.schedulingStrategy == FeedConstants.SCHEDULE_STRATEGIES.TIMER_DRIVEN.value || this.feed.schedule.schedulingStrategy === FeedConstants.SCHEDULE_STRATEGIES.PRIMARY_NODE_ONLY.value) { cronExpressionValue = FeedConstants.DEFAULT_CRON; timerAmountValue = this.parseTimerAmount(); timerUnitsValue = this.parseTimerUnits(); } else if(this.feed.schedule.schedulingStrategy == FeedConstants.SCHEDULE_STRATEGIES.CRON_DRIVEN.value){ cronExpressionValue = this.feed.schedule.schedulingPeriod; } this.checkAndSetValue("cronExpression",cronExpressionValue); if(!this.checkAndSetValue("timerAmount",timerAmountValue)) { let timerAmountFormControl = new FormControl(timerAmountValue, [ Validators.required, this.timerAmountValidator(this.feed.registeredTemplate != undefined ? this.feed.registeredTemplate.isStream : false), //TODO pass in the 'isStream' flag when selecting a template for a new feed and populate or push it on the feed object for this check Validators.min(0) ]); this.scheduleForm.registerControl("timerAmount", timerAmountFormControl); } if(!this.checkAndSetValue("timerUnits",timerUnitsValue)) { let timerUnitsFormControl = new FormControl(timerUnitsValue, [Validators.required]); this.scheduleForm.registerControl("timerUnits", timerUnitsFormControl) } if(this.isTriggerDriven()) { let preconditions = this.preconditions.map(precondition => precondition.propertyValuesDisplayString).join(","); if(!this.checkAndSetValue("preconditions",preconditions)){ this.scheduleForm.addControl("preconditions", new FormControl(preconditions,[Validators.required])); } } else { if(this.scheduleForm.contains("preconditions")){ this.scheduleForm.removeControl("preconditions"); } } } /** * Show alert for a rapid timer for batch feed. * @param ev */ private showBatchTimerAlert(ev?: any) { this.dialogService.openAlert({ message: 'Warning: This is a batch-type feed, and scheduling for a very fast timer is not permitted. Please modify the timer amount to a non-zero value.', disableClose: true, title: 'Warning: Rapid Timer (Batch Feed)', closeButton: 'Close', width: '200 px', }); } public timerChanged(){ } /** * Save the form back to the feed */ updateModel(): Feed{ let formModel = this.scheduleForm.value; let scheduleStrategyValue = this.scheduleForm.get("scheduleStrategy").value; this.feed.schedule.schedulingStrategy = formModel.scheduleStrategy; if(this.isCronDriven()){ this.feed.schedule.schedulingPeriod = formModel.cronExpression; } else if(this.isTriggerDriven()) { this.feed.schedule.preconditions = this.preconditions; } else { this.feed.schedule.schedulingPeriod = formModel.timerAmount+" "+formModel.timerUnits; } return this.feed; } /** * Resets the form with the feed values * @param {Feed} feed */ reset(feed:Feed){ this.preconditions = this.feed.schedule.preconditions != undefined ? this.feed.schedule.preconditions : []; this.registerFormControls(); } /** * Get info on NiFi clustering */ private detectNiFiClusterStatus() { this.nifiService.getNiFiClusterStatus().subscribe((nifiClusterStatus: NiFiClusterStatus) => { if (nifiClusterStatus.clustered != null) { this.isClustered = nifiClusterStatus.clustered; } else { this.isClustered = false; } if (nifiClusterStatus.version != null) { this.supportsExecutionNode = ((this.isClustered) && (!nifiClusterStatus.version.match(/^0\.|^1\.0/))); } else { this.supportsExecutionNode = false; } }); } /** * returns the timer amount numeric value (i.e. for 5 hrs it will return 5) * @return {number} */ private parseTimerAmount() : number { return parseInt(this.feed.schedule.schedulingPeriod); } /** * returns the timer units (i.e. for 5 hrs it will return 'hrs') * @return {string} */ private parseTimerUnits() : string { let timerUnits = "min" var startIndex = this.feed.schedule.schedulingPeriod.indexOf(" "); if (startIndex != -1) { timerUnits = this.feed.schedule.schedulingPeriod.substring(startIndex + 1); } return timerUnits; } /** * Different templates have different schedule strategies. * Filter out those that are not needed based upon the template */ private updateScheduleStrategies() { this.scheduleStrategies = _.filter(this.allScheduleStrategies, (strategy: any) => { if (this.feed && this.feed.registeredTemplate && this.feed.registeredTemplate.allowPreconditions) { return (strategy.value === FeedConstants.SCHEDULE_STRATEGIES.TRIGGER_DRIVEN.value); } else if (strategy.value === FeedConstants.SCHEDULE_STRATEGIES.PRIMARY_NODE_ONLY.value) { return (this.isClustered && !this.supportsExecutionNode); } else { return (strategy.value !== FeedConstants.SCHEDULE_STRATEGIES.TRIGGER_DRIVEN.value); } }); let currentStrategy = this.getScheduleStrategy(); if(this.scheduleStrategies.find((strategy:any) => strategy.value ==currentStrategy ) == undefined){ this.resetScheduleStrategy(); } } private showPreconditionDialog(index: any) { this.preconditionDialogService.openDialog({feed: this.feed, preconditions:this.preconditions, itemIndex: index}, this._viewContainerRef).subscribe((preconditions:any[]) => { let preconditionsString =preconditions.map(precondition => precondition.name).join(","); this.checkAndSetValue("preconditions",preconditionsString) this.preconditions = preconditions; }); } /** * Validates the inputs are good */ public validate() { if(this.feed) { if (FeedConstants.SCHEDULE_STRATEGIES.TRIGGER_DRIVEN.value == this.feed.schedule.schedulingStrategy) { return this.preconditions.length >0; } else if (!this.editable) { this.feed.schedule.schedulingPeriod != null } else { return this.scheduleForm.valid; } } else { return false; } } /** * Custom validator for timer amount * @param {boolean} isStreamingFeed * @returns {ValidatorFn} */ private timerAmountValidator(isStreamingFeed: boolean): ValidatorFn { return (control: AbstractControl): { [key: string]: boolean } | null => { if (isStreamingFeed === false && control.value != null && control.value == 0) { return { 'batchFeedRequiresNonZeroTimerAmount': true }; } return null; } }; private resetScheduleStrategy(){ let scheduleStrategy = this.scheduleForm.get("scheduleStrategy"); if(scheduleStrategy) { scheduleStrategy.setValue(null); } } private getScheduleStrategy(){ let scheduleStrategy = this.scheduleForm.get("scheduleStrategy"); if(scheduleStrategy) { return scheduleStrategy.value }else { return null; // return FeedConstants.SCHEDULE_STRATEGIES.CRON_DRIVEN.value; } } public isCronDriven() :boolean { return FeedConstants.SCHEDULE_STRATEGIES.CRON_DRIVEN.value == this.getScheduleStrategy() } public isTimerDriven():boolean { return FeedConstants.SCHEDULE_STRATEGIES.TIMER_DRIVEN.value == this.getScheduleStrategy() } public isPrimaryNodeOnly():boolean { return FeedConstants.SCHEDULE_STRATEGIES.PRIMARY_NODE_ONLY.value == this.getScheduleStrategy() } public isTriggerDriven():boolean { return FeedConstants.SCHEDULE_STRATEGIES.TRIGGER_DRIVEN.value == this.getScheduleStrategy() } }
the_stack
module android.R{ import Resources = android.content.res.Resources; import Color = android.graphics.Color; import Drawable = android.graphics.drawable.Drawable; import InsetDrawable = android.graphics.drawable.InsetDrawable; import ColorDrawable = android.graphics.drawable.ColorDrawable; import LayerDrawable = android.graphics.drawable.LayerDrawable; import RotateDrawable = android.graphics.drawable.RotateDrawable; import ScaleDrawable = android.graphics.drawable.ScaleDrawable; import AnimationDrawable = android.graphics.drawable.AnimationDrawable; import StateListDrawable = android.graphics.drawable.StateListDrawable; import RoundRectDrawable = android.graphics.drawable.RoundRectDrawable; import ShadowDrawable = android.graphics.drawable.ShadowDrawable; import Gravity = android.view.Gravity; const density = Resources.getDisplayMetrics().density; export class drawable{ static get btn_default():Drawable { let stateList = new StateListDrawable(); stateList.addState([-android.view.View.VIEW_STATE_WINDOW_FOCUSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_default_normal_holo_light); stateList.addState([-android.view.View.VIEW_STATE_WINDOW_FOCUSED, -android.view.View.VIEW_STATE_ENABLED], R.image.btn_default_disabled_holo_light); stateList.addState([android.view.View.VIEW_STATE_PRESSED], R.image.btn_default_pressed_holo_light); stateList.addState([android.view.View.VIEW_STATE_FOCUSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_default_focused_holo_light); stateList.addState([android.view.View.VIEW_STATE_ENABLED], R.image.btn_default_normal_holo_light); stateList.addState([android.view.View.VIEW_STATE_FOCUSED], R.image.btn_default_disabled_focused_holo_light); stateList.addState([], R.image.btn_default_disabled_holo_light); return stateList; } static get editbox_background():Drawable { let stateList = new StateListDrawable(); stateList.addState([android.view.View.VIEW_STATE_FOCUSED], R.image.editbox_background_focus_yellow); stateList.addState([], R.image.editbox_background_normal); return stateList; } static get btn_check():Drawable { let stateList = new StateListDrawable(); //Enabled states stateList.addState([android.view.View.VIEW_STATE_CHECKED, -android.view.View.VIEW_STATE_WINDOW_FOCUSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_check_on_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, -android.view.View.VIEW_STATE_WINDOW_FOCUSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_check_off_holo_light); stateList.addState([android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_PRESSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_check_on_pressed_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_PRESSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_check_off_pressed_holo_light); stateList.addState([android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_FOCUSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_check_on_focused_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_FOCUSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_check_off_focused_holo_light); stateList.addState([android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_check_on_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_check_off_holo_light); //Disabled states stateList.addState([android.view.View.VIEW_STATE_CHECKED, -android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_check_on_disabled_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, -android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_check_off_disabled_holo_light); stateList.addState([android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_FOCUSED], R.image.btn_check_on_disabled_focused_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_FOCUSED], R.image.btn_check_off_disabled_focused_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED], R.image.btn_check_off_disabled_holo_light); stateList.addState([android.view.View.VIEW_STATE_CHECKED], R.image.btn_check_on_disabled_holo_light); return stateList; } static get btn_radio():Drawable { let stateList = new StateListDrawable(); //Enabled states stateList.addState([android.view.View.VIEW_STATE_CHECKED, -android.view.View.VIEW_STATE_WINDOW_FOCUSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_radio_on_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, -android.view.View.VIEW_STATE_WINDOW_FOCUSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_radio_off_holo_light); stateList.addState([android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_PRESSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_radio_on_pressed_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_PRESSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_radio_off_pressed_holo_light); stateList.addState([android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_FOCUSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_radio_on_focused_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_FOCUSED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_radio_off_focused_holo_light); stateList.addState([android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_radio_on_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_ENABLED], R.image.btn_radio_off_holo_light); //Disabled states stateList.addState([android.view.View.VIEW_STATE_CHECKED, -android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_radio_on_disabled_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, -android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_radio_off_disabled_holo_light); stateList.addState([android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_FOCUSED], R.image.btn_radio_on_disabled_focused_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED, android.view.View.VIEW_STATE_FOCUSED], R.image.btn_radio_off_disabled_focused_holo_light); stateList.addState([-android.view.View.VIEW_STATE_CHECKED], R.image.btn_radio_off_disabled_holo_light); stateList.addState([android.view.View.VIEW_STATE_CHECKED], R.image.btn_radio_on_disabled_holo_light); return stateList; } static get progress_small_holo():Drawable { let rotate1 = new RotateDrawable(null); rotate1.mState.mDrawable = R.image.spinner_16_outer_holo; rotate1.mState.mPivotXRel = true; rotate1.mState.mPivotX = 0.5; rotate1.mState.mPivotYRel = true; rotate1.mState.mPivotY = 0.5; rotate1.mState.mFromDegrees = 0; rotate1.mState.mToDegrees = 1080; let rotate2 = new RotateDrawable(null); rotate2.mState.mDrawable = R.image.spinner_16_inner_holo; rotate2.mState.mPivotXRel = true; rotate2.mState.mPivotX = 0.5; rotate2.mState.mPivotYRel = true; rotate2.mState.mPivotY = 0.5; rotate2.mState.mFromDegrees = 720; rotate2.mState.mToDegrees = 0; return new LayerDrawable([rotate1, rotate2]); } static get progress_medium_holo():Drawable { let rotate1 = new RotateDrawable(null); rotate1.mState.mDrawable = R.image.spinner_48_outer_holo; rotate1.mState.mPivotXRel = true; rotate1.mState.mPivotX = 0.5; rotate1.mState.mPivotYRel = true; rotate1.mState.mPivotY = 0.5; rotate1.mState.mFromDegrees = 0; rotate1.mState.mToDegrees = 1080; let rotate2 = new RotateDrawable(null); rotate2.mState.mDrawable = R.image.spinner_48_inner_holo; rotate2.mState.mPivotXRel = true; rotate2.mState.mPivotX = 0.5; rotate2.mState.mPivotYRel = true; rotate2.mState.mPivotY = 0.5; rotate2.mState.mFromDegrees = 720; rotate2.mState.mToDegrees = 0; return new LayerDrawable([rotate1, rotate2]); } static get progress_large_holo():Drawable { let rotate1 = new RotateDrawable(null); rotate1.mState.mDrawable = R.image.spinner_76_outer_holo; rotate1.mState.mPivotXRel = true; rotate1.mState.mPivotX = 0.5; rotate1.mState.mPivotYRel = true; rotate1.mState.mPivotY = 0.5; rotate1.mState.mFromDegrees = 0; rotate1.mState.mToDegrees = 1080; let rotate2 = new RotateDrawable(null); rotate2.mState.mDrawable = R.image.spinner_76_inner_holo; rotate2.mState.mPivotXRel = true; rotate2.mState.mPivotX = 0.5; rotate2.mState.mPivotYRel = true; rotate2.mState.mPivotY = 0.5; rotate2.mState.mFromDegrees = 720; rotate2.mState.mToDegrees = 0; return new LayerDrawable([rotate1, rotate2]); } static get progress_horizontal_holo():Drawable { let layerDrawable = new LayerDrawable(null); let returnHeight = ()=> 3 * density; let insetTopBottom = Math.floor(8 * density); let bg = new ColorDrawable(0x4c000000); bg.getIntrinsicHeight = returnHeight; layerDrawable.addLayer(bg, R.id.background, 0, insetTopBottom, 0, insetTopBottom); let secondary = new ScaleDrawable(new ColorDrawable(0x4c33b5e5), Gravity.LEFT, 1, -1); secondary.getIntrinsicHeight = returnHeight; layerDrawable.addLayer(secondary, R.id.secondaryProgress, 0, insetTopBottom, 0, insetTopBottom); let progress = new ScaleDrawable(new ColorDrawable(0xcc33b5e5), Gravity.LEFT, 1, -1); progress.getIntrinsicHeight = returnHeight; layerDrawable.addLayer(progress, R.id.progress, 0, insetTopBottom, 0, insetTopBottom); layerDrawable.ensurePadding(); layerDrawable.onStateChange(layerDrawable.getState()); return layerDrawable; } static get progress_indeterminate_horizontal_holo():Drawable { let animDrawable = new AnimationDrawable(); animDrawable.setOneShot(false); let frame = R.image.progressbar_indeterminate_holo1; frame.setCallback(animDrawable); animDrawable.addFrame(frame, 50); frame = R.image.progressbar_indeterminate_holo2; frame.setCallback(animDrawable); animDrawable.addFrame(frame, 50); frame = R.image.progressbar_indeterminate_holo3; frame.setCallback(animDrawable); animDrawable.addFrame(frame, 50); frame = R.image.progressbar_indeterminate_holo4; frame.setCallback(animDrawable); animDrawable.addFrame(frame, 50); frame = R.image.progressbar_indeterminate_holo5; frame.setCallback(animDrawable); animDrawable.addFrame(frame, 50); frame = R.image.progressbar_indeterminate_holo6; frame.setCallback(animDrawable); animDrawable.addFrame(frame, 50); frame = R.image.progressbar_indeterminate_holo7; frame.setCallback(animDrawable); animDrawable.addFrame(frame, 50); frame = R.image.progressbar_indeterminate_holo8; frame.setCallback(animDrawable); animDrawable.addFrame(frame, 50); return animDrawable; } static get ratingbar_full_empty_holo_light():Drawable { let stateList = new StateListDrawable(); stateList.addState([android.view.View.VIEW_STATE_PRESSED, android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_rating_star_off_pressed_holo_light); stateList.addState([android.view.View.VIEW_STATE_FOCUSED, android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_rating_star_off_pressed_holo_light); stateList.addState([android.view.View.VIEW_STATE_SELECTED, android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_rating_star_off_pressed_holo_light); //stateList.addState([android.view.View.VIEW_STATE_FOCUSED, android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_rating_star_off_focused_holo_light); //stateList.addState([android.view.View.VIEW_STATE_SELECTED, android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_rating_star_off_focused_holo_light); stateList.addState([], R.image.btn_rating_star_off_normal_holo_light); return stateList; } static get ratingbar_full_filled_holo_light():Drawable { let stateList = new StateListDrawable(); stateList.addState([android.view.View.VIEW_STATE_PRESSED, android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_rating_star_on_pressed_holo_light); stateList.addState([android.view.View.VIEW_STATE_FOCUSED, android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_rating_star_on_pressed_holo_light); stateList.addState([android.view.View.VIEW_STATE_SELECTED, android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_rating_star_on_pressed_holo_light); //stateList.addState([android.view.View.VIEW_STATE_FOCUSED, android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_rating_star_on_focused_holo_light); //stateList.addState([android.view.View.VIEW_STATE_SELECTED, android.view.View.VIEW_STATE_WINDOW_FOCUSED], R.image.btn_rating_star_on_focused_holo_light); stateList.addState([], R.image.btn_rating_star_on_normal_holo_light); return stateList; } static get ratingbar_full_holo_light():Drawable { let layerDrawable = new LayerDrawable(null); layerDrawable.addLayer(R.drawable.ratingbar_full_empty_holo_light, R.id.background); layerDrawable.addLayer(R.drawable.ratingbar_full_empty_holo_light, R.id.secondaryProgress); layerDrawable.addLayer(R.drawable.ratingbar_full_filled_holo_light, R.id.progress); layerDrawable.ensurePadding(); layerDrawable.onStateChange(layerDrawable.getState()); return layerDrawable; } static get ratingbar_holo_light():Drawable { let layerDrawable = new LayerDrawable(null); layerDrawable.addLayer(R.image.rate_star_big_off_holo_light, R.id.background); layerDrawable.addLayer(R.image.rate_star_big_half_holo_light, R.id.secondaryProgress); layerDrawable.addLayer(R.image.rate_star_big_on_holo_light, R.id.progress); layerDrawable.ensurePadding(); layerDrawable.onStateChange(layerDrawable.getState()); return layerDrawable; } static get ratingbar_small_holo_light():Drawable { let layerDrawable = new LayerDrawable(null); layerDrawable.addLayer(R.image.rate_star_small_off_holo_light, R.id.background); layerDrawable.addLayer(R.image.rate_star_small_half_holo_light, R.id.secondaryProgress); layerDrawable.addLayer(R.image.rate_star_small_on_holo_light, R.id.progress); layerDrawable.ensurePadding(); layerDrawable.onStateChange(layerDrawable.getState()); return layerDrawable; } static get scrubber_control_selector_holo():Drawable { let stateList = new StateListDrawable(); stateList.addState([-android.view.View.VIEW_STATE_ENABLED], R.image.scrubber_control_disabled_holo); stateList.addState([android.view.View.VIEW_STATE_PRESSED], R.image.scrubber_control_pressed_holo); stateList.addState([android.view.View.VIEW_STATE_SELECTED], R.image.scrubber_control_focused_holo); stateList.addState([], R.image.scrubber_control_normal_holo); return stateList; } static get scrubber_progress_horizontal_holo_light():Drawable { let layerDrawable = new LayerDrawable(null); layerDrawable.addLayer(R.drawable.scrubber_track_holo_light, R.id.background); let secondary = new ScaleDrawable(R.drawable.scrubber_secondary_holo, Gravity.LEFT, 1, -1); layerDrawable.addLayer(secondary, R.id.secondaryProgress); let progress = new ScaleDrawable(R.drawable.scrubber_primary_holo, Gravity.LEFT, 1, -1); layerDrawable.addLayer(progress, R.id.progress); layerDrawable.ensurePadding(); layerDrawable.onStateChange(layerDrawable.getState()); return layerDrawable; } static get scrubber_primary_holo():Drawable { let line = new ColorDrawable(0xff33b5e5); line.getIntrinsicHeight = ()=> 3 * density; return new InsetDrawable(line, 0, 5 * density, 0, 5 * density); } static get scrubber_secondary_holo():Drawable { let line = new ColorDrawable(0x4c33b5e5); line.getIntrinsicHeight = ()=> 3 * density; return new InsetDrawable(line, 0, 5 * density, 0, 5 * density); } static get scrubber_track_holo_light():Drawable { let line = new ColorDrawable(0x66666666); line.getIntrinsicHeight = ()=> 1 * density; return new InsetDrawable(line, 0, 6 * density, 0, 6 * density); } static get list_selector_background():Drawable { return this.item_background; } static get list_divider():Drawable { let divider = new ColorDrawable(0xffcccccc); return divider; } static get divider_vertical():Drawable { return this.divider_horizontal; } static get divider_horizontal():Drawable { let divider = new ColorDrawable(0xffdddddd); divider.getIntrinsicWidth = ()=> 1; divider.getIntrinsicHeight = ()=> 1; return divider; } static get item_background(){ let stateList = new StateListDrawable(); stateList.addState([android.view.View.VIEW_STATE_FOCUSED, -android.view.View.VIEW_STATE_ENABLED], new ColorDrawable(0xffebebeb)); stateList.addState([android.view.View.VIEW_STATE_FOCUSED, android.view.View.VIEW_STATE_PRESSED], new ColorDrawable(0x88888888)); stateList.addState([-android.view.View.VIEW_STATE_FOCUSED, android.view.View.VIEW_STATE_PRESSED], new ColorDrawable(0x88888888)); stateList.addState([android.view.View.VIEW_STATE_FOCUSED], new ColorDrawable(0xffaaaaaa)); stateList.addState([], new ColorDrawable(Color.TRANSPARENT)); return stateList; } static get toast_frame(){ let bg = new RoundRectDrawable(0xff333333, 2 * density, 2 * density, 2 * density, 2 * density); bg.getIntrinsicHeight = ()=> 32 * density; bg.getPadding = (rect)=>{ rect.set(12 * density, 6 * density, 12 * density, 6 * density); return true; }; let shadow = new ShadowDrawable(bg, 5 * density, 0, 2 * density, 0x44000000); return new InsetDrawable(shadow, 7 * density);//more space show shadow } } }
the_stack
import {Command, Notice, Plugin} from 'obsidian'; import {exec, ExecException, ExecOptions} from "child_process"; import {combineObjects, getOperatingSystem, getPluginAbsolutePath, getVaultAbsolutePath} from "./Common"; import {parseShellCommandVariables} from "./variables/parseShellCommandVariables"; import {RunMigrations} from "./Migrations"; import { newShellCommandConfiguration, ShellCommandsConfiguration } from "./settings/ShellCommandConfiguration"; import { getDefaultSettings, SettingsVersionString, ShellCommandsPluginSettings, } from "./settings/ShellCommandsPluginSettings"; import {ObsidianCommandsContainer} from "./ObsidianCommandsContainer"; import {ShellCommandsSettingsTab} from "./settings/ShellCommandsSettingsTab"; import * as path from "path"; import * as fs from "fs"; import {ConfirmExecutionModal} from "./ConfirmExecutionModal"; import {handleShellCommandOutput} from "./output_channels/OutputChannelDriverFunctions"; import {BaseEncodingOptions} from "fs"; import {TShellCommand, TShellCommandContainer} from "./TShellCommand"; import {getUsersDefaultShell, isShellSupported} from "./Shell"; import {TShellCommandTemporary} from "./TShellCommandTemporary"; import {versionCompare} from "./lib/version_compare"; import {debugLog, setDEBUG_ON} from "./Debug"; import {addCustomAutocompleteItems} from "./settings/setting_elements/Autocomplete"; export default class ShellCommandsPlugin extends Plugin { /** * Defines the settings structure version. Change this when a new plugin version is released, but only if that plugin * version introduces changes to the settings structure. Do not change if the settings structure stays unchanged. */ public static SettingsVersion: SettingsVersionString = "0.8.0"; settings: ShellCommandsPluginSettings; obsidian_commands: ObsidianCommandsContainer = {}; private t_shell_commands: TShellCommandContainer = {}; /** * Temporary holder for ShellCommandConfigurations whose variables are already parsed before the actual execution during command palette preview. * This array gets emptied after every shell command execution. * * @private */ private preparsed_t_shell_commands: TShellCommandContainer = {}; async onload() { debugLog('loading plugin'); // Load settings if (!await this.loadSettings()) { // Loading the settings has failed due to an unsupported settings file version. // The plugin should not be used, and it has actually disabled itself, but the code execution needs to be // stopped manually. return; } // Run possible configuration migrations await RunMigrations(this); // Generate TShellCommand objects from configuration (only after configuration migrations are done) this.loadTShellCommands(); // Make all defined shell commands to appear in the Obsidian command list let shell_commands = this.getTShellCommands(); for (let shell_command_id in shell_commands) { let t_shell_command = shell_commands[shell_command_id]; this.registerShellCommand(t_shell_command); } // Load a custom autocomplete list if it exists. this.loadCustomAutocompleteList(); this.addSettingTab(new ShellCommandsSettingsTab(this.app, this)); } private loadTShellCommands() { this.t_shell_commands = {}; let shell_command_configurations = this.getShellCommandConfigurations(); for (let shell_command_id in shell_command_configurations) { this.t_shell_commands[shell_command_id] = new TShellCommand(this, shell_command_id, shell_command_configurations[shell_command_id]); } } getTShellCommands() { return this.t_shell_commands; } private getShellCommandConfigurations(): ShellCommandsConfiguration { return this.settings.shell_commands; } /** * Creates a new shell command object and registers it to Obsidian's command palette, but does not save the modified * configuration to disk. To save the addition, call saveSettings(). */ public newTShellCommand() { const shell_command_id = this.generateNewShellCommandID(); const shell_command_configuration = newShellCommandConfiguration(); this.settings.shell_commands[shell_command_id] = shell_command_configuration; this.t_shell_commands[shell_command_id] = new TShellCommand(this, shell_command_id, shell_command_configuration); this.registerShellCommand(this.t_shell_commands[shell_command_id]); return this.t_shell_commands[shell_command_id]; } /** * @param t_shell_command */ private registerShellCommand(t_shell_command: TShellCommand) { let shell_command_id = t_shell_command.getId(); debugLog("Registering shell command #" + shell_command_id + "..."); let obsidian_command: Command = { id: this.generateObsidianCommandId(shell_command_id), name: this.generateObsidianCommandName(t_shell_command), // Use 'checkCallback' instead of normal 'callback' because we also want to get called when the command palette is opened. checkCallback: (is_opening_command_palette) => { if (is_opening_command_palette) { // The user is currently opening the command palette. // Do not execute the command yet, but parse variables for preview, if enabled in the settings. debugLog("Getting command palette preview for shell command #" + t_shell_command.getId()); if (this.settings.preview_variables_in_command_palette) { let preparsed_t_shell_command: TShellCommandTemporary = TShellCommandTemporary.fromTShellCommand(t_shell_command); // Clone t_shell_command so that we won't edit the original configuration. // Parse variables in the actual shell command let parsed_shell_command = parseShellCommandVariables(this, preparsed_t_shell_command.getShellCommand(), preparsed_t_shell_command.getShell()); if (Array.isArray(parsed_shell_command)) { // Variable parsing failed, because an array was returned, which contains error messages. // Just cancel the preview, the command will be shown with variable names. Discard the error messages. debugLog("Shell command preview: Variable parsing failed for shell command " + preparsed_t_shell_command.getShellCommand()); return true; } else { // Variable parsing succeeded. // Use the parsed values. preparsed_t_shell_command.getConfiguration().platform_specific_commands = {default: parsed_shell_command}; // Overrides all possible OS specific shell command versions. } // Also parse variables in an alias, in case the command has one. Variables in aliases do not do anything practical, but they can reveal the user what variables are used in the command. let parsed_alias = parseShellCommandVariables(this, preparsed_t_shell_command.getAlias(), preparsed_t_shell_command.getShell()); if (Array.isArray(parsed_alias)) { // Variable parsing failed, because an array was returned, which contains error messages. // Just cancel the preview, the alias will be shown with variable names. Discard the error messages. debugLog("Shell command preview: Variable parsing failed for alias " + preparsed_t_shell_command.getAlias()); return true; } else { // Variable parsing succeeded. // Use the parsed values. preparsed_t_shell_command.getConfiguration().alias = parsed_alias; } // Rename the command in command palette let prefix = this.getPluginName() + ": "; // Normally Obsidian prefixes all commands with the plugin name automatically, but now that we are actually _editing_ a command in the palette (not creating a new one), Obsidian won't do the prefixing for us. obsidian_command.name = prefix + this.generateObsidianCommandName(preparsed_t_shell_command); // Store the preparsed shell command so that we can use exactly the same values if the command gets later executed. this.preparsed_t_shell_commands[shell_command_id] = preparsed_t_shell_command; } return true; // Need to return true, otherwise the command would be left out from the command palette. } else { // The user has instructed to execute the command. // Check if we happen to have a preparsed command (= variables parsed at the time of opening the command palette) if (undefined === this.preparsed_t_shell_commands[shell_command_id]) { // No preparsed command. Execute a standard version of the command, and do variable parsing now. let parsed_shell_command = parseShellCommandVariables(this, t_shell_command.getShellCommand(), t_shell_command.getShell()); if (Array.isArray(parsed_shell_command)) { // The command could not be parsed correctly. // Display error messages this.newErrors(parsed_shell_command); } else { // The command was parsed correctly. this.confirmAndExecuteShellCommand(parsed_shell_command, t_shell_command); } } else { // We do have a preparsed version of this command. // No need to check if the parsing had previously succeeded, because if it would have failed, the command would not be in the preparsed commands' array. this.confirmAndExecuteShellCommand(this.preparsed_t_shell_commands[shell_command_id].getShellCommand(), t_shell_command); } // Delete the whole array of preparsed commands. Even though we only used just one command from it, we need to notice that opening a command // palette might generate multiple preparsed commands in the array, but as the user selects and executes only one command, all these temporary // commands are now obsolete. Delete them just in case the user toggles the variable preview feature off in the settings. We do not want to // execute obsolete commands accidentally. This deletion also needs to be done even if the executed command was not a preparsed command, because // even when preparsing is turned on in the settings, singular commands may fail to parse and therefore they would not be in this array, but other // commands might be. this.resetPreparsedShellCommandConfigurations(); } } }; this.addCommand(obsidian_command) this.obsidian_commands[shell_command_id] = obsidian_command; // Store the reference so that we can edit the command later in ShellCommandsSettingsTab if needed. debugLog("Registered.") } /** * Called when it's known that preparsed shell command variables have old data and should not be used later. */ resetPreparsedShellCommandConfigurations() { this.preparsed_t_shell_commands = {}; } /** * Called after turning "Preview variables in command palette" setting off, to make sure that all shell commands have {{variable}} names visible instead of their values. */ resetCommandPaletteNames() { let shell_commands = this.getTShellCommands(); for (let shell_command_id in shell_commands) { let t_shell_command = shell_commands[shell_command_id]; this.obsidian_commands[shell_command_id].name = this.generateObsidianCommandName(t_shell_command); } } generateObsidianCommandId(shell_command_id: string) { return "shell-command-" + shell_command_id; } generateObsidianCommandName(t_shell_command: TShellCommand) { let prefix = "Execute: "; if (t_shell_command.getAlias()) { // If an alias is set for the command, Obsidian's command palette should display the alias text instead of the actual command. return prefix + t_shell_command.getAlias(); } return prefix + t_shell_command.getShellCommand(); } /** * * @param shell_command The actual shell command that will be executed. * @param t_shell_command Used for reading other properties. t_shell_command.shell_command won't be used! */ confirmAndExecuteShellCommand(shell_command: string, t_shell_command: TShellCommand) { // Check if the command needs confirmation before execution if (t_shell_command.getConfirmExecution()) { // Yes, a confirmation is needed. // Open a confirmation modal. new ConfirmExecutionModal(this, shell_command, t_shell_command) .open() ; return; // Do not execute now. The modal will call executeShellCommand() later if needed. } else { // No need to confirm. // Execute. this.executeShellCommand(shell_command, t_shell_command); } } /** * Does not ask for confirmation before execution. This should only be called if: a) a confirmation is already asked from a user, or b) this command is defined not to need a confirmation. * Use confirmAndExecuteShellCommand() instead to have a confirmation asked before the execution. * * @param shell_command The actual shell command that will be executed. * @param t_shell_command Used for reading other properties. t_shell_command.shell_command won't be used! */ executeShellCommand(shell_command: string, t_shell_command: TShellCommand) { let working_directory = this.getWorkingDirectory(); // Check that the shell command is not empty shell_command = shell_command.trim(); if (!shell_command.length) { // It is empty debugLog("The shell command is empty. :("); this.newError("The shell command is empty :("); return; } // Check that the currently defined shell is supported by this plugin. If using system default shell, it's possible // that the shell is something that is not supported. Also, the settings file can be edited manually, and incorrect // shell can be written there. const shell = t_shell_command.getShell(); if (!isShellSupported(shell)) { debugLog("Shell is not supported: " + shell); this.newError("This plugin does not support the following shell: " + shell); return; } // Check that the working directory exists and is a folder if (!fs.existsSync(working_directory)) { // Working directory does not exist // Prevent execution debugLog("Working directory does not exist: " + working_directory); this.newError("Working directory does not exist: " + working_directory); } else if (!fs.lstatSync(working_directory).isDirectory()) { // Working directory is not a directory. // Prevent execution debugLog("Working directory exists but is not a folder: " + working_directory); this.newError("Working directory exists but is not a folder: " + working_directory); } else { // Working directory is OK // Prepare execution options let options: BaseEncodingOptions & ExecOptions = { "cwd": working_directory, "shell": shell, }; // Execute the shell command debugLog("Executing command " + shell_command + " in " + working_directory + "..."); exec(shell_command, options, (error: ExecException|null, stdout: string, stderr: string) => { if (null !== error) { // Some error occurred debugLog("Command executed and failed. Error number: " + error.code + ". Message: " + error.message); // Check if this error should be displayed to the user or not if (t_shell_command.getIgnoreErrorCodes().contains(error.code)) { // The user has ignored this error. debugLog("User has ignored this error, so won't display it."); // Handle only stdout output stream handleShellCommandOutput(this, t_shell_command, stdout, "", null); } else { // Show the error. debugLog("Will display the error to user."); // Check that stderr actually contains an error message if (!stderr.length) { // Stderr is empty, so the error message is probably given by Node.js's child_process. // Direct error.message to the stderr variable, so that the user can see error.message when stderr is unavailable. stderr = error.message; } // Handle both stdout and stderr output streams handleShellCommandOutput(this, t_shell_command, stdout, stderr, error.code); } } else { // Probably no errors, but do one more check. // Even when 'error' is null and everything should be ok, there may still be error messages outputted in stderr. if (stderr.length > 0) { // Check a special case: should error code 0 be ignored? if (t_shell_command.getIgnoreErrorCodes().contains(0)) { // Exit code 0 is on the ignore list, so suppress stderr output. stderr = ""; debugLog("Shell command executed: Encountered error code 0, but stderr is ignored."); } else { debugLog("Shell command executed: Encountered error code 0, and stderr will be relayed to an output handler."); } } else { debugLog("Shell command executed: No errors."); } // Handle output handleShellCommandOutput(this, t_shell_command, stdout, stderr, 0); // Use zero as an error code instead of null (0 means no error). If stderr happens to contain something, exit code 0 gets displayed in an error balloon (if that is selected as a driver for stderr). } }); } } getWorkingDirectory() { // Returns either a user defined working directory, or an automatically detected one. let working_directory = this.settings.working_directory; if (working_directory.length == 0) { // No working directory specified, so use the vault directory. return getVaultAbsolutePath(this.app); } else if (!path.isAbsolute(working_directory)) { // The working directory is relative. // Help to make it refer to the vault's directory. Without this, the relative path would refer to Obsidian's installation directory (at least on Windows). return path.join(getVaultAbsolutePath(this.app), working_directory); } return working_directory; } onunload() { debugLog('unloading plugin'); } /** * * @param current_settings_version * @private * @return True if the given settings version is supported by this plugin version, or an error message string if it's not supported. */ private isSettingsVersionSupported(current_settings_version: SettingsVersionString) { if (current_settings_version === "prior-to-0.7.0") { // 0.x.y supports all old settings formats that do not define a version number. This support will be removed in 1.0.0. return true; } else { // Compare the version number /** Note that the plugin version may be different than what will be used in the version comparison. The plugin version will be displayed in possible error messages. */ const plugin_version = this.getPluginVersion(); const version_comparison = versionCompare(ShellCommandsPlugin.SettingsVersion, current_settings_version); if (version_comparison === 0) { // The versions are equal. // Supported. return true; } else if (version_comparison < 0) { // The compared version is newer than what the plugin can support. return "The settings file is saved by a newer version of this plugin, so this plugin does not support the structure of the settings file. Please upgrade this plugin to at least version " + current_settings_version + ". Now the plugin version is " + plugin_version; } else { // The compared version is older than the version that the plugin currently uses to write settings. // 0.x.y supports all old settings versions. In 1.0.0, some old settings formats might lose their support, but that's not yet certain. return true; } } } public getPluginVersion() { return this.manifest.version; } async loadSettings() { // Try to read a settings file let all_settings: ShellCommandsPluginSettings; this.settings = await this.loadData(); // May have missing main settings fields, if the settings file is from an older version of SC. It will be migrated later. if (null === this.settings) { // The settings file does not exist. // Use default settings this.settings = getDefaultSettings(true); all_settings = this.settings; } else { // Succeeded to load a settings file. // In case the settings file does not have 'debug' or 'settings_version' fields, create them. all_settings = combineObjects(getDefaultSettings(false), this.settings); // This temporary settings object always has all fields defined (except sub fields, such as shell command specific fields, may still be missing, but they are not needed this early). This is used so that it's certain that the fields 'debug' and 'settings_version' exist. } // Update debug status - before this line debugging is always OFF! setDEBUG_ON(all_settings.debug); // Ensure that the loaded settings file is supported. const version_support = this.isSettingsVersionSupported(all_settings.settings_version); if (typeof version_support === "string") { // The settings version is not supported. new Notice("SHELL COMMANDS PLUGIN HAS DISABLED ITSELF in order to prevent misinterpreting settings / corrupting the settings file!", 120*1000); new Notice(version_support as string, 120*1000); await this.disablePlugin(); return false; // The plugin should not be used. } return true; // Settings are loaded and the plugin can be used. } async saveSettings() { // Update settings version in case it's old. this.settings.settings_version = ShellCommandsPlugin.SettingsVersion; // Write settings await this.saveData(this.settings); } private loadCustomAutocompleteList() { const custom_autocomplete_file_name = "autocomplete.yaml"; const custom_autocomplete_file_path = path.join(getPluginAbsolutePath(this), custom_autocomplete_file_name); if (fs.existsSync(custom_autocomplete_file_path)) { debugLog("loadCustomAutocompleteList(): " + custom_autocomplete_file_name + " exists, will load it now."); const custom_autocomplete_content = fs.readFileSync(custom_autocomplete_file_path).toLocaleString(); const result = addCustomAutocompleteItems(custom_autocomplete_content) if (true === result) { // OK debugLog("loadCustomAutocompleteList(): " + custom_autocomplete_file_name + " loaded."); } else { // An error has occurred. debugLog("loadCustomAutocompleteList(): " + result); this.newError("Shell commands: Unable to parse " + custom_autocomplete_file_name + ": " + result); } } else { debugLog("loadCustomAutocompleteList(): " + custom_autocomplete_file_name + " does not exists, so won't load it. This is perfectly ok."); } } private async disablePlugin() { // This unfortunately accesses a private API. // @ts-ignore await this.app.plugins.disablePlugin(this.manifest.id); } /** * @return string Returns "0" if there are no shell commands yet, otherwise returns the max ID + 1, as a string. */ generateNewShellCommandID() { let existing_ids = Object.getOwnPropertyNames(this.getTShellCommands()); let new_id = 0; for (let i in existing_ids) { let existing_id = parseInt(existing_ids[i]); if (existing_id >= new_id) { new_id = existing_id + 1; } } return String(new_id); } getPluginId() { return this.manifest.id; } getPluginName() { return this.manifest.name; } newError(message: string) { new Notice(message, this.settings.error_message_duration * 1000); // * 1000 = convert seconds to milliseconds. } newErrors(messages: string[]) { messages.forEach((message: string) => { this.newError(message); }); } newNotification(message: string) { new Notice(message, this.settings.notification_message_duration * 1000); // * 1000 = convert seconds to milliseconds. } public getDefaultShell(): string { let operating_system = getOperatingSystem() let shell_name = this.settings.default_shells[operating_system]; // Can also be undefined. if (undefined === shell_name) { shell_name = getUsersDefaultShell(); } return shell_name; } }
the_stack
import { CstParser, ILexingError, IRecognitionException } from 'chevrotain'; import * as lexer from './lexer'; export interface ParseQueryConfig { allowApexBindVariables?: boolean; ignoreParseErrors?: boolean; logErrors?: boolean; } interface ParenCount { right: number; left: number; } class LexingError extends Error { constructor(lexingError: ILexingError) { super(`${lexingError.message} (${lexingError.line}:${lexingError.column})`); this.name = 'LexingError'; } } class ParsingError extends Error { constructor(parsingError: IRecognitionException) { super(parsingError.message); this.name = parsingError.name; } } export class SoqlParser extends CstParser { // Cache larger OR expressions // https://sap.github.io/chevrotain/docs/guide/performance.html#caching-arrays-of-alternatives private $_dateFunctionOr: any = undefined; private $_aggregateFunction: any = undefined; private $_otherFunction: any = undefined; private $_atomicExpression: any = undefined; private $_apexBindVariableExpression: any = undefined; private $_arrayExpression: any = undefined; private $_relationalOperator: any = undefined; private $_selectClause: any = undefined; private $_selectClauseFunctionIdentifier: any = undefined; private $_withDataCategoryArr: any = undefined; // Set to true to allow apex bind variables, such as "WHERE Id IN :accountIds" public allowApexBindVariables = false; public ignoreParseErrors = false; constructor({ ignoreParseErrors }: { ignoreParseErrors: boolean } = { ignoreParseErrors: false }) { super(lexer.allTokens, { // true in production (webpack replaces this string) skipValidations: false, recoveryEnabled: ignoreParseErrors, // nodeLocationTracking: 'full', // not sure if needed, could look at }); this.ignoreParseErrors = ignoreParseErrors; this.performSelfAnalysis(); } public selectStatement = this.RULE('selectStatement', () => { this.SUBRULE(this.selectClause); this.SUBRULE(this.fromClause); this.OPTION(() => { this.SUBRULE(this.usingScopeClause); }); this.OPTION1(() => { this.SUBRULE(this.whereClause); }); this.OPTION2(() => { this.MANY({ DEF: () => { this.SUBRULE(this.withClause); }, }); }); this.OPTION3(() => { this.SUBRULE(this.groupByClause); this.OPTION4(() => { this.SUBRULE(this.havingClause); }); }); this.OPTION5(() => { this.SUBRULE(this.orderByClause); }); this.OPTION6(() => { this.SUBRULE(this.limitClause); }); this.OPTION7(() => { this.SUBRULE(this.offsetClause); }); this.OPTION8(() => { this.SUBRULE(this.forViewOrReference); }); this.OPTION9(() => { this.SUBRULE(this.updateTrackingViewstat); }); }); // TODO: this is a hack and the paren expressions should be re-worked, but it is a significant amount of work and difficult to handle in the visitor // If There are more open parens than closing parens, force parsing error - RParenMismatch is not a valid token and does not have a pattern // Because we are not actually doing any calculations with results, our strategy for calculating parens within an expression is semi-ok // but should be considered for a refactor at some point /** * Will throw a parsing error if there is a paren mismatch * @param parenCount */ private $_checkBalancedParens(parenCount: ParenCount) { if (!this.RECORDING_PHASE && parenCount) { const parenMatch = parenCount.left - parenCount.right; if (parenMatch !== 0) { this.CONSUME(lexer.RParenMismatch, { ERR_MSG: `Expecting a token type of --> RParen <-- but found --> '' <--` }); } } } private selectClause = this.RULE( 'selectClause', () => { this.CONSUME(lexer.Select); this.AT_LEAST_ONE_SEP({ SEP: lexer.Comma, DEF: () => { this.OR( this.$_selectClause || (this.$_selectClause = [ // selectClauseFunctionIdentifier must be first because the alias could also be an identifier { ALT: () => this.SUBRULE(this.selectClauseFunctionIdentifier, { LABEL: 'field' }) }, { ALT: () => this.SUBRULE(this.selectClauseSubqueryIdentifier, { LABEL: 'field' }) }, { ALT: () => this.SUBRULE(this.selectClauseTypeOf, { LABEL: 'field' }) }, { ALT: () => this.SUBRULE(this.selectClauseIdentifier, { LABEL: 'field' }) }, ]), ); }, }); }, { resyncEnabled: false }, ); private selectClauseFunctionIdentifier = this.RULE( 'selectClauseFunctionIdentifier', () => { this.OR( this.$_selectClauseFunctionIdentifier || (this.$_selectClauseFunctionIdentifier = [ { ALT: () => this.SUBRULE(this.dateFunction, { LABEL: 'fn' }) }, { ALT: () => this.SUBRULE(this.aggregateFunction, { LABEL: 'fn', ARGS: [true] }) }, { ALT: () => this.SUBRULE(this.locationFunction, { LABEL: 'fn' }) }, { ALT: () => this.SUBRULE(this.fieldsFunction, { LABEL: 'fn' }) }, { ALT: () => this.SUBRULE(this.otherFunction, { LABEL: 'fn' }) }, ]), ); this.OPTION(() => this.CONSUME(lexer.Identifier, { LABEL: 'alias' })); }, { resyncEnabled: false }, ); private selectClauseSubqueryIdentifier = this.RULE( 'selectClauseSubqueryIdentifier', () => { this.CONSUME(lexer.LParen); this.SUBRULE(this.selectStatement); this.CONSUME(lexer.RParen); }, { resyncEnabled: false }, ); private selectClauseTypeOf = this.RULE( 'selectClauseTypeOf', () => { this.CONSUME(lexer.Typeof); this.CONSUME(lexer.Identifier, { LABEL: 'typeOfField' }); this.AT_LEAST_ONE({ DEF: () => { this.SUBRULE(this.selectClauseTypeOfThen); }, }); this.OPTION(() => { this.SUBRULE(this.selectClauseTypeOfElse); }); this.CONSUME(lexer.End); }, { resyncEnabled: false }, ); private selectClauseIdentifier = this.RULE( 'selectClauseIdentifier', () => { this.CONSUME(lexer.Identifier, { LABEL: 'field' }); this.OPTION(() => this.CONSUME1(lexer.Identifier, { LABEL: 'alias' })); }, { resyncEnabled: false }, ); private selectClauseTypeOfThen = this.RULE( 'selectClauseTypeOfThen', () => { this.CONSUME(lexer.When); this.CONSUME(lexer.Identifier, { LABEL: 'typeOfField' }); this.CONSUME(lexer.Then); this.AT_LEAST_ONE_SEP({ SEP: lexer.Comma, DEF: () => { this.CONSUME1(lexer.Identifier, { LABEL: 'field' }); }, }); }, { resyncEnabled: false }, ); private selectClauseTypeOfElse = this.RULE( 'selectClauseTypeOfElse', () => { this.CONSUME(lexer.Else); this.AT_LEAST_ONE_SEP({ SEP: lexer.Comma, DEF: () => { this.CONSUME(lexer.Identifier, { LABEL: 'field' }); }, }); }, { resyncEnabled: false }, ); private fromClause = this.RULE( 'fromClause', () => { this.CONSUME(lexer.From); this.CONSUME(lexer.Identifier); this.OPTION({ GATE: () => !(this.LA(1).tokenType === lexer.Offset && this.LA(2).tokenType === lexer.UnsignedInteger), DEF: () => this.CONSUME1(lexer.Identifier, { LABEL: 'alias' }), }); }, { resyncEnabled: false }, ); private usingScopeClause = this.RULE('usingScopeClause', () => { this.CONSUME(lexer.Using); this.CONSUME(lexer.Scope); this.CONSUME(lexer.UsingScopeEnumeration); }); private whereClause = this.RULE('whereClause', () => { this.CONSUME(lexer.Where); // Get paren count to ensure that we only parse balanced parens for this where clause // and do not parse any extra parens that might belong to subquery or might be invalid const parenCount = this.getParenCount(); this.AT_LEAST_ONE({ DEF: () => { this.SUBRULE(this.conditionExpression, { ARGS: [parenCount, false, true, true] }); }, }); // TODO: this is a hack and the paren expressions should be re-worked, but it is a significant amount of work and difficult to handle in the visitor // If There are more open parens than closing parens, force parsing error - RParenMismatch is not a valid token and does not have a pattern // Because we are not actually doing any calculations with results, our strategy for calculating parens within an expression is semi-ok // but should be considered for a refactor at some point this.$_checkBalancedParens(parenCount); }); private whereClauseSubqueryIdentifier = this.RULE('whereClauseSubqueryIdentifier', () => { this.CONSUME(lexer.LParen); this.SUBRULE(this.selectStatement); this.CONSUME(lexer.RParen); }); private conditionExpression = this.RULE( 'conditionExpression', (parenCount?: ParenCount, allowSubquery?: boolean, alowAggregateFn?: boolean, allowLocationFn?: boolean) => { // argument is undefined during self-analysis, need to initialize to avoid exception parenCount = this.getParenCount(parenCount); this.OPTION(() => { this.OR([ { ALT: () => this.CONSUME(lexer.And, { LABEL: 'logicalOperator' }) }, { ALT: () => this.CONSUME(lexer.Or, { LABEL: 'logicalOperator' }) }, ]); }); // MAX_LOOKAHEAD -> this is increased because an arbitrary number of parens could be used causing a parsing error // this does not allow infinite parentheses, but is more than enough for any real use-cases // Under no circumstances would large numbers of nested expressions not be expressable with fewer conditions this.MANY({ MAX_LOOKAHEAD: 10, DEF: () => this.SUBRULE(this.expressionPartWithNegation, { ARGS: [parenCount], LABEL: 'expressionNegation' }), }); this.OR1({ MAX_LOOKAHEAD: 10, DEF: [{ ALT: () => this.SUBRULE(this.expression, { ARGS: [parenCount, allowSubquery, alowAggregateFn, allowLocationFn] }) }], }); }, ); private withClause = this.RULE('withClause', () => { this.CONSUME(lexer.With); this.OR([ { ALT: () => this.CONSUME(lexer.SecurityEnforced, { LABEL: 'withSecurityEnforced' }) }, { ALT: () => this.SUBRULE(this.withDataCategory) }, ]); }); private withDataCategory = this.RULE('withDataCategory', () => { this.CONSUME(lexer.DataCategory); this.AT_LEAST_ONE_SEP({ SEP: lexer.And, DEF: () => { this.SUBRULE(this.withDataCategoryArr); }, }); }); private withDataCategoryArr = this.RULE('withDataCategoryArr', () => { this.CONSUME(lexer.Identifier, { LABEL: 'dataCategoryGroupName' }); this.OR( this.$_withDataCategoryArr || (this.$_withDataCategoryArr = [ { ALT: () => this.CONSUME(lexer.At, { LABEL: 'filteringSelector' }) }, { ALT: () => this.CONSUME(lexer.Above, { LABEL: 'filteringSelector' }) }, { ALT: () => this.CONSUME(lexer.Below, { LABEL: 'filteringSelector' }) }, { ALT: () => this.CONSUME(lexer.AboveOrBelow, { LABEL: 'filteringSelector' }) }, ]), ); this.OPTION(() => { this.CONSUME1(lexer.LParen); }); this.AT_LEAST_ONE_SEP1({ SEP: lexer.Comma, DEF: () => { this.CONSUME1(lexer.Identifier, { LABEL: 'dataCategoryName' }); }, }); this.OPTION1(() => { this.CONSUME2(lexer.RParen); }); }); private groupByClause = this.RULE('groupByClause', () => { this.CONSUME(lexer.GroupBy); this.AT_LEAST_ONE_SEP({ SEP: lexer.Comma, DEF: () => { this.OR([ { ALT: () => this.SUBRULE(this.cubeFunction, { LABEL: 'groupBy' }) }, { ALT: () => this.SUBRULE(this.rollupFunction, { LABEL: 'groupBy' }) }, { ALT: () => this.SUBRULE(this.dateFunction, { LABEL: 'groupBy' }) }, { ALT: () => this.CONSUME(lexer.Identifier, { LABEL: 'groupBy' }) }, ]); }, }); }); private havingClause = this.RULE('havingClause', () => { this.CONSUME(lexer.Having); const parenCount = this.getParenCount(); this.AT_LEAST_ONE({ DEF: () => { this.SUBRULE(this.conditionExpression, { ARGS: [parenCount, true] }); }, }); // TODO: this is a hack and the paren expressions should be re-worked, but it is a significant amount of work and difficult to handle in the visitor // If There are more open parens than closing parens, force parsing error - RParenMismatch is not a valid token and does not have a pattern // Because we are not actually doing any calculations with results, our strategy for calculating parens within an expression is semi-ok // but should be considered for a refactor at some point this.$_checkBalancedParens(parenCount); }); private orderByClause = this.RULE('orderByClause', () => { this.CONSUME(lexer.OrderBy); this.AT_LEAST_ONE_SEP({ SEP: lexer.Comma, DEF: () => { this.OR([ { ALT: () => this.SUBRULE(this.orderByGroupingFunctionExpression, { LABEL: 'orderByExpressionOrFn' }) }, { ALT: () => this.SUBRULE(this.orderBySpecialFunctionExpression, { LABEL: 'orderByExpressionOrFn' }) }, { ALT: () => this.SUBRULE(this.orderByExpression, { LABEL: 'orderByExpressionOrFn' }) }, ]); }, }); }); private orderByExpression = this.RULE('orderByExpression', () => { this.CONSUME(lexer.Identifier); this.OPTION(() => { this.OR([{ ALT: () => this.CONSUME(lexer.Asc, { LABEL: 'order' }) }, { ALT: () => this.CONSUME(lexer.Desc, { LABEL: 'order' }) }]); }); this.OPTION1(() => { this.CONSUME(lexer.Nulls); this.OR1([{ ALT: () => this.CONSUME(lexer.First, { LABEL: 'nulls' }) }, { ALT: () => this.CONSUME(lexer.Last, { LABEL: 'nulls' }) }]); }); }); private orderByGroupingFunctionExpression = this.RULE('orderByGroupingFunctionExpression', () => { this.CONSUME(lexer.Grouping, { LABEL: 'fn' }); this.SUBRULE(this.functionExpression); }); private orderBySpecialFunctionExpression = this.RULE('orderBySpecialFunctionExpression', () => { this.OR([ { ALT: () => this.SUBRULE(this.aggregateFunction) }, { ALT: () => this.SUBRULE(this.dateFunction) }, { ALT: () => this.SUBRULE(this.locationFunction) }, ]); this.OPTION(() => { this.OR1([{ ALT: () => this.CONSUME(lexer.Asc, { LABEL: 'order' }) }, { ALT: () => this.CONSUME(lexer.Desc, { LABEL: 'order' }) }]); }); this.OPTION1(() => { this.CONSUME(lexer.Nulls); this.OR2([{ ALT: () => this.CONSUME(lexer.First, { LABEL: 'nulls' }) }, { ALT: () => this.CONSUME(lexer.Last, { LABEL: 'nulls' }) }]); }); }); private limitClause = this.RULE('limitClause', () => { this.CONSUME(lexer.Limit); this.CONSUME(lexer.UnsignedInteger, { LABEL: 'value' }); }); private offsetClause = this.RULE('offsetClause', () => { this.CONSUME(lexer.Offset); this.CONSUME(lexer.UnsignedInteger, { LABEL: 'value' }); }); // these are made undefined to ensure that V8 knows about these private dateFunction = this.RULE('dateFunction', () => { this.OR( this.$_dateFunctionOr || // https://sap.github.io/chevrotain/docs/guide/performance.html#caching-arrays-of-alternatives (this.$_dateFunctionOr = [ { ALT: () => this.CONSUME(lexer.CalendarMonth, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.CalendarQuarter, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.CalendarYear, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.DayInMonth, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.DayInWeek, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.DayInYear, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.DayOnly, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.FiscalMonth, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.FiscalQuarter, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.FiscalYear, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.HourInDay, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.WeekInMonth, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.WeekInYear, { LABEL: 'fn' }) }, ]), ); this.SUBRULE(this.functionExpression); }); private aggregateFunction = this.RULE('aggregateFunction', () => { this.OR( this.$_aggregateFunction || (this.$_aggregateFunction = [ { ALT: () => this.CONSUME(lexer.Avg, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.Count, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.CountDistinct, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.Min, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.Max, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.Sum, { LABEL: 'fn' }) }, ]), ); this.SUBRULE(this.functionExpression, { ARGS: [true] }); }); private fieldsFunction = this.RULE('fieldsFunction', () => { this.CONSUME(lexer.Fields, { LABEL: 'fn' }); this.CONSUME(lexer.LParen); this.CONSUME(lexer.FieldsFunctionParamIdentifier, { LABEL: 'params' }); this.CONSUME(lexer.RParen); }); private otherFunction = this.RULE('otherFunction', () => { this.OR( this.$_otherFunction || (this.$_otherFunction = [ { ALT: () => this.CONSUME(lexer.Format, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.Tolabel, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.ConvertTimeZone, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.ConvertCurrency, { LABEL: 'fn' }) }, { ALT: () => this.CONSUME(lexer.Grouping, { LABEL: 'fn' }) }, ]), ); this.SUBRULE(this.functionExpression); }); private cubeFunction = this.RULE('cubeFunction', () => { this.CONSUME(lexer.Cube, { LABEL: 'fn' }); this.SUBRULE(this.functionExpression); }); private rollupFunction = this.RULE('rollupFunction', () => { this.CONSUME(lexer.Rollup, { LABEL: 'fn' }); this.SUBRULE(this.functionExpression); }); private functionExpression = this.RULE('functionExpression', (skipAggregate?: boolean) => { this.CONSUME(lexer.LParen); this.MANY_SEP({ SEP: lexer.Comma, DEF: () => { this.OR([ { GATE: () => !skipAggregate, ALT: () => this.SUBRULE(this.aggregateFunction, { LABEL: 'params' }) }, { ALT: () => this.SUBRULE(this.otherFunction, { LABEL: 'params' }) }, { ALT: () => this.CONSUME(lexer.StringIdentifier, { LABEL: 'params' }) }, { ALT: () => this.CONSUME(lexer.NumberIdentifier, { LABEL: 'params' }) }, { ALT: () => this.CONSUME(lexer.Identifier, { LABEL: 'params' }) }, ]); }, }); this.CONSUME(lexer.RParen); }); private locationFunction = this.RULE('locationFunction', () => { this.CONSUME(lexer.Distance); this.CONSUME(lexer.LParen); this.CONSUME(lexer.Identifier, { LABEL: 'location1' }); this.CONSUME(lexer.Comma); this.OR([ { ALT: () => this.SUBRULE(this.geolocationFunction, { LABEL: 'location2' }) }, { ALT: () => this.CONSUME1(lexer.Identifier, { LABEL: 'location2' }) }, ]); this.CONSUME1(lexer.Comma); this.CONSUME(lexer.GeolocationUnit, { LABEL: 'unit' }); this.CONSUME(lexer.RParen); }); private geolocationFunction = this.RULE('geolocationFunction', () => { this.CONSUME(lexer.Geolocation); this.CONSUME(lexer.LParen); this.CONSUME(lexer.NumberIdentifier, { LABEL: 'latitude' }); this.CONSUME(lexer.Comma); this.CONSUME1(lexer.NumberIdentifier, { LABEL: 'longitude' }); this.CONSUME(lexer.RParen); }); private expressionPartWithNegation = this.RULE('expressionPartWithNegation', (parenCount?: ParenCount) => { let leftParenCount = 0; // ensure parenCount is not mutated unless rule is executed this.MANY(() => { this.CONSUME(lexer.LParen); leftParenCount++; }); this.CONSUME(lexer.Not, { LABEL: 'expressionNegation' }); if (parenCount && leftParenCount) { parenCount.left += leftParenCount; } }); private expression = this.RULE( 'expression', (parenCount?: ParenCount, allowSubquery?: boolean, alowAggregateFn?: boolean, allowLocationFn?: boolean) => { this.OPTION1(() => { this.MANY1(() => { this.CONSUME(lexer.LParen); if (parenCount) { parenCount.left++; } }); }); this.OR1([ { GATE: () => alowAggregateFn, ALT: () => this.SUBRULE(this.aggregateFunction, { LABEL: 'lhs' }) }, { GATE: () => allowLocationFn, ALT: () => this.SUBRULE(this.locationFunction, { LABEL: 'lhs' }) }, { ALT: () => this.SUBRULE(this.dateFunction, { LABEL: 'lhs' }) }, { ALT: () => this.SUBRULE(this.otherFunction, { LABEL: 'lhs' }) }, { ALT: () => this.CONSUME(lexer.Identifier, { LABEL: 'lhs' }) }, ]); this.OR2([ { ALT: () => this.SUBRULE(this.expressionWithRelationalOperator, { LABEL: 'operator' }) }, { ALT: () => this.SUBRULE(this.expressionWithSetOperator, { LABEL: 'operator', ARGS: [allowSubquery] }) }, ]); this.OPTION3(() => { this.MANY2({ GATE: () => (parenCount ? parenCount.left > parenCount.right : true), DEF: () => { this.CONSUME(lexer.RParen); if (parenCount) { parenCount.right++; } }, }); }); }, ); private expressionWithRelationalOperator = this.RULE('expressionWithRelationalOperator', () => { this.SUBRULE(this.relationalOperator); this.SUBRULE(this.atomicExpression, { LABEL: 'rhs' }); }); private expressionWithSetOperator = this.RULE('expressionWithSetOperator', (allowSubquery?: boolean) => { this.SUBRULE(this.setOperator); this.SUBRULE2(this.atomicExpression, { LABEL: 'rhs', ARGS: [true, allowSubquery] }); }); private atomicExpression = this.RULE('atomicExpression', (isArray, allowSubquery?: boolean) => { this.OR( this.$_atomicExpression || (this.$_atomicExpression = [ { GATE: () => this.allowApexBindVariables, ALT: () => this.SUBRULE(this.apexBindVariableExpression) }, // SET / SUBQUERY { GATE: () => isArray, ALT: () => this.SUBRULE(this.arrayExpression) }, { GATE: () => isArray && allowSubquery, ALT: () => this.SUBRULE(this.whereClauseSubqueryIdentifier) }, // NON-SET { GATE: () => !isArray, ALT: () => this.CONSUME(lexer.DateIdentifier) }, { GATE: () => !isArray, ALT: () => this.CONSUME(lexer.CurrencyPrefixedDecimal, { LABEL: 'CurrencyPrefixedDecimal' }) }, { GATE: () => !isArray, ALT: () => this.CONSUME(lexer.CurrencyPrefixedInteger, { LABEL: 'CurrencyPrefixedInteger' }) }, { GATE: () => !isArray, ALT: () => this.CONSUME(lexer.NumberIdentifier) }, { GATE: () => !isArray, ALT: () => this.CONSUME(lexer.Null) }, { GATE: () => !isArray, ALT: () => this.SUBRULE(this.booleanValue) }, { GATE: () => !isArray, ALT: () => this.CONSUME(lexer.DateLiteral) }, { GATE: () => !isArray, ALT: () => this.SUBRULE(this.dateNLiteral) }, { GATE: () => !isArray, ALT: () => this.CONSUME(lexer.StringIdentifier) }, ]), ); }); private apexBindVariableExpression = this.RULE('apexBindVariableExpression', () => { this.CONSUME(lexer.Colon); // First item in list could optionally be a new instantiation this.OPTION(() => { this.SUBRULE(this.apexBindVariableNewInstantiation, { LABEL: 'apex' }); this.OPTION1(() => { this.CONSUME(lexer.Decimal); }); }); // Chained function calls or nested arguments with function calls at the end this.MANY_SEP({ SEP: lexer.Decimal, DEF: () => { this.OR( this.$_apexBindVariableExpression || (this.$_apexBindVariableExpression = [ { ALT: () => this.SUBRULE(this.apexBindVariableFunctionCall, { LABEL: 'apex' }) }, { ALT: () => this.SUBRULE(this.apexBindVariableIdentifier, { LABEL: 'apex' }) }, ]), ); }, }); }); private apexBindVariableIdentifier = this.RULE('apexBindVariableIdentifier', () => { this.CONSUME(lexer.Identifier); this.OPTION(() => this.SUBRULE(this.apexBindVariableFunctionArrayAccessor)); }); private apexBindVariableNewInstantiation = this.RULE('apexBindVariableNewInstantiation', () => { this.CONSUME(lexer.ApexNew, { LABEL: 'new' }); this.CONSUME(lexer.Identifier, { LABEL: 'function' }); this.OPTION(() => { this.SUBRULE(this.apexBindVariableGeneric); }); this.SUBRULE(this.apexBindVariableFunctionParams); this.OPTION1(() => this.SUBRULE(this.apexBindVariableFunctionArrayAccessor)); }); private apexBindVariableFunctionCall = this.RULE('apexBindVariableFunctionCall', () => { this.CONSUME(lexer.Identifier, { LABEL: 'function' }); this.SUBRULE(this.apexBindVariableFunctionParams); this.OPTION(() => this.SUBRULE(this.apexBindVariableFunctionArrayAccessor)); }); private apexBindVariableGeneric = this.RULE('apexBindVariableGeneric', () => { this.CONSUME(lexer.LessThan); this.AT_LEAST_ONE_SEP({ SEP: lexer.Comma, DEF: () => { this.CONSUME(lexer.Identifier, { LABEL: 'parameter' }); }, }); this.CONSUME(lexer.GreaterThan); }); private apexBindVariableFunctionParams = this.RULE('apexBindVariableFunctionParams', () => { this.CONSUME(lexer.LParen); this.MANY_SEP({ SEP: lexer.Comma, DEF: () => { this.CONSUME(lexer.Identifier, { LABEL: 'parameter' }); }, }); this.CONSUME(lexer.RParen); }); // foo[3] or foo[somIntVariable] private apexBindVariableFunctionArrayAccessor = this.RULE('apexBindVariableFunctionArrayAccessor', () => { this.CONSUME(lexer.LSquareBracket); this.OR([ { ALT: () => this.CONSUME(lexer.UnsignedInteger, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.Identifier, { LABEL: 'value' }) }, ]); this.CONSUME(lexer.RSquareBracket); }); private arrayExpression = this.RULE('arrayExpression', () => { this.CONSUME(lexer.LParen); this.AT_LEAST_ONE_SEP({ SEP: lexer.Comma, DEF: () => { this.OR( this.$_arrayExpression || (this.$_arrayExpression = [ { ALT: () => this.CONSUME(lexer.CurrencyPrefixedDecimal, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.CurrencyPrefixedInteger, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.NumberIdentifier, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.DateIdentifier, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.Null, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.True, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.False, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.DateLiteral, { LABEL: 'value' }) }, { ALT: () => this.SUBRULE(this.dateNLiteral, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.StringIdentifier, { LABEL: 'value' }) }, ]), ); }, }); this.CONSUME(lexer.RParen); }); private relationalOperator = this.RULE('relationalOperator', () => { this.OR( this.$_relationalOperator || (this.$_relationalOperator = [ { ALT: () => this.CONSUME(lexer.Equal, { LABEL: 'operator' }) }, { ALT: () => this.CONSUME(lexer.NotEqual, { LABEL: 'operator' }) }, { ALT: () => this.CONSUME(lexer.GreaterThan, { LABEL: 'operator' }) }, { ALT: () => this.CONSUME(lexer.GreaterThanOrEqual, { LABEL: 'operator' }) }, { ALT: () => this.CONSUME(lexer.LessThan, { LABEL: 'operator' }) }, { ALT: () => this.CONSUME(lexer.LessThanOrEqual, { LABEL: 'operator' }) }, { ALT: () => this.CONSUME(lexer.Like, { LABEL: 'operator' }) }, ]), ); }); private setOperator = this.RULE('setOperator', () => { this.OR([ { ALT: () => this.CONSUME(lexer.In, { LABEL: 'operator' }) }, { ALT: () => this.CONSUME(lexer.NotIn, { LABEL: 'operator' }) }, { ALT: () => this.CONSUME(lexer.Includes, { LABEL: 'operator' }) }, { ALT: () => this.CONSUME(lexer.Excludes, { LABEL: 'operator' }) }, ]); }); private booleanValue = this.RULE('booleanValue', () => { this.OR([ { ALT: () => this.CONSUME(lexer.True, { LABEL: 'boolean' }) }, { ALT: () => this.CONSUME(lexer.False, { LABEL: 'boolean' }) }, ]); }); private dateNLiteral = this.RULE('dateNLiteral', () => { this.CONSUME(lexer.DateNLiteral, { LABEL: 'dateNLiteral' }); this.CONSUME(lexer.Colon); this.OR1([ { ALT: () => this.CONSUME(lexer.UnsignedInteger, { LABEL: 'variable' }) }, { ALT: () => this.CONSUME(lexer.SignedInteger, { LABEL: 'variable' }) }, ]); }); private forViewOrReference = this.RULE('forViewOrReference', () => { this.CONSUME(lexer.For); this.OR([ { ALT: () => this.CONSUME(lexer.View, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.Reference, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.Update, { LABEL: 'value' }) }, ]); }); private updateTrackingViewstat = this.RULE('updateTrackingViewstat', () => { this.CONSUME(lexer.Update); this.OR([ { ALT: () => this.CONSUME(lexer.Tracking, { LABEL: 'value' }) }, { ALT: () => this.CONSUME(lexer.Viewstat, { LABEL: 'value' }) }, ]); }); private getParenCount(parenCount?: ParenCount): ParenCount { return parenCount || { right: 0, left: 0 }; } } let parser = new SoqlParser(); export function parse(soql: string, options?: ParseQueryConfig) { const { allowApexBindVariables, logErrors, ignoreParseErrors } = options || { allowApexBindVariables: false, logErrors: false, ignoreParseErrors: false, }; const lexResult = lexer.lex(soql); if (lexResult.errors.length > 0) { if (logErrors) { console.log('Lexing Errors:'); console.log(lexResult.errors); } throw new LexingError(lexResult.errors[0]); } // get new instance if ignoreParseErrors changes if (parser.ignoreParseErrors !== ignoreParseErrors) { parser = new SoqlParser({ ignoreParseErrors }); } // setting a new input will RESET the parser instance's state. parser.input = lexResult.tokens; // If true, allows WHERE foo = :bar parser.allowApexBindVariables = allowApexBindVariables || false; const cst = parser.selectStatement(); if (parser.errors.length > 0) { if (logErrors) { console.log('Parsing Errors:'); console.log(parser.errors); } if (!ignoreParseErrors) { throw new ParsingError(parser.errors[0]); } } return { cst, parseErrors: parser.errors.map(err => new ParsingError(err)), }; }
the_stack
import React from "react"; import PropTypes from "prop-types"; import * as CSS from "csstype"; export class SpriteSheetInstance extends React.Component<Props> { play(): void; pause(): void; goToAndPlay(frame: number): void; goToAndPause(frame: number): void; setStartAt(frame: number): void; setEndAt(frame: number): void; setFps(fps: number): void; setDirection(direction: Direction): void; getInfo(type: NumberInfoType): number; getInfo(type: BooleanInfoType): boolean; getInfo(type: "direction"): Direction; } export type Callback = (spritesheet: SpriteSheetInstance) => void; export type Direction = "forward" | "rewind"; export type NumberInfoType = | "frame" | "fps" | "steps" | "width" | "height" | "scale" | "completeLoopCicles"; export type BooleanInfoType = "isPlaying" | "isPaused"; export interface Props { className?: string; style?: CSS.Properties; image: string; widthFrame: number; heightFrame: number; steps: number; fps: number; direction: Direction; timeout?: number; autoplay?: boolean; loop?: boolean; isResponsive?: boolean; startAt?: number; endAt?: number; background?: string; backgroundSize?: CSS.Property.BackgroundSize; backgroundRepeat?: CSS.Property.BackgroundRepeat; backgroundPosition?: CSS.Property.BackgroundPosition; getInstance?: Callback; onClick?: Callback; onDoubleClick?: Callback; onMouseMove?: Callback; onMouseEnter?: Callback; onMouseLeave?: Callback; onMouseOver?: Callback; onMouseOut?: Callback; onMouseDown?: Callback; onMouseUp?: Callback; onInit?: Callback; onResize?: Callback; onPlay?: Callback; onPause?: Callback; onLoopComplete?: Callback; onEachFrame?: Callback; onEnterFrame?: Array<{ frame: number; callback: () => void; }>; } const ID = function () { // Math.random should be unique because of its seeding algorithm. // Convert it to base 36 (numbers + letters), and grab the first 9 characters // after the decimal. return "_" + Math.random().toString(36).substr(2, 9); }; class Spritesheet extends React.Component<Props> { constructor(props: Props) { super(props); const { isResponsive, startAt, endAt, fps, steps, direction } = props; this.id = `react-responsive-spritesheet--${ID()}`; this.spriteEl = this.spriteElContainer = this.spriteElMove = this.imageSprite = this.cols = this.rows = null; this.intervalSprite = false; this.isResponsive = isResponsive; this.startAt = this.setStartAt(startAt); this.endAt = this.setEndAt(endAt); this.fps = fps; this.steps = steps; this.completeLoopCicles = 0; this.isPlaying = false; this.spriteScale = 1; this.direction = this.setDirection(direction); this.frame = this.startAt ? this.startAt : this.direction === "rewind" ? this.steps - 1 : 0; } componentDidMount() { this.init(); } componentWillUnmount() { window.removeEventListener("resize", this.resize); } renderElements = () => { const { image, className, style, widthFrame, heightFrame, background, backgroundSize, backgroundRepeat, backgroundPosition, onClick, onDoubleClick, onMouseMove, onMouseEnter, onMouseLeave, onMouseOver, onMouseOut, onMouseDown, onMouseUp, } = this.props; const containerStyles = { position: "relative", overflow: "hidden", width: `${widthFrame}px`, height: `${heightFrame}px`, transform: `scale(${this.spriteScale})`, transformOrigin: "0 0", backgroundImage: `url(${background})`, backgroundSize, backgroundRepeat, backgroundPosition, }; const moveStyles = { overflow: "hidden", backgroundRepeat: "no-repeat", display: "table-cell", backgroundImage: `url(${image})`, width: `${widthFrame}px`, height: `${heightFrame}px`, transformOrigin: "0 50%", }; const elMove = React.createElement("div", { className: "react-responsive-spritesheet-container__move", style: moveStyles, }); const elContainer = React.createElement( "div", { className: "react-responsive-spritesheet-container", style: containerStyles, }, elMove ); const elSprite = React.createElement( "div", { className: `react-responsive-spritesheet ${this.id} ${className}`, style, onClick: () => onClick(this.setInstance()), onDoubleClick: () => onDoubleClick(this.setInstance()), onMouseMove: () => onMouseMove(this.setInstance()), onMouseEnter: () => onMouseEnter(this.setInstance()), onMouseLeave: () => onMouseLeave(this.setInstance()), onMouseOver: () => onMouseOver(this.setInstance()), onMouseOut: () => onMouseOut(this.setInstance()), onMouseDown: () => onMouseDown(this.setInstance()), onMouseUp: () => onMouseUp(this.setInstance()), }, elContainer ); return elSprite; }; init = () => { const { image, widthFrame, heightFrame, autoplay, getInstance, onInit } = this.props; const imgLoadSprite = new Image(); imgLoadSprite.src = image; imgLoadSprite.onload = () => { if (document && document.querySelector(`.${this.id}`)) { this.imageSprite = imgLoadSprite; this.cols = this.imageSprite.width === widthFrame ? 1 : this.imageSprite.width / widthFrame; this.rows = this.imageSprite.height === heightFrame ? 1 : this.imageSprite.height / heightFrame; this.spriteEl = document.querySelector(`.${this.id}`); this.spriteElContainer = this.spriteEl.querySelector( ".react-responsive-spritesheet-container" ); this.spriteElMove = this.spriteElContainer.querySelector( ".react-responsive-spritesheet-container__move" ); this.resize(false); window.addEventListener("resize", this.resize); this.moveImage(false); setTimeout(() => { this.resize(false); }, 10); if (autoplay !== false) this.play(true); const instance = this.setInstance(); getInstance(instance); onInit(instance); } }; imgLoadSprite.onerror = () => { throw new Error(`Failed to load image ${imgLoadSprite.src}`); }; }; resize = (callback = true) => { const { widthFrame, onResize } = this.props; if (this.isResponsive) { this.spriteScale = this.spriteEl.offsetWidth / widthFrame; this.spriteElContainer.style.transform = `scale(${this.spriteScale})`; this.spriteEl.style.height = `${this.getInfo("height")}px`; if (callback && onResize) onResize(this.setInstance()); } }; play = (withTimeout = false) => { const { onPlay, timeout } = this.props; if (!this.isPlaying) { setTimeout( () => { onPlay(this.setInstance()); this.setIntervalPlayFunctions(); this.isPlaying = true; }, withTimeout ? timeout : 0 ); } }; setIntervalPlayFunctions = () => { if (this.intervalSprite) clearInterval(this.intervalSprite); this.intervalSprite = setInterval(() => { if (this.isPlaying) this.moveImage(); }, 1000 / this.fps); }; moveImage = (play = true) => { const { onEnterFrame, onEachFrame, loop, onLoopComplete } = this.props; const currentRow = Math.floor(this.frame / this.cols); const currentCol = this.frame - this.cols * currentRow; this.spriteElMove.style.backgroundPosition = `-${ this.props.widthFrame * currentCol }px -${this.props.heightFrame * currentRow}px`; if (onEnterFrame) { onEnterFrame.map((frameAction) => { if (frameAction.frame === this.frame && frameAction.callback) { frameAction.callback(); } }); } if (play) { if (this.direction === "rewind") { this.frame -= 1; } else { this.frame += 1; } if (onEachFrame) onEachFrame(this.setInstance()); } if (this.isPlaying) { if ( (this.direction === "forward" && (this.frame === this.steps || this.frame === this.endAt)) || (this.direction === "rewind" && (this.frame === -1 || this.frame === this.endAt)) ) { if (loop) { if (onLoopComplete) onLoopComplete(this.setInstance()); this.completeLoopCicles += 1; this.frame = this.startAt ? this.startAt : this.direction === "rewind" ? this.steps - 1 : 0; } else { this.pause(); } } } }; pause = () => { const { onPause } = this.props; this.isPlaying = false; clearInterval(this.intervalSprite); onPause(this.setInstance()); }; goToAndPlay = (frame) => { this.frame = frame ? frame : this.frame; this.play(); }; goToAndPause = (frame) => { this.pause(); this.frame = frame ? frame : this.frame; this.moveImage(); }; setStartAt = (frame) => { this.startAt = frame ? frame - 1 : 0; return this.startAt; }; setEndAt = (frame) => { this.endAt = frame; return this.endAt; }; setFps(fps) { this.fps = fps; this.setIntervalPlayFunctions(); } setDirection = (direction) => { this.direction = direction === "rewind" ? "rewind" : "forward"; return this.direction; }; getInfo = (param) => { switch (param) { case "direction": return this.direction; case "frame": return this.frame; case "fps": return this.fps; case "steps": return this.steps; case "width": return this.spriteElContainer.getBoundingClientRect().width; case "height": return this.spriteElContainer.getBoundingClientRect().height; case "scale": return this.spriteScale; case "isPlaying": return this.isPlaying; case "isPaused": return !this.isPlaying; case "completeLoopCicles": return this.completeLoopCicles; default: throw new Error( `Invalid param \`${param}\` requested by Spritesheet.getinfo(). See the documentation on https://github.com/danilosetra/react-responsive-spritesheet` ); } }; setInstance() { return { play: this.play, pause: this.pause, goToAndPlay: this.goToAndPlay, goToAndPause: this.goToAndPause, setStartAt: this.setStartAt, setEndAt: this.setEndAt, setFps: this.setFps, setDirection: this.setDirection, getInfo: this.getInfo, }; } render() { return this.renderElements(); } } Spritesheet.propTypes = { className: PropTypes.string, style: PropTypes.object, image: PropTypes.string.isRequired, widthFrame: PropTypes.number.isRequired, heightFrame: PropTypes.number.isRequired, isResponsive: PropTypes.bool, steps: PropTypes.number.isRequired, fps: PropTypes.number.isRequired, direction: PropTypes.string, timeout: PropTypes.number, autoplay: PropTypes.bool, loop: PropTypes.bool, startAt: PropTypes.number, endAt: PropTypes.oneOfType([PropTypes.oneOf([false]), PropTypes.number]), background: PropTypes.string, backgroundSize: PropTypes.string, backgroundRepeat: PropTypes.string, backgroundPosition: PropTypes.string, getInstance: PropTypes.func, onClick: PropTypes.func, onDoubleClick: PropTypes.func, onMouseMove: PropTypes.func, onMouseEnter: PropTypes.func, onMouseLeave: PropTypes.func, onMouseOver: PropTypes.func, onMouseOut: PropTypes.func, onMouseDown: PropTypes.func, onMouseUp: PropTypes.func, onInit: PropTypes.func, onResize: PropTypes.oneOfType([PropTypes.oneOf([false]), PropTypes.func]), onPlay: PropTypes.func, onPause: PropTypes.func, onLoopComplete: PropTypes.oneOfType([ PropTypes.oneOf([false]), PropTypes.func, ]), onEachFrame: PropTypes.oneOfType([PropTypes.oneOf([false]), PropTypes.func]), onEnterFrame: PropTypes.oneOfType([ PropTypes.oneOf([false]), PropTypes.array, ]), }; Spritesheet.defaultProps = { className: "", style: {}, isResponsive: true, direction: "forward", timeout: 0, autoplay: true, loop: false, startAt: 0, endAt: false, background: "", backgroundSize: "cover", backgroundRepeat: "no-repeat", backgroundPosition: "", getInstance: () => {}, onClick: () => {}, onDoubleClick: () => {}, onMouseMove: () => {}, onMouseEnter: () => {}, onMouseLeave: () => {}, onMouseOver: () => {}, onMouseOut: () => {}, onMouseDown: () => {}, onMouseUp: () => {}, onInit: () => {}, onResize: false, onPlay: () => {}, onPause: () => {}, onLoopComplete: false, onEachFrame: false, onEnterFrame: false, }; export default Spritesheet;
the_stack
import {ICacheRegistryService} from "./i-cache-registry-service"; import {PolyfillFeature, PolyfillFeatureInput} from "../../../polyfill/polyfill-feature"; import {getPolyfillConfigChecksum, getPolyfillIdentifier, getPolyfillSetIdentifier} from "../../../util/polyfill/polyfill-util"; import {join} from "crosspath"; import {constant} from "../../../constant/constant"; import {IMemoryRegistryService, PolyfillCachingContext} from "../polyfill-registry/i-memory-registry-service"; import {PolyfillName} from "../../../polyfill/polyfill-name"; import {coerce, gt} from "semver"; import {IRegistryGetResult} from "../polyfill-registry/i-registry-get-result"; import {ILoggerService} from "../../logger/i-logger-service"; import {PolyfillDictEntry, PolyfillDictNormalizedEntry} from "../../../polyfill/polyfill-dict"; import pkg from "../../../../package.json"; import {Config} from "../../../config/config"; import {IMetricsService} from "../../metrics/i-metrics-service"; import {FileSystem} from "../../../common/lib/file-system/file-system"; /** * A class that can cache generated Polyfills on disk */ export class CacheRegistryService implements ICacheRegistryService { constructor( private readonly fileSystem: FileSystem, private readonly logger: ILoggerService, private readonly memoryRegistry: IMemoryRegistryService, private readonly metricsService: IMetricsService, private readonly config: Config ) {} /** * Initializes the Cache registry */ async initialize(): Promise<void> { // Flush the entire cache if requested if (this.config.clearCache) { await this.flushCache(); } // Otherwise, update the disk cache await this.updateDiskCache(); } /** * Gets the contents for the polyfill with the given name and with the given encoding */ async get(name: PolyfillFeature | Set<PolyfillFeature>, context: PolyfillCachingContext): Promise<IRegistryGetResult | undefined> { // Attempt to fetch it from the in-memory registry const memoryHit = await this.memoryRegistry.get(name, context); if (memoryHit != null) return memoryHit; // Otherwise, attempt to get it from cache const buffer = await this.getFromCache(this.getCachePath(name, context)); // If not possible, return undefined if (buffer == null) return undefined; // Otherwise, store it in the memory registry and return the Buffer return await this.memoryRegistry.set(name, buffer, context); } /** * Gets the Set of Polyfill feature inputs that matches the given input */ async getPolyfillFeatureSet(input: Set<PolyfillFeatureInput>, context: PolyfillCachingContext): Promise<Set<PolyfillFeature> | undefined> { // Attempt to fetch it from the in-memory registry const memoryHit = await this.memoryRegistry.getPolyfillFeatureSet(input, context); if (memoryHit != null) return memoryHit; // Otherwise, attempt to get it from cache const cachePath = this.getCachePathForPolyfillSet(input, context); const buffer = await this.getFromCache(cachePath); // If not possible, return undefined if (buffer == null) return undefined; // Otherwise, store it in the memory registry and return the Buffer try { const polyfillFeatures = JSON.parse(buffer.toString()); return await this.memoryRegistry.setPolyfillFeatureSet(input, new Set(polyfillFeatures), context); } catch (ex) { // It wasn't possible to parse that buffer. The disk cache is in an invalid state, and should be cleaned up await this.deleteFromCache(cachePath); this.metricsService.captureMessage(`Wiped bad cache entry at path: ${cachePath}`); return undefined; } } /** * Returns true if a polyfill wil the given name exists */ async has(name: PolyfillFeature | Set<PolyfillFeature>, context: PolyfillCachingContext): Promise<boolean> { return (await this.get(name, context)) != null; } /** * Returns true if there is a PolyfillFeature Set in the cache that matches the given input Set */ async hasPolyfillFeatureSet(input: Set<PolyfillFeatureInput>, context: PolyfillCachingContext): Promise<boolean> { return (await this.getPolyfillFeatureSet(input, context)) != null; } /** * Sets the contents for the polyfill with the given name and of the given encoding */ async set(name: PolyfillFeature | Set<PolyfillFeature>, contents: Buffer, context: PolyfillCachingContext): Promise<IRegistryGetResult> { // Add it to the memory cache as well as the disk cache await this.writeToCache(this.getCachePath(name, context), contents); return await this.memoryRegistry.set(name, contents, context); } /** * Sets the given PolyfillFeature Set for the given Set of PolyfillFeature inputs */ async setPolyfillFeatureSet(input: Set<PolyfillFeatureInput>, polyfillSet: Set<PolyfillFeature>, context: PolyfillCachingContext): Promise<Set<PolyfillFeature>> { // Add it to the memory cache as well as the disk cache await this.writeToCache(this.getCachePathForPolyfillSet(input, context), Buffer.from(JSON.stringify([...polyfillSet]))); return await this.memoryRegistry.setPolyfillFeatureSet(input, polyfillSet, context); } /** * Returns true if the given polyfill name needs an update within the cache */ async needsUpdate(polyfillName: PolyfillName, currentVersion: string): Promise<boolean> { const packageVersionMap = await this.getPackageVersionMap(); const cachedVersion = packageVersionMap[polyfillName]; return cachedVersion == null || isNaN(parseInt(cachedVersion)) || gt(coerce(currentVersion)!.version, coerce(cachedVersion)!.version); } /** * Updates the cached package version map */ async updatePackageVersionMap(options: IterableIterator<[PolyfillName, string]>): Promise<void> { const packageVersionMap = await this.getPackageVersionMap(); for (const [name, version] of options) { packageVersionMap[name] = version; } await this.fileSystem.writeFile(constant.path.cachePackageVersionMap, JSON.stringify(packageVersionMap, null, " ")); } private pickVersionForPolyfillEntry(entry: PolyfillDictNormalizedEntry): string { if ("library" in entry) { if (typeof entry.library === "string") { return pkg.dependencies[entry.library]; } let combinedVersionSet = new Set<string>(); for (const key of ["window", "worker", "node"] as const) { if (entry.library[key] == null) continue; combinedVersionSet.add(pkg.dependencies[entry.library[key]]); return [...combinedVersionSet].join(":"); } throw new ReferenceError(`It wasn't possible to detect a version for the library: ${entry.library}`); } else { return entry.version; } } /** * Updates the disk cache. If the cache is already valid, there is nothing to do. * Otherwise, it will store all polyfilled libraries and their current versions */ private async updateDiskCache(): Promise<void> { // Start with validating the disk cache const cacheIsValid = await this.validateDiskCache(); // If the cache is valid, do no more if (cacheIsValid) return; // Otherwise, build a map of libraries and their versions const libraryToVersionMap: Map<PolyfillName, string> = new Map(); const entries = Object.entries(constant.polyfill) as [PolyfillName, PolyfillDictEntry][]; await Promise.all( entries.map(async ([polyfillName, polyfill]) => { // Skip aliases if ("polyfills" in polyfill) return; // Map the version to the library name if (!libraryToVersionMap.has(polyfillName)) { libraryToVersionMap.set(polyfillName, this.pickVersionForPolyfillEntry(polyfill)); } }) ); // Update the disk cache await this.updatePackageVersionMap(libraryToVersionMap.entries()); await this.updateCachedPolyfillConfigChecksumPackageVersionMap(); } /** * Validates the disk cache. If any version of any package has been updated, * the entire cache will be flushed. * If 'true' is returned, the cache is valid */ private async validateDiskCache(): Promise<boolean> { const lastCachedConfigChecksum = await this.getLastCachedPolyfillConfigChecksum(); // If the config changed, the disk cache needs to be flushed if (lastCachedConfigChecksum !== getPolyfillConfigChecksum()) { this.logger.debug(`The checksum for the config changed! Flushing cache...`); await this.flushCache(); return false; } for (const [polyfillName, polyfill] of Object.entries(constant.polyfill)) { // Skip aliases if ("polyfills" in polyfill) continue; // If the local copy of the polyfill needs to be updated, flush the entire cache if (await this.needsUpdate(polyfillName as PolyfillName, this.pickVersionForPolyfillEntry(polyfill))) { this.logger.debug(`${polyfillName} needs an update! Flushing cache...`); await this.flushCache(); return false; } } return true; } /** * Flushes the cache entirely */ private async flushCache(): Promise<boolean> { return this.fileSystem.delete(constant.path.cacheRoot); } /** * Writes the given Buffer to cache */ private async writeToCache(path: string, content: Buffer): Promise<void> { return this.fileSystem.writeFile(path, content); } /** * Gets the package version map from the cache. A new one will be created if it doesn't exist already * * @returns */ private async getPackageVersionMap(): Promise<{[key: string]: string}> { const packageVersionMapRaw = await this.getFromCache(constant.path.cachePackageVersionMap); try { return packageVersionMapRaw == null ? {} : JSON.parse(packageVersionMapRaw.toString()); } catch (ex) { // If it couldn't be decoded, fall back to an empty cache map, but also flush that entry from the cache await this.deleteFromCache(constant.path.cachePackageVersionMap); this.metricsService.captureMessage(`Wiped bad package version map from the cache at path: ${constant.path.cachePackageVersionMap}`); return {}; } } private async getLastCachedPolyfillConfigChecksum(): Promise<string | undefined> { const buffer = await this.getFromCache(constant.path.configChecksum); return buffer != null ? buffer.toString("utf8") : undefined; } private async updateCachedPolyfillConfigChecksumPackageVersionMap(): Promise<void> { await this.fileSystem.writeFile(constant.path.configChecksum, getPolyfillConfigChecksum()); } /** * Returns the contents on the given path from the cache */ private async getFromCache(path: string): Promise<Buffer | undefined> { return this.fileSystem.readFile(path); } /** * Deletes the contents on the given path from the cache */ private async deleteFromCache(path: string): Promise<boolean> { return this.fileSystem.delete(path); } /** * Gets the cache path to the given name and encoding */ private getCachePath(name: PolyfillFeature | Set<PolyfillFeature>, context: PolyfillCachingContext): string { return join(constant.path.cacheRoot, getPolyfillIdentifier(name, context)); } /** * Gets the cache path to the given Polyfill Feature Set */ private getCachePathForPolyfillSet(input: Set<PolyfillFeatureInput>, context: PolyfillCachingContext): string { return join(constant.path.cacheRoot, getPolyfillSetIdentifier(input, context)); } }
the_stack
import * as path from "path"; import { Load } from "koatty_loader"; import { Koatty } from 'koatty_core'; import { LoadConfigs as loadConf } from "koatty_config"; import { Logger, SetLogger } from "../util/Logger"; import { prevent } from "koatty_exception"; import { IMiddleware, IPlugin } from './Component'; import { AppReadyHookFunc } from "./Bootstrap"; import { checkClass, Helper } from "../util/Helper"; import { IOCContainer, TAGGED_CLS } from "koatty_container"; import { APP_READY_HOOK, COMPONENT_SCAN, CONFIGURATION_SCAN } from './Constants'; import { BaseController } from "../controller/BaseController"; import { TraceMiddleware } from "../middleware/TraceMiddleware"; import { PayloadMiddleware } from "../middleware/PayloadMiddleware"; /** * * * @interface ComponentItem */ interface ComponentItem { id: string; target: any; } /** * */ export class Loader { /** * initialize env * * @static * @param {Koatty} app * @memberof Loader */ public static initialize(app: Koatty) { const env = (process.execArgv ?? []).join(","); if (env.indexOf('ts-node') > -1 || env.indexOf('--debug') > -1) { app.appDebug = true; } // app.env app.env = process.env.KOATTY_ENV || process.env.NODE_ENV; if ((env.indexOf('--production') > -1) || ((app.env ?? '').indexOf('pro') > -1)) { app.appDebug = false; } if (app.appDebug) { app.env = 'development'; process.env.NODE_ENV = 'development'; process.env.APP_DEBUG = 'true'; Logger.setLevel("DEBUG"); } else { app.env = 'production'; process.env.NODE_ENV = 'production'; Logger.setLevel("INFO"); } // define path const rootPath = app.rootPath || process.cwd(); const appPath = app.appPath || path.resolve(rootPath, env.indexOf('ts-node') > -1 ? 'src' : 'dist'); const thinkPath = path.resolve(__dirname, '..'); Helper.define(app, 'rootPath', rootPath); Helper.define(app, 'appPath', appPath); Helper.define(app, 'thinkPath', thinkPath); process.env.ROOT_PATH = rootPath; process.env.APP_PATH = appPath; process.env.THINK_PATH = thinkPath; // Compatible with old version, will be deprecated Helper.define(app, 'prevent', prevent); Helper.define(app, 'root_path', rootPath); Helper.define(app, 'app_path', appPath); Helper.define(app, 'think_path', thinkPath); } /** * Get component metadata * * @static * @param {Koatty} app * @param {*} target * @returns {*} {any[]} * @memberof Loader */ public static GetComponentMetas(app: Koatty, target: any): any[] { let componentMetas = []; const componentMeta = IOCContainer.getClassMetadata(TAGGED_CLS, COMPONENT_SCAN, target); if (componentMeta) { if (Helper.isArray(componentMeta)) { componentMetas = componentMeta; } else { componentMetas.push(componentMeta); } } if (componentMetas.length < 1) { componentMetas = [app.appPath]; } return componentMetas; } /** * Load all bean, excepted config/*、App.ts * * @static * @param {Koatty} app * @param {*} target * @memberof Loader */ public static CheckAllComponents(app: Koatty, target: any) { // component metadata const componentMetas = Loader.GetComponentMetas(app, target); // configuration metadata const configurationMetas = Loader.GetConfigurationMetas(app, target); const exSet = new Set(); Load(componentMetas, '', (fileName: string, xpath: string, xTarget: any) => { checkClass(fileName, xpath, xTarget, exSet); }, ['**/**.js', '**/**.ts', '!**/**.d.ts'], [...configurationMetas, `${target.name || '.no'}.ts`]); exSet.clear(); } /** * Get configuration metadata * * @static * @param {Koatty} app * @param {*} target * @returns {*} {any[]} * @memberof Loader */ public static GetConfigurationMetas(app: Koatty, target: any): any[] { const confMeta = IOCContainer.getClassMetadata(TAGGED_CLS, CONFIGURATION_SCAN, target); let configurationMetas = []; if (confMeta) { if (Helper.isArray(confMeta)) { configurationMetas = confMeta; } else { configurationMetas.push(confMeta); } } return configurationMetas; } /** * Set Logger level * * @static * @param {Koatty} app * @memberof Loader */ public static SetLogger(app: Koatty) { const configs = app.getMetaData("_configs") ?? {}; //Logger if (configs.config) { const opt = configs.config; let logLevel: any = "DEBUG", logFileLevel: any = "INFO", logConsole = true, logFile = false, logFilePath = app.rootPath + "/logs"; if (app.env === "production") { logLevel = "INFO"; logFileLevel = "WARN"; logConsole = false; logFile = true; } if (opt.logs_level) { logLevel = opt.logs_level; } if (opt.logs_write_level) { logFileLevel = opt.logs_write_level; } if (opt.logs_write !== undefined) { logFile = !!opt.logs_write; } if (opt.logs_console !== undefined) { logConsole = !!opt.logs_console; } if (opt.logs_path) { logFilePath = opt.logs_path; } SetLogger(app, { logLevel, logConsole, logFile, logFileLevel, logFilePath }); } } /** * Load app ready hook funcs * * @static * @param {Koatty} app * @param {*} target * @memberof Loader */ public static LoadAppReadyHooks(app: Koatty, target: any) { const funcs = IOCContainer.getClassMetadata(TAGGED_CLS, APP_READY_HOOK, target); if (Helper.isArray(funcs)) { funcs.forEach((element: AppReadyHookFunc): any => { app.once('appReady', () => element(app)); return null; }); } } /** * Load configuration * * @static * @param {Koatty} app * @param {string[]} [loadPath] * @memberof Loader */ public static LoadConfigs(app: Koatty, loadPath?: string[]) { const frameConfig: any = {}; // Logger.Debug(`Load configuration path: ${app.thinkPath}/config`); Load(["./config"], app.thinkPath, function (name: string, path: string, exp: any) { frameConfig[name] = exp; }); if (Helper.isArray(loadPath)) { loadPath = loadPath.length > 0 ? loadPath : ["./config"]; } let appConfig = loadConf(loadPath, app.appPath); appConfig = Helper.extend(frameConfig, appConfig, true); app.setMetaData("_configs", appConfig); } /** * Load middlewares * [async] * @static * @param {*} app * @param {(string | string[])} [loadPath] * @memberof Loader */ public static async LoadMiddlewares(app: Koatty, loadPath?: string[]) { let middlewareConf = app.config(undefined, "middleware"); if (Helper.isEmpty(middlewareConf)) { middlewareConf = { config: {}, list: [] }; } //Mount default middleware Load(loadPath || ["./middleware"], app.thinkPath); //Mount application middleware // const middleware: any = {}; const appMiddleware = IOCContainer.listClass("MIDDLEWARE") ?? []; appMiddleware.push({ id: "TraceMiddleware", target: TraceMiddleware }); appMiddleware.push({ id: "PayloadMiddleware", target: PayloadMiddleware }); appMiddleware.forEach((item: ComponentItem) => { item.id = (item.id ?? "").replace("MIDDLEWARE:", ""); if (item.id && Helper.isClass(item.target)) { IOCContainer.reg(item.id, item.target, { scope: "Prototype", type: "MIDDLEWARE", args: [] }); } }); const middlewareConfList = middlewareConf.list; const defaultList = ["TraceMiddleware", "PayloadMiddleware"]; //de-duplication const appMList = new Set(defaultList); middlewareConfList.forEach((item: string) => { if (!defaultList.includes(item)) { appMList.add(item); } }); //Automatically call middleware for (const key of appMList) { const handle: IMiddleware = IOCContainer.get(key, "MIDDLEWARE"); if (!handle) { Logger.Error(`Middleware ${key} load error.`); continue; } if (!Helper.isFunction(handle.run)) { Logger.Error(`Middleware ${key} must be implements method 'run'.`); continue; } if (middlewareConf.config[key] === false) { // Default middleware cannot be disabled if (defaultList.includes(key)) { Logger.Warn(`Middleware ${key} cannot be disabled.`); } else { Logger.Warn(`Middleware ${key} is loaded but not allowed to execute.`); continue; } } Logger.Debug(`Load middleware: ${key}`); const result = await handle.run(middlewareConf.config[key] || {}, app); if (Helper.isFunction(result)) { if (result.length < 3) { app.use(result); } else { app.useExp(result); } } } } /** * Load controllers * * @static * @param {*} app * @memberof Loader */ public static LoadControllers(app: Koatty) { const controllerList = IOCContainer.listClass("CONTROLLER"); const controllers: string[] = []; controllerList.forEach((item: ComponentItem) => { item.id = (item.id ?? "").replace("CONTROLLER:", ""); if (item.id && Helper.isClass(item.target)) { Logger.Debug(`Load controller: ${item.id}`); // registering to IOC IOCContainer.reg(item.id, item.target, { scope: "Prototype", type: "CONTROLLER", args: [] }); const ctl = IOCContainer.getInsByClass(item.target); if (!(ctl instanceof BaseController)) { throw new Error(`class ${item.id} does not inherit from BaseController`); } controllers.push(item.id); } }); return controllers; } /** * Load services * * @static * @param {*} app * @memberof Loader */ public static LoadServices(app: Koatty) { const serviceList = IOCContainer.listClass("SERVICE"); serviceList.forEach((item: ComponentItem) => { item.id = (item.id ?? "").replace("SERVICE:", ""); if (item.id && Helper.isClass(item.target)) { Logger.Debug(`Load service: ${item.id}`); // registering to IOC IOCContainer.reg(item.id, item.target, { scope: "Singleton", type: "SERVICE", args: [] }); } }); } /** * Load components * * @static * @param {*} app * @memberof Loader */ public static LoadComponents(app: Koatty) { const componentList = IOCContainer.listClass("COMPONENT"); componentList.forEach((item: ComponentItem) => { item.id = (item.id ?? "").replace("COMPONENT:", ""); if (item.id && !(item.id).endsWith("Plugin") && Helper.isClass(item.target)) { Logger.Debug(`Load component: ${item.id}`); // registering to IOC IOCContainer.reg(item.id, item.target, { scope: "Singleton", type: "COMPONENT", args: [] }); } }); } /** * Load plugins * * @static * @param {*} app * @memberof Loader */ public static async LoadPlugins(app: Koatty) { const componentList = IOCContainer.listClass("COMPONENT"); let pluginsConf = app.config(undefined, "plugin"); if (Helper.isEmpty(pluginsConf)) { pluginsConf = { config: {}, list: [] }; } const pluginList = []; componentList.forEach(async (item: ComponentItem) => { item.id = (item.id ?? "").replace("COMPONENT:", ""); if (item.id && (item.id).endsWith("Plugin") && Helper.isClass(item.target)) { // registering to IOC IOCContainer.reg(item.id, item.target, { scope: "Singleton", type: "COMPONENT", args: [] }); pluginList.push(item.id); } }); const pluginConfList = pluginsConf.list; if (pluginList.length > pluginConfList.length) { Logger.Warn("Some plugins is loaded but not allowed to execute."); } for (const key of pluginConfList) { const handle: IPlugin = IOCContainer.get(key, "COMPONENT"); if (!Helper.isFunction(handle.run)) { Logger.Error(`plugin ${key} must be implements method 'run'.`); continue; } if (pluginsConf.config[key] === false) { continue; } // sync exec await handle.run(pluginsConf.config[key] ?? {}, app); } } }
the_stack
import { aws_apigateway, aws_iam } from "aws-cdk-lib"; import type { DynamoDB as AWSDynamoDB, EventBridge } from "aws-sdk"; import { JsonFormat } from "typesafe-dynamodb"; import { TypeSafeDynamoDBv2 } from "typesafe-dynamodb/lib/client-v2"; import { DeleteItemInput, DeleteItemOutput, } from "typesafe-dynamodb/lib/delete-item"; import { GetItemInput, GetItemOutput } from "typesafe-dynamodb/lib/get-item"; import { TableKey } from "typesafe-dynamodb/lib/key"; import { PutItemInput, PutItemOutput } from "typesafe-dynamodb/lib/put-item"; import { QueryInput, QueryOutput } from "typesafe-dynamodb/lib/query"; import { ScanInput, ScanOutput } from "typesafe-dynamodb/lib/scan"; import { UpdateItemInput, UpdateItemOutput, } from "typesafe-dynamodb/lib/update-item"; import { ASL } from "./asl"; import { ErrorCodes, SynthError } from "./error-code"; import { Argument, Expr, isVariableReference } from "./expression"; import { Function, isFunction, NativeIntegration, NativePreWarmContext, PrewarmClients, } from "./function"; import { isArgument, isIdentifier, isObjectLiteralExpr, isPropAssignExpr, isReferenceExpr, isStringLiteralExpr, } from "./guards"; import { IntegrationCall, IntegrationInput, makeIntegration, } from "./integration"; import { isTable, AnyTable, ITable } from "./table"; import type { AnyFunction } from "./util"; type Item<T extends ITable<any, any, any>> = T extends ITable<infer I, any, any> ? I : never; type PartitionKey<T extends ITable<any, any, any>> = T extends ITable< any, infer PK, any > ? PK : never; type RangeKey<T extends ITable<any, any, any>> = T extends ITable< any, any, infer SK > ? SK : never; export function isAWS(a: any): a is typeof $AWS { return a?.kind === "AWS"; } /** * The `AWS` namespace exports functions that map to AWS Step Functions AWS-SDK Integrations. * * @see https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html */ export namespace $AWS { export const kind = "AWS"; /** * @see https://docs.aws.amazon.com/step-functions/latest/dg/connect-ddb.html */ export namespace DynamoDB { /** * @see https://docs.aws.amazon.com/step-functions/latest/dg/connect-ddb.html */ export const DeleteItem = makeDynamoIntegration< "deleteItem", < T extends ITable<any, any, any>, Key extends TableKey< Item<T>, PartitionKey<T>, RangeKey<T>, JsonFormat.AttributeValue >, ConditionExpression extends string | undefined, ReturnValue extends AWSDynamoDB.ReturnValue = "NONE" >( input: { TableName: T } & Omit< DeleteItemInput< Item<T>, PartitionKey<T>, RangeKey<T>, Key, ConditionExpression, ReturnValue, JsonFormat.AttributeValue >, "TableName" > ) => DeleteItemOutput<Item<T>, ReturnValue, JsonFormat.AttributeValue> >("deleteItem", { native: { bind: (context, table) => { table.resource.grantWriteData(context.resource); }, call: async (args, preWarmContext) => { const dynamo = preWarmContext.getOrInit< TypeSafeDynamoDBv2< Item<AnyTable>, PartitionKey<AnyTable>, RangeKey<AnyTable> > >(PrewarmClients.DYNAMO); const [input] = args; const { TableName: table, ...rest } = input; return dynamo .deleteItem({ ...rest, TableName: input.TableName.tableName, }) .promise(); }, }, }); /** * @see https://docs.aws.amazon.com/step-functions/latest/dg/connect-ddb.html */ export const GetItem = makeDynamoIntegration< "getItem", < Item extends object, PartitionKey extends keyof Item, RangeKey extends keyof Item | undefined, Key extends TableKey< Item, PartitionKey, RangeKey, JsonFormat.AttributeValue >, AttributesToGet extends keyof Item | undefined = undefined, ProjectionExpression extends string | undefined = undefined >( input: { TableName: ITable<Item, PartitionKey, RangeKey> } & Omit< GetItemInput< Item, PartitionKey, RangeKey, Key, AttributesToGet, ProjectionExpression, JsonFormat.AttributeValue >, "TableName" > ) => GetItemOutput< Item, PartitionKey, RangeKey, Key, AttributesToGet, ProjectionExpression, JsonFormat.AttributeValue > >("getItem", { native: { bind: (context: Function<any, any>, table: AnyTable) => { table.resource.grantReadData(context.resource); }, call: async ( args: [ { TableName: AnyTable } & Omit< GetItemInput< Item<AnyTable>, PartitionKey<AnyTable>, RangeKey<AnyTable>, any, any, any, any >, "TableName" > ], preWarmContext: NativePreWarmContext ) => { const dynamo = preWarmContext.getOrInit< TypeSafeDynamoDBv2< Item<AnyTable>, PartitionKey<AnyTable>, RangeKey<AnyTable> > >(PrewarmClients.DYNAMO); const [input] = args; const { TableName: table, AttributesToGet, ...rest } = input; const payload = { ...rest, AttributesToGet: AttributesToGet as any, TableName: table.tableName, }; return dynamo.getItem(payload).promise(); }, // Typesafe DynamoDB was causing a "excessive depth error" } as any, }); /** * @see https://docs.aws.amazon.com/step-functions/latest/dg/connect-ddb.html */ export const UpdateItem = makeDynamoIntegration< "updateItem", < T extends ITable<any, any, any>, Key extends TableKey< Item<T>, PartitionKey<T>, RangeKey<T>, JsonFormat.AttributeValue >, UpdateExpression extends string, ConditionExpression extends string | undefined = undefined, ReturnValue extends AWSDynamoDB.ReturnValue = "NONE" >( input: { TableName: T } & Omit< UpdateItemInput< Item<T>, PartitionKey<T>, RangeKey<T>, Key, UpdateExpression, ConditionExpression, ReturnValue, JsonFormat.AttributeValue >, "TableName" > ) => UpdateItemOutput< Item<T>, PartitionKey<T>, RangeKey<T>, Key, ReturnValue, JsonFormat.AttributeValue > >("updateItem", { native: { bind: (context, table) => { table.resource.grantWriteData(context.resource); }, call: async (args, preWarmContext) => { const dynamo = preWarmContext.getOrInit< TypeSafeDynamoDBv2< Item<AnyTable>, PartitionKey<AnyTable>, RangeKey<AnyTable> > >(PrewarmClients.DYNAMO); const [input] = args; const { TableName: table, ...rest } = input; return dynamo .updateItem({ ...rest, TableName: table.tableName, }) .promise(); }, }, }); /** * @see https://docs.aws.amazon.com/step-functions/latest/dg/connect-ddb.html */ export const PutItem = makeDynamoIntegration< "putItem", < T extends ITable<any, any, any>, I extends Item<T>, ConditionExpression extends string | undefined = undefined, ReturnValue extends AWSDynamoDB.ReturnValue = "NONE" >( input: { TableName: T } & Omit< PutItemInput< Item<T>, ConditionExpression, ReturnValue, JsonFormat.AttributeValue >, "TableName" > ) => PutItemOutput<I, ReturnValue, JsonFormat.AttributeValue> >("putItem", { native: { bind: (context, table) => { table.resource.grantWriteData(context.resource); }, call: async (args, preWarmContext) => { const dynamo = preWarmContext.getOrInit< TypeSafeDynamoDBv2< Item<AnyTable>, PartitionKey<AnyTable>, RangeKey<AnyTable> > >(PrewarmClients.DYNAMO); const [input] = args; const { TableName: table, Item, ...rest } = input; return dynamo .putItem({ ...rest, Item: Item as any, TableName: table.tableName, }) .promise(); }, }, }); export const Query = makeDynamoIntegration< "query", < T extends ITable<any, any, any>, KeyConditionExpression extends string, FilterExpression extends string | undefined = undefined, ProjectionExpression extends string | undefined = undefined, AttributesToGet extends keyof Item<T> | undefined = undefined >( input: { TableName: T } & Omit< QueryInput< Item<T>, KeyConditionExpression, FilterExpression, ProjectionExpression, AttributesToGet, JsonFormat.AttributeValue >, "TableName" > ) => QueryOutput<Item<T>, AttributesToGet, JsonFormat.AttributeValue> >("query", { native: { bind: (context, table) => { table.resource.grantReadData(context.resource); }, call: async (args, preWarmContext) => { const dynamo = preWarmContext.getOrInit< TypeSafeDynamoDBv2< Item<AnyTable>, PartitionKey<AnyTable>, RangeKey<AnyTable> > >(PrewarmClients.DYNAMO); const [input] = args; const { TableName: table, AttributesToGet, ...rest } = input; return dynamo .query({ ...rest, AttributesToGet: AttributesToGet as any, TableName: table.tableName, }) .promise(); }, }, }); export const Scan = makeDynamoIntegration< "scan", < T extends ITable<any, any, any>, FilterExpression extends string | undefined = undefined, ProjectionExpression extends string | undefined = undefined, AttributesToGet extends keyof Item<T> | undefined = undefined >( input: { TableName: T } & Omit< ScanInput< Item<T>, FilterExpression, ProjectionExpression, AttributesToGet, JsonFormat.AttributeValue >, "TableName" > ) => ScanOutput<Item<T>, AttributesToGet, JsonFormat.AttributeValue> >("scan", { native: { bind: (context, table) => { table.resource.grantReadData(context.resource); }, call: async (args, preWarmContext) => { const dynamo = preWarmContext.getOrInit< TypeSafeDynamoDBv2< Item<AnyTable>, PartitionKey<AnyTable>, RangeKey<AnyTable> > >(PrewarmClients.DYNAMO); const [input] = args; const { TableName: table, AttributesToGet, ...rest } = input; return dynamo .scan({ ...rest, AttributesToGet: AttributesToGet as any, TableName: table.tableName, }) .promise(); }, }, }); export type OperationName = | "deleteItem" | "getItem" | "putItem" | "updateItem" | "scan" | "query"; function makeDynamoIntegration< Op extends OperationName, F extends AnyFunction >( operationName: Op, integration: Omit< IntegrationInput<`$AWS.DynamoDB.${Op}`, F>, "kind" | "native" > & { native: Omit<NativeIntegration<F>, "preWarm" | "bind"> & { bind: (context: Function<any, any>, table: AnyTable) => void; }; } ): IntegrationCall<`$AWS.DynamoDB.${Op}`, F> { return makeIntegration<`$AWS.DynamoDB.${Op}`, F>({ ...integration, kind: `$AWS.DynamoDB.${operationName}`, apiGWVtl: { renderRequest(call, context) { const input = call.args[0].expr; if (!isObjectLiteralExpr(input)) { throw new SynthError( ErrorCodes.Expected_an_object_literal, `input to $AWS.DynamoDB.${operationName} must be an object literal` ); } const table = getTableArgument(operationName, call.args); // const table = getTableArgument(call.args.map((arg) => arg.expr!)); grantTablePermissions(table, context.role, operationName); return `{ "TableName":"${table.resource.tableName}", ${input.properties .flatMap((prop) => { if (isPropAssignExpr(prop)) { const name = isIdentifier(prop.name) ? prop.name : isStringLiteralExpr(prop.name) ? prop.name.value : undefined; if (name === undefined) { throw new SynthError( ErrorCodes.API_Gateway_does_not_support_computed_property_names ); } if (name === "TableName") { return []; } return [`"${name}":${context.exprToJson(prop.expr)}`]; } else { throw new SynthError( ErrorCodes.API_Gateway_does_not_support_spread_assignment_expressions ); } }) .join(",\n ")} }`; }, createIntegration: (options) => { return new aws_apigateway.AwsIntegration({ service: "dynamodb", action: operationName, integrationHttpMethod: "POST", options: { ...options, passthroughBehavior: aws_apigateway.PassthroughBehavior.NEVER, }, }); }, }, asl(call, context) { const input = call.getArgument("input")?.expr; if (!isObjectLiteralExpr(input)) { throw new Error( `input parameter must be an ObjectLiteralExpr, but was ${input?.kind}` ); } const table = getTableArgument(operationName, call.args); grantTablePermissions(table, context.role, operationName); return { Type: "Task", Resource: `arn:aws:states:::aws-sdk:dynamodb:${operationName}`, Parameters: ASL.toJson(input), }; }, native: { ...integration.native, bind: (context, args) => { const table = getTableArgument(operationName, args); integration.native.bind(context, table); }, preWarm(prewarmContext) { prewarmContext.getOrInit(PrewarmClients.DYNAMO); }, }, unhandledContext(kind, contextKind) { throw new Error( `${kind} is only available within an '${ASL.ContextName}' context, but was called from within a '${contextKind}' context.` ); }, }); } /** * @internal */ export function grantTablePermissions( table: AnyTable, role: aws_iam.IRole, operationName: OperationName ) { if ( operationName === "deleteItem" || operationName === "putItem" || operationName === "updateItem" ) { table.resource.grantWriteData(role); } else { table.resource.grantReadData(role); } } /** * @internal */ export function getTableArgument(op: string, args: Argument[] | Expr[]) { let inputArgument; if (isArgument(args[0])) { inputArgument = args[0].expr; } else { inputArgument = args[0]; } // integ(input: { TableName }) if (!inputArgument || !isObjectLiteralExpr(inputArgument)) { throw new SynthError( ErrorCodes.Expected_an_object_literal, `First argument into ${op} should be an input object, found ${inputArgument?.kind}` ); } const tableProp = inputArgument.getProperty("TableName"); if (!tableProp || !isPropAssignExpr(tableProp)) { throw new SynthError( ErrorCodes.Expected_an_object_literal, `First argument into ${op} should be an input with a property TableName that is a Table.` ); } const tableRef = tableProp.expr; if (!isReferenceExpr(tableRef)) { throw new SynthError( ErrorCodes.Expected_an_object_literal, `First argument into ${op} should be an input with a property TableName that is a Table.` ); } const table = tableRef.ref(); if (!isTable(table)) { throw Error(`TableName argument should be a Table object.`); } return table; } } export namespace Lambda { /** * @param input * @see https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html */ export const Invoke = makeIntegration< "Lambda.Invoke", <Input, Output>(input: { FunctionName: Function<Input, Output>; Payload: Input; ClientContext?: string; InvocationType?: "Event" | "RequestResponse" | "DryRun"; LogType?: "None" | "Tail"; Qualifier?: string; }) => Omit<AWS.Lambda.InvocationResponse, "payload"> & { Payload: Output; } >({ kind: "Lambda.Invoke", asl(call) { const input = call.args[0].expr; if (input === undefined) { throw new Error("missing argument 'input'"); } else if (input.kind !== "ObjectLiteralExpr") { throw new Error("argument 'input' must be an ObjectLiteralExpr"); } const functionName = input.getProperty("FunctionName")?.expr; if (functionName === undefined) { throw new Error("missing required property 'FunctionName'"); } else if (functionName.kind !== "ReferenceExpr") { throw new Error( "property 'FunctionName' must reference a functionless.Function" ); } const functionRef = functionName.ref(); if (!isFunction(functionRef)) { throw new Error( "property 'FunctionName' must reference a functionless.Function" ); } const payload = input.getProperty("Payload")?.expr; if (payload === undefined) { throw new Error("missing property 'payload'"); } return { Type: "Task", Resource: "arn:aws:states:::lambda:invoke", Parameters: { FunctionName: functionRef.resource.functionName, [`Payload${payload && isVariableReference(payload) ? ".$" : ""}`]: payload ? ASL.toJson(payload) : null, }, }; }, unhandledContext(kind, contextKind) { throw new Error( `$AWS.${kind} is only available within an '${ASL.ContextName}' context, but was called from within a '${contextKind}' context.` ); }, }); } export namespace EventBridge { /** * @see https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutEvents.html */ export const putEvents = makeIntegration< "EventBridge.putEvent", ( request: AWS.EventBridge.Types.PutEventsRequest ) => AWS.EventBridge.Types.PutEventsResponse >({ kind: "EventBridge.putEvent", native: { // Access needs to be granted manually bind: () => {}, preWarm: (prewarmContext: NativePreWarmContext) => { prewarmContext.getOrInit(PrewarmClients.EVENT_BRIDGE); }, call: async ([request], preWarmContext) => { const eventBridge = preWarmContext.getOrInit<EventBridge>( PrewarmClients.EVENT_BRIDGE ); return eventBridge .putEvents({ Entries: request.Entries.map((e) => ({ ...e, })), }) .promise(); }, }, }); } }
the_stack
import {BrowserWindow, shell, WebContents} from 'electron'; import log from 'electron-log'; import {TeamWithTabs} from 'types/config'; import urlUtils from 'common/utils/url'; import ContextMenu from 'main/contextMenu'; import WindowManager from '../windows/windowManager'; import {protocols} from '../../../electron-builder.json'; import allowProtocolDialog from '../allowProtocolDialog'; import {composeUserAgent} from '../utils'; import {MattermostView} from './MattermostView'; type CustomLogin = { inProgress: boolean; } const scheme = protocols && protocols[0] && protocols[0].schemes && protocols[0].schemes[0]; export class WebContentsEventManager { customLogins: Record<number, CustomLogin>; listeners: Record<number, () => void>; popupWindow?: BrowserWindow; constructor() { this.customLogins = {}; this.listeners = {}; } isTrustedPopupWindow = (webContents: WebContents) => { if (!webContents) { return false; } if (!this.popupWindow) { return false; } return BrowserWindow.fromWebContents(webContents) === this.popupWindow; } generateWillNavigate = (getServersFunction: () => TeamWithTabs[]) => { return (event: Event & {sender: WebContents}, url: string) => { const contentID = event.sender.id; const parsedURL = urlUtils.parseURL(url)!; const configServers = getServersFunction(); const server = urlUtils.getView(parsedURL, configServers); if (server && (urlUtils.isTeamUrl(server.url, parsedURL) || urlUtils.isAdminUrl(server.url, parsedURL) || this.isTrustedPopupWindow(event.sender))) { return; } if (server && urlUtils.isCustomLoginURL(parsedURL, server, configServers)) { return; } if (parsedURL.protocol === 'mailto:') { return; } if (this.customLogins[contentID]?.inProgress) { return; } log.info(`Prevented desktop from navigating to: ${url}`); event.preventDefault(); }; }; generateDidStartNavigation = (getServersFunction: () => TeamWithTabs[]) => { return (event: Event & {sender: WebContents}, url: string) => { const serverList = getServersFunction(); const contentID = event.sender.id; const parsedURL = urlUtils.parseURL(url)!; const server = urlUtils.getView(parsedURL, serverList); if (!urlUtils.isTrustedURL(parsedURL, serverList)) { return; } const serverURL = urlUtils.parseURL(server?.url || ''); if (server && urlUtils.isCustomLoginURL(parsedURL, server, serverList)) { this.customLogins[contentID].inProgress = true; } else if (server && this.customLogins[contentID].inProgress && urlUtils.isInternalURL(serverURL || new URL(''), parsedURL)) { this.customLogins[contentID].inProgress = false; } }; }; denyNewWindow = (details: Electron.HandlerDetails): {action: 'deny' | 'allow'} => { log.warn(`Prevented popup window to open a new window to ${details.url}.`); return {action: 'deny'}; }; generateNewWindowListener = (getServersFunction: () => TeamWithTabs[], spellcheck?: boolean) => { return (details: Electron.HandlerDetails): {action: 'deny' | 'allow'} => { const parsedURL = urlUtils.parseURL(details.url); if (!parsedURL) { log.warn(`Ignoring non-url ${details.url}`); return {action: 'deny'}; } const configServers = getServersFunction(); // Dev tools case if (parsedURL.protocol === 'devtools:') { return {action: 'allow'}; } // Check for custom protocol if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:' && parsedURL.protocol !== `${scheme}:`) { allowProtocolDialog.handleDialogEvent(parsedURL.protocol, details.url); return {action: 'deny'}; } // Check for valid URL // Let the browser handle invalid URIs if (!urlUtils.isValidURI(details.url)) { shell.openExternal(details.url); return {action: 'deny'}; } const server = urlUtils.getView(parsedURL, configServers); if (!server) { shell.openExternal(details.url); return {action: 'deny'}; } // Public download links case // TODO: We might be handling different types differently in the future, for now // we are going to mimic the browser and just pop a new browser window for public links if (parsedURL.pathname.match(/^(\/api\/v[3-4]\/public)*\/files\//)) { shell.openExternal(details.url); return {action: 'deny'}; } // Image proxy case if (parsedURL.pathname.match(/^\/api\/v[3-4]\/image/)) { shell.openExternal(details.url); return {action: 'deny'}; } if (parsedURL.pathname.match(/^\/help\//)) { // Help links case // continue to open special case internal urls in default browser shell.openExternal(details.url); return {action: 'deny'}; } if (urlUtils.isTeamUrl(server.url, parsedURL, true)) { WindowManager.showMainWindow(parsedURL); return {action: 'deny'}; } if (urlUtils.isAdminUrl(server.url, parsedURL)) { log.info(`${details.url} is an admin console page, preventing to open a new window`); return {action: 'deny'}; } if (this.popupWindow && this.popupWindow.webContents.getURL() === details.url) { log.info(`Popup window already open at provided url: ${details.url}`); return {action: 'deny'}; } // TODO: move popups to its own and have more than one. if (urlUtils.isPluginUrl(server.url, parsedURL) || urlUtils.isManagedResource(server.url, parsedURL)) { if (!this.popupWindow) { this.popupWindow = new BrowserWindow({ backgroundColor: '#fff', // prevents blurry text: https://electronjs.org/docs/faq#the-font-looks-blurry-what-is-this-and-what-can-i-do //parent: WindowManager.getMainWindow(), show: false, center: true, webPreferences: { nativeWindowOpen: true, spellcheck: (typeof spellcheck === 'undefined' ? true : spellcheck), }, }); this.popupWindow.webContents.setWindowOpenHandler(this.denyNewWindow); this.popupWindow.once('ready-to-show', () => { this.popupWindow!.show(); }); this.popupWindow.once('closed', () => { this.popupWindow = undefined; }); } if (urlUtils.isManagedResource(server.url, parsedURL)) { this.popupWindow.loadURL(details.url); } else { // currently changing the userAgent for popup windows to allow plugins to go through google's oAuth // should be removed once a proper oAuth2 implementation is setup. this.popupWindow.loadURL(details.url, { userAgent: composeUserAgent(), }); } const contextMenu = new ContextMenu({}, this.popupWindow); contextMenu.reload(); } return {action: 'deny'}; }; }; removeWebContentsListeners = (id: number) => { if (this.listeners[id]) { this.listeners[id](); } }; addWebContentsEventListeners = (mmview: MattermostView, getServersFunction: () => TeamWithTabs[]) => { const contents = mmview.view.webContents; // initialize custom login tracking this.customLogins[contents.id] = { inProgress: false, }; if (this.listeners[contents.id]) { this.removeWebContentsListeners(contents.id); } const willNavigate = this.generateWillNavigate(getServersFunction); contents.on('will-navigate', willNavigate as (e: Event, u: string) => void); // TODO: Electron types don't include sender for some reason // handle custom login requests (oath, saml): // 1. are we navigating to a supported local custom login path from the `/login` page? // - indicate custom login is in progress // 2. are we finished with the custom login process? // - indicate custom login is NOT in progress const didStartNavigation = this.generateDidStartNavigation(getServersFunction); contents.on('did-start-navigation', didStartNavigation as (e: Event, u: string) => void); const spellcheck = mmview.options.webPreferences?.spellcheck; const newWindow = this.generateNewWindowListener(getServersFunction, spellcheck); contents.setWindowOpenHandler(newWindow); contents.on('page-title-updated', mmview.handleTitleUpdate); contents.on('page-favicon-updated', mmview.handleFaviconUpdate); contents.on('update-target-url', mmview.handleUpdateTarget); contents.on('did-navigate', mmview.handleDidNavigate); const removeListeners = () => { try { contents.removeListener('will-navigate', willNavigate as (e: Event, u: string) => void); contents.removeListener('did-start-navigation', didStartNavigation as (e: Event, u: string) => void); contents.removeListener('page-title-updated', mmview.handleTitleUpdate); contents.removeListener('page-favicon-updated', mmview.handleFaviconUpdate); contents.removeListener('update-target-url', mmview.handleUpdateTarget); contents.removeListener('did-navigate', mmview.handleDidNavigate); } catch (e) { log.error(`Error while trying to detach listeners, this might be ok if the process crashed: ${e}`); } }; this.listeners[contents.id] = removeListeners; contents.once('render-process-gone', (event, details) => { if (details.reason !== 'clean-exit') { log.error('Renderer process for a webcontent is no longer available:', details.reason); } removeListeners(); }); }; } const webContentsEventManager = new WebContentsEventManager(); export default webContentsEventManager;
the_stack
import { Octokit } from '@octokit/rest'; import Jimp from 'jimp'; import { NextApiRequest, NextApiResponse } from 'next'; import seedrandom from 'seedrandom'; import YAML from 'yaml'; import { errorMessages, generateQueryParameterErrorMessage } from '../../../data/errorMessages'; import { systemColors } from '../../../data/systemColors'; const getGitHubToken = () => { const tokens = [process.env.GITHUB_TOKEN, process.env.GITHUB_TOKEN_2].filter(Boolean); return tokens[Math.floor(Math.random() * tokens.length)]; }; const fromAWS = (path: string) => 'https://s3.ca-central-1.amazonaws.com/austinpaquette.com'.concat(path); /* eslint-disable unicorn/no-for-loop */ const weightedRandom = (items: [string, number][], randomizer: () => number = Math.random) => { // First, we loop the main dataset to count up the total weight. We're starting the counter at one because the upper boundary of Math.random() is exclusive. let total = 1; for (let i = 0; i < items.length; ++i) { total += items[i][1]; } // Total in hand, we can now pick a random value akin to our // random index from before. const threshold = Math.floor(randomizer() * total); // Now we just need to loop through the main data one more time // until we discover which value would live within this // particular threshold. We need to keep a running count of // weights as we go, so let's just reuse the "total" variable // since it was already declared. total = 0; for (let i = 0; i < items.length; ++i) { // Add the weight to our running total. total += items[i][1]; // If this value falls within the threshold, we're done! if (total >= threshold) { return items[i][0]; } } }; /* eslint-enable unicorn/no-for-loop */ const hexToRgb = (hex: string): Nullable<RGB> => { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") const shorthandRegex = /^#?([\da-f])([\da-f])([\da-f])$/i; hex = hex.replace(shorthandRegex, function (_, r, g, b) { return r + r + g + g + b + b; }); const result = /^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i.exec(hex); return result ? { red: Number.parseInt(result[1], 16), green: Number.parseInt(result[2], 16), blue: Number.parseInt(result[3], 16), } : null; }; const acceptableParameters = { colors: ['repository', 'system'], dots: ['circle', 'square'], display: ['dark', 'light'], responseType: ['image', 'json'], }; export default async (request: NextApiRequest, response: NextApiResponse): Promise<void> => { try { /** * Incoming Endpoint Parameters */ const [owner, repo] = (request.query.repo as string[]) || ['pqt', 'social-preview']; /** * Incoming Query Parameter: GitHub Personal Access Token * ! (DO NOT STORE THIS ANYWHERE. EVER. USE IT, THEN LOSE IT.) */ const token: Nullable<string> = (request.query.token as string) || null; /** * Incoming Query Parameter: Custom Seed String for the randomizer function */ const seed: Nullable<string> = (request.query.seed as string) || null; /** * Incoming Query Parameter: Determines whether to generate the image with repository colors or system-provided ones */ let colors: Nullable<string> = (request.query.colors as string) || 'repository'; /** * Immediately throw if an invalid parameter value is requested */ if (!acceptableParameters.colors.includes(colors)) { throw generateQueryParameterErrorMessage('colors', acceptableParameters.colors, 'repository'); } /** * Conditionally used variable (only used if the colors param is set to repository) */ let linguist: Linguist; let languages: Languages; /** * Incoming Query Parameter: Determines whether the base is dark or light (and the foreground is the opposite) */ const displayParameter = (request.query.display as string) || 'light'; /** * Immediately throw if an invalid parameter value is requested */ if (!acceptableParameters.display.includes(displayParameter)) { throw generateQueryParameterErrorMessage('display', acceptableParameters.display, 'light'); } /** * Incoming Query Parameter: Determines whether the dots are squares or circles */ const dotTypeParameter = (request.query.dots as string) || 'circle'; /** * Immediately throw if an invalid parameter value is requested */ if (!acceptableParameters.dots.includes(dotTypeParameter)) { throw generateQueryParameterErrorMessage('dots', acceptableParameters.dots, 'circle'); } /** * Incoming Query Parameter: Determines how the API responds to the request. JSON or Image */ const responseTypeParameter = (request.query.responseType as string) || 'json'; /** * Immediately throw if an invalid parameter value is requested */ if (!acceptableParameters.responseType.includes(responseTypeParameter)) { throw generateQueryParameterErrorMessage('responseType', acceptableParameters.responseType, 'json'); } /** * Instantiate the GitHub API Client */ const octokit = new Octokit({ auth: token || getGitHubToken(), }); /** * Fetch the GitHub Repository */ const { data: repository } = await octokit.repos.get({ owner, repo, }); if (colors === 'repository') { /** * Fetch the GitHub Respository Language Data */ const { data } = await octokit.repos.listLanguages({ owner, repo, }); if (Object.keys(data).length === 0) { colors = 'system'; } else { languages = data as Languages; /** * Fetch the GitHub language colors source-of-truth */ const { data: linguistInitial } = await octokit.repos.getContents({ owner: 'github', repo: 'linguist', path: 'lib/linguist/languages.yml', mediaType: { format: 'base64', }, }); /** * Create a Buffer for the linguistInitial content * Parse the YML file so we can extract the colors we need from it later */ const linguistContent = linguistInitial as { content: string }; const linguistBuffer = Buffer.from(linguistContent.content as string, 'base64'); linguist = YAML.parse(linguistBuffer.toString('utf-8')) as Linguist; } } /** * Initialize the random function with a custom seed so it's consistent * This accepts the query param and will otherwise fallback on the unique repository ID */ const random = seedrandom(seed || repository.id.toString()); /** * Remote Template Images */ const template = { base: displayParameter === 'light' ? await Jimp.read(fromAWS('/meta/base.png')) : await Jimp.read(fromAWS('/meta/base_dark.png')), dot: dotTypeParameter === 'circle' ? await Jimp.read(fromAWS('/meta/dot_black.png')) : await Jimp.read(fromAWS('/meta/square_black.png')), circle: await Jimp.read(fromAWS('/meta/dot_black.png')), square: await Jimp.read(fromAWS('/meta/square_black.png')), githubLogo: displayParameter === 'light' ? await Jimp.read(fromAWS('/meta/github_black.png')) : await Jimp.read(fromAWS('/meta/github_white.png')), }; /** * Font family used for writing */ const font = displayParameter === 'light' ? await Jimp.loadFont( 'https://unpkg.com/@jimp/plugin-print@0.10.3/fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt' ) : await Jimp.loadFont( 'https://unpkg.com/@jimp/plugin-print@0.10.3/fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt' ); // const fontSm = await Jimp.loadFont( // 'https://unpkg.com/@jimp/plugin-print@0.10.3/fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt' // ); const fontSm = displayParameter === 'light' ? await Jimp.loadFont( 'https://unpkg.com/@jimp/plugin-print@0.10.3/fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt' ) : await Jimp.loadFont( 'https://unpkg.com/@jimp/plugin-print@0.10.3/fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt' ); /** * Required Image Dimensions */ const width = 1280; const height = 640; /** * Total Count of Squares (Dimensions) */ const horizontal = width / 20; const vertical = height / 20; /** * Spacing */ const spacing = 40; /** * Base Image */ const dots = [...new Array(horizontal * vertical)]; const image = template.base.clone().resize(width, height); /** * Protected Area Coordinates */ const protectedArea = { x: { min: 185, max: 1085 }, y: { min: 185, max: 445 }, }; /** * Positional and Location Helper Functions */ const getXPosition = (index: number): number => { return 5 + (index % horizontal) * 20; }; const getYPosition = (index: number): number => { return 5 + 20 * Math.floor(index / horizontal); }; const isInnerRing = (index: number, rows = 1): boolean => { if ( getXPosition(index) > protectedArea.x.min - rows * 20 && getXPosition(index) < protectedArea.x.max + rows * 20 && getYPosition(index) > protectedArea.y.min - rows * 20 && getYPosition(index) < protectedArea.y.max + rows * 20 ) { return true; } return false; }; const isProtectedArea = (index: number): boolean => { if ( getXPosition(index) > protectedArea.x.min && getXPosition(index) < protectedArea.x.max && getYPosition(index) > protectedArea.y.min && getYPosition(index) < protectedArea.y.max ) { return true; } return false; }; const generateOpacity = (index: number, opacityStart: number): number => { const opacityBoost = 0.45; const opacity = opacityStart + opacityBoost > 1 ? 1 : opacityStart + opacityBoost; // if (isInnerRing(index, 1)) return 0.05 * opacity; // if (isInnerRing(index, 2)) return 0.1 * opacity; // if (isInnerRing(index, 3)) return 0.15 * opacity; // if (isInnerRing(index, 4)) return 0.2 * opacity; // if (isInnerRing(index, 5)) return 0.25 * opacity; // if (isInnerRing(index, 6)) return 0.3 * opacity; // if (isInnerRing(index, 7)) return 0.35 * opacity; // if (isInnerRing(index, 8)) return 0.4 * opacity; // if (isInnerRing(index, 9)) return 0.45 * opacity; // if (isInnerRing(index, 10)) return 0.5 * opacity; if (isInnerRing(index, 1)) return 0.4 * opacity; if (isInnerRing(index, 2)) return 0.4 * opacity; if (isInnerRing(index, 3)) return 0.5 * opacity; if (isInnerRing(index, 4)) return 0.5 * opacity; if (isInnerRing(index, 5)) return 0.6 * opacity; // if (isInnerRing(index, 6)) return 0.3 * opacity; // if (isInnerRing(index, 7)) return 0.4 * opacity; // if (isInnerRing(index, 8)) return 0.4 * opacity; // if (isInnerRing(index, 9)) return 0.5 * opacity; // if (isInnerRing(index, 10)) return 0.5 * opacity; return opacity; }; /** * Color Generation Helper Function */ const getDotColor = (): RGB => { if (colors === 'system') { const hexColor = systemColors[Math.floor(random() * systemColors.length)]; const color = hexToRgb(hexColor); return color as RGB; } /** * Randomly select the language key we want to use to fetch our color. * Provide preference to the language-byte-counter provided by GitHub. */ const colorLanguageKey = weightedRandom(Object.entries(languages), random) as string; /** * If it exists, pluck the Hexidecimal code we need for the language key randomly picked */ let { color: hexColor } = linguist[colorLanguageKey] as { color: string | undefined }; /** * Fix the hex color to a sensible default if it's undefined */ if (hexColor === undefined) { hexColor = 'cccccc'; } /** * Convert the Hexidecimal value to a Jimp compatible RGB */ let color = hexToRgb(hexColor); /** * Fix the color to a sensible default if it's null */ if (color === null) { color = hexToRgb('cccccc') as RGB; } return color; }; /** * Reducer Function for applying the dynamic generation logic to each dot */ const dotReducer = (_: unknown, __: unknown, index: number): void => { /** * If the index is within a protected area we already know to stop. * Nothing will be added in the protected region. */ if (isProtectedArea(index)) return; /** * If we randomly generate a number between 1 and 100 and it's 80 or greater, let's just skip. * This reduces needlessly large amounts of squares from being added in a somewhat controlled way. * This basically gives us a percentage of reduction. */ const reduction = 80; // const reduction = 0; if (Math.floor(random() * 100) + 1 >= 100 - reduction) return; /** * If we haven't returned already, we're ready to proceed. */ const dot = template.dot.clone(); /** * Destructure the color and apply it to the square */ const { red, green, blue } = getDotColor(); dot.color([ { apply: 'red', params: [red] }, { apply: 'green', params: [green] }, { apply: 'blue', params: [blue] }, ]); /** * Randomly generate (and validate) the opacity of our square. * The generateOpacity function adds the fade out effect towards to the center */ const opacity = generateOpacity(index, random()); dot.opacity(opacity); /** * Our Square is not ready let's finally apply it to our image */ image.composite(dot, getXPosition(index), getYPosition(index)); }; dots.reduce(dotReducer, dots[0]); /** * Generate a secondary image to place on the protected area */ const protectedAreaImageWidth = protectedArea.x.max - protectedArea.x.min - 20; const protectedAreaImageHeight = protectedArea.y.max - protectedArea.y.min - 20; const protectedAreaImage = template.base.clone().resize(protectedAreaImageWidth, protectedAreaImageHeight); /** * If the full name doesn't bleed outside of the boundaries */ if (Jimp.measureText(font, repository.full_name) + spacing + 128 <= protectedAreaImageWidth) { /** * Find the Boundaries of the text that's about to be written on the image */ const textWidth = Jimp.measureText(font, repository.full_name); const textHeight = Jimp.measureTextHeight(font, repository.full_name, protectedAreaImageWidth); /** * Apply Title */ protectedAreaImage.print( font, protectedAreaImageWidth / 2 - textWidth / 2 + (128 + spacing) / 2, protectedAreaImageHeight / 2 - textHeight / 2, { text: repository.full_name }, width - spacing * 2, height - spacing * 2 ); /** * Place the protected area image onto the protected area */ protectedAreaImage.composite( template.githubLogo, 450 - 128 / 2 - textWidth / 2 - 40, protectedAreaImageHeight / 2 - 128 / 2 ); } else { /** * Find the Boundaries of the text that's about to be written on the image */ const textWidth = Jimp.measureText(font, repository.name); const textHeight = Jimp.measureTextHeight(font, repository.name, protectedAreaImageWidth); /** * Alignment Helpers */ const textHorizontalAlignment = protectedAreaImageWidth / 2 - textWidth / 2 + (128 + spacing) / 2; const textVerticalAlignment = protectedAreaImageHeight / 2 - textHeight / 2; /** * Apply Owner */ protectedAreaImage .print( fontSm, textHorizontalAlignment, textVerticalAlignment - 14, { text: repository.owner.login }, width - spacing * 2, height - spacing * 2 ) .opacity(0.7); /** * Apply Repository */ protectedAreaImage.print( font, textHorizontalAlignment, textVerticalAlignment + 14, { text: repository.name }, width - spacing * 2, height - spacing * 2 ); /** * Place the protected area image onto the protected area */ protectedAreaImage.composite( template.githubLogo, 450 - 128 / 2 - textWidth / 2 - 40, protectedAreaImageHeight / 2 - 128 / 2 ); } image.composite(protectedAreaImage, 200, 200); if (responseTypeParameter === 'image') { /** * Set the Content-Type header so the browser knows we're directly returning an image */ response.setHeader('Content-Type', 'image/png'); return response.end(await image.getBufferAsync(Jimp.MIME_PNG)); } else { return response.status(200).json({ data: { id: repository.id, owner, repo, darkmode: displayParameter === 'dark', squares: dotTypeParameter === 'squares', colors: colors === 'repository', image: await image.getBase64Async(Jimp.MIME_PNG), }, }); } } catch (error) { console.log(error.status); console.log(error); if (!error.status) { return response.json({ data: { error, }, }); } return response.status(error.status).json({ data: { error: errorMessages[error.status], }, }); } };
the_stack
var browser: Browser = browser || chrome; var hostname = typeof (location) != 'undefined' ? location.hostname : ''; if (hostname.startsWith('www.')) { hostname = hostname.substring(4); } if (hostname == 'mobile.twitter.com') hostname = 'twitter.com'; if (hostname.endsWith('.reddit.com')) hostname = 'reddit.com'; if (hostname.endsWith('.facebook.com')) hostname = 'facebook.com'; if (hostname.endsWith('.youtube.com')) hostname = 'youtube.com'; var myself: string = null; var isSocialNetwork: boolean = null; function fixupSiteStyles() { if (hostname == 'facebook.com') { let m = document.querySelector("[id^='profile_pic_header_']") if (m) myself = 'facebook.com/' + captureRegex(m.id, /header_(\d+)/); } else if (hostname == 'medium.com') { addStyleSheet(` a.show-thread-link, a.ThreadedConversation-moreRepliesLink { color: inherit !important; } .fullname, .stream-item a:hover .fullname, .stream-item a:active .fullname {color:inherit;} `); } else if (domainIs(hostname, 'tumblr.com')) { addStyleSheet(` .assigned-label-transphobic { outline: 2px solid var(--ShinigamiEyesTransphobic) !important; } .assigned-label-t-friendly { outline: 1px solid var(--ShinigamiEyesTFriendly) !important; } `); } else if (hostname == 'rationalwiki.org' || domainIs(hostname, 'wikipedia.org')) { addStyleSheet(` .assigned-label-transphobic { outline: 1px solid var(--ShinigamiEyesTransphobic) !important; } .assigned-label-t-friendly { outline: 1px solid var(--ShinigamiEyesTFriendly) !important; } `); } else if (hostname == 'twitter.com') { myself = getIdentifier(<HTMLAnchorElement>document.querySelector('.DashUserDropdown-userInfo a')); addStyleSheet(` .pretty-link b, .pretty-link s { color: inherit !important; } a.show-thread-link, a.ThreadedConversation-moreRepliesLink { color: inherit !important; } .fullname, .stream-item a:hover .fullname, .stream-item a:active .fullname {color:inherit;} `); } else if (hostname == 'reddit.com') { myself = getIdentifier(<HTMLAnchorElement>document.querySelector('#header-bottom-right .user a')); if (!myself) { let m = document.querySelector('#USER_DROPDOWN_ID'); if (m) { let username = [...m.querySelectorAll('*')].filter(x => x.childNodes.length == 1 && x.firstChild.nodeType == 3).map(x => x.textContent)[0] if (username) myself = 'reddit.com/user/' + username; } } addStyleSheet(` .author { color: #369 !important;} `); } } function addStyleSheet(css: string) { const style = document.createElement('style'); style.textContent = css; document.head.appendChild(style); } function maybeDisableCustomCss() { var shouldDisable: (s: { ownerNode: HTMLElement }) => boolean = null; if (hostname == 'twitter.com') shouldDisable = x => x.ownerNode && x.ownerNode.id && x.ownerNode.id.startsWith('user-style'); else if (hostname == 'medium.com') shouldDisable = x => x.ownerNode && x.ownerNode.className && x.ownerNode.className == 'js-collectionStyle'; else if (hostname == 'disqus.com') shouldDisable = x => x.ownerNode && x.ownerNode.id && x.ownerNode.id.startsWith('css_'); if (shouldDisable) [...document.styleSheets].filter(<any>shouldDisable).forEach(x => x.disabled = true); } function init() { isSocialNetwork = [ 'facebook.com', 'youtube.com', 'reddit.com', 'twitter.com', 'medium.com', 'disqus.com', 'rationalwiki.org', 'duckduckgo.com', 'bing.com', ].includes(hostname) || domainIs(hostname, 'tumblr.com') || domainIs(hostname, 'wikipedia.org') || /^google(\.co)?\.\w+$/.test(hostname); fixupSiteStyles(); if (domainIs(hostname, 'youtube.com')) { setInterval(updateYouTubeChannelHeader, 300); setInterval(updateAllLabels, 6000); } if (hostname == 'twitter.com') { setInterval(updateTwitterClasses, 800); } document.addEventListener('contextmenu', evt => { lastRightClickedElement = <HTMLElement>evt.target; }, true); maybeDisableCustomCss(); updateAllLabels(); if (isSocialNetwork) { var observer = new MutationObserver(mutationsList => { maybeDisableCustomCss(); for (const mutation of mutationsList) { if (mutation.type == 'childList') { for (const node of mutation.addedNodes) { if (node instanceof HTMLAnchorElement) { initLink(node); } if (node instanceof HTMLElement) { for (const subnode of node.querySelectorAll('a')) { initLink(subnode); } } } } } solvePendingLabels(); }); observer.observe(document.body, { childList: true, subtree: true }); } } var lastRightClickedElement: HTMLElement = null; var lastAppliedYouTubeUrl: string = null; var lastAppliedYouTubeTitle: string = null; var lastAppliedTwitterUrl: string = null; function updateTwitterClasses() { if (location.href != lastAppliedTwitterUrl) { setTimeout(updateAllLabels, 200); lastAppliedTwitterUrl = location.href; } for (const a of document.querySelectorAll('a')) { if (a.assignedCssLabel && !a.classList.contains('has-assigned-label')) { a.classList.add('assigned-label-' + a.assignedCssLabel); a.classList.add('has-assigned-label'); } } } function updateYouTubeChannelHeader() { var url = window.location.href; var title = <HTMLElement>document.querySelector('#channel-header ytd-channel-name yt-formatted-string'); if (title && !title.parentElement.offsetParent) title = null; var currentTitle = title ? title.textContent : null; if (url == lastAppliedYouTubeUrl && currentTitle == lastAppliedYouTubeTitle) return; lastAppliedYouTubeUrl = url; lastAppliedYouTubeTitle = currentTitle; if (currentTitle) { var replacement = <HTMLAnchorElement>document.getElementById('channel-title-replacement'); if (!replacement) { replacement = <HTMLAnchorElement>document.createElement('A'); replacement.id = 'channel-title-replacement' replacement.className = title.className; title.parentNode.insertBefore(replacement, title.nextSibling); title.style.display = 'none'; replacement.style.fontSize = '2.4rem'; replacement.style.fontWeight = '400'; replacement.style.lineHeight = '3rem'; replacement.style.textDecoration = 'none'; replacement.style.color = 'var(--yt-spec-text-primary)'; } replacement.textContent = lastAppliedYouTubeTitle; replacement.href = lastAppliedYouTubeUrl; } updateAllLabels(); setTimeout(updateAllLabels, 2000); setTimeout(updateAllLabels, 4000); } function updateAllLabels(refresh?: boolean) { if (refresh) knownLabels = {}; if (isSocialNetwork) { for (const a of document.getElementsByTagName('a')) { initLink(a); } } solvePendingLabels(); } var knownLabels: LabelMap = {}; var currentlyAppliedTheme = '_none_'; var labelsToSolve: LabelToSolve[] = []; function solvePendingLabels() { if (!labelsToSolve.length) return; var uniqueIdentifiers = Array.from(new Set(labelsToSolve.map(x => x.identifier))); var tosolve = labelsToSolve; labelsToSolve = []; browser.runtime.sendMessage<ShinigamiEyesCommand, LabelMap>({ ids: uniqueIdentifiers, myself: <string>myself }, (response: LabelMap) => { const theme = response[':theme']; if (theme != currentlyAppliedTheme) { if (currentlyAppliedTheme) document.body.classList.remove('shinigami-eyes-theme-' + currentlyAppliedTheme); if (theme) document.body.classList.add('shinigami-eyes-theme-' + theme); currentlyAppliedTheme = theme; } for (const item of tosolve) { const label = response[item.identifier]; knownLabels[item.identifier] = label || ''; applyLabel(item.element, item.identifier); } }); } function applyLabel(a: HTMLAnchorElement, identifier: string) { if (a.assignedCssLabel) { a.classList.remove('assigned-label-' + a.assignedCssLabel); a.classList.remove('has-assigned-label'); } a.assignedCssLabel = knownLabels[identifier] || ''; if (a.assignedCssLabel) { a.classList.add('assigned-label-' + a.assignedCssLabel); a.classList.add('has-assigned-label'); if (hostname == 'twitter.com') a.classList.remove('u-textInheritColor'); } } function initLink(a: HTMLAnchorElement) { var identifier = getIdentifier(a); if (!identifier) { if (hostname == 'youtube.com' || hostname == 'twitter.com') applyLabel(a, ''); return; } var label = knownLabels[identifier]; if (label === undefined) { labelsToSolve.push({ element: a, identifier: identifier }); return; } applyLabel(a, identifier); } function domainIs(host: string, baseDomain: string) { if (baseDomain.length > host.length) return false; if (baseDomain.length == host.length) return baseDomain == host; var k = host.charCodeAt(host.length - baseDomain.length - 1); if (k == 0x2E /* . */) return host.endsWith(baseDomain); else return false; } function getPartialPath(path: string, num: number) { var m = path.split('/') m = m.slice(1, 1 + num); if (m.length && !m[m.length - 1]) m.length--; if (m.length != num) return '!!' return '/' + m.join('/'); } function getPathPart(path: string, index: number) { return path.split('/')[index + 1] || null; } function captureRegex(str: string, regex: RegExp) { if (!str) return null; var match = str.match(regex); if (match && match[1]) return match[1]; return null; } function getCurrentFacebookPageId() { // page var elem = <HTMLAnchorElement>document.querySelector("a[rel=theater][aria-label='Profile picture']"); if (elem) { var p = captureRegex(elem.href, /facebook\.com\/(\d+)/) if (p) return p; } // page (does not work if page is loaded directly) elem = document.querySelector("[ajaxify^='/page_likers_and_visitors_dialog']") if (elem) return captureRegex(elem.getAttribute('ajaxify'), /\/(\d+)\//); // group elem = document.querySelector("[id^='headerAction_']"); if (elem) return captureRegex(elem.id, /_(\d+)/); // profile elem = document.querySelector('#pagelet_timeline_main_column'); if (elem && elem.dataset.gt) return JSON.parse(elem.dataset.gt).profile_owner; return null; } function getIdentifier(link: string | HTMLAnchorElement, originalTarget?: HTMLElement) { try { var k = link instanceof Node ? getIdentifierFromElementImpl(link, originalTarget) : getIdentifierFromURLImpl(tryParseURL(link)); if (!k || k.indexOf('!') != -1) return null; return k.toLowerCase(); } catch (e) { console.warn("Unable to get identifier for " + link); return null; } } function isFacebookPictureLink(element: HTMLAnchorElement) { var href = element.href; return href && (href.includes('/photo/') || href.includes('/photo.php')); } function getIdentifierFromElementImpl(element: HTMLAnchorElement, originalTarget: HTMLElement): string { if (!element) return null; const dataset = element.dataset; if (hostname == 'reddit.com') { const parent = element.parentElement; if (parent && parent.classList.contains('domain') && element.textContent.startsWith('self.')) return null; } else if (hostname == 'disqus.com') { if (element.classList && element.classList.contains('time-ago')) return null; } else if (hostname == 'facebook.com') { const parent = element.parentElement; const firstChild = <HTMLElement>element.firstChild; if (parent && (parent.tagName == 'H1' || parent.id == 'fb-timeline-cover-name')) { const id = getCurrentFacebookPageId(); //console.log('Current fb page: ' + id) if (id) return 'facebook.com/' + id; } // comment timestamp if (firstChild && firstChild.tagName == 'ABBR' && element.lastChild == firstChild) return null; // post 'see more' if (element.classList.contains('see_more_link')) return null; // post 'continue reading' if (parent && parent.classList.contains('text_exposed_link')) return null; // React comment timestamp if (parent && parent.tagName == 'LI') return null; // React post timestamp if (element.getAttribute('role') == 'link' && parent && parent.tagName == 'SPAN' && firstChild && firstChild.tagName == 'SPAN' && firstChild.tabIndex == 0) return null; // React big profile picture (user or page) if (originalTarget instanceof SVGImageElement && isFacebookPictureLink(element) && !getMatchingAncestorByCss(element, '[role=article]')) { return getIdentifier(window.location.href); } // React cover picture if (originalTarget instanceof HTMLImageElement && isFacebookPictureLink(element) && element.getAttribute('aria-label') && !getMatchingAncestorByCss(element, '[role=article]')) { return getIdentifier(window.location.href); } if (dataset) { const hovercard = dataset.hovercard; if (hovercard) { const id = captureRegex(hovercard, /id=(\d+)/); if (id) return 'facebook.com/' + id; } // post Comments link if (dataset.testid == 'UFI2CommentsCount/root') return null; // notification if (dataset.testid == 'notif_list_item_link') return null; // post Comments link if (dataset.commentPreludeRef) return null; // page left sidebar if (dataset.endpoint) return null; // profile tabs if (dataset.tabKey) return null; const gt = dataset.gt; if (gt) { const gtParsed = JSON.parse(gt); if (gtParsed.engagement && gtParsed.engagement.eng_tid) { return 'facebook.com/' + gtParsed.engagement.eng_tid; } } // comment interaction buttons if (dataset.sigil) return null; let p = <HTMLElement>element; while (p) { const bt = p.dataset.bt; if (bt) { const btParsed = JSON.parse(bt); if (btParsed.id) return 'facebook.com/' + btParsed.id; } p = p.parentElement; } } } else if (hostname == 'twitter.com') { if (dataset && dataset.expandedUrl) return getIdentifier(dataset.expandedUrl); if (element.href.startsWith('https://t.co/')) { const title = element.title; if (title && (title.startsWith('http://') || title.startsWith('https://'))) return getIdentifier(title); const content = element.textContent; if (!content.includes(' ') && content.includes('.') && !content.includes('…')) { const url = content.startsWith('http://') || content.startsWith('https://') ? content : 'http://' + content; return getIdentifier(url); } } } else if (domainIs(hostname, 'wikipedia.org')) { if (element.classList.contains('interlanguage-link-target')) return null; } if (element.classList.contains('tumblelog')) return element.textContent.replace('@', '') + '.tumblr.com'; const href = element.href; if (href && (!href.endsWith('#') || href.includes('&stick='))) return getIdentifierFromURLImpl(tryParseURL(href)); return null; } function tryParseURL(urlstr: string) { if (!urlstr) return null; try { const url = new URL(urlstr); if (url.protocol != 'http:' && url.protocol != 'https:') return null; return url; } catch (e) { return null; } } function tryUnwrapNestedURL(url: URL): URL { if (!url) return null; if (domainIs(url.host, 'youtube.com') && url.pathname == '/redirect') { const q = url.searchParams.get('q'); if (q && !q.startsWith('http:') && !q.startsWith('https:') && q.includes('.')) return tryParseURL('http://' + q); } if (url.href.indexOf('http', 1) != -1) { if (url.pathname.startsWith('/intl/')) return null; // facebook language switch links // const values = url.searchParams.values() // HACK: values(...) is not iterable on facebook (babel polyfill?) const values = url.search.split('&').map(x => { if (x.startsWith('ref_url=')) return ''; const eq = x.indexOf('='); return eq == -1 ? '' : decodeURIComponent(x.substr(eq + 1)); }); for (const value of values) { if (value.startsWith('http:') || value.startsWith('https:')) { return tryParseURL(value); } } const newurl = tryParseURL(url.href.substring(url.href.indexOf('http', 1))); if (newurl) return newurl; } return null; } function getIdentifierFromURLImpl(url: URL): string { if (!url) return null; // nested urls const nested = tryUnwrapNestedURL(url); if (nested) { return getIdentifierFromURLImpl(nested); } // fb group member badge if (url.pathname.includes('/badge_member_list/')) return null; let host = url.hostname; const searchParams = url.searchParams; if (domainIs(host, 'web.archive.org')) { const match = captureRegex(url.href, /\/web\/\w+\/(.*)/); if (!match) return null; return getIdentifierFromURLImpl(tryParseURL('http://' + match)); } if (host.startsWith('www.')) host = host.substring(4); const pathArray = url.pathname.split('/'); if (domainIs(host, 'facebook.com')) { if (searchParams.get('story_fbid')) return null; const fbId = searchParams.get('id'); const p = url.pathname.replace('/pg/', '/'); const isGroup = p.startsWith('/groups/'); if (isGroup && p.includes('/user/')) return 'facebook.com/' + pathArray[4]; // fb.com/groups/.../user/... return 'facebook.com/' + (fbId || getPartialPath(p, isGroup ? 2 : 1).substring(1)); } else if (domainIs(host, 'reddit.com')) { const pathname = url.pathname.replace('/u/', '/user/'); if (!pathname.startsWith('/user/') && !pathname.startsWith('/r/')) return null; if (pathname.includes('/comments/') && hostname == 'reddit.com') return null; return 'reddit.com' + getPartialPath(pathname, 2); } else if (domainIs(host, 'twitter.com')) { return 'twitter.com' + getPartialPath(url.pathname, 1); } else if (domainIs(host, 'youtube.com')) { const pathname = url.pathname; if (pathname.startsWith('/user/') || pathname.startsWith('/c/') || pathname.startsWith('/channel/')) return 'youtube.com' + getPartialPath(pathname, 2); return 'youtube.com' + getPartialPath(pathname, 1); } else if (domainIs(host, 'disqus.com') && url.pathname.startsWith('/by/')) { return 'disqus.com' + getPartialPath(url.pathname, 2); } else if (domainIs(host, 'medium.com')) { const hostParts = host.split('.'); if (hostParts.length == 3 && hostParts[0] != 'www') { return host; } return 'medium.com' + getPartialPath(url.pathname.replace('/t/', '/'), 1); } else if (domainIs(host, 'tumblr.com')) { if (url.pathname.startsWith('/register/follow/')) { const name = getPathPart(url.pathname, 2); return name ? name + '.tumblr.com' : null; } if (host != 'www.tumblr.com' && host != 'assets.tumblr.com' && host.indexOf('.media.') == -1) { if (!url.pathname.startsWith('/tagged/')) return url.host; } return null; } else if (domainIs(host, 'wikipedia.org') || domainIs(host, 'rationalwiki.org')) { const pathname = url.pathname; if (url.hash) return null; if (pathname == '/w/index.php' && searchParams.get('action') == 'edit') { const title = searchParams.get('title'); if (title && title.startsWith('User:')) { return 'wikipedia.org/wiki/' + title; } } if (pathname.startsWith('/wiki/Special:Contributions/') && url.href == window.location.href) return 'wikipedia.org/wiki/User:' + pathArray[3]; if (pathname.startsWith('/wiki/User:')) return 'wikipedia.org/wiki/User:' + pathArray[2].split(':')[1]; if (pathname.includes(':')) return null; if (pathname.startsWith('/wiki/')) return 'wikipedia.org' + decodeURIComponent(getPartialPath(pathname, 2)); else return null; } else if (host.indexOf('.blogspot.') != -1) { const m = captureRegex(host, /([a-zA-Z0-9\-]*)\.blogspot/); if (m) return m + '.blogspot.com'; else return null; } else if (host.includes('google.')) { if (url.pathname == '/search' && searchParams.get('stick') && !searchParams.get('tbm') && !searchParams.get('start')) { const q = searchParams.get('q'); if (q) return 'wikipedia.org/wiki/' + q.replace(/\s/g, '_'); } return null; } else { if (host.startsWith('m.')) host = host.substr(2); return host; } } init(); var lastGeneratedLinkId = 0; function getMatchingAncestor(node: HTMLElement, match: (node: HTMLElement) => boolean) { while (node) { if (match(node)) return node; node = node.parentElement; } return node; } function getMatchingAncestorByCss(node: HTMLElement, cssMatch: string) { return getMatchingAncestor(node, x => x.matches(cssMatch)); } function getSnippet(node: HTMLElement) : HTMLElement { if (hostname == 'facebook.com') { const pathname = window.location.pathname; const isPhotoPage = pathname.startsWith('/photo') || pathname.includes('/photos/') || pathname.startsWith('/video') || pathname.includes('/videos/'); if (isPhotoPage) { const sidebar = document.querySelector('[role=complementary]'); if (sidebar) return sidebar.parentElement; } const isSearchPage = pathname.startsWith('/search/'); return getMatchingAncestor(node, x => { if (x.getAttribute('role') == 'article' && (isSearchPage || x.getAttribute('aria-labelledby'))) return true; var dataset = x.dataset; if (!dataset) return false; if (dataset.ftr) return true; if (dataset.highlightTokens) return true; if (dataset.gt && dataset.vistracking) return true; return false; }); } if (hostname == 'reddit.com') return getMatchingAncestorByCss(node, '.scrollerItem, .thing, .Comment'); if (hostname == 'twitter.com') return getMatchingAncestorByCss(node, '.stream-item, .permalink-tweet-container, article'); if (hostname == 'disqus.com') return getMatchingAncestorByCss(node, '.post-content'); if (hostname == 'medium.com') return getMatchingAncestorByCss(node, '.streamItem, .streamItemConversationItem'); if (hostname == 'youtube.com') return getMatchingAncestorByCss(node, 'ytd-comment-renderer, ytd-video-secondary-info-renderer'); if (hostname == 'tumblr.com') return getMatchingAncestor(node, x => (x.dataset && !!(x.dataset.postId || x.dataset.id)) || x.classList.contains('post')); return null; } function getBadIdentifierReason(identifier: string, url: string, target: HTMLElement) { identifier = identifier || ''; url = url || ''; if (url) { const nested = tryUnwrapNestedURL(tryParseURL(url)); if (nested) url = nested.href; } if (identifier == 't.co') return 'Shortened link. Please follow the link and then mark the resulting page.'; if ( identifier.startsWith('reddit.com/user/') || identifier == 'twitter.com/threadreaderapp' || identifier == 'twitter.com/threader_app') return 'This is user is a bot.'; if (identifier == 'twitter.com/hashtag') return 'Hashtags cannot be labeled, only users.'; if (url.includes('youtube.com/watch')) return 'Only channels can be labeled, not specific videos.'; if (url.includes('reddit.com/') && url.includes('/comments/')) return 'Only users and subreddits can be labeled, not specific posts.'; if (url.includes('facebook.com') && ( url.includes('/posts/') || url.includes('/photo/') || url.includes('/photo.php') || url.includes('/permalink.php') || url.includes('/permalink/') || url.includes('/photos/'))) return 'Only pages, users and groups can be labeled, not specific posts or photos.'; if (url.includes('wiki') && url.includes('#')) return 'Wiki paragraphs cannot be labeled, only whole articles.'; return null; } var previousConfirmationMessage: HTMLElement = null; function displayConfirmation(identifier: string, label: LabelKind, badIdentifierReason: BadIdentifierReason, url: string, target: HTMLElement) { if (previousConfirmationMessage) { previousConfirmationMessage.remove(); previousConfirmationMessage = null; } if (!label) return; if (isSocialNetwork && label != 'bad-identifier') return; const confirmation = document.createElement('div'); const background = label == 't-friendly' ? '#eaffcf' : label == 'transphobic' ? '#f5d7d7' : '#eeeeee'; confirmation.style.cssText = `transition: opacity 7s ease-in-out !important; opacity: 1; position: fixed; padding: 30px 15px; z-index: 99999999; white-space: pre-wrap; top: 200px; left: 30%; right: 30%; background: ${background}; color: black; font-weight: bold; font-family: Arial; box-shadow: 0px 5px 10px #ddd; border: 1px solid #ccc; font-size: 11pt;`; let text: string; if (label == 'bad-identifier') { const displayReason = getBadIdentifierReason(identifier, url, target); if (displayReason) text = displayReason; else if (badIdentifierReason == 'SN') text = 'This social network is not supported: ' + identifier + '.'; else if (badIdentifierReason == 'AR') text = 'This is an archival link, it cannot be labeled: ' + identifier; else text = `This item could not be labeled. Possible reasons: • It doesn't represent a specific user or page • It's not a kind of object supported by Shinigami Eyes ${identifier || url} `; } else { text = identifier + ( label == 't-friendly' ? ' will be displayed as trans-friendly on search engines and social networks.' : label == 'transphobic' ? ' will be displayed as anti-trans on search engines and social networks.' : ' has been cleared.' ); } confirmation.textContent = text; document.body.appendChild(confirmation); previousConfirmationMessage = confirmation; confirmation.addEventListener('mousedown', () => confirmation.remove()); setTimeout(() => { confirmation.style.opacity = '0'; }, 2000); setTimeout(() => { confirmation.remove(); }, 9000); } browser.runtime.onMessage.addListener<ShinigamiEyesMessage, ShinigamiEyesSubmission>((message, sender, sendResponse) => { if (message.updateAllLabels || message.confirmSetLabel) { displayConfirmation(message.confirmSetIdentifier, message.confirmSetLabel, message.badIdentifierReason, message.confirmSetUrl, null); updateAllLabels(true); return; } message.contextPage = window.location.href; const originalTarget = lastRightClickedElement; let target = originalTarget; // message.elementId ? browser.menus.getTargetElement(message.elementId) : null; while (target) { if (target instanceof HTMLAnchorElement) break; target = target.parentElement; } if (target && (<HTMLAnchorElement>target).href != message.url) target = null; var identifier = target ? getIdentifier(<HTMLAnchorElement>target, originalTarget) : getIdentifier(message.url); if (!identifier) { displayConfirmation(null, 'bad-identifier', null, message.url, target); return; } message.identifier = identifier; if (identifier.startsWith('facebook.com/')) message.secondaryIdentifier = getIdentifier(message.url); var snippet = getSnippet(target); message.linkId = ++lastGeneratedLinkId; if (target) target.setAttribute('shinigami-eyes-link-id', '' + lastGeneratedLinkId); message.snippet = snippet ? snippet.outerHTML : null; var debugClass = 'shinigami-eyes-debug-snippet-highlight'; if (snippet && message.debug) { snippet.classList.add(debugClass); if (message.debug <= 1) setTimeout(() => snippet.classList.remove(debugClass), 1500) } message.isSocialNetwork = isSocialNetwork; sendResponse(message); })
the_stack
import {MDCTabInteractionEvent} from '../../mdc-tab/types'; import {verifyDefaultAdapter} from '../../../testing/helpers/foundation'; import {setUpFoundationTest} from '../../../testing/helpers/setup'; import {MDCTabBarFoundation} from '../foundation'; function setupTest() { const {foundation, mockAdapter} = setUpFoundationTest(MDCTabBarFoundation); return {foundation, mockAdapter}; } describe('MDCTabBarFoundation', () => { it('exports cssClasses', () => { expect('cssClasses' in MDCTabBarFoundation).toBe(true); }); it('exports strings', () => { expect('strings' in MDCTabBarFoundation).toBe(true); }); it('exports numbers', () => { expect('numbers' in MDCTabBarFoundation).toBe(true); }); it('defaultAdapter returns a complete adapter implementation', () => { verifyDefaultAdapter(MDCTabBarFoundation, [ 'scrollTo', 'incrementScroll', 'getScrollPosition', 'getScrollContentWidth', 'getOffsetWidth', 'isRTL', 'setActiveTab', 'activateTabAtIndex', 'deactivateTabAtIndex', 'focusTabAtIndex', 'getTabIndicatorClientRectAtIndex', 'getTabDimensionsAtIndex', 'getPreviousActiveTabIndex', 'getFocusedTabIndex', 'getIndexOfTabById', 'getTabListLength', 'notifyTabActivated', ]); }); const setupKeyDownTest = () => { const {foundation, mockAdapter} = setupTest(); foundation.setUseAutomaticActivation(false); foundation.scrollIntoView = jasmine.createSpy( 'scrollIntoView'); // Avoid errors due to adapters being stubs foundation.activateTab = jasmine.createSpy('activateTab'); return {foundation, mockAdapter}; }; const mockKeyDownEvent = ({key, keyCode}: {key?: string, keyCode?: number}) => { const preventDefault = jasmine.createSpy('preventDefault'); const fakeEvent = { key, keyCode, preventDefault, } as unknown as KeyboardEvent; return {preventDefault, fakeEvent}; }; it('#handleTabInteraction() activates the tab', () => { const {foundation, mockAdapter} = setupKeyDownTest(); foundation.handleTabInteraction({detail: {}} as MDCTabInteractionEvent); expect(mockAdapter.setActiveTab).toHaveBeenCalled(); }); it('#handleKeyDown() focuses the tab at the 0th index on home key press', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.HOME_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 36}); mockAdapter.getFocusedTabIndex.and.returnValue(2); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledWith(0); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() focuses the tab at the N - 1 index on end key press', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.END_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 35}); mockAdapter.getFocusedTabIndex.and.returnValue(2); mockAdapter.getTabListLength.and.returnValue(13); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledWith(12); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() focuses the tab at the previous index on left arrow press', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.ARROW_LEFT_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 37}); mockAdapter.getFocusedTabIndex.and.returnValue(2); mockAdapter.getTabListLength.and.returnValue(13); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledWith(1); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() focuses the tab at the next index when the right arrow key is pressed' + ' and the text direction is RTL', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.ARROW_LEFT_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 37}); mockAdapter.isRTL.and.returnValue(true); mockAdapter.getFocusedTabIndex.and.returnValue(2); mockAdapter.getTabListLength.and.returnValue(13); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledWith(3); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() focuses the tab at the N - 1 index when the left arrow key is pressed' + ' and the current active index is 0', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.ARROW_LEFT_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 37}); mockAdapter.getFocusedTabIndex.and.returnValue(0); mockAdapter.getTabListLength.and.returnValue(13); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledWith(12); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() focuses the tab at the N - 1 index when the right arrow key is pressed' + ' and the current active index is the 0th index and the text direction is RTL', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: 'ArrowRight'}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 39}); mockAdapter.isRTL.and.returnValue(true); mockAdapter.getFocusedTabIndex.and.returnValue(0); mockAdapter.getTabListLength.and.returnValue(13); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledWith(12); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() focuses the tab at the next index when the right arrow key is pressed', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.ARROW_RIGHT_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 39}); mockAdapter.getFocusedTabIndex.and.returnValue(2); mockAdapter.getTabListLength.and.returnValue(13); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledWith(3); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() focuses the tab at the previous index when the right arrow key is pressed' + ' and the text direction is RTL', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.ARROW_RIGHT_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 39}); mockAdapter.isRTL.and.returnValue(true); mockAdapter.getFocusedTabIndex.and.returnValue(2); mockAdapter.getTabListLength.and.returnValue(13); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledWith(1); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() focuses the tab at the 0th index when the right arrow key is pressed' + ' and the current active index is the max index', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.ARROW_RIGHT_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 39}); mockAdapter.getFocusedTabIndex.and.returnValue(12); mockAdapter.getTabListLength.and.returnValue(13); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledWith(0); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() focuses the tab at the 0th index when the left arrow key is pressed' + ' and the current active index is the max index and the text direction is RTL', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.ARROW_LEFT_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 37}); mockAdapter.isRTL.and.returnValue(true); mockAdapter.getFocusedTabIndex.and.returnValue(12); mockAdapter.getTabListLength.and.returnValue(13); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledWith(0); expect(mockAdapter.focusTabAtIndex).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() activates the current focused tab on space/enter press w/o useAutomaticActivation', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const index = 2; mockAdapter.getFocusedTabIndex.and.returnValue(index); foundation.handleKeyDown(mockKeyDownEvent({ key: MDCTabBarFoundation.strings.SPACE_KEY }).fakeEvent); foundation.handleKeyDown(mockKeyDownEvent({keyCode: 32}).fakeEvent); foundation.handleKeyDown(mockKeyDownEvent({ key: MDCTabBarFoundation.strings.ENTER_KEY }).fakeEvent); foundation.handleKeyDown(mockKeyDownEvent({keyCode: 13}).fakeEvent); expect(mockAdapter.setActiveTab).toHaveBeenCalledWith(index); expect(mockAdapter.setActiveTab).toHaveBeenCalledTimes(4); }); it('#handleKeyDown() does nothing on space/enter press w/ useAutomaticActivation', () => { const {foundation, mockAdapter} = setupKeyDownTest(); foundation.setUseAutomaticActivation(true); foundation.handleKeyDown(mockKeyDownEvent({ key: MDCTabBarFoundation.strings.SPACE_KEY }).fakeEvent); foundation.handleKeyDown(mockKeyDownEvent({keyCode: 32}).fakeEvent); foundation.handleKeyDown(mockKeyDownEvent({ key: MDCTabBarFoundation.strings.ENTER_KEY }).fakeEvent); foundation.handleKeyDown(mockKeyDownEvent({keyCode: 13}).fakeEvent); expect(mockAdapter.setActiveTab) .not.toHaveBeenCalledWith(jasmine.any(Number)); }); it('#handleKeyDown() activates the tab at the 0th index on home key press w/ useAutomaticActivation', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.HOME_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 36}); foundation.setUseAutomaticActivation(true); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.setActiveTab).toHaveBeenCalledWith(0); expect(mockAdapter.setActiveTab).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() activates the tab at the N - 1 index on end key press w/ useAutomaticActivation', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.END_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 35}); foundation.setUseAutomaticActivation(true); mockAdapter.getTabListLength.and.returnValue(13); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.setActiveTab).toHaveBeenCalledWith(12); expect(mockAdapter.setActiveTab).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() activates the tab at the previous index on left arrow press w/ useAutomaticActivation', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: MDCTabBarFoundation.strings.ARROW_LEFT_KEY}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 37}); foundation.setUseAutomaticActivation(true); mockAdapter.getPreviousActiveTabIndex.and.returnValue(2); mockAdapter.getTabListLength.and.returnValue(13); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.setActiveTab).toHaveBeenCalledWith(1); expect(mockAdapter.setActiveTab).toHaveBeenCalledTimes(2); }); it('#handleKeyDown() prevents the default behavior for handled non-activation keys', () => { [MDCTabBarFoundation.strings.ARROW_LEFT_KEY, MDCTabBarFoundation.strings.ARROW_RIGHT_KEY, MDCTabBarFoundation.strings.HOME_KEY, MDCTabBarFoundation.strings.END_KEY, ].forEach((evtName) => { const {foundation} = setupKeyDownTest(); const {fakeEvent, preventDefault} = mockKeyDownEvent({key: evtName}); foundation.handleKeyDown(fakeEvent); expect(preventDefault).toHaveBeenCalled(); }); }); it('#handleKeyDown() does not prevent the default behavior for handled activation keys', () => { [MDCTabBarFoundation.strings.SPACE_KEY, MDCTabBarFoundation.strings.ENTER_KEY] .forEach((evtName) => { const {foundation} = setupKeyDownTest(); const {fakeEvent, preventDefault} = mockKeyDownEvent({key: evtName}); foundation.handleKeyDown(fakeEvent); expect(preventDefault).not.toHaveBeenCalled(); }); }); it('#handleKeyDown() prevents the default behavior for handled non-activation keyCodes', () => { [MDCTabBarFoundation.numbers.ARROW_LEFT_KEYCODE, MDCTabBarFoundation.numbers.ARROW_RIGHT_KEYCODE, MDCTabBarFoundation.numbers.HOME_KEYCODE, MDCTabBarFoundation.numbers.END_KEYCODE, ].forEach((keyCode) => { const {foundation} = setupKeyDownTest(); const {fakeEvent, preventDefault} = mockKeyDownEvent({keyCode}); foundation.handleKeyDown(fakeEvent); expect(preventDefault).toHaveBeenCalled(); }); }); it('#handleKeyDown() prevents the default behavior for handled activation keyCodes', () => { [MDCTabBarFoundation.numbers.SPACE_KEYCODE, MDCTabBarFoundation.numbers.ENTER_KEYCODE] .forEach((keyCode) => { const {foundation} = setupKeyDownTest(); const {fakeEvent, preventDefault} = mockKeyDownEvent({keyCode}); foundation.handleKeyDown(fakeEvent); expect(preventDefault).not.toHaveBeenCalled(); }); }); it('#handleKeyDown() does not prevent the default behavior for unhandled keys', () => { const {foundation} = setupKeyDownTest(); const {fakeEvent, preventDefault} = mockKeyDownEvent({key: 'Shift'}); foundation.handleKeyDown(fakeEvent); expect(preventDefault).not.toHaveBeenCalled(); }); it('#handleKeyDown() does not prevent the default behavior for unhandled keyCodes', () => { const {foundation} = setupKeyDownTest(); const {fakeEvent, preventDefault} = mockKeyDownEvent({keyCode: 16}); foundation.handleKeyDown(fakeEvent); expect(preventDefault).not.toHaveBeenCalled(); }); it('#handleKeyDown() does not activate a tab when an unhandled key is pressed', () => { const {foundation, mockAdapter} = setupKeyDownTest(); const {fakeEvent: fakeKeyEvent} = mockKeyDownEvent({key: 'Shift'}); const {fakeEvent: fakeKeyCodeEvent} = mockKeyDownEvent({keyCode: 16}); foundation.handleKeyDown(fakeKeyEvent); foundation.handleKeyDown(fakeKeyCodeEvent); expect(mockAdapter.setActiveTab).not.toHaveBeenCalled(); }); const setupActivateTabTest = () => { const {foundation, mockAdapter} = setupTest(); const scrollIntoView = jasmine.createSpy(''); foundation.scrollIntoView = scrollIntoView; return {foundation, mockAdapter, scrollIntoView}; }; it('#activateTab() does nothing if the index overflows the tab list', () => { const {foundation, mockAdapter} = setupActivateTabTest(); mockAdapter.getTabListLength.and.returnValue(13); foundation.activateTab(13); expect(mockAdapter.deactivateTabAtIndex) .not.toHaveBeenCalledWith(jasmine.any(Number)); expect(mockAdapter.activateTabAtIndex) .not.toHaveBeenCalledWith(jasmine.any(Number)); }); it('#activateTab() does nothing if the index underflows the tab list', () => { const {foundation, mockAdapter} = setupActivateTabTest(); mockAdapter.getTabListLength.and.returnValue(13); foundation.activateTab(-1); expect(mockAdapter.deactivateTabAtIndex) .not.toHaveBeenCalledWith(jasmine.any(Number)); expect(mockAdapter.activateTabAtIndex) .not.toHaveBeenCalledWith(jasmine.any(Number)); }); it('#activateTab() does nothing if the index is the same as the previous active index', () => { const {foundation, mockAdapter} = setupActivateTabTest(); mockAdapter.getPreviousActiveTabIndex.and.returnValue(0); mockAdapter.getTabListLength.and.returnValue(13); foundation.activateTab(0); expect(mockAdapter.deactivateTabAtIndex) .not.toHaveBeenCalledWith(jasmine.any(Number)); expect(mockAdapter.activateTabAtIndex) .not.toHaveBeenCalledWith(jasmine.any(Number)); }); it(`#activateTab() does not emit the ${ MDCTabBarFoundation.strings.TAB_ACTIVATED_EVENT} event if the index` + ' is the currently active index', () => { const {foundation, mockAdapter} = setupActivateTabTest(); mockAdapter.getTabListLength.and.returnValue(13); mockAdapter.getPreviousActiveTabIndex.and.returnValue(6); foundation.activateTab(6); expect(mockAdapter.notifyTabActivated) .not.toHaveBeenCalledWith(jasmine.any(Number)); }); it('#activateTab() deactivates the previously active tab', () => { const {foundation, mockAdapter} = setupActivateTabTest(); mockAdapter.getTabListLength.and.returnValue(13); mockAdapter.getPreviousActiveTabIndex.and.returnValue(6); foundation.activateTab(1); expect(mockAdapter.deactivateTabAtIndex).toHaveBeenCalledWith(6); }); it('#activateTab() does not deactivate the previously active tab if there is none', () => { const {foundation, mockAdapter} = setupActivateTabTest(); mockAdapter.getTabListLength.and.returnValue(13); mockAdapter.getPreviousActiveTabIndex.and.returnValue(-1); foundation.activateTab(1); expect(mockAdapter.deactivateTabAtIndex) .not.toHaveBeenCalledWith(jasmine.any(Number)); }); it('#activateTab() activates the newly active tab with the previously active tab\'s indicatorClientRect', () => { const {foundation, mockAdapter} = setupActivateTabTest(); mockAdapter.getTabListLength.and.returnValue(13); mockAdapter.getPreviousActiveTabIndex.and.returnValue(6); mockAdapter.getTabIndicatorClientRectAtIndex.and.returnValue({ left: 22, right: 33, }); foundation.activateTab(1); expect(mockAdapter.activateTabAtIndex) .toHaveBeenCalledWith(1, {left: 22, right: 33}); }); it('#activateTab() scrolls the new tab index into view', () => { const {foundation, mockAdapter, scrollIntoView} = setupActivateTabTest(); mockAdapter.getTabListLength.and.returnValue(13); mockAdapter.getPreviousActiveTabIndex.and.returnValue(6); mockAdapter.getTabIndicatorClientRectAtIndex.and.returnValue({ left: 22, right: 33, }); foundation.activateTab(1); expect(scrollIntoView).toHaveBeenCalledWith(1); }); it(`#activateTab() emits the ${ MDCTabBarFoundation.strings .TAB_ACTIVATED_EVENT} with the index of the tab`, () => { const {foundation, mockAdapter} = setupActivateTabTest(); mockAdapter.getTabListLength.and.returnValue(13); mockAdapter.getPreviousActiveTabIndex.and.returnValue(6); mockAdapter.getTabIndicatorClientRectAtIndex.and.returnValue({ left: 22, right: 33, }); foundation.activateTab(1); expect(mockAdapter.notifyTabActivated).toHaveBeenCalledWith(1); }); function setupScrollIntoViewTest({ activeIndex = 0, tabListLength = 10, indicatorClientRect = {}, scrollContentWidth = 1000, scrollPosition = 0, offsetWidth = 400, tabDimensionsMap = {}, } = {}) { const {foundation, mockAdapter} = setupTest(); mockAdapter.getPreviousActiveTabIndex.and.returnValue(activeIndex); mockAdapter.getTabListLength.and.returnValue(tabListLength); mockAdapter.getTabIndicatorClientRectAtIndex.withArgs(jasmine.any(Number)) .and.returnValue(indicatorClientRect); mockAdapter.getScrollPosition.and.returnValue(scrollPosition); mockAdapter.getScrollContentWidth.and.returnValue(scrollContentWidth); mockAdapter.getOffsetWidth.and.returnValue(offsetWidth); mockAdapter.getTabDimensionsAtIndex.withArgs(jasmine.any(Number)) .and.callFake((index: number) => { return (tabDimensionsMap as any)[index]; }); return {foundation, mockAdapter}; } it('#scrollIntoView() does nothing if the index overflows the tab list', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ tabListLength: 13, }); foundation.scrollIntoView(13); expect(mockAdapter.scrollTo) .not.toHaveBeenCalledWith(jasmine.any(Number)); expect(mockAdapter.incrementScroll) .not.toHaveBeenCalledWith(jasmine.any(Number)); }); it('#scrollIntoView() does nothing if the index underflows the tab list', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ tabListLength: 9, }); foundation.scrollIntoView(-1); expect(mockAdapter.scrollTo) .not.toHaveBeenCalledWith(jasmine.any(Number)); expect(mockAdapter.incrementScroll) .not.toHaveBeenCalledWith(jasmine.any(Number)); }); it('#scrollIntoView() scrolls to 0 if the index is 0', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ tabListLength: 9, }); foundation.scrollIntoView(0); expect(mockAdapter.scrollTo).toHaveBeenCalledWith(0); }); it('#scrollIntoView() scrolls to the scroll content width if the index is the max possible', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ tabListLength: 9, scrollContentWidth: 987, }); foundation.scrollIntoView(8); expect(mockAdapter.scrollTo).toHaveBeenCalledWith(987); }); it('#scrollIntoView() increments the scroll by 150 when the selected tab is 100px to the right' + ' and the closest tab\'s left content edge is 30px from its left root edge', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ activeIndex: 0, tabListLength: 9, scrollContentWidth: 1000, offsetWidth: 200, tabDimensionsMap: { 1: { rootLeft: 0, rootRight: 300, }, 2: { rootLeft: 300, contentLeft: 330, contentRight: 370, rootRight: 400, }, }, }); foundation.scrollIntoView(1); expect(mockAdapter.incrementScroll) .toHaveBeenCalledWith( 130 + MDCTabBarFoundation.numbers.EXTRA_SCROLL_AMOUNT); }); it('#scrollIntoView() increments the scroll by 250 when the selected tab is 100px to the left, is 100px wide,' + ' and the closest tab\'s left content edge is 30px from its left root edge and the text direction is RTL', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ activeIndex: 0, tabListLength: 9, scrollContentWidth: 1000, offsetWidth: 200, scrollPosition: 100, tabDimensionsMap: { 5: { rootLeft: 400, contentLeft: 430, contentRight: 470, rootRight: 500, }, 4: { rootLeft: 500, rootRight: 600, }, }, }); mockAdapter.isRTL.and.returnValue(true); foundation.scrollIntoView(4); expect(mockAdapter.incrementScroll) .toHaveBeenCalledWith( 230 + MDCTabBarFoundation.numbers.EXTRA_SCROLL_AMOUNT); }); it('#scrollIntoView() increments the scroll by -250 when the selected tab is 100px to the left, is 100px wide,' + ' and the closest tab\'s right content edge is 30px from its right root edge', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ activeIndex: 3, tabListLength: 9, scrollContentWidth: 1000, scrollPosition: 500, offsetWidth: 200, tabDimensionsMap: { 1: { rootLeft: 190, contentLeft: 220, contentRight: 270, rootRight: 300, }, 2: { rootLeft: 300, contentLeft: 330, contentRight: 370, rootRight: 400, }, }, }); foundation.scrollIntoView(2); expect(mockAdapter.incrementScroll) .toHaveBeenCalledWith( -230 - MDCTabBarFoundation.numbers.EXTRA_SCROLL_AMOUNT); }); it('#scrollIntoView() increments the scroll by -150 when the selected tab is 100px wide,' + ' and the closest tab\'s right content edge is 30px from its right root edge and the text direction is RTL', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ activeIndex: 3, tabListLength: 9, scrollContentWidth: 1000, scrollPosition: 300, offsetWidth: 200, tabDimensionsMap: { 2: { rootLeft: 700, contentLeft: 730, contentRight: 770, rootRight: 800, }, 1: { rootLeft: 800, contentLeft: 830, contentRight: 870, rootRight: 900, }, }, }); mockAdapter.isRTL.and.returnValue(true); foundation.scrollIntoView(2); expect(mockAdapter.incrementScroll) .toHaveBeenCalledWith( -130 - MDCTabBarFoundation.numbers.EXTRA_SCROLL_AMOUNT); }); it('#scrollIntoView() does nothing when the tab is perfectly in the center', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ activeIndex: 3, tabListLength: 9, scrollContentWidth: 1000, scrollPosition: 200, offsetWidth: 300, tabDimensionsMap: { 1: { rootLeft: 200, contentLeft: 230, contentRight: 270, rootRight: 300, }, 2: { rootLeft: 300, contentLeft: 330, contentRight: 370, rootRight: 400, }, }, }); foundation.scrollIntoView(2); expect(mockAdapter.scrollTo) .not.toHaveBeenCalledWith(jasmine.any(Number)); expect(mockAdapter.incrementScroll) .not.toHaveBeenCalledWith(jasmine.any(Number)); }); it('#scrollIntoView() does nothing when the tab is perfectly in the center and the text direction is RTL', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ activeIndex: 3, tabListLength: 10, scrollContentWidth: 1000, scrollPosition: 500, offsetWidth: 300, tabDimensionsMap: { 8: { rootLeft: 200, contentLeft: 230, contentRight: 270, rootRight: 300, }, 7: { rootLeft: 300, contentLeft: 330, contentRight: 370, rootRight: 400, }, }, }); mockAdapter.isRTL.and.returnValue(true); foundation.scrollIntoView(7); expect(mockAdapter.scrollTo) .not.toHaveBeenCalledWith(jasmine.any(Number)); expect(mockAdapter.incrementScroll) .not.toHaveBeenCalledWith(jasmine.any(Number)); }); it('#scrollIntoView() increments the scroll by 0 when the tab and its left neighbor\'s content are visible', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ activeIndex: 3, tabListLength: 9, scrollContentWidth: 1000, scrollPosition: 200, offsetWidth: 500, tabDimensionsMap: { 1: { rootLeft: 200, contentLeft: 230, contentRight: 270, rootRight: 300, }, 2: { rootLeft: 300, contentLeft: 330, contentRight: 370, rootRight: 400, }, }, }); foundation.scrollIntoView(2); expect(mockAdapter.incrementScroll).toHaveBeenCalledWith(0); }); it('#scrollIntoView() increments the scroll by 0 when the tab and its right neighbor\'s content are visible', () => { const {foundation, mockAdapter} = setupScrollIntoViewTest({ activeIndex: 3, tabListLength: 9, scrollContentWidth: 1000, scrollPosition: 22, offsetWidth: 400, tabDimensionsMap: { 1: { rootLeft: 200, contentLeft: 230, contentRight: 270, rootRight: 300, }, 2: { rootLeft: 300, contentLeft: 330, contentRight: 370, rootRight: 400, }, }, }); foundation.scrollIntoView(1); expect(mockAdapter.incrementScroll).toHaveBeenCalledWith(0); }); });
the_stack
import { CdkDragStart } from '@angular/cdk/drag-drop'; import { AfterContentInit, AfterViewChecked, AfterViewInit, ApplicationRef, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, HostListener, Injector, NgZone, OnChanges, OnDestroy, OnInit, SimpleChange, SimpleChanges, ViewChild, ViewEncapsulation } from '@angular/core'; import { fadeInLinearAnimation } from '@angular-ru/cdk/animations'; import { hasItems } from '@angular-ru/cdk/array'; import { coerceBoolean } from '@angular-ru/cdk/coercion'; import { Any, DeepPartial, Nullable, PlainObjectOf, SortOrderType } from '@angular-ru/cdk/typings'; import { checkValueIsFilled, detectChanges, isFalse, isFalsy, isNil, isNotNil } from '@angular-ru/cdk/utils'; import { EMPTY, fromEvent, Observable, Subject } from 'rxjs'; import { catchError, takeUntil } from 'rxjs/operators'; import { AbstractTableBuilderApiDirective } from './abstract-table-builder-api.directive'; import { NgxColumnComponent } from './components/ngx-column/ngx-column.component'; import { TABLE_GLOBAL_OPTIONS } from './config/table-global-options'; import { AutoHeightDirective } from './directives/auto-height.directive'; import { CalculateRange, ColumnsSchema } from './interfaces/table-builder.external'; import { RecalculatedStatus, RowId, TableSimpleChanges, TemplateKeys } from './interfaces/table-builder.internal'; import { getClientHeight } from './operators/get-client-height'; import { ContextMenuService } from './services/context-menu/context-menu.service'; import { DraggableService } from './services/draggable/draggable.service'; import { FilterableService } from './services/filterable/filterable.service'; import { TableFilterType } from './services/filterable/table-filter-type'; import { ResizableService } from './services/resizer/resizable.service'; import { SelectionService } from './services/selection/selection.service'; import { SortableService } from './services/sortable/sortable.service'; import { NgxTableViewChangesService } from './services/table-view-changes/ngx-table-view-changes.service'; import { TemplateParserService } from './services/template-parser/template-parser.service'; const { TIME_IDLE, TIME_RELOAD, FRAME_TIME, MACRO_TIME, CHANGE_DELAY }: typeof TABLE_GLOBAL_OPTIONS = TABLE_GLOBAL_OPTIONS; @Component({ selector: 'ngx-table-builder', templateUrl: './table-builder.component.html', styleUrls: ['./table-builder.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ TemplateParserService, SortableService, SelectionService, ResizableService, ContextMenuService, FilterableService, DraggableService ], encapsulation: ViewEncapsulation.None, animations: [fadeInLinearAnimation] }) export class TableBuilderComponent<T> extends AbstractTableBuilderApiDirective<T> implements OnChanges, OnInit, AfterContentInit, AfterViewInit, AfterViewChecked, OnDestroy { @ViewChild('header', { static: false }) public headerRef!: ElementRef<HTMLDivElement>; @ViewChild('footer', { static: false }) public footerRef!: ElementRef<HTMLDivElement>; @ViewChild(AutoHeightDirective, { static: false }) public readonly autoHeight!: AutoHeightDirective<T>; public dirty: boolean = true; public rendering: boolean = false; public isRendered: boolean = false; public contentInit: boolean = false; public contentCheck: boolean = false; public recalculated: RecalculatedStatus = { recalculateHeight: false }; public sourceIsNull: boolean = false; public afterViewInitDone: boolean = false; public readonly selection: SelectionService<T>; public readonly templateParser: TemplateParserService<T>; public readonly ngZone: NgZone; public readonly resize: ResizableService; public readonly sortable: SortableService<T>; public readonly contextMenu: ContextMenuService<T>; public readonly filterable: FilterableService<T>; protected readonly app: ApplicationRef; protected readonly draggable: DraggableService<T>; protected readonly viewChanges: NgxTableViewChangesService; private forcedRefresh: boolean = false; private readonly _destroy$: Subject<boolean> = new Subject<boolean>(); private timeoutCheckedTaskId: Nullable<number> = null; private timeoutScrolledId: Nullable<number> = null; private timeoutViewCheckedId: Nullable<number> = null; private frameCalculateViewportId: Nullable<number> = null; private selectionUpdateTaskId: Nullable<number> = null; private changesTimerId: number = 0; constructor(public readonly cd: ChangeDetectorRef, injector: Injector) { super(); this.selection = injector.get<SelectionService<T>>(SelectionService); this.templateParser = injector.get<TemplateParserService<T>>(TemplateParserService); this.ngZone = injector.get<NgZone>(NgZone); this.resize = injector.get<ResizableService>(ResizableService); this.sortable = injector.get<SortableService<T>>(SortableService); this.contextMenu = injector.get<ContextMenuService<T>>(ContextMenuService); this.app = injector.get<ApplicationRef>(ApplicationRef); this.filterable = injector.get<FilterableService<T>>(FilterableService); this.draggable = injector.get<DraggableService<T>>(DraggableService); this.viewChanges = injector.get<NgxTableViewChangesService>(NgxTableViewChangesService); } public get destroy$(): Subject<boolean> { return this._destroy$; } public get selectedKeyList(): RowId[] { return this.selection.selectionModel.selectedList; } /** @deprecated * Use `selectedKeyList` instead */ public get selectionEntries(): PlainObjectOf<boolean> { return this.selection.selectionModel.entries; } public get sourceExists(): boolean { return this.sourceRef.length > 0; } public get rootHeight(): string { const height: Nullable<string | number> = this.expandableTableExpanded ? this.height : getClientHeight(this.headerRef) + getClientHeight(this.footerRef); if (checkValueIsFilled(height)) { const heightAsNumber: number = Number(height); return isNaN(heightAsNumber) ? String(height) : `${height}px`; } else { return ''; } } private get expandableTableExpanded(): boolean { return ( isNil(this.headerTemplate) || !coerceBoolean(this.headerTemplate.expandablePanel) || coerceBoolean(this.headerTemplate.expanded) ); } private get viewIsDirty(): boolean { return this.contentCheck && !this.forcedRefresh; } private get needUpdateViewport(): boolean { return this.viewPortInfo.prevScrollOffsetTop !== this.scrollOffsetTop; } private get viewportHeight(): number { return this.scrollContainer.nativeElement.offsetHeight; } private get scrollOffsetTop(): number { return this.scrollContainer.nativeElement.scrollTop; } private get nonIdenticalStructure(): boolean { return this.sourceExists && this.getCountKeys() !== this.renderedCountKeys; } public checkSourceIsNull(): boolean { // eslint-disable-next-line return !('length' in (this.source || {})); } public recalculateHeight(): void { this.recalculated = { recalculateHeight: true }; this.forceCalculateViewport(); this.idleDetectChanges(); } @HostListener('contextmenu', ['$event']) public openContextMenu($event: MouseEvent): void { if (isNotNil(this.contextMenuTemplate)) { this.contextMenu.openContextMenu($event); } } public ngOnChanges(changes: SimpleChanges): void { this.checkCorrectInitialSchema(changes); this.sourceIsNull = this.checkSourceIsNull(); if (TableSimpleChanges.SKIP_SORT in changes) { this.sortable.setSkipSort(this.isSkippedInternalSort); } if (this.nonIdenticalStructure) { this.preRenderTable(); } else if (TableSimpleChanges.SOURCE_KEY in changes && this.isRendered) { this.preSortAndFilterTable(); } if (TableSimpleChanges.SORT_TYPES in changes) { this.setSortTypes(); } this.handleFilterDefinitionChanges(changes); clearTimeout(this.changesTimerId); // eslint-disable-next-line no-restricted-properties this.changesTimerId = window.setTimeout((): void => this.updateViewport(), CHANGE_DELAY); } public markForCheck(): void { this.contentCheck = true; } public ngOnInit(): void { if (this.isEnableSelection) { this.selection.listenShiftKey(); this.selection.primaryKey = this.primaryKey; this.selection.selectionModeIsEnabled = true; this.selection.setProducerDisableFn(this.produceDisableFn); } this.sortable.setSortChanges(this.sortChanges); } public markVisibleColumn(column: HTMLDivElement, visible: boolean): void { (column as Any).visible = visible; this.idleDetectChanges(); } public ngAfterContentInit(): void { this.markDirtyCheck(); this.markTemplateContentCheck(); if (this.sourceExists) { this.render(); } this.listenExpandChange(); } public ngAfterViewInit(): void { this.listenTemplateChanges(); this.listenFilterResetChanges(); this.listenSelectionChanges(); this.listenColumnListChanges(); this.recheckTemplateChanges(); this.afterViewInitChecked(); } public cdkDragMoved(event: CdkDragStart, root: HTMLElement): void { this.isDragMoving = true; // eslint-disable-next-line @typescript-eslint/dot-notation const preview: HTMLElement = event.source._dragRef['_preview']; const top: number = root.getBoundingClientRect().top; // eslint-disable-next-line @typescript-eslint/dot-notation const transform: string = event.source._dragRef['_preview'].style.transform ?? ''; const [x, , z]: [number, number, number] = transform .replace(/translate3d|\(|\)|px/g, '') .split(',') .map((val: string): number => parseFloat(val)) as [number, number, number]; preview.style.transform = `translate3d(${x}px, ${top}px, ${z}px)`; } public ngAfterViewChecked(): void { if (this.viewIsDirty) { this.viewForceRefresh(); } } public ngOnDestroy(): void { window.clearTimeout(this.timeoutScrolledId!); window.clearTimeout(this.timeoutViewCheckedId!); window.clearTimeout(this.timeoutCheckedTaskId!); window.cancelAnimationFrame(this.frameCalculateViewportId!); this.templateParser.schema = null; this._destroy$.next(true); /** * @description * If you want an Observable to be done with his task, you call observable.complete(). * This only exists on Subject and those who extend Subject. * The complete method in itself will also unsubscribe any possible subscriptions. */ this._destroy$.complete(); } public markTemplateContentCheck(): void { this.contentInit = isNotNil(this.source) || isFalsy(this.columnTemplates?.length); } public markDirtyCheck(): void { this.dirty = false; } /** * @internal * @description: Key table generation for internal use * @sample: keys - ['id', 'value'] -> { id: true, value: true } */ public generateColumnsKeyMap(keys: string[]): PlainObjectOf<boolean> { const map: PlainObjectOf<boolean> = {}; keys.forEach((key: string): void => { map[key] = true; }); return map; } public render(): void { this.contentCheck = false; this.ngZone.run((): void => { // eslint-disable-next-line no-restricted-properties window.setTimeout((): void => { this.renderTable(); this.idleDetectChanges(); }, TIME_IDLE); }); } public renderTable(): void { if (this.rendering) { return; } this.rendering = true; const columnList: string[] = this.generateDisplayedColumns(); if (this.sortable.notEmpty) { this.sortAndFilter().then((): void => { this.syncDrawColumns(columnList); this.emitRendered(); }); } else { this.syncDrawColumns(columnList); this.emitRendered(); } } public toggleColumnVisibility(key?: Nullable<string>): void { if (isNotNil(key)) { this.recheckViewportChecked(); this.templateParser.toggleColumnVisibility(key); this.ngZone.runOutsideAngular((): void => { window.requestAnimationFrame((): void => { this.changeSchema(); this.recheckViewportChecked(); detectChanges(this.cd); }); }); } } public updateColumnsSchema(patch: PlainObjectOf<Partial<ColumnsSchema>>): void { this.templateParser.updateColumnsSchema(patch); this.changeSchema(); } public resetSchema(): void { this.columnListWidth = 0; this.schemaColumns = null; detectChanges(this.cd); this.renderTable(); this.changeSchema([]); this.ngZone.runOutsideAngular((): void => { // eslint-disable-next-line no-restricted-properties window.setTimeout((): void => { this.tableViewportChecked = true; this.calculateColumnWidthSummary(); detectChanges(this.cd); }, TABLE_GLOBAL_OPTIONS.TIME_IDLE); }); } public calculateViewport(force: boolean = false): void { if (this.ignoreCalculate()) { return; } const isDownMoved: boolean = this.isDownMoved(); this.viewPortInfo.prevScrollOffsetTop = this.scrollOffsetTop; const start: number = this.getOffsetVisibleStartIndex(); const end: number = this.calculateEndIndex(start); const bufferOffset: number = this.calculateBuffer(isDownMoved, start, end); this.calculateViewPortByRange({ start, end, bufferOffset, force }); this.viewPortInfo.bufferOffset = bufferOffset; } public setSource(source: Nullable<T[]>): void { this.originalSource = this.source = this.selection.rows = source; } public updateTableHeight(): void { this.autoHeight.calculateHeight(); detectChanges(this.cd); } public filterBySubstring(substring: Nullable<Any>): void { this.filterable.filterValue = substring?.toString(); this.filter(); } protected calculateViewPortByRange({ start, end, bufferOffset, force }: CalculateRange): void { let newStartIndex: number = start; if (this.startIndexIsNull()) { this.updateViewportInfo(newStartIndex, end); } else if (this.needRecalculateBuffer(bufferOffset)) { newStartIndex = this.recalculateStartIndex(newStartIndex); this.updateViewportInfo(newStartIndex, end); detectChanges(this.cd); } else if (bufferOffset < 0 || force) { newStartIndex = this.recalculateStartIndex(newStartIndex); this.updateViewportInfo(newStartIndex, end); detectChanges(this.cd); return; } if (force) { this.idleDetectChanges(); } } protected startIndexIsNull(): boolean { return typeof this.viewPortInfo.startIndex !== 'number'; } protected needRecalculateBuffer(bufferOffset: number): boolean { return bufferOffset <= TABLE_GLOBAL_OPTIONS.BUFFER_OFFSET && bufferOffset >= 0; } protected recalculateStartIndex(start: number): number { const newStart: number = start - TABLE_GLOBAL_OPTIONS.MIN_BUFFER; return newStart >= 0 ? newStart : 0; } protected calculateBuffer(isDownMoved: boolean, start: number, end: number): number { const lastVisibleIndex: number = this.getOffsetVisibleEndIndex(); return isDownMoved ? (this.viewPortInfo.endIndex ?? end) - lastVisibleIndex : start - this.viewPortInfo.startIndex!; } protected calculateEndIndex(start: number): number { const end: number = start + this.getVisibleCountItems() + TABLE_GLOBAL_OPTIONS.MIN_BUFFER; return end > this.sourceRef.length ? this.sourceRef.length : end; } protected ignoreCalculate(): boolean { return isNil(this.source) || !this.viewportHeight; } protected isDownMoved(): boolean { return this.scrollOffsetTop > this.viewPortInfo.prevScrollOffsetTop!; } protected updateViewportInfo(start: number, end: number): void { this.viewPortInfo.startIndex = start; this.viewPortInfo.endIndex = end; this.viewPortInfo.indexes = []; this.viewPortInfo.virtualIndexes = []; for (let i: number = start, even: number = 2; i < end; i++) { this.viewPortInfo.indexes.push(i); this.viewPortInfo.virtualIndexes.push({ position: i, stripped: this.striped ? i % even === 0 : false, offsetTop: i * this.clientRowHeight }); } this.createDiffIndexes(); this.viewPortInfo.scrollTop = start * this.clientRowHeight; } private checkCorrectInitialSchema(changes: SimpleChanges = {}): void { if (TableSimpleChanges.SCHEMA_COLUMNS in changes) { const schemaChange: Nullable<SimpleChange> = changes[TableSimpleChanges.SCHEMA_COLUMNS]; if (isNotNil(schemaChange?.currentValue)) { if (isNil(this.name)) { console.error(`Table name is required! Example: <ngx-table-builder name="my-table-name" />`); } if (isNil(this.schemaVersion)) { console.error(`Table version is required! Example: <ngx-table-builder [schema-version]="2" />`); } } } } private setSortTypes(): void { this.sortable.setDefinition({ ...(this.sortTypes as PlainObjectOf<SortOrderType>) }); if (this.sourceExists) { this.sortAndFilter().then((): void => this.reCheckDefinitions()); } } private handleFilterDefinitionChanges(changes: SimpleChanges): void { if (TableSimpleChanges.FILTER_DEFINITION in changes) { this.filterable.setDefinition(this.filterDefinition ?? []); this.filter(); } } private listenColumnListChanges(): void { this.columnList.changes .pipe(takeUntil(this._destroy$)) .subscribe((): void => this.calculateColumnWidthSummary()); } private createDiffIndexes(): void { this.viewPortInfo.diffIndexes = this.viewPortInfo.oldIndexes ? this.viewPortInfo.oldIndexes.filter((index: number): boolean => isFalse(this.viewPortInfo.indexes?.includes(index) ?? false) ) : []; this.viewPortInfo.oldIndexes = this.viewPortInfo.indexes; } private listenFilterResetChanges(): void { this.filterable.resetEvents$.pipe(takeUntil(this._destroy$)).subscribe((): void => { this.source = this.originalSource; this.calculateViewport(true); }); } private afterViewInitChecked(): void { this.ngZone.runOutsideAngular((): void => { // eslint-disable-next-line no-restricted-properties this.timeoutViewCheckedId = window.setTimeout((): void => { this.afterViewInitDone = true; this.listenScroll(); if (!this.isRendered && !this.rendering && this.sourceRef.length === 0) { this.emitRendered(); detectChanges(this.cd); } }, MACRO_TIME); }); } private listenScroll(): void { this.ngZone.runOutsideAngular((): void => { fromEvent(this.scrollContainer.nativeElement, 'scroll', { passive: true }) .pipe( catchError((): Observable<never> => { this.calculateViewport(true); return EMPTY; }), takeUntil(this._destroy$) ) .subscribe((): void => this.scrollHandler()); }); } private scrollHandler(): void { if (!this.needUpdateViewport) { return; } this.ngZone.runOutsideAngular((): void => this.updateViewport()); } private updateViewport(): void { this.cancelScrolling(); this.frameCalculateViewportId = window.requestAnimationFrame((): void => this.calculateViewport()); } private cancelScrolling(): void { this.viewPortInfo.isScrolling = true; window.cancelAnimationFrame(this.frameCalculateViewportId!); this.ngZone.runOutsideAngular((): void => { window.clearTimeout(this.timeoutScrolledId!); // eslint-disable-next-line no-restricted-properties this.timeoutScrolledId = window.setTimeout((): void => { this.viewPortInfo.isScrolling = false; detectChanges(this.cd); }, TIME_RELOAD); }); } private getOffsetVisibleEndIndex(): number { return Math.floor((this.scrollOffsetTop + this.viewportHeight) / this.clientRowHeight) - 1; } private getVisibleCountItems(): number { return Math.ceil(this.viewportHeight / this.clientRowHeight - 1); } private getOffsetVisibleStartIndex(): number { return Math.ceil(this.scrollOffsetTop / this.clientRowHeight); } private preSortAndFilterTable(): void { this.setSource(this.source); this.sortAndFilter().then((): void => { this.reCheckDefinitions(); this.checkSelectionValue(); }); } private preRenderTable(): void { this.tableViewportChecked = false; this.renderedCountKeys = this.getCountKeys(); this.customModelColumnsKeys = this.generateCustomModelColumnsKeys(); this.modelColumnKeys = this.generateModelColumnKeys(); this.setSource(this.source); const unDirty: boolean = !this.dirty; this.checkSelectionValue(); this.checkFilterValues(); if (unDirty) { this.markForCheck(); } const recycleView: boolean = unDirty && this.isRendered && this.contentInit; if (recycleView) { this.renderTable(); } } private checkSelectionValue(): void { if (this.isEnableSelection) { this.selection.invalidate(); } } private checkFilterValues(): void { if (this.isEnableFiltering) { this.filterable.filterType = this.filterable.filterType ?? this.columnOptions?.filterType ?? TableFilterType.CONTAINS; this.modelColumnKeys.forEach((key: string): void => { (this.filterable.filterTypeDefinition as Any)[key] = (this.filterable.filterTypeDefinition as Any)[key] ?? this.filterable.filterType; }); } } private recheckTemplateChanges(): void { this.ngZone.runOutsideAngular((): void => { // eslint-disable-next-line no-restricted-properties window.setTimeout((): void => detectChanges(this.cd), TIME_RELOAD); }); } private listenSelectionChanges(): void { if (this.isEnableSelection) { this.selection.onChanges$.pipe(takeUntil(this._destroy$)).subscribe((): void => { detectChanges(this.cd); this.tryRefreshViewModelBySelection(); }); } } private tryRefreshViewModelBySelection(): void { this.ngZone.runOutsideAngular((): void => { window.cancelAnimationFrame(this.selectionUpdateTaskId!); this.selectionUpdateTaskId = window.requestAnimationFrame((): void => this.app.tick()); }); } private viewForceRefresh(): void { this.ngZone.runOutsideAngular((): void => { window.clearTimeout(this.timeoutCheckedTaskId!); // eslint-disable-next-line no-restricted-properties this.timeoutCheckedTaskId = window.setTimeout((): void => { this.forcedRefresh = true; this.markTemplateContentCheck(); this.render(); }, FRAME_TIME); }); } private listenTemplateChanges(): void { if (isNotNil(this.columnTemplates)) { this.columnTemplates.changes.pipe(takeUntil(this._destroy$)).subscribe((): void => { this.markForCheck(); this.markTemplateContentCheck(); }); } if (isNotNil(this.contextMenuTemplate)) { this.contextMenu.events$.pipe(takeUntil(this._destroy$)).subscribe((): void => detectChanges(this.cd)); } } private syncDrawColumns(columnList: string[]): void { for (let index: number = 0; index < columnList.length; index++) { const key: string = columnList[index] as string; const schema: Nullable<ColumnsSchema> = this.getCompiledColumnSchema(key, index); if (isNotNil(schema)) { this.processedColumnList(schema, columnList[index]); } } } private getCustomColumnSchemaByIndex(index: number): Partial<ColumnsSchema> { return this.schemaColumns?.columns?.[index] ?? ({} as Any); } /** * @description - it is necessary to combine the templates given from the server and default * @param key - column schema from rendered templates map * @param index - column position */ private getCompiledColumnSchema(key: string, index: number): Nullable<ColumnsSchema> { const customColumn: Partial<ColumnsSchema> = this.getCustomColumnSchemaByIndex(index); if (!this.templateParser.compiledTemplates[key]) { const column: NgxColumnComponent<T> = new NgxColumnComponent<T>().withKey(key); this.templateParser.compileColumnMetadata(column); } const defaultColumn: Nullable<ColumnsSchema> = this.templateParser.compiledTemplates[key]; if (customColumn.key === defaultColumn?.key) { this.templateParser.compiledTemplates[key] = { ...defaultColumn, ...customColumn } as ColumnsSchema; } return this.templateParser.compiledTemplates[key]; } /** * TODO: the schema is not used anything * @description: column meta information processing * @param schema - column schema * @param key - column name */ private processedColumnList(schema: ColumnsSchema, key: Nullable<string>): void { const hasSchema: boolean = checkValueIsFilled((this.templateParser.schema ?? schema) as Any); if (hasSchema) { const compiledSchema: Nullable<ColumnsSchema> = this.templateParser.compiledTemplates[key as string]; if (isNotNil(compiledSchema)) { this.templateParser.schema?.columns.push(compiledSchema); } } } /** * @description: notification that the table has been rendered * @see TableBuilderComponent#isRendered */ private emitRendered(): void { this.rendering = false; this.calculateViewport(true); this.recheckViewportChecked(); this.ngZone.runOutsideAngular((): void => { // eslint-disable-next-line no-restricted-properties window.setTimeout((): void => { this.isRendered = true; detectChanges(this.cd); this.recalculateHeight(); this.afterRendered.emit(this.isRendered); this.onChanges.emit(this.source ?? null); }, TIME_RELOAD); }); } /** * @description: parsing templates and input parameters (keys, schemaColumns) for the number of columns */ private generateDisplayedColumns(): string[] { let generatedList: string[]; this.templateParser.initialSchema(this.columnOptions!); const { simpleRenderedKeys, allRenderedKeys }: TemplateKeys = this.parseTemplateKeys(); const isValid: boolean = this.validationSchemaColumnsAndResetIfInvalid(); if (isValid) { generatedList = this.schemaColumns?.columns?.map( (column: DeepPartial<ColumnsSchema>): string => column.key as string ) ?? []; } else if (this.keys.length) { generatedList = this.customModelColumnsKeys; } else if (simpleRenderedKeys.size) { generatedList = allRenderedKeys; } else { generatedList = this.modelColumnKeys; } return generatedList; } // eslint-disable-next-line max-lines-per-function private validationSchemaColumnsAndResetIfInvalid(): boolean { let isValid: boolean = isNotNil(this.schemaColumns) && (this.schemaColumns?.columns?.length ?? 0) > 0; if (isValid) { const nameIsValid: boolean = this.schemaColumns?.name === this.name; const versionIsValid: boolean = this.schemaColumns?.version === this.schemaVersion; const invalid: boolean = !nameIsValid || !versionIsValid; if (invalid) { isValid = false; console.error( 'The table name or version is mismatched by your schema, your schema will be reset.', 'Current name: ', this.name, 'Current version: ', this.schemaVersion, 'Schema: ', this.schemaColumns ); this.changeSchema([]); } } return isValid; } /** * @description: this method returns the keys by which to draw table columns * <allowedKeyMap> - possible keys from the model, this must be checked, * because users can draw the wrong keys in the template (ngx-column key=invalid) */ private parseTemplateKeys(): TemplateKeys { const modelKeys: string[] = this.getModelKeys(); const keys: string[] = hasItems(this.keys) ? this.keys.filter((key: string): boolean => modelKeys.includes(key)) : modelKeys; this.templateParser.keyMap = this.generateColumnsKeyMap(keys); this.templateParser.allowedKeyMap = this.keys.length ? this.generateColumnsKeyMap(this.customModelColumnsKeys) : this.generateColumnsKeyMap(this.modelColumnKeys); this.templateParser.parse(this.columnTemplates!); return { allRenderedKeys: Array.from(this.templateParser.fullTemplateKeys!), overridingRenderedKeys: this.templateParser.overrideTemplateKeys!, simpleRenderedKeys: this.templateParser.templateKeys! }; } private listenExpandChange(): void { this.headerTemplate?.expandedChange.pipe(takeUntil(this._destroy$)).subscribe((): void => { this.updateTableHeight(); this.changeSchema(); }); } }
the_stack
const typeCache: { [key: string]: TypeInfo } = {}; /** * `MethodInfo` mapped to short names. */ const methodCache: { [key: string]: MethodInfo } = {}; const listeners: { (): void }[] = []; /** Whether grammar has been compiled to simple cache map. */ let compiled = false; /** * Whether grammar is currently being compiled. Not sure yet if this check is * needed, if VSCode makes concurrent calls. */ let compiling = false; /** * Basic information about a symbol, whether type, method, directive or access * modifier. */ export interface SymbolInfo { about: string; } /** * Data request method * @see https://cloud.google.com/firestore/docs/reference/security/#request_methods */ export interface AllowInfo extends SymbolInfo { name: string; /** Key list converted to object map during compile. */ includeTypes?: string[]; includes?: AllowInfo[]; } export interface TypeInfo extends SymbolInfo { methods?: { [key: string]: MethodInfo }; fields?: { [key: string]: TypeInfo }; /** * Assigning a `basicType` will attach that types fields and methods to this * type. */ basicType?: string; } export interface MethodInfo extends SymbolInfo { parameters?: string[]; returns?: string; /** * Snippets are generated during compile if `parameters` have been defined. * @see https://code.visualstudio.com/docs/editor/userdefinedsnippets */ snippet?: string; } /** * Find type information with given short or fully-qualified name. */ export async function findType(name: string): Promise<TypeInfo | null> { if (name == null || name == '') { return null; } await compile(); return typeCache[name] !== undefined ? typeCache[name] : null; } /** * Find any named symbol whether a type, method or access modifier. */ export async function findAny(name: string): Promise<SymbolInfo | null> { if (name == null || name == '') { return null; } await compile(); const allow = allowTypes.find(a => a.name == name); if (allow !== undefined) { return allow; } const info = typeCache[name]; if (info !== undefined) { return info; } const method = methodCache[name]; if (method !== undefined) { return method; } return null; } /** * Get named access modifiers. */ export async function accessModifiers(): Promise<AllowInfo[]> { await compile(); return allowTypes; } /** * Compile heirarchical grammar into flat map for faster lookup. If already * compiled then promise resolves immediately. Otherwise the resolver is added * to any prior resolvers (listeners) awaiting compilation. */ export function compile(force = false): Promise<void> { if (force) { compiled = false; } return compiled ? Promise.resolve() : new Promise((resolve, _reject) => { listeners.push(resolve); if (!compiling) { compiling = true; compileBasicMethods(basicTypes); compileTypes(grammar); compileAllowTypes(allowTypes); compiled = true; compiling = false; } while (listeners.length > 0) { const fn = listeners.pop(); if (fn !== undefined) { fn(); } } }); } /** * Assign basic type members to implementing types. For example, assign `string` * methods to `request.path`. */ function compileTypes( fields: { [key: string]: TypeInfo }, path: string = '' ): void { Object.keys(fields).forEach(key => { const info = fields[key]; const name = key as string; const full = path + (path != '' ? '.' : '') + name; if (info.basicType) { // copy members from basic type const basic = basicTypes[info.basicType]; if (basic) { info.methods = basic.methods; info.fields = basic.fields; } } else if (info.methods) { compileMethods(info.methods); } // cache with both simple and fully-qualified name typeCache[name] = info; typeCache[full] = info; if (info.fields) { compileTypes(info.fields, full); } }); } /** * Generate snippets for basic type methods so they don't have to be generated * again when assigned to an implementing type. */ function compileBasicMethods(fields: { [key: string]: TypeInfo }): void { Object.keys(fields).forEach(key => { const info = fields[key]; if (info.methods) { compileMethods(info.methods); } // recurse if basic type has children if (info.fields) { compileBasicMethods(info.fields); } }); } /** * Generate snippets for methods that define their parameters. Methods that have * an empty parameter array will get a parameterless method call snippet like * `method()`. * * @see https://code.visualstudio.com/docs/editor/userdefinedsnippets */ function compileMethods(methods: { [key: string]: MethodInfo }): void { Object.keys(methods).forEach(key => { const info = methods[key]; if (info.parameters) { let args = ''; if (info.parameters.length > 0) { args = info.parameters.reduce((snippet, p, i) => { if (i > 0) { snippet += ', '; } return snippet + `\${${i + 1}:${p}}`; }, ''); } info.snippet = `${key}(${args})$0`; } if (methodCache[key] !== undefined) { // If the same method name is used by multiple types then clone to // break the shared reference and combine their descriptions. const existing = Object.assign({}, methodCache[key]); if (!existing.about.startsWith('- ')) { existing.about = '- ' + existing.about; } existing.about += '\n- ' + info.about; methodCache[key] = existing; } else { methodCache[key] = info; } }); } function compileAllowTypes(access: AllowInfo[]): void { access.forEach(info => { if (info.includeTypes) { info.includes = info.includeTypes .map(name => access.find(a => a.name == name)) .filter(info => info !== undefined) as AllowInfo[]; //info.snippet = `${key}(${args})$0`; } }); } /** * Permitted request methods * @see https://cloud.google.com/firestore/docs/reference/security/#request_methods */ const allowTypes: AllowInfo[] = [ { name: 'read', about: 'Allow `get` and `list` operations', includeTypes: ['get', 'list'] }, { name: 'get', about: 'Corresponds to `get()` query method' }, { name: 'list', about: 'Corresponds to `where().get()` query method' }, { name: 'write', about: 'Allows `create`, `update` and `delete` operations', includeTypes: ['create', 'update', 'delete'] }, { name: 'create', about: 'Corresponds to `set()` and `add()` query methods' }, { name: 'update', about: 'Corresponds to `update()` query method' }, { name: 'delete', about: 'Corresponds to `remove()` query method' } ]; /** * Basic type members are assigned by reference to the symbols implementing * them. */ const basicTypes: { [key: string]: TypeInfo } = { string: { about: 'Strings can be lexographically compared and ordered using the `==`, `!=`, `>`, `<`, `>=`, and `<=` operators.', methods: { size: { about: 'Returns the number of characters in the string.', parameters: [] }, matches: { about: 'Performs a regular expression match, returns `true` if the string matches the given regular expression. Uses Google RE2 syntax.', parameters: ['regex'] }, split: { about: 'Splits a string according to a provided regular expression and returns a list of strings. Uses Google RE2 syntax.', returns: 'list', parameters: ['regex'] } } }, timestamp: { about: 'Timestamps are in UTC, with possible values beginning at 0001-01-01T00.00.00Z and ending at 9999-12-31T23.59.59Z.', methods: { date: { about: 'A timestamp value containing the year, month, and day only.', parameters: [] }, year: { about: 'The year value as an `int`, from 1 to 9999.', parameters: [] }, month: { about: 'The month value as an `int`, from 1 to 12.', parameters: [] }, day: { about: 'The current day of the month as an `int`, from 1 to 31.', parameters: [] }, time: { about: 'A `duration` value containing the current time.', returns: 'duration', parameters: [] }, hours: { about: 'The hours value as an `int`, from 0 to 23.', parameters: [] }, minutes: { about: 'The minutes value as an `int`, from 0 to 59.', parameters: [] }, seconds: { about: 'The seconds value as an int, from 0 to 59.', parameters: [] }, nanos: { about: 'The fractional seconds in nanos as an `int`.', parameters: [] }, dayOfWeek: { about: 'The day of the week, from 1 (Monday) to 7 (Sunday).', parameters: [] }, dayOfYear: { about: 'The day of the current year, from 1 to 366.', parameters: [] }, toMillis: { about: 'Returns the current number of milliseconds since the Unix epoch.', parameters: [] } } }, duration: { about: 'Duration values are represented as seconds plus fractional seconds in nanoseconds.', methods: { seconds: { about: 'The number of seconds in the current duration. Must be between -315,576,000,000 and +315,576,000,000 inclusive.', parameters: [] }, nanos: { about: 'The number of fractional seconds (in nanoseconds) of the current duration. Must be beween -999,999,999 and +999,999,999 inclusive. For non-zero seconds and non-zero nanonseconds, the signs of both must be in agreement.', parameters: [] } } }, list: { about: 'A list contains an ordered array of values, which can of type: `null`, `bool`, `int`, `float`, `string`, `path`, `list`, `map`, `timestamp`, or `duration`.', methods: { in: { about: 'Returns `true` if the desired value is present in the list or `false` if not present.', parameters: ['value'] }, join: { about: 'Combines a list of strings into a single string, separated by the given string.', parameters: [] }, size: { about: 'The number of items in the list.', parameters: [] }, hasAny: { about: 'Returns `true` if any given values are present in the list.', parameters: ['list'] }, hasAll: { about: 'Returns `true` if all values are present in the list.', parameters: ['list'] } } }, map: { about: 'A map contains key/value pairs, where keys are strings and values can be any of: `null`, `bool`, `int`, `float`, `string`, `path`, `list`, `map`, `timestamp`, or `duration`.', methods: { in: { about: 'Returns true if the desired key is present in the map or false if not present.', parameters: ['key'] }, size: { about: 'The number of keys in the map.', parameters: [] }, keys: { about: 'A list of all keys in the map.', returns: 'list', parameters: [] }, values: { about: 'A list of all values in the map, in key order.', returns: 'list', parameters: [] } } } }; /** * Types defined in Firestore Security Reference * https://cloud.google.com/firestore/docs/reference/security/ */ const grammar: { [key: string]: TypeInfo } = { global: { about: 'Globally defined methods', methods: { path: { about: 'Converts a string argument to a path.' }, exists: { about: '`exists()` takes a path and returns a bool, indicating whether a document exists at that path. The path provided must begin with `/databases/$(database)/documents`.' }, get: { about: '`get()` takes a path and returns the resource at that path. Like `exists()`, the path provided must begin with `/databases/$(database)/documents`.' } } }, math: { about: 'Cloud Firestore Security Rules also provides a number of mathematics helper functions to simplify expressions.', methods: { ceil: { about: 'Ceiling of the numeric value', parameters: ['number'] }, floor: { about: 'Floor of the numeric value', parameters: ['number'] }, round: { about: 'Round the input value to the nearest `int`', parameters: ['number'] }, abs: { about: 'Absolute value of the input', parameters: ['number'] }, isInfinite: { about: 'Test whether the value is ±∞, returns a `bool`', parameters: ['number'] }, isNaN: { about: 'Test whether the value is not a number `NaN`, returns a `bool`', parameters: ['number'] } } }, request: { about: 'The request variable is provided within a condition to represent the request being made at that path. The request variable has a number of properties which can be used to decide whether to allow the incoming request.', fields: { path: { about: 'The path variable contains the path that a request is being performed against.', basicType: 'string' }, resource: { about: 'The resource variable contains data and metadata about the document being written. It is closely related to the request variable, which contains the current document at the requested path, as opposed to the document being written.', fields: { data: { about: 'Developer provided data is surfaced in request.resource.data, which is a map containing the fields and values.', basicType: 'map' } } }, time: { about: 'The time variable contains a timestamp representing the current server time a request is being evaluated at. You can use this to provide time-based access to files, such as: only allowing files to be uploaded until a certain date, or only allowing files to be read up to an hour after they were uploaded.', basicType: 'timestamp' }, auth: { about: "When an authenticated user performs a request against Cloud Firestore, the auth variable is populated with the user's uid (`request.auth.uid`) as well as the claims of the Firebase Authentication JWT (`request.auth.token`).", fields: { uid: { about: "The user's Firebase UID. This is unique within a project.", basicType: 'string' }, token: { about: 'Firebase Authentication JWT', fields: { email: { about: 'The email address associated with the account, if present.', basicType: 'string' }, email_verified: { about: '`true` if the user has verified they have access to the `email` address. Some providers automatically verify email addresses they own.' }, phone_number: { about: 'The phone number associated with the account, if present.', basicType: 'string' }, name: { about: "The user's display name, if set.", basicType: 'string' }, sub: { about: "The user's Firebase UID. This is unique within a project.", basicType: 'string' }, firebase: { about: 'Firebase specific token properties.', fields: { identities: { about: 'Dictionary of all the identities that are associated with this user\'s account. The keys of the dictionary can be any of the following: email, phone, google.com, facebook.com, github.com, twitter.com. The values of the dictionary are arrays of unique identifiers for each identity provider associated with the account. For example, auth.token.firebase.identities["google.com"][0] contains the first Google user ID associated with the account.', basicType: 'map' }, sign_in_provider: { about: 'The sign-in provider used to obtain this token. Can be one of the following strings: custom, password, phone, anonymous, google.com, facebook.com, github.com, twitter.com.', basicType: 'string' } } } } } } } } } };
the_stack
import { throttle, isFinite, isEqual } from 'lodash'; import { getColor, getColorNum } from 'src/lib/getColor'; import * as PIXI from 'src/lib/pixi'; import type { Settings } from 'src/types'; import type { Nvim, Transport, UiEventsHandlers, UiEventsArgs, ModeInfo, HighlightAttrs, } from '@vvim/nvim'; export type Screen = { screenCoords: (width: number, height: number) => [number, number]; getCursorElement: () => HTMLDivElement; }; type CalculatedProps = { bgColor: string; fgColor: string; spColor?: string; hiItalic: boolean; hiBold: boolean; hiUnderline: boolean; hiUndercurl: boolean; hiStrikethrough: boolean; }; type HighlightProps = { calculated?: CalculatedProps; value?: HighlightAttrs; }; type HighlightTable = Record<number, HighlightProps>; type Char = { sprite: PIXI.Sprite; bg: PIXI.Sprite; char?: string | null; hlId?: number; }; const DEFAULT_FONT_FAMILY = 'monospace'; const screen = ({ settings, transport, nvim, }: { settings: Settings; transport: Transport; nvim: Nvim; }): Screen => { let screenContainer: HTMLDivElement; let cursorEl: HTMLDivElement; let screenEl: HTMLDivElement; let cursorPosition: [number, number] = [0, 0]; let cursorChar: string; let startCursorBlinkOnTimeout: NodeJS.Timeout | null; let startCursorBlinkOffTimeout: NodeJS.Timeout | null; let blinkOnCursorBlinkInterval: NodeJS.Timeout | null; let blinkOffCursorBlinkInterval: NodeJS.Timeout | null; let scale: number; let charWidth: number; let charHeight: number; let fontFamily = DEFAULT_FONT_FAMILY; let fontSize = 12; let lineHeight = 1.25; let letterSpacing = 0; const defaultFgColor = 'rgb(255,255,255)'; const defaultBgColor = 'rgb(0,0,0)'; const defaultSpColor = 'rgb(255,255,255)'; let cols: number; let rows: number; let modeInfoSet: Record<string, ModeInfo>; let mode: string; let showBold = true; let showItalic = true; let showUnderline = true; let showUndercurl = true; let showStrikethrough = true; const charCanvas = new OffscreenCanvas(1, 1); const charCtx = charCanvas.getContext('2d', { alpha: true }) as OffscreenCanvasRenderingContext2D; const chars: Char[][] = []; const highlightTable: HighlightTable = { '0': { calculated: { bgColor: defaultBgColor, fgColor: defaultFgColor, spColor: defaultSpColor, hiItalic: false, hiBold: false, hiUnderline: false, hiUndercurl: false, hiStrikethrough: false, }, }, // Inverted default color for cursor '-1': { calculated: { bgColor: defaultFgColor, fgColor: defaultBgColor, spColor: defaultSpColor, hiItalic: false, hiBold: false, hiUnderline: false, hiUndercurl: false, hiStrikethrough: false, }, }, }; // WebGL let stage: PIXI.Container; let renderer: PIXI.Renderer; let charsContainer: PIXI.Container; let bgContainer: PIXI.Container; let cursorContainer: PIXI.Container; let cursorSprite: PIXI.Sprite; let cursorBg: PIXI.Graphics; let needRerender = false; const TARGET_FPS = 60; const getCursorElement = (): HTMLDivElement => cursorEl; const windowPixelSize = () => ({ width: window.screen.width * window.devicePixelRatio, height: window.screen.height * window.devicePixelRatio, }); const initCursor = () => { cursorEl = document.createElement('div'); cursorEl.style.position = 'absolute'; cursorEl.style.zIndex = '100'; cursorEl.style.top = '0'; cursorEl.style.left = '0'; screenEl.appendChild(cursorEl); }; const initScreen = () => { screenContainer = document.createElement('div'); document.body.appendChild(screenContainer); screenContainer.style.position = 'absolute'; screenContainer.style.left = '0'; screenContainer.style.top = '0'; screenContainer.style.transformOrigin = '0 0'; screenEl = document.createElement('div'); // @ts-expect-error incomplete type declaration for style? screenEl.style.contain = 'strict'; screenEl.style.overflow = 'hidden'; // Init WebGL for text const pixi = new PIXI.Application({ transparent: true, autoStart: false, ...windowPixelSize(), }); screenEl.appendChild(pixi.view); screenContainer.appendChild(screenEl); stage = pixi.stage; renderer = pixi.renderer as PIXI.Renderer; pixi.ticker.stop(); charsContainer = new PIXI.Container(); bgContainer = new PIXI.Container(); cursorContainer = new PIXI.Container(); cursorSprite = new PIXI.Sprite(); cursorBg = new PIXI.Graphics(); stage.addChild(bgContainer); stage.addChild(charsContainer); stage.addChild(cursorContainer); cursorContainer.addChild(cursorBg); cursorContainer.addChild(cursorSprite); // Init screen for background screenEl.style.width = `${windowPixelSize().width}px`; screenEl.style.height = `${windowPixelSize().width}px`; }; const RETINA_SCALE = 2; const isRetina = () => window.devicePixelRatio === RETINA_SCALE; const scaledLetterSpacing = () => { if (isRetina() || letterSpacing === 0) { return letterSpacing; } return letterSpacing > 0 ? Math.floor(letterSpacing / RETINA_SCALE) : Math.ceil(letterSpacing / RETINA_SCALE); }; const scaledFontSize = () => fontSize * scale; const measureCharSize = () => { const char = document.createElement('span'); char.innerHTML = '0'; char.style.fontFamily = fontFamily; char.style.fontSize = `${scaledFontSize()}px`; char.style.lineHeight = `${Math.round(scaledFontSize() * lineHeight)}px`; char.style.position = 'absolute'; char.style.left = '-1000px'; char.style.top = '0'; screenEl.appendChild(char); const oldCharWidth = charWidth; const oldCharHeight = charHeight; charWidth = Math.max(char.offsetWidth + scaledLetterSpacing(), 1); charHeight = char.offsetHeight; if (oldCharWidth !== charWidth || oldCharHeight !== charHeight) { cursorSprite.x = -charWidth; cursorEl.style.width = `${charWidth}px`; cursorEl.style.height = `${charHeight}px`; if (charCanvas) { charCanvas.width = charWidth * 3; charCanvas.height = charHeight; } PIXI.utils.clearTextureCache(); } screenEl.removeChild(char); }; const font = (p: CalculatedProps) => [p.hiItalic ? 'italic' : '', p.hiBold ? 'bold' : '', `${scaledFontSize()}px`, fontFamily].join( ' ', ); const getCharBitmap = (char: string, props: CalculatedProps) => { if (props.hiUndercurl) { charCtx.strokeStyle = props.spColor as string; charCtx.lineWidth = scaledFontSize() * 0.08; const x = charWidth; const y = charHeight - (scaledFontSize() * 0.08) / 2; const h = charHeight * 0.2; // Height of the wave charCtx.beginPath(); charCtx.moveTo(x, y); charCtx.bezierCurveTo(x + x / 4, y, x + x / 4, y - h / 2, x + x / 2, y - h / 2); charCtx.bezierCurveTo(x + (x / 4) * 3, y - h / 2, x + (x / 4) * 3, y, x + x, y); charCtx.stroke(); } charCtx.fillStyle = props.fgColor; charCtx.font = font(props); charCtx.textAlign = 'left'; charCtx.textBaseline = 'middle'; if (char) { charCtx.fillText( char, Math.round(scaledLetterSpacing() / 2) + charWidth, Math.round(charHeight / 2), ); } if (props.hiUnderline) { charCtx.strokeStyle = props.fgColor; charCtx.lineWidth = scale; charCtx.beginPath(); charCtx.moveTo(charWidth, charHeight - scale); charCtx.lineTo(charWidth * 2, charHeight - scale); charCtx.stroke(); } if (props.hiStrikethrough) { charCtx.strokeStyle = props.fgColor; charCtx.lineWidth = scale; charCtx.beginPath(); charCtx.moveTo(charWidth, charHeight * 0.5); charCtx.lineTo(charWidth * 2, charHeight * 0.5); charCtx.stroke(); } return charCanvas.transferToImageBitmap(); }; const getCharTexture = (char: string, hlId: number) => { const key = `${char}:${hlId}`; if (!PIXI.utils.TextureCache[key]) { const props = highlightTable[hlId].calculated; // @ts-expect-error getCharBitmap returns ImageBitmap that can be used as texture PIXI.Texture.addToCache(PIXI.Texture.from(getCharBitmap(char, props)), key); } return PIXI.Texture.from(key); }; const getBgTexture = (bgColor: string, j: number) => { const isLastCol = j === cols - 1; const key = `bg:${bgColor}:${isLastCol}`; if (!PIXI.utils.TextureCache[key]) { charCtx.fillStyle = bgColor; if (isLastCol) { charCtx.fillRect(0, 0, charWidth * 2, charHeight); } else { charCtx.fillRect(0, 0, charWidth, charHeight); } PIXI.Texture.addToCache(PIXI.Texture.from(charCanvas.transferToImageBitmap()), key); } return PIXI.Texture.from(key); }; const initChar = (i: number, j: number) => { if (!chars[i]) chars[i] = []; if (!chars[i][j]) { chars[i][j] = { sprite: new PIXI.Sprite(), bg: new PIXI.Sprite(), }; charsContainer.addChild(chars[i][j].sprite); bgContainer.addChild(chars[i][j].bg); } }; const printChar = (i: number, j: number, char: string, hlId: number) => { initChar(i, j); // Print char chars[i][j].char = char; chars[i][j].hlId = hlId; chars[i][j].sprite.texture = getCharTexture(char, hlId); chars[i][j].sprite.position.set((j - 1) * charWidth, i * charHeight); chars[i][j].sprite.visible = true; // Draw bg chars[i][j].bg.position.set(j * charWidth, i * charHeight); const bgColor = highlightTable[hlId]?.calculated?.bgColor; if (hlId !== 0 && bgColor && bgColor !== highlightTable[0]?.calculated?.bgColor) { chars[i][j].bg.texture = getBgTexture(bgColor, j); chars[i][j].bg.visible = true; } else { chars[i][j].bg.visible = false; } }; const cursorBlinkOn = () => { cursorContainer.visible = true; renderer.render(stage); }; const cursorBlinkOff = () => { cursorContainer.visible = false; renderer.render(stage); }; const cursorBlink = ({ blinkon, blinkoff, blinkwait, }: { blinkon?: number; blinkoff?: number; blinkwait?: number } = {}) => { cursorContainer.visible = true; if (startCursorBlinkOnTimeout) clearTimeout(startCursorBlinkOnTimeout); if (startCursorBlinkOffTimeout) clearTimeout(startCursorBlinkOffTimeout); if (blinkOnCursorBlinkInterval) clearInterval(blinkOnCursorBlinkInterval); if (blinkOffCursorBlinkInterval) clearInterval(blinkOffCursorBlinkInterval); startCursorBlinkOnTimeout = null; startCursorBlinkOffTimeout = null; blinkOnCursorBlinkInterval = null; blinkOffCursorBlinkInterval = null; if (blinkoff && blinkon) { startCursorBlinkOffTimeout = setTimeout(() => { cursorBlinkOff(); blinkOffCursorBlinkInterval = setInterval(cursorBlinkOff, blinkoff + blinkon); startCursorBlinkOnTimeout = setTimeout(() => { cursorBlinkOn(); blinkOnCursorBlinkInterval = setInterval(cursorBlinkOn, blinkoff + blinkon); }, blinkoff); }, blinkwait); } }; const clearCursor = () => { cursorBg.clear(); cursorSprite.visible = false; }; const redrawCursor = () => { const m = modeInfoSet && modeInfoSet[mode]; cursorBlink(m); if (!m) return; // TODO: check if cursor changed (char, hlId, etc) clearCursor(); const hlId = m.attr_id === 0 ? -1 : m.attr_id; cursorBg.beginFill(getColorNum(highlightTable[hlId]?.calculated?.bgColor)); if (m.cursor_shape === 'block') { cursorChar = chars[cursorPosition[0]][cursorPosition[1]].char || ' '; cursorSprite.texture = getCharTexture(cursorChar, hlId); cursorBg.drawRect(0, 0, charWidth, charHeight); cursorSprite.visible = true; } else if (m.cursor_shape === 'vertical') { const curWidth = m.cell_percentage ? Math.max(scale, Math.round((charWidth / 100) * m.cell_percentage)) : scale; cursorBg.drawRect(0, 0, curWidth, charHeight); } else if (m.cursor_shape === 'horizontal') { const curHeight = m.cell_percentage ? Math.max(scale, Math.round((charHeight / 100) * m.cell_percentage)) : scale; cursorBg.drawRect(0, charHeight - curHeight, charWidth, curHeight); } needRerender = true; }; const repositionCursor = (newCursor: [number, number]): void => { if (newCursor) cursorPosition = newCursor; const left = cursorPosition[1] * charWidth; const top = cursorPosition[0] * charHeight; cursorContainer.position.set(left, top); cursorEl.style.transform = `translate(${left}px, ${top}px)`; redrawCursor(); }; const optionSet = { guifont: (newFont: string) => { const [newFontFamily, newFontSize] = newFont.trim().split(':h'); if (newFontFamily && newFontFamily !== '') { nvim.command(`VVset fontfamily=${newFontFamily.replace(/_/g, '\\ ')}`); if (newFontSize && newFontFamily !== '') { nvim.command(`VVset fontsize=${newFontSize}`); } } }, }; const reprintAllChars = () => { if (highlightTable[0]?.calculated?.bgColor) { document.body.style.background = highlightTable[0].calculated.bgColor; transport.send('set-background-color', highlightTable[0].calculated.bgColor); } PIXI.utils.clearTextureCache(); for (let i = 0; i <= rows; i += 1) { for (let j = 0; j <= cols; j += 1) { initChar(i, j); const { char, hlId } = chars[i][j]; if (char && isFinite(hlId)) { printChar(i, j, char, hlId as number); } } } needRerender = true; }; const recalculateHighlightTable = () => { ((Object.keys(highlightTable) as unknown) as number[]).forEach((id) => { if (id > 0) { const { foreground, background, special, reverse, standout, italic, bold, underline, undercurl, strikethrough, } = highlightTable[id].value || {}; const r = reverse || standout; const fg = getColor(foreground, highlightTable[0]?.calculated?.fgColor) as string; const bg = getColor(background, highlightTable[0]?.calculated?.bgColor) as string; const sp = getColor(special, highlightTable[0]?.calculated?.spColor) as string; highlightTable[(id as unknown) as number].calculated = { fgColor: r ? bg : fg, bgColor: r ? fg : bg, spColor: sp, hiItalic: showItalic && !!italic, hiBold: showBold && !!bold, hiUnderline: showUnderline && !!underline, hiUndercurl: showUndercurl && !!undercurl, hiStrikethrough: showStrikethrough && !!strikethrough, }; } }); reprintAllChars(); }; const rerender = throttle(() => { renderer.render(stage); }, 1000 / TARGET_FPS); const rerenderIfNeeded = () => { if (needRerender) { needRerender = false; rerender(); } }; // https://github.com/neovim/neovim/blob/master/runtime/doc/ui.txt const redrawCmd: Partial<UiEventsHandlers> = { set_title: () => { /* empty */ }, set_icon: () => { /* empty */ }, win_viewport: () => { /* empty */ }, mode_info_set: (props) => { modeInfoSet = props[0][1].reduce((r, modeInfo) => ({ ...r, [modeInfo.name]: modeInfo }), {}); redrawCursor(); }, option_set: (options) => { options.forEach(([option, value]) => { // @ts-expect-error TODO if (optionSet[option]) { // @ts-expect-error TODO optionSet[option](value); } else { // console.warn('Unknown option', option, value); // eslint-disable-line no-console } }); }, mode_change: (modes) => { [mode] = modes[modes.length - 1]; redrawCursor(); }, mouse_on: () => { /* empty */ }, mouse_off: () => { /* empty */ }, busy_start: () => { /* empty */ }, busy_stop: () => { /* empty */ }, suspend: () => { /* empty */ }, update_menu: () => { /* empty */ }, bell: () => { /* empty */ }, visual_bell: () => { /* empty */ }, hl_group_set: () => { /* empty */ }, flush: () => { rerenderIfNeeded(); }, grid_resize: (props) => { /* eslint-disable prefer-destructuring */ cols = props[0][1]; rows = props[0][2]; /* eslint-enable prefer-destructuring */ if (cols * charWidth > renderer.width || rows * charHeight > renderer.height) { // Add extra column on the right to fill it with adjacent color to have a nice right border const width = (cols + 1) * charWidth; const height = rows * charHeight; screenEl.style.width = `${width}px`; screenEl.style.height = `${height}px`; renderer.resize(width, height); needRerender = true; } }, default_colors_set: (props) => { const [foreground, background, special] = props[props.length - 1]; const calculated = { bgColor: getColor(background, defaultBgColor) as string, fgColor: getColor(foreground, defaultFgColor) as string, spColor: getColor(special, defaultSpColor), hiItalic: false, hiBold: false, hiUnderline: false, hiUndercurl: false, hiStrikethrough: false, }; if (!highlightTable[0] || !isEqual(highlightTable[0].calculated, calculated)) { highlightTable[0] = { calculated }; highlightTable[-1] = { calculated: { ...calculated, bgColor: getColor(foreground, defaultFgColor) as string, fgColor: getColor(background, defaultBgColor) as string, }, }; recalculateHighlightTable(); } }, hl_attr_define: (props) => { props.forEach(([id, value]) => { highlightTable[id] = { value, }; }); recalculateHighlightTable(); }, grid_line: (props) => { for (let gridKey = 0, gridLength = props.length; gridKey < gridLength; gridKey += 1) { const row = props[gridKey][1]; const col = props[gridKey][2]; const cells = props[gridKey][3]; let lineLength = 0; let currentHlId = 0; for (let cellKey = 0, cellsLength = cells.length; cellKey < cellsLength; cellKey += 1) { const [char, hlId, length = 1] = cells[cellKey]; if (hlId !== undefined && isFinite(hlId)) { currentHlId = hlId; } for (let j = 0; j < length; j += 1) { printChar(row, col + lineLength + j, char, currentHlId); } lineLength += length; } } needRerender = true; if ( chars[cursorPosition[0]] && chars[cursorPosition[0]][cursorPosition[1]] && cursorChar !== chars[cursorPosition[0]][cursorPosition[1]].char ) { redrawCursor(); } }, grid_clear: () => { cursorPosition = [0, 0]; charsContainer.children.forEach((c) => { c.visible = false; // eslint-disable-line no-param-reassign }); bgContainer.children.forEach((c) => { c.visible = false; // eslint-disable-line no-param-reassign }); for (let i = 0; i <= rows; i += 1) { if (!chars[i]) chars[i] = []; for (let j = 0; j <= cols; j += 1) { initChar(i, j); chars[i][j].char = null; } } needRerender = true; }, grid_destroy: () => { /* empty */ }, grid_cursor_goto: ([[_, ...newCursor]]) => { repositionCursor(newCursor); // Temporary workaround to fix cursor position in terminal mode. Nvim API does not send the very last cursor // position in terminal on redraw, but when you send any command to nvim, it redraws it correctly. Need to // investigate it and find a better permanent fix. Maybe this is a bug in nvim and then // TODO: file a ticket to nvim. nvim.getMode(); }, grid_scroll: ([[_grid, top, bottom, left, right, scrollCount]]) => { for ( let i = scrollCount > 0 ? top : bottom - 1; scrollCount > 0 ? i <= bottom - scrollCount - 1 : i >= top - scrollCount; i += scrollCount > 0 ? 1 : -1 ) { for (let j = left; j <= right - 1; j += 1) { const sourceI = i + scrollCount; initChar(i, j); initChar(sourceI, j); // Swap char to scroll to destination [chars[i][j], chars[sourceI][j]] = [chars[sourceI][j], chars[i][j]]; // Update scrolled char sprite position if (chars[i][j].sprite) { chars[i][j].sprite.y = i * charHeight; chars[i][j].bg.y = i * charHeight; } // Clear and reposition old char if (chars[sourceI][j].sprite) { chars[sourceI][j].sprite.visible = false; chars[sourceI][j].bg.visible = false; chars[sourceI][j].sprite.y = sourceI * charHeight; chars[sourceI][j].bg.y = sourceI * charHeight; } } } needRerender = true; }, }; const handleSet = { fontfamily: (newFontFamily: string) => { fontFamily = `${newFontFamily}, ${DEFAULT_FONT_FAMILY}`; }, fontsize: (newFontSize: string) => { fontSize = parseInt(newFontSize, 10); }, letterspacing: (newLetterSpacing: string) => { letterSpacing = parseInt(newLetterSpacing, 10); }, lineheight: (newLineHeight: string) => { lineHeight = parseFloat(newLineHeight); }, bold: (value: boolean) => { showBold = value; }, italic: (value: boolean) => { showItalic = value; }, underline: (value: boolean) => { showUnderline = value; }, undercurl: (value: boolean) => { showUndercurl = value; }, strikethrough: (value: boolean) => { showStrikethrough = value; }, }; const redraw = (args: UiEventsArgs) => { args.forEach(([cmd, ...props]) => { const command = redrawCmd[cmd]; if (command) { // @ts-expect-error TODO: find the way to type it without errors command(props); } else { console.warn('Unknown redraw command', cmd, props); // eslint-disable-line no-console } }); }; const setScale = () => { scale = isRetina() ? RETINA_SCALE : 1; screenContainer.style.transform = `scale(${1 / scale})`; screenContainer.style.width = `${scale * 100}%`; screenContainer.style.height = `${scale * 100}%`; // Detect when you drag between retina/non-retina displays window.matchMedia('screen and (min-resolution: 2dppx)').addListener(async () => { setScale(); measureCharSize(); await nvim.uiTryResize(cols, rows); }); }; /** * Return grid [col, row] coordinates by pixel coordinates. */ const screenCoords = (width: number, height: number): [number, number] => { return [Math.floor((width * scale) / charWidth), Math.floor((height * scale) / charHeight)]; }; const resize = (forceRedraw = false) => { const [newCols, newRows] = screenCoords(window.innerWidth, window.innerHeight); if (newCols !== cols || newRows !== rows || forceRedraw) { cols = newCols; rows = newRows; nvim.uiTryResize(cols, rows); } }; const uiAttach = () => { [cols, rows] = screenCoords(window.innerWidth, window.innerHeight); nvim.uiAttach(cols, rows, { ext_linegrid: true }); window.addEventListener( 'resize', throttle(() => resize(), 1000 / TARGET_FPS), ); }; const updateSettings = (newSettings: Settings, isInitial = false) => { let requireRedraw = isInitial; let requireRecalculateHighlight = false; const requireRedrawProps = [ 'fontfamily', 'fontsize', 'letterspacing', 'lineheight', 'bold', 'italic', 'underline', 'undercurl', 'strikethrough', ]; const requireRecalculateHighlightProps = [ 'bold', 'italic', 'underline', 'undercurl', 'strikethrough', ]; Object.keys(newSettings).forEach((key) => { // @ts-expect-error TODO if (handleSet[key]) { requireRedraw = requireRedraw || requireRedrawProps.includes(key); requireRecalculateHighlight = requireRecalculateHighlight || requireRecalculateHighlightProps.includes(key); // @ts-expect-error TODO handleSet[key](newSettings[key]); } }); if (requireRecalculateHighlight && !isInitial) { recalculateHighlightTable(); } if (requireRedraw) { measureCharSize(); PIXI.utils.clearTextureCache(); if (!isInitial) { resize(true); } } }; initScreen(); initCursor(); setScale(); nvim.on('redraw', redraw); transport.on('updateSettings', (s) => updateSettings(s)); updateSettings(settings, true); uiAttach(); return { screenCoords, getCursorElement, }; }; export default screen;
the_stack
import JovoCliCore, { getRawString, InstallContext, JovoCli } from '@jovotech/cli-core'; import { JovoModelData } from '@jovotech/model'; import { JovoModelGoogle } from '@jovotech/model-google'; import { BuildHook, BuildPlatformContextGoogle } from '../../src/cli/hooks/BuildHook'; import { Plugin } from '../__mocks__/Plugin'; // Create mock modules. This allows us to modify the behavior for individual functions. jest.mock('@jovotech/cli-core', () => ({ ...Object.assign({}, jest.requireActual('@jovotech/cli-core')), JovoCli: jest.fn().mockReturnValue({ project: { hasModelFiles: jest.fn(), saveModel: jest.fn(), backupModel: jest.fn() }, }), })); jest.mock('@jovotech/model-google'); beforeEach(() => { const plugin: Plugin = new Plugin(); const cli: JovoCli = new JovoCli(); plugin.$cli = cli; BuildHook.prototype['$cli'] = cli; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore BuildHook.prototype['$plugin'] = plugin; BuildHook.prototype['$context'] = { command: 'build:platform', locales: [], platforms: [], flags: {}, args: {}, } as unknown as BuildPlatformContextGoogle; }); afterEach(() => { jest.restoreAllMocks(); }); describe('install()', () => { test('should register events correctly', () => { const hook: BuildHook = new BuildHook(); expect(hook['middlewareCollection']).toBeUndefined(); hook.install(); expect(hook['middlewareCollection']).toBeDefined(); }); }); describe('addCliOptions()', () => { test('should do nothing if command is not equal to "build:platform"', () => { const args: InstallContext = { command: 'invalid', flags: {}, args: [] }; const spiedAddClioptions: jest.SpyInstance = jest.spyOn(BuildHook.prototype, 'addCliOptions'); const hook: BuildHook = new BuildHook(); hook.addCliOptions(args); expect(spiedAddClioptions).toReturn(); expect(args.flags).not.toHaveProperty('project-id'); }); test('should add "project-id" to flags', () => { const hook: BuildHook = new BuildHook(); const args: InstallContext = { command: 'build:platform', flags: {}, args: [] }; hook.addCliOptions(args); expect(args.flags).toHaveProperty('project-id'); }); }); describe('checkForPlatform()', () => { test('should do nothing if platform plugin is selected', () => { const uninstall: jest.Mock = jest.fn(); jest.spyOn(BuildHook.prototype, 'uninstall').mockImplementation(uninstall); const hook: BuildHook = new BuildHook(); hook.$context.platforms.push('testPlugin'); hook.checkForPlatform(); expect(uninstall).not.toBeCalled(); }); test('should call uninstall() if platform plugin is not selected', () => { const uninstall: jest.Mock = jest.fn(); jest.spyOn(BuildHook.prototype, 'uninstall').mockImplementation(() => uninstall()); const hook: BuildHook = new BuildHook(); hook.$context.platforms.push('invalid'); hook.checkForPlatform(); expect(uninstall).toBeCalledTimes(1); }); }); describe('updatePluginContext()', () => { test('should throw an error if project-id is not set', () => { const hook: BuildHook = new BuildHook(); hook.$context.command = 'invalidCommand'; expect(hook.updatePluginContext.bind(hook)).toThrow(); try { hook.updatePluginContext(); } catch (error) { expect(error.message).toMatch('Could not find project ID.'); } expect(hook.$context).not.toHaveProperty('project-id'); }); test('should set "project-id" from flags', () => { jest.spyOn(BuildHook.prototype, 'setDefaultLocale').mockReturnThis(); const hook: BuildHook = new BuildHook(); hook['$context'].flags['project-id'] = '123'; hook.updatePluginContext(); // eslint-disable-next-line @typescript-eslint/no-explicit-any expect(hook.$context.googleAssistant.projectId).toBe('123'); }); test('should set "project-id" from config', () => { BuildHook.prototype['$plugin'].config.projectId = '123'; const hook: BuildHook = new BuildHook(); hook.updatePluginContext(); // eslint-disable-next-line @typescript-eslint/no-explicit-any expect(hook.$context.googleAssistant.projectId).toBe('123'); }); test('should throw an error if "project-id" could not be found', () => { const hook: BuildHook = new BuildHook(); expect(hook.updatePluginContext.bind(hook)).toThrow('Could not find project ID.'); }); }); describe('checkForCleanBuild()', () => { test('should not do anything if --clean is not set', () => { jest.spyOn(JovoCliCore, 'deleteFolderRecursive').mockReturnThis(); const hook: BuildHook = new BuildHook(); hook.checkForCleanBuild(); expect(JovoCliCore.deleteFolderRecursive).not.toBeCalled(); }); test('should call deleteFolderRecursive() if --clean is set', () => { jest.spyOn(JovoCliCore, 'deleteFolderRecursive').mockReturnThis(); jest.spyOn(BuildHook.prototype.$plugin, 'platformPath', 'get').mockReturnValue('test'); const hook: BuildHook = new BuildHook(); hook.$context.flags.clean = true; hook.checkForCleanBuild(); expect(JovoCliCore.deleteFolderRecursive).toBeCalledTimes(1); expect(JovoCliCore.deleteFolderRecursive).toBeCalledWith('test'); }); }); describe('validateLocales()', () => { test('should throw an error if generic locale is required, but not provided', () => { jest.spyOn(JovoCliCore, 'getResolvedLocales').mockReturnValue(['en-US']); const hook: BuildHook = new BuildHook(); hook.$context.locales.push('en'); expect(hook.validateLocales.bind(hook)).toThrow(); try { hook.validateLocales(); } catch (error) { // Strip error message from ANSI escape codes. expect(getRawString(error.message)).toMatch('Locale en-US requires a generic locale en.'); } }); test('should throw an error if a locale is not supported', () => { jest.spyOn(JovoCliCore, 'getResolvedLocales').mockReturnValue(['zh']); const hook: BuildHook = new BuildHook(); hook.$context.locales.push('zh'); expect(hook.validateLocales.bind(hook)).toThrow(); try { hook.validateLocales(); } catch (error) { // Strip error message from ANSI escape codes. expect(getRawString(error.message)).toMatch( 'Locale zh is not supported by Google Conversational Actions.', ); } }); }); describe('validateModels()', () => { // test.skip('should call jovo.project!.validateModel() for each locale', () => {}); }); describe.skip('buildReverse()', () => { test("should return if platforms don't match", async () => { const mockedBuildReverse: jest.SpyInstance = jest.spyOn(BuildHook.prototype, 'buildReverse'); const hook: BuildHook = new BuildHook(); await hook.buildReverse(); expect(mockedBuildReverse).toReturn(); }); test('should reverse build model files for all platform locales, set the invocation name and save the model', async () => { const saveModel: jest.Mock = jest.fn(); const model: JovoModelData = { invocation: '', }; jest.spyOn(BuildHook.prototype['$cli']['project']!, 'hasModelFiles').mockReturnValue(false); jest.spyOn(BuildHook.prototype['$cli']['project']!, 'saveModel').mockImplementation(saveModel); jest.spyOn(JovoModelGoogle.prototype, 'exportJovoModel').mockReturnValue(model); jest.spyOn(BuildHook.prototype, 'getPlatformInvocationName').mockReturnValue('testInvocation'); const mockedSetDefaultLocale: jest.SpyInstance = jest .spyOn(BuildHook.prototype, 'setDefaultLocale') .mockReturnThis(); const mockedGetPlatformLocales: jest.SpyInstance = jest .spyOn(BuildHook.prototype, 'getPlatformLocales') .mockReturnValue(['en', 'en-US']); const mockedGetPlatformModels: jest.SpyInstance = jest .spyOn(BuildHook.prototype, 'getPlatformModels') .mockReturnThis(); const hook: BuildHook = new BuildHook(); // Enable this plugin. hook.$context.platforms.push('testPlugin'); await hook.buildReverse(); expect(mockedSetDefaultLocale).toBeCalledTimes(1); expect(mockedGetPlatformLocales).toBeCalledTimes(1); expect(mockedGetPlatformModels).toBeCalledTimes(2); expect(mockedGetPlatformModels.mock.calls).toEqual([['en'], ['en-US']]); expect(saveModel).toBeCalledTimes(2); expect(model.invocation).toMatch('testInvocation'); expect(saveModel.mock.calls).toEqual([ [model, 'en'], [model, 'en-US'], ]); }); test('should reverse build model files for the locale provided by --locale', async () => { const saveModel: jest.Mock = jest.fn(); const model: JovoModelData = { invocation: '', }; jest.spyOn(BuildHook.prototype['$cli']['project']!, 'hasModelFiles').mockReturnValue(false); jest.spyOn(BuildHook.prototype['$cli']['project']!, 'saveModel').mockImplementation(saveModel); jest.spyOn(JovoModelGoogle.prototype, 'exportJovoModel').mockReturnValue(model); jest.spyOn(BuildHook.prototype, 'getPlatformInvocationName').mockReturnValue('testInvocation'); const mockedSetDefaultLocale: jest.SpyInstance = jest .spyOn(BuildHook.prototype, 'setDefaultLocale') .mockReturnThis(); const mockedGetPlatformLocales: jest.SpyInstance = jest .spyOn(BuildHook.prototype, 'getPlatformLocales') .mockReturnValue(['en', 'en-US']); const mockedGetPlatformModels: jest.SpyInstance = jest .spyOn(BuildHook.prototype, 'getPlatformModels') .mockReturnThis(); const hook: BuildHook = new BuildHook(); // Enable this plugin. hook.$context.platforms.push('testPlugin'); hook.$context.flags.locale = ['en']; await hook.buildReverse(); expect(mockedSetDefaultLocale).toBeCalledTimes(1); expect(mockedGetPlatformLocales).toBeCalledTimes(1); expect(mockedGetPlatformModels).toBeCalledTimes(1); expect(mockedGetPlatformModels).toBeCalledWith('en'); expect(saveModel).toBeCalledTimes(1); expect(model.invocation).toMatch('testInvocation'); expect(saveModel).toBeCalledWith(model, 'en'); }); test('should throw an error if platform models for a provided locale cannot be found', async () => { const model: JovoModelData = { invocation: '', }; jest.spyOn(BuildHook.prototype, 'setDefaultLocale').mockReturnThis(); jest.spyOn(BuildHook.prototype, 'getPlatformLocales').mockReturnValue(['en', 'en-US']); jest.spyOn(JovoModelGoogle.prototype, 'exportJovoModel').mockReturnValue(model); jest.spyOn(BuildHook.prototype, 'getPlatformInvocationName').mockReturnValue('testInvocation'); const hook: BuildHook = new BuildHook(); // Enable this plugin. hook.$context.platforms.push('testPlugin'); hook.$context.flags.locale = ['de']; expect(hook.buildReverse.bind(hook)).rejects.toReturn(); try { await hook.buildReverse(); } catch (error) { expect(getRawString(error.message)).toMatch('Could not find platform models for locale: de'); } }); test('should prompt for overwriting existing model files and return upon cancel', async () => { jest.spyOn(BuildHook.prototype['$cli']['project']!, 'hasModelFiles').mockReturnValue(true); jest.spyOn(BuildHook.prototype, 'setDefaultLocale').mockReturnThis(); jest.spyOn(BuildHook.prototype, 'getPlatformLocales').mockReturnValue(['en', 'en-US']); const mockedPromptOverwriteReverseBuild: jest.SpyInstance = jest .spyOn(JovoCliCore, 'promptOverwriteReverseBuild') .mockReturnValue( new Promise((res) => res({ overwrite: 'cancel', }), ), ); const mockedBuildReverse: jest.SpyInstance = jest.spyOn(BuildHook.prototype, 'buildReverse'); const hook: BuildHook = new BuildHook(); // Enable this plugin. hook.$context.platforms.push('testPlugin'); await hook.buildReverse(); expect(mockedPromptOverwriteReverseBuild).toBeCalledTimes(1); expect(mockedBuildReverse).toReturn(); }); test('should prompt for overwriting existing model files and back them up accordingly', async () => { const backupModel: jest.Mock = jest.fn(); const saveModel: jest.Mock = jest.fn(); const model: JovoModelData = { invocation: '', }; jest.spyOn(BuildHook.prototype['$cli']['project']!, 'hasModelFiles').mockReturnValue(true); jest.spyOn(BuildHook.prototype['$cli']['project']!, 'saveModel').mockImplementation(saveModel); jest .spyOn(BuildHook.prototype['$cli']['project']!, 'backupModel') .mockImplementation(backupModel); jest.spyOn(BuildHook.prototype, 'setDefaultLocale').mockReturnThis(); jest.spyOn(BuildHook.prototype, 'getPlatformLocales').mockReturnValue(['en', 'en-US']); jest.spyOn(BuildHook.prototype, 'getPlatformModels').mockReturnThis(); jest.spyOn(JovoModelGoogle.prototype, 'exportJovoModel').mockReturnValue(model); jest.spyOn(BuildHook.prototype, 'getPlatformInvocationName').mockReturnValue('testInvocation'); const mockedPromptOverwriteReverseBuild: jest.SpyInstance = jest .spyOn(JovoCliCore, 'promptOverwriteReverseBuild') .mockReturnValue( new Promise((res) => res({ overwrite: 'backup', }), ), ); const hook: BuildHook = new BuildHook(); // Enable this plugin. hook.$context.platforms.push('testPlugin'); await hook.buildReverse(); expect(mockedPromptOverwriteReverseBuild).toBeCalledTimes(1); expect(backupModel).toBeCalledTimes(2); expect(backupModel.mock.calls).toEqual([['en'], ['en-US']]); }); test('should throw an error if something went wrong while exporting the Jovo Language Model', async () => { jest.spyOn(BuildHook.prototype['$cli']['project']!, 'hasModelFiles').mockReturnValue(false); jest.spyOn(JovoModelGoogle.prototype, 'exportJovoModel').mockReturnValue(undefined); jest.spyOn(BuildHook.prototype, 'setDefaultLocale').mockReturnThis(); jest.spyOn(BuildHook.prototype, 'getPlatformLocales').mockReturnValue(['en', 'en-US']); jest.spyOn(BuildHook.prototype, 'getPlatformModels').mockReturnThis(); const hook: BuildHook = new BuildHook(); // Enable this plugin. hook.$context.platforms.push('testPlugin'); expect(hook.buildReverse.bind(hook)).rejects.toReturn(); try { await hook.buildReverse(); } catch (error) { expect(error.message).toMatch('Something went wrong while exporting your Jovo model.'); } }); });
the_stack
import { assertType, autoIncrementAnnotation, BackReferenceOptionsResolved, clearTypeJitContainer, copyAndSetParent, dataAnnotation, databaseAnnotation, DatabaseFieldOptions, embeddedAnnotation, entityAnnotation, EntityOptions, excludedAnnotation, getBackReferenceType, getClassType, getReferenceType, getTypeJitContainer, groupAnnotation, hasMember, indexAnnotation, IndexOptions, isBackReferenceType, isReferenceType, isType, memberNameToString, primaryKeyAnnotation, ReferenceOptions, ReflectionKind, ReflectionVisibility, stringifyResolvedType, stringifyType, Type, TypeClass, TypeFunction, TypeMethod, TypeMethodSignature, TypeObjectLiteral, TypeParameter, TypeProperty, TypePropertySignature, TypeTemplateLiteral } from './type.js'; import { AbstractClassType, arrayRemoveItem, ClassType, getClassName, isArray, isClass, stringifyValueWithType } from '@deepkit/core'; import { Packed, resolvePacked, resolveRuntimeType } from './processor.js'; import { NoTypeReceived } from '../utils.js'; import { findCommonLiteral } from '../inheritance.js'; import type { ValidateFunction } from '../validator.js'; import { isWithDeferredDecorators } from '../decorator.js'; import { SerializedTypes, serializeType } from '../type-serialization.js'; /** * Receives the runtime type of template argument. * * Use * * ```typescript * * function f<T>(type?: ReceiveType<T>): Type { * return resolveReceiveType(type); * } * * ``` */ export type ReceiveType<T> = Packed | Type | ClassType<T>; export function resolveReceiveType(type?: Packed | Type | ClassType | AbstractClassType | ReflectionClass<any>): Type { if (!type) throw new NoTypeReceived(); if (type instanceof ReflectionClass) return type.type; if (isArray(type) && type.__type) return type.__type; if (isType(type)) return type as Type; if (isClass(type)) return resolveRuntimeType(type) as Type; return resolvePacked(type); } export function reflect(o: any, ...args: any[]): Type { return resolveRuntimeType(o, args) as Type; } export function valuesOf<T>(args: any[] = [], p?: ReceiveType<T>): (string | number | symbol | Type)[] { const type = typeOf(args, p); if (type.kind === ReflectionKind.union) { return type.types.map(v => { if (v.kind === ReflectionKind.literal) return v.literal; return v; }) as (string | number | symbol | Type)[]; } if (type.kind === ReflectionKind.objectLiteral || type.kind === ReflectionKind.class) { return type.types.map(v => { if (v.kind === ReflectionKind.method) return v; if (v.kind === ReflectionKind.property) return v.type; if (v.kind === ReflectionKind.propertySignature) return v.type; if (v.kind === ReflectionKind.methodSignature) return v; return v; }) as (string | number | symbol | Type)[]; } return []; } export function propertiesOf<T>(args: any[] = [], p?: ReceiveType<T>): (string | number | symbol | Type)[] { const type = typeOf(args, p); if (type.kind === ReflectionKind.objectLiteral || type.kind === ReflectionKind.class) { return type.types.map(v => { if (v.kind === ReflectionKind.method) return v.name; if (v.kind === ReflectionKind.property) return v.name; if (v.kind === ReflectionKind.propertySignature) return v.name; if (v.kind === ReflectionKind.methodSignature) return v.name; return v; }) as (string | number | symbol | Type)[]; } return []; } export function typeOf<T>(args: any[] = [], p?: ReceiveType<T>): Type { if (p) { return resolveRuntimeType(p, args) as Type; } throw new Error('No type given'); } export function removeTypeName<T extends Type>(type: T): Omit<T, 'typeName' | 'typeArguments'> { const o = { ...type }; if ('typeName' in o) delete o.typeName; if ('typeArguments' in o) delete o.typeArguments; return o; } export function getProperty(type: TypeObjectLiteral | TypeClass, memberName: number | string | symbol): TypeProperty | TypePropertySignature | undefined { for (const t of type.types) { if ((t.kind === ReflectionKind.property || t.kind === ReflectionKind.propertySignature) && t.name === memberName) return t; } return; } export function toSignature(type: TypeProperty | TypeMethod | TypePropertySignature | TypeMethodSignature): TypePropertySignature | TypeMethodSignature { if (type.kind === ReflectionKind.propertySignature || type.kind === ReflectionKind.methodSignature) return type; if (type.kind === ReflectionKind.property) { return { ...type, parent: type.parent as any, kind: ReflectionKind.propertySignature }; } return { ...type, parent: type.parent as any, kind: ReflectionKind.methodSignature }; } export function hasCircularReference(type: Type) { const jit = getTypeJitContainer(type); if (jit.hasCircularReference !== undefined) return jit.hasCircularReference; let hasCircular = false; visit(type, () => undefined, () => { hasCircular = true; }); return jit.hasCircularReference = hasCircular; } let visitStackId: number = 0; export function visit(type: Type, visitor: (type: Type) => false | void, onCircular?: () => void): void { const stack: { type: Type, depth: number }[] = []; stack.push({ type, depth: 0 }); const stackId: number = visitStackId++; while (stack.length) { const entry = stack.shift(); if (!entry) break; const type = entry.type; const jit = getTypeJitContainer(type); if (jit.visitStack && jit.visitStack.id === stackId && jit.visitStack.depth < entry.depth) { if (onCircular) onCircular(); return; } jit.visitStack = { id: stackId, depth: entry.depth }; visitor(type); switch (type.kind) { case ReflectionKind.objectLiteral: case ReflectionKind.tuple: case ReflectionKind.union: case ReflectionKind.class: case ReflectionKind.intersection: case ReflectionKind.templateLiteral: for (const member of type.types) stack.push({ type: member, depth: entry.depth + 1 }); break; case ReflectionKind.string: case ReflectionKind.number: case ReflectionKind.bigint: case ReflectionKind.symbol: case ReflectionKind.regexp: case ReflectionKind.boolean: if (type.origin) stack.push({ type: type.origin, depth: entry.depth + 1 }); break; case ReflectionKind.function: case ReflectionKind.method: case ReflectionKind.methodSignature: stack.push({ type: type.return, depth: entry.depth + 1 }); for (const member of type.parameters) stack.push({ type: member, depth: entry.depth + 1 }); break; case ReflectionKind.propertySignature: case ReflectionKind.property: case ReflectionKind.array: case ReflectionKind.promise: case ReflectionKind.parameter: case ReflectionKind.tupleMember: case ReflectionKind.rest: stack.push({ type: type.type, depth: entry.depth + 1 }); break; case ReflectionKind.indexSignature: stack.push({ type: type.index, depth: entry.depth + 1 }); stack.push({ type: type.type, depth: entry.depth + 1 }); break; } } } function hasFunctionExpression(fn: Function): boolean { let code = fn.toString(); if (code.startsWith('() => ')) code = code.slice('() => '.length); if (code.startsWith('function () { return ')) { code = code.slice('function () { return '.length); if (code.endsWith('; }')) code = code.slice(0, -3); } if (code.startsWith('function() { return ')) { code = code.slice('function() { return '.length); if (code.endsWith('; }')) code = code.slice(0, -3); } if (code[0] === '\'' && code[code.length - 1] === '\'') return false; if (code[0] === '"' && code[code.length - 1] === '"') return false; if (code[0] === '`' && code[code.length - 1] === '`') return false; return code.includes('('); } export class ReflectionParameter { type: Type; constructor( public readonly parameter: TypeParameter, public readonly reflectionFunction: ReflectionMethod | ReflectionFunction, ) { this.type = this.parameter.type; } getType(): Type { return this.type; } getName(): string { return this.parameter.name; } get name(): string { return this.parameter.name; } isOptional(): boolean { return this.parameter.optional === true; } hasDefault(): boolean { return this.parameter.default !== undefined; } isValueRequired(): boolean { if (this.hasDefault()) return false; return !this.isOptional(); } getDefaultValue(): any { if (this.parameter.default !== undefined) { return this.parameter.default(); } } hasDefaultFunctionExpression(): boolean { return !!(this.parameter.default && hasFunctionExpression(this.parameter.default)); } applyDecorator(t: TData) { if (t.type) { this.type = resolveReceiveType(t.type); if (this.getVisibility() !== undefined && this.reflectionFunction instanceof ReflectionMethod) { this.reflectionFunction.reflectionClass.getProperty(this.getName())!.setType(this.type); } } } getVisibility(): ReflectionVisibility | undefined { return this.parameter.visibility; } isPublic(): boolean { return this.parameter.visibility === ReflectionVisibility.public; } isProtected(): boolean { return this.parameter.visibility === ReflectionVisibility.protected; } isPrivate(): boolean { return this.parameter.visibility === ReflectionVisibility.private; } } export class ReflectionFunction { parameters: ReflectionParameter[] = []; constructor( public readonly type: TypeMethod | TypeMethodSignature | TypeFunction, ) { for (const p of this.type.parameters) { this.parameters.push(new ReflectionParameter(p, this)); } } static from(fn: Function): ReflectionFunction { //todo: cache it if (!('__type' in fn)) { //functions without any types have no __type attached return new ReflectionFunction({ kind: ReflectionKind.function, function: fn, return: { kind: ReflectionKind.any }, parameters: [] }); } const type = reflect(fn); if (type.kind !== ReflectionKind.function) { throw new Error(`Given object is not a function ${fn}`); } return new ReflectionFunction(type); } getParameterNames(): (string)[] { return this.getParameters().map(v => v.getName()); } hasParameter(name: string | number | symbol): boolean { return !!this.getParameterOrUndefined(name); } getParameterOrUndefined(name: string | number | symbol): ReflectionParameter | undefined { for (const property of this.getParameters()) { if (property.getName() === name) return property; } return; } getParameter(name: string | number | symbol): ReflectionParameter { const property = this.getParameterOrUndefined(name); if (!property) throw new Error(`No parameter ${String(name)} in method ${this.name} found.`); return property; } getParameterType(name: string | number | symbol): Type | undefined { const parameter = this.getParameter(name); if (parameter) return parameter.getType(); return; } getParameters(): ReflectionParameter[] { return this.parameters; } getReturnType(): Type { return this.type.return; } getName(): number | string | symbol { return this.type.name || 'anonymous'; } get name(): string { return memberNameToString(this.getName()); } } export class ReflectionMethod extends ReflectionFunction { /** * Whether this method acts as validator. */ validator: boolean = false; constructor( public type: TypeMethod | TypeMethodSignature, public reflectionClass: ReflectionClass<any>, ) { super(type); } setType(method: TypeMethod | TypeMethodSignature) { this.type = method; this.parameters = []; for (const p of this.type.parameters) { this.parameters.push(new ReflectionParameter(p, this)); } } applyDecorator(data: TData) { this.validator = data.validator; if (this.validator) { this.reflectionClass.validationMethod = this.getName(); } } clone(reflectionClass?: ReflectionClass<any>, method?: TypeMethod | TypeMethodSignature): ReflectionMethod { const c = new ReflectionMethod(method || this.type, reflectionClass || this.reflectionClass); //todo, clone parameter return c; } isOptional(): boolean { return this.type.optional === true; } } export function resolveForeignReflectionClass(property: ReflectionProperty): ReflectionClass<any> { if (property.isReference()) return property.getResolvedReflectionClass(); if (property.isBackReference()) { if (property.isArray()) { return resolveClassType(property.getSubType()); } return property.getResolvedReflectionClass(); } throw new Error(`Property ${property.name} is neither a Reference nor a BackReference.`); } /** * Resolved the class/object ReflectionClass of the given TypeClass|TypeObjectLiteral */ export function resolveClassType(type: Type): ReflectionClass<any> { if (type.kind !== ReflectionKind.class && type.kind !== ReflectionKind.objectLiteral) { throw new Error(`Cant resolve ReflectionClass of type ${type.kind} since its not a class or object literal`); } return ReflectionClass.from(type); } export class ReflectionProperty { //is this really necessary? jsonType?: Type; serializer?: SerializerFn; deserializer?: SerializerFn; data: { [name: string]: any } = {}; type: Type; symbol: symbol; constructor( public property: TypeProperty | TypePropertySignature, public reflectionClass: ReflectionClass<any>, ) { this.type = property.type; this.setType(this.type); this.symbol = Symbol(memberNameToString(this.getName())); } setType(type: Type) { this.type = type; } isPrimaryKey(): boolean { return primaryKeyAnnotation.isPrimaryKey(this.getType()); } isEmbedded(): boolean { return !!embeddedAnnotation.getFirst(this.getType()); } /** * Returns the sub type if available (for arrays for example). * * @throws Error if the property type does not support sub types. */ getSubType(): Type { if (this.type.kind === ReflectionKind.array) return this.type.type as Type; throw new Error(`Type ${this.type.kind} does not support sub types`); } /** * If undefined, it's not an embedded class. */ getEmbedded(): { prefix?: string } | undefined { return embeddedAnnotation.getFirst(this.getType()); } isBackReference(): boolean { return isBackReferenceType(this.getType()); } getBackReference(): BackReferenceOptionsResolved { return getBackReferenceType(this.getType()); } isAutoIncrement(): boolean { return autoIncrementAnnotation.getFirst(this.getType()) === true; } isReference(): boolean { return isReferenceType(this.getType()); } isArray(): boolean { return this.type.kind === ReflectionKind.array; } isDate(): boolean { return this.type.kind === ReflectionKind.class && this.type.classType === Date; } isNumber(): boolean { return this.type.kind === ReflectionKind.number || this.type.kind === ReflectionKind.bigint; } getForeignKeyName(): string { return this.getNameAsString(); } getReference(): ReferenceOptions | undefined { return getReferenceType(this.getType()); } getGroups(): string[] { return groupAnnotation.getAnnotations(this.getType()); } getExcluded(): string[] { return excludedAnnotation.getAnnotations(this.getType()); } isSerializerExcluded(name: string): boolean { return excludedAnnotation.isExcluded(this.getType(), name); } getData(): { [name: string]: any } { return dataAnnotation.getFirst(this.getType()) || {}; } /** * Returns the ReflectionClass of the reference class/object literal. * * @throws Error if the property is not from type TypeClass or TypeObjectLiteral */ getResolvedReflectionClass(): ReflectionClass<any> { if (this.type.kind !== ReflectionKind.class && this.type.kind !== ReflectionKind.objectLiteral) { throw new Error(`Could not resolve reflection class since ${this.name} is not a class|object but of type ${stringifyType(this.type)}`); } return resolveClassType(this.getType()); } /** * If undefined the property is not an index. * A unique property is defined as index with IndexOptions.unique=true. */ getIndex(): IndexOptions | undefined { return indexAnnotation.getFirst(this.getType()); } /** * Returns database specific options, if defined * * ```typescript * interface User { * logins: number & DatabaseField<{type: 'integer(8)'}>; * * //of for a specific db engine * logins: number & Sqlite<{type: 'integer(8)'}>; * } * * ``` */ getDatabase<T extends DatabaseFieldOptions>(name: string): T | undefined { return databaseAnnotation.getDatabase<T>(this.getType(), name); } clone(reflectionClass?: ReflectionClass<any>, property?: TypeProperty | TypePropertySignature): ReflectionProperty { const c = new ReflectionProperty(copyAndSetParent(property || this.property), reflectionClass || this.reflectionClass); c.jsonType = this.jsonType; c.serializer = this.serializer; c.deserializer = this.deserializer; return c; } applyDecorator(data: TData) { this.serializer = data.serializer; this.deserializer = data.deserializer; Object.assign(this.data, data.data); //note: data.validators is already applied in Processor } getName(): number | string | symbol { return this.property.name; } getNameAsString(): string { return memberNameToString(this.property.name); } get name(): string { return memberNameToString(this.property.name); } getKind(): ReflectionKind { return this.type.kind; } getType(): Type { return this.type as Type; } getDescription(): string { return this.property.description || ''; } /** * Whether a value is required from serialization point of view. * If this property has for example a default value (set via constructor or manually via t.default), * then the value is not required to instantiate the property value. */ isValueRequired(): boolean { if (this.hasDefault()) return false; return !this.isOptional(); } /** * Returns true when `undefined` or a missing value is allowed at the class itself. * This is now only true when `optional` is set, but also when type is `any`. */ isActualOptional(): boolean { return this.isOptional() || this.type.kind === ReflectionKind.any; } /** * If the property is actual optional or is an union with undefined in it. */ isOptional(): boolean { return this.property.optional === true || (this.type.kind === ReflectionKind.union && this.type.types.some(v => v.kind === ReflectionKind.undefined)); } setOptional(v: boolean): void { this.property.optional = v ? true : undefined; } isNullable(): boolean { return (this.type.kind === ReflectionKind.union && this.type.types.some(v => v.kind === ReflectionKind.null)); } isReadonly(): boolean { return this.property.readonly === true; } isAbstract(): boolean { return this.property.kind === ReflectionKind.property && this.property.abstract === true; } hasDefault(): boolean { return this.property.kind === ReflectionKind.property && this.property.default !== undefined; } getDefaultValue(): any { if (this.property.kind === ReflectionKind.property && this.property.default !== undefined) { try { return this.property.default(); } catch { return; } } } hasDefaultFunctionExpression(): boolean { return this.property.kind === ReflectionKind.property && !!this.property.default && hasFunctionExpression(this.property.default); } getDefaultValueFunction(): (() => any) | undefined { if (this.property.kind === ReflectionKind.property && this.property.default !== undefined) { return this.property.default; } return; } getVisibility(): ReflectionVisibility | undefined { return this.property.kind === ReflectionKind.property ? this.property.visibility : undefined; } isPublic(): boolean { return this.property.kind === ReflectionKind.property ? this.property.visibility === ReflectionVisibility.public : true; } isProtected(): boolean { return this.property.kind === ReflectionKind.property ? this.property.visibility === ReflectionVisibility.protected : false; } isPrivate(): boolean { return this.property.kind === ReflectionKind.property ? this.property.visibility === ReflectionVisibility.private : false; } } export const reflectionClassSymbol = Symbol('reflectionClass'); export interface SerializerFn { (value: any, property: ReflectionProperty): any; } export class TData { validator: boolean = false; validators: ValidateFunction[] = []; type?: Packed | Type | ClassType; data: { [name: string]: any } = {}; serializer?: SerializerFn; deserializer?: SerializerFn; } export class EntityData { name?: string; collectionName?: string; databaseSchemaName?: string; disableConstructor: boolean = false; data: { [name: string]: any } = {}; indexes: { names: string[], options: IndexOptions }[] = []; singleTableInheritance?: true; } function applyEntityOptions(reflection: ReflectionClass<any>, entityOptions: EntityOptions) { if (entityOptions.name !== undefined) reflection.name = entityOptions.name; if (entityOptions.description !== undefined) reflection.description = entityOptions.description; if (entityOptions.collection !== undefined) reflection.collectionName = entityOptions.collection; if (entityOptions.database !== undefined) reflection.databaseSchemaName = entityOptions.database; if (entityOptions.singleTableInheritance !== undefined) reflection.singleTableInheritance = entityOptions.singleTableInheritance; if (entityOptions.indexes !== undefined) reflection.indexes = entityOptions.indexes; } /** * @reflection never */ export class ReflectionClass<T> { /** * The description, extracted from the class JSDoc @description. */ description: string = ''; /** * A place where arbitrary data is stored, usually set via decorator t.data. */ data: { [name: string]: any } = {}; /** * The unique entity name. * * ```typescript * @entity.name('user') * class User { * * } * ``` */ name?: string; databaseSchemaName?: string; disableConstructor: boolean = false; /** * The collection name, used in database context (also known as table name). * * Usually, if this is not set, `name` will be used. * * ```typescript * @entity.collection('users').name('user') * class User { * * } * ``` */ collectionName?: string; /** * True when @entity.singleTableInheritance was set. */ singleTableInheritance: boolean = false; /** * Contains all indexed, multi-field using entity.index and all indexes from properties. * * ```typescript * @entity * .collection('users') * .name('user') * .index(['username', 'email']) * .index(['email', 'region'], {unique: true}) * class User { * username: string; * email: string; * } * ``` */ indexes: { names: string[], options: IndexOptions }[] = []; protected propertyNames: string[] = []; protected methodNames: string[] = []; protected properties: ReflectionProperty[] = []; protected methods: ReflectionMethod[] = []; /** * References and back references. */ protected references: ReflectionProperty[] = []; protected primaries: ReflectionProperty[] = []; protected autoIncrements: ReflectionProperty[] = []; /** * If a custom validator method was set via @t.validator, then this is the method name. */ public validationMethod?: string | symbol | number | TypeTemplateLiteral; /** * A class using @t.singleTableInheritance registers itself in this array in its super class. */ public subClasses: ReflectionClass<any>[] = []; constructor(public readonly type: TypeClass | TypeObjectLiteral, public readonly parent?: ReflectionClass<any>) { if (type.kind !== ReflectionKind.class && type.kind !== ReflectionKind.objectLiteral) throw new Error('Only class, interface, or object literal type possible'); if (parent) { this.name = parent.name; this.collectionName = parent.collectionName; this.databaseSchemaName = parent.databaseSchemaName; for (const member of parent.getProperties()) { this.registerProperty(member.clone(this)); } for (const member of parent.getMethods()) { this.registerMethod(member.clone(this)); } } for (const member of type.types) { this.add(member); } const entityOptions = entityAnnotation.getFirst(this.type); if (entityOptions) { applyEntityOptions(this, entityOptions); } //apply decorators if (type.kind === ReflectionKind.class && isWithDeferredDecorators(type.classType)) { for (const decorator of type.classType.__decorators) { if (decorator.target !== type.classType) continue; const { data, property, parameterIndexOrDescriptor } = decorator; if (property === undefined && parameterIndexOrDescriptor === undefined) { this.applyDecorator(data); } else if (property !== undefined && parameterIndexOrDescriptor === undefined) { const reflectionProperty = this.getPropertyOrUndefined(property); if (reflectionProperty) reflectionProperty.applyDecorator(data); const reflectionMethod = this.getMethodOrUndefined(property); if (reflectionMethod) reflectionMethod.applyDecorator(data); } else if (parameterIndexOrDescriptor !== undefined) { const reflectionMethod = this.getMethodOrUndefined(property || 'constructor'); if (reflectionMethod) { const params = reflectionMethod.getParameters(); const param = params[parameterIndexOrDescriptor]; if (param) param.applyDecorator(data); } } } } } clone(): ReflectionClass<any> { const reflection = new ReflectionClass(copyAndSetParent(this.type), this.parent); reflection.name = this.name; reflection.collectionName = this.collectionName; reflection.databaseSchemaName = this.databaseSchemaName; reflection.singleTableInheritance = this.singleTableInheritance; reflection.indexes = this.indexes.slice(); reflection.subClasses = this.subClasses.slice(); reflection.data = { ...this.data }; return reflection; } toString(): string { return stringifyResolvedType(this.type); } getPropertiesDeclaredInConstructor(): ReflectionProperty[] { const constructor = this.getMethod('constructor'); if (!constructor) return []; const propertyNames = constructor.parameters.filter(v => v.getVisibility() !== undefined).map(v => v.getName()); return this.properties.filter(v => propertyNames.includes(memberNameToString(v.getName()))); } clearJitContainer() { clearTypeJitContainer(this.type); } getJitContainer() { return getTypeJitContainer(this.type); } getClassType(): ClassType { return this.type.kind === ReflectionKind.class ? this.type.classType : Object; } getClassName(): string { return this.type.kind === ReflectionKind.class ? getClassName(this.getClassType()) : this.type.typeName || 'Object'; } createDefaultObject(): object { try { return new (this.getClassType()); } catch { return {}; } } getName(): string { return this.name || this.getClassName(); } getCollectionName(): string { return this.collectionName || this.getName(); } hasProperty(name: string | symbol | number): boolean { return this.propertyNames.includes(memberNameToString(name)); } hasMethod(name: string | symbol | number): boolean { return this.methodNames.includes(memberNameToString(name)); } getPrimary(): ReflectionProperty { if (!this.primaries.length) { throw new Error(`Class ${this.getClassName()} has no primary key.`); } return this.primaries[0]; } getAutoIncrement(): ReflectionProperty | undefined { return this.autoIncrements[0]; } public isSchemaOf(classType: ClassType): boolean { if (this.getClassType() === classType) return true; let currentProto = Object.getPrototypeOf(this.getClassType().prototype); while (currentProto && currentProto !== Object.prototype) { if (currentProto === classType) return true; currentProto = Object.getPrototypeOf(currentProto); } return false; } hasPrimary(): boolean { return this.primaries.length > 0; } getPrimaries(): ReflectionProperty[] { return this.primaries; } /** * Returns the ReflectionClass object from parent/super class, if available. */ getSuperReflectionClass(): ReflectionClass<any> | undefined { return this.parent; } removeProperty(name: string | number | symbol) { const property = this.properties.find(v => v.getName() === name); if (!property) throw new Error(`Property ${String(name)} not known in ${this.getClassName()}`); ; const stringName = memberNameToString(name); arrayRemoveItem(this.propertyNames, stringName); const indexType = this.type.types.findIndex(v => (v.kind === ReflectionKind.property || v.kind === ReflectionKind.propertySignature) && v.name === name); if (indexType !== -1) this.type.types.splice(indexType, 1); arrayRemoveItem(this.properties, property); if (property.isReference() || property.isBackReference()) { arrayRemoveItem(this.references, property); } if (property.isPrimaryKey()) arrayRemoveItem(this.primaries, property); if (property.isAutoIncrement()) arrayRemoveItem(this.autoIncrements, property); const index = property.getIndex(); if (index) { const indexFound = this.indexes.findIndex(v => v.names.length === 0 && v.names[0] === property.name); if (indexFound !== -1) this.indexes.splice(indexFound, 1); } } registerProperty(property: ReflectionProperty) { if (this.propertyNames.includes(property.name)) { this.removeProperty(property.getName()); } if (!hasMember(this.type, property.getName())) { this.type.types.push(property.property as any); } property.property.parent = this.type; this.properties.push(property); this.propertyNames.push(property.name); if (property.isReference() || property.isBackReference()) { this.references.push(property); } if (property.isPrimaryKey()) this.primaries.push(property); if (property.isAutoIncrement()) this.autoIncrements.push(property); const index = property.getIndex(); if (index) { this.indexes.push({ names: [property.name], options: index }); } this.getJitContainer(); } addProperty(prop: { name: number | string | symbol; optional?: true; readonly?: true; description?: string; visibility?: ReflectionVisibility type: Type; }): ReflectionProperty { const type = { kind: this.type.kind === ReflectionKind.class ? ReflectionKind.property : ReflectionKind.propertySignature, parent: this.type, ...prop } as TypeProperty | TypePropertySignature; if (type.kind === ReflectionKind.property) { type.visibility = prop.visibility ?? ReflectionVisibility.public; } const property = new ReflectionProperty(type, this); this.registerProperty(property); return property; } registerMethod(method: ReflectionMethod) { if (this.methodNames.includes(method.name)) return; this.methods.push(method); this.methodNames.push(method.name); } add(member: Type) { if (member.kind === ReflectionKind.property || member.kind === ReflectionKind.propertySignature) { const existing = this.getPropertyOrUndefined(member.name); if (existing) { existing.setType(member.type); } else { this.registerProperty(new ReflectionProperty(member, this)); } } if (member.kind === ReflectionKind.method || member.kind === ReflectionKind.methodSignature) { const existing = this.getMethodOrUndefined(member.name); if (existing) { existing.setType(member); } else { this.registerMethod(new ReflectionMethod(member, this)); } } } public assignedSingleTableInheritanceSubClassesByIdentifier?: { [id: string]: ReflectionClass<any> }; getAssignedSingleTableInheritanceSubClassesByIdentifier(): { [id: string]: ReflectionClass<any> } | undefined { if (!this.subClasses.length) return; if (this.assignedSingleTableInheritanceSubClassesByIdentifier) return this.assignedSingleTableInheritanceSubClassesByIdentifier; let isBaseOfSingleTableEntity = false; for (const schema of this.subClasses) { if (schema.singleTableInheritance) { isBaseOfSingleTableEntity = true; break; } } if (!isBaseOfSingleTableEntity) return; const discriminant = this.getSingleTableInheritanceDiscriminantName(); for (const schema of this.subClasses) { if (schema.singleTableInheritance) { if (!this.assignedSingleTableInheritanceSubClassesByIdentifier) this.assignedSingleTableInheritanceSubClassesByIdentifier = {}; const property = schema.getProperty(discriminant); assertType(property.type, ReflectionKind.literal); this.assignedSingleTableInheritanceSubClassesByIdentifier[property.type.literal as string] = schema; } } return this.assignedSingleTableInheritanceSubClassesByIdentifier; } hasSingleTableInheritanceSubClasses(): boolean { return this.getAssignedSingleTableInheritanceSubClassesByIdentifier() !== undefined; } getSingleTableInheritanceDiscriminantName(): string { if (!this.data.singleTableInheritanceProperty) { // let discriminant = findCommonDiscriminant(this.subClasses); //when no discriminator was found, find a common literal const discriminant = findCommonLiteral(this.subClasses); if (!discriminant) { throw new Error(`Sub classes of ${this.getClassName()} single-table inheritance [${this.subClasses.map(v => v.getClassName())}] have no common discriminant or common literal. Please define one.`); } this.data.singleTableInheritanceProperty = this.getProperty(discriminant); } return (this.data.singleTableInheritanceProperty as ReflectionProperty).name; } applyDecorator(data: EntityData) { Object.assign(this.data, data.data); if (data.name !== undefined) this.name = data.name; if (data.collectionName !== undefined) this.collectionName = data.collectionName; if (data.databaseSchemaName !== undefined) this.databaseSchemaName = data.databaseSchemaName; this.disableConstructor = data.disableConstructor; this.indexes.push(...data.indexes); if (data.singleTableInheritance) { this.singleTableInheritance = true; if (this.parent) { //the subclass is only added when really needed (e.g. for tracking childs of a single table inheritance setup) otherwise it's a memory leak when a lot of classes //are dynamically created. this.parent.subClasses.push(this); } } } static from<T>(classTypeIn?: ReceiveType<T> | AbstractClassType<T> | TypeClass | TypeObjectLiteral | ReflectionClass<any>, args: any[] = []): ReflectionClass<T> { if (!classTypeIn) throw new Error(`No type given in ReflectionClass.from<T>`); if (isArray(classTypeIn)) classTypeIn = resolveReceiveType(classTypeIn); if (classTypeIn instanceof ReflectionClass) return classTypeIn; if (isType(classTypeIn)) { if (classTypeIn.kind === ReflectionKind.objectLiteral || (classTypeIn.kind === ReflectionKind.class && classTypeIn.typeArguments)) { const jit = getTypeJitContainer(classTypeIn); if (jit.reflectionClass) return jit.reflectionClass; return jit.reflectionClass = new ReflectionClass<T>(classTypeIn); } if (classTypeIn.kind !== ReflectionKind.class) throw new Error(`TypeClass or TypeObjectLiteral expected, not ${classTypeIn.kind}`); } const classType = isType(classTypeIn) ? (classTypeIn as TypeClass).classType : (classTypeIn as any)['prototype'] ? classTypeIn as ClassType<T> : classTypeIn.constructor as ClassType<T>; if (!classType.prototype.hasOwnProperty(reflectionClassSymbol)) { Object.defineProperty(classType.prototype, reflectionClassSymbol, { writable: true, enumerable: false }); } if (classType.prototype[reflectionClassSymbol] && args.length === 0) { return classType.prototype[reflectionClassSymbol]; } const type = isType(classTypeIn) ? classTypeIn as TypeClass : ('__type' in classType ? resolveRuntimeType(classType, args) : { kind: ReflectionKind.class, classType, types: [] } as TypeClass); if (type.kind !== ReflectionKind.class) { throw new Error(`Given class is not a class but kind ${type.kind}. classType: ${stringifyValueWithType(classType)}`); } const parentProto = Object.getPrototypeOf(classType.prototype); const parentReflectionClass: ReflectionClass<T> | undefined = parentProto && parentProto.constructor !== Object ? ReflectionClass.from(parentProto, type.extendsArguments) : undefined; const reflectionClass = new ReflectionClass(type, parentReflectionClass); if (args.length === 0) { classType.prototype[reflectionClassSymbol] = reflectionClass; return reflectionClass; } else { return reflectionClass; } } getIndexSignatures() { throw new Error('todo'); } getPropertyNames(): (string | number | symbol)[] { return this.propertyNames; } getProperties(): ReflectionProperty[] { return this.properties; } getMethodNames(): (string | number | symbol)[] { return this.methodNames; } getMethods(): ReflectionMethod[] { return this.methods; } /** * Returns references and back references. */ getReferences(): ReflectionProperty[] { return this.references; } getConstructorOrUndefined(): ReflectionMethod | undefined { return this.getMethodOrUndefined('constructor'); } getPropertyOrUndefined(name: string | number | symbol | TypeTemplateLiteral): ReflectionProperty | undefined { for (const property of this.getProperties()) { if (property.getName() === name) return property; } return; } getProperty(name: string | number | symbol): ReflectionProperty { const property = this.getPropertyOrUndefined(name); if (!property) throw new Error(`No property ${memberNameToString(name)} found in ${this.getClassName()}`); return property; } getMethodParameters(name: string | number | symbol): ReflectionParameter[] { const method = this.getMethodOrUndefined(name); return method ? method.getParameters() : []; } getMethodOrUndefined(name: string | number | symbol | TypeTemplateLiteral): ReflectionMethod | undefined { for (const method of this.getMethods()) { if (method.getName() === name) return method; } return; } getMethod(name: string | number | symbol): ReflectionMethod { const method = this.getMethodOrUndefined(name); if (!method) throw new Error(`No method ${memberNameToString(name)} found in ${this.getClassName()}`); return method; } public hasCircularReference(): boolean { return hasCircularReference(this.type); } serializeType(): SerializedTypes { return serializeType(this.type); } /** * All references have a counter-part. This methods finds it and errors if not possible. * * If the given reference is a owning reference it finds the correct backReference, * which can be found by checking all reference options.mappedBy. * * If the given reference is a back reference it finds the owning reference, * which can be found by using its options.mappedBy. * * Alternatively we simply check for resolvedClassType to be given `classType`, and if only one * found, we return it. When more than one found, we throw an error saying the user he * should make its relation mapping not ambiguous. */ public findReverseReference(toClassType: ClassType, fromReference: ReflectionProperty): ReflectionProperty { if (fromReference.isBackReference() && fromReference.getBackReference().mappedBy) { if (resolveForeignReflectionClass(fromReference).getClassType() === this.getClassType()) { return this.getProperty(fromReference.getBackReference().mappedBy as string); } } const candidates: ReflectionProperty[] = []; for (const backRef of this.references) { if (backRef === fromReference) continue; //backRef points to something completely different if (!backRef.isArray() && resolveForeignReflectionClass(backRef).getClassType() !== toClassType) continue; if (backRef.isArray() && getClassType(backRef.getSubType()) !== toClassType) continue; //we found the perfect match, manually annotated if (backRef.isBackReference() && backRef.getBackReference().mappedBy) { if (backRef.getBackReference().mappedBy === fromReference.name) { return backRef; } continue; } if (fromReference.isBackReference() && fromReference.getBackReference().mappedBy && !fromReference.getBackReference().via) { if (fromReference.getBackReference().mappedBy === backRef.name) { //perfect match return backRef; } continue; } //add to candidates if possible if (fromReference.isBackReference() && fromReference.getBackReference().via && backRef.isBackReference() && backRef.getBackReference().via) { if (fromReference.getBackReference().via === backRef.getBackReference().via) { candidates.push(backRef); } continue; } if (fromReference.isBackReference() && fromReference.isArray() && !fromReference.getBackReference().via) { //other side must be non-array if (backRef.isArray()) continue; } candidates.push(backRef); } if (candidates.length > 1) { throw new Error(`Class ${this.getClassName()} has multiple potential reverse references [${candidates.map(v => v.name).join(', ')}] for ${fromReference.name} to class ${getClassName(toClassType)}. ` + `Please specify each back reference by using 'mappedBy', e.g. @t.backReference({mappedBy: 'fieldNameOnTheOtherSide'} so its not ambiguous anymore.`); } if (candidates.length === 1) return candidates[0]; throw new Error(`Class ${this.getClassName()} has no reference to class ${getClassName(toClassType)} defined.`); } public extractPrimaryKey(item: object): Partial<T> { const primaryKey: Partial<T> = {}; for (const pk of this.getPrimaries()) { (primaryKey as any)[pk.name] = (item as any)[pk.name]; } return primaryKey; } } // old function to decorate an interface // export function decorate<T>(decorate: { [P in keyof T]?: FreeDecoratorFn<any> }, p?: ReceiveType<T>): ReflectionClass<T> { // const type = typeOf([], p); // if (type.kind === ReflectionKind.objectLiteral) { // const classType = class { // }; // const reflection = new ReflectionClass({ kind: ReflectionKind.class, classType, types: type.types }); // (classType as any).prototype[reflectionClassSymbol] = reflection; // // for (const [p, fn] of Object.entries(decorate)) { // (fn as FreeDecoratorFn<any>)(classType, p); // } // // return reflection; // } // throw new Error('Decorate is only possible on object literal/interfaces.'); // }
the_stack
/// <reference types="phantomjs" /> export function create(options?: CasperOptions): Casper; export function selectXPath(expression: string): object; export class Casper { constructor(options: CasperOptions); test: Tester; options: CasperOptions; // Properties __utils__: ClientUtils; // Methods back(): Casper; base64encode(url: string, method?: string, data?: any): string; bypass(nb: number): Casper; click(selector: string, X?: number | string, Y?: number | string): boolean; clickLabel(label: string, tag?: string): boolean; capture(targetFilePath: string, clipRect?: ClipRect, imgOptions?: ImgOptions): Casper; captureBase64(format: string, area?: string | ClipRect | CasperSelector): string; captureSelector(targetFile: string, selector: string, imgOptions?: ImgOptions): Casper; clear(): Casper; clearCache(): Casper; clearMemoryCache(): Casper; debugHTML(selector?: string, outer?: boolean): Casper; debugPage(): Casper; die(message: string, status?: number): Casper; download(url: string, target: string, method?: string, data?: any): Casper; each<T>(array: T[], fn: (this: Casper, item: T, index: number) => void): Casper; eachThen(array: any[], then?: FunctionThen): Casper; echo(message: string, style?: string): Casper; evaluate<T>(fn: (...args: any[]) => T, ...args: any[]): T; evaluateOrDie(fn: () => any, message?: string, status?: number): Casper; exit(status?: number): Casper; exists(selector: string): boolean; fetchText(selector: string): string; forward(): Casper; log(message: string, level?: string, space?: string): Casper; fill(selector: string, values: any, submit?: boolean): void; fillSelectors(selector: string, values: any, submit?: boolean): void; fillXPath(selector: string, values: any, submit?: boolean): void; getCurrentUrl(): string; getElementAttribute(selector: string, attribute: string): string; getElementsAttribute(selector: string, attribute: string): string; getElementBounds(selector: string, page?: boolean): ElementBounds | null; getElementsBounds(selector: string): ElementBounds[]; getElementInfo(selector: string): ElementInfo; getElementsInfo(selector: string): ElementInfo; getFormValues(selector: string): any; getGlobal(name: string): any; getHTML(selector?: string, outer?: boolean): string; getPageContent(): string; getTitle(): string; mouseEvent(type: string, selector: string, X?: number|string, Y?: number|string): boolean; newPage(): any; open(location: string, settings: OpenSettings): Casper; reload(then?: FunctionThen): Casper; repeat(times: number, then: FunctionThen): Casper; resourceExists(test: string | Function | RegExp): boolean; run(onComplete?: Function, time?: number): Casper; scrollTo(x: number, y: number): Casper; scrollToBottom(): Casper; sendKeys(selector: string, keys: string, options?: KeyOptions): Casper; setHttpAuth(username: string, password: string): Casper; setMaxListeners(maxListeners: number): Casper; start(url?: string, then?: FunctionThen): Casper; status(asString?: false): number; status(asString: true): string; switchToFrame(frameInfo: string | number): Casper; switchToMainFrame(): Casper; switchToParentFrame(): Casper; then(fn: (this: Casper) => void): Casper; thenBypass(nb: number): Casper; thenBypassIf(condition: any, nb: number): Casper; thenBypassUnless(condition: any, nb: number): Casper; thenClick(selector: string, then?: FunctionThen): Casper; thenEvaluate(fn: () => any, ...args: any[]): Casper; thenOpen(location: string, then?: (response: HttpResponse) => void): Casper; thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void): Casper; thenOpenAndEvaluate(location: string, then?: FunctionThen, ...args: any[]): Casper; toString(): string; unwait(): Casper; // 2017-10-19 Doc said returning String but code return Casper object. userAgent(agent: string): Casper; viewport(width: number, height: number, then?: FunctionThen): Casper; visible(selector: string): boolean; wait(timeout: number, then?: FunctionThen): Casper; waitFor(testFx: Function, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number, details?: any): Casper; waitForAlert(then: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitForExec(command: string | null, parameter: string[], then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitForPopup(urlPattern: RegExp | string | number | FindByUrlNameTitle, then?: FunctionThen, onTimeout?: Function, timeout?: number): Casper; waitForResource(testFx: RegExp | string | ((resource: {url: string}) => boolean), then?: FunctionThen, onTimeout?: Function, timeout?: number): Casper; waitForUrl(url: RegExp | string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitForSelector(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitWhileSelector(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitForSelectorTextChange(selectors: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitForText(pattern: RegExp | string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitUntilVisible(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; waitWhileVisible(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; warn(message: string): Casper; withFrame(frameInfo: string | number, then: FunctionThen): Casper; withPopup(popupInfo: RegExp | string | number | FindByUrlNameTitle, step: FunctionThen): Casper; withSelectorScope(selector: string, then: FunctionThen): Casper; zoom(factor: number): Casper; // do not exists anymore // removeAllFilters(filter: string): Casper; // do not exists anymore // setFilter(filter: string, cb: Function): boolean; } export type FunctionThen = (this: Casper, response: HttpResponse) => void; export type FunctionOnTimeout = (this: Casper, timeout: number, details: any) => void; // not visible in doc // interface QtRuntimeObject {id?: any; url?: string;} // see modules/pagestack.js in casperjs export interface ImgOptions { // format to set the image format manually, avoiding relying on the filename format?: string; // quality to set the image quality, from 1 to 100 quality?: number; } export interface FindByUrlNameTitle { url?: string; title?: string; windowName?: string; } export interface Header { name: string; value: string; } export interface CasperSelector { type?: 'xpath' | 'css'; path: string; } export interface KeyOptions { reset?: boolean; keepFocus?: boolean; modifiers?: string; // combinaison of 'ctrl+alt+shift+meta+keypad' } export interface HttpResponse { contentType: string; headers: Header[]; id: number; redirectURL: string | null; stage: string; status: number; statusText: string; time: string; url: string; data: any; } export interface OpenSettings { method: string; data: any; headers: any; } export interface ElementBounds { top: number; left: number; width: number; height: number; } export interface ElementInfo { nodeName: string; attributes: any; tag: string; html: string; text: string; x: number; y: number; width: number; height: number; visible: boolean; } export interface CasperOptions { clientScripts?: any[]; exitOnError?: boolean; httpStatusHandlers?: any; logLevel?: string; onAlert?: Function; onDie?: Function; onError?: Function; onLoadError?: Function; onPageInitialized?: Function; onResourceReceived?: Function; onResourceRequested?: Function; onStepComplete?: Function; onStepTimeout?: Function; onTimeout?: Function; onWaitTimeout?: Function; page?: WebPage; pageSettings?: any; remoteScripts?: any[]; safeLogs?: boolean; silentErrors?: boolean; stepTimeout?: number; timeout?: number; verbose?: boolean; viewportSize?: any; retryTimeout?: number; waitTimeout?: number; } export interface ClientUtils { echo(message: string): void; encode(contents: string): void; exists(selector: string): void; findAll(selector: string): void; findOne(selector: string): void; getBase64(url: string, method?: string, data?: any): void; getBinary(url: string, method?: string, data?: any): void; getDocumentHeight(): void; getElementBounds(selector: string): void; getElementsBounds(selector: string): void; getElementByXPath(expression: string, scope?: HTMLElement): void; getElementsByXPath(expression: string, scope?: HTMLElement): void; getFieldValue(inputName: string): void; getFormValues(selector: string): void; mouseEvent(type: string, selector: string): void; removeElementsByXPath(expression: string): void; sendAJAX(url: string, method?: string, data?: any, async?: boolean): void; visible(selector: string): void; } export interface Colorizer { colorize(text: string, styleName: string): void; format(text: string, style: any): void; } export interface Tester { assert(condition: boolean, message?: string): any; assertDoesntExist(selector: string, message?: string): any; assertElementCount(selctor: string, expected: number, message?: string): any; assertEquals(testValue: any, expected: any, message?: string): any; assertEval(fn: Function, message: string, args: any): any; assertEvalEquals(fn: Function, expected: any, message?: string, args?: any): any; assertExists(selector: string, message?: string): any; assertFalsy(subject: any, message?: string): any; assertField(inputName: string, expected: string, message?: string): any; assertFieldName(inputName: string, expected: string, message?: string, options?: any): any; assertFieldCSS(cssSelector: string, expected: string, message?: string): any; assertFieldXPath(xpathSelector: string, expected: string, message?: string): any; assertHttpStatus(status: number, message?: string): any; assertMatch(subject: any, pattern: RegExp, message?: string): any; assertNot(subject: any, message?: string): any; assertNotEquals(testValue: any, expected: any, message?: string): any; assertNotVisible(selector: string, message?: string): any; assertRaises(fn: Function, args: any[], message?: string): any; assertSelectorDoesntHaveText(selector: string, text: string, message?: string): any; assertSelectorExists(selector: string, message?: string): any; assertSelectorHasText(selector: string, text: string, message?: string): any; assertResourceExists(testFx: Function, message?: string): any; assertTextExists(expected: string, message?: string): any; assertTextDoesntExist(unexpected: string, message: string): any; assertTitle(expected: string, message?: string): any; assertTitleMatch(pattern: RegExp, message?: string): any; assertTruthy(subject: any, message?: string): any; assertType(input: any, type: string, message?: string): any; assertInstanceOf(input: any, ctor: Function, message?: string): any; assertUrlMatch(pattern: RegExp | string, message?: string): any; assertVisible(selector: string, message?: string): any; /* since 1.1 */ begin(description: string, planned: number, suite: Function): any; begin(description: string, suite: Function): any; begin(description: string, planned: number, config: object): any; begin(description: string, config: object): any; colorize(message: string, style: string): any; comment(message: string): any; done(expected?: number): any; error(message: string): any; fail(message: string): any; formatMessage(message: string, style: string): any; getFailures(): Cases; getPasses(): Cases; info(message: string): any; pass(message: string): any; renderResults(exit: boolean, status: number, save: string): any; setup(fn: Function): any; skip(nb: number, message: string): any; tearDown(fn: Function): any; } export interface Cases { length: number; cases: Case[]; } export interface Case { success: boolean; type: string; standard: string; file: string; values: CaseValues; } export interface CaseValues { subject: boolean; expected: boolean; } export interface Utils { betterTypeOf(input: any): any; dump(value: any): any; fileExt(file: string): any; fillBlanks(text: string, pad: number): any; format(f: string, ...args: any[]): any; getPropertyPath(obj: any, path: string): any; inherits(ctor: any, superCtor: any): any; isArray(value: any): any; isCasperObject(value: any): any; isClipRect(value: any): any; isFalsy(subject: any): any; isFunction(value: any): any; isJsFile(file: string): any; isNull(value: any): any; isNumber(value: any): any; isObject(value: any): any; isRegExp(value: any): any; isString(value: any): any; isTruthy(subject: any): any; isType(what: any, type: string): any; isUndefined(value: any): any; isWebPage(what: any): any; mergeObjects(origin: any, add: any): any; node(name: string, attributes: any): any; serialize(value: any): any; unique(array: any[]): any; }
the_stack
import { joinName } from "uniforms"; import * as React from "react"; import { PropsWithChildren, useCallback, useEffect, useMemo, useRef } from "react"; import { AutoField } from "./AutoField"; import { DataType } from "@kogito-tooling/boxed-expression-component/dist/api"; import { DmnRunnerRule } from "../boxed"; import { DecisionResult, DmnSchemaProperties, DmnValidator, FORMS_ID, Result } from "../dmn"; import { ColumnInstance } from "react-table"; import { DmnTableJsonSchemaBridge } from "../dmn/DmnTableJsonSchemaBridge"; import { DmnAutoRow, DmnAutoRowApi } from "../dmn/DmnAutoRow"; import { diff } from "deep-object-diff"; interface InputField { dataType: DataType; width: number; name: string; cellDelegate: (formId: string) => React.ReactNode; } interface InputWithInsideProperties extends InputField { insideProperties: Array<InputField>; } type InputFields = InputField | InputWithInsideProperties; export function isInputWithInsideProperties(toBeDetermined: InputFields): toBeDetermined is InputWithInsideProperties { return (toBeDetermined as InputWithInsideProperties).insideProperties !== undefined; } interface OutputField { dataType: DataType; width?: number; name: string; } interface OutputTypesField extends OutputField { type: string; } interface OutputWithInsideProperties extends OutputTypesField { insideProperties: Array<OutputTypesField>; } type OutputTypesFields = OutputTypesField | OutputWithInsideProperties; type OutputFields = OutputField | OutputWithInsideProperties; type OutputTypesAndNormalFields = OutputTypesFields | OutputFields; export function isOutputWithInsideProperties( toBeDetermined: OutputTypesAndNormalFields ): toBeDetermined is OutputWithInsideProperties { return (toBeDetermined as OutputWithInsideProperties).insideProperties !== undefined; } const CELL_MINIMUM_WIDTH = 150; const DEFAULT_DATE_TIME_CELL_WDITH = 296; const DEFAULT_DATE_CELL_WIDTH = 180; export function usePrevious<T>(value: T) { const ref = useRef<T>(); useEffect(() => { ref.current = value; }, [value]); return ref.current; } export function useGrid( jsonSchema: object, results: Array<DecisionResult[] | undefined> | undefined, inputRows: Array<object>, setInputRows: React.Dispatch<React.SetStateAction<Array<object>>>, rowCount: number, formsDivRendered: boolean, rowsRef: Map<number, React.RefObject<DmnAutoRowApi> | null>, inputColumnsCache: React.MutableRefObject<ColumnInstance[]>, outputColumnsCache: React.MutableRefObject<ColumnInstance[]>, defaultModel: React.MutableRefObject<Array<object>>, defaultValues: object ) { const removeInputName = useCallback((fullName: string) => { return fullName.match(/\./) ? fullName.split(".").slice(1).join("-") : fullName; }, []); const getDataTypeProps = useCallback((type: string | undefined) => { let extractedType = (type ?? "").split("FEEL:").pop(); if ((extractedType?.length ?? 0) > 1) { extractedType = (type ?? "").split(":").pop()?.split("}").join("").trim(); } switch (extractedType) { case "<Undefined>": return { dataType: DataType.Undefined, width: CELL_MINIMUM_WIDTH }; case "Any": return { dataType: DataType.Any, width: CELL_MINIMUM_WIDTH }; case "boolean": return { dataType: DataType.Boolean, width: CELL_MINIMUM_WIDTH }; case "context": return { dataType: DataType.Context, width: CELL_MINIMUM_WIDTH }; case "date": return { dataType: DataType.Date, width: DEFAULT_DATE_CELL_WIDTH }; case "date and time": return { dataType: DataType.DateTime, width: DEFAULT_DATE_TIME_CELL_WDITH }; case "days and time duration": return { dataType: DataType.DateTimeDuration, width: CELL_MINIMUM_WIDTH }; case "number": return { dataType: DataType.Number, width: CELL_MINIMUM_WIDTH }; case "string": return { dataType: DataType.String, width: CELL_MINIMUM_WIDTH }; case "time": return { dataType: DataType.Time, width: CELL_MINIMUM_WIDTH }; case "years and months duration": return { dataType: DataType.YearsMonthsDuration, width: CELL_MINIMUM_WIDTH }; default: return { dataType: (extractedType as DataType) ?? DataType.Undefined, width: CELL_MINIMUM_WIDTH }; } }, []); const deepGenerateInputFields = useCallback( (jsonSchemaBridge: DmnTableJsonSchemaBridge, fieldName: any, parentName = ""): InputFields | undefined => { const joinedName = joinName(parentName, fieldName); if (jsonSchemaBridge) { const field = jsonSchemaBridge.getField(joinedName); if (field.type === "object") { const insideProperties: Array<InputField> = jsonSchemaBridge .getSubfields(joinedName) .reduce((acc: Array<InputField>, subField: string) => { const field = deepGenerateInputFields( jsonSchemaBridge, subField, joinedName ) as InputWithInsideProperties; if (field && field.insideProperties) { return [...acc, ...field.insideProperties]; } return [...acc, field]; }, []); return { ...getDataTypeProps(field["x-dmn-type"]), insideProperties, name: joinedName, width: insideProperties.reduce((acc, insideProperty) => acc + insideProperty.width, 0), } as InputWithInsideProperties; } return { ...getDataTypeProps(field["x-dmn-type"]), name: removeInputName(joinedName), cellDelegate: (formId: string) => <AutoField key={joinedName} name={joinedName} form={formId} />, } as InputField; } }, [getDataTypeProps, removeInputName] ); const generateInputFields = useCallback( (jsonSchemaBridge: DmnTableJsonSchemaBridge) => { const subfields = jsonSchemaBridge?.getSubfields(); return ( subfields?.reduce((acc: Array<InputFields>, fieldName: string) => { const generateInputFields = deepGenerateInputFields(jsonSchemaBridge, fieldName); if (generateInputFields) { return [...acc, generateInputFields]; } }, [] as Array<InputFields>) ?? [] ); }, [deepGenerateInputFields] ); // when update schema, re-create the json schema and generate the new inputs using the saved columns properties const jsonSchemaBridge = useMemo(() => { return new DmnValidator().getBridge(jsonSchema ?? {}); }, [jsonSchema]); const previousBridge = usePrevious(jsonSchemaBridge); const inputs = useMemo(() => { const newInputs = generateInputFields(jsonSchemaBridge); inputColumnsCache.current?.map((column) => { if (column.groupType === "input") { const inputToUpdate = newInputs.find((e) => e.name === column.label); if (inputToUpdate && isInputWithInsideProperties(inputToUpdate) && column?.columns) { inputToUpdate.insideProperties.forEach((insideProperty) => { const columnFound = column.columns?.find((nestedColumn) => nestedColumn.label === insideProperty.name); if (columnFound && columnFound.width) { insideProperty.width = columnFound.width as number; } }); } else if (inputToUpdate && isInputWithInsideProperties(inputToUpdate) && column.width) { inputToUpdate.insideProperties.forEach((insideProperty) => { const width = (column.width as number) / inputToUpdate.insideProperties.length; if (width < CELL_MINIMUM_WIDTH) { insideProperty.width = CELL_MINIMUM_WIDTH; } else { insideProperty.width = width; } }); } if (inputToUpdate && column.width && column.width > inputToUpdate.width) { inputToUpdate.width = column.width as number; } } }); return newInputs; }, [inputColumnsCache, generateInputFields, jsonSchemaBridge]); useEffect(() => { if (previousBridge === undefined) { return; } setInputRows((previousData) => { const newData = [...previousData]; const propertiesDifference = diff( (previousBridge.schema ?? {}).definitions?.InputSet?.properties ?? {}, jsonSchemaBridge.schema?.definitions?.InputSet?.properties ?? {} ); const updatedData = newData.map((data) => { return Object.entries(propertiesDifference).reduce( (row, [property, value]) => { if (Object.keys(row).length === 0) { return row; } if (!value || value.type || value.$ref) { delete (row as any)[property]; } if (value?.["x-dmn-type"]) { (row as any)[property] = undefined; } return row; }, { ...defaultValues, ...data } ); }); defaultModel.current = updatedData; return updatedData; }); }, [defaultModel, defaultValues, jsonSchemaBridge, previousBridge, setInputRows]); const updateWidth = useCallback( (output: any[]) => { inputColumnsCache.current?.forEach((column) => { if (column.groupType === "input") { const inputToUpdate = inputs.find((i) => i.name === column.label); if (inputToUpdate && isInputWithInsideProperties(inputToUpdate) && column?.columns) { inputToUpdate.insideProperties.forEach((insideProperty) => { const columnFound = column.columns?.find((nestedColumn) => nestedColumn.label === insideProperty.name); if (columnFound && columnFound.width) { insideProperty.width = columnFound.width as number; } }); } if (inputToUpdate && column.width) { inputToUpdate.width = column.width as number; } } }); outputColumnsCache.current?.forEach((column) => { if (column.groupType === "output") { const outputToUpdate = output.find((e) => e.name === column.label); if (outputToUpdate?.insideProperties && column?.columns) { (outputToUpdate.insideProperties as any[]).forEach((insideProperty) => { if (insideProperty !== null && typeof insideProperty === "object") { Object.keys(insideProperty).map((insidePropertyKey) => { const columnFound = column.columns?.find((nestedColumn) => nestedColumn.label === insidePropertyKey); if (columnFound) { insideProperty[insidePropertyKey] = { value: insideProperty[insidePropertyKey], width: columnFound.width, }; } }); } else if (insideProperty) { const columnFound = column.columns?.find((nestedColumn) => nestedColumn.label === insideProperty.name); if (columnFound) { insideProperty.width = columnFound.width; } } }); } if (outputToUpdate) { outputToUpdate.width = column.width; } } }); }, [inputColumnsCache, outputColumnsCache, inputs] ); const onModelUpdate = useCallback( (model: object, index) => { setInputRows?.((previousData) => { const newData = [...previousData]; newData[index] = model; return newData; }); }, [setInputRows] ); const inputRules: Partial<DmnRunnerRule>[] = useMemo(() => { if (jsonSchemaBridge === undefined || !formsDivRendered) { return [] as Partial<DmnRunnerRule>[]; } const inputEntriesLength = inputs.reduce( (length, input) => (isInputWithInsideProperties(input) ? length + input.insideProperties.length : length + 1), 0 ); const inputEntries = Array.from(Array(inputEntriesLength)); return Array.from(Array(rowCount)).map((e, rowIndex) => { return { inputEntries, rowDelegate: ({ children }: PropsWithChildren<any>) => { const dmnAutoRowRef = React.createRef<DmnAutoRowApi>(); rowsRef.set(rowIndex, dmnAutoRowRef); return ( <DmnAutoRow ref={dmnAutoRowRef} formId={FORMS_ID} rowIndex={rowIndex} model={defaultModel.current[rowIndex]} jsonSchemaBridge={jsonSchemaBridge} onModelUpdate={(model) => onModelUpdate(model, rowIndex)} > {children} </DmnAutoRow> ); }, } as Partial<DmnRunnerRule>; }); }, [jsonSchemaBridge, formsDivRendered, inputs, rowCount, rowsRef, defaultModel, onModelUpdate]); const deepFlattenOutput = useCallback((acc: any, entry: string, value: object) => { return Object.entries(value).map(([deepEntry, deepValue]) => { if (typeof deepValue === "object" && deepValue !== null) { deepFlattenOutput(acc, deepEntry, deepValue); } acc[`${entry}-${deepEntry}`] = deepValue; return acc; }); }, []); const deepGenerateOutputTypesMapFields = useCallback( ( outputTypeMap: Map<string, OutputTypesFields>, properties: DmnSchemaProperties[], jsonSchemaBridge: DmnTableJsonSchemaBridge ) => { return Object.entries(properties).map(([name, property]: [string, DmnSchemaProperties]) => { if (property["x-dmn-type"]) { const dataType = getDataTypeProps(property["x-dmn-type"]).dataType; outputTypeMap.set(name, { type: property.type, dataType, name }); return { name, type: property.type, width: CELL_MINIMUM_WIDTH, dataType }; } const path: string[] = property.$ref.split("/").slice(1); // remove # const data = path.reduce( (acc: { [x: string]: object }, property: string) => acc[property], jsonSchemaBridge.schema ); const dataType = getDataTypeProps(data["x-dmn-type"]).dataType; if (data.properties) { const insideProperties = deepGenerateOutputTypesMapFields(outputTypeMap, data.properties, jsonSchemaBridge); outputTypeMap.set(name, { type: data.type, insideProperties, dataType, name }); } else { outputTypeMap.set(name, { type: data.type, dataType, name }); } return { name, dataType: data.type, width: CELL_MINIMUM_WIDTH } as OutputTypesField; }); }, [getDataTypeProps] ); const { outputs, outputRules } = useMemo(() => { const decisionResults = results?.filter((result) => result !== undefined); if (jsonSchemaBridge === undefined || decisionResults === undefined) { return { outputs: [] as OutputFields[], outputRules: [] as Partial<DmnRunnerRule>[] }; } // generate a map that contains output types const outputTypeMap = Object.entries( (jsonSchemaBridge as any).schema?.definitions?.OutputSet?.properties ?? [] ).reduce((outputTypeMap: Map<string, OutputTypesFields>, [name, properties]: [string, DmnSchemaProperties]) => { if (properties["x-dmn-type"]) { const dataType = getDataTypeProps(properties["x-dmn-type"]).dataType; outputTypeMap.set(name, { type: properties.type, dataType, name }); } else { const path = properties.$ref.split("/").slice(1); // remove # const data = path.reduce((acc: any, property: string) => acc[property], (jsonSchemaBridge as any).schema); const dataType = getDataTypeProps(data["x-dmn-type"]).dataType; if (data.properties) { const insideProperties = deepGenerateOutputTypesMapFields(outputTypeMap, data.properties, jsonSchemaBridge); outputTypeMap.set(name, { type: data.type, insideProperties, dataType, name }); } else { outputTypeMap.set(name, { type: data.type, dataType, name }); } } return outputTypeMap; }, new Map<string, OutputFields>()); // generate outputs const outputMap = decisionResults.reduce( (acc: Map<string, OutputFields>, decisionResult: DecisionResult[] | undefined) => { if (decisionResult) { decisionResult.forEach(({ decisionName }) => { const data = outputTypeMap.get(decisionName); const dataType = data?.dataType ?? DataType.Undefined; if (data && isOutputWithInsideProperties(data)) { acc.set(decisionName, { name: decisionName, dataType, insideProperties: data.insideProperties, width: data.insideProperties.reduce((acc: number, column: any) => acc + column.width, 0), }); } else { acc.set(decisionName, { name: decisionName, dataType, width: CELL_MINIMUM_WIDTH, }); } }); } return acc; }, new Map<string, OutputFields>() ); const outputEntries = decisionResults.reduce((acc: Result[], decisionResult: DecisionResult[] | undefined) => { if (decisionResult) { const outputResults = decisionResult.map(({ result, decisionName }) => { if (result === null || typeof result !== "object") { const dmnRunnerClause = outputMap.get(decisionName); if (dmnRunnerClause && isOutputWithInsideProperties(dmnRunnerClause)) { return dmnRunnerClause.insideProperties.reduce((acc, insideProperty) => { acc[insideProperty.name] = "null"; return acc; }, {} as { [x: string]: any }); } } if (result === null) { return "null"; } if (result === true) { return "true"; } if (result === false) { return "false"; } if (typeof result === "object") { return Object.entries(result).reduce((acc: any, [entry, value]) => { if (typeof value === "object" && value !== null) { deepFlattenOutput(acc, entry, value); } else { acc[entry] = value; } return acc; }, {}); } return result; }); return [...acc, outputResults]; } return acc; }, []); const outputRules: Partial<DmnRunnerRule>[] = Array.from(Array(rowCount)).map((e, i) => ({ outputEntries: (outputEntries?.[i] as string[]) ?? [], })); const outputs = Array.from(outputMap.values()); updateWidth(outputs); return { outputs, outputRules }; }, [ deepFlattenOutput, deepGenerateOutputTypesMapFields, getDataTypeProps, jsonSchemaBridge, results, rowCount, updateWidth, ]); return useMemo(() => { return { jsonSchemaBridge, inputs, inputRules, outputs, outputRules, updateWidth, }; }, [inputRules, inputs, jsonSchemaBridge, outputRules, outputs, updateWidth]); }
the_stack
import * as React from 'react'; import { TVertex } from '../../src/types'; export type TLargeNode = TVertex<{ service: string; operation: string }>; export default { edges: [ { from: 'fervent::ferve/fervent', to: 'carson::carso/carson', }, { from: 'fervent::ferve/fervent', to: 'volhard::volha/volhard', }, { from: 'fervent::ferve/fervent', to: 'yalow::yalow/yalow', }, { from: 'fervent::ferve/fervent', to: 'mystifying::mysti/mystifying', }, { from: 'fervent::ferve/fervent', to: 'meninsky::menin/meninsky', }, { from: 'fervent::ferve/fervent', to: 'admiring::admir/admiring', }, { from: 'fervent::ferve/fervent', to: 'fervent::ferve/fervent', }, { from: 'fervent::ferve/fervent', to: 'hoover::hoove/hoover', }, { from: 'fervent::ferve/fervent', to: 'brahmagupta::brahm/brahmagupta', }, { from: 'fervent::ferve/fervent', to: 'banach::banac/banach', }, { from: 'fervent::ferve/fervent', to: 'chatterjee::chatt/chatterjee', }, { from: 'fervent::ferve/fervent', to: 'unruffled::unruf/unruffled', }, { from: 'fervent::ferve/fervent', to: 'shockley::shock/shockley', }, { from: 'fervent::ferve/fervent', to: 'pasteur::paste/pasteur', }, { from: 'fervent::ferve/fervent', to: 'upbeat::upbea/upbeat', }, { from: 'fervent::ferve/fervent', to: 'darwin::darwi/darwin', }, { from: 'fervent::ferve/fervent', to: 'priceless::price/priceless', }, { from: 'fervent::ferve/fervent', to: 'sammet::samme/sammet', }, { from: 'fervent::ferve/fervent', to: 'serene::seren/serene', }, { from: 'fervent::ferve/fervent', to: 'vigorous::vigor/vigorous', }, { from: 'fervent::ferve/fervent', to: 'gracious::graci/gracious', }, { from: 'fervent::ferve/fervent', to: 'hardcore::hardc/hardcore', }, { from: 'fervent::ferve/fervent', to: 'elastic::elast/elastic', }, { from: 'fervent::ferve/fervent', to: 'dazzling::dazzl/dazzling', }, { from: 'fervent::ferve/fervent', to: 'neumann::neuma/neumann', }, { from: 'keller::kelle/keller', to: 'fervent::ferve/fervent', }, { from: 'keller::kelle/keller', to: 'shockley::shock/shockley', }, { from: 'carson::carso/carson', to: 'heuristic::heuri/heuristic', }, { from: 'murdock::murdo/murdock', to: 'fervent::ferve/fervent', }, { from: 'mystifying::mysti/mystifying', to: 'eloquent::eloqu/eloquent', }, { from: 'mystifying::mysti/mystifying', to: 'peaceful::peace/peaceful', }, { from: 'shockley::shock/shockley', to: 'fervent::ferve/fervent', }, { from: 'shockley::shock/shockley', to: 'volhard::volha/volhard', }, { from: 'shockley::shock/shockley', to: 'brahmagupta::brahm/brahmagupta', }, { from: 'shockley::shock/shockley', to: 'mystifying::mysti/mystifying', }, { from: 'shockley::shock/shockley', to: 'darwin::darwi/darwin', }, { from: 'shockley::shock/shockley', to: 'upbeat::upbea/upbeat', }, { from: 'brahmagupta::brahm/brahmagupta', to: 'infallible::infal/infallible', }, { from: 'brahmagupta::brahm/brahmagupta', to: 'heuristic::heuri/heuristic', }, { from: 'brahmagupta::brahm/brahmagupta', to: 'easley::easle/easley', }, { from: 'infallible::infal/infallible', to: 'sharp::sharp/sharp', }, { from: 'banach::banac/banach', to: 'lalande::lalan/lalande', }, { from: 'banach::banac/banach', to: 'brave::brave/brave', }, { from: 'banach::banac/banach', to: 'wright::wrigh/wright', }, { from: 'banach::banac/banach', to: 'jones::jones/jones', }, { from: 'banach::banac/banach', to: 'bose::bose/bose', }, { from: 'banach::banac/banach', to: 'ecstatic::ecsta/ecstatic', }, { from: 'banach::banac/banach', to: 'volhard::volha/volhard', }, { from: 'banach::banac/banach', to: 'tereshkova::teres/tereshkova', }, { from: 'banach::banac/banach', to: 'lichterman::licht/lichterman', }, { from: 'chatterjee::chatt/chatterjee', to: 'heuristic::heuri/heuristic', }, { from: 'sharp::sharp/sharp', to: 'sharp::sharp/sharp', }, { from: 'lalande::lalan/lalande', to: 'visvesvaraya::visve/visvesvaraya', }, { from: 'upbeat::upbea/upbeat', to: 'tereshkova::teres/tereshkova', }, { from: 'upbeat::upbea/upbeat', to: 'volhard::volha/volhard', }, { from: 'priceless::price/priceless', to: 'priceless::price/priceless', }, { from: 'sammet::samme/sammet', to: 'mclean::mclea/mclean', }, { from: 'mclean::mclea/mclean', to: 'stupefied::stupe/stupefied', }, { from: 'wright::wrigh/wright', to: 'bhabha::bhabh/bhabha', }, { from: 'jones::jones/jones', to: 'youthful::youth/youthful', }, { from: 'jones::jones/jones', to: 'heuristic::heuri/heuristic', }, { from: 'youthful::youth/youthful', to: 'lumiere::lumie/lumiere', }, { from: 'lumiere::lumie/lumiere', to: 'lumiere::lumie/lumiere', }, { from: 'ecstatic::ecsta/ecstatic', to: 'golick::golic/golick', }, { from: 'ecstatic::ecsta/ecstatic', to: 'goldstine::golds/goldstine', }, { from: 'ecstatic::ecsta/ecstatic', to: 'volhard::volha/volhard', }, { from: 'golick::golic/golick', to: 'zhukovsky::zhuko/zhukovsky', }, { from: 'zhukovsky::zhuko/zhukovsky', to: 'zhukovsky::zhuko/zhukovsky', }, { from: 'goldstine::golds/goldstine', to: 'dubinsky::dubin/dubinsky', }, { from: 'dubinsky::dubin/dubinsky', to: 'dubinsky::dubin/dubinsky', }, { from: 'vigorous::vigor/vigorous', to: 'joliot::jolio/joliot', }, { from: 'vigorous::vigor/vigorous', to: 'vigorous::vigor/vigorous', }, { from: 'vigorous::vigor/vigorous', to: 'pensive::pensi/pensive', }, { from: 'jolly::jolly/jolly', to: 'fervent::ferve/fervent', }, { from: 'euclid::eucli/euclid', to: 'jolly::jolly/jolly', }, { from: 'boring::borin/boring', to: 'fervent::ferve/fervent', }, { from: 'fermi::fermi/fermi', to: 'fervent::ferve/fervent', }, ], vertices: [ { key: 'fervent::ferve/fervent', service: 'fervent', operation: 'ferve/fervent', }, { key: 'carson::carso/carson', service: 'carson', operation: 'carso/carson', }, { key: 'volhard::volha/volhard', service: 'volhard', operation: 'volha/volhard', }, { key: 'yalow::yalow/yalow', service: 'yalow', operation: 'yalow/yalow', }, { key: 'mystifying::mysti/mystifying', service: 'mystifying', operation: 'mysti/mystifying', }, { key: 'meninsky::menin/meninsky', service: 'meninsky', operation: 'menin/meninsky', }, { key: 'admiring::admir/admiring', service: 'admiring', operation: 'admir/admiring', }, { key: 'hoover::hoove/hoover', service: 'hoover', operation: 'hoove/hoover', }, { key: 'brahmagupta::brahm/brahmagupta', service: 'brahmagupta', operation: 'brahm/brahmagupta', }, { key: 'banach::banac/banach', service: 'banach', operation: 'banac/banach', }, { key: 'chatterjee::chatt/chatterjee', service: 'chatterjee', operation: 'chatt/chatterjee', }, { key: 'unruffled::unruf/unruffled', service: 'unruffled', operation: 'unruf/unruffled', }, { key: 'shockley::shock/shockley', service: 'shockley', operation: 'shock/shockley', }, { key: 'pasteur::paste/pasteur', service: 'pasteur', operation: 'paste/pasteur', }, { key: 'upbeat::upbea/upbeat', service: 'upbeat', operation: 'upbea/upbeat', }, { key: 'darwin::darwi/darwin', service: 'darwin', operation: 'darwi/darwin', }, { key: 'priceless::price/priceless', service: 'priceless', operation: 'price/priceless', }, { key: 'sammet::samme/sammet', service: 'sammet', operation: 'samme/sammet', }, { key: 'serene::seren/serene', service: 'serene', operation: 'seren/serene', }, { key: 'vigorous::vigor/vigorous', service: 'vigorous', operation: 'vigor/vigorous', }, { key: 'gracious::graci/gracious', service: 'gracious', operation: 'graci/gracious', }, { key: 'hardcore::hardc/hardcore', service: 'hardcore', operation: 'hardc/hardcore', }, { key: 'elastic::elast/elastic', service: 'elastic', operation: 'elast/elastic', }, { key: 'dazzling::dazzl/dazzling', service: 'dazzling', operation: 'dazzl/dazzling', }, { key: 'neumann::neuma/neumann', service: 'neumann', operation: 'neuma/neumann', }, { key: 'keller::kelle/keller', service: 'keller', operation: 'kelle/keller', }, { key: 'heuristic::heuri/heuristic', service: 'heuristic', operation: 'heuri/heuristic', }, { key: 'murdock::murdo/murdock', service: 'murdock', operation: 'murdo/murdock', }, { key: 'eloquent::eloqu/eloquent', service: 'eloquent', operation: 'eloqu/eloquent', }, { key: 'peaceful::peace/peaceful', service: 'peaceful', operation: 'peace/peaceful', }, { key: 'infallible::infal/infallible', service: 'infallible', operation: 'infal/infallible', }, { key: 'easley::easle/easley', service: 'easley', operation: 'easle/easley', }, { key: 'sharp::sharp/sharp', service: 'sharp', operation: 'sharp/sharp', }, { key: 'lalande::lalan/lalande', service: 'lalande', operation: 'lalan/lalande', }, { key: 'brave::brave/brave', service: 'brave', operation: 'brave/brave', }, { key: 'wright::wrigh/wright', service: 'wright', operation: 'wrigh/wright', }, { key: 'jones::jones/jones', service: 'jones', operation: 'jones/jones', }, { key: 'bose::bose/bose', service: 'bose', operation: 'bose/bose', }, { key: 'ecstatic::ecsta/ecstatic', service: 'ecstatic', operation: 'ecsta/ecstatic', }, { key: 'tereshkova::teres/tereshkova', service: 'tereshkova', operation: 'teres/tereshkova', }, { key: 'lichterman::licht/lichterman', service: 'lichterman', operation: 'licht/lichterman', }, { key: 'visvesvaraya::visve/visvesvaraya', service: 'visvesvaraya', operation: 'visve/visvesvaraya', }, { key: 'mclean::mclea/mclean', service: 'mclean', operation: 'mclea/mclean', }, { key: 'stupefied::stupe/stupefied', service: 'stupefied', operation: 'stupe/stupefied', }, { key: 'bhabha::bhabh/bhabha', service: 'bhabha', operation: 'bhabh/bhabha', }, { key: 'youthful::youth/youthful', service: 'youthful', operation: 'youth/youthful', }, { key: 'lumiere::lumie/lumiere', service: 'lumiere', operation: 'lumie/lumiere', }, { key: 'golick::golic/golick', service: 'golick', operation: 'golic/golick', }, { key: 'goldstine::golds/goldstine', service: 'goldstine', operation: 'golds/goldstine', }, { key: 'zhukovsky::zhuko/zhukovsky', service: 'zhukovsky', operation: 'zhuko/zhukovsky', }, { key: 'dubinsky::dubin/dubinsky', service: 'dubinsky', operation: 'dubin/dubinsky', }, { key: 'joliot::jolio/joliot', service: 'joliot', operation: 'jolio/joliot', }, { key: 'pensive::pensi/pensive', service: 'pensive', operation: 'pensi/pensive', }, { key: 'jolly::jolly/jolly', service: 'jolly', operation: 'jolly/jolly', }, { key: 'euclid::eucli/euclid', service: 'euclid', operation: 'eucli/euclid', }, { key: 'boring::borin/boring', service: 'boring', operation: 'borin/boring', }, { key: 'fermi::fermi/fermi', service: 'fermi', operation: 'fermi/fermi', }, ], }; export function getNodeLabel(vertex: TVertex<{ key: string }>) { const [svc, op] = vertex.key.split('::', 2); return ( <span className="DemoGraph--nodeLabel"> <strong>{svc}</strong> <br /> {op} </span> ); }
the_stack
import { int64AsNumber } from "@collabs/core"; import { ListPositionSourceMetadataMessage, ListPositionSourceSave, } from "../../../generated/proto_compiled"; export type ListPosition = [ sender: string, counter: number, valueIndex: number ]; /** * Manages "items" (contiguous blocks of values) for a ListPositionSource. * * Implementation advice: * - Okay to modify input items directly and return them so long as the * ListPositionSource's user doesn't * keep references outside that might be affected (including args before and * after a method call). * * @type I The "Item" type, which holds a range of values (e.g., string, array, * number indicating number of values). */ export interface ListItemManager<I> { /** * Return item's length. */ length(item: I): number; /** * Return a singleton item containing just the value at the given index in * item. */ get(item: I, index: number): I; /** * Return an item containing the contents of a followed by the contents * of b. */ merge(a: I, b: I): I; /** * Return an item containing the contents of a followed by b and then c. * Can assume b is a singleton. */ merge3(a: I, b: I, c: I): I; /** * Split item at index, returning items representing values: * - left: item[:index] * - right: item[index:] */ split(item: I, index: number): [left: I, right: I]; /** * Split item at index and also delete the value at index, * returning items representing values: * - left: item[:index] * - right: item[index + 1:] */ splitDelete(item: I, index: number): [left: I, right: I]; /** * Return item with its first value trimmed, i.e., item[1:]. */ trimFirst(item: I): I; /** * Return item with its last value trimmed, i.e., item[:length-1]. */ trimLast(item: I): I; } /** * Every non-root waypoint must have at least one value. */ class Waypoint<I> { constructor( /** * "" for the root. */ readonly sender: string, /** * Nonnegative, increases monotonically (so you can * store value arrays in an array.). */ readonly counter: number, /** * null only for the root. * * Mutable only for during loading (then is temporarily * null while we construct everything). */ public parentWaypoint: Waypoint<I> | null, /** * The valueIndex of our true parent (a value within * parentWaypoint). * * Unspecified for the root. */ readonly parentValueIndex: number ) {} /** * The number of present values at this waypoint or its * descendants. */ totalPresentValues = 0; /** * The children (both left + right) in LtR order. * * A child is one of: * - A child waypoint, i.e., a waypoint that is a true * child of one of this waypoint's values. * - An item of type I, containing a contiguous sequence of present values. * - A negative number, indicating a number of unpresent values * equal to its absolute value. * * Since every waypoint must have at least one value (including the root's * fake value), this has at least non-waypoint (item or negative number). */ children: (Waypoint<I> | I | number)[] = []; } function isWaypoint<I>(child: Waypoint<I> | I | number): child is Waypoint<I> { return typeof child === "object" && (<object>child).constructor === Waypoint; } function isItem<I>(child: I | number): child is I { return !(typeof child === "number" && child < 0); } function isDeletedValue<I>(child: Waypoint<I> | I | number) { return typeof child === "number" && child < 0; } /** * @return 1 for item, -1 for deleted values (negative number), 0 for waypoint. */ function signOf<I>(child: Waypoint<I> | I | number): 1 | -1 | 0 { if (isWaypoint(child)) return 0; else if (isDeletedValue(child)) return -1; else return 1; } /** * @type I The "Item" type, which holds a range of values (e.g., string, array, * number indicating number of values). For implementation reasons, * items may not be negative numbers or null. */ export class ListPositionSource<I> { /** * Map key is waypoint.sender, index in the array is waypoint.counter. */ private readonly waypointsByID = new Map<string, Waypoint<I>[]>(); /** * Root waypoint. */ private readonly rootWaypoint: Waypoint<I>; /** * Used for assigning unique counters to our Waypoints. * * >= 0. */ private nextCounter = 0; /** * [constructor description] * @param replicaID A unique ID for the local replica. * Must not be "". * @param initialItem An item consistent of the initial * values in the list, i.e., values that are present * at the list's creation before any operations are * performed, or undefined if there are no such values. * The initial values are assigned the positions * ["", 0, i] for i in [1, itemManager.length(initialItem)], * i.e., you should store them keyed by those positions. * (Note 1-indexed, not 0-indexed.) */ constructor( readonly replicaID: string, private readonly itemManager: ListItemManager<I>, initialItem?: I ) { if (replicaID === "") { throw new Error('replicaID must not be ""'); } this.rootWaypoint = new Waypoint("", 0, null, 0); this.waypointsByID.set("", [this.rootWaypoint]); // Fake leftmost value, marked as unpresent. this.rootWaypoint.children.push(-1); if ( initialItem !== undefined && this.itemManager.length(initialItem) !== 0 ) { // Initial values. this.rootWaypoint.children.push(initialItem); this.rootWaypoint.totalPresentValues = this.itemManager.length(initialItem); } } private valueChildLength(valueChild: number | I): number { return typeof valueChild === "number" && valueChild < 0 ? -valueChild : this.itemManager.length(<I>valueChild); } /** * Includes error checking. */ private getWaypoint(sender: string, counter: number): Waypoint<I> { const bySender = this.waypointsByID.get(sender); if (bySender === undefined) { throw new Error( "Unknown position, did you forget to receivePositions/receiveAndAddPositions? (reason: sender)" ); } if (counter < 0) { throw new Error("Invalid position: counter < 0"); } if (counter >= bySender.length) { throw new Error( "Unknown position, did you forget to receivePositions/receiveAndAddPositions? (reason: counter)" ); } return bySender[counter]; } // OPT: Go back to allowing negative valueIndex? See how well it helps // performance (e.g. by reducing waypoints and tree depth). // Should be fine now that we are storing values for the user // (and they can use a map or two arrays to DIY). // OPT: opt getting valueIndex in case where startPos comes from get(). /** * [createPositions description] * @param prevPos position to the left of where you want to insert, or * null for the beginning of the list. * @return [description] */ createPositions( prevPos: ListPosition | null ): [counter: number, startValueIndex: number, metadata: Uint8Array | null] { // Find the position to the left of our insertion point // ("leftNeighbor") - prevPos if non-null, else the fake leftmost value. // Present unless it's the fake leftmost value. // Specifically, we represent leftNeighbor as the value // at leftOffset within the number // leftWaypoint.children[leftChildIndex] const leftWaypoint = prevPos === null ? this.rootWaypoint : this.getWaypoint(prevPos[0], prevPos[1]); let leftChildIndex: number; let leftOffset: number; let leftValueIndex: number; if (prevPos === null) { leftChildIndex = 0; leftOffset = 0; leftValueIndex = 0; } else { if (prevPos[2] < 0) { throw new Error("Invalid prevPos: valueIndex is < 0"); } leftOffset = prevPos[2]; for ( leftChildIndex = 0; leftChildIndex < leftWaypoint.children.length; leftChildIndex++ ) { const child = leftWaypoint.children[leftChildIndex]; if (isDeletedValue(child)) { const count = -child; if (leftOffset < count) break; leftOffset -= count; } else if (!isWaypoint(child)) { // Item case. const count = this.itemManager.length(<I>child); if (leftOffset < count) break; leftOffset -= count; } } if (leftChildIndex === leftWaypoint.children.length) { throw new Error("Invalid prevPos: valueIndex is not known"); } leftValueIndex = prevPos[2]; } const leftChild = <number | I>leftWaypoint.children[leftChildIndex]; const leftChildCount = this.valueChildLength(leftChild); // The created position will be a new true right child // of left neighbor, unless left neighbor already has a // right child. In that case, we will instead be a new // true left child of rightNeighbor, which we define to // be the next (possibly unpresent) value to the right of // left neighbor. // // (Since we count unpresent values in the definition of rightNeighbor, it is impossible for left neighbor // to have a right child and rightNeighbor to have // a left child: they would end up being desendants // of each other. Thus our created position always has // no existing same-side true siblings.) // See if leftWaypoint has no values after leftNeighbor. let isLastValue = true; if (leftOffset !== leftChildCount - 1) { isLastValue = false; } else { for (let i = leftWaypoint.children.length - 1; i > leftChildIndex; i--) { if (!isWaypoint(leftWaypoint.children[i])) { isLastValue = false; break; } } } if (isLastValue) { // leftWaypoint has no values after leftNeighbor. // However, it is possible that the next leftWaypoint // child is a true right child of leftNeighbor. if (leftChildIndex + 1 < leftWaypoint.children.length) { const nextChild = <Waypoint<I>>( leftWaypoint.children[leftChildIndex + 1] ); if (nextChild.parentValueIndex === leftValueIndex) { // Become the new leftmost descendant of nextChild. return this.createLeftmostDescendant(nextChild); } } // If we get here, then leftNeighbor has no true right // children; become its right child. if (leftWaypoint.sender === this.replicaID) { // Reuse leftWaypoint. return [leftWaypoint.counter, leftValueIndex + 1, null]; } else { return this.createNewWaypoint(leftWaypoint, leftValueIndex, "right"); } } // If we get here, then leftNeighbor already has a right // child; find rightNeighbor and become its new // leftmost descendant. if (leftOffset === leftChildCount - 1) { // rightNeighbor comes from the next child. const nextChild = leftWaypoint.children[leftChildIndex + 1]; if (isWaypoint(nextChild)) { // Become the new leftmost descendant of nextChild. return this.createLeftmostDescendant(nextChild); } } // If we get here, then rightNeighbor is the next of // leftWaypoint's values. return this.createNewWaypoint(leftWaypoint, leftValueIndex + 1, "left"); } private createLeftmostDescendant( waypoint: Waypoint<I> ): [counter: number, startValueIndex: number, metadata: Uint8Array | null] { let curWaypoint = waypoint; for (;;) { const firstChild = curWaypoint.children[0]; if (isWaypoint(firstChild)) { // firstChild is a waypoint; "recurse". curWaypoint = firstChild; } else { // The leftmost child of curWaypoint is a value. // That is necessarily the leftmost descendant of // waypoint. // Note because we are a left child, there is no // chance to reuse curWaypoint, even if we sent it. return this.createNewWaypoint(curWaypoint, 0, "left"); } } } private createNewWaypoint( parentWaypoint: Waypoint<I>, parentValueIndex: number, childSide: "left" | "right" ): [counter: number, startValueIndex: number, metadata: Uint8Array | null] { const message = ListPositionSourceMetadataMessage.create({ parentWaypointSender: parentWaypoint.sender === this.replicaID ? undefined : parentWaypoint.sender, parentWaypointCounterAndSide: childSide === "right" ? parentWaypoint.counter : ~parentWaypoint.counter, parentValueIndex, }); const metadata = ListPositionSourceMetadataMessage.encode(message).finish(); return [this.nextCounter, 0, metadata]; } // OPT: in receivePositions and add/delete, optimize the (common) case where // the user calls find right afterward? Can try to avoid looping over // waypoint children twice. (Perhaps that is what makes our sendTime // twice as slow as receiveTime, unlike in Yjs.) receivePositions( startPos: ListPosition, count: number, metadata: Uint8Array | null ): void { this.receivePositionsInternal(startPos, count, metadata, -1); } receiveAndAddPositions( startPos: ListPosition, item: I, metadata: Uint8Array | null ): void { this.receivePositionsInternal( startPos, this.itemManager.length(item), metadata, 1, item ); } /** * [receivePositionsInternal description] * @param startPos [description] * @param count [description] * @param metadata [description] * @param sign [description] * @param item Only present for additions (sign = 1). */ private receivePositionsInternal( startPos: ListPosition, count: number, metadata: Uint8Array | null, sign: 1 | -1, item?: I ): void { // TODO: wait to change anything until after all checks have passed (so error = no effect) if (startPos[0] === "") { throw new Error('Invalid startPos: sender is ""'); } if (startPos[2] < 0) { throw new Error("Invalid startPos: valueIndex is < 0"); } if (metadata === null) { // The new positions are just new values appended to the last value // child in startPos's waypoint (which necessarily already exists). const waypoint = this.getWaypoint(startPos[0], startPos[1]); for ( let childIndex = waypoint.children.length - 1; childIndex >= 0; childIndex-- ) { const child = waypoint.children[childIndex]; if (!isWaypoint(child)) { // Found the last value child. if (sign === 1) { if (isItem(child)) { // Merge. waypoint.children[childIndex] = this.itemManager.merge( child, item! ); } else { // Insert new item. waypoint.children.splice(childIndex + 1, 0, item!); } } else { if (isItem(child)) { // Insert new deleted values. waypoint.children.splice(childIndex + 1, 0, -count); } else { // Merge. waypoint.children[childIndex] = child - count; } } break; } } if (sign === 1) this.updateTotalPresentValues(waypoint, count); } else { const decoded = ListPositionSourceMetadataMessage.decode(metadata); // Get parentWaypoint. const parentWaypointSender = Object.prototype.hasOwnProperty.call( decoded, "parentWaypointSender" ) ? decoded.parentWaypointSender : startPos[0]; const parentWaypointCounterAndSide = int64AsNumber( decoded.parentWaypointCounterAndSide ); let parentWaypointCounter: number; let side: "left" | "right"; if (parentWaypointCounterAndSide >= 0) { parentWaypointCounter = parentWaypointCounterAndSide; side = "right"; } else { parentWaypointCounter = ~parentWaypointCounterAndSide; side = "left"; } const parentWaypoint = this.getWaypoint( parentWaypointSender, parentWaypointCounter ); // Create a new waypoint based on startPos. if (startPos[1] < 0) { throw new Error("Invalid startPos: counter is < 0"); } const newWaypoint = new Waypoint( startPos[0], startPos[1], parentWaypoint, decoded.parentValueIndex ); newWaypoint.children.push(sign === 1 ? item! : -count); if (startPos[0] === this.replicaID) this.nextCounter++; // Store newWaypoint in this.waypoints. if (newWaypoint.sender === "") { throw new Error( 'Invalid call to receivePositions: startPos\'s sender is "", which is a reserved replicaID' ); } if (newWaypoint.counter === 0) { // New sender. if (this.waypointsByID.has(newWaypoint.sender)) { throw new Error( `Invalid call to receivePositions: counter is not the next counter from sender (counter = ${ newWaypoint.counter }, should be ${this.waypointsByID.get(newWaypoint.sender)!.length})` ); } this.waypointsByID.set(newWaypoint.sender, [newWaypoint]); } else { const bySender = this.waypointsByID.get(newWaypoint.sender); if (bySender === undefined || newWaypoint.counter !== bySender.length) { throw new Error( `Invalid call to receivePositions: counter is not the next counter from sender (counter = ${ newWaypoint.counter }, should be ${bySender === undefined ? 0 : bySender.length})` ); } bySender.push(newWaypoint); } // Store newWaypoint in parentWaypoint.children. if (side === "right") { if (newWaypoint.sender === parentWaypoint.sender) { throw new Error( "Invalid call to receivePositions: startPos does not correspond to metadata (right side same senders)" ); } // Regardless of newWaypoint.parentValueIndex, it // goes to the right of all values: any values that // are not causally to its left are sibling insertions // by parentWaypoint.sender, which we arbitrarily // sort on the left. // Remains to sort newWaypoint // among any waypoint children at the end, in order: // reverse parentValueIndex, then sender. let childIndex: number; for ( childIndex = parentWaypoint.children.length - 1; childIndex >= 0; childIndex-- ) { const child = parentWaypoint.children[childIndex]; if ( !isWaypoint(child) || child.parentValueIndex > newWaypoint.parentValueIndex || (child.parentValueIndex === newWaypoint.parentValueIndex && child.sender < newWaypoint.sender) ) { // child is lesser; insert after. break; } } parentWaypoint.children.splice(childIndex + 1, 0, newWaypoint); } else { // side === "left" if (newWaypoint.parentValueIndex === 0) { // newWaypoint goes before all values. // Remains to sort newWaypoint among any // waypoint siblings, in order by sender. this.insertLeftChild(parentWaypoint, newWaypoint, 0); } else { // First find valueIndex - 1 (which is to our left) // within children. // remaining counts the number of values to pass over. let remaining = newWaypoint.parentValueIndex; let childIndex: number; let childCount!: number; for ( childIndex = 0; childIndex < parentWaypoint.children.length; childIndex++ ) { const child = parentWaypoint.children[childIndex]; if (!isWaypoint(child)) { childCount = this.valueChildLength(child); if (remaining <= childCount) break; else remaining -= childCount; } } if (childIndex === parentWaypoint.children.length) { throw new Error( "Invalid call to receivePositions: the parent valueIndex is not known" ); } if (remaining < childCount) { // Need to split child. const child = <number | I>parentWaypoint.children[childIndex]; if (isItem(child)) { const [left, right] = this.itemManager.split(child, remaining); parentWaypoint.children.splice( childIndex, 1, left, newWaypoint, right ); } else { parentWaypoint.children.splice( childIndex, 1, -remaining, newWaypoint, -(childCount - remaining) ); } } else { // newWaypoint goes after child. // Remains to sort newWaypoint among any // waypoint siblings, in order by sender. this.insertLeftChild(parentWaypoint, newWaypoint, childIndex + 1); } } } if (sign === 1) this.updateTotalPresentValues(newWaypoint, count); } } /** * Inserts newWaypoint into parentWaypoint as a left * child of some value, sorting it among its siblings. * searchStart is the first place to search (LtR), i.e., * the childIndex after (true parent value - 1). * This method sorts newWaypoint among any siblings * that appear from searchStart until the next value * (or the end), in order by sender. */ private insertLeftChild( parentWaypoint: Waypoint<I>, newWaypoint: Waypoint<I>, searchStart: number ) { for ( let nextChildIndex = searchStart; nextChildIndex < parentWaypoint.children.length; nextChildIndex++ ) { const nextChild = parentWaypoint.children[nextChildIndex]; // Note nextChild could be a true right child // of newWaypoint.parentValueIndex - 1; we // are greater than those. if ( !isWaypoint(nextChild) || (nextChild.parentValueIndex === newWaypoint.parentValueIndex && nextChild.sender > newWaypoint.sender) ) { // nextChild is greater; insert before. parentWaypoint.children.splice(nextChildIndex, 0, newWaypoint); return; } } // Impossible to get here since children must include a value. throw new Error("Internal error: insertLeftChild found no value"); } /** * [add description] * * Note: does nothing if pos is already present (doesn't replace the * existing value). * * @param pos [description] * @param singletonItem An item containing just the added value. * @return Whether pos was actually added, i.e., it * was previously not present. * @throws If singletonItem's length is not 1. */ add(pos: ListPosition, singletonItem: I): boolean { if (this.itemManager.length(singletonItem) !== 1) { throw new Error("add only supports singleton items (length 1)"); } return this.addOrDelete(pos, 1, singletonItem) !== null; } // OPT: how to do optimized delete range? // (Finding first and last indices, then looping over // them and deleting some but not all.) /** * [delete description] * @param pos [description] * @return A singleton item containing the deleted value, or null * if nothing happened (pos was already not present). */ delete(pos: ListPosition): I | null { return this.addOrDelete(pos, -1); } /** * [addOrDelete description] * @param pos [description] * @param sign [description] * @param item [description] * @return A singleton item containing the added/deleted value, or undefined * if nothing changed (pos's presence already matched sign). */ private addOrDelete(pos: ListPosition, sign: 1 | -1, item?: I): I | null { // Find waypoint. const bySender = this.waypointsByID.get(pos[0]); if (bySender === undefined) { throw new Error( "Unknown position, did you forget to receivePositions/receiveAndAddPositions? (reason: sender)" ); } if (pos[1] < 0) { throw new Error("Invalid position: counter < 0"); } if (pos[1] >= bySender.length) { throw new Error( "Unknown position, did you forget to receivePositions/receiveAndAddPositions? (reason: counter)" ); } const waypoint = bySender[pos[1]]; // Find valueIndex in waypoint.children. if (pos[2] < 0) { throw new Error("Invalid position: valueIndex < 0"); } let remaining = pos[2]; let childIndex: number; let childCount!: number; for (childIndex = 0; childIndex < waypoint.children.length; childIndex++) { const child = waypoint.children[childIndex]; if (!isWaypoint(child)) { childCount = this.valueChildLength(child); if (remaining < childCount) break; remaining -= childCount; } } if (childIndex === waypoint.children.length) { throw new Error( "Unknown position, did you forget to receivePositions/receiveAndAddPositions? (reason: valueIndex)" ); } const child = <number | I>waypoint.children[childIndex]; // Add it if needed. const childSign = isItem(child) ? 1 : -1; if (childSign === sign) return null; const mergePrev = remaining === 0 && childIndex - 1 >= 0 && signOf(waypoint.children[childIndex - 1]) === sign; const mergeNext = remaining === childCount - 1 && childIndex + 1 < waypoint.children.length && signOf(waypoint.children[childIndex + 1]) === sign; const toReturn = sign === 1 ? item! : this.itemManager.get(<I>child, remaining); // TODO: test every case if (remaining === 0 && childCount === 1) { if (mergePrev && mergeNext) { const newChild = sign === 1 ? this.itemManager.merge3( <I>waypoint.children[childIndex - 1], item!, <I>waypoint.children[childIndex + 1] ) : <number>waypoint.children[childIndex - 1] + -1 + <number>waypoint.children[childIndex + 1]; waypoint.children.splice(childIndex - 1, 3, newChild); } else if (mergePrev) { const newChild = sign === 1 ? this.itemManager.merge( <I>waypoint.children[childIndex - 1], item! ) : <number>waypoint.children[childIndex - 1] - 1; waypoint.children.splice(childIndex - 1, 2, newChild); } else if (mergeNext) { const newChild = sign === 1 ? this.itemManager.merge( item!, <I>waypoint.children[childIndex + 1] ) : -1 + <number>waypoint.children[childIndex + 1]; waypoint.children.splice(childIndex, 2, newChild); } else { waypoint.children[childIndex] = sign === 1 ? item! : -1; } } else if (remaining === 0) { if (mergePrev) { if (sign === 1) { waypoint.children[childIndex - 1] = this.itemManager.merge( <I>waypoint.children[childIndex - 1], item! ); (<number>waypoint.children[childIndex]) += 1; // -(-1) } else { (<number>waypoint.children[childIndex - 1]) -= 1; // -(+1) waypoint.children[childIndex] = this.itemManager.trimFirst(<I>child); } } else { if (sign === 1) { // Subtract 1 length from child (a deleted value) by adding 1 = -(-1). waypoint.children.splice(childIndex, 1, item!, <number>child + 1); } else { waypoint.children.splice( childIndex, 1, -1, this.itemManager.trimFirst(<I>child) ); } } } else if (remaining === childCount - 1) { if (mergeNext) { if (sign === 1) { (<number>waypoint.children[childIndex]) += 1; // -(-1) waypoint.children[childIndex + 1] = this.itemManager.merge( item!, <I>waypoint.children[childIndex + 1] ); } else { waypoint.children[childIndex] = this.itemManager.trimLast(<I>child); (<number>waypoint.children[childIndex + 1]) -= 1; // -(+1) } } else { if (sign === 1) { // Subtract 1 length from child (a deleted value) by adding 1 = -(-1). waypoint.children.splice(childIndex, 1, <number>child + 1, item!); } else { waypoint.children.splice( childIndex, 1, this.itemManager.trimLast(<I>child), -1 ); } } } else { // Split child. if (sign === 1) { waypoint.children.splice( childIndex, 1, -remaining, item!, -(childCount - remaining - 1) ); } else { const [left, right] = this.itemManager.splitDelete(<I>child, remaining); waypoint.children.splice(childIndex, 1, left, -1, right); } } this.updateTotalPresentValues(waypoint, sign); return toReturn; } /** * Updates totalPresentValues on waypoint and its ancestors, adding delta. */ private updateTotalPresentValues( startWaypoint: Waypoint<I>, delta: number ): void { for ( let curWaypoint: Waypoint<I> | null = startWaypoint; curWaypoint !== null; curWaypoint = curWaypoint.parentWaypoint ) { curWaypoint.totalPresentValues += delta; } } has(pos: ListPosition): boolean { const waypoint = this.getWaypoint(pos[0], pos[1]); // Find valueIndex in waypoint.children. if (pos[2] < 0) { throw new Error("Invalid position: valueIndex < 0"); } let remaining = pos[2]; let childIndex: number; for (childIndex = 0; childIndex < waypoint.children.length; childIndex++) { const child = waypoint.children[childIndex]; if (!isWaypoint(child)) { const count = this.valueChildLength(child); if (remaining < count) { // pos is within child. return child > 0; } remaining -= count; } } throw new Error( "Unknown position, did you forget to receivePositions/receiveAndAddPositions? (reason: valueIndex)" ); } getPosition(index: number): ListPosition { if (index < 0 || index >= this.length) { throw new Error(`index out of bounds: ${index} (length: ${this.length})`); } const [waypoint, childIndex, , offset] = this.getInternal(index); const valueIndex = this.getValueIndex(waypoint, childIndex, offset); return [waypoint.sender, waypoint.counter, valueIndex]; } getItem(index: number): [item: I, offset: number] { const [, , child, offset] = this.getInternal(index); return [child, offset]; } // OPT: optimize forward/backwards loop access /** * index must be valid; else may infinite loop. * * The indicated child will always be a positive number, since * we only consider present values. */ private getInternal( index: number ): [waypoint: Waypoint<I>, childIndex: number, child: I, offset: number] { // Tree walk. let remaining = index; let curWaypoint = this.rootWaypoint; for (;;) { // Walk the children of curWaypoint. child_loop: { for ( let childIndex = 0; childIndex < curWaypoint.children.length; childIndex++ ) { const child = curWaypoint.children[childIndex]; if (isWaypoint(child)) { if (remaining < child.totalPresentValues) { // child contains the value, "recurse" by // going to the next outer loop iteration. curWaypoint = child; break child_loop; } remaining -= child.totalPresentValues; } else if (isItem(child)) { const count = this.itemManager.length(child); if (remaining < count) { // Found the value; return. return [curWaypoint, childIndex, child, remaining]; } remaining -= count; } // else unpresent values; skip over. } // End of for loop, but didn't find index among children. throw new Error("Internal error: failed to find valid index"); } } } private getValueIndex( waypoint: Waypoint<I>, childIndex: number, offset: number ) { let subtotal = 0; for (let i = 0; i < childIndex; i++) { const child = waypoint.children[i]; if (!isWaypoint(child)) subtotal += this.valueChildLength(child); } return subtotal + offset; } get length(): number { return this.rootWaypoint.totalPresentValues; } findPosition(pos: ListPosition): [geIndex: number, isPresent: boolean] { const waypoint = this.getWaypoint(pos[0], pos[1]); // geIndex within waypoint's subtree. let [geIndex, isPresent] = this.findWithinSubtree(waypoint, pos[2]); // Now account for present values to the left of // waypoint's subtree. let curWaypoint = waypoint; let curParent = curWaypoint.parentWaypoint; while (curParent !== null) { // Loop through curParent's children until we find // curWaypoint, adding up their indices. for (const child of curParent.children) { if (isWaypoint(child)) { if (child === curWaypoint) { // Done looping over children. break; } else { geIndex += child.totalPresentValues; } } else if (isItem(child)) { geIndex += this.itemManager.length(child); } } // Now find where curParent is within its own parent. curWaypoint = curParent; curParent = curWaypoint.parentWaypoint; } return [geIndex, isPresent]; } /** * @return [the geIndex of the given valueIndex within * waypoint's subtree, whether it is present] */ private findWithinSubtree( waypoint: Waypoint<I>, valueIndex: number ): [geIndex: number, isPresent: boolean] { if (valueIndex < 0) { throw new Error("Invalid position: valueIndex < 0"); } let geIndex = 0; let remaining = valueIndex; for (const child of waypoint.children) { if (isWaypoint(child)) { geIndex += child.totalPresentValues; } else if (isItem(child)) { const count = this.itemManager.length(child); if (remaining < count) { // Found valueIndex. return [geIndex + remaining, true]; } else { remaining -= count; geIndex += count; } } else { const count = -child; if (remaining < count) { // Found valueIndex. return [geIndex, false]; } else { remaining -= count; } } } // If we get to here, we didn't find valueIndex. throw new Error( "Unknown position, did you forget to receivePositions/receiveAndAddPositions? (reason: valueIndex)" ); } /** * Mutating the ListPositionSource while iterating is unsafe. */ *positions(): IterableIterator<ListPosition> { for (const [ waypoint, , startValueIndex, count, ] of this.itemPositionsInternal()) { for (let i = 0; i < count; i++) { yield [waypoint.sender, waypoint.counter, startValueIndex + i]; } } } /** * Mutating the ListPositionSource while iterating is unsafe. */ *items(): IterableIterator<I> { for (const [, , , , item] of this.itemPositionsInternal()) { yield item; } } *itemPositions(): IterableIterator< [startPos: ListPosition, length: number, item: I] > { for (const [ waypoint, , startValueIndex, count, item, ] of this.itemPositionsInternal()) { yield [[waypoint.sender, waypoint.counter, startValueIndex], count, item]; } } /** * Mutating the ListPositionSource while iterating is unsafe, except for * directly replacing waypoint children (i.e., setting an index). * * @param inLoad Set to true during load(), when the items are actually * replaced with their lengths (as positive numbers). */ private *itemPositionsInternal( inLoad = false ): IterableIterator< [ waypoint: Waypoint<I>, childIndex: number, startValueIndex: number, count: number, item: I ] > { // Walk the tree. const stack: [ waypoint: Waypoint<I>, childIndex: number, valueIndex: number ][] = []; let waypoint = this.rootWaypoint; let childIndex = 0; let valueIndex = 0; for (;;) { if (childIndex === waypoint.children.length) { // Done with this waypoint; pop the stack. if (stack.length === 0) { // Completely done. return; } [waypoint, childIndex, valueIndex] = stack.pop()!; childIndex++; continue; } const child = waypoint.children[childIndex]; if (isWaypoint(child)) { // Recurse if nonempty, else skip. if (child.totalPresentValues > 0) { stack.push([waypoint, childIndex, valueIndex]); waypoint = child; childIndex = 0; valueIndex = 0; continue; } } else if (isItem(child)) { // Yield child. const count = inLoad ? <number>(<unknown>child) : this.itemManager.length(child); yield [waypoint, childIndex, valueIndex, count, child]; valueIndex += count; } else { // Deleted values; skip. valueIndex += -child; } // Move to the next child. childIndex++; } } // // For debugging. // printTreeWalk() { // let numNodes = 1; // let maxDepth = 1; // // Walk the tree. // console.log("Tree walk by " + this.replicaID); // const stack: [waypoint: Waypoint<I>, childIndex: number][] = []; // let waypoint = this.rootWaypoint; // let childIndex = 0; // console.log(`Root (${waypoint.totalPresentValues}):`); // process.stdout.write(" "); // for (;;) { // if (childIndex === waypoint.children.length) { // // Done with this waypoint; pop the stack. // console.log(""); // if (stack.length === 0) { // // Completely done. // console.log(`Nodes: ${numNodes}`); // console.log(`Depth: ${maxDepth}`); // return; // } // [waypoint, childIndex] = stack.pop()!; // childIndex++; // for (let i = 0; i < stack.length + 1; i++) { // process.stdout.write(" "); // } // continue; // } // // const child = waypoint.children[childIndex]; // if (isWaypoint(child)) { // // Waypoint child. Recurse. // process.stdout.write("\n"); // for (let i = 0; i < stack.length + 1; i++) { // process.stdout.write(" "); // } // stack.push([waypoint, childIndex]); // waypoint = child; // childIndex = 0; // process.stdout.write( // `[${waypoint.sender}, ${waypoint.counter}] (${waypoint.totalPresentValues}):\n` // ); // for (let i = 0; i < stack.length + 1; i++) { // process.stdout.write(" "); // } // numNodes++; // maxDepth = Math.max(maxDepth, stack.length + 1); // continue; // } else if (isItem(child)) { // process.stdout.write(`${this.itemManager.length(child)}, `); // } else { // process.stdout.write(`${child}, `); // } // // // Move to the next child. // childIndex++; // } // } /** * Useful during loading. * * @return The number of valid counters for sender, equivalently, * 1 plus sender's max counter so far. */ countersFor(sender: string): number { return this.waypointsByID.get(sender)?.length ?? 0; } /** * This only saves the positions; you must save values separately. * It's easiest to do that by extracting the (non-CRDT) array of values * and saving that directly; you'll need that for load anyway. */ save(): Uint8Array { const replicaIDs: string[] = []; const replicaCounts: number[] = []; // Maps replicaIDs to the first index corresponding // to that replicaID in parentWaypoints. const startIndices = new Map<string, number>(); let index = 0; for (const [replicaID, waypoints] of this.waypointsByID) { if (replicaID === "") continue; replicaIDs.push(replicaID); replicaCounts.push(waypoints.length); startIndices.set(replicaID, index); index += waypoints.length; } const parentWaypoints: number[] = []; const parentValueIndices: number[] = []; const totalPresentValuess: number[] = []; const children: number[] = []; const childTypes: number[] = []; for (const waypoints of this.waypointsByID.values()) { for (const waypoint of waypoints) { if (waypoint !== this.rootWaypoint) { const parentWaypoint = waypoint.parentWaypoint!; if (parentWaypoint === this.rootWaypoint) { parentWaypoints.push(0); } else { parentWaypoints.push( 1 + startIndices.get(parentWaypoint.sender)! + parentWaypoint.counter ); } parentValueIndices.push(waypoint.parentValueIndex); } // We are guaranteed rootWaypoint is first since // it is in the first entry in waypointsByID. totalPresentValuess.push(waypoint.totalPresentValues); for ( let childIndex = 0; childIndex < waypoint.children.length; childIndex++ ) { const startTag = childIndex === waypoint.children.length - 1 ? 4 : 0; const child = waypoint.children[childIndex]; if (isWaypoint(child)) { children.push(startIndices.get(child.sender)! + child.counter); childTypes.push(2 + startTag); } else if (isItem(child)) { children.push(this.itemManager.length(child)); childTypes.push(0 + startTag); } else { children.push(-child); childTypes.push(1 + startTag); } } } } const message = ListPositionSourceSave.create({ oldReplicaID: this.replicaID, oldNextCounter: this.nextCounter, replicaIDs, replicaCounts, parentWaypoints, parentValueIndices, totalPresentValuess, children, childTypes, }); return ListPositionSourceSave.encode(message).finish(); } /** * [load description] * @param saveData [description] * @param nextItem A function that returns an item containing the * `count` next values when called repeatedly. * This must only be null if you are using NumberItemManager * (when it's null, we skip a step that is redundant for NumberItemManager). */ load( saveData: Uint8Array, nextItem: ((count: number, startPos: ListPosition) => I) | null ): void { const decoded = ListPositionSourceSave.decode(saveData); if (decoded.oldReplicaID === this.replicaID) { this.nextCounter = decoded.oldNextCounter; } // All waypoints, in order [root, then same order // as parentWaypoints]. // I.e., indices = values in parentWaypoints. const allWaypoints: Waypoint<I>[] = [this.rootWaypoint]; // Fill in this.waypointsByID and allWaypoints. let i = 0; // Index into parentWaypoints. for ( let replicaIDIndex = 0; replicaIDIndex < decoded.replicaIDs.length; replicaIDIndex++ ) { const replicaID = decoded.replicaIDs[replicaIDIndex]; const bySender: Waypoint<I>[] = []; this.waypointsByID.set(replicaID, bySender); for ( let counter = 0; counter < decoded.replicaCounts[replicaIDIndex]; counter++ ) { const waypoint = new Waypoint<I>( replicaID, counter, null, // parentWaypoint is set later. decoded.parentValueIndices[i] ); bySender.push(waypoint); allWaypoints.push(waypoint); i++; } } // Set waypoint parentWaypoints. Note we skip rootWaypoint. for (let j = 1; j < allWaypoints.length; j++) { allWaypoints[j].parentWaypoint = allWaypoints[decoded.parentWaypoints[j - 1]]; } // Set waypoint children. // At first, we leave out items, instead putting their length in their // place (as if this.itemManager was NumberItemManager). We fill in items // in the next loop below. // For root, we have to remove its initial children first. this.rootWaypoint.children.splice(0); let childrenIndex = 0; for (let j = 0; j < allWaypoints.length; j++) { const waypoint = allWaypoints[j]; waypoint.totalPresentValues = int64AsNumber( decoded.totalPresentValuess[j] ); for (;;) { const child = decoded.children[childrenIndex]; const childType = decoded.childTypes[childrenIndex]; childrenIndex++; switch (childType & 3) { case 0: // Positive number (length of the actual item). waypoint.children.push(child); break; case 1: // Negative number. waypoint.children.push(-child); break; case 2: // Waypoint. waypoint.children.push(allWaypoints[child + 1]); break; } if ((childType & 4) === 4) break; } } // Replace the item placeholders (their lengths) with the actual items, // by looping over both the values and positions in order. if (nextItem !== null) { for (const [ waypoint, childIndex, startValueIndex, count, ] of this.itemPositionsInternal(true)) { waypoint.children[childIndex] = nextItem(count, [ waypoint.sender, waypoint.counter, startValueIndex, ]); } } } }
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as moment from 'moment'; import * as models from '../models'; /** * @class * ProviderOperations * __NOTE__: An instance of this class is automatically created for an * instance of the ManagedLabsClient. */ export interface ProviderOperations { /** * Result of the request to list REST API operations * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProviderOperationResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProviderOperationResult>>; /** * Result of the request to list REST API operations * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProviderOperationResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProviderOperationResult} [result] - The deserialized result object if an error did not occur. * See {@link ProviderOperationResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProviderOperationResult>; list(callback: ServiceCallback<models.ProviderOperationResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProviderOperationResult>): void; /** * Result of the request to list REST API operations * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProviderOperationResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProviderOperationResult>>; /** * Result of the request to list REST API operations * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProviderOperationResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProviderOperationResult} [result] - The deserialized result object if an error did not occur. * See {@link ProviderOperationResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProviderOperationResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.ProviderOperationResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProviderOperationResult>): void; } /** * @class * GlobalUsers * __NOTE__: An instance of this class is automatically created for an * instance of the ManagedLabsClient. */ export interface GlobalUsers { /** * Gets the virtual machine details * * @param {string} userName The name of the user. * * @param {object} environmentOperationsPayload Represents payload for any * Environment operations like get, start, stop, connect * * @param {string} environmentOperationsPayload.environmentId The resourceId of * the environment * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=environment)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GetEnvironmentResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getEnvironmentWithHttpOperationResponse(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GetEnvironmentResponse>>; /** * Gets the virtual machine details * * @param {string} userName The name of the user. * * @param {object} environmentOperationsPayload Represents payload for any * Environment operations like get, start, stop, connect * * @param {string} environmentOperationsPayload.environmentId The resourceId of * the environment * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=environment)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GetEnvironmentResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GetEnvironmentResponse} [result] - The deserialized result object if an error did not occur. * See {@link GetEnvironmentResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.GetEnvironmentResponse>; getEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, callback: ServiceCallback<models.GetEnvironmentResponse>): void; getEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GetEnvironmentResponse>): void; /** * Get batch operation status * * @param {string} userName The name of the user. * * @param {object} operationBatchStatusPayload Payload to get the status of an * operation * * @param {array} operationBatchStatusPayload.urls The operation url of long * running operation * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationBatchStatusResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getOperationBatchStatusWithHttpOperationResponse(userName: string, operationBatchStatusPayload: models.OperationBatchStatusPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationBatchStatusResponse>>; /** * Get batch operation status * * @param {string} userName The name of the user. * * @param {object} operationBatchStatusPayload Payload to get the status of an * operation * * @param {array} operationBatchStatusPayload.urls The operation url of long * running operation * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationBatchStatusResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationBatchStatusResponse} [result] - The deserialized result object if an error did not occur. * See {@link OperationBatchStatusResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getOperationBatchStatus(userName: string, operationBatchStatusPayload: models.OperationBatchStatusPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationBatchStatusResponse>; getOperationBatchStatus(userName: string, operationBatchStatusPayload: models.OperationBatchStatusPayload, callback: ServiceCallback<models.OperationBatchStatusResponse>): void; getOperationBatchStatus(userName: string, operationBatchStatusPayload: models.OperationBatchStatusPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationBatchStatusResponse>): void; /** * Gets the status of long running operation * * @param {string} userName The name of the user. * * @param {object} operationStatusPayload Payload to get the status of an * operation * * @param {string} operationStatusPayload.operationUrl The operation url of * long running operation * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationStatusResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getOperationStatusWithHttpOperationResponse(userName: string, operationStatusPayload: models.OperationStatusPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationStatusResponse>>; /** * Gets the status of long running operation * * @param {string} userName The name of the user. * * @param {object} operationStatusPayload Payload to get the status of an * operation * * @param {string} operationStatusPayload.operationUrl The operation url of * long running operation * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationStatusResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationStatusResponse} [result] - The deserialized result object if an error did not occur. * See {@link OperationStatusResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getOperationStatus(userName: string, operationStatusPayload: models.OperationStatusPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationStatusResponse>; getOperationStatus(userName: string, operationStatusPayload: models.OperationStatusPayload, callback: ServiceCallback<models.OperationStatusResponse>): void; getOperationStatus(userName: string, operationStatusPayload: models.OperationStatusPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationStatusResponse>): void; /** * Get personal preferences for a user * * @param {string} userName The name of the user. * * @param {object} personalPreferencesOperationsPayload Represents payload for * any Environment operations like get, start, stop, connect * * @param {string} [personalPreferencesOperationsPayload.labAccountResourceId] * Resource Id of the lab account * * @param {string} [personalPreferencesOperationsPayload.addRemove] Enum * indicating if user is adding or removing a favorite lab. Possible values * include: 'Add', 'Remove' * * @param {string} [personalPreferencesOperationsPayload.labResourceId] * Resource Id of the lab to add/remove from the favorites list * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GetPersonalPreferencesResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getPersonalPreferencesWithHttpOperationResponse(userName: string, personalPreferencesOperationsPayload: models.PersonalPreferencesOperationsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GetPersonalPreferencesResponse>>; /** * Get personal preferences for a user * * @param {string} userName The name of the user. * * @param {object} personalPreferencesOperationsPayload Represents payload for * any Environment operations like get, start, stop, connect * * @param {string} [personalPreferencesOperationsPayload.labAccountResourceId] * Resource Id of the lab account * * @param {string} [personalPreferencesOperationsPayload.addRemove] Enum * indicating if user is adding or removing a favorite lab. Possible values * include: 'Add', 'Remove' * * @param {string} [personalPreferencesOperationsPayload.labResourceId] * Resource Id of the lab to add/remove from the favorites list * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GetPersonalPreferencesResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GetPersonalPreferencesResponse} [result] - The deserialized result object if an error did not occur. * See {@link GetPersonalPreferencesResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getPersonalPreferences(userName: string, personalPreferencesOperationsPayload: models.PersonalPreferencesOperationsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GetPersonalPreferencesResponse>; getPersonalPreferences(userName: string, personalPreferencesOperationsPayload: models.PersonalPreferencesOperationsPayload, callback: ServiceCallback<models.GetPersonalPreferencesResponse>): void; getPersonalPreferences(userName: string, personalPreferencesOperationsPayload: models.PersonalPreferencesOperationsPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GetPersonalPreferencesResponse>): void; /** * List Environments for the user * * @param {string} userName The name of the user. * * @param {object} listEnvironmentsPayload Represents the payload to list * environments owned by a user * * @param {string} [listEnvironmentsPayload.labId] The resource Id of the lab * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ListEnvironmentsResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listEnvironmentsWithHttpOperationResponse(userName: string, listEnvironmentsPayload: models.ListEnvironmentsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ListEnvironmentsResponse>>; /** * List Environments for the user * * @param {string} userName The name of the user. * * @param {object} listEnvironmentsPayload Represents the payload to list * environments owned by a user * * @param {string} [listEnvironmentsPayload.labId] The resource Id of the lab * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ListEnvironmentsResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ListEnvironmentsResponse} [result] - The deserialized result object if an error did not occur. * See {@link ListEnvironmentsResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listEnvironments(userName: string, listEnvironmentsPayload: models.ListEnvironmentsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ListEnvironmentsResponse>; listEnvironments(userName: string, listEnvironmentsPayload: models.ListEnvironmentsPayload, callback: ServiceCallback<models.ListEnvironmentsResponse>): void; listEnvironments(userName: string, listEnvironmentsPayload: models.ListEnvironmentsPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ListEnvironmentsResponse>): void; /** * List labs for the user. * * @param {string} userName The name of the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ListLabsResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listLabsWithHttpOperationResponse(userName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ListLabsResponse>>; /** * List labs for the user. * * @param {string} userName The name of the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ListLabsResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ListLabsResponse} [result] - The deserialized result object if an error did not occur. * See {@link ListLabsResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listLabs(userName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ListLabsResponse>; listLabs(userName: string, callback: ServiceCallback<models.ListLabsResponse>): void; listLabs(userName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ListLabsResponse>): void; /** * Register a user to a managed lab * * @param {string} userName The name of the user. * * @param {object} registerPayload Represents payload for Register action. * * @param {string} [registerPayload.registrationCode] The registration code of * the lab. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ registerWithHttpOperationResponse(userName: string, registerPayload: models.RegisterPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Register a user to a managed lab * * @param {string} userName The name of the user. * * @param {object} registerPayload Represents payload for Register action. * * @param {string} [registerPayload.registrationCode] The registration code of * the lab. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ register(userName: string, registerPayload: models.RegisterPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; register(userName: string, registerPayload: models.RegisterPayload, callback: ServiceCallback<void>): void; register(userName: string, registerPayload: models.RegisterPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Resets the user password on an environment This operation can take a while * to complete * * @param {string} userName The name of the user. * * @param {object} resetPasswordPayload Represents the payload for resetting * passwords. * * @param {string} resetPasswordPayload.environmentId The resourceId of the * environment * * @param {string} [resetPasswordPayload.username] The username for which the * password will be reset. * * @param {string} [resetPasswordPayload.password] The password to assign to * the user specified in * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ resetPasswordWithHttpOperationResponse(userName: string, resetPasswordPayload: models.ResetPasswordPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Resets the user password on an environment This operation can take a while * to complete * * @param {string} userName The name of the user. * * @param {object} resetPasswordPayload Represents the payload for resetting * passwords. * * @param {string} resetPasswordPayload.environmentId The resourceId of the * environment * * @param {string} [resetPasswordPayload.username] The username for which the * password will be reset. * * @param {string} [resetPasswordPayload.password] The password to assign to * the user specified in * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ resetPassword(userName: string, resetPasswordPayload: models.ResetPasswordPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; resetPassword(userName: string, resetPasswordPayload: models.ResetPasswordPayload, callback: ServiceCallback<void>): void; resetPassword(userName: string, resetPasswordPayload: models.ResetPasswordPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Starts an environment by starting all resources inside the environment. This * operation can take a while to complete * * @param {string} userName The name of the user. * * @param {object} environmentOperationsPayload Represents payload for any * Environment operations like get, start, stop, connect * * @param {string} environmentOperationsPayload.environmentId The resourceId of * the environment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ startEnvironmentWithHttpOperationResponse(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts an environment by starting all resources inside the environment. This * operation can take a while to complete * * @param {string} userName The name of the user. * * @param {object} environmentOperationsPayload Represents payload for any * Environment operations like get, start, stop, connect * * @param {string} environmentOperationsPayload.environmentId The resourceId of * the environment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ startEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; startEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, callback: ServiceCallback<void>): void; startEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Stops an environment by stopping all resources inside the environment This * operation can take a while to complete * * @param {string} userName The name of the user. * * @param {object} environmentOperationsPayload Represents payload for any * Environment operations like get, start, stop, connect * * @param {string} environmentOperationsPayload.environmentId The resourceId of * the environment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ stopEnvironmentWithHttpOperationResponse(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Stops an environment by stopping all resources inside the environment This * operation can take a while to complete * * @param {string} userName The name of the user. * * @param {object} environmentOperationsPayload Represents payload for any * Environment operations like get, start, stop, connect * * @param {string} environmentOperationsPayload.environmentId The resourceId of * the environment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ stopEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; stopEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, callback: ServiceCallback<void>): void; stopEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Resets the user password on an environment This operation can take a while * to complete * * @param {string} userName The name of the user. * * @param {object} resetPasswordPayload Represents the payload for resetting * passwords. * * @param {string} resetPasswordPayload.environmentId The resourceId of the * environment * * @param {string} [resetPasswordPayload.username] The username for which the * password will be reset. * * @param {string} [resetPasswordPayload.password] The password to assign to * the user specified in * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginResetPasswordWithHttpOperationResponse(userName: string, resetPasswordPayload: models.ResetPasswordPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Resets the user password on an environment This operation can take a while * to complete * * @param {string} userName The name of the user. * * @param {object} resetPasswordPayload Represents the payload for resetting * passwords. * * @param {string} resetPasswordPayload.environmentId The resourceId of the * environment * * @param {string} [resetPasswordPayload.username] The username for which the * password will be reset. * * @param {string} [resetPasswordPayload.password] The password to assign to * the user specified in * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginResetPassword(userName: string, resetPasswordPayload: models.ResetPasswordPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginResetPassword(userName: string, resetPasswordPayload: models.ResetPasswordPayload, callback: ServiceCallback<void>): void; beginResetPassword(userName: string, resetPasswordPayload: models.ResetPasswordPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Starts an environment by starting all resources inside the environment. This * operation can take a while to complete * * @param {string} userName The name of the user. * * @param {object} environmentOperationsPayload Represents payload for any * Environment operations like get, start, stop, connect * * @param {string} environmentOperationsPayload.environmentId The resourceId of * the environment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStartEnvironmentWithHttpOperationResponse(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts an environment by starting all resources inside the environment. This * operation can take a while to complete * * @param {string} userName The name of the user. * * @param {object} environmentOperationsPayload Represents payload for any * Environment operations like get, start, stop, connect * * @param {string} environmentOperationsPayload.environmentId The resourceId of * the environment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStartEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginStartEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, callback: ServiceCallback<void>): void; beginStartEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Stops an environment by stopping all resources inside the environment This * operation can take a while to complete * * @param {string} userName The name of the user. * * @param {object} environmentOperationsPayload Represents payload for any * Environment operations like get, start, stop, connect * * @param {string} environmentOperationsPayload.environmentId The resourceId of * the environment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStopEnvironmentWithHttpOperationResponse(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Stops an environment by stopping all resources inside the environment This * operation can take a while to complete * * @param {string} userName The name of the user. * * @param {object} environmentOperationsPayload Represents payload for any * Environment operations like get, start, stop, connect * * @param {string} environmentOperationsPayload.environmentId The resourceId of * the environment * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStopEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginStopEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, callback: ServiceCallback<void>): void; beginStopEnvironment(userName: string, environmentOperationsPayload: models.EnvironmentOperationsPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * LabAccounts * __NOTE__: An instance of this class is automatically created for an * instance of the ManagedLabsClient. */ export interface LabAccounts { /** * List lab accounts in a subscription. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=sizeConfiguration)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationLabAccount>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionWithHttpOperationResponse(options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationLabAccount>>; /** * List lab accounts in a subscription. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=sizeConfiguration)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationLabAccount} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationLabAccount} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationLabAccount} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscription(options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationLabAccount>; listBySubscription(callback: ServiceCallback<models.ResponseWithContinuationLabAccount>): void; listBySubscription(options: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationLabAccount>): void; /** * List lab accounts in a resource group. * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=sizeConfiguration)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationLabAccount>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationLabAccount>>; /** * List lab accounts in a resource group. * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=sizeConfiguration)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationLabAccount} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationLabAccount} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationLabAccount} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationLabAccount>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.ResponseWithContinuationLabAccount>): void; listByResourceGroup(resourceGroupName: string, options: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationLabAccount>): void; /** * Get lab account * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=sizeConfiguration)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LabAccount>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LabAccount>>; /** * Get lab account * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=sizeConfiguration)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LabAccount} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LabAccount} [result] - The deserialized result object if an error did not occur. * See {@link LabAccount} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, labAccountName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.LabAccount>; get(resourceGroupName: string, labAccountName: string, callback: ServiceCallback<models.LabAccount>): void; get(resourceGroupName: string, labAccountName: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LabAccount>): void; /** * Create or replace an existing Lab Account. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} labAccount Represents a lab account. * * @param {boolean} [labAccount.enabledRegionSelection] Represents if region * selection is enabled * * @param {string} [labAccount.provisioningState] The provisioning status of * the resource. * * @param {string} [labAccount.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [labAccount.location] The location of the resource. * * @param {object} [labAccount.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LabAccount>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labAccount: models.LabAccount, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LabAccount>>; /** * Create or replace an existing Lab Account. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} labAccount Represents a lab account. * * @param {boolean} [labAccount.enabledRegionSelection] Represents if region * selection is enabled * * @param {string} [labAccount.provisioningState] The provisioning status of * the resource. * * @param {string} [labAccount.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [labAccount.location] The location of the resource. * * @param {object} [labAccount.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LabAccount} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LabAccount} [result] - The deserialized result object if an error did not occur. * See {@link LabAccount} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, labAccountName: string, labAccount: models.LabAccount, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LabAccount>; createOrUpdate(resourceGroupName: string, labAccountName: string, labAccount: models.LabAccount, callback: ServiceCallback<models.LabAccount>): void; createOrUpdate(resourceGroupName: string, labAccountName: string, labAccount: models.LabAccount, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LabAccount>): void; /** * Delete lab account. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete lab account. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, labAccountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, labAccountName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, labAccountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Modify properties of lab accounts. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} labAccount Represents a lab account. * * @param {boolean} [labAccount.enabledRegionSelection] Represents if region * selection is enabled * * @param {string} [labAccount.provisioningState] The provisioning status of * the resource. * * @param {string} [labAccount.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [labAccount.location] The location of the resource. * * @param {object} [labAccount.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LabAccount>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labAccount: models.LabAccountFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LabAccount>>; /** * Modify properties of lab accounts. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} labAccount Represents a lab account. * * @param {boolean} [labAccount.enabledRegionSelection] Represents if region * selection is enabled * * @param {string} [labAccount.provisioningState] The provisioning status of * the resource. * * @param {string} [labAccount.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [labAccount.location] The location of the resource. * * @param {object} [labAccount.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LabAccount} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LabAccount} [result] - The deserialized result object if an error did not occur. * See {@link LabAccount} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, labAccountName: string, labAccount: models.LabAccountFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LabAccount>; update(resourceGroupName: string, labAccountName: string, labAccount: models.LabAccountFragment, callback: ServiceCallback<models.LabAccount>): void; update(resourceGroupName: string, labAccountName: string, labAccount: models.LabAccountFragment, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LabAccount>): void; /** * Create a lab in a lab account. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} createLabProperties Properties for creating a managed lab * and a default environment setting * * @param {object} [createLabProperties.environmentSettingCreationParameters] * Settings related to creating an environment setting * * @param {object} * createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters * The resource specific settings * * @param {string} * [createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.location] * The location where the virtual machine will live * * @param {string} * [createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.name] * The name of the resource setting * * @param {string} * createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.galleryImageResourceId * The resource id of the gallery image used for creating the virtual machine * * @param {string} * [createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.size] * The size of the virtual machine. Possible values include: 'Basic', * 'Standard', 'Performance' * * @param {object} * createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.referenceVmCreationParameters * Creation parameters for Reference Vm * * @param {string} * createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.referenceVmCreationParameters.userName * The username of the virtual machine * * @param {string} * createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.referenceVmCreationParameters.password * The password of the virtual machine. * * @param {object} createLabProperties.labCreationParameters Settings related * to creating a lab * * @param {number} [createLabProperties.labCreationParameters.maxUsersInLab] * Maximum number of users allowed in the lab. * * @param {string} createLabProperties.name The name of the resource * * @param {string} [createLabProperties.location] The location of the resource * * @param {object} [createLabProperties.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createLabWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, createLabProperties: models.CreateLabProperties, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Create a lab in a lab account. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} createLabProperties Properties for creating a managed lab * and a default environment setting * * @param {object} [createLabProperties.environmentSettingCreationParameters] * Settings related to creating an environment setting * * @param {object} * createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters * The resource specific settings * * @param {string} * [createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.location] * The location where the virtual machine will live * * @param {string} * [createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.name] * The name of the resource setting * * @param {string} * createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.galleryImageResourceId * The resource id of the gallery image used for creating the virtual machine * * @param {string} * [createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.size] * The size of the virtual machine. Possible values include: 'Basic', * 'Standard', 'Performance' * * @param {object} * createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.referenceVmCreationParameters * Creation parameters for Reference Vm * * @param {string} * createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.referenceVmCreationParameters.userName * The username of the virtual machine * * @param {string} * createLabProperties.environmentSettingCreationParameters.resourceSettingCreationParameters.referenceVmCreationParameters.password * The password of the virtual machine. * * @param {object} createLabProperties.labCreationParameters Settings related * to creating a lab * * @param {number} [createLabProperties.labCreationParameters.maxUsersInLab] * Maximum number of users allowed in the lab. * * @param {string} createLabProperties.name The name of the resource * * @param {string} [createLabProperties.location] The location of the resource * * @param {object} [createLabProperties.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createLab(resourceGroupName: string, labAccountName: string, createLabProperties: models.CreateLabProperties, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; createLab(resourceGroupName: string, labAccountName: string, createLabProperties: models.CreateLabProperties, callback: ServiceCallback<void>): void; createLab(resourceGroupName: string, labAccountName: string, createLabProperties: models.CreateLabProperties, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Get regional availability information for each size category configured * under a lab account * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GetRegionalAvailabilityResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getRegionalAvailabilityWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GetRegionalAvailabilityResponse>>; /** * Get regional availability information for each size category configured * under a lab account * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GetRegionalAvailabilityResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GetRegionalAvailabilityResponse} [result] - The deserialized result object if an error did not occur. * See {@link GetRegionalAvailabilityResponse} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getRegionalAvailability(resourceGroupName: string, labAccountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GetRegionalAvailabilityResponse>; getRegionalAvailability(resourceGroupName: string, labAccountName: string, callback: ServiceCallback<models.GetRegionalAvailabilityResponse>): void; getRegionalAvailability(resourceGroupName: string, labAccountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GetRegionalAvailabilityResponse>): void; /** * Delete lab account. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete lab account. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName: string, labAccountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(resourceGroupName: string, labAccountName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(resourceGroupName: string, labAccountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * List lab accounts in a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationLabAccount>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationLabAccount>>; /** * List lab accounts in a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationLabAccount} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationLabAccount} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationLabAccount} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscriptionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationLabAccount>; listBySubscriptionNext(nextPageLink: string, callback: ServiceCallback<models.ResponseWithContinuationLabAccount>): void; listBySubscriptionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationLabAccount>): void; /** * List lab accounts in a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationLabAccount>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationLabAccount>>; /** * List lab accounts in a resource group. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationLabAccount} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationLabAccount} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationLabAccount} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationLabAccount>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.ResponseWithContinuationLabAccount>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationLabAccount>): void; } /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the ManagedLabsClient. */ export interface Operations { /** * Get operation * * @param {string} locationName The name of the location. * * @param {string} operationName The name of the operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(locationName: string, operationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationResult>>; /** * Get operation * * @param {string} locationName The name of the location. * * @param {string} operationName The name of the operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(locationName: string, operationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationResult>; get(locationName: string, operationName: string, callback: ServiceCallback<models.OperationResult>): void; get(locationName: string, operationName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationResult>): void; } /** * @class * GalleryImages * __NOTE__: An instance of this class is automatically created for an * instance of the ManagedLabsClient. */ export interface GalleryImages { /** * List gallery images in a given lab account. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=author)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationGalleryImage>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationGalleryImage>>; /** * List gallery images in a given lab account. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=author)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationGalleryImage} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationGalleryImage} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationGalleryImage} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName: string, labAccountName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationGalleryImage>; list(resourceGroupName: string, labAccountName: string, callback: ServiceCallback<models.ResponseWithContinuationGalleryImage>): void; list(resourceGroupName: string, labAccountName: string, options: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationGalleryImage>): void; /** * Get gallery image * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} galleryImageName The name of the gallery Image. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=author)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GalleryImage>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, galleryImageName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GalleryImage>>; /** * Get gallery image * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} galleryImageName The name of the gallery Image. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=author)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GalleryImage} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GalleryImage} [result] - The deserialized result object if an error did not occur. * See {@link GalleryImage} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, labAccountName: string, galleryImageName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.GalleryImage>; get(resourceGroupName: string, labAccountName: string, galleryImageName: string, callback: ServiceCallback<models.GalleryImage>): void; get(resourceGroupName: string, labAccountName: string, galleryImageName: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GalleryImage>): void; /** * Create or replace an existing Gallery Image. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} galleryImageName The name of the gallery Image. * * @param {object} galleryImage Represents an image from the Azure Marketplace * * @param {boolean} [galleryImage.isEnabled] Indicates whether this gallery * image is enabled. * * @param {boolean} [galleryImage.isOverride] Indicates whether this gallery * has been overridden for this lab account * * @param {boolean} [galleryImage.isPlanAuthorized] Indicates if the plan has * been authorized for programmatic deployment. * * @param {string} [galleryImage.provisioningState] The provisioning status of * the resource. * * @param {string} [galleryImage.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [galleryImage.location] The location of the resource. * * @param {object} [galleryImage.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GalleryImage>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: models.GalleryImage, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GalleryImage>>; /** * Create or replace an existing Gallery Image. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} galleryImageName The name of the gallery Image. * * @param {object} galleryImage Represents an image from the Azure Marketplace * * @param {boolean} [galleryImage.isEnabled] Indicates whether this gallery * image is enabled. * * @param {boolean} [galleryImage.isOverride] Indicates whether this gallery * has been overridden for this lab account * * @param {boolean} [galleryImage.isPlanAuthorized] Indicates if the plan has * been authorized for programmatic deployment. * * @param {string} [galleryImage.provisioningState] The provisioning status of * the resource. * * @param {string} [galleryImage.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [galleryImage.location] The location of the resource. * * @param {object} [galleryImage.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GalleryImage} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GalleryImage} [result] - The deserialized result object if an error did not occur. * See {@link GalleryImage} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: models.GalleryImage, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GalleryImage>; createOrUpdate(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: models.GalleryImage, callback: ServiceCallback<models.GalleryImage>): void; createOrUpdate(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: models.GalleryImage, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GalleryImage>): void; /** * Delete gallery image. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} galleryImageName The name of the gallery Image. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, galleryImageName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete gallery image. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} galleryImageName The name of the gallery Image. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, labAccountName: string, galleryImageName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, labAccountName: string, galleryImageName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, labAccountName: string, galleryImageName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Modify properties of gallery images. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} galleryImageName The name of the gallery Image. * * @param {object} galleryImage Represents an image from the Azure Marketplace * * @param {boolean} [galleryImage.isEnabled] Indicates whether this gallery * image is enabled. * * @param {boolean} [galleryImage.isOverride] Indicates whether this gallery * has been overridden for this lab account * * @param {boolean} [galleryImage.isPlanAuthorized] Indicates if the plan has * been authorized for programmatic deployment. * * @param {string} [galleryImage.provisioningState] The provisioning status of * the resource. * * @param {string} [galleryImage.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [galleryImage.location] The location of the resource. * * @param {object} [galleryImage.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GalleryImage>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: models.GalleryImageFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GalleryImage>>; /** * Modify properties of gallery images. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} galleryImageName The name of the gallery Image. * * @param {object} galleryImage Represents an image from the Azure Marketplace * * @param {boolean} [galleryImage.isEnabled] Indicates whether this gallery * image is enabled. * * @param {boolean} [galleryImage.isOverride] Indicates whether this gallery * has been overridden for this lab account * * @param {boolean} [galleryImage.isPlanAuthorized] Indicates if the plan has * been authorized for programmatic deployment. * * @param {string} [galleryImage.provisioningState] The provisioning status of * the resource. * * @param {string} [galleryImage.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [galleryImage.location] The location of the resource. * * @param {object} [galleryImage.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GalleryImage} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GalleryImage} [result] - The deserialized result object if an error did not occur. * See {@link GalleryImage} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: models.GalleryImageFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GalleryImage>; update(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: models.GalleryImageFragment, callback: ServiceCallback<models.GalleryImage>): void; update(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: models.GalleryImageFragment, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GalleryImage>): void; /** * List gallery images in a given lab account. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationGalleryImage>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationGalleryImage>>; /** * List gallery images in a given lab account. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationGalleryImage} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationGalleryImage} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationGalleryImage} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationGalleryImage>; listNext(nextPageLink: string, callback: ServiceCallback<models.ResponseWithContinuationGalleryImage>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationGalleryImage>): void; } /** * @class * Labs * __NOTE__: An instance of this class is automatically created for an * instance of the ManagedLabsClient. */ export interface Labs { /** * List labs in a given lab account. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=maxUsersInLab)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationLab>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationLab>>; /** * List labs in a given lab account. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=maxUsersInLab)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationLab} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationLab} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationLab} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName: string, labAccountName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationLab>; list(resourceGroupName: string, labAccountName: string, callback: ServiceCallback<models.ResponseWithContinuationLab>): void; list(resourceGroupName: string, labAccountName: string, options: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationLab>): void; /** * Get lab * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=maxUsersInLab)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Lab>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Lab>>; /** * Get lab * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=maxUsersInLab)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Lab} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Lab} [result] - The deserialized result object if an error did not occur. * See {@link Lab} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, labAccountName: string, labName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.Lab>; get(resourceGroupName: string, labAccountName: string, labName: string, callback: ServiceCallback<models.Lab>): void; get(resourceGroupName: string, labAccountName: string, labName: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Lab>): void; /** * Create or replace an existing Lab. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} lab Represents a lab. * * @param {number} [lab.maxUsersInLab] Maximum number of users allowed in the * lab. * * @param {moment.duration} [lab.usageQuota] Maximum duration a user can use an * environment for in the lab. * * @param {string} [lab.userAccessMode] Lab user access mode (open to all vs. * restricted to those listed on the lab). Possible values include: * 'Restricted', 'Open' * * @param {string} [lab.provisioningState] The provisioning status of the * resource. * * @param {string} [lab.uniqueIdentifier] The unique immutable identifier of a * resource (Guid). * * @param {string} [lab.location] The location of the resource. * * @param {object} [lab.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Lab>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, lab: models.Lab, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Lab>>; /** * Create or replace an existing Lab. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} lab Represents a lab. * * @param {number} [lab.maxUsersInLab] Maximum number of users allowed in the * lab. * * @param {moment.duration} [lab.usageQuota] Maximum duration a user can use an * environment for in the lab. * * @param {string} [lab.userAccessMode] Lab user access mode (open to all vs. * restricted to those listed on the lab). Possible values include: * 'Restricted', 'Open' * * @param {string} [lab.provisioningState] The provisioning status of the * resource. * * @param {string} [lab.uniqueIdentifier] The unique immutable identifier of a * resource (Guid). * * @param {string} [lab.location] The location of the resource. * * @param {object} [lab.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Lab} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Lab} [result] - The deserialized result object if an error did not occur. * See {@link Lab} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, lab: models.Lab, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Lab>; createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, lab: models.Lab, callback: ServiceCallback<models.Lab>): void; createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, lab: models.Lab, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Lab>): void; /** * Delete lab. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete lab. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Modify properties of labs. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} lab Represents a lab. * * @param {number} [lab.maxUsersInLab] Maximum number of users allowed in the * lab. * * @param {moment.duration} [lab.usageQuota] Maximum duration a user can use an * environment for in the lab. * * @param {string} [lab.userAccessMode] Lab user access mode (open to all vs. * restricted to those listed on the lab). Possible values include: * 'Restricted', 'Open' * * @param {string} [lab.provisioningState] The provisioning status of the * resource. * * @param {string} [lab.uniqueIdentifier] The unique immutable identifier of a * resource (Guid). * * @param {string} [lab.location] The location of the resource. * * @param {object} [lab.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Lab>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, lab: models.LabFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Lab>>; /** * Modify properties of labs. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} lab Represents a lab. * * @param {number} [lab.maxUsersInLab] Maximum number of users allowed in the * lab. * * @param {moment.duration} [lab.usageQuota] Maximum duration a user can use an * environment for in the lab. * * @param {string} [lab.userAccessMode] Lab user access mode (open to all vs. * restricted to those listed on the lab). Possible values include: * 'Restricted', 'Open' * * @param {string} [lab.provisioningState] The provisioning status of the * resource. * * @param {string} [lab.uniqueIdentifier] The unique immutable identifier of a * resource (Guid). * * @param {string} [lab.location] The location of the resource. * * @param {object} [lab.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Lab} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Lab} [result] - The deserialized result object if an error did not occur. * See {@link Lab} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, labAccountName: string, labName: string, lab: models.LabFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Lab>; update(resourceGroupName: string, labAccountName: string, labName: string, lab: models.LabFragment, callback: ServiceCallback<models.Lab>): void; update(resourceGroupName: string, labAccountName: string, labName: string, lab: models.LabFragment, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Lab>): void; /** * Add users to a lab * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} addUsersPayload Payload for Add Users operation on a Lab. * * @param {array} addUsersPayload.emailAddresses List of user emails addresses * to add to the lab. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ addUsersWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, addUsersPayload: models.AddUsersPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Add users to a lab * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} addUsersPayload Payload for Add Users operation on a Lab. * * @param {array} addUsersPayload.emailAddresses List of user emails addresses * to add to the lab. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ addUsers(resourceGroupName: string, labAccountName: string, labName: string, addUsersPayload: models.AddUsersPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; addUsers(resourceGroupName: string, labAccountName: string, labName: string, addUsersPayload: models.AddUsersPayload, callback: ServiceCallback<void>): void; addUsers(resourceGroupName: string, labAccountName: string, labName: string, addUsersPayload: models.AddUsersPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Register to managed lab. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ registerWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Register to managed lab. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ register(resourceGroupName: string, labAccountName: string, labName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; register(resourceGroupName: string, labAccountName: string, labName: string, callback: ServiceCallback<void>): void; register(resourceGroupName: string, labAccountName: string, labName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Delete lab. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete lab. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * List labs in a given lab account. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationLab>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationLab>>; /** * List labs in a given lab account. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationLab} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationLab} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationLab} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationLab>; listNext(nextPageLink: string, callback: ServiceCallback<models.ResponseWithContinuationLab>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationLab>): void; } /** * @class * EnvironmentSettings * __NOTE__: An instance of this class is automatically created for an * instance of the ManagedLabsClient. */ export interface EnvironmentSettings { /** * List environment setting in a given lab. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=publishingState)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationEnvironmentSetting>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationEnvironmentSetting>>; /** * List environment setting in a given lab. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=publishingState)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationEnvironmentSetting} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationEnvironmentSetting} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationEnvironmentSetting} * for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName: string, labAccountName: string, labName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationEnvironmentSetting>; list(resourceGroupName: string, labAccountName: string, labName: string, callback: ServiceCallback<models.ResponseWithContinuationEnvironmentSetting>): void; list(resourceGroupName: string, labAccountName: string, labName: string, options: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationEnvironmentSetting>): void; /** * Get environment setting * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=publishingState)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EnvironmentSetting>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EnvironmentSetting>>; /** * Get environment setting * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=publishingState)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {EnvironmentSetting} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {EnvironmentSetting} [result] - The deserialized result object if an error did not occur. * See {@link EnvironmentSetting} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.EnvironmentSetting>; get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: ServiceCallback<models.EnvironmentSetting>): void; get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EnvironmentSetting>): void; /** * Create or replace an existing Environment Setting. This operation can take a * while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} environmentSetting Represents settings of an environment, * from which environment instances would be created * * @param {string} [environmentSetting.configurationState] Describes the user's * progress in configuring their environment setting. Possible values include: * 'NotApplicable', 'Completed' * * @param {string} [environmentSetting.description] Describes the environment * and its resource settings * * @param {string} [environmentSetting.title] Brief title describing the * environment and its resource settings * * @param {object} environmentSetting.resourceSettings The resource specific * settings * * @param {string} [environmentSetting.resourceSettings.galleryImageResourceId] * The resource id of the gallery image used for creating the virtual machine * * @param {string} [environmentSetting.resourceSettings.size] The size of the * virtual machine. Possible values include: 'Basic', 'Standard', 'Performance' * * @param {object} environmentSetting.resourceSettings.referenceVm Details * specific to Reference Vm * * @param {string} environmentSetting.resourceSettings.referenceVm.userName The * username of the virtual machine * * @param {string} [environmentSetting.resourceSettings.referenceVm.password] * The password of the virtual machine. This will be set to null in GET * resource API * * @param {string} [environmentSetting.provisioningState] The provisioning * status of the resource. * * @param {string} [environmentSetting.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [environmentSetting.location] The location of the resource. * * @param {object} [environmentSetting.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EnvironmentSetting>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EnvironmentSetting>>; /** * Create or replace an existing Environment Setting. This operation can take a * while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} environmentSetting Represents settings of an environment, * from which environment instances would be created * * @param {string} [environmentSetting.configurationState] Describes the user's * progress in configuring their environment setting. Possible values include: * 'NotApplicable', 'Completed' * * @param {string} [environmentSetting.description] Describes the environment * and its resource settings * * @param {string} [environmentSetting.title] Brief title describing the * environment and its resource settings * * @param {object} environmentSetting.resourceSettings The resource specific * settings * * @param {string} [environmentSetting.resourceSettings.galleryImageResourceId] * The resource id of the gallery image used for creating the virtual machine * * @param {string} [environmentSetting.resourceSettings.size] The size of the * virtual machine. Possible values include: 'Basic', 'Standard', 'Performance' * * @param {object} environmentSetting.resourceSettings.referenceVm Details * specific to Reference Vm * * @param {string} environmentSetting.resourceSettings.referenceVm.userName The * username of the virtual machine * * @param {string} [environmentSetting.resourceSettings.referenceVm.password] * The password of the virtual machine. This will be set to null in GET * resource API * * @param {string} [environmentSetting.provisioningState] The provisioning * status of the resource. * * @param {string} [environmentSetting.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [environmentSetting.location] The location of the resource. * * @param {object} [environmentSetting.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {EnvironmentSetting} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {EnvironmentSetting} [result] - The deserialized result object if an error did not occur. * See {@link EnvironmentSetting} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EnvironmentSetting>; createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSetting, callback: ServiceCallback<models.EnvironmentSetting>): void; createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSetting, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EnvironmentSetting>): void; /** * Delete environment setting. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete environment setting. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Modify properties of environment setting. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} environmentSetting Represents settings of an environment, * from which environment instances would be created * * @param {string} [environmentSetting.configurationState] Describes the user's * progress in configuring their environment setting. Possible values include: * 'NotApplicable', 'Completed' * * @param {string} [environmentSetting.description] Describes the environment * and its resource settings * * @param {string} [environmentSetting.title] Brief title describing the * environment and its resource settings * * @param {object} [environmentSetting.resourceSettings] The resource specific * settings * * @param {string} [environmentSetting.resourceSettings.galleryImageResourceId] * The resource id of the gallery image used for creating the virtual machine * * @param {string} [environmentSetting.resourceSettings.size] The size of the * virtual machine. Possible values include: 'Basic', 'Standard', 'Performance' * * @param {object} [environmentSetting.resourceSettings.referenceVm] Details * specific to Reference Vm * * @param {string} [environmentSetting.resourceSettings.referenceVm.userName] * The username of the virtual machine * * @param {string} [environmentSetting.resourceSettings.referenceVm.password] * The password of the virtual machine. This will be set to null in GET * resource API * * @param {string} [environmentSetting.provisioningState] The provisioning * status of the resource. * * @param {string} [environmentSetting.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [environmentSetting.location] The location of the resource. * * @param {object} [environmentSetting.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EnvironmentSetting>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSettingFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EnvironmentSetting>>; /** * Modify properties of environment setting. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} environmentSetting Represents settings of an environment, * from which environment instances would be created * * @param {string} [environmentSetting.configurationState] Describes the user's * progress in configuring their environment setting. Possible values include: * 'NotApplicable', 'Completed' * * @param {string} [environmentSetting.description] Describes the environment * and its resource settings * * @param {string} [environmentSetting.title] Brief title describing the * environment and its resource settings * * @param {object} [environmentSetting.resourceSettings] The resource specific * settings * * @param {string} [environmentSetting.resourceSettings.galleryImageResourceId] * The resource id of the gallery image used for creating the virtual machine * * @param {string} [environmentSetting.resourceSettings.size] The size of the * virtual machine. Possible values include: 'Basic', 'Standard', 'Performance' * * @param {object} [environmentSetting.resourceSettings.referenceVm] Details * specific to Reference Vm * * @param {string} [environmentSetting.resourceSettings.referenceVm.userName] * The username of the virtual machine * * @param {string} [environmentSetting.resourceSettings.referenceVm.password] * The password of the virtual machine. This will be set to null in GET * resource API * * @param {string} [environmentSetting.provisioningState] The provisioning * status of the resource. * * @param {string} [environmentSetting.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [environmentSetting.location] The location of the resource. * * @param {object} [environmentSetting.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {EnvironmentSetting} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {EnvironmentSetting} [result] - The deserialized result object if an error did not occur. * See {@link EnvironmentSetting} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSettingFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EnvironmentSetting>; update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSettingFragment, callback: ServiceCallback<models.EnvironmentSetting>): void; update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSettingFragment, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EnvironmentSetting>): void; /** * Claims a random environment for a user in an environment settings * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ claimAnyWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Claims a random environment for a user in an environment settings * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ claimAny(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; claimAny(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: ServiceCallback<void>): void; claimAny(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Provisions/deprovisions required resources for an environment setting based * on current state of the lab/environment setting. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} publishPayload Payload for Publish operation on * EnvironmentSetting. * * @param {boolean} [publishPayload.useExistingImage] Whether to use existing * VM custom image when publishing. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ publishWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, publishPayload: models.PublishPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Provisions/deprovisions required resources for an environment setting based * on current state of the lab/environment setting. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} publishPayload Payload for Publish operation on * EnvironmentSetting. * * @param {boolean} [publishPayload.useExistingImage] Whether to use existing * VM custom image when publishing. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ publish(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, publishPayload: models.PublishPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; publish(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, publishPayload: models.PublishPayload, callback: ServiceCallback<void>): void; publish(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, publishPayload: models.PublishPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Starts a template by starting all resources inside the template. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ startWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts a template by starting all resources inside the template. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ start(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; start(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: ServiceCallback<void>): void; start(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Starts a template by starting all resources inside the template. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ stopWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts a template by starting all resources inside the template. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ stop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; stop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: ServiceCallback<void>): void; stop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Create or replace an existing Environment Setting. This operation can take a * while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} environmentSetting Represents settings of an environment, * from which environment instances would be created * * @param {string} [environmentSetting.configurationState] Describes the user's * progress in configuring their environment setting. Possible values include: * 'NotApplicable', 'Completed' * * @param {string} [environmentSetting.description] Describes the environment * and its resource settings * * @param {string} [environmentSetting.title] Brief title describing the * environment and its resource settings * * @param {object} environmentSetting.resourceSettings The resource specific * settings * * @param {string} [environmentSetting.resourceSettings.galleryImageResourceId] * The resource id of the gallery image used for creating the virtual machine * * @param {string} [environmentSetting.resourceSettings.size] The size of the * virtual machine. Possible values include: 'Basic', 'Standard', 'Performance' * * @param {object} environmentSetting.resourceSettings.referenceVm Details * specific to Reference Vm * * @param {string} environmentSetting.resourceSettings.referenceVm.userName The * username of the virtual machine * * @param {string} [environmentSetting.resourceSettings.referenceVm.password] * The password of the virtual machine. This will be set to null in GET * resource API * * @param {string} [environmentSetting.provisioningState] The provisioning * status of the resource. * * @param {string} [environmentSetting.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [environmentSetting.location] The location of the resource. * * @param {object} [environmentSetting.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EnvironmentSetting>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EnvironmentSetting>>; /** * Create or replace an existing Environment Setting. This operation can take a * while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} environmentSetting Represents settings of an environment, * from which environment instances would be created * * @param {string} [environmentSetting.configurationState] Describes the user's * progress in configuring their environment setting. Possible values include: * 'NotApplicable', 'Completed' * * @param {string} [environmentSetting.description] Describes the environment * and its resource settings * * @param {string} [environmentSetting.title] Brief title describing the * environment and its resource settings * * @param {object} environmentSetting.resourceSettings The resource specific * settings * * @param {string} [environmentSetting.resourceSettings.galleryImageResourceId] * The resource id of the gallery image used for creating the virtual machine * * @param {string} [environmentSetting.resourceSettings.size] The size of the * virtual machine. Possible values include: 'Basic', 'Standard', 'Performance' * * @param {object} environmentSetting.resourceSettings.referenceVm Details * specific to Reference Vm * * @param {string} environmentSetting.resourceSettings.referenceVm.userName The * username of the virtual machine * * @param {string} [environmentSetting.resourceSettings.referenceVm.password] * The password of the virtual machine. This will be set to null in GET * resource API * * @param {string} [environmentSetting.provisioningState] The provisioning * status of the resource. * * @param {string} [environmentSetting.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [environmentSetting.location] The location of the resource. * * @param {object} [environmentSetting.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {EnvironmentSetting} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {EnvironmentSetting} [result] - The deserialized result object if an error did not occur. * See {@link EnvironmentSetting} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSetting, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EnvironmentSetting>; beginCreateOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSetting, callback: ServiceCallback<models.EnvironmentSetting>): void; beginCreateOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentSetting: models.EnvironmentSetting, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EnvironmentSetting>): void; /** * Delete environment setting. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete environment setting. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Starts a template by starting all resources inside the template. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStartWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts a template by starting all resources inside the template. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStart(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginStart(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: ServiceCallback<void>): void; beginStart(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Starts a template by starting all resources inside the template. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStopWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts a template by starting all resources inside the template. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginStop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: ServiceCallback<void>): void; beginStop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * List environment setting in a given lab. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationEnvironmentSetting>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationEnvironmentSetting>>; /** * List environment setting in a given lab. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationEnvironmentSetting} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationEnvironmentSetting} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationEnvironmentSetting} * for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationEnvironmentSetting>; listNext(nextPageLink: string, callback: ServiceCallback<models.ResponseWithContinuationEnvironmentSetting>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationEnvironmentSetting>): void; } /** * @class * Environments * __NOTE__: An instance of this class is automatically created for an * instance of the ManagedLabsClient. */ export interface Environments { /** * List environments in a given environment setting. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=networkInterface)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationEnvironment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationEnvironment>>; /** * List environments in a given environment setting. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=networkInterface)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationEnvironment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationEnvironment} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationEnvironment} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationEnvironment>; list(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: ServiceCallback<models.ResponseWithContinuationEnvironment>): void; list(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationEnvironment>): void; /** * Get environment * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=networkInterface)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Environment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Environment>>; /** * Get environment * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($expand=networkInterface)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Environment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Environment} [result] - The deserialized result object if an error did not occur. * See {@link Environment} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.Environment>; get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, callback: ServiceCallback<models.Environment>): void; get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Environment>): void; /** * Create or replace an existing Environment. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} environment Represents an environment instance * * @param {object} [environment.resourceSets] The set of a VM and the setting * id it was created for * * @param {string} [environment.resourceSets.vmResourceId] VM resource Id for * the environment * * @param {string} [environment.resourceSets.resourceSettingId] * resourceSettingId for the environment * * @param {string} [environment.provisioningState] The provisioning status of * the resource. * * @param {string} [environment.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [environment.location] The location of the resource. * * @param {object} [environment.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Environment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: models.Environment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Environment>>; /** * Create or replace an existing Environment. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} environment Represents an environment instance * * @param {object} [environment.resourceSets] The set of a VM and the setting * id it was created for * * @param {string} [environment.resourceSets.vmResourceId] VM resource Id for * the environment * * @param {string} [environment.resourceSets.resourceSettingId] * resourceSettingId for the environment * * @param {string} [environment.provisioningState] The provisioning status of * the resource. * * @param {string} [environment.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [environment.location] The location of the resource. * * @param {object} [environment.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Environment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Environment} [result] - The deserialized result object if an error did not occur. * See {@link Environment} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: models.Environment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Environment>; createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: models.Environment, callback: ServiceCallback<models.Environment>): void; createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: models.Environment, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Environment>): void; /** * Delete environment. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete environment. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Modify properties of environments. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} environment Represents an environment instance * * @param {object} [environment.resourceSets] The set of a VM and the setting * id it was created for * * @param {string} [environment.resourceSets.vmResourceId] VM resource Id for * the environment * * @param {string} [environment.resourceSets.resourceSettingId] * resourceSettingId for the environment * * @param {string} [environment.provisioningState] The provisioning status of * the resource. * * @param {string} [environment.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [environment.location] The location of the resource. * * @param {object} [environment.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Environment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: models.EnvironmentFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Environment>>; /** * Modify properties of environments. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} environment Represents an environment instance * * @param {object} [environment.resourceSets] The set of a VM and the setting * id it was created for * * @param {string} [environment.resourceSets.vmResourceId] VM resource Id for * the environment * * @param {string} [environment.resourceSets.resourceSettingId] * resourceSettingId for the environment * * @param {string} [environment.provisioningState] The provisioning status of * the resource. * * @param {string} [environment.uniqueIdentifier] The unique immutable * identifier of a resource (Guid). * * @param {string} [environment.location] The location of the resource. * * @param {object} [environment.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Environment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Environment} [result] - The deserialized result object if an error did not occur. * See {@link Environment} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: models.EnvironmentFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Environment>; update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: models.EnvironmentFragment, callback: ServiceCallback<models.Environment>): void; update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: models.EnvironmentFragment, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Environment>): void; /** * Claims the environment and assigns it to the user * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ claimWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Claims the environment and assigns it to the user * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ claim(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; claim(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, callback: ServiceCallback<void>): void; claim(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Resets the user password on an environment This operation can take a while * to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} resetPasswordPayload Represents the payload for resetting * passwords. * * @param {string} resetPasswordPayload.environmentId The resourceId of the * environment * * @param {string} [resetPasswordPayload.username] The username for which the * password will be reset. * * @param {string} [resetPasswordPayload.password] The password to assign to * the user specified in * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ resetPasswordWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, resetPasswordPayload: models.ResetPasswordPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Resets the user password on an environment This operation can take a while * to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} resetPasswordPayload Represents the payload for resetting * passwords. * * @param {string} resetPasswordPayload.environmentId The resourceId of the * environment * * @param {string} [resetPasswordPayload.username] The username for which the * password will be reset. * * @param {string} [resetPasswordPayload.password] The password to assign to * the user specified in * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ resetPassword(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, resetPasswordPayload: models.ResetPasswordPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; resetPassword(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, resetPasswordPayload: models.ResetPasswordPayload, callback: ServiceCallback<void>): void; resetPassword(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, resetPasswordPayload: models.ResetPasswordPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Starts an environment by starting all resources inside the environment. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ startWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts an environment by starting all resources inside the environment. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ start(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; start(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, callback: ServiceCallback<void>): void; start(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Stops an environment by stopping all resources inside the environment This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ stopWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Stops an environment by stopping all resources inside the environment This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ stop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; stop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, callback: ServiceCallback<void>): void; stop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Delete environment. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete environment. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Resets the user password on an environment This operation can take a while * to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} resetPasswordPayload Represents the payload for resetting * passwords. * * @param {string} resetPasswordPayload.environmentId The resourceId of the * environment * * @param {string} [resetPasswordPayload.username] The username for which the * password will be reset. * * @param {string} [resetPasswordPayload.password] The password to assign to * the user specified in * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginResetPasswordWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, resetPasswordPayload: models.ResetPasswordPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Resets the user password on an environment This operation can take a while * to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} resetPasswordPayload Represents the payload for resetting * passwords. * * @param {string} resetPasswordPayload.environmentId The resourceId of the * environment * * @param {string} [resetPasswordPayload.username] The username for which the * password will be reset. * * @param {string} [resetPasswordPayload.password] The password to assign to * the user specified in * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginResetPassword(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, resetPasswordPayload: models.ResetPasswordPayload, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginResetPassword(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, resetPasswordPayload: models.ResetPasswordPayload, callback: ServiceCallback<void>): void; beginResetPassword(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, resetPasswordPayload: models.ResetPasswordPayload, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Starts an environment by starting all resources inside the environment. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStartWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Starts an environment by starting all resources inside the environment. This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStart(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginStart(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, callback: ServiceCallback<void>): void; beginStart(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Stops an environment by stopping all resources inside the environment This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginStopWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Stops an environment by stopping all resources inside the environment This * operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} environmentSettingName The name of the environment Setting. * * @param {string} environmentName The name of the environment. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginStop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginStop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, callback: ServiceCallback<void>): void; beginStop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * List environments in a given environment setting. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationEnvironment>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationEnvironment>>; /** * List environments in a given environment setting. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationEnvironment} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationEnvironment} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationEnvironment} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationEnvironment>; listNext(nextPageLink: string, callback: ServiceCallback<models.ResponseWithContinuationEnvironment>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationEnvironment>): void; } /** * @class * Users * __NOTE__: An instance of this class is automatically created for an * instance of the ManagedLabsClient. */ export interface Users { /** * List users in a given lab. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=email)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationUser>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationUser>>; /** * List users in a given lab. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=email)' * * @param {string} [options.filter] The filter to apply to the operation. * * @param {number} [options.top] The maximum number of resources to return from * the operation. * * @param {string} [options.orderby] The ordering expression for the results, * using OData notation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationUser} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationUser} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationUser} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName: string, labAccountName: string, labName: string, options?: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationUser>; list(resourceGroupName: string, labAccountName: string, labName: string, callback: ServiceCallback<models.ResponseWithContinuationUser>): void; list(resourceGroupName: string, labAccountName: string, labName: string, options: { expand? : string, filter? : string, top? : number, orderby? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationUser>): void; /** * Get user * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} userName The name of the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=email)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<User>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, userName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.User>>; /** * Get user * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} userName The name of the user. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify the $expand query. Example: * 'properties($select=email)' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {User} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {User} [result] - The deserialized result object if an error did not occur. * See {@link User} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, labAccountName: string, labName: string, userName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.User>; get(resourceGroupName: string, labAccountName: string, labName: string, userName: string, callback: ServiceCallback<models.User>): void; get(resourceGroupName: string, labAccountName: string, labName: string, userName: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.User>): void; /** * Create or replace an existing User. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} userName The name of the user. * * @param {object} user The User registered to a lab * * @param {string} [user.provisioningState] The provisioning status of the * resource. * * @param {string} [user.uniqueIdentifier] The unique immutable identifier of a * resource (Guid). * * @param {string} [user.location] The location of the resource. * * @param {object} [user.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<User>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, userName: string, user: models.User, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.User>>; /** * Create or replace an existing User. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} userName The name of the user. * * @param {object} user The User registered to a lab * * @param {string} [user.provisioningState] The provisioning status of the * resource. * * @param {string} [user.uniqueIdentifier] The unique immutable identifier of a * resource (Guid). * * @param {string} [user.location] The location of the resource. * * @param {object} [user.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {User} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {User} [result] - The deserialized result object if an error did not occur. * See {@link User} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, userName: string, user: models.User, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.User>; createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, userName: string, user: models.User, callback: ServiceCallback<models.User>): void; createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, userName: string, user: models.User, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.User>): void; /** * Delete user. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} userName The name of the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, userName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete user. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} userName The name of the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, userName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, userName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, userName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Modify properties of users. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} userName The name of the user. * * @param {object} user The User registered to a lab * * @param {string} [user.provisioningState] The provisioning status of the * resource. * * @param {string} [user.uniqueIdentifier] The unique immutable identifier of a * resource (Guid). * * @param {string} [user.location] The location of the resource. * * @param {object} [user.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<User>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, userName: string, user: models.UserFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.User>>; /** * Modify properties of users. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} userName The name of the user. * * @param {object} user The User registered to a lab * * @param {string} [user.provisioningState] The provisioning status of the * resource. * * @param {string} [user.uniqueIdentifier] The unique immutable identifier of a * resource (Guid). * * @param {string} [user.location] The location of the resource. * * @param {object} [user.tags] The tags of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {User} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {User} [result] - The deserialized result object if an error did not occur. * See {@link User} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, labAccountName: string, labName: string, userName: string, user: models.UserFragment, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.User>; update(resourceGroupName: string, labAccountName: string, labName: string, userName: string, user: models.UserFragment, callback: ServiceCallback<models.User>): void; update(resourceGroupName: string, labAccountName: string, labName: string, userName: string, user: models.UserFragment, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.User>): void; /** * Delete user. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} userName The name of the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, labAccountName: string, labName: string, userName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete user. This operation can take a while to complete * * @param {string} resourceGroupName The name of the resource group. * * @param {string} labAccountName The name of the lab Account. * * @param {string} labName The name of the lab. * * @param {string} userName The name of the user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, userName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, userName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, userName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * List users in a given lab. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ResponseWithContinuationUser>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ResponseWithContinuationUser>>; /** * List users in a given lab. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ResponseWithContinuationUser} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ResponseWithContinuationUser} [result] - The deserialized result object if an error did not occur. * See {@link ResponseWithContinuationUser} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ResponseWithContinuationUser>; listNext(nextPageLink: string, callback: ServiceCallback<models.ResponseWithContinuationUser>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ResponseWithContinuationUser>): void; }
the_stack
import { expect } from "chai"; import { Candle } from "../src/Candle"; import { IClient } from "../src/IClient"; import { Level2Snapshot } from "../src/Level2Snapshots"; import { Level2Update } from "../src/Level2Update"; import { Level3Snapshot } from "../src/Level3Snapshot"; import { Level3Update } from "../src/Level3Update"; import { Market } from "../src/Market"; import { Ticker } from "../src/Ticker"; import { Trade } from "../src/Trade"; export const wait = (ms: number = 0) => new Promise(resolve => setTimeout(resolve, ms)); export type TestSpec = { clientFactory: () => IClient; clientName: string; exchangeName: string; skip?: boolean; fetchMarkets?: () => Promise<Market[]>; markets?: Market[]; fetchTradeMarkets?: () => Promise<Market[]>; tradeMarkets?: Market[]; fetchAllMarkets?: () => Promise<Market[]>; allMarkets?: Market[]; unsubWaitMs?: number; getEventingSocket?: (client: IClient, market: Market) => any; marketIdList?: string[]; marketBaseList?: string[]; marketQuoteList?: string[]; testConnectEvents?: boolean; testDisconnectEvents?: boolean; testReconnectionEvents?: boolean; testCloseEvents?: boolean; testAllMarketsTrades?: boolean; testAllMarketsTradesSuccess?: number; testAllMarketsL2Updates?: boolean; testAllMarketsL2UpdatesSuccess?: number; hasTickers?: boolean; hasTrades?: boolean; hasCandles?: boolean; hasLevel2Snapshots?: boolean; hasLevel2Updates?: boolean; hasLevel3Snapshots?: boolean; hasLevel3Updates?: boolean; ticker?: TickerOptions; trade?: TradeOptions; candle?: CandleOptions; l2snapshot?: L2SnapshotOptions; l2update?: L2UpdateOptions; l3snapshot?: L3SnapshotOptions; l3update?: L3UpdateOptions; }; export type TickerOptions = { hasTimestamp?: boolean; hasLast?: boolean; hasOpen?: boolean; hasHigh?: boolean; hasLow?: boolean; hasVolume?: boolean; hasQuoteVolume?: boolean; hasChange?: boolean; hasChangePercent?: boolean; hasBid?: boolean; hasBidVolume?: boolean; hasAsk?: boolean; hasAskVolume?: boolean; hasSequenceId?: boolean; }; export type TradeOptions = { hasTradeId?: boolean; hasSequenceId?: boolean; tradeIdPattern?: RegExp; tests?: (spec: any, result: any) => void; }; export type CandleOptions = { hasSequenceId?: boolean; tests?: (spec: any, result: any) => void; }; export type L2SnapshotOptions = { hasTimestampMs?: boolean; hasSequenceId?: boolean; hasCount?: boolean; hasEventId?: boolean; tests?: (spec: any, result: any) => void; }; export type L2UpdateOptions = { hasSnapshot?: boolean; hasTimestampMs?: boolean; hasSequenceId?: boolean; hasLastSequenceId?: boolean; hasEventId?: boolean; hasEventMs?: boolean; hasCount?: boolean; tests?: (spec: any, result: any) => void; done?: (spec: any, result: any, update: Level2Update) => boolean; }; export type L3UpdateOptions = { hasSnapshot?: boolean; hasTimestampMs?: boolean; hasSequenceId?: boolean; hasCount?: boolean; orderIdPattern?: RegExp; tests?: (spec: any, result: any) => void; done?: (spec: any, result: any, update: Level3Update) => boolean; }; export type L3SnapshotOptions = { hasTimestampMs?: boolean; hasSequenceId?: boolean; tests?: (spec: any, result: any) => void; }; export type TestRunnerState = { client?: IClient; }; export type TestRunnerResult = { ready?: boolean; market?: Market; ticker?: Ticker; trade?: Trade; candle?: Candle; snapshot?: Level2Snapshot | Level3Snapshot; snapMarket?: Market; update?: Level2Update | Level3Update; updateMarket?: Market; }; export function testClient(spec: TestSpec) { if (spec.skip) return; describe(spec.clientName, () => { const state: TestRunnerState = {}; before(async function () { this.timeout(30000); state.client = spec.clientFactory(); if (spec.fetchMarkets) { spec.markets = await spec.fetchMarkets(); } if (spec.fetchTradeMarkets) { spec.tradeMarkets = await spec.fetchTradeMarkets(); } else if (!spec.tradeMarkets) { spec.tradeMarkets = spec.markets; } if (spec.fetchAllMarkets) { spec.allMarkets = await spec.fetchAllMarkets(); } spec.marketIdList = spec.markets.map(p => p.id); spec.marketBaseList = spec.markets.map(p => p.base); spec.marketQuoteList = spec.markets.map(p => p.quote); }); describe("capabilities", () => { it(`should ${spec.hasTickers ? "support" : "not support"} tickers`, () => { expect(state.client.hasTickers).to.equal(spec.hasTickers); }); it(`should ${spec.hasTrades ? "support" : "not support"} trades`, () => { expect(state.client.hasTrades).to.equal(spec.hasTrades); }); it(`should ${spec.hasCandles ? "support" : "not support"} candles`, () => { expect(state.client.hasCandles).to.equal(spec.hasCandles); }); it(`should ${ spec.hasLevel2Snapshots ? "support" : "not support" } level2 snapshots`, () => { expect(state.client.hasLevel2Snapshots).to.equal(spec.hasLevel2Snapshots); }); it(`should ${spec.hasLevel2Updates ? "support" : "not support"} level2 updates`, () => { expect(state.client.hasLevel2Updates).to.equal(spec.hasLevel2Updates); }); it(`should ${ spec.hasLevel3Snapshots ? "support" : "not support" } level3 snapshots`, () => { expect(state.client.hasLevel3Snapshots).to.equal(spec.hasLevel3Snapshots); }); it(`should ${spec.hasLevel3Updates ? "support" : "not support"} level3 updates`, () => { expect(state.client.hasLevel3Updates).to.equal(spec.hasLevel3Updates); }); }); if (spec.hasTickers && spec.ticker) { testTickers(spec, state); } if (spec.hasTrades && spec.trade) { testTrades(spec, state); } if (spec.hasCandles && spec.candle) { testCandles(spec, state); } if (spec.hasLevel2Snapshots && spec.l2snapshot) { testLevel2Snapshots(spec, state); } if (spec.hasLevel2Updates && spec.l2update) { testLevel2Updates(spec, state); } if (spec.hasLevel3Updates && spec.l3update) { testLevel3Updates(spec, state); } describe("close", () => { it("should close client", () => { state.client.close(); }); }); }); describe(spec.clientName + " events", () => { let client; let actual = []; before(() => { client = spec.clientFactory(); }); beforeEach(() => { actual = []; }); afterEach(() => { client.removeAllListeners(); }); function pushEvent(name) { return () => { actual.push(name); }; } function assertEvents(expected, done) { return () => { try { expect(actual).to.deep.equal(expected); setTimeout(done, 1000); // delay this to prevent async "connection" events to complete } catch (ex) { done(ex); } }; } if (spec.testConnectEvents) { it("subscribe triggers `connecting` > `connected`", done => { client.on("connecting", pushEvent("connecting")); client.on("connected", pushEvent("connected")); client.on("connected", assertEvents(["connecting", "connected"], done)); client.subscribeTrades(spec.markets[0]); }).timeout(5000); } if (spec.testDisconnectEvents) { it("disconnection triggers `disconnected` > `connecting` > `connected`", done => { client.on("disconnected", pushEvent("disconnected")); client.on("connecting", pushEvent("connecting")); client.on("connected", pushEvent("connected")); client.on( "connected", assertEvents(["disconnected", "connecting", "connected"], done), ); const p = client._wss ? Promise.resolve(client._wss) : Promise.resolve(spec.getEventingSocket(client, spec.markets[0])); p.then(smartws => { smartws._retryTimeoutMs = 1000; smartws._wss.close(); // simulate a failure by directly closing the underlying socket }).catch(done); }).timeout(5000); } if (spec.testReconnectionEvents) { it("reconnects triggers `reconnecting` > `closing` > `closed` > `connecting` > `connected`", done => { client.on("reconnecting", pushEvent("reconnecting")); client.on("closing", pushEvent("closing")); client.on("closed", pushEvent("closed")); client.on("connecting", pushEvent("connecting")); client.on("connected", pushEvent("connected")); client.on( "connected", assertEvents( ["reconnecting", "closing", "closed", "connecting", "connected"], done, ), ); client.reconnect(); }).timeout(5000); } if (spec.testCloseEvents) { it("close triggers `closing` > `closed`", done => { client.on("reconnecting", () => { throw new Error("should not emit reconnecting"); }); client.on("closing", pushEvent("closing")); client.on("closed", pushEvent("closed")); client.on("closed", assertEvents(["closing", "closed"], done)); client.close(); }).timeout(5000); } }); describe(spec.clientName + " all markets", () => { let client; before(async function () { this.timeout(15000); if (spec.fetchAllMarkets && !spec.allMarkets) { spec.allMarkets = await spec.fetchAllMarkets(); } }); beforeEach(() => { client = spec.clientFactory(); }); if (spec.testAllMarketsTrades) { it(`subscribeTrades wait for ${spec.testAllMarketsTradesSuccess} markets`, done => { const markets = new Set(); client.on("error", err => { client.removeAllListeners("trade"); client.removeAllListeners("error"); client.close(); done(err); }); client.on("trade", (trade, market) => { markets.add(market.id); if (markets.size >= spec.testAllMarketsTradesSuccess) { client.removeAllListeners("trade"); client.close(); done(); } }); for (const market of spec.allMarkets) { client.subscribeTrades(market); } }).timeout(60000); } if (spec.testAllMarketsL2Updates) { it(`subscribeL2Updates wait for ${spec.testAllMarketsL2UpdatesSuccess} markets`, done => { const markets = new Set(); client.on("error", err => { client.removeAllListeners("l2update"); client.removeAllListeners("error"); client.close(); done(err); }); client.on("l2update", (_, market) => { markets.add(market.id); if (markets.size >= spec.testAllMarketsTradesSuccess) { client.removeAllListeners("l2update"); client.close(); done(); } }); for (const market of spec.allMarkets) { client.subscribeLevel2Updates(market); } }).timeout(60000); } }); } function testTickers(spec, state) { describe("subscribeTicker", () => { const result: TestRunnerResult = {}; let client; before(() => { client = state.client; }); it("should subscribe and emit a ticker", done => { for (const market of spec.markets) { client.subscribeTicker(market); } client.on("ticker", (ticker, market) => { result.ready = true; result.ticker = ticker; result.market = market; client.removeAllListeners("ticker"); done(); }); }) .timeout(60000) .retries(3); it("should unsubscribe from tickers", async () => { for (const market of spec.markets) { client.unsubscribeTicker(market); } await wait(500); }); describe("results", () => { before(function () { if (!result.ready) return this.skip(); }); it("market should be the subscribing market", () => { expect(result.market).to.be.oneOf(spec.markets); }); it("ticker.exchange should be the exchange name", () => { expect(result.ticker.exchange).to.equal(spec.exchangeName); }); it("ticker.base should match market.base", () => { expect(result.ticker.base).to.be.oneOf(spec.marketBaseList); }); it("ticker.quote should match market.quote", () => { expect(result.ticker.quote).to.be.oneOf(spec.marketQuoteList); }); if (spec.ticker.hasTimestamp) { testTimestampMs(result, "ticker.timestamp"); } else { testUndefined(result, "ticker.timestamp"); } if (spec.ticker.hasSequenceId) { testPositiveNumber(result, "ticker.sequenceId"); } else { testUndefined(result, "ticker.sequenceId"); } const numberProps = [ [spec.ticker.hasLast, "ticker.last"], [spec.ticker.hasOpen, "ticker.open"], [spec.ticker.hasHigh, "ticker.high"], [spec.ticker.hasLow, "ticker.low"], [spec.ticker.hasVolume, "ticker.volume"], [spec.ticker.hasQuoteVolume, "ticker.quoteVolume"], [spec.ticker.hasChange, "ticker.change"], [spec.ticker.hasChangePercent, "ticker.changePercent"], [spec.ticker.hasBid, "ticker.bid"], [spec.ticker.hasBidVolume, "ticker.bidVolume"], [spec.ticker.hasAsk, "ticker.ask"], [spec.ticker.hasAskVolume, "ticker.askVolume"], ]; for (const [hasSpec, prop] of numberProps) { if (hasSpec) { testNumberString(result, prop); } else { testUndefined(result, prop); } } }); }); } function testTrades(spec, state) { describe("subscribeTrades", () => { const result: TestRunnerResult = {}; let client; before(() => { client = state.client; }); it("should subscribe and emit a trade", done => { // give it 2 minutes, then just abort this test const timeoutHandle = setTimeout(() => { client.removeAllListeners("trade"); clearTimeout(timeoutHandle); done(); }, 120000); for (const market of spec.tradeMarkets) { client.subscribeTrades(market); } client.on("trade", (trade, market) => { result.ready = true; result.trade = trade; result.market = market; client.removeAllListeners("trade"); clearTimeout(timeoutHandle); done(); }); }).timeout(122000); it("should unsubscribe from trades", async () => { for (const market of spec.tradeMarkets) { client.unsubscribeTrades(market); } await wait(spec.unsubWaitMs); }); describe("results", () => { before(function () { if (!result.ready) return this.skip(); }); it("market should be the subscribing market", () => { expect(result.market).to.be.oneOf(spec.tradeMarkets); }); it("trade.exchange should be the exchange name", () => { expect(result.trade.exchange).to.equal(spec.exchangeName); }); it("trade.base should match market.base", () => { expect(result.trade.base).to.be.oneOf(spec.marketBaseList); }); it("trade.quote should match market.quote", () => { expect(result.trade.quote).to.be.oneOf(spec.marketQuoteList); }); if (spec.trade.hasTradeId) { testString(result, "trade.tradeId"); } else { testUndefined(result, "trade.tradeId"); } if (spec.trade.hasSequenceId) { testPositiveNumber(result, `trade.sequenceId`); } else { testUndefined(result, `trade.sequenceId`); } if (spec.trade.tradeIdPattern) { it(`trade.tradeId should match pattern ${spec.trade.tradeIdPattern}`, () => { expect(result.trade.tradeId).to.match(spec.trade.tradeIdPattern); }); } testTimestampMs(result, "trade.unix"); it("trade.side should be either 'buy' or 'sell'", () => { expect(result.trade.side).to.match(/buy|sell/); }); testNumberString(result, "trade.price"); testNumberString(result, "trade.amount"); if (spec.trade.tests) { spec.trade.tests(spec, result); } }); }); } function testCandles(spec, state) { describe("subscribeCandles", () => { const result: TestRunnerResult = {}; let client; before(() => { client = state.client; }); it("should subscribe and emit a candle", done => { for (const market of spec.markets) { client.subscribeCandles(market); } client.on("candle", (candle, market) => { result.ready = true; result.market = market; result.candle = candle; client.removeAllListeners("candle"); done(); }); }) .timeout(60000) .retries(3); it("should unsubscribe from candles", async () => { for (const market of spec.markets) { client.unsubscribeCandles(market); } await wait(spec.unsubWaitMs); }); describe("results", () => { before(function () { if (!result.ready) return this.skip(); }); it("market should be the subscribing market", () => { expect(result.market).to.be.oneOf(spec.markets); }); testCandleResult(spec, result); }); }); } function testCandleResult(spec, result) { testTimestampMs(result, `candle.timestampMs`); testNumberString(result, `candle.open`); testNumberString(result, `candle.high`); testNumberString(result, `candle.low`); testNumberString(result, `candle.close`); testNumberString(result, `candle.volume`); } function testLevel2Snapshots(spec, state) { describe("subscribeLevel2Snapshots", () => { const result: TestRunnerResult = {}; let client; before(() => { client = state.client; }); it("should subscribe and emit a l2snapshot", done => { for (const market of spec.markets) { client.subscribeLevel2Snapshots(market); } client.on("l2snapshot", (snapshot, market) => { result.ready = true; result.snapshot = snapshot; result.market = market; client.removeAllListeners("l2snapshot"); done(); }); }) .timeout(60000) .retries(3); it("should unsubscribe from l2snapshot", async () => { for (const market of spec.markets) { client.unsubscribeLevel2Snapshots(market); } await wait(spec.unsubWaitMs); }); describe("results", () => { before(function () { if (!result.ready) return this.skip(); }); it("market should be the subscribing market", () => { expect(result.market).to.be.oneOf(spec.markets); }); testLevel2Result(spec, result, "snapshot"); }); }); } function testLevel2Updates(spec, state) { describe("subscribeLevel2Updates", () => { const result: TestRunnerResult = {}; let client; before(() => { client = state.client; }); it("should subscribe and emit a l2update", done => { for (const market of spec.markets) { client.subscribeLevel2Updates(market); } client.on("l2snapshot", (snapshot, market) => { result.ready = true; result.snapshot = snapshot; result.snapMarket = market; }); client.on("l2update", (update, market) => { result.update = update; result.updateMarket = market; if ( // check if done override method exists method in spec (!spec.l2update.done || spec.l2update.done(spec, result, update, market)) && // check if we require a snapshot (!spec.l2update.hasSnapshot || result.snapshot) ) { result.ready = true; client.removeAllListeners("l2update"); done(); } }); }) .timeout(60000) .retries(3); it("should unsubscribe from l2update", async () => { for (const market of spec.markets) { client.unsubscribeLevel2Updates(market); } await wait(spec.unsubWaitMs); }); describe("results", () => { before(function () { if (!result.ready) { this.skip(); return; } }); if (spec.l2update.hasSnapshot) { it("snapshot market should be the subscribing market", () => { expect(result.snapMarket).to.be.oneOf(spec.markets); }); testLevel2Result(spec, result, "snapshot"); } it("update market should be the subscribing market", () => { expect(result.updateMarket).to.be.oneOf(spec.markets); }); testLevel2Result(spec, result, "update"); if (spec.l2update.tests) { spec.l2update.tests(spec, result); } }); }); } function testLevel2Result(spec, result, type) { it(`${type}.exchange should be the exchange name`, () => { expect(result[type].exchange).to.equal(spec.exchangeName); }); it(`${type}.base should match market.base`, () => { expect(result[type].base).to.be.oneOf(spec.marketBaseList); }); it(`${type}.quote should match market.quote`, () => { expect(result[type].quote).to.be.oneOf(spec.marketQuoteList); }); if (spec[`l2${type}`].hasTimestampMs) { testTimestampMs(result, `${type}.timestampMs`); } else { testUndefined(result, `${type}.timestampMs`); } if (spec[`l2${type}`].hasSequenceId) { testPositiveNumber(result, `${type}.sequenceId`); } else { testUndefined(result, `${type}.sequenceId`); } if (spec[`l2${type}`].hasLastSequenceId) { testPositiveNumber(result, `${type}.lastSequenceId`); } if (spec[`l2${type}`].hasEventMs) { testTimestampMs(result, `${type}.eventMs`); } else { testUndefined(result, `${type}.eventMs`); } if (spec[`l2${type}`].hasEventId) { testPositiveNumber(result, `${type}.eventId`); } else { testUndefined(result, `${type}.eventId`); } it(`${type}.bid/ask.price should be a string`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).price; expect(actual).to.be.a("string"); }); it(`${type}.bid/ask.price should parse to a number`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).price; expect(parseFloat(actual)).to.not.be.NaN; }); it(`${type}.bid/ask.size should be a string`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).size; expect(actual).to.be.a("string"); }); it(`${type}.bid/ask.size should parse to a number`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).size; expect(parseFloat(actual)).to.not.be.NaN; }); if (spec[`l2${type}`].hasCount) { it(`${type}.bid/ask.count should be a string`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).count; expect(actual).to.be.a("string"); }); it(`${type}.bid/ask.count should parse to a number`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).count; expect(parseFloat(actual)).to.not.be.NaN; }); } else { it(`${type}.bid/ask.count should undefined`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).count; expect(actual).to.be.undefined; }); } } function testLevel3Updates(spec, state) { describe("subscribeLevel3Updates", () => { const result: TestRunnerResult = { ready: false, }; let client; before(() => { client = state.client; }); it("should subscribe and emit a l3update", done => { for (const market of spec.markets) { client.subscribeLevel3Updates(market); } client.on("l3snapshot", (snapshot, market) => { result.snapshot = snapshot; result.market = market; }); client.on("l3update", (update, market) => { result.update = update; result.market = market; try { if ( // check if done override method exists method in spec (!spec.l3update.done || spec.l3update.done(spec, result, update, market)) && // check if we require a snapshot (!spec.l3update.hasSnapshot || result.snapshot) ) { result.ready = true; client.removeAllListeners("l3update"); done(); } } catch (ex) { client.removeAllListeners("l3update"); done(ex); } }); }) .timeout(60000) .retries(3); it("should unsubscribe from l3update", async () => { for (const market of spec.markets) { client.unsubscribeLevel3Updates(market); } await wait(spec.unsubWaitMs); }); describe("results", () => { before(function () { if (!result.ready) return this.skip(); }); it("market should be the subscribing market", () => { expect(result.market).to.be.oneOf(spec.markets); }); if (spec.l3update.hasSnapshot) { testLevel3Result(spec, result, "snapshot"); } testLevel3Result(spec, result, "update"); }); }); } function testLevel3Result(spec, result, type) { it(`${type}.exchange should be the exchange name`, () => { expect(result[type].exchange).to.equal(spec.exchangeName); }); it(`${type}.base should match market.base`, () => { expect(result[type].base).to.be.oneOf(spec.marketBaseList); }); it(`${type}.quote should match market.quote`, () => { expect(result[type].quote).to.be.oneOf(spec.marketQuoteList); }); if (spec[`l3${type}`].hasTimestampMs) { testTimestampMs(result, `${type}.timestampMs`); } else { testUndefined(result, `${type}.timestampMs`); } if (spec[`l3${type}`].hasSequenceId) { testPositiveNumber(result, `${type}.sequenceId`); } else { testUndefined(result, `${type}.sequenceId`); } it(`${type}.bid/ask.orderId should be a string`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).orderId; expect(actual).to.be.a("string"); }); if (spec[`l3${type}`].orderIdPattern) { it(`${type}.bid/ask.orderId should match ${spec[`l3${type}`].orderIdPattern}`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).orderId; expect(actual).to.match(spec[`l3${type}`].orderIdPattern); }); } it(`${type}.bid/ask.price should be a string`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).price; expect(actual).to.be.a("string"); }); it(`${type}.bid/ask.price should parse to a number`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).price; expect(parseFloat(actual)).to.not.be.NaN; }); it(`${type}.bid/ask.size should be a string`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).size; expect(actual).to.be.a("string"); }); it(`${type}.bid/ask.size should parse to a number`, () => { const actual = (result[type].bids[0] || result[type].asks[0]).size; expect(parseFloat(actual)).to.not.be.NaN; }); } ////////////////////////////////////////////////////// function testPositiveNumber(result, prop) { it(`${prop} should be a number`, () => { const actual = deepValue(result, prop); expect(actual).to.be.a("number"); }); it(`${prop} should be positive`, () => { const actual = deepValue(result, prop); expect(actual).to.be.gte(0); }); } function testNumberString(result, prop) { it(`${prop} should be a string`, () => { const actual = deepValue(result, prop); expect(actual).to.be.a("string"); }); it(`${prop} should parse to a number`, () => { const actual = deepValue(result, prop); expect(parseFloat(actual)).to.not.be.NaN; }); } function testUndefined(result, propPath) { it(`${propPath} should be undefined`, () => { const actual = deepValue(result, propPath); expect(actual).to.be.undefined; }); } function testTimestampMs(result, propPath) { it(`${propPath} should be a number`, () => { const actual = deepValue(result, propPath); expect(actual).to.be.a("number"); }); it(`${propPath} should be in milliseconds`, () => { const actual = deepValue(result, propPath); expect(actual).to.be.greaterThan(1531677480000); }); } function testString(result, propPath) { it(`${propPath} should be a string`, () => { const actual = deepValue(result, propPath); expect(actual).to.be.a("string"); }); it(`${propPath} should not be empty`, () => { const actual = deepValue(result, propPath); expect(actual).to.not.equal(""); }); } function deepValue(obj, path) { const parts = path.split("."); let result = obj; for (const part of parts) { result = result[part]; } return result; }
the_stack
import Chart from 'chart.js/auto'; import { preview } from 'preview'; import * as React from 'react'; import log from '../../shared/log'; import { GraphField, GraphPanelInfo, GraphPanelInfoType, GraphPanelInfoWidth, PanelInfo, PanelResult, } from '../../shared/state'; import { Button } from '../components/Button'; import { FieldPicker, unusedFields } from '../components/FieldPicker'; import { FormGroup } from '../components/FormGroup'; import { PanelSourcePicker } from '../components/PanelSourcePicker'; import { Radio } from '../components/Radio'; import { Select } from '../components/Select'; import { SettingsContext } from '../Settings'; import { evalColumnPanel } from './TablePanel'; import { PanelBodyProps, PanelDetailsProps, PanelUIDetails } from './types'; export function evalGraphPanel( panel: GraphPanelInfo, panels: Array<PanelInfo>, idMap: Record<string | string, string> ) { return evalColumnPanel( panel.id, panel.graph.panelSource, [panel.graph.x, ...panel.graph.ys.map((y) => y.field)], idMap, panels ); } // Generated by https://medialab.github.io/iwanthue/ const COLORS = [ '#57cb9d', '#e541a0', '#5ec961', '#7857cc', '#a3be37', '#cd6ddb', '#51a531', '#af3a99', '#487f24', '#647de2', '#c9b233', '#8753a5', '#e59a31', '#5a6bac', '#df6a28', '#5fa2da', '#d2442d', '#42c0c7', '#e22959', '#389051', '#e268a8', '#879936', '#c194dd', '#596d18', '#bb3668', '#41a386', '#ec516b', '#277257', '#bc3740', '#83b571', '#934270', '#beb96d', '#9a5a93', '#be9637', '#c174a0', '#367042', '#e57177', '#527436', '#ec95af', '#716615', '#974863', '#948948', '#98434a', '#666630', '#e1856f', '#95632e', '#b56364', '#d69e6c', '#a74c28', '#d98048', ]; function getNDifferentColors( n: number, groups: number, group: number ): Array<string> { const colors: Array<string> = []; const offset = groups * group; while (n) { colors.push(COLORS[(offset + n) % COLORS.length]); n--; } return colors; } function colorForDataset( ys: Array<GraphField>, graphType: GraphPanelInfoType | undefined, unique: boolean, valueLabels: Array<string>, field: string ): string | string[] { const colors = getNDifferentColors( ys.length > 1 ? ys.length : valueLabels.length, 1, 0 ); // This is the multiple Y-es case. Color needs to be consistent // across _field_. Multiple Y-es isn't a thing for pie graphs // though. if (ys.length > 1 && graphType !== 'pie') { // This keeps color consistent for a field name even as the order // of the field may change. const sortedFields = ys.map((y) => y.field).sort(); const index = sortedFields.indexOf(field); return colors[index]; } if (!unique) { return colors[0]; } const copyOfValueLabels = [...valueLabels]; // So we can sort this // Assign colors based on labels alphabetic order const colorsSortedByLabelAlphabeticOrder = copyOfValueLabels .sort() .map((label, i) => ({ label, color: colors[i] })); // Then resort based on label real order. This keeps colors // consistent for the same label even as the order of labels changes const colorsSortedByRealLabelOrder = colorsSortedByLabelAlphabeticOrder .sort((a, b) => valueLabels.indexOf(a.label) - valueLabels.indexOf(b.label)) .map((c) => c.color); return colorsSortedByRealLabelOrder; } export function GraphPanel({ panel, panels }: PanelBodyProps<GraphPanelInfo>) { const { state: { theme }, } = React.useContext(SettingsContext); const data = panel.resultMeta || new PanelResult(); const value = (data || {}).value || []; const ref = React.useRef(null); React.useEffect(() => { if (!ref || !value || !value.length) { return; } if (!Array.isArray(value)) { log.error( `Expected array input to graph, got (${typeof value}): ` + preview(value) ); return; } // Only doesn't exist in tests const parent = ref.current.closest('.panel-body'); let background = 'white'; if (parent) { const style = window.getComputedStyle(parent); background = style.getPropertyValue('background-color'); // TODO: don't hardcode this Chart.defaults.color = theme === 'light' ? 'black' : 'white'; } const ys = [...panel.graph.ys]; if (panel.graph.type === 'pie') { ys.reverse(); } const labels = value.map((d) => d[panel.graph.x]); const ctx = ref.current.getContext('2d'); const chart = new Chart(ctx, { plugins: [ { id: 'background-of-chart', // Pretty silly there's no builtin way to set a background color // https://stackoverflow.com/a/38493678/1507139 beforeDraw: function () { if (!ref || !ref.current) { return; } ctx.save(); ctx.fillStyle = background; ctx.fillRect(0, 0, ref.current.width, ref.current.height); ctx.restore(); }, }, ], options: { scales: ys.length === 1 ? { y: { title: { display: true, text: ys[0].label } } } : undefined, responsive: true, plugins: { legend: { title: { display: true, text: panel.name, }, labels: { // Hide legend unless there are multiple Y-es generateLabels: panel.graph.ys.length < 2 ? ((() => '') as any) : undefined, }, }, }, }, type: panel.graph.type, data: { labels, datasets: ys.map(({ field, label }) => { const backgroundColor = colorForDataset( ys, panel.graph.type, panel.graph.colors.unique, labels, field ); return { label, data: value.map((d) => +d[field]), backgroundColor, tooltip: { callbacks: panel.graph.type === 'pie' ? { label: (ctx: any) => { const reversedIndex = ys.length - ctx.datasetIndex - 1; // Explicitly do read from the not-reversed panel.graph.ys array. // This library stacks levels in reverse of what you'd expect. const serieses = panel.graph.ys.slice( 0, reversedIndex + 1 ); const labels = serieses.map( ({ label, field }) => `${label}: ${+value[ctx.dataIndex][field]}` ); labels.unshift(ctx.label); return labels; }, } : undefined, }, }; }), }, }); return () => chart.destroy(); }, [ ref.current, data, panel.name, panel.graph.x, panel.graph.ys, panel.graph.type, panel.graph.colors.unique, panel.graph.width, theme, ]); if (!value || !value.length) { return null; } return <canvas className={`canvas--${panel.graph.width}`} ref={ref} />; } export function GraphPanelDetails({ panel, panels, updatePanel, }: PanelDetailsProps<GraphPanelInfo>) { const data = (panels.find((p) => p.id === panel.graph.panelSource) || {}).resultMeta || new PanelResult(); React.useEffect(() => { if (panel.graph.ys.length) { return; } const fields = unusedFields( data?.shape, panel.graph.x, ...panel.graph.ys.map((y) => y.field) ); if (fields) { panel.graph.ys.push({ label: '', field: '' }); updatePanel(panel); } }); return ( <React.Fragment> <div className="flex"> <div> <FormGroup label="General"> <div className="form-row"> <PanelSourcePicker currentPanel={panel.id} panels={panels} value={panel.graph.panelSource} onChange={(value: string) => { panel.graph.panelSource = value; updatePanel(panel); }} /> </div> </FormGroup> <FormGroup label={panel.graph.type === 'pie' ? 'Slice' : 'X-Axis'}> <div className="form-row"> <FieldPicker label="Field" shape={data?.shape} value={panel.graph.x} onChange={(value: string) => { panel.graph.x = value; updatePanel(panel); }} /> </div> </FormGroup> <FormGroup label={ panel.graph.type === 'pie' ? 'Slice Size Series' : 'Y-Axis Series' } > {panel.graph.ys.map((y, i) => ( <div className="form-row form-row--multi vertical-align-center" key={y.field + i} > <FieldPicker used={[...panel.graph.ys.map((y) => y.field), panel.graph.x]} onDelete={() => { panel.graph.ys.splice(i, 1); updatePanel(panel); }} preferredDefaultType="number" label="Field" value={y.field} shape={data?.shape} onChange={(value: string) => { y.field = value; updatePanel(panel); }} labelValue={y.label} labelOnChange={(value: string) => { y.label = value; updatePanel(panel); }} /> </div> ))} <Button onClick={() => { panel.graph.ys.push({ label: '', field: '' }); updatePanel(panel); }} > Add Series </Button> </FormGroup> </div> <div> <FormGroup label="Display"> <div className="form-row"> <Select label="Graph Type" value={panel.graph.type} onChange={(value: string) => { panel.graph.type = value as GraphPanelInfoType; updatePanel(panel); }} > <option value="bar">Bar Chart</option> <option value="line">Line Chart</option> <option value="pie">Pie Chart</option> </Select> </div> <div className="form-row"> <Radio label="Unique Colors" value={String(panel.graph.colors.unique)} onChange={(value: string) => { panel.graph.colors.unique = value === 'true'; updatePanel(panel); }} options={[ { label: 'Yes', value: 'true' }, { label: 'No', value: 'false' }, ]} /> </div> <div className="form-row"> <Radio label="Width" value={panel.graph.width} onChange={(value: string) => { panel.graph.width = value as GraphPanelInfoWidth; updatePanel(panel); }} options={[ { label: 'Small', value: 'small' }, { label: 'Medium', value: 'medium' }, { label: 'Large', value: 'large' }, ]} /> </div> </FormGroup> </div> </div> </React.Fragment> ); } export const graphPanel: PanelUIDetails<GraphPanelInfo> = { icon: 'bar_chart', eval: evalGraphPanel, id: 'graph', label: 'Graph', details: GraphPanelDetails, body: GraphPanel, previewable: false, factory: () => new GraphPanelInfo(), hasStdout: false, info: null, dashboard: true, };
the_stack
import React, { Component, PureComponent, useState, useCallback, CSSProperties } from 'react'; import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { SortableContainer, SortableElement, arrayMove } from '../external/react-sortable-hoc' import classnames from 'classnames' import ContextMenuArea from './ContextMenuArea' import CharGrid from '../components/CharGrid' import * as framebuf from '../redux/editor' import * as toolbar from '../redux/toolbar' import * as screens from '../redux/screens' import * as selectors from '../redux/selectors' import * as screensSelectors from '../redux/screensSelectors' import { getSettingsCurrentColorPalette } from '../redux/settingsSelectors' import * as utils from '../utils' import * as fp from '../utils/fp' import { faPlus } from '@fortawesome/free-solid-svg-icons' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import styles from './FramebufferTabs.module.css' import { Framebuf, Rgb, Font, RootState } from '../redux/types'; interface NameInputDispatchProps { Toolbar: toolbar.PropsFromDispatch; } interface NameInputProps { name: string; onSubmit: (name: string) => void; onCancel: () => void; onBlur: () => void; } interface NameInputState { name: string; } // This class is a bit funky with how it disables/enables keyboard shortcuts // globally for the app while the input element has focus. Maybe there'd be a // better way to do this, but this seems to work. class NameInput_ extends Component<NameInputProps & NameInputDispatchProps, NameInputState> { state = { name: this.props.name } componentWillUnmount () { this.props.Toolbar.setShortcutsActive(true) } handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault() this.props.onSubmit(this.state.name) this.props.Toolbar.setShortcutsActive(true) } handleChange = (e: React.FormEvent<EventTarget>) => { let target = e.target as HTMLInputElement; this.setState({ name: target.value }) } handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Escape') { e.preventDefault() this.props.onCancel() this.props.Toolbar.setShortcutsActive(true) } } handleBlur = (_e: React.FormEvent<HTMLInputElement>) => { this.props.onBlur() this.props.Toolbar.setShortcutsActive(true) } handleFocus = (e: React.FormEvent<HTMLInputElement>) => { let target = e.target as HTMLInputElement; this.props.Toolbar.setShortcutsActive(false) target.select() } render () { return ( <div className={styles.tabNameEditor}> <form onSubmit={this.handleSubmit}> <input autoFocus onKeyDown={this.handleKeyDown} value={this.state.name} onChange={this.handleChange} onBlur={this.handleBlur} onFocus={this.handleFocus} type='text' size={14} /> </form> </div> ) } } const NameInput = connect( null, (dispatch) => { return { Toolbar: bindActionCreators(toolbar.Toolbar.actions, dispatch) } } )(NameInput_) interface NameEditorProps { name: string; onNameSave: (name: string) => void; } interface NameEditorState { editing: boolean; } class NameEditor extends Component<NameEditorProps, NameEditorState> { state = { editing: false } handleEditingClick = () => { this.setState({ editing: true }) } handleBlur = () => { this.setState({ editing: false}) } handleSubmit = (name: string) => { this.setState({ editing: false}) this.props.onNameSave(name) } handleCancel = () => { this.setState({ editing: false}) } render () { const nameElts = this.state.editing ? <NameInput name={this.props.name} onSubmit={this.handleSubmit} onBlur={this.handleBlur} onCancel={this.handleCancel} /> : <div className={styles.tabName} onClick={this.handleEditingClick}> {this.props.name} </div> return ( <div className={styles.tabNameContainer}> {nameElts} </div> ) } } function computeContainerSize(fb: Framebuf, maxHeight: number) { const pixWidth = fb.width * 8; const pixHeight = fb.height * 8; // TODO if height is bigger than maxHeight, need to scale differently // to fit the box. const s = maxHeight / pixHeight; return { divWidth: pixWidth * s, divHeight: maxHeight, scaleX: s, scaleY: s } } interface FramebufTabProps { id: number; active: boolean; framebufId: number; framebuf: Framebuf; colorPalette: Rgb[]; font: Font; setName: (name: string, framebufId: number) => void; onSetActiveTab: (id: number) => void; onDuplicateTab: (id: number) => void; onRemoveTab: (id: number) => void; }; class FramebufTab extends PureComponent<FramebufTabProps> { tabRef = React.createRef<HTMLDivElement>(); handleSelect = () => { this.props.onSetActiveTab(this.props.id) } handleMenuDuplicate = () => { this.props.onDuplicateTab(this.props.id) } handleMenuRemove = () => { this.props.onRemoveTab(this.props.id) } handleNameSave = (name: string) => { if (name !== '') { this.props.setName(name, this.props.framebufId) } } componentDidUpdate() { if (this.props.active && this.tabRef.current) { this.tabRef.current.scrollIntoView(); } } render () { const { width, height, framebuf, backgroundColor, borderColor } = this.props.framebuf const font = this.props.font const colorPalette = this.props.colorPalette const backg = utils.colorIndexToCssRgb(colorPalette, backgroundColor) const bord = utils.colorIndexToCssRgb(colorPalette, borderColor) const maxHeight = 25*2*1.5; const { divWidth, divHeight, scaleX, scaleY } = computeContainerSize(this.props.framebuf, maxHeight); const s = { width: divWidth, height: divHeight, backgroundColor: '#000', borderStyle: 'solid', borderWidth: '5px', borderColor: bord }; const scaleStyle: CSSProperties = { transform: `scale(${scaleX}, ${scaleY})`, transformOrigin: '0% 0%', imageRendering: 'pixelated' }; const menuItems = [ { label: "Duplicate", click: this.handleMenuDuplicate }, { label: "Remove", click: this.handleMenuRemove } ]; return ( <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', marginRight: '4px' }} ref={this.tabRef} > <ContextMenuArea menuItems={menuItems}> <div onClick={this.handleSelect} className={classnames(styles.tab, this.props.active ? styles.active : null)} style={s} > <div style={scaleStyle}> <CharGrid width={width} height={height} backgroundColor={backg} grid={false} framebuf={framebuf} font={font} colorPalette={colorPalette} /> </div> </div> </ContextMenuArea> <NameEditor name={fp.maybeDefault(this.props.framebuf.name, 'Untitled' as string)} onNameSave={this.handleNameSave} /> </div> ) } } const SortableFramebufTab = SortableElement((props: FramebufTabProps) => <FramebufTab {...props} /> ) const SortableTabList = SortableContainer((props: {children: any}) => { return ( <div className={styles.tabs}> {props.children} </div> ) }) type ScreenDimsProps = { dims: { width: number, height: number }; Toolbar: toolbar.PropsFromDispatch; }; type ScreenDimsEditProps = { stopEditing: () => void; }; function ScreenDimsEdit (props: ScreenDimsProps & ScreenDimsEditProps) { const { width, height } = props.dims; const [dimsText, setDimsText] = useState(`${width}x${height}`); const handleBlur = useCallback(() => { props.stopEditing(); }, []); const handleSubmit = useCallback((e: React.FormEvent) => { e.preventDefault(); props.stopEditing(); const numsRe = /^([0-9]+)x([0-9]+)/; const matches = numsRe.exec(dimsText); if (matches) { const width = Math.max(1, Math.min(1024, parseInt(matches[1]))); const height = Math.max(1, Math.min(1024, parseInt(matches[2]))); props.Toolbar.setNewScreenSize({ width, height }); } }, [dimsText]); const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => { setDimsText(e.target.value); }, []); const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === 'Escape') { props.stopEditing(); } }, []); const handleFocus = useCallback((e: React.FormEvent<HTMLInputElement>) => { let target = e.target as HTMLInputElement; props.Toolbar.setShortcutsActive(false); target.select(); }, []); return ( <div className={styles.tabNameEditor}> <form onSubmit={handleSubmit} > <input autoFocus type='text' pattern='[0-9]+x[0-9]+' title='Specify screen width x height (e.g., 40x25)' value={dimsText} onKeyDown={handleKeyDown} onBlur={handleBlur} onFocus={handleFocus} onChange={handleChange} /> </form> </div> ); } function ScreenDims (props: ScreenDimsProps) { const [editing, setEditing] = useState(false); const stopEditing = useCallback(() => { setEditing(false); props.Toolbar.setShortcutsActive(true); }, []); return ( <div className={styles.screenDimContainer} onClick={() => setEditing(true)} > {editing ? <ScreenDimsEdit {...props} stopEditing={stopEditing} /> : <div className={styles.screenDimText}>{props.dims.width}x{props.dims.height}</div>} </div> ); } function NewTabButton (props: { dims: { width: number, height: number }, onClick: () => void, Toolbar: toolbar.PropsFromDispatch }) { // onClick is not in FontAwesomeIcon props and don't know how to pass // it otherwise. const typingWorkaround = { onClick: props.onClick }; return ( <div className={classnames(styles.tab, styles.newScreen)}> <FontAwesomeIcon {...typingWorkaround} icon={faPlus} /> <ScreenDims dims={props.dims} Toolbar={props.Toolbar} /> </div> ) } interface FramebufferTabsDispatch { Screens: screens.PropsFromDispatch; Toolbar: toolbar.PropsFromDispatch; } interface FramebufferTabsProps { screens: number[]; activeScreen: number; colorPalette: Rgb[]; newScreenSize: { width: number, height: number }; getFramebufByIndex: (framebufId: number) => Framebuf | null; getFont: (framebuf: Framebuf) => { charset: string, font: Font }; setFramebufName: (name: string, framebufIndex: number) => void; } class FramebufferTabs_ extends Component<FramebufferTabsProps & FramebufferTabsDispatch> { handleActiveClick = (idx: number) => { this.props.Screens.setCurrentScreenIndex(idx) } handleNewTab = () => { this.props.Screens.newScreen() // Context menu eats the ctrl key up event, so force it to false this.props.Toolbar.setCtrlKey(false) } handleRemoveTab = (idx: number) => { this.props.Screens.removeScreen(idx) // Context menu eats the ctrl key up event, so force it to false this.props.Toolbar.setCtrlKey(false) } handleDuplicateTab = (idx: number) => { this.props.Screens.cloneScreen(idx) // Context menu eats the ctrl key up event, so force it to false this.props.Toolbar.setCtrlKey(false) } onSortEnd = (args: {oldIndex: number, newIndex: number}) => { this.props.Screens.setScreenOrder(arrayMove(this.props.screens, args.oldIndex, args.newIndex)) } render () { const lis = this.props.screens.map((framebufId, i) => { const framebuf = this.props.getFramebufByIndex(framebufId)! const { font } = this.props.getFont(framebuf); return ( <SortableFramebufTab key={framebufId} index={i} id={i} framebufId={framebufId} onSetActiveTab={this.handleActiveClick} onRemoveTab={this.handleRemoveTab} onDuplicateTab={this.handleDuplicateTab} framebuf={framebuf} active={i === this.props.activeScreen} font={font} colorPalette={this.props.colorPalette} setName={this.props.setFramebufName} /> ) }) return ( <div className={styles.tabHeadings}> <SortableTabList distance={5} axis='x' lockAxis='x' onSortEnd={this.onSortEnd} > {lis} <NewTabButton dims={this.props.newScreenSize} Toolbar={this.props.Toolbar} onClick={this.handleNewTab} /> </SortableTabList> </div> ) } } export default connect( (state: RootState) => { return { newScreenSize: state.toolbar.newScreenSize, activeScreen: screensSelectors.getCurrentScreenIndex(state), screens: screensSelectors.getScreens(state), getFramebufByIndex: (idx: number) => selectors.getFramebufByIndex(state, idx), getFont: (fb: Framebuf) => selectors.getFramebufFont(state, fb), colorPalette: getSettingsCurrentColorPalette(state) } }, (dispatch) => { return { Toolbar: toolbar.Toolbar.bindDispatch(dispatch), Screens: bindActionCreators(screens.actions, dispatch), setFramebufName: bindActionCreators(framebuf.actions.setName, dispatch) } } )(FramebufferTabs_)
the_stack
import * as path from "path"; import * as vscode from "vscode"; import { Logger } from "../logger/logger"; import { OutputChannel } from "../logger/outputChannel"; import { LocDictionary } from "../localizationDictionary"; import { INewProjectArgs } from "./newProjectInit"; import { IComponent } from "../espIdf/idfComponent/IdfComponent"; import { copy, ensureDir, readFile, writeJSON } from "fs-extra"; import * as utils from "../utils"; import { IExample } from "../examples/Example"; import { setCurrentSettingsInTemplate } from "./utils"; const locDictionary = new LocDictionary("NewProjectPanel"); export class NewProjectPanel { public static currentPanel: NewProjectPanel | undefined; public static createOrShow( extensionPath: string, newProjectArgs?: INewProjectArgs ) { const column = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : vscode.ViewColumn.One; if (NewProjectPanel.currentPanel) { NewProjectPanel.currentPanel.panel.reveal(column); } else { NewProjectPanel.currentPanel = new NewProjectPanel( extensionPath, newProjectArgs, column ); } } public static isCreatedAndHidden(): boolean { return ( NewProjectPanel.currentPanel && !NewProjectPanel.currentPanel.panel.visible ); } private static readonly viewType = "newProjectWizard"; private readonly panel: vscode.WebviewPanel; private extensionPath: string; private _disposables: vscode.Disposable[] = []; private constructor( extensionPath: string, newProjectArgs: INewProjectArgs, column: vscode.ViewColumn ) { this.extensionPath = extensionPath; const newProjectTitle = locDictionary.localize( "newProject.panelName", "New Project" ); let localResourceRoots: vscode.Uri[] = []; localResourceRoots.push( vscode.Uri.file(path.join(this.extensionPath, "dist", "views")) ); if (newProjectArgs.espAdfPath) { localResourceRoots.push(vscode.Uri.file(newProjectArgs.espAdfPath)); } if (newProjectArgs.espIdfPath) { localResourceRoots.push(vscode.Uri.file(newProjectArgs.espIdfPath)); } if (newProjectArgs.espMdfPath) { localResourceRoots.push(vscode.Uri.file(newProjectArgs.espMdfPath)); } this.panel = vscode.window.createWebviewPanel( NewProjectPanel.viewType, newProjectTitle, column, { enableScripts: true, retainContextWhenHidden: true, localResourceRoots, } ); this.panel.iconPath = vscode.Uri.file( path.join(extensionPath, "media", "espressif_icon.png") ); const scriptPath = this.panel.webview.asWebviewUri( vscode.Uri.file( path.join(this.extensionPath, "dist", "views", "newProject-bundle.js") ) ); this.panel.webview.html = this.createHtml(scriptPath); const containerPath = process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME; this.panel.webview.onDidReceiveMessage(async (message) => { switch (message.command) { case "createProject": if ( message.components && message.containerFolder && message.openOcdConfigFiles && message.port && message.projectName && message.target && message.template ) { this.createProject( message.components, message.target, message.openOcdConfigFiles, message.port, message.containerFolder, message.projectName, message.template ); } break; case "getTemplateDetail": if (message.path) { await this.getTemplateDetail(message.path); } break; case "loadComponent": let selectedFolder = await this.openFolder(); if (selectedFolder) { const newComponent: IComponent = { name: path.basename(selectedFolder), path: selectedFolder, }; this.panel.webview.postMessage({ command: "addComponentPath", component: newComponent, }); } break; case "openProjectDirectory": let selectedProjectDir = await this.openFolder(); if (selectedProjectDir) { this.panel.webview.postMessage({ command: "setContainerDirectory", projectDirectory: selectedProjectDir, }); } break; case "requestInitValues": if ( newProjectArgs && newProjectArgs.targetList && newProjectArgs.targetList.length > 0 && newProjectArgs.serialPortList && newProjectArgs.serialPortList.length > 0 ) { const defConfigFiles = newProjectArgs.boards && newProjectArgs.boards.length > 0 ? newProjectArgs.boards[0].configFiles : newProjectArgs.targetList[0].configFiles; this.panel.webview.postMessage({ boards: newProjectArgs.boards, command: "initialLoad", containerDirectory: containerPath, projectName: "project-name", serialPortList: newProjectArgs.serialPortList, targetList: newProjectArgs.targetList, openOcdConfigFiles: defConfigFiles, templates: newProjectArgs.templates, }); } break; default: break; } }); this.panel.onDidDispose( () => { NewProjectPanel.currentPanel = undefined; }, null, this._disposables ); } private async createProject( components: IComponent[], idfTarget: string, openOcdConfigs: string, port: string, projectDirectory: string, projectName: string, template: IExample ) { const newProjectPath = path.join(projectDirectory, projectName); let isSkipped = false; await vscode.window.withProgress( { cancellable: true, location: vscode.ProgressLocation.Notification, title: "ESP-IDF: Create project", }, async ( progress: vscode.Progress<{ message: string; increment: number }>, token: vscode.CancellationToken ) => { try { const projectDirExists = await utils.dirExistPromise( projectDirectory ); if (!projectDirExists) { vscode.window.showInformationMessage( "Project directory doesn't exists." ); this.panel.webview.postMessage({ command: "goToBeginning", }); isSkipped = true; return; } const projectNameExists = await utils.dirExistPromise(newProjectPath); if (projectNameExists) { const overwriteProject = await vscode.window.showInformationMessage( `${newProjectPath} already exists. Overwrite content?`, "Yes", "No" ); if ( typeof overwriteProject === "undefined" || overwriteProject === "No" ) { isSkipped = true; return; } } await ensureDir(newProjectPath, { mode: 0o775 }); if (template && template.path !== "") { await utils.copyFromSrcProject(template.path, newProjectPath); } else { const boilerplatePath = path.join( this.extensionPath, "templates", "boilerplate" ); await utils.copyFromSrcProject(boilerplatePath, newProjectPath); } await utils.updateProjectNameInCMakeLists( newProjectPath, projectName ); const settingsJsonPath = path.join( newProjectPath, ".vscode", "settings.json" ); const settingsJson = await setCurrentSettingsInTemplate( settingsJsonPath, idfTarget, openOcdConfigs, port ); await writeJSON(settingsJsonPath, settingsJson, { spaces: vscode.workspace.getConfiguration().get("editor.tabSize") || 2, }); if (components && components.length > 0) { const componentsPath = path.join(newProjectPath, "components"); await ensureDir(componentsPath, { mode: 0o775 }); for (const comp of components) { const doesComponentExists = await utils.dirExistPromise( comp.path ); if (doesComponentExists) { const compPath = path.join(componentsPath, comp.name); await ensureDir(compPath, { mode: 0o775 }); await copy(comp.path, compPath); } else { const msg = `Component ${comp.name} path: ${comp.path} doesn't exist. Ignoring in new project...`; Logger.info(msg); OutputChannel.appendLine(msg); } } } } catch (error) { Logger.errorNotify(error.message, error); } } ); if (isSkipped) { return; } const projectCreatedMsg = `Project ${projectName} has been created. Open project in a new window?`; const openProjectChoice = await vscode.window.showInformationMessage( projectCreatedMsg, "Yes", "No" ); if (openProjectChoice && openProjectChoice === "Yes") { vscode.commands.executeCommand( "vscode.openFolder", vscode.Uri.file(newProjectPath), true ); } } private async openFolder() { const selectedFolder = await vscode.window.showOpenDialog({ canSelectFolders: true, canSelectFiles: false, canSelectMany: false, }); if (selectedFolder && selectedFolder.length > 0) { return selectedFolder[0].fsPath; } } private async getTemplateDetail(projectPath: string) { try { const pathToUse = vscode.Uri.file(path.join(projectPath, "README.md")); const readMeContent = await readFile(pathToUse.fsPath); const contentStr = utils.markdownToWebviewHtml( readMeContent.toString(), projectPath, this.panel ); this.panel.webview.postMessage({ command: "setExampleDetail", templateDetail: contentStr, }); } catch (error) { this.panel.webview.postMessage({ command: "set_example_detail", templateDetail: "No README.md available for this project.", }); } } private createHtml(scriptPath: vscode.Uri): string { return `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ESP-IDF Project</title> </head> <body> <div id="app"></div> </body> <script src="${scriptPath}"></script> </html>`; } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/configurationOperationsMappers"; import * as Parameters from "../models/parameters"; import { IotHubGatewayServiceAPIsContext } from "../iotHubGatewayServiceAPIsContext"; /** Class representing a ConfigurationOperations. */ export class ConfigurationOperations { private readonly client: IotHubGatewayServiceAPIsContext; /** * Create a ConfigurationOperations. * @param {IotHubGatewayServiceAPIsContext} client Reference to the service client. */ constructor(client: IotHubGatewayServiceAPIsContext) { this.client = client; } /** * Gets a configuration on the IoT Hub for automatic device/module management. * @param id The unique identifier of the configuration. * @param [options] The optional parameters * @returns Promise<Models.ConfigurationGetResponse> */ get(id: string, options?: msRest.RequestOptionsBase): Promise<Models.ConfigurationGetResponse>; /** * @param id The unique identifier of the configuration. * @param callback The callback */ get(id: string, callback: msRest.ServiceCallback<Models.Configuration>): void; /** * @param id The unique identifier of the configuration. * @param options The optional parameters * @param callback The callback */ get(id: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Configuration>): void; get(id: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Configuration>, callback?: msRest.ServiceCallback<Models.Configuration>): Promise<Models.ConfigurationGetResponse> { return this.client.sendOperationRequest( { id, options }, getOperationSpec, callback) as Promise<Models.ConfigurationGetResponse>; } /** * Creates or updates a configuration on the IoT Hub for automatic device/module management. * Configuration identifier and Content cannot be updated. * @param id The unique identifier of the configuration. * @param configuration The configuration to be created or updated. * @param [options] The optional parameters * @returns Promise<Models.ConfigurationCreateOrUpdateResponse> */ createOrUpdate(id: string, configuration: Models.Configuration, options?: Models.ConfigurationCreateOrUpdateOptionalParams): Promise<Models.ConfigurationCreateOrUpdateResponse>; /** * @param id The unique identifier of the configuration. * @param configuration The configuration to be created or updated. * @param callback The callback */ createOrUpdate(id: string, configuration: Models.Configuration, callback: msRest.ServiceCallback<Models.Configuration>): void; /** * @param id The unique identifier of the configuration. * @param configuration The configuration to be created or updated. * @param options The optional parameters * @param callback The callback */ createOrUpdate(id: string, configuration: Models.Configuration, options: Models.ConfigurationCreateOrUpdateOptionalParams, callback: msRest.ServiceCallback<Models.Configuration>): void; createOrUpdate(id: string, configuration: Models.Configuration, options?: Models.ConfigurationCreateOrUpdateOptionalParams | msRest.ServiceCallback<Models.Configuration>, callback?: msRest.ServiceCallback<Models.Configuration>): Promise<Models.ConfigurationCreateOrUpdateResponse> { return this.client.sendOperationRequest( { id, configuration, options }, createOrUpdateOperationSpec, callback) as Promise<Models.ConfigurationCreateOrUpdateResponse>; } /** * Deletes a configuration on the IoT Hub for automatic device/module management. * @param id The unique identifier of the configuration. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(id: string, options?: Models.ConfigurationDeleteMethodOptionalParams): Promise<msRest.RestResponse>; /** * @param id The unique identifier of the configuration. * @param callback The callback */ deleteMethod(id: string, callback: msRest.ServiceCallback<void>): void; /** * @param id The unique identifier of the configuration. * @param options The optional parameters * @param callback The callback */ deleteMethod(id: string, options: Models.ConfigurationDeleteMethodOptionalParams, callback: msRest.ServiceCallback<void>): void; deleteMethod(id: string, options?: Models.ConfigurationDeleteMethodOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { id, options }, deleteMethodOperationSpec, callback); } /** * Gets configurations on the IoT Hub for automatic device/module management. Pagination is not * supported. * @param [options] The optional parameters * @returns Promise<Models.ConfigurationGetConfigurationsResponse> */ getConfigurations(options?: Models.ConfigurationGetConfigurationsOptionalParams): Promise<Models.ConfigurationGetConfigurationsResponse>; /** * @param callback The callback */ getConfigurations(callback: msRest.ServiceCallback<Models.Configuration[]>): void; /** * @param options The optional parameters * @param callback The callback */ getConfigurations(options: Models.ConfigurationGetConfigurationsOptionalParams, callback: msRest.ServiceCallback<Models.Configuration[]>): void; getConfigurations(options?: Models.ConfigurationGetConfigurationsOptionalParams | msRest.ServiceCallback<Models.Configuration[]>, callback?: msRest.ServiceCallback<Models.Configuration[]>): Promise<Models.ConfigurationGetConfigurationsResponse> { return this.client.sendOperationRequest( { options }, getConfigurationsOperationSpec, callback) as Promise<Models.ConfigurationGetConfigurationsResponse>; } /** * Validates target condition and custom metric queries for a configuration on the IoT Hub. * @param input The configuration for target condition and custom metric queries. * @param [options] The optional parameters * @returns Promise<Models.ConfigurationTestQueriesResponse> */ testQueries(input: Models.ConfigurationQueriesTestInput, options?: msRest.RequestOptionsBase): Promise<Models.ConfigurationTestQueriesResponse>; /** * @param input The configuration for target condition and custom metric queries. * @param callback The callback */ testQueries(input: Models.ConfigurationQueriesTestInput, callback: msRest.ServiceCallback<Models.ConfigurationQueriesTestResponse>): void; /** * @param input The configuration for target condition and custom metric queries. * @param options The optional parameters * @param callback The callback */ testQueries(input: Models.ConfigurationQueriesTestInput, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConfigurationQueriesTestResponse>): void; testQueries(input: Models.ConfigurationQueriesTestInput, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConfigurationQueriesTestResponse>, callback?: msRest.ServiceCallback<Models.ConfigurationQueriesTestResponse>): Promise<Models.ConfigurationTestQueriesResponse> { return this.client.sendOperationRequest( { input, options }, testQueriesOperationSpec, callback) as Promise<Models.ConfigurationTestQueriesResponse>; } /** * Applies the configuration content to an edge device. * @param id The unique identifier of the edge device. * @param content The configuration content. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ applyOnEdgeDevice(id: string, content: Models.ConfigurationContent, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param id The unique identifier of the edge device. * @param content The configuration content. * @param callback The callback */ applyOnEdgeDevice(id: string, content: Models.ConfigurationContent, callback: msRest.ServiceCallback<void>): void; /** * @param id The unique identifier of the edge device. * @param content The configuration content. * @param options The optional parameters * @param callback The callback */ applyOnEdgeDevice(id: string, content: Models.ConfigurationContent, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; applyOnEdgeDevice(id: string, content: Models.ConfigurationContent, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { id, content, options }, applyOnEdgeDeviceOperationSpec, callback); } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "configurations/{id}", urlParameters: [ Parameters.id ], queryParameters: [ Parameters.apiVersion ], responses: { 200: { bodyMapper: Mappers.Configuration }, default: {} }, serializer }; const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "configurations/{id}", urlParameters: [ Parameters.id ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.ifMatch ], requestBody: { parameterPath: "configuration", mapper: { ...Mappers.Configuration, required: true } }, responses: { 200: { bodyMapper: Mappers.Configuration }, 201: { bodyMapper: Mappers.Configuration }, default: {} }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "configurations/{id}", urlParameters: [ Parameters.id ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.ifMatch ], responses: { 204: {}, default: {} }, serializer }; const getConfigurationsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "configurations", queryParameters: [ Parameters.top, Parameters.apiVersion ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "Configuration" } } } } }, default: {} }, serializer }; const testQueriesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "configurations/testQueries", queryParameters: [ Parameters.apiVersion ], requestBody: { parameterPath: "input", mapper: { ...Mappers.ConfigurationQueriesTestInput, required: true } }, responses: { 200: { bodyMapper: Mappers.ConfigurationQueriesTestResponse }, default: {} }, serializer }; const applyOnEdgeDeviceOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "devices/{id}/applyConfigurationContent", urlParameters: [ Parameters.id ], queryParameters: [ Parameters.apiVersion ], requestBody: { parameterPath: "content", mapper: { ...Mappers.ConfigurationContent, required: true } }, responses: { 204: {}, default: {} }, serializer };
the_stack
var Assets = {}; var images = {}; var createjs = window["createjs"]; var ss = {}; (function(lib: any, img, cjs, ss) { var p; // shortcut to reference prototypes // library properties: lib.properties = { width: 550, height: 400, fps: 24, color: "#999999", manifest: [] }; // symbols: (lib.triangle = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics .beginFill("#FFFFFF") .beginStroke() .moveTo(-0.7, -27.8) .lineTo(32, 27.1) .lineTo(-32, 27.8) .closePath(); this.shape.setTransform(0, -7); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-32, -34.8, 64, 55.7); (lib.star_10 = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics .beginFill("#FFFFFF") .beginStroke() .moveTo(-4.3, 18.3) .lineTo(-19.9, 29.3) .lineTo(-14.1, 10.3) .lineTo(-32, 10.3) .lineTo(-19.7, 0.7) .lineTo(-31.2, -8.7) .lineTo(-15.2, -8.8) .lineTo(-21.7, -26.4) .lineTo(-5.4, -16.4) .lineTo(-0.2, -31.8) .lineTo(4.4, -17.6) .lineTo(17.8, -27.4) .lineTo(13.1, -8.5) .lineTo(30.3, -8.1) .lineTo(19.9, 0.1) .lineTo(32, 8.4) .lineTo(12.8, 9.5) .lineTo(18.2, 29.8) .lineTo(4.9, 20) .lineTo(1.4, 31.8) .closePath(); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-32, -31.7, 64, 63.6); (lib.star = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics .beginFill("#FFFFFF") .beginStroke() .moveTo(-0.2, 17.3) .lineTo(-20.2, 31.5) .lineTo(-13, 7.4) .lineTo(-32, -8) .lineTo(-7.8, -8.4) .lineTo(0.3, -32) .lineTo(8, -8.2) .lineTo(32, -7.4) .lineTo(12.8, 7.5) .lineTo(19.4, 32) .closePath(); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-32, -32, 64, 64); (lib.square = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics .beginFill() .beginStroke("#FFFFFF") .setStrokeStyle(8, 1, 1) .moveTo(-32, -32) .lineTo(32, -32) .lineTo(32, 32) .lineTo(-32, 32) .closePath(); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-36, -36, 72, 72); (lib.reverse_blur_circle = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics .beginFill() .beginStroke("#FFFFFF") .setStrokeStyle(8, 1, 1) .moveTo(32, 0) .curveTo(32, 13.2, 22.6, 22.6) .curveTo(13.3, 32, 0, 32) .curveTo(-13.2, 32, -22.7, 22.6) .curveTo(-32, 13.2, -32, 0) .curveTo(-32, -13.3, -22.7, -22.7) .curveTo(-13.2, -32, 0, -32) .curveTo(13.3, -32, 22.6, -22.7) .curveTo(32, -13.3, 32, 0) .closePath(); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-36, -36, 72, 72); (lib.kirakira2 = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics .beginFill("#FFFFFF") .beginStroke() .moveTo(-4, 9.5) .curveTo(-7.8, 0, -13.4, -0.1) .curveTo(-7.8, -0.2, -4, -9.9) .curveTo(-0.1, -19.2, 0, -32) .curveTo(0.1, -19.2, 4, -9.9) .curveTo(8, -0.2, 13.4, -0.1) .curveTo(8, 0, 4, 9.5) .curveTo(0.1, 19, 0, 32) .curveTo(-0.1, 19, -4, 9.5) .closePath(); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-13.4, -32, 26.8, 64); (lib.kirakira = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics .beginFill("#FFFFFF") .beginStroke() .moveTo(-9.6, 9.3) .curveTo(-18.9, 0, -32, -0.1) .curveTo(-18.9, -0.2, -9.6, -9.6) .curveTo(-0.2, -19, -0.1, -32) .curveTo(0, -19, 9.4, -9.6) .curveTo(18.9, -0.2, 32, -0.1) .curveTo(18.9, 0, 9.4, 9.3) .curveTo(0, 18.8, -0.1, 32) .curveTo(-0.2, 18.8, -9.6, 9.3) .closePath(); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-32, -32, 64, 64); (lib.heart = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics .beginFill("#FFFFFF") .beginStroke() .moveTo(-20.2, 10) .lineTo(-24.8, 3.5) .curveTo(-27, 0.1, -28.5, -3.1) .curveTo(-30.1, -6.4, -31.1, -9.5) .curveTo(-32, -13, -32, -16) .curveTo(-32, -19.7, -30.4, -22.7) .curveTo(-29.1, -25.4, -26.6, -27.4) .curveTo(-24, -29.1, -21, -30.1) .curveTo(-18.1, -31.1, -15, -31.1) .curveTo(-11.7, -31.1, -8.8, -29.9) .curveTo(-6.4, -29, -4.5, -27.4) .curveTo(-3, -25.9, -1.7, -23.9) .lineTo(0, -20.8) .lineTo(1.7, -23.9) .curveTo(3, -25.9, 4.5, -27.4) .curveTo(6.6, -29.1, 8.8, -29.9) .curveTo(11.7, -31.1, 15.2, -31.1) .curveTo(18.4, -31.1, 21.3, -30.1) .curveTo(24.2, -29.1, 26.7, -27.2) .curveTo(29.1, -25.3, 30.5, -22.6) .curveTo(32, -19.7, 32, -16.1) .curveTo(32, -13.3, 31, -9.7) .curveTo(30.2, -6.5, 28.5, -3.2) .curveTo(27.1, 0, 24.9, 3.3) .lineTo(20.3, 9.7) .curveTo(13.4, 17.7, 9.7, 21.6) .lineTo(0, 31) .curveTo(-13.6, 18.3, -20.2, 10) .closePath(); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-32, -31, 64, 62.1); (lib.flower = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics .beginFill("#FFFFFF") .beginStroke() .moveTo(4, 27.3) .curveTo(0.5, 23.7, 0.5, 18.9) .lineTo(0.5, 15.2) .lineTo(-0.5, 15.2) .lineTo(-0.7, 18.9) .curveTo(-0.9, 24, -4.1, 27.6) .curveTo(-7.4, 31.1, -12.1, 31.1) .curveTo(-17, 31.1, -20.8, 27.5) .curveTo(-24.7, 23.7, -24.7, 19.1) .curveTo(-24.7, 15.3, -22.2, 12.1) .curveTo(-19.7, 8.8, -16.1, 7.7) .lineTo(-12.5, 6.4) .lineTo(-12.7, 5.8) .lineTo(-13, 5.4) .lineTo(-16.5, 6.6) .lineTo(-20.2, 7.1) .curveTo(-25.3, 7.1, -28.7, 4) .curveTo(-32, 0.7, -32, -4.1) .curveTo(-32, -9.4, -28.7, -13) .curveTo(-25.5, -16.8, -20.6, -16.8) .curveTo(-17.8, -16.8, -15, -15.4) .curveTo(-12.2, -14, -10.5, -11.6) .lineTo(-8.4, -8.7) .lineTo(-8, -8.8) .lineTo(-7.4, -9.3) .lineTo(-9.6, -12.2) .curveTo(-10.7, -14, -11.3, -15.8) .curveTo(-11.9, -17.9, -12, -19.9) .curveTo(-12, -24.7, -8.5, -28) .curveTo(-5.3, -31.1, -0.1, -31.1) .curveTo(5.2, -31.1, 8.5, -28) .curveTo(11.7, -24.7, 11.8, -19.9) .curveTo(11.7, -17.7, 11.2, -15.7) .curveTo(10.7, -13.8, 9.5, -12.2) .lineTo(7.4, -9.3) .lineTo(7.8, -9) .lineTo(8.2, -8.7) .lineTo(10.5, -11.6) .curveTo(12.2, -14, 14.8, -15.4) .curveTo(17.6, -16.8, 20.4, -16.8) .curveTo(25.3, -16.8, 28.5, -13) .curveTo(32, -9.4, 32, -4.1) .curveTo(32, 0.8, 28.5, 4) .curveTo(25.3, 7.1, 20, 7.1) .lineTo(16.4, 6.6) .lineTo(12.9, 5.5) .curveTo(12.8, 5.6, 12.8, 5.6) .curveTo(12.7, 5.7, 12.7, 5.7) .curveTo(12.7, 5.8, 12.7, 5.8) .curveTo(12.7, 5.9, 12.7, 6) .lineTo(12.5, 6.4) .lineTo(15.9, 7.7) .curveTo(19.7, 9.1, 22.1, 12.2) .curveTo(24.5, 15.3, 24.5, 19.1) .curveTo(24.5, 23.7, 20.8, 27.5) .curveTo(16.9, 31.1, 11.9, 31.1) .curveTo(7.4, 31.1, 4, 27.3) .closePath() .moveTo(-7.7, -5.9) .curveTo(-10.9, -2.7, -10.9, 1.8) .curveTo(-10.9, 6.3, -7.7, 9.4) .curveTo(-4.6, 12.5, -0.1, 12.5) .curveTo(4.4, 12.5, 7.6, 9.4) .curveTo(10.6, 6.3, 10.6, 1.8) .curveTo(10.6, -2.7, 7.6, -5.9) .curveTo(4.4, -9, -0.1, -9) .curveTo(-4.6, -9, -7.7, -5.9) .closePath(); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-32, -31, 64, 62.2); (lib.circle = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics .beginFill("#FFFFFF") .beginStroke() .drawEllipse(-10.8, -10.8, 21.7, 21.7); this.shape.setTransform(0, 0, 2.949, 2.949); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-32, -32, 64, 64); (lib.blur_circle = function() { this.initialize(); // レイヤー 1 this.shape = new cjs.Shape(); this.shape.graphics .beginRadialGradientFill( ["#FFFFFF", "rgba(255,255,255,0)"], [0, 1], 0, 0, 0, 0, 0, 11 ) .beginStroke() .drawEllipse(-10.8, -10.8, 21.7, 21.7); this.shape.setTransform(0, 0, 3, 3); this.addChild(this.shape); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(-32.5, -32.5, 65.1, 65.1); // stage content: (lib.assetshapes = function() { this.initialize(); // triangle this.instance = new lib.triangle(); this.instance.setTransform(323.6, 39.6); // square this.instance_1 = new lib.square(); this.instance_1.setTransform(518, 151.5); // kirakira2 this.instance_2 = new lib.kirakira2(); this.instance_2.setTransform(420.8, 32.6); // kirakira this.instance_3 = new lib.kirakira(); this.instance_3.setTransform(32, 151.5); // flower this.instance_4 = new lib.flower(); this.instance_4.setTransform(396.5, 151.5); // star_10 this.instance_5 = new lib.star_10(); this.instance_5.setTransform(518, 32.6); // star this.instance_6 = new lib.star(); this.instance_6.setTransform(275, 151.5); // circle this.instance_7 = new lib.circle(); this.instance_7.setTransform(226.4, 32.6); // reverse_blur_circle this.instance_8 = new lib.reverse_blur_circle(); this.instance_8.setTransform(153.5, 151.5); // blur_circle this.instance_9 = new lib.blur_circle(); this.instance_9.setTransform(129.2, 32.6); // heart this.instance_10 = new lib.heart(); this.instance_10.setTransform(32, 32.6); this.addChild( this.instance_10, this.instance_9, this.instance_8, this.instance_7, this.instance_6, this.instance_5, this.instance_4, this.instance_3, this.instance_2, this.instance_1, this.instance ); }).prototype = p = new cjs.Container(); p.nominalBounds = new cjs.Rectangle(275, 200, 554, 187.5); })( (Assets = Assets || {}), (images = images || {}), (createjs = createjs || {}), (ss = ss || {}) ); export { Assets };
the_stack
import { emptyArray } from "../platform.js"; import { ArrayObserver, Splice, SpliceStrategy, SpliceStrategySupport, } from "./arrays.js"; const enum Edit { leave = 0, update = 1, add = 2, delete = 3, } // Note: This function is *based* on the computation of the Levenshtein // "edit" distance. The one change is that "updates" are treated as two // edits - not one. With Array splices, an update is really a delete // followed by an add. By retaining this, we optimize for "keeping" the // maximum array items in the original array. For example: // // 'xxxx123' to '123yyyy' // // With 1-edit updates, the shortest path would be just to update all seven // characters. With 2-edit updates, we delete 4, leave 3, and add 4. This // leaves the substring '123' intact. function calcEditDistances( current: any[], currentStart: number, currentEnd: number, old: any[], oldStart: number, oldEnd: number ): any[] { // "Deletion" columns const rowCount = oldEnd - oldStart + 1; const columnCount = currentEnd - currentStart + 1; const distances = new Array(rowCount); let north; let west; // "Addition" rows. Initialize null column. for (let i = 0; i < rowCount; ++i) { distances[i] = new Array(columnCount); distances[i][0] = i; } // Initialize null row for (let j = 0; j < columnCount; ++j) { distances[0][j] = j; } for (let i = 1; i < rowCount; ++i) { for (let j = 1; j < columnCount; ++j) { if (current[currentStart + j - 1] === old[oldStart + i - 1]) { distances[i][j] = distances[i - 1][j - 1]; } else { north = distances[i - 1][j] + 1; west = distances[i][j - 1] + 1; distances[i][j] = north < west ? north : west; } } } return distances; } // This starts at the final weight, and walks "backward" by finding // the minimum previous weight recursively until the origin of the weight // matrix. function spliceOperationsFromEditDistances(distances: number[][]): number[] { let i = distances.length - 1; let j = distances[0].length - 1; let current = distances[i][j]; const edits: number[] = []; while (i > 0 || j > 0) { if (i === 0) { edits.push(Edit.add); j--; continue; } if (j === 0) { edits.push(Edit.delete); i--; continue; } const northWest = distances[i - 1][j - 1]; const west = distances[i - 1][j]; const north = distances[i][j - 1]; let min; if (west < north) { min = west < northWest ? west : northWest; } else { min = north < northWest ? north : northWest; } if (min === northWest) { if (northWest === current) { edits.push(Edit.leave); } else { edits.push(Edit.update); current = northWest; } i--; j--; } else if (min === west) { edits.push(Edit.delete); i--; current = west; } else { edits.push(Edit.add); j--; current = north; } } return edits.reverse(); } function sharedPrefix(current: any[], old: any[], searchLength: number): number { for (let i = 0; i < searchLength; ++i) { if (current[i] !== old[i]) { return i; } } return searchLength; } function sharedSuffix(current: any[], old: any[], searchLength: number): number { let index1 = current.length; let index2 = old.length; let count = 0; while (count < searchLength && current[--index1] === old[--index2]) { count++; } return count; } function intersect(start1: number, end1: number, start2: number, end2: number): number { // Disjoint if (end1 < start2 || end2 < start1) { return -1; } // Adjacent if (end1 === start2 || end2 === start1) { return 0; } // Non-zero intersect, span1 first if (start1 < start2) { if (end1 < end2) { return end1 - start2; // Overlap } return end2 - start2; // Contained } // Non-zero intersect, span2 first if (end2 < end1) { return end2 - start1; // Overlap } return end1 - start1; // Contained } /** * @remarks * Lacking individual splice mutation information, the minimal set of * splices can be synthesized given the previous state and final state of an * array. The basic approach is to calculate the edit distance matrix and * choose the shortest path through it. * * Complexity: O(l * p) * l: The length of the current array * p: The length of the old array */ function calc( current: unknown[], currentStart: number, currentEnd: number, old: unknown[], oldStart: number, oldEnd: number ): Splice[] { let prefixCount = 0; let suffixCount = 0; const minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); if (currentStart === 0 && oldStart === 0) { prefixCount = sharedPrefix(current, old, minLength); } if (currentEnd === current.length && oldEnd === old.length) { suffixCount = sharedSuffix(current, old, minLength - prefixCount); } currentStart += prefixCount; oldStart += prefixCount; currentEnd -= suffixCount; oldEnd -= suffixCount; if (currentEnd - currentStart === 0 && oldEnd - oldStart === 0) { return emptyArray as any; } if (currentStart === currentEnd) { const splice = new Splice(currentStart, [], 0); while (oldStart < oldEnd) { splice.removed.push(old[oldStart++]); } return [splice]; } else if (oldStart === oldEnd) { return [new Splice(currentStart, [], currentEnd - currentStart)]; } const ops = spliceOperationsFromEditDistances( calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd) ); const splices: Splice[] = []; let splice: Splice | undefined = void 0; let index = currentStart; let oldIndex = oldStart; for (let i = 0; i < ops.length; ++i) { switch (ops[i]) { case Edit.leave: if (splice !== void 0) { splices.push(splice); splice = void 0; } index++; oldIndex++; break; case Edit.update: if (splice === void 0) { splice = new Splice(index, [], 0); } splice.addedCount++; index++; splice.removed.push(old[oldIndex]); oldIndex++; break; case Edit.add: if (splice === void 0) { splice = new Splice(index, [], 0); } splice.addedCount++; index++; break; case Edit.delete: if (splice === void 0) { splice = new Splice(index, [], 0); } splice.removed.push(old[oldIndex]); oldIndex++; break; // no default } } if (splice !== void 0) { splices.push(splice); } return splices; } function merge(splice: Splice, splices: Splice[]): void { let inserted = false; let insertionOffset = 0; for (let i = 0; i < splices.length; i++) { const current = splices[i]; current.index += insertionOffset; if (inserted) { continue; } const intersectCount = intersect( splice.index, splice.index + splice.removed.length, current.index, current.index + current.addedCount ); if (intersectCount >= 0) { // Merge the two splices splices.splice(i, 1); i--; insertionOffset -= current.addedCount - current.removed.length; splice.addedCount += current.addedCount - intersectCount; const deleteCount = splice.removed.length + current.removed.length - intersectCount; if (!splice.addedCount && !deleteCount) { // merged splice is a noop. discard. inserted = true; } else { let currentRemoved = current.removed; if (splice.index < current.index) { // some prefix of splice.removed is prepended to current.removed. const prepend = splice.removed.slice(0, current.index - splice.index); prepend.push(...currentRemoved); currentRemoved = prepend; } if ( splice.index + splice.removed.length > current.index + current.addedCount ) { // some suffix of splice.removed is appended to current.removed. const append = splice.removed.slice( current.index + current.addedCount - splice.index ); currentRemoved.push(...append); } splice.removed = currentRemoved; if (current.index < splice.index) { splice.index = current.index; } } } else if (splice.index < current.index) { // Insert splice here. inserted = true; splices.splice(i, 0, splice); i++; const offset = splice.addedCount - splice.removed.length; current.index += offset; insertionOffset += offset; } } if (!inserted) { splices.push(splice); } } function project(array: unknown[], changes: Splice[]): Splice[] { let splices: Splice[] = []; const initialSplices: Splice[] = []; for (let i = 0, ii = changes.length; i < ii; i++) { merge(changes[i], initialSplices); } for (let i = 0, ii = initialSplices.length; i < ii; ++i) { const splice = initialSplices[i]; if (splice.addedCount === 1 && splice.removed.length === 1) { if (splice.removed[0] !== array[splice.index]) { splices.push(splice); } continue; } splices = splices.concat( calc( array, splice.index, splice.index + splice.addedCount, splice.removed, 0, splice.removed.length ) ); } return splices; } /** * A SpliceStrategy that attempts to merge all splices into the minimal set of * splices needed to represent the change from the old array to the new array. * @public */ export const mergeSpliceStrategy: SpliceStrategy = Object.freeze({ support: SpliceStrategySupport.optimized, normalize( previous: unknown[] | undefined, current: unknown[], changes: Splice[] | undefined ): readonly Splice[] { if (previous === void 0) { if (changes === void 0) { return emptyArray; } return changes.length > 1 ? project(current, changes) : changes; } return calc(current, 0, current.length, previous, 0, previous.length); }, pop( array: any[], observer: ArrayObserver, pop: typeof Array.prototype.pop, args: any[] ) { const notEmpty = array.length > 0; const result = pop.apply(array, args); if (notEmpty) { observer.addSplice(new Splice(array.length, [result], 0)); } return result; }, push( array: any[], observer: ArrayObserver, push: typeof Array.prototype.push, args: any[] ): any { const result = push.apply(array, args); observer.addSplice( new Splice(array.length - args.length, [], args.length).adjustTo(array) ); return result; }, reverse( array: any[], observer: ArrayObserver, reverse: typeof Array.prototype.reverse, args: any[] ): any { observer.flush(); const oldArray = array.slice(); const result = reverse.apply(array, args); observer.reset(oldArray); return result; }, shift( array: any[], observer: ArrayObserver, shift: typeof Array.prototype.shift, args: any[] ): any { const notEmpty = array.length > 0; const result = shift.apply(array, args); if (notEmpty) { observer.addSplice(new Splice(0, [result], 0)); } return result; }, sort( array: any[], observer: ArrayObserver, sort: typeof Array.prototype.sort, args: any[] ): any[] { observer.flush(); const oldArray = array.slice(); const result = sort.apply(array, args); observer.reset(oldArray); return result; }, splice( array: any[], observer: ArrayObserver, splice: typeof Array.prototype.splice, args: any[] ): any { const result = splice.apply(array, args); observer.addSplice( new Splice(+args[0], result, args.length > 2 ? args.length - 2 : 0).adjustTo( array ) ); return result; }, unshift( array: any[], observer: ArrayObserver, unshift: typeof Array.prototype.unshift, args: any[] ): any[] { const result = unshift.apply(array, args); observer.addSplice(new Splice(0, [], args.length).adjustTo(array)); return result; }, }); /** * A splice strategy that doesn't create splices, but instead * tracks every change as a full array reset. * @public */ export const resetSpliceStrategy: SpliceStrategy = Object.freeze({ support: SpliceStrategySupport.reset, normalize( previous: unknown[] | undefined, current: unknown[], changes: Splice[] | undefined ): readonly Splice[] { return SpliceStrategy.reset; }, pop( array: any[], observer: ArrayObserver, pop: typeof Array.prototype.pop, args: any[] ) { const result = pop.apply(array, args); observer.reset(array); return result; }, push( array: any[], observer: ArrayObserver, push: typeof Array.prototype.push, args: any[] ): any { const result = push.apply(array, args); observer.reset(array); return result; }, reverse( array: any[], observer: ArrayObserver, reverse: typeof Array.prototype.reverse, args: any[] ): any { const result = reverse.apply(array, args); observer.reset(array); return result; }, shift( array: any[], observer: ArrayObserver, shift: typeof Array.prototype.shift, args: any[] ): any { const result = shift.apply(array, args); observer.reset(array); return result; }, sort( array: any[], observer: ArrayObserver, sort: typeof Array.prototype.sort, args: any[] ): any[] { const result = sort.apply(array, args); observer.reset(array); return result; }, splice( array: any[], observer: ArrayObserver, splice: typeof Array.prototype.splice, args: any[] ): any { const result = splice.apply(array, args); observer.reset(array); return result; }, unshift( array: any[], observer: ArrayObserver, unshift: typeof Array.prototype.unshift, args: any[] ): any[] { const result = unshift.apply(array, args); observer.reset(array); return result; }, });
the_stack
function getDivider(execDir: string) { let divider = '/'; if (execDir === undefined || execDir === '/') { divider = ''; } return divider; } function cleanDir(dir: string) { let ds = dir; if (ds === undefined) { return ''; } if (ds !== '/' && String(ds).endsWith('/')) { ds = String(ds).substring(0, ds.length - 1); } return ds; } function sanitizeNumber(num: number, min: number, max: number) { let n = num; if (n <= min) { n = min; } if (n > max) { n = max; } return n; } function getSystemdCommand(service: string) { return `# to start service sudo systemctl daemon-reload sudo systemctl cat ${service}.service sudo systemctl enable ${service}.service sudo systemctl start ${service}.service # to get logs from service sudo systemctl status ${service}.service -l --no-pager sudo journalctl -u ${service}.service -l --no-pager|less sudo journalctl -f -u ${service}.service # to stop service sudo systemctl stop ${service}.service sudo systemctl disable ${service}.service `; } export class EtcdFlag { name: string; dataDir: string; certsDir: string; ipAddress: string; clientPort: number; peerPort: number; initialClusterToken: string; initialClusterState: string; initialCluster: string; clientRootCAFile: string; clientCertFile: string; clientKeyFile: string; peerRootCAFile: string; peerCertFile: string; peerKeyFile: string; constructor( name: string, dataDir: string, certsDir: string, ipAddress: string, clientPort: number, peerPort: number, initialClusterToken: string, initialClusterState: string, rootCAPrefix: string, ) { this.name = name; this.dataDir = dataDir; this.ipAddress = ipAddress; this.clientPort = clientPort; this.peerPort = peerPort; this.initialClusterToken = initialClusterToken; this.initialClusterState = initialClusterState; this.initialCluster = ''; this.certsDir = certsDir; this.clientRootCAFile = rootCAPrefix + '.pem'; this.clientCertFile = this.name + '.pem'; this.clientKeyFile = this.name + '-key.pem'; this.peerRootCAFile = rootCAPrefix + '.pem'; this.peerCertFile = this.name + '.pem'; this.peerKeyFile = this.name + '-key.pem'; } getDataDir() { return cleanDir(this.dataDir); } getCertsDir() { return cleanDir(this.certsDir); } getDataDirPrepareCommand() { let ds = this.getDataDir(); let cs = `# make sure etcd process has write access to this directory # remove this directory if the cluster is new; keep if restarting etcd `; if (ds !== '') { cs += `# rm -rf ` + ds + ` `; } return cs; } getCFSSLFilesTxt() { let lineBreak = ` `; let txt = ''; txt += this.getCertsDir() + `/` + this.name + '-ca-csr.json' + lineBreak; txt += this.getCertsDir() + `/` + this.name + '.csr' + lineBreak; txt += this.getCertsDir() + `/` + this.name + '-key.pem' + lineBreak; txt += this.getCertsDir() + `/` + this.name + '.pem'; return txt; } getListenClientURLs(secure: boolean) { let protocol = 'http'; if (secure) { protocol = 'https'; } // let s = ''; // if (this.ipAddress === 'localhost' || this.ipAddress === '0.0.0.0') { // return protocol + '://' + this.ipAddress + ':' + String(this.clientPort); // } else { // if (!docker) { // s += protocol + '://' + '0.0.0.0' + ':' + String(this.clientPort); // s += ','; // } // } return protocol + '://' + this.ipAddress + ':' + String(this.clientPort); } getAdvertiseClientURLs(secure: boolean) { let protocol = 'http'; if (secure) { protocol = 'https'; } return protocol + '://' + this.ipAddress + ':' + String(this.clientPort); } getPeerURL(secure: boolean) { let protocol = 'http'; if (secure) { protocol = 'https'; } return protocol + '://' + this.ipAddress + ':' + String(this.peerPort); } getSystemdCommand() { return getSystemdCommand(this.name); } } const flagHelpURL = 'https://github.com/coreos/etcd/blob/master/etcdmain/help.go'; export class Etcd { version: string; execDir: string; // cluster-wise configuration secure: boolean; enableProfile: boolean; debug: boolean; autoCompactHour: number; clusterSize: number; // per-node configuration flags: EtcdFlag[]; constructor( version: string, execDir: string, secure: boolean, enableProfile: boolean, debug: boolean, autoCompactHour: number, clusterSize: number, flags: EtcdFlag[], ) { this.version = version; this.execDir = execDir; this.secure = secure; this.enableProfile = enableProfile; this.debug = debug; this.autoCompactHour = autoCompactHour; this.clusterSize = clusterSize; this.flags = flags; } getFlagHelpURL() { return flagHelpURL; } getExecDir() { return cleanDir(this.execDir); } getCFSSLFilesTxt() { let lineBreak = ` `; let txt = ''; for (let _i = 0; _i < this.flags.length; _i++) { txt += this.flags[_i].getCFSSLFilesTxt(); if (_i + 1 === sanitizeNumber(this.clusterSize, 1, 7)) { break; } txt += lineBreak; } return txt; } getInstallCommandGitSource(gitUser: string, gitBranch: string) { let divide = getDivider(this.getExecDir()); let txt = 'if [ "${GOPATH}" === "" ]; then' + ` ` + 'echo "GOPATH does not exist!"' + ` ` + 'exit 255' + ` ` + 'else' + ` ` + 'echo "GOPATH: ${GOPATH}"' + ` fi GIT_PATH=github.com/coreos/etcd USER_NAME=${gitUser} BRANCH_NAME=${gitBranch} ` + 'rm -rf ${GOPATH}/src/${GIT_PATH}' + ` ` + 'git clone https://github.com/${USER_NAME}/etcd' + ' \\' + ` ` + '--branch ${BRANCH_NAME}' + ' \\' + ` ` + '${GOPATH}/src/${GIT_PATH}' + ` ` + 'cd ${GOPATH}/src/${GIT_PATH} && ./build' + ` `; if (this.getExecDir() === '/') { txt += `# sudo cp ` + '${GOPATH}/src/${GIT_PATH}/bin/etcd* /usr/local/bin' + ` `; } txt += `sudo cp ` + '${GOPATH}/src/${GIT_PATH}/bin/etcd* ' + this.getExecDir() + ` ` + this.getExecDir() + divide + `etcd --version ` + 'ETCDCTL_API=3' + ' ' + this.getExecDir() + divide + `etcdctl version `; return txt; } getInstallCommandLinux() { let divide = getDivider(this.getExecDir()); let txt = `ETCD_VER=${this.version} # choose either URL GOOGLE_URL=https://storage.googleapis.com/etcd GITHUB_URL=https://github.com/coreos/etcd/releases/download ` + 'DOWNLOAD_URL=${GOOGLE_URL}' + ` `; txt += 'rm -f /tmp/etcd-${ETCD_VER}-linux-amd64.tar.gz' + ` ` + 'rm -rf /tmp/test-etcd && mkdir -p /tmp/test-etcd' + ` ` + 'curl -L ${DOWNLOAD_URL}/${ETCD_VER}/etcd-${ETCD_VER}-linux-amd64.tar.gz -o /tmp/etcd-${ETCD_VER}-linux-amd64.tar.gz' + ` ` + 'tar xzvf /tmp/etcd-${ETCD_VER}-linux-amd64.tar.gz -C /tmp/test-etcd --strip-components=1' + ` `; if (this.getExecDir() === '/') { txt += '# sudo cp /tmp/test-etcd/etcd* /usr/local/bin' + ` `; } let copycmd = 'sudo cp /tmp/test-etcd/etcd* ' + this.getExecDir(); if (this.getExecDir() === '/tmp/test-etcd') { copycmd = '# sudo cp /tmp/test-etcd/etcd* [YOUR_EXEC_DIR]' + ` ` + '# sudo mkdir -p /usr/local/bin/ && sudo cp /tmp/test-etcd/etcd* /usr/local/bin/'; } txt += copycmd + ` ` + this.getExecDir() + divide + `etcd --version ` + 'ETCDCTL_API=3' + ' ' + this.getExecDir() + divide + `etcdctl version `; return txt; } getInstallCommandOSX() { let divide = getDivider(this.getExecDir()); let txt = `ETCD_VER=${this.version} # choose either URL GOOGLE_URL=https://storage.googleapis.com/etcd GITHUB_URL=https://github.com/coreos/etcd/releases/download ` + 'DOWNLOAD_URL=${GOOGLE_URL}' + ` `; txt += 'rm -f /tmp/etcd-${ETCD_VER}-darwin-amd64.zip' + ` ` + 'rm -rf /tmp/test-etcd && mkdir -p /tmp/test-etcd' + ` ` + 'curl -L ${DOWNLOAD_URL}/${ETCD_VER}/etcd-${ETCD_VER}-darwin-amd64.zip -o /tmp/etcd-${ETCD_VER}-darwin-amd64.zip' + ` ` + 'unzip /tmp/etcd-${ETCD_VER}-darwin-amd64.zip -d /tmp' + ` ` + 'mv /tmp/etcd-${ETCD_VER}-darwin-amd64/* /tmp/test-etcd' + ` `; if (this.getExecDir() === '/') { txt += '# sudo cp /tmp/test-etcd/etcd* /usr/local/bin' + ` `; } let copycmd = 'sudo cp /tmp/test-etcd/etcd* ' + this.getExecDir(); if (this.getExecDir() === '/tmp/test-etcd') { copycmd = '# sudo cp /tmp/test-etcd/etcd* [YOUR_EXEC_DIR]' + ` ` + '# sudo mkdir -p /usr/local/bin/ && sudo cp /tmp/test-etcd/etcd* /usr/local/bin/'; } txt += copycmd + ` ` + this.getExecDir() + divide + `etcd --version ` + 'ETCDCTL_API=3' + ' ' + this.getExecDir() + divide + `etcdctl version `; return txt; } getClientEndpointsTxt() { let txt = ''; for (let _i = 0; _i < this.flags.length; _i++) { if (_i > 0) { txt += ','; } txt += this.flags[_i].ipAddress + ':' + String(this.flags[_i].clientPort); if (_i + 1 === sanitizeNumber(this.clusterSize, 1, 7)) { break; } } return txt; } getClientEndpointsWithScheme() { let eps: string[] = []; for (let _i = 0; _i < this.flags.length; _i++) { let addr = this.flags[_i].ipAddress + ':' + String(this.flags[_i].clientPort); let protocol = 'http'; if (this.secure) { protocol = 'https'; } let ep = protocol + '://' + addr; eps.push(ep); if (_i + 1 === sanitizeNumber(this.clusterSize, 1, 7)) { break; } } return eps; } getClientEndpointsWithSchemeTxt() { let eps = this.getClientEndpointsWithScheme(); let txt = ''; for (let _i = 0; _i < eps.length; _i++) { if (_i > 0) { txt += ','; } txt += eps[_i]; } return txt; } getInitialClusterTxt() { if (this.clusterSize > 7) { return '(error: cluster size over 7 is not supported)'; } let txt = ''; for (let _i = 0; _i < this.flags.length; _i++) { if (_i > 0) { txt += ','; } txt += this.flags[_i].name + '=' + this.flags[_i].getPeerURL(this.secure); if (_i + 1 === sanitizeNumber(this.clusterSize, 1, 7)) { break; } } for (let _i = 0; _i < this.flags.length; _i++) { this.flags[_i].initialCluster = txt; } return txt; } getFlagTxt(flag: EtcdFlag, skipDataDir: boolean, oneLine: boolean, docker: boolean) { let flags: string[] = []; flags.push('--name' + ' ' + flag.name); let dataDir = flag.getDataDir(); if (docker) { dataDir = '/etcd-data'; } if (!skipDataDir && dataDir !== '') { flags.push('--data-dir' + ' ' + dataDir); } let certsDir = flag.getCertsDir(); if (docker) { certsDir = '/etcd-ssl-certs-dir'; } flags.push('--listen-client-urls' + ' ' + flag.getListenClientURLs(this.secure)); flags.push('--advertise-client-urls' + ' ' + flag.getAdvertiseClientURLs(this.secure)); flags.push('--listen-peer-urls' + ' ' + flag.getPeerURL(this.secure)); flags.push('--initial-advertise-peer-urls' + ' ' + flag.getPeerURL(this.secure)); flags.push('--initial-cluster' + ' ' + this.getInitialClusterTxt()); flags.push('--initial-cluster-token' + ' ' + flag.initialClusterToken); flags.push('--initial-cluster-state' + ' ' + flag.initialClusterState); if (this.autoCompactHour > 0) { flags.push('--auto-compaction-retention' + ' ' + String(this.autoCompactHour)); } if (this.secure) { flags.push('--client-cert-auth'); flags.push('--trusted-ca-file' + ' ' + certsDir + '/' + flag.clientRootCAFile); flags.push('--cert-file' + ' ' + certsDir + '/' + flag.clientCertFile); flags.push('--key-file' + ' ' + certsDir + '/' + flag.clientKeyFile); flags.push('--peer-client-cert-auth'); flags.push('--peer-trusted-ca-file' + ' ' + certsDir + '/' + flag.peerRootCAFile); flags.push('--peer-cert-file' + ' ' + certsDir + '/' + flag.peerCertFile); flags.push('--peer-key-file' + ' ' + certsDir + '/' + flag.peerKeyFile); } if (this.enableProfile) { flags.push('--enable-pprof'); } if (this.debug) { flags.push('--debug'); } let txt = ''; let lineBreak = ' \\' + ` `; if (oneLine) { lineBreak = ' '; } for (let _i = 0; _i < flags.length; _i++) { txt += flags[_i]; if (_i !== flags.length - 1) { txt += lineBreak; } } return txt; } getCommand(flag: EtcdFlag, skipDataDir: boolean, oneLine: boolean, docker: boolean) { let divide = getDivider(this.getExecDir()); let exec = this.getExecDir() + divide + 'etcd'; return exec + ' ' + this.getFlagTxt(flag, skipDataDir, oneLine, docker); } getEndpointHealthCommand(flag: EtcdFlag, docker: boolean) { let divide = getDivider(this.getExecDir()); let exec = this.getExecDir() + divide + 'etcdctl'; let lineBreak = ` `; let cmd = 'ETCDCTL_API=3 ' + exec + ' \\' + lineBreak + '--endpoints' + ' ' + this.getClientEndpointsTxt() + ' \\' + lineBreak; if (this.secure) { cmd += '--cacert' + ' ' + flag.getCertsDir() + '/' + flag.clientRootCAFile + ' \\' + lineBreak + '--cert' + ' ' + flag.getCertsDir() + '/' + flag.clientCertFile + ' \\' + lineBreak + '--key' + ' ' + flag.getCertsDir() + '/' + flag.clientKeyFile + ' \\' + lineBreak; } cmd += 'endpoint health'; if (docker) { // sudo docker exec etcd-v3.1.0 /bin/sh -c "export ETCDCTL_API=3 && /usr/local/bin/etcdctl endpoint health" cmd += ` # to use 'docker' command to check the status `; cmd += '/usr/bin/docker' + ' \\' + lineBreak; cmd += 'exec' + ' \\' + lineBreak; cmd += 'etcd-' + this.version + ' \\' + lineBreak; cmd += '/bin/sh' + ' ' + '-c' + ' '; cmd += '"'; cmd += 'export ETCDCTL_API=3'; cmd += ' && '; cmd += '/usr/local/bin/etcdctl'; cmd += ' ' + '--endpoints' + ' ' + this.getClientEndpointsTxt(); cmd += ' '; if (this.secure) { let cs = '/etcd-ssl-certs-dir'; cmd += '--cacert' + ' ' + cs + '/' + flag.clientRootCAFile; cmd += ' ' + '--cert' + ' ' + cs + '/' + flag.clientCertFile; cmd += ' ' + '--key' + ' ' + cs + '/' + flag.clientKeyFile; cmd += ' '; } cmd += 'endpoint health'; cmd += '"' + ` `; } return cmd; } getServiceFile(flag: EtcdFlag) { return `# to write service file for etcd cat > /tmp/${flag.name}.service <<EOF [Unit] Description=etcd Documentation=https://github.com/coreos/etcd Conflicts=etcd.service Conflicts=etcd2.service [Service] Type=notify Restart=always RestartSec=5s LimitNOFILE=40000 TimeoutStartSec=0 ExecStart=` + this.getCommand(flag, false, false, false) + ` [Install] WantedBy=multi-user.target EOF sudo mv /tmp/${flag.name}.service /etc/systemd/system/${flag.name}.service `; } getServiceFileDocker(flag: EtcdFlag) { let dockerExec = '/usr/bin'; let divideDocker = getDivider(dockerExec); let execDocker = dockerExec + divideDocker + 'docker'; let dockerContainerName = 'etcd-' + this.version; let dockerRunFlags: string[] = []; dockerRunFlags.push('run'); dockerRunFlags.push('--rm'); dockerRunFlags.push('--net=host'); dockerRunFlags.push('--name' + ' ' + dockerContainerName); dockerRunFlags.push('--volume' + '=' + flag.getDataDir() + ':' + '/etcd-data'); if (this.secure) { dockerRunFlags.push('--volume' + '=' + flag.getCertsDir() + ':' + '/etcd-ssl-certs-dir'); } dockerRunFlags.push('gcr.io/etcd-development/etcd:' + this.version); dockerRunFlags.push('/usr/local/bin/etcd'); let execStart = execDocker; let lineBreak = ' \\' + ` `; for (let _i = 0; _i < dockerRunFlags.length; _i++) { execStart += lineBreak + dockerRunFlags[_i]; } execStart += lineBreak + this.getFlagTxt(flag, false, false, true); // do not skip --data-dir flag for OCI // docker stop sends 'SIGTERM' // docker kill sends 'SIGKILL' let execStop = execDocker + ' ' + 'stop' + ' ' + dockerContainerName; // ExecStartPre=/usr/bin/docker` + lineBreak + 'kill' + lineBreak + 'etcd-' + this.version + ` // ExecStartPre=/usr/bin/docker` + lineBreak + 'rm --force' + lineBreak + 'etcd-' + this.version + ` let cmd = ''; cmd += `# to write service file for etcd with Docker cat > /tmp/${flag.name}.service <<EOF [Unit] Description=etcd with Docker Documentation=https://github.com/coreos/etcd [Service] Restart=always RestartSec=5s TimeoutStartSec=0 LimitNOFILE=40000 ExecStart=` + execStart + ` ExecStop=` + execStop + ` ` + ` [Install] WantedBy=multi-user.target EOF sudo mv /tmp/${flag.name}.service /etc/systemd/system/${flag.name}.service `; return cmd; } }
the_stack
import BaseClient from "./BaseClient"; import { Callback, ClientOptions, DefaultResponse, FilteringParameters, } from "./models/index"; import { Bounce, BounceActivationResponse, BounceCounts, BounceDump, BounceFilteringParameters, Bounces, BrowserUsageCounts, ClickCounts, ClickLocationCounts, ClickPlaformUsageCounts, CreateInboundRuleRequest, CreateMessageStreamRequest, CreateSuppressionsRequest, CreateTemplateRequest, CreateWebhookRequest, DeleteSuppressionsRequest, DeliveryStatistics, EmailClientUsageCounts, EmailPlaformUsageCounts, EmailReadTimesCounts, InboundMessageDetails, InboundMessages, InboundMessagesFilteringParameters, InboundRule, InboundRules, Message, MessageSendingResponse, MessageStream, MessageStreamArchiveResponse, MessageStreams, MessageStreamsFilteringParameters, MessageStreamUnarchiveResponse, OpenCounts, OutboundMessageClicks, OutboundMessageClicksFilteringParameters, OutboundMessageDetails, OutboundMessageDump, OutboundMessageOpens, OutboundMessageOpensFilteringParameters, OutboundMessages, OutboundMessagesFilteringParameters, OutboundStatistics, SentCounts, Server, SpamCounts, StatisticsFilteringParameters, Suppressions, SuppressionStatuses, Template, TemplatedMessage, TemplateFilteringParameters, Templates, TemplateValidation, TemplateValidationOptions, TrackedEmailCounts, UpdateMessageStreamRequest, UpdateServerRequest, UpdateTemplateRequest, UpdateWebhookRequest, Webhook, WebhookFilteringParameters, Webhooks, } from "./models/index"; /** * Server client class that can be used to interact with an individual Postmark Server. */ export default class ServerClient extends BaseClient { /** * Create a client. * * @param serverToken - The token for the server that you wish to interact with. * @param configOptions - Options to customize the behavior of the this client. */ constructor(serverToken: string, configOptions?: ClientOptions.Configuration) { super(serverToken, ClientOptions.DefaultHeaderNames.SERVER_TOKEN, configOptions); } /** Send a single email message. * * @param email - Email message to send. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public sendEmail(email: Message, callback?: Callback<MessageSendingResponse>): Promise<MessageSendingResponse> { return this.processRequestWithBody<MessageSendingResponse>(ClientOptions.HttpMethod.POST, "/email", email, callback); } /** * Send a batch of email messages. * * @param emails - An array of messages to send. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public sendEmailBatch(emails: Message[], callback?: Callback<MessageSendingResponse[]>): Promise<MessageSendingResponse[]> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, "/email/batch", emails, callback); } /** * Send a message using a template. * * @param template - Message you wish to send. * @param callback If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public sendEmailWithTemplate(template: TemplatedMessage, callback?: Callback<MessageSendingResponse>): Promise<MessageSendingResponse> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, "/email/withTemplate", template, callback); } /** * Send a batch of template email messages. * * @param templates - An array of templated messages you wish to send using this Client. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public sendEmailBatchWithTemplates(templates: TemplatedMessage[], callback?: Callback<MessageSendingResponse[]>): Promise<MessageSendingResponse[]> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, "/email/batchWithTemplates", { Messages: templates }, callback); } /** * Get bounce statistic information for the associated Server. * * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getDeliveryStatistics(callback?: Callback<DeliveryStatistics>): Promise<DeliveryStatistics> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/deliveryStats", {}, callback); } /** * Get a batch of bounces. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getBounces(filter: BounceFilteringParameters = new BounceFilteringParameters(), callback?: Callback<Bounces>): Promise<Bounces> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/bounces", filter, callback); } /** * Get details for a specific Bounce. * * @param id - The ID of the Bounce you wish to retrieve. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getBounce(id: number, callback?: Callback<Bounce>): Promise<Bounce> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/bounces/${id}`, {}, callback); } /** * Get a Bounce Dump for a specific Bounce. * * @param id - The ID of the Bounce for which you wish to retrieve Bounce Dump. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getBounceDump(id: number, callback?: Callback<BounceDump>): Promise<BounceDump> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/bounces/${id}/dump`, {}, callback); } /** * Activate email address that was deactivated due to a Bounce. * * @param id - The ID of the Bounce for which you wish to activate the associated email. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public activateBounce(id: number, callback?: Callback<BounceActivationResponse>): Promise<BounceActivationResponse> { return this.processRequestWithBody(ClientOptions.HttpMethod.PUT, `/bounces/${id}/activate`, {}, callback); } /** * Get the list of templates associated with this server. * * @param filter - Optional filtering options. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getTemplates(filter: TemplateFilteringParameters = new TemplateFilteringParameters(), callback?: Callback<Templates>): Promise<Templates> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/templates", filter, callback); } /** * Get the a specific template associated with this server. * * @param idOrAlias - ID or alias for the template you wish to retrieve. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getTemplate(idOrAlias: (number | string), callback?: Callback<Template>): Promise<Template> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/templates/${idOrAlias}`, {}, callback); } /** * Delete a template associated with this server. * * @param idOrAlias - ID or template alias you wish to delete. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public deleteTemplate(idOrAlias: (number | string), callback?: Callback<DefaultResponse>): Promise<DefaultResponse> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.DELETE, `/templates/${idOrAlias}`, {}, callback); } /** * Create a new template on the associated server. * * @param options - Configuration options to be used to create the Template. * @param callback If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public createTemplate(options: CreateTemplateRequest, callback?: Callback<Template>): Promise<Template> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, "/templates/", options, callback); } /** * Update a template on the associated server. * * @param idOrAlias - Id or alias of the template you wish to update. * @param options - Template options you wish to update. * @param callback If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public editTemplate(idOrAlias: (number | string), options: UpdateTemplateRequest, callback?: Callback<Template>): Promise<Template> { return this.processRequestWithBody(ClientOptions.HttpMethod.PUT, `/templates/${idOrAlias}`, options, callback); } /** * Validate template markup to verify that it will be parsed. Also provides a recommended template * model to be used when sending using the specified template content. * * @param options - The template content you wish to validate. * @param callback If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public validateTemplate(options: TemplateValidationOptions, callback?: Callback<TemplateValidation>): Promise<TemplateValidation> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, "/templates/validate", options, callback); } /** * Get the information for the Server associated with this Client. * * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getServer(callback?: Callback<Server>): Promise<Server> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/server", {}, callback); } /** * Modify the Server associated with this Client. * * @param options - The options you wish to modify. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public editServer(options: UpdateServerRequest, callback?: Callback<Server>): Promise<Server> { return this.processRequestWithBody(ClientOptions.HttpMethod.PUT, "/server", options, callback); } /** * Get a batch of Outbound Messages. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getOutboundMessages(filter: OutboundMessagesFilteringParameters = new OutboundMessagesFilteringParameters(), callback?: Callback<OutboundMessages>): Promise<OutboundMessages> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/messages/outbound", filter, callback); } /** * Get details for a specific Outbound Message. * * @param messageId - The ID of the OutboundMessage you wish to retrieve. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getOutboundMessageDetails(messageId: string, callback?: Callback<OutboundMessageDetails>): Promise<OutboundMessageDetails> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/messages/outbound/${messageId}`, {}, callback); } /** * Get details for a specific Outbound Message. * * @param messageId - The ID of the OutboundMessage you wish to retrieve. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getOutboundMessageDump(messageId: string, callback?: Callback<OutboundMessageDump>): Promise<OutboundMessageDump> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/messages/outbound/${messageId}/dump`, {}, callback); } /** * Get a batch of Inbound Messages. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getInboundMessages(filter: InboundMessagesFilteringParameters = new InboundMessagesFilteringParameters(), callback?: Callback<InboundMessages>): Promise<InboundMessages> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/messages/inbound", filter, callback); } /** * Get details for a specific Inbound Message. * * @param messageId - The ID of the Inbound Message you wish to retrieve. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getInboundMessageDetails(messageId: string, callback?: Callback<InboundMessageDetails>): Promise<InboundMessageDetails> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/messages/inbound/${messageId}/details`, {}, callback); } /** * Cause an Inbound Message to bypass filtering rules defined on this Client's associated Server. * * @param messageId - The ID of the Inbound Message for which you wish to bypass the filtering rules. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public bypassBlockedInboundMessage(messageId: string, callback?: Callback<DefaultResponse>): Promise<DefaultResponse> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.PUT, `/messages/inbound/${messageId}/bypass`, {}, callback); } /** * Request that Postmark retry POSTing to the Inbound Hook for the specified message. * * @param messageId - The ID of the Inbound Message for which you wish to retry the inbound hook. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public retryInboundHookForMessage(messageId: string, callback?: Callback<DefaultResponse>): Promise<DefaultResponse> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.PUT, `/messages/inbound/${messageId}/retry`, {}, callback); } /** * Get the Opens for Outbound Messages. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getMessageOpens(filter: OutboundMessageOpensFilteringParameters = new OutboundMessageOpensFilteringParameters(), callback?: Callback<OutboundMessageOpens>): Promise<OutboundMessageOpens> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/messages/outbound/opens", filter, callback); } /** * Get details of Opens for specific Outbound Message. * * @param messageId - Message ID of the message for which you wish to retrieve Opens. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getMessageOpensForSingleMessage(messageId: string, filter: OutboundMessageOpensFilteringParameters = new OutboundMessageOpensFilteringParameters(50, 0), callback?: Callback<OutboundMessageOpens>): Promise<OutboundMessageOpens> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/messages/outbound/opens/${messageId}`, filter, callback); } /** * Get the Clicks for Outbound Messages. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getMessageClicks(filter: OutboundMessageClicksFilteringParameters = new OutboundMessageClicksFilteringParameters(), callback?: Callback<OutboundMessageClicks>): Promise<OutboundMessageClicks> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/messages/outbound/clicks", filter, callback); } /** * Get Click information for a single Outbound Message. * * @param messageId - The MessageID for which clicks should be retrieved. * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getMessageClicksForSingleMessage(messageId: string, filter: OutboundMessageClicksFilteringParameters = new OutboundMessageClicksFilteringParameters(), callback?: Callback<OutboundMessageClicks>): Promise<OutboundMessageClicks> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/messages/outbound/clicks/${messageId}`, filter, callback); } /** * Get overview statistics on Outbound Messages sent from the Server associated with this Client. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getOutboundOverview(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<OutboundStatistics>): Promise<OutboundStatistics> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound", filter, callback); } /** * Get statistics on email sent from the Server associated with this Client. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getSentCounts(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<SentCounts>): Promise<SentCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/sends", filter, callback); } /** * Get statistiscs on emails that bounced after being sent from the Server associated with this Client. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getBounceCounts(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<BounceCounts>): Promise<BounceCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/bounces", filter, callback); } /** * Get SPAM complaint statistics for email sent from the Server associated with this Client. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getSpamComplaintsCounts(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<SpamCounts>): Promise<SpamCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/spam", filter, callback); } /** * Get email tracking statistics for messages sent from the Server associated with this Client. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getTrackedEmailCounts(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<TrackedEmailCounts>): Promise<TrackedEmailCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/tracked", filter, callback); } /** * Get Open statistics for messages sent from the Server associated with this Client. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getEmailOpenCounts(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<OpenCounts>): Promise<OpenCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/opens", filter, callback); } /** * Get Email Client Platform statistics for messages sent from the Server associated with this Client. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getEmailOpenPlatformUsage(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<EmailPlaformUsageCounts>): Promise<EmailPlaformUsageCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/opens/platforms", filter, callback); } /** * Get statistics on which Email Clients were used to open messages sent from the Server associated with this Client. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getEmailOpenClientUsage(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<EmailClientUsageCounts>): Promise<EmailClientUsageCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/opens/emailClients", filter, callback); } /** * Get Read Time statistics for messages sent from the Server associated with this Client. * @param filter Optional filtering parameters. * @param callback If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getEmailOpenReadTimes(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<EmailReadTimesCounts>): Promise<EmailReadTimesCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/opens/readTimes", filter, callback); } /** * Get total clicks statistics for tracked links for messages sent from the Server associated with this Client. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getClickCounts(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<ClickCounts>): Promise<ClickCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/clicks", filter, callback); } /** * Get browser family statistics for tracked links for messages sent from the Server associated with this Client. * @param filter Optional filtering parameters. * @param callback If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getClickBrowserUsage(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<BrowserUsageCounts>): Promise<BrowserUsageCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/clicks/browserFamilies", filter, callback); } /** * Get browser platform statistics for tracked links for messages sent from the Server associated with this Client. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getClickPlatformUsage(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<ClickPlaformUsageCounts>): Promise<ClickPlaformUsageCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/clicks/platforms", filter, callback); } /** * Get click location (in HTML or Text body of the email) statistics for tracked links for messages sent * from the Server associated with this Client. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getClickLocation(filter: StatisticsFilteringParameters = new StatisticsFilteringParameters(), callback?: Callback<ClickLocationCounts>): Promise<ClickLocationCounts> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/stats/outbound/clicks/location", filter, callback); } /** * Create an Inbound Rule Trigger. * * @param options - Configuration options to be used when creating this Trigger. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public createInboundRuleTrigger(options: CreateInboundRuleRequest, callback?: Callback<InboundRule>): Promise<InboundRule> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, "/triggers/inboundRules", options, callback); } /** * Delete an Inbound Rule Trigger. * * @param id - The ID of the Inbound Rule Trigger you wish to delete. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public deleteInboundRuleTrigger(id: number, callback?: Callback<DefaultResponse>): Promise<DefaultResponse> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.DELETE, `/triggers/inboundRules/${id}`, {}, callback); } /** * Get a list of Inbound Rule Triggers. * * @param filter - Optional filtering parameters. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getInboundRuleTriggers(filter: FilteringParameters = new FilteringParameters(), callback?: Callback<InboundRules>): Promise<InboundRules> { this.setDefaultPaginationValues(filter); return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/triggers/inboundRules", filter, callback); } /** * Get the list of Webhooks for specific server. * * @param filter - Optional filtering parameters * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getWebhooks(filter: WebhookFilteringParameters = {}, callback?: Callback<Webhooks>): Promise<Webhooks> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/webhooks", filter, callback); } /** * Get details for a specific Webhook. * * @param id - The ID of the Webhook you wish to retrieve. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getWebhook(id: number, callback?: Callback<Webhook>): Promise<Webhook> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/webhooks/${id}`, {}, callback); } /** * Create a Webhook on the associated server. * * @param options - Configuration options to be used when creating Webhook trigger. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public createWebhook(options: CreateWebhookRequest, callback?: Callback<Webhook>): Promise<Webhook> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, "/webhooks", options, callback); } /** * Update Webhook on the associated server. * * @param id - Id of the webhook you wish to update. * @param options - Webhook options you wish to update. * @param callback If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public editWebhook(id: number, options: UpdateWebhookRequest, callback?: Callback<Webhook>): Promise<Webhook> { return this.processRequestWithBody(ClientOptions.HttpMethod.PUT, `/webhooks/${id}`, options, callback); } /** * Delete an existing Webhook. * * @param id - The ID of the Webhook you wish to delete. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public deleteWebhook(id: number, callback?: Callback<DefaultResponse>): Promise<DefaultResponse> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.DELETE, `/webhooks/${id}`, {}, callback); } /** * Get the list of message streams on a server. * * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getMessageStreams(filter: MessageStreamsFilteringParameters = {}, callback?: Callback<MessageStreams>): Promise<MessageStreams> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, "/message-streams", filter, callback); } /** * Get details for a specific message stream on a server. * * @param id - The ID of the message stream you wish to retrieve. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getMessageStream(id: string, callback?: Callback<MessageStream>): Promise<MessageStream> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/message-streams/${id}`, {}, callback); } /** * Update message stream on the associated server. * * @param id - Id of the webhook you wish to update. * @param options - Webhook options you wish to update. * @param callback If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public editMessageStream(id: string, options: UpdateMessageStreamRequest, callback?: Callback<MessageStream>): Promise<MessageStream> { return this.processRequestWithBody(ClientOptions.HttpMethod.PATCH, `/message-streams/${id}`, options, callback); } /** * Create a message stream on the associated server. * * @param options - Configuration options to be used when creating message stream on the server. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public createMessageStream(options: CreateMessageStreamRequest, callback?: Callback<MessageStream>): Promise<MessageStream> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, "/message-streams", options, callback); } /** * Archive a message stream on the associated server. * * @param options - Configuration options to be used when creating message stream on the server. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public archiveMessageStream(id: string , callback?: Callback<MessageStreamArchiveResponse>): Promise<MessageStreamArchiveResponse> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, `/message-streams/${id}/archive`, {}, callback); } /** * Unrchive a message stream on the associated server. * * @param options - Configuration options to be used when creating message stream on the server. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public unarchiveMessageStream(id: string , callback?: Callback<MessageStreamUnarchiveResponse>): Promise<MessageStreamUnarchiveResponse> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, `/message-streams/${id}/unarchive`, {}, callback); } /** * Get the list of suppressions for a message stream on a server. * * @param messageStream - Select message stream * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public getSuppressions(messageStream: string, callback?: Callback<Suppressions>): Promise<Suppressions> { return this.processRequestWithoutBody(ClientOptions.HttpMethod.GET, `/message-streams/${messageStream}/suppressions/dump`, callback); } /** * Add email addresses to a suppressions list on a message stream on a server. * * @param messageStream - Select message stream * @param options - Suppressions you wish to add. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public createSuppressions(messageStream: string, options: CreateSuppressionsRequest, callback?: Callback<SuppressionStatuses>): Promise<SuppressionStatuses> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, `/message-streams/${messageStream}/suppressions`, options, callback); } /** * Delete email addresses from a suppressions list on a message stream on a server. * * @param messageStream - Select message stream * @param options - Suppressions you wish to delete. * @param callback - If the callback is provided, it will be passed to the resulting promise as a continuation. * @returns A promise that will complete when the API responds (or an error occurs). */ public deleteSuppressions(messageStream: string, options: DeleteSuppressionsRequest, callback?: Callback<SuppressionStatuses>): Promise<SuppressionStatuses> { return this.processRequestWithBody(ClientOptions.HttpMethod.POST, `/message-streams/${messageStream}/suppressions/delete`, options, callback); } }
the_stack
import LottieView from 'lottie-react-native'; import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState, } from 'react'; import { Dimensions, Image, StatusBar, StyleSheet, useWindowDimensions, View, ViewStyle, } from 'react-native'; import { AwesomeSliderProps, Slider, SliderThemeType, } from 'react-native-awesome-slider/src/index'; import { clamp } from 'react-native-awesome-slider/src/utils'; import type { PanGesture } from 'react-native-gesture-handler'; import { Gesture, GestureDetector } from 'react-native-gesture-handler'; import Orientation, { OrientationType } from 'react-native-orientation-locker'; import Animated, { cancelAnimation, runOnJS, useAnimatedProps, useAnimatedStyle, useDerivedValue, useSharedValue, withDelay, withTiming, } from 'react-native-reanimated'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import Video, { OnLoadData, OnProgressData, OnSeekData, VideoProperties, } from 'react-native-video'; import { Text } from './components'; import { Ripple } from './components/ripple'; import { TapControler } from './tap-controler'; import { palette } from './theme/palette'; import { bin, isIos, useRefs } from './utils'; import { VideoLoader } from './video-loading'; import { formatTime, formatTimeToMins, secondToTime } from './video-utils'; export const { width, height, scale, fontScale } = Dimensions.get('window'); const VIDEO_DEFAULT_HEIGHT = width * (9 / 16); const hitSlop = { left: 8, bottom: 8, right: 8, top: 8 }; const controlAnimteConfig = { duration: 200, }; const AnimatedLottieView = Animated.createAnimatedComponent(LottieView); export type VideoProps = VideoProperties & { showOnStart?: boolean; onEnterFullscreen?: () => void; onExitFullscreen?: () => void; controlTimeout?: number; videoDefaultHeight?: number; headerBarTitle?: string; onTapBack?: () => void; navigation?: any; autoPlay?: boolean; onToggleAutoPlay?: (state: boolean) => void; onTapMore?: () => void; doubleTapInterval?: number; theme?: SliderThemeType; paused: boolean; onPausedChange: (paused: boolean) => void; onTapPause?: (paused: boolean) => void; sliderProps?: Omit< AwesomeSliderProps, 'progress' | 'minimumValue' | 'maximumValue' >; videoHeight: Animated.SharedValue<number>; customAnimationStyle?: Animated.AnimateStyle<ViewStyle>; controlViewOpacityValue?: Animated.SharedValue<number>; onCustomPanGesture?: PanGesture; isFullScreen: Animated.SharedValue<boolean>; disableControl?: boolean; renderBackIcon?: () => JSX.Element; renderFullScreenBackIcon?: () => JSX.Element; renderMore?: () => JSX.Element; renderFullScreen?: () => JSX.Element; onVideoPlayEnd?: () => void; onAutoPlayText?: string; offAutoPlayText?: string; }; export type VideoPlayerRef = { /** * Check control view to see if it is displayed before playing */ setPlay: () => void; /** * Check control view to see if it is displayed before pause */ setPause: () => void; /** * toggle full screen */ toggleFullSreen: (isFullScreen: boolean) => void; /** * toggle control opatity */ toggleControlViewOpacity: (isShow: boolean) => void; /** * seek to progress */ setSeekTo: (second: number) => void; }; const VideoPlayer = forwardRef<VideoPlayerRef, VideoProps>( ( { resizeMode = 'contain', showOnStart = true, source, style, onEnterFullscreen, onExitFullscreen, controlTimeout = 2000, videoDefaultHeight = VIDEO_DEFAULT_HEIGHT, headerBarTitle = '', onTapBack, navigation, autoPlay = false, onToggleAutoPlay, onTapMore, doubleTapInterval = 500, theme = { minimumTrackTintColor: palette.Main(1), maximumTrackTintColor: palette.B(0.6), cacheTrackTintColor: palette.G1(1), bubbleBackgroundColor: palette.B(0.8), disableMinTrackTintColor: palette.Main(1), }, paused, onPausedChange, onTapPause, sliderProps, videoHeight, customAnimationStyle, onCustomPanGesture, isFullScreen, disableControl, renderBackIcon, renderMore, renderFullScreen, renderFullScreenBackIcon, onVideoPlayEnd, onAutoPlayText = 'Autoplay is on', offAutoPlayText = 'Autoplay is off', ...rest }, ref, ) => { /** * hooks */ const insets = useSafeAreaInsets(); const insetsRef = useRef(insets); const dimensions = useWindowDimensions(); const leftDoubleTapBoundary = dimensions.width / 2 - insets.left - insets.right - 80; const rightDoubleTapBoundary = dimensions.width - leftDoubleTapBoundary - insets.left - insets.right; const [isFullScreenState, setIsFullscreen] = useState(false); const [currentTime, setCurrentTime] = useState(0); const [duration, setDuration] = useState(0); const [isLoadEnd, setIsLoadEnd] = useState(false); const [loading, setIsLoading] = useState(false); const [showTimeRemaining, setShowTimeRemaining] = useState(true); const [allowAutoPlayVideo, setAllowAutoPlayVideo] = useState(autoPlay); useImperativeHandle(ref, () => ({ setPlay: () => { 'worklet'; checkTapTakesEffect(); play(); }, setPause: () => { 'worklet'; checkTapTakesEffect(); pause(); }, toggleFullSreen: (isFullScrren: boolean) => { isFullScrren ? enterFullScreen() : exitFullScreen(); }, toggleControlViewOpacity: (isShow: boolean) => { 'worklet'; isShow ? showControlAnimation() : hideControlAnimation(); }, setSeekTo: (seconds: number) => { seekTo(seconds); }, })); /** * refs */ const videoPlayer = useRef<Video>(null); const mounted = useRef(false); const autoPlayAnimation = useSharedValue(autoPlay ? 1 : 0); const { rippleLeft, rippleRight } = useRefs(); /** * reanimated value */ const controlViewOpacity = useSharedValue(showOnStart ? 1 : 0); const autoPlayTextAnimation = useSharedValue(0); const doubleLeftOpacity = useSharedValue(0); const doubleRightOpacity = useSharedValue(0); const videoScale = useSharedValue(1); const videoTransY = useSharedValue(0); const panIsVertical = useSharedValue(false); const doubleTapIsAlive = useSharedValue(false); const max = useSharedValue(100); const min = useSharedValue(0); const isScrubbing = useSharedValue(false); const isSeeking = useRef(false); const progress = useSharedValue(0); const defaultVideoStyle = useAnimatedStyle(() => { return { transform: [ { scale: videoScale.value, }, { translateY: videoTransY.value, }, ], height: videoHeight.value, }; }, []); const videoStyle = customAnimationStyle ? customAnimationStyle : defaultVideoStyle; const bottomControlStyle = useAnimatedStyle(() => { return { transform: [ { translateY: isFullScreen.value ? -42 : 0, }, ], }; }); const topControlStyle = useAnimatedStyle(() => { return { transform: [ { translateY: isFullScreen.value ? -42 : 0, }, ], opacity: withTiming(bin(!isFullScreen.value)), }; }); const topFullscreenControlStyle = useAnimatedStyle(() => { return { opacity: withTiming(bin(isFullScreen.value)), }; }); const bottomSliderStyle = useAnimatedStyle(() => { return { opacity: withTiming(bin(!isFullScreen.value)), }; }); const fullScreenSliderStyle = useAnimatedStyle(() => { return { opacity: withTiming(bin(isFullScreen.value)), }; }); const controlViewStyles = useAnimatedStyle(() => { return { opacity: controlViewOpacity.value, }; }); const autoPlayTextStyle = useAnimatedStyle(() => { return { opacity: autoPlayTextAnimation.value, }; }); const getDoubleLeftStyle = useAnimatedStyle(() => { return { opacity: withTiming(doubleLeftOpacity.value), }; }); const getDoubleRightStyle = useAnimatedStyle(() => { return { opacity: withTiming(doubleRightOpacity.value), }; }); /** * useAnimatedProps */ const playAnimated = useDerivedValue(() => { return paused ? 0.5 : 0; }, [paused]); const playAnimatedProps = useAnimatedProps(() => { return { progress: withTiming(playAnimated.value), }; }); const fullscreenAnimatedProps = useAnimatedProps(() => { return { progress: withTiming(isFullScreen.value ? 0.5 : 0), }; }); const autoPlayAnimatedProps = useAnimatedProps(() => { return { progress: withTiming(autoPlayAnimation.value, { duration: 600 }), }; }); /** * useEffect */ useEffect(() => { mounted.current = true; Orientation.lockToPortrait(); StatusBar.setBarStyle('light-content'); paused ? pause() : play(); const unBeforeRemove = navigation?.addListener( 'beforeRemove', (e: any) => { e?.preventDefault(); if (isFullScreen.value) { toggleFullScreen(); } else { navigation.dispatch(e.data.action); } }, ); return () => { mounted.current = false; clearControlTimeout(); pause(); Orientation.lockToPortrait(); unBeforeRemove && unBeforeRemove(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); /** * Set a timeout when the controls are shown * that hides them after a length of time. */ const setControlTimeout = () => { 'worklet'; controlViewOpacity.value = withDelay(controlTimeout, withTiming(0)); }; /** * Clear the hide controls timeout. */ const clearControlTimeout = () => { 'worklet'; cancelAnimation(controlViewOpacity); }; /** * Reset the timer completely */ const resetControlTimeout = () => { 'worklet'; clearControlTimeout(); setControlTimeout(); }; /** * Animation to show controls * fade in. */ const showControlAnimation = () => { 'worklet'; controlViewOpacity.value = withTiming(1, controlAnimteConfig); setControlTimeout(); }; /** * Animation to show controls * fade out. */ const hideControlAnimation = () => { 'worklet'; controlViewOpacity.value = withTiming(0, controlAnimteConfig); }; /** * check on tap icon * @returns bool */ const checkTapTakesEffect = () => { 'worklet'; if (disableControl) { return false; } resetControlTimeout(); if (controlViewOpacity.value === 0) { showControlAnimation(); return false; } return true; }; const seekByStep = (isBack = false) => { seekTo(currentTime - (isBack ? 10 : -10)); }; /** * Toggle player full screen state on <Video> component */ const enterFullScreen = () => { onEnterFullscreen?.(); setIsFullscreen(true); StatusBar.setHidden(true, 'fade'); Orientation.lockToLandscape(); isFullScreen.value = true; videoHeight.value = width; }; const exitFullScreen = () => { onExitFullscreen?.(); setIsFullscreen(false); StatusBar.setHidden(false, 'fade'); Orientation.lockToPortrait(); isFullScreen.value = false; videoHeight.value = videoDefaultHeight; }; const toggleFullScreenOnJS = () => { Orientation.getOrientation(orientation => { if (isFullScreen.value || orientation !== OrientationType.PORTRAIT) { exitFullScreen(); StatusBar.setHidden(false, 'fade'); } else { enterFullScreen(); StatusBar.setHidden(true, 'fade'); } }); }; const toggleFullScreen = () => { 'worklet'; const status = checkTapTakesEffect(); if (!status) { return; } runOnJS(toggleFullScreenOnJS)(); }; /** * on pan event */ const defalutPanGesture = Gesture.Pan() .onStart(({ velocityY, velocityX }) => { panIsVertical.value = Math.abs(velocityY) > Math.abs(velocityX); }) .onUpdate(({ translationY }) => { controlViewOpacity.value = withTiming(0, { duration: 100 }); if (isFullScreen.value) { if (translationY > 0 && Math.abs(translationY) < 100) { videoScale.value = clamp( 0.9, 1 - Math.abs(translationY) * 0.008, 1, ); videoTransY.value = translationY; } } else { if (translationY < 0 && Math.abs(translationY) < 40) { videoScale.value = Math.abs(translationY) * 0.012 + 1; } } }) .onEnd(({ translationY }, success) => { if (!panIsVertical.value && !success) { return; } if (isFullScreen.value) { if (translationY >= 100) { runOnJS(exitFullScreen)(); } } else { if (-translationY >= 40) { runOnJS(enterFullScreen)(); } } videoTransY.value = 0; videoScale.value = withTiming(1); }); const onPanGesture = onCustomPanGesture ? onCustomPanGesture : defalutPanGesture; const singleTapHandler = Gesture.Tap().onEnd((_event, success) => { if (disableControl) { return; } if (success) { if (controlViewOpacity.value === 0) { controlViewOpacity.value = withTiming(1, controlAnimteConfig); setControlTimeout(); } else { controlViewOpacity.value = withTiming(0, controlAnimteConfig); } } }); const doubleTapHandle = Gesture.Tap() .numberOfTaps(2) .maxDuration(doubleTapInterval) .onStart(({ x }) => { doubleTapIsAlive.value = x < leftDoubleTapBoundary && x > rightDoubleTapBoundary; }) .onEnd(({ x, y, numberOfPointers }, success) => { if (success) { if (numberOfPointers !== 1) { return; } if (x < leftDoubleTapBoundary) { doubleLeftOpacity.value = 1; rippleLeft.current?.onPress({ x, y }); runOnJS(seekByStep)(true); return; } if (x > rightDoubleTapBoundary) { doubleRightOpacity.value = 1; rippleRight.current?.onPress({ x: x - rightDoubleTapBoundary, y, }); runOnJS(seekByStep)(false); return; } } }); /** * On toggle play * @returns */ const togglePlayOnJS = () => { if (isLoadEnd) { onReplyVideo(); setIsLoadEnd(false); } onTapPause?.(!paused); paused ? play() : pause(); }; const onPauseTapHandler = () => { 'worklet'; const status = checkTapTakesEffect(); if (!status) { return; } runOnJS(togglePlayOnJS)(); }; /** * on tap back * @returns */ const onBackTapHandlerOnJS = () => { Orientation.getOrientation(orientation => { if (isFullScreen.value || orientation !== OrientationType.PORTRAIT) { setIsFullscreen(false); exitFullScreen(); StatusBar.setHidden(false, 'fade'); } else { onTapBack?.(); } }); }; /** * When load starts we display a loading icon * and show the controls. */ const onLoadStart = () => { setIsLoading(true); }; /** * Toggle between showing time remaining or * video duration in the timer control */ const toggleTimerOnJS = () => { setShowTimeRemaining(!showTimeRemaining); }; const toggleTimer = () => { 'worklet'; const status = checkTapTakesEffect(); if (!status) { return; } runOnJS(toggleTimerOnJS)(); }; const onTapSlider = () => { if (disableControl) { return; } if (controlViewOpacity.value === 0) { showControlAnimation(); } }; /** * Calculate the time to show in the timer area * based on if they want to see time remaining * or duration. Formatted to look as 00:00. */ const calculateTime = () => { return showTimeRemaining ? `${formatTimeToMins(currentTime)}` : `-${formatTime({ time: duration - currentTime, duration: duration, })}`; }; /** * Seek to a time in the video. * * @param {float} time time to seek to in ms */ const seekTo = (time = 0) => { setCurrentTime(time); videoPlayer.current?.seek(time); }; const onLoad = (data: OnLoadData) => { setDuration(data?.duration); max.value = data?.duration; setIsLoading(false); setControlTimeout(); }; const onEnd = () => { setIsLoadEnd(true); pause(); onVideoPlayEnd?.(); }; /** * For onSeek we clear scrubbing if set. * * @param {object} data The video meta data */ const onSeek = (data: OnSeekData) => { if (isScrubbing.value) { // Seeking may be false here if the user released the seek bar while the player was still processing // the last seek command. In this case, perform the steps that have been postponed. if (!isSeeking.current) { setControlTimeout(); pause(); } isSeeking.current = false; isScrubbing.value = false; setCurrentTime(data.currentTime); } else { isSeeking.current = false; } }; /** * For onprogress we fire listeners that * update our seekbar and timer. * * @param {object} data The video meta data */ const onProgress = ({ currentTime: cTime }: OnProgressData) => { if (!isScrubbing.value) { if (!isSeeking.current) { progress.value = cTime; } setCurrentTime(cTime); } }; /** * on replay video */ const onReplyVideo = () => { seekTo(0); setCurrentTime(0); progress.value = 0; }; /** * play the video */ const play = () => { onPausedChange(false); }; /** * pause the video */ const pause = () => { onPausedChange(true); }; /** * on toggle auto play mode * @returns */ const toggleAutoPlayOnJS = () => { setAllowAutoPlayVideo(!allowAutoPlayVideo); onToggleAutoPlay?.(!allowAutoPlayVideo); }; const toggleAutoPlay = () => { 'worklet'; const status = checkTapTakesEffect(); if (!status) { return; } autoPlayAnimation.value = autoPlayAnimation.value === 0 ? 0.5 : 0; autoPlayTextAnimation.value = withTiming(1); autoPlayTextAnimation.value = withDelay(3000, withTiming(0)); runOnJS(toggleAutoPlayOnJS)(); }; const _renderMore = useCallback( () => ( <TapControler onPress={onMoreTapHandler}> {renderMore ? ( renderMore() ) : ( <Image source={require('./assets/more_24.png')} style={styles.more} /> )} </TapControler> ), // eslint-disable-next-line react-hooks/exhaustive-deps [renderMore], ); const onBackTapHandler = () => { 'worklet'; const status = checkTapTakesEffect(); if (!status) { return; } runOnJS(onBackTapHandlerOnJS)(); }; const _renderBack = useCallback( () => ( <TapControler onPress={onBackTapHandler}> {renderBackIcon ? ( renderBackIcon() ) : ( <Image source={require('./assets/right_16.png')} style={styles.back} /> )} </TapControler> ), // eslint-disable-next-line react-hooks/exhaustive-deps [renderBackIcon], ); const _renderFullScreenBack = useCallback( () => ( <TapControler onPress={onBackTapHandler}> {renderFullScreenBackIcon ? ( renderFullScreenBackIcon() ) : ( <Image source={require('./assets/right_16.png')} style={styles.back} /> )} </TapControler> ), // eslint-disable-next-line react-hooks/exhaustive-deps [renderBackIcon], ); const onMoreTapHandler = () => { 'worklet'; const status = checkTapTakesEffect(); if (!status) { return; } if (onTapMore) { runOnJS(onTapMore)(); } }; /** * Render the seekbar and attach its handlers */ const onSlidingComplete = (val: number) => { isSeeking.current = true; seekTo(val); }; const onSlidingStart = () => { clearControlTimeout(); }; const taps = Gesture.Exclusive(doubleTapHandle, singleTapHandler); const gesture = Gesture.Race(onPanGesture, taps); return ( <> <StatusBar barStyle={'light-content'} translucent backgroundColor={'#000'} /> <GestureDetector gesture={gesture}> <Animated.View style={[styles.container, videoStyle, style]}> <Video {...rest} ref={videoPlayer} resizeMode={resizeMode} paused={paused} onLoadStart={onLoadStart} style={styles.video} source={source} onLoad={onLoad} onSeek={onSeek} onEnd={onEnd} onProgress={onProgress} fullscreenAutorotate={true} /> <VideoLoader loading={loading} /> <Animated.View style={StyleSheet.absoluteFillObject}> <Animated.View style={[styles.controlView, controlViewStyles]}> <Animated.View hitSlop={hitSlop} style={[ controlStyle.group, styles.topControls, topControlStyle, ]}> {Boolean(onTapBack) && _renderBack()} <View style={controlStyle.line}> {Boolean(onToggleAutoPlay) && ( <Animated.View style={[controlStyle.autoPlayText, autoPlayTextStyle]}> <Text tx={ allowAutoPlayVideo ? onAutoPlayText : offAutoPlayText } t4 color={'#fff'} /> </Animated.View> )} {Boolean(onToggleAutoPlay) && ( <TapControler onPress={toggleAutoPlay} style={controlStyle.autoPlay}> <AnimatedLottieView animatedProps={autoPlayAnimatedProps} source={require('./assets/lottie-auto-play.json')} /> </TapControler> )} {Boolean(onTapMore) && _renderMore()} </View> </Animated.View> <Animated.View style={[ controlStyle.group, styles.topControls, styles.topFullscreenControls, topFullscreenControlStyle, ]} pointerEvents={isFullScreenState ? 'auto' : 'none'}> <View style={controlStyle.line}> {Boolean(onTapBack) && _renderFullScreenBack()} <Text tx={headerBarTitle} h5 numberOfLines={1} style={styles.headerBarTitle} color={palette.W(1)} /> </View> <View style={controlStyle.line}> {Boolean(onToggleAutoPlay) && ( <Animated.View style={[controlStyle.autoPlayText, autoPlayTextStyle]}> <Text tx={ allowAutoPlayVideo ? onAutoPlayText : offAutoPlayText } t4 color={'#fff'} /> </Animated.View> )} {Boolean(onToggleAutoPlay) && ( <TapControler onPress={toggleAutoPlay} style={controlStyle.autoPlay}> <AnimatedLottieView animatedProps={autoPlayAnimatedProps} source={require('./assets/lottie-auto-play.json')} /> </TapControler> )} {Boolean(onTapMore) && _renderMore()} </View> </Animated.View> <View style={controlStyle.pauseView}> <TapControler onPress={onPauseTapHandler} style={controlStyle.pause}> <AnimatedLottieView animatedProps={playAnimatedProps} source={require('./assets/lottie-play.json')} /> </TapControler> </View> <Animated.View style={[ controlStyle.group, controlStyle.bottomControls, bottomControlStyle, ]}> <View style={[controlStyle.bottomControlGroup, controlStyle.row]}> <TapControler onPress={toggleTimer}> <Text style={controlStyle.timerText}> <Text style={controlStyle.timerText} color={palette.W(1)} tx={calculateTime()} t3 /> <Text style={controlStyle.timerText} color={palette.W(1)} tx={` / ${formatTimeToMins(duration)}`} t3 /> </Text> </TapControler> <TapControler onPress={toggleFullScreen} style={controlStyle.fullToggle}> {renderFullScreen ? ( renderFullScreen() ) : ( <AnimatedLottieView animatedProps={fullscreenAnimatedProps} source={require('./assets/lottie-fullscreen.json')} /> )} </TapControler> </View> <Animated.View style={[ { width: height - insetsRef.current.top - insetsRef.current.bottom - 40, }, fullScreenSliderStyle, ]}> {duration > 0 && ( <Slider theme={theme} progress={progress} onSlidingComplete={onSlidingComplete} onSlidingStart={onSlidingStart} minimumValue={min} maximumValue={max} isScrubbing={isScrubbing} bubble={secondToTime} disableTapEvent onTap={onTapSlider} thumbScaleValue={controlViewOpacity} thumbWidth={8} sliderHeight={2} {...sliderProps} /> )} </Animated.View> </Animated.View> </Animated.View> <Ripple ref={rippleLeft} onAnimationEnd={() => { doubleLeftOpacity.value = 0; }} style={[controlStyle.doubleTap, controlStyle.leftDoubleTap]} containerStyle={[{ width: leftDoubleTapBoundary }]}> <Animated.View style={getDoubleLeftStyle}> <LottieView source={require('./assets/lottie-seek-back.json')} autoPlay loop style={controlStyle.backStep} /> <Text tx="10s" isCenter color={palette.W(1)} t5 /> </Animated.View> </Ripple> <Ripple ref={rippleRight} onAnimationEnd={() => { doubleRightOpacity.value = 0; }} style={[ controlStyle.doubleTap, controlStyle.rightDoubleTapContainer, ]} containerStyle={[{ width: leftDoubleTapBoundary }]}> <Animated.View style={getDoubleRightStyle}> <LottieView source={require('./assets/lottie-seek-back.json')} autoPlay loop style={[ controlStyle.backStep, { transform: [{ rotate: '90deg' }] }, ]} /> <Text tx="10s" isCenter color={palette.W(1)} t5 /> </Animated.View> </Ripple> <Animated.View style={[styles.slider, bottomSliderStyle]}> {duration > 0 && ( <Slider theme={theme} progress={progress} onSlidingComplete={onSlidingComplete} onSlidingStart={onSlidingStart} minimumValue={min} maximumValue={max} isScrubbing={isScrubbing} bubble={(value: number) => { return secondToTime(value); }} disableTapEvent onTap={onTapSlider} thumbScaleValue={controlViewOpacity} thumbWidth={12} sliderHeight={2} {...sliderProps} /> )} </Animated.View> </Animated.View> {isIos && ( <View style={[styles.stopBackView, { left: -insets.left }]} pointerEvents={isFullScreenState ? 'auto' : 'none'} /> )} </Animated.View> </GestureDetector> </> ); }, ); VideoPlayer.displayName = 'VideoPlayer'; export default VideoPlayer; const styles = StyleSheet.create({ controlView: { backgroundColor: 'rgba(0,0,0,.6)', justifyContent: 'center', overflow: 'hidden', ...StyleSheet.absoluteFillObject, }, headerBarTitle: { marginLeft: 20, maxWidth: height / 2, }, slider: { width: width, zIndex: 1, position: 'absolute', left: 0, right: 0, bottom: 0, }, stopBackView: { height: '100%', position: 'absolute', width: 40, }, topControls: { flexDirection: 'row', justifyContent: 'space-between', position: 'absolute', top: 12, width: '100%', }, topFullscreenControls: { top: 32, }, video: { width: '100%', height: '100%', }, back: { width: 16, height: 16, }, more: { width: 24, height: 24, }, container: { backgroundColor: palette.B(1), width: '100%', alignItems: 'center', elevation: 10, justifyContent: 'center', zIndex: 10, }, }); const controlStyle = StyleSheet.create({ autoPlay: { height: 24, marginRight: 32, width: 24, }, autoPlayText: { marginRight: 10, }, bottomControlGroup: { justifyContent: 'space-between', marginBottom: 10, }, bottomControls: { bottom: 0, position: 'absolute', width: '100%', }, fullToggle: { height: 20, width: 20, }, group: { paddingHorizontal: 20, }, line: { alignItems: 'center', flexDirection: 'row', }, pause: { height: 48, width: 48, }, pauseView: { alignSelf: 'center', }, row: { alignItems: 'center', flexDirection: 'row', }, timerText: { textAlign: 'right', }, doubleTap: { position: 'absolute', height: '100%', justifyContent: 'center', alignContent: 'center', alignItems: 'center', }, leftDoubleTap: { left: 0, borderTopRightRadius: width, borderBottomRightRadius: width, }, rightDoubleTapContainer: { borderTopLeftRadius: width, borderBottomLeftRadius: width, right: 0, }, backStep: { width: 40, height: 40, }, });
the_stack
import * as debug from '../debug' import { icons } from '../iconBase' import * as utils from '../utils' import * as widgets from '../widgets' import { solidLogicSingleton } from '../logic' import * as ns from '../ns' import { logInLoadProfile, selectWorkspace } from '../authn/authn' import { DataBrowserContext, NewPaneOptions, PaneDefinition } from 'pane-registry' import { CreateContext, NewAppInstanceOptions } from './types' const kb = solidLogicSingleton.store /* newThingUI -- return UI for user to select a new object, folder, etc ** ** context must include: dom, div, ** optional: folder: NamedNode -- the folder where the thing is bring put ** (suppresses asking for a full URI or workspace) ** */ export function newThingUI ( createContext: CreateContext, dataBrowserContext: DataBrowserContext, thePanes: Array<PaneDefinition> ): void { const dom = createContext.dom const div = createContext.div if (createContext.me && !createContext.me.uri) { throw new Error('newThingUI: Invalid userid: ' + createContext.me) } const iconStyle = 'padding: 0.7em; width: 2em; height: 2em;' // was: 'padding: 1em; width: 3em; height: 3em;' const star = div.appendChild(dom.createElement('img')) let visible = false // the inividual tools tools // noun_272948.svg = black star // noun_34653_green.svg = green plus star.setAttribute('src', icons.iconBase + 'noun_34653_green.svg') star.setAttribute('style', iconStyle) star.setAttribute('title', 'Add another tool') const complain = function complain (message) { const pre = div.appendChild(dom.createElement('pre')) pre.setAttribute('style', 'background-color: pink') pre.appendChild(dom.createTextNode(message)) } function styleTheIcons (style) { for (let i = 0; i < iconArray.length; i++) { let st = iconStyle + style if (iconArray[i].disabled) { // @@ unused st += 'opacity: 0.3;' } iconArray[i].setAttribute('style', st) // eg 'background-color: #ccc;' } } function selectTool (icon) { styleTheIcons('display: none;') // 'background-color: #ccc;' icon.setAttribute('style', iconStyle + 'background-color: yellow;') } function selectNewTool (_event?) { visible = !visible star.setAttribute( 'style', iconStyle + (visible ? 'background-color: yellow;' : '') ) styleTheIcons(visible ? '' : 'display: none;') } star.addEventListener('click', selectNewTool) function makeNewAppInstance (options: NewAppInstanceOptions) { return new Promise(function (resolve, reject) { let selectUI // , selectUIParent function callbackWS (ws, newBase) { logInLoadProfile(createContext).then( _context => { const newPaneOptions: NewPaneOptions = Object.assign({ newBase: newBase, folder: options.folder || undefined, workspace: ws }, options) for (const opt in options) { // get div, dom, me, folder, pane, refreshTable newPaneOptions[opt] = options[opt] } debug.log(`newThingUI: Minting new ${newPaneOptions.pane.name} at ${newPaneOptions.newBase}`) options.pane .mintNew!(dataBrowserContext, newPaneOptions) .then(function (newPaneOptions) { if (!newPaneOptions || !newPaneOptions.newInstance) { throw new Error('Cannot mint new - missing newInstance') } if (newPaneOptions.folder) { const tail = newPaneOptions.newInstance.uri.slice( newPaneOptions.folder.uri.length ) const isPackage = tail.includes('/') debug.log(' new thing is packge? ' + isPackage) if (isPackage) { kb.add( newPaneOptions.folder, ns.ldp('contains'), kb.sym(newPaneOptions.newBase), newPaneOptions.folder.doc() ) } else { // single file kb.add( newPaneOptions.folder, ns.ldp('contains'), newPaneOptions.newInstance, newPaneOptions.folder.doc() ) // Ping the patch system? } // @ts-ignore @@ TODO check whether refresh can exist here. Either fix type or remove unreachable code if (newPaneOptions.refreshTarget && newPaneOptions.refreshTarget.refresh) { // @@ TODO Remove the need to cast as any ;(newPaneOptions.refreshTarget as any).refresh() // Refresh the containing display } // selectUI.parentNode.removeChild(selectUI) It removes itself } else { const p = options.div.appendChild(dom.createElement('p')) p.setAttribute('style', 'font-size: 120%;') // Make link to new thing p.innerHTML = "Your <a target='_blank' href='" + newPaneOptions.newInstance.uri + "'><b>new " + options.noun + '</b></a> is ready to be set up. ' + "<br/><br/><a target='_blank' href='" + newPaneOptions.newInstance.uri + "'>Go to your new " + options.noun + '.</a>' // selectUI.parentNode.removeChild(selectUI) // Clean up // selectUIParent.removeChild(selectUI) // Clean up } selectNewTool() // toggle star to plain and menu vanish again }) .catch(function (err) { complain(err) reject(err) }) }, err => { // login fails complain('Error logging on: ' + err) } ) } // callbackWS const pa = options.pane // options.appPathSegment = pa.name // was 'edu.mit.solid.pane.' options.noun = pa.mintClass ? utils.label(pa.mintClass) : pa.name options.appPathSegment = options.noun.slice(0, 1).toUpperCase() + options.noun.slice(1) if (!options.folder) { // No folder given? Ask user for full URI selectUI = selectWorkspace(dom, { noun: options.noun, appPathSegment: options.appPathSegment }, callbackWS) options.div.appendChild(selectUI) // selectUIParent = options.div } else { const gotName = function (name) { if (!name) { // selectUIParent.removeChild(selectUI) itremves itself if cancelled selectNewTool() // toggle star to plain and menu vanish again } else { let uri = options.folder!.uri if (!uri.endsWith('/')) { uri = uri + '/' } uri = uri + encodeURIComponent(name) + '/' callbackWS(null, uri) } } widgets .askName( dom, kb, options.div, ns.foaf('name'), null, options.noun ) .then(gotName) // selectUI = getNameForm(dom, kb, options.noun, gotName) // options.div.appendChild(selectUI) // selectUIParent = options.div } }) } // makeNewAppInstance const iconArray: Array<any> = [] const mintingPanes = Object.values(thePanes).filter(pane => pane.mintNew) const mintingClassMap = mintingPanes.reduce((classMap, pane) => { if (pane.mintClass) { classMap[pane.mintClass.uri] = (classMap[pane.mintClass.uri] || 0) + 1 } return classMap }, {}) mintingPanes.forEach(pane => { // @@ TODO Remove the need to cast to any const icon: any = createContext.div.appendChild(dom.createElement('img')) icon.setAttribute('src', pane.icon) const noun = pane.mintClass ? mintingClassMap[pane.mintClass.uri] > 1 ? `${utils.label(pane.mintClass)} (using ${pane.name} pane)` : utils.label(pane.mintClass) : pane.name + ' @@' icon.setAttribute('title', 'Make new ' + noun) icon.setAttribute('style', iconStyle + 'display: none;') iconArray.push(icon) if (!icon.disabled) { icon.addEventListener('click', function (e) { selectTool(icon) makeNewAppInstance({ event: e, folder: createContext.folder || null, iconEle: icon, pane, noun, noIndexHTML: true, // do NOT @@ for now write a HTML file div: createContext.div, me: createContext.me, dom: createContext.dom, refreshTarget: createContext.refreshTarget }) }) } }) } // Form to get the name of a new thing before we create it // // Used in contacts for new groups, individuals. // /* function getNameForm (dom, kb, classLabel, gotNameCallback) { const form = dom.createElement('div') // form is broken as HTML behaviour can resurface on js error form.innerHTML = '<p>Name of new ' + classLabel + ':</p>' const namefield = dom.createElement('input') namefield.setAttribute('type', 'text') namefield.setAttribute('size', '30') namefield.setAttribute('style', style.textInputStyle) namefield.setAttribute('maxLength', '2048') // No arbitrary limits namefield.select() // focus next user input const gotName = function () { namefield.setAttribute('class', 'pendingedit') namefield.disabled = true continueButton.disabled = true cancel.disabled = true gotNameCallback(true, namefield.value) } namefield.addEventListener('keyup', function (e) { if (e.keyCode === 13) { gotName() } }, false) form.appendChild(namefield) form.appendChild(dom.createElement('br')) const cancel = form.appendChild(widgets.cancelButton(dom)) cancel.addEventListener('click', function (e) { form.parentNode.removeChild(form) gotNameCallback(false) }, false) const continueButton = form.appendChild(widgets.continueButton(dom)) continueButton.addEventListener('click', function (e) { gotName() }, false) return form } */
the_stack
import { expect } from "chai"; import * as _ from "lodash"; import * as nock from "nock"; import { AlexaPlatform, IVoxaIntentEvent, VoxaApp } from "../../src"; import { AlexaRequestBuilder, isAlexaEvent } from "./../tools"; import { variables } from "./../variables"; import { views } from "./../views"; const LIST_ID = "YW16bjEuYWNjb3VudC5BRkdDNTRFVFI1MkxIS1JMMjZQUkdEM0FYWkdBLVNIT1BQSU5HX0lURU0="; const LIST_NAME = "MY CUSTOM LIST"; const listMock = { lists: [ { listId: LIST_ID, name: "Alexa shopping list", state: "active", statusMap: [ { href: `/v2/householdlists/${LIST_ID}/active`, status: "active", }, { href: `/v2/householdlists/${LIST_ID}/completed`, status: "completed", }, ], version: 1, }, { listId: "YW16bjEuYWNjb3VudC5BRkdDNTRFVFI1MkxIS1JMMjZQUkdEM0FYWkdBLVRBU0s=", name: "Alexa to-do list", state: "active", statusMap: [ { href: "/v2/householdlists/YW16bjEuYWNjb3VudC5BRkdDNTRFVFI1MkxIS1JMMjZQUkdEM0FYWkdBLVRBU0s=/active", status: "active", }, { href: "/v2/householdlists/YW16bjEuYWNjb3VudC5BRkdDNTRFVFI1MkxIS1JMMjZQUkdEM0FYWkdBLVRBU0s=/completed", status: "completed", }, ], version: 1, }, ], }; const listCreatedMock = { listId: "listId", name: LIST_NAME, state: "active", statusMap: [ { href: "/v2/householdlists/c73aa488-ba0c-433a-a8c7-33f84b8361ba/active", status: "active", }, { href: "/v2/householdlists/c73aa488-ba0c-433a-a8c7-33f84b8361ba/completed", status: "completed", }, ], version: 1, }; const listByIdMock = { items: [{ id: "1", name: "milk" }, { id: "2", name: "eggs" }], listId: "listId", name: LIST_NAME, state: "active", version: 1, }; const itemCreatedMock = { createdTime: "Thu Aug 16 14:42:54 UTC 2018", href: "/v2/householdlists/c73aa488-ba0c-433a-a8c7-33f84b8361ba/items/0701d6ee-f407-458d-87ad-41b5bb8381bf", id: "id", status: "active", updatedTime: "Thu Aug 16 14:42:54 UTC 2018", value: "milk", version: 1, }; describe("Lists", () => { let event: any; let app: VoxaApp; let alexaSkill: AlexaPlatform; beforeEach(() => { const rb = new AlexaRequestBuilder(); app = new VoxaApp({ views, variables }); alexaSkill = new AlexaPlatform(app); event = rb.getIntentRequest("AddProductToListIntent", { productName: "milk", }); }); afterEach(() => { nock.cleanAll(); }); it("should create a custom list and create an item", async () => { const reqheaders = { authorization: `Bearer ${ event.context.System.user.permissions.consentToken }`, }; nock("https://api.amazonalexa.com", { reqheaders }) .persist() .get("/v2/householdlists/") .reply(200, JSON.stringify(listMock)) .persist() .post("/v2/householdlists/", { name: LIST_NAME, state: "active" }) .reply(200, JSON.stringify(listCreatedMock)) .persist() .post("/v2/householdlists/listId/items", { status: "active", value: "milk", }) .reply(200, JSON.stringify(itemCreatedMock)); alexaSkill.onIntent( "AddProductToListIntent", async (voxaEvent: IVoxaIntentEvent) => { const { productName } = _.get(voxaEvent, "intent.params"); let listInfo: any; if (isAlexaEvent(voxaEvent)) { listInfo = await voxaEvent.alexa.lists.getOrCreateList(LIST_NAME); } let listItem: any = _.find(listInfo.items, { name: productName }); if (listItem) { return false; } if (isAlexaEvent(voxaEvent)) { listItem = await voxaEvent.alexa.lists.createItem( listInfo.listId, productName, ); } if (listItem) { return { tell: "Lists.ProductCreated" }; } return { tell: "Lists.AlreadyCreated" }; }, ); const reply = await alexaSkill.execute(event); expect(_.get(reply, "response.outputSpeech.ssml")).to.include( "Product has been successfully created", ); expect(reply.response.reprompt).to.be.undefined; expect(_.get(reply, "sessionAttributes.state")).to.equal("die"); expect(reply.response.shouldEndSession).to.equal(true); }); it("should modify custom list, and modify an item", async () => { const reqheaders = { authorization: `Bearer ${ event.context.System.user.permissions.consentToken }`, }; const value = "NEW NAME"; const newListName = "NEW LIST"; const customListMock: any = _.cloneDeep(listMock); customListMock.lists.push({ listId: "listId", name: LIST_NAME }); const customItemCreatedMock: any = _.cloneDeep(itemCreatedMock); customItemCreatedMock.name = value; nock("https://api.amazonalexa.com", { reqheaders }) .persist() .get("/v2/householdlists/") .reply(200, JSON.stringify(customListMock)) .persist() .get("/v2/householdlists/listId/active") .reply(200, JSON.stringify(listByIdMock)) .persist() .put("/v2/householdlists/listId", { name: newListName, state: "active", version: 1, }) .reply(200, JSON.stringify(listByIdMock)) .persist() .put("/v2/householdlists/listId/items/1", { status: "active", value, version: 1, }) .reply(200, JSON.stringify(customItemCreatedMock)); event.request.intent.name = "ModifyProductInListIntent"; alexaSkill.onIntent( "ModifyProductInListIntent", async (voxaEvent: IVoxaIntentEvent) => { const { productName } = _.get(voxaEvent, "intent.params"); if (isAlexaEvent(voxaEvent)) { const listInfo = await voxaEvent.alexa.lists.getOrCreateList( LIST_NAME, ); listInfo.listId = listInfo.listId || ""; await voxaEvent.alexa.lists.updateList( listInfo.listId, newListName, "active", 1, ); const listItem: any = _.find(_.get(listInfo, "items"), { name: productName, }); await voxaEvent.alexa.lists.updateItem( listInfo.listId, listItem.id, value, "active", 1, ); } return { tell: "Lists.ProductModified" }; }, ); const reply = await alexaSkill.execute(event); expect(_.get(reply, "response.outputSpeech.ssml")).to.include( "Product has been successfully modified", ); expect(reply.response.reprompt).to.be.undefined; expect(_.get(reply, "sessionAttributes.state")).to.equal("die"); expect(reply.response.shouldEndSession).to.equal(true); }); it("should delete item from list, and delete list", async () => { const reqheaders = { authorization: `Bearer ${ event.context.System.user.permissions.consentToken }`, }; const value = "NEW NAME"; const customItemCreatedMock: any = _.cloneDeep(itemCreatedMock); customItemCreatedMock.name = value; nock("https://api.amazonalexa.com", { reqheaders }) .persist() .delete("/v2/householdlists/listId") .reply(200) .persist() .delete("/v2/householdlists/listId/items/1") .reply(200); event.request.intent.name = "DeleteIntent"; alexaSkill.onIntent("DeleteIntent", (voxaEvent: IVoxaIntentEvent) => { if (isAlexaEvent(voxaEvent)) { return voxaEvent.alexa.lists .deleteItem("listId", "1") .then(() => voxaEvent.alexa.lists.deleteList("listId")) .then(() => ({ tell: "Lists.ListDeleted" })); } }); const reply = await alexaSkill.execute(event); expect(_.get(reply, "response.outputSpeech.ssml")).to.include( "List has been successfully deleted", ); expect(reply.response.reprompt).to.be.undefined; expect(_.get(reply, "sessionAttributes.state")).to.equal("die"); expect(reply.response.shouldEndSession).to.equal(true); }); it("should show the lists with at least 1 item", async () => { const reqheaders = { authorization: `Bearer ${ event.context.System.user.permissions.consentToken }`, }; const value = "NEW NAME"; const newListName = "NEW LIST"; const customItemCreatedMock: any = _.cloneDeep(itemCreatedMock); customItemCreatedMock.name = value; const shoppintListMock = _.cloneDeep(listByIdMock); shoppintListMock.name = "Alexa shopping list"; const toDoListMock = _.cloneDeep(listByIdMock); toDoListMock.name = "Alexa to-do list"; nock("https://api.amazonalexa.com", { reqheaders }) .persist() .get("/v2/householdlists/") .reply(200, JSON.stringify(listMock)) .persist() .get("/v2/householdlists/listId/active") .reply(200, JSON.stringify(listByIdMock)) .persist() .get( "/v2/householdlists/YW16bjEuYWNjb3VudC5BRkdDNTRFVFI1MkxIS1JMMjZQUkdEM0FYWkdBLVNIT1BQSU5HX0lURU0=/active", ) .reply(200, JSON.stringify(shoppintListMock)) .persist() .get( "/v2/householdlists/YW16bjEuYWNjb3VudC5BRkdDNTRFVFI1MkxIS1JMMjZQUkdEM0FYWkdBLVRBU0s=/active", ) .reply(200, JSON.stringify(toDoListMock)) .persist() .put("/v2/householdlists/listId", { name: newListName, state: "active", version: 1, }) .reply(200, JSON.stringify(listByIdMock)) .persist() .put("/v2/householdlists/listId/items/1", { status: "active", value, version: 1, }) .reply(200, JSON.stringify(customItemCreatedMock)) .persist() .get("/v2/householdlists/listId/items/1") .reply(200, JSON.stringify(customItemCreatedMock)); event.request.intent.name = "ShowIntent"; alexaSkill.onIntent("ShowIntent", async (voxaEvent: IVoxaIntentEvent) => { const listsWithItems = []; if (isAlexaEvent(voxaEvent)) { const listMetadataInfo = await voxaEvent.alexa.lists.getDefaultShoppingList(); listMetadataInfo.listId = listMetadataInfo.listId || ""; let listInfo = await voxaEvent.alexa.lists.getListById( listMetadataInfo.listId, ); if (!_.isEmpty(listInfo.items)) { listsWithItems.push(listInfo.name); } listInfo = await voxaEvent.alexa.lists.getDefaultToDoList(); listInfo.listId = listInfo.listId || ""; listInfo = await voxaEvent.alexa.lists.getListById(listInfo.listId); if (!_.isEmpty(listInfo.items)) { listsWithItems.push(listInfo.name); } listInfo = await voxaEvent.alexa.lists.getListById("listId"); listInfo.listId = listInfo.listId || ""; if (!_.isEmpty(listInfo.items)) { listsWithItems.push(listInfo.name); } voxaEvent.model.listsWithItems = listsWithItems; let data: any = { name: newListName, state: "active", version: 1, }; listInfo = await voxaEvent.alexa.lists.updateList( listInfo.listId, data, ); listInfo.listId = listInfo.listId || ""; const itemInfo = await voxaEvent.alexa.lists.getListItem( listInfo.listId, "1", ); data = { status: itemInfo.status, value, version: 1, }; await voxaEvent.alexa.lists.updateItem(listInfo.listId, "1", data); } return { tell: "Lists.WithItems" }; }); const reply = await alexaSkill.execute(event); const outputSpeech = `Lists with items are: Alexa shopping list, Alexa to-do list, and ${LIST_NAME}`; expect(_.get(reply, "response.outputSpeech.ssml")).to.include(outputSpeech); expect(reply.response.reprompt).to.be.undefined; expect(_.get(reply, "sessionAttributes.state")).to.equal("die"); expect(reply.response.shouldEndSession).to.equal(true); }); });
the_stack
import { setupCategory } from "../utils/helpers"; import { useContentGqlHandler } from "../utils/useContentGqlHandler"; import mocks from "./mocks/workflows"; describe("Workflow assignment to a PB Page", () => { const options = { path: "manage/en-US" }; const { createWorkflowMutation, updateWorkflowMutation, listWorkflowsQuery, getWorkflowQuery, createCategory, getCategory, createPage, getPageQuery, publishPage, until, reviewer: reviewerGQL, securityIdentity } = useContentGqlHandler({ ...options }); const login = async () => { await securityIdentity.login(); }; const setupReviewer = async () => { await login(); await until( () => reviewerGQL.listReviewersQuery({}).then(([data]) => data), (response: any) => response.data.apw.listReviewers.data.length === 1, { name: "Wait for listReviewers" } ); const [listReviewersResponse] = await reviewerGQL.listReviewersQuery({}); const [reviewer] = listReviewersResponse.data.apw.listReviewers.data; return reviewer; }; const setup = async () => { const reviewer = await setupReviewer(); const category = await setupCategory({ getCategory, createCategory }); return { reviewer, category }; }; test("Page should have a workflow assigned right after create", async () => { const reviewer = await setupReviewer(); const category = await setupCategory({ getCategory, createCategory }); const workflows = []; /* Create 5 workflow entries */ for (let i = 0; i < 5; i++) { const createWorkflowInput = mocks.createWorkflow( { title: `Main review workflow - ${i + 1}`, app: i % 2 === 0 ? "pageBuilder" : "cms", scope: mocks.scopes[i] }, [reviewer] ); const [createWorkflowResponse] = await createWorkflowMutation({ data: createWorkflowInput }); const workflow = createWorkflowResponse.data.apw.createWorkflow.data; workflows.push(workflow); } await until( () => listWorkflowsQuery({}).then(([data]) => data), (response: any) => response.data.apw.listWorkflows.data.length === 5 ); const [firstWorkflow] = workflows; /** * Create a page and see what workflow has been assigned to it */ const [createPageResponse] = await createPage({ category: category.slug }); const createdPageData = createPageResponse.data.pageBuilder.createPage.data; expect(createdPageData.category.slug).toEqual(category.slug); expect(createdPageData.settings.apw.workflowId).toEqual(firstWorkflow.id); /** * New revision should also has the workflow assigned. */ const [createPageFromResponse] = await createPage({ from: createdPageData.id, category: category.slug }); const newRevisionData = createPageFromResponse.data.pageBuilder.createPage.data; expect(newRevisionData.settings.apw.workflowId).toEqual(firstWorkflow.id); }); test("Page should have the latest created workflow assigned in case of multiple matching workflows", async () => { const reviewer = await setupReviewer(); const category = await setupCategory({ getCategory, createCategory }); const workflows = []; const workflowScopes = mocks.getPageBuilderScope("", "static"); /* Create 5 workflow entries */ for (let i = 0; i < 5; i++) { const [createWorkflowResponse] = await createWorkflowMutation({ data: mocks.createWorkflow( { title: `Main review workflow - ${i + 1}`, app: "pageBuilder", scope: workflowScopes[i] }, [reviewer] ) }); const workflow = createWorkflowResponse.data.apw.createWorkflow.data; workflows.push(workflow); } await until( () => listWorkflowsQuery({}).then(([data]) => data), (response: any) => response.data.apw.listWorkflows.data.length === 5 ); /** * Create a page and see what workflow has been assigned to it */ const [createPageResponse] = await createPage({ category: category.slug }); const createdPageData = createPageResponse.data.pageBuilder.createPage.data; expect(createdPageData.category.slug).toEqual(category.slug); expect(createdPageData.settings.apw.workflowId).toEqual(workflows[3].id); }); test("Page should not have a workflow assigned in case of no workflow exist", async () => { const reviewer = await setupReviewer(); const category = await setupCategory({ getCategory, createCategory }); // Create a workflow entry const [createWorkflowResponse] = await createWorkflowMutation({ data: { ...mocks.createWorkflow({}, [reviewer]), app: "cms" } }); const workflow = createWorkflowResponse.data.apw.createWorkflow.data; await until( () => listWorkflowsQuery({}).then(([data]) => data), (response: any) => response.data.apw.listWorkflows.data.length === 1 ); // List workflows const [listWorkflowsResponse] = await listWorkflowsQuery({}); expect(listWorkflowsResponse).toEqual({ data: { apw: { listWorkflows: { data: [workflow], error: null, meta: { totalCount: 1, hasMoreItems: false, cursor: null } } } } }); // Create a page and check if there is a workflow assigned const [createPageResponse] = await createPage({ category: category.slug }); const createdPageData = createPageResponse.data.pageBuilder.createPage.data; expect(createdPageData.category.slug).toEqual(category.slug); expect(createdPageData.settings.apw).toEqual(null); }); test("Page should have the workflow assigned even when the workflow is created after page", async () => { const reviewer = await setupReviewer(); const category = await setupCategory({ getCategory, createCategory }); /** * Create a page even before a workflow is created. */ const [createPageResponse] = await createPage({ category: category.slug }); const page = createPageResponse.data.pageBuilder.createPage.data; expect(page.category.slug).toEqual(category.slug); expect(page.settings.apw).toEqual(null); /* Create a workflow. */ const [createWorkflowResponse] = await createWorkflowMutation({ data: mocks.createWorkflow( { title: `Main review workflow`, app: "pageBuilder", scope: { type: "pb", data: { pages: [page.pid] } } }, [reviewer] ) }); const workflow = createWorkflowResponse.data.apw.createWorkflow.data; await until( () => listWorkflowsQuery({}).then(([data]) => data), (response: any) => response.data.apw.listWorkflows.data.length === 1 ); /** * Now page should have this workflow assigned to it. */ const [getPageResponse] = await getPageQuery({ id: page.id }); expect(getPageResponse.data.pageBuilder.getPage.data.settings.apw.workflowId).toBe( workflow.id ); /** * Let's try creating one more workflow with same scope. */ /* Create a workflow. */ const [createAnotherWorkflowResponse] = await createWorkflowMutation({ data: mocks.createWorkflow( { title: `Main review workflow - 2`, app: "pageBuilder", scope: { type: "pb", data: { pages: [page.pid, page.pid + "999999"] } } }, [reviewer] ) }); const anotherWorkflowWithSameScope = createAnotherWorkflowResponse.data.apw.createWorkflow.data; /** * Now page should have new newly created workflow assigned to it. */ const [getPageResponseAgain] = await getPageQuery({ id: page.id }); expect(getPageResponseAgain.data.pageBuilder.getPage.data.settings.apw.workflowId).toBe( anotherWorkflowWithSameScope.id ); }); test("Pages should have the workflow assigned even after the workflow has been updated", async () => { const { reviewer, category } = await setup(); /** * Create two new pages while we don't have any workflow in the system. */ const pages = []; for (let i = 0; i < 2; i++) { const [createPageResponse] = await createPage({ category: category.slug }); const page = createPageResponse.data.pageBuilder.createPage.data; expect(page.category.slug).toEqual(category.slug); expect(page.settings.apw).toEqual(null); /* * Save it for later */ pages.push(page); } const [firstPage, secondPage] = pages; /* Create a workflow and add first page in its scope. */ const [createWorkflowResponse] = await createWorkflowMutation({ data: mocks.createWorkflow( { title: `Main review workflow`, app: "pageBuilder", scope: { type: "pb", data: { pages: [firstPage.pid] } } }, [reviewer] ) }); expect(createWorkflowResponse).toEqual({ data: { apw: { createWorkflow: { data: expect.any(Object), error: null } } } }); await until( () => listWorkflowsQuery({}).then(([data]) => data), (response: any) => response.data.apw.listWorkflows.data.length === 1 ); const workflow = createWorkflowResponse.data.apw.createWorkflow.data; /** * Now first page should have this workflow assigned to it. */ const [getPageResponse] = await getPageQuery({ id: firstPage.id }); expect(getPageResponse.data.pageBuilder.getPage.data.settings.apw).toEqual({ workflowId: workflow.id, contentReviewId: null }); /** * Let's update the workflow scope. */ const [updateWorkflowResponse] = await updateWorkflowMutation({ id: workflow.id, data: { title: workflow.title, steps: workflow.steps, scope: { type: "pb", data: { pages: [secondPage.pid] } } } }); await until( () => getWorkflowQuery({ id: workflow.id }).then(([data]) => data), (response: any) => response.data.apw.getWorkflow.data.savedOn !== workflow.savedOn, { name: "Wait for getWorkflow query" } ); const updatedWorkflow = updateWorkflowResponse.data.apw.updateWorkflow.data; expect(updatedWorkflow).toEqual({ id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "12345678", displayName: "John Doe", type: "admin" }, app: expect.any(String), title: expect.any(String), steps: [ { title: expect.any(String), id: expect.any(String), type: expect.any(String), reviewers: [expect.any(String)] } ], scope: { type: expect.any(String), data: { pages: [secondPage.pid] } } }); /** * Now second page should have this workflow assigned to it. */ const [getSecondPageResponse] = await getPageQuery({ id: secondPage.id }); expect(getSecondPageResponse.data.pageBuilder.getPage.data.settings.apw).toEqual({ workflowId: workflow.id, contentReviewId: null }); }); test(`Assign workflow to a "published" page`, async () => { const { reviewer, category } = await setup(); /** * Create two new pages while we don't have any workflow in the system. */ const pages = []; for (let i = 0; i < 2; i++) { const [createPageResponse] = await createPage({ category: category.slug }); const page = createPageResponse.data.pageBuilder.createPage.data; expect(page.category.slug).toEqual(category.slug); expect(page.settings.apw).toEqual(null); /* * Save it for later */ pages.push(page); } const [firstPage, secondPage] = pages; /** * Let's publish the second page. */ const [publishPageResponse] = await publishPage({ id: secondPage.id }); expect(publishPageResponse).toEqual({ data: { pageBuilder: { publishPage: { data: expect.any(Object), error: null } } } }); /* Create a workflow and add both pages in its scope. */ const [createWorkflowResponse] = await createWorkflowMutation({ data: mocks.createWorkflow( { title: `Main review workflow`, app: "pageBuilder", scope: { type: "pb", data: { pages: [firstPage.pid, secondPage.pid] } } }, [reviewer] ) }); expect(createWorkflowResponse).toEqual({ data: { apw: { createWorkflow: { data: expect.any(Object), error: null } } } }); await until( () => listWorkflowsQuery({}).then(([data]) => data), (response: any) => response.data.apw.listWorkflows.data.length === 1 ); const workflow = createWorkflowResponse.data.apw.createWorkflow.data; /** * Now first page should have this workflow assigned to it. */ const [getPageResponse] = await getPageQuery({ id: firstPage.id }); expect(getPageResponse.data.pageBuilder.getPage.data.settings.apw).toEqual({ workflowId: workflow.id, contentReviewId: null }); /** * But, second page should not have this workflow assigned to it. */ const [getSecondPageResponse] = await getPageQuery({ id: secondPage.id }); expect(getSecondPageResponse.data.pageBuilder.getPage.data.settings.apw).toBe(null); /** * Now, let's create a new revision of the second page i.e. published page. */ const [createPageFromResponse] = await createPage({ from: secondPage.id, category: category.slug }); expect(createPageFromResponse).toEqual({ data: { pageBuilder: { createPage: { data: expect.any(Object), error: null } } } }); const secondPageNewRevision = createPageFromResponse.data.pageBuilder.createPage.data; /** * Now, it should have a workflow assigned. */ expect(secondPageNewRevision.settings.apw).toEqual({ workflowId: workflow.id, contentReviewId: null }); }); test(`Should remove "workflowId" from a page after workflow update`, async () => { const { reviewer, category } = await setup(); /** * Create two new pages while we don't have any workflow in the system. */ const pages = []; for (let i = 0; i < 2; i++) { const [createPageResponse] = await createPage({ category: category.slug }); const page = createPageResponse.data.pageBuilder.createPage.data; expect(page.category.slug).toEqual(category.slug); expect(page.settings.apw).toEqual(null); /* * Save it for later */ pages.push(page); } const [firstPage, secondPage] = pages; /* * Create a workflow and add both pages in its scope. */ const [createWorkflowResponse] = await createWorkflowMutation({ data: mocks.createWorkflow( { title: `Main review workflow`, app: "pageBuilder", scope: { type: "pb", data: { pages: [firstPage.pid, secondPage.pid] } } }, [reviewer] ) }); expect(createWorkflowResponse).toEqual({ data: { apw: { createWorkflow: { data: expect.any(Object), error: null } } } }); await until( () => listWorkflowsQuery({}).then(([data]) => data), (response: any) => response.data.apw.listWorkflows.data.length === 1 ); const workflow = createWorkflowResponse.data.apw.createWorkflow.data; /** * Both pages should have this workflow assigned to them. */ for (let i = 0; i < pages.length; i++) { const [getPageResponse] = await getPageQuery({ id: pages[i].id }); expect(getPageResponse.data.pageBuilder.getPage.data.settings.apw).toEqual({ workflowId: workflow.id, contentReviewId: null }); } /** * Now, let's update the workflow such that second page is no longer in its scope. */ const [updateWorkflowResponse] = await updateWorkflowMutation({ id: workflow.id, data: { title: workflow.title, steps: workflow.steps, scope: { type: "pb", data: { pages: [firstPage.pid] } } } }); expect(updateWorkflowResponse).toEqual({ data: { apw: { updateWorkflow: { data: { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "12345678", displayName: "John Doe", type: "admin" }, app: expect.any(String), title: expect.any(String), steps: [ { title: expect.any(String), id: expect.any(String), type: expect.any(String), reviewers: [expect.any(String)] } ], scope: { type: expect.any(String), data: { pages: [firstPage.pid] } } }, error: null } } } }); /** * Now only firstPage should have the workflowId attached. */ const [getPageResponse] = await getPageQuery({ id: firstPage.id }); expect(getPageResponse.data.pageBuilder.getPage.data.settings.apw).toEqual({ workflowId: workflow.id, contentReviewId: null }); const [getPage2Response] = await getPageQuery({ id: secondPage.id }); expect(getPage2Response.data.pageBuilder.getPage.data.settings.apw).toEqual({ workflowId: null, contentReviewId: null }); }); });
the_stack
'use strict'; import * as nls from 'vs/nls'; import * as strings from 'vs/base/common/strings'; import { onUnexpectedError } from 'vs/base/common/errors'; import { EventEmitter, BulkListenerCallback } from 'vs/base/common/eventEmitter'; import { IDisposable, Disposable } from 'vs/base/common/lifecycle'; import { CursorCollection } from 'vs/editor/common/controller/cursorCollection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { Selection, SelectionDirection, ISelection } from 'vs/editor/common/core/selection'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { CursorColumns, CursorConfiguration, EditOperationResult, SingleCursorState, IViewModelHelper, CursorContext, CursorState, RevealTarget, IColumnSelectData, ICursors } from 'vs/editor/common/controller/cursorCommon'; import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry'; import { DeleteOperations } from 'vs/editor/common/controller/cursorDeleteOperations'; import { TypeOperations } from 'vs/editor/common/controller/cursorTypeOperations'; import { TextModelEventType, ModelRawContentChangedEvent, RawContentChangedType } from 'vs/editor/common/model/textModelEvents'; import { CursorEventType, CursorChangeReason, ICursorPositionChangedEvent, VerticalRevealType, ICursorSelectionChangedEvent, ICursorRevealRangeEvent, CursorScrollRequest } from 'vs/editor/common/controller/cursorEvents'; import { CommonEditorRegistry } from 'vs/editor/common/editorCommonExtensions'; import { CoreEditorCommand } from 'vs/editor/common/controller/coreCommands'; interface IMultipleCursorOperationContext { cursorPositionChangeReason: CursorChangeReason; shouldReveal: boolean; shouldPushStackElementBefore: boolean; shouldPushStackElementAfter: boolean; eventSource: string; eventData: any; executeCommands: editorCommon.ICommand[]; isAutoWhitespaceCommand: boolean[]; } interface IExecContext { selectionStartMarkers: string[]; positionMarkers: string[]; } interface ICommandData { operations: editorCommon.IIdentifiedSingleEditOperation[]; hadTrackedRange: boolean; hadTrackedEditOperation: boolean; } interface ICommandsData { operations: editorCommon.IIdentifiedSingleEditOperation[]; hadTrackedRanges: boolean[]; anyoneHadTrackedRange: boolean; anyoneHadTrackedEditOperation: boolean; } export class Cursor extends Disposable implements ICursors { public onDidChangePosition(listener: (e: ICursorPositionChangedEvent) => void): IDisposable { return this._eventEmitter.addListener(CursorEventType.CursorPositionChanged, listener); } public onDidChangeSelection(listener: (e: ICursorSelectionChangedEvent) => void): IDisposable { return this._eventEmitter.addListener(CursorEventType.CursorSelectionChanged, listener); } private configuration: editorCommon.IConfiguration; public context: CursorContext; private model: editorCommon.IModel; private _eventEmitter: EventEmitter; public addBulkListener(listener: BulkListenerCallback): IDisposable { return this._eventEmitter.addBulkListener(listener); } private cursors: CursorCollection; private viewModelHelper: IViewModelHelper; private _isHandling: boolean; private _isDoingComposition: boolean; private _columnSelectData: IColumnSelectData; private enableEmptySelectionClipboard: boolean; private _handlers: { [key: string]: (ctx: IMultipleCursorOperationContext) => void; }; constructor(configuration: editorCommon.IConfiguration, model: editorCommon.IModel, viewModelHelper: IViewModelHelper, enableEmptySelectionClipboard: boolean) { super(); this._eventEmitter = this._register(new EventEmitter()); this.configuration = configuration; this.model = model; this.viewModelHelper = viewModelHelper; this.enableEmptySelectionClipboard = enableEmptySelectionClipboard; const createCursorContext = () => { const config = new CursorConfiguration( this.model.getLanguageIdentifier(), this.model.getOneIndent(), this.model.getOptions(), this.configuration ); this.context = new CursorContext( this.model, this.viewModelHelper, config ); if (this.cursors) { this.cursors.updateContext(this.context); } }; createCursorContext(); this.cursors = new CursorCollection(this.context); this._isHandling = false; this._isDoingComposition = false; this._columnSelectData = null; this._register(this.model.addBulkListener((events) => { if (this._isHandling) { return; } let hadContentChange = false; let hadFlushEvent = false; for (let i = 0, len = events.length; i < len; i++) { const event = events[i]; const eventType = event.type; if (eventType === TextModelEventType.ModelRawContentChanged2) { hadContentChange = true; const changeEvent = <ModelRawContentChangedEvent>event.data; for (let j = 0, lenJ = changeEvent.changes.length; j < lenJ; j++) { const change = changeEvent.changes[j]; if (change.changeType === RawContentChangedType.Flush) { hadFlushEvent = true; } } } } if (!hadContentChange) { return; } this._onModelContentChanged(hadFlushEvent); })); this._register(this.model.onDidChangeLanguage((e) => { createCursorContext(); })); this._register(LanguageConfigurationRegistry.onDidChange(() => { // TODO@Alex: react only if certain supports changed? (and if my model's mode changed) createCursorContext(); })); this._register(model.onDidChangeOptions(() => { createCursorContext(); })); this._register(this.configuration.onDidChange((e) => { if (CursorConfiguration.shouldRecreate(e)) { createCursorContext(); } })); this._handlers = {}; this._registerHandlers(); } public dispose(): void { this.model = null; this.cursors.dispose(); this.cursors = null; this.configuration = null; this.viewModelHelper = null; super.dispose(); } public getPrimaryCursor(): CursorState { return this.cursors.getPrimaryCursor(); } public getLastAddedCursorIndex(): number { return this.cursors.getLastAddedCursorIndex(); } public getAll(): CursorState[] { return this.cursors.getAll(); } public setStates(source: string, reason: CursorChangeReason, states: CursorState[]): void { const oldSelections = this.cursors.getSelections(); const oldViewSelections = this.cursors.getViewSelections(); // TODO@Alex // ensure valid state on all cursors // this.cursors.ensureValidState(); this.cursors.setStates(states); this.cursors.normalize(); this._columnSelectData = null; const newSelections = this.cursors.getSelections(); const newViewSelections = this.cursors.getViewSelections(); let somethingChanged = false; if (oldSelections.length !== newSelections.length) { somethingChanged = true; } else { for (let i = 0, len = oldSelections.length; !somethingChanged && i < len; i++) { if (!oldSelections[i].equalsSelection(newSelections[i])) { somethingChanged = true; } } for (let i = 0, len = oldViewSelections.length; !somethingChanged && i < len; i++) { if (!oldViewSelections[i].equalsSelection(newViewSelections[i])) { somethingChanged = true; } } } if (somethingChanged) { this.emitCursorPositionChanged(source, reason); this.emitCursorSelectionChanged(source, reason); } } public setColumnSelectData(columnSelectData: IColumnSelectData): void { this._columnSelectData = columnSelectData; } public reveal(horizontal: boolean, target: RevealTarget): void { this._revealRange(target, VerticalRevealType.Simple, horizontal); } public revealRange(revealHorizontal: boolean, modelRange: Range, viewRange: Range, verticalType: VerticalRevealType) { this.emitCursorRevealRange(modelRange, viewRange, verticalType, revealHorizontal); } public scrollTo(desiredScrollTop: number): void { this._eventEmitter.emit(CursorEventType.CursorScrollRequest, new CursorScrollRequest( desiredScrollTop )); } public saveState(): editorCommon.ICursorState[] { var selections = this.cursors.getSelections(), result: editorCommon.ICursorState[] = [], selection: Selection; for (var i = 0; i < selections.length; i++) { selection = selections[i]; result.push({ inSelectionMode: !selection.isEmpty(), selectionStart: { lineNumber: selection.selectionStartLineNumber, column: selection.selectionStartColumn, }, position: { lineNumber: selection.positionLineNumber, column: selection.positionColumn, } }); } return result; } public restoreState(states: editorCommon.ICursorState[]): void { var desiredSelections: ISelection[] = [], state: editorCommon.ICursorState; for (var i = 0; i < states.length; i++) { state = states[i]; var positionLineNumber = 1, positionColumn = 1; // Avoid missing properties on the literal if (state.position && state.position.lineNumber) { positionLineNumber = state.position.lineNumber; } if (state.position && state.position.column) { positionColumn = state.position.column; } var selectionStartLineNumber = positionLineNumber, selectionStartColumn = positionColumn; // Avoid missing properties on the literal if (state.selectionStart && state.selectionStart.lineNumber) { selectionStartLineNumber = state.selectionStart.lineNumber; } if (state.selectionStart && state.selectionStart.column) { selectionStartColumn = state.selectionStart.column; } desiredSelections.push({ selectionStartLineNumber: selectionStartLineNumber, selectionStartColumn: selectionStartColumn, positionLineNumber: positionLineNumber, positionColumn: positionColumn }); } this._onHandler('restoreState', (ctx: IMultipleCursorOperationContext) => { this.cursors.setSelections(desiredSelections); return false; }, 'restoreState', null); } private _onModelContentChanged(hadFlushEvent: boolean): void { if (hadFlushEvent) { // a model.setValue() was called this.cursors.dispose(); this.cursors = new CursorCollection(this.context); this.emitCursorPositionChanged('model', CursorChangeReason.ContentFlush); this.emitCursorSelectionChanged('model', CursorChangeReason.ContentFlush); } else { if (!this._isHandling) { // Read the markers before entering `_onHandler`, since that would validate // the position and ruin the markers const selectionsFromMarkers = this.cursors.readSelectionFromMarkers(); this._onHandler('recoverSelectionFromMarkers', (ctx: IMultipleCursorOperationContext) => { ctx.cursorPositionChangeReason = CursorChangeReason.RecoverFromMarkers; ctx.shouldReveal = false; ctx.shouldPushStackElementBefore = false; ctx.shouldPushStackElementAfter = false; this.cursors.setSelections(selectionsFromMarkers); }, 'modelChange', null); } } } // ------ some getters/setters public getSelection(): Selection { return this.cursors.getPrimaryCursor().modelState.selection; } public getSelections(): Selection[] { return this.cursors.getSelections(); } public getPosition(): Position { return this.cursors.getPrimaryCursor().modelState.position; } public setSelections(source: string, selections: ISelection[]): void { this._onHandler('setSelections', (ctx: IMultipleCursorOperationContext) => { ctx.shouldReveal = false; this.cursors.setSelections(selections); return false; }, source, null); } // ------ auxiliary handling logic private _createAndInterpretHandlerCtx(eventSource: string, eventData: any, callback: (currentHandlerCtx: IMultipleCursorOperationContext) => void): void { var ctx: IMultipleCursorOperationContext = { cursorPositionChangeReason: CursorChangeReason.NotSet, shouldReveal: true, eventSource: eventSource, eventData: eventData, executeCommands: [], isAutoWhitespaceCommand: [], shouldPushStackElementBefore: false, shouldPushStackElementAfter: false }; callback(ctx); this._interpretHandlerContext(ctx); this.cursors.normalize(); } private _onHandler(command: string, handler: (ctx: IMultipleCursorOperationContext) => void, source: string, data: any): void { this._isHandling = true; try { const oldSelections = this.cursors.getSelections(); const oldViewSelections = this.cursors.getViewSelections(); // ensure valid state on all cursors this.cursors.ensureValidState(); let cursorPositionChangeReason: CursorChangeReason; let shouldReveal: boolean; this._createAndInterpretHandlerCtx(source, data, (currentHandlerCtx: IMultipleCursorOperationContext) => { handler(currentHandlerCtx); cursorPositionChangeReason = currentHandlerCtx.cursorPositionChangeReason; shouldReveal = currentHandlerCtx.shouldReveal; }); const newSelections = this.cursors.getSelections(); const newViewSelections = this.cursors.getViewSelections(); let somethingChanged = false; if (oldSelections.length !== newSelections.length) { somethingChanged = true; } else { for (let i = 0, len = oldSelections.length; !somethingChanged && i < len; i++) { if (!oldSelections[i].equalsSelection(newSelections[i])) { somethingChanged = true; } } for (let i = 0, len = oldViewSelections.length; !somethingChanged && i < len; i++) { if (!oldViewSelections[i].equalsSelection(newViewSelections[i])) { somethingChanged = true; } } } if (somethingChanged) { this.emitCursorPositionChanged(source, cursorPositionChangeReason); if (shouldReveal) { this._revealRange(RevealTarget.Primary, VerticalRevealType.Simple, true); } this.emitCursorSelectionChanged(source, cursorPositionChangeReason); } } catch (err) { onUnexpectedError(err); } this._isHandling = false; } private _interpretHandlerContext(ctx: IMultipleCursorOperationContext): void { if (ctx.shouldPushStackElementBefore) { this.model.pushStackElement(); ctx.shouldPushStackElementBefore = false; } this._columnSelectData = null; this._internalExecuteCommands(ctx.executeCommands, ctx.isAutoWhitespaceCommand); ctx.executeCommands = []; if (ctx.shouldPushStackElementAfter) { this.model.pushStackElement(); ctx.shouldPushStackElementAfter = false; } } private _interpretCommandResult(cursorState: Selection[]): void { if (!cursorState || cursorState.length === 0) { return; } this.cursors.setSelections(cursorState); } private _getEditOperationsFromCommand(ctx: IExecContext, majorIdentifier: number, command: editorCommon.ICommand, isAutoWhitespaceCommand: boolean): ICommandData { // This method acts as a transaction, if the command fails // everything it has done is ignored var operations: editorCommon.IIdentifiedSingleEditOperation[] = [], operationMinor = 0; var addEditOperation = (selection: Range, text: string) => { if (selection.isEmpty() && text === '') { // This command wants to add a no-op => no thank you return; } operations.push({ identifier: { major: majorIdentifier, minor: operationMinor++ }, range: selection, text: text, forceMoveMarkers: false, isAutoWhitespaceEdit: isAutoWhitespaceCommand }); }; var hadTrackedEditOperation = false; var addTrackedEditOperation = (selection: Range, text: string) => { hadTrackedEditOperation = true; addEditOperation(selection, text); }; var hadTrackedRange = false; var trackSelection = (selection: Selection, trackPreviousOnEmpty?: boolean) => { var selectionMarkerStickToPreviousCharacter: boolean, positionMarkerStickToPreviousCharacter: boolean; if (selection.isEmpty()) { // Try to lock it with surrounding text if (typeof trackPreviousOnEmpty === 'boolean') { selectionMarkerStickToPreviousCharacter = trackPreviousOnEmpty; positionMarkerStickToPreviousCharacter = trackPreviousOnEmpty; } else { var maxLineColumn = this.model.getLineMaxColumn(selection.startLineNumber); if (selection.startColumn === maxLineColumn) { selectionMarkerStickToPreviousCharacter = true; positionMarkerStickToPreviousCharacter = true; } else { selectionMarkerStickToPreviousCharacter = false; positionMarkerStickToPreviousCharacter = false; } } } else { if (selection.getDirection() === SelectionDirection.LTR) { selectionMarkerStickToPreviousCharacter = false; positionMarkerStickToPreviousCharacter = true; } else { selectionMarkerStickToPreviousCharacter = true; positionMarkerStickToPreviousCharacter = false; } } var l = ctx.selectionStartMarkers.length; ctx.selectionStartMarkers[l] = this.model._addMarker(0, selection.selectionStartLineNumber, selection.selectionStartColumn, selectionMarkerStickToPreviousCharacter); ctx.positionMarkers[l] = this.model._addMarker(0, selection.positionLineNumber, selection.positionColumn, positionMarkerStickToPreviousCharacter); return l.toString(); }; var editOperationBuilder: editorCommon.IEditOperationBuilder = { addEditOperation: addEditOperation, addTrackedEditOperation: addTrackedEditOperation, trackSelection: trackSelection }; try { command.getEditOperations(this.model, editOperationBuilder); } catch (e) { e.friendlyMessage = nls.localize('corrupt.commands', "Unexpected exception while executing command."); onUnexpectedError(e); return { operations: [], hadTrackedRange: false, hadTrackedEditOperation: false }; } return { operations: operations, hadTrackedRange: hadTrackedRange, hadTrackedEditOperation: hadTrackedEditOperation }; } private _getEditOperations(ctx: IExecContext, commands: editorCommon.ICommand[], isAutoWhitespaceCommand: boolean[]): ICommandsData { var oneResult: ICommandData; var operations: editorCommon.IIdentifiedSingleEditOperation[] = []; var hadTrackedRanges: boolean[] = []; var anyoneHadTrackedEditOperation: boolean = false; var anyoneHadTrackedRange: boolean; for (var i = 0; i < commands.length; i++) { if (commands[i]) { oneResult = this._getEditOperationsFromCommand(ctx, i, commands[i], isAutoWhitespaceCommand[i]); operations = operations.concat(oneResult.operations); hadTrackedRanges[i] = oneResult.hadTrackedRange; anyoneHadTrackedRange = anyoneHadTrackedRange || hadTrackedRanges[i]; anyoneHadTrackedEditOperation = anyoneHadTrackedEditOperation || oneResult.hadTrackedEditOperation; } else { hadTrackedRanges[i] = false; } } return { operations: operations, hadTrackedRanges: hadTrackedRanges, anyoneHadTrackedRange: anyoneHadTrackedRange, anyoneHadTrackedEditOperation: anyoneHadTrackedEditOperation }; } private _getLoserCursorMap(operations: editorCommon.IIdentifiedSingleEditOperation[]): { [index: string]: boolean; } { // This is destructive on the array operations = operations.slice(0); // Sort operations with last one first operations.sort((a: editorCommon.IIdentifiedSingleEditOperation, b: editorCommon.IIdentifiedSingleEditOperation): number => { // Note the minus! return -(Range.compareRangesUsingEnds(a.range, b.range)); }); // Operations can not overlap! var loserCursorsMap: { [index: string]: boolean; } = {}; var previousOp: editorCommon.IIdentifiedSingleEditOperation; var currentOp: editorCommon.IIdentifiedSingleEditOperation; var loserMajor: number; for (var i = 1; i < operations.length; i++) { previousOp = operations[i - 1]; currentOp = operations[i]; if (previousOp.range.getStartPosition().isBefore(currentOp.range.getEndPosition())) { if (previousOp.identifier.major > currentOp.identifier.major) { // previousOp loses the battle loserMajor = previousOp.identifier.major; } else { loserMajor = currentOp.identifier.major; } loserCursorsMap[loserMajor.toString()] = true; for (var j = 0; j < operations.length; j++) { if (operations[j].identifier.major === loserMajor) { operations.splice(j, 1); if (j < i) { i--; } j--; } } if (i > 0) { i--; } } } return loserCursorsMap; } private _internalExecuteCommands(commands: editorCommon.ICommand[], isAutoWhitespaceCommand: boolean[]): void { var ctx: IExecContext = { selectionStartMarkers: [], positionMarkers: [] }; this._innerExecuteCommands(ctx, commands, isAutoWhitespaceCommand); for (var i = 0; i < ctx.selectionStartMarkers.length; i++) { this.model._removeMarker(ctx.selectionStartMarkers[i]); this.model._removeMarker(ctx.positionMarkers[i]); } } private _arrayIsEmpty(commands: editorCommon.ICommand[]): boolean { var i: number, len: number; for (i = 0, len = commands.length; i < len; i++) { if (commands[i]) { return false; } } return true; } private _innerExecuteCommands(ctx: IExecContext, commands: editorCommon.ICommand[], isAutoWhitespaceCommand: boolean[]): void { if (this.configuration.editor.readOnly) { return; } if (this._arrayIsEmpty(commands)) { return; } var selectionsBefore = this.cursors.getSelections(); var commandsData = this._getEditOperations(ctx, commands, isAutoWhitespaceCommand); if (commandsData.operations.length === 0 && !commandsData.anyoneHadTrackedRange) { return; } var rawOperations = commandsData.operations; var editableRange = this.model.getEditableRange(); var editableRangeStart = editableRange.getStartPosition(); var editableRangeEnd = editableRange.getEndPosition(); for (var i = 0; i < rawOperations.length; i++) { var operationRange = rawOperations[i].range; if (!editableRangeStart.isBeforeOrEqual(operationRange.getStartPosition()) || !operationRange.getEndPosition().isBeforeOrEqual(editableRangeEnd)) { // These commands are outside of the editable range return; } } var loserCursorsMap = this._getLoserCursorMap(rawOperations); if (loserCursorsMap.hasOwnProperty('0')) { // These commands are very messed up console.warn('Ignoring commands'); return; } // Remove operations belonging to losing cursors var filteredOperations: editorCommon.IIdentifiedSingleEditOperation[] = []; for (var i = 0; i < rawOperations.length; i++) { if (!loserCursorsMap.hasOwnProperty(rawOperations[i].identifier.major.toString())) { filteredOperations.push(rawOperations[i]); } } // TODO@Alex: find a better way to do this. // give the hint that edit operations are tracked to the model if (commandsData.anyoneHadTrackedEditOperation && filteredOperations.length > 0) { filteredOperations[0]._isTracked = true; } var selectionsAfter = this.model.pushEditOperations(selectionsBefore, filteredOperations, (inverseEditOperations: editorCommon.IIdentifiedSingleEditOperation[]): Selection[] => { var groupedInverseEditOperations: editorCommon.IIdentifiedSingleEditOperation[][] = []; for (var i = 0; i < selectionsBefore.length; i++) { groupedInverseEditOperations[i] = []; } for (var i = 0; i < inverseEditOperations.length; i++) { var op = inverseEditOperations[i]; if (!op.identifier) { // perhaps auto whitespace trim edits continue; } groupedInverseEditOperations[op.identifier.major].push(op); } var minorBasedSorter = (a: editorCommon.IIdentifiedSingleEditOperation, b: editorCommon.IIdentifiedSingleEditOperation) => { return a.identifier.minor - b.identifier.minor; }; var cursorSelections: Selection[] = []; for (var i = 0; i < selectionsBefore.length; i++) { if (groupedInverseEditOperations[i].length > 0 || commandsData.hadTrackedRanges[i]) { groupedInverseEditOperations[i].sort(minorBasedSorter); cursorSelections[i] = commands[i].computeCursorState(this.model, { getInverseEditOperations: () => { return groupedInverseEditOperations[i]; }, getTrackedSelection: (id: string) => { var idx = parseInt(id, 10); var selectionStartMarker = this.model._getMarker(ctx.selectionStartMarkers[idx]); var positionMarker = this.model._getMarker(ctx.positionMarkers[idx]); return new Selection(selectionStartMarker.lineNumber, selectionStartMarker.column, positionMarker.lineNumber, positionMarker.column); } }); } else { cursorSelections[i] = selectionsBefore[i]; } } return cursorSelections; }); // Extract losing cursors var losingCursorIndex: string; var losingCursors: number[] = []; for (losingCursorIndex in loserCursorsMap) { if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) { losingCursors.push(parseInt(losingCursorIndex, 10)); } } // Sort losing cursors descending losingCursors.sort((a: number, b: number): number => { return b - a; }); // Remove losing cursors for (var i = 0; i < losingCursors.length; i++) { selectionsAfter.splice(losingCursors[i], 1); } this._interpretCommandResult(selectionsAfter); } // ----------------------------------------------------------------------------------------------------------- // ----- emitting events private emitCursorPositionChanged(source: string, reason: CursorChangeReason): void { var positions = this.cursors.getPositions(); var primaryPosition = positions[0]; var secondaryPositions = positions.slice(1); var viewPositions = this.cursors.getViewPositions(); var primaryViewPosition = viewPositions[0]; var secondaryViewPositions = viewPositions.slice(1); var isInEditableRange: boolean = true; if (this.model.hasEditableRange()) { var editableRange = this.model.getEditableRange(); if (!editableRange.containsPosition(primaryPosition)) { isInEditableRange = false; } } var e: ICursorPositionChangedEvent = { position: primaryPosition, viewPosition: primaryViewPosition, secondaryPositions: secondaryPositions, secondaryViewPositions: secondaryViewPositions, reason: reason, source: source, isInEditableRange: isInEditableRange }; this._eventEmitter.emit(CursorEventType.CursorPositionChanged, e); } private emitCursorSelectionChanged(source: string, reason: CursorChangeReason): void { let selections = this.cursors.getSelections(); let primarySelection = selections[0]; let secondarySelections = selections.slice(1); let viewSelections = this.cursors.getViewSelections(); let primaryViewSelection = viewSelections[0]; let secondaryViewSelections = viewSelections.slice(1); let e: ICursorSelectionChangedEvent = { selection: primarySelection, viewSelection: primaryViewSelection, secondarySelections: secondarySelections, secondaryViewSelections: secondaryViewSelections, source: source || 'keyboard', reason: reason }; this._eventEmitter.emit(CursorEventType.CursorSelectionChanged, e); } private _revealRange(revealTarget: RevealTarget, verticalType: VerticalRevealType, revealHorizontal: boolean): void { var positions = this.cursors.getPositions(); var viewPositions = this.cursors.getViewPositions(); var position = positions[0]; var viewPosition = viewPositions[0]; if (revealTarget === RevealTarget.TopMost) { for (var i = 1; i < positions.length; i++) { if (positions[i].isBefore(position)) { position = positions[i]; viewPosition = viewPositions[i]; } } } else if (revealTarget === RevealTarget.BottomMost) { for (var i = 1; i < positions.length; i++) { if (position.isBeforeOrEqual(positions[i])) { position = positions[i]; viewPosition = viewPositions[i]; } } } else { if (positions.length > 1) { // no revealing! return; } } var range = new Range(position.lineNumber, position.column, position.lineNumber, position.column); var viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column); this.emitCursorRevealRange(range, viewRange, verticalType, revealHorizontal); } public emitCursorRevealRange(range: Range, viewRange: Range, verticalType: VerticalRevealType, revealHorizontal: boolean) { var e: ICursorRevealRangeEvent = { range: range, viewRange: viewRange, verticalType: verticalType, revealHorizontal: revealHorizontal }; this._eventEmitter.emit(CursorEventType.CursorRevealRange, e); } // ----------------------------------------------------------------------------------------------------------- // ----- handlers beyond this point public trigger(source: string, handlerId: string, payload: any): void { if (!this._handlers.hasOwnProperty(handlerId)) { const command = CommonEditorRegistry.getEditorCommand(handlerId); if (!command || !(command instanceof CoreEditorCommand)) { return; } payload = payload || {}; payload.source = source; command.runCoreEditorCommand(this, payload); return; } let handler = this._handlers[handlerId]; this._onHandler(handlerId, handler, source, payload); } private _registerHandlers(): void { let H = editorCommon.Handler; this._handlers[H.LineInsertBefore] = (ctx) => this._lineInsertBefore(ctx); this._handlers[H.LineInsertAfter] = (ctx) => this._lineInsertAfter(ctx); this._handlers[H.LineBreakInsert] = (ctx) => this._lineBreakInsert(ctx); this._handlers[H.Type] = (ctx) => this._type(ctx); this._handlers[H.ReplacePreviousChar] = (ctx) => this._replacePreviousChar(ctx); this._handlers[H.CompositionStart] = (ctx) => this._compositionStart(ctx); this._handlers[H.CompositionEnd] = (ctx) => this._compositionEnd(ctx); this._handlers[H.Tab] = (ctx) => this._tab(ctx); this._handlers[H.Indent] = (ctx) => this._indent(ctx); this._handlers[H.Outdent] = (ctx) => this._outdent(ctx); this._handlers[H.Paste] = (ctx) => this._paste(ctx); this._handlers[H.DeleteLeft] = (ctx) => this._deleteLeft(ctx); this._handlers[H.DeleteRight] = (ctx) => this._deleteRight(ctx); this._handlers[H.Cut] = (ctx) => this._cut(ctx); this._handlers[H.Undo] = (ctx) => this._undo(ctx); this._handlers[H.Redo] = (ctx) => this._redo(ctx); this._handlers[H.ExecuteCommand] = (ctx) => this._externalExecuteCommand(ctx); this._handlers[H.ExecuteCommands] = (ctx) => this._externalExecuteCommands(ctx); } public getColumnSelectData(): IColumnSelectData { if (this._columnSelectData) { return this._columnSelectData; } const primaryCursor = this.cursors.getPrimaryCursor(); const primaryPos = primaryCursor.viewState.position; return { toViewLineNumber: primaryPos.lineNumber, toViewVisualColumn: CursorColumns.visibleColumnFromColumn2(this.context.config, this.context.viewModel, primaryPos) }; } // -------------------- START editing operations private _applyEdits(ctx: IMultipleCursorOperationContext, edits: EditOperationResult): void { ctx.shouldReveal = true; ctx.shouldPushStackElementBefore = edits.shouldPushStackElementBefore; ctx.shouldPushStackElementAfter = edits.shouldPushStackElementAfter; const commands = edits.commands; for (let i = 0, len = commands.length; i < len; i++) { const command = commands[i]; ctx.executeCommands[i] = command ? command.command : null; ctx.isAutoWhitespaceCommand[i] = command ? command.isAutoWhitespaceCommand : false; } } private _getAllCursorsModelState(sorted: boolean = false): SingleCursorState[] { let cursors = this.cursors.getAll(); if (sorted) { cursors = cursors.sort((a, b) => { return Range.compareRangesUsingStarts(a.modelState.selection, b.modelState.selection); }); } let r: SingleCursorState[] = []; for (let i = 0, len = cursors.length; i < len; i++) { r[i] = cursors[i].modelState; } return r; } private _lineInsertBefore(ctx: IMultipleCursorOperationContext): void { this._applyEdits(ctx, TypeOperations.lineInsertBefore(this.context.config, this.context.model, this._getAllCursorsModelState())); } private _lineInsertAfter(ctx: IMultipleCursorOperationContext): void { this._applyEdits(ctx, TypeOperations.lineInsertAfter(this.context.config, this.context.model, this._getAllCursorsModelState())); } private _lineBreakInsert(ctx: IMultipleCursorOperationContext): void { this._applyEdits(ctx, TypeOperations.lineBreakInsert(this.context.config, this.context.model, this._getAllCursorsModelState())); } private _type(ctx: IMultipleCursorOperationContext): void { var text = ctx.eventData.text; if (!this._isDoingComposition && ctx.eventSource === 'keyboard') { // If this event is coming straight from the keyboard, look for electric characters and enter for (let i = 0, len = text.length; i < len; i++) { let charCode = text.charCodeAt(i); let chr: string; if (strings.isHighSurrogate(charCode) && i + 1 < len) { chr = text.charAt(i) + text.charAt(i + 1); i++; } else { chr = text.charAt(i); } // Here we must interpret each typed character individually, that's why we create a new context this._createAndInterpretHandlerCtx(ctx.eventSource, ctx.eventData, (charHandlerCtx: IMultipleCursorOperationContext) => { // Decide what all cursors will do up-front this._applyEdits(charHandlerCtx, TypeOperations.typeWithInterceptors(this.context.config, this.context.model, this._getAllCursorsModelState(), chr)); // The last typed character gets to win ctx.cursorPositionChangeReason = charHandlerCtx.cursorPositionChangeReason; ctx.shouldReveal = charHandlerCtx.shouldReveal; }); } } else { this._applyEdits(ctx, TypeOperations.typeWithoutInterceptors(this.context.config, this.context.model, this._getAllCursorsModelState(), text)); } } private _replacePreviousChar(ctx: IMultipleCursorOperationContext): void { let text = ctx.eventData.text; let replaceCharCnt = ctx.eventData.replaceCharCnt; this._applyEdits(ctx, TypeOperations.replacePreviousChar(this.context.config, this.context.model, this._getAllCursorsModelState(), text, replaceCharCnt)); } private _compositionStart(ctx: IMultipleCursorOperationContext): void { this._isDoingComposition = true; } private _compositionEnd(ctx: IMultipleCursorOperationContext): void { this._isDoingComposition = false; } private _tab(ctx: IMultipleCursorOperationContext): void { this._applyEdits(ctx, TypeOperations.tab(this.context.config, this.context.model, this._getAllCursorsModelState())); } private _indent(ctx: IMultipleCursorOperationContext): void { this._applyEdits(ctx, TypeOperations.indent(this.context.config, this.context.model, this._getAllCursorsModelState())); } private _outdent(ctx: IMultipleCursorOperationContext): void { this._applyEdits(ctx, TypeOperations.outdent(this.context.config, this.context.model, this._getAllCursorsModelState())); } private _distributePasteToCursors(ctx: IMultipleCursorOperationContext): string[] { if (ctx.eventData.pasteOnNewLine) { return null; } var selections = this.cursors.getSelections(); if (selections.length === 1) { return null; } for (var i = 0; i < selections.length; i++) { if (selections[i].startLineNumber !== selections[i].endLineNumber) { return null; } } var pastePieces = ctx.eventData.text.split(/\r\n|\r|\n/); if (pastePieces.length !== selections.length) { return null; } return pastePieces; } private _paste(ctx: IMultipleCursorOperationContext): void { var distributedPaste = this._distributePasteToCursors(ctx); ctx.cursorPositionChangeReason = CursorChangeReason.Paste; if (distributedPaste) { this._applyEdits(ctx, TypeOperations.distributedPaste(this.context.config, this.context.model, this._getAllCursorsModelState(true), distributedPaste)); } else { this._applyEdits(ctx, TypeOperations.paste(this.context.config, this.context.model, this._getAllCursorsModelState(), ctx.eventData.text, ctx.eventData.pasteOnNewLine)); } } private _deleteLeft(ctx: IMultipleCursorOperationContext): void { this._applyEdits(ctx, DeleteOperations.deleteLeft(this.context.config, this.context.model, this._getAllCursorsModelState())); } private _deleteRight(ctx: IMultipleCursorOperationContext): void { this._applyEdits(ctx, DeleteOperations.deleteRight(this.context.config, this.context.model, this._getAllCursorsModelState())); } private _cut(ctx: IMultipleCursorOperationContext): void { this._applyEdits(ctx, DeleteOperations.cut(this.context.config, this.context.model, this._getAllCursorsModelState(), this.enableEmptySelectionClipboard)); } // -------------------- END editing operations private _undo(ctx: IMultipleCursorOperationContext): void { ctx.cursorPositionChangeReason = CursorChangeReason.Undo; this._interpretCommandResult(this.model.undo()); } private _redo(ctx: IMultipleCursorOperationContext): void { ctx.cursorPositionChangeReason = CursorChangeReason.Redo; this._interpretCommandResult(this.model.redo()); } private _externalExecuteCommand(ctx: IMultipleCursorOperationContext): void { const command = <editorCommon.ICommand>ctx.eventData; this.cursors.killSecondaryCursors(); ctx.shouldReveal = true; ctx.shouldPushStackElementBefore = true; ctx.shouldPushStackElementAfter = true; ctx.executeCommands[0] = command; ctx.isAutoWhitespaceCommand[0] = false; } private _externalExecuteCommands(ctx: IMultipleCursorOperationContext): void { const commands = <editorCommon.ICommand[]>ctx.eventData; ctx.shouldReveal = true; ctx.shouldPushStackElementBefore = true; ctx.shouldPushStackElementAfter = true; for (let i = 0; i < commands.length; i++) { ctx.executeCommands[i] = commands[i]; ctx.isAutoWhitespaceCommand[i] = false; } } }
the_stack
import * as core from '../core' import * as app from '../app/app' import manager from '../app/manager' import Axis from '../models/axis' import Query from '../models/data/query' import Container from '../models/items/container' import Separator from '../models/items/separator' import Cell from '../models/items/cell' import Row from '../models/items/row' import { make } from '../models/items/factory' import { logger } from '../util' import * as queries from './queries' import * as props from './property-sheets' export * from './property-sheets' declare var $, bootbox, ts const log = logger('edit') /** * Toggle mode-specific CSS rules for dashboard structural elements. */ app.add_mode_handler(app.Mode.EDIT, { enter: function() { log.debug('mode_handler.enter()') $('.ds-dashboard .ds-section, .ds-cell, .ds-row').addClass('ds-edit') }, exit: function() { log.debug('mode_handler.exit()') $('.ds-dashboard .ds-section, .ds-cell, .ds-row').removeClass('ds-edit') }, refresh: function() { log.debug('mode_handler.refresh()') $('.ds-dashboard .ds-section, .ds-cell, .ds-row').addClass('ds-edit') } }) /* ----------------------------------------------------------------------------- Item Actions ----------------------------------------------------------------------------- */ let duplicate_item_action = new core.Action({ name: 'duplicate', display: 'Duplicate Item', icon: 'fa fa-copy', handler: function(action, item) { let dashboard = manager.current.dashboard let parent = dashboard.find_parent(item) let dup = make(item.toJSON()).set_item_id(null) dup.visit(function(child) { child.item_id = null }) parent.add_after(item, dup) dashboard.update_index() manager.update_item_view(parent) } }) let delete_action = new core.Action({ name: 'delete', display: 'Delete item', icon: 'fa fa-trash-o', handler: function(action, item) { let parent = manager.current.dashboard.find_parent(item) if (!parent) { return } if (parent && (parent instanceof Container) && parent.remove(item)) { manager.update_item_view(parent) } } }) let move_back_action = new core.Action({ name: 'move-back', display: 'Move item back one place', icon: 'fa fa-caret-left', handler: function(action, item) { let parent = manager.current.dashboard.find_parent(item) if ((parent instanceof Container) && parent.move(item, -1)) { manager.update_item_view(parent) } } }) let move_forward_action = new core.Action({ name: 'move-forward', display: 'Move item forward one place', icon: 'fa fa-caret-right', handler: function(action, item) { let parent = manager.current.dashboard.find_parent(item) if ((parent instanceof Container) && parent.move(item, 1)) { manager.update_item_view(parent) } } }) let view_definition_action = new core.Action({ name: 'view-definition', display: 'View definition...', icon: 'fa fa-code', handler: function(action, item) { let contents = ts.templates.edit.item_source({item:item}) bootbox.alert({ backdrop: false, message: contents }) } }) /* ----------------------------------------------------------------------------- New from Graphite URL Action ----------------------------------------------------------------------------- */ function new_chart_from_graphite_url(url_string) { let dash = manager.current.dashboard let url = new URI(url_string) let data = url.search(true) let query = queries.new_query(dash, data.target) let type = 'standard_time_series' if (data.areaMode && data.areaMode === 'stacked') { type = 'stacked_area_chart' } else if (data.graphType && data.graphType === 'pie') { type = 'donut_chart' } let chart = make(type) .set_dashboard(dash) .set_query(query.name) .set_height(Math.min(8, Math.floor(((data.height || 400) / 80)))) .set_title(data.title) chart.options = chart.options || {} if (data.vtitle) { if (!chart.options.y1) chart.options.y1 = new Axis() chart.options.y1.label = data.vtitle } if (data.yMin) { if (!chart.options.y1) chart.options.y1 = new Axis() chart.options.y1.min = data.yMin } if (data.yMax) { if (!chart.options.y1) chart.options.y1 = new Axis() chart.options.y1.max = data.yMax } if (data.template) { chart.options.palette = data.template } return chart } core.actions.register({ name: 'new-chart-from-url', category: 'new-item-chart', display: 'Add new chart from Graphite URL', icon: 'fa fa-image', css: 'new-item', handler: function(action, container) { bootbox.prompt({ title: "Enter a Graphite chart URL", backdrop: false, callback: function(result) { if (result) { let item = new_chart_from_graphite_url(result) if (item) { container.add(item) } } } }) } }) /* ----------------------------------------------------------------------------- New item handling ----------------------------------------------------------------------------- */ function new_item_actions() : core.ActionList { let list = [].concat(core.actions.get('new-item-structural', 'row'), core.Action.DIVIDER, core.actions.list('new-item-display').sort(function(a, b) { return a.icon.localeCompare(b.icon) }), core.Action.DIVIDER, core.actions.list('new-item-data-table').sort(function(a, b) { return a.icon.localeCompare(b.icon) }), core.Action.DIVIDER, core.actions.list('new-item-chart').sort(function(a, b) { return a.icon.localeCompare(b.icon) }) ) let other = core.actions.list('new-item') if (other && other.length) { list.concat(other.sort(function(a, b) { return a.icon.localeCompare(b.icon) })) } return list } let new_item_action_for_cell = new core.Action({ name: 'new-item', category: 'new-item', css: 'ds-new-item', display: 'Add new dashboard item...', icon: 'fa fa-plus', actions: new_item_actions }) let new_item_action_for_section = new core.Action({ name: 'new-item', category: 'new-item', css: 'ds-new-item', display: 'Add new dashboard item...', icon: 'fa fa-plus', actions: () : core.ActionList => { return [].concat(core.actions.get('new-item-structural', 'section'), core.actions.get('new-item-structural', 'row'), core.Action.DIVIDER, core.actions.list('new-item-display').sort(function(a, b) { return a.icon.localeCompare(b.icon) }) ) } }) let combinations = [ [12], [], [6,6], [4,4,4], [3,3,3,3], [2,2,2,2,2,2], [], [9,3], [6,3,3], [3,9], [3,3,6], [], [8,4], [8,2,2], [4,8], [2,2,8] ] core.actions.register('new-combination', combinations.map((combo) => { if (!combo || !combo.length ) { return core.Action.DIVIDER } return new core.Action({ category: 'new-combination', name: 'new-combination-' + combo.join('-'), display: '[' + combo.join(', ') + ']', icon: 'fa fa-columns', css: 'new-item', handler: (action, container) => { let row = new Row() for (let span of combo) { row.add(new Cell({span: span})) } container.add(row) } }) }) ) let new_combinations_action_for_section = new core.Action({ name: 'new-item-combination', category: 'new-item', css: 'ds-new-item', display: 'Add new row combination...', icon: 'fa fa-th', actions: () : core.ActionList => { return core.actions.list('new-combination') } }) $(document).on('click', 'li.new-item', function(event) { log.debug('li.new-item.click') let elt = $(this) let category = elt.attr('data-ds-category') let name = elt.attr('data-ds-action') let item_id = elt.parent().parent().parent().parent()[0].getAttribute('data-ds-item-id') let item = manager.current.dashboard.get_item(item_id) let action = core.actions.get(category, name) log.debug(`li.new-item:click(): ${item_id}, ${action}, ${category}/${name}`) action.handler(action, item) return false }) /* ----------------------------------------------------------------------------- Section actions ----------------------------------------------------------------------------- */ core.actions.register('edit-bar-section', [ new_item_action_for_section, new_combinations_action_for_section, duplicate_item_action, core.Action.DIVIDER, move_back_action, move_forward_action, core.Action.DIVIDER, delete_action ]) /* ----------------------------------------------------------------------------- Row actions ----------------------------------------------------------------------------- */ core.actions.register('edit-bar-row', [ new core.Action({ name: 'new-cell', display: 'Add new Cell', icon: 'fa fa-plus', handler: function(action, container) { container.add('cell') } }), duplicate_item_action, core.Action.DIVIDER, move_back_action, move_forward_action, core.Action.DIVIDER, delete_action ]) /* ----------------------------------------------------------------------------- Cell actions ----------------------------------------------------------------------------- */ core.actions.register('edit-bar-cell', [ new_item_action_for_cell, duplicate_item_action, core.Action.DIVIDER, move_back_action, move_forward_action, new core.Action({ name: 'increase-span', display: 'Increase cell span by one', icon: 'fa fa-expand', handler: function(action, item) { if (item.span) { item.span += 1 manager.update_item_view(item) } } }), new core.Action({ name: 'decrease-span', display: 'Decrease cell span by one', icon: 'fa fa-compress', handler: function(action, item) { if (item.span) { item.span -= 1 manager.update_item_view(item) } } }), core.Action.DIVIDER, delete_action ]) /* ----------------------------------------------------------------------------- Item actions ----------------------------------------------------------------------------- */ core.actions.register('edit-bar-item', [ duplicate_item_action, core.Action.DIVIDER, move_back_action, move_forward_action, view_definition_action, core.Action.DIVIDER, delete_action ]) /* ----------------------------------------------------------------------------- Edit Bar Handler ----------------------------------------------------------------------------- */ $(document).on('click', '.ds-edit-bar button', function(event) { log.debug('click.ds-edit-bar button') let element = $(this)[0] let parent = $(this).parent()[0] let item_id = parent.getAttribute('data-ds-item-id') let name = element.getAttribute('data-ds-action') let category = element.getAttribute('data-ds-category') let action = core.actions.get(category, name) let item = manager.current.dashboard.get_item(item_id) if (action) { action.handler(action, item) } })
the_stack
import { AsyncHierarchyIterable, AsyncOrderedHierarchyIterable } from '@esfx/async-iter-hierarchy'; import { AsyncOrderedIterable } from "@esfx/async-iter-ordered"; import { toAsyncOrderedIterable } from "@esfx/async-iter-ordered-fromsync"; import { Comparer, Comparison } from "@esfx/equatable"; import * as assert from "@esfx/internal-assert"; import { HierarchyIterable, OrderedHierarchyIterable } from '@esfx/iter-hierarchy'; import { OrderedIterable } from "@esfx/iter-ordered"; import { flowHierarchy } from './internal/utils'; import { toArrayAsync } from './scalars'; class AsyncReverseIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>) { this._source = source; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const list = await toArrayAsync(this._source); list.reverse(); yield* list; } } /** * Creates an `AsyncIterable` whose elements are in the reverse order. * @category Subquery */ export function reverseAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` whose elements are in the reverse order. * @category Subquery */ export function reverseAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncIterable<T>; export function reverseAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); return flowHierarchy(new AsyncReverseIterable(source), source); } class AsyncOrderByIterable<T, K> implements AsyncOrderedIterable<T> { protected _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _keySelector: (element: T) => K; private _keyComparer: Comparer<K>; private _descending: boolean; private _parent?: AsyncOrderByIterable<T, any>; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyComparer: Comparer<K>, descending: boolean, parent?: AsyncOrderByIterable<T, any>) { this._source = source; this._keySelector = keySelector; this._keyComparer = keyComparer; this._descending = descending; this._parent = parent; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const source = this._source; const array = await toArrayAsync(source); const sorter = this._getSorter(array); const len = array.length; const indices = new Array<number>(len); for (let i = 0; i < len; ++i) { indices[i] = i; } indices.sort(sorter); for (const index of indices) { yield array[index]; } } [AsyncOrderedIterable.thenByAsync]<K>(keySelector: (element: T) => K, keyComparer: Comparison<K> | Comparer<K>, descending: boolean): AsyncOrderedIterable<T> { if (typeof keyComparer === "function") keyComparer = Comparer.create(keyComparer); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeType(Comparer.hasInstance, keyComparer, "keyComparer"); assert.mustBeBoolean(descending, "descending"); return new AsyncOrderByIterable(this._source, keySelector, keyComparer, descending, this); } private _getSorter(elements: T[], next?: (x: number, y: number) => number): (x: number, y: number) => number { const keySelector = this._keySelector; const comparer = this._keyComparer; const descending = this._descending; const parent = this._parent; const keys = elements.map(keySelector); const sorter = (x: number, y: number): number => { const result = comparer.compare(keys[x], keys[y]); if (result === 0) { return next ? next(x, y) : x - y; } return descending ? -result : result; }; return parent ? parent._getSorter(elements, sorter) : sorter; } } /** * Creates an `AsyncOrderedIterable` whose elements are sorted in ascending order by the provided key. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for an element. * @param keyComparer An optional callback used to compare two keys. * @category Order */ export function orderByAsync<TNode, T extends TNode, K>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): AsyncOrderedHierarchyIterable<TNode, T>; /** * Creates an `AsyncOrderedIterable` whose elements are sorted in ascending order by the provided key. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for an element. * @param keyComparer An optional callback used to compare two keys. * @category Order */ export function orderByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): AsyncOrderedIterable<T>; export function orderByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyComparer: Comparison<K> | Comparer<K> = Comparer.defaultComparer): AsyncOrderedIterable<T> { if (typeof keyComparer === "function") keyComparer = Comparer.create(keyComparer); assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeType(Comparer.hasInstance, keyComparer, "keyComparer"); return flowHierarchy(new AsyncOrderByIterable(source, keySelector, keyComparer, /*descending*/ false), source); } /** * Creates an `AsyncOrderedIterable` whose elements are sorted in descending order by the provided key. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for an element. * @param keyComparer An optional callback used to compare two keys. * @category Order */ export function orderByDescendingAsync<TNode, T extends TNode, K>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): AsyncOrderedHierarchyIterable<TNode, T>; /** * Creates an `AsyncOrderedIterable` whose elements are sorted in descending order by the provided key. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for an element. * @param keyComparer An optional callback used to compare two keys. * @category Order */ export function orderByDescendingAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): AsyncOrderedIterable<T>; export function orderByDescendingAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyComparer: Comparison<K> | Comparer<K> = Comparer.defaultComparer): AsyncOrderedIterable<T> { if (typeof keyComparer === "function") keyComparer = Comparer.create(keyComparer); assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeType(Comparer.hasInstance, keyComparer, "keyComparer"); return flowHierarchy(new AsyncOrderByIterable(source, keySelector, keyComparer, /*descending*/ true), source); } /** * Creates a subsequent `AsyncOrderedIterable` whose elements are also sorted in ascending order by the provided key. * * @param source An `AsyncOrderedIterable` or `OrderedIterable` object. * @param keySelector A callback used to select the key for an element. * @param keyComparer An optional callback used to compare two keys. * @category Order */ export function thenByAsync<TNode, T extends TNode, K>(source: AsyncOrderedHierarchyIterable<TNode, T> | OrderedHierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): AsyncOrderedHierarchyIterable<TNode, T>; /** * Creates a subsequent `AsyncOrderedIterable` whose elements are also sorted in ascending order by the provided key. * * @param source An `AsyncOrderedIterable` or `OrderedIterable` object. * @param keySelector A callback used to select the key for an element. * @param keyComparer An optional callback used to compare two keys. * @category Order */ export function thenByAsync<T, K>(source: AsyncOrderedIterable<T> | OrderedIterable<T>, keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): AsyncOrderedIterable<T>; export function thenByAsync<T, K>(source: AsyncOrderedIterable<T> | OrderedIterable<T>, keySelector: (element: T) => K, keyComparer: Comparison<K> | Comparer<K> = Comparer.defaultComparer): AsyncOrderedIterable<T> { if (typeof keyComparer === "function") keyComparer = Comparer.create(keyComparer); assert.assertType(AsyncOrderedIterable.hasInstance(source) || OrderedIterable.hasInstance(source), "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeType(Comparer.hasInstance, keyComparer, "keyComparer"); return flowHierarchy(toAsyncOrderedIterable(source)[AsyncOrderedIterable.thenByAsync](keySelector, keyComparer, /*descending*/ false), source); } /** * Creates a subsequent `AsyncOrderedIterable` whose elements are also sorted in descending order by the provided key. * * @param source An `AsyncOrderedIterable` or `OrderedIterable` object. * @param keySelector A callback used to select the key for an element. * @param keyComparer An optional callback used to compare two keys. * @category Order */ export function thenByDescendingAsync<TNode, T extends TNode, K>(source: AsyncOrderedHierarchyIterable<TNode, T> | OrderedHierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): AsyncOrderedHierarchyIterable<TNode, T>; /** * Creates a subsequent `AsyncOrderedIterable` whose elements are also sorted in descending order by the provided key. * * @param source An `AsyncOrderedIterable` or `OrderedIterable` object. * @param keySelector A callback used to select the key for an element. * @param keyComparer An optional callback used to compare two keys. * @category Order */ export function thenByDescendingAsync<T, K>(source: AsyncOrderedIterable<T> | OrderedIterable<T>, keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): AsyncOrderedIterable<T>; export function thenByDescendingAsync<T, K>(source: AsyncOrderedIterable<T> | OrderedIterable<T>, keySelector: (element: T) => K, keyComparer: Comparison<K> | Comparer<K> = Comparer.defaultComparer): AsyncOrderedIterable<T> { if (typeof keyComparer === "function") keyComparer = Comparer.create(keyComparer); assert.assertType(AsyncOrderedIterable.hasInstance(source) || OrderedIterable.hasInstance(source), "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeType(Comparer.hasInstance, keyComparer, "keyComparer"); return flowHierarchy(toAsyncOrderedIterable(source)[AsyncOrderedIterable.thenByAsync](keySelector, keyComparer, /*descending*/ true), source); }
the_stack
import { Applicative3 } from 'fp-ts/lib/Applicative' import { Apply3 } from 'fp-ts/lib/Apply' import { Either } from 'fp-ts/lib/Either' import { identity, Predicate, Refinement } from 'fp-ts/lib/function' import { Functor3 } from 'fp-ts/lib/Functor' import { IO } from 'fp-ts/lib/IO' import { IOEither } from 'fp-ts/lib/IOEither' import { Monad3 } from 'fp-ts/lib/Monad' import { MonadThrow3 } from 'fp-ts/lib/MonadThrow' import { Option } from 'fp-ts/lib/Option' import { pipe } from 'fp-ts/lib/pipeable' import { State } from 'fp-ts/lib/State' import { getStateM } from 'fp-ts/lib/StateT' import { Task } from 'fp-ts/lib/Task' import * as TE from 'fp-ts/lib/TaskEither' import TaskEither = TE.TaskEither const T = getStateM(TE.taskEither) // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 0.1.0 */ export interface StateTaskEither<S, E, A> { (s: S): TaskEither<E, [A, S]> } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 0.1.0 */ export const get: <S>() => StateTaskEither<S, never, S> = T.get /** * @category constructors * @since 0.1.0 */ export const put: <S>(s: S) => StateTaskEither<S, never, void> = T.put /** * @category constructors * @since 0.1.0 */ export const modify: <S>(f: (s: S) => S) => StateTaskEither<S, never, void> = T.modify /** * @category constructors * @since 0.1.0 */ export const gets: <S, A>(f: (s: S) => A) => StateTaskEither<S, never, A> = T.gets /** * @category constructors * @since 0.1.0 */ export const left: <S, E>(e: E) => StateTaskEither<S, E, never> = (e) => fromTaskEither(TE.left(e)) /** * @category constructors * @since 0.1.0 */ export const right: <S, A>(a: A) => StateTaskEither<S, never, A> = T.of /** * @category constructors * @since 0.1.0 */ export const leftIO: <S, E>(me: IO<E>) => StateTaskEither<S, E, never> = (me) => fromTaskEither(TE.leftIO(me)) /** * @category constructors * @since 0.1.0 */ export const rightIO: <S, A>(ma: IO<A>) => StateTaskEither<S, never, A> = (ma) => fromTaskEither(TE.rightIO(ma)) /** * @category constructors * @since 0.1.0 */ export const leftTask: <S, E>(me: Task<E>) => StateTaskEither<S, E, never> = (me) => fromTaskEither(TE.leftTask(me)) /** * @category constructors * @since 0.1.0 */ export const rightTask: <S, A>(ma: Task<A>) => StateTaskEither<S, never, A> = (ma) => fromTaskEither(TE.rightTask(ma)) /** * @category constructors * @since 0.1.0 */ export const leftState: <S, E>(me: State<S, E>) => StateTaskEither<S, E, never> = (me) => (s) => TE.left(me(s)[0]) /** * @category constructors * @since 0.1.0 */ export const rightState: <S, A>(ma: State<S, A>) => StateTaskEither<S, never, A> = T.fromState /** * @category constructors * @since 0.1.18 */ export const fromOption: <E>(onNone: () => E) => <R, A>(ma: Option<A>) => StateTaskEither<R, E, A> = (onNone) => (ma) => ma._tag === 'None' ? left(onNone()) : right(ma.value) /** * @category constructors * @since 0.1.18 */ export const fromEither: <R, E, A>(ma: Either<E, A>) => StateTaskEither<R, E, A> = (ma) => ma._tag === 'Left' ? left(ma.left) : right(ma.right) /** * @category constructors * @since 0.1.0 */ export const fromIOEither: <S, E, A>(ma: IOEither<E, A>) => StateTaskEither<S, E, A> = (ma) => fromTaskEither(TE.fromIOEither(ma)) /** * @category constructors * @since 0.1.0 */ export const fromTaskEither: <S, E, A>(ma: TaskEither<E, A>) => StateTaskEither<S, E, A> = T.fromM /** * @category constructors * @since 0.1.10 */ export const fromEitherK: <E, A extends Array<unknown>, B>( f: (...a: A) => Either<E, B> ) => <S>(...a: A) => StateTaskEither<S, E, B> = (f) => (...a) => fromEither(f(...a)) /** * @category constructors * @since 0.1.10 */ export const fromIOEitherK: <E, A extends Array<unknown>, B>( f: (...a: A) => IOEither<E, B> ) => <S>(...a: A) => StateTaskEither<S, E, B> = (f) => (...a) => fromIOEither(f(...a)) /** * @category constructors * @since 0.1.10 */ export const fromTaskEitherK: <E, A extends Array<unknown>, B>( f: (...a: A) => TaskEither<E, B> ) => <S>(...a: A) => StateTaskEither<S, E, B> = (f) => (...a) => fromTaskEither(f(...a)) /** * @category constructors * @since 0.1.18 */ export const fromPredicate: { <E, A, B extends A>(refinement: Refinement<A, B>, onFalse: (a: A) => E): <R>(a: A) => StateTaskEither<R, E, B> <E, A>(predicate: Predicate<A>, onFalse: (a: A) => E): <R>(a: A) => StateTaskEither<R, E, A> } = <E, A>(predicate: Predicate<A>, onFalse: (a: A) => E) => <R>(a: A): StateTaskEither<R, E, A> => predicate(a) ? right(a) : left(onFalse(a)) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @category combinators * @since 0.1.18 */ export const filterOrElse: { <E, A, B extends A>(refinement: Refinement<A, B>, onFalse: (a: A) => E): <R>( ma: StateTaskEither<R, E, A> ) => StateTaskEither<R, E, B> <E, A>(predicate: Predicate<A>, onFalse: (a: A) => E): <R>(ma: StateTaskEither<R, E, A>) => StateTaskEither<R, E, A> } = <E, A>(predicate: Predicate<A>, onFalse: (a: A) => E) => <R>( ma: StateTaskEither<R, E, A> ): StateTaskEither<R, E, A> => T.chain(ma, (a) => (predicate(a) ? right(a) : left(onFalse(a)))) // ------------------------------------------------------------------------------------- // pipeables // ------------------------------------------------------------------------------------- /** * @category Functor * @since 0.1.18 */ export const map: <A, B>(f: (a: A) => B) => <R, E>(fa: StateTaskEither<R, E, A>) => StateTaskEither<R, E, B> = (f) => ( fa ) => T.map(fa, f) /** * @category Apply * @since 0.1.18 */ export const ap: <R, E, A>( fa: StateTaskEither<R, E, A> ) => <B>(fab: StateTaskEither<R, E, (a: A) => B>) => StateTaskEither<R, E, B> = (fa) => (fab) => T.ap(fab, fa) /** * @category Apply * @since 0.1.18 */ export const apFirst = <R, E, B>(fb: StateTaskEither<R, E, B>) => <A>( fa: StateTaskEither<R, E, A> ): StateTaskEither<R, E, A> => pipe( fa, map((a) => (_: B) => a), ap(fb) ) /** * @category Apply * @since 0.1.18 */ export const apSecond = <R, E, B>(fb: StateTaskEither<R, E, B>) => <A>( fa: StateTaskEither<R, E, A> ): StateTaskEither<R, E, B> => pipe( fa, map(() => (b: B) => b), ap(fb) ) /** * @category Applicative * @since 0.1.18 */ export const of: <R, E, A>(a: A) => StateTaskEither<R, E, A> = right /** * @category Monad * @since 0.1.18 */ export const chain: <R, E, A, B>( f: (a: A) => StateTaskEither<R, E, B> ) => (ma: StateTaskEither<R, E, A>) => StateTaskEither<R, E, B> = (f) => (ma) => T.chain(ma, f) /** * @category Monad * @since 0.1.18 */ export const chainFirst: <R, E, A, B>( f: (a: A) => StateTaskEither<R, E, B> ) => (ma: StateTaskEither<R, E, A>) => StateTaskEither<R, E, A> = (f) => (ma) => T.chain(ma, (a) => T.map(f(a), () => a)) /** * @category Monad * @since 0.1.10 */ export const chainEitherK = <E, A, B>( f: (a: A) => Either<E, B> ): (<S>(ma: StateTaskEither<S, E, A>) => StateTaskEither<S, E, B>) => chain<any, E, A, B>(fromEitherK(f)) /** * @category Monad * @since 0.1.10 */ export const chainIOEitherK = <E, A, B>( f: (a: A) => IOEither<E, B> ): (<S>(ma: StateTaskEither<S, E, A>) => StateTaskEither<S, E, B>) => chain<any, E, A, B>(fromIOEitherK(f)) /** * @category Monad * @since 0.1.10 */ export const chainTaskEitherK = <E, A, B>( f: (a: A) => TaskEither<E, B> ): (<S>(ma: StateTaskEither<S, E, A>) => StateTaskEither<S, E, B>) => chain<any, E, A, B>(fromTaskEitherK(f)) /** * @category Monad * @since 0.1.18 */ export const flatten: <R, E, A>(mma: StateTaskEither<R, E, StateTaskEither<R, E, A>>) => StateTaskEither<R, E, A> = ( mma ) => T.chain(mma, identity) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * @category instances * @since 0.1.0 */ export const URI = 'StateTaskEither' /** * @category instances * @since 0.1.0 */ export type URI = typeof URI declare module 'fp-ts/lib/HKT' { interface URItoKind3<R, E, A> { StateTaskEither: StateTaskEither<R, E, A> } } /** * @category instances * @since 0.1.18 */ export const Functor: Functor3<URI> = { URI, map: T.map } /** * @category instances * @since 0.1.18 */ export const Applicative: Applicative3<URI> = { URI, map: T.map, ap: T.ap, of } /** * @category instances * @since 0.1.18 */ export const Apply: Apply3<URI> = { URI, map: T.map, ap: T.ap } /** * @category instances * @since 0.1.18 */ export const Monad: Monad3<URI> = { URI, map: T.map, ap: T.ap, chain: T.chain, of } /** * @category instances * @since 0.1.0 */ export const stateTaskEither: Monad3<URI> & MonadThrow3<URI> = { URI, map: T.map, of: right, ap: T.ap, chain: T.chain, throwError: left } /** * Like `stateTaskEither` but `ap` is sequential * * @category instances * @since 0.1.0 */ export const stateTaskEitherSeq: typeof stateTaskEither = { ...stateTaskEither, ap: (mab, ma) => T.chain(mab, (f) => T.map(ma, f)) } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 0.1.0 */ export const evalState: <S, E, A>(ma: StateTaskEither<S, E, A>, s: S) => TaskEither<E, A> = T.evalState /** * @since 0.1.0 */ export const execState: <S, E, A>(ma: StateTaskEither<S, E, A>, s: S) => TaskEither<E, S> = T.execState /** * @since 0.1.0 */ export const run: <S, E, A>(ma: StateTaskEither<S, E, A>, s: S) => Promise<Either<E, [A, S]>> = (ma, s) => ma(s)()
the_stack
import 'es6-promise/auto' import imageLoaded from 'image-loaded' import raf from 'raf' import {Animation, AnimationOptions, Frame, SpriteSheet, SpriteSheetOptions} from './types' const playheadDefaults: Animation = { play: true, delay: 50, tempo: 1, run: -1, reversed: false, script: [], lastTime: 0, nextDelay: 0, currentSprite: 1, currentFrame: -1, onPlay: null, onStop: null, onFrame: null, onOutOfView: null } class Spriteling { public spriteSheet: SpriteSheet = { loaded: false, url: null, cols: null, rows: null, cutOffFrames: 0, top: null, bottom: null, left: null, right: null, startSprite: 1, downsizeRatio: 1, totalSprites: 0, sheetWidth: 0, sheetHeight: 0, frameWidth: 0, frameHeight: 0, animations: {}, onLoaded: null } private playhead: Animation private readonly element: HTMLElement private debug: boolean private loadingPromise: Promise<void> /** * Creates a new Spriteling instance. The options object can contain the following values * - url: url to spriteSheet, if not set the css background-image will be used * - cols: number columns in the spritesheet (mandatory) * - rows: number rows in the spritesheet (mandatory) * - cutOffFrames: number of sprites not used in the spritesheet (default: 0) * - top/bottom/left/right: starting offset position of placeholder element * - startSprite: number of the first sprite to show when done loading * - onLoaded: callback that will be called when loading has finished * * Element can be a css selector or existing DOM element or null, in which case a new div element will be created * * Debug adds logging in console, useful when working on the animation * * @param {object} options * @param {HTMLElement | string} element * @param {boolean} debug */ constructor( options: SpriteSheetOptions, element?: HTMLElement | string, debug: boolean = false ) { // Lookup element by selector if (element) { this.element = typeof element === 'string' ? document.querySelector(element) as HTMLElement : element } // No element found, let's create one instead if (!this.element) { if (typeof this.element !== 'undefined') { this.log('warn', `element "${element}" not found, created new element instead`) } this.element = document.createElement('div') document.body.appendChild(this.element) } // Add spriteling class this.element.className += ' spriteling' // Combine options with defaults this.spriteSheet = {...this.spriteSheet, ...options} this.playhead = {...playheadDefaults} this.debug = debug || false // Initialize spritesheet if (!options.cols) { this.log('error', 'options.cols not set') } if (!options.rows) { this.log('error', 'options.rows not set') } if (!options.url) { // If no sprite is specified try to use background-image const elementStyle = window.getComputedStyle(this.element) const cssBackgroundImage = elementStyle.getPropertyValue('background-image') if (!cssBackgroundImage || cssBackgroundImage === 'none') { this.log('error', 'no spritesheet image found, please specify it with options.url or set as css background') } else { this.spriteSheet.url = cssBackgroundImage.replace(/"/g, '').replace(/url\(|\)$/ig, '') } } // Create loading promise this.loadingPromise = this.loadSpriteSheet().then(() => { this.spriteSheet.loaded = true // If starting sprite is set, show it if (this.spriteSheet.startSprite > 1 && this.spriteSheet.startSprite <= this.spriteSheet.totalSprites) { this.drawFrame({sprite: this.spriteSheet.startSprite}) } // onLoaded callback if (typeof this.spriteSheet.onLoaded === 'function') { this.spriteSheet.onLoaded() } }) } /** * Stop the current animation and show the specified sprite * @param {number} spriteNumber */ public async showSprite( spriteNumber: number ): Promise<void> { await this.loadingPromise this.playhead.play = false this.drawFrame({sprite: spriteNumber}) } /** * Get the current spriteNumber that is shown * @returns {number} */ public currentSprite(): number { return this.playhead.currentSprite } /** * Add a named animation sequence * * Name can be any string value * * Script should be an array of frame objects, each can have the following properties * - sprite: which sprite to show (mandatory) * - delay: alternate delay then the default delay * - top/left/bottom/right: reposition the placeholder element * * @param {string} name * @param {Frame[]} script */ public addScript(name: string, script: Frame[]) { this.spriteSheet.animations[name] = script } /** * Resume/play current or given animation. * Method can be called in four ways: * * .play() - resume current animation sequence (if not set - loops over all sprites once) * .play(scriptName) - play given animation script * .play(scriptName, { options }) - play given animation script with given options * .play({ options }) - play current animation with given options * * ScriptName loads a previously added animation with .addScript() * * Options object can contain * - play: start playing the animation right away (default: true) * - run: the number of times the animation should run, -1 is infinite (default: 1) * - delay: default delay for all frames that don't have a delay set (default: 50) * - tempo: timescale for all delays, double-speed = 2, half-speed = .5 (default:1) * - reversed: direction of the animation head, true == backwards (default: false) * - script: New unnamed animation sequence, array of frames, see .addScript (default: null) * - onPlay/onStop/onFrame/onOutOfView: callbacks called at the appropriate times (default: null) * * @param {string | Animation} scriptName * @param {Animation} options * @returns {boolean} */ public async play( scriptName?: string | AnimationOptions, options?: AnimationOptions ): Promise<void> { await this.loadingPromise // play() if (!scriptName && !options) { // Play if not already playing if (!this.playhead.play) { if (this.playhead.run === 0) { this.playhead.run = 1 } this.playhead.play = true } } else { let animationScript: Frame[] let animationOptions: AnimationOptions = {} // play('someAnimation') if (typeof scriptName === 'string' && !options) { if (this.spriteSheet.animations[scriptName]) { this.log('info', `playing animation "${scriptName}"`) animationScript = this.spriteSheet.animations[scriptName] } else { this.log('warn', `animation "${scriptName}" not found`) } // play('someAnimation', { options }) } else if (typeof scriptName === 'string' && typeof options === 'object') { animationScript = this.spriteSheet.animations[scriptName] animationOptions = options // play({ options }) } else if (typeof scriptName === 'object' && !options) { animationScript = scriptName.script || this.playhead.script animationOptions = scriptName } // Fallback to all script if (!animationScript) { this.log('info', `playing animation "all"`) animationScript = this.spriteSheet.animations.all } // Set starting frame let currentFrame = -1 if (animationOptions.reversed) { currentFrame = animationScript.length } this.playhead = { ...playheadDefaults, ...{script: animationScript}, ...animationOptions, ...{currentFrame} } } // Enter the animation loop if (this.playhead.run !== 0 && this.playhead.play) { this.loop() } // onPlay callback if (typeof this.playhead.onPlay === 'function') { this.playhead.onPlay() } } /** * Get the current play state * @returns {boolean} */ public isPlaying(): boolean { return this.playhead.play } /** * Set playback tempo, double-speed = 2, half-speed = .5 (default:1) * @param {number} tempo */ public async setTempo( tempo: number ): Promise<void> { await this.loadingPromise this.playhead.tempo = tempo } /** * Get playback tempo, double-speed = 2, half-speed = .5 (default:1) * @returns {number} */ public getTempo(): number { return this.playhead.tempo } /** * Step the animation ahead one frame * @returns {boolean} */ public async next(): Promise<void> { await this.loadingPromise // Update frame counter this.playhead.currentFrame += 1 // End of script? if (this.playhead.currentFrame === this.playhead.script.length) { this.playhead.run -= 1 this.playhead.currentFrame = 0 } // Stop when playing and run reached 0 if (this.playhead.play && this.playhead.run === 0) { this.stop() } else { const frame = this.playhead.script[this.playhead.currentFrame] this.drawFrame(frame) } } /** * Step the animation backwards one frame * @returns {boolean} */ public async previous(): Promise<void> { await this.loadingPromise // Update frame counter this.playhead.currentFrame -= 1 // End of script? if (this.playhead.currentFrame < 0) { this.playhead.currentFrame = this.playhead.script.length - 1 this.playhead.run -= 1 } if (this.playhead.play && this.playhead.run === 0) { this.stop() } else { const frame = this.playhead.script[this.playhead.currentFrame] this.drawFrame(frame) } } /** * Jump to certain frame within current animation sequence * @param frameNumber [integer] * @returns {boolean} */ public async goTo( frameNumber: number ): Promise<void> { await this.loadingPromise // Make sure given frame is within the animation const baseNumber = Math.floor(frameNumber / this.playhead.script.length) frameNumber = Math.floor(frameNumber - (baseNumber * this.playhead.script.length)) // Draw frame this.playhead.currentFrame = frameNumber const frame = this.playhead.script[this.playhead.currentFrame] if (frame) { this.log('info', `frame: ${this.playhead.currentFrame}, sprite: ${frame.sprite}`) this.drawFrame(frame) } } /** * Reverse direction of play */ public async reverse(): Promise<void> { await this.loadingPromise this.playhead.reversed = !this.playhead.reversed } /** * Get the current direction of play * @returns {boolean} */ public isReversed(): boolean { return this.playhead.reversed } /** * Stop the animation */ public async stop(): Promise<void> { await this.loadingPromise this.playhead.play = false // onStop callback if (typeof this.playhead.onStop === 'function') { this.playhead.onStop() } } /** * Reset playhead to first frame */ public async reset(): Promise<void> { await this.loadingPromise this.goTo(0) } /** * Removes the element and kills the animation loop */ public destroy() { this.playhead.play = false this.element.parentNode.removeChild(this.element) } /** * Load the spritesheet and position it correctly */ private loadSpriteSheet() { return new Promise((resolve) => { const preload = new Image() preload.src = this.spriteSheet.url imageLoaded(preload, () => { const sheet = this.spriteSheet const element = this.element this.log('info', `loaded: ${sheet.url}, sprites ${sheet.cols} x ${sheet.rows}`) sheet.sheetWidth = preload.width sheet.sheetHeight = preload.height sheet.frameWidth = sheet.sheetWidth / sheet.cols / sheet.downsizeRatio sheet.frameHeight = sheet.sheetHeight / sheet.rows / sheet.downsizeRatio sheet.totalSprites = (sheet.cols * sheet.rows) - sheet.cutOffFrames if (sheet.frameWidth % 1 !== 0) { this.log('error', `frameWidth ${sheet.frameWidth} is not a whole number`) } if (sheet.frameHeight % 1 !== 0) { this.log('error', `frameHeight ${sheet.frameHeight} is not a whole number`) } element.style.position = 'absolute' element.style.width = `${sheet.frameWidth}px` element.style.height = `${sheet.frameHeight}px` element.style.backgroundImage = `url(${sheet.url})` element.style.backgroundPosition = '0 0' if (sheet.downsizeRatio > 1) { element.style.backgroundSize = `${sheet.sheetWidth / sheet.downsizeRatio}px ${sheet.sheetHeight / sheet.downsizeRatio}px` } if (sheet.top !== null) { if (sheet.top === 'center') { element.style.top = '50%' element.style.marginTop = `${sheet.frameHeight / 2 * -1}px` } else { element.style.top = `${sheet.top}px` } } if (sheet.right !== null) { element.style.right = `${sheet.right}px` } if (sheet.bottom !== null) { element.style.bottom = `${sheet.bottom}px` } if (sheet.left !== null) { if (sheet.left === 'center') { element.style.left = `${sheet.left}px` element.style.marginLeft = `${sheet.frameWidth / 2 * -1}px` } else { element.style.left = `${sheet.left}px` } } // Auto script the first 'all' animation sequence and make it default this.autoScript() const animationOptions = {script: sheet.animations.all} this.playhead = {...playheadDefaults, ...animationOptions} resolve() }) }) } /** * Generate a linear script based on the spritesheet itself */ private autoScript() { const script = [] for (let i = 0; i < this.spriteSheet.totalSprites; i++) { script[i] = {sprite: (i + 1)} } this.addScript('all', script) } /** * The animation loop */ private loop = (time: number = 0) => { const requestFrameId = raf(this.loop) const playhead = this.playhead // Wait until fully loaded if (!this.element || !this.spriteSheet.loaded) { return } // Throttle on nextDelay if ((time - playhead.lastTime) >= playhead.nextDelay) { this.render(time) } // Cancel animation loop if play = false if (!playhead.play) { raf.cancel(requestFrameId) return } } private async render(time: number) { const element = this.element const playhead = this.playhead // Render next frame only if element is visible and within viewport if (element.offsetParent !== null && this.inViewport()) { // Only play if run counter is still <> 0 if (playhead.run !== 0) { if (playhead.reversed) { await this.previous() } else { await this.next() } const frame = playhead.script[playhead.currentFrame] this.log('info', `run: ${playhead.run}, frame`, frame) playhead.lastTime = time } } else { if (typeof playhead.onOutOfView === 'function') { playhead.onOutOfView() } } } /** * Draw a single frame */ private drawFrame(frame: Frame) { const sheet = this.spriteSheet const playhead = this.playhead const element = this.element this.playhead.nextDelay = frame.delay ? frame.delay : this.playhead.delay this.playhead.nextDelay /= this.playhead.tempo if (frame.sprite !== playhead.currentSprite) { const rect = element.getBoundingClientRect() const row = Math.ceil(frame.sprite / sheet.cols) const col = frame.sprite - ((row - 1) * sheet.cols) const bgX = ((col - 1) * sheet.frameWidth) * -1 const bgY = ((row - 1) * sheet.frameHeight) * -1 if (row > sheet.rows || col > sheet.cols) { this.log('warn', `position ${frame.sprite} out of bound`) } // Set sprite playhead.currentSprite = frame.sprite // Animate background element.style.backgroundPosition = `${bgX}px ${bgY}px` // Move if indicated if (frame.top) { element.style.top = `${rect.top + frame.top}px` } if (frame.right) { element.style.right = `${rect.right + frame.right}px` } if (frame.bottom) { element.style.bottom = `${rect.bottom + frame.bottom}px` } if (frame.left) { element.style.left = `${rect.left + frame.left}px` } } // onFrame callback if (typeof playhead.onFrame === 'function') { playhead.onFrame(playhead.currentFrame) } return true } /** * Test to see if an element is within the viewport * @returns {boolean} */ private inViewport(): boolean { const sheet = this.spriteSheet const rect = this.element.getBoundingClientRect() return ( rect.top + sheet.frameHeight >= 0 && rect.left + sheet.frameWidth >= 0 && rect.bottom - sheet.frameHeight <= (window.innerHeight || document.documentElement.clientHeight) && rect.right - sheet.frameWidth <= (window.innerWidth || document.documentElement.clientWidth) ) } /** * Log utility method * @param level * @param message * @private */ private log(level, ...message) { if (typeof console === 'undefined' || (level === 'info' && !this.debug)) { return } console[level](`Spriteling`, ...message) } } export default Spriteling
the_stack
import * as React from "react"; import { dispatch, getDocumentService, getState, getStore, getThemeService, } from "@core/service-registry"; import { CSSProperties } from "styled-components"; import MonacoEditor from "react-monaco-editor"; import * as monacoEditor from "monaco-editor/esm/vs/editor/editor.api"; import ReactResizeDetector from "react-resize-detector"; import { DocumentPanelDescriptorBase } from "../document-area/DocumentFactory"; import { FileOperationResponse } from "@core/messaging/message-types"; import { IDocumentPanel } from "@abstractions/document-service"; import { sendFromIdeToEmu } from "@core/messaging/message-sending"; import { getEditorService } from "./editorService"; import { findBreakpoint } from "@abstractions/debug-helpers"; import { SourceCodeBreakpoint } from "@abstractions/code-runner-service"; import { addBreakpointAction, normalizeBreakpointsAction, removeBreakpointAction, scrollBreakpointsAction, } from "@core/state/debugger-reducer"; // --- Wait 1000 ms before saving the document being edited const SAVE_DEBOUNCE = 1000; // --- Shortcuts to Monaco editor types type Decoration = monacoEditor.editor.IModelDeltaDecoration; type MarkdownString = monacoEditor.IMarkdownString; /** * Component properties */ interface Props { descriptor: IDocumentPanel; sourceCode: string; language: string; } /** * Component state */ interface State { width: string; height: string; show: boolean; } /** * This component implements a document editor based on Monaco editor */ export default class EditorDocument extends React.Component<Props, State> { private divHost = React.createRef<HTMLDivElement>(); private _editor: monacoEditor.editor.IStandaloneCodeEditor; private _unsavedChangeCounter = 0; private _descriptorChanged: () => void; private _refreshBreakpoints: () => void; private _subscribedToBreakpointEvents = false; private _oldDecorations: string[] = []; private _oldHoverDecorations: string[] = []; private _previousContent: string | null = null; /** * Initializes the editor * @param props */ constructor(props: Props) { super(props); this.state = { width: "100%", height: "100%", show: false, }; // --- Bind these event handlers this._descriptorChanged = () => this.descriptorChanged(); this._refreshBreakpoints = () => this.refreshBreakpoints(); } /** * Gets the resource name of this document */ get resourceName(): string { const projPath = getState().project.path; return this.props.descriptor.id.substr(projPath.length); } /** * Set up the Monaco editor before instantiating it * @param monaco */ editorWillMount(monaco: typeof monacoEditor): void { // --- Does the editor uses a custom language (and not one supported // --- out of the box)? if ( !monaco.languages .getLanguages() .some(({ id }) => id === this.props.language) ) { // --- Do we support that custom language? const languageInfo = getDocumentService().getCustomLanguage( this.props.language ); if (languageInfo) { // --- Yes, register the new language monaco.languages.register({ id: languageInfo.id }); // --- Register a tokens provider for the language monaco.languages.setMonarchTokensProvider( languageInfo.id, languageInfo.languageDef ); // --- Set the editing configuration for the language monaco.languages.setLanguageConfiguration( languageInfo.id, languageInfo.options ); // --- Define light theme for the language if (languageInfo.lightTheme) { monaco.editor.defineTheme(`${languageInfo.id}-light`, { base: "vs", inherit: true, rules: languageInfo.lightTheme.rules, encodedTokensColors: languageInfo.lightTheme.encodedTokensColors, colors: languageInfo.lightTheme.colors, }); } // --- Define dark theme for the language if (languageInfo.darkTheme) { monaco.editor.defineTheme(`${languageInfo.id}-dark`, { base: "vs-dark", inherit: true, rules: languageInfo.darkTheme.rules, encodedTokensColors: languageInfo.darkTheme.encodedTokensColors, colors: languageInfo.darkTheme.colors, }); } } } } /** * Set up the editor after that has been instantiated * @param editor * @param monaco */ editorDidMount( editor: monacoEditor.editor.IStandaloneCodeEditor, monaco: typeof monacoEditor ) { // --- Restore the previously saved state, provided we have one monaco.languages.setMonarchTokensProvider; this._editor = editor; const documentResource = this.props.descriptor.id; const state = getEditorService().loadState(documentResource); if (state) { this._editor.setValue(state.text); this._editor.restoreViewState(state.viewState); } // --- Take the focus, if the document want to have it if (this.props.descriptor.initialFocus) { window.requestAnimationFrame(() => this._editor.focus()); } // --- Does the editor support breakpoints? const languageInfo = getDocumentService().getCustomLanguage( this.props.language ); if (languageInfo?.supportsBreakpoints) { // --- Yes, this document manages breakpoints const store = getStore(); // --- Take care to refresh the breakpoint decorations whenever // --- breakpoints change store.breakpointsChanged.on(this._refreshBreakpoints); // --- Also, after a compilation, we have information about unreachable // --- breakpoints, refresh the decorations store.compilationChanged.on(this._refreshBreakpoints); // --- As we subscribed to breakpoint-related events, when disposing the // --- component, we need to unsubscribe from them. this._subscribedToBreakpointEvents = true; // --- Handle mouse events editor.onMouseDown((e) => this.handleEditorMouseDown(e)); editor.onMouseMove((e) => this.handleEditorMouseMove(e)); editor.onMouseLeave((e) => this.handleEditorMouseLeave(e)); // --- Display breakpoint information this.refreshBreakpoints(); } // --- Save the last value of the editor this._previousContent = editor.getValue(); } /** * Subscribes to events after the component has been mounted */ componentDidMount(): void { this.setState({ show: true }); this.props.descriptor.documentDescriptorChanged.on(this._descriptorChanged); } /** * Unsubscribes from events before the component is unmounted */ async componentWillUnmount(): Promise<void> { // --- Dispose event handler this.props.descriptor.documentDescriptorChanged.off( this._descriptorChanged ); if (this._subscribedToBreakpointEvents) { const store = getStore(); store.breakpointsChanged.off(this._refreshBreakpoints); store.compilationChanged.off(this._refreshBreakpoints); } // --- Check if this document is still registered const docId = this.props.descriptor.id; const doc = getDocumentService().getDocumentById(docId); if (doc) { // --- If so, save its state const text = this._editor.getValue(); getEditorService().saveState(this.props.descriptor.id, { text: this._editor.getValue(), viewState: this._editor.saveViewState(), }); // --- If there are pending changes not saved yet, save now if (this._unsavedChangeCounter > 0) { await this.saveDocument(text); } } } /** * Render the component visuals */ render() { const placeholderStyle: CSSProperties = { display: "flex", flexDirection: "column", flexGrow: 1, flexShrink: 1, width: "100%", height: "100%", overflow: "hidden", }; // --- Does the editor support breakpoints? const languageInfo = getDocumentService().getCustomLanguage( this.props.language ); const options: monacoEditor.editor.IEditorOptions = { selectOnLineNumbers: true, glyphMargin: languageInfo?.supportsBreakpoints, hover: { enabled: true, delay: 5000, sticky: true, }, }; const tone = getThemeService().getActiveTheme().tone; let theme = tone === "light" ? "vs" : "vs-dark"; if ( (languageInfo?.lightTheme && tone === "light") || (languageInfo?.darkTheme && tone === "dark") ) { theme = `${this.props.language}-${tone}`; } return ( <> <div ref={this.divHost} style={placeholderStyle}> {this.state.show && ( <MonacoEditor language={this.props.language} theme={theme} value={this.props.sourceCode} options={options} onChange={(value, e) => this.onEditorContentsChange(value, e)} editorWillMount={(editor) => this.editorWillMount(editor)} editorDidMount={(editor, monaco) => this.editorDidMount(editor, monaco) } /> )} </div> <ReactResizeDetector handleWidth handleHeight onResize={() => { this._editor.layout(); }} /> </> ); } /** * Make the editor focused when the descriptor changes to focused */ descriptorChanged(): void { if (this.props.descriptor.initialFocus) { window.requestAnimationFrame(() => this._editor.focus()); } } /** * Respond to editor contents changes * @param _newValue New editor contents * @param e Description of changes */ async onEditorContentsChange( _newValue: string, e: monacoEditor.editor.IModelContentChangedEvent ) { // --- Make the document permanent in the document tab bar const documentService = getDocumentService(); const currentDoc = documentService.getDocumentById( this.props.descriptor.id ); if (currentDoc?.temporary) { // --- Make a temporary document permanent currentDoc.temporary = false; documentService.registerDocument(currentDoc, true); } // --- Does the editor support breakpoints? const languageInfo = getDocumentService().getCustomLanguage( this.props.language ); if (languageInfo?.supportsBreakpoints) { // --- Keep track of breakpoint changes if (e.changes.length > 0) { // --- Get the text that has been deleted const change = e.changes[0]; const deletedText = monacoEditor.editor .createModel(this._previousContent) .getValueInRange(change.range); const deletedLines = (deletedText.match(new RegExp(e.eol, "g")) || []) .length; // --- Have we deleted one or more EOLs? if (deletedLines > 0) { // --- Yes, scroll up breakpoints const newBp = this.createBreakpointForLine( change.range.startLineNumber + deletedLines ); dispatch(scrollBreakpointsAction(newBp, -deletedLines)); } // --- Have we inserted one or more EOLs? const insertedLines = (change.text.match(new RegExp(e.eol, "g")) || []) .length; if (insertedLines > 0) { // --- Yes, scroll down breakpoints. const newBp = this.createBreakpointForLine( change.range.startLineNumber + (change.range.startColumn === 1 ? 0 : 1) ); dispatch(scrollBreakpointsAction(newBp, insertedLines)); } // --- If changed, normalize breakpoints if (deletedLines > 0 || insertedLines > 0) { dispatch( normalizeBreakpointsAction( this.resourceName, this._editor.getModel().getLineCount() ) ); } } } // --- Save the current value as the previous one this._previousContent = this._editor.getValue(); // --- Save document after the change (with delay) this._unsavedChangeCounter++; await new Promise((r) => setTimeout(r, SAVE_DEBOUNCE)); if (this._unsavedChangeCounter === 1 && this._previousContent) { await this.saveDocument(this._editor.getModel().getValue()); } this._unsavedChangeCounter--; } /** * Saves the document to its file * @param documentText Document text to save */ async saveDocument(documentText: string): Promise<void> { const result = await sendFromIdeToEmu<FileOperationResponse>({ type: "SaveFileContents", name: this.props.descriptor.id, contents: documentText, }); if (result.error) { console.error(result.error); } } /** * Takes care that the editor's breakpoint decorations are updated * @param breakpoints Current breakpoints * @param compilation Current compilations */ refreshBreakpoints(): void { // --- Filter for source code breakpoint belonging to this resoure const state = getState(); const breakpoints = state.debugger?.breakpoints ?? []; const editorBps = breakpoints.filter( (bp) => bp.type === "source" && bp.resource === this.resourceName ) as SourceCodeBreakpoint[]; // --- Get the active compilation result const compilationResult = state?.compilation?.result; // --- Create the array of decorators const decorations: Decoration[] = []; const editorLines = this._editor.getModel().getLineCount(); editorBps.forEach((bp) => { let unreachable = false; if (compilationResult?.errors?.length === 0) { // --- In case of a successful compilation, test if the breakpoint is allowed const fileIndex = compilationResult.sourceFileList.findIndex((fi) => fi.filename.endsWith(this.resourceName) ); if (fileIndex >= 0) { // --- We have address information for this source code file const bpInfo = compilationResult.listFileItems.find( (li) => li.fileIndex === fileIndex && li.lineNumber === bp.line ); unreachable = !bpInfo; } } if (bp.line <= editorLines) { const decoration = unreachable ? createUnreachableBreakpointDecoration(bp.line) : createBreakpointDecoration(bp.line); decorations.push(decoration); } else { dispatch(removeBreakpointAction(bp)); } }); this._oldDecorations = this._editor.deltaDecorations( this._oldDecorations, decorations ); } /** * Handles the editor's mousemove event * @param e */ handleEditorMouseMove(e: monacoEditor.editor.IEditorMouseEvent): void { if (e.target?.type === 2) { // --- Mouse is over the margin, display the breakpoint placeholder const lineNo = e.target.position.lineNumber; const existBp = this.findBreakpoint(lineNo); const message = `Click to ${ existBp ? "remove the existing" : "add a new" } breakpoint`; this._oldHoverDecorations = this._editor.deltaDecorations( this._oldHoverDecorations, [createHoverBreakpointDecoration(lineNo, message)] ); } else { // --- Mouse is out of margin, remove the breakpoint placeholder this._editor.deltaDecorations(this._oldHoverDecorations, []); } } /** * Handles the editor's mouseleave event * @param e */ handleEditorMouseLeave(e: monacoEditor.editor.IEditorMouseEvent): void { this._editor.deltaDecorations(this._oldHoverDecorations, []); } /** * Handles the editor's mouseleave event * @param e */ handleEditorMouseDown(e: monacoEditor.editor.IEditorMouseEvent): void { if (e.target?.type === 2) { // --- Breakpoint glyph is clicked const lineNo = e.target.position.lineNumber; const newBp = this.createBreakpointForLine(lineNo); const existBp = this.findBreakpoint(lineNo); if (existBp) { dispatch(removeBreakpointAction(existBp)); } else { dispatch(addBreakpointAction(newBp)); } this.handleEditorMouseLeave(e); } } /** * Tests if the breakpoint exists in the specified line * @param line Line number to test */ private createBreakpointForLine(line: number): SourceCodeBreakpoint | null { return { type: "source", resource: this.resourceName, line, }; } /** * Tests if the breakpoint exists in the specified line * @param line Line number to test */ private findBreakpoint(line: number): SourceCodeBreakpoint | null { const newBp: SourceCodeBreakpoint = { type: "source", resource: this.resourceName, line, }; const breakpoints = getState().debugger?.breakpoints ?? []; return findBreakpoint(breakpoints, newBp) as SourceCodeBreakpoint; } } /** * Descriptor for the sample side bar panel */ export class EditorDocumentPanelDescriptor extends DocumentPanelDescriptorBase { constructor( id: string, title: string, public readonly language: string, public readonly contents: string ) { super(id, title); } /** * Creates a node that represents the contents of a side bar panel */ createContentElement(): React.ReactNode { return ( <EditorDocument descriptor={this} sourceCode={this.contents} language={this.language} /> ); } } /** * Creates a breakpoint decoration * @param lineNo Line to apply the decoration to */ function createBreakpointDecoration( lineNo: number, message?: string ): Decoration { const hoverMessage: MarkdownString = message ? { value: message } : null; return { range: new monacoEditor.Range(lineNo, 1, lineNo, 1), options: { isWholeLine: false, glyphMarginClassName: "breakpointMargin", glyphMarginHoverMessage: hoverMessage, }, }; } /** * Creates a breakpoint decoration * @param lineNo Line to apply the decoration to */ function createHoverBreakpointDecoration( lineNo: number, message?: string ): Decoration { const hoverMessage: MarkdownString = message ? { value: message } : null; return { range: new monacoEditor.Range(lineNo, 1, lineNo, 1), options: { isWholeLine: false, glyphMarginClassName: "hoverBreakpointMargin", glyphMarginHoverMessage: hoverMessage, }, }; } /** * Creates an unreachable breakpoint decoration * @param lineNo Line to apply the decoration to * @returns */ function createUnreachableBreakpointDecoration(lineNo: number): Decoration { return { range: new monacoEditor.Range(lineNo, 1, lineNo, 1), options: { isWholeLine: false, glyphMarginClassName: "unreachableBreakpointMargin", }, }; } /** * Creates a current breakpoint decoration * @param lineNo Line to apply the decoration to * @returns */ function createCurrentBreakpointDecoration(lineNo: number): Decoration { return { range: new monacoEditor.Range(lineNo, 1, lineNo, 1), options: { isWholeLine: true, className: "activeBreakpointLine", glyphMarginClassName: "activeBreakpointMargin", }, }; }
the_stack
namespace LiteMol.Viewer.ValidatorDB { import Entity = Bootstrap.Entity; import Transformer = Bootstrap.Entity.Transformer; export interface Report extends Entity<Entity.Behaviour.Props<Interactivity.Behaviour>> { } export const Report = Entity.create<Entity.Behaviour.Props<Interactivity.Behaviour>>({ name: 'Ligand Validation Report', typeClass: 'Behaviour', shortName: 'VR', description: 'Represents ValidatorDB ligand validation report.' }); export namespace Api { export type Report = { get(authAsymId: string): undefined | { get(authSeqNumber: number): undefined | { flags: string[], isRed: boolean, chiralityMismatches: { has(atomName: string): boolean } } } }; function getResidueId(id: string, out: { authSeqNumber: number, authAsymId: string }) { let fields = id.split(' '); out.authSeqNumber = +fields[1]; out.authAsymId = fields[2]; } function getAtomName(id: string) { return id.split(' ')[0]; } const RedFlags = Core.Utils.FastSet.ofArray(['Missing', 'NotAnalyzed']); function isRed(flags: string[]) { for (let f of flags) if (RedFlags.has(f as 'Missing' | 'NotAnalyzed')) return true; return false; } export function createReport(data: any): Report { let report: any = Core.Utils.FastMap.create<string, any>(); if (!data.Models) return report; let residue = { authSeqNumber: 0, authAsymId: '' }; let emptySet = Core.Utils.FastSet.create<number>(); for (let model of data.Models) { for (let entry of model.Entries) { if (!entry.MainResidue) continue; getResidueId(entry.MainResidue, residue); let residueReport = report.get(residue.authAsymId) as Core.Utils.FastMap<number, any>; if (residueReport === void 0) { residueReport = Core.Utils.FastMap.create<number, any>(); report.set(residue.authAsymId, residueReport); } let flags: string[] = []; if (entry.Flags.indexOf('Missing_Atoms') >= 0) flags.push('Missing Atoms'); if (entry.Flags.indexOf('Missing_Rings') >= 0) flags.push('Missing Rings'); if (entry.Flags.indexOf('Missing_Degenerate') >= 0) flags.push('Degenerate'); if (entry.Flags.indexOf('HasAll_BadChirality') >= 0) flags.push('Bad Chirality'); if (!flags.length) flags.push('No Issue'); let chiralityMismatchSet: Core.Utils.FastSet<string> | undefined = void 0; let chiralityMismatches = entry.ChiralityMismatches; for (let _m of Object.keys(chiralityMismatches)) { if (!Object.prototype.hasOwnProperty.call(chiralityMismatches, _m)) continue; let a = chiralityMismatches[_m]; if (!chiralityMismatchSet) chiralityMismatchSet = Core.Utils.FastSet.create<string>(); chiralityMismatchSet.add(getAtomName(a)); } residueReport.set(residue.authSeqNumber, { isRed: isRed(entry.Flags), flags, chiralityMismatches: chiralityMismatchSet ? chiralityMismatchSet : emptySet }); } } return report; } } export namespace Interactivity { export class Behaviour implements Bootstrap.Behaviour.Dynamic { private provider: Bootstrap.Interactivity.HighlightProvider; dispose() { this.context.highlight.removeProvider(this.provider); } register(behaviour: any) { this.context.highlight.addProvider(this.provider); } private getChainId(id: string) { let idx = id.indexOf('-'); // check if we are in a computed chain. if (idx > 0) return id.substr(0, idx); return id; } private processInfo(info: Bootstrap.Interactivity.Info): string | undefined { let i = Bootstrap.Interactivity.Molecule.transformInteraction(info); if (!i || i.residues.length !== 1) return void 0; let r = this.report; if (i.atoms.length === 1) { let a = i.atoms[0]; let chain = r.get(this.getChainId(a.residue.chain.authAsymId)); let residue = chain ? chain.get(a.residue.authSeqNumber) : void 0; let badChirality = residue ? residue.chiralityMismatches.has(a.name) : false; if (!residue) return void 0; return `<div><small>[Validation]</small> Atom: <b>${badChirality ? 'Bad Chirality' : 'OK'}</b>, Residue: <b>${residue.flags.join(', ')}</b></div>`; } else { let res = i.residues[0]; let chain = r.get(this.getChainId(res.chain.authAsymId)); let residue = chain ? chain.get(res.authSeqNumber) : void 0; if (!residue) return void 0; return `<div><small>[Validation]</small> Residue: <b>${residue.flags.join(', ')}</b></div>`; } } constructor(public context: Bootstrap.Context, public report: Api.Report) { this.provider = info => { try { return this.processInfo(info); } catch (e) { console.error('Error showing validation label', e); return void 0; } }; } } } namespace Theme { const colorMap = (function () { let colors = Core.Utils.FastMap.create<number, LiteMol.Visualization.Color>(); colors.set(0, { r: 0.4, g: 0.4, b: 0.4 }); colors.set(1, { r: 0, g: 1, b: 0 }); colors.set(2, { r: 1, g: 0, b: 0 }); return colors; })(); const defaultColor = <LiteMol.Visualization.Color>{ r: 0.6, g: 0.6, b: 0.6 }; const selectionColor = <LiteMol.Visualization.Color>{ r: 0, g: 0, b: 1 }; const highlightColor = <LiteMol.Visualization.Color>{ r: 1, g: 0, b: 1 }; function createAtomMapNormal(model: LiteMol.Core.Structure.Molecule.Model, report: Api.Report) { let map = new Uint8Array(model.data.atoms.count); let { authAsymId, authSeqNumber, atomStartIndex, atomEndIndex } = model.data.residues; let { authName } = model.data.atoms; for (let rI = 0, _rI = model.data.residues.count; rI < _rI; rI++) { let repC = report.get(authAsymId[rI]); if (!repC) continue; let repR = repC.get(authSeqNumber[rI]); if (!repR) continue; let chiralityMismatches = repR.chiralityMismatches; for (let aI = atomStartIndex[rI], _aI = atomEndIndex[rI]; aI < _aI; aI++) { if (repR.isRed || chiralityMismatches.has(authName[aI])) map[aI] = 2; else map[aI] = 1; } } return map; } function createAtomMapComputed(model: LiteMol.Core.Structure.Molecule.Model, report: Api.Report) { let parent = model.parent!; let map = new Uint8Array(model.data.atoms.count); let { authSeqNumber, atomStartIndex, atomEndIndex, chainIndex } = model.data.residues; let { sourceChainIndex } = model.data.chains; let { authAsymId } = parent.data.chains; let { authName } = model.data.atoms; for (let rI = 0, _rI = model.data.residues.count; rI < _rI; rI++) { let repC = report.get(authAsymId[sourceChainIndex![chainIndex[rI]]]); if (!repC) continue; let repR = repC.get(authSeqNumber[rI]); if (!repR) continue; let chiralityMismatches = repR.chiralityMismatches; for (let aI = atomStartIndex[rI], _aI = atomEndIndex[rI]; aI < _aI; aI++) { if (repR.isRed || chiralityMismatches.has(authName[aI])) map[aI] = 2; else map[aI] = 1; } } return map; } export function create(entity: Bootstrap.Entity.Molecule.Model, report: any) { let model = entity.props.model; let map = model.source === Core.Structure.Molecule.Model.Source.File ? createAtomMapNormal(model, report) : createAtomMapComputed(model, report); let colors = Core.Utils.FastMap.create<string, LiteMol.Visualization.Color>(); colors.set('Uniform', defaultColor) colors.set('Selection', selectionColor) colors.set('Highlight', highlightColor); let mapping = Visualization.Theme.createColorMapMapping(i => map[i], colorMap, defaultColor); return Visualization.Theme.createMapping(mapping, { colors, interactive: true, transparency: { alpha: 1.0 } }); } } const Create = Bootstrap.Tree.Transformer.create<Entity.Data.String, Report, { id?: string }>({ id: 'validatordb-create', name: 'Ligand Validation', description: 'Create the validation report from a string.', from: [Entity.Data.String], to: [Report], defaultParams: () => ({}) }, (context, a, t) => { return Bootstrap.Task.create<Report>(`ValidatorDB Report (${t.params.id})`, 'Normal', async ctx => { await ctx.updateProgress('Parsing...'); let data = JSON.parse(a.props.data); let report = Api.createReport(data || {}); return Report.create(t, { label: 'Ligand Validation Report', behaviour: new Interactivity.Behaviour(context, report) }); }).setReportTime(true); } ); export const DownloadAndCreate = Bootstrap.Tree.Transformer.action<Entity.Molecule.Molecule, Entity.Action, { reportRef?: string }>({ id: 'validatordb-download-and-create', name: 'Ligand Validation Report', description: 'Download Validation Report from ValidatorDB', from: [Entity.Molecule.Molecule], to: [Entity.Action], defaultParams: () => ({}) }, (context, a, t) => { let id = a.props.molecule.id.trim().toLocaleLowerCase(); let action = Bootstrap.Tree.Transform.build() .add(a, Transformer.Data.Download, { url: `https://webchem.ncbr.muni.cz/Platform/ValidatorDb/Data/${id}?source=ByStructure`, type: 'String', id, description: 'Validation Data', title: 'Validation' }) .then(Create, { id }, { isBinding: true, ref: t.params.reportRef }); return action; }, "Validation report loaded. Hovering over residue will now contain validation info. To apply validation coloring, select the 'Ligand Validation Report' entity in the tree and apply it the right panel. " + "Only missing atoms/rings and chirality issues are shown, for more details please visit https://webchem.ncbr.muni.cz/Platform/ValidatorDb/Index."); export const ApplyTheme = Bootstrap.Tree.Transformer.create<Report, Entity.Action, { }>({ id: 'validatordb-apply-theme', name: 'Apply Coloring', description: 'Colors all visuals using the validation report.', from: [Report], to: [Entity.Action], defaultParams: () => ({}) }, (context, a, t) => { return Bootstrap.Task.create<Entity.Action>('Validation Coloring', 'Background', async ctx => { let molecule = Bootstrap.Tree.Node.findAncestor(a, Bootstrap.Entity.Molecule.Molecule); if (!molecule) { throw 'No suitable parent found.'; } let themes = Core.Utils.FastMap.create<number, Visualization.Theme>(); let visuals = context.select(Bootstrap.Tree.Selection.byValue(molecule).subtree().ofType(Bootstrap.Entity.Molecule.Visual)); for (let v of visuals) { let model = Bootstrap.Utils.Molecule.findModel(v); if (!model) continue; let theme = themes.get(model.id); if (!theme) { theme = Theme.create(model, a.props.behaviour.report); themes.set(model.id, theme); } Bootstrap.Command.Visual.UpdateBasicTheme.dispatch(context, { visual: v as any, theme }); } context.logger.message('Validation coloring applied.'); return Bootstrap.Tree.Node.Null; }); }); }
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 EMRcontainers extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: EMRcontainers.Types.ClientConfiguration) config: Config & EMRcontainers.Types.ClientConfiguration; /** * Cancels a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. */ cancelJobRun(params: EMRcontainers.Types.CancelJobRunRequest, callback?: (err: AWSError, data: EMRcontainers.Types.CancelJobRunResponse) => void): Request<EMRcontainers.Types.CancelJobRunResponse, AWSError>; /** * Cancels a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. */ cancelJobRun(callback?: (err: AWSError, data: EMRcontainers.Types.CancelJobRunResponse) => void): Request<EMRcontainers.Types.CancelJobRunResponse, AWSError>; /** * Creates a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. */ createManagedEndpoint(params: EMRcontainers.Types.CreateManagedEndpointRequest, callback?: (err: AWSError, data: EMRcontainers.Types.CreateManagedEndpointResponse) => void): Request<EMRcontainers.Types.CreateManagedEndpointResponse, AWSError>; /** * Creates a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. */ createManagedEndpoint(callback?: (err: AWSError, data: EMRcontainers.Types.CreateManagedEndpointResponse) => void): Request<EMRcontainers.Types.CreateManagedEndpointResponse, AWSError>; /** * Creates a virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. */ createVirtualCluster(params: EMRcontainers.Types.CreateVirtualClusterRequest, callback?: (err: AWSError, data: EMRcontainers.Types.CreateVirtualClusterResponse) => void): Request<EMRcontainers.Types.CreateVirtualClusterResponse, AWSError>; /** * Creates a virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. */ createVirtualCluster(callback?: (err: AWSError, data: EMRcontainers.Types.CreateVirtualClusterResponse) => void): Request<EMRcontainers.Types.CreateVirtualClusterResponse, AWSError>; /** * Deletes a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. */ deleteManagedEndpoint(params: EMRcontainers.Types.DeleteManagedEndpointRequest, callback?: (err: AWSError, data: EMRcontainers.Types.DeleteManagedEndpointResponse) => void): Request<EMRcontainers.Types.DeleteManagedEndpointResponse, AWSError>; /** * Deletes a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. */ deleteManagedEndpoint(callback?: (err: AWSError, data: EMRcontainers.Types.DeleteManagedEndpointResponse) => void): Request<EMRcontainers.Types.DeleteManagedEndpointResponse, AWSError>; /** * Deletes a virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. */ deleteVirtualCluster(params: EMRcontainers.Types.DeleteVirtualClusterRequest, callback?: (err: AWSError, data: EMRcontainers.Types.DeleteVirtualClusterResponse) => void): Request<EMRcontainers.Types.DeleteVirtualClusterResponse, AWSError>; /** * Deletes a virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. */ deleteVirtualCluster(callback?: (err: AWSError, data: EMRcontainers.Types.DeleteVirtualClusterResponse) => void): Request<EMRcontainers.Types.DeleteVirtualClusterResponse, AWSError>; /** * Displays detailed information about a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. */ describeJobRun(params: EMRcontainers.Types.DescribeJobRunRequest, callback?: (err: AWSError, data: EMRcontainers.Types.DescribeJobRunResponse) => void): Request<EMRcontainers.Types.DescribeJobRunResponse, AWSError>; /** * Displays detailed information about a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. */ describeJobRun(callback?: (err: AWSError, data: EMRcontainers.Types.DescribeJobRunResponse) => void): Request<EMRcontainers.Types.DescribeJobRunResponse, AWSError>; /** * Displays detailed information about a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. */ describeManagedEndpoint(params: EMRcontainers.Types.DescribeManagedEndpointRequest, callback?: (err: AWSError, data: EMRcontainers.Types.DescribeManagedEndpointResponse) => void): Request<EMRcontainers.Types.DescribeManagedEndpointResponse, AWSError>; /** * Displays detailed information about a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. */ describeManagedEndpoint(callback?: (err: AWSError, data: EMRcontainers.Types.DescribeManagedEndpointResponse) => void): Request<EMRcontainers.Types.DescribeManagedEndpointResponse, AWSError>; /** * Displays detailed information about a specified virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. */ describeVirtualCluster(params: EMRcontainers.Types.DescribeVirtualClusterRequest, callback?: (err: AWSError, data: EMRcontainers.Types.DescribeVirtualClusterResponse) => void): Request<EMRcontainers.Types.DescribeVirtualClusterResponse, AWSError>; /** * Displays detailed information about a specified virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. */ describeVirtualCluster(callback?: (err: AWSError, data: EMRcontainers.Types.DescribeVirtualClusterResponse) => void): Request<EMRcontainers.Types.DescribeVirtualClusterResponse, AWSError>; /** * Lists job runs based on a set of parameters. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. */ listJobRuns(params: EMRcontainers.Types.ListJobRunsRequest, callback?: (err: AWSError, data: EMRcontainers.Types.ListJobRunsResponse) => void): Request<EMRcontainers.Types.ListJobRunsResponse, AWSError>; /** * Lists job runs based on a set of parameters. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. */ listJobRuns(callback?: (err: AWSError, data: EMRcontainers.Types.ListJobRunsResponse) => void): Request<EMRcontainers.Types.ListJobRunsResponse, AWSError>; /** * Lists managed endpoints based on a set of parameters. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. */ listManagedEndpoints(params: EMRcontainers.Types.ListManagedEndpointsRequest, callback?: (err: AWSError, data: EMRcontainers.Types.ListManagedEndpointsResponse) => void): Request<EMRcontainers.Types.ListManagedEndpointsResponse, AWSError>; /** * Lists managed endpoints based on a set of parameters. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. */ listManagedEndpoints(callback?: (err: AWSError, data: EMRcontainers.Types.ListManagedEndpointsResponse) => void): Request<EMRcontainers.Types.ListManagedEndpointsResponse, AWSError>; /** * Lists the tags assigned to the resources. */ listTagsForResource(params: EMRcontainers.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: EMRcontainers.Types.ListTagsForResourceResponse) => void): Request<EMRcontainers.Types.ListTagsForResourceResponse, AWSError>; /** * Lists the tags assigned to the resources. */ listTagsForResource(callback?: (err: AWSError, data: EMRcontainers.Types.ListTagsForResourceResponse) => void): Request<EMRcontainers.Types.ListTagsForResourceResponse, AWSError>; /** * Lists information about the specified virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. */ listVirtualClusters(params: EMRcontainers.Types.ListVirtualClustersRequest, callback?: (err: AWSError, data: EMRcontainers.Types.ListVirtualClustersResponse) => void): Request<EMRcontainers.Types.ListVirtualClustersResponse, AWSError>; /** * Lists information about the specified virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. */ listVirtualClusters(callback?: (err: AWSError, data: EMRcontainers.Types.ListVirtualClustersResponse) => void): Request<EMRcontainers.Types.ListVirtualClustersResponse, AWSError>; /** * Starts a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. */ startJobRun(params: EMRcontainers.Types.StartJobRunRequest, callback?: (err: AWSError, data: EMRcontainers.Types.StartJobRunResponse) => void): Request<EMRcontainers.Types.StartJobRunResponse, AWSError>; /** * Starts a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. */ startJobRun(callback?: (err: AWSError, data: EMRcontainers.Types.StartJobRunResponse) => void): Request<EMRcontainers.Types.StartJobRunResponse, AWSError>; /** * Assigns tags to resources. A tag is a label that you assign to an AWS resource. Each tag consists of a key and an optional value, both of which you define. Tags enable you to categorize your AWS resources by attributes such as purpose, owner, or environment. When you have many resources of the same type, you can quickly identify a specific resource based on the tags you've assigned to it. For example, you can define a set of tags for your Amazon EMR on EKS clusters to help you track each cluster's owner and stack level. We recommend that you devise a consistent set of tag keys for each resource type. You can then search and filter the resources based on the tags that you add. */ tagResource(params: EMRcontainers.Types.TagResourceRequest, callback?: (err: AWSError, data: EMRcontainers.Types.TagResourceResponse) => void): Request<EMRcontainers.Types.TagResourceResponse, AWSError>; /** * Assigns tags to resources. A tag is a label that you assign to an AWS resource. Each tag consists of a key and an optional value, both of which you define. Tags enable you to categorize your AWS resources by attributes such as purpose, owner, or environment. When you have many resources of the same type, you can quickly identify a specific resource based on the tags you've assigned to it. For example, you can define a set of tags for your Amazon EMR on EKS clusters to help you track each cluster's owner and stack level. We recommend that you devise a consistent set of tag keys for each resource type. You can then search and filter the resources based on the tags that you add. */ tagResource(callback?: (err: AWSError, data: EMRcontainers.Types.TagResourceResponse) => void): Request<EMRcontainers.Types.TagResourceResponse, AWSError>; /** * Removes tags from resources. */ untagResource(params: EMRcontainers.Types.UntagResourceRequest, callback?: (err: AWSError, data: EMRcontainers.Types.UntagResourceResponse) => void): Request<EMRcontainers.Types.UntagResourceResponse, AWSError>; /** * Removes tags from resources. */ untagResource(callback?: (err: AWSError, data: EMRcontainers.Types.UntagResourceResponse) => void): Request<EMRcontainers.Types.UntagResourceResponse, AWSError>; } declare namespace EMRcontainers { export type ACMCertArn = string; export interface CancelJobRunRequest { /** * The ID of the job run to cancel. */ id: ResourceIdString; /** * The ID of the virtual cluster for which the job run will be canceled. */ virtualClusterId: ResourceIdString; } export interface CancelJobRunResponse { /** * The output contains the ID of the cancelled job run. */ id?: ResourceIdString; /** * The output contains the virtual cluster ID for which the job run is cancelled. */ virtualClusterId?: ResourceIdString; } export type ClientToken = string; export interface CloudWatchMonitoringConfiguration { /** * The name of the log group for log publishing. */ logGroupName: LogGroupName; /** * The specified name prefix for log streams. */ logStreamNamePrefix?: String256; } export type ClusterId = string; export interface Configuration { /** * The classification within a configuration. */ classification: String1024; /** * A set of properties specified within a configuration classification. */ properties?: SensitivePropertiesMap; /** * A list of additional configurations to apply within a configuration object. */ configurations?: ConfigurationList; } export type ConfigurationList = Configuration[]; export interface ConfigurationOverrides { /** * The configurations for the application running by the job run. */ applicationConfiguration?: ConfigurationList; /** * The configurations for monitoring. */ monitoringConfiguration?: MonitoringConfiguration; } export interface ContainerInfo { /** * The information about the EKS cluster. */ eksInfo?: EksInfo; } export interface ContainerProvider { /** * The type of the container provider. EKS is the only supported type as of now. */ type: ContainerProviderType; /** * The ID of the container cluster. */ id: ClusterId; /** * The information about the container cluster. */ info?: ContainerInfo; } export type ContainerProviderType = "EKS"|string; export interface CreateManagedEndpointRequest { /** * The name of the managed endpoint. */ name: ResourceNameString; /** * The ID of the virtual cluster for which a managed endpoint is created. */ virtualClusterId: ResourceIdString; /** * The type of the managed endpoint. */ type: EndpointType; /** * The Amazon EMR release version. */ releaseLabel: ReleaseLabel; /** * The ARN of the execution role. */ executionRoleArn: IAMRoleArn; /** * The certificate ARN of the managed endpoint. */ certificateArn: ACMCertArn; /** * The configuration settings that will be used to override existing configurations. */ configurationOverrides?: ConfigurationOverrides; /** * The client idempotency token for this create call. */ clientToken: ClientToken; /** * The tags of the managed endpoint. */ tags?: TagMap; } export interface CreateManagedEndpointResponse { /** * The output contains the ID of the managed endpoint. */ id?: ResourceIdString; /** * The output contains the name of the managed endpoint. */ name?: ResourceNameString; /** * The output contains the ARN of the managed endpoint. */ arn?: EndpointArn; /** * The output contains the ID of the virtual cluster. */ virtualClusterId?: ResourceIdString; } export interface CreateVirtualClusterRequest { /** * The specified name of the virtual cluster. */ name: ResourceNameString; /** * The container provider of the virtual cluster. */ containerProvider: ContainerProvider; /** * The client token of the virtual cluster. */ clientToken: ClientToken; /** * The tags assigned to the virtual cluster. */ tags?: TagMap; } export interface CreateVirtualClusterResponse { /** * This output contains the virtual cluster ID. */ id?: ResourceIdString; /** * This output contains the name of the virtual cluster. */ name?: ResourceNameString; /** * This output contains the ARN of virtual cluster. */ arn?: VirtualClusterArn; } export type _Date = Date; export interface DeleteManagedEndpointRequest { /** * The ID of the managed endpoint. */ id: ResourceIdString; /** * The ID of the endpoint's virtual cluster. */ virtualClusterId: ResourceIdString; } export interface DeleteManagedEndpointResponse { /** * The output displays the ID of the managed endpoint. */ id?: ResourceIdString; /** * The output displays the ID of the endpoint's virtual cluster. */ virtualClusterId?: ResourceIdString; } export interface DeleteVirtualClusterRequest { /** * The ID of the virtual cluster that will be deleted. */ id: ResourceIdString; } export interface DeleteVirtualClusterResponse { /** * This output contains the ID of the virtual cluster that will be deleted. */ id?: ResourceIdString; } export interface DescribeJobRunRequest { /** * The ID of the job run request. */ id: ResourceIdString; /** * The ID of the virtual cluster for which the job run is submitted. */ virtualClusterId: ResourceIdString; } export interface DescribeJobRunResponse { /** * The output displays information about a job run. */ jobRun?: JobRun; } export interface DescribeManagedEndpointRequest { /** * This output displays ID of the managed endpoint. */ id: ResourceIdString; /** * The ID of the endpoint's virtual cluster. */ virtualClusterId: ResourceIdString; } export interface DescribeManagedEndpointResponse { /** * This output displays information about a managed endpoint. */ endpoint?: Endpoint; } export interface DescribeVirtualClusterRequest { /** * The ID of the virtual cluster that will be described. */ id: ResourceIdString; } export interface DescribeVirtualClusterResponse { /** * This output displays information about the specified virtual cluster. */ virtualCluster?: VirtualCluster; } export interface EksInfo { /** * The namespaces of the EKS cluster. */ namespace?: KubernetesNamespace; } export interface Endpoint { /** * The ID of the endpoint. */ id?: ResourceIdString; /** * The name of the endpoint. */ name?: ResourceNameString; /** * The ARN of the endpoint. */ arn?: EndpointArn; /** * The ID of the endpoint's virtual cluster. */ virtualClusterId?: ResourceIdString; /** * The type of the endpoint. */ type?: EndpointType; /** * The state of the endpoint. */ state?: EndpointState; /** * The EMR release version to be used for the endpoint. */ releaseLabel?: ReleaseLabel; /** * The execution role ARN of the endpoint. */ executionRoleArn?: IAMRoleArn; /** * The certificate ARN of the endpoint. */ certificateArn?: ACMCertArn; /** * The configuration settings that are used to override existing configurations for endpoints. */ configurationOverrides?: ConfigurationOverrides; /** * The server URL of the endpoint. */ serverUrl?: UriString; /** * The date and time when the endpoint was created. */ createdAt?: _Date; /** * The security group configuration of the endpoint. */ securityGroup?: String256; /** * The subnet IDs of the endpoint. */ subnetIds?: SubnetIds; /** * Additional details of the endpoint state. */ stateDetails?: String256; /** * The reasons why the endpoint has failed. */ failureReason?: FailureReason; /** * The tags of the endpoint. */ tags?: TagMap; } export type EndpointArn = string; export type EndpointState = "CREATING"|"ACTIVE"|"TERMINATING"|"TERMINATED"|"TERMINATED_WITH_ERRORS"|string; export type EndpointStates = EndpointState[]; export type EndpointType = string; export type EndpointTypes = EndpointType[]; export type Endpoints = Endpoint[]; export type EntryPointArgument = string; export type EntryPointArguments = EntryPointArgument[]; export type EntryPointPath = string; export type FailureReason = "INTERNAL_ERROR"|"USER_ERROR"|"VALIDATION_ERROR"|"CLUSTER_UNAVAILABLE"|string; export type IAMRoleArn = string; export type JavaInteger = number; export type JobArn = string; export interface JobDriver { /** * The job driver parameters specified for spark submit. */ sparkSubmitJobDriver?: SparkSubmitJobDriver; } export interface JobRun { /** * The ID of the job run. */ id?: ResourceIdString; /** * The name of the job run. */ name?: ResourceNameString; /** * The ID of the job run's virtual cluster. */ virtualClusterId?: ResourceIdString; /** * The ARN of job run. */ arn?: JobArn; /** * The state of the job run. */ state?: JobRunState; /** * The client token used to start a job run. */ clientToken?: ClientToken; /** * The execution role ARN of the job run. */ executionRoleArn?: IAMRoleArn; /** * The release version of Amazon EMR. */ releaseLabel?: ReleaseLabel; /** * The configuration settings that are used to override default configuration. */ configurationOverrides?: ConfigurationOverrides; /** * Parameters of job driver for the job run. */ jobDriver?: JobDriver; /** * The date and time when the job run was created. */ createdAt?: _Date; /** * The user who created the job run. */ createdBy?: RequestIdentityUserArn; /** * The date and time when the job run has finished. */ finishedAt?: _Date; /** * Additional details of the job run state. */ stateDetails?: String256; /** * The reasons why the job run has failed. */ failureReason?: FailureReason; /** * The assigned tags of the job run. */ tags?: TagMap; } export type JobRunState = "PENDING"|"SUBMITTED"|"RUNNING"|"FAILED"|"CANCELLED"|"CANCEL_PENDING"|"COMPLETED"|string; export type JobRunStates = JobRunState[]; export type JobRuns = JobRun[]; export type KubernetesNamespace = string; export interface ListJobRunsRequest { /** * The ID of the virtual cluster for which to list the job run. */ virtualClusterId: ResourceIdString; /** * The date and time before which the job runs were submitted. */ createdBefore?: _Date; /** * The date and time after which the job runs were submitted. */ createdAfter?: _Date; /** * The name of the job run. */ name?: ResourceNameString; /** * The states of the job run. */ states?: JobRunStates; /** * The maximum number of job runs that can be listed. */ maxResults?: JavaInteger; /** * The token for the next set of job runs to return. */ nextToken?: NextToken; } export interface ListJobRunsResponse { /** * This output lists information about the specified job runs. */ jobRuns?: JobRuns; /** * This output displays the token for the next set of job runs. */ nextToken?: NextToken; } export interface ListManagedEndpointsRequest { /** * The ID of the virtual cluster. */ virtualClusterId: ResourceIdString; /** * The date and time before which the endpoints are created. */ createdBefore?: _Date; /** * The date and time after which the endpoints are created. */ createdAfter?: _Date; /** * The types of the managed endpoints. */ types?: EndpointTypes; /** * The states of the managed endpoints. */ states?: EndpointStates; /** * The maximum number of managed endpoints that can be listed. */ maxResults?: JavaInteger; /** * The token for the next set of managed endpoints to return. */ nextToken?: NextToken; } export interface ListManagedEndpointsResponse { /** * The managed endpoints to be listed. */ endpoints?: Endpoints; /** * The token for the next set of endpoints to return. */ nextToken?: NextToken; } export interface ListTagsForResourceRequest { /** * The ARN of tagged resources. */ resourceArn: RsiArn; } export interface ListTagsForResourceResponse { /** * The tags assigned to resources. */ tags?: TagMap; } export interface ListVirtualClustersRequest { /** * The container provider ID of the virtual cluster. */ containerProviderId?: String1024; /** * The container provider type of the virtual cluster. EKS is the only supported type as of now. */ containerProviderType?: ContainerProviderType; /** * The date and time after which the virtual clusters are created. */ createdAfter?: _Date; /** * The date and time before which the virtual clusters are created. */ createdBefore?: _Date; /** * The states of the requested virtual clusters. */ states?: VirtualClusterStates; /** * The maximum number of virtual clusters that can be listed. */ maxResults?: JavaInteger; /** * The token for the next set of virtual clusters to return. */ nextToken?: NextToken; } export interface ListVirtualClustersResponse { /** * This output lists the specified virtual clusters. */ virtualClusters?: VirtualClusters; /** * This output displays the token for the next set of virtual clusters. */ nextToken?: NextToken; } export type LogGroupName = string; export interface MonitoringConfiguration { /** * Monitoring configurations for the persistent application UI. */ persistentAppUI?: PersistentAppUI; /** * Monitoring configurations for CloudWatch. */ cloudWatchMonitoringConfiguration?: CloudWatchMonitoringConfiguration; /** * Amazon S3 configuration for monitoring log publishing. */ s3MonitoringConfiguration?: S3MonitoringConfiguration; } export type NextToken = string; export type PersistentAppUI = "ENABLED"|"DISABLED"|string; export type ReleaseLabel = string; export type RequestIdentityUserArn = string; export type ResourceIdString = string; export type ResourceNameString = string; export type RsiArn = string; export interface S3MonitoringConfiguration { /** * Amazon S3 destination URI for log publishing. */ logUri: UriString; } export type SensitivePropertiesMap = {[key: string]: String1024}; export interface SparkSubmitJobDriver { /** * The entry point of job application. */ entryPoint: EntryPointPath; /** * The arguments for job application. */ entryPointArguments?: EntryPointArguments; /** * The Spark submit parameters that are used for job runs. */ sparkSubmitParameters?: SparkSubmitParameters; } export type SparkSubmitParameters = string; export interface StartJobRunRequest { /** * The name of the job run. */ name?: ResourceNameString; /** * The virtual cluster ID for which the job run request is submitted. */ virtualClusterId: ResourceIdString; /** * The client idempotency token of the job run request. */ clientToken: ClientToken; /** * The execution role ARN for the job run. */ executionRoleArn: IAMRoleArn; /** * The Amazon EMR release version to use for the job run. */ releaseLabel: ReleaseLabel; /** * The job driver for the job run. */ jobDriver: JobDriver; /** * The configuration overrides for the job run. */ configurationOverrides?: ConfigurationOverrides; /** * The tags assigned to job runs. */ tags?: TagMap; } export interface StartJobRunResponse { /** * This output displays the started job run ID. */ id?: ResourceIdString; /** * This output displays the name of the started job run. */ name?: ResourceNameString; /** * This output lists the ARN of job run. */ arn?: JobArn; /** * This output displays the virtual cluster ID for which the job run was submitted. */ virtualClusterId?: ResourceIdString; } export type String1024 = string; export type String128 = string; export type String256 = string; export type StringEmpty256 = string; export type SubnetIds = String256[]; export type TagKeyList = String128[]; export type TagMap = {[key: string]: StringEmpty256}; export interface TagResourceRequest { /** * The ARN of resources. */ resourceArn: RsiArn; /** * The tags assigned to resources. */ tags: TagMap; } export interface TagResourceResponse { } export interface UntagResourceRequest { /** * The ARN of resources. */ resourceArn: RsiArn; /** * The tag keys of the resources. */ tagKeys: TagKeyList; } export interface UntagResourceResponse { } export type UriString = string; export interface VirtualCluster { /** * The ID of the virtual cluster. */ id?: ResourceIdString; /** * The name of the virtual cluster. */ name?: ResourceNameString; /** * The ARN of the virtual cluster. */ arn?: VirtualClusterArn; /** * The state of the virtual cluster. */ state?: VirtualClusterState; /** * The container provider of the virtual cluster. */ containerProvider?: ContainerProvider; /** * The date and time when the virtual cluster is created. */ createdAt?: _Date; /** * The assigned tags of the virtual cluster. */ tags?: TagMap; } export type VirtualClusterArn = string; export type VirtualClusterState = "RUNNING"|"TERMINATING"|"TERMINATED"|"ARRESTED"|string; export type VirtualClusterStates = VirtualClusterState[]; export type VirtualClusters = VirtualCluster[]; /** * 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 = "2020-10-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 EMRcontainers client. */ export import Types = EMRcontainers; } export = EMRcontainers;
the_stack
import {afterAll, beforeAll, describe, expect, it} from "@jest/globals"; import {Helper} from "./helper"; import {ElementHandle} from "puppeteer"; // captcha を完全に動的にするには、ページ内から読み込まれる画像リクエストのヘッダーをいじらないといけないので一旦保留 // import {sprintf} from 'sprintf-js'; // // // https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Math/random // function getRandomInt(min:number, max:number) :number{ // min = Math.ceil(min); // max = Math.floor(max); // return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive // } // // function generateRandomCaptchaKey():string{ // return sprintf("%04d", getRandomInt(1000,9999)); // } // await c.page.setExtraHTTPHeaders({ // "x-debug-force-captcha-key": captcha_key // }); describe("crawl some blog", () => { let c: Helper; let captcha_key: string = "1234"; const start_url = "/testblog2/"; beforeAll(async () => { c = new Helper(); await c.init(); }); it("open blog top", async () => { await c.openUrl(c.getBaseUrl() + start_url); await c.getSS("blog_top"); expect(await c.page.title()).toEqual("testblog2"); }); it("blog top - check cookie", async () => { const cookies = await c.page.cookies(); // ここがコケるということは、テスト無しにクッキーが追加されているかも expect(cookies.length).toEqual(2); const [session_cookie] = cookies.filter((elm) => elm.name === "dojima"); const [template_cookie] = cookies.filter( (elm) => elm.name === "template_blog_fc2" ); // console.log(session_cookie); expect(session_cookie.domain).toEqual("localhost"); expect(session_cookie.path).toEqual("/"); expect(session_cookie.expires).toEqual(-1); expect(session_cookie.httpOnly).toEqual(true); expect(session_cookie.secure).toEqual(false); expect(session_cookie.session).toEqual(true); expect(session_cookie.sameSite).toEqual("Lax"); // console.log(template_cookie); expect(template_cookie.value).toEqual("glid"); expect(template_cookie.domain).toEqual("localhost"); expect(template_cookie.path).toEqual("/"); // cookieは30日後に失効するように発行されているが、テスト時に正確に一致を期待してはいけないので前後60秒の誤差を許す const cookie_fuzz_lower = Math.floor(new Date().getTime() / 1000) + (30 * 24 * 60 * 60) - 60; const cookie_fuzz_higher = Math.floor(new Date().getTime() / 1000) + (30 * 24 * 60 * 60) + 60; expect(template_cookie.expires).toBeGreaterThan(cookie_fuzz_lower); expect(template_cookie.expires).toBeLessThan(cookie_fuzz_higher); expect(template_cookie.httpOnly).toEqual(false); expect(template_cookie.secure).toEqual(false); expect(template_cookie.session).toEqual(false); expect(template_cookie.sameSite).toEqual("Lax"); }); it("blog top - check fuzzy display contents", async () => { const title_text = await c.getTextBySelector("h1 a"); expect(title_text).toEqual("testblog2"); const entry_bodies = await c.page.$$eval("div.entry_body", (elm_list) => { let bodies = []; elm_list.forEach((elm) => bodies.push(elm.textContent)); return bodies; }); expect(entry_bodies[0].match(/3rd/)).toBeTruthy(); expect(entry_bodies[1].match(/2nd/)).toBeTruthy(); expect(entry_bodies[2].match(/テスト記事1/)).toBeTruthy(); }); it("blog top - click first entry's 「続きを読む」", async () => { const response = await c.clickBySelector("div.entry_body a"); await c.getSS("entry"); expect(response.url()).toEqual(c.getBaseUrl() + start_url + "blog-entry-3.html"); expect(await c.page.title()).toEqual("3rd - testblog2"); const entry_h2_title = await c.getTextBySelector("h2.entry_header"); expect(entry_h2_title.match(/3rd/)).toBeTruthy(); const entry_body = await c.getTextBySelector("div.entry_body"); expect(entry_body.match(/3rd/)).toBeTruthy(); }); it("entry page - click next page", async () => { const response = await c.clickBySelector("a.nextentry"); await c.getSS("entry_next_page"); expect(response.status()).toEqual(200); expect(response.url()).toEqual(c.getBaseUrl() + start_url + "blog-entry-2.html"); expect(await c.page.title()).toEqual("2nd - testblog2"); const entry_h2_title = await c.getTextBySelector("h2.entry_header"); expect(entry_h2_title.match(/2nd/)).toBeTruthy(); const entry_body = await c.getTextBySelector("div.entry_body"); expect(entry_body.match(/2nd/)).toBeTruthy(); }); it("entry page - click prev page", async () => { const response = await c.clickBySelector("a.preventry"); await c.getSS("entry_prev_page"); expect(response.status()).toEqual(200); expect(response.url()).toEqual(c.getBaseUrl() + start_url + "blog-entry-3.html"); expect(await c.page.title()).toEqual("3rd - testblog2"); const entry_h2_title = await c.getTextBySelector("h2.entry_header"); expect(entry_h2_title.match(/3rd/)).toBeTruthy(); const entry_body = await c.getTextBySelector("div.entry_body"); expect(entry_body.match(/3rd/)).toBeTruthy(); }); let posted_comment_num; let post_comment_title; it("entry page - fill comment form", async () => { // check comment form is shown expect( (await c.page.$eval("#cm h3.sub_header", (elm) => elm.textContent)).match( /コメント/ ) ).toBeTruthy(); expect( ( await c.page.$eval( "#cm div.form h4.sub_title", (elm) => elm.textContent ) ).match(/コメントの投稿/) ).toBeTruthy(); // generate uniq title post_comment_title = "テストタイトル_" + Math.floor(Math.random() * 1000000).toString(); await c.getSS("comment_before_fill"); await fillCommentForm( c.page, "テスト太郎", post_comment_title, "test@example.jp", "http://example.jp", "これはテスト投稿です\nこれはテスト投稿です!", "pass_is_pass" ) await c.getSS("comment_after_fill"); const response = await c.clickBySelector("#comment_form input[type=submit]"); await c.getSS("comment_confirm"); expect(response.url()).toEqual(c.getBaseUrl() + start_url); }); it("comment form - fail with wrong captcha", async () => { // input wrong captcha await c.page.type("input[name=token]", "0000"/*wrong key*/); const response = await c.clickBySelector("#sys-comment-form input[type=submit]"); await c.getSS("comment_wrong_captcha"); expect(response.status()).toEqual(200); expect(response.url()).toEqual(c.getBaseUrl() + start_url); // 特定しやすいセレクタがないので、回してチェックする const is_captcha_failed = await c.page.$$eval("p", (elms) => { let isOk = false; elms.forEach((elm) => { if (elm.textContent.match(/認証に失敗しました/)) { isOk = true; } }); return isOk; }); expect(is_captcha_failed).toBeTruthy(); }); it("comment form - successful comment posting", async () => { await c.page.type("input[name=token]", captcha_key); await c.getSS("before_comment_success"); const response = await c.clickBySelector("#sys-comment-form input[type=submit]"); expect(response.status()).toEqual(200); const exp = new RegExp( c.getBaseUrl() + start_url + "index.php\\?mode=entries&process=view&id=[0-9]{1,100}" ); expect(response.url().match(exp)).not.toBeNull(); await c.getSS("comment_success"); const comment_a_text = await c.page.$eval("#e3 > div.entry_footer > ul > li:nth-child(2) > a[title=コメントの投稿]", elm => elm.textContent); posted_comment_num = parseInt(comment_a_text.match(/CM:([0-9]{1,3})/)[1]); }); it("entry page - edit exists comment", async () => { await c.getSS("comment_edit_before"); await c.clickElement(await getEditLinkByTitle(post_comment_title)); await fillEditForm( c.page, "テスト太郎2", "edited_" + post_comment_title, "test2@example.jp", "http://example.jp/2", "これは編集済み", "pass_is_pass" ) await c.getSS("comment_edit_page"); // 確認フォームへ let response = await c.clickBySelector("#comment_form > p > input[type=submit]:nth-child(1)"); await c.getSS("comment_edit_confirm"); expect(response.status()).toEqual(200); // 保存実行 await c.page.type("input[name=token]", captcha_key); response = await c.clickBySelector("#sys-comment-form input[type=submit]"); await c.getSS("comment_edit_success"); expect(response.status()).toEqual(200); }); it("entry page - fail comment delete by wrong password", async () => { await c.getSS("comment_delete_fail_before"); // open comment edit page await c.clickElement(await getEditLinkByTitle("edited_" + post_comment_title)); const h3_test = await c.page.$eval("#edit > h3.sub_header", (elm) => { return elm.textContent; }); expect(h3_test.match(/コメントの編集/)).toBeTruthy(); // click delete button let response = await c.clickBySelector("#comment_form > p > input[type=submit]:nth-child(2)"); expect(response.status()).toEqual(200); expect(response.url()).toEqual(c.getBaseUrl() + start_url); // check shown error text const wrong_password_error_text = await c.page.$eval("#comment_form > dl > dd:nth-child(13) > p", elm => elm.textContent); expect(/必ず入力してください/.exec(wrong_password_error_text)).toBeTruthy(); }); it("entry page - successfully delete comment", async () => { await c.openUrl(c.getBaseUrl() + start_url + "blog-entry-3.html"); // open comment edit page await c.getSS("comment_before_delete1"); await c.clickElement(await getEditLinkByTitle("edited_" + post_comment_title)); await c.page.type("#pass", "pass_is_pass"); await c.getSS("comment_before_delete"); let response = await c.clickBySelector("#comment_form > p > input[type=submit]:nth-child(2)"); expect(response.url()).toEqual(c.getBaseUrl() + start_url + "index.php?mode=entries&process=view&id=3"); await c.getSS("comment_deleted"); const comment_a_text = await c.page.$eval("#e3 > div.entry_footer > ul > li:nth-child(2) > a", elm => elm.textContent); const comment_num = parseInt(comment_a_text.match(/CM:([0-9]{1,3})/)[1]); // expect(comment_num).toEqual(posted_comment_num/*-1*/); // パラレルでテストが実行されるので、数を数えても正しくできない }); afterAll(async () => { await c.browser.close(); }); // ======================== async function getEditLinkByTitle(title): Promise<ElementHandle> { // 該当するタイトルの編集リンクを探す const elm_list = await c.page.$$("#cm div.sub_content"); const data_list = []; for (let i = 0; i < elm_list.length; i++) { const item = { title: await (await elm_list[i].$eval("h4", elm => elm.textContent)), editLink: await (await elm_list[i].$("a[title='コメントの編集']")), debugHtml: await (await elm_list[i].getProperty('innerHTML')).jsonValue() }; data_list.push(item); } let edit_link: ElementHandle; data_list.forEach((row) => { if (row.title === title) { edit_link = row.editLink; } }); if (!edit_link) { throw new Error("link(a[title='コメントの編集']) not found"); } return edit_link; } async function fillCommentForm( page, name, title, email, url, body, pass = "", ) { await page.$eval( "#comment_form input[name='comment[name]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form input[name='comment[name]']", name ); await page.$eval( "#comment_form input[name='comment[title]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form input[name='comment[title]']", title ); await page.$eval( "#comment_form input[name='comment[mail]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form input[name='comment[mail]']", email ); await page.$eval( "#comment_form input[name='comment[url]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form input[name='comment[url]']", url ); await page.$eval( "#comment_form textarea[name='comment[body]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form textarea[name='comment[body]']", body ); await page.$eval( "#comment_form input[name='comment[pass]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form input[name='comment[pass]']", pass ); } async function fillEditForm( page, name, title, email, url, body, pass = "", ) { await page.$eval( "#comment_form input[name='edit[name]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form input[name='edit[name]']", name ); await page.$eval( "#comment_form input[name='edit[title]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form input[name='edit[title]']", title ); await page.$eval( "#comment_form input[name='edit[mail]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form input[name='edit[mail]']", email ); await page.$eval( "#comment_form input[name='edit[url]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form input[name='edit[url]']", url ); await page.$eval( "#comment_form textarea[name='edit[body]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form textarea[name='edit[body]']", body ); await page.$eval( "#comment_form input[name='edit[pass]']", (elm: HTMLInputElement) => (elm.value = "") ); await page.type( "#comment_form input[name='edit[pass]']", pass ); } });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { ContentType } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ApiManagementClient } from "../apiManagementClient"; import { ContentTypeContract, ContentTypeListByServiceNextOptionalParams, ContentTypeListByServiceOptionalParams, ContentTypeListByServiceResponse, ContentTypeGetOptionalParams, ContentTypeGetResponse, ContentTypeCreateOrUpdateOptionalParams, ContentTypeCreateOrUpdateResponse, ContentTypeDeleteOptionalParams, ContentTypeListByServiceNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing ContentType operations. */ export class ContentTypeImpl implements ContentType { private readonly client: ApiManagementClient; /** * Initialize a new instance of the class ContentType class. * @param client Reference to the service client */ constructor(client: ApiManagementClient) { this.client = client; } /** * Lists the developer portal's content types. Content types describe content items' properties, * validation rules, and constraints. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ public listByService( resourceGroupName: string, serviceName: string, options?: ContentTypeListByServiceOptionalParams ): PagedAsyncIterableIterator<ContentTypeContract> { const iter = this.listByServicePagingAll( resourceGroupName, serviceName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByServicePagingPage( resourceGroupName, serviceName, options ); } }; } private async *listByServicePagingPage( resourceGroupName: string, serviceName: string, options?: ContentTypeListByServiceOptionalParams ): AsyncIterableIterator<ContentTypeContract[]> { let result = await this._listByService( resourceGroupName, serviceName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByServiceNext( resourceGroupName, serviceName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByServicePagingAll( resourceGroupName: string, serviceName: string, options?: ContentTypeListByServiceOptionalParams ): AsyncIterableIterator<ContentTypeContract> { for await (const page of this.listByServicePagingPage( resourceGroupName, serviceName, options )) { yield* page; } } /** * Lists the developer portal's content types. Content types describe content items' properties, * validation rules, and constraints. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ private _listByService( resourceGroupName: string, serviceName: string, options?: ContentTypeListByServiceOptionalParams ): Promise<ContentTypeListByServiceResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, options }, listByServiceOperationSpec ); } /** * Gets the details of the developer portal's content type. Content types describe content items' * properties, validation rules, and constraints. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param contentTypeId Content type identifier. * @param options The options parameters. */ get( resourceGroupName: string, serviceName: string, contentTypeId: string, options?: ContentTypeGetOptionalParams ): Promise<ContentTypeGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, contentTypeId, options }, getOperationSpec ); } /** * Creates or updates the developer portal's content type. Content types describe content items' * properties, validation rules, and constraints. Custom content types' identifiers need to start with * the `c-` prefix. Built-in content types can't be modified. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param contentTypeId Content type identifier. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, serviceName: string, contentTypeId: string, options?: ContentTypeCreateOrUpdateOptionalParams ): Promise<ContentTypeCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, contentTypeId, options }, createOrUpdateOperationSpec ); } /** * Removes the specified developer portal's content type. Content types describe content items' * properties, validation rules, and constraints. Built-in content types (with identifiers starting * with the `c-` prefix) can't be removed. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param contentTypeId Content type identifier. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header * response of the GET request or it should be * for unconditional update. * @param options The options parameters. */ delete( resourceGroupName: string, serviceName: string, contentTypeId: string, ifMatch: string, options?: ContentTypeDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, contentTypeId, ifMatch, options }, deleteOperationSpec ); } /** * ListByServiceNext * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param nextLink The nextLink from the previous successful call to the ListByService method. * @param options The options parameters. */ private _listByServiceNext( resourceGroupName: string, serviceName: string, nextLink: string, options?: ContentTypeListByServiceNextOptionalParams ): Promise<ContentTypeListByServiceNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, nextLink, options }, listByServiceNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listByServiceOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/contentTypes", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ContentTypeCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/contentTypes/{contentTypeId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ContentTypeContract, headersMapper: Mappers.ContentTypeGetHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.contentTypeId ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/contentTypes/{contentTypeId}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.ContentTypeContract, headersMapper: Mappers.ContentTypeCreateOrUpdateHeaders }, 201: { bodyMapper: Mappers.ContentTypeContract, headersMapper: Mappers.ContentTypeCreateOrUpdateHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.contentTypeId ], headerParameters: [Parameters.accept, Parameters.ifMatch], serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/contentTypes/{contentTypeId}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.contentTypeId ], headerParameters: [Parameters.accept, Parameters.ifMatch1], serializer }; const listByServiceNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ContentTypeCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
import React from 'react'; import { StyleSheet, View } from 'react-native'; import MapView, {Marker, Polyline, Circle} from 'react-native-maps'; import BackgroundGeolocation, { State, Location, MotionChangeEvent, Geofence, GeofencesChangeEvent, GeofenceEvent } from "../react-native-background-geolocation"; import SettingsService from "./lib/SettingsService"; import ENV from "../ENV"; import {COLORS, SOUNDS} from './lib/config'; import { toRad, toDeg, getBearing, computeOffsetCoordinate } from "./lib/GeoMath" /// A default empty location object for the MapView. const UNDEFINED_LOCATION = { timestamp: '', latitude:0, longitude:0 } /// Zoom values for the MapView const LATITUDE_DELTA = 0.00922; const LONGITUDE_DELTA = 0.00421; /// Color consts for MapView markers. const STATIONARY_REGION_FILL_COLOR = "rgba(200,0,0,0.2)" const STATIONARY_REGION_STROKE_COLOR = "rgba(200,0,0,0.2)" const GEOFENCE_STROKE_COLOR = "rgba(17,183,0,0.5)" const GEOFENCE_FILL_COLOR ="rgba(17,183,0,0.2)" const GEOFENCE_STROKE_COLOR_ACTIVATED = "rgba(127,127,127,0.5)"; const GEOFENCE_FILL_COLOR_ACTIVATED = "rgba(127,127,127, 0.2)"; const POLYLINE_STROKE_COLOR = "rgba(32,64,255,0.6)"; const TSMapView = (props) => { const navigation = props.navigation; /// MapView State. const [markers, setMarkers] = React.useState<any[]>([]); const [showsUserLocation, setShowsUserLocation] = React.useState(false); const [tracksViewChanges, setTracksViewChanges] = React.useState(false); const [followsUserLocation, setFollowUserLocation] = React.useState(false); const [mapScrollEnabled, setMapScrollEnabled] = React.useState(false); const [stationaryLocation, setStationaryLocation] = React.useState(UNDEFINED_LOCATION); const [mapCenter, setMapCenter] = React.useState({ latitude: 45.518853, longitude: -73.60055, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA }); const [stationaryRadius, setStationaryRadius] = React.useState(200); const [geofencesHit, setGeofencesHit] = React.useState<any[]>([]); const [geofencesHitEvents, setGeofenceHitEvents] = React.useState<any[]>([]); const [coordinates, setCoordinates] = React.useState<any[]>([]); const [stopZones, setStopZones] = React.useState<any[]>([]); /// BackgroundGeolocation Events. const [location, setLocation] = React.useState<Location>(null); const [motionChangeEvent, setMotionChangeEvent] = React.useState<MotionChangeEvent>(null); const [lastMotionChangeEvent, setLastMotionChangeEvent] = React.useState<MotionChangeEvent>(null); const [geofences, setGeofences] = React.useState<any[]>([]); const [geofenceEvent, setGeofenceEvent] = React.useState<GeofenceEvent>(null); const [geofencesChangeEvent, setGeofencesChangeEvent] = React.useState<GeofencesChangeEvent>(null); const [enabled, setEnabled] = React.useState(false); /// Handy Util class. const settingsService = SettingsService.getInstance(); /// Collection of BackgroundGeolocation event-subscriptions. const subscriptions:any[] = []; /// [Helper] Add a BackgroundGeolocation event subscription to collection const subscribe = (subscription:any) => { subscriptions.push(subscription); } /// [Helper] Iterate BackgroundGeolocation subscriptions and .remove() each. const unsubscribe = () => { subscriptions.forEach((subscription:any) => subscription.remove()); subscriptions.splice(0, subscriptions.length); } /// Register BackgroundGeolocation event-listeners. React.useEffect(() => { BackgroundGeolocation.getState().then((state:State) => { setEnabled(state.enabled); }); // All BackgroundGeolocation event-listeners use React.useState setters. subscribe(BackgroundGeolocation.onLocation(setLocation, (error) => { console.warn('[onLocation] ERROR: ', error); })); subscribe(BackgroundGeolocation.onMotionChange(setMotionChangeEvent)); subscribe(BackgroundGeolocation.onGeofence(setGeofenceEvent)); subscribe(BackgroundGeolocation.onGeofencesChange(setGeofencesChangeEvent)); subscribe(BackgroundGeolocation.onEnabledChange(setEnabled)); return () => { // Important for with live-reload to remove BackgroundGeolocation event subscriptions. unsubscribe(); clearMarkers(); } }, []); /// onEnabledChange effect. /// React.useEffect(() => { onEnabledChange(); }, [enabled]); /// onLocation effect. /// React.useEffect(() => { if (!location) return; onLocation(); }, [location]); /// onMotionChange effect /// React.useEffect(() => { if (!motionChangeEvent) return; onMotionChange(); }, [motionChangeEvent]); /// onGeofence effect. /// React.useEffect(() => { if (!geofenceEvent) return; onGeofence(); }, [geofenceEvent]); /// onGeofencesChange effect /// React.useEffect(() => { if (!geofencesChangeEvent) return; onGeofencesChange(); }, [geofencesChangeEvent]); /// onLocation effect-handler /// Adds a location Marker to MapView /// const onLocation = () => { console.log('[location] - ', location); if (!location.sample) { addMarker(location); } setCenter(location); } /// GeofenceEvent effect-handler /// Renders geofence event markers to MapView. /// const onGeofence = () => { const location:Location = geofenceEvent.location; const marker = geofences.find((m:any) => { return m.identifier === geofenceEvent.identifier; }); if (!marker) { return; } marker.fillColor = GEOFENCE_STROKE_COLOR_ACTIVATED; marker.strokeColor = GEOFENCE_STROKE_COLOR_ACTIVATED; const coords = location.coords; let hit = geofencesHit.find((hit:any) => { return hit.identifier === geofenceEvent.identifier; }); if (!hit) { hit = { identifier: geofenceEvent.identifier, radius: marker.radius, center: { latitude: marker.center.latitude, longitude: marker.center.longitude }, events: [] }; setGeofencesHit(previous => [...previous, hit]); } // Get bearing of location relative to geofence center. const bearing = getBearing(marker.center, location.coords); const edgeCoordinate = computeOffsetCoordinate(marker.center, marker.radius, bearing); const record = { coordinates: [ edgeCoordinate, {latitude: coords.latitude, longitude: coords.longitude}, ], action: geofenceEvent.action, key: geofenceEvent.identifier + ":" + geofenceEvent.action + ":" + location.timestamp }; setGeofenceHitEvents(previous => [...previous, record]); } /// GeofencesChangeEvent effect-handler /// Renders/removes geofence markers to/from MapView /// const onGeofencesChange = () => { let on = geofencesChangeEvent.on; let off = geofencesChangeEvent.off; // Filter out all "off" geofences. let geofencesOn = geofences.filter((geofence:Geofence) => { return off.indexOf(geofence.identifier) < 0; }); console.log('[geofenceschange] - ', geofencesChangeEvent); // Add new "on" geofences. on.forEach((geofence:Geofence) => { let marker = geofencesOn.find((m:Geofence) => { return m.identifier === geofence.identifier;}); if (marker) { return; } geofencesOn.push(createGeofenceMarker(geofence)); }); setGeofences(geofencesOn); } /// EnabledChange effect-handler. /// Removes all MapView Markers when plugin is disabled. /// const onEnabledChange = () => { console.log('[onEnabledChange]', enabled); setShowsUserLocation(enabled); if (!enabled) { clearMarkers(); } } /// onMotionChangeEvent effect-handler. /// show/hide the red stationary-geofence according isMoving /// const onMotionChange = async () => { console.log('[onMotionChange] - ', motionChangeEvent.isMoving, motionChangeEvent.location); let location = motionChangeEvent.location; let state:any = { isMoving: motionChangeEvent.isMoving }; if (motionChangeEvent.isMoving) { if (lastMotionChangeEvent) { setStopZones(previous => [...previous, { coordinate: { latitude: lastMotionChangeEvent.location.coords.latitude, longitude: lastMotionChangeEvent.location.coords.longitude }, key: lastMotionChangeEvent.location.timestamp }]); } setStationaryRadius(0); setStationaryLocation(UNDEFINED_LOCATION); } else { let state = await BackgroundGeolocation.getState(); let geofenceProximityRadius = state.geofenceProximityRadius || 1000; setStationaryRadius((state.trackingMode == 1) ? 200 : (geofenceProximityRadius/2)); setStationaryLocation({ timestamp: location.timestamp, latitude: location.coords.latitude, longitude: location.coords.longitude }); } setLastMotionChangeEvent(motionChangeEvent); } /// MapView Location marker-renderer. const renderMarkers = () => { let rs:any = []; markers.map((marker:any) => { rs.push(( <Marker key={marker.key} tracksViewChanges={tracksViewChanges} coordinate={marker.coordinate} anchor={{x:0, y:0.1}} title={marker.title}> <View style={[styles.markerIcon]}></View> </Marker> )); }); return rs; } /// Render stop-zone markers -- small red circles where the plugin previously entered /// the stationary state. const renderStopZoneMarkers = () => { return stopZones.map((stopZone:any) => ( <Marker key={stopZone.key} tracksViewChanges={tracksViewChanges} coordinate={stopZone.coordinate} anchor={{x:0, y:0}}> <View style={[styles.stopZoneMarker]}></View> </Marker> )); } /// Render the list of current active geofences that BackgroundGeolocation is monitoring. const renderActiveGeofences = () => { return geofences.map((geofence:any) => { return ( <Circle key={geofence.identifier} radius={geofence.radius} center={geofence.center} strokeWidth={1} strokeColor={geofence.strokeColor} fillColor={geofence.fillColor} onPress={onPressGeofence} /> ) }); } /// Render the list of geofences which have fired. const renderGeofencesHit = () => { let rs = []; return geofencesHit.map((hit:any) => { return ( <Circle key={"hit:" + hit.identifier} radius={hit.radius+1} center={hit.center} strokeWidth={1} strokeColor={COLORS.black}> </Circle> ); }); } /// Render the series of markers showing where a geofence hit event occurred. const renderGeofencesHitEvents = () => { return geofencesHitEvents.map((event:any) => { let isEnter = (event.action === 'ENTER'); let color = undefined; switch(event.action) { case 'ENTER': color = COLORS.green; break; case 'EXIT': color = COLORS.red; break; case 'DWELL': color = COLORS.gold; break; } let markerStyle = { backgroundColor: color }; return ( <View key={event.key}> <Polyline key="polyline" coordinates={event.coordinates} geodesic={true} strokeColor={COLORS.black} strokeWidth={1} zIndex={1} lineCap="square" /> <Marker key="edge_marker" coordinate={event.coordinates[0]} anchor={{x:0, y:0.1}}> <View style={[styles.geofenceHitMarker, markerStyle]}></View> </Marker> <Marker key="location_marker" coordinate={event.coordinates[1]} anchor={{x:0, y:0.1}}> <View style={styles.markerIcon}></View> </Marker> </View> ); }); } /// Center the map. const setCenter = (location:Location) => { setMapCenter({ latitude: location.coords.latitude, longitude: location.coords.longitude, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA }); } /// Add a location Marker to map. const addMarker = (location:Location) => { const timestamp = new Date(); const marker = { key: `${location.uuid}:${timestamp.getTime()}`, title: location.timestamp, heading: location.coords.heading, coordinate: { latitude: location.coords.latitude, longitude: location.coords.longitude } }; setMarkers(previous => [...previous, marker]); setCoordinates(previous => [...previous, { latitude: location.coords.latitude, longitude: location.coords.longitude }]); } /// Returns a geofence marker for MapView const createGeofenceMarker = (geofence:Geofence) => { return { radius: geofence.radius, center: { latitude: geofence.latitude, longitude: geofence.longitude }, identifier: geofence.identifier, strokeColor:GEOFENCE_STROKE_COLOR, fillColor: GEOFENCE_FILL_COLOR } } /// Map pan/drag handler. const onMapPanDrag = () => { setFollowUserLocation(false); setMapScrollEnabled(true); } /// Map long-press handler for adding a geofence. const onLongPress = (params:any) => { const coordinate = params.nativeEvent.coordinate; settingsService.playSound('LONG_PRESS_ACTIVATE'); navigation.navigate('Geofence', {coordinate:coordinate}); } /// Geofence press-handler. const onPressGeofence = () => { console.log('[onPressGeofence] NO IMPLEMENTATION'); } /// Clear all markers from the map when plugin is toggled off. const clearMarkers = () => { setCoordinates([]); setMarkers([]); setStopZones([]); setGeofences([]); setGeofencesHit([]); setGeofenceHitEvents([]); setStationaryRadius(0); setGeofenceEvent(null); } return ( <MapView showsUserLocation={showsUserLocation} region={mapCenter} followsUserLocation={false} onLongPress={onLongPress} onPanDrag={onMapPanDrag} scrollEnabled={mapScrollEnabled} showsMyLocationButton={false} showsPointsOfInterest={false} showsScale={false} showsTraffic={false} style={styles.map} toolbarEnabled={false}> <Circle key={"stationary-location:" + stationaryLocation.timestamp} radius={stationaryRadius} fillColor={STATIONARY_REGION_FILL_COLOR} strokeColor={STATIONARY_REGION_STROKE_COLOR} strokeWidth={1} center={{ latitude: stationaryLocation.latitude, longitude: stationaryLocation.longitude }} /> <Polyline key="polyline" coordinates={coordinates} geodesic={true} strokeColor='rgba(0,179,253, 0.6)' strokeWidth={6} zIndex={0} /> {renderMarkers()} {renderStopZoneMarkers()} {renderActiveGeofences()} {renderGeofencesHit()} {renderGeofencesHitEvents()} </MapView> ) } export default TSMapView; var styles = StyleSheet.create({ container: { backgroundColor: '#272727' }, map: { flex: 1 }, stopZoneMarker: { borderWidth:1, borderColor: 'red', backgroundColor: COLORS.red, opacity: 0.2, borderRadius: 15, zIndex: 0, width: 30, height: 30 }, geofenceHitMarker: { borderWidth: 1, borderColor:'black', borderRadius: 6, zIndex: 10, width: 12, height:12 }, markerIcon: { borderWidth:1, borderColor:'#000000', backgroundColor: COLORS.polyline_color, //backgroundColor: 'rgba(0,179,253, 0.6)', width: 10, height: 10, borderRadius: 5 } });
the_stack
import FilterUtil from './FilterUtil'; import { Filter, Rule } from 'geostyler-style'; import TestUtil from './TestUtil'; describe('FilterUtil', () => { let filter: Filter; beforeEach(() => { filter = TestUtil.getDummyGsFilter(); }); describe('featureMatchesFilter', () => { it('returns true if a feature matches the filter', () => { const dummyData = TestUtil.getComplexGsDummyData(); const matchingFeature = dummyData.exampleFeatures.features[0]; matchingFeature.properties.state = 'germany'; matchingFeature.properties.population = 150000; matchingFeature.properties.name = 'NotSchalke'; const matches = FilterUtil.featureMatchesFilter(filter, matchingFeature); expect(matches).toBe(true); }); it('returns false if a feature does not match the filter', () => { const dummyData = TestUtil.getComplexGsDummyData(); const matchingFeature = dummyData.exampleFeatures.features[0]; matchingFeature.properties.state = 'belgium'; matchingFeature.properties.population = 150000; matchingFeature.properties.name = 'NotSchalke'; const matches = FilterUtil.featureMatchesFilter(filter, matchingFeature); expect(matches).toBe(false); }); }); describe('getMatches', () => { it('returns an array of all matched features', () => { const dummyData = TestUtil.getComplexGsDummyData(); dummyData.exampleFeatures.features[0].properties.state = 'germany'; dummyData.exampleFeatures.features[0].properties.population = 150000; dummyData.exampleFeatures.features[0].properties.name = 'NotSchalke'; const matchingFeature = dummyData.exampleFeatures.features[0]; const matches = FilterUtil.getMatches(filter, dummyData); expect(matches).toEqual([matchingFeature]); }); it('returns an empty array if no matches found', () => { const dummyData = TestUtil.getComplexGsDummyData(); const matches = FilterUtil.getMatches(filter, dummyData); expect(matches).toHaveLength(0); }); }); describe('calculateCountAndDuplicates', () => { it('returns the right number of duplicates, not considering scale constraints', () => { const dummyData = TestUtil.getComplexGsDummyData(); const filter2 = TestUtil.getDummyGsFilter(); dummyData.exampleFeatures.features[0].properties.state = 'germany'; dummyData.exampleFeatures.features[0].properties.population = 150000; dummyData.exampleFeatures.features[0].properties.name = 'NotSchalke'; const rules: Rule[] = [{ name: 'rule1', symbolizers: [] }, { name: 'rule2', symbolizers: [], filter: filter2 }]; const result = FilterUtil.calculateCountAndDuplicates(rules, dummyData); expect(result.duplicates[0]).toBeCloseTo(1); expect(result.duplicates[1]).toBeCloseTo(1); }); it('returns the right number of duplicates per scale', () => { const dummyData = TestUtil.getComplexGsDummyData(); dummyData.exampleFeatures.features[0].properties.state = 'germany'; dummyData.exampleFeatures.features[0].properties.population = 150000; dummyData.exampleFeatures.features[0].properties.name = 'NotSchalke'; const rules: Rule[] = [ { 'name': 'Mehr als 4', 'symbolizers': [ { 'kind': 'Mark', 'wellKnownName': 'circle' } ], 'filter': [ '>', 'pop', 4000000 ], 'scaleDenominator': { 'max': 10000, 'min': 0 } }, { 'name': 'Mehr als 8', 'symbolizers': [ { 'kind': 'Mark', 'wellKnownName': 'circle', 'color': '#0E1058' } ], 'filter': [ '>', 'pop', 8000000 ], 'scaleDenominator': { 'max': 10000, 'min': 0 } }, { 'name': 'Mehr als 4', 'symbolizers': [ { 'kind': 'Mark', 'wellKnownName': 'circle', 'color': '#0E1058' } ], 'filter': [ '>', 'pop', 4000000 ], 'scaleDenominator': { 'min': 10000, 'max': 0 } }, { 'name': 'Mehr als 8', 'symbolizers': [ { 'kind': 'Mark', 'wellKnownName': 'circle', 'color': '#0E1058' } ], 'filter': [ '>', 'pop', 8000000 ], 'scaleDenominator': { 'min': 10000, 'max': null } } ]; const result = FilterUtil.calculateCountAndDuplicates(rules, dummyData); expect(result.duplicates[0]).toBe(13); expect(result.duplicates[1]).toBe(9); expect(result.duplicates[2]).toBe(13); expect(result.duplicates[3]).toBe(9); }); }); describe('positionArrayAsString', () => { it('transforms positionArrays to strings as expected', () => { const array1 = [1, 3, 6, 2]; const array2 = [3, 3, 5]; const array3 = [4, 7]; const string1 = '[1][3][6][2]'; const string2 = '[3][3][5]'; const string3 = '[4][7]'; expect(FilterUtil.positionArrayAsString(array1)).toEqual(string1); expect(FilterUtil.positionArrayAsString(array2)).toEqual(string2); expect(FilterUtil.positionArrayAsString(array3)).toEqual(string3); }); }); describe('positionStringAsArray', () => { it('transforms positionStrings to arrays as expected', () => { const array1 = [1, 3, 6, 2]; const array2 = [3, 3, 5]; const array3 = [4, 7]; const string1 = '[1][3][6][2]'; const string2 = '[3][3][5]'; const string3 = '[4][7]'; expect(FilterUtil.positionStringAsArray(string1)).toEqual(array1); expect(FilterUtil.positionStringAsArray(string2)).toEqual(array2); expect(FilterUtil.positionStringAsArray(string3)).toEqual(array3); }); }); describe('getFilterAtPosition', () => { it('returns the expected filter', () => { expect(FilterUtil.getFilterAtPosition(filter, '')).toEqual(filter); expect(FilterUtil.getFilterAtPosition(filter, '[1]')).toEqual(filter[1]); expect(FilterUtil.getFilterAtPosition(filter, '[1][1]')).toEqual(filter[1][1]); expect(FilterUtil.getFilterAtPosition(filter, '[1][2]')).toEqual(filter[1][2]); expect(FilterUtil.getFilterAtPosition(filter, '[2][1]')).toEqual(filter[2][1]); }); }); describe('removeFilter', () => { it('removes a filter at a given position', () => { const got1: Filter = [ '&&', [ '||', ['>=', 'population', 100000], ['<', 'population', 200000] ], [ '!', ['==', 'name', 'Schalke'] ] ]; const newFilter1 = FilterUtil.removeFilter(filter, '[1]'); expect(newFilter1).toEqual(got1); }); }); describe('changeFilter', () => { it('changes a Filter at a given position', () => { const got1: Filter = [ '||', ['==', 'state', 'germany'], [ '||', ['>=', 'population', 100000], ['<', 'population', 200000] ], [ '!', ['==', 'name', 'Schalke'] ] ]; const newFilter1 = FilterUtil.changeFilter(filter, '', 'or'); expect(newFilter1).toEqual(got1); const got2: Filter = [ '&&', ['==', 'state', 'germany'], ['!', ['==', '', '']], ['!', ['==', 'name', 'Schalke']] ]; const newFilter2 = FilterUtil.changeFilter(filter, '[2]', 'not'); expect(newFilter2).toEqual(got2); const got3: Filter = [ '&&', ['==', 'state', 'germany'], ['==', '', ''], [ '!', ['==', 'name', 'Schalke'] ] ]; const newFilter3 = FilterUtil.changeFilter(filter, '[2]', 'comparison'); expect(newFilter3).toEqual(got3); }); }); describe('addFilter', () => { it('adds a filter of a given type at the given position.', () => { const got1: Filter = [ '&&', ['==', 'state', 'germany'], [ '||', ['>=', 'population', 100000], ['<', 'population', 200000] ], [ '!', ['==', 'name', 'Schalke'] ], ['&&', ['==', '', ''], ['==', '', '']] ]; const newFilter1 = FilterUtil.addFilter(filter, '', 'and'); expect(newFilter1).toEqual(got1); const got2: Filter = [ '&&', ['==', 'state', 'germany'], [ '||', ['>=', 'population', 100000], ['<', 'population', 200000], ['==', '', ''] ], [ '!', ['==', 'name', 'Schalke'] ] ]; const newFilter2 = FilterUtil.addFilter(filter, '[2]', 'comparison'); expect(newFilter2).toEqual(got2); }); }); describe('removeAtPosition', () => { it('removes a filter at the expected position', () => { const got = [ '&&', ['==', 'state', 'germany'], [ '!', ['==', 'name', 'Schalke'] ] ]; const newFilter = FilterUtil.removeAtPosition(filter, '[2]'); expect(newFilter).toEqual(got); const got2 = [ '&&', [ '!', ['==', 'name', 'Schalke'] ] ]; const newFilter2 = FilterUtil.removeAtPosition(newFilter, '[1]'); expect(newFilter2).toEqual(got2); }); }); describe('insertAtPosition', () => { it('insterts a filter at the expected position', () => { const baseFilter: Filter = [ '&&', [ '!', ['==', 'name', 'Schalke'] ] ]; const got = [ '&&', ['==', 'state', 'germany'], [ '!', ['==', 'name', 'Schalke'] ] ]; const newFilter = FilterUtil.insertAtPosition(baseFilter, ['==', 'state', 'germany'], '[1]', 0); expect(newFilter).toEqual(got); const newFilter2 = FilterUtil.insertAtPosition( newFilter, [ '||', ['>=', 'population', 100000], ['<', 'population', 200000] ], '[1]', 2 ); expect(newFilter2).toEqual(filter); }); }); });
the_stack
import { ISEAPair } from "../sea/ISEAPair"; import { And } from "../shared/And"; import { AckCallback } from "./AckCallback"; import { AuthCallback } from "./AuthCallback"; import { CreateCallback } from "./CreateCallback"; import { IGunConstructorOptions } from "./IGunConstructorOptions"; import { IGunDataType, IGunNodeDataType } from "./IGunDataType"; import { IGunFinalUserTreeMethods } from "./IGunFinalUserTreeMethods"; import { IGunReturnObject } from "./IGunReturnObject"; import { IGunTree } from "./IGunTree"; export interface IGunUserInstance<CurrentDataType extends IGunNodeDataType, TKey extends string | undefined> { /** * check out https://gun.eco/docs/User#user-secret * save secret that only trusted users can read * */ not?(callback: (key: TKey) => void): IGunUserInstance<CurrentDataType, TKey> ; /** * Say you save some data, but want to do something with it later, like expire it or refresh it. * Well, then `later` is for you! You could use this to easily implement a TTL or similar behavior. * * **Warning**: Not included by default! You must include it yourself via `require('gun/lib/later.js')` or * `<script src="https://cdn.jsdelivr.net/npm/gun/lib/later.js"></script>`! */ later?(callback: (data: CurrentDataType, key: TKey) => void, seconds: number): IGunUserInstance<CurrentDataType, TKey> ; off(): IGunUserInstance<CurrentDataType, TKey> ; /* /** * Save data into gun, syncing it with your connected peers. * * * You cannot save primitive values at the root level. * * @param data You do not need to re-save the entire object every time, * gun will automatically merge your data into what already exists as a "partial" update. * * * `undefined`, `NaN`, `Infinity`, `array`, will be rejected. * * Traditional arrays are dangerous in real-time apps. Use `gun.set` instead. * * @param callback invoked on each acknowledgment * @param options additional options (used for specifying certs) */ put(data: Partial<CurrentDataType>, callback?: AckCallback | null, options?: { opt?: { cert?: string } }):IGunUserInstance<CurrentDataType, TKey> /** * Subscribe to updates and changes on a node or property in real-time. * @param option Currently, the only option is to filter out old data, and just be given the changes. * If you're listening to a node with 100 fields, and just one changes, * you'll instead be passed a node with a single property representing that change rather than the full node every time. * @param callback * Once initially and whenever the property or node you're focused on changes, this callback is immediately fired with the data as it is at that point in time. * * Since gun streams data, the callback will probably be called multiple times as new chunks come in. * To remove a listener call .off() on the same property or node. */ on(callback: (data: IGunReturnObject<CurrentDataType, TKey>, key: TKey, _msg:any, _ev:any) => void, option?: { change: boolean; } | boolean, eas?:{$?:any, subs?: unknown[] | { push(arg: unknown) }}, as?:any): IGunUserInstance<CurrentDataType, TKey> | Promise<IGunReturnObject<CurrentDataType, TKey>>; /** * Subscribe to database event. * @param eventName event name that you want listen to (currently only 'auth') * @param callback once event fire callback */ on(eventName: 'auth', cb: AuthCallback, eas?:{$?:any, subs?: unknown[] | { push(arg: unknown) }}, as?:any):IGunUserInstance<CurrentDataType, TKey> /** * Get the current data without subscribing to updates. Or `undefined` if it cannot be found. * @returns In the document, it said the return value may change in the future. Don't rely on it. */ once(callback?: (data: IGunReturnObject<CurrentDataType, TKey>, key: TKey) => void, option?: { wait: number; }): IGunUserInstance<CurrentDataType, TKey> | Promise<IGunReturnObject<CurrentDataType, TKey>>; /** * Open behaves very similarly to gun.on, except it gives you the **full depth of a document** on every update. * It also works with graphs, tables, or other data structures. Think of it as opening up a live connection to a document. * * **Warning**: Not included by default! You must include it yourself via `require('gun/lib/open.js')` or * `<script src="https://cdn.jsdelivr.net/npm/gun/lib/open.js"></script>`! */ open?(callback: (data: IGunReturnObject<CurrentDataType, TKey>) => any, opt?: { at?: any, key?: any, doc?: any, ids?: any, any?: any, meta?: any, ev?: { off?: () => {} } }, at?: Partial<CurrentDataType>): IGunUserInstance<CurrentDataType, TKey> | Promise<IGunReturnObject<CurrentDataType, TKey>>; /** * Loads the full object once. It is the same as `open` but with the behavior of `once`. * * **Warning**: Not included by default! You must include it yourself via `require('gun/lib/load.js')` or * `<script src="https://cdn.jsdelivr.net/npm/gun/lib/load.js"></script>`! */ load?(callback: (data: IGunReturnObject<CurrentDataType, TKey>) => void, opt?: { at?: any, key?: any, doc?: any, ids?: any, any?: any, meta?: any, ev?: { off?: () => {} } }, at?: Partial<CurrentDataType>): IGunUserInstance<CurrentDataType, TKey> | Promise<IGunReturnObject<CurrentDataType, TKey>> /**goes back user chain */ back(amount?:number) : IGunUserInstance<CurrentDataType, string> secret(string: string, callback : (...args:unknown[])=> any): IGunUserInstance<CurrentDataType, TKey> is?: { alias: string | ISEAPair epub: string pub: string } /** * Creates a new user and calls callback upon completion. * @param alias Username or Alias which can be used to find a user. * @param pass Passphrase that will be extended with PBKDF2 to make it a secure way to login. * @param cb Callback that is to be called upon creation of the user. * @param opt Option Object containing options for creation. (In gun options are added at end of syntax. opt is rarely used, hence is added at the end.) */ create(alias: string, pass: string, cb?: CreateCallback, opt?: {}): unknown; /** * Creates a new user and calls callback upon completion. * @param pair User cryptographic pair * @param cb Callback that is to be called upon creation of the user. * @param opt Option Object containing options for creation. (In gun options are added at end of syntax. opt is rarely used, hence is added at the end.) */ create(pair: ISEAPair, cb?: AuthCallback, opt?: {}): unknown; /** * Authenticates a user, previously created via User.create. * @param alias Username or Alias which can be used to find a user. * @param pass Passphrase for the user * @param cb Callback that is to be called upon authentication of the user. * @param opt Option Object containing options for authentication. (In gun options are added at end of syntax. opt is rarely used, hence is added at the end.) */ auth(alias: string, pass: string, cb?:AuthCallback, opt?: {}): unknown /** * Authenticates a user, previously created via User.create. * @param pair Public/Private Key Pair * @param cb Callback that is to be called upon authentication of the user. * @param opt Option Object containing options for authentication. (In gun options are added at end of syntax. opt is rarely used, hence is added at the end.) */ auth(pair: ISEAPair, cb?: AuthCallback, opt?: {}): unknown; /** * Log out currently authenticated user. Parameters are unused in the current implementation. * @param opt unused in current implementation. * @param cb unused in current implementation. */ leave(opt?: never, cb?: never): unknown; /** * Deletes a user from the current gun instance and propagates the delete to other peers. * @param alias Username or alias. * @param pass Passphrase for the user. * @param cb Callback that is called when the user was successfully deleted. */ delete(alias: string, pass: string, cb?: (ack: { ok: 0; }) => void): Promise<void>; /** * Where to read data from. * @param key The key is the ID or property name of the data that you saved from earlier * (or that will be saved later). * * Note that if you use .put at any depth after a get it first reads the data and then writes, merging the data as a partial update. * @param callback You will usually be using gun.on or gun.once to actually retrieve your data, * not this callback (it is intended for more low-level control, for module and extensions). * * **Avoid use callback. The type in the document may be wrong.** * * **Here the type of callback respect to the actual behavior** */ get<K extends keyof CurrentDataType>(key: K, callback?: ( data: IGunReturnObject<CurrentDataType[K], string>, key: K) => any): And< Promise<CurrentDataType[K]>, CurrentDataType[K] extends IGunDataType ? IGunUserInstance<CurrentDataType[K], string> & IGunFinalUserTreeMethods<CurrentDataType[K], K, string> : IGunDataType extends CurrentDataType[K] ? IGunFinalUserTreeMethods<CurrentDataType[K], K, string> & IGunUserInstance< IGunDataType , string> : IGunFinalUserTreeMethods<CurrentDataType[K], K, string>> /** * **.set does not mean 'set data', it means a Mathematical Set** * * Add a unique item to an unordered list. * `gun.set` works like a mathematical set, where each item in the list is unique. * If the item is added twice, it will be merged. * * **This means only objects, for now, are supported.** * @param data the object to add to the set * @param callback optional function to invoke when the operation is complete * @param options additional options (used for specifying certs) */ set<K extends keyof CurrentDataType>(data: CurrentDataType[K], callback?: AckCallback | null, options?: { opt?: { cert?: string } }): CurrentDataType[K] extends IGunDataType? IGunUserInstance<CurrentDataType[K], string>: IGunFinalUserTreeMethods<CurrentDataType[K], K, string> ; opt(opt: IGunConstructorOptions): unknown /** * Recall saves a users credentials in sessionStorage of the browser. As long as the tab of your app is not closed the user stays logged in, even through page refreshes and reloads. * @param opt option object If you want to use browser sessionStorage to allow users to stay logged in as long as the session is open, set opt.sessionStorage to true * @param cb internally the callback is passed on to the user.auth function to log the user back in. Refer to user.auth for callback documentation. */ recall(opt?: { sessionStorage: boolean; }, cb?: AuthCallback): IGunUserInstance<CurrentDataType, TKey>; map(match: IGunTree ): CurrentDataType[keyof CurrentDataType] extends IGunDataType? IGunUserInstance<CurrentDataType[keyof CurrentDataType], string> : IGunFinalUserTreeMethods<CurrentDataType[keyof CurrentDataType], keyof CurrentDataType, string> map<T>(match: (data: CurrentDataType) => T ): IGunFinalUserTreeMethods<T, keyof CurrentDataType, string> /** * Subscribes to all future events that occur on the Timegraph and retrieve a specified number of old events * * **Warning**: The Timegraph extension isn't required by default, you would need to include at "gun/lib/time.js" */ time?<K extends keyof CurrentDataType>(callback: (data: CurrentDataType[K], key: K, time: number) => void, alsoReceiveNOldEvents?: number): CurrentDataType[K] extends IGunDataType ? IGunUserInstance<CurrentDataType[K], string>: IGunFinalUserTreeMethods<CurrentDataType[K], K, string>; /** Pushes data to a Timegraph with it's time set to Gun.state()'s time */ time?<K extends keyof CurrentDataType>(data: CurrentDataType[K]): CurrentDataType[K] extends IGunDataType ? IGunUserInstance<CurrentDataType[K], string>: IGunFinalUserTreeMethods<CurrentDataType[K], K, string>; /** * @param publicKey If you know a users publicKey you can get their user graph and see any unencrypted data they may have stored there. */ user<TUserGraph extends IGunDataType>(): IGunUserInstance<TUserGraph, undefined> user(publicKey: string): IGunUserInstance<CurrentDataType, undefined> }
the_stack
export * from "./core-react/UiCore"; export * from "./core-react/badge/Badge"; export * from "./core-react/badge/BadgeUtilities"; export * from "./core-react/badge/BetaBadge"; export * from "./core-react/badge/NewBadge"; export * from "./core-react/base/Div"; export * from "./core-react/base/DivWithOutsideClick"; export * from "./core-react/base/Centered"; export * from "./core-react/base/FillCentered"; export * from "./core-react/base/FlexWrapContainer"; export * from "./core-react/base/Gap"; export * from "./core-react/base/PointerEvents"; export * from "./core-react/base/ScrollView"; export * from "./core-react/button/Button"; export * from "./core-react/button/UnderlinedButton"; export * from "./core-react/checklistbox/CheckListBox"; export * from "./core-react/contextmenu/ContextMenu"; export * from "./core-react/contextmenu/ContextMenuDirection"; export * from "./core-react/contextmenu/ContextMenuDivider"; export * from "./core-react/contextmenu/ContextMenuItem"; export * from "./core-react/contextmenu/ContextSubMenu"; export * from "./core-react/contextmenu/GlobalContextMenu"; export * from "./core-react/contextmenu/PopupContextMenu"; export * from "./core-react/dialog/Dialog"; export * from "./core-react/dialog/DialogButtonDef"; export * from "./core-react/dialog/GlobalDialog"; export * from "./core-react/elementseparator/ElementSeparator"; export * from "./core-react/enums/Alignment"; export * from "./core-react/enums/CheckBoxState"; export * from "./core-react/enums/Orientation"; export * from "./core-react/enums/SortDirection"; export * from "./core-react/enums/TimeFormat"; export * from "./core-react/expandable/ExpandableList"; export * from "./core-react/expandable/ExpandableBlock"; export * from "./core-react/focus/ItemKeyboardNavigator"; export * from "./core-react/focustrap/FocusTrap"; export * from "./core-react/form/Field"; export * from "./core-react/form/Form"; export * from "./core-react/hocs/withIsPressed"; export * from "./core-react/hocs/withOnOutsideClick"; export * from "./core-react/hocs/withTimeout"; export * from "./core-react/icons/IconComponent"; export * from "./core-react/icons/SvgPath"; export * from "./core-react/icons/SvgSprite"; export * from "./core-react/icons/WebFontIcon"; export * from "./core-react/autosuggest/AutoSuggest"; export * from "./core-react/checkbox/Checkbox"; export * from "./core-react/imagecheckbox/ImageCheckBox"; export * from "./core-react/inputs/Input"; export * from "./core-react/inputs/InputLabel"; export * from "./core-react/inputs/InputStatus"; export * from "./core-react/inputs/iconinput/IconInput"; export * from "./core-react/inputs/LabeledComponentProps"; export * from "./core-react/inputs/LabeledInput"; export * from "./core-react/inputs/LabeledTextarea"; export * from "./core-react/inputs/numberinput/NumberInput"; export * from "./core-react/inputs/Textarea"; export * from "./core-react/listbox/Listbox"; export * from "./core-react/loading/LoadingBar"; export * from "./core-react/loading/LoadingPrompt"; export * from "./core-react/loading/LoadingSpinner"; export * from "./core-react/loading/LoadingStatus"; export * from "./core-react/loading/Spinner"; export * from "./core-react/messagebox/MessageBox"; export * from "./core-react/messagebox/MessageSeverity"; export * from "./core-react/notification/MessageRenderer"; export * from "./core-react/notification/MessageType"; export * from "./core-react/popup/Popup"; export * from "./core-react/progress-indicators/ProgressBar"; export * from "./core-react/progress-indicators/ProgressSpinner"; export * from "./core-react/radialmenu/RadialMenu"; export * from "./core-react/radialmenu/Annulus"; export * from "./core-react/radio/Radio"; export * from "./core-react/select/LabeledSelect"; export * from "./core-react/select/Select"; export * from "./core-react/select/ThemedSelect"; export * from "./core-react/select/LabeledThemedSelect"; export * from "./core-react/searchbox/SearchBox"; export * from "./core-react/settings/SettingsManager"; export * from "./core-react/settings/SettingsContainer"; export * from "./core-react/slider/Slider"; export * from "./core-react/splitbutton/SplitButton"; export * from "./core-react/tabs/HorizontalTabs"; export * from "./core-react/tabs/VerticalTabs"; export * from "./core-react/tabs/Tabs"; export * from "./core-react/text/BodyText"; export * from "./core-react/text/BlockText"; export * from "./core-react/text/DisabledText"; export * from "./core-react/text/FilteredText"; export * from "./core-react/text/Headline"; export * from "./core-react/text/LeadingText"; export * from "./core-react/text/LeadingText2"; export * from "./core-react/text/MutedText"; export * from "./core-react/text/SmallText"; export * from "./core-react/text/Subheading"; export * from "./core-react/text/Subheading2"; export * from "./core-react/text/StyledText"; export * from "./core-react/text/TextProps"; export * from "./core-react/text/Title"; export * from "./core-react/text/Title2"; export * from "./core-react/tiles/FeaturedTile"; export * from "./core-react/tiles/MinimalFeaturedTile"; export * from "./core-react/tiles/MinimalTile"; export * from "./core-react/tiles/Tile"; export * from "./core-react/toggle/Toggle"; export * from "./core-react/toggle/LabeledToggle"; export * from "./core-react/tooltip/Tooltip"; export { ExpansionToggle, ExpansionToggleProps } from "./core-react/tree/ExpansionToggle"; export { TreeBranch, TreeBranchProps } from "./core-react/tree/Branch"; export { TreeNode, TreeNodeProps, NodeCheckboxProps, NodeCheckboxRenderer, NodeCheckboxRenderProps } from "./core-react/tree/Node"; export { Tree, TreeProps } from "./core-react/tree/Tree"; export { TreeNodePlaceholder, TreeNodePlaceholderProps } from "./core-react/tree/Placeholder"; export * from "./core-react/uisettings/UiSetting"; export * from "./core-react/uisettings/UiSettingsStorage"; export * from "./core-react/uisettings/LocalSettingsStorage"; export * from "./core-react/uisettings/SessionSettingsStorage"; export * from "./core-react/utils/IconHelper"; export * from "./core-react/utils/Point"; export * from "./core-react/utils/PointProps"; export * from "./core-react/utils/Props"; export * from "./core-react/utils/Rectangle"; export * from "./core-react/utils/Size"; export * from "./core-react/utils/Timer"; export * from "./core-react/utils/UiEvent"; export * from "./core-react/utils/UiGeometry"; export * from "./core-react/utils/flattenChildren"; export * from "./core-react/utils/getBestBWContrastColor"; export * from "./core-react/utils/getCssVariable"; export * from "./core-react/utils/getDisplayName"; export * from "./core-react/utils/getUserColor"; export * from "./core-react/utils/shallowDiffers"; export * from "./core-react/utils/typeUtils"; export * from "./core-react/utils/isPromiseLike"; export * from "./core-react/utils/ScrollPositionMaintainer"; export * from "./core-react/utils/hooks/useDisposable"; export * from "./core-react/utils/hooks/useEffectSkipFirst"; export * from "./core-react/utils/hooks/useEventListener"; export * from "./core-react/utils/hooks/ResizeObserverPolyfill"; export * from "./core-react/utils/hooks/useOnOutsideClick"; export * from "./core-react/utils/hooks/useProximityToMouse"; export * from "./core-react/utils/hooks/useRefEffect"; export * from "./core-react/utils/hooks/useRefs"; export * from "./core-react/utils/hooks/useRefState"; export * from "./core-react/utils/hooks/useResizeObserver"; export * from "./core-react/utils/hooks/useTargeted"; export * from "./core-react/utils/hooks/useWidgetOpacityContext"; /** @docs-package-description * The core-react package contains general purpose React components, such as Dialog, MessageBox, SearchBox, RadialMenu and SplitButton. * For more information, see [learning about core-react]($docs/learning/ui/core/index.md). */ /** * @docs-group-description AutoSuggest * Component for input with an auto-suggestion dropdown. */ /** * @docs-group-description Base * Low-level classes and components for building application UI. */ /** * @docs-group-description Button * Components for working with various Buttons. */ /** * @docs-group-description Checkbox * Component is a wrapper for the `<input type="checkbox">` HTML element. */ /** * @docs-group-description CheckListBox * Components for working with a Check listbox. */ /** * @docs-group-description Common * Common classes and enums used across various UI components. */ /** * @docs-group-description ContextMenu * Components for working with a Context Menu. */ /** * @docs-group-description Dialog * Components for working with a Dialog or MessageBox. */ /** * @docs-group-description ElementSeparator * Components for working with a ElementSeparator. */ /** * @docs-group-description Expandable * Components for working with a ExpandableBlock or ExpandableList. */ /** * @docs-group-description Form * Components used to create a Form using supplied properties to specify fields. */ /** * @docs-group-description Icon * Component that renders core-react icon when given an icon name or SVG source. */ /** * @docs-group-description Inputs * Components for working with input controls, such as Input, IconInput, NumberInput and Textarea. */ /** * @docs-group-description Loading * Components for working with Loading spinners and progress indicators and bars. */ /** * @docs-group-description Notification * Components for working with messages and tooltips. */ /** * @docs-group-description Popup * Components for working with a Popup. */ /** * @docs-group-description RadialMenu * Components for working with a RadialMenu. */ /** * @docs-group-description Radio * Component is a wrapper for the `<input type="radio">` HTML element. */ /** * @docs-group-description SearchBox * Components for working with a SearchBox. */ /** * @docs-group-description Select * Component is a wrapper for the `<select>` HTML element. */ /** * @docs-group-description Settings * Manager and UI Components that allow users to modify settings for different packages and extensions. */ /** * @docs-group-description Slider * Component displays a range slider with thumbs for changing the value. */ /** * @docs-group-description SplitButton * Components for working with a SplitButton. */ /** * @docs-group-description Tabs * Components for working with horizontal or vertical tabs. */ /** * @docs-group-description Text * Components for working with styled text. */ /** * @docs-group-description Tiles * Components for a container rendering elements that can be grouped together. */ /** * @docs-group-description Toggle * Components for working with a Toggle switch. */ /** * @docs-group-description Tooltip * Components for working with a Tooltip. */ /** * @docs-group-description Tree * Presentation React components for working with a Tree. */ /** * @docs-group-description UiSettings * Interfaces and classes for working with persistent UI settings. */ /** * @docs-group-description Utilities * Various utility classes, functions and React hooks for working with a UI. */
the_stack
import { AsyncTest, Expect, FocusTest, IgnoreTest, TestFixture, Timeout, } from "alsatian"; import { PubSub } from "apollo-server-express"; import { EventEmitter } from "events"; import { IGraphqlWsStartMessage, IStoredPubSubSubscription, MapSimpleTable, } from "fanout-graphql-tools"; import * as http from "http"; import * as killable from "killable"; import { AddressInfo } from "net"; import * as url from "url"; import * as WebSocket from "ws"; import { cli, DecorateIf } from "../_test/cli"; import { FanoutGraphqlHttpAtUrlTest, itemsFromLinkObservable, timer, } from "../_test/testFanoutGraphqlAtUrl"; import { FanoutGraphqlSubscriptionQueries, INote, } from "./FanoutGraphqlApolloConfig"; import { apolloServerInfo, FanoutGraphqlExpressServer, } from "./FanoutGraphqlExpressServer"; import WebSocketApolloClient from "./WebSocketApolloClient"; const hostOfAddressInfo = (address: AddressInfo): string => { const host = address.address === "" || address.address === "::" ? "localhost" : address.address; return host; }; const urlOfServerAddress = (address: AddressInfo): string => { return url.format({ hostname: hostOfAddressInfo(address), port: address.port, protocol: "http", }); }; interface IListeningServerInfo { /** url at which the server can be reached */ url: string; /** host of server */ hostname: string; /** port of server */ port: number; } const withListeningServer = ( httpServer: http.Server, port: string | number = 0, ) => async ( doWorkWithServer: (serverInfo: IListeningServerInfo) => Promise<void>, ) => { const { kill } = killable(httpServer); // listen await new Promise((resolve, reject) => { httpServer.on("listening", resolve); httpServer.on("error", error => { reject(error); }); try { httpServer.listen(port); } catch (error) { reject(error); } }); const address = httpServer.address(); if (typeof address === "string" || !address) { throw new Error(`Can't determine URL from address ${address}`); } await doWorkWithServer({ hostname: hostOfAddressInfo(address), port: address.port, url: urlOfServerAddress(address), }); await new Promise((resolve, reject) => { try { kill((error: Error | undefined) => { reject(error); }); } catch (error) { reject(error); } }); return; }; const ChangingValue = <T>(): [ (v: T) => void, () => Promise<T>, () => Promise<T> ] => { let value: T | undefined; let valueIsSet = false; const emitter = new EventEmitter(); const setValue = (valueIn: T) => { value = valueIn; valueIsSet = true; emitter.emit("value", value); }; const getNextValue = async (): Promise<T> => { return new Promise((resolve, reject) => { emitter.on("value", resolve); }); }; const getValue = async (): Promise<T> => { if (valueIsSet) { return value as T; } return getNextValue(); }; return [setValue, getValue, getNextValue]; }; /** Given a base URL and a Path, return a new URL with that path on the baseUrl (existing path on baseUrl is ignored) */ const urlWithPath = (baseUrl: string, pathname: string): string => { const parsedBaseUrl = url.parse(baseUrl); const newUrl = url.format({ ...parsedBaseUrl, pathname }); return newUrl; }; /** Test FanoutGraphqlExpressServer */ @TestFixture() export class FanoutGraphqlExpressServerTestSuite { /** * Test FanoutGraphqlExpressServer with defaults */ @AsyncTest() public async testFanoutGraphqlExpressServer() { const [setLatestSocket, _, socketChangedEvent] = ChangingValue(); const fanoutGraphqlExpressServer = FanoutGraphqlExpressServer({ grip: false, onSubscriptionConnection: setLatestSocket, pubsub: new PubSub(), tables: { connections: MapSimpleTable(), notes: MapSimpleTable<INote>(), pubSubSubscriptions: MapSimpleTable(), }, }); await withListeningServer(fanoutGraphqlExpressServer.httpServer)( async () => { await FanoutGraphqlHttpAtUrlTest( apolloServerInfo( fanoutGraphqlExpressServer.httpServer, fanoutGraphqlExpressServer, ), socketChangedEvent, ); return; }, ); return; } /** * Test FanoutGraphqlExpressServer as requested through pushpin (must be running outside of this test suite). * https://pushpin.org/docs/getting-started/ * Your /etc/pushpin/routes file should be like: * ``` * * localhost:57410,over_http * ``` */ @AsyncTest() @Timeout(1000 * 60 * 10) @DecorateIf( () => !Boolean(process.env.PUSHPIN_PROXY_URL), IgnoreTest("process.env.PUSHPIN_PROXY_URL is not defined"), ) public async testFanoutGraphqlExpressServerThroughPushpin( graphqlPort = 57410, pushpinProxyUrl = process.env.PUSHPIN_PROXY_URL || "http://localhost:7999", pushpinGripUrl = "http://localhost:5561", ) { const [setLatestSocket, _, socketChangedEvent] = ChangingValue(); const fanoutGraphqlExpressServer = FanoutGraphqlExpressServer({ grip: { url: pushpinGripUrl, }, onSubscriptionConnection: setLatestSocket, tables: { connections: MapSimpleTable(), notes: MapSimpleTable<INote>(), pubSubSubscriptions: MapSimpleTable(), }, }); await withListeningServer( fanoutGraphqlExpressServer.httpServer, graphqlPort, )(async () => { await FanoutGraphqlHttpAtUrlTest( { subscriptionsUrl: urlWithPath( pushpinProxyUrl, fanoutGraphqlExpressServer.subscriptionsPath, ), url: urlWithPath( pushpinProxyUrl, fanoutGraphqlExpressServer.graphqlPath, ), }, socketChangedEvent, ); return; }); } /** * Test that the server deletes rows from the subscription table after a subscription cleanly closes. */ @AsyncTest() @Timeout(1000 * 60 * 10) @DecorateIf( () => !Boolean(process.env.PUSHPIN_PROXY_URL), IgnoreTest("process.env.PUSHPIN_PROXY_URL is not defined"), ) public async testFanoutGraphqlExpressServerThroughPushpinDeletesSubscriptionAfterGqlWsStop( graphqlPort = 57410, pushpinProxyUrl = process.env.PUSHPIN_PROXY_URL, pushpinGripUrl = "http://localhost:5561", ) { if ( ! pushpinProxyUrl) { throw new Error(`pushpinProxyUrl is required for this test, but got ${pushpinProxyUrl}`) } const [setLatestSocket, _, socketChangedEvent] = ChangingValue(); const [ setLastSubscriptionStop, , lastSubscriptionStopChange, ] = ChangingValue(); const pubSubSubscriptions = MapSimpleTable<IStoredPubSubSubscription>(); const fanoutGraphqlExpressServer = FanoutGraphqlExpressServer({ grip: { url: pushpinGripUrl, }, onSubscriptionConnection: setLatestSocket, onSubscriptionStop: setLastSubscriptionStop, tables: { connections: MapSimpleTable(), notes: MapSimpleTable<INote>(), pubSubSubscriptions, }, }); await withListeningServer( fanoutGraphqlExpressServer.httpServer, graphqlPort, )(async () => { // We're going to make a new ApolloClient to subscribe with, and assert that starting and stopping subscriptions results in the expected number of rows in subscriptions table. const apolloClient = WebSocketApolloClient({ subscriptionsUrl: urlWithPath( pushpinProxyUrl, fanoutGraphqlExpressServer.subscriptionsPath, ), url: urlWithPath( pushpinProxyUrl, fanoutGraphqlExpressServer.graphqlPath, ), }); // Before any subscriptions, there should be 0 subscriptions stored const storedSubscriptionsBeforeSubscribe = await pubSubSubscriptions.scan(); Expect(storedSubscriptionsBeforeSubscribe.length).toEqual(0); // Subscribe const noteAddedObservable = apolloClient.subscribe( FanoutGraphqlSubscriptionQueries.noteAdded(), ); const { items, subscription } = itemsFromLinkObservable( noteAddedObservable, ); await socketChangedEvent(); // Now that the subscription is established, there should be one stored subscription const storedSubscriptionsOnceSubscribed = await pubSubSubscriptions.scan(); Expect(storedSubscriptionsOnceSubscribed.length).toEqual(1); // Now we'll unsubscribe and then make sure the stored subscription is deleted subscription.unsubscribe(); await lastSubscriptionStopChange(); // There should be no more stored subscriptions const storedSubscriptionsAfterUnsubscribe = await pubSubSubscriptions.scan(); Expect(storedSubscriptionsAfterUnsubscribe.length).toEqual(0); }); } /** Test with a raw WebSocket client and make sure that subscriptions are cleaned up after WebSocket#close() */ @AsyncTest() @DecorateIf( () => !Boolean(process.env.PUSHPIN_PROXY_URL), IgnoreTest("process.env.PUSHPIN_PROXY_URL is not defined"), ) public async testFanoutGraphqlExpressServerThroughPushpinAndTestSubscriptionsDeletedAfterConnectionClose( graphqlPort = 57410, pushpinProxyUrl = process.env.PUSHPIN_PROXY_URL || "http://localhost:7999", pushpinGripUrl = "http://localhost:5561", ) { // const keepAliveIntervalSeconds = 5; const [setLatestSocket, _, subscriptionStartedEvent] = ChangingValue(); const [ setLastSubscriptionStop, , lastSubscriptionStopChange, ] = ChangingValue(); const pubSubSubscriptions = MapSimpleTable<IStoredPubSubSubscription>(); const fanoutGraphqlExpressServer = FanoutGraphqlExpressServer({ grip: { url: pushpinGripUrl, }, onSubscriptionConnection: setLatestSocket, onSubscriptionStop: setLastSubscriptionStop, tables: { connections: MapSimpleTable(), notes: MapSimpleTable<INote>(), pubSubSubscriptions, }, webSocketOverHttp: { keepAliveIntervalSeconds, }, }); await withListeningServer( fanoutGraphqlExpressServer.httpServer, graphqlPort, )(async () => { try { const subscriptionsUrl = urlWithPath( pushpinProxyUrl, fanoutGraphqlExpressServer.subscriptionsPath, ); interface IWebSocketMessageEvent { /** message data */ data: string; } const nextWebSocketMessage = ( socket: WebSocket, ): Promise<IWebSocketMessageEvent> => new Promise((resolve, reject) => { socket.addEventListener("message", event => resolve(event)); }); const ws = new WebSocket(subscriptionsUrl); const opened = new Promise((resolve, reject) => { ws.addEventListener("error", reject); ws.addEventListener("open", resolve); }); await opened; // write graphql-ws so that a subscription gets created // connection_init ws.send(JSON.stringify({ type: "connection_init", payload: {} })); const message = await nextWebSocketMessage(ws); Expect(JSON.parse(message.data).type).toEqual("connection_ack"); const subscriptionStartMessage = ( operationId: string, ): IGraphqlWsStartMessage => { return { id: operationId, payload: { // "extensions": {}, operationName: null, query: ` subscription { noteAdded { content id __typename } } `, variables: {}, }, type: "start", }; }; // send start message up the websocket to create a few subscriptions let nextOperationId = 1; const subscriptionsToCreate = 3; for (const i of Array.from({ length: subscriptionsToCreate })) { ws.send( JSON.stringify(subscriptionStartMessage(String(nextOperationId++))), ); await subscriptionStartedEvent(); } // make sure subscriptions were stored, since we'll assert they are deleted later after connection close const storedSubscriptionsAfterSubscribe = await pubSubSubscriptions.scan(); Expect(storedSubscriptionsAfterSubscribe.length).toEqual( subscriptionsToCreate, ); // now close the websocket ane make sure all the subscriptions got deleted const closed = new Promise((resolve, reject) => { ws.addEventListener("close", resolve); }); ws.close(); await closed; const storedSubscriptionsAfterWebSocketClose = await pubSubSubscriptions.scan(); Expect(storedSubscriptionsAfterWebSocketClose.length).toBe(0); } catch (error) { throw error; } }); } } if (require.main === module) { cli(__filename).catch((error: Error) => { throw error; }); }
the_stack
import { EDBEntity, getRandStr, TAdminCustomField, TBasePageEntity, TImageSettings } from '@cromwell/core'; import { SelectChangeEvent, SelectProps, TextField, TextFieldProps } from '@mui/material'; import React, { useEffect, useRef, useState } from 'react'; import { debounce } from 'throttle-debounce'; import { ColorPicker } from '../components/colorPicker/ColorPicker'; import entityEditStyles from '../components/entity/entityEdit/EntityEdit.module.scss'; import { GalleryPicker, GalleryPickerProps } from '../components/galleryPicker/GalleryPicker'; import { ImagePicker, ImagePickerProps } from '../components/imagePicker/ImagePicker'; import { Select } from '../components/select/Select'; import { getEditorData, getEditorHtml, initTextEditor } from './editor/editor'; import { useForceUpdate } from './forceUpdate'; export type TRegisteredCustomField = TAdminCustomField & { component: (props: { initialValue: string | undefined; entity: TBasePageEntity }) => JSX.Element; saveData: () => string | Promise<string>; } const customFields: Record<EDBEntity | string, Record<string, TRegisteredCustomField>> = {}; const customFieldsForceUpdates: Partial<Record<EDBEntity, (() => void)>> = {}; const onFieldRegisterListeners: Record<string, ((field: TRegisteredCustomField) => any)> = {}; export const registerCustomField = (field: TRegisteredCustomField) => { if (!customFields[field.entityType]) customFields[field.entityType] = {}; customFields[field.entityType][field.key] = field; customFieldsForceUpdates[field.entityType]?.(); Object.values(onFieldRegisterListeners).forEach(listener => listener(field)); } export const unregisterCustomField = (entityType: string, key: string) => { if (customFields[entityType]) { delete customFields[entityType][key]; customFieldsForceUpdates[entityType]?.(); } } export const addOnFieldRegisterEventListener = (id: string, listener: ((field: TRegisteredCustomField) => any)) => { onFieldRegisterListeners[id] = listener; } export const removeOnFieldRegisterEventListener = (id: string) => { delete onFieldRegisterListeners[id]; } export const RenderCustomFields = (props: { entityType: EDBEntity | string; entityData: TBasePageEntity; refetchMeta: () => Promise<Record<string, string> | undefined | null>; }) => { const { entityType, entityData, refetchMeta } = props; const forceUpdate = useForceUpdate(); customFieldsForceUpdates[entityType] = forceUpdate; const [updatedMeta, setUpdatedMeta] = useState<Record<string, string> | null>(null); useEffect(() => { // If some field registered after this page has fetched entity data, we need to // re-request data for this field to get its custom meta const onFieldRegistered = debounce(300, async () => { const newMeta = await refetchMeta(); if (newMeta) setUpdatedMeta(newMeta); }); addOnFieldRegisterEventListener(entityType, onFieldRegistered); return () => { removeOnFieldRegisterEventListener(entityType); delete customFieldsForceUpdates[entityType]; } }, []); // Just update the values that are undefined, but leave the rest // for user input to be untouched const customMeta = Object.assign({}, updatedMeta, entityData?.customMeta); return <>{Object.values(customFields[entityType] ?? {}) .sort((a, b) => (a.order ?? 0) - (b.order ?? 0)) .map(field => { const Comp = field.component; return <Comp key={field.key} initialValue={customMeta?.[field.key]} entity={entityData} /> })}</> } export const getCustomMetaFor = async (entityType: EDBEntity | string): Promise<Record<string, string>> => { return Object.assign({}, ...(await Promise.all(Object.values(customFields[entityType] ?? {}) .map(async field => { return { [field.key]: await field.saveData(), } })))); } export const getCustomMetaKeysFor = (entityType: EDBEntity | string): string[] => { return Object.values(customFields[entityType] ?? {}).map(field => field.key); } export const getCustomFieldsFor = (entityType: EDBEntity | string): TRegisteredCustomField[] => { return Object.values(customFields[entityType] ?? {}); } const useInitialValue = (initialValue: string): [string, React.Dispatch<React.SetStateAction<string>>] => { const [value, setValue] = useState(initialValue); const initialValueRef = useRef(initialValue); if (initialValue !== initialValueRef.current) { initialValueRef.current = initialValue; setValue(initialValue); } return [value, setValue]; } export const registerSimpleTextCustomField = (settings: { entityType: EDBEntity | string; key: string; label?: string; props?: TextFieldProps; }) => { let customFieldValue; registerCustomField({ id: getRandStr(10), fieldType: 'Simple text', ...settings, component: (props) => { const [value, setValue] = useInitialValue(props.initialValue); customFieldValue = value; return <TextField value={value ?? ''} onChange={e => { setValue(e.target.value); }} label={settings.label ?? settings.key} fullWidth variant="standard" style={{ marginBottom: '15px' }} {...(settings.props ?? {})} /> }, saveData: () => (!customFieldValue) ? null : customFieldValue, }); } export const registerTextEditorCustomField = (settings: { entityType: EDBEntity | string; key: string; label?: string; props?: TextFieldProps; }) => { const editorId = 'editor_' + getRandStr(12); registerCustomField({ id: getRandStr(10), fieldType: 'Text editor', ...settings, component: (props) => { const initialValueRef = useRef<null | string>(null); const initEditor = async () => { let data: { html: string; json: string; } | undefined = undefined; if (initialValueRef.current) { try { data = JSON.parse(initialValueRef.current); } catch (error) { console.error(error); } } await initTextEditor({ htmlId: editorId, data: data?.json, placeholder: settings.label, }); } useEffect(() => { if (props.initialValue !== initialValueRef.current) { initialValueRef.current = props.initialValue; initEditor(); } }); return ( <div style={{ margin: '15px 0' }} className={entityEditStyles.descriptionEditor}> <div style={{ height: '350px' }} id={editorId}></div> </div> ) }, saveData: async () => { const json = await getEditorData(editorId); if (!json?.blocks?.length) return null; const html = await getEditorHtml(editorId); return JSON.stringify({ html, json, }); }, }); } export const registerSelectCustomField = (settings: { entityType: EDBEntity | string; key: string; label?: string; options?: string[]; props?: SelectProps<string>; }) => { let customFieldValue; registerCustomField({ id: getRandStr(10), fieldType: 'Select', ...settings, component: (props) => { const [value, setValue] = useInitialValue(props.initialValue); customFieldValue = value; return ( <Select style={{ margin: '15px 0' }} label={settings.label} value={value} onChange={(event: SelectChangeEvent<string>) => { setValue(event.target.value); }} size="small" variant="standard" fullWidth options={settings.options?.map(opt => ({ label: opt, value: opt }))} {...(settings.props ?? {})} /> ) }, saveData: () => (!customFieldValue) ? null : customFieldValue, }); } export const registerImageCustomField = (settings: { entityType: EDBEntity | string; key: string; label?: string; props?: ImagePickerProps; }) => { let customFieldValue; registerCustomField({ id: getRandStr(10), fieldType: 'Image', ...settings, component: (props) => { const [value, setValue] = useInitialValue(props.initialValue); customFieldValue = value; return ( <ImagePicker value={value} onChange={(value) => { setValue(value); }} showRemove label={settings.label} style={{ margin: '15px 0' }} variant="standard" {...(settings.props ?? {})} /> ) }, saveData: () => (!customFieldValue) ? null : customFieldValue, }); } export const registerGalleryCustomField = (settings: { entityType: EDBEntity | string; key: string; label?: string; props?: GalleryPickerProps; }) => { let customFieldValue: string; registerCustomField({ id: getRandStr(10), fieldType: 'Gallery', ...settings, component: (props) => { const [value, setValue] = useInitialValue(props.initialValue); customFieldValue = value; return ( <GalleryPicker images={value?.split(',').map(src => ({ src })) ?? []} onChange={(value: TImageSettings[]) => { const valStr = value.map(val => val.src).join(','); setValue(valStr); }} label={settings.label} style={{ margin: '15px 0', border: '1px solid #ccc', borderRadius: '6px', padding: '10px' }} {...(settings.props ?? {})} /> ) }, saveData: () => (!customFieldValue) ? null : customFieldValue, }); } export const registerColorCustomField = (settings: { entityType: EDBEntity | string; key: string; label?: string; props?: ImagePickerProps; }) => { let customFieldValue; registerCustomField({ id: getRandStr(10), fieldType: 'Color', ...settings, component: (props) => { const [value, setValue] = useInitialValue(props.initialValue); customFieldValue = value; return ( <ColorPicker value={value} label={settings.label} onChange={(value) => { setValue(value); }} style={{ margin: '15px 0' }} {...(settings.props ?? {})} /> ) }, saveData: () => (!customFieldValue) ? null : customFieldValue, }); } export const registerCustomFieldOfType = (field: TAdminCustomField) => { if (field.fieldType === 'Simple text') { registerSimpleTextCustomField(field); } if (field.fieldType === 'Text editor') { registerTextEditorCustomField(field); } if (field.fieldType === 'Select') { registerSelectCustomField(field); } if (field.fieldType === 'Image') { registerImageCustomField(field); } if (field.fieldType === 'Gallery') { registerGalleryCustomField(field); } if (field.fieldType === 'Color') { registerColorCustomField(field); } }
the_stack
import { toTypedArray } from "./helpers"; import Shape from "./Shape"; /** * Something which consumes outputs generated by the Rune. */ export interface Output { consume(data: Uint8Array): void; } /** * Inputs provided by the application. */ export interface Capability { generate(dest: Uint8Array): void; setParameter(name: string, value: number): void; } /** * Functions required by the Rune runtime. */ export interface Imports { createOutput(type: number): Output; createCapability(type: number): Capability; createModel(mimetype: string, model: ArrayBuffer): Promise<Model>; log(message: string | StructuredLogMessage): void; } /** * Something which can run inference on a model. */ export interface Model { transform( inputArray: Uint8Array[], inputDimensions: Shape[], outputArray: Uint8Array[], outputDimensions: Shape[], ): void; } type TensorDescriptor = { dimensions: string, }; type ModelInfo = { id: number, modelSize: number, inputs?: TensorDescriptor[], outputs?: TensorDescriptor[], }; /** * Public interface exposed by the WebAssembly module. */ interface Exports extends WebAssembly.Exports { memory: WebAssembly.Memory; _manifest(): void; _call(capability_type: number, input_type: number, capability_index: number): void; } export class Runtime { instance: WebAssembly.Instance; constructor(instance: WebAssembly.Instance) { this.instance = instance; } static async load(wasm: ArrayBuffer, imports: Imports) { let memory: WebAssembly.Memory; const { hostFunctions, finaliseModels } = importsToHostFunctions( imports, () => memory, ); const { instance } = await WebAssembly.instantiate(wasm, hostFunctions); const exports = instance.exports; if (!isRuneExports(exports)) { throw new Error("Invalid Rune exports"); } memory = exports.memory; exports._manifest(); // now we've asked for all the models to be loaded, let's wait until // they are done before continuing await finaliseModels(); return new Runtime(instance); } manifest() { return this.exports._manifest(); } call() { this.exports._call(0, 0, 0); } get exports() { // Note: checked inside Runtime.load() and exports will never change. const { exports } = this.instance; if (isRuneExports(exports)) { return exports; } else { throw Error(); } } } type Dict<Key extends keyof any, Value> = Partial<Record<Key, Value>>; /** * Generate a bunch of host functions backed by the supplied @param imports. */ function importsToHostFunctions( imports: Imports, getMemory: () => WebAssembly.Memory, ) { const memory = () => { const m = getMemory(); if (!m) throw new Error("WebAssembly memory wasn't initialized"); return new Uint8Array(m.buffer); }; const ids = counter(); const outputs: Dict<number, Output> = {}; const capabilities: Dict<number, Capability> = {}; const pendingModels: Promise<[number, Model]>[] = []; const models: Record<number, Model> = {}; const modelsDescription: Record<number, ModelInfo> = {}; const utf8 = new TextDecoder(); const decoder = new TextDecoder("utf8"); // Annoyingly, this needs to be an object literal instead of a class. const env = { _debug(msg: number, len: number) { const raw = memory().subarray(msg, msg + len); const decoded = utf8.decode(raw); const parsed = tryParseJSON(decoded); function tryParseJSON(input: string): any | undefined { try { return JSON.parse(input); } catch { return; } } if (isStructuredLogMessage(parsed)) { imports.log(parsed); if (parsed.level == "ERROR") { // Translate all errors inside the Rune into exceptions, // aborting execution. throw new Error(parsed.message); } } else { imports.log(decoded); } }, request_output(type: number) { const output = imports.createOutput(type); const id = ids(); outputs[id] = output; return id; }, consume_output(id: number, buffer: number, len: number) { const output = outputs[id]; if (output) { const data = memory().subarray(buffer, buffer + len); output.consume(data); } else { throw new Error("Invalid output"); } }, request_capability(type: number) { const capability = imports.createCapability(type); const id = ids(); capabilities[id] = capability; return id; }, request_capability_set_param(id: number, keyPtr: number, keyLength: number, valuePtr: number, valueLength: number, valueType: number) { const keyBytes = memory().subarray(keyPtr, keyPtr + keyLength); const key = decoder.decode(keyBytes); const bytes = memory().subarray(valuePtr, valuePtr + valueLength).slice(0); const value = decodeValue(valueType, bytes); const capability = capabilities[id]; if (!capability) { throw new Error(`Tried to set "${key}" to ${value} but capability ${id} doesn't exist`); } capability.setParameter(key, value); }, request_provider_response(buffer: number, len: number, id: number) { const cap = capabilities[id]; if (!cap) { throw new Error("Invalid capability"); } const dest = memory().subarray(buffer, buffer + len); cap.generate(dest); }, rune_model_load(mimetype: number, mimetype_len: number, model: number, model_len: number, input_descriptors: number, input_len: number, output_descriptors: number, output_len: number) { const mime = decoder.decode(memory().subarray(mimetype, mimetype + mimetype_len)); const model_data = memory().subarray(model, model + model_len); //inputs let o = memory().subarray(input_descriptors, input_descriptors + 8 * input_len); let inputs = []; for (let i = 0; i < input_len; i++) { const inputs_pointer = new Uint32Array(new Uint8Array([o[i * 8], o[i * 8 + 1], o[i * 8 + 2], o[i * 8 + 3]]).buffer)[0]; const inputs_length = new Uint32Array(new Uint8Array([o[i * 8 + 4], o[i * 8 + 5], o[i * 8 + 6], o[i * 8 + 7]]).buffer)[0]; const inputs_string = decoder.decode(memory().subarray(inputs_pointer, inputs_pointer + inputs_length)); inputs.push({ "dimensions": inputs_string }); } //outputs o = memory().subarray(output_descriptors, output_descriptors + 8 * output_len); let outputs = []; for (let i = 0; i < output_len; i++) { const outputs_pointer = new Uint32Array(new Uint8Array([o[i * 8], o[i * 8 + 1], o[i * 8 + 2], o[i * 8 + 3]]).buffer)[0]; const outputs_length = new Uint32Array(new Uint8Array([o[i * 8 + 4], o[i * 8 + 5], o[i * 8 + 6], o[i * 8 + 7]]).buffer)[0]; const outputs_string = decoder.decode(memory().subarray(outputs_pointer, outputs_pointer + outputs_length)); outputs.push({ "dimensions": outputs_string }); } const pending = imports.createModel(mime, model_data); const id = ids(); pendingModels.push(pending.then(model => [id, model])); modelsDescription[id] = { id, inputs, outputs, "modelSize": model_len }; return id; }, async rune_model_infer(id: number, inputs: number, outputs: number) { const model = models[id]; let modelsDes = modelsDescription[id]; let inputArray = []; let inputDimensions = []; for (let i = 0; i < modelsDes!.inputs!.length; i++) { let dimensions = Shape.parse(modelsDes!.inputs![i].dimensions); let o = memory().subarray(inputs + i * 4, inputs + 4 + i * 4); const pointer = new Uint32Array(new Uint8Array([o[0], o[1], o[2], o[3]]).buffer)[0]; inputArray.push(memory().subarray(pointer, pointer + dimensions.byteSize)); inputDimensions.push(dimensions); } let outputArray = []; let outputDimensions = []; for (let i = 0; i < modelsDes!.outputs!.length; i++) { let dimensions = Shape.parse(modelsDes!.outputs![i].dimensions); let o = memory().subarray(outputs + i * 4, outputs + 4 + i * 4); const pointer = new Uint32Array(new Uint8Array([o[0], o[1], o[2], o[3]]).buffer)[0]; outputArray.push(memory().subarray(pointer, pointer + dimensions.byteSize)); outputDimensions.push(dimensions); } model.transform(inputArray, inputDimensions, outputArray, outputDimensions); return id; }, tfm_model_invoke(id: number, inputPtr: number, inputLen: number, outputPtr: number, outputLen: number) { deprecated("tfm_model_invoke()", "0.5"); }, tfm_preload_model(data: number, len: number, numInputs: number, numOutputs: number) { deprecated("tfm_preload_model()", "0.5"); }, }; async function synchroniseModelLoading() { const loadedModels = await Promise.all(pendingModels); pendingModels.length = 0; loadedModels.forEach(([id, model]) => { models[id] = model; }); } return { hostFunctions: { env }, finaliseModels: synchroniseModelLoading, }; } function counter() { let value = 0; return () => { value++; return value - 1; }; } function isRuneExports(obj: any): obj is Exports { return (obj && obj.memory instanceof WebAssembly.Memory && obj._call instanceof Function && obj._manifest instanceof Function); } export function isStructuredLogMessage(obj?: any): obj is StructuredLogMessage { return obj && typeof obj.level == 'string' && typeof obj.message == 'string' && typeof obj.target == 'string' && typeof obj.module_path == 'string' && typeof obj.file == 'string' && typeof obj.line == 'number'; } export type StructuredLogMessage = { level: string, message: string, target: string, module_path: string, file: string, line: number, }; interface TypedArray extends ArrayBuffer { readonly buffer: ArrayBuffer; } //this function can convert any TypedArray to any other kind of TypedArray : function convertTypedArray<T>(src: TypedArray, constructor: any): T { // Instantiate a buffer (zeroed out) and copy the bytes from "src" into it. const buffer = new constructor(src.byteLength); buffer.set(src.buffer); return buffer[0] as T; } function deprecated(feature: string, version: string) { throw new Error(`This runtime no longer supports Runes using "${feature}". Please rebuild with Rune ${version}`); } function decodeValue(valueType: number, bytes: Uint8Array): number { switch (valueType) { case 1: const i32s = toTypedArray("i32", bytes); return i32s[0]; case 2: const f32s = toTypedArray("f32", bytes); return f32s[0]; case 5: return bytes[0]; case 6: const i16s = toTypedArray("i16", bytes); return i16s[0]; case 7: const i8s = toTypedArray("i8", bytes); return i8s[0]; default: throw new Error(`Unknown value type, ${valueType}, with binary representation, ${bytes}`); } }
the_stack
import BN from 'bn.js'; import BigNumber from 'bignumber.js'; import { PromiEvent, TransactionReceipt, EventResponse, EventData, Web3ContractContext, } from 'ethereum-abi-types-generator'; export interface CallOptions { from?: string; gasPrice?: string; gas?: number; } export interface SendOptions { from: string; value?: number | string | BN | BigNumber; gasPrice?: string; gas?: number; } export interface EstimateGasOptions { from?: string; value?: number | string | BN | BigNumber; gas?: number; } export interface MethodPayableReturnContext { send(options: SendOptions): PromiEvent<TransactionReceipt>; send( options: SendOptions, callback: (error: Error, result: any) => void ): PromiEvent<TransactionReceipt>; estimateGas(options: EstimateGasOptions): Promise<number>; estimateGas( options: EstimateGasOptions, callback: (error: Error, result: any) => void ): Promise<number>; encodeABI(): string; } export interface MethodConstantReturnContext<TCallReturn> { call(): Promise<TCallReturn>; call(options: CallOptions): Promise<TCallReturn>; call( options: CallOptions, callback: (error: Error, result: TCallReturn) => void ): Promise<TCallReturn>; encodeABI(): string; } export interface MethodReturnContext extends MethodPayableReturnContext {} export type ContractContext = Web3ContractContext< StakingMultiRewards, StakingMultiRewardsMethodNames, StakingMultiRewardsEventsContext, StakingMultiRewardsEvents >; export type StakingMultiRewardsEvents = | 'OwnerChanged' | 'OwnerNominated' | 'PauseChanged' | 'Recovered' | 'RewardAdded' | 'RewardPaid' | 'RewardsDurationUpdated' | 'Staked' | 'Withdrawn'; export interface StakingMultiRewardsEventsContext { OwnerChanged( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; OwnerNominated( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; PauseChanged( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Recovered( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RewardAdded( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RewardPaid( parameters: { filter?: { user?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RewardsDurationUpdated( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Staked( parameters: { filter?: { user?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Withdrawn( parameters: { filter?: { user?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; } export type StakingMultiRewardsMethodNames = | 'new' | 'acceptOwnership' | 'balanceOf' | 'dualRewardsDistribution' | 'earnedA' | 'earnedB' | 'exit' | 'getReward' | 'getRewardAForDuration' | 'getRewardBForDuration' | 'lastPauseTime' | 'lastTimeRewardApplicable' | 'lastUpdateTime' | 'nominateNewOwner' | 'nominatedOwner' | 'notifyRewardAmount' | 'owner' | 'paused' | 'periodFinish' | 'recoverERC20' | 'rewardPerTokenA' | 'rewardPerTokenAStored' | 'rewardPerTokenB' | 'rewardPerTokenBStored' | 'rewardRateA' | 'rewardRateB' | 'rewardsA' | 'rewardsB' | 'rewardsDuration' | 'rewardsTokenA' | 'rewardsTokenB' | 'setDualRewardsDistribution' | 'setPaused' | 'setRewardsDuration' | 'stake' | 'stakingToken' | 'totalSupply' | 'updatePeriodFinish' | 'userRewardPerTokenAPaid' | 'userRewardPerTokenBPaid' | 'withdraw'; export interface StakingMultiRewards { /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: constructor * @param _owner Type: address, Indexed: false * @param _dualRewardsDistribution Type: address, Indexed: false * @param _rewardsTokenA Type: address, Indexed: false * @param _rewardsTokenB Type: address, Indexed: false * @param _stakingToken Type: address, Indexed: false */ 'new'( _owner: string, _dualRewardsDistribution: string, _rewardsTokenA: string, _rewardsTokenB: string, _stakingToken: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ acceptOwnership(): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param account Type: address, Indexed: false */ balanceOf(account: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ dualRewardsDistribution(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param account Type: address, Indexed: false */ earnedA(account: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param account Type: address, Indexed: false */ earnedB(account: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ exit(): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ getReward(): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ getRewardAForDuration(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ getRewardBForDuration(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ lastPauseTime(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ lastTimeRewardApplicable(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ lastUpdateTime(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _owner Type: address, Indexed: false */ nominateNewOwner(_owner: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ nominatedOwner(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param rewardA Type: uint256, Indexed: false * @param rewardB Type: uint256, Indexed: false */ notifyRewardAmount(rewardA: string, rewardB: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ owner(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ paused(): MethodConstantReturnContext<boolean>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ periodFinish(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param tokenAddress Type: address, Indexed: false * @param tokenAmount Type: uint256, Indexed: false */ recoverERC20(tokenAddress: string, tokenAmount: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardPerTokenA(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardPerTokenAStored(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardPerTokenB(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardPerTokenBStored(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardRateA(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardRateB(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: address, Indexed: false */ rewardsA(parameter0: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: address, Indexed: false */ rewardsB(parameter0: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardsDuration(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardsTokenA(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardsTokenB(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _dualRewardsDistribution Type: address, Indexed: false */ setDualRewardsDistribution(_dualRewardsDistribution: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _paused Type: bool, Indexed: false */ setPaused(_paused: boolean): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _rewardsDuration Type: uint256, Indexed: false */ setRewardsDuration(_rewardsDuration: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param amount Type: uint256, Indexed: false */ stake(amount: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ stakingToken(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ totalSupply(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param timestamp Type: uint256, Indexed: false */ updatePeriodFinish(timestamp: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: address, Indexed: false */ userRewardPerTokenAPaid(parameter0: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: address, Indexed: false */ userRewardPerTokenBPaid(parameter0: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param amount Type: uint256, Indexed: false */ withdraw(amount: string): MethodReturnContext; }
the_stack
import BigNumber from 'bignumber.js'; import _ from 'lodash'; import { mineAvgBlock } from './helpers/EVM'; import initializePerpetual from './helpers/initializePerpetual'; import { expectBalances, mintAndDeposit, expectPositions } from './helpers/balances'; import { ITestContext, perpetualDescribe } from './helpers/perpetualDescribe'; import { buy, sell } from './helpers/trade'; import { expect, expectBN, expectBaseValueEqual, expectThrow } from './helpers/Expect'; import { FEES, INTEGERS, PRICES } from '../src/lib/Constants'; import { BaseValue, BigNumberable, Order, Price, SigningMethod, address, } from '../src/lib/types'; const initialPrice = new Price(100); const longBorderlinePrice = new Price(55); const longUndercollateralizedPrice = new Price('54.999999'); const longUnderwaterPrice = new Price('49.999999'); const shortBorderlinePrice = new Price('136.363636'); const shortUndercollateralizedPrice = new Price('136.363637'); const shortUnderwaterPrice = new Price('150.000001'); const positionSize = new BigNumber(10); let admin: address; let long: address; let short: address; let thirdParty: address; let globalOperator: address; async function init(ctx: ITestContext): Promise<void> { await initializePerpetual(ctx); admin = ctx.accounts[0]; long = ctx.accounts[1]; short = ctx.accounts[2]; thirdParty = ctx.accounts[3]; globalOperator = ctx.accounts[4]; // Set up initial balances: // +---------+--------+----------+-------------------+ // | account | margin | position | collateralization | // |---------+--------+----------+-------------------| // | long | -500 | 10 | 200% | // | short | 1500 | -10 | 150% | // +---------+--------+----------+-------------------+ await Promise.all([ ctx.perpetual.testing.oracle.setPrice(initialPrice), ctx.perpetual.admin.setGlobalOperator(globalOperator, true, { from: admin }), mintAndDeposit(ctx, long, new BigNumber(500)), mintAndDeposit(ctx, short, new BigNumber(500)), ]); await buy(ctx, long, short, positionSize, new BigNumber(1000)); } perpetualDescribe('P1Liquidation', init, (ctx: ITestContext) => { describe('trade()', () => { it('Fails if the caller is not the perpetual contract', async () => { await expectThrow( ctx.perpetual.liquidation.trade( long, short, long, shortUndercollateralizedPrice, positionSize, false, ), 'msg.sender must be PerpetualV1', ); }); }); describe('trade(), via PerpetualV1', () => { it('Succeeds partially liquidating a long position', async () => { await ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice); const liquidationAmount = positionSize.div(2); const txResult = await liquidate(long, short, liquidationAmount); await expectBalances( ctx, txResult, [long, short], [new BigNumber(-250), new BigNumber(1250)], [new BigNumber(5), new BigNumber(-5)], ); // Check logs. const logs = ctx.perpetual.logs.parseLogs(txResult); const filteredLogs = _.filter(logs, { name: 'LogLiquidated' }); expect(filteredLogs.length).to.equal(1); const liquidatedLog = filteredLogs[0]; expect(liquidatedLog.args.maker).to.equal(long); expect(liquidatedLog.args.taker).to.equal(short); expectBN(liquidatedLog.args.amount).to.equal(liquidationAmount); expect(liquidatedLog.args.isBuy).to.equal(true); expectBaseValueEqual(liquidatedLog.args.oraclePrice, longUndercollateralizedPrice); }); it('Succeeds partially liquidating a short position', async () => { await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice); const liquidationAmount = positionSize.div(2); const txResult = await liquidate(short, long, liquidationAmount); await expectBalances( ctx, txResult, [long, short], [new BigNumber(250), new BigNumber(750)], [new BigNumber(5), new BigNumber(-5)], ); // Check logs. const logs = ctx.perpetual.logs.parseLogs(txResult); const filteredLogs = _.filter(logs, { name: 'LogLiquidated' }); expect(filteredLogs.length).to.equal(1); const liquidatedLog = filteredLogs[0]; expect(liquidatedLog.args.maker).to.equal(short); expect(liquidatedLog.args.taker).to.equal(long); expectBN(liquidatedLog.args.amount).to.equal(liquidationAmount); expect(liquidatedLog.args.isBuy).to.equal(false); expectBaseValueEqual(liquidatedLog.args.oraclePrice, shortUndercollateralizedPrice); }); it('Succeeds fully liquidating an undercollateralized long position', async () => { await ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice); const txResult = await liquidate(long, short, positionSize); await expectBalances( ctx, txResult, [long, short], [new BigNumber(0), new BigNumber(1000)], [new BigNumber(0), new BigNumber(0)], ); }); it('Succeeds fully liquidating an undercollateralized short position', async () => { await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice); const txResult = await liquidate(short, long, positionSize); await expectBalances( ctx, txResult, [long, short], [new BigNumber(1000), new BigNumber(0)], [new BigNumber(0), new BigNumber(0)], ); }); it('Succeeds fully liquidating an underwater long position', async () => { await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice); const txResult = await liquidate(long, short, positionSize); await expectBalances( ctx, txResult, [long, short], [new BigNumber(0), new BigNumber(1000)], [new BigNumber(0), new BigNumber(0)], ); }); it('Succeeds fully liquidating an underwater short position', async () => { await ctx.perpetual.testing.oracle.setPrice(shortUnderwaterPrice); const txResult = await liquidate(short, long, positionSize); await expectBalances( ctx, txResult, [long, short], [new BigNumber(1000), new BigNumber(0)], [new BigNumber(0), new BigNumber(0)], ); }); it('Succeeds with all-or-nothing', async () => { await ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice); const txResult = await liquidate(long, short, positionSize, { allOrNothing: true }); await expectBalances( ctx, txResult, [long, short], [new BigNumber(0), new BigNumber(1000)], [new BigNumber(0), new BigNumber(0)], ); }); it('Succeeds when the amount is zero and the maker is long', async () => { await ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice); const txResult = await liquidate(long, short, 0); await expectBalances( ctx, txResult, [long, short], [new BigNumber(-500), new BigNumber(1500)], [new BigNumber(10), new BigNumber(-10)], ); }); it('Succeeds when the amount is zero and the maker is short', async () => { await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice); const txResult = await liquidate(short, long, 0); await expectBalances( ctx, txResult, [long, short], [new BigNumber(-500), new BigNumber(1500)], [new BigNumber(10), new BigNumber(-10)], ); }); it('Succeeds even if amount is greater than the maker position', async () => { // Cover some of the short position. await mintAndDeposit(ctx, thirdParty, new BigNumber(10000)); await buy(ctx, short, thirdParty, new BigNumber(1), new BigNumber(150)); // New balances: // | account | margin | position | // |---------+--------+----------| // | long | -500 | 10 | // | short | 1350 | -9 | // Liquidate the short position. await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice); const txResult = await liquidate(short, long, positionSize); // The actual amount executed should be bounded by the maker position. await expectBalances( ctx, txResult, [long, short, thirdParty], [new BigNumber(850), new BigNumber(0), new BigNumber(10150)], [new BigNumber(1), new BigNumber(0), new BigNumber(-1)], ); }); it('Succeeds even if amount is greater than the taker position', async () => { // Sell off some of the long position. await mintAndDeposit(ctx, thirdParty, new BigNumber(10000)); await sell(ctx, long, thirdParty, new BigNumber(1), new BigNumber(150)); // New balances: // | account | margin | position | // |---------+--------+----------| // | long | -350 | 9 | // | short | 1500 | -10 | // Liquidate the short position. await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice); const txResult = await liquidate(short, long, positionSize); // Liquidiation amount should NOT be bounded by the taker position. await expectBalances( ctx, txResult, [long, short, thirdParty], [new BigNumber(1150), new BigNumber(0), new BigNumber(9850)], [new BigNumber(-1), new BigNumber(0), new BigNumber(1)], ); }); it('Cannot liquidate a long position that is not undercollateralized', async () => { await ctx.perpetual.testing.oracle.setPrice(longBorderlinePrice); await expectThrow( liquidate(long, short, positionSize), 'Cannot liquidate since maker is not undercollateralized', ); }); it('Cannot liquidate a short position that is not undercollateralized', async () => { await ctx.perpetual.testing.oracle.setPrice(shortBorderlinePrice); await expectThrow( liquidate(short, long, positionSize), 'Cannot liquidate since maker is not undercollateralized', ); }); it('Cannot liquidate a long position if isBuy is false', async () => { await ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice); await expectThrow( liquidate(long, short, positionSize, { isBuy: false }), 'liquidation must not increase maker\'s position size', ); }); it('Cannot liquidate a short position if isBuy is true', async () => { await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice); await expectThrow( liquidate(short, long, positionSize, { isBuy: true }), 'liquidation must not increase maker\'s position size', ); }); it('With all-or-nothing, fails if amount is greater than the maker position', async () => { // Attempt to liquidate the short position. await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice); await expectThrow( liquidate(short, long, positionSize.plus(1), { allOrNothing: true }), 'allOrNothing is set and maker position is less than amount', ); }); it('With all-or-nothing, succeeds even if amount is greater than taker position', async () => { // Sell off some of the long position. await mintAndDeposit(ctx, thirdParty, new BigNumber(10000)); await sell(ctx, long, thirdParty, 1, 150); // Liquidate the short position. await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice); await liquidate(short, long, positionSize, { allOrNothing: true }); }); it('Succeeds liquidating a long against a long', async () => { // Turn the short into a long. await mintAndDeposit(ctx, thirdParty, new BigNumber(10000)); const txResult = await buy(ctx, short, thirdParty, positionSize.times(2), new BigNumber(500)); // Sanity check. await expectPositions( ctx, txResult, [long, short], [positionSize, positionSize], false, // positionsSumToZero ); await ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice); await liquidate(long, short, positionSize); }); it('Succeeds liquidating a short against a short', async () => { // Turn the long into a short. await mintAndDeposit(ctx, thirdParty, new BigNumber(10000)); const txResult = await sell(ctx, long, thirdParty, positionSize.times(2), 2500); // Sanity check. await expectPositions( ctx, txResult, [long, short], [positionSize.negated(), positionSize.negated()], false, // positionsSumToZero ); await ctx.perpetual.testing.oracle.setPrice(shortUndercollateralizedPrice); await liquidate(short, long, positionSize); }); it('Succeeds liquidating after an order has executed in the same tx', async () => { await Promise.all([ ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice), ctx.perpetual.admin.setGlobalOperator(short, true, { from: admin }), ]); const defaultOrder: Order = { isBuy: true, isDecreaseOnly: false, amount: new BigNumber(1), limitPrice: initialPrice, triggerPrice: PRICES.NONE, limitFee: FEES.ZERO, maker: long, taker: short, expiration: INTEGERS.ZERO, salt: new BigNumber(444), }; const defaultSignedOrder = await ctx.perpetual.orders.getSignedOrder( defaultOrder, SigningMethod.Hash, ); // Fill the order and then liquidate the entire short position. await ctx.perpetual.trade.initiate() .fillSignedOrder( defaultSignedOrder, defaultSignedOrder.amount, defaultSignedOrder.limitPrice, defaultSignedOrder.limitFee, ) .liquidate(long, short, positionSize.plus(new BigNumber(1)), true, false) .commit({ from: short }); }); it('Cannot liquidate if the sender is not a global operator', async () => { await ctx.perpetual.testing.oracle.setPrice(longUndercollateralizedPrice); const error = 'Sender is not a global operator'; await expectThrow( liquidate(long, short, positionSize, { sender: thirdParty }), error, ); await expectThrow( liquidate(long, short, positionSize, { sender: admin }), error, ); }); describe('when an account has no positive value', async () => { beforeEach(async () => { // Short begins with -10 position, 1500 margin. // Set a negative funding rate and accumulate 2000 margin worth of interest. await ctx.perpetual.testing.funder.setFunding(new BaseValue(-2)); await mineAvgBlock(); await ctx.perpetual.margin.deposit(short, 0); const balance = await ctx.perpetual.getters.getAccountBalance(short); expectBN(balance.position).to.equal(-10); expectBN(balance.margin).to.equal(-500); }); it('Cannot directly liquidate the account', async () => { await expectThrow( liquidate(short, long, positionSize), 'Cannot liquidate when maker position and margin are both negative', ); }); it('Succeeds liquidating after bringing margin up to zero', async () => { // Avoid additional funding. await ctx.perpetual.testing.funder.setFunding(new BaseValue(0)); // Deposit margin into the target account to bring it to zero margin. await ctx.perpetual.margin.withdraw(long, long, 500, { from: long }); await ctx.perpetual.margin.deposit(short, 500, { from: long }); // Liquidate the underwater account. const txResult = await liquidate(short, long, positionSize); // Check balances. await expectBalances( ctx, txResult, [long, short], [new BigNumber(1000), new BigNumber(0)], [new BigNumber(0), new BigNumber(0)], ); }); }); }); async function liquidate( maker: address, taker: address, amount: BigNumberable, args: { allOrNothing?: boolean, isBuy?: boolean, sender?: address, } = {}, ) { let { isBuy } = args; if (typeof isBuy !== 'boolean') { // By default, infer isBuy from the sign of the maker position. isBuy = (await ctx.perpetual.getters.getAccountBalance(maker)).position.isPositive(); } return ctx.perpetual.trade .initiate() .liquidate(maker, taker, amount, isBuy, !!args.allOrNothing) .commit({ from: args.sender || globalOperator }); } });
the_stack
import { find } from 'lodash'; import { post } from 'request'; import * as extend from 'extend'; import * as WebSocket from 'ws'; import { EventEmitter } from 'eventemitter3'; import { setWsHeartbeat } from 'ws-heartbeat/client'; export class SlackBot extends EventEmitter { token: any; name: any; disconnect: any; wsUrl: any; self: any; team: any; channels: any; users: any; ims: any; groups: any; ws: any; /** * @param {object} params * @constructor */ constructor(params: any) { super(); this.token = params.token; this.name = params.name; this.disconnect = params.disconnect; console.assert(params.token, 'token must be defined'); if (!this.disconnect) { this.login(); } } /** * Starts a Real Time Messaging API session */ login() { this.api('rtm.start') .then((data: any) => { this.wsUrl = data.url; this.self = data.self; this.team = data.team; this.channels = data.channels; this.users = data.users; this.ims = data.ims; this.groups = data.groups; this.emit('start'); this.connect(); }) Promise.reject((data: any) => { this.emit('error', new Error(data.error ? data.error : data)); }) Promise.resolve(); } /** * Establish a WebSocket connection */ connect() { this.ws = new WebSocket(this.wsUrl); setWsHeartbeat(this.ws, '{ "kind": "ping" }'); this.ws.on('open', (data: any) => { this.emit('open', data); }); this.ws.on('close', (data: any) => { this.emit('close', data); }); this.ws.on('message', (data: any) => { try { this.emit('message', JSON.parse(data)); } catch (e) { console.log(e); } }); } /** * Get channels * @returns Promise */ getChannels() { if (this.channels) { return Promise.resolve({ channels: this.channels }); } return this.api('channels.list'); } /** * Get users */ getUsers() { if (this.users) { return Promise.resolve({ members: this.users }); } return this.api('users.list'); } /** * Get groups */ getGroups() { if (this.groups) { return Promise.resolve({ groups: this.groups }); } return this.api('groups.list'); } /** * Get user by name * @param name * @returns */ getUser(name: string) { return this.getUsers().then((data: any) => { var res = find(data.members, { name: name }); console.assert(res, 'user not found'); return res; }); } /** * Get channel by name * @param name * @returns {object} */ getChannel(name: string) { return this.getChannels().then((data: any) => { var res = find(data.channels, { name: name }); console.assert(res, 'channel not found'); return res; }); } /** * Get group by name * @param name * @returns {object} */ getGroup(name: string) { return this.getGroups().then((data: any) => { var res = find(data.groups, { name: name }); console.assert(res, 'group not found'); return res; }); } /** * Get user by id * @param id * @returns {object} */ getUserById(id: string) { return this.getUsers().then((data: any) => { var res = find(data.members, { id: id }); console.assert(res, 'user not found'); return res; }); } /** * Get channel by id * @param id * @returns {object} */ getChannelById(id: string) { return this.getChannels().then((data: any) => { var res = find(data.channels, { id: id }); console.assert(res, 'channel not found'); return res; }); } /** * Get group by id * @param id * @returns {object} */ getGroupById(id: string) { return this.getGroups().then((data: any) => { var res = find(data.groups, { id: id }); console.assert(res, 'group not found'); return res; }); } /** * Get channel ID * @param name * @returns */ getChannelId(name: string) { return this.getChannel(name).then((channel: any) => { return channel.id; }); } /** * Get group ID * @param name * @returns */ getGroupId(name: string): Promise<any> { return this.getGroup(name).then((group: any) => { return group.id; }); } /** * Get user ID * @param name * @returns */ getUserId(name: string) { return this.getUser(name).then((user: any) => { return user.id; }); } /** * Get user by email * @param email * @returns {object} */ getUserByEmail(email: string) { return this.getUsers().then((data: any) => { return find(data.members, { profile: { email: email } }); }); } /** * Get "direct message" channel ID * @param name * @returns {vow.Promise} */ getChatId(name: string): any { return this.getUser(name) .then((data: any) => { var chatId = find(this.ims, { user: data.id }); return (chatId && chatId.id) || this.openIm(data.id); }) .then((data: any) => { return typeof data === 'string' ? data : data.channel.id; }); } /** * Opens a "direct message" channel with another member of your Slack team * @param userId * @returns {vow.Promise} */ openIm(userId: string) { return this.api('im.open', { user: userId }); } /** * Get a list of all im channels * @returns {vow.Promise} */ getImChannels() { if (this.ims) { return Promise.resolve({ ims: this.ims }); } return this.api('im.list'); } /** * Posts an ephemeral message to a channel and user * @param id - channel ID * @param user - user ID * @param text * @param {object} params * @returns {vow.Promise} */ postEphemeral(id: string, user: string, text: string, params: any) { params = extend( { text: text, channel: id, user: user, username: this.name, }, params || {}, ); return this.api('chat.postEphemeral', params); } /** * Posts a message to a channel by ID * @param id - channel ID * @param text * @param {object} params * @returns {vow.Promise} */ postMessage(id: string, text: string, params: any) { params = extend( { text: text, channel: id, username: this.name, }, params || {}, ); return this.api('chat.postMessage', params); } /** * Updates a message by timestamp * @param id - channel ID * @param ts - timestamp * @param text * @param {object} params * @returns {vow.Promise} */ updateMessage(id: string, ts: string, text: string, params: any) { params = extend( { ts: ts, channel: id, username: this.name, text: text, }, params || {}, ); return this.api('chat.update', params); } /** * Posts a message to user by name * @param name * @param text * @param {object} params * @param {function} cb * @returns {vow.Promise} */ postMessageToUser(name: string, text: string, params: any, cb: any) { return this._post((params || {}).slackbot ? 'slackbot' : 'user', name, text, params, cb); } /** * Posts a message to channel by name * @param name * @param text * @param {object} params * @param {function} cb * @returns {vow.Promise} */ postMessageToChannel(name: string, text: string, params: any, cb: any) { return this._post('channel', name, text, params, cb); } /** * Posts a message to group by name * @param name * @param text * @param {object} params * @param {function} cb * @returns {vow.Promise} */ postMessageToGroup(name: string, text: string, params: any, cb: any) { return this._post('group', name, text, params, cb); } /** * Common method for posting messages * @param type * @param name * @param text * @param {object} params * @param {function} cb * @returns * @private */ _post(type: string, name: string, text: string, params: any, cb: any) { let method: any = { group: 'getGroupId', channel: 'getChannelId', user: 'getChatId', slackbot: 'getUserId', }[type]; if (typeof params === 'function') { cb = params; params = null; } return this[method](name) .then((itemId: any) => { return this.postMessage(itemId, text, params); }) .always((data: any) => { if (cb) { cb(data._value); } }); } /** * Posts a message to group | channel | user * @param name * @param text * @param {object} params * @param {function} cb * @returns {vow.Promise} */ postTo(name: string, text: string, params: any, cb: any) { return Promise.all([this.getChannels(), this.getUsers(), this.getGroups()]).then((data: any) => { name = this._cleanName(name); let all = [].concat(data[0].channels, data[1].members, data[2].groups); let result: any = find(all, { name: name }); console.assert(result, 'wrong name'); if (result['is_channel']) { return this.postMessageToChannel(name, text, params, cb); } else if (result['is_group']) { return this.postMessageToGroup(name, text, params, cb); } else { return this.postMessageToUser(name, text, params, cb); } }); } /** * Remove @ or # character from group | channel | user name * @param name * @returns */ _cleanName(name: string) { if (typeof name !== 'string') { return name; } var firstCharacter = name.charAt(0); if (firstCharacter === '#' || firstCharacter === '@') { name = name.slice(1); } return name; } /** * Preprocessing of params * @param params * @returns {object} * @private */ _preprocessParams(params: any) { params = extend(params || {}, { token: this.token }); Object.keys(params).forEach(function(name) { var param = params[name]; if (param && typeof param === 'object') { params[name] = JSON.stringify(param); } }); return params; } /** * Send request to API method * @param methodName * @param {object} params * @returns {vow.Promise} * @private */ api(methodName?: string, params?: any) { var data = { url: 'https://slack.com/api/' + methodName, form: this._preprocessParams(params), }; return new Promise((resolve: any, reject: any) => { post(data, (err, request, body) => { if (err) { reject(err); return false; } try { body = JSON.parse(body); // Response always contain a top-level boolean property ok, // indicating success or failure if (body.ok) { resolve(body); } else { reject(body); } } catch (e) { reject(e); } }); }); } }
the_stack
import { OfficeExtension } from "../../api-extractor-inputs-office/office" import { Office as Outlook} from "../../api-extractor-inputs-outlook/outlook" //////////////////////////////////////////////////////////////// /////////////////////// Begin Word APIs //////////////////////// //////////////////////////////////////////////////////////////// export declare namespace Word { /** * Represents the body of a document or a section. * * @remarks * [Api set: WordApi 1.1] */ export class Body extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * Gets the collection of rich text content control objects in the body. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly contentControls: Word.ContentControlCollection; /** * Gets the text format of the body. Use this to get and set font name, size, color and other properties. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly font: Word.Font; /** * Gets the collection of InlinePicture objects in the body. The collection does not include floating images. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly inlinePictures: Word.InlinePictureCollection; /** * Gets the collection of paragraph objects in the body. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly paragraphs: Word.ParagraphCollection; /** * Gets the content control that contains the body. Throws an error if there isn't a parent content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly parentContentControl: Word.ContentControl; /** * Gets or sets the style name for the body. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style: string; /** * Gets the text of the body. Use the insertText method to insert text. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly text: string; /** * Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.BodyUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Word.Body): void; /** * Clears the contents of the body object. The user can perform the undo operation on the cleared content. * * @remarks * [Api set: WordApi 1.1] */ clear(): void; /** * Gets an HTML representation of the body object. When rendered in a web page or HTML viewer, the formatting will be a close, but not exact, match for of the formatting of the document. This method does not return the exact same HTML for the same document on different platforms (Windows, Mac, Word on the web, etc.). If you need exact fidelity, or consistency across platforms, use `Body.getOoxml()` and convert the returned XML to HTML. * * @remarks * [Api set: WordApi 1.1] */ getHtml(): OfficeExtension.ClientResult<string>; /** * Gets the OOXML (Office Open XML) representation of the body object. * * @remarks * [Api set: WordApi 1.1] */ getOoxml(): OfficeExtension.ClientResult<string>; /** * Inserts a break at the specified location in the main document. * * @remarks * [Api set: WordApi 1.1] * * @param breakType - Required. The break type to add to the body. * @param insertLocation - Required. The value can be 'Start' or 'End'. */ insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * Inserts a break at the specified location in the main document. * * @remarks * [Api set: WordApi 1.1] * * @param breakTypeString - Required. The break type to add to the body. * @param insertLocation - Required. The value can be 'Start' or 'End'. */ insertBreak(breakTypeString: "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): void; /** * Wraps the body object with a Rich Text content control. * * @remarks * [Api set: WordApi 1.1] */ insertContentControl(): Word.ContentControl; /** * Inserts a document into the body at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param base64File - Required. The base64 encoded content of a .docx file. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. */ insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts a document into the body at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param base64File - Required. The base64 encoded content of a .docx file. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. */ insertFileFromBase64(base64File: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts HTML at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param html - Required. The HTML to be inserted in the document. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. */ insertHtml(html: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts HTML at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param html - Required. The HTML to be inserted in the document. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. */ insertHtml(html: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts a picture into the body at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param base64EncodedImage - Required. The base64 encoded image to be inserted in the body. * @param insertLocation - Required. The value can be 'Start' or 'End'. */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation): Word.InlinePicture; /** * Inserts a picture into the body at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param base64EncodedImage - Required. The base64 encoded image to be inserted in the body. * @param insertLocationString - Required. The value can be 'Start' or 'End'. */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.InlinePicture; /** * Inserts OOXML at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param ooxml - Required. The OOXML to be inserted. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. */ insertOoxml(ooxml: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts OOXML at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param ooxml - Required. The OOXML to be inserted. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. */ insertOoxml(ooxml: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts a paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param paragraphText - Required. The paragraph text to be inserted. * @param insertLocation - Required. The value can be 'Start' or 'End'. */ insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * Inserts a paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param paragraphText - Required. The paragraph text to be inserted. * @param insertLocationString - Required. The value can be 'Start' or 'End'. */ insertParagraph(paragraphText: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * Inserts text into the body at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param text - Required. Text to be inserted. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. */ insertText(text: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts text into the body at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param text - Required. Text to be inserted. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. */ insertText(text: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Performs a search with the specified SearchOptions on the scope of the body object. The search results are a collection of range objects. * * @remarks * [Api set: WordApi 1.1] * * @param searchText - Required. The search text. Can be a maximum of 255 characters. * @param searchOptions - Optional. Options for the search. */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; ignoreSpace?: boolean; matchCase?: boolean; matchPrefix?: boolean; matchSuffix?: boolean; matchWholeWord?: boolean; matchWildcards?: boolean; }): Word.RangeCollection; /** * Selects the body and navigates the Word UI to it. * * @remarks * [Api set: WordApi 1.1] * * @param selectionMode - Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default. */ select(selectionMode?: Word.SelectionMode): void; /** * Selects the body and navigates the Word UI to it. * * @remarks * [Api set: WordApi 1.1] * * @param selectionModeString - Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default. */ select(selectionModeString?: "Select" | "Start" | "End"): void; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.BodyLoadOptions): Word.Body; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.Body; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Word.Body; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.Body; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.Body; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Word.Body object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.BodyData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Word.Interfaces.BodyData; } /** * Represents a content control. Content controls are bounded and potentially labeled regions in a document that serve as containers for specific types of content. Individual content controls may contain contents such as images, tables, or paragraphs of formatted text. Currently, only rich text content controls are supported. * * @remarks * [Api set: WordApi 1.1] */ export class ContentControl extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * Gets the collection of content control objects in the content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly contentControls: Word.ContentControlCollection; /** * Gets the text format of the content control. Use this to get and set font name, size, color, and other properties. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly font: Word.Font; /** * Gets the collection of inlinePicture objects in the content control. The collection does not include floating images. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly inlinePictures: Word.InlinePictureCollection; /** * Get the collection of paragraph objects in the content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly paragraphs: Word.ParagraphCollection; /** * Gets the content control that contains the content control. Throws an error if there isn't a parent content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly parentContentControl: Word.ContentControl; /** * Gets or sets the appearance of the content control. The value can be 'BoundingBox', 'Tags', or 'Hidden'. * * @remarks * [Api set: WordApi 1.1] */ appearance: Word.ContentControlAppearance | "BoundingBox" | "Tags" | "Hidden"; /** * Gets or sets a value that indicates whether the user can delete the content control. Mutually exclusive with removeWhenEdited. * * @remarks * [Api set: WordApi 1.1] */ cannotDelete: boolean; /** * Gets or sets a value that indicates whether the user can edit the contents of the content control. * * @remarks * [Api set: WordApi 1.1] */ cannotEdit: boolean; /** * Gets or sets the color of the content control. Color is specified in '#RRGGBB' format or by using the color name. * * @remarks * [Api set: WordApi 1.1] */ color: string; /** * Gets an integer that represents the content control identifier. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly id: number; /** * Gets or sets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty. * * **Note**: The set operation for this property is not supported in Word on the web. * * @remarks * [Api set: WordApi 1.1] */ placeholderText: string; /** * Gets or sets a value that indicates whether the content control is removed after it is edited. Mutually exclusive with cannotDelete. * * @remarks * [Api set: WordApi 1.1] */ removeWhenEdited: boolean; /** * Gets or sets the style name for the content control. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style: string; /** * Gets or sets a tag to identify a content control. * * @remarks * [Api set: WordApi 1.1] */ tag: string; /** * Gets the text of the content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly text: string; /** * Gets or sets the title for a content control. * * @remarks * [Api set: WordApi 1.1] */ title: string; /** * Gets the content control type. Only rich text content controls are supported currently. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly type: Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText"; /** * Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.ContentControlUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Word.ContentControl): void; /** * Clears the contents of the content control. The user can perform the undo operation on the cleared content. * * @remarks * [Api set: WordApi 1.1] */ clear(): void; /** * Deletes the content control and its content. If keepContent is set to true, the content is not deleted. * * @remarks * [Api set: WordApi 1.1] * * @param keepContent - Required. Indicates whether the content should be deleted with the content control. If keepContent is set to true, the content is not deleted. */ delete(keepContent: boolean): void; /** * Gets an HTML representation of the content control object. When rendered in a web page or HTML viewer, the formatting will be a close, but not exact, match for of the formatting of the document. This method does not return the exact same HTML for the same document on different platforms (Windows, Mac, Word on the web, etc.). If you need exact fidelity, or consistency across platforms, use `ContentControl.getOoxml()` and convert the returned XML to HTML. * * @remarks * [Api set: WordApi 1.1] */ getHtml(): OfficeExtension.ClientResult<string>; /** * Gets the Office Open XML (OOXML) representation of the content control object. * * @remarks * [Api set: WordApi 1.1] */ getOoxml(): OfficeExtension.ClientResult<string>; /** * Inserts a break at the specified location in the main document. This method cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls. * * @remarks * [Api set: WordApi 1.1] * * @param breakType - Required. Type of break. * @param insertLocation - Required. The value can be 'Start', 'End', 'Before', or 'After'. */ insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * Inserts a break at the specified location in the main document. This method cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls. * * @remarks * [Api set: WordApi 1.1] * * @param breakTypeString - Required. Type of break. * @param insertLocation - Required. The value can be 'Start', 'End', 'Before', or 'After'. */ insertBreak(breakTypeString: "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): void; /** * Inserts a document into the content control at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param base64File - Required. The base64 encoded content of a .docx file. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. */ insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts a document into the content control at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param base64File - Required. The base64 encoded content of a .docx file. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. */ insertFileFromBase64(base64File: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts HTML into the content control at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param html - Required. The HTML to be inserted in to the content control. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. */ insertHtml(html: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts HTML into the content control at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param html - Required. The HTML to be inserted in to the content control. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. */ insertHtml(html: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts an inline picture into the content control at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param base64EncodedImage - Required. The base64 encoded image to be inserted in the content control. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation): Word.InlinePicture; /** * Inserts an inline picture into the content control at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param base64EncodedImage - Required. The base64 encoded image to be inserted in the content control. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.InlinePicture; /** * Inserts OOXML into the content control at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param ooxml - Required. The OOXML to be inserted in to the content control. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. */ insertOoxml(ooxml: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts OOXML into the content control at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param ooxml - Required. The OOXML to be inserted in to the content control. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. */ insertOoxml(ooxml: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts a paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param paragraphText - Required. The paragraph text to be inserted. * @param insertLocation - Required. The value can be 'Start', 'End', 'Before', or 'After'. 'Before' and 'After' cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls. */ insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * Inserts a paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param paragraphText - Required. The paragraph text to be inserted. * @param insertLocationString - Required. The value can be 'Start', 'End', 'Before', or 'After'. 'Before' and 'After' cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls. */ insertParagraph(paragraphText: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * Inserts text into the content control at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param text - Required. The text to be inserted in to the content control. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. */ insertText(text: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts text into the content control at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param text - Required. The text to be inserted in to the content control. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. */ insertText(text: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Performs a search with the specified SearchOptions on the scope of the content control object. The search results are a collection of range objects. * * @remarks * [Api set: WordApi 1.1] * * @param searchText - Required. The search text. * @param searchOptions - Optional. Options for the search. */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; ignoreSpace?: boolean; matchCase?: boolean; matchPrefix?: boolean; matchSuffix?: boolean; matchWholeWord?: boolean; matchWildcards?: boolean; }): Word.RangeCollection; /** * Selects the content control. This causes Word to scroll to the selection. * * @remarks * [Api set: WordApi 1.1] * * @param selectionMode - Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default. */ select(selectionMode?: Word.SelectionMode): void; /** * Selects the content control. This causes Word to scroll to the selection. * * @remarks * [Api set: WordApi 1.1] * * @param selectionModeString - Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default. */ select(selectionModeString?: "Select" | "Start" | "End"): void; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.ContentControlLoadOptions): Word.ContentControl; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.ContentControl; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Word.ContentControl; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.ContentControl; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.ContentControl; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Word.ContentControl object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.ContentControlData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Word.Interfaces.ContentControlData; } /** * Contains a collection of {@link Word.ContentControl} objects. Content controls are bounded and potentially labeled regions in a document that serve as containers for specific types of content. Individual content controls may contain contents such as images, tables, or paragraphs of formatted text. Currently, only rich text content controls are supported. * * @remarks * [Api set: WordApi 1.1] */ export class ContentControlCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: Word.ContentControl[]; /** * Gets a content control by its identifier. Throws an error if there isn't a content control with the identifier in this collection. * * @remarks * [Api set: WordApi 1.1] * * @param id - Required. A content control identifier. */ getById(id: number): Word.ContentControl; /** * Gets the content controls that have the specified tag. * * @remarks * [Api set: WordApi 1.1] * * @param tag - Required. A tag set on a content control. */ getByTag(tag: string): Word.ContentControlCollection; /** * Gets the content controls that have the specified title. * * @remarks * [Api set: WordApi 1.1] * * @param title - Required. The title of a content control. */ getByTitle(title: string): Word.ContentControlCollection; /** * Gets a content control by its index in the collection. * * @remarks * [Api set: WordApi 1.1] * * @param index - The index. */ getItem(index: number): Word.ContentControl; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.ContentControlCollectionLoadOptions & Word.Interfaces.CollectionLoadOptions): Word.ContentControlCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.ContentControlCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: OfficeExtension.LoadOption): Word.ContentControlCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.ContentControlCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.ContentControlCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `Word.ContentControlCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.ContentControlCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): Word.Interfaces.ContentControlCollectionData; } /** * The Document object is the top level object. A Document object contains one or more sections, content controls, and the body that contains the contents of the document. * * @remarks * [Api set: WordApi 1.1] */ export class Document extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * Gets the body object of the main document. The body is the text that excludes headers, footers, footnotes, textboxes, etc.. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly body: Word.Body; /** * Gets the collection of content control objects in the document. This includes content controls in the body of the document, headers, footers, textboxes, etc.. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly contentControls: Word.ContentControlCollection; /** * Gets the collection of section objects in the document. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly sections: Word.SectionCollection; /** * Indicates whether the changes in the document have been saved. A value of true indicates that the document hasn't changed since it was saved. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly saved: boolean; /** * Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.DocumentUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Word.Document): void; /** * Gets the current selection of the document. Multiple selections are not supported. * * @remarks * [Api set: WordApi 1.1] */ getSelection(): Word.Range; /** * Saves the document. This uses the Word default file naming convention if the document has not been saved before. * * @remarks * [Api set: WordApi 1.1] */ save(): void; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.DocumentLoadOptions): Word.Document; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.Document; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Word.Document; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.Document; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.Document; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Word.Document object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.DocumentData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Word.Interfaces.DocumentData; } /** * Represents a font. * * @remarks * [Api set: WordApi 1.1] */ export class Font extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * Gets or sets a value that indicates whether the font is bold. True if the font is formatted as bold, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ bold: boolean; /** * Gets or sets the color for the specified font. You can provide the value in the '#RRGGBB' format or the color name. * * @remarks * [Api set: WordApi 1.1] */ color: string; /** * Gets or sets a value that indicates whether the font has a double strikethrough. True if the font is formatted as double strikethrough text, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ doubleStrikeThrough: boolean; /** * Gets or sets the highlight color. To set it, use a value either in the '#RRGGBB' format or the color name. To remove highlight color, set it to null. The returned highlight color can be in the '#RRGGBB' format, an empty string for mixed highlight colors, or null for no highlight color. **Note**: Only the default highlight colors are available in Office for Windows Desktop. These are "Yellow", "Lime", "Turquoise", "Pink", "Blue", "Red", "DarkBlue", "Teal", "Green", "Purple", "DarkRed", "Olive", "Gray", "LightGray", and "Black". When the add-in runs in Office for Windows Desktop, any other color is converted to the closest color when applied to the font. * * @remarks * [Api set: WordApi 1.1] */ highlightColor: string; /** * Gets or sets a value that indicates whether the font is italicized. True if the font is italicized, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ italic: boolean; /** * Gets or sets a value that represents the name of the font. * * @remarks * [Api set: WordApi 1.1] */ name: string; /** * Gets or sets a value that represents the font size in points. * * @remarks * [Api set: WordApi 1.1] */ size: number; /** * Gets or sets a value that indicates whether the font has a strikethrough. True if the font is formatted as strikethrough text, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ strikeThrough: boolean; /** * Gets or sets a value that indicates whether the font is a subscript. True if the font is formatted as subscript, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ subscript: boolean; /** * Gets or sets a value that indicates whether the font is a superscript. True if the font is formatted as superscript, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ superscript: boolean; /** * Gets or sets a value that indicates the font's underline type. 'None' if the font is not underlined. * * @remarks * [Api set: WordApi 1.1] */ underline: Word.UnderlineType | "Mixed" | "None" | "Hidden" | "DotLine" | "Single" | "Word" | "Double" | "Thick" | "Dotted" | "DottedHeavy" | "DashLine" | "DashLineHeavy" | "DashLineLong" | "DashLineLongHeavy" | "DotDashLine" | "DotDashLineHeavy" | "TwoDotDashLine" | "TwoDotDashLineHeavy" | "Wave" | "WaveHeavy" | "WaveDouble"; /** * Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.FontUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Word.Font): void; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.FontLoadOptions): Word.Font; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.Font; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Word.Font; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.Font; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.Font; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Word.Font object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.FontData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Word.Interfaces.FontData; } /** * Represents an inline picture. * * @remarks * [Api set: WordApi 1.1] */ export class InlinePicture extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * Gets the parent paragraph that contains the inline image. Read-only. * * @remarks * [Api set: WordApi 1.2] */ readonly paragraph: Word.Paragraph; /** * Gets the content control that contains the inline image. Throws an error if there isn't a parent content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly parentContentControl: Word.ContentControl; /** * Gets or sets a string that represents the alternative text associated with the inline image. * * @remarks * [Api set: WordApi 1.1] */ altTextDescription: string; /** * Gets or sets a string that contains the title for the inline image. * * @remarks * [Api set: WordApi 1.1] */ altTextTitle: string; /** * Gets or sets a number that describes the height of the inline image. * * @remarks * [Api set: WordApi 1.1] */ height: number; /** * Gets or sets a hyperlink on the image. Use a '#' to separate the address part from the optional location part. * * @remarks * [Api set: WordApi 1.1] */ hyperlink: string; /** * Gets or sets a value that indicates whether the inline image retains its original proportions when you resize it. * * @remarks * [Api set: WordApi 1.1] */ lockAspectRatio: boolean; /** * Gets or sets a number that describes the width of the inline image. * * @remarks * [Api set: WordApi 1.1] */ width: number; /** * Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.InlinePictureUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Word.InlinePicture): void; /** * Deletes the inline picture from the document. * * @remarks * [Api set: WordApi 1.2] */ delete(): void; /** * Gets the base64 encoded string representation of the inline image. * * @remarks * [Api set: WordApi 1.1] */ getBase64ImageSrc(): OfficeExtension.ClientResult<string>; /** * Inserts a break at the specified location in the main document. * * @remarks * [Api set: WordApi 1.2] * * @param breakType - Required. The break type to add. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * Inserts a break at the specified location in the main document. * * @remarks * [Api set: WordApi 1.2] * * @param breakTypeString - Required. The break type to add. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertBreak(breakTypeString: "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): void; /** * Wraps the inline picture with a rich text content control. * * @remarks * [Api set: WordApi 1.1] */ insertContentControl(): Word.ContentControl; /** * Inserts a document at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param base64File - Required. The base64 encoded content of a .docx file. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts a document at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param base64File - Required. The base64 encoded content of a .docx file. * @param insertLocationString - Required. The value can be 'Before' or 'After'. */ insertFileFromBase64(base64File: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts HTML at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param html - Required. The HTML to be inserted. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertHtml(html: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts HTML at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param html - Required. The HTML to be inserted. * @param insertLocationString - Required. The value can be 'Before' or 'After'. */ insertHtml(html: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts an inline picture at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param base64EncodedImage - Required. The base64 encoded image to be inserted. * @param insertLocation - Required. The value can be 'Replace', 'Before', or 'After'. */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation): Word.InlinePicture; /** * Inserts an inline picture at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param base64EncodedImage - Required. The base64 encoded image to be inserted. * @param insertLocationString - Required. The value can be 'Replace', 'Before', or 'After'. */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.InlinePicture; /** * Inserts OOXML at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param ooxml - Required. The OOXML to be inserted. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertOoxml(ooxml: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts OOXML at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param ooxml - Required. The OOXML to be inserted. * @param insertLocationString - Required. The value can be 'Before' or 'After'. */ insertOoxml(ooxml: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts a paragraph at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param paragraphText - Required. The paragraph text to be inserted. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * Inserts a paragraph at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param paragraphText - Required. The paragraph text to be inserted. * @param insertLocationString - Required. The value can be 'Before' or 'After'. */ insertParagraph(paragraphText: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * Inserts text at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param text - Required. Text to be inserted. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertText(text: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts text at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param text - Required. Text to be inserted. * @param insertLocationString - Required. The value can be 'Before' or 'After'. */ insertText(text: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Selects the inline picture. This causes Word to scroll to the selection. * * @remarks * [Api set: WordApi 1.2] * * @param selectionMode - Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default. */ select(selectionMode?: Word.SelectionMode): void; /** * Selects the inline picture. This causes Word to scroll to the selection. * * @remarks * [Api set: WordApi 1.2] * * @param selectionModeString - Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default. */ select(selectionModeString?: "Select" | "Start" | "End"): void; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.InlinePictureLoadOptions): Word.InlinePicture; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.InlinePicture; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Word.InlinePicture; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.InlinePicture; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.InlinePicture; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Word.InlinePicture object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.InlinePictureData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Word.Interfaces.InlinePictureData; } /** * Contains a collection of {@link Word.InlinePicture} objects. * * @remarks * [Api set: WordApi 1.1] */ export class InlinePictureCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: Word.InlinePicture[]; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.InlinePictureCollectionLoadOptions & Word.Interfaces.CollectionLoadOptions): Word.InlinePictureCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.InlinePictureCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: OfficeExtension.LoadOption): Word.InlinePictureCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.InlinePictureCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.InlinePictureCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `Word.InlinePictureCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.InlinePictureCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): Word.Interfaces.InlinePictureCollectionData; } /** * Represents a single paragraph in a selection, range, content control, or document body. * * @remarks * [Api set: WordApi 1.1] */ export class Paragraph extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * Gets the collection of content control objects in the paragraph. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly contentControls: Word.ContentControlCollection; /** * Gets the text format of the paragraph. Use this to get and set font name, size, color, and other properties. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly font: Word.Font; /** * Gets the collection of InlinePicture objects in the paragraph. The collection does not include floating images. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly inlinePictures: Word.InlinePictureCollection; /** * Gets the content control that contains the paragraph. Throws an error if there isn't a parent content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly parentContentControl: Word.ContentControl; /** * Gets or sets the alignment for a paragraph. The value can be 'left', 'centered', 'right', or 'justified'. * * @remarks * [Api set: WordApi 1.1] */ alignment: Word.Alignment | "Mixed" | "Unknown" | "Left" | "Centered" | "Right" | "Justified"; /** * Gets or sets the value, in points, for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent. * * @remarks * [Api set: WordApi 1.1] */ firstLineIndent: number; /** * Gets or sets the left indent value, in points, for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ leftIndent: number; /** * Gets or sets the line spacing, in points, for the specified paragraph. In the Word UI, this value is divided by 12. * * @remarks * [Api set: WordApi 1.1] */ lineSpacing: number; /** * Gets or sets the amount of spacing, in grid lines, after the paragraph. * * @remarks * [Api set: WordApi 1.1] */ lineUnitAfter: number; /** * Gets or sets the amount of spacing, in grid lines, before the paragraph. * * @remarks * [Api set: WordApi 1.1] */ lineUnitBefore: number; /** * Gets or sets the outline level for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ outlineLevel: number; /** * Gets or sets the right indent value, in points, for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ rightIndent: number; /** * Gets or sets the spacing, in points, after the paragraph. * * @remarks * [Api set: WordApi 1.1] */ spaceAfter: number; /** * Gets or sets the spacing, in points, before the paragraph. * * @remarks * [Api set: WordApi 1.1] */ spaceBefore: number; /** * Gets or sets the style name for the paragraph. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style: string; /** * Gets the text of the paragraph. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly text: string; /** * Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.ParagraphUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Word.Paragraph): void; /** * Clears the contents of the paragraph object. The user can perform the undo operation on the cleared content. * * @remarks * [Api set: WordApi 1.1] */ clear(): void; /** * Deletes the paragraph and its content from the document. * * @remarks * [Api set: WordApi 1.1] */ delete(): void; /** * Gets an HTML representation of the paragraph object. When rendered in a web page or HTML viewer, the formatting will be a close, but not exact, match for of the formatting of the document. This method does not return the exact same HTML for the same document on different platforms (Windows, Mac, Word on the web, etc.). If you need exact fidelity, or consistency across platforms, use `Paragraph.getOoxml()` and convert the returned XML to HTML. * * @remarks * [Api set: WordApi 1.1] */ getHtml(): OfficeExtension.ClientResult<string>; /** * Gets the Office Open XML (OOXML) representation of the paragraph object. * * @remarks * [Api set: WordApi 1.1] */ getOoxml(): OfficeExtension.ClientResult<string>; /** * Inserts a break at the specified location in the main document. * * @remarks * [Api set: WordApi 1.1] * * @param breakType - Required. The break type to add to the document. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * Inserts a break at the specified location in the main document. * * @remarks * [Api set: WordApi 1.1] * * @param breakTypeString - Required. The break type to add to the document. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertBreak(breakTypeString: "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): void; /** * Wraps the paragraph object with a rich text content control. * * @remarks * [Api set: WordApi 1.1] */ insertContentControl(): Word.ContentControl; /** * Inserts a document into the paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param base64File - Required. The base64 encoded content of a .docx file. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. */ insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts a document into the paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param base64File - Required. The base64 encoded content of a .docx file. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. */ insertFileFromBase64(base64File: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts HTML into the paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param html - Required. The HTML to be inserted in the paragraph. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. */ insertHtml(html: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts HTML into the paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param html - Required. The HTML to be inserted in the paragraph. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. */ insertHtml(html: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts a picture into the paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param base64EncodedImage - Required. The base64 encoded image to be inserted. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation): Word.InlinePicture; /** * Inserts a picture into the paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param base64EncodedImage - Required. The base64 encoded image to be inserted. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.InlinePicture; /** * Inserts OOXML into the paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param ooxml - Required. The OOXML to be inserted in the paragraph. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. */ insertOoxml(ooxml: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts OOXML into the paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param ooxml - Required. The OOXML to be inserted in the paragraph. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. */ insertOoxml(ooxml: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts a paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param paragraphText - Required. The paragraph text to be inserted. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * Inserts a paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param paragraphText - Required. The paragraph text to be inserted. * @param insertLocationString - Required. The value can be 'Before' or 'After'. */ insertParagraph(paragraphText: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * Inserts text into the paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param text - Required. Text to be inserted. * @param insertLocation - Required. The value can be 'Replace', 'Start', or 'End'. */ insertText(text: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts text into the paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param text - Required. Text to be inserted. * @param insertLocationString - Required. The value can be 'Replace', 'Start', or 'End'. */ insertText(text: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Performs a search with the specified SearchOptions on the scope of the paragraph object. The search results are a collection of range objects. * * @remarks * [Api set: WordApi 1.1] * * @param searchText - Required. The search text. * @param searchOptions - Optional. Options for the search. */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; ignoreSpace?: boolean; matchCase?: boolean; matchPrefix?: boolean; matchSuffix?: boolean; matchWholeWord?: boolean; matchWildcards?: boolean; }): Word.RangeCollection; /** * Selects and navigates the Word UI to the paragraph. * * @remarks * [Api set: WordApi 1.1] * * @param selectionMode - Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default. */ select(selectionMode?: Word.SelectionMode): void; /** * Selects and navigates the Word UI to the paragraph. * * @remarks * [Api set: WordApi 1.1] * * @param selectionModeString - Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default. */ select(selectionModeString?: "Select" | "Start" | "End"): void; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.ParagraphLoadOptions): Word.Paragraph; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.Paragraph; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Word.Paragraph; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.Paragraph; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.Paragraph; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Word.Paragraph object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.ParagraphData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Word.Interfaces.ParagraphData; } /** * Contains a collection of {@link Word.Paragraph} objects. * * @remarks * [Api set: WordApi 1.1] */ export class ParagraphCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: Word.Paragraph[]; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.ParagraphCollectionLoadOptions & Word.Interfaces.CollectionLoadOptions): Word.ParagraphCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.ParagraphCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: OfficeExtension.LoadOption): Word.ParagraphCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.ParagraphCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.ParagraphCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `Word.ParagraphCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.ParagraphCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): Word.Interfaces.ParagraphCollectionData; } /** * Represents a contiguous area in a document. * * @remarks * [Api set: WordApi 1.1] */ export class Range extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * Gets the collection of content control objects in the range. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly contentControls: Word.ContentControlCollection; /** * Gets the text format of the range. Use this to get and set font name, size, color, and other properties. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly font: Word.Font; /** * Gets the collection of inline picture objects in the range. Read-only. * * @remarks * [Api set: WordApi 1.2] */ readonly inlinePictures: Word.InlinePictureCollection; /** * Gets the collection of paragraph objects in the range. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly paragraphs: Word.ParagraphCollection; /** * Gets the content control that contains the range. Throws an error if there isn't a parent content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly parentContentControl: Word.ContentControl; /** * Gets or sets the style name for the range. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style: string; /** * Gets the text of the range. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly text: string; /** * Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.RangeUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Word.Range): void; /** * Clears the contents of the range object. The user can perform the undo operation on the cleared content. * * @remarks * [Api set: WordApi 1.1] */ clear(): void; /** * Deletes the range and its content from the document. * * @remarks * [Api set: WordApi 1.1] */ delete(): void; /** * Gets an HTML representation of the range object. When rendered in a web page or HTML viewer, the formatting will be a close, but not exact, match for of the formatting of the document. This method does not return the exact same HTML for the same document on different platforms (Windows, Mac, Word on the web, etc.). If you need exact fidelity, or consistency across platforms, use `Range.getOoxml()` and convert the returned XML to HTML. * * @remarks * [Api set: WordApi 1.1] */ getHtml(): OfficeExtension.ClientResult<string>; /** * Gets the OOXML representation of the range object. * * @remarks * [Api set: WordApi 1.1] */ getOoxml(): OfficeExtension.ClientResult<string>; /** * Inserts a break at the specified location in the main document. * * @remarks * [Api set: WordApi 1.1] * * @param breakType - Required. The break type to add. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * Inserts a break at the specified location in the main document. * * @remarks * [Api set: WordApi 1.1] * * @param breakTypeString - Required. The break type to add. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertBreak(breakTypeString: "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): void; /** * Wraps the range object with a rich text content control. * * @remarks * [Api set: WordApi 1.1] */ insertContentControl(): Word.ContentControl; /** * Inserts a document at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param base64File - Required. The base64 encoded content of a .docx file. * @param insertLocation - Required. The value can be 'Replace', 'Start', 'End', 'Before', or 'After'. */ insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts a document at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param base64File - Required. The base64 encoded content of a .docx file. * @param insertLocationString - Required. The value can be 'Replace', 'Start', 'End', 'Before', or 'After'. */ insertFileFromBase64(base64File: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts HTML at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param html - Required. The HTML to be inserted. * @param insertLocation - Required. The value can be 'Replace', 'Start', 'End', 'Before', or 'After'. */ insertHtml(html: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts HTML at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param html - Required. The HTML to be inserted. * @param insertLocationString - Required. The value can be 'Replace', 'Start', 'End', 'Before', or 'After'. */ insertHtml(html: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts a picture at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param base64EncodedImage - Required. The base64 encoded image to be inserted. * @param insertLocation - Required. The value can be 'Replace', 'Start', 'End', 'Before', or 'After'. */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation): Word.InlinePicture; /** * Inserts a picture at the specified location. * * @remarks * [Api set: WordApi 1.2] * * @param base64EncodedImage - Required. The base64 encoded image to be inserted. * @param insertLocationString - Required. The value can be 'Replace', 'Start', 'End', 'Before', or 'After'. */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.InlinePicture; /** * Inserts OOXML at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param ooxml - Required. The OOXML to be inserted. * @param insertLocation - Required. The value can be 'Replace', 'Start', 'End', 'Before', or 'After'. */ insertOoxml(ooxml: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts OOXML at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param ooxml - Required. The OOXML to be inserted. * @param insertLocationString - Required. The value can be 'Replace', 'Start', 'End', 'Before', or 'After'. */ insertOoxml(ooxml: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Inserts a paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param paragraphText - Required. The paragraph text to be inserted. * @param insertLocation - Required. The value can be 'Before' or 'After'. */ insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * Inserts a paragraph at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param paragraphText - Required. The paragraph text to be inserted. * @param insertLocationString - Required. The value can be 'Before' or 'After'. */ insertParagraph(paragraphText: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * Inserts text at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param text - Required. Text to be inserted. * @param insertLocation - Required. The value can be 'Replace', 'Start', 'End', 'Before', or 'After'. */ insertText(text: string, insertLocation: Word.InsertLocation): Word.Range; /** * Inserts text at the specified location. * * @remarks * [Api set: WordApi 1.1] * * @param text - Required. Text to be inserted. * @param insertLocationString - Required. The value can be 'Replace', 'Start', 'End', 'Before', or 'After'. */ insertText(text: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * Performs a search with the specified SearchOptions on the scope of the range object. The search results are a collection of range objects. * * @remarks * [Api set: WordApi 1.1] * * @param searchText - Required. The search text. * @param searchOptions - Optional. Options for the search. */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; ignoreSpace?: boolean; matchCase?: boolean; matchPrefix?: boolean; matchSuffix?: boolean; matchWholeWord?: boolean; matchWildcards?: boolean; }): Word.RangeCollection; /** * Selects and navigates the Word UI to the range. * * @remarks * [Api set: WordApi 1.1] * * @param selectionMode - Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default. */ select(selectionMode?: Word.SelectionMode): void; /** * Selects and navigates the Word UI to the range. * * @remarks * [Api set: WordApi 1.1] * * @param selectionModeString - Optional. The selection mode can be 'Select', 'Start', or 'End'. 'Select' is the default. */ select(selectionModeString?: "Select" | "Start" | "End"): void; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.RangeLoadOptions): Word.Range; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.Range; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Word.Range; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.Range; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.Range; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Word.Range object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.RangeData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Word.Interfaces.RangeData; } /** * Contains a collection of {@link Word.Range} objects. * * @remarks * [Api set: WordApi 1.1] */ export class RangeCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: Word.Range[]; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.RangeCollectionLoadOptions & Word.Interfaces.CollectionLoadOptions): Word.RangeCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.RangeCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: OfficeExtension.LoadOption): Word.RangeCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.RangeCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.RangeCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `Word.RangeCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.RangeCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): Word.Interfaces.RangeCollectionData; } /** * Specifies the options to be included in a search operation. * * To learn more about how to use search options in the Word JavaScript APIs, read {@link https://docs.microsoft.com/office/dev/add-ins/word/search-option-guidance | Use search options to find text in your Word add-in}. * * @remarks * [Api set: WordApi 1.1] */ export class SearchOptions extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * Gets or sets a value that indicates whether to ignore all punctuation characters between words. Corresponds to the Ignore punctuation check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ ignorePunct: boolean; /** * Gets or sets a value that indicates whether to ignore all whitespace between words. Corresponds to the Ignore whitespace characters check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ ignoreSpace: boolean; /** * Gets or sets a value that indicates whether to perform a case sensitive search. Corresponds to the Match case check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchCase: boolean; /** * Gets or sets a value that indicates whether to match words that begin with the search string. Corresponds to the Match prefix check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchPrefix: boolean; /** * Gets or sets a value that indicates whether to match words that end with the search string. Corresponds to the Match suffix check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchSuffix: boolean; /** * Gets or sets a value that indicates whether to find operation only entire words, not text that is part of a larger word. Corresponds to the Find whole words only check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchWholeWord: boolean; /** * Gets or sets a value that indicates whether the search will be performed using special search operators. Corresponds to the Use wildcards check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchWildcards: boolean; /** * Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.SearchOptionsUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Word.SearchOptions): void; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.SearchOptionsLoadOptions): Word.SearchOptions; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.SearchOptions; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Word.SearchOptions; /** * Create a new instance of Word.SearchOptions object */ static newObject(context: OfficeExtension.ClientRequestContext): Word.SearchOptions; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Word.SearchOptions object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.SearchOptionsData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Word.Interfaces.SearchOptionsData; } /** * Represents a section in a Word document. * * @remarks * [Api set: WordApi 1.1] */ export class Section extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** * Gets the body object of the section. This does not include the header/footer and other section metadata. Read-only. * * @remarks * [Api set: WordApi 1.1] */ readonly body: Word.Body; /** * Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type. * @param properties - A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called. * @param options - Provides an option to suppress errors if the properties object tries to set any read-only properties. */ set(properties: Interfaces.SectionUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Word.Section): void; /** * Gets one of the section's footers. * * @remarks * [Api set: WordApi 1.1] * * @param type - Required. The type of footer to return. This value can be: 'Primary', 'FirstPage', or 'EvenPages'. */ getFooter(type: Word.HeaderFooterType): Word.Body; /** * Gets one of the section's footers. * * @remarks * [Api set: WordApi 1.1] * * @param typeString - Required. The type of footer to return. This value can be: 'Primary', 'FirstPage', or 'EvenPages'. */ getFooter(typeString: "Primary" | "FirstPage" | "EvenPages"): Word.Body; /** * Gets one of the section's headers. * * @remarks * [Api set: WordApi 1.1] * * @param type - Required. The type of header to return. This value can be: 'Primary', 'FirstPage', or 'EvenPages'. */ getHeader(type: Word.HeaderFooterType): Word.Body; /** * Gets one of the section's headers. * * @remarks * [Api set: WordApi 1.1] * * @param typeString - Required. The type of header to return. This value can be: 'Primary', 'FirstPage', or 'EvenPages'. */ getHeader(typeString: "Primary" | "FirstPage" | "EvenPages"): Word.Body; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.SectionLoadOptions): Word.Section; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.Section; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: { select?: string; expand?: string; }): Word.Section; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.Section; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.Section; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original Word.Section object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.SectionData`) that contains shallow copies of any loaded child properties from the original object. */ toJSON(): Word.Interfaces.SectionData; } /** * Contains the collection of the document's {@link Word.Section} objects. * * @remarks * [Api set: WordApi 1.1] */ export class SectionCollection extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; /** Gets the loaded child items in this collection. */ readonly items: Word.Section[]; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param options - Provides options for which properties of the object to load. */ load(options?: Word.Interfaces.SectionCollectionLoadOptions & Word.Interfaces.CollectionLoadOptions): Word.SectionCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNames - A comma-delimited string or an array of strings that specify the properties to load. */ load(propertyNames?: string | string[]): Word.SectionCollection; /** * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param propertyNamesAndPaths - `propertyNamesAndPaths.select` is a comma-delimited string that specifies the properties to load, and `propertyNamesAndPaths.expand` is a comma-delimited string that specifies the navigation properties to load. */ load(propertyNamesAndPaths?: OfficeExtension.LoadOption): Word.SectionCollection; /** * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for `context.trackedObjects.add(thisObject)`. If you are using this object across `.sync` calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ track(): Word.SectionCollection; /** * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for `context.trackedObjects.remove(thisObject)`. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call `context.sync()` before the memory release takes effect. */ untrack(): Word.SectionCollection; /** * Overrides the JavaScript `toJSON()` method in order to provide more useful output when an API object is passed to `JSON.stringify()`. (`JSON.stringify`, in turn, calls the `toJSON` method of the object that is passed to it.) * Whereas the original `Word.SectionCollection` object is an API object, the `toJSON` method returns a plain JavaScript object (typed as `Word.Interfaces.SectionCollectionData`) that contains an "items" array with shallow copies of any loaded properties from the collection's items. */ toJSON(): Word.Interfaces.SectionCollectionData; } /** * Provides information about the type of a raised event. For each object type, please keep the order of: deleted, selection changed, data changed, added. * * @remarks * [Api set: WordApi] */ enum EventType { /** * ContentControlDeleted represent the event that the content control has been deleted. * @remarks * [Api set: WordApi] */ contentControlDeleted = "ContentControlDeleted", /** * ContentControlSelectionChanged represents the event that the selection in the content control has been changed. * @remarks * [Api set: WordApi] */ contentControlSelectionChanged = "ContentControlSelectionChanged", /** * ContentControlDataChanged represents the event that the data in the content control have been changed. * @remarks * [Api set: WordApi] */ contentControlDataChanged = "ContentControlDataChanged", /** * ContentControlAdded represents the event a content control has been added to the document. * @remarks * [Api set: WordApi] */ contentControlAdded = "ContentControlAdded", /** * AnnotationAdded represents the event an annotation has been added to the document. * @remarks * [Api set: WordApi] */ annotationAdded = "AnnotationAdded", /** * AnnotationAdded represents the event an annotation has been updated in the document. * @remarks * [Api set: WordApi] */ annotationChanged = "AnnotationChanged", /** * AnnotationAdded represents the event an annotation has been deleted from the document. * @remarks * [Api set: WordApi] */ annotationDeleted = "AnnotationDeleted", } /** * Specifies supported content control types and subtypes. * * @remarks * [Api set: WordApi] */ enum ContentControlType { /** * @remarks * [Api set: WordApi] */ unknown = "Unknown", /** * @remarks * [Api set: WordApi] */ richTextInline = "RichTextInline", /** * @remarks * [Api set: WordApi] */ richTextParagraphs = "RichTextParagraphs", /** * Contains a whole cell. * @remarks * [Api set: WordApi] */ richTextTableCell = "RichTextTableCell", /** * Contains a whole row. * @remarks * [Api set: WordApi] */ richTextTableRow = "RichTextTableRow", /** * Contains a whole table. * @remarks * [Api set: WordApi] */ richTextTable = "RichTextTable", /** * @remarks * [Api set: WordApi] */ plainTextInline = "PlainTextInline", /** * @remarks * [Api set: WordApi] */ plainTextParagraph = "PlainTextParagraph", /** * @remarks * [Api set: WordApi] */ picture = "Picture", /** * @remarks * [Api set: WordApi] */ buildingBlockGallery = "BuildingBlockGallery", /** * @remarks * [Api set: WordApi] */ checkBox = "CheckBox", /** * @remarks * [Api set: WordApi] */ comboBox = "ComboBox", /** * @remarks * [Api set: WordApi] */ dropDownList = "DropDownList", /** * @remarks * [Api set: WordApi] */ datePicker = "DatePicker", /** * @remarks * [Api set: WordApi] */ repeatingSection = "RepeatingSection", /** * Identifies a rich text content control. * @remarks * [Api set: WordApi] */ richText = "RichText", /** * @remarks * [Api set: WordApi] */ plainText = "PlainText", } /** * ContentControl appearance * * @remarks * [Api set: WordApi] * * Content control appearance options are bounding box, tags, or hidden. */ enum ContentControlAppearance { /** * Represents a content control shown as a shaded rectangle or bounding box (with optional title). * @remarks * [Api set: WordApi] */ boundingBox = "BoundingBox", /** * Represents a content control shown as start and end markers. * @remarks * [Api set: WordApi] */ tags = "Tags", /** * Represents a content control that is not shown. * @remarks * [Api set: WordApi] */ hidden = "Hidden", } /** * The supported styles for underline format. * * @remarks * [Api set: WordApi] */ enum UnderlineType { /** * @remarks * [Api set: WordApi] */ mixed = "Mixed", /** * No underline. * @remarks * [Api set: WordApi] */ none = "None", /** * **Warning**: `hidden` has been deprecated. * * @deprecated `hidden` is no longer supported. * @remarks * [Api set: WordApi] */ hidden = "Hidden", /** * **Warning**: `dotLine` has been deprecated. * * @deprecated `dotLine` is no longer supported. * @remarks * [Api set: WordApi] */ dotLine = "DotLine", /** * A single underline. This is the default value. * @remarks * [Api set: WordApi] */ single = "Single", /** * Only underline individual words. * @remarks * [Api set: WordApi] */ word = "Word", /** * A double underline. * @remarks * [Api set: WordApi] */ double = "Double", /** * A single thick underline. * @remarks * [Api set: WordApi] */ thick = "Thick", /** * A dotted underline. * @remarks * [Api set: WordApi] */ dotted = "Dotted", /** * @remarks * [Api set: WordApi] */ dottedHeavy = "DottedHeavy", /** * A single dash underline. * @remarks * [Api set: WordApi] */ dashLine = "DashLine", /** * @remarks * [Api set: WordApi] */ dashLineHeavy = "DashLineHeavy", /** * @remarks * [Api set: WordApi] */ dashLineLong = "DashLineLong", /** * @remarks * [Api set: WordApi] */ dashLineLongHeavy = "DashLineLongHeavy", /** * An alternating dot-dash underline. * @remarks * [Api set: WordApi] */ dotDashLine = "DotDashLine", /** * @remarks * [Api set: WordApi] */ dotDashLineHeavy = "DotDashLineHeavy", /** * An alternating dot-dot-dash underline. * @remarks * [Api set: WordApi] */ twoDotDashLine = "TwoDotDashLine", /** * @remarks * [Api set: WordApi] */ twoDotDashLineHeavy = "TwoDotDashLineHeavy", /** * A single wavy underline. * @remarks * [Api set: WordApi] */ wave = "Wave", /** * @remarks * [Api set: WordApi] */ waveHeavy = "WaveHeavy", /** * @remarks * [Api set: WordApi] */ waveDouble = "WaveDouble", } /** * Specifies the form of a break. * * @remarks * [Api set: WordApi] */ enum BreakType { /** * Page break at the insertion point. * @remarks * [Api set: WordApi] */ page = "Page", /** * **Warning**: `next` has been deprecated. Use `sectionNext` instead. * * @deprecated Use sectionNext instead. * @remarks * [Api set: WordApi] */ next = "Next", /** * Section break on next page. * @remarks * [Api set: WordApi] */ sectionNext = "SectionNext", /** * New section without a corresponding page break. * @remarks * [Api set: WordApi] */ sectionContinuous = "SectionContinuous", /** * Section break with the next section beginning on the next even-numbered page. If the section break falls on an even-numbered page, Word leaves the next odd-numbered page blank. * @remarks * [Api set: WordApi] */ sectionEven = "SectionEven", /** * Section break with the next section beginning on the next odd-numbered page. If the section break falls on an odd-numbered page, Word leaves the next even-numbered page blank. * @remarks * [Api set: WordApi] */ sectionOdd = "SectionOdd", /** * Line break. * @remarks * [Api set: WordApi] */ line = "Line", } /** * The insertion location types. * * @remarks * [Api set: WordApi] * * To be used with an API call, such as `obj.insertSomething(newStuff, location);` * If the location is "Before" or "After", the new content will be outside of the modified object. * If the location is "Start" or "End", the new content will be included as part of the modified object. */ enum InsertLocation { /** * Add content before the contents of the calling object. * @remarks * [Api set: WordApi] */ before = "Before", /** * Add content after the contents of the calling object. * @remarks * [Api set: WordApi] */ after = "After", /** * Prepend content to the contents of the calling object. * @remarks * [Api set: WordApi] */ start = "Start", /** * Append content to the contents of the calling object. * @remarks * [Api set: WordApi] */ end = "End", /** * Replace the contents of the current object. * @remarks * [Api set: WordApi] */ replace = "Replace", } /** * @remarks * [Api set: WordApi] */ enum Alignment { /** * @remarks * [Api set: WordApi] */ mixed = "Mixed", /** * Unknown alignment. * @remarks * [Api set: WordApi] */ unknown = "Unknown", /** * Alignment to the left. * @remarks * [Api set: WordApi] */ left = "Left", /** * Alignment to the center. * @remarks * [Api set: WordApi] */ centered = "Centered", /** * Alignment to the right. * @remarks * [Api set: WordApi] */ right = "Right", /** * Fully justified alignment. * @remarks * [Api set: WordApi] */ justified = "Justified", } /** * @remarks * [Api set: WordApi] */ enum HeaderFooterType { /** * Returns the header or footer on all pages of a section, but excludes the first page or odd pages if they are different. * @remarks * [Api set: WordApi] */ primary = "Primary", /** * Returns the header or footer on the first page of a section. * @remarks * [Api set: WordApi] */ firstPage = "FirstPage", /** * Returns all headers or footers on even-numbered pages of a section. * @remarks * [Api set: WordApi] */ evenPages = "EvenPages", } /** * @remarks * [Api set: WordApi] */ enum BodyType { /** * @remarks * [Api set: WordApi] */ unknown = "Unknown", /** * @remarks * [Api set: WordApi] */ mainDoc = "MainDoc", /** * @remarks * [Api set: WordApi] */ section = "Section", /** * @remarks * [Api set: WordApi] */ header = "Header", /** * @remarks * [Api set: WordApi] */ footer = "Footer", /** * @remarks * [Api set: WordApi] */ tableCell = "TableCell", } /** * This enum sets where the cursor (insertion point) in the document is after a selection. * * @remarks * [Api set: WordApi] */ enum SelectionMode { /** * The entire range is selected. * @remarks * [Api set: WordApi] */ select = "Select", /** * The cursor is at the beginning of the selection (just before the start of the selected range). * @remarks * [Api set: WordApi] */ start = "Start", /** * The cursor is at the end of the selection (just after the end of the selected range). * @remarks * [Api set: WordApi] */ end = "End", } /** * @remarks * [Api set: WordApi] */ enum ImageFormat { /** * @remarks * [Api set: WordApi] */ unsupported = "Unsupported", /** * @remarks * [Api set: WordApi] */ undefined = "Undefined", /** * @remarks * [Api set: WordApi] */ bmp = "Bmp", /** * @remarks * [Api set: WordApi] */ jpeg = "Jpeg", /** * @remarks * [Api set: WordApi] */ gif = "Gif", /** * @remarks * [Api set: WordApi] */ tiff = "Tiff", /** * @remarks * [Api set: WordApi] */ png = "Png", /** * @remarks * [Api set: WordApi] */ icon = "Icon", /** * @remarks * [Api set: WordApi] */ exif = "Exif", /** * @remarks * [Api set: WordApi] */ wmf = "Wmf", /** * @remarks * [Api set: WordApi] */ emf = "Emf", /** * @remarks * [Api set: WordApi] */ pict = "Pict", /** * @remarks * [Api set: WordApi] */ pdf = "Pdf", /** * @remarks * [Api set: WordApi] */ svg = "Svg", } /** * @remarks * [Api set: WordApi] */ enum RangeLocation { /** * The object's whole range. If the object is a paragraph content control or table content control, the EOP or Table characters after the content control are also included. * @remarks * [Api set: WordApi] */ whole = "Whole", /** * The starting point of the object. For content control, it is the point after the opening tag. * @remarks * [Api set: WordApi] */ start = "Start", /** * The ending point of the object. For paragraph, it is the point before the EOP. For content control, it is the point before the closing tag. * @remarks * [Api set: WordApi] */ end = "End", /** * For content control only. It is the point before the opening tag. * @remarks * [Api set: WordApi] */ before = "Before", /** * The point after the object. If the object is a paragraph content control or table content control, it is the point after the EOP or Table characters. * @remarks * [Api set: WordApi] */ after = "After", /** * The range between 'Start' and 'End'. * @remarks * [Api set: WordApi] */ content = "Content", } /** * @remarks * [Api set: WordApi] */ enum LocationRelation { /** * Indicates that this instance and the range are in different sub-documents. * @remarks * [Api set: WordApi] */ unrelated = "Unrelated", /** * Indicates that this instance and the range represent the same range. * @remarks * [Api set: WordApi] */ equal = "Equal", /** * Indicates that this instance contains the range and that it shares the same start character. The range does not share the same end character as this instance. * @remarks * [Api set: WordApi] */ containsStart = "ContainsStart", /** * Indicates that this instance contains the range and that it shares the same end character. The range does not share the same start character as this instance. * @remarks * [Api set: WordApi] */ containsEnd = "ContainsEnd", /** * Indicates that this instance contains the range, with the exception of the start and end character of this instance. * @remarks * [Api set: WordApi] */ contains = "Contains", /** * Indicates that this instance is inside the range and that it shares the same start character. The range does not share the same end character as this instance. * @remarks * [Api set: WordApi] */ insideStart = "InsideStart", /** * Indicates that this instance is inside the range and that it shares the same end character. The range does not share the same start character as this instance. * @remarks * [Api set: WordApi] */ insideEnd = "InsideEnd", /** * Indicates that this instance is inside the range. The range does not share the same start and end characters as this instance. * @remarks * [Api set: WordApi] */ inside = "Inside", /** * Indicates that this instance occurs before, and is adjacent to, the range. * @remarks * [Api set: WordApi] */ adjacentBefore = "AdjacentBefore", /** * Indicates that this instance starts before the range and overlaps the range’s first character. * @remarks * [Api set: WordApi] */ overlapsBefore = "OverlapsBefore", /** * Indicates that this instance occurs before the range. * @remarks * [Api set: WordApi] */ before = "Before", /** * Indicates that this instance occurs after, and is adjacent to, the range. * @remarks * [Api set: WordApi] */ adjacentAfter = "AdjacentAfter", /** * Indicates that this instance starts inside the range and overlaps the range’s last character. * @remarks * [Api set: WordApi] */ overlapsAfter = "OverlapsAfter", /** * Indicates that this instance occurs after the range. * @remarks * [Api set: WordApi] */ after = "After", } /** * @remarks * [Api set: WordApi] */ enum BorderLocation { /** * @remarks * [Api set: WordApi] */ top = "Top", /** * @remarks * [Api set: WordApi] */ left = "Left", /** * @remarks * [Api set: WordApi] */ bottom = "Bottom", /** * @remarks * [Api set: WordApi] */ right = "Right", /** * @remarks * [Api set: WordApi] */ insideHorizontal = "InsideHorizontal", /** * @remarks * [Api set: WordApi] */ insideVertical = "InsideVertical", /** * @remarks * [Api set: WordApi] */ inside = "Inside", /** * @remarks * [Api set: WordApi] */ outside = "Outside", /** * @remarks * [Api set: WordApi] */ all = "All", } /** * @remarks * [Api set: WordApi] */ enum CellPaddingLocation { /** * @remarks * [Api set: WordApi] */ top = "Top", /** * @remarks * [Api set: WordApi] */ left = "Left", /** * @remarks * [Api set: WordApi] */ bottom = "Bottom", /** * @remarks * [Api set: WordApi] */ right = "Right", } /** * @remarks * [Api set: WordApi] */ enum BorderType { /** * @remarks * [Api set: WordApi] */ mixed = "Mixed", /** * @remarks * [Api set: WordApi] */ none = "None", /** * @remarks * [Api set: WordApi] */ single = "Single", /** * @remarks * [Api set: WordApi] */ double = "Double", /** * @remarks * [Api set: WordApi] */ dotted = "Dotted", /** * @remarks * [Api set: WordApi] */ dashed = "Dashed", /** * @remarks * [Api set: WordApi] */ dotDashed = "DotDashed", /** * @remarks * [Api set: WordApi] */ dot2Dashed = "Dot2Dashed", /** * @remarks * [Api set: WordApi] */ triple = "Triple", /** * @remarks * [Api set: WordApi] */ thinThickSmall = "ThinThickSmall", /** * @remarks * [Api set: WordApi] */ thickThinSmall = "ThickThinSmall", /** * @remarks * [Api set: WordApi] */ thinThickThinSmall = "ThinThickThinSmall", /** * @remarks * [Api set: WordApi] */ thinThickMed = "ThinThickMed", /** * @remarks * [Api set: WordApi] */ thickThinMed = "ThickThinMed", /** * @remarks * [Api set: WordApi] */ thinThickThinMed = "ThinThickThinMed", /** * @remarks * [Api set: WordApi] */ thinThickLarge = "ThinThickLarge", /** * @remarks * [Api set: WordApi] */ thickThinLarge = "ThickThinLarge", /** * @remarks * [Api set: WordApi] */ thinThickThinLarge = "ThinThickThinLarge", /** * @remarks * [Api set: WordApi] */ wave = "Wave", /** * @remarks * [Api set: WordApi] */ doubleWave = "DoubleWave", /** * @remarks * [Api set: WordApi] */ dashedSmall = "DashedSmall", /** * @remarks * [Api set: WordApi] */ dashDotStroked = "DashDotStroked", /** * @remarks * [Api set: WordApi] */ threeDEmboss = "ThreeDEmboss", /** * @remarks * [Api set: WordApi] */ threeDEngrave = "ThreeDEngrave", } /** * @remarks * [Api set: WordApi] */ enum VerticalAlignment { /** * @remarks * [Api set: WordApi] */ mixed = "Mixed", /** * @remarks * [Api set: WordApi] */ top = "Top", /** * @remarks * [Api set: WordApi] */ center = "Center", /** * @remarks * [Api set: WordApi] */ bottom = "Bottom", } /** * @remarks * [Api set: WordApi] */ enum ListLevelType { /** * @remarks * [Api set: WordApi] */ bullet = "Bullet", /** * @remarks * [Api set: WordApi] */ number = "Number", /** * @remarks * [Api set: WordApi] */ picture = "Picture", } /** * @remarks * [Api set: WordApi] */ enum ListBullet { /** * @remarks * [Api set: WordApi] */ custom = "Custom", /** * @remarks * [Api set: WordApi] */ solid = "Solid", /** * @remarks * [Api set: WordApi] */ hollow = "Hollow", /** * @remarks * [Api set: WordApi] */ square = "Square", /** * @remarks * [Api set: WordApi] */ diamonds = "Diamonds", /** * @remarks * [Api set: WordApi] */ arrow = "Arrow", /** * @remarks * [Api set: WordApi] */ checkmark = "Checkmark", } /** * @remarks * [Api set: WordApi] */ enum ListNumbering { /** * @remarks * [Api set: WordApi] */ none = "None", /** * @remarks * [Api set: WordApi] */ arabic = "Arabic", /** * @remarks * [Api set: WordApi] */ upperRoman = "UpperRoman", /** * @remarks * [Api set: WordApi] */ lowerRoman = "LowerRoman", /** * @remarks * [Api set: WordApi] */ upperLetter = "UpperLetter", /** * @remarks * [Api set: WordApi] */ lowerLetter = "LowerLetter", } /** * @remarks * [Api set: WordApi] */ enum Style { /** * Mixed styles or other style not in this list. * @remarks * [Api set: WordApi] */ other = "Other", /** * Reset character and paragraph style to default. * @remarks * [Api set: WordApi] */ normal = "Normal", /** * @remarks * [Api set: WordApi] */ heading1 = "Heading1", /** * @remarks * [Api set: WordApi] */ heading2 = "Heading2", /** * @remarks * [Api set: WordApi] */ heading3 = "Heading3", /** * @remarks * [Api set: WordApi] */ heading4 = "Heading4", /** * @remarks * [Api set: WordApi] */ heading5 = "Heading5", /** * @remarks * [Api set: WordApi] */ heading6 = "Heading6", /** * @remarks * [Api set: WordApi] */ heading7 = "Heading7", /** * @remarks * [Api set: WordApi] */ heading8 = "Heading8", /** * @remarks * [Api set: WordApi] */ heading9 = "Heading9", /** * Table-of-content level 1. * @remarks * [Api set: WordApi] */ toc1 = "Toc1", /** * Table-of-content level 2. * @remarks * [Api set: WordApi] */ toc2 = "Toc2", /** * Table-of-content level 3. * @remarks * [Api set: WordApi] */ toc3 = "Toc3", /** * Table-of-content level 4. * @remarks * [Api set: WordApi] */ toc4 = "Toc4", /** * Table-of-content level 5. * @remarks * [Api set: WordApi] */ toc5 = "Toc5", /** * Table-of-content level 6. * @remarks * [Api set: WordApi] */ toc6 = "Toc6", /** * Table-of-content level 7. * @remarks * [Api set: WordApi] */ toc7 = "Toc7", /** * Table-of-content level 8. * @remarks * [Api set: WordApi] */ toc8 = "Toc8", /** * Table-of-content level 9. * @remarks * [Api set: WordApi] */ toc9 = "Toc9", /** * @remarks * [Api set: WordApi] */ footnoteText = "FootnoteText", /** * @remarks * [Api set: WordApi] */ header = "Header", /** * @remarks * [Api set: WordApi] */ footer = "Footer", /** * @remarks * [Api set: WordApi] */ caption = "Caption", /** * @remarks * [Api set: WordApi] */ footnoteReference = "FootnoteReference", /** * @remarks * [Api set: WordApi] */ endnoteReference = "EndnoteReference", /** * @remarks * [Api set: WordApi] */ endnoteText = "EndnoteText", /** * @remarks * [Api set: WordApi] */ title = "Title", /** * @remarks * [Api set: WordApi] */ subtitle = "Subtitle", /** * @remarks * [Api set: WordApi] */ hyperlink = "Hyperlink", /** * @remarks * [Api set: WordApi] */ strong = "Strong", /** * @remarks * [Api set: WordApi] */ emphasis = "Emphasis", /** * @remarks * [Api set: WordApi] */ noSpacing = "NoSpacing", /** * @remarks * [Api set: WordApi] */ listParagraph = "ListParagraph", /** * @remarks * [Api set: WordApi] */ quote = "Quote", /** * @remarks * [Api set: WordApi] */ intenseQuote = "IntenseQuote", /** * @remarks * [Api set: WordApi] */ subtleEmphasis = "SubtleEmphasis", /** * @remarks * [Api set: WordApi] */ intenseEmphasis = "IntenseEmphasis", /** * @remarks * [Api set: WordApi] */ subtleReference = "SubtleReference", /** * @remarks * [Api set: WordApi] */ intenseReference = "IntenseReference", /** * @remarks * [Api set: WordApi] */ bookTitle = "BookTitle", /** * @remarks * [Api set: WordApi] */ bibliography = "Bibliography", /** * Table-of-content heading. * @remarks * [Api set: WordApi] */ tocHeading = "TocHeading", /** * @remarks * [Api set: WordApi] */ tableGrid = "TableGrid", /** * @remarks * [Api set: WordApi] */ plainTable1 = "PlainTable1", /** * @remarks * [Api set: WordApi] */ plainTable2 = "PlainTable2", /** * @remarks * [Api set: WordApi] */ plainTable3 = "PlainTable3", /** * @remarks * [Api set: WordApi] */ plainTable4 = "PlainTable4", /** * @remarks * [Api set: WordApi] */ plainTable5 = "PlainTable5", /** * @remarks * [Api set: WordApi] */ tableGridLight = "TableGridLight", /** * @remarks * [Api set: WordApi] */ gridTable1Light = "GridTable1Light", /** * @remarks * [Api set: WordApi] */ gridTable1Light_Accent1 = "GridTable1Light_Accent1", /** * @remarks * [Api set: WordApi] */ gridTable1Light_Accent2 = "GridTable1Light_Accent2", /** * @remarks * [Api set: WordApi] */ gridTable1Light_Accent3 = "GridTable1Light_Accent3", /** * @remarks * [Api set: WordApi] */ gridTable1Light_Accent4 = "GridTable1Light_Accent4", /** * @remarks * [Api set: WordApi] */ gridTable1Light_Accent5 = "GridTable1Light_Accent5", /** * @remarks * [Api set: WordApi] */ gridTable1Light_Accent6 = "GridTable1Light_Accent6", /** * @remarks * [Api set: WordApi] */ gridTable2 = "GridTable2", /** * @remarks * [Api set: WordApi] */ gridTable2_Accent1 = "GridTable2_Accent1", /** * @remarks * [Api set: WordApi] */ gridTable2_Accent2 = "GridTable2_Accent2", /** * @remarks * [Api set: WordApi] */ gridTable2_Accent3 = "GridTable2_Accent3", /** * @remarks * [Api set: WordApi] */ gridTable2_Accent4 = "GridTable2_Accent4", /** * @remarks * [Api set: WordApi] */ gridTable2_Accent5 = "GridTable2_Accent5", /** * @remarks * [Api set: WordApi] */ gridTable2_Accent6 = "GridTable2_Accent6", /** * @remarks * [Api set: WordApi] */ gridTable3 = "GridTable3", /** * @remarks * [Api set: WordApi] */ gridTable3_Accent1 = "GridTable3_Accent1", /** * @remarks * [Api set: WordApi] */ gridTable3_Accent2 = "GridTable3_Accent2", /** * @remarks * [Api set: WordApi] */ gridTable3_Accent3 = "GridTable3_Accent3", /** * @remarks * [Api set: WordApi] */ gridTable3_Accent4 = "GridTable3_Accent4", /** * @remarks * [Api set: WordApi] */ gridTable3_Accent5 = "GridTable3_Accent5", /** * @remarks * [Api set: WordApi] */ gridTable3_Accent6 = "GridTable3_Accent6", /** * @remarks * [Api set: WordApi] */ gridTable4 = "GridTable4", /** * @remarks * [Api set: WordApi] */ gridTable4_Accent1 = "GridTable4_Accent1", /** * @remarks * [Api set: WordApi] */ gridTable4_Accent2 = "GridTable4_Accent2", /** * @remarks * [Api set: WordApi] */ gridTable4_Accent3 = "GridTable4_Accent3", /** * @remarks * [Api set: WordApi] */ gridTable4_Accent4 = "GridTable4_Accent4", /** * @remarks * [Api set: WordApi] */ gridTable4_Accent5 = "GridTable4_Accent5", /** * @remarks * [Api set: WordApi] */ gridTable4_Accent6 = "GridTable4_Accent6", /** * @remarks * [Api set: WordApi] */ gridTable5Dark = "GridTable5Dark", /** * @remarks * [Api set: WordApi] */ gridTable5Dark_Accent1 = "GridTable5Dark_Accent1", /** * @remarks * [Api set: WordApi] */ gridTable5Dark_Accent2 = "GridTable5Dark_Accent2", /** * @remarks * [Api set: WordApi] */ gridTable5Dark_Accent3 = "GridTable5Dark_Accent3", /** * @remarks * [Api set: WordApi] */ gridTable5Dark_Accent4 = "GridTable5Dark_Accent4", /** * @remarks * [Api set: WordApi] */ gridTable5Dark_Accent5 = "GridTable5Dark_Accent5", /** * @remarks * [Api set: WordApi] */ gridTable5Dark_Accent6 = "GridTable5Dark_Accent6", /** * @remarks * [Api set: WordApi] */ gridTable6Colorful = "GridTable6Colorful", /** * @remarks * [Api set: WordApi] */ gridTable6Colorful_Accent1 = "GridTable6Colorful_Accent1", /** * @remarks * [Api set: WordApi] */ gridTable6Colorful_Accent2 = "GridTable6Colorful_Accent2", /** * @remarks * [Api set: WordApi] */ gridTable6Colorful_Accent3 = "GridTable6Colorful_Accent3", /** * @remarks * [Api set: WordApi] */ gridTable6Colorful_Accent4 = "GridTable6Colorful_Accent4", /** * @remarks * [Api set: WordApi] */ gridTable6Colorful_Accent5 = "GridTable6Colorful_Accent5", /** * @remarks * [Api set: WordApi] */ gridTable6Colorful_Accent6 = "GridTable6Colorful_Accent6", /** * @remarks * [Api set: WordApi] */ gridTable7Colorful = "GridTable7Colorful", /** * @remarks * [Api set: WordApi] */ gridTable7Colorful_Accent1 = "GridTable7Colorful_Accent1", /** * @remarks * [Api set: WordApi] */ gridTable7Colorful_Accent2 = "GridTable7Colorful_Accent2", /** * @remarks * [Api set: WordApi] */ gridTable7Colorful_Accent3 = "GridTable7Colorful_Accent3", /** * @remarks * [Api set: WordApi] */ gridTable7Colorful_Accent4 = "GridTable7Colorful_Accent4", /** * @remarks * [Api set: WordApi] */ gridTable7Colorful_Accent5 = "GridTable7Colorful_Accent5", /** * @remarks * [Api set: WordApi] */ gridTable7Colorful_Accent6 = "GridTable7Colorful_Accent6", /** * @remarks * [Api set: WordApi] */ listTable1Light = "ListTable1Light", /** * @remarks * [Api set: WordApi] */ listTable1Light_Accent1 = "ListTable1Light_Accent1", /** * @remarks * [Api set: WordApi] */ listTable1Light_Accent2 = "ListTable1Light_Accent2", /** * @remarks * [Api set: WordApi] */ listTable1Light_Accent3 = "ListTable1Light_Accent3", /** * @remarks * [Api set: WordApi] */ listTable1Light_Accent4 = "ListTable1Light_Accent4", /** * @remarks * [Api set: WordApi] */ listTable1Light_Accent5 = "ListTable1Light_Accent5", /** * @remarks * [Api set: WordApi] */ listTable1Light_Accent6 = "ListTable1Light_Accent6", /** * @remarks * [Api set: WordApi] */ listTable2 = "ListTable2", /** * @remarks * [Api set: WordApi] */ listTable2_Accent1 = "ListTable2_Accent1", /** * @remarks * [Api set: WordApi] */ listTable2_Accent2 = "ListTable2_Accent2", /** * @remarks * [Api set: WordApi] */ listTable2_Accent3 = "ListTable2_Accent3", /** * @remarks * [Api set: WordApi] */ listTable2_Accent4 = "ListTable2_Accent4", /** * @remarks * [Api set: WordApi] */ listTable2_Accent5 = "ListTable2_Accent5", /** * @remarks * [Api set: WordApi] */ listTable2_Accent6 = "ListTable2_Accent6", /** * @remarks * [Api set: WordApi] */ listTable3 = "ListTable3", /** * @remarks * [Api set: WordApi] */ listTable3_Accent1 = "ListTable3_Accent1", /** * @remarks * [Api set: WordApi] */ listTable3_Accent2 = "ListTable3_Accent2", /** * @remarks * [Api set: WordApi] */ listTable3_Accent3 = "ListTable3_Accent3", /** * @remarks * [Api set: WordApi] */ listTable3_Accent4 = "ListTable3_Accent4", /** * @remarks * [Api set: WordApi] */ listTable3_Accent5 = "ListTable3_Accent5", /** * @remarks * [Api set: WordApi] */ listTable3_Accent6 = "ListTable3_Accent6", /** * @remarks * [Api set: WordApi] */ listTable4 = "ListTable4", /** * @remarks * [Api set: WordApi] */ listTable4_Accent1 = "ListTable4_Accent1", /** * @remarks * [Api set: WordApi] */ listTable4_Accent2 = "ListTable4_Accent2", /** * @remarks * [Api set: WordApi] */ listTable4_Accent3 = "ListTable4_Accent3", /** * @remarks * [Api set: WordApi] */ listTable4_Accent4 = "ListTable4_Accent4", /** * @remarks * [Api set: WordApi] */ listTable4_Accent5 = "ListTable4_Accent5", /** * @remarks * [Api set: WordApi] */ listTable4_Accent6 = "ListTable4_Accent6", /** * @remarks * [Api set: WordApi] */ listTable5Dark = "ListTable5Dark", /** * @remarks * [Api set: WordApi] */ listTable5Dark_Accent1 = "ListTable5Dark_Accent1", /** * @remarks * [Api set: WordApi] */ listTable5Dark_Accent2 = "ListTable5Dark_Accent2", /** * @remarks * [Api set: WordApi] */ listTable5Dark_Accent3 = "ListTable5Dark_Accent3", /** * @remarks * [Api set: WordApi] */ listTable5Dark_Accent4 = "ListTable5Dark_Accent4", /** * @remarks * [Api set: WordApi] */ listTable5Dark_Accent5 = "ListTable5Dark_Accent5", /** * @remarks * [Api set: WordApi] */ listTable5Dark_Accent6 = "ListTable5Dark_Accent6", /** * @remarks * [Api set: WordApi] */ listTable6Colorful = "ListTable6Colorful", /** * @remarks * [Api set: WordApi] */ listTable6Colorful_Accent1 = "ListTable6Colorful_Accent1", /** * @remarks * [Api set: WordApi] */ listTable6Colorful_Accent2 = "ListTable6Colorful_Accent2", /** * @remarks * [Api set: WordApi] */ listTable6Colorful_Accent3 = "ListTable6Colorful_Accent3", /** * @remarks * [Api set: WordApi] */ listTable6Colorful_Accent4 = "ListTable6Colorful_Accent4", /** * @remarks * [Api set: WordApi] */ listTable6Colorful_Accent5 = "ListTable6Colorful_Accent5", /** * @remarks * [Api set: WordApi] */ listTable6Colorful_Accent6 = "ListTable6Colorful_Accent6", /** * @remarks * [Api set: WordApi] */ listTable7Colorful = "ListTable7Colorful", /** * @remarks * [Api set: WordApi] */ listTable7Colorful_Accent1 = "ListTable7Colorful_Accent1", /** * @remarks * [Api set: WordApi] */ listTable7Colorful_Accent2 = "ListTable7Colorful_Accent2", /** * @remarks * [Api set: WordApi] */ listTable7Colorful_Accent3 = "ListTable7Colorful_Accent3", /** * @remarks * [Api set: WordApi] */ listTable7Colorful_Accent4 = "ListTable7Colorful_Accent4", /** * @remarks * [Api set: WordApi] */ listTable7Colorful_Accent5 = "ListTable7Colorful_Accent5", /** * @remarks * [Api set: WordApi] */ listTable7Colorful_Accent6 = "ListTable7Colorful_Accent6", } /** * @remarks * [Api set: WordApi] */ enum DocumentPropertyType { /** * @remarks * [Api set: WordApi] */ string = "String", /** * @remarks * [Api set: WordApi] */ number = "Number", /** * @remarks * [Api set: WordApi] */ date = "Date", /** * @remarks * [Api set: WordApi] */ boolean = "Boolean", } /** * @remarks * [Api set: WordApi] */ enum TapObjectType { /** * @remarks * [Api set: WordApi] */ chart = "Chart", /** * @remarks * [Api set: WordApi] */ smartArt = "SmartArt", /** * @remarks * [Api set: WordApi] */ table = "Table", /** * @remarks * [Api set: WordApi] */ image = "Image", /** * @remarks * [Api set: WordApi] */ slide = "Slide", /** * @remarks * [Api set: WordApi] */ ole = "OLE", /** * @remarks * [Api set: WordApi] */ text = "Text", } /** * @remarks * [Api set: WordApi] */ enum FileContentFormat { /** * @remarks * [Api set: WordApi] */ base64 = "Base64", /** * @remarks * [Api set: WordApi] */ html = "Html", /** * @remarks * [Api set: WordApi] */ ooxml = "Ooxml", } enum ErrorCodes { accessDenied = "AccessDenied", generalException = "GeneralException", invalidArgument = "InvalidArgument", itemNotFound = "ItemNotFound", notImplemented = "NotImplemented", searchDialogIsOpen = "SearchDialogIsOpen", searchStringInvalidOrTooLong = "SearchStringInvalidOrTooLong", } export module Interfaces { /** * Provides ways to load properties of only a subset of members of a collection. */ export interface CollectionLoadOptions { /** * Specify the number of items in the queried collection to be included in the result. */ $top?: number; /** * Specify the number of items in the collection that are to be skipped and not included in the result. If top is specified, the selection of result will start after skipping the specified number of items. */ $skip?: number; } /** An interface for updating data on the Body object, for use in `body.set({ ... })`. */ export interface BodyUpdateData { /** * Gets the text format of the body. Use this to get and set font name, size, color and other properties. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontUpdateData; /** * Gets or sets the style name for the body. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: string; } /** An interface for updating data on the ContentControl object, for use in `contentControl.set({ ... })`. */ export interface ContentControlUpdateData { /** * Gets the text format of the content control. Use this to get and set font name, size, color, and other properties. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontUpdateData; /** * Gets or sets the appearance of the content control. The value can be 'BoundingBox', 'Tags', or 'Hidden'. * * @remarks * [Api set: WordApi 1.1] */ appearance?: Word.ContentControlAppearance | "BoundingBox" | "Tags" | "Hidden"; /** * Gets or sets a value that indicates whether the user can delete the content control. Mutually exclusive with removeWhenEdited. * * @remarks * [Api set: WordApi 1.1] */ cannotDelete?: boolean; /** * Gets or sets a value that indicates whether the user can edit the contents of the content control. * * @remarks * [Api set: WordApi 1.1] */ cannotEdit?: boolean; /** * Gets or sets the color of the content control. Color is specified in '#RRGGBB' format or by using the color name. * * @remarks * [Api set: WordApi 1.1] */ color?: string; /** * Gets or sets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty. * * **Note**: The set operation for this property is not supported in Word on the web. * * @remarks * [Api set: WordApi 1.1] */ placeholderText?: string; /** * Gets or sets a value that indicates whether the content control is removed after it is edited. Mutually exclusive with cannotDelete. * * @remarks * [Api set: WordApi 1.1] */ removeWhenEdited?: boolean; /** * Gets or sets the style name for the content control. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: string; /** * Gets or sets a tag to identify a content control. * * @remarks * [Api set: WordApi 1.1] */ tag?: string; /** * Gets or sets the title for a content control. * * @remarks * [Api set: WordApi 1.1] */ title?: string; } /** An interface for updating data on the ContentControlCollection object, for use in `contentControlCollection.set({ ... })`. */ export interface ContentControlCollectionUpdateData { items?: Word.Interfaces.ContentControlData[]; } /** An interface for updating data on the CustomProperty object, for use in `customProperty.set({ ... })`. */ export interface CustomPropertyUpdateData { } /** An interface for updating data on the CustomPropertyCollection object, for use in `customPropertyCollection.set({ ... })`. */ export interface CustomPropertyCollectionUpdateData { items?: Word.Interfaces.CustomPropertyData[]; } /** An interface for updating data on the Document object, for use in `document.set({ ... })`. */ export interface DocumentUpdateData { /** * Gets the body object of the main document. The body is the text that excludes headers, footers, footnotes, textboxes, etc.. * * @remarks * [Api set: WordApi 1.1] */ body?: Word.Interfaces.BodyUpdateData; } /** An interface for updating data on the DocumentCreated object, for use in `documentCreated.set({ ... })`. */ export interface DocumentCreatedUpdateData { /** * Gets the body object of the document. The body is the text that excludes headers, footers, footnotes, textboxes, etc.. * * @remarks * [Api set: WordApiHiddenDocument 1.3] */ body?: Word.Interfaces.BodyUpdateData; /** * Gets the properties of the document. * * @remarks * [Api set: WordApiHiddenDocument 1.3] */ properties?: Word.Interfaces.DocumentPropertiesUpdateData; } /** An interface for updating data on the DocumentProperties object, for use in `documentProperties.set({ ... })`. */ export interface DocumentPropertiesUpdateData { } /** An interface for updating data on the Font object, for use in `font.set({ ... })`. */ export interface FontUpdateData { /** * Gets or sets a value that indicates whether the font is bold. True if the font is formatted as bold, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ bold?: boolean; /** * Gets or sets the color for the specified font. You can provide the value in the '#RRGGBB' format or the color name. * * @remarks * [Api set: WordApi 1.1] */ color?: string; /** * Gets or sets a value that indicates whether the font has a double strikethrough. True if the font is formatted as double strikethrough text, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ doubleStrikeThrough?: boolean; /** * Gets or sets the highlight color. To set it, use a value either in the '#RRGGBB' format or the color name. To remove highlight color, set it to null. The returned highlight color can be in the '#RRGGBB' format, an empty string for mixed highlight colors, or null for no highlight color. **Note**: Only the default highlight colors are available in Office for Windows Desktop. These are "Yellow", "Lime", "Turquoise", "Pink", "Blue", "Red", "DarkBlue", "Teal", "Green", "Purple", "DarkRed", "Olive", "Gray", "LightGray", and "Black". When the add-in runs in Office for Windows Desktop, any other color is converted to the closest color when applied to the font. * * @remarks * [Api set: WordApi 1.1] */ highlightColor?: string; /** * Gets or sets a value that indicates whether the font is italicized. True if the font is italicized, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ italic?: boolean; /** * Gets or sets a value that represents the name of the font. * * @remarks * [Api set: WordApi 1.1] */ name?: string; /** * Gets or sets a value that represents the font size in points. * * @remarks * [Api set: WordApi 1.1] */ size?: number; /** * Gets or sets a value that indicates whether the font has a strikethrough. True if the font is formatted as strikethrough text, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ strikeThrough?: boolean; /** * Gets or sets a value that indicates whether the font is a subscript. True if the font is formatted as subscript, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ subscript?: boolean; /** * Gets or sets a value that indicates whether the font is a superscript. True if the font is formatted as superscript, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ superscript?: boolean; /** * Gets or sets a value that indicates the font's underline type. 'None' if the font is not underlined. * * @remarks * [Api set: WordApi 1.1] */ underline?: Word.UnderlineType | "Mixed" | "None" | "Hidden" | "DotLine" | "Single" | "Word" | "Double" | "Thick" | "Dotted" | "DottedHeavy" | "DashLine" | "DashLineHeavy" | "DashLineLong" | "DashLineLongHeavy" | "DotDashLine" | "DotDashLineHeavy" | "TwoDotDashLine" | "TwoDotDashLineHeavy" | "Wave" | "WaveHeavy" | "WaveDouble"; } /** An interface for updating data on the InlinePicture object, for use in `inlinePicture.set({ ... })`. */ export interface InlinePictureUpdateData { /** * Gets or sets a string that represents the alternative text associated with the inline image. * * @remarks * [Api set: WordApi 1.1] */ altTextDescription?: string; /** * Gets or sets a string that contains the title for the inline image. * * @remarks * [Api set: WordApi 1.1] */ altTextTitle?: string; /** * Gets or sets a number that describes the height of the inline image. * * @remarks * [Api set: WordApi 1.1] */ height?: number; /** * Gets or sets a hyperlink on the image. Use a '#' to separate the address part from the optional location part. * * @remarks * [Api set: WordApi 1.1] */ hyperlink?: string; /** * Gets or sets a value that indicates whether the inline image retains its original proportions when you resize it. * * @remarks * [Api set: WordApi 1.1] */ lockAspectRatio?: boolean; /** * Gets or sets a number that describes the width of the inline image. * * @remarks * [Api set: WordApi 1.1] */ width?: number; } /** An interface for updating data on the InlinePictureCollection object, for use in `inlinePictureCollection.set({ ... })`. */ export interface InlinePictureCollectionUpdateData { items?: Word.Interfaces.InlinePictureData[]; } /** An interface for updating data on the ListCollection object, for use in `listCollection.set({ ... })`. */ export interface ListCollectionUpdateData { items?: Word.Interfaces.ListData[]; } /** An interface for updating data on the ListItem object, for use in `listItem.set({ ... })`. */ export interface ListItemUpdateData { } /** An interface for updating data on the Paragraph object, for use in `paragraph.set({ ... })`. */ export interface ParagraphUpdateData { /** * Gets the text format of the paragraph. Use this to get and set font name, size, color, and other properties. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontUpdateData; /** * Gets or sets the alignment for a paragraph. The value can be 'left', 'centered', 'right', or 'justified'. * * @remarks * [Api set: WordApi 1.1] */ alignment?: Word.Alignment | "Mixed" | "Unknown" | "Left" | "Centered" | "Right" | "Justified"; /** * Gets or sets the value, in points, for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent. * * @remarks * [Api set: WordApi 1.1] */ firstLineIndent?: number; /** * Gets or sets the left indent value, in points, for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ leftIndent?: number; /** * Gets or sets the line spacing, in points, for the specified paragraph. In the Word UI, this value is divided by 12. * * @remarks * [Api set: WordApi 1.1] */ lineSpacing?: number; /** * Gets or sets the amount of spacing, in grid lines, after the paragraph. * * @remarks * [Api set: WordApi 1.1] */ lineUnitAfter?: number; /** * Gets or sets the amount of spacing, in grid lines, before the paragraph. * * @remarks * [Api set: WordApi 1.1] */ lineUnitBefore?: number; /** * Gets or sets the outline level for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ outlineLevel?: number; /** * Gets or sets the right indent value, in points, for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ rightIndent?: number; /** * Gets or sets the spacing, in points, after the paragraph. * * @remarks * [Api set: WordApi 1.1] */ spaceAfter?: number; /** * Gets or sets the spacing, in points, before the paragraph. * * @remarks * [Api set: WordApi 1.1] */ spaceBefore?: number; /** * Gets or sets the style name for the paragraph. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: string; } /** An interface for updating data on the ParagraphCollection object, for use in `paragraphCollection.set({ ... })`. */ export interface ParagraphCollectionUpdateData { items?: Word.Interfaces.ParagraphData[]; } /** An interface for updating data on the Range object, for use in `range.set({ ... })`. */ export interface RangeUpdateData { /** * Gets the text format of the range. Use this to get and set font name, size, color, and other properties. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontUpdateData; /** * Gets or sets the style name for the range. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: string; } /** An interface for updating data on the RangeCollection object, for use in `rangeCollection.set({ ... })`. */ export interface RangeCollectionUpdateData { items?: Word.Interfaces.RangeData[]; } /** An interface for updating data on the SearchOptions object, for use in `searchOptions.set({ ... })`. */ export interface SearchOptionsUpdateData { /** * Gets or sets a value that indicates whether to ignore all punctuation characters between words. Corresponds to the Ignore punctuation check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ ignorePunct?: boolean; /** * Gets or sets a value that indicates whether to ignore all whitespace between words. Corresponds to the Ignore whitespace characters check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ ignoreSpace?: boolean; /** * Gets or sets a value that indicates whether to perform a case sensitive search. Corresponds to the Match case check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchCase?: boolean; /** * Gets or sets a value that indicates whether to match words that begin with the search string. Corresponds to the Match prefix check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchPrefix?: boolean; /** * Gets or sets a value that indicates whether to match words that end with the search string. Corresponds to the Match suffix check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchSuffix?: boolean; /** * Gets or sets a value that indicates whether to find operation only entire words, not text that is part of a larger word. Corresponds to the Find whole words only check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchWholeWord?: boolean; /** * Gets or sets a value that indicates whether the search will be performed using special search operators. Corresponds to the Use wildcards check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchWildcards?: boolean; } /** An interface for updating data on the Section object, for use in `section.set({ ... })`. */ export interface SectionUpdateData { /** * Gets the body object of the section. This does not include the header/footer and other section metadata. * * @remarks * [Api set: WordApi 1.1] */ body?: Word.Interfaces.BodyUpdateData; } /** An interface for updating data on the SectionCollection object, for use in `sectionCollection.set({ ... })`. */ export interface SectionCollectionUpdateData { items?: Word.Interfaces.SectionData[]; } /** An interface for updating data on the Table object, for use in `table.set({ ... })`. */ export interface TableUpdateData { } /** An interface for updating data on the TableCollection object, for use in `tableCollection.set({ ... })`. */ export interface TableCollectionUpdateData { items?: Word.Interfaces.TableData[]; } /** An interface for updating data on the TableRow object, for use in `tableRow.set({ ... })`. */ export interface TableRowUpdateData { } /** An interface for updating data on the TableRowCollection object, for use in `tableRowCollection.set({ ... })`. */ export interface TableRowCollectionUpdateData { items?: Word.Interfaces.TableRowData[]; } /** An interface for updating data on the TableCell object, for use in `tableCell.set({ ... })`. */ export interface TableCellUpdateData { } /** An interface for updating data on the TableCellCollection object, for use in `tableCellCollection.set({ ... })`. */ export interface TableCellCollectionUpdateData { items?: Word.Interfaces.TableCellData[]; } /** An interface for updating data on the TableBorder object, for use in `tableBorder.set({ ... })`. */ export interface TableBorderUpdateData { } /** An interface describing the data returned by calling `body.toJSON()`. */ export interface BodyData { /** * Gets the collection of rich text content control objects in the body. Read-only. * * @remarks * [Api set: WordApi 1.1] */ contentControls?: Word.Interfaces.ContentControlData[]; /** * Gets the text format of the body. Use this to get and set font name, size, color and other properties. Read-only. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontData; /** * Gets the collection of InlinePicture objects in the body. The collection does not include floating images. Read-only. * * @remarks * [Api set: WordApi 1.1] */ inlinePictures?: Word.Interfaces.InlinePictureData[]; /** * Gets the collection of paragraph objects in the body. Read-only. * * @remarks * [Api set: WordApi 1.1] */ paragraphs?: Word.Interfaces.ParagraphData[]; /** * Gets or sets the style name for the body. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: string; /** * Gets the text of the body. Use the insertText method to insert text. Read-only. * * @remarks * [Api set: WordApi 1.1] */ text?: string; } /** An interface describing the data returned by calling `contentControl.toJSON()`. */ export interface ContentControlData { /** * Gets the collection of content control objects in the content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ contentControls?: Word.Interfaces.ContentControlData[]; /** * Gets the text format of the content control. Use this to get and set font name, size, color, and other properties. Read-only. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontData; /** * Gets the collection of inlinePicture objects in the content control. The collection does not include floating images. Read-only. * * @remarks * [Api set: WordApi 1.1] */ inlinePictures?: Word.Interfaces.InlinePictureData[]; /** * Get the collection of paragraph objects in the content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ paragraphs?: Word.Interfaces.ParagraphData[]; /** * Gets or sets the appearance of the content control. The value can be 'BoundingBox', 'Tags', or 'Hidden'. * * @remarks * [Api set: WordApi 1.1] */ appearance?: Word.ContentControlAppearance | "BoundingBox" | "Tags" | "Hidden"; /** * Gets or sets a value that indicates whether the user can delete the content control. Mutually exclusive with removeWhenEdited. * * @remarks * [Api set: WordApi 1.1] */ cannotDelete?: boolean; /** * Gets or sets a value that indicates whether the user can edit the contents of the content control. * * @remarks * [Api set: WordApi 1.1] */ cannotEdit?: boolean; /** * Gets or sets the color of the content control. Color is specified in '#RRGGBB' format or by using the color name. * * @remarks * [Api set: WordApi 1.1] */ color?: string; /** * Gets an integer that represents the content control identifier. Read-only. * * @remarks * [Api set: WordApi 1.1] */ id?: number; /** * Gets or sets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty. * * **Note**: The set operation for this property is not supported in Word on the web. * * @remarks * [Api set: WordApi 1.1] */ placeholderText?: string; /** * Gets or sets a value that indicates whether the content control is removed after it is edited. Mutually exclusive with cannotDelete. * * @remarks * [Api set: WordApi 1.1] */ removeWhenEdited?: boolean; /** * Gets or sets the style name for the content control. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: string; /** * Gets or sets a tag to identify a content control. * * @remarks * [Api set: WordApi 1.1] */ tag?: string; /** * Gets the text of the content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ text?: string; /** * Gets or sets the title for a content control. * * @remarks * [Api set: WordApi 1.1] */ title?: string; /** * Gets the content control type. Only rich text content controls are supported currently. Read-only. * * @remarks * [Api set: WordApi 1.1] */ type?: Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText"; } /** An interface describing the data returned by calling `contentControlCollection.toJSON()`. */ export interface ContentControlCollectionData { items?: Word.Interfaces.ContentControlData[]; } /** An interface describing the data returned by calling `customProperty.toJSON()`. */ export interface CustomPropertyData { } /** An interface describing the data returned by calling `customPropertyCollection.toJSON()`. */ export interface CustomPropertyCollectionData { items?: Word.Interfaces.CustomPropertyData[]; } /** An interface describing the data returned by calling `document.toJSON()`. */ export interface DocumentData { /** * Gets the body object of the main document. The body is the text that excludes headers, footers, footnotes, textboxes, etc.. Read-only. * * @remarks * [Api set: WordApi 1.1] */ body?: Word.Interfaces.BodyData; /** * Gets the collection of content control objects in the document. This includes content controls in the body of the document, headers, footers, textboxes, etc.. Read-only. * * @remarks * [Api set: WordApi 1.1] */ contentControls?: Word.Interfaces.ContentControlData[]; /** * Gets the collection of section objects in the document. Read-only. * * @remarks * [Api set: WordApi 1.1] */ sections?: Word.Interfaces.SectionData[]; /** * Indicates whether the changes in the document have been saved. A value of true indicates that the document hasn't changed since it was saved. Read-only. * * @remarks * [Api set: WordApi 1.1] */ saved?: boolean; } /** An interface describing the data returned by calling `documentCreated.toJSON()`. */ export interface DocumentCreatedData { /** * Gets the body object of the document. The body is the text that excludes headers, footers, footnotes, textboxes, etc.. Read-only. * * @remarks * [Api set: WordApiHiddenDocument 1.3] */ body?: Word.Interfaces.BodyData; /** * Gets the collection of content control objects in the document. This includes content controls in the body of the document, headers, footers, textboxes, etc.. Read-only. * * @remarks * [Api set: WordApiHiddenDocument 1.3] */ contentControls?: Word.Interfaces.ContentControlData[]; /** * Gets the properties of the document. Read-only. * * @remarks * [Api set: WordApiHiddenDocument 1.3] */ properties?: Word.Interfaces.DocumentPropertiesData; /** * Gets the collection of section objects in the document. Read-only. * * @remarks * [Api set: WordApiHiddenDocument 1.3] */ sections?: Word.Interfaces.SectionData[]; /** * Indicates whether the changes in the document have been saved. A value of true indicates that the document hasn't changed since it was saved. Read-only. * * @remarks * [Api set: WordApiHiddenDocument 1.3] */ saved?: boolean; } /** An interface describing the data returned by calling `documentProperties.toJSON()`. */ export interface DocumentPropertiesData { } /** An interface describing the data returned by calling `font.toJSON()`. */ export interface FontData { /** * Gets or sets a value that indicates whether the font is bold. True if the font is formatted as bold, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ bold?: boolean; /** * Gets or sets the color for the specified font. You can provide the value in the '#RRGGBB' format or the color name. * * @remarks * [Api set: WordApi 1.1] */ color?: string; /** * Gets or sets a value that indicates whether the font has a double strikethrough. True if the font is formatted as double strikethrough text, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ doubleStrikeThrough?: boolean; /** * Gets or sets the highlight color. To set it, use a value either in the '#RRGGBB' format or the color name. To remove highlight color, set it to null. The returned highlight color can be in the '#RRGGBB' format, an empty string for mixed highlight colors, or null for no highlight color. **Note**: Only the default highlight colors are available in Office for Windows Desktop. These are "Yellow", "Lime", "Turquoise", "Pink", "Blue", "Red", "DarkBlue", "Teal", "Green", "Purple", "DarkRed", "Olive", "Gray", "LightGray", and "Black". When the add-in runs in Office for Windows Desktop, any other color is converted to the closest color when applied to the font. * * @remarks * [Api set: WordApi 1.1] */ highlightColor?: string; /** * Gets or sets a value that indicates whether the font is italicized. True if the font is italicized, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ italic?: boolean; /** * Gets or sets a value that represents the name of the font. * * @remarks * [Api set: WordApi 1.1] */ name?: string; /** * Gets or sets a value that represents the font size in points. * * @remarks * [Api set: WordApi 1.1] */ size?: number; /** * Gets or sets a value that indicates whether the font has a strikethrough. True if the font is formatted as strikethrough text, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ strikeThrough?: boolean; /** * Gets or sets a value that indicates whether the font is a subscript. True if the font is formatted as subscript, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ subscript?: boolean; /** * Gets or sets a value that indicates whether the font is a superscript. True if the font is formatted as superscript, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ superscript?: boolean; /** * Gets or sets a value that indicates the font's underline type. 'None' if the font is not underlined. * * @remarks * [Api set: WordApi 1.1] */ underline?: Word.UnderlineType | "Mixed" | "None" | "Hidden" | "DotLine" | "Single" | "Word" | "Double" | "Thick" | "Dotted" | "DottedHeavy" | "DashLine" | "DashLineHeavy" | "DashLineLong" | "DashLineLongHeavy" | "DotDashLine" | "DotDashLineHeavy" | "TwoDotDashLine" | "TwoDotDashLineHeavy" | "Wave" | "WaveHeavy" | "WaveDouble"; } /** An interface describing the data returned by calling `inlinePicture.toJSON()`. */ export interface InlinePictureData { /** * Gets or sets a string that represents the alternative text associated with the inline image. * * @remarks * [Api set: WordApi 1.1] */ altTextDescription?: string; /** * Gets or sets a string that contains the title for the inline image. * * @remarks * [Api set: WordApi 1.1] */ altTextTitle?: string; /** * Gets or sets a number that describes the height of the inline image. * * @remarks * [Api set: WordApi 1.1] */ height?: number; /** * Gets or sets a hyperlink on the image. Use a '#' to separate the address part from the optional location part. * * @remarks * [Api set: WordApi 1.1] */ hyperlink?: string; /** * Gets or sets a value that indicates whether the inline image retains its original proportions when you resize it. * * @remarks * [Api set: WordApi 1.1] */ lockAspectRatio?: boolean; /** * Gets or sets a number that describes the width of the inline image. * * @remarks * [Api set: WordApi 1.1] */ width?: number; } /** An interface describing the data returned by calling `inlinePictureCollection.toJSON()`. */ export interface InlinePictureCollectionData { items?: Word.Interfaces.InlinePictureData[]; } /** An interface describing the data returned by calling `list.toJSON()`. */ export interface ListData { } /** An interface describing the data returned by calling `listCollection.toJSON()`. */ export interface ListCollectionData { items?: Word.Interfaces.ListData[]; } /** An interface describing the data returned by calling `listItem.toJSON()`. */ export interface ListItemData { } /** An interface describing the data returned by calling `paragraph.toJSON()`. */ export interface ParagraphData { /** * Gets the text format of the paragraph. Use this to get and set font name, size, color, and other properties. Read-only. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontData; /** * Gets the collection of InlinePicture objects in the paragraph. The collection does not include floating images. Read-only. * * @remarks * [Api set: WordApi 1.1] */ inlinePictures?: Word.Interfaces.InlinePictureData[]; /** * Gets or sets the alignment for a paragraph. The value can be 'left', 'centered', 'right', or 'justified'. * * @remarks * [Api set: WordApi 1.1] */ alignment?: Word.Alignment | "Mixed" | "Unknown" | "Left" | "Centered" | "Right" | "Justified"; /** * Gets or sets the value, in points, for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent. * * @remarks * [Api set: WordApi 1.1] */ firstLineIndent?: number; /** * Gets or sets the left indent value, in points, for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ leftIndent?: number; /** * Gets or sets the line spacing, in points, for the specified paragraph. In the Word UI, this value is divided by 12. * * @remarks * [Api set: WordApi 1.1] */ lineSpacing?: number; /** * Gets or sets the amount of spacing, in grid lines, after the paragraph. * * @remarks * [Api set: WordApi 1.1] */ lineUnitAfter?: number; /** * Gets or sets the amount of spacing, in grid lines, before the paragraph. * * @remarks * [Api set: WordApi 1.1] */ lineUnitBefore?: number; /** * Gets or sets the outline level for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ outlineLevel?: number; /** * Gets or sets the right indent value, in points, for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ rightIndent?: number; /** * Gets or sets the spacing, in points, after the paragraph. * * @remarks * [Api set: WordApi 1.1] */ spaceAfter?: number; /** * Gets or sets the spacing, in points, before the paragraph. * * @remarks * [Api set: WordApi 1.1] */ spaceBefore?: number; /** * Gets or sets the style name for the paragraph. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: string; /** * Gets the text of the paragraph. Read-only. * * @remarks * [Api set: WordApi 1.1] */ text?: string; } /** An interface describing the data returned by calling `paragraphCollection.toJSON()`. */ export interface ParagraphCollectionData { items?: Word.Interfaces.ParagraphData[]; } /** An interface describing the data returned by calling `range.toJSON()`. */ export interface RangeData { /** * Gets the text format of the range. Use this to get and set font name, size, color, and other properties. Read-only. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontData; /** * Gets the collection of inline picture objects in the range. Read-only. * * @remarks * [Api set: WordApi 1.2] */ inlinePictures?: Word.Interfaces.InlinePictureData[]; /** * Gets or sets the style name for the range. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: string; /** * Gets the text of the range. Read-only. * * @remarks * [Api set: WordApi 1.1] */ text?: string; } /** An interface describing the data returned by calling `rangeCollection.toJSON()`. */ export interface RangeCollectionData { items?: Word.Interfaces.RangeData[]; } /** An interface describing the data returned by calling `searchOptions.toJSON()`. */ export interface SearchOptionsData { /** * Gets or sets a value that indicates whether to ignore all punctuation characters between words. Corresponds to the Ignore punctuation check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ ignorePunct?: boolean; /** * Gets or sets a value that indicates whether to ignore all whitespace between words. Corresponds to the Ignore whitespace characters check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ ignoreSpace?: boolean; /** * Gets or sets a value that indicates whether to perform a case sensitive search. Corresponds to the Match case check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchCase?: boolean; /** * Gets or sets a value that indicates whether to match words that begin with the search string. Corresponds to the Match prefix check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchPrefix?: boolean; /** * Gets or sets a value that indicates whether to match words that end with the search string. Corresponds to the Match suffix check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchSuffix?: boolean; /** * Gets or sets a value that indicates whether to find operation only entire words, not text that is part of a larger word. Corresponds to the Find whole words only check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchWholeWord?: boolean; /** * Gets or sets a value that indicates whether the search will be performed using special search operators. Corresponds to the Use wildcards check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchWildcards?: boolean; } /** An interface describing the data returned by calling `section.toJSON()`. */ export interface SectionData { /** * Gets the body object of the section. This does not include the header/footer and other section metadata. Read-only. * * @remarks * [Api set: WordApi 1.1] */ body?: Word.Interfaces.BodyData; } /** An interface describing the data returned by calling `sectionCollection.toJSON()`. */ export interface SectionCollectionData { items?: Word.Interfaces.SectionData[]; } /** An interface describing the data returned by calling `table.toJSON()`. */ export interface TableData { } /** An interface describing the data returned by calling `tableCollection.toJSON()`. */ export interface TableCollectionData { items?: Word.Interfaces.TableData[]; } /** An interface describing the data returned by calling `tableRow.toJSON()`. */ export interface TableRowData { } /** An interface describing the data returned by calling `tableRowCollection.toJSON()`. */ export interface TableRowCollectionData { items?: Word.Interfaces.TableRowData[]; } /** An interface describing the data returned by calling `tableCell.toJSON()`. */ export interface TableCellData { } /** An interface describing the data returned by calling `tableCellCollection.toJSON()`. */ export interface TableCellCollectionData { items?: Word.Interfaces.TableCellData[]; } /** An interface describing the data returned by calling `tableBorder.toJSON()`. */ export interface TableBorderData { } /** * Represents the body of a document or a section. * * @remarks * [Api set: WordApi 1.1] */ export interface BodyLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * Gets the text format of the body. Use this to get and set font name, size, color and other properties. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontLoadOptions; /** * Gets the content control that contains the body. Throws an error if there isn't a parent content control. * * @remarks * [Api set: WordApi 1.1] */ parentContentControl?: Word.Interfaces.ContentControlLoadOptions; /** * Gets or sets the style name for the body. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: boolean; /** * Gets the text of the body. Use the insertText method to insert text. Read-only. * * @remarks * [Api set: WordApi 1.1] */ text?: boolean; } /** * Represents a content control. Content controls are bounded and potentially labeled regions in a document that serve as containers for specific types of content. Individual content controls may contain contents such as images, tables, or paragraphs of formatted text. Currently, only rich text content controls are supported. * * @remarks * [Api set: WordApi 1.1] */ export interface ContentControlLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * Gets the text format of the content control. Use this to get and set font name, size, color, and other properties. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontLoadOptions; /** * Gets the content control that contains the content control. Throws an error if there isn't a parent content control. * * @remarks * [Api set: WordApi 1.1] */ parentContentControl?: Word.Interfaces.ContentControlLoadOptions; /** * Gets or sets the appearance of the content control. The value can be 'BoundingBox', 'Tags', or 'Hidden'. * * @remarks * [Api set: WordApi 1.1] */ appearance?: boolean; /** * Gets or sets a value that indicates whether the user can delete the content control. Mutually exclusive with removeWhenEdited. * * @remarks * [Api set: WordApi 1.1] */ cannotDelete?: boolean; /** * Gets or sets a value that indicates whether the user can edit the contents of the content control. * * @remarks * [Api set: WordApi 1.1] */ cannotEdit?: boolean; /** * Gets or sets the color of the content control. Color is specified in '#RRGGBB' format or by using the color name. * * @remarks * [Api set: WordApi 1.1] */ color?: boolean; /** * Gets an integer that represents the content control identifier. Read-only. * * @remarks * [Api set: WordApi 1.1] */ id?: boolean; /** * Gets or sets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty. * * **Note**: The set operation for this property is not supported in Word on the web. * * @remarks * [Api set: WordApi 1.1] */ placeholderText?: boolean; /** * Gets or sets a value that indicates whether the content control is removed after it is edited. Mutually exclusive with cannotDelete. * * @remarks * [Api set: WordApi 1.1] */ removeWhenEdited?: boolean; /** * Gets or sets the style name for the content control. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: boolean; /** * Gets or sets a tag to identify a content control. * * @remarks * [Api set: WordApi 1.1] */ tag?: boolean; /** * Gets the text of the content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ text?: boolean; /** * Gets or sets the title for a content control. * * @remarks * [Api set: WordApi 1.1] */ title?: boolean; /** * Gets the content control type. Only rich text content controls are supported currently. Read-only. * * @remarks * [Api set: WordApi 1.1] */ type?: boolean; } /** * Contains a collection of {@link Word.ContentControl} objects. Content controls are bounded and potentially labeled regions in a document that serve as containers for specific types of content. Individual content controls may contain contents such as images, tables, or paragraphs of formatted text. Currently, only rich text content controls are supported. * * @remarks * [Api set: WordApi 1.1] */ export interface ContentControlCollectionLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * For EACH ITEM in the collection: Gets the text format of the content control. Use this to get and set font name, size, color, and other properties. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontLoadOptions; /** * For EACH ITEM in the collection: Gets the content control that contains the content control. Throws an error if there isn't a parent content control. * * @remarks * [Api set: WordApi 1.1] */ parentContentControl?: Word.Interfaces.ContentControlLoadOptions; /** * For EACH ITEM in the collection: Gets or sets the appearance of the content control. The value can be 'BoundingBox', 'Tags', or 'Hidden'. * * @remarks * [Api set: WordApi 1.1] */ appearance?: boolean; /** * For EACH ITEM in the collection: Gets or sets a value that indicates whether the user can delete the content control. Mutually exclusive with removeWhenEdited. * * @remarks * [Api set: WordApi 1.1] */ cannotDelete?: boolean; /** * For EACH ITEM in the collection: Gets or sets a value that indicates whether the user can edit the contents of the content control. * * @remarks * [Api set: WordApi 1.1] */ cannotEdit?: boolean; /** * For EACH ITEM in the collection: Gets or sets the color of the content control. Color is specified in '#RRGGBB' format or by using the color name. * * @remarks * [Api set: WordApi 1.1] */ color?: boolean; /** * For EACH ITEM in the collection: Gets an integer that represents the content control identifier. Read-only. * * @remarks * [Api set: WordApi 1.1] */ id?: boolean; /** * For EACH ITEM in the collection: Gets or sets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty. * * **Note**: The set operation for this property is not supported in Word on the web. * * @remarks * [Api set: WordApi 1.1] */ placeholderText?: boolean; /** * For EACH ITEM in the collection: Gets or sets a value that indicates whether the content control is removed after it is edited. Mutually exclusive with cannotDelete. * * @remarks * [Api set: WordApi 1.1] */ removeWhenEdited?: boolean; /** * For EACH ITEM in the collection: Gets or sets the style name for the content control. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: boolean; /** * For EACH ITEM in the collection: Gets or sets a tag to identify a content control. * * @remarks * [Api set: WordApi 1.1] */ tag?: boolean; /** * For EACH ITEM in the collection: Gets the text of the content control. Read-only. * * @remarks * [Api set: WordApi 1.1] */ text?: boolean; /** * For EACH ITEM in the collection: Gets or sets the title for a content control. * * @remarks * [Api set: WordApi 1.1] */ title?: boolean; /** * For EACH ITEM in the collection: Gets the content control type. Only rich text content controls are supported currently. Read-only. * * @remarks * [Api set: WordApi 1.1] */ type?: boolean; } /** * The Document object is the top level object. A Document object contains one or more sections, content controls, and the body that contains the contents of the document. * * @remarks * [Api set: WordApi 1.1] */ export interface DocumentLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * Gets the body object of the main document. The body is the text that excludes headers, footers, footnotes, textboxes, etc.. * * @remarks * [Api set: WordApi 1.1] */ body?: Word.Interfaces.BodyLoadOptions; /** * Indicates whether the changes in the document have been saved. A value of true indicates that the document hasn't changed since it was saved. Read-only. * * @remarks * [Api set: WordApi 1.1] */ saved?: boolean; } /** * Represents a font. * * @remarks * [Api set: WordApi 1.1] */ export interface FontLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * Gets or sets a value that indicates whether the font is bold. True if the font is formatted as bold, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ bold?: boolean; /** * Gets or sets the color for the specified font. You can provide the value in the '#RRGGBB' format or the color name. * * @remarks * [Api set: WordApi 1.1] */ color?: boolean; /** * Gets or sets a value that indicates whether the font has a double strikethrough. True if the font is formatted as double strikethrough text, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ doubleStrikeThrough?: boolean; /** * Gets or sets the highlight color. To set it, use a value either in the '#RRGGBB' format or the color name. To remove highlight color, set it to null. The returned highlight color can be in the '#RRGGBB' format, an empty string for mixed highlight colors, or null for no highlight color. **Note**: Only the default highlight colors are available in Office for Windows Desktop. These are "Yellow", "Lime", "Turquoise", "Pink", "Blue", "Red", "DarkBlue", "Teal", "Green", "Purple", "DarkRed", "Olive", "Gray", "LightGray", and "Black". When the add-in runs in Office for Windows Desktop, any other color is converted to the closest color when applied to the font. * * @remarks * [Api set: WordApi 1.1] */ highlightColor?: boolean; /** * Gets or sets a value that indicates whether the font is italicized. True if the font is italicized, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ italic?: boolean; /** * Gets or sets a value that represents the name of the font. * * @remarks * [Api set: WordApi 1.1] */ name?: boolean; /** * Gets or sets a value that represents the font size in points. * * @remarks * [Api set: WordApi 1.1] */ size?: boolean; /** * Gets or sets a value that indicates whether the font has a strikethrough. True if the font is formatted as strikethrough text, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ strikeThrough?: boolean; /** * Gets or sets a value that indicates whether the font is a subscript. True if the font is formatted as subscript, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ subscript?: boolean; /** * Gets or sets a value that indicates whether the font is a superscript. True if the font is formatted as superscript, otherwise, false. * * @remarks * [Api set: WordApi 1.1] */ superscript?: boolean; /** * Gets or sets a value that indicates the font's underline type. 'None' if the font is not underlined. * * @remarks * [Api set: WordApi 1.1] */ underline?: boolean; } /** * Represents an inline picture. * * @remarks * [Api set: WordApi 1.1] */ export interface InlinePictureLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * Gets the parent paragraph that contains the inline image. * * @remarks * [Api set: WordApi 1.2] */ paragraph?: Word.Interfaces.ParagraphLoadOptions; /** * Gets the content control that contains the inline image. Throws an error if there isn't a parent content control. * * @remarks * [Api set: WordApi 1.1] */ parentContentControl?: Word.Interfaces.ContentControlLoadOptions; /** * Gets or sets a string that represents the alternative text associated with the inline image. * * @remarks * [Api set: WordApi 1.1] */ altTextDescription?: boolean; /** * Gets or sets a string that contains the title for the inline image. * * @remarks * [Api set: WordApi 1.1] */ altTextTitle?: boolean; /** * Gets or sets a number that describes the height of the inline image. * * @remarks * [Api set: WordApi 1.1] */ height?: boolean; /** * Gets or sets a hyperlink on the image. Use a '#' to separate the address part from the optional location part. * * @remarks * [Api set: WordApi 1.1] */ hyperlink?: boolean; /** * Gets or sets a value that indicates whether the inline image retains its original proportions when you resize it. * * @remarks * [Api set: WordApi 1.1] */ lockAspectRatio?: boolean; /** * Gets or sets a number that describes the width of the inline image. * * @remarks * [Api set: WordApi 1.1] */ width?: boolean; } /** * Contains a collection of {@link Word.InlinePicture} objects. * * @remarks * [Api set: WordApi 1.1] */ export interface InlinePictureCollectionLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * For EACH ITEM in the collection: Gets the parent paragraph that contains the inline image. * * @remarks * [Api set: WordApi 1.2] */ paragraph?: Word.Interfaces.ParagraphLoadOptions; /** * For EACH ITEM in the collection: Gets the content control that contains the inline image. Throws an error if there isn't a parent content control. * * @remarks * [Api set: WordApi 1.1] */ parentContentControl?: Word.Interfaces.ContentControlLoadOptions; /** * For EACH ITEM in the collection: Gets or sets a string that represents the alternative text associated with the inline image. * * @remarks * [Api set: WordApi 1.1] */ altTextDescription?: boolean; /** * For EACH ITEM in the collection: Gets or sets a string that contains the title for the inline image. * * @remarks * [Api set: WordApi 1.1] */ altTextTitle?: boolean; /** * For EACH ITEM in the collection: Gets or sets a number that describes the height of the inline image. * * @remarks * [Api set: WordApi 1.1] */ height?: boolean; /** * For EACH ITEM in the collection: Gets or sets a hyperlink on the image. Use a '#' to separate the address part from the optional location part. * * @remarks * [Api set: WordApi 1.1] */ hyperlink?: boolean; /** * For EACH ITEM in the collection: Gets or sets a value that indicates whether the inline image retains its original proportions when you resize it. * * @remarks * [Api set: WordApi 1.1] */ lockAspectRatio?: boolean; /** * For EACH ITEM in the collection: Gets or sets a number that describes the width of the inline image. * * @remarks * [Api set: WordApi 1.1] */ width?: boolean; } /** * Represents a single paragraph in a selection, range, content control, or document body. * * @remarks * [Api set: WordApi 1.1] */ export interface ParagraphLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * Gets the text format of the paragraph. Use this to get and set font name, size, color, and other properties. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontLoadOptions; /** * Gets the content control that contains the paragraph. Throws an error if there isn't a parent content control. * * @remarks * [Api set: WordApi 1.1] */ parentContentControl?: Word.Interfaces.ContentControlLoadOptions; /** * Gets or sets the alignment for a paragraph. The value can be 'left', 'centered', 'right', or 'justified'. * * @remarks * [Api set: WordApi 1.1] */ alignment?: boolean; /** * Gets or sets the value, in points, for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent. * * @remarks * [Api set: WordApi 1.1] */ firstLineIndent?: boolean; /** * Gets or sets the left indent value, in points, for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ leftIndent?: boolean; /** * Gets or sets the line spacing, in points, for the specified paragraph. In the Word UI, this value is divided by 12. * * @remarks * [Api set: WordApi 1.1] */ lineSpacing?: boolean; /** * Gets or sets the amount of spacing, in grid lines, after the paragraph. * * @remarks * [Api set: WordApi 1.1] */ lineUnitAfter?: boolean; /** * Gets or sets the amount of spacing, in grid lines, before the paragraph. * * @remarks * [Api set: WordApi 1.1] */ lineUnitBefore?: boolean; /** * Gets or sets the outline level for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ outlineLevel?: boolean; /** * Gets or sets the right indent value, in points, for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ rightIndent?: boolean; /** * Gets or sets the spacing, in points, after the paragraph. * * @remarks * [Api set: WordApi 1.1] */ spaceAfter?: boolean; /** * Gets or sets the spacing, in points, before the paragraph. * * @remarks * [Api set: WordApi 1.1] */ spaceBefore?: boolean; /** * Gets or sets the style name for the paragraph. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: boolean; /** * Gets the text of the paragraph. Read-only. * * @remarks * [Api set: WordApi 1.1] */ text?: boolean; } /** * Contains a collection of {@link Word.Paragraph} objects. * * @remarks * [Api set: WordApi 1.1] */ export interface ParagraphCollectionLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * For EACH ITEM in the collection: Gets the text format of the paragraph. Use this to get and set font name, size, color, and other properties. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontLoadOptions; /** * For EACH ITEM in the collection: Gets the content control that contains the paragraph. Throws an error if there isn't a parent content control. * * @remarks * [Api set: WordApi 1.1] */ parentContentControl?: Word.Interfaces.ContentControlLoadOptions; /** * For EACH ITEM in the collection: Gets or sets the alignment for a paragraph. The value can be 'left', 'centered', 'right', or 'justified'. * * @remarks * [Api set: WordApi 1.1] */ alignment?: boolean; /** * For EACH ITEM in the collection: Gets or sets the value, in points, for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent. * * @remarks * [Api set: WordApi 1.1] */ firstLineIndent?: boolean; /** * For EACH ITEM in the collection: Gets or sets the left indent value, in points, for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ leftIndent?: boolean; /** * For EACH ITEM in the collection: Gets or sets the line spacing, in points, for the specified paragraph. In the Word UI, this value is divided by 12. * * @remarks * [Api set: WordApi 1.1] */ lineSpacing?: boolean; /** * For EACH ITEM in the collection: Gets or sets the amount of spacing, in grid lines, after the paragraph. * * @remarks * [Api set: WordApi 1.1] */ lineUnitAfter?: boolean; /** * For EACH ITEM in the collection: Gets or sets the amount of spacing, in grid lines, before the paragraph. * * @remarks * [Api set: WordApi 1.1] */ lineUnitBefore?: boolean; /** * For EACH ITEM in the collection: Gets or sets the outline level for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ outlineLevel?: boolean; /** * For EACH ITEM in the collection: Gets or sets the right indent value, in points, for the paragraph. * * @remarks * [Api set: WordApi 1.1] */ rightIndent?: boolean; /** * For EACH ITEM in the collection: Gets or sets the spacing, in points, after the paragraph. * * @remarks * [Api set: WordApi 1.1] */ spaceAfter?: boolean; /** * For EACH ITEM in the collection: Gets or sets the spacing, in points, before the paragraph. * * @remarks * [Api set: WordApi 1.1] */ spaceBefore?: boolean; /** * For EACH ITEM in the collection: Gets or sets the style name for the paragraph. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: boolean; /** * For EACH ITEM in the collection: Gets the text of the paragraph. Read-only. * * @remarks * [Api set: WordApi 1.1] */ text?: boolean; } /** * Represents a contiguous area in a document. * * @remarks * [Api set: WordApi 1.1] */ export interface RangeLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * Gets the text format of the range. Use this to get and set font name, size, color, and other properties. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontLoadOptions; /** * Gets the content control that contains the range. Throws an error if there isn't a parent content control. * * @remarks * [Api set: WordApi 1.1] */ parentContentControl?: Word.Interfaces.ContentControlLoadOptions; /** * Gets or sets the style name for the range. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: boolean; /** * Gets the text of the range. Read-only. * * @remarks * [Api set: WordApi 1.1] */ text?: boolean; } /** * Contains a collection of {@link Word.Range} objects. * * @remarks * [Api set: WordApi 1.1] */ export interface RangeCollectionLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * For EACH ITEM in the collection: Gets the text format of the range. Use this to get and set font name, size, color, and other properties. * * @remarks * [Api set: WordApi 1.1] */ font?: Word.Interfaces.FontLoadOptions; /** * For EACH ITEM in the collection: Gets the content control that contains the range. Throws an error if there isn't a parent content control. * * @remarks * [Api set: WordApi 1.1] */ parentContentControl?: Word.Interfaces.ContentControlLoadOptions; /** * For EACH ITEM in the collection: Gets or sets the style name for the range. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. * * @remarks * [Api set: WordApi 1.1] */ style?: boolean; /** * For EACH ITEM in the collection: Gets the text of the range. Read-only. * * @remarks * [Api set: WordApi 1.1] */ text?: boolean; } /** * Specifies the options to be included in a search operation. * * @remarks * [Api set: WordApi 1.1] */ export interface SearchOptionsLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * Gets or sets a value that indicates whether to ignore all punctuation characters between words. Corresponds to the Ignore punctuation check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ ignorePunct?: boolean; /** * Gets or sets a value that indicates whether to ignore all whitespace between words. Corresponds to the Ignore whitespace characters check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ ignoreSpace?: boolean; /** * Gets or sets a value that indicates whether to perform a case sensitive search. Corresponds to the Match case check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchCase?: boolean; /** * Gets or sets a value that indicates whether to match words that begin with the search string. Corresponds to the Match prefix check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchPrefix?: boolean; /** * Gets or sets a value that indicates whether to match words that end with the search string. Corresponds to the Match suffix check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchSuffix?: boolean; /** * Gets or sets a value that indicates whether to find operation only entire words, not text that is part of a larger word. Corresponds to the Find whole words only check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchWholeWord?: boolean; /** * Gets or sets a value that indicates whether the search will be performed using special search operators. Corresponds to the Use wildcards check box in the Find and Replace dialog box. * * @remarks * [Api set: WordApi 1.1] */ matchWildcards?: boolean; } /** * Represents a section in a Word document. * * @remarks * [Api set: WordApi 1.1] */ export interface SectionLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * Gets the body object of the section. This does not include the header/footer and other section metadata. * * @remarks * [Api set: WordApi 1.1] */ body?: Word.Interfaces.BodyLoadOptions; } /** * Contains the collection of the document's {@link Word.Section} objects. * * @remarks * [Api set: WordApi 1.1] */ export interface SectionCollectionLoadOptions { /** Specifying `$all` for the LoadOptions loads all the scalar properties (e.g.: `Range.address`) but not the navigational properties (e.g.: `Range.format.fill.color`). */ $all?: boolean; /** * For EACH ITEM in the collection: Gets the body object of the section. This does not include the header/footer and other section metadata. * * @remarks * [Api set: WordApi 1.1] */ body?: Word.Interfaces.BodyLoadOptions; } } } export declare namespace Word { /** * The RequestContext object facilitates requests to the Word application. Since the Office add-in and the Word application run in two different processes, the request context is required to get access to the Word object model from the add-in. */ export class RequestContext extends OfficeExtension.ClientRequestContext { constructor(url?: string); readonly document: Document; } /** * Executes a batch script that performs actions on the Word object model, using the RequestContext of previously created API objects. * @param objects - An array of previously created API objects. The array will be validated to make sure that all of the objects share the same context. The batch will use this shared RequestContext, which means that any changes applied to these objects will be picked up by "context.sync()". * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Word application. Since the Office add-in and the Word application run in two different processes, the RequestContext is required to get access to the Word object model from the add-in. */ export function run<T>(objects: OfficeExtension.ClientObject[], batch: (context: Word.RequestContext) => Promise<T>): Promise<T>; /** * Executes a batch script that performs actions on the Word object model, using the RequestContext of a previously created API object. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. * @param object - A previously created API object. The batch will use the same RequestContext as the passed-in object, which means that any changes applied to the object will be picked up by "context.sync()". * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Word application. Since the Office add-in and the Word application run in two different processes, the RequestContext is required to get access to the Word object model from the add-in. */ export function run<T>(object: OfficeExtension.ClientObject, batch: (context: Word.RequestContext) => Promise<T>): Promise<T>; /** * Executes a batch script that performs actions on the Word object model, using a new RequestContext. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Word application. Since the Office add-in and the Word application run in two different processes, the RequestContext is required to get access to the Word object model from the add-in. * * @remarks * * In addition to this signature, the method also has the following signatures, which allow you to resume using the request context of previously created objects: * * run<T>(object: OfficeExtension.ClientObject, batch: (context: Word.RequestContext) => Promise<T>): Promise<T>; * * run<T>(objects: OfficeExtension.ClientObject[], batch: (context: Word.RequestContext) => Promise<T>): Promise<T>; */ export function run<T>(batch: (context: Word.RequestContext) => Promise<T>): Promise<T>; } //////////////////////////////////////////////////////////////// //////////////////////// End Word APIs ///////////////////////// ////////////////////////////////////////////////////////////////
the_stack
import {PodStatsRecord, SimpleDataTableOrNull} from 'org_xprof/frontend/app/common/interfaces/data_table'; import {Diagnostics} from 'org_xprof/frontend/app/common/interfaces/diagnostics'; import {OpProfileNode} from 'org_xprof/frontend/app/common/interfaces/op_profile_node'; import {Store} from '@ngrx/store'; import {setLoadingStateAction} from 'org_xprof/frontend/app/store/actions'; const PRIMITIVE_TYPE_BYTE_SIZE: {[key: string]: number} = { 'BF16': 2, 'C64': 8, 'F16': 2, 'F32': 4, 'F64': 8, 'PRED': 1, 'TOKEN': 0, 'S8': 1, 'S16': 2, 'S32': 4, 'S64': 8, 'U8': 1, 'U16': 2, 'U32': 4, 'U64': 8, }; const SHUFFLED_MATERIAL_COLORS = [ '#e91e63', '#2196f3', '#81c784', '#4dd0e1', '#3f51b5', '#e53935', '#ff9100', '#b39ddb', '#90a4ae', '#26c6da', '#ad1457', '#03a9f4', '#2196f3', '#c2185b', '#795548', '#f9a825', '#00bfa5', '#880e4f', '#d500f9', '#ce93d8', '#ec407a', '#4caf50', '#ff8f00', '#ffca28', '#ab47bc', '#00e5ff', '#ff9800', '#40c4ff', '#1e88e5', '#9fa8da', '#bf360c', '#00b8d4', '#f57f17', '#64b5f6', '#e040fb', '#ffab91', '#4caf50', '#01579b', '#66bb6a', '#ef9a9a', '#558b2f', '#fb8c00', '#ff4081', '#00e676', '#388e3c', '#424242', '#6d4c41', '#c62828', '#616161', '#00897b', '#448aff', '#0d47a1', '#607d8b', '#673ab7', '#00c853', '#2e7d32', '#ffa726', '#5e35b1', '#ba68c8', '#8d6e63', '#00bcd4', '#ff6f00', '#f4511e', '#ff1744', '#9e9e9e', '#d81b60', '#4a148c', '#26a69a', '#689f38', '#7b1fa2', '#b0bec5', '#304ffe', '#f48fb1', '#ffd600', '#ffb74d', '#8bc34a', '#303f9f', '#5d4037', '#80cbc4', '#ffcc80', '#00acc1', '#3e2723', '#ff5252', '#ff7043', '#e91e63', '#ea80fc', '#e65100', '#d84315', '#212121', '#ff5722', '#1976d2', '#2962ff', '#bdbdbd', '#3949ab', '#69f0ae', '#d50000', '#ffd740', '#c0ca33', '#ff6e40', '#00b0ff', '#2979ff', '#e64a19', '#7c4dff', '#607d8b', '#009688', '#ffb300', '#c51162', '#ffc400', '#29b6f6', '#3d5afe', '#76ff03', '#cddc39', '#b388ff', '#5c6bc0', '#9e9d24', '#7cb342', '#ef5350', '#fdd835', '#ef6c00', '#4fc3f7', '#6200ea', '#004d40', '#ff8a65', '#ffab00', '#80deea', '#0097a7', '#7e57c2', '#ff6d00', '#1565c0', '#455a64', '#ffc107', '#4527a0', '#ff5722', '#f44336', '#f57c00', '#827717', '#a5d6a7', '#82b1ff', '#9c27b0', '#ff80ab', '#e1bee7', '#78909c', '#311b92', '#00695c', '#4e342e', '#3f51b5', '#651fff', '#9e9e9e', '#81d4fa', '#f8bbd0', '#b71c1c', '#0091ea', '#673ab7', '#a1887f', '#4db6ac', '#ffa000', '#6a1b9a', '#43a047', '#bcaaa4', '#546e7a', '#aeea00', '#e57373', '#ffccbc', '#006064', '#fbc02d', '#ffeb3b', '#8bc34a', '#039be5', '#8e24aa', '#80d8ff', '#009688', '#9ccc65', '#512da8', '#ffc107', '#757575', '#0277bd', '#ff3d00', '#33691e', '#03a9f4', '#00838f', '#ff8a80', '#283593', '#f50057', '#1a237e', '#90caf9', '#9c27b0', '#aa00ff', '#aed581', '#afb42b', '#9575cd', '#d32f2f', '#64dd17', '#f44336', '#795548', '#cddc39', '#ff9e80', '#7986cb', '#dd2c00', '#0288d1', '#ff9800', '#263238', '#00796b', '#42a5f5', '#8c9eff', '#1b5e20', '#ffab40', '#536dfe', '#00bcd4', '#f06292', ]; const KNOWN_TOOLS = [ 'input_pipeline_analyzer', 'memory_profile', 'memory_viewer', 'op_profile', 'pod_viewer', 'tensorflow_stats', 'trace_viewer', 'tf_data_bottleneck_analysis', ]; /** * Returns the number of bytes of the primitive type. */ export function byteSizeOfPrimitiveType(type: string): number { if (!PRIMITIVE_TYPE_BYTE_SIZE.hasOwnProperty(type)) { console.error('Unhandled primitive type ' + type); return 0; } return PRIMITIVE_TYPE_BYTE_SIZE[type]; } /** * Converts from number of bytes to MiB. */ export function bytesToMiB(numBytes: number): number { return numBytes / (1024 * 1024); } /** * Format the number as human-readable text. * @param num Number to convert. * @param si True to use metric (SI) units, aka powers of 1000. False to use * binary (IEC), aka powers of 1024. * @param dp Number of decimal places to display. * @param suffix Text to append to the string as common unit, e.g. FLOP/s. */ export function humanReadableText( num: number, {si = false, dp = 2, suffix = 'B'} = {}): string { const base = si ? 1000 : 1024; const units = si ? ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] : ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi']; const i = num === 0 ? 0 : Math.floor(Math.log(num) / Math.log(base)); return (Number(num / Math.pow(base, i)).toFixed(dp) + ' ' + units[i] + suffix) || ''; } /** * Returns a color for chart item by index. */ export function getChartItemColorByIndex(index: number): string { return SHUFFLED_MATERIAL_COLORS[index % SHUFFLED_MATERIAL_COLORS.length]; } /** * Converts from string to number. */ export function toNumber(value: string|undefined): number { const num = Number(value); return isNaN(num) ? 0 : num; } /** * Returns a rgba string. */ function rgba(red: number, green: number, blue: number, alpha: number): string { return 'rgba(' + Math.round(red * 255).toString() + ',' + Math.round(green * 255).toString() + ',' + Math.round(blue * 255).toString() + ',' + alpha.toString() + ')'; } /** * Computes a flame color. */ export function flameColor( fraction: number, brightness?: number, opacity?: number, curve?: Function): string { if (brightness === void 0) { brightness = 1; } if (opacity === void 0) { opacity = 1; } if (curve === void 0) { curve = (x: number) => 1 - Math.sqrt(1 - x); } if (isNaN(fraction)) { return rgba(brightness, brightness, brightness, opacity); } fraction = curve(fraction); // Or everythin is depressing and red. return fraction < 0.5 ? rgba(brightness, 2 * fraction * brightness, 0, opacity) : rgba(2 * (1 - fraction) * brightness, brightness, 0, opacity); } /** * Computes a Flops color. */ export function flopsColor(fraction: number): string { return flameColor(Math.min(fraction, 1), 0.7, 1, Math.sqrt); } /** * Computes a memory bandwidth color. */ export function bwColor(fraction: number): string { return flameColor(Math.max(1 - fraction, 0), 0.7, 1, Math.sqrt); } /** * Computes the utilization for operations. */ export function flopsUtilization(node: OpProfileNode): number { // NaN indicates undefined utilization for fused operations (we can't // measure performance inside a fusion). It could also indicate operations // with zero time, but they currently don't appear in the profile. if (!node || !node.metrics || !node.metrics.time) return NaN; return (node.metrics.flops || 0) / node.metrics.time; } /** * Computes the flops rate for operations. */ export function flopsRate(node: OpProfileNode): number { // NaN indicates undefined flops for fused operations (we can't // measure performance inside a fusion). It could also indicate operations // with zero time, but they currently don't appear in the profile. if (!node || !node.metrics || !node.metrics.rawTime) return NaN; // The unit of rawTime is picoseconds. return (node.metrics.rawFlops || 0) * 1E12 / node.metrics.rawTime; } /** * Computes a memory bandwidth utilization. */ export function memoryBandwidthUtilization(node: OpProfileNode): number { // NaN indicates undefined memory bandwidth utilization (the profile was // collected from older versions of profiler). if (!node || !node.metrics || !node.metrics.memoryBandwidth) return NaN; return node.metrics.memoryBandwidth; } /** * Computes the memory bandwidth for operations. */ export function memoryBandwidth(node: OpProfileNode): number { // NaN indicates undefined memory utilization (the profile was collected // from older versions of profiler). if (!node || !node.metrics || !node.metrics.rawTime) return NaN; // The unit of rawTime is picoseconds. return (node.metrics.rawBytesAccessed || 0) * 1E12 / node.metrics.rawTime; } /** * Returns whether a node has flops utilization. */ export function hasFlopsUtilization(node: OpProfileNode): boolean { return !!node && !!node.metrics && !!node.metrics.time; } /** * Returns whether a node has memory bandwidth utilization. */ export function hasMemoryBandwidthUtilization(node: OpProfileNode): boolean { return !!node && !!node.metrics && !!node.metrics.memoryBandwidth; } /** * Computes a percent. */ export function percent(fraction: number): string { if (isNaN(fraction)) return '-'; if (fraction >= 1.995) { return '200%'; } else if (fraction < 0.00001) { return '0.00%'; } else { return `${Math.round(fraction * 100)}%`; } } /** * Computes wasted time. */ export function timeWasted(node: OpProfileNode): number { if (!node || !node.metrics) return NaN; return ( (node.metrics.time || 0) * (1 - Math.max(flopsUtilization(node), memoryBandwidthUtilization(node)))); } /** * Returns podStatsRecord stepBreakdownUs field property. */ export function getPodStatsRecordBreakdownProperty( podStatsRecord: PodStatsRecord, key: string): number { if (podStatsRecord.stepBreakdownUs) { return podStatsRecord.stepBreakdownUs[key] || 0; } return 0; } /** * Scrolls to the bottom of sidenav to show detail views. */ export function scrollBottomOfSidenav() { const sidenavContainer = document.querySelector('.mat-drawer-inner-container'); if (sidenavContainer) { setTimeout(() => { sidenavContainer.scrollTo(0, sidenavContainer.scrollHeight); }, 1); } } /** * Returns a string with an anchor tag. */ export function addAnchorTag(value: string = ''): string { return '<a>' + value + '</a>'; } /** * Returns a string with the known tool name changed to an anchor tag. */ export function convertKnownToolToAnchorTag(value: string = ''): string { KNOWN_TOOLS.forEach(tool => { value = value.replace(new RegExp(tool, 'g'), addAnchorTag(tool)); }); return value; } /** * Parse diagnostics data table and returns Diagnostics object. */ export function parseDiagnosticsDataTable( diagnosticsTable: SimpleDataTableOrNull): Diagnostics { const diagnostics: Diagnostics = {info: [], warnings: [], errors: []}; if (!diagnosticsTable || !diagnosticsTable.rows) return diagnostics; /** Convert data table to string arrays */ diagnosticsTable.rows.forEach(row => { if (String(row.c![0].v!) === 'ERROR') { diagnostics.errors.push(String(row.c![1].v!)); } else if (String(row.c![0].v!) === 'WARNING') { diagnostics.warnings.push(String(row.c![1].v!)); } else { diagnostics.info.push(String(row.c![1].v!)); } }); return diagnostics; } /** * Sets the global loading state. */ export function setLoadingState( beingLoaded: boolean, store: Store<{}>) { if (beingLoaded) { store.dispatch(setLoadingStateAction({ loadingState: { loading: true, message: 'Loading data', } })); } else { store.dispatch(setLoadingStateAction({ loadingState: { loading: false, message: '', } })); } }
the_stack
import { expect } from "chai"; import * as React from "react"; import * as sinon from "sinon"; import * as moq from "typemoq"; import { AxisIndex, Matrix3d, Transform, Vector3d } from "@itwin/core-geometry"; import { DrawingViewState, IModelConnection, ScreenViewport } from "@itwin/core-frontend"; import { fireEvent, render, waitFor } from "@testing-library/react"; import { TestUtils } from "../TestUtils"; import { CubeHover, CubeNavigationAid, CubeNavigationHitBoxX, CubeNavigationHitBoxY, CubeNavigationHitBoxZ, FaceCell, NavCubeFace } from "../../imodel-components-react/navigationaids/CubeNavigationAid"; import { ViewportComponentEvents } from "../../imodel-components-react/viewport/ViewportComponentEvents"; import { Face } from "../../imodel-components-react/navigationaids/Cube"; describe("CubeNavigationAid", () => { before(async () => { await TestUtils.initializeUiIModelComponents(); }); after(() => { TestUtils.terminateUiIModelComponents(); }); let rotation = Matrix3d.createIdentity(); const connection = moq.Mock.ofType<IModelConnection>(); const viewState = moq.Mock.ofType<DrawingViewState>(); viewState.setup((x) => x.id).returns(() => "id1"); viewState.setup((x) => x.classFullName).returns(() => "Bis:DrawingViewDefinition"); viewState.setup((x) => x.getRotation).returns(() => () => rotation); const vp = moq.Mock.ofType<ScreenViewport>(); vp.setup((x) => x.view).returns(() => viewState.object); vp.setup((x) => x.rotation).returns(() => rotation); const waitForSpy = async (spy: sinon.SinonSpy, timeoutMillis: number = 1500) => { return waitFor(() => { if (!spy.called) throw new Error("Waiting for spy timed out!"); }, { timeout: timeoutMillis, interval: 10 }); }; const cssMatrix3dToBentleyTransform = (mStr: string) => { const mat = mStr.match(/matrix3d\(([-\de\. ,]+)\)/); if (mat !== null && mat[1] !== undefined) { const params = mat[1].split(","); if (params.length !== 16) return undefined; const p = []; for (const param of params) { const n = parseFloat(param); if (isNaN(n)) { return undefined; } p.push(n); } return Transform.createRowValues( p[0], p[4], p[8], p[12], p[1], p[5], p[9], p[13], p[2], p[6], p[10], p[14], ); } return undefined; }; describe("<CubeNavigationAid />", () => { it("should render", () => { render(<CubeNavigationAid iModelConnection={connection.object} />); }); it("should exist", async () => { const component = render(<CubeNavigationAid iModelConnection={connection.object} />); const navAid = component.getByTestId("components-cube-navigation-aid"); expect(navAid).to.exist; }); it("should change from top to front when arrow clicked", async () => { const animationEnd = sinon.fake(); const component = render(<CubeNavigationAid iModelConnection={connection.object} animationTime={.1} onAnimationEnd={animationEnd} />); const topFace = component.getByTestId("components-cube-face-top"); const pointerButton = component.getByTestId("cube-pointer-button-down"); const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; pointerButton.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, view: window })); await waitForSpy(animationEnd); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.matrix.isAlmostEqual(Matrix3d.createRowValues(1, 0, 0, 0, 0, -1, 0, 1, 0))).is.true; }); it("should change from top to back when arrow clicked", async () => { const animationEnd = sinon.fake(); const component = render(<CubeNavigationAid iModelConnection={connection.object} animationTime={.1} onAnimationEnd={animationEnd} />); const topFace = component.getByTestId("components-cube-face-top"); const pointerButton = component.getByTestId("cube-pointer-button-up"); const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; pointerButton.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, view: window })); await waitForSpy(animationEnd); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.matrix.isAlmostEqual(Matrix3d.createRowValues(-1, 0, 0, 0, 0, -1, 0, -1, 0))).is.true; }); it("should change from top to left when arrow clicked", async () => { const animationEnd = sinon.fake(); const component = render(<CubeNavigationAid iModelConnection={connection.object} animationTime={.1} onAnimationEnd={animationEnd} />); const topFace = component.getByTestId("components-cube-face-top"); const pointerButton = component.getByTestId("cube-pointer-button-left"); const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; pointerButton.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, view: window })); await waitForSpy(animationEnd); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.matrix.isAlmostEqual(Matrix3d.createRowValues(0, 1, 0, 0, 0, -1, -1, 0, 0))).is.true; }); it("should change from top to right when arrow clicked", async () => { const animationEnd = sinon.fake(); const component = render(<CubeNavigationAid iModelConnection={connection.object} animationTime={.1} onAnimationEnd={animationEnd} />); const topFace = component.getByTestId("components-cube-face-top"); const pointerButton = component.getByTestId("cube-pointer-button-right"); const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; pointerButton.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, view: window })); await waitForSpy(animationEnd); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.matrix.isAlmostEqual(Matrix3d.createRowValues(0, -1, 0, 0, 0, -1, 1, 0, 0))).is.true; }); it("should highlight hovered cell", async () => { const component = render(<CubeNavigationAid iModelConnection={connection.object} />); const topCenterCell = component.getByTestId("nav-cube-face-cell-top-0-0-1"); expect(topCenterCell.classList.contains("cube-hover")).to.be.false; topCenterCell.dispatchEvent(new MouseEvent("mouseover", { bubbles: true, cancelable: true, view: window })); expect(topCenterCell.classList.contains("cube-hover")).to.be.true; }); it("should click center cell", async () => { const component = render(<CubeNavigationAid iModelConnection={connection.object} />); const topFace = component.getByTestId("components-cube-face-top"); const topCenterCell = component.getByTestId("nav-cube-face-cell-top-0-0-1"); expect(topCenterCell.classList.contains("cube-active")).to.be.false; const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; topCenterCell.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, view: window })); expect(topCenterCell.classList.contains("cube-active")).to.be.true; topCenterCell.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, view: window })); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; }); it("should click corner cell", async () => { const animationEnd = sinon.fake(); const component = render(<CubeNavigationAid iModelConnection={connection.object} animationTime={.1} onAnimationEnd={animationEnd} />); const topFace = component.getByTestId("components-cube-face-top"); const topCornerCell = component.getByTestId("nav-cube-face-cell-top-1-0-1"); expect(topCornerCell.classList.contains("cube-active")).to.be.false; const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; topCornerCell.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, view: window })); expect(topCornerCell.classList.contains("cube-active")).to.be.true; topCornerCell.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, view: window })); await waitForSpy(animationEnd); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.matrix.isAlmostEqual(Matrix3d.createRowValues(0, -1, 0, 0.70710678, 0, -0.70710678, 0.70710678, 0, 0.70710678))).is.true; }); it("should switch from edge to top face", async () => { const animationEnd = sinon.fake(); const component = render(<CubeNavigationAid iModelConnection={connection.object} animationTime={.1} onAnimationEnd={animationEnd} />); const topFace = component.getByTestId("components-cube-face-top"); const topEdgeCell = component.getByTestId("nav-cube-face-cell-top-1-0-1"); const topCenterCell = component.getByTestId("nav-cube-face-cell-top-0-0-1"); const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; topEdgeCell.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, view: window })); topEdgeCell.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, view: window })); await waitForSpy(animationEnd); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.matrix.isAlmostEqual(Matrix3d.createRowValues(0, -1, 0, 0.70710678, 0, -0.70710678, 0.70710678, 0, 0.70710678))).is.true; animationEnd.resetHistory(); topCenterCell.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, view: window })); topCenterCell.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, view: window })); await waitForSpy(animationEnd); const mat3 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat3.matrix.isAlmostEqual(Matrix3d.createRowValues(0, -1, 0, 1, 0, 0, 0, 0, 1))).is.true; }); it("should switch from edge to bottom face", async () => { const animationEnd = sinon.fake(); const component = render(<CubeNavigationAid iModelConnection={connection.object} animationTime={.1} onAnimationEnd={animationEnd} />); const topFace = component.getByTestId("components-cube-face-top"); const bottomCornerCell = component.getByTestId("nav-cube-face-cell-bottom--1-0--1"); const bottomCornerCenter = component.getByTestId("nav-cube-face-cell-bottom-0-0--1"); const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; bottomCornerCell.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, view: window })); bottomCornerCell.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, view: window })); await waitForSpy(animationEnd); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.matrix.isAlmostEqual(Matrix3d.createRowValues(0, 1, 0, 0.70710678, 0, -0.70710678, -0.70710678, 0, -0.70710678))).is.true; animationEnd.resetHistory(); bottomCornerCenter.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, view: window })); bottomCornerCenter.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, view: window })); await waitForSpy(animationEnd); const mat3 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat3.matrix.isAlmostEqual(Matrix3d.createRowValues(0, 1, 0, 1, 0, 0, 0, 0, -1))).is.true; }); it("should drag cube", async () => { const component = render(<CubeNavigationAid iModelConnection={connection.object} />); const topFace = component.getByTestId("components-cube-face-top"); const topCenterCell = component.getByTestId("nav-cube-face-cell-top-0-0-1"); expect(topCenterCell.classList.contains("cube-active")).to.be.false; const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; topCenterCell.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, view: window, clientX: 2, clientY: 2 })); topCenterCell.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, cancelable: true, view: window, clientX: 10, clientY: 2 })); topCenterCell.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, cancelable: true, view: window, clientX: 20, clientY: 2 })); topCenterCell.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, view: window, clientX: 20, clientY: 2 })); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.matrix.isAlmostEqual(Matrix3d.createRowValues(0.62160997, 0.7833269, 0, -0.7833269, 0.62160997, 0, 0, 0, 1))).is.true; }); it.skip("should touch drag cube", async () => { // Touch isn't currently supported so we can't test it... const component = render(<CubeNavigationAid iModelConnection={connection.object} />); const topFace = component.getByTestId("components-cube-face-top"); const topCenterCell = component.getByTestId("nav-cube-face-cell-top-0-0-1"); expect(topCenterCell.classList.contains("cube-active")).to.be.false; const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; const touchStart = new Touch({ identifier: 0, target: topCenterCell, clientX: 2, clientY: 2 }); // <== ReferenceError: Touch is not defined const touchMove1 = new Touch({ identifier: 0, target: topCenterCell, clientX: 10, clientY: 2 }); const touchMove2 = new Touch({ identifier: 0, target: topCenterCell, clientX: 20, clientY: 2 }); const touchEnd = new Touch({ identifier: 0, target: topCenterCell, clientX: 20, clientY: 2 }); topCenterCell.dispatchEvent(new TouchEvent("touchstart", { bubbles: true, cancelable: true, view: window, touches: [touchStart], changedTouches: [touchStart], targetTouches: [touchStart] })); topCenterCell.dispatchEvent(new TouchEvent("touchmove", { bubbles: true, cancelable: true, view: window, touches: [touchMove1], changedTouches: [touchMove1], targetTouches: [touchMove1] })); topCenterCell.dispatchEvent(new TouchEvent("touchmove", { bubbles: true, cancelable: true, view: window, touches: [touchMove2], changedTouches: [touchMove2], targetTouches: [touchMove2] })); topCenterCell.dispatchEvent(new TouchEvent("touchend", { bubbles: true, cancelable: true, view: window, touches: [touchEnd], changedTouches: [touchEnd] })); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.isIdentity).is.false; }); describe("onViewRotationChangeEvent", () => { beforeEach(() => { rotation = Matrix3d.createIdentity(); }); it("should update onViewRotationChangeEvent", async () => { const component = render(<CubeNavigationAid iModelConnection={connection.object} viewport={vp.object} />); const topFace = component.getByTestId("components-cube-face-top"); const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; ViewportComponentEvents.onViewRotationChangeEvent.emit({ viewport: vp.object }); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; }); it("should update onViewRotationChangeEvent with new rotation", async () => { const component = render(<CubeNavigationAid iModelConnection={connection.object} viewport={vp.object} />); const topFace = component.getByTestId("components-cube-face-top"); const mat = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat.matrix.isAlmostEqual(Matrix3d.createIdentity())).is.true; rotation = Matrix3d.create90DegreeRotationAroundAxis(AxisIndex.Z); ViewportComponentEvents.onViewRotationChangeEvent.emit({ viewport: vp.object }); const mat2 = cssMatrix3dToBentleyTransform(topFace.style.transform)!; expect(mat2.matrix.isAlmostEqual(Matrix3d.createRowValues(0, 1, 0, -1, 0, 0, 0, 0, 1))).is.true; }); }); }); describe("<NavCubeFace />", () => { it("should render", () => { render(<NavCubeFace face={Face.Top} label="test" hoverMap={{}} onFaceCellClick={sinon.fake()} onFaceCellHoverChange={sinon.fake()} />); }); it("should exist", () => { const component = render(<NavCubeFace face={Face.Top} label="test" hoverMap={{}} onFaceCellClick={sinon.fake()} onFaceCellHoverChange={sinon.fake()} />); const face = component.getByTestId("nav-cube-face"); expect(face).to.exist; }); describe("methods and callbacks", () => { beforeEach(() => { NavCubeFace.faceCellToPos = sinon.spy(NavCubeFace.faceCellToPos); render(<NavCubeFace face={Face.Top} label="test" hoverMap={{}} onFaceCellClick={sinon.fake()} onFaceCellHoverChange={sinon.fake()} />); }); describe("faceCellToPos", () => { it("should be called when component is rendered", () => { NavCubeFace.faceCellToPos.should.have.been.calledWith(Face.Top, 0, 0); }); it("should return correct Point3d", () => { const pos = NavCubeFace.faceCellToPos(Face.Back, -1, 1); pos.x.should.equal(CubeNavigationHitBoxX.Right); pos.y.should.equal(CubeNavigationHitBoxY.Back); pos.z.should.equal(CubeNavigationHitBoxZ.Bottom); }); }); }); }); describe("<FaceCell />", () => { it("should render", () => { render(<FaceCell onFaceCellClick={sinon.fake()} onFaceCellHoverChange={sinon.fake()} hoverMap={{}} vector={Vector3d.create(1, 1, 1)} face={Face.Top} />); }); it("should exist", () => { const component = render(<FaceCell onFaceCellClick={sinon.fake()} onFaceCellHoverChange={sinon.fake()} hoverMap={{}} vector={Vector3d.create(1, 1, 1)} face={Face.Top} />); const faceCell = component.getByTestId("nav-cube-face-cell-top-1-1-1"); expect(faceCell).to.exist; }); describe("onFaceCellClick", () => { it("should be called when cell is clicked", () => { const cellClick = sinon.spy(); const pos = Vector3d.create(1, 1, 1); const component = render(<FaceCell onFaceCellClick={cellClick} onFaceCellHoverChange={sinon.fake()} hoverMap={{}} vector={pos} face={Face.Top} />); const faceCell = component.getByTestId("nav-cube-face-cell-top-1-1-1"); fireEvent.mouseDown(faceCell); fireEvent.mouseUp(faceCell); expect(cellClick).to.be.called; }); it("should be called when cell is touched", () => { const cellClick = sinon.spy(); const pos = Vector3d.create(1, 1, 1); const component = render(<FaceCell onFaceCellClick={cellClick} onFaceCellHoverChange={sinon.fake()} hoverMap={{}} vector={pos} face={Face.Top} />); const faceCell = component.getByTestId("nav-cube-face-cell-top-1-1-1"); fireEvent.touchStart(faceCell, { targetTouches: [{ clientX: 10, clientY: 10, }], }); fireEvent.touchEnd(faceCell, { changedTouches: [{ clientX: 10, clientY: 10, }], }); expect(cellClick).to.be.called; }); }); describe("onFaceCellHoverChange", () => { it("should be called when cell is hovered", () => { const cellHover = sinon.spy(); const pos = Vector3d.create(1, 1, 1); const component = render(<FaceCell onFaceCellClick={sinon.fake()} onFaceCellHoverChange={cellHover} hoverMap={{}} vector={pos} face={Face.Top} />); const faceCell = component.getByTestId("nav-cube-face-cell-top-1-1-1"); fireEvent.mouseOver(faceCell); expect(cellHover).to.be.calledWithExactly(pos, CubeHover.Hover); }); it("should be called when cell is unhovered", () => { const cellHover = sinon.spy(); const pos = Vector3d.create(1, 1, 1); const component = render(<FaceCell onFaceCellClick={sinon.fake()} onFaceCellHoverChange={cellHover} hoverMap={{}} vector={pos} face={Face.Top} />); const faceCell = component.getByTestId("nav-cube-face-cell-top-1-1-1"); fireEvent.mouseOver(faceCell); fireEvent.mouseOut(faceCell); expect(cellHover).to.be.calledWithExactly(pos, CubeHover.None); }); it("should be called when cell is clicked", () => { const cellHover = sinon.spy(); const pos = Vector3d.create(1, 1, 1); const component = render(<FaceCell onFaceCellClick={sinon.fake()} onFaceCellHoverChange={cellHover} hoverMap={{}} vector={pos} face={Face.Top} />); const faceCell = component.getByTestId("nav-cube-face-cell-top-1-1-1"); fireEvent.mouseDown(faceCell); expect(cellHover).to.be.calledWithExactly(pos, CubeHover.Active); }); it("should be called when cell is unclicked", () => { const cellHover = sinon.spy(); const pos = Vector3d.create(1, 1, 1); const component = render(<FaceCell onFaceCellClick={sinon.fake()} onFaceCellHoverChange={cellHover} hoverMap={{}} vector={pos} face={Face.Top} />); const faceCell = component.getByTestId("nav-cube-face-cell-top-1-1-1"); fireEvent.mouseDown(faceCell); fireEvent.mouseUp(faceCell); expect(cellHover).to.be.calledWithExactly(pos, CubeHover.None); }); }); }); });
the_stack
* Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useEffect, useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { Grid, Checkbox, Button, FormControl, Input, InputLabel } from '@material-ui/core'; import Alert from '@material-ui/lab/Alert'; import FileCopyIcon from '@material-ui/icons/FileCopy'; import { TableData } from 'Models'; import { UnControlled as CodeMirror } from 'react-codemirror2'; import 'codemirror/lib/codemirror.css'; import 'codemirror/theme/material.css'; import 'codemirror/mode/javascript/javascript'; import 'codemirror/mode/sql/sql'; import 'codemirror/addon/hint/show-hint'; import 'codemirror/addon/hint/sql-hint'; import 'codemirror/addon/hint/show-hint.css'; import NativeCodeMirror from 'codemirror'; import _ from 'lodash'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Switch from '@material-ui/core/Switch'; import exportFromJSON from 'export-from-json'; import Utils from '../utils/Utils'; import AppLoader from '../components/AppLoader'; import CustomizedTables from '../components/Table'; import QuerySideBar from '../components/Query/QuerySideBar'; import TableToolbar from '../components/TableToolbar'; import SimpleAccordion from '../components/SimpleAccordion'; import PinotMethodUtils from '../utils/PinotMethodUtils'; import '../styles/styles.css'; import {Resizable} from "re-resizable"; import { useHistory, useLocation } from 'react-router'; const useStyles = makeStyles((theme) => ({ title: { flexGrow: 1, paddingLeft: '20px', }, rightPanel: {}, codeMirror: { height: '100%', '& .CodeMirror': { height: '100%', border: '1px solid #BDCCD9', fontSize: '13px', }, }, queryOutput: { '& .CodeMirror': { height: 430, border: '1px solid #BDCCD9' }, }, btn: { margin: '10px 10px 0 0', height: 30, }, checkBox: { margin: '20px 0', }, actionBtns: { margin: '20px 0', height: 50, }, runNowBtn: { marginLeft: 'auto', paddingLeft: '74px', }, sqlDiv: { height: '100%', border: '1px #BDCCD9 solid', borderRadius: 4, marginBottom: '20px', paddingBottom: '48px', }, sqlError: { whiteSpace: 'pre-wrap', }, timeoutControl: { bottom: 10 } })); const jsonoptions = { lineNumbers: true, mode: 'application/json', styleActiveLine: true, gutters: ['CodeMirror-lint-markers'], theme: 'default', readOnly: true, }; const sqloptions = { lineNumbers: true, mode: 'text/x-sql', styleActiveLine: true, lint: true, theme: 'default', indentWithTabs: true, smartIndent: true, lineWrapping: true, extraKeys: { "'@'": 'autocomplete' }, }; const sqlFuntionsList = [ 'COUNT', 'MIN', 'MAX', 'SUM', 'AVG', 'MINMAXRANGE', 'DISTINCTCOUNT', 'DISTINCTCOUNTBITMAP', 'SEGMENTPARTITIONEDDISTINCTCOUNT', 'DISTINCTCOUNTHLL', 'DISTINCTCOUNTRAWHLL', 'FASTHLL', 'DISTINCTCOUNTTHETASKETCH', 'DISTINCTCOUNTRAWTHETASKETCH', 'COUNTMV', 'MINMV', 'MAXMV', 'SUMMV', 'AVGMV', 'MINMAXRANGEMV', 'DISTINCTCOUNTMV', 'DISTINCTCOUNTBITMAPMV', 'DISTINCTCOUNTHLLMV', 'DISTINCTCOUNTRAWHLLMV', 'DISTINCT', 'ST_UNION']; const responseStatCols = [ 'timeUsedMs', 'numDocsScanned', 'totalDocs', 'numServersQueried', 'numServersResponded', 'numSegmentsQueried', 'numSegmentsProcessed', 'numSegmentsMatched', 'numConsumingSegmentsQueried', 'numEntriesScannedInFilter', 'numEntriesScannedPostFilter', 'numGroupsLimitReached', 'partialResponse', 'minConsumingFreshnessTimeMs', 'offlineThreadCpuTimeNs', 'realtimeThreadCpuTimeNs', 'offlineSystemActivitiesCpuTimeNs', 'realtimeSystemActivitiesCpuTimeNs', 'offlineResponseSerializationCpuTimeNs', 'realtimeResponseSerializationCpuTimeNs', 'offlineTotalCpuTimeNs', 'realtimeTotalCpuTimeNs' ]; // A custom hook that builds on useLocation to parse the query string function useQuery() { const { search } = useLocation(); return React.useMemo(() => new URLSearchParams(search), [search]); } const QueryPage = () => { const classes = useStyles(); const history = useHistory(); let queryParam = useQuery(); const [fetching, setFetching] = useState(true); const [queryLoader, setQueryLoader] = useState(false); const [tableList, setTableList] = useState<TableData>({ columns: [], records: [], }); const [tableSchema, setTableSchema] = useState<TableData>({ columns: [], records: [], }); const [resultData, setResultData] = useState<TableData>({ columns: [], records: [], }); const [selectedTable, setSelectedTable] = useState(''); const [inputQuery, setInputQuery] = useState(queryParam.get('query') || ''); const [queryTimeout, setQueryTimeout] = useState(Number(queryParam.get('timeout') || '') || ''); const [outputResult, setOutputResult] = useState(''); const [resultError, setResultError] = useState(''); const [queryStats, setQueryStats] = useState<TableData>({ columns: [], records: [], }); const [checked, setChecked] = React.useState({ tracing: queryParam.get('tracing') === 'true', showResultJSON: false, }); const queryExecuted = React.useRef(false); const [boolFlag, setBoolFlag] = useState(false); const [copyMsg, showCopyMsg] = React.useState(false); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { setChecked({ ...checked, [event.target.name]: event.target.checked }); }; const handleOutputDataChange = (editor, data, value) => { setInputQuery(value); }; const handleQueryInterfaceKeyDown = (editor, event) => { // Map Cmd + Enter KeyPress to executing the query if (event.metaKey == true && event.keyCode == 13) { handleRunNow(editor.getValue()); } // Map Cmd + / KeyPress to toggle commenting the query if (event.metaKey == true && event.keyCode == 191) { handleComment(editor); } } const handleComment = (cm: NativeCodeMirror.Editor) => { const selections = cm.listSelections(); if (!selections) { return; } const query = cm.getValue(); const querySplit = query.split(/\r?\n/); _.forEach(selections, (range) => { // anchor and head are based on where the selection starts/ends, but for the purpose // of determining the line number range of the selection, we need start/end in order. const start = Math.min(range.anchor.line, range.head.line); let end = Math.max(range.anchor.line, range.head.line); const isSingleLineSelection = start === end; const isLastLineFirstChar = (range.anchor.line === end && range.anchor.ch === 0) || (range.head.line === end && range.head.ch === 0); // If the selection is on the last line and the first character, we do not comment that line. // This happens if you are using shift + down to select lines. if (isLastLineFirstChar && !isSingleLineSelection) { end = end - 1; } const isEntireSelectionCommented = _.range(start, end + 1).every((line) => { return querySplit[line].startsWith("--") || querySplit[line].trim().length === 0; }); for (let line = start; line <= end; line++) { const lineIsCommented = querySplit[line].startsWith("--"); const lineIsEmpty = querySplit[line].trim().length === 0; if (isEntireSelectionCommented) { // If the entire range is commented, then we uncomment all the lines if (lineIsCommented) { querySplit[line] = querySplit[line].replace(/^--\s*/, ''); } } else { // If the range is not commented, then we comment all the uncommented lines if (!lineIsEmpty && !lineIsCommented) { querySplit[line] = `-- ${querySplit[line]}`; } } } }); setInputQuery(querySplit.join("\n")); } const handleRunNow = async (query?: string) => { setQueryLoader(true); queryExecuted.current = true; let params; let timeoutStr = ''; if(queryTimeout){ timeoutStr = ` option(timeoutMs=${queryTimeout})` } const finalQuery = `${query || inputQuery.trim()}`; params = JSON.stringify({ sql: `${finalQuery}${timeoutStr}`, trace: checked.tracing, }); if(finalQuery !== ''){ queryParam.set('query', finalQuery); queryParam.set('tracing', checked.tracing.toString()); if(queryTimeout !== undefined && queryTimeout !== ''){ queryParam.set('timeout', queryTimeout.toString()); } history.push({ pathname: '/query', search: `?${queryParam.toString()}` }) } const results = await PinotMethodUtils.getQueryResults(params, checked); setResultError(results.error || ''); setResultData(results.result || { columns: [], records: [] }); setQueryStats(results.queryStats || { columns: responseStatCols, records: [] }); setOutputResult(JSON.stringify(results.data, null, 2) || ''); setQueryLoader(false); queryExecuted.current = false; }; const fetchSQLData = async (tableName) => { setQueryLoader(true); const result = await PinotMethodUtils.getTableSchemaData(tableName); const tableSchema = Utils.syncTableSchemaData(result, false); setTableSchema(tableSchema); const query = `select * from ${tableName} limit 10`; setInputQuery(query); setSelectedTable(tableName); handleRunNow(query); }; const downloadData = (exportType) => { const data = Utils.tableFormat(resultData); const fileName = 'Pinot Data Explorer'; exportFromJSON({ data, fileName, exportType }); }; const copyToClipboard = () => { // Create an auxiliary hidden input const aux = document.createElement('input'); // Get the text from the element passed into the input aux.setAttribute('value', JSON.stringify(resultData)); // Append the aux input to the body document.body.appendChild(aux); // Highlight the content aux.select(); // Execute the copy command document.execCommand('copy'); // Remove the input from the body document.body.removeChild(aux); showCopyMsg(true); setTimeout(() => { showCopyMsg(false); }, 3000); }; const fetchData = async () => { const result = await PinotMethodUtils.getQueryTablesList({bothType: false}); setTableList(result); setFetching(false); }; useEffect(() => { fetchData(); if(inputQuery){ handleRunNow(inputQuery); } }, []); useEffect(()=>{ const query = queryParam.get('query'); if(!queryExecuted.current && query){ setInputQuery(query); setChecked({ tracing: queryParam.get('tracing') === 'true', showResultJSON: checked.showResultJSON, }); setQueryTimeout(Number(queryParam.get('timeout') || '') || ''); setBoolFlag(!boolFlag); } }, [queryParam]); useEffect(()=>{ const query = queryParam.get('query'); if(!queryExecuted.current && query){ handleRunNow(); } }, [boolFlag]); const handleSqlHints = (cm: NativeCodeMirror.Editor) => { const tableNames = []; tableList.records.forEach((obj, i) => { tableNames.push(obj[i]); }); const columnNames = tableSchema.records.map((obj) => { return obj[0]; }); const hintOptions = []; const defaultHint = (NativeCodeMirror as any).hint.sql(cm); Array.prototype.push.apply(hintOptions, Utils.generateCodeMirrorOptions(tableNames, 'TABLE')); Array.prototype.push.apply(hintOptions, Utils.generateCodeMirrorOptions(columnNames, 'COLUMNS')); Array.prototype.push.apply(hintOptions, Utils.generateCodeMirrorOptions(sqlFuntionsList, 'FUNCTION')); const cur = cm.getCursor(); const curLine = cm.getLine(cur.line); let start = cur.ch; let end = start; // eslint-disable-next-line no-plusplus while (end < curLine.length && /[\w$]/.test(curLine.charAt(end))) ++end; // eslint-disable-next-line no-plusplus while (start && /[\w$]/.test(curLine.charAt(start - 1))) --start; const curWord = start !== end && curLine.slice(start, end); const regex = new RegExp(`^${ curWord}`, 'i'); const finalList = (!curWord ? hintOptions : hintOptions.filter(function (item) { return item.displayText.match(regex); })).sort(); Array.prototype.push.apply(defaultHint.list, finalList); defaultHint.list = _.uniqBy(defaultHint.list, 'text'); return defaultHint; }; const sqlEditorTooltip = "This editor supports auto-completion feature. Type @ in the editor to see the list of SQL keywords, functions, table name and column names." return fetching ? ( <AppLoader /> ) : ( <> <Grid item> <QuerySideBar tableList={tableList} fetchSQLData={fetchSQLData} tableSchema={tableSchema} selectedTable={selectedTable} queryLoader={queryLoader} /> </Grid> <Grid item xs style={{ padding: 20, backgroundColor: 'white', maxHeight: 'calc(100vh - 70px)', overflowY: 'auto', }} > <Grid container> <Grid item xs={12} className={classes.rightPanel}> <Resizable defaultSize={{ width: '100%', height: 148, }} minHeight={148} maxWidth={'100%'} maxHeight={'50vh'} enable={{bottom: true}}> <div className={classes.sqlDiv}> <TableToolbar name="SQL Editor" showSearchBox={false} showTooltip={true} tooltipText={sqlEditorTooltip} /> <CodeMirror options={{ ...sqloptions, hintOptions: { hint: handleSqlHints, }, }} value={inputQuery} onChange={handleOutputDataChange} onKeyDown={handleQueryInterfaceKeyDown} className={classes.codeMirror} autoCursor={false} /> </div> </Resizable> <Grid container className={classes.checkBox}> <Grid item xs={2}> <Checkbox name="tracing" color="primary" onChange={handleChange} checked={checked.tracing} /> Tracing </Grid> <Grid item xs={3}> <FormControl fullWidth={true} className={classes.timeoutControl}> <InputLabel htmlFor="my-input">Timeout (in Milliseconds)</InputLabel> <Input id="my-input" type="number" value={queryTimeout} onChange={(e)=> setQueryTimeout(Number(e.target.value) || '')}/> </FormControl> </Grid> <Grid item xs={3} className={classes.runNowBtn}> <Button variant="contained" color="primary" onClick={() => handleRunNow()} > Run Query </Button> </Grid> </Grid> {queryLoader ? ( <AppLoader /> ) : ( <> {queryStats.columns.length ? ( <Grid item xs style={{ backgroundColor: 'white' }}> <CustomizedTables title="Query Response Stats" data={queryStats} showSearchBox={true} inAccordionFormat={true} /> </Grid> ) : null} {resultError ? ( <Alert severity="error" className={classes.sqlError}> {resultError} </Alert> ) : ( <> <Grid item xs style={{ backgroundColor: 'white' }}> {resultData.columns.length ? ( <> <Grid container className={classes.actionBtns}> <Button variant="contained" color="primary" size="small" className={classes.btn} onClick={() => downloadData('xls')} > Excel </Button> <Button variant="contained" color="primary" size="small" className={classes.btn} onClick={() => downloadData('csv')} > CSV </Button> <Button variant="contained" color="primary" size="small" className={classes.btn} onClick={() => copyToClipboard()} > Copy </Button> {copyMsg ? ( <Alert icon={<FileCopyIcon fontSize="inherit" />} severity="info" > Copied {resultData.records.length} rows to Clipboard </Alert> ) : null} <FormControlLabel control={ <Switch checked={checked.showResultJSON} onChange={handleChange} name="showResultJSON" color="primary" /> } label="Show JSON format" className={classes.runNowBtn} /> </Grid> {!checked.showResultJSON ? ( <CustomizedTables title="Query Result" data={resultData} isPagination isSticky={true} showSearchBox={true} inAccordionFormat={true} /> ) : resultData.columns.length ? ( <SimpleAccordion headerTitle="Query Result (JSON Format)" showSearchBox={false} > <CodeMirror options={jsonoptions} value={outputResult} className={classes.queryOutput} autoCursor={false} /> </SimpleAccordion> ) : null} </> ) : null} </Grid> </> )} </> )} </Grid> </Grid> </Grid> </> ); }; export default QueryPage;
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { DomainServices } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { DomainServicesClient } from "../domainServicesClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { DomainService, DomainServicesListNextOptionalParams, DomainServicesListOptionalParams, DomainServicesListByResourceGroupNextOptionalParams, DomainServicesListByResourceGroupOptionalParams, DomainServicesListResponse, DomainServicesListByResourceGroupResponse, DomainServicesCreateOrUpdateOptionalParams, DomainServicesCreateOrUpdateResponse, DomainServicesGetOptionalParams, DomainServicesGetResponse, DomainServicesDeleteOptionalParams, DomainServicesUpdateOptionalParams, DomainServicesUpdateResponse, DomainServicesListNextResponse, DomainServicesListByResourceGroupNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing DomainServices operations. */ export class DomainServicesImpl implements DomainServices { private readonly client: DomainServicesClient; /** * Initialize a new instance of the class DomainServices class. * @param client Reference to the service client */ constructor(client: DomainServicesClient) { this.client = client; } /** * The List Domain Services in Subscription operation lists all the domain services available under the * given subscription (and across all resource groups within that subscription). * @param options The options parameters. */ public list( options?: DomainServicesListOptionalParams ): PagedAsyncIterableIterator<DomainService> { const iter = this.listPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(options); } }; } private async *listPagingPage( options?: DomainServicesListOptionalParams ): AsyncIterableIterator<DomainService[]> { let result = await this._list(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( options?: DomainServicesListOptionalParams ): AsyncIterableIterator<DomainService> { for await (const page of this.listPagingPage(options)) { yield* page; } } /** * The List Domain Services in Resource Group operation lists all the domain services available under * the given resource group. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: DomainServicesListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<DomainService> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: DomainServicesListByResourceGroupOptionalParams ): AsyncIterableIterator<DomainService[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByResourceGroupNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: DomainServicesListByResourceGroupOptionalParams ): AsyncIterableIterator<DomainService> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * The List Domain Services in Subscription operation lists all the domain services available under the * given subscription (and across all resource groups within that subscription). * @param options The options parameters. */ private _list( options?: DomainServicesListOptionalParams ): Promise<DomainServicesListResponse> { return this.client.sendOperationRequest({ options }, listOperationSpec); } /** * The List Domain Services in Resource Group operation lists all the domain services available under * the given resource group. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: DomainServicesListByResourceGroupOptionalParams ): Promise<DomainServicesListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * The Create Domain Service operation creates a new domain service with the specified parameters. If * the specific service already exists, then any patchable properties will be updated and any immutable * properties will remain unchanged. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param domainServiceName The name of the domain service. * @param domainService Properties supplied to the Create or Update a Domain Service operation. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, domainServiceName: string, domainService: DomainService, options?: DomainServicesCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<DomainServicesCreateOrUpdateResponse>, DomainServicesCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<DomainServicesCreateOrUpdateResponse> => { 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, domainServiceName, domainService, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * The Create Domain Service operation creates a new domain service with the specified parameters. If * the specific service already exists, then any patchable properties will be updated and any immutable * properties will remain unchanged. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param domainServiceName The name of the domain service. * @param domainService Properties supplied to the Create or Update a Domain Service operation. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, domainServiceName: string, domainService: DomainService, options?: DomainServicesCreateOrUpdateOptionalParams ): Promise<DomainServicesCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, domainServiceName, domainService, options ); return poller.pollUntilDone(); } /** * The Get Domain Service operation retrieves a json representation of the Domain Service. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param domainServiceName The name of the domain service. * @param options The options parameters. */ get( resourceGroupName: string, domainServiceName: string, options?: DomainServicesGetOptionalParams ): Promise<DomainServicesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, domainServiceName, options }, getOperationSpec ); } /** * The Delete Domain Service operation deletes an existing Domain Service. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param domainServiceName The name of the domain service. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, domainServiceName: string, options?: DomainServicesDeleteOptionalParams ): 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, domainServiceName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * The Delete Domain Service operation deletes an existing Domain Service. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param domainServiceName The name of the domain service. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, domainServiceName: string, options?: DomainServicesDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, domainServiceName, options ); return poller.pollUntilDone(); } /** * The Update Domain Service operation can be used to update the existing deployment. The update call * only supports the properties listed in the PATCH body. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param domainServiceName The name of the domain service. * @param domainService Properties supplied to the Update a Domain Service operation. * @param options The options parameters. */ async beginUpdate( resourceGroupName: string, domainServiceName: string, domainService: DomainService, options?: DomainServicesUpdateOptionalParams ): Promise< PollerLike< PollOperationState<DomainServicesUpdateResponse>, DomainServicesUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<DomainServicesUpdateResponse> => { 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, domainServiceName, domainService, options }, updateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * The Update Domain Service operation can be used to update the existing deployment. The update call * only supports the properties listed in the PATCH body. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param domainServiceName The name of the domain service. * @param domainService Properties supplied to the Update a Domain Service operation. * @param options The options parameters. */ async beginUpdateAndWait( resourceGroupName: string, domainServiceName: string, domainService: DomainService, options?: DomainServicesUpdateOptionalParams ): Promise<DomainServicesUpdateResponse> { const poller = await this.beginUpdate( resourceGroupName, domainServiceName, domainService, options ); return poller.pollUntilDone(); } /** * ListNext * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( nextLink: string, options?: DomainServicesListNextOptionalParams ): Promise<DomainServicesListNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listNextOperationSpec ); } /** * ListByResourceGroupNext * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method. * @param options The options parameters. */ private _listByResourceGroupNext( resourceGroupName: string, nextLink: string, options?: DomainServicesListByResourceGroupNextOptionalParams ): Promise<DomainServicesListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listByResourceGroupNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.AAD/domainServices", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DomainServiceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AAD/domainServices", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DomainServiceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AAD/domainServices/{domainServiceName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.DomainService }, 201: { bodyMapper: Mappers.DomainService }, 202: { bodyMapper: Mappers.DomainService }, 204: { bodyMapper: Mappers.DomainService }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.domainService, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.domainServiceName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AAD/domainServices/{domainServiceName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DomainService }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.domainServiceName ], headerParameters: [Parameters.accept], serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AAD/domainServices/{domainServiceName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.domainServiceName ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AAD/domainServices/{domainServiceName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.DomainService }, 201: { bodyMapper: Mappers.DomainService }, 202: { bodyMapper: Mappers.DomainService }, 204: { bodyMapper: Mappers.DomainService }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.domainService, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.domainServiceName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DomainServiceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DomainServiceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer };
the_stack
import { AudioTransformDevice, AudioVideoFacade, AudioVideoObserver, ConsoleLogger, DefaultActiveSpeakerPolicy, DefaultDeviceController, DefaultMeetingSession, Device, EventAttributes, EventName, EventReporter, isAudioTransformDevice, isVideoTransformDevice, Logger, LogLevel, MeetingSessionConfiguration, MeetingSessionPOSTLogger, MeetingSessionStatus, MeetingSessionStatusCode, MultiLogger, VideoDownlinkBandwidthPolicy, VideoTransformDevice, } from 'amazon-chime-sdk-js'; import { DeviceLabels, DeviceLabelTrigger, MeetingStatus } from '../../types'; import { audioInputSelectionToDevice, supportsSetSinkId, videoInputSelectionToDevice, } from '../../utils/device-utils'; import { AttendeeResponse, DevicePermissionStatus, FullDeviceInfoType, MeetingJoinData, MeetingManagerConfig, PostLogConfig, } from './types'; function noOpDeviceLabelHook(): Promise<MediaStream> { return Promise.resolve(new MediaStream()); } export class MeetingManager implements AudioVideoObserver { meetingSession: DefaultMeetingSession | null = null; meetingStatus: MeetingStatus = MeetingStatus.Loading; meetingStatusObservers: ((meetingStatus: MeetingStatus) => void)[] = []; audioVideo: AudioVideoFacade | null = null; audioVideoObservers: AudioVideoObserver = {}; configuration: MeetingSessionConfiguration | null = null; meetingId: string | null = null; meetingRegion: string | null = null; getAttendee?: ( chimeAttendeeId: string, externalUserId?: string ) => Promise<AttendeeResponse>; selectedAudioOutputDevice: string | null = null; selectedAudioOutputDeviceObservers: ((deviceId: string | null) => void)[] = []; selectedAudioInputDevice: string | null = null; selectedAudioInputTransformDevice: Device | AudioTransformDevice | null = null; selectedAudioInputDeviceObservers: ((deviceId: string | null) => void)[] = []; selectedAudioInputTransformDeviceObservers: (( device: Device | AudioTransformDevice | null ) => void)[] = []; selectAudioInputDeviceError: Error | null = null; selectAudioInputDeviceErrorObservers: (( selectAudioInputDeviceError: Error | null ) => void)[] = []; selectedVideoInputDevice: string | null = null; selectedVideoInputTransformDevice: Device | VideoTransformDevice | null = null; selectedVideoInputTransformDeviceObservers: (( device: Device | VideoTransformDevice | null ) => void)[] = []; selectedVideoInputDeviceObservers: ((deviceId: string | null) => void)[] = []; selectVideoInputDeviceError: Error | null = null; selectVideoInputDeviceErrorObservers: (( selectVideoInputDeviceError: Error | null ) => void)[] = []; deviceLabelTriggerChangeObservers: (() => void)[] = []; audioInputDevices: MediaDeviceInfo[] | null = null; audioOutputDevices: MediaDeviceInfo[] | null = null; videoInputDevices: MediaDeviceInfo[] | null = null; devicePermissionStatus = DevicePermissionStatus.UNSET; devicePermissionsObservers: ((permission: DevicePermissionStatus) => void)[] = []; activeSpeakerListener: ((activeSpeakers: string[]) => void) | null = null; activeSpeakerCallbacks: ((activeSpeakers: string[]) => void)[] = []; activeSpeakers: string[] = []; audioVideoCallbacks: ((audioVideo: AudioVideoFacade | null) => void)[] = []; devicesUpdatedCallbacks: ((fullDeviceInfo: FullDeviceInfoType) => void)[] = []; // This variable will be deprecated in favor of `meetingManagerConfig`. // Please use `meetingManagerConfig` to use `MeetingManagerConfig` values. logLevel: LogLevel = LogLevel.WARN; // This variable will be deprecated in favor of `meetingManagerConfig`. // Please use `meetingManagerConfig` to use `MeetingManagerConfig` values. postLoggerConfig: PostLogConfig | null = null; eventReporter: EventReporter; // This variable will be deprecated in favor of `meetingManagerConfig`. // Please use `meetingManagerConfig` to use `MeetingManagerConfig` values. simulcastEnabled: boolean = false; // This variable will be deprecated in favor of `meetingManagerConfig`. // Please use `meetingManagerConfig` to use `MeetingManagerConfig` values. videoDownlinkBandwidthPolicy: VideoDownlinkBandwidthPolicy | undefined; // This variable will be deprecated in favor of `meetingManagerConfig`. // Please use `meetingManagerConfig` to use `MeetingManagerConfig` values. logger: Logger | undefined; private meetingEventObserverSet = new Set< (name: EventName, attributes: EventAttributes) => void >(); private eventDidReceiveRef: AudioVideoObserver; constructor(private meetingManagerConfig: MeetingManagerConfig) { const { simulcastEnabled, logger: configLogger, logLevel, postLogConfig, videoDownlinkBandwidthPolicy, } = this.meetingManagerConfig; // We are assigning the values from the `meetingManagerConfig` to preserve backward compatibility. // Please use `this.meetingManagerConfig` for any values going forward. if (simulcastEnabled) { this.simulcastEnabled = simulcastEnabled; } if (configLogger) { this.logger = configLogger; } else { this.logLevel = logLevel; if (postLogConfig) { this.postLoggerConfig = postLogConfig; } } if (videoDownlinkBandwidthPolicy) { this.videoDownlinkBandwidthPolicy = videoDownlinkBandwidthPolicy; } this.eventDidReceiveRef = { eventDidReceive: (name: EventName, attributes: EventAttributes) => { this.publishEventDidReceiveUpdate(name, attributes); }, }; } initializeMeetingManager(): void { this.meetingSession = null; this.audioVideo = null; this.configuration = null; this.meetingId = null; this.meetingRegion = null; this.selectedAudioOutputDevice = null; this.selectedAudioInputDevice = null; this.selectedAudioInputTransformDevice = null; this.selectedVideoInputDevice = null; this.selectedVideoInputTransformDevice = null; this.selectAudioInputDeviceError = null; this.selectVideoInputDeviceError = null; this.audioInputDevices = []; this.audioOutputDevices = []; this.videoInputDevices = []; this.activeSpeakers = []; this.activeSpeakerListener = null; this.audioVideoObservers = {}; } async join({ meetingInfo, attendeeInfo, deviceLabels = DeviceLabels.AudioAndVideo, eventReporter, meetingManagerConfig, }: MeetingJoinData) { if (meetingManagerConfig) { this.meetingManagerConfig = meetingManagerConfig; } this.configuration = new MeetingSessionConfiguration( meetingInfo, attendeeInfo ); this.meetingRegion = meetingInfo.MediaRegion; this.meetingId = this.configuration.meetingId; if (eventReporter) { this.eventReporter = eventReporter; } await this.initializeMeetingSession(this.configuration, deviceLabels); } async start(): Promise<void> { this.audioVideo?.start(); } async leave(): Promise<void> { if (this.audioVideo) { this.audioVideo.stopContentShare(); this.audioVideo.stopLocalVideoTile(); this.audioVideo.unbindAudioElement(); try { await this.audioVideo.chooseVideoInputDevice(null); await this.audioVideo.chooseAudioInputDevice(null); await this.audioVideo.chooseAudioOutputDevice(null); } catch (error) { console.log('Unable to set device to null on leave.'); } if (this.activeSpeakerListener) { this.audioVideo.unsubscribeFromActiveSpeakerDetector( this.activeSpeakerListener ); } this.audioVideo.stop(); } this.initializeMeetingManager(); this.publishAudioVideo(); this.publishActiveSpeaker(); } async initializeMeetingSession( configuration: MeetingSessionConfiguration, deviceLabels: DeviceLabels | DeviceLabelTrigger = DeviceLabels.AudioAndVideo ): Promise<any> { const { simulcastEnabled, enableWebAudio, logger: configLogger, videoUplinkBandwidthPolicy, videoDownlinkBandwidthPolicy, } = this.meetingManagerConfig; // We are assigning the values from the `meetingManagerConfig` to preserve backward compatibility. // Please use `this.meetingManagerConfig` for any values going forward. if (simulcastEnabled) { configuration.enableUnifiedPlanForChromiumBasedBrowsers = true; configuration.enableSimulcastForUnifiedPlanChromiumBasedBrowsers = true; } const logger = configLogger ? configLogger : this.createLogger(configuration); if (videoUplinkBandwidthPolicy) { configuration.videoUplinkBandwidthPolicy = videoUplinkBandwidthPolicy; } if (videoDownlinkBandwidthPolicy) { configuration.videoDownlinkBandwidthPolicy = videoDownlinkBandwidthPolicy; } const deviceController = new DefaultDeviceController(logger, { enableWebAudio, }); this.meetingSession = new DefaultMeetingSession( configuration, logger, deviceController, this.eventReporter ); this.audioVideo = this.meetingSession.audioVideo; // When an attendee leaves, we remove AudioVideoObservers and nullify AudioVideoFacade and MeetingSession object. // This results into missing few meeting events triggered with audioVideoDidStop such as meetingEnded, meetingFailed and meetingStartFailed. // We may also loose audioInputUnselected and videoInputUnselected events as we choose null devices when an attendee leaves. // When a new AudioVideoFacade object is created remove and re-add the eventDidReceive observer which wont leak. this.audioVideo.removeObserver(this.eventDidReceiveRef); this.audioVideo.addObserver(this.eventDidReceiveRef); this.setupAudioVideoObservers(); this.setupDeviceLabelTrigger(deviceLabels); await this.listAndSelectDevices(deviceLabels); this.publishAudioVideo(); this.setupActiveSpeakerDetection(); this.meetingStatus = MeetingStatus.Loading; this.publishMeetingStatus(); } createLogger(configuration: MeetingSessionConfiguration) { const { logLevel, postLogConfig } = this.meetingManagerConfig; const consoleLogger = new ConsoleLogger('SDK', logLevel); let logger: ConsoleLogger | MultiLogger = consoleLogger; if (postLogConfig) { const { name, batchSize, intervalMs, url, logLevel } = postLogConfig; logger = new MultiLogger( consoleLogger, new MeetingSessionPOSTLogger( name, configuration, batchSize, intervalMs, url, logLevel ) ); } return logger; } audioVideoDidStart = () => { console.log( '[MeetingManager audioVideoDidStart] Meeting started successfully' ); this.meetingStatus = MeetingStatus.Succeeded; this.publishMeetingStatus(); }; audioVideoDidStop = (sessionStatus: MeetingSessionStatus) => { const sessionStatusCode = sessionStatus.statusCode(); switch (sessionStatusCode) { case MeetingSessionStatusCode.AudioCallEnded: console.log( `[MeetingManager audioVideoDidStop] Meeting ended for all: ${sessionStatusCode}` ); this.meetingStatus = MeetingStatus.Ended; this.publishMeetingStatus(); this.leave(); break; case MeetingSessionStatusCode.Left: console.log( `[MeetingManager audioVideoDidStop] Left the meeting: ${sessionStatusCode}` ); this.meetingStatus = MeetingStatus.Left; this.publishMeetingStatus(); this.leave(); break; case MeetingSessionStatusCode.AudioJoinedFromAnotherDevice: console.log( `[MeetingManager audioVideoDidStop] Meeting joined from another device: ${sessionStatusCode}` ); this.meetingStatus = MeetingStatus.JoinedFromAnotherDevice; this.publishMeetingStatus(); this.leave(); break; default: // The following status codes are Failures according to MeetingSessionStatus if (sessionStatus.isFailure()) { console.log( `[MeetingManager audioVideoDidStop] Non-Terminal failure occured: ${sessionStatusCode}` ); this.meetingStatus = MeetingStatus.Failed; this.publishMeetingStatus(); } else if (sessionStatus.isTerminal()) { console.log( `[MeetingManager audioVideoDidStop] Terminal failure occured: ${sessionStatusCode}` ); this.meetingStatus = MeetingStatus.TerminalFailure; this.publishMeetingStatus(); } console.log( `[MeetingManager audioVideoDidStop] session stopped with code ${sessionStatusCode}` ); this.leave(); } if (this.audioVideo) { this.audioVideo.removeObserver(this.audioVideoObservers); } }; setupAudioVideoObservers() { if (!this.audioVideo) { return; } this.audioVideoObservers = { audioVideoDidStart: this.audioVideoDidStart, audioVideoDidStop: this.audioVideoDidStop, }; this.audioVideo.addObserver(this.audioVideoObservers); } async updateDeviceLists(): Promise<void> { this.audioInputDevices = (await this.audioVideo?.listAudioInputDevices()) || []; this.videoInputDevices = (await this.audioVideo?.listVideoInputDevices()) || []; this.audioOutputDevices = (await this.audioVideo?.listAudioOutputDevices()) || []; } setupDeviceLabelTrigger( deviceLabels: DeviceLabels | DeviceLabelTrigger = DeviceLabels.AudioAndVideo ): void { let callback: DeviceLabelTrigger; if (typeof deviceLabels === 'function') { callback = deviceLabels; } else if (deviceLabels === DeviceLabels.None) { callback = noOpDeviceLabelHook; } else { const constraints: MediaStreamConstraints = {}; switch (deviceLabels) { case DeviceLabels.Audio: constraints.audio = true; break; case DeviceLabels.Video: constraints.video = true; break; case DeviceLabels.AudioAndVideo: constraints.audio = true; constraints.video = true; break; } callback = async (): Promise<MediaStream> => { this.devicePermissionStatus = DevicePermissionStatus.IN_PROGRESS; this.publishDevicePermissionStatus(); try { const devices = await navigator.mediaDevices.enumerateDevices(); const hasVideoInput = devices.some( (value) => value.kind === 'videoinput' ); const stream = await navigator.mediaDevices.getUserMedia({ audio: constraints.audio, video: constraints.video && hasVideoInput, }); this.devicePermissionStatus = DevicePermissionStatus.GRANTED; this.publishDevicePermissionStatus(); return stream; } catch (error) { console.error('Failed to get device permissions'); this.devicePermissionStatus = DevicePermissionStatus.DENIED; this.publishDevicePermissionStatus(); throw new Error(error); } }; } this.audioVideo?.setDeviceLabelTrigger(callback); } setupActiveSpeakerDetection(): void { const activeSpeakerPolicy = this.meetingManagerConfig.activeSpeakerPolicy; this.publishActiveSpeaker(); this.activeSpeakerListener = (activeSpeakers: string[]) => { this.activeSpeakers = activeSpeakers; this.activeSpeakerCallbacks.forEach((cb) => cb(activeSpeakers)); }; this.audioVideo?.subscribeToActiveSpeakerDetector( activeSpeakerPolicy ? activeSpeakerPolicy : new DefaultActiveSpeakerPolicy(), this.activeSpeakerListener ); } async listAndSelectDevices( deviceLabels: DeviceLabels | DeviceLabelTrigger = DeviceLabels.AudioAndVideo ): Promise<void> { await this.updateDeviceLists(); // If `deviceLabels` is of `DeviceLabelTrigger` type, no device will be selected. // In this case, you need to handle the device selection yourself. if (typeof deviceLabels === 'function') return; let isAudioDeviceRequested: boolean = false; let isVideoDeviceRequested: boolean = false; switch (deviceLabels) { case DeviceLabels.None: break; case DeviceLabels.Audio: isAudioDeviceRequested = true; break; case DeviceLabels.Video: isVideoDeviceRequested = true; break; case DeviceLabels.AudioAndVideo: isAudioDeviceRequested = true; isVideoDeviceRequested = true; break; } if ( isAudioDeviceRequested && !this.selectedAudioInputDevice && this.audioInputDevices && this.audioInputDevices.length ) { this.selectedAudioInputDevice = this.audioInputDevices[0].deviceId; this.selectedAudioInputTransformDevice = this.selectedAudioInputDevice; try { await this.audioVideo?.chooseAudioInputDevice( this.audioInputDevices[0].deviceId ); } catch (error) { console.error(`Error in selecting audio input device - ${error}`); } this.publishSelectedAudioInputDevice(); this.publishSelectedAudioInputTransformDevice(); } if ( isAudioDeviceRequested && !this.selectedAudioOutputDevice && this.audioOutputDevices && this.audioOutputDevices.length ) { this.selectedAudioOutputDevice = this.audioOutputDevices[0].deviceId; if (supportsSetSinkId()) { try { await this.audioVideo?.chooseAudioOutputDevice( this.audioOutputDevices[0].deviceId ); } catch (error) { console.error('Failed to choose audio output device.', error); } } this.publishSelectedAudioOutputDevice(); } if ( isVideoDeviceRequested && !this.selectedVideoInputDevice && this.videoInputDevices && this.videoInputDevices.length ) { this.selectedVideoInputDevice = this.videoInputDevices[0].deviceId; this.selectedVideoInputTransformDevice = this.selectedVideoInputDevice; this.publishSelectedVideoInputDevice(); this.publishSelectedVideoInputTransformDevice(); } } selectAudioInputDevice = async ( device: Device | AudioTransformDevice ): Promise<void> => { let receivedDevice = device; if (typeof device === 'string') { receivedDevice = audioInputSelectionToDevice(device); } if (receivedDevice === null) { try { await this.audioVideo?.chooseAudioInputDevice(null); this.selectAudioInputDeviceError = null; } catch (error) { this.selectAudioInputDeviceError = error; console.error('Failed to choose audio input device.', error); } this.selectedAudioInputTransformDevice = null; this.selectedAudioInputDevice = null; } else { try { await this.audioVideo?.chooseAudioInputDevice(receivedDevice); this.selectAudioInputDeviceError = null; } catch (error) { this.selectAudioInputDeviceError = error; console.error('Failed to choose audio input device.', error); } let innerDevice = null; if (isAudioTransformDevice(device)) { innerDevice = await device.intrinsicDevice(); } else { innerDevice = device; } const deviceId = DefaultDeviceController.getIntrinsicDeviceId(innerDevice); if (typeof deviceId === 'string') { this.selectedAudioInputDevice = deviceId; } else if (Array.isArray(deviceId) && deviceId[0]) { this.selectedAudioInputDevice = deviceId[0]; } this.selectedAudioInputTransformDevice = device; } this.publishSelectedAudioInputDevice(); this.publishSelectAudioInputDeviceError(); this.publishSelectedAudioInputTransformDevice(); }; selectAudioOutputDevice = async (deviceId: string): Promise<void> => { try { await this.audioVideo?.chooseAudioOutputDevice(deviceId); this.selectedAudioOutputDevice = deviceId; this.publishSelectedAudioOutputDevice(); } catch (error) { console.error(`Error setting audio output`, error); } }; selectVideoInputDevice = async ( device: Device | VideoTransformDevice ): Promise<void> => { let receivedDevice = device; if (typeof device === 'string') { receivedDevice = videoInputSelectionToDevice(device); } if (receivedDevice === null) { try { await this.audioVideo?.chooseVideoInputDevice(null); this.selectVideoInputDeviceError = null; } catch (error) { this.selectVideoInputDeviceError = error; console.error('Failed to choose video input device.', error); } this.selectedVideoInputDevice = null; this.selectedVideoInputTransformDevice = null; } else { try { await this.audioVideo?.chooseVideoInputDevice(receivedDevice); this.selectVideoInputDeviceError = null; } catch (error) { this.selectVideoInputDeviceError = error; console.error('Failed to choose video input device.', error); } let innerDevice = null; if (isVideoTransformDevice(device)) { innerDevice = await device.intrinsicDevice(); } else { innerDevice = device; } const deviceId = DefaultDeviceController.getIntrinsicDeviceId(innerDevice); if (typeof deviceId === 'string') { this.selectedVideoInputDevice = deviceId; } else if (Array.isArray(deviceId) && deviceId[0]) { this.selectedVideoInputDevice = deviceId[0]; } this.selectedVideoInputTransformDevice = device; } this.publishSelectedVideoInputDevice(); this.publishSelectVideoInputDeviceError(); this.publishSelectedVideoInputTransformDevice(); }; invokeDeviceProvider = (deviceLabels: DeviceLabels) => { this.setupDeviceLabelTrigger(deviceLabels); this.publishDeviceLabelTriggerChange(); }; /** * ==================================================================== * Subscriptions * ==================================================================== */ subscribeToAudioVideo = ( callback: (av: AudioVideoFacade | null) => void ): void => { this.audioVideoCallbacks.push(callback); }; unsubscribeFromAudioVideo = ( callbackToRemove: (av: AudioVideoFacade | null) => void ): void => { this.audioVideoCallbacks = this.audioVideoCallbacks.filter( (callback) => callback !== callbackToRemove ); }; publishAudioVideo = () => { this.audioVideoCallbacks.forEach((callback) => { callback(this.audioVideo); }); }; subscribeToActiveSpeaker = ( callback: (activeSpeakers: string[]) => void ): void => { this.activeSpeakerCallbacks.push(callback); callback(this.activeSpeakers); }; unsubscribeFromActiveSpeaker = ( callbackToRemove: (activeSpeakers: string[]) => void ): void => { this.activeSpeakerCallbacks = this.activeSpeakerCallbacks.filter( (callback) => callback !== callbackToRemove ); }; publishActiveSpeaker = () => { this.activeSpeakerCallbacks.forEach((callback) => { callback(this.activeSpeakers); }); }; subscribeToDevicePermissionStatus = ( callback: (permission: DevicePermissionStatus) => void ): void => { this.devicePermissionsObservers.push(callback); }; unsubscribeFromDevicePermissionStatus = ( callbackToRemove: (permission: DevicePermissionStatus) => void ): void => { this.devicePermissionsObservers = this.devicePermissionsObservers.filter( (callback) => callback !== callbackToRemove ); }; private publishDevicePermissionStatus = (): void => { for (const observer of this.devicePermissionsObservers) { observer(this.devicePermissionStatus); } }; subscribeToSelectedVideoInputDevice = ( callback: (deviceId: string | null) => void ): void => { this.selectedVideoInputDeviceObservers.push(callback); }; unsubscribeFromSelectedVideoInputDevice = ( callbackToRemove: (deviceId: string | null) => void ): void => { this.selectedVideoInputDeviceObservers = this.selectedVideoInputDeviceObservers.filter( (callback) => callback !== callbackToRemove ); }; private publishSelectedVideoInputDevice = (): void => { for (const observer of this.selectedVideoInputDeviceObservers) { observer(this.selectedVideoInputDevice); } }; subscribeToSelectedVideoInputTransformDevice = ( callback: (device: Device | VideoTransformDevice) => void ): void => { this.selectedVideoInputTransformDeviceObservers.push(callback); }; unsubscribeFromSelectedVideoInputTranformDevice = ( callbackToRemove: (device: Device | VideoTransformDevice) => void ): void => { this.selectedVideoInputTransformDeviceObservers = this.selectedVideoInputTransformDeviceObservers.filter( (callback) => callback !== callbackToRemove ); }; private publishSelectedVideoInputTransformDevice = (): void => { for (const observer of this.selectedVideoInputTransformDeviceObservers) { observer(this.selectedVideoInputTransformDevice); } }; subscribeToSelectedAudioInputDevice = ( callback: (deviceId: string | null) => void ): void => { this.selectedAudioInputDeviceObservers.push(callback); }; subscribeToSelectedAudioInputTransformDevice = ( callback: (device: Device | AudioTransformDevice | null) => void ): void => { this.selectedAudioInputTransformDeviceObservers.push(callback); }; unsubscribeFromSelectedAudioInputDevice = ( callbackToRemove: (deviceId: string | null) => void ): void => { this.selectedAudioInputDeviceObservers = this.selectedAudioInputDeviceObservers.filter( (callback) => callback !== callbackToRemove ); }; unsubscribeFromSelectedAudioInputTransformDevice = ( callbackToRemove: (device: Device | AudioTransformDevice | null) => void ): void => { this.selectedAudioInputTransformDeviceObservers = this.selectedAudioInputTransformDeviceObservers.filter( (callback) => callback !== callbackToRemove ); }; private publishSelectedAudioInputDevice = (): void => { for (const observer of this.selectedAudioInputDeviceObservers) { observer(this.selectedAudioInputDevice); } }; private publishSelectedAudioInputTransformDevice = (): void => { for (const observer of this.selectedAudioInputTransformDeviceObservers) { observer(this.selectedAudioInputTransformDevice); } }; subscribeToSelectedAudioOutputDevice = ( callback: (deviceId: string | null) => void ): void => { this.selectedAudioOutputDeviceObservers.push(callback); }; unsubscribeFromSelectedAudioOutputDevice = ( callbackToRemove: (deviceId: string | null) => void ): void => { this.selectedAudioOutputDeviceObservers = this.selectedAudioOutputDeviceObservers.filter( (callback) => callback !== callbackToRemove ); }; private publishSelectedAudioOutputDevice = (): void => { for (const observer of this.selectedAudioOutputDeviceObservers) { observer(this.selectedAudioOutputDevice); } }; subscribeToMeetingStatus = ( callback: (meetingStatus: MeetingStatus) => void ): void => { this.meetingStatusObservers.push(callback); callback(this.meetingStatus); }; unsubscribeFromMeetingStatus = ( callbackToRemove: (meetingStatus: MeetingStatus) => void ): void => { this.meetingStatusObservers = this.meetingStatusObservers.filter( (callback) => callback !== callbackToRemove ); }; private publishMeetingStatus = () => { this.meetingStatusObservers.forEach((callback) => { callback(this.meetingStatus); }); }; subscribeToSelectAudioInputDeviceError = ( callback: (errorMessage: Error | null) => void ): void => { this.selectAudioInputDeviceErrorObservers.push(callback); }; unsubscribeFromSelectAudioInputDeviceError = ( callbackToRemove: (errorMessage: Error | null) => void ): void => { this.selectAudioInputDeviceErrorObservers = this.selectAudioInputDeviceErrorObservers.filter( (callback) => callback !== callbackToRemove ); }; private publishSelectAudioInputDeviceError = (): void => { for (const observer of this.selectAudioInputDeviceErrorObservers) { observer(this.selectAudioInputDeviceError); } }; subscribeToSelectVideoInputDeviceError = ( callback: (errorMessage: Error | null) => void ): void => { this.selectVideoInputDeviceErrorObservers.push(callback); }; unsubscribeFromSelectVideoInputDeviceError = ( callbackToRemove: (errorMessage: Error | null) => void ): void => { this.selectVideoInputDeviceErrorObservers = this.selectVideoInputDeviceErrorObservers.filter( (callback) => callback !== callbackToRemove ); }; private publishSelectVideoInputDeviceError = (): void => { for (const observer of this.selectVideoInputDeviceErrorObservers) { observer(this.selectVideoInputDeviceError); } }; subscribeToDeviceLabelTriggerChange = (callback: () => void): void => { this.deviceLabelTriggerChangeObservers.push(callback); }; unsubscribeFromDeviceLabelTriggerChange = ( callbackToRemove: () => void ): void => { this.deviceLabelTriggerChangeObservers = this.deviceLabelTriggerChangeObservers.filter( (callback) => callback !== callbackToRemove ); }; private publishDeviceLabelTriggerChange = (): void => { for (const callback of this.deviceLabelTriggerChangeObservers) { callback(); } }; subscribeToEventDidReceive = ( callback: (name: EventName, attributes: EventAttributes) => void ): void => { this.meetingEventObserverSet.add(callback); }; unsubscribeFromEventDidReceive = ( callbackToRemove: (name: EventName, attributes: EventAttributes) => void ): void => { this.meetingEventObserverSet.delete(callbackToRemove); }; private publishEventDidReceiveUpdate = ( name: EventName, attributes: EventAttributes ) => { this.meetingEventObserverSet.forEach((callback) => callback(name, attributes) ); }; } export default MeetingManager;
the_stack
import { Quaternion, Vector2, Vector3, Vector4 } from "@oasis-engine/math"; import { InterpolableValueType } from "./enums/InterpolableValueType"; import { InterpolationType } from "./enums/InterpolationType"; import { FloatArrayKeyframe, FloatKeyframe, InterpolableValue, QuaternionKeyframe, UnionInterpolableKeyframe, Vector2Keyframe, Vector3Keyframe } from "./KeyFrame"; /** * Store a collection of Keyframes that can be evaluated over time. */ export class AnimationCurve { /** All keys defined in the animation curve. */ keys: UnionInterpolableKeyframe[] = []; /** The interpolationType of the animation curve. */ interpolation: InterpolationType; /** @internal */ _valueSize: number; /** @internal */ _valueType: InterpolableValueType; private _currentValue: InterpolableValue; private _length: number = 0; private _currentIndex: number = 0; /** * Animation curve length in seconds. */ get length(): number { return this._length; } /** * Add a new key to the curve. * @param key - The keyframe */ addKey(key: UnionInterpolableKeyframe): void { const { time } = key; this.keys.push(key); if (time > this._length) { this._length = time; } if (!this._valueSize) { //CM: It's not reasonable to write here. if (typeof key.value == "number") { this._valueSize = 1; this._valueType = InterpolableValueType.Float; this._currentValue = 0; } if (key.value instanceof Vector2) { this._valueSize = 2; this._valueType = InterpolableValueType.Vector2; this._currentValue = new Vector2(); } if (key.value instanceof Vector3) { this._valueSize = 3; this._valueType = InterpolableValueType.Vector3; this._currentValue = new Vector3(); } if (key.value instanceof Vector4) { this._valueSize = 4; this._valueType = InterpolableValueType.Vector4; this._currentValue = new Vector4(); } if (key.value instanceof Quaternion) { this._valueSize = 4; this._valueType = InterpolableValueType.Quaternion; this._currentValue = new Quaternion(); } if (key.value instanceof Float32Array) { const size = key.value.length; this._valueSize = size; this._valueType = InterpolableValueType.FloatArray; this._currentValue = new Float32Array(size); } } this.keys.sort((a, b) => a.time - b.time); } /** * Evaluate the curve at time. * @param time - The time within the curve you want to evaluate */ evaluate(time: number): InterpolableValue { const { keys, interpolation } = this; const { length } = this.keys; // Compute curIndex and nextIndex. let curIndex = this._currentIndex; // Reset loop. if (curIndex !== -1 && time < keys[curIndex].time) { curIndex = -1; } let nextIndex = curIndex + 1; while (nextIndex < length) { if (time < keys[nextIndex].time) { break; } curIndex++; nextIndex++; } this._currentIndex = curIndex; // Evaluate value. let value: InterpolableValue; if (curIndex === -1) { value = (<UnionInterpolableKeyframe>keys[0]).value; } else if (nextIndex === length) { value = (<UnionInterpolableKeyframe>keys[curIndex]).value; } else { // Time between first frame and end frame. const curFrameTime = keys[curIndex].time; const duration = keys[nextIndex].time - curFrameTime; const t = (time - curFrameTime) / duration; const dur = duration; switch (interpolation) { case InterpolationType.Linear: value = this._evaluateLinear(curIndex, nextIndex, t); break; case InterpolationType.Step: value = this._evaluateStep(nextIndex); break; case InterpolationType.CubicSpine: case InterpolationType.Hermite: value = this._evaluateHermite(curIndex, nextIndex, t, dur); } } return value; } /** * Removes the keyframe at index and inserts key. * @param index - The index of the key to move * @param key - The key to insert */ moveKey(index: number, key: UnionInterpolableKeyframe): void { this.keys[index] = key; } /** * Removes a key. * @param index - The index of the key to remove */ removeKey(index: number): void { this.keys.splice(index, 1); const { keys } = this; const count = this.keys.length; let newLength = 0; for (let i = count - 1; i >= 0; i--) { if (keys[i].time > length) { newLength = keys[i].time; } } this._length = newLength; } private _evaluateLinear(frameIndex: number, nextFrameIndex: number, t: number): InterpolableValue { const { _valueType, keys } = this; switch (_valueType) { case InterpolableValueType.Float: return (<FloatKeyframe>keys[frameIndex]).value * (1 - t) + (<FloatKeyframe>keys[nextFrameIndex]).value * t; case InterpolableValueType.FloatArray: const curValue = this._currentValue; const value = (<FloatArrayKeyframe>keys[frameIndex]).value; const nextValue = (<FloatArrayKeyframe>keys[nextFrameIndex]).value; for (let i = 0, n = value.length; i < n; i++) { curValue[i] = value[i] * (1 - t) + nextValue[i] * t; } return curValue; case InterpolableValueType.Vector2: Vector2.lerp( (<Vector2Keyframe>keys[frameIndex]).value, (<Vector2Keyframe>keys[nextFrameIndex]).value, t, <Vector2>this._currentValue ); return this._currentValue; case InterpolableValueType.Vector3: Vector3.lerp( (<Vector3Keyframe>keys[frameIndex]).value, (<Vector3Keyframe>keys[nextFrameIndex]).value, t, <Vector3>this._currentValue ); return this._currentValue; case InterpolableValueType.Quaternion: Quaternion.slerp( (<QuaternionKeyframe>keys[frameIndex]).value, (<QuaternionKeyframe>keys[nextFrameIndex]).value, t, <Quaternion>this._currentValue ); return this._currentValue; } } private _evaluateStep(nextFrameIndex: number): InterpolableValue { const { _valueSize, keys } = this; if (_valueSize === 1) { return (<UnionInterpolableKeyframe>keys[nextFrameIndex]).value; } else { return (<UnionInterpolableKeyframe>keys[nextFrameIndex]).value; } } private _evaluateHermite(frameIndex: number, nextFrameIndex: number, t: number, dur: number): InterpolableValue { const { _valueSize, keys } = this; const curKey = keys[frameIndex]; const nextKey = keys[nextFrameIndex]; switch (_valueSize) { case 1: { const t0 = (<FloatKeyframe>curKey).outTangent, t1 = (<FloatKeyframe>nextKey).inTangent, p0 = (<FloatKeyframe>curKey).value, p1 = (<FloatKeyframe>nextKey).value; if (Number.isFinite(t0) && Number.isFinite(t1)) { const t2 = t * t; const t3 = t2 * t; const a = 2.0 * t3 - 3.0 * t2 + 1.0; const b = t3 - 2.0 * t2 + t; const c = t3 - t2; const d = -2.0 * t3 + 3.0 * t2; return a * p0 + b * t0 * dur + c * t1 * dur + d * p1; } else { return (<FloatKeyframe>curKey).value; } } case 2: { const p0 = (<Vector2Keyframe>curKey).value; const tan0 = (<Vector2Keyframe>curKey).outTangent; const p1 = (<Vector2Keyframe>nextKey).value; const tan1 = (<Vector2Keyframe>nextKey).inTangent; const t2 = t * t; const t3 = t2 * t; const a = 2.0 * t3 - 3.0 * t2 + 1.0; const b = t3 - 2.0 * t2 + t; const c = t3 - t2; const d = -2.0 * t3 + 3.0 * t2; let t0 = tan0.x, t1 = tan1.x; if (Number.isFinite(t0) && Number.isFinite(t1)) { (<Vector2>this._currentValue).x = a * p0.x + b * t0 * dur + c * t1 * dur + d * p1.x; } else { (<Vector2>this._currentValue).x = p0.x; } (t0 = tan0.y), (t1 = tan1.y); if (Number.isFinite(t0) && Number.isFinite(t1)) (<Vector2>this._currentValue).y = a * p0.y + b * t0 * dur + c * t1 * dur + d * p1.y; else { (<Vector2>this._currentValue).y = p0.y; } return this._currentValue; } case 3: { const p0 = (<Vector3Keyframe>curKey).value; const tan0 = (<Vector3Keyframe>curKey).outTangent; const p1 = (<Vector3Keyframe>nextKey).value; const tan1 = (<Vector3Keyframe>nextKey).inTangent; const t2 = t * t; const t3 = t2 * t; const a = 2.0 * t3 - 3.0 * t2 + 1.0; const b = t3 - 2.0 * t2 + t; const c = t3 - t2; const d = -2.0 * t3 + 3.0 * t2; let t0 = tan0.x, t1 = tan1.x; if (Number.isFinite(t0) && Number.isFinite(t1)) { (<Vector3>this._currentValue).x = a * p0.x + b * t0 * dur + c * t1 * dur + d * p1.x; } else { (<Vector3>this._currentValue).x = p0.x; } (t0 = tan0.y), (t1 = tan1.y); if (Number.isFinite(t0) && Number.isFinite(t1)) { (<Vector3>this._currentValue).y = a * p0.y + b * t0 * dur + c * t1 * dur + d * p1.y; } else { (<Vector3>this._currentValue).y = p0.y; } (t0 = tan0.z), (t1 = tan1.z); if (Number.isFinite(t0) && Number.isFinite(t1)) { (<Vector3>this._currentValue).z = a * p0.z + b * t0 * dur + c * t1 * dur + d * p1.z; } else { (<Vector3>this._currentValue).z = p0.z; } return <Vector3>this._currentValue; } case 4: { const p0 = (<QuaternionKeyframe>curKey).value; const tan0 = (<QuaternionKeyframe>curKey).outTangent; const p1 = (<QuaternionKeyframe>nextKey).value; const tan1 = (<QuaternionKeyframe>nextKey).inTangent; const t2 = t * t; const t3 = t2 * t; const a = 2.0 * t3 - 3.0 * t2 + 1.0; const b = t3 - 2.0 * t2 + t; const c = t3 - t2; const d = -2.0 * t3 + 3.0 * t2; let t0 = tan0.x, t1 = tan1.x; if (Number.isFinite(t0) && Number.isFinite(t1)) { (<Quaternion>this._currentValue).x = a * p0.x + b * t0 * dur + c * t1 * dur + d * p1.x; } else { (<Quaternion>this._currentValue).x = p0.x; } (t0 = tan0.y), (t1 = tan1.y); if (Number.isFinite(t0) && Number.isFinite(t1)) { (<Quaternion>this._currentValue).y = a * p0.y + b * t0 * dur + c * t1 * dur + d * p1.y; } else { (<Quaternion>this._currentValue).y = p0.y; } (t0 = tan0.z), (t1 = tan1.z); if (Number.isFinite(t0) && Number.isFinite(t1)) { (<Quaternion>this._currentValue).z = a * p0.z + b * t0 * dur + c * t1 * dur + d * p1.z; } else { (<Quaternion>this._currentValue).z = p0.z; } (t0 = tan0.w), (t1 = tan1.w); if (Number.isFinite(t0) && Number.isFinite(t1)) { (<Quaternion>this._currentValue).w = a * p0.w + b * t0 * dur + c * t1 * dur + d * p1.w; } else { (<Quaternion>this._currentValue).w = p0.w; } return <Quaternion>this._currentValue; } } } }
the_stack
import {DataType, fused, serialization, util} from '@tensorflow/tfjs-core'; import {AssertionError, ValueError} from '../errors'; // tslint:enable /** * If `value` is an Array, equivalent to Python's `value * numValues`. * If `value` is not an Array, equivalent to Python's `[value] * numValues` */ // tslint:disable-next-line:no-any export function pyListRepeat(value: any, numValues: number): any[] { if (Array.isArray(value)) { // tslint:disable-next-line:no-any let newArray: any[] = []; for (let i = 0; i < numValues; i++) { newArray = newArray.concat(value); } return newArray; } else { const newArray = new Array(numValues); newArray.fill(value); return newArray; } } export function assert(val: boolean, message?: string): void { if (!val) { throw new AssertionError(message); } } /** * Count the number of elements of the `array` that are equal to `reference`. */ export function count<T>(array: T[], refernce: T) { let counter = 0; for (const item of array) { if (item === refernce) { counter++; } } return counter; } /** * If an array is of length 1, just return the first element. Otherwise, return * the full array. * @param tensors */ export function singletonOrArray<T>(xs: T[]): T|T[] { if (xs.length === 1) { return xs[0]; } return xs; } /** * Normalizes a list/tensor into a list. * * If a tensor is passed, we return * a list of size 1 containing the tensor. * * @param x target object to be normalized. */ // tslint:disable-next-line:no-any export function toList(x: any): any[] { if (Array.isArray(x)) { return x; } return [x]; } /** * Generate a UID for a list */ // tslint:disable-next-line:no-any export function objectListUid(objs: any|any[]): string { const objectList = toList(objs); let retVal = ''; for (const obj of objectList) { if (obj.id == null) { throw new ValueError( `Object ${obj} passed to objectListUid without an id`); } if (retVal !== '') { retVal = retVal + ', '; } retVal = `${retVal}${Math.abs(obj.id)}`; } return retVal; } /** * Converts string to snake-case. * @param name */ export function toSnakeCase(name: string): string { const intermediate = name.replace(/(.)([A-Z][a-z0-9]+)/g, '$1_$2'); const insecure = intermediate.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); /* If the class is private the name starts with "_" which is not secure for creating scopes. We prefix the name with "private" in this case. */ if (insecure[0] !== '_') { return insecure; } return 'private' + insecure; } export function toCamelCase(identifier: string): string { // quick return for empty string or single character strings if (identifier.length <= 1) { return identifier; } // Check for the underscore indicating snake_case if (identifier.indexOf('_') === -1) { return identifier; } return identifier.replace(/[_]+(\w|$)/g, (m, p1) => p1.toUpperCase()); } // tslint:disable-next-line:no-any let _GLOBAL_CUSTOM_OBJECTS = {} as {[objName: string]: any}; export function serializeKerasObject(instance: serialization.Serializable): serialization.ConfigDictValue { if (instance === null || instance === undefined) { return null; } const dict: serialization.ConfigDictValue = {}; dict['className'] = instance.getClassName(); dict['config'] = instance.getConfig(); return dict; } /** * Replace ndarray-style scalar objects in serialization objects with numbers. * * Background: In some versions of tf.keras, certain scalar values in the HDF5 * model save file can be serialized as: `{'type': 'ndarray', 'value': num}`, * where in `num` is a plain number. This method converts such serialization * to a `number`. * * @param config The keras-format serialization object to be processed * (in place). */ function convertNDArrayScalarsInConfig(config: serialization.ConfigDictValue): void { if (config == null || typeof config !== 'object') { return; } else if (Array.isArray(config)) { config.forEach(configItem => convertNDArrayScalarsInConfig(configItem)); } else { const fields = Object.keys(config); for (const field of fields) { const value = config[field]; if (value != null && typeof value === 'object') { if (!Array.isArray(value) && value['type'] === 'ndarray' && typeof value['value'] === 'number') { config[field] = value['value']; } else { convertNDArrayScalarsInConfig(value as serialization.ConfigDict); } } } } } /** * Deserialize a saved Keras Object * @param identifier either a string ID or a saved Keras dictionary * @param moduleObjects a list of Python class names to object constructors * @param customObjects a list of Python class names to object constructors * @param printableModuleName debug text for the object being reconstituted * @param fastWeightInit Optional flag to use fast weight initialization * during deserialization. This is applicable to cases in which * the initialization will be immediately overwritten by loaded weight * values. Default: `false`. * @returns a TensorFlow.js Layers object */ // tslint:disable:no-any export function deserializeKerasObject( identifier: string|serialization.ConfigDict, moduleObjects = {} as {[objName: string]: any}, customObjects = {} as {[objName: string]: any}, printableModuleName = 'object', fastWeightInit = false): any { // tslint:enable if (typeof identifier === 'string') { const functionName = identifier; let fn; if (functionName in customObjects) { fn = customObjects[functionName]; } else if (functionName in _GLOBAL_CUSTOM_OBJECTS) { fn = _GLOBAL_CUSTOM_OBJECTS[functionName]; } else { fn = moduleObjects[functionName]; if (fn == null) { throw new ValueError( `Unknown ${printableModuleName}: ${identifier}. ` + `This may be due to one of the following reasons:\n` + `1. The ${printableModuleName} is defined in Python, in which ` + `case it needs to be ported to TensorFlow.js or your JavaScript ` + `code.\n` + `2. The custom ${printableModuleName} is defined in JavaScript, ` + `but is not registered properly with ` + `tf.serialization.registerClass().`); // TODO(cais): Add link to tutorial page on custom layers. } } return fn; } else { // In this case we are dealing with a Keras config dictionary. const config = identifier; if (config['className'] == null || config['config'] == null) { throw new ValueError( `${printableModuleName}: Improper config format: ` + `${JSON.stringify(config)}.\n` + `'className' and 'config' must set.`); } const className = config['className'] as string; let cls, fromConfig; if (className in customObjects) { [cls, fromConfig] = customObjects[className]; } else if (className in _GLOBAL_CUSTOM_OBJECTS) { [cls, fromConfig] = _GLOBAL_CUSTOM_OBJECTS['className']; } else if (className in moduleObjects) { [cls, fromConfig] = moduleObjects[className]; } if (cls == null) { throw new ValueError( `Unknown ${printableModuleName}: ${className}. ` + `This may be due to one of the following reasons:\n` + `1. The ${printableModuleName} is defined in Python, in which ` + `case it needs to be ported to TensorFlow.js or your JavaScript ` + `code.\n` + `2. The custom ${printableModuleName} is defined in JavaScript, ` + `but is not registered properly with ` + `tf.serialization.registerClass().`); // TODO(cais): Add link to tutorial page on custom layers. } if (fromConfig != null) { // Porting notes: Instead of checking to see whether fromConfig accepts // customObjects, we create a customObjects dictionary and tack it on to // config['config'] as config['config'].customObjects. Objects can use it, // if they want. // tslint:disable-next-line:no-any const customObjectsCombined = {} as {[objName: string]: any}; for (const key of Object.keys(_GLOBAL_CUSTOM_OBJECTS)) { customObjectsCombined[key] = _GLOBAL_CUSTOM_OBJECTS[key]; } for (const key of Object.keys(customObjects)) { customObjectsCombined[key] = customObjects[key]; } // Add the customObjects to config const nestedConfig = config['config'] as serialization.ConfigDict; nestedConfig['customObjects'] = customObjectsCombined; const backupCustomObjects = {..._GLOBAL_CUSTOM_OBJECTS}; for (const key of Object.keys(customObjects)) { _GLOBAL_CUSTOM_OBJECTS[key] = customObjects[key]; } convertNDArrayScalarsInConfig(config['config']); const returnObj = fromConfig(cls, config['config'], customObjects, fastWeightInit); _GLOBAL_CUSTOM_OBJECTS = {...backupCustomObjects}; return returnObj; } else { // Then `cls` may be a function returning a class. // In this case by convention `config` holds // the kwargs of the function. const backupCustomObjects = {..._GLOBAL_CUSTOM_OBJECTS}; for (const key of Object.keys(customObjects)) { _GLOBAL_CUSTOM_OBJECTS[key] = customObjects[key]; } // In python this is **config['config'], for tfjs-layers we require // classes that use this fall-through construction method to take // a config interface that mimics the expansion of named parameters. const returnObj = new cls(config['config']); _GLOBAL_CUSTOM_OBJECTS = {...backupCustomObjects}; return returnObj; } } } /** * Compares two numbers for sorting. * @param a * @param b */ export function numberCompare(a: number, b: number) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** * Comparison of two numbers for reverse sorting. * @param a * @param b */ export function reverseNumberCompare(a: number, b: number) { return -1 * numberCompare(a, b); } /** * Convert a string into the corresponding DType. * @param dtype * @returns An instance of DType. */ export function stringToDType(dtype: string): DataType { switch (dtype) { case 'float32': return 'float32'; default: throw new ValueError(`Invalid dtype: ${dtype}`); } } /** * Test the element-by-element equality of two Arrays of strings. * @param xs First array of strings. * @param ys Second array of strings. * @returns Wether the two arrays are all equal, element by element. */ export function stringsEqual(xs: string[], ys: string[]): boolean { if (xs == null || ys == null) { return xs === ys; } if (xs.length !== ys.length) { return false; } for (let i = 0; i < xs.length; ++i) { if (xs[i] !== ys[i]) { return false; } } return true; } /** * Get the unique elements of an array. * @param xs Array. * @returns An Array consisting of the unique elements in `xs`. */ export function unique<T>(xs: T[]): T[] { if (xs == null) { return xs; } const out: T[] = []; // TODO(cais): Maybe improve performance by sorting. for (const x of xs) { if (out.indexOf(x) === -1) { out.push(x); } } return out; } /** * Determine if an Object is empty (i.e., does not have own properties). * @param obj Object * @returns Whether the Object is empty. * @throws ValueError: If object is `null` or `undefined`. */ export function isObjectEmpty(obj: {}): boolean { if (obj == null) { throw new ValueError(`Invalid value in obj: ${JSON.stringify(obj)}`); } for (const key in obj) { if (obj.hasOwnProperty(key)) { return false; } } return true; } /** * Helper function used to build type union/enum run-time checkers. * @param values The list of allowed values. * @param label A string name for the type * @param value The value to test. * @throws ValueError: If the value is not in values nor `undefined`/`null`. */ export function checkStringTypeUnionValue( values: string[], label: string, value: string): void { if (value == null) { return; } if (values.indexOf(value) < 0) { throw new ValueError(`${value} is not a valid ${label}. Valid values are ${ values} or null/undefined.`); } } /** * Helper function for verifying the types of inputs. * * Ensures that the elements of `x` are all of type `expectedType`. * Also verifies that the length of `x` is within bounds. * * @param x Object to test. * @param expectedType The string expected type of all of the elements in the * Array. * @param minLength Return false if x.length is less than this. * @param maxLength Return false if x.length is greater than this. * @returns true if and only if `x` is an `Array<expectedType>` with * length >= `minLength` and <= `maxLength`. */ // tslint:disable:no-any export function checkArrayTypeAndLength( x: any, expectedType: string, minLength = 0, maxLength = Infinity): boolean { assert(minLength >= 0); assert(maxLength >= minLength); return ( Array.isArray(x) && x.length >= minLength && x.length <= maxLength && x.every(e => typeof e === expectedType)); } // tslint:enable:no-any /** * Assert that a value or an array of value are positive integer. * * @param value The value being asserted on. May be a single number or an array * of numbers. * @param name Name of the value, used to make the error message. */ export function assertPositiveInteger(value: number|number[], name: string) { if (Array.isArray(value)) { util.assert( value.length > 0, () => `${name} is unexpectedly an empty array.`); value.forEach( (v, i) => assertPositiveInteger(v, `element ${i + 1} of ${name}`)); } else { util.assert( Number.isInteger(value) && value > 0, () => `Expected ${name} to be a positive integer, but got ` + `${formatAsFriendlyString(value)}.`); } } /** * Format a value into a display-friendly, human-readable fashion. * * - `null` is formatted as `'null'` * - Strings are formated with flanking pair of quotes. * - Arrays are formatted with flanking pair of square brackets. * * @param value The value to display. * @return Formatted string. */ // tslint:disable-next-line:no-any export function formatAsFriendlyString(value: any): string { if (value === null) { return 'null'; } else if (Array.isArray(value)) { return '[' + value.map(v => formatAsFriendlyString(v)).join(',') + ']'; } else if (typeof value === 'string') { return `"${value}"`; } else { return `${value}`; } } /** * Returns a function `f2` (decorator) which wraps the original function * `f`. `f2` guarantees that `f` can be called at most once * every `waitMs` ms. If `f2` is called more often, it will return * the last returned result of `f`. * * @param f The original function `f` to wrap. * @param waitMs The time between two consecutive calls to `f` in ms. */ export function debounce<T>( f: (...args: Array<{}>) => T, waitMs: number, nowFunc?: Function): (...args: Array<{}>) => T { let lastTime = nowFunc != null ? nowFunc() : util.now(); let lastResult: T; const f2 = (...args: Array<{}>) => { const now = nowFunc != null ? nowFunc() : util.now(); if (now - lastTime < waitMs) { return lastResult; } lastTime = now; lastResult = f(...args); return lastResult; }; return f2; } /** * Returns the fusable activation given a layers identifier. * * @param activationName The layers identifier string. * @return The name of the fusable activation. */ export function mapActivationToFusedKernel(activationName: string): fused.Activation { if (activationName === 'relu') { return 'relu'; } if (activationName === 'linear') { return 'linear'; } if (activationName === 'elu') { return 'elu'; } return null; } type PossibleValues = Array<Array<boolean|string|number>>; /** * Returns the cartesian product of sets of values. * This works the same as itertools.product in Python. * * Example: * * filters = [128, 256, 512] * paddings = ['same', 'valid'] * * product = [ [128, 'same'], [128, 'valid'], [256, 'same'], [256, 'valid'], * [512, 'same'], [512, 'valid']] * * @param arrayOfValues List/array of values. * @return The cartesian product. */ export function getCartesianProductOfValues(...arrayOfValues: PossibleValues): PossibleValues { assert(arrayOfValues.length > 0, 'arrayOfValues is empty'); for (const values of arrayOfValues) { assert(Array.isArray(values), 'one of the values is not an array'); assert(values.length > 0, 'one of the values is empty'); } return arrayOfValues.reduce((products, values) => { if (products.length === 0) { return values.map(value => [value]); } return values .map(value => { return products.map((prevValue) => [...prevValue, value]); }) .reduce((flattenedProduct, unflattenedProduct) => { return flattenedProduct.concat(unflattenedProduct); }, []); }, [] as PossibleValues); }
the_stack
import * as flatbuffers from 'flatbuffers'; import { GeometryType } from '../flat-geobuf/geometry-type.js'; export class Geometry { bb: flatbuffers.ByteBuffer|null = null; bb_pos = 0; __init(i:number, bb:flatbuffers.ByteBuffer):Geometry { this.bb_pos = i; this.bb = bb; return this; } static getRootAsGeometry(bb:flatbuffers.ByteBuffer, obj?:Geometry):Geometry { return (obj || new Geometry()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } static getSizePrefixedRootAsGeometry(bb:flatbuffers.ByteBuffer, obj?:Geometry):Geometry { bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); return (obj || new Geometry()).__init(bb.readInt32(bb.position()) + bb.position(), bb); } ends(index: number):number|null { const offset = this.bb!.__offset(this.bb_pos, 4); return offset ? this.bb!.readUint32(this.bb!.__vector(this.bb_pos + offset) + index * 4) : 0; } endsLength():number { const offset = this.bb!.__offset(this.bb_pos, 4); return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; } endsArray():Uint32Array|null { const offset = this.bb!.__offset(this.bb_pos, 4); return offset ? new Uint32Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; } xy(index: number):number|null { const offset = this.bb!.__offset(this.bb_pos, 6); return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0; } xyLength():number { const offset = this.bb!.__offset(this.bb_pos, 6); return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; } xyArray():Float64Array|null { const offset = this.bb!.__offset(this.bb_pos, 6); return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; } z(index: number):number|null { const offset = this.bb!.__offset(this.bb_pos, 8); return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0; } zLength():number { const offset = this.bb!.__offset(this.bb_pos, 8); return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; } zArray():Float64Array|null { const offset = this.bb!.__offset(this.bb_pos, 8); return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; } m(index: number):number|null { const offset = this.bb!.__offset(this.bb_pos, 10); return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0; } mLength():number { const offset = this.bb!.__offset(this.bb_pos, 10); return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; } mArray():Float64Array|null { const offset = this.bb!.__offset(this.bb_pos, 10); return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; } t(index: number):number|null { const offset = this.bb!.__offset(this.bb_pos, 12); return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0; } tLength():number { const offset = this.bb!.__offset(this.bb_pos, 12); return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; } tArray():Float64Array|null { const offset = this.bb!.__offset(this.bb_pos, 12); return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; } tm(index: number):bigint|null { const offset = this.bb!.__offset(this.bb_pos, 14); return offset ? this.bb!.readUint64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); } tmLength():number { const offset = this.bb!.__offset(this.bb_pos, 14); return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; } type():GeometryType { const offset = this.bb!.__offset(this.bb_pos, 16); return offset ? this.bb!.readUint8(this.bb_pos + offset) : GeometryType.Unknown; } parts(index: number, obj?:Geometry):Geometry|null { const offset = this.bb!.__offset(this.bb_pos, 18); return offset ? (obj || new Geometry()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; } partsLength():number { const offset = this.bb!.__offset(this.bb_pos, 18); return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; } static startGeometry(builder:flatbuffers.Builder) { builder.startObject(8); } static addEnds(builder:flatbuffers.Builder, endsOffset:flatbuffers.Offset) { builder.addFieldOffset(0, endsOffset, 0); } static createEndsVector(builder:flatbuffers.Builder, data:number[]|Uint32Array):flatbuffers.Offset; /** * @deprecated This Uint8Array overload will be removed in the future. */ static createEndsVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset; static createEndsVector(builder:flatbuffers.Builder, data:number[]|Uint32Array|Uint8Array):flatbuffers.Offset { builder.startVector(4, data.length, 4); for (let i = data.length - 1; i >= 0; i--) { builder.addInt32(data[i]!); } return builder.endVector(); } static startEndsVector(builder:flatbuffers.Builder, numElems:number) { builder.startVector(4, numElems, 4); } static addXy(builder:flatbuffers.Builder, xyOffset:flatbuffers.Offset) { builder.addFieldOffset(1, xyOffset, 0); } static createXyVector(builder:flatbuffers.Builder, data:number[]|Float64Array):flatbuffers.Offset; /** * @deprecated This Uint8Array overload will be removed in the future. */ static createXyVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset; static createXyVector(builder:flatbuffers.Builder, data:number[]|Float64Array|Uint8Array):flatbuffers.Offset { builder.startVector(8, data.length, 8); for (let i = data.length - 1; i >= 0; i--) { builder.addFloat64(data[i]!); } return builder.endVector(); } static startXyVector(builder:flatbuffers.Builder, numElems:number) { builder.startVector(8, numElems, 8); } static addZ(builder:flatbuffers.Builder, zOffset:flatbuffers.Offset) { builder.addFieldOffset(2, zOffset, 0); } static createZVector(builder:flatbuffers.Builder, data:number[]|Float64Array):flatbuffers.Offset; /** * @deprecated This Uint8Array overload will be removed in the future. */ static createZVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset; static createZVector(builder:flatbuffers.Builder, data:number[]|Float64Array|Uint8Array):flatbuffers.Offset { builder.startVector(8, data.length, 8); for (let i = data.length - 1; i >= 0; i--) { builder.addFloat64(data[i]!); } return builder.endVector(); } static startZVector(builder:flatbuffers.Builder, numElems:number) { builder.startVector(8, numElems, 8); } static addM(builder:flatbuffers.Builder, mOffset:flatbuffers.Offset) { builder.addFieldOffset(3, mOffset, 0); } static createMVector(builder:flatbuffers.Builder, data:number[]|Float64Array):flatbuffers.Offset; /** * @deprecated This Uint8Array overload will be removed in the future. */ static createMVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset; static createMVector(builder:flatbuffers.Builder, data:number[]|Float64Array|Uint8Array):flatbuffers.Offset { builder.startVector(8, data.length, 8); for (let i = data.length - 1; i >= 0; i--) { builder.addFloat64(data[i]!); } return builder.endVector(); } static startMVector(builder:flatbuffers.Builder, numElems:number) { builder.startVector(8, numElems, 8); } static addT(builder:flatbuffers.Builder, tOffset:flatbuffers.Offset) { builder.addFieldOffset(4, tOffset, 0); } static createTVector(builder:flatbuffers.Builder, data:number[]|Float64Array):flatbuffers.Offset; /** * @deprecated This Uint8Array overload will be removed in the future. */ static createTVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset; static createTVector(builder:flatbuffers.Builder, data:number[]|Float64Array|Uint8Array):flatbuffers.Offset { builder.startVector(8, data.length, 8); for (let i = data.length - 1; i >= 0; i--) { builder.addFloat64(data[i]!); } return builder.endVector(); } static startTVector(builder:flatbuffers.Builder, numElems:number) { builder.startVector(8, numElems, 8); } static addTm(builder:flatbuffers.Builder, tmOffset:flatbuffers.Offset) { builder.addFieldOffset(5, tmOffset, 0); } static createTmVector(builder:flatbuffers.Builder, data:bigint[]):flatbuffers.Offset { builder.startVector(8, data.length, 8); for (let i = data.length - 1; i >= 0; i--) { builder.addInt64(data[i]!); } return builder.endVector(); } static startTmVector(builder:flatbuffers.Builder, numElems:number) { builder.startVector(8, numElems, 8); } static addType(builder:flatbuffers.Builder, type:GeometryType) { builder.addFieldInt8(6, type, GeometryType.Unknown); } static addParts(builder:flatbuffers.Builder, partsOffset:flatbuffers.Offset) { builder.addFieldOffset(7, partsOffset, 0); } static createPartsVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { builder.startVector(4, data.length, 4); for (let i = data.length - 1; i >= 0; i--) { builder.addOffset(data[i]!); } return builder.endVector(); } static startPartsVector(builder:flatbuffers.Builder, numElems:number) { builder.startVector(4, numElems, 4); } static endGeometry(builder:flatbuffers.Builder):flatbuffers.Offset { const offset = builder.endObject(); return offset; } static createGeometry(builder:flatbuffers.Builder, endsOffset:flatbuffers.Offset, xyOffset:flatbuffers.Offset, zOffset:flatbuffers.Offset, mOffset:flatbuffers.Offset, tOffset:flatbuffers.Offset, tmOffset:flatbuffers.Offset, type:GeometryType, partsOffset:flatbuffers.Offset):flatbuffers.Offset { Geometry.startGeometry(builder); Geometry.addEnds(builder, endsOffset); Geometry.addXy(builder, xyOffset); Geometry.addZ(builder, zOffset); Geometry.addM(builder, mOffset); Geometry.addT(builder, tOffset); Geometry.addTm(builder, tmOffset); Geometry.addType(builder, type); Geometry.addParts(builder, partsOffset); return Geometry.endGeometry(builder); } }
the_stack
import { createElement, remove, select } from '@syncfusion/ej2-base'; import { EmitType } from '@syncfusion/ej2-base'; import { Query, DataManager, ODataV4Adaptor } from '@syncfusion/ej2-data'; import { Grid } from '../../../src/grid/base/grid'; import { extend } from '../../../src/grid/base/util'; import { Page, Sort, Group, Edit, Toolbar, Selection } from '../../../src/grid/actions'; import { Data } from '../../../src/grid/actions/data'; import { data } from '../base/datasource.spec'; import '../../../node_modules/es6-promise/dist/es6-promise'; import { createGrid, destroy } from '../base/specutil.spec'; import { DataStateChangeEventArgs, DataSourceChangedEventArgs } from '../../../src/grid/base/interface'; import {profile , inMB, getMemoryProfile} from '../base/common.spec'; Grid.Inject(Page, Sort, Group, Edit, Toolbar); describe('Data module', () => { describe('Locale data testing', () => { type MockAjaxReturn = { promise: Promise<Object>, request: JasmineAjaxRequest }; type ResponseType = { result: Object[], count: number | string }; let mockAjax: Function = (d: { data: { [o: string]: Object | Object[] } | Object[], dm?: DataManager }, query: Query | Function, response?: Object): MockAjaxReturn => { jasmine.Ajax.install(); let dataManager = d.dm || new DataManager({ url: '/api/Employees', }); let prom: Promise<Object> = dataManager.executeQuery(query); let request: JasmineAjaxRequest; let defaults: Object = { 'status': 200, 'contentType': 'application/json', 'responseText': JSON.stringify(d.data) }; let responses: Object = {}; request = jasmine.Ajax.requests.mostRecent(); extend(responses, defaults, response); request.respondWith(responses); return { promise: prom, request: request } }; let gridObj: Grid; let elem: HTMLElement = createElement('div', { id: 'Grid' }); beforeAll((done: Function) => { 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) } let dataBound: EmitType<Object> = () => { done(); }; document.body.appendChild(elem); gridObj = new Grid( { dataSource: data, query: new Query().take(5), allowPaging: false, dataBound: dataBound, columns: [ { headerText: 'OrderID', field: 'OrderID' }, { headerText: 'CustomerID', field: 'CustomerID' }, { headerText: 'EmployeeID', field: 'EmployeeID' }, { headerText: 'ShipCountry', field: 'ShipCountry' }, { headerText: 'ShipCity', field: 'ShipCity' }, ], }); gridObj.appendTo('#Grid'); }); it('TR generated testing', () => { expect(gridObj.element.querySelectorAll('.e-row').length).toBe(5); }); afterAll(() => { remove(elem); jasmine.Ajax.uninstall(); }); }); describe('Remote data without columns testing', () => { let gridObj: Grid; let elem: HTMLElement = createElement('div', { id: 'Grid' }); let resquest: JasmineAjaxRequest; let dataManager: DataManager; let query: Query = new Query().take(5); beforeAll((done: Function) => { let dataBound: EmitType<Object> = () => { done(); }; jasmine.Ajax.install(); dataManager = new DataManager({ url: 'service/Orders/' }); document.body.appendChild(elem); gridObj = new Grid( { dataSource: dataManager, dataBound: dataBound, query: query, allowPaging: true, }); gridObj.appendTo('#Grid'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify({ d: data.slice(0, 15), __count: 15 }) }); }); it('TR generated testing', () => { expect(gridObj.element.querySelectorAll('.e-row').length).toBe(15); }); it('Column count testing', () => { expect(gridObj.element.querySelectorAll('.e-headercell').length).toBe(12); }); afterAll(() => { remove(gridObj.element); jasmine.Ajax.uninstall(); }); }); describe('actionFailure after control destroyed', () => { let actionFailedFunction: () => void = jasmine.createSpy('actionFailure'); let elem: HTMLElement = createElement('div', { id: 'Grid' }); let gridObj: Grid; beforeAll(() => { jasmine.Ajax.install(); document.body.appendChild(elem); gridObj = new Grid({ dataSource: new DataManager({ url: '/test/db', adaptor: new ODataV4Adaptor }), columns: [ { headerText: 'OrderID', field: 'OrderID' }, { headerText: 'CustomerID', field: 'CustomerID' }, { headerText: 'EmployeeID', field: 'EmployeeID' }, { headerText: 'ShipCountry', field: 'ShipCountry' }, { headerText: 'ShipCity', field: 'ShipCity' }, ], actionFailure: actionFailedFunction }); gridObj.appendTo('#Grid'); }); beforeEach((done: Function) => { let request: JasmineAjaxRequest = jasmine.Ajax.requests.mostRecent(); request.respondWith({ 'status': 404, 'contentType': 'application/json', 'responseText': 'Page not found' }); setTimeout(() => { done(); }, 100); }); it('actionFailure testing', () => { expect(actionFailedFunction).toHaveBeenCalled(); }); afterAll(() => { remove(elem); jasmine.Ajax.uninstall(); }); }); describe('Grid with empty datasource', () => { let gridObj: Grid; let elem: HTMLElement = createElement('div', { id: 'Grid' }); beforeAll((done: Function) => { let dataBound: EmitType<Object> = () => { done(); }; document.body.appendChild(elem); gridObj = new Grid( { dataSource: null, allowPaging: false, columns: [ { headerText: 'OrderID', field: 'OrderID' }, { headerText: 'CustomerID', field: 'CustomerID' }, { headerText: 'EmployeeID', field: 'EmployeeID' }, { headerText: 'ShipCountry', field: 'ShipCountry' }, { headerText: 'ShipCity', field: 'ShipCity' }, ], dataBound: dataBound }); gridObj.appendTo('#Grid'); }); it('Row count testing', () => { expect(gridObj.element.querySelectorAll('.e-row').length).toBe(0); //for coverage gridObj.isDestroyed = true; let data = new Data(gridObj); (gridObj.renderModule as any).data.destroy(); gridObj.isDestroyed = false; }); afterAll(() => { remove(elem); }); }); describe('datamanager offline - success testing', () => { let gridObj: Grid; let dataManager: DataManager; let elem: HTMLElement = createElement('div', { id: 'Grid' }); let actionComplete: (e?: Object) => void; beforeAll((done: Function) => { jasmine.Ajax.install(); dataManager = new DataManager({ url: '/test/db', adaptor: new ODataV4Adaptor, offline: true } ); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify({value: data.slice(0, 15)}) }); let dataBound: EmitType<Object> = () => { done(); }; document.body.appendChild(elem); gridObj = new Grid( { dataSource: dataManager, allowPaging: true, columns: [ { headerText: 'OrderID', field: 'OrderID' }, { headerText: 'CustomerID', field: 'CustomerID' }, { headerText: 'EmployeeID', field: 'EmployeeID' }, { headerText: 'ShipCountry', field: 'ShipCountry' }, { headerText: 'ShipCity', field: 'ShipCity' }, ], dataBound: dataBound, actionComplete: actionComplete, }); gridObj.appendTo('#Grid'); }); it('promise test', () => { expect(dataManager.ready).not.toBeNull(); expect(dataManager.dataSource.json.length).toBe(15); }); it('Row count testing', () => { expect(gridObj.element.querySelectorAll('.e-row').length).toBe(12); }); afterAll(() => { jasmine.Ajax.uninstall(); remove(elem); }); }); describe('datamanager offline - failure testing', () => { let gridObj: Grid; let dataManager: any = new DataManager(data as JSON[]); dataManager.ready = { then: (args: any) => { return { catch: (args: any) => { { args.call(this, {}); } } }; } }; let elem: HTMLElement = createElement('div', { id: 'Grid' }); let actionComplete: (e?: Object) => void; beforeAll((done: Function) => { let dataBound: EmitType<Object> = () => { done(); }; let actionFailure: EmitType<Object> = () => { done(); }; document.body.appendChild(elem); gridObj = new Grid( { dataSource: dataManager, allowPaging: false, columns: [ { headerText: 'OrderID', field: 'OrderID' }, { headerText: 'CustomerID', field: 'CustomerID' }, { headerText: 'EmployeeID', field: 'EmployeeID' }, { headerText: 'ShipCountry', field: 'ShipCountry' }, { headerText: 'ShipCity', field: 'ShipCity' }, ], dataBound: dataBound, actionComplete: actionComplete, actionFailure: actionFailure }); gridObj.appendTo('#Grid'); }); it('Row count testing', () => { expect(gridObj.element.querySelectorAll('.e-row').length).toBe(0); }); it('EJ2-7420- Get Column by field test', () => { expect((<any>gridObj.getDataModule()).getColumnByField('ShipCity').field).toBe('ShipCity'); }); afterAll(() => { remove(elem); }); }); describe('Custom Data Source =>', () => { let gridObj: Grid; let dataStateChange: (s?: DataStateChangeEventArgs) => void; let dataSourceChanged: (s?: DataSourceChangedEventArgs) => void; beforeAll((done: Function) => { let options: Object = { dataSource: { result : data.slice(0,6), count : data.length }, allowSorting: true, allowGrouping: true, allowPaging: true, pageSettings: {pageSize: 6}, toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'], editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true }, columns: [ { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 100, isPrimaryKey: true }, { field: 'CustomerID', headerText: 'Customer ID', width: 120 }, { field: 'Freight', headerText: 'Freight', textAlign: 'Right', width: 120, format: 'C2' }, { field: 'ShipCountry', headerText: 'Ship Country', width: 150 } ], dataStateChange: dataStateChange, dataSourceChanged: dataSourceChanged, }; gridObj = createGrid(options, done); }); //Local Custom Data Service it('Initial Page rendering ', (done: Function) => { dataStateChange = ( s: DataStateChangeEventArgs ): void => { expect(s.action.requestType).toBe('paging'); expect(s.skip).toBe(12); expect(s.take).toBe(6); done(); } gridObj.dataStateChange = dataStateChange; gridObj.dataSourceChanged = null; gridObj.goToPage(3); }); it('Sorting in Custom Data Service =>', (done: Function) => { dataStateChange = ( s: DataStateChangeEventArgs ): void => { expect(s.action.requestType).toBe('sorting'); expect(s.sorted[0].name).toBe('CustomerID'); done(); } gridObj.dataStateChange = dataStateChange; gridObj.dataSourceChanged = null; gridObj.sortColumn('CustomerID', 'Ascending', false); }); it('Grouping in Custom Data Service =>', (done: Function) => { dataStateChange = ( s: DataStateChangeEventArgs ): void => { expect(s.group[0]).toBe('CustomerID'); done(); } gridObj.dataStateChange = dataStateChange; gridObj.dataSourceChanged = null; gridObj.groupModule.groupColumn('CustomerID'); }); it('Deleting a record =>', (done: Function) => { dataSourceChanged = ( s: DataSourceChangedEventArgs ): void => { expect(s.requestType).toBe('delete'); gridObj.dataStateChange = null; done(); } gridObj.dataSourceChanged = dataSourceChanged; gridObj.editModule.deleteRecord('OrderID', gridObj.currentViewData[2]); }); afterAll((done) => { destroy(gridObj); }); }); describe('Custom Data Source with inline editing =>', () => { let gridObj: Grid; let dataStateChange: (s?: DataStateChangeEventArgs) => void; let dataSourceChanged: (s?: DataSourceChangedEventArgs) => void; beforeAll((done: Function) => { let options: Object = { dataSource: { result : data.slice(0,6), count : data.length }, allowSorting: true, allowGrouping: true, allowPaging: true, pageSettings: {pageSize: 6}, toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'], editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true }, columns: [ { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 100, isPrimaryKey: true }, { field: 'CustomerID', headerText: 'Customer ID', width: 120 }, { field: 'Freight', headerText: 'Freight', textAlign: 'Right', width: 120, format: 'C2' }, { field: 'ShipCountry', headerText: 'Ship Country', width: 150 } ], dataStateChange: dataStateChange, dataSourceChanged: dataSourceChanged, }; gridObj = createGrid(options, done); }); it('Editing a record =>', (done: Function) => { dataSourceChanged = ( s: DataSourceChangedEventArgs ): void => { expect(s.requestType).toBe('save'); expect(s.action).toBe('edit'); gridObj.dataStateChange = null; done(); } gridObj.selectRow(0); gridObj.startEdit(); (select('#' + gridObj.element.id + 'CustomerID', gridObj.element) as any).value = 'updated'; gridObj.dataSourceChanged = dataSourceChanged; gridObj.endEdit(); }); afterAll((done) => { destroy(gridObj); }); }); describe('Custom Data Source with Batch editing =>', () => { let gridObj: Grid; let dataStateChange: (s?: DataStateChangeEventArgs) => void; let dataSourceChanged: (s?: DataSourceChangedEventArgs) => void; beforeAll((done: Function) => { let options: Object = { dataSource: { result : data.slice(0,6), count : data.length }, allowSorting: true, allowGrouping: true, allowPaging: true, pageSettings: {pageSize: 6}, toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'], editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Batch'}, columns: [ { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 100, isPrimaryKey: true }, { field: 'CustomerID', headerText: 'Customer ID', width: 120 }, { field: 'Freight', headerText: 'Freight', textAlign: 'Right', width: 120, format: 'C2' }, { field: 'ShipCountry', headerText: 'Ship Country', width: 150 } ], dataStateChange: dataStateChange, dataSourceChanged: dataSourceChanged, }; gridObj = createGrid(options, done); }); it('Batch Editing a record =>', (done: Function) => { dataSourceChanged = ( s: DataSourceChangedEventArgs ): void => { expect(s.requestType).toBe('batchsave'); gridObj.dataStateChange = null; done(); } gridObj.dataSourceChanged = dataSourceChanged; gridObj.editModule.editCell(4, 'CustomerID'); (select('#' + gridObj.element.id + 'CustomerID', gridObj.element) as any).value = 'updated'; gridObj.editModule.saveCell(); gridObj.editModule.batchSave(); (select('#' + gridObj.element.id + 'EditConfirm', gridObj.element)as any).querySelectorAll('button')[0].click(); }); afterAll((done) => { destroy(gridObj); }); }); describe('Multi Delete in a single request =>', () => { let gridObj: Grid; let actionComplete: () => void; beforeAll((done: Function) => { let options: Object = { dataSource: data.map(data => data), selectionSettings: { type: 'Multiple' }, pageSettings: { pageSize: 6 }, toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'], editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Normal' }, columns: [ { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 100, isPrimaryKey: true }, { field: 'CustomerID', headerText: 'Customer ID', width: 120 }, { field: 'Freight', headerText: 'Freight', textAlign: 'Right', width: 120, format: 'C2' }, { field: 'ShipCountry', headerText: 'Ship Country', width: 150 } ], actionComplete: actionComplete, }; gridObj = createGrid(options, done); }); it(' Multi Select and delete => ', (done: Function) => { actionComplete = (args?: any): void => { expect(args.requestType).toBe('delete'); expect(args.data.length).toBe(2); done(); } gridObj.actionComplete = actionComplete; gridObj.selectRows([2, 4]); gridObj.deleteRecord(); }); 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); }); afterAll((done) => { destroy(gridObj); }); }); });
the_stack
import { IAuthApiService } from '~/services/Apis/auth/IAuthApiService'; import { UserData } from '~/types/models-data/auth/UserData'; import { BlockUserApiParams, GetUserApiParams, LoginApiParams, LoginResponse, RegistrationApiParams, RegistrationResponse, ReportUserApiParams, RequestResetPasswordApiParams, ResetPasswordApiParams, SearchUsersApiParams, UnblockUserApiParams, IsInviteTokenValidApiParams, IsEmailAvailableApiParams, IsUsernameAvailableApiParams, UpdateUserApiParams, GetFollowingsApiParams, GetFollowersApiParams, SearchFollowingsApiParams, SearchFollowersApiParams } from '~/services/Apis/auth/AuthApiServiceTypes'; import { IHttpService } from '~/services/http/IHttpService'; import { inject, injectable } from '~/node_modules/inversify'; import { TYPES } from '~/services/inversify-types'; import { AxiosResponse } from '~/node_modules/axios'; import { IUtilsService } from '~/services/utils/IUtilsService'; @injectable() export class AuthApiService implements IAuthApiService { static LOGIN_PATH = 'api/auth/login/'; static RESET_PASSWORD_PATH = 'api/auth/password/verify/'; static REQUEST_RESET_PASSWORD_PATH = 'api/auth/password/reset/'; static REGISTER_PATH = 'api/auth/register/'; static AUTHENTICATED_USER_PATH = 'api/auth/user/'; static GET_USERS_PATH = 'api/auth/users/'; static VALIDATE_INVITE_TOKEN = 'api/auth/register/verify-token/'; static REPORT_USER_PATH = 'api/auth/users/{userUsername}/report/'; static BLOCK_USER_PATH = 'api/auth/users/{userUsername}/block/'; static UNBLOCK_USER_PATH = 'api/auth/users/{userUsername}/unblock/'; static GET_FOLLOWERS_PATH = 'api/auth/followers/'; static SEARCH_FOLLOWERS_PATH = 'api/auth/followers/search/'; static GET_FOLLOWINGS_PATH = 'api/auth/followings/'; static SEARCH_FOLLOWINGS_PATH = 'api/auth/followings/search/'; static CHECK_EMAIL_PATH = 'api/auth/email-check/'; static CHECK_USERNAME_PATH = 'api/auth/username-check/'; static UPDATE_AUTHENTICATED_USER_PATH = 'api/auth/user/'; constructor(@inject(TYPES.HttpService) private httpService: IHttpService, @inject(TYPES.UtilsService) private utilsService: IUtilsService) { } requestResetPassword(data: RequestResetPasswordApiParams): Promise<AxiosResponse<void>> { return this.httpService.post<void>(AuthApiService.REQUEST_RESET_PASSWORD_PATH, { email: data.email, captchaToken: data.captchaToken }, { isApiRequest: true, }) } resetPassword(data: ResetPasswordApiParams): Promise<AxiosResponse<void>> { return this.httpService.post<void>(AuthApiService.RESET_PASSWORD_PATH, { token: data.resetToken, new_password: data.newPassword }, { isApiRequest: true, }) } login(data: LoginApiParams): Promise<AxiosResponse<LoginResponse>> { return this.httpService.post<LoginResponse>(AuthApiService.LOGIN_PATH, { username: data.username, password: data.password }, { isApiRequest: true, }) } register(data: RegistrationApiParams): Promise<AxiosResponse<RegistrationResponse>> { const bodyFormData = new FormData(); bodyFormData.set('email', data.email); bodyFormData.set('name', data.name); bodyFormData.set('username', data.userUsername); bodyFormData.set('password', data.password); bodyFormData.set('token', data.inviteToken); bodyFormData.set('is_of_legal_age', data.isOfLegalAge.toString()); bodyFormData.set('are_guidelines_accepted', data.areGuidelinesAccepted.toString()); return this.httpService.post<RegistrationResponse>(AuthApiService.REGISTER_PATH, bodyFormData, { isApiRequest: true }); } isInviteTokenValid(data: IsInviteTokenValidApiParams): Promise<AxiosResponse<void>> { return this.httpService.post<void>(AuthApiService.VALIDATE_INVITE_TOKEN, { token: data.token }, { isApiRequest: true, }); } isEmailAvailable(data: IsEmailAvailableApiParams): Promise<AxiosResponse<void>> { return this.httpService.post<void>(AuthApiService.CHECK_EMAIL_PATH, { email: data.email }, { isApiRequest: true, }); } isUsernameAvailable(data: IsUsernameAvailableApiParams): Promise<AxiosResponse<void>> { return this.httpService.post<void>(AuthApiService.CHECK_USERNAME_PATH, { username: data.username }, { isApiRequest: true, }); } getUser(params: GetUserApiParams): Promise<AxiosResponse<UserData>> { return this.httpService.get<UserData>(`${AuthApiService.GET_USERS_PATH}${params.userUsername}/`, { isApiRequest: true, appendAuthorizationToken: true }); } getAuthenticatedUser(): Promise<AxiosResponse<UserData>> { return this.httpService.get<UserData>(AuthApiService.AUTHENTICATED_USER_PATH, { isApiRequest: true, appendAuthorizationToken: true }); } updateUser(params: UpdateUserApiParams): Promise<AxiosResponse<UserData>> { const bodyFormData = new FormData(); if (typeof params.avatar === 'string' && params.avatar.length === 0) { bodyFormData.set('avatar', params.avatar); } if (params.avatar instanceof File || params.avatar instanceof Blob) { // hacky but I think it's guaranteed that the cropper will return a PNG blob bodyFormData.set('avatar', params.avatar, 'avatar.png'); } if (typeof params.cover === 'string' && params.cover.length === 0) { bodyFormData.set('cover', params.cover); } if (params.cover instanceof File || params.cover instanceof Blob) { // hacky but I think it's guaranteed that the cropper will return a PNG blob bodyFormData.set('cover', params.cover, 'cover.png'); } if (params.name) { bodyFormData.set('name', params.name); } if (params.username) { bodyFormData.set('username', params.username); } if (params.url) { bodyFormData.set('url', params.url); } if (params.bio) { bodyFormData.set('bio', params.bio); } if (params.visibility) { bodyFormData.set('visibility', params.visibility.toString()); } if (params.location) { bodyFormData.set('location', params.location); } if (typeof params.followersCountVisible === 'boolean') { bodyFormData.set('followers_count_visible', params.followersCountVisible.toString()); } if (typeof params.communityPostsVisible === 'boolean') { bodyFormData.set('community_posts_visible', params.communityPostsVisible.toString()); } return this.httpService.patch(AuthApiService.UPDATE_AUTHENTICATED_USER_PATH, bodyFormData, { appendAuthorizationToken: true, isApiRequest: true }); } searchUsers(params: SearchUsersApiParams): Promise<AxiosResponse<UserData[]>> { return this.httpService.get<UserData[]>(`${AuthApiService.GET_USERS_PATH}`, { queryParams: { query: params.query }, isApiRequest: true, appendAuthorizationTokenIfExists: params.appendAuthorizationTokenIfExists, }); } reportUser(params: ReportUserApiParams): Promise<AxiosResponse<void>> { const path = this.utilsService.parseTemplateString(AuthApiService.REPORT_USER_PATH, { userUsername: params.userUsername }); const body = { 'category_id': params.moderationCategoryId }; if (params.description) body['description'] = params.description; return this.httpService.post<void>(path, body, { isApiRequest: true, appendAuthorizationToken: true }); } blockUser(params: BlockUserApiParams): Promise<AxiosResponse<void>> { const path = this.utilsService.parseTemplateString(AuthApiService.BLOCK_USER_PATH, { userUsername: params.userUsername }); return this.httpService.post<void>(path, null, { isApiRequest: true, appendAuthorizationToken: true }); } unblockUser(params: UnblockUserApiParams): Promise<AxiosResponse<void>> { const path = this.utilsService.parseTemplateString(AuthApiService.UNBLOCK_USER_PATH, { userUsername: params.userUsername }); return this.httpService.post<void>(path, null, { isApiRequest: true, appendAuthorizationToken: true }); } searchFollowings(params: SearchFollowingsApiParams): Promise<AxiosResponse<UserData[]>> { const queryParams = { query: params.query, ...(typeof params.count !== 'undefined' && { count: params.count }) }; return this.httpService.get<UserData[]>(AuthApiService.SEARCH_FOLLOWINGS_PATH, { queryParams, isApiRequest: true, appendAuthorizationToken: true }); } getFollowings(params: GetFollowingsApiParams): Promise<AxiosResponse<UserData[]>> { const queryParams = { ...(typeof params.count !== 'undefined' && { count: params.count }), ...(typeof params.maxId !== 'undefined' && { max_id: params.maxId }) }; return this.httpService.get<UserData[]>(AuthApiService.GET_FOLLOWINGS_PATH, { queryParams, isApiRequest: true, appendAuthorizationToken: params.appendAuthorizationToken ?? true }); } searchFollowers(params: SearchFollowersApiParams): Promise<AxiosResponse<UserData[]>> { const queryParams = { query: params.query, ...(typeof params.count !== 'undefined' && { count: params.count }) }; return this.httpService.get<UserData[]>(AuthApiService.SEARCH_FOLLOWERS_PATH, { queryParams, isApiRequest: true, appendAuthorizationToken: true }); } getFollowers(params: GetFollowersApiParams): Promise<AxiosResponse<UserData[]>> { const queryParams = { ...(typeof params.count !== 'undefined' && { count: params.count }), ...(typeof params.maxId !== 'undefined' && { max_id: params.maxId }) }; return this.httpService.get<UserData[]>(AuthApiService.GET_FOLLOWERS_PATH, { queryParams, isApiRequest: true, appendAuthorizationToken: params.appendAuthorizationToken ?? true }); } }
the_stack
import Stream = require("stream"); import Process = require("process"); import File = require("fs"); import ChildProcess = require("child_process"); import Path = require("path"); import Net = require("net"); // Note: The 'import * as Foo from "./Foo' syntax avoids the "compiler re-write problem" that breaks debugger hover inspection import * as AmbrosiaStorage from "./Storage"; import * as Configuration from "./Configuration"; import * as Messages from "./Messages"; import * as Meta from "./Meta"; import * as Root from "./AmbrosiaRoot"; import * as Streams from "./Streams"; import * as Utils from "./Utils/Utils-Index"; // TODO: Revisit all "NonNullAssertion [for 'strictNullChecks']" comments and try to eliminate use of the non-null assertion // operator ("!" suffix), since its use can hide "real" errors from the compiler. The comment makes the operators easy to find. // These were sometimes used to help minimize code-churn when making the initial migration to 'strictNullChecks'. /** Type of a failed Promise. */ export type RejectedPromise = (error: Error) => void; export const POST_METHOD_ID: number = -1; export const POST_BY_IMPULSE_METHOD_ID: number = -2; /** A named argument for a post method call. */ export interface PostMethodArg { argName: string, argValue: any } type PostMethodArgs = (PostMethodArg | undefined)[]; // We need to include undefined to support optional parameters [see arg()] /** The name of the local immortal instance. */ export function instanceName(): string { return (Configuration.loadedConfig().instanceName); } /** * Creates a named argument for a post method call.\ * An optional argument is indicated by the supplied 'name' ending with '?'.\ * Note: Returns _undefined_ if 'value' is _undefined_. */ // Note: IC.arg() must be used to provide the arguments for post methods [but not for non-post methods], because // post method args are just a subset of the JSON args that are sent (we send meta-data in the JSON args too). export function arg(name: string, value: any): PostMethodArg | undefined { if (value === undefined) // This can happen when using the TS wrapper functions produced by Meta.emitTypeScriptFile() [when optional PostMethodArg values are omitted in the call to the wrapper] { return (undefined); // This 'PostMethodArg' will get filtered out by IC.postFork() } Meta.checkName(name, "method argument"); return ({ argName: name, argValue: value }); } /** * Instantiates the application state class instance using the supplied constructor (class name). The constructor will be called using the supplied 'restoredAppState' * which is **required** when restoring a checkpoint (or when upgrading app state), but can be omitted otherwise. Note that when restoring a checkpoint, 'restoredAppState' * will be a deserialized data-only object, ie. it will have the same "shape" as a 'T' but it will not be a constructed 'T' instance. * * Must be called **immediately** after receiving (restoring) a checkpoint, although if using simpleCheckpointConsumer() this will be done automatically. * * **WARNING:** The returned application state instance MUST remain the same for the life of the app because Ambrosia holds a reference to it. */ export function initializeAmbrosiaState<T extends Root.AmbrosiaAppState>(appStateConstructor: new (restoredAppState?: T) => T, restoredAppState?: T): T { Root.checkAppStateConstructor(appStateConstructor); // We call 'new' because we have to rehydrate the class (prototype) too - the deserialized data alone (restoredAppState) is not enough const appState: T = new appStateConstructor(restoredAppState); // Runtime type check if (!(appState instanceof Root.AmbrosiaAppState)) // Or: Root.AmbrosiaAppState.prototype.isPrototypeOf(appState) { throw new Error(`The instantiated 'appStateConstructor' class ('${appStateConstructor.name}') does not derive from AmbrosiaAppState`); } // Check for an empty __ambrosiaInternalState [which could arise from a user-coding mistake] since this is always an error condition if (!appState.__ambrosiaInternalState) { const emptyValue: string = (appState.__ambrosiaInternalState === null) ? "null" : ((appState.__ambrosiaInternalState === undefined) ? "undefined" : "(empty)"); throw new Error(`The instantiated 'appStateConstructor' class ('${appStateConstructor.name}') has a ${emptyValue} __ambrosiaInternalState; this can indicate possible app state corruption`); } // Check that the instantiated appState didn't create a new __ambrosiaInternalState if (restoredAppState && !appState.__ambrosiaInternalState.isSameInstance(restoredAppState)) { throw new Error(`The instantiated 'appStateConstructor' class ('${appStateConstructor.name}') did not maintain the __ambrosiaInternalState from the supplied 'restoredAppState'`); } // Check for serializability try { Utils.checkForCircularReferences(appState, true); } catch (error: unknown) { throw new Error(`The instantiated 'appStateConstructor' class ('${appStateConstructor.name}') is invalid (reason: ${Utils.makeError(error).message})`); } _appState = appState; return (appState); } /** * Throws if the supplied 'appState' is not the same instance as the 'appState' passed to IC.initializeAmbrosiaState().\ * MUST be called immediately before producing (saving) a checkpoint, although if using simpleCheckpointProducer() this will be done automatically. */ export function checkAmbrosiaState(appState: Root.AmbrosiaAppState): void { if (!_appState.__ambrosiaInternalState.isSameInstance(appState)) { throw new Error(`The supplied appState is not the same instance as the appState returned from IC.initializeAmbrosiaState(); this can be the result of an accidental reassignment of appState`); } } /** [Internal] Resets the flags that should become set when an upgrade is correctly performed [by user code]. */ export function clearUpgradeFlags(): void { _icUpgradeCalled = false; _appState.__ambrosiaInternalState.upgradeCalled = false; } /** [Internal] Returns true if all the the flags that should become set when an upgrade is correctly performed [by user code] have been set. */ export function checkUpgradeFlags(): boolean { return (_icUpgradeCalled && _appState.__ambrosiaInternalState.upgradeCalled); } /** A singleton-instanced class that provides methods for tunneling RPC calls through the [built-in] 'post' method. */ class Poster { public static METHOD_PARAMETER_PREFIX: string = "arg:"; // Used to distinguish actual method arguments from internal arguments (like "senderInstanceName") private static METHOD_RESULT_SUFFIX: string = "_Result"; private static UNDEFINED_RETURN_VALUE: string = "__UNDEFINED__"; private static _poster: Poster; // The singleton instance // Private because to create a [singleton] Poster instance the createPoster() method should be used private constructor() { } /** Returns the next 'post' call ID. */ private nextPostCallID() { if (!_appState) { throw new Error("_appState not set; IC.initializeAmbrosiaState() may not have been called immediately after receiving a checkpoint"); } return (_appState.__ambrosiaInternalState.getNextPostCallID()); } /** Creates the singleton instance of the Poster class. */ static createPoster(): Poster { if (!this._poster) { this._poster = new Poster(); } return (this._poster); } /** * Creates a wrapper around the supplied dispatcher to intercept post method result RPCs, handle "built-in" post methods, check if * the post method/version is published, and - optionally - check the parameters (name/type) of a [non built-in] post method call. */ wrapDispatcher(dispatcher: Messages.MessageDispatcher): Messages.MessageDispatcher { const postInterceptDispatcher = function(message: Messages.DispatchedMessage): void { if (message.type === Messages.DispatchedMessageType.RPC) { let rpc: Messages.IncomingRPC = message as Messages.IncomingRPC; let expandTypes: boolean = false; let attrs: string = ""; if (rpc.methodID === POST_BY_IMPULSE_METHOD_ID) { // Create a Post call from the Impulse self-call // TODO: The downside of handling this internally (rather than via code-gen), is that the user never gets to know the callID // for the post method call [unlike when using postFork()], which may make it harder to write the postResult handler const destinationInstance: string = rpc.getJsonParam("destinationInstance"); const methodName: string = rpc.getJsonParam("methodName"); const methodVersion: number = parseInt(rpc.getJsonParam("methodVersion")); const resultTimeoutInMs: number = parseInt(rpc.getJsonParam("resultTimeoutInMs")); const callContextData: any = rpc.getJsonParam("callContextData"); const methodArgs: PostMethodArg[] = rpc.getJsonParam("methodArgs"); Utils.log(`Intercepted [Impulse] RPC invocation for post method '${methodName}'`); postFork(destinationInstance, methodName, methodVersion, resultTimeoutInMs, callContextData, ...methodArgs); return; } if (rpc.methodID === POST_METHOD_ID) { // Handle post method results if (_poster.isPostResult(rpc)) { // isPostResult() will have invoked the result handler, so we're done return; } // Handle "built-in" post methods (Note: These methods are NOT published) switch (getPostMethodName(rpc)) { case "_getPublishedMethods": expandTypes = getPostMethodArg(rpc, "expandTypes"); let includePostMethodsOnly: boolean = getPostMethodArg(rpc, "includePostMethodsOnly"); let methodListXml: string = Meta.getPublishedMethodsXml(expandTypes, includePostMethodsOnly); attrs = `fromInstance="${_config.icInstanceName}" expandedTypes="${expandTypes}"`; postResult<string>(rpc, (methodListXml.length === 0) ? `<Methods ${attrs}/>` : `<Methods ${attrs}>${methodListXml}</Methods>`); return; case "_getPublishedTypes": expandTypes = getPostMethodArg(rpc, "expandTypes"); let typeListXml: string = Meta.getPublishedTypesXml(expandTypes); attrs = `fromInstance="${_config.icInstanceName}" expandedTypes="${expandTypes}"`; postResult<string>(rpc, (typeListXml.length === 0) ? `<Types ${attrs}/>` : `<Types ${attrs}>${typeListXml}</Types>`); return; case "_isPublishedMethod": let methodName: string = getPostMethodArg(rpc, "methodName"); let methodVersion: number = getPostMethodArg(rpc, "methodVersion"); let isPublished: boolean = (Meta.getPublishedMethod(methodName, methodVersion) !== null); postResult<boolean>(rpc, isPublished); return; case "_echo": postResult(rpc, getPostMethodArg(rpc, "payload")); // Note: The <T> value for postResult() isn't known in this case return; case "_ping": postResult<number>(rpc, getPostMethodArg(rpc, "sentTime")); // The actual result (roundtripTimeInMs) is computed when the postResult is received return; } // Handle the case where the post method/version has not been published (or the supplied parameters don't match the published parameters) // Note: We can't do the same for non-post methods [by checking for the methodID] because non-post methods don't have an error-return capability let methodName: string = getPostMethodName(rpc); let methodVersion: number = getPostMethodVersion(rpc); let isPublished: boolean = Meta.isPublishedMethod(methodName); let method: Meta.Method | null = !isPublished ? null : Meta.getPublishedMethod(methodName, methodVersion); let isSupportedVersion: boolean = (method !== null); if (method !== null) // "if (isSupportedVersion)" isn't sufficient to make the compiler happy when using 'strictNullChecks' { let unknownArgNames: string[] = []; for (const paramName of rpc.jsonParamNames) { if (paramName.startsWith(Poster.METHOD_PARAMETER_PREFIX)) { // Whether the method parameter is optional but was supplied as required, or (conversely) if the method // parameter is required but was supplied as optional, we'll still accept the supplied parameter const argName: string = paramName.replace(Poster.METHOD_PARAMETER_PREFIX, ""); if (method.parameterNames.map(pn => Meta.Method.trimRest(Utils.trimTrailingChar(pn, "?"))).indexOf(Utils.trimTrailingChar(argName, "?")) === -1) { unknownArgNames.push(argName); } } } if (unknownArgNames.length > 0) { Utils.log(`Warning: Instance '${getPostMethodSender(rpc)}' supplied ${unknownArgNames.length} unexpected arguments (${unknownArgNames.join(", ")}) for post method '${methodName}'`); postError(rpc, new Error(`${unknownArgNames.length} unexpected arguments (${unknownArgNames.join(", ")}) were supplied`)); return; } // Check that all the required published parameters have been supplied, and are of the correct type for (let i = 0; i < method.parameterNames.length; i++) { let paramName: string = Meta.Method.trimRest(method.parameterNames[i]); let paramType: string = method.parameterTypes[i]; let expandedParamType: string = method.expandedParameterTypes[i]; let incomingParamName: string = Poster.METHOD_PARAMETER_PREFIX + paramName; let incomingParamValue: any = rpc.getJsonParam(incomingParamName); if (!paramName.endsWith("?") && (incomingParamValue === undefined)) { Utils.log(`Warning: Instance '${getPostMethodSender(rpc)}' did not supply required argument '${paramName}' for post method '${methodName}'`); postError(rpc, new Error(`Required argument '${paramName}' was not supplied (argument type: ${paramType})`)); return; } // Check that the type of the published/supplied parameters match if (_config.lbOptions.typeCheckIncomingPostMethodParameters && method.isTypeChecked && (paramType !== "any") && (expandedParamType !== "any")) { const incomingParamType: string = Meta.Type.getRuntimeType(incomingParamValue); // May return null if (incomingParamType) { const failureReason: string | null = Meta.Type.compareTypes(incomingParamType, expandedParamType); if (failureReason) { Utils.log(`Warning: Instance '${getPostMethodSender(rpc)}' sent a parameter ('${paramName}') of the wrong type (${incomingParamType}) for post method '${methodName}'; ${failureReason}`); postError(rpc, new Error(`Argument '${paramName}' is of the wrong type (${incomingParamType}); ${failureReason}`)); return; } } } } } if (!isPublished) { Utils.log(`Warning: Instance '${getPostMethodSender(rpc)}' requested a non-published post method '${methodName}'`); postError(rpc, new Error(`The method is not published`)); return; } if (!isSupportedVersion) { Utils.log(`Warning: Instance '${getPostMethodSender(rpc)}' requested a non-published version (${methodVersion}) of post method '${methodName}'`); postError(rpc, new Error(`The requested version (${methodVersion}) of the method is not published`)); return; } } } // Call the app-provided dispatcher. // Note: The VSCode profiler may report that all the functions in the app's dispatcher are actually being called by postInterceptDispatcher(). // The current thinking for why this happens is because the V8 compiler is doing some sort of tail-call optimization. // A workaround to get a more "reasonable" function name (eg. "wrappedDispatcher") recorded by the profiler is to do this: // function wrappedDispatcher() // { // dispatcher(message); // } // wrappedDispatcher(); // However, this is a performance issue as we're putting another "needless" frame on the stack. // The better workaround is for the user to modify their dispatcher method (if they so desire) to get a "full fidelity" stack when profiled, // eg. by making a nested function call to the "real" dispatcher. dispatcher(message); } return (postInterceptDispatcher); } /** * Posts an RPC message (using Fork, which is the only RPC type supported for post). The receiver will examine the 'methodName' parameter of the IncomingRPC.jsonParams * to decide which method to invoke. The results of post methods will be sent to the PostResultDispatcher specified in the AmbrosiaConfig parameter of IC.start().\ * **WARNING:** To ensure replay integrity, pay careful attention to the restrictions on the PostResultDispatcher. */ post(destinationInstance: string, methodName: string, methodVersion: number, resultTimeoutInMs: number = -1, callContextData: any = null, ...methodArgs: PostMethodArg[]): number { let message: Uint8Array; let jsonArgs: Utils.SimpleObject = {}; let callID: number = this.nextPostCallID(); // This will ensure that we'll associate the posted result (if any) with the correct resultHandler Utils.log(`Posting method '${methodName}' (version ${methodVersion}) to ${isSelf(destinationInstance) ? "local" : `'${destinationInstance}'`} IC`); if (methodName.endsWith(Poster.METHOD_RESULT_SUFFIX)) { throw new Error(`Invalid methodName '${methodName}': the name cannot end with '${Poster.METHOD_RESULT_SUFFIX}'`); } jsonArgs["senderInstanceName"] = _config.icInstanceName; jsonArgs["destinationInstanceName"] = destinationInstance; // Only required in the case of a timeout [which results in a self-send of the result] jsonArgs["methodName"] = methodName; jsonArgs["methodVersion"] = methodVersion; jsonArgs["callID"] = callID; for (let i = 0; i < methodArgs.length; i++) { jsonArgs[`${Poster.METHOD_PARAMETER_PREFIX}${methodArgs[i].argName}`] = methodArgs[i].argValue; // For example: jsonArgs["arg:digits?"] = 5 } // Note: The result will be dispatched to the user's PostResultDispatcher by isPostResult() message = Messages.makeRpcMessage(Messages.RPCType.Fork, destinationInstance, POST_METHOD_ID, jsonArgs); sendMessage(message, Messages.MessageType.RPC, destinationInstance); // Although passing the callContextData in the jsonArgs would work, it's very inefficient. The data doesn't need to leave the local instance since // that's the only place it's ever used. So passing it in the call would both bloat the log and slow down TCP throughput. This issue would become // acute for large callContextData, especially for high-frequency post methods; the situation is made even worse because the callContextData is // logged and sent twice (once in the outgoing post, then again in the incoming postResult). // So instead we simply store it in the app state. In almost all cases, the [now locally stored] callContextData will be very short lived; as soon // as the postResult is received the callContextData will be purged from the app state. Only in the case where a TakeCheckpoint message arrives // between a post and its postResult will the callContextData get persisted to a checkpoint. That said, if the destination instance is offline and // the post() call didn't specify a timeout, then the checkpoint would get bloated with callContextData for all the pending post calls. // // Additionally, we want to keep track of all in-flight post methods so that: // a) We can know if the result has already been received [see isPostResult() and startPostResultTimeout()]. // b) We can restart the timeouts [if needed] for in-flight post methods after recovery finishes [see onRecoveryComplete()]. // c) We can [optionally] detect unresponsive destination instances [see below]. // But first, since callContextData has type 'any', we need to check that it will serialize [to app state] if (callContextData) { Meta.checkRuntimeType(callContextData, "callContextData"); } const callDetails: InFlightPostMethodDetails = new InFlightPostMethodDetails(callID, callContextData, methodName, resultTimeoutInMs, destinationInstance, message); _appState.__ambrosiaInternalState.pushInFlightPostCall(callID, callDetails); if (Messages.isRecoveryRunning()) { _postCallsMadeDuringRecovery.add(callID); } this.startPostResultTimeout(callID, callDetails); // Detect/report unresponsive destination instances if ((_config.lbOptions.maxInFlightPostMethods !== -1) && !Messages.isRecoveryRunning()) { const inFlightCallIDs: number[] = _appState.__ambrosiaInternalState.inFlightCallIDs(); const inFlightPostMethodCount: number = inFlightCallIDs.length; if ((inFlightPostMethodCount % Math.max(1, _config.lbOptions.maxInFlightPostMethods)) === 0) { let destinationTotals: { [destinationInstance: string]: number } = {}; let totalsList: string = ""; for (const callID of inFlightCallIDs) { const methodDetails: InFlightPostMethodDetails = Utils.assertDefined(_appState.__ambrosiaInternalState.getInFlightPostCall(callID)); if (destinationTotals[methodDetails.destinationInstance] === undefined) { destinationTotals[methodDetails.destinationInstance] = 0; } destinationTotals[methodDetails.destinationInstance]++; } for (const destination of Object.keys(destinationTotals)) { totalsList += (totalsList.length === 0 ? "" : ", ") + `${destination} = ${destinationTotals[destination]}`; } Utils.log(`Warning: There are ${inFlightPostMethodCount} in-flight post methods (${totalsList})`, null, Utils.LoggingLevel.Minimal); } } return (callID); } /** * Starts the result timeout (if needed) for the supplied post method call.\ * Returns true only if the timeout was started. */ startPostResultTimeout(callID: number, methodDetails: InFlightPostMethodDetails): boolean { if ((methodDetails.resultTimeoutInMs !== -1) && _config.lbOptions.allowPostMethodTimeouts && !Messages.isRecoveryRunning()) { // Note: We don't start the timer during recovery because the outcome [for all but the in-flight posts] is already in the log. // Timeouts will be started for any in-flight (ie. sent but no response yet received) post methods by onRecoveryComplete(). setTimeout(() => { // If we haven't yet received the result, self-post a timeout error result. // Note: We can't simply call "postResultDispatcher(timeoutError)" on a timer due to recovery issues. Namely, if the timeout occurred when run in realtime // but the actual result was [eventually] received after the timeout, then during recovery the actual result will happen BEFORE the timeout due to playback // time compression. But if we explicitly post the error then during playback the timeout result will correctly precede the actual result (if the actual // result ever arrives), faithfully replaying what happened in realtime. // Note: This approach can lead to BOTH the timeout result AND the actual result being received, since the timeout does not cancel the sending of the actual result. // Further, the test below can succeed in the time-window of after the actual result has been sent but before it has been received. if (_appState.__ambrosiaInternalState.getInFlightPostCall(callID) && methodDetails.outgoingRpc) { let timeoutError: string = `Timeout: The result for method '${methodDetails.methodName}' did not return after ${methodDetails.resultTimeoutInMs}ms`; let incomingRpc: Messages.IncomingRPC = Messages.makeIncomingRpcFromOutgoingRpc(methodDetails.outgoingRpc); // Note: We post the timeout error as an Impulse because it's occurring as the result of a timer which won't run during recovery postImpulseError(incomingRpc, new Error(timeoutError)); } }, methodDetails.resultTimeoutInMs); return (true); } return (false); } /** * Sends the result of a (post) method back to the caller, which will handle it in its PostResultDispatcher. * If the method returned void, the 'result' can be omitted. */ postResult<T>(rpc: Messages.IncomingRPC, responseRpcType: Messages.RPCType = Messages.RPCType.Fork, result?: T | Error): void { let methodName: string = rpc.getJsonParam("methodName"); let destinationInstance: string = rpc.getJsonParam("senderInstanceName"); let message: Uint8Array; let jsonArgs: Utils.SimpleObject = {}; jsonArgs["senderInstanceName"] = _config.icInstanceName; jsonArgs["destinationInstanceName"] = destinationInstance; jsonArgs["methodName"] = methodName + Poster.METHOD_RESULT_SUFFIX; jsonArgs["methodVersion"] = rpc.getJsonParam("methodVersion"); // We just echo this back to the caller jsonArgs["callID"] = rpc.getJsonParam("callID"); // We just echo this back to the caller if (result instanceof Error) { // Note: The Error object doesn't have a toJSON() member, so JSON.stringify() returns "{}". As a workaround we only include Error.message, which will serialize. // Note: In the case of a timeout, postResult() will be a self-call, so we can't assume that _config.icInstanceName was the post destination. jsonArgs["errorMsg"] = `Post method '${methodName}' (callID ${jsonArgs["callID"]}) sent to '${rpc.getJsonParam("destinationInstanceName")}' failed (reason: ${result.message})`; if (_config.lbOptions.allowPostMethodErrorStacks) { // Note: This is expensive [in # bytes] and may pose a security risk, so whether to send it is configurable (similar to <customErrors mode="Off"/> in IIS) jsonArgs["originalError"] = result.stack; } } else { // Using UNDEFINED_RETURN_VALUE is to support the case of the caller just wanting to know if a method [that returns void] completes (or fails) jsonArgs["result"] = (result === undefined) ? Poster.UNDEFINED_RETURN_VALUE : result; // 'undefined' won't pass through JSON.stringify() [null is OK] } Utils.log(`Posting [${Messages.RPCType[responseRpcType]}] ${result instanceof Error ? "error for" : "result of"} method '${methodName}' to ${isSelf(destinationInstance) ? "local" : `'${destinationInstance}'`} IC`); message = Messages.makeRpcMessage(responseRpcType, destinationInstance, POST_METHOD_ID, jsonArgs); sendMessage(message, Messages.MessageType.RPC, destinationInstance); } /** * Returns true if the supplied RPC is the posted return value of a posted method.\ * If the RPC is indeed a post method return value, also invokes the PostResultDispatcher passed to IC.start() via it's AmbrosiaConfig parameter. */ private isPostResult(rpc: Messages.IncomingRPC): boolean { if (rpc.methodID === POST_METHOD_ID) { let methodName: string = rpc.getJsonParam("methodName"); if (methodName.endsWith(Poster.METHOD_RESULT_SUFFIX) && ((rpc.getJsonParam("result") !== undefined) || (rpc.getJsonParam("errorMsg") !== undefined))) { let result: any = rpc.getJsonParam("result"); let errorMsg: string = rpc.getJsonParam("errorMsg"); let originalError: string = rpc.getJsonParam("originalError"); // Note: The source instance can be configured not to send this [which is the default behavior] let callID: number = rpc.getJsonParam("callID"); let senderInstanceName: string = rpc.getJsonParam("senderInstanceName"); let methodVersion: number = parseInt(rpc.getJsonParam("methodVersion")); let baseMethodName: string = methodName.slice(0, -Poster.METHOD_RESULT_SUFFIX.length); // Handle the void-return case [which is just notification of method completion]; receiving an 'undefined' result can also indicate a potential error in the sender's method handler code if (result === Poster.UNDEFINED_RETURN_VALUE) // 'undefined' won't pass through JSON.stringify() { result = undefined; } let showParams: boolean = _config.lbOptions.debugOutputLogging; // For debugging Utils.log(`Intercepted [${Messages.RPCType[rpc.rpcType]}] RPC call for post method '${methodName}' [resultType: ${errorMsg ? "error" : "normal"}]` + (showParams ? ` with params: ${rpc.makeDisplayParams()}`: "")); if (errorMsg && originalError) { Utils.log(`Originating error (on publisher ['${senderInstanceName}'] of post method '${baseMethodName}'):`); Utils.log(originalError); } // Note: The method may no longer be in-flight due to a timeout error if (_appState.__ambrosiaInternalState.getInFlightPostCall(callID)) { // Invoke the user-provided PostResultDispatcher (result/error handler) const callDetails: InFlightPostMethodDetails = _appState.__ambrosiaInternalState.popInFlightPostCall(callID); // Note: active/active secondaries remain in constant recovery, so we remove the callID from _postCallsMadeDuringRecovery to stop the set from growing // monotonically on a secondary. Similarly, removing a "known received" callID on a recovering standalone instance also helps keep the set small. if (Messages.isRecoveryRunning() && _postCallsMadeDuringRecovery.has(callID)) { _postCallsMadeDuringRecovery.delete(callID); } if (_config.postResultDispatcher) { switch (baseMethodName) { case "_ping": // Override the nominal result (sentTime) with the actual round-trip time const pingSucceeded: boolean = !errorMsg; const roundtripTimeInMs: number = pingSucceeded ? Date.now() - parseInt(result) : -1; result = roundtripTimeInMs; // Ping is expected to encounter unresponsive instances, so we don't consider a timeout to be a "real" error for ping if (errorMsg.indexOf("Timeout") !== -1) { errorMsg = ""; } break; } if (!_config.postResultDispatcher(senderInstanceName, baseMethodName, methodVersion, callID, callDetails.callContextData, result, errorMsg)) { Utils.log(`Warning: The result of post method '${baseMethodName}' from '${senderInstanceName}' was not handled by the provided PostResultDispatcher`); } } else { Utils.log(`Warning: The result of post method '${baseMethodName}' from '${senderInstanceName}' was not handled (reason: No PostResultDispatcher was provided)`); } } else { if (Messages.isRecoveryRunning() && !_postCallsMadeDuringRecovery.has(callID)) { // The callID isn't in the in-flight list (which can span restarts), but it's not in the "sent during recovery" list either. So we're // receiving a replayed post result for a post call that we haven't re-sent. Because we didn't send it, nextPostCallID() will not // have been called, so there will now be a permanent mismatch in the callID's of replayed post results and re-sent post calls. // This situation can arise due to a deterministic programming error (eg. making a post call as the direct result of user input without // using an Impulse to invoke the post). Since determinism is broken, there's no point carrying on with recovery, so we throw (this will // bubble up to the uncaught exception handler which will terminate the process). throw new Error(`Recovery failed (reason: Deterministic programming error detected; a replayed post result (for method '${baseMethodName}' (callID ${callID}) from '${senderInstanceName}') ` + `was received without its originating post call being made; this is often caused by not using an Impulse to invoke the originating post call)`); } // This can legitimately happen when either: // a) A timeout occurred waiting for the post result to arrive [so postResultDispatcher() will already have been called by the timeout error] // b) A result for both a timeout error AND the actual result were received [so the first one received will have called postResultDispatcher()] Utils.log(`Warning: The result of post method '${baseMethodName}' (callID ${callID}) from '${senderInstanceName}' has already been handled`); } return (true); } } return (false); } } let _appState: Root.AmbrosiaAppState; // Reference to the user-supplied application state let _config: Configuration.AmbrosiaConfig; let _icProcess: ChildProcess.ChildProcess | null = null; let _lbSendSocket: Net.Socket | null = null; // Our connection to the IC's receive port let _lbReceiveSocket: Net.Socket | null = null; // Our connection to the IC's send port let _outgoingMessageStream: Streams.OutgoingMessageStream; export let _counters : { remoteSentMessageCount: number, sentForkMessageCount: number, receivedForkMessageCount: number, receivedMessageCount: number } = { remoteSentMessageCount: 0, sentForkMessageCount: 0, receivedForkMessageCount: 0, receivedMessageCount: 0 }; let _knownDestinationInstanceNames: string[] = []; let _selfConnectionCount: number = 0; let _selfConnectionCountCheckTimer: NodeJS.Timeout; let _selfConnectionCheckTimer: NodeJS.Timeout; let _remoteConnectionCount: number = 0; let _remoteConnectionCountCheckTimer: NodeJS.Timeout; let _poster: Poster = Poster.createPoster(); let _remoteInstanceNames: string[] = []; let _isPrimary: boolean = false; // Whether this IC is currently the Primary let _icStoppedSignalled: boolean = false; let _icStoppingDueToError: boolean = false; let _icUpgradeCalled: boolean = false; let _postCallsMadeDuringRecovery = new Set<number>(); // The CallIDs of all post calls made while recovery is running /** Whether the IC is currently running [due to the local LB starting it]. */ export function isRunning(): boolean { return (_icProcess !== null); } /** Returns the process ID of the IC (if it's running), or -1 (if it's not). */ export function PID(): number { return (_icProcess ? _icProcess?.pid ?? -1 : -1) } /** * [Internal] Gets or sets whether the IC is currently the Primary.\ * Note: Becoming the Primary can happen when the instance is running either standalone or in active/active. */ export function isPrimary(value?: boolean): boolean { if (value !== undefined) { if (value !== _isPrimary) { _isPrimary = value; if (_isPrimary) { Utils.log("Local instance is now primary"); } } } return (_isPrimary); } /** [Internal] Returns true if the outgoing message stream (to the IC) has filled past the specified percentOfStreamMaximum (0.0 to 1.0). */ export function isOutgoingMessageStreamGettingFull(percentOfStreamMaximum: number): boolean { const isGettingFull: boolean = _outgoingMessageStream && (_outgoingMessageStream.readableLength > (_outgoingMessageStream.maxQueuedBytes * Math.max(0, Math.min(1, percentOfStreamMaximum)))); return (isGettingFull); } /** [Internal] Returns the number of bytes that are waiting to be sent in the outgoing message stream (to the IC). */ export function outgoingMessageStreamBacklog(): number { return (_outgoingMessageStream ? _outgoingMessageStream.readableLength : 0); } /** [Internal] Handles the lbOptions.deleteLogs configuration setting. */ export async function deleteLogsAsync(): Promise<void> { const config: Configuration.AmbrosiaConfigFile = Configuration.loadedConfig(); const FILES: string = Configuration.LogStorageType[Configuration.LogStorageType.Files]; const BLOBS: string = Configuration.LogStorageType[Configuration.LogStorageType.Blobs]; const instanceLogFolder: string = Path.join(config.icLogFolder, `${config.instanceName}_${config.appVersion}`); // TODO: There may (one day) also be a "shardID" (Int64) subfolder (see: \AMBROSIA\AmbrosiaLib\Ambrosia\Program.cs) // We can only delete the logs if we're controlling starting/stopping of the IC if (!config.isIntegratedIC) { return; } if ((config.icLogStorageType === FILES) && !File.existsSync(config.icLogFolder)) { File.mkdirSync(config.icLogFolder); // Note: We don't need to do the equivalent when storing logs in Azure Blobs } if (config.lbOptions.deleteLogs) { const deletedFileCount: number = await deleteInstanceLogFolderAsync(instanceLogFolder, config.icLogStorageType); const storageType: string = (config.icLogStorageType === BLOBS) ? "Azure" : "disk"; Utils.log(`Warning: ${deletedFileCount} log/checkpoint files ${(deletedFileCount === 0) ? "found" : "deleted"} [on ${storageType}] - Recovery will not run`); } else { let recoveryMsg: string = "Recovery will not run (no logs found)"; // If the config doesn't specify that the logs should be deleted but the log folder is empty (eg. due to manual deletion), // then we still need to explicitly remove the log folder to avoid the IC failing with "FATAL ERROR 2: Missing checkpoint 1" // [the same (or at least equivalent) issue happens with either LogStorageType] switch (config.icLogStorageType) { case FILES: if (File.existsSync(instanceLogFolder)) { if (File.readdirSync(instanceLogFolder).length === 0) { File.rmdirSync(instanceLogFolder); } else { if (File.readdirSync(instanceLogFolder).filter(fn => /serverlog[\d]+$/.test(fn))) { recoveryMsg = "Recovery will run"; } } } break; case BLOBS: if (await AmbrosiaStorage.folderContainsBlobLogAsync(instanceLogFolder)) { recoveryMsg = "Recovery will run"; } break; } Utils.log(!config.isTimeTravelDebugging ? recoveryMsg : "Warning: Recovery will run in time-travel debugging mode (the 'RecoveryComplete' event will NOT be raised)"); } } /** [Internal] Initializes the set of remote IC instances that this instance communicates with. This list is used for checking IC startup integrity. */ export function setRemoteInstanceNames(remoteInstanceNames: string[]): void { _remoteInstanceNames = remoteInstanceNames; } /** [Internal] Class representing an in-flight (ie. sent but no result yet received) post method call. */ export class InFlightPostMethodDetails { callID: number; callContextData: any; methodName: string; resultTimeoutInMs: number; destinationInstance: string; outgoingRpc: Uint8Array | null; constructor(callID: number, callContextData: any, methodName: string, resultTimeoutInMs: number, destinationInstance: string, outgoingRpc: Uint8Array | null) { this.callID = callID; this.callContextData = callContextData; this.methodName = methodName; this.resultTimeoutInMs = resultTimeoutInMs; this.destinationInstance = destinationInstance; // The outgoingRpc is only needed to send a timeout error result, so if the method has no timeout then we skip storing it [to save space, both in memory and in the checkpoint] this.outgoingRpc = (resultTimeoutInMs === -1) ? null : outgoingRpc; } /** Factory method that instantiates a new InFlightPostMethodDetails from an existing instance. */ static createFrom(details: InFlightPostMethodDetails): InFlightPostMethodDetails { return (new this(details.callID, details.callContextData, details.methodName, details.resultTimeoutInMs, details.destinationInstance, details.outgoingRpc)); } } /** Performs house-keeping checks and actions needed when recovery completes. */ export function onRecoveryComplete() { Utils.log(`Recovery complete (Received ${_counters.receivedMessageCount} messages [${_counters.receivedForkMessageCount} Fork messages], sent ${_counters.sentForkMessageCount} Fork messages)`); if (_counters.sentForkMessageCount < _counters.receivedForkMessageCount) { // If the log ONLY contained messages sent to ourself, then at this point we [might] have an error condition, and the Immortal Coordinator process // may go into a CPU spin while it waits for the missing messages. However, since (incoming) replayed messages don't include the source // (sender) we cannot make this determination. The best we can do is to check if we sent any messages to a remote instance during recovery // and then use that as a proxy for the fact that we likely received messages from instance(s) other than ourself, and - in which case - we // will skip the warning that there *might* be a problem. if (_counters.remoteSentMessageCount === 0) { Utils.log(`Warning: If the log is known to ONLY contain self-call messages, then at least ${_counters.receivedForkMessageCount} Fork messages should have ` + `been sent during replay, not ${_counters.sentForkMessageCount}; this condition can indicate an app programming error ` + `(eg. making a Post/Fork RPC call when an Impulse RPC call should have been used) or an app programming issue ` + `(eg. making a Post/Fork RPC call using a timer that delays the send until after recovery completes)`); } } _counters.remoteSentMessageCount = _counters.receivedMessageCount = _counters.receivedForkMessageCount = _counters.sentForkMessageCount = 0; _postCallsMadeDuringRecovery.clear(); // Start result timeouts for any in-flight (ie. sent but no response yet received) post methods. // Note: Unless the in-flight method was called right at the end of recovery, it is likely that the amount of time we'll actually end up waiting for a // [unresponsive] method to complete will be longer - possibly considerably so - than the requested InFlightPostMethodDetails.resultTimeoutInMs. let restartedTimeoutCount: number = 0; for (const callID of _appState.__ambrosiaInternalState.inFlightCallIDs()) { let methodDetails: InFlightPostMethodDetails = Utils.assertDefined(_appState.__ambrosiaInternalState.getInFlightPostCall(callID)); if (_poster.startPostResultTimeout(callID, methodDetails)) { restartedTimeoutCount++; } } if (restartedTimeoutCount > 0) { Utils.log(`Restarted result timeouts for ${restartedTimeoutCount} in-flight post methods`, null, Utils.LoggingLevel.Minimal); } } /** * Returns true if the IC is ready to handle self-call RPC's. * If the IC is not ready, then the response to a self-call RPC (from the IC) will be delayed. */ export function readyForSelfCallRpc(): boolean { return (_selfConnectionCount === 4); } /** Returns true if the specified IC instance name matches the local IC instance name. */ export function isSelf(instanceName: string): boolean { return (Utils.equalIgnoringCase(_config.icInstanceName, instanceName)); } /** * Returns true if the specified destination instance name has not been sent to before [during the current lifetime of the Immortal]. * Will always return false for the local IC instance name. */ export function isNewDestination(destinationInstanceName: string): boolean { let isNew: boolean = true; if (isSelf(destinationInstanceName)) { return (false); } for (let i = 0; i < _knownDestinationInstanceNames.length; i++) { if (Utils.equalIgnoringCase(destinationInstanceName, _knownDestinationInstanceNames[i])) { isNew = false; break; } } if (isNew) { _knownDestinationInstanceNames.push(destinationInstanceName); } return (isNew); } let _isReadyForSelfCallRpc: boolean = false; let _selfCallRpcWarningShown: boolean = false; function checkReadyForSelfCallRpc(destinationInstance: string): void { if (!_isReadyForSelfCallRpc && isSelf(destinationInstance)) { if (!_selfCallRpcWarningShown && !readyForSelfCallRpc()) { Utils.log("Warning: Local IC not ready to handle self-call RPC's: The response from the IC will be delayed"); _selfCallRpcWarningShown = true; } else { _isReadyForSelfCallRpc = true; } } } /** * Calls the specified method ID (as a Fork RPC).\ * The message for the call will not be sent until the next tick of the event loop. */ export function callFork(destinationInstance: string, methodID: number, jsonOrRawArgs: object | Uint8Array): void { checkReadyForSelfCallRpc(destinationInstance); if (Utils.canLog(Utils.LoggingLevel.Verbose)) { Utils.log(`Calling Fork method (ID ${methodID}) on ${isSelf(destinationInstance) ? "local" : `'${destinationInstance}'`} IC`); } const message: Uint8Array = Messages.makeRpcMessage(Messages.RPCType.Fork, destinationInstance, methodID, jsonOrRawArgs); sendMessage(message, Messages.MessageType.RPC, destinationInstance); } /** * Queues, but does not send, a [Fork] call of the specified method ID.\ * Use flushQueue() to send all the queued calls.\ * Note: A callFork() or callImpulse() will also result in the queue being flushed (at the next tick of the event loop). */ export function queueFork(destinationInstance: string, methodID: number, jsonOrRawArgs: object | Uint8Array): void { _outgoingMessageStream.queueBytes(Messages.makeRpcMessage(Messages.RPCType.Fork, destinationInstance, methodID, jsonOrRawArgs)); } /** * Calls the specified method ID (as an Impulse RPC).\ * The message for the call will not be sent until the next tick of the event loop. */ export function callImpulse(destinationInstance: string, methodID: number, jsonOrRawArgs: object | Uint8Array): void { checkReadyForSelfCallRpc(destinationInstance); if (Utils.canLog(Utils.LoggingLevel.Verbose)) { Utils.log(`Calling Impulse method (ID ${methodID}) on ${isSelf(destinationInstance) ? "local" : `'${destinationInstance}'`} IC`); } const message: Uint8Array = Messages.makeRpcMessage(Messages.RPCType.Impulse, destinationInstance, methodID, jsonOrRawArgs); sendMessage(message, Messages.MessageType.RPC, destinationInstance); } /** * Queues, but does not send, a [Impulse] call of the specified method ID.\ * Use flushQueue() to send all the queued calls.\ * Note: A callFork() or callImpulse() will also result in the queue being flushed (at the next tick of the event loop). */ export function queueImpulse(destinationInstance: string, methodID: number, jsonOrRawArgs: object | Uint8Array): void { _outgoingMessageStream.queueBytes(Messages.makeRpcMessage(Messages.RPCType.Impulse, destinationInstance, methodID, jsonOrRawArgs)); } /** * Calls the specified post method (as a Fork RPC). Returns the unique call ID. * * The result (or error) of the called method will be received via the PostResultDispatcher provided to IC.start() in its AmbrosiaConfig parameter. */ // Note: There is no postImpulse(), nor should there be. An Impulse cannot be re-sent during recovery by the LB (only received), and we need // a post method to ALWAYS be re-sent during recovery so that nextPostCallID() gets called, which keeps the deterministically re-created // state (__ambrosiaInternalState._lastCallID) in-sync with the received (replayed) post results. // So instead we offer postByImpulse(), which invokes the post method indirectly via a self-call Impulse RPC. By using a // well-known method ID (POST_BY_IMPULSE_METHOD_ID) the Impulse can be intercepted (in postInterceptDispatcher()) and // converted into the actual post call. The downside of this approach is that the caller of postByImpulse() cannot know // the callID of the post method, which may make writing the postResult handler more difficult. TODO: This could be resolved // by not handling POST_BY_IMPULSE_METHOD_ID internally, and instead handling it via the [editable] code-generated dispatcher. export function postFork(destinationInstance: string, methodName: string, methodVersion: number, resultTimeoutInMs: number = -1, callContextData: any = null, ...methodArgs: PostMethodArgs): number { checkReadyForSelfCallRpc(destinationInstance); const filteredMethodArgs: PostMethodArg[] = methodArgs.filter(arg => arg !== undefined) as PostMethodArg[]; // Remove any 'undefined' elements in the array [see arg()] const callID: number = _poster.post(destinationInstance, methodName, methodVersion, resultTimeoutInMs, callContextData, ...filteredMethodArgs); return (callID); } /** * Calls the specified post method (via a self-call Impulse RPC). Returns void, unlike postFork(), so the callID will not be known. * * Note: **Do not** attempt to pass state information to your postResult handler outside of either the 'callContextData' or your application state. * This is because the code that calls postByImpulse() will not (must not) re-run during recovery. * * The result (or error) of the called method will be received via the PostResultDispatcher provided to IC.start() in its AmbrosiaConfig parameter. */ // Note: See comments above on postFork(). export function postByImpulse(destinationInstance: string, methodName: string, methodVersion: number, resultTimeoutInMs: number = -1, callContextData: any = null, ...methodArgs: PostMethodArgs): void { const jsonArgs: Utils.SimpleObject = {}; jsonArgs["destinationInstance"] = destinationInstance; jsonArgs["methodName"] = methodName; jsonArgs["methodVersion"] = methodVersion; jsonArgs["resultTimeoutInMs"] = resultTimeoutInMs; jsonArgs["callContextData"] = callContextData; jsonArgs["methodArgs"] = methodArgs.filter(arg => arg !== undefined); // Remove any 'undefined' elements in the array [see arg()] // Note: This is ALWAYS a self-call (the subsequent postFork() will use 'destinationInstance') callImpulse(instanceName(), POST_BY_IMPULSE_METHOD_ID, jsonArgs); } /** * Returns (via Fork) the result of a post method [contained in the supplied RPC] to the post-caller. * If there is no return value (ie. the method returned void) then 'result' can be omitted, but postResult() should always still be called. */ export function postResult<T>(rpc: Messages.IncomingRPC, result?: T): void { _poster.postResult<T>(rpc, Messages.RPCType.Fork, result); } /** Returns (via Fork) an error when attempting to execute a post method [contained in the supplied RPC] to the post-caller. */ export function postError(rpc: Messages.IncomingRPC, error: Error): void { _poster.postResult<Error>(rpc, Messages.RPCType.Fork, error); } /** * [Internal] The Impulse version of postError(). For internal use only.\ * **WARNING:** Will cause an exception if called during recovery (replay). */ function postImpulseError(rpc: Messages.IncomingRPC, error: Error): void { _poster.postResult<Error>(rpc, Messages.RPCType.Impulse, error); } /** * Returns the value of the specified (post) method parameter, or throws if the parameter cannot be found (unless the * parameter is optional, as indicated by a trailing "?" in the argName, in which case it will return 'undefined'). */ export function getPostMethodArg(rpc: Messages.IncomingRPC, argName: string): any { checkIsPostMethod(rpc); let isOptionalArg: boolean = argName.trim().endsWith("?"); let paramName: string = `${Poster.METHOD_PARAMETER_PREFIX}${argName}`; if (rpc.hasJsonParam(paramName)) { return (rpc.getJsonParam(paramName)); } if (!isOptionalArg && rpc.hasJsonParam(paramName + "?")) { // The caller [of getPostMethodArg()] didn't specify that the arg was optional, but an optional version of the arg was sent in the RPC, so we use this return (rpc.getJsonParam(paramName + "?")); } if (isOptionalArg && rpc.hasJsonParam(Utils.trimTrailingChar(paramName, "?"))) { // The caller [of getPostMethodArg()] did specify that the arg was optional, but an non-optional version of the arg was sent in the RPC, so we use this return (rpc.getJsonParam(Utils.trimTrailingChar(paramName, "?"))); } if (isOptionalArg) { return (undefined); } throw new Error(`Expected post method parameter '${argName}' to be present, but it was not found in the jsonParams`); } /** Returns the name of the (post) method called by the supplied RPC. */ export function getPostMethodName(rpc: Messages.IncomingRPC): string { checkIsPostMethod(rpc); return (rpc.getJsonParam("methodName")); } /** Returns the version of the (post) method called by the supplied RPC. */ export function getPostMethodVersion(rpc: Messages.IncomingRPC): number { checkIsPostMethod(rpc); return (parseInt(rpc.getJsonParam("methodVersion"))); } /** * Returns the sender (instance name) of the (post) method called by the supplied RPC.\ * **WARNING:** This is not a strong identity assertion because it's a spoofable value. Use it only for reporting, **not** for any kind of authorization. */ export function getPostMethodSender(rpc: Messages.IncomingRPC): string { checkIsPostMethod(rpc); return (rpc.getJsonParam("senderInstanceName")); } /** Throws if the supplied IncomingRPC is not a post method call. */ function checkIsPostMethod(rpc: Messages.IncomingRPC): void { if (rpc.methodID !== POST_METHOD_ID) { throw new Error(`The supplied RPC (methodID ${rpc.methodID}) is not a 'post' method`); } } /** * A utility post method that simply "echos" the value back to the [local] caller.\ * For example, an app that only made self-calls could, theoretically, be built using just this method * without having to publish any post methods of its own.\ * Result: The value that was supplied. Echoing a value makes it "replayable" by forcing it to be logged. * Handle the result in your PostResultDispatcher() for method name '_echo'. * Returns a unique callID for the method. */ export function echo_Post<T>(value: T, callContextData: any = null, timeoutInMs: number = -1): number { const callID: number = postFork(_config.icInstanceName, "_echo", 1, timeoutInMs, callContextData, arg("payload", value)); return (callID); } /** * An Impulse wrapper for echo_Post(). Returns void, unlike echo_Post(). * @see echo_Post */ export function echo_PostByImpulse<T>(value: T, callContextData: any = null, timeoutInMs: number = -1): void { postByImpulse(_config.icInstanceName, "_echo", 1, timeoutInMs, callContextData, arg("payload", value)); } /** * A utility post method used to check whether a given instance is responsive.\ * The 'timeout' defaults to 3000ms.\ * Result: The total round-trip time in milliseconds, or -1 if the operation timed out. * Handle the result in your PostResultDispatcher() for method name '_ping'. * Returns a unique callID for the method. */ export function ping_Post(destinationInstance: string, timeoutInMs: number = 3000): number { const callContextData: object = { destinationInstance: destinationInstance, timeoutInMs: timeoutInMs }; const callID: number = postFork(destinationInstance, "_ping", 1, timeoutInMs, callContextData, arg("sentTime", Date.now())); return (callID); } /** * An Impulse wrapper for ping_Post(). Returns void, unlike ping_Post(). * @see ping_Post */ export function ping_PostByImpulse(destinationInstance: string, timeoutInMs: number = 3000): void { const callContextData: object = { destinationInstance: destinationInstance, timeoutInMs: timeoutInMs }; postByImpulse(destinationInstance, "_ping", 1, timeoutInMs, callContextData, arg("sentTime", Date.now())); } /** * Requests the local IC to take a checkpoint immediately.\ * Normally, a checkpoint is only taken (by the IC) whenever the log size exceeds the 'logTriggerSize' (MB) that the IC was either registered or started with. */ export function requestCheckpoint(): void { let checkpointMessage: Uint8Array = Messages.makeTakeCheckpointMessage(); sendMessage(checkpointMessage, Messages.MessageType.TakeCheckpoint, _config.icInstanceName); } /** * [Internal] Sends a complete [binary] message to an IC. The message will be queued until the next tick of the event loop, but messages will always be sent in chronological order.\ * Note: The 'messageType' and 'destinationInstance' parameters are for logging purposes only, and MUST match the values included in the message 'bytes'. */ export function sendMessage(bytes: Uint8Array, messageType: Messages.MessageType, destinationInstance: string, immediateFlush: boolean = false): void { if (Utils.canLog(Utils.LoggingLevel.Verbose)) { let messageName: string = Messages.MessageType[messageType]; let destination: string = isSelf(destinationInstance) ? "local" : `'${destinationInstance}'`; let showBytes: boolean = _config.lbOptions.debugOutputLogging; // For debugging Utils.log(`Sending ${messageName ? `'${messageName}' ` : ""}to ${destination} IC (${bytes.length} bytes)` + (showBytes ? `: ${Utils.makeDisplayBytes(bytes)}` : "")); } _outgoingMessageStream.addBytes(bytes, immediateFlush); } /** * [Internal] [Experimental] An asynchronous version of sendMessage().\ * This can be more responsive than sendMessage() when called in a loop, because it avoids queuing messages until the function running the loop ends. This allows message I/O to interleave.\ * Note: The 'messageType' and 'destinationInstance' parameters are for logging purposes only, and do not supercede the values included in the message 'bytes'. */ async function sendMessageAsync(bytes: Uint8Array, messageType: Messages.MessageType, destinationInstance: string): Promise<void> { let promise: Promise<void> = new Promise<void>((resolve, reject: RejectedPromise) => { try { sendMessage(bytes, messageType, destinationInstance, true); // We use setImmediate() here to delay scheduling the continuation until AFTER the I/O events generated (queued) by sendMessage(). // This allows I/O events to interleave (ie. messages can be received while we're sending messages). setImmediate(() => resolve()); } catch (error: unknown) { reject(Utils.makeError(error)); } }); return (promise); } /** * Sends (synchronously) all calls queued with queueFork() / queueImpulse().\ * Returns the number of messages that were queued. * * **WARNING:** When enqueuing multiple batches (eg. in a loop), this method should be called from within the same asynchronous callback * (eg. via setImmediate()) that also enqueued the batch. Otherwise, because this method runs synchronously, I/O with the IC will not interleave. */ export function flushQueue(): number { let queueLength: number = _outgoingMessageStream.flushQueue(); return (queueLength); } /** Returns the number of messages currently in the [outgoing] message queue. */ export function queueLength(): number { return (_outgoingMessageStream.queueLength); } /** [Internal] Streams (asynchronously) data to the local IC. Any subsequent messages sent via sendMessage() will queue until the stream finishes. */ export function sendStream(byteStream: Stream.Readable, streamLength: number = -1, streamName?: string, onFinished?: (error?: Error) => void): void { streamName = `${streamName ? `'${streamName}' ` : ""}`; Utils.log(`Streaming ${streamName}to local IC...`); function onSendStreamFinished(error?: Error) { Utils.log(`Stream ${streamName}${error ? `failed (reason: ${error.message})` : "finished"}`); if (onFinished) { onFinished(error); } } _outgoingMessageStream.addStreamedBytes(byteStream, streamLength, onSendStreamFinished); } /** [Internal] [Experimental] An awaitable version of sendStream(). */ async function sendStreamAsync(byteStream: Stream.Readable, streamLength: number = -1, streamName?: string): Promise<void> { let promise: Promise<void> = new Promise<void>((resolve, reject: RejectedPromise) => { try { function onSendStreamFinished(error?: Error) { error ? reject(error) : resolve(); } sendStream(byteStream, streamLength, streamName, onSendStreamFinished); } catch (error: unknown) { reject(Utils.makeError(error)); } }); return (promise); } /** [Internal] Streams (asynchronously) the outgoing checkpoint to the IC. Any subsequent messages sent via sendMessage() will queue until the stream finishes (after which outgoingCheckpoint.onFinished() is called). */ export function sendCheckpoint(outgoingCheckpoint: Streams.OutgoingCheckpoint, onSuccess?: () => void): void { // A check to make the compiler happy when using 'strictNullChecks' if (!_lbReceiveSocket) { throw new Error("Unable to send checkpoint (reason: The inbound socket from the IC is null, so it cannot be paused)"); } // When the IC asks the LB to take a checkpoint, the IC won't send any further log pages until it receives the last // byte of checkpoint data from the LB. So we don't need to guard against the app state being changed (by the app // continuing to process incoming messages) while we stream the checkpoint [which we could do by temorarily pausing // the inbound socket from the IC (_lbReceiveSocket) until the stream is finished]. function onSendCheckpointFinished(error?: Error): void { // A check to make the compiler happy when using 'strictNullChecks' if (!_lbReceiveSocket) { throw new Error("Unable to continue after sending checkpoint (reason: The inbound socket from the IC is null, so it cannot be resumed)"); } if (outgoingCheckpoint.onFinished) { outgoingCheckpoint.onFinished(error); } if (!error) { emitAppEvent(Messages.AppEventType.CheckpointSaved); if (onSuccess) { onSuccess(); } } if (error && !outgoingCheckpoint.onFinished) { throw error; // The "uncaughtException" handler will catch this } } sendStream(outgoingCheckpoint.dataStream, outgoingCheckpoint.length, `CheckpointDataStream (${outgoingCheckpoint.length} bytes)`, onSendCheckpointFinished); } /** [Internal] [Experimental] An awaitable version of sendCheckpoint(). The outgoingCheckpoint.onFinished must be null; use the continuation instead. */ // TODO: This needs more testing. async function sendCheckpointAsync(outgoingCheckpoint: Streams.OutgoingCheckpoint): Promise<void> { let promise: Promise<void> = new Promise<void>((resolve, reject: RejectedPromise) => { try { if (outgoingCheckpoint.onFinished) { throw new Error("The outgoingCheckpoint.onFinished must be null when used with sendCheckpointAsync(); use the continuation instead"); } outgoingCheckpoint.onFinished = function onCheckpointFinished(error?: Error) { error ? reject(error) : resolve(); }; sendCheckpoint(outgoingCheckpoint); } catch (error: unknown) { reject(Utils.makeError(error)); } }); return (promise); } /** * Upgrades (switches) the executing code of the IC. Typically, the new handlers will reside in an "upgraded" PublisherFramework.g.ts * [generated] file which will be included in the app along with the current PublisherFramework.g.ts file.\ * Should be called when AppEventType.UpgradeCode becomes signalled. */ export function upgrade(dispatcher: Messages.MessageDispatcher, checkpointProducer: Streams.CheckpointProducer, checkpointConsumer: Streams.CheckpointConsumer, postResultDispatcher?: Messages.PostResultDispatcher): void { _config.updateHandlers(dispatcher, checkpointProducer, checkpointConsumer, postResultDispatcher); _config.dispatcher = _poster.wrapDispatcher(_config.dispatcher); _icUpgradeCalled = true; } /** [Internal] Deletes Ambrosia log/checkpoint files from the specified folder (on disk or in Azure), then removes the folder. Returns the number of files deleted. */ export async function deleteInstanceLogFolderAsync(instanceLogFolder: string, icLogStorageType: keyof typeof Configuration.LogStorageType): Promise<number> { let deletedFileCount: number = 0; switch (icLogStorageType) { case Configuration.LogStorageType[Configuration.LogStorageType.Files]: // Clear (reset) the log folder [this will remove all logs and checkpoints for the instance] // Note: It's not sufficient just to delete the files, the directory has to be deleted too, otherwise the IC will fail with "FATAL ERROR 2: Missing checkpoint 1" if (File.existsSync(instanceLogFolder)) { // Delete all log/checkpoint files (if any) from the folder. // Note: We filter for "*serverlog*", "*serverchkpt*", and "serverkillFile" files to provide protection // in the case that the config.icLogFolder is [accidentally] set to, for example, a system folder. File.readdirSync(instanceLogFolder) .filter(fn => /serverlog[\d]+$/.test(fn) || /serverchkpt[\d]+$/.test(fn) || (fn === "serverkillFile")) .forEach((fileName: string) => { let fullFileName: string = Path.join(instanceLogFolder, fileName); Utils.deleteFile(fullFileName); deletedFileCount++; }); File.rmdirSync(instanceLogFolder); // Note: rmdirSync() will throw if the directory is not empty } break; case Configuration.LogStorageType[Configuration.LogStorageType.Blobs]: deletedFileCount = await AmbrosiaStorage.deleteBlobLogsAsync(instanceLogFolder); break; } return (deletedFileCount); } /** * Starts the Immortal Coordinator process. * Returns the application state instantiated using 'appStateConstructor' (the application state class name). */ export function start<T extends Root.AmbrosiaAppState>(config: Configuration.AmbrosiaConfig, appStateConstructor: new (restoredAppState?: T) => T): T { Root.checkAppStateConstructor(appStateConstructor); // This instantiates the application state, which we return to the caller; it also checks that the constructed state derives from AmbrosiaAppState const appState: T = initializeAmbrosiaState(appStateConstructor); _config = config; _config.dispatcher = _poster.wrapDispatcher(_config.dispatcher); // If an upgrade has occurred, we simply invoke IC.upgrade() again [via the user-provided AppEventType.UpgradeCode handler] to switch _config over to using the upgraded handlers. // When the user is ready for the next upgrade [or anytime after the last upgrade], 'activeCode' should be reset to "VCurrent" and the handlers supplied to IC.start() should // be replaced by the handlers assigned via the IC.upgrade() call in the AppEventType.UpgradeCode handler. if (config.activeCode === Configuration.ActiveCodeType.VNext) { _icUpgradeCalled = false; emitAppEvent(Messages.AppEventType.UpgradeCode); if (!_icUpgradeCalled) { throw new Error(`The 'activeCode' setting is "VNext", but there is no VNext code to use (reason: IC.upgrade() was not called by your AppEventType.UpgradeCode handler)`); } } Utils.log(`Using "${Configuration.ActiveCodeType[config.activeCode]}" application code (appVersion: ${config.appVersion}, upgradeVersion: ${config.upgradeVersion})`); if (_config.isIntegratedIC) { const icExecutable: string = Utils.getICExecutable(config.icBinFolder, config.useNetCore, config.isTimeTravelDebugging); // This may throw // See https://github.com/microsoft/AMBROSIA/blob/master/Samples/HelloWorld/TimeTravel-Windows.md let commonArgs: string[] = [`--instanceName=${config.icInstanceName}`, `--receivePort=${config.icReceivePort}`, `--sendPort=${config.icSendPort}`, `--log=${config.icLogFolder}`]; let timeTravelDebuggingArgs: string[] = ["DebugInstance", ...commonArgs, `--checkpoint=${config.debugStartCheckpoint}`, `--currentVersion=${config.appVersion}`]; if (config.debugTestUpgrade) { timeTravelDebuggingArgs.push("--testingUpgrade"); } let normalArgs: string[] = [`--port=${config.icCraPort}`, ...commonArgs]; // TODO: This version check is brittle: It would be better for the IC to support a --version parameter which makes it simply echo its version to the console (like "node --version"). // Having the binary set its 'File version' attribute then reading it with https://www.npmjs.com/package/win-version-info would only work on Windows. const isPostSledgeHammer: boolean = (Utils.getFileLastModifiedTime(icExecutable) > new Date("10/15/2020 04:52 PM")); // 'Last modified' of the release binary + 1 minute const optionalNormalArgs: { optionName: string, argPair: string }[] = [ { optionName: "logTriggerSizeInMB", argPair: `--logTriggerSize=${config.logTriggerSizeInMB}` }, // If not set locally (via ambrosiaConfig.json) we can just let the IC default to the registered value [either explicitly set or the default] // Note: Internally [to the IC], supplying --replicaNum (even to 0) automatically sets --activeActive to true [see ParseOptions() in \ambrosia\ImmortalCoordinator\Program.cs, and bug #173] { optionName: "isActiveActive", argPair: (config.isActiveActive ? "--activeActive" : "") }, // If set locally, MUST match the value specified when 'AddReplica' was run (we enforce this) { optionName: "replicaNumber", argPair: (config.isActiveActive && (config.replicaNumber > 0) ? `--replicaNum=${config.replicaNumber}` : "") }, // If set locally, MUST match the value specified when 'AddReplica' was run (we cannot enforce this) { optionName: "icLogStorageType", argPair: `--logStorageType=${config.icLogStorageType}` }, { optionName: "icIPv4Address", argPair: `--IPAddr=${config.icIPv4Address}` }, { optionName: "secureNetworkAssemblyName", argPair: `--assemblyName=${config.secureNetworkAssemblyName}` }, { optionName: "secureNetworkClassName", argPair: `--assemblyClass=${config.secureNetworkClassName}` } ]; optionalNormalArgs.forEach(oa => { if (config.isConfiguredLocally(oa.optionName) && (oa.argPair !== "")) { normalArgs.push(oa.argPair); } }); const args: string[] = config.isTimeTravelDebugging ? timeTravelDebuggingArgs : normalArgs; Utils.log(`Starting ${icExecutable}...`, null, Utils.LoggingLevel.Minimal); Utils.log(`Args: ${args.join(" ").replace(/--/g, "")}`, null, Utils.LoggingLevel.Minimal); Utils.logMemoryUsage(); emitAppEvent(Messages.AppEventType.ICStarting); // The following starts the IC process directly (no visible console) and pipes both stdout/stderr to our stdout. // To aid in distinguishing the IC output from our own output we use the Utils.StandardOutputFormatter class. _icProcess = ChildProcess.spawn(config.useNetCore ? "dotnet" : icExecutable, (config.useNetCore ? [icExecutable] : []).concat(args), { stdio: ["ignore", "pipe", "pipe"], shell: false, detached: false }); if (!_icProcess.stdout || !_icProcess.stderr) { throw new Error(`Unable to redirect stdout/stderr for IC executable (${icExecutable})`); } const icSource: string = "[IC]"; const icColor: Utils.ConsoleForegroundColors = Utils.ConsoleForegroundColors.Cyan; const icExceptionColor: Utils.ConsoleForegroundColors = Utils.ConsoleForegroundColors.Red; const CRA_INSTANCE_DOWN_MSG: string = "Possible reason: The connection-initiating CRA instance appears to be down"; let outputFormatter: Utils.StandardOutputFormatter = new Utils.StandardOutputFormatter(icSource, icColor, icExceptionColor, [/FATAL ERROR/, new RegExp(CRA_INSTANCE_DOWN_MSG), /^Adding input:$/, /^Adding output:$/, /^restoring input:$/, /^restoring output:$/, // These detect self-connections /^Adding input:/, /^Adding output:/, /^restoring input:/, /^restoring output:/]); // These detect remote-connections let outputFormatterStream: Utils.StandardOutputFormatter = _icProcess.stdout.pipe(outputFormatter); if (Utils.canLogToConsole()) { outputFormatterStream.pipe(Process.stdout); _icProcess.stderr.pipe(Process.stdout); } else { // We still need a [no-op] place for the "transformed" outputFormatterStream to be written // [otherwise the Transform stream will simply endlessly buffer as it reads data from stdout] // Note: On Windows NUL is a device, not a file, so it must be accessed via device namespace by putting \\.\ at the beginning let nullOut: File.WriteStream = File.createWriteStream(Utils.isWindows() ? "\\\\.\\NUL" : "/dev/null"); outputFormatterStream.pipe(nullOut); _icProcess.stderr.pipe(nullOut); // This is just to prevent the stderr output from appearing } // Add a handler to detect watched-for tokens outputFormatter.on("tokenFound", (token: string, line: string) => { switch (token) { case `/${CRA_INSTANCE_DOWN_MSG}/`: // Upon attempting to connect to an instance that is down, or upon startup of an instance that has just been registered // for the first time, the IC will report this "expected" CRA error [possibly more than once, consecutively]: // // System.InvalidOperationException: Nullable object must have a value. // at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) // at CRA.ClientLibrary.CRAClientLibrary.<ConnectAsync>d__53.MoveNext() // Possible reason: The connection-initiating CRA instance appears to be down or could not be found. Restart it and this connection will be completed automatically if (config.isFirstStartAfterInitialRegistration) { // WORKAROUND: Log that this was an "expected error". This can be removed when bug #156 is resolved. Utils.log(`Warning: Because this is the first start of the instance after initial registration, the prior ${icSource} 'System.InvalidOperationException' is expected`); } break; case "/FATAL ERROR/": // Note: We leave the reporting (logging) of fatal errors to StandardOutputFormatter onError("FatalError", null, true); break; case "/^Adding input:$/": case "/^Adding output:$/": case "/^restoring input:$/": case "/^restoring output:$/": checkSelfConnectionsCount(); break; case "/^Adding input:/": case "/^Adding output:/": case "/^restoring input:/": case "/^restoring output:/": _remoteConnectionCount++; checkRemoteConnectionsCount(); break; } }); _icProcess.on("exit", (code: number, signal: NodeJS.Signals) => { if (_icStoppingDueToError && !code) { // If the IC fails with a FATAL error, it's almost certain that the process has already terminated (so "exit" has already been raised) // in which case the stop() called by onError() will not result in "exit" firing (again). But just to be safe, we handle this unlikely // case here (ie. the case of onError() -> (timer) -> stop() -> _icProcess.kill() -> "exit" event [in this case 'code' will be null]). // Note: This case can also happen when testing onError() [by calling it directly without an actual IC failure]. code = 1; // ERROR_EXIT_CODE } if (code === 4294967295) // 0xFFFFFFFF { code = -1; } // Note: On Windows, exit code 0xC000013A means that the application terminated as a result of either a CTRL+Break or closing the console window. // On Windows, an explicit kill (via either Task Manager or taskkill /F) will result in a code of '1' and a signal of 'null'. let byUserRequest: boolean = (Process.platform === "win32") && (code == 0xC000013A); let exitState: string = byUserRequest ? "at user request" : (code === null ? (signal === "SIGTERM" ? "normally" : `abnormally [signal: ${signal}]`) : `abnormally [exit code: ${code}]`); let icExecutableName: string = Path.basename(Utils.getICExecutable(config.icBinFolder, config.useNetCore, config.isTimeTravelDebugging)); try { Utils.log(`${icExecutableName} stopped (${exitState})`); // Note: The user-provided AppEventType.ICStopped handler may also call stop(), but we can't rely on that stop(); // Note: The user-provided AppEventType.ICStopped handler may throw; the code-gen'd dispatcher() will catch this, but the user may not be using it or may have modified it _icStoppedSignalled = true; emitAppEvent(Messages.AppEventType.ICStopped, code === null ? 0 : code); } catch (error: unknown) { Utils.log(Utils.makeError(error)); } }); Utils.log(`\'${config.icInstanceName}\'${config.replicaNumber > 0 ? ` (replica #${config.replicaNumber})` : ""} IC started (PID ${_icProcess.pid})`); emitAppEvent(Messages.AppEventType.ICStarted); } else { const icLocation: string = !_config.icIPv4Address || Utils.isLocalIPAddress(_config.icIPv4Address) ? "locally" : `on ${_config.icIPv4Address}`; Utils.log(`Warning: IC must be manually started ${icLocation} (because 'icHostingMode' is "${Configuration.ICHostingMode[_config.icHostingMode]}" and a remote 'icIPv4Address' was not specified)`); } connectToIC(); return (appState); } /** * Stops the Immortal Coordinator process (if it's running).\ * This method also stops Node if 'exitApp' is true (the default).\ * **WARNING:** Setting 'exitApp' to false requires that you **must** shutdown Node in your AppEventType.ICStopped handler. */ export function stop(exitApp: boolean = true): void { if (!_icProcess) { if ((_config.icHostingMode === Configuration.ICHostingMode.Separated) && exitApp) { Utils.logMemoryUsage(); Utils.closeOutputLog(); // Note: Without calling Process.exit() Node will wait for any pending timers before exiting. As an alternative, we could // keep track of all [our] pending timers and then unref() them here, but this would add considerable overhead. Process.exit(); // Stop Node.exe } return; } if (_outgoingMessageStream && (queueLength() !== 0)) { // Not sure if this condition ever arises, but keeping this here as a canary Utils.log(`Warning: IC stopping while there are still ${queueLength()} outgoing messages in the queue`, null, Utils.LoggingLevel.Minimal); } logInFlightPostMethodsCount(); if (_lbSendSocket) { if (_outgoingMessageStream) { // Attempt to flush the queue before exiting. We do this to handle the case of IC.sendMessage() being called right before IC.stop(). // In this case, the resulting pending flushQueue() [that occurs via setImmediate()] may error when it attempts to push to the // [now closed] stream. By preemptively flushing (synchronously) we attempt to avert the error. try { flushQueue(); } catch (error: unknown) { Utils.log(`Error: Unable to flush ${_outgoingMessageStream.queueLength} messages from the outgoing message queue (reason: ${Utils.makeError(error).message})`); } try { if (_outgoingMessageStream.canClose()) { _outgoingMessageStream.close(); } } catch (error: unknown) { Utils.log(`Error: Unable to close _outgoingMessageStream (reason: ${Utils.makeError(error).message})`); } } try { _lbSendSocket.destroy(); } catch (error: unknown) { Utils.log(`Error: Unable to destroy _lbSendSocket (reason: ${Utils.makeError(error).message})`); } _lbSendSocket = null; } if (_lbReceiveSocket) { try { _lbReceiveSocket.destroy(); } catch (error: unknown) { Utils.log(`Error: Unable to destroy _lbReceiveSocket (reason: ${Utils.makeError(error).message})`); } _lbReceiveSocket = null; } if (_icProcess) { const IC_TERMINATION_TIMEOUT_IN_MS: number = 500; const TIMEOUT_EXIT_CODE: number = 101; // The IC failed to exit in a "reasonable" time (IC_TERMINATION_TIMEOUT_IN_MS) const ERROR_EXIT_CODE: number = 1; _icProcess.kill(); // This will raise the "exit" event for _icProcess, whose handler will raise AppEventType.ICStopped _icProcess = null; if (exitApp) { // We wait IC_TERMINATION_TIMEOUT_IN_MS to give the IC process a chance to terminate and emit its "exit" event (which raises // AppEventType.ICStopped), and also allows time to capture any final "straggler" output from either the IC or LB. setTimeout(() => { const appExitCode: number = _icStoppedSignalled ? (_icStoppingDueToError ? ERROR_EXIT_CODE : 0) : TIMEOUT_EXIT_CODE; if (!_icStoppedSignalled) { const icExecutableName: string = Path.basename(Utils.getICExecutable(_config.icBinFolder, _config.useNetCore, _config.isTimeTravelDebugging)); Utils.log(`Warning: ${icExecutableName} did not stop after ${IC_TERMINATION_TIMEOUT_IN_MS}ms`); try { // Because the IC took longer than IC_TERMINATION_TIMEOUT_IN_MS to stop, we need to raise // AppEventType.ICStopped "manually" so that the app can do any necessary cleanup before we exit emitAppEvent(Messages.AppEventType.ICStopped, _icStoppingDueToError ? ERROR_EXIT_CODE : TIMEOUT_EXIT_CODE); } catch (error: unknown) { Utils.log(Utils.makeError(error)); } } Utils.logMemoryUsage(); Utils.closeOutputLog(); // Note: Without calling Process.exit() Node will wait for any pending timers before exiting. As an alternative, we could // keep track of all [our] pending timers and then unref() them here, but this would add considerable overhead. Process.exit(appExitCode); // Stop Node.exe }, IC_TERMINATION_TIMEOUT_IN_MS); } } } /** Handler called if there are I/O errors with the IC, or if the IC reports a fatal error. */ function onError(source: string, error: Error | null, isFatalError?: boolean): void { if (error) { Utils.logWithColor(Utils.ConsoleForegroundColors.Red, `${error.stack}`, `[IC:${source}]`, Utils.LoggingLevel.Minimal); /* // Commented out because in a "migration on the same machine" scenario, if a second LB gets an ECONNRESET because it can't connect to the IC // (or its connection is initially allowed but then rejected?) then it shouldn't kill the IC because the IC is still being used by the first LB. if (error.message.indexOf("ECONNRESET") !== -1) { // The IC terminated unexpectedly, so we can't continue [as an Immortal, the IC and the LB must share the same lifespan]. // We do this just as a safety net since if the IC has terminated, the _icProcess "exit" event handler will also call stop(). isFatalError = true; } */ } if (isFatalError) { _icStoppingDueToError = true; // Allow some time for the process to terminate "naturally", then explicitly [try to] stop it. // Note: If the _icProcess "exit" event fires BEFORE this timeout elapses, stop() will be a no-op. setTimeout(() => stop(), 250); // If _icProcess hasn't already terminated, stop() will raise AppEventType.ICStopped via the _icProcess "exit" event handler } } /** * Once the LB connects to the IC, the IC should then create 4 connections to itself (to the Input/Output ports for 2 channels: data and control). * Thus, the IC should report a total of 4 "Adding/restoring input:/output:" messages (in any combination), otherwise it indicates that the IC is * not properly registered (or is not behaving as expected). This function checks for this condition. */ function checkSelfConnectionsCount(timeoutInMs: number = 5000): void { if (++_selfConnectionCount === 4) { // The IC is now capable of handling (ie. immediately responding to) self-call RPC's emitAppEvent(Messages.AppEventType.ICReadyForSelfCallRpc); } _selfConnectionCountCheckTimer = Utils.restartOnceOnlyTimer(_selfConnectionCountCheckTimer, timeoutInMs, () => { // The CRA will make connections [for a given instance] one-at-a-time in the order they appear in the CRAConnectionsTable [ie. sorted ascending by RowKey, which // includes the instance name]. If a remote instance is down, CRA will wait indefinitely for the vertex to connect. Consequently, the CRA may get "stuck" before // it makes it to either the 'control' and/or 'data' connections for the local instance, resulting in either 0 or 2 self-connection messages instead of 4. if (_selfConnectionCount !== 4) { Utils.log(`Warning: The IC has reported ${_selfConnectionCount} self-connection messages when 4 were expected; ` + `${(_remoteInstanceNames.length > 0) ? `one-or-more of the expected IC instances ('${_remoteInstanceNames.join("', '")}') may be down, or ` : ""}` + `the '${_config.icInstanceName}' IC may need to be re-registered`); } else { // This handles the case where we don't receive ANY "Adding/restoring input/output:(remoteInstanceName)" messages in the output, // so checkRemoteConnectionsCount() will never have been called checkRemoteConnectionsCount(); } }); } /** * The LB should make 4 connections (to the Input/Output ports for 2 channels: data and control) to each instance (vertex) in the CRAConnectionTable. * This function checks if the required number of connections has been made (within the specified timeoutInMs). */ function checkRemoteConnectionsCount(timeoutInMs: number = _remoteInstanceNames.length * 4 * 1000): void { if (_remoteInstanceNames.length === 0) { return; } _remoteConnectionCountCheckTimer = Utils.restartOnceOnlyTimer(_remoteConnectionCountCheckTimer, timeoutInMs, () => { let expectedRemoteConnectionCount: number = _remoteInstanceNames.length * 4; if (_remoteConnectionCount !== expectedRemoteConnectionCount) { Utils.log(`Warning: The IC has reported ${_remoteConnectionCount} remote connection messages when ${expectedRemoteConnectionCount} were expected; ` + `one-or-more of the remote IC instances ('${_remoteInstanceNames.join("', '")}') may be down`); } }); } /** * Once the LB connects to the IC, the IC should then create 4 connections to itself (to the Input/Output ports for 2 channels: data and control). * This function checks if ANY connection has been made (within, by default, 10 seconds). */ export function checkSelfConnection(timeoutInMs: number = 10 * 1000) { // We only monitor IC output when running the IC integrated if (!_config.isIntegratedIC) { return; } _selfConnectionCheckTimer = Utils.restartOnceOnlyTimer(_selfConnectionCheckTimer, timeoutInMs, () => { if (_selfConnectionCount === 0) { Utils.log(`Warning: The IC has not yet reported making any connections to itself (required for self-call RPC support); ` + `${(_remoteInstanceNames.length > 0) ? `one-or-more of the expected IC instances ('${_remoteInstanceNames.join("', '")}') may be down, or ` : ""}` + `the '${_config.icInstanceName}' IC may need to be re-registered`); } }); } let _waitingToConnectToICSendPort: boolean = true; let _waitingToConnectToICReceivePort: boolean = true; let _lastICSendPortConnectAttemptTime: number = 0; let _lastICReceivePortConnectAttemptTime: number = 0; let _minimumConnectionRetryDelayInMs: number = 3000; // Retry connections no more frequently than this /** Connects (asynchronously) to the IC's send/receive sockets and, when both are connected, starts processing messages. */ // Note: Net.connect() and Socket.connect() can have different timeout behavior depending on the version of NodeJS, the OS, and (possibly) // the failure reason (eg. ECONNREFUSED vs ENOTFOUND), so we use our own retry timeout logic to get [more] consistent behavior. function connectToIC(): void { const hostName: string = (!_config.icIPv4Address || Utils.isLocalIPAddress(_config.icIPv4Address)) ? "localhost" : _config.icIPv4Address; /** [Local function] Connects to the IC's receive port (this is the port we will send on). */ function connectLBSendSocket(): void { _lastICReceivePortConnectAttemptTime = Date.now(); if (_lbSendSocket === null) { Utils.log(`LB Connecting to IC receive port (${hostName}:${_config.icReceivePort})...`); // Note: When running in the "Integrated" icHostingMode, [at least] the first connection attempt will // typically fail with "connect ECONNREFUSED 127.0.0.1:<port>" because the IC hasn't yet created the port _lbSendSocket = Net.connect(_config.icReceivePort, hostName); // Note: connect() is asynchronous _lbSendSocket.once("connect", () => { Utils.log(`LB connected to IC receive port (${hostName}:${_config.icReceivePort})`); _waitingToConnectToICReceivePort = false; _minimumConnectionRetryDelayInMs = 250; // Once we're connected to the IC receive port, the IC send port should be available to connect to immediately onConnectionMade(); }); _lbSendSocket.on("error", (error: Error) => { if (_waitingToConnectToICReceivePort) { const timeSinceLastConnectAttemptInMs: number = Date.now() - _lastICReceivePortConnectAttemptTime; const retryDelayInMs: number = Math.max(0, _minimumConnectionRetryDelayInMs - timeSinceLastConnectAttemptInMs); Utils.log(`LB retrying to connect to IC receive port (in ${retryDelayInMs}ms); last attempt failed (reason: ${error.message})...`); emitAppEvent(Messages.AppEventType.WaitingToConnectToIC); setTimeout(() => connectLBSendSocket(), retryDelayInMs); return; } onError("LBSend->ICReceive Socket", error); }); } else { // Typically, this will succeed _lbSendSocket.connect(_config.icReceivePort, hostName); // Note: connect() is asynchronous } } /** [Local function] Connects to the IC's send port (this is the port we will receive on). */ function connectLBReceiveSocket(): void { _lastICSendPortConnectAttemptTime = Date.now(); if (_lbReceiveSocket === null) { Utils.log(`LB connecting to IC send port (${hostName}:${_config.icSendPort})...`); // Note: When running in the "Integrated" icHostingMode, since we're already connected to the IC's receive port, // the send port connection attempt will typically always succeed on the first try _lbReceiveSocket = Net.connect(_config.icSendPort, hostName); // Note: connect() is asynchronous // Add handlers _lbReceiveSocket.once("connect", () => { Utils.log(`LB connected to IC send port (${hostName}:${_config.icSendPort})`); _waitingToConnectToICSendPort = false; onConnectionMade(); }); _lbReceiveSocket.on("error", (error: Error) => { if (_waitingToConnectToICSendPort) { const timeSinceLastConnectAttemptInMs: number = Date.now() - _lastICSendPortConnectAttemptTime; const retryDelayInMs: number = Math.max(0, _minimumConnectionRetryDelayInMs - timeSinceLastConnectAttemptInMs); Utils.log(`LB retrying to connect to IC send port (in ${retryDelayInMs}ms); last attempt failed (reason: ${error.message})...`); emitAppEvent(Messages.AppEventType.WaitingToConnectToIC); setTimeout(() => connectLBReceiveSocket(), retryDelayInMs); return; } onError("LBReceive->ICSend Socket", error); }); } else { // Typically, this will succeed _lbReceiveSocket.connect(_config.icSendPort, hostName); // Note: connect() is asynchronous } } /** [Local function] Checks if both connections (send and receive socket) have been made, and - if so - proceeds to the next step of the LB startup. */ function onConnectionMade(): void { if (!_waitingToConnectToICReceivePort) { if (_waitingToConnectToICSendPort) { // We've connected to the IC's receive port (but not the send port), so now we can connect to the IC's send port (our receive socket) connectLBReceiveSocket(); } else { // Both connections have been made const maxQueueSizeInBytes: number = Configuration.loadedConfig().lbOptions.maxMessageQueueSizeInMB * 1024 * 1024; _outgoingMessageStream = new Streams.OutgoingMessageStream(_lbSendSocket!, (error: Error) => onError("OutgoingMessageStream", error), true, maxQueueSizeInBytes); // NonNullAssertion [for 'strictNullChecks'] onICConnected(); emitAppEvent(Messages.AppEventType.ICConnected); } } } // We must connect to the IC's ports in order: receive port first, then send port. // We do this to match the IC's accept() order for these sockets, and to avoid the corner case of 2 LB's connecting to one port each on the same IC (see bug #182)]. connectLBSendSocket(); } /** Called when the LB and IC are connected (on both ports). Sets up the data handler for the receive socket. */ function onICConnected(): void { const INITIAL_PAGE_BUFFER_SIZE: number = 16 * 1024 * 1024; // 16 MB [the IC has an 8 MB limit for a log page size] const ONE_MB: number = 1024 * 1024; const MEMORY_LOGGING_THRESHOLD: number = ONE_MB * 256; let receivingCheckpoint: boolean = false; let checkpointBytesTotal: number = 0; let checkpointBytesRemaining: number = 0; let incomingCheckpoint: Streams.IncomingCheckpoint; let checkpointStream: Stream.Writable; // This is where we will write received checkpoint data let pageReceiveBuffer: Buffer = Buffer.alloc(INITIAL_PAGE_BUFFER_SIZE); // This is where we will accumulate bytes until we have [at least] 1 complete log page [the buffer will auto-grow/shrink as needed] let bufferOffset: number = 0; // The current write position in pageReceiveBuffer let bufferShrinkTimer: NodeJS.Timeout; // Timer used to auto-shrink pageReceiveBuffer after auto-grow let checkpointRestoreStartTime: number = 0; let totalICBytesReceived: number = 0; let nextMemoryLoggingThreshold: number = MEMORY_LOGGING_THRESHOLD; _lbReceiveSocket!.on("data", onICData); // NonNullAssertion [for 'strictNullChecks'] /** [Local function] Called whenever we receive a chunk of data from the IC. The chunk will never be more than 65536 bytes. */ function onICData(data: Buffer): void { if (Utils.isTraceFlagEnabled(Utils.TraceFlag.MemoryUsage)) { if (totalICBytesReceived + data.length > Number.MAX_SAFE_INTEGER) // Unlikely (8 petabytes), but possible { totalICBytesReceived = 0; nextMemoryLoggingThreshold = MEMORY_LOGGING_THRESHOLD; } totalICBytesReceived += data.length; if (totalICBytesReceived > nextMemoryLoggingThreshold) { nextMemoryLoggingThreshold += MEMORY_LOGGING_THRESHOLD; Utils.logMemoryUsage(); } } processIncomingICData(data); } /** [Local function] Called when we've received the last 'chunk' of checkpoint data from the IC. */ function onCheckpointEnd(finalCheckpointChunk: Uint8Array, remainingBuffer?: Buffer) { receivingCheckpoint = false; checkpointBytesRemaining = 0; // Wait for checkpointStream to finish // Note: To be sure that we don't start reading/processing [additional] log pages until the checkpoint has been fully received [restored], we // pause the inbound socket from the IC until the checkpointStream 'finish' event handler completes [which can include calling user-code] _lbReceiveSocket!.pause(); // NonNullAssertion [for 'strictNullChecks'] checkpointStream.on("finish", (error?: Error) => { incomingCheckpoint.onFinished(error); Utils.log(`Checkpoint (${checkpointBytesTotal} bytes) ${error ? `restore failed (reason: ${error.message})` : `restored (in ${Date.now() - checkpointRestoreStartTime}ms)`}`); if (!error) { logInFlightPostMethodsCount(); emitAppEvent(Messages.AppEventType.CheckpointLoaded, checkpointBytesTotal); } // The 'finalCheckpointChunk' may have been part of a buffer that ALSO contained part (or all) of the next // log page in it (after the checkpoint chunk), so it's now safe to finish processing that part of the buffer if (remainingBuffer && (remainingBuffer.length > 0)) { processIncomingICData(remainingBuffer); // Note: This will cause re-entrancy into processIncomingICData() } _lbReceiveSocket!.resume(); // NonNullAssertion [for 'strictNullChecks'] }); checkpointStream.end(finalCheckpointChunk); // This will make checkpointStream [synchronously] emit a 'finish' event which will [synchronously] invoke the 'finish' handler above } /** * [Local function] [Re]Schedules an operation to shrink pageReceiveBuffer to its original size, but only if the buffer is empty. * The delayInMs defaults to 5 minutes. */ function scheduleBufferAutoShrink(delayInMs: number = 5 * 60 * 1000): void { if (!bufferShrinkTimer) { bufferShrinkTimer = setTimeout(() => { if (bufferOffset === 0) { if (pageReceiveBuffer.length > INITIAL_PAGE_BUFFER_SIZE) { pageReceiveBuffer = Buffer.alloc(INITIAL_PAGE_BUFFER_SIZE); Utils.log(`Log page buffer decreased to ${INITIAL_PAGE_BUFFER_SIZE} bytes (${(INITIAL_PAGE_BUFFER_SIZE / (1024 * 1024)).toFixed(2)} MB)`, null, Utils.LoggingLevel.Minimal); } } else { // We can't shrink yet (the buffer is still being processed), so try again later bufferShrinkTimer.refresh(); // Utils.log(`DEBUG: Unable to shrink buffer (reason: buffer not empty)`); } }, delayInMs); } else { // The timer is already running, so restart it bufferShrinkTimer.refresh(); } } /** * [Local function] Reads the log pages (and checkpoint data) received from the IC. Checkpoint data can be large, and is * sent without a header, so we read it in a different "mode" to the way we read regular log pages. Note the the data (chunk) * received from the IC will be no larger than 65536 bytes, but it can still potentially contain hundreds of log pages. */ function processIncomingICData(data: Buffer): void { // If we're in the process of receiving checkpoint data, we follow a different path than the "normal" sequence-of-log-pages path if (receivingCheckpoint) { if (checkpointBytesRemaining > data.length) { // The data is all checkpoint data checkpointStream.write(data); // If this returns false, it will just buffer checkpointBytesRemaining -= data.length; return; // Wait for more data (via the _lbReceiveSocket "data" event) } else { // The data includes the tail of the checkpoint (and possibly part, or all, of the next log page) const checkpointTailChunk: Uint8Array = new Uint8Array(checkpointBytesRemaining); data.copy(checkpointTailChunk, 0, 0, checkpointBytesRemaining); if (checkpointBytesRemaining < data.length) { // data contains part (or all) of the next log page, so we pass that along to onCheckpointEnd() to handle when it's finished const remainingBufferLength: number = data.length - checkpointBytesRemaining; const remainingBuffer: Buffer = Buffer.alloc(remainingBufferLength); data.copy(remainingBuffer, 0, checkpointBytesRemaining, data.length); onCheckpointEnd(checkpointTailChunk, remainingBuffer); } else { // data only contains checkpoint data (checkpointBytesRemaining == data.length), so that's all we need to process onCheckpointEnd(checkpointTailChunk); } return; // Wait for the next log page (via the _lbReceiveSocket "data" event) } } // TESTING (2 log pages, the first with 2 messages, the second with one message) // let logRec1: Buffer = Buffer.from([0x96, 0x61, 0xd1, 0xdc, 0x1c, 0x00, 0x00, 0x00, 0x02, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x0b, 0x02, 0x09]); // let logRec2: Buffer = Buffer.from([0x96, 0x61, 0xd1, 0xdc, 0x1a, 0x00, 0x00, 0x00, 0x02, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x0b]); // data = Buffer.alloc(logRec1.length + logRec2.length, Buffer.concat([logRec1, logRec2])); // Note: There is no way to know [from the message header] the instance name of the IC that sent the data if (Utils.canLog(Utils.LoggingLevel.Verbose)) { let showBytes: boolean = _config.lbOptions.debugOutputLogging; // For debugging Utils.log(`Received data from IC (${data.length} bytes)` + (showBytes ? `: ${Utils.makeDisplayBytes(data)}` : "")); } pageReceiveBuffer.set(data, bufferOffset); // Note: set() will throw a "RangeError: offset is out of bounds" if the operation causes buffer overflow bufferOffset += data.length; let logPageLength: number = Messages.readLogPageLength(pageReceiveBuffer, bufferOffset); // Limited check for pageReceiveBuffer corruption (eg. an "interior" log page data chunk being written [erroneously] to the start of pageReceiveBuffer). // Also, the IC is using negative log page lengths (in a persisted page) to indicate that the xxHash64 checksum was used. The IC should always be // sendind the LB an abs(logPageLength), but we check that to be safe. if (logPageLength < -1) { const headerBytes: string = Utils.makeDisplayBytes(pageReceiveBuffer, 0, 24); throw new Error(`The log page header has an invalid logPageLength (${logPageLength}); header bytes: [${headerBytes}], bufferOffset: ${bufferOffset}, last log page ID: ${Messages.lastLogPageSequenceID()}, last complete log page ID: ${Messages.lastCompleteLogPageSequenceID()}`); } // If needed, auto-grow pageReceiveBuffer if (logPageLength > pageReceiveBuffer.length) { // Note: Because Node reads TCP data in chunks (of up to 64 KB) which are not aligned with log page boundaries (ie. the IC's data // chunks can include part (or all) of the next log page), we allocate space (64 KB) for an additional "full" chunk. // For example, if logPageLength is 65537 bytes, it could arrive in 2 chunks each of 65536 bytes (with 65535 bytes in the // second chunk belonging to the next log page). If we didn't add space for that "additional" chunk, we wouldn't have space // to receive all the chunks for the first log page (or to receive the start of the next log page). // Aside: "The current unit of data transfer in Node is 64 KB and is hard-coded" (source: https://github.com/libuv/libuv/issues/1217). // For example: https://github.com/nodejs/node/blob/926152a38c8fbe6c0b016ea36edb0b219c0fc7fd/deps/uv/src/win/tcp.c#L1060 const newPageReceiveBuffer = Buffer.alloc(logPageLength + (64 * 1024)); pageReceiveBuffer.copy(newPageReceiveBuffer, 0, 0, bufferOffset); pageReceiveBuffer = newPageReceiveBuffer; Utils.log(`Log page buffer increased to ${pageReceiveBuffer.length} bytes (${(pageReceiveBuffer.length / (1024 * 1024)).toFixed(2)} MB)`, null, Utils.LoggingLevel.Minimal); scheduleBufferAutoShrink(); // Because the large log page [that caused auto-grow] may be atypical, we schedule an auto-shrink [to avoid hogging memory indefinitely] } // First, process any previous log page(s) we had to interrupt because it was generating too much outgoing data (so we had to halt processing of the page to let I/O with the IC interleave) let unprocessedPageCount: number = Messages.processInterruptedLogPages(_config); // Process all the complete log pages (if any) in pageReceiveBuffer while ((logPageLength = Messages.getCompleteLogPageLength(pageReceiveBuffer, bufferOffset)) !== -1) { // Dispatch all messages in the log page checkpointBytesTotal = Messages.processLogPage(pageReceiveBuffer, _config); if (checkpointBytesTotal >= 0) // An empty checkpoint is still a valid checkpoint { // We just read a 'Checkpoint' message (which will be the only message in the log page) // so we need to switch "modes" (receivingCheckpoint = true) to read the checkpoint data receivingCheckpoint = true; checkpointBytesRemaining = checkpointBytesTotal; incomingCheckpoint = _config.checkpointConsumer(); checkpointStream = incomingCheckpoint.dataStream; checkpointRestoreStartTime = Date.now(); // @ts-tactical-any-cast: Suppress error "Type 'null' is not assignable to type 'AmbrosiaAppState'. ts(2322)" [because we use 'strictNullChecks'] _appState = null as any; // The app MUST call initializeAmbrosiaState() after restoring the checkpoint, and we want things to break if it doesn't // Rather than, say, encoding the size as the first 8 bytes of the stream, we use an AppEvent // (in the C# LB this is handled automatically by [DataContract], so we can't do the same) emitAppEvent(Messages.AppEventType.IncomingCheckpointStreamSize, checkpointBytesTotal); } if (logPageLength < bufferOffset) { // We have part of the next log page(s) in pageReceiveBuffer, so truncate to just that portion // [the truncated part is the log page that has already been handled by processLogPage()] pageReceiveBuffer.copyWithin(0, logPageLength, bufferOffset); bufferOffset -= logPageLength; if (receivingCheckpoint) { // Rather than part of the next log page, we have part (or all) of the checkpoint data (and maybe some of the next log page after that) if (checkpointBytesTotal <= bufferOffset) { // We have already read ALL of the checkpoint data let checkpointChunk: Uint8Array = new Uint8Array(checkpointBytesTotal); pageReceiveBuffer.copy(checkpointChunk, 0, 0, checkpointBytesTotal); if (checkpointBytesTotal < bufferOffset) { pageReceiveBuffer.copyWithin(0, checkpointBytesTotal, bufferOffset); bufferOffset -= checkpointBytesTotal; // pageReceiveBuffer will now contain part (or all) of the next log page } else { // checkpointBytesTotal == bufferOffset, so pageReceiveBuffer only contains checkpoint data bufferOffset = 0; // Empty the buffer } const remainingBuffer: Buffer = Buffer.alloc(bufferOffset); pageReceiveBuffer.copy(remainingBuffer, 0, 0, bufferOffset); bufferOffset = 0; // Empty the buffer [this is safe, since remainingBuffer now contains anything that was left in the buffer] onCheckpointEnd(checkpointChunk, remainingBuffer); break; // Exit from the normal log page 'while' loop [any remaining data in pageReceiveBuffer will be processed by onCheckpointEnd() when it's finished] } else { // We have only read PART of the checkpoint data: it will take additional reads to receive it all checkpointStream.write(pageReceiveBuffer.slice(0, bufferOffset)); // If this returns false, it will just buffer checkpointBytesRemaining -= bufferOffset; bufferOffset = 0; // Empty the buffer break; // Exit from the normal log page 'while' loop [received checkpoint data will continue to be processed via the 'receivingCheckpoint = true' path] } } } else { // We have a single, complete log page bufferOffset = 0; // Empty the buffer [this will terminate the log page 'while' loop] } } // If we've fallen behind on processing log pages, then pause the incoming message stream [the incoming data will still be buffered - just by Node, not us]. // Doing this gives the outgoing message stream an opportunity to empty (especially during recovery, when we are rapidly inundated with log pages from the IC). unprocessedPageCount = Messages.interruptedLogPageBacklogCount(); if (unprocessedPageCount > 0) { if (_lbReceiveSocket && !_lbReceiveSocket.isPaused()) { // Note: According to https://www.derpturkey.com/node-js-socket-backpressure-in-paused-mode-2/, when a socket is paused // it should exert backpressure on the the sender (the IC) [via TCP flow control] to slow the sender down, so the // IC should NOT cause the _lbReceiveSocket stream to buffer indefinitely (potentially leading to an OOM condition). _lbReceiveSocket.pause(); Utils.traceLog(Utils.TraceFlag.LogPageInterruption, `Incoming message stream paused (${unprocessedPageCount} log pages are backlogged)`); setImmediate(() => resumeReadingFromIC()); // TODO: Rather than polling, it's probably more efficient to use: _outgoingMessageStream.once("drain", resumeReadingFromIC); } } /** [Local function] Checks if the outgoing message stream is now empty, and if it is, resumes the incoming message stream. Otherwise, re-schedules the check. */ function resumeReadingFromIC(): void { if (_lbReceiveSocket && _lbReceiveSocket.isPaused()) { const isOutgoingMessageStreamEmpty: boolean = !isOutgoingMessageStreamGettingFull(0); if (isOutgoingMessageStreamEmpty) { _lbReceiveSocket.resume(); Utils.traceLog(Utils.TraceFlag.LogPageInterruption, `Incoming message stream resumed (outgoing message stream is now empty)`); } else { // Allow more time for the outgoing stream to empty, then check again setImmediate(() => resumeReadingFromIC()); } } } } } /** Raises the specified event, which can be handled in the app's MessageDispatcher(). */ export function emitAppEvent(eventType: Messages.AppEventType, ...args: any[]) { if (eventType === Messages.AppEventType.BecomingPrimary) { // The 'isFirstStartAfterInitialRegistration' condition only applies during the startup phase of the newly registered instance Configuration.loadedConfig().isFirstStartAfterInitialRegistration = false; } _config.dispatcher(new Messages.AppEvent(eventType, ...args)); } /** Returns the number of post methods that are currently in-flight (ie. sent but no response yet received). */ export function inFlightPostMethodsCount(): number { const inFlightPostMethodsCount: number = _appState.__ambrosiaInternalState.inFlightCallIDs().length; return (inFlightPostMethodsCount); } /** Logs the count of currently in-flight (ie. sent but no response yet received) post methods, if there are any. */ function logInFlightPostMethodsCount(): void { const methodCount: number = inFlightPostMethodsCount(); if (methodCount > 0) { Utils.log(`There are ${methodCount} in-flight post methods`, null, Utils.LoggingLevel.Minimal); } }
the_stack
import * as path from 'path'; import * as FS from '../../tools/fs'; import * as semver from 'semver'; import Logger from '../../tools/env.logger'; import ServicePaths from '../../services/service.paths'; import ServiceRenderState from '../../services/service.render.state'; import ServiceElectron from '../../services/service.electron'; import ServiceElectronService from '../../services/service.electron.state'; import ServiceEnv from '../../services/service.env'; import ServiceSettings from '../../services/service.settings'; import ServiceStorage, { IStorageScheme } from '../../services/service.storage'; import InstalledPlugin from './plugin.installed'; import ControllerPluginStore from './plugins.store'; import ControllerPluginsStorage from './plugins.storage'; import ControllerPluginsIncompatiblesStorage from './plugins.incompatibles'; import { IPCMessages, Subscription } from '../../services/service.electron'; import { CommonInterfaces } from '../../interfaces/interface.common'; import { ErrorCompatibility } from './plugin.installed'; import { PromisesQueue } from '../../tools/promise.queue'; import { dialog, OpenDialogReturnValue } from 'electron'; import { CSettingsAliases, CSettingsEtries, registerPluginsManagerSettings } from './settings/settings.index'; interface IQueueTask { name: string; version: string; } /** * @class ControllerPluginsManager * @description Delivery default plugins into chipmunk folder */ export default class ControllerPluginsManager { private _logger: Logger = new Logger('ControllerPluginsManager'); private _queue: { install: Map<string, IQueueTask>, uninstall: Map<string, string>, upgrade: Map<string, IQueueTask>, update: Map<string, IQueueTask>, compatibility: Map<string, IQueueTask>, } = { install: new Map(), uninstall: new Map(), upgrade: new Map(), update: new Map(), compatibility: new Map(), }; private _store: ControllerPluginStore; private _storage: ControllerPluginsStorage; private _incompatibles: ControllerPluginsIncompatiblesStorage; private _downloads: PromisesQueue = new PromisesQueue('Downloads plugins queue'); private _subscriptions: { [key: string ]: Subscription } = { }; private _settings: { [CSettingsAliases.PluginsUpdates]: boolean, [CSettingsAliases.PluginsUpgrades]: boolean, [CSettingsAliases.RemoveNotValid]: boolean, [CSettingsAliases.DefaultsPlugins]: boolean, } = { [CSettingsAliases.PluginsUpdates]: true, [CSettingsAliases.PluginsUpgrades]: true, [CSettingsAliases.RemoveNotValid]: true, [CSettingsAliases.DefaultsPlugins]: true, }; constructor(store: ControllerPluginStore, storage: ControllerPluginsStorage) { this._store = store; this._storage = storage; this._incompatibles = new ControllerPluginsIncompatiblesStorage(); } public init(): Promise<void> { return new Promise((resolve, reject) => { Promise.all([ ServiceElectron.IPC.subscribe(IPCMessages.PluginsInstalledRequest, this._ipc_PluginsInstalledRequest.bind(this)).then((subscription: Subscription) => { this._subscriptions.PluginsInstalledRequest = subscription; }), ServiceElectron.IPC.subscribe(IPCMessages.PluginsIncompatiblesRequest, this._ipc_PluginsIncompatiblesRequest.bind(this)).then((subscription: Subscription) => { this._subscriptions.PluginsIncompatiblesRequest = subscription; }), ServiceElectron.IPC.subscribe(IPCMessages.PluginsStoreAvailableRequest, this._ipc_PluginsStoreAvailableRequest.bind(this)).then((subscription: Subscription) => { this._subscriptions.PluginsStoreAvailableRequest = subscription; }), ServiceElectron.IPC.subscribe(IPCMessages.PluginsInstallRequest, this._ipc_PluginsInstallRequest.bind(this)).then((subscription: Subscription) => { this._subscriptions.PluginsInstallRequest = subscription; }), ServiceElectron.IPC.subscribe(IPCMessages.PluginsUpdateRequest, this._ipc_PluginsUpdateRequest.bind(this)).then((subscription: Subscription) => { this._subscriptions.PluginsUpdateRequest = subscription; }), ServiceElectron.IPC.subscribe(IPCMessages.PluginsUpgradeRequest, this._ipc_PluginsUpgradeRequest.bind(this)).then((subscription: Subscription) => { this._subscriptions.PluginsUpgradeRequest = subscription; }), ServiceElectron.IPC.subscribe(IPCMessages.PluginsUninstallRequest, this._ipc_PluginsUninstallRequest.bind(this)).then((subscription: Subscription) => { this._subscriptions.PluginsUninstallRequest = subscription; }), ServiceElectron.IPC.subscribe(IPCMessages.PluginAddRequest, this._ipc_PluginAddRequest.bind(this)).then((subscription: Subscription) => { this._subscriptions.PluginAddRequest = subscription; }), ]).then(() => { this._logger.debug(`All subscriptions are done`); }).catch((error: Error) => { this._logger.debug(`Fail to subscribe due error: ${error.message}`); }).finally(() => { registerPluginsManagerSettings().catch((settingErr: Error) => { this._logger.debug(`Fail to register settings due error: ${settingErr.message}`); }).finally(() => { this._loadSettings(); resolve(); }); }); }); } public destroy(): Promise<void> { return new Promise((resolve) => { Object.keys(this._subscriptions).forEach((key: string) => { (this._subscriptions as any)[key].destroy(); }); resolve(); }); } public load(): Promise<void> { return new Promise((resolve, reject) => { ServiceElectronService.logStateToRender(`Reading installed plugins...`); const pluginStorageFolder: string = ServicePaths.getPlugins(); // Get all sub folders from plugins folder. Expecting: there are plugins folders FS.readFolders(pluginStorageFolder).then((folders: string[]) => { if (folders.length === 0) { // No any plugins this._logger.debug(`No any plugins were found. Target folder: ${pluginStorageFolder}`); return resolve(); } const toBeRemoved: InstalledPlugin[] = []; // Check each plugin folder and read package.json of render and process apps Promise.all(folders.map((folder: string) => { const plugin: InstalledPlugin = new InstalledPlugin(folder, path.resolve(pluginStorageFolder, folder), this._store); return plugin.read().then(() => { this._storage.include(plugin); }).catch((pluginErr: Error | ErrorCompatibility) => { if (pluginErr instanceof ErrorCompatibility) { this._logger.warn(`Plugin "${plugin.getName()}" could not be used because compability: ${pluginErr.message}`); const version: string | undefined = this._store.getLatestVersion(plugin.getName())?.version; this._queue.compatibility.set(plugin.getName(), { name: plugin.getName(), version: version === undefined ? 'latest' : version, }); this._incompatibles.add(plugin); } else { this._logger.warn(`Fail to read plugin data in "${folder}". Plugin will be ignored. Error: ${pluginErr.message}`); toBeRemoved.push(plugin); } }); })).catch((readErr: Error) => { this._logger.warn(`Error during reading plugins: ${readErr.message}`); }).finally(() => { ServiceElectronService.logStateToRender(`Removing invalid plugins...`); if (!this._settings.RemoveNotValid) { if (toBeRemoved.length > 0) { this._logger.debug(`Found ${toBeRemoved.length} not valid plugins to be removed. But because this._settings.RemoveNotValid=false, plugins will not be removed. Not valid plugins:\n${toBeRemoved.map((plugin: InstalledPlugin) => { return `\t - ${plugin.getPath()}`; }).join('\n')}`); } return resolve(); } else { Promise.all(toBeRemoved.map((plugin: InstalledPlugin) => { return plugin.remove().then(() => { ServiceElectronService.logStateToRender(`Plugin "${plugin.getPath()}" has been removed.`); this._logger.debug(`Plugin "${plugin.getPath()}" is removed.`); }).catch((removeErr: Error) => { this._logger.warn(`Fail remove plugin "${plugin.getPath()}" due error: ${removeErr.message}`); return Promise.resolve(); }); })).catch((removeErr: Error) => { this._logger.warn(`Error during removing plugins: ${removeErr.message}`); }).finally(() => { resolve(); }); } }); }).catch((error: Error) => { this._logger.error(`Fail to read plugins folder (${pluginStorageFolder}) due error: ${error.message}.`); resolve(); }); }); } public add(name: string, version: string): Promise<void> { return new Promise((resolve, reject) => { if (this._downloads.has(name)) { return reject(new Error(this._logger.warn(`Plugin "${name}" is already in queue`))); } this._downloads.add(this._store.delivery(name, version), name).then(() => { this._queue.install.set(name, { name: name, version: version }); resolve(); }).catch((deliveryErr: Error) => { reject(deliveryErr); }); }); } public update(name: string, version: string): Promise<void> { return new Promise((resolve, reject) => { if (this._downloads.has(name)) { return reject(new Error(this._logger.warn(`Plugin "${name}" is already in queue`))); } this._downloads.add(this._store.delivery(name, version), name).then(() => { this._queue.update.set(name, { name: name, version: version }); resolve(); }).catch((deliveryErr: Error) => { reject(deliveryErr); }); }); } public upgrade(name: string, version: string): Promise<void> { return new Promise((resolve, reject) => { if (this._downloads.has(name)) { return reject(new Error(this._logger.warn(`Plugin "${name}" is already in queue`))); } this._downloads.add(this._store.delivery(name, version), name).then(() => { this._queue.upgrade.set(name, { name: name, version: version }); resolve(); }).catch((deliveryErr: Error) => { reject(deliveryErr); }); }); } public remove(name: string): Promise<void> { return new Promise((resolve, reject) => { this._queue.uninstall.set(name, name); resolve(); }); } public install(plugins: IQueueTask[]): Promise<void> { return new Promise((resolve, reject) => { Promise.all(plugins.map((task: IQueueTask) => { const plugin: InstalledPlugin = new InstalledPlugin(task.name, path.resolve(ServicePaths.getPlugins(), task.name), this._store); return plugin.install(task.version).then(() => { this._logger.env(`Plugin "${task.name}" is installed. Will include plugin into storage.`); this._storage.include(plugin); }).catch((installErr: Error) => { this._logger.warn(`Fail to install plugin "${task.name}" due error: ${installErr.message}`); }); })).catch((error: Error) => { reject(error); }).finally(() => { resolve(); }); }); } public uninstall(plugins: InstalledPlugin[]): Promise<void> { return new Promise((resolve, reject) => { Promise.all(plugins.map((plugin: InstalledPlugin) => { return plugin.remove().catch((removeErr: Error) => { this._logger.warn(`Fail to remove plugin "${plugin.getName()}" due error: ${removeErr.message}. In any way will try to exclude plugin.`); }).finally(() => { return this._storage.exclude(plugin.getName()).catch((exclErr: Error) => { this._logger.warn(`Fail exclude plugin "${plugin.getName()}" due error: ${exclErr.message}`); }); }); })).then(() => { resolve(); }).catch((error: Error) => { reject(error); }); }); } public defaults(): Promise<void> { return new Promise((resolve) => { if (!this._settings.DefaultsPlugins) { this._logger.debug(`Checking defaults plugins is skipped because envvar _settings.DefaultsPlugins is false`); return resolve(); } const installed: string[] = this.getInstalled().map((plugin: CommonInterfaces.Plugins.IPlugin) => { return plugin.name; }).filter(n => n !== undefined); const required: IQueueTask[] = this._store.getDefaults(installed).map((name: string) => { const version: string | undefined = this._store.getLatestVersion(name)?.version; if (version === undefined) { return { name: '', version: '' }; } else { return { name: name, version: version }; } }).filter(r => r.name !== ''); if (required.length === 0) { return resolve(); } this._logger.debug(`Installing default plugins`); this.install(this._filterDefault(required)).catch((error: Error) => { this._logger.warn(`Error during installation of plugins: ${error.message}`); }).finally(() => { resolve(); }); }); } public getInstalled(): CommonInterfaces.Plugins.IPlugin[] { const installed: InstalledPlugin[] = this._storage.getInstalled(); return installed.map((plugin: InstalledPlugin) => { return plugin.getInfo(); }).filter((info: CommonInterfaces.Plugins.IPlugin | undefined) => { return info !== undefined; }) as CommonInterfaces.Plugins.IPlugin[]; } public getIncompatibles(): CommonInterfaces.Plugins.IPlugin[] { const incompatibles: InstalledPlugin[] = this._incompatibles.get(); return incompatibles.map((plugin: InstalledPlugin) => { return plugin.getInfo(); }).filter((info: CommonInterfaces.Plugins.IPlugin | undefined) => { return info !== undefined; }) as CommonInterfaces.Plugins.IPlugin[]; } public revision() { this._store.remote().then(() => { this._logger.env(`Plugin's state is updated from remote store`); }).catch((error: Error) => { this._logger.env(`Fail to update plugin's state from remote store due error: ${error.message}`); }).finally(() => { ServiceRenderState.doOnReady('ControllerPluginsManager: PluginsDataReady', () => { ServiceElectron.IPC.send(new IPCMessages.PluginsDataReady()).then(() => { this._logger.env(`Notification about plugins data state was sent to render`); }).catch((notifyErr: Error) => { this._logger.warn(`Fail to notify render about plugins data state due error: ${notifyErr.message}`); }).finally(() => { // Check plugins to be upgraded this._queue.compatibility.forEach((task: IQueueTask) => { ServiceElectron.IPC.send(new IPCMessages.PluginsNotificationUpgrade({ name: task.name, versions: this._store.getSuitableVersions(task.name), })); }); // Check plugins to be update this._storage.getInstalled().forEach((plugin: InstalledPlugin) => { const updates: CommonInterfaces.Plugins.IHistory[] | Error = plugin.getSuitableUpdates(); if (updates instanceof Error) { this._logger.warn(`Fail to get suitable update for plugin "${plugin.getName()}" due error: ${updates.message}`); return; } if (updates.length === 0) { return; } this._logger.debug(`Plugin "${plugin.getName()}" has available updates:\n${updates.map(u => `\t- ${u.version}`).join('\n')}`); ServiceElectron.IPC.send(new IPCMessages.PluginsNotificationUpdate({ name: plugin.getName(), versions: updates, })); }); }); }); }); } public accomplish(): Promise<void> { return new Promise((resolve, reject) => { // Shutdown all plugins this._storage.shutdown().then(() => { this._logger.debug(`All plugins are down`); }).catch((shutdownErr: Error) => { this._logger.warn(`Fail to shutdown all plugins before close due error: ${shutdownErr.message}`); }).finally(() => { this._downloads.do(() => { // Upgrade tasks const upgrade: Promise<any> = Promise.all(!this._settings.PluginsUpgrades ? [] : Array.from(this._queue.upgrade.values()).map((task: IQueueTask) => { return this.install([task]).catch((upgErr: Error) => { this._logger.warn(`Fail to upgrade plugin "${task.name}" due error: ${upgErr.message}`); }); })).then(() => { this._logger.warn(`Upgrade - done`); }).catch((error: Error) => { this._logger.warn(`Fail to do upgrade of plugins due error: ${error.message}`); }); // Update tasks const update: Promise<any> = Promise.all(!this._settings.PluginsUpdates ? [] : Array.from(this._queue.update.values()).map((task: IQueueTask) => { const plugin: InstalledPlugin | undefined = this._storage.getPluginByName(task.name); if (plugin === undefined) { this._logger.warn(`Fail to find installed plugin "${task.name}" to update it`); return Promise.resolve(); } return plugin.update(task.version).catch((updErr: Error) => { this._logger.warn(`Fail to update plugin "${task.name}" to version ${task.version} due error: ${updErr.message}`); }); })).then(() => { this._logger.warn(`Update - done`); }).catch((error: Error) => { this._logger.warn(`Fail to do update of plugins due error: ${error.message}`); }); // Installation const install: Promise<any> = Promise.all(Array.from(this._queue.install.values()).map((task: IQueueTask) => { return this.install([task]).catch((instErr: Error) => { this._logger.warn(`Fail to install plugin "${name}" due error: ${instErr.message}`); }); })).then(() => { this._logger.warn(`Install - done`); }).catch((error: Error) => { this._logger.warn(`Fail to do install of plugins due error: ${error.message}`); }); // Deinstall const uninstall: Promise<any> = Promise.all(Array.from(this._queue.uninstall.values()).map((name: string) => { const installed: InstalledPlugin | undefined = this._storage.getPluginByName(name); const incompatible: InstalledPlugin | undefined = this._incompatibles.getPluginByName(name); const plugin: InstalledPlugin | undefined = installed !== undefined ? installed : incompatible; if (plugin === undefined) { this._logger.warn(`Fail to find a plugin "${name}" to uninstall it`); return Promise.resolve(); } return plugin.remove().then(() => { this._logger.debug(`Plugin "${name}" is removed.`); }).catch((rmErr: Error) => { this._logger.warn(`Fail to remove plugin "${name}" due error: ${rmErr.message}`); }); })).then(() => { this._logger.warn(`Deinstall - done`); }).catch((error: Error) => { this._logger.warn(`Fail to do uninstall of plugins due error: ${error.message}`); }); Promise.all([ upgrade, update, uninstall, install, ]).then(() => { resolve(); }).catch((error: Error) => { reject(new Error(this._logger.warn(`Fail to update plugins due error: ${error.message}`))); }); }); }); }); } private _uninstalledDefaultPlugin(plugin: string) { if (!this._store.isDefault(plugin)) { return; } const stored: IStorageScheme.IStorage = ServiceStorage.get().get(); const plugins: string[] = stored.pluginDefaultUninstalled; if (plugins.includes(plugin)) { return; } plugins.unshift(plugin); ServiceStorage.get().set({ pluginDefaultUninstalled: plugins, }).catch((err: Error) => { this._logger.error(err.message); }); } private _reinstalledDefaultPlugin(plugin: string) { if (!this._store.isDefault(plugin)) { return; } const stored: IStorageScheme.IStorage = ServiceStorage.get().get(); const plugins: string[] = stored.pluginDefaultUninstalled; const index: number = plugins.indexOf(plugin); if (index === -1) { return; } plugins.splice(index, 1); ServiceStorage.get().set({ pluginDefaultUninstalled: plugins, }).catch((err: Error) => { this._logger.error(err.message); }); } private _ipc_PluginsInstalledRequest(message: IPCMessages.PluginsInstalledRequest, response: (instance: any) => any) { response(new IPCMessages.PluginsInstalledResponse({ plugins: this.getInstalled().map((plugin: CommonInterfaces.Plugins.IPlugin) => { plugin.suitable = this._store.getSuitableVersions(plugin.name).map(r => r.version); return plugin; }), })).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsInstalledRequest due error: ${error.message}`); }); } private _ipc_PluginsIncompatiblesRequest(message: IPCMessages.PluginsIncompatiblesRequest, response: (instance: any) => any) { response(new IPCMessages.PluginsIncompatiblesResponse({ plugins: this.getIncompatibles().map((plugin: CommonInterfaces.Plugins.IPlugin) => { plugin.suitable = []; return plugin; }), })).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsIncompatiblesRequest due error: ${error.message}`); }); } private _ipc_PluginsStoreAvailableRequest(message: IPCMessages.PluginsStoreAvailableRequest, response: (instance: any) => any) { response(new IPCMessages.PluginsStoreAvailableResponse({ plugins: this._store.getAvailable().map((plugin: CommonInterfaces.Plugins.IPlugin) => { plugin.suitable = this._store.getSuitableVersions(plugin.name).map(r => r.version); return plugin; }), })).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsStoreAvailableResponse due error: ${error.message}`); }); } private _ipc_PluginsInstallRequest(message: IPCMessages.TMessage, response: (instance: any) => any) { const msg: IPCMessages.PluginsInstallRequest = message as IPCMessages.PluginsInstallRequest; let version: string | undefined = msg.version; if (typeof version !== 'string' || version === 'latest' || !semver.valid(version)) { version = this._store.getLatestVersion(msg.name)?.version; if (version === undefined) { return response(new IPCMessages.PluginsInstallResponse({ error: this._logger.warn(`Fail to find suitable version`), })).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsInstallResponse due error: ${error.message}`); }); } } this._reinstalledDefaultPlugin(msg.name); this.add(msg.name, version).then(() => { response(new IPCMessages.PluginsInstallResponse({})).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsInstallResponse due error: ${error.message}`); }); }).catch((addErr: Error) => { this._logger.warn(`Fail to delivery requested plugin "${msg.name}" due error: ${addErr.message}`); response(new IPCMessages.PluginsInstallResponse({ error: addErr.message, })).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsInstallResponse due error: ${error.message}`); }); }); } private _ipc_PluginsUpdateRequest(message: IPCMessages.TMessage, response: (instance: any) => any) { const msg: IPCMessages.PluginsInstallRequest = message as IPCMessages.PluginsUpdateRequest; let version: string | undefined = msg.version; if (typeof version !== 'string' || version === 'latest' || !semver.valid(version)) { version = this._store.getLatestVersion(msg.name)?.version; if (version === undefined) { return response(new IPCMessages.PluginsUpdateResponse({ error: this._logger.warn(`Fail to find suitable version`), })).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsUpdateResponse due error: ${error.message}`); }); } } this.update(msg.name, version).then(() => { response(new IPCMessages.PluginsUpdateResponse({})).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsUpdateResponse due error: ${error.message}`); }); }).catch((addErr: Error) => { this._logger.warn(`Fail to delivery requested plugin "${msg.name}" due error: ${addErr.message}`); response(new IPCMessages.PluginsUpdateResponse({ error: addErr.message, })).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsUpdateResponse due error: ${error.message}`); }); }); } private _ipc_PluginsUpgradeRequest(message: IPCMessages.TMessage, response: (instance: any) => any) { const msg: IPCMessages.PluginsInstallRequest = message as IPCMessages.PluginsUpgradeRequest; let version: string | undefined = msg.version; if (typeof version !== 'string' || version === 'latest' || !semver.valid(version)) { version = this._store.getLatestVersion(msg.name)?.version; if (version === undefined) { return response(new IPCMessages.PluginsUpgradeResponse({ error: this._logger.warn(`Fail to find suitable version`), })).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsUpgradeResponse due error: ${error.message}`); }); } } this.upgrade(msg.name, version).then(() => { response(new IPCMessages.PluginsUpgradeResponse({})).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsUpgradeResponse due error: ${error.message}`); }); }).catch((addErr: Error) => { this._logger.warn(`Fail to delivery requested plugin "${msg.name}" due error: ${addErr.message}`); response(new IPCMessages.PluginsUpgradeResponse({ error: addErr.message, })).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsUpgradeResponse due error: ${error.message}`); }); }); } private _ipc_PluginsUninstallRequest(message: IPCMessages.TMessage, response: (instance: any) => any) { const msg: IPCMessages.PluginsUninstallRequest = message as IPCMessages.PluginsUninstallRequest; this.remove(msg.name).then(() => { this._uninstalledDefaultPlugin(msg.name); response(new IPCMessages.PluginsUninstallResponse({})).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsUninstallResponse due error: ${error.message}`); }); }).catch((removeErr: Error) => { this._logger.warn(`Fail to prepare for remove plugin "${msg.name}" due error: ${removeErr.message}`); response(new IPCMessages.PluginsUninstallResponse({ error: removeErr.message, })).catch((error: Error) => { this._logger.warn(`Fail to send response on PluginsUninstallResponse due error: ${error.message}`); }); }); } private _ipc_PluginAddRequest(message: IPCMessages.TMessage, response: (instance: any) => any) { const msg: IPCMessages.PluginAddRequest = message as IPCMessages.PluginAddRequest; const win = ServiceElectron.getBrowserWindow(); if (win === undefined) { return response(new IPCMessages.PluginAddResponse({ error: `Fail to find active browser window`, })); } dialog.showOpenDialog(win, { properties: ['openFile', 'showHiddenFiles'], filters: [ { name: 'Plugins', extensions: ['tgz'], }, ], }).then((returnValue: OpenDialogReturnValue) => { if (!(returnValue.filePaths instanceof Array) || returnValue.filePaths.length !== 1) { return response(new IPCMessages.PluginAddResponse({})); } const filename: string = returnValue.filePaths[0]; const plugin: InstalledPlugin = new InstalledPlugin(filename, filename, this._store); plugin.import(filename).then(() => { plugin.read().then(() => { plugin.delivery().then(() => { response(new IPCMessages.PluginAddResponse({ name: plugin.getName(), })); }).catch((deliveryErr: Error) => { response(new IPCMessages.PluginAddResponse({ error: this._logger.error(`Fail to delivery plugin due error: ${deliveryErr.message}`), })); }); }).catch((pluginErr: Error | ErrorCompatibility) => { if (pluginErr instanceof ErrorCompatibility) { this._logger.warn(`Plugin "${plugin.getName()}" could not be used because compability: ${pluginErr.message}`); response(new IPCMessages.PluginAddResponse({ error: this._logger.error(`Compability error: ${pluginErr.message}`), })); } else { response(new IPCMessages.PluginAddResponse({ error: this._logger.warn(`Fail to read plugin data in "${plugin.getPath()}". Error: ${pluginErr.message}`), })); } }); }).catch((impErr: Error) => { response(new IPCMessages.PluginAddResponse({ error: this._logger.error(`Error while importing plugin: ${impErr.message}`), })); }); }).catch((error: Error) => { response(new IPCMessages.PluginAddResponse({ error: this._logger.error(`Fail open file due error: ${error.message}`), })); }); } private _filterDefault(tasks: IQueueTask[]): IQueueTask[] { const plugins: string[] = ServiceStorage.get().get().pluginDefaultUninstalled; return tasks.filter((task: IQueueTask) => { return !plugins.includes(task.name); }); } private _loadSettings() { [ CSettingsAliases.PluginsUpdates, CSettingsAliases.PluginsUpgrades, CSettingsAliases.RemoveNotValid, CSettingsAliases.DefaultsPlugins].forEach((alias: CSettingsAliases) => { const setting: boolean | Error = ServiceSettings.get<boolean>(CSettingsEtries[alias].getFullPath()); if (setting instanceof Error) { this._logger.warn(`Fail to load settings "${CSettingsEtries[alias].getFullPath()}" due error: ${setting.message}`); } else { this._settings[alias] = setting; } }); if (ServiceEnv.get().CHIPMUNK_PLUGINS_NO_UPDATES) { this._settings.PluginsUpdates = false; } if (ServiceEnv.get().CHIPMUNK_PLUGINS_NO_UPGRADE) { this._settings.PluginsUpgrades = false; } if (ServiceEnv.get().CHIPMUNK_PLUGINS_NO_REMOVE_NOTVALID) { this._settings.RemoveNotValid = false; } if (ServiceEnv.get().CHIPMUNK_PLUGINS_NO_DEFAULTS) { this._settings.DefaultsPlugins = false; } } } /* function error() { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('1')) }, 2000); }); } function ok() { return new Promise((resolve, reject) => { setTimeout(() => { resolve() }, 2000); }); } function delay() { return new Promise((resolve, reject) => { setTimeout(() => { resolve() }, 4000); }); } Promise.all([ error().catch((err) => { console.log(`ERROR`); }).finally(() => { return delay(); }), ok() ]).then(() => { console.log('all done'); }).catch((e) => { console.log('OPPPS'); }); */ /* function error() { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('1')) }, 2000); }); } function test() { return error().catch(() => { console.log('CATCH ERR'); }); } test().then(() => { console.log('OK'); }) */ /* function error() { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('1')) }, 2000); }); } const smth = error().catch(() => { console.log('ERROR'); }).finally(() => { console.log('FIN'); }); smth.then(() => { console.log('HERE'); }) */
the_stack
import test from "ava" import {ReadableStream} from "web-streams-polyfill" import {Blob} from "./Blob" test("Constructor creates a new Blob when called without arguments", t => { const blob = new Blob() t.true(blob instanceof Blob) }) test("Empty Blob returned by Blob constructor has the size of 0", t => { const blob = new Blob() t.is(blob.size, 0) }) test("The size property is read-only", t => { const blob = new Blob() // @ts-expect-error try { blob.size = 42 } catch { /* noop */ } t.is(blob.size, 0) }) test("The size property cannot be removed", t => { const blob = new Blob() // @ts-expect-error try { delete blob.size } catch { /* noop */ } t.true("size" in blob) }) test("Blob type is an empty string by default", t => { const blob = new Blob() t.is(blob.type, "") }) test("The type property is read-only", t => { const expected = "text/plain" const blob = new Blob([], {type: expected}) // @ts-expect-error try { blob.type = "application/json" } catch { /* noop */ } t.is(blob.type, expected) }) test("The type property cannot be removed", t => { const blob = new Blob() // @ts-expect-error try { delete blob.type } catch { /* noop */ } t.true("type" in blob) }) test( "Constructor throws an error when first argument is not an object", t => { const rounds: unknown[] = [null, true, false, 0, 1, 1.5, "FAIL"] rounds.forEach(round => { // @ts-expect-error const trap = () => new Blob(round) t.throws(trap, { instanceOf: TypeError, message: "Failed to construct 'Blob': " + "The provided value cannot be converted to a sequence." }) }) } ) test( "Constructor throws an error when first argument is not an iterable object", t => { const rounds = [new Date(), new RegExp(""), {}, {0: "FAIL", length: 1}] rounds.forEach(round => { // @ts-expect-error const trap = () => new Blob(round) t.throws(trap, { instanceOf: TypeError, message: "Failed to construct 'Blob': " + "The object must have a callable @@iterator property." }) }) } ) test("Creates a new Blob from an array of strings", async t => { const source = ["one", "two", "three"] const blob = new Blob(source) t.is(await blob.text(), source.join("")) }) test("Creates a new Blob from an array of Uint8Array", async t => { const encoder = new TextEncoder() const source = ["one", "two", "three"] const blob = new Blob(source.map(part => encoder.encode(part))) t.is(await blob.text(), source.join("")) }) test("Creates a new Blob from an array of ArrayBuffer", async t => { const encoder = new TextEncoder() const source = ["one", "two", "three"] const blob = new Blob(source.map(part => encoder.encode(part).buffer)) t.is(await blob.text(), source.join("")) }) test("Creates a new Blob from an array of Blob", async t => { const source = ["one", "two", "three"] const blob = new Blob(source.map(part => new Blob([part]))) t.is(await blob.text(), source.join("")) }) test("Accepts a String object as a sequence", async t => { const expected = "abc" // eslint-disable-next-line no-new-wrappers const blob = new Blob(new String(expected)) t.is(await blob.text(), expected) }) test("Accepts Uint8Array as a sequence", async t => { const expected = [1, 2, 3] const blob = new Blob(new Uint8Array(expected)) t.is(await blob.text(), expected.join("")) }) test("Accepts iterable object as a sequence", async t => { const blob = new Blob({[Symbol.iterator]: Array.prototype[Symbol.iterator]}) t.is(blob.size, 0) t.is(await blob.text(), "") }) test("Constructor reads blobParts from iterable object", async t => { const source = ["one", "two", "three"] const expected = source.join("") const blob = new Blob({ * [Symbol.iterator]() { yield* source } }) t.is(blob.size, new TextEncoder().encode(expected).byteLength) t.is(await blob.text(), expected) }) test("Blob has the size measured from the blobParts", t => { const source = ["one", "two", "three"] const expected = new TextEncoder().encode(source.join("")).byteLength const blob = new Blob(source) t.is(blob.size, expected) }) test("Accepts type for Blob as an option in the second argument", t => { const expected = "text/markdown" const blob = new Blob(["Some *Markdown* content"], {type: expected}) t.is(blob.type, expected) }) test("Casts elements of the blobPart array to a string", async t => { const source: unknown[] = [ null, undefined, true, false, 0, 1, // eslint-disable-next-line no-new-wrappers new String("string object"), [], {0: "FAIL", length: 1}, {toString() { return "stringA" }}, {toString: undefined, valueOf() { return "stringB" }}, ] const expected = source.map(element => String(element)).join("") const blob = new Blob(source) t.is(await blob.text(), expected) }) test("undefined value has no affect on property bag argument", t => { const blob = new Blob([], undefined) t.is(blob.type, "") }) test("null value has no affect on property bag argument", t => { const blob = new Blob([], null) t.is(blob.type, "") }) test("Invalid type in property bag will result in an empty string", t => { const blob = new Blob([], {type: "\u001Ftext/plain"}) t.is(blob.type, "") }) test( "Throws an error if invalid property bag passed", t => { const rounds = [ 123, 123.4, true, false, "FAIL" ] rounds.forEach(round => { // @ts-expect-error const trap = () => new Blob([], round) t.throws(trap, { instanceOf: TypeError, message: "Failed to construct 'Blob': " + "parameter 2 cannot convert to dictionary." }) }) } ) test("Blob-like objects must be recognized as Blob in instanceof test", t => { class BlobAlike { type = "" size = 0 stream() { return new ReadableStream() } arrayBuffer() { return new ArrayBuffer(0) } [Symbol.toStringTag] = "Blob" } const blob = new BlobAlike() t.true(blob instanceof Blob) }) test("Blob-shaped objects must be recognized as Blob in instanceof test", t => { const blobAlike = { type: "", size: 0, stream() { return new ReadableStream() }, arrayBuffer() { return new ArrayBuffer(0) }, [Symbol.toStringTag]: "Blob" } t.true(blobAlike instanceof Blob) }) test( "Blob-like objects with only arrayBuffer method must be recognized as Blob", t => { const blobAlike = { type: "", size: 0, arrayBuffer() { return new ArrayBuffer(0) }, [Symbol.toStringTag]: "Blob" } t.true(blobAlike instanceof Blob) } ) test(".slice() a new blob when called without arguments", async t => { const blob = new Blob(["a", "b", "c"]) const sliced = blob.slice() t.is(sliced.size, blob.size) t.is(await sliced.text(), await blob.text()) }) test(".slice() an empty blob with the start and the end set to 0", async t => { const blob = new Blob(["a", "b", "c"]) const sliced = blob.slice(0, 0) t.is(sliced.size, 0) t.is(await sliced.text(), "") }) test(".slice() slices the Blob within given range", async t => { const text = "The MIT License" const blob = new Blob([text]).slice(0, 3) t.is(await blob.text(), "The") }) test(".slice() slices the Blob from arbitary start", async t => { const text = "The MIT License" const blob = new Blob([text]).slice(4, 15) t.is(await blob.text(), "MIT License") }) test( ".slice() slices the Blob from the end when start argument is negative", async t => { const text = "The MIT License" const blob = new Blob([text]).slice(-7) t.is(await blob.text(), "License") } ) test( ".slice() slices the Blob from the start when end argument is negative", async t => { const text = "The MIT License" const blob = new Blob([text]).slice(0, -8) t.is(await blob.text(), "The MIT") } ) test(".slice() slices Blob in blob parts", async t => { const text = "The MIT License" const blob = new Blob([new Blob([text]), new Blob([text])]).slice(8, 18) t.is(await blob.text(), "LicenseThe") }) test(".slice() slices within multiple parts", async t => { const blob = new Blob(["Hello", "world"]).slice(4, 7) t.is(await blob.text(), "owo") }) test(".slice() throws away unwanted parts", async t => { const blob = new Blob(["a", "b", "c"]).slice(1, 2) t.is(await blob.text(), "b") }) test(".slice() takes type as the 3rd argument", t => { const expected = "text/plain" const blob = new Blob([], {type: "text/html"}).slice(0, 0, expected) t.is(blob.type, expected) }) test( ".text() returns a the Blob content as string when awaited", async t => { const blob = new Blob([ "a", new TextEncoder().encode("b"), new Blob(["c"]), new TextEncoder().encode("d").buffer, ]) t.is(await blob.text(), "abcd") } ) test( ".arrayBuffer() returns the Blob content as ArrayBuffer when awaited", async t => { const source = new TextEncoder().encode("abc") const blob = new Blob([source]) t.true(Buffer.from(await blob.arrayBuffer()).equals(source)) } ) test(".stream() returns ReadableStream", t => { const stream = new Blob().stream() t.true(stream instanceof ReadableStream) }) test(".stream() allows to read Blob as a stream", async t => { const source = Buffer.from("Some content") const stream = new Blob([source]).stream() const chunks: Uint8Array[] = [] for await (const chunk of stream) { chunks.push(chunk) } t.true(Buffer.concat(chunks).equals(source)) }) test(".stream() returned ReadableStream can be cancelled", async t => { const stream = new Blob(["Some content"]).stream() // Cancel the stream before start reading, or this will throw an error await stream.cancel() const reader = stream.getReader() const {done, value: chunk} = await reader.read() t.true(done) t.is(chunk, undefined) })
the_stack
import { writable } from "svelte/store"; import APIClient from "./api-cli"; import Storage from "../../modules/storage/storage"; // import Hyperstorage from "../../modules/hyperstorage/hyperstorage"; // import Note, { NoteGeo } from "../notes/note.class"; // import { ToastStore } from "../../components/toast/toast.store"; // import { AlertStore } from "../../components/alert/alert.store"; // import { NoteStore } from "../notes/note.store"; import _ from "lodash"; import NLog from "../../modules/nomie-log/nomie-log"; import { Interact } from "../../store/interact"; import tick from "../../utils/tick/tick"; import dayjs from "dayjs"; import { LedgerStore } from "../../store/ledger"; import { Lang } from "../../store/lang"; // import wait from "../../modules/utils/wait"; // import { DeviceStore } from "../device/device.store"; // const console = new Logger("🚦 Nomie API"); // Todo consider making this configurable const NAPI = new APIClient({ domain: "nomieapi.com/.netlify/functions" }); export interface MassNapiLogImport { // success:Array<{nLog:any, log:NapiLog}>; success: Array<{ nlog: NLog; log: NapiLog }>; errors: Array<{ error: Error; log: NapiLog }>; } // From the Nomie API Service export interface NapiLog { date: Date; id: string; lat?: number; lng?: number; note: string; source: string; saved?: boolean; discarded?: boolean; } // Store State Type interface ApiStateConfig { registered?: boolean; apiKey?: string | undefined; privateKey?: string | undefined; autoImport?: boolean; ready?: boolean; items?: Array<NapiLog>; inArchive?: Array<NapiLog>; inAPI?: Array<NapiLog>; generating?: boolean; deviceDisabled?: boolean; } const API_PING_TIME = 1000 * 60; // check every 4 minutes const API_DEVICE_DISABLED = 'napi-device-disabled'; // Nomie API Store const createApiStore = () => { // Setup non syncing storage // const ApiLogStore = new Hyperstorage("api-logs"); const ApiLogStore = new Storage.SideStore('napi/saved.json'); // holder for the Auto Import Time Check let monitorInterval: any; // Create the State const _state: ApiStateConfig = { deviceDisabled: !canApiRunOnDevice(), registered: undefined, apiKey: null, privateKey: null, autoImport: false, ready: false, items: [], inArchive: [], inAPI: [], generating: false, }; // Get Store Items const { update, subscribe, set } = writable(_state); function canApiRunOnDevice():boolean { return localStorage.getItem(API_DEVICE_DISABLED) ? false : true; } /** * Get Store Logs from the Archives */ function getArchives():Array<NapiLog> { return ApiLogStore.get("napi/saved.json") || []; } /** * Set Stored Logs to the Archive * @param stored */ // function clearArchives() { // return ApiLogStore.put("napi/saved.json", []); // } async function setArchives(stored: Array<NapiLog> = []) { ApiLogStore.put("napi/saved.json", stored); fuse({inArchive: stored.sort((a,b)=>{ return a.date < b.date ? 1 : -1})}); return true; } /** * Fuse State * Getter and Updater for the Svelte Store State **/ function fuse(_state: ApiStateConfig = {}): ApiStateConfig { let updatedState: ApiStateConfig; update((state) => { updatedState = { ...state, ..._state }; return updatedState; }); return updatedState; } const methods = { // Load the Napi - and fire things when ready async init() { // Auto clear sicne we can toggle now methods.stopMonitoring(); // Can it run on this device? const canRun:boolean = canApiRunOnDevice(); // Initialize the Client if(canRun === true) { await NAPI.init(); } // When Ready NAPI.onReady(async () => { console.log("✅ Nomie API Client Ready"); // Are they registered const isRegistered: boolean = NAPI.isRegistered(); // Update State Accordingly const state = fuse( isRegistered ? { registered: true, apiKey: NAPI.keyLocker.apiKey, privateKey: NAPI.keyLocker.privateKey, autoImport: ApiLogStore.get("auto-import") ? true : false, } : { registered: false, apiKey: undefined, privateKey: undefined, autoImport: false, } ); // Get the Logs if we're registered if (isRegistered && canRun) { await tick(200); methods.startMonitoringAPI(state.autoImport); } }); console.log("✅ Nomie API Store initialized"); }, clearArchives() { console.log("Clear?"); ApiLogStore.put("napi/saved.json", []); methods.init(); }, toggleDeviceDisabled() { console.log("Toggling device disabled"); if(canApiRunOnDevice()) { console.log("Currently Enabled switching to disabled"); localStorage.setItem(API_DEVICE_DISABLED, '1'); fuse({ deviceDisabled: true}) } else { console.log("Currently DIsabled switching to ENABLED"); localStorage.removeItem(API_DEVICE_DISABLED); fuse({ deviceDisabled: false}) } methods.init(); }, async toggleAutoImport() { update((state) => { console.log("Current Toggle state", state.autoImport); state.autoImport = !state.autoImport; console.log("After Toggle Toggle state", state.autoImport); ApiLogStore.put("auto-import", state.autoImport); return state; }); await tick(200); window.location.reload(); }, /** * * Discard a Log * This will remove a log from the archive * * @param napiLog */ discard(napiLog: NapiLog) { let stored: Array<NapiLog> = getArchives() || []; setArchives( stored.map((log) => { if (log.id == napiLog.id) { log.discarded = true; } return log; }) ); update((state) => { state.items = stored.filter((l) => !l.discarded && !l.saved).sort((a,b)=>a.date > b.date ? 1 : -1); return state; }); }, /** * Get Archive Log * These are just stored in lcoal storage */ getArchivesLogs(): Array<NapiLog> { return getArchives() || []; }, /** * Set Archives * Save them all in one big chunkt. * @param logs */ setArchivesLogs(logs: Array<NapiLog>) { return setArchives(logs); // ApiLogStore.put('napi/stored', logs); }, /** * * Destory the API * * This is to absolutely destory the API from the Device and the Server * */ async destroy(): Promise<boolean> { // Ask user for confirmation const ask = await Interact.confirm( "Destroy this API Key on the device and server?", `It will no longer work, ever. This will make the API completely unusable to external systems` ); if (ask) { try { // Call Destory await NAPI.destory(); // Clear local config methods.clearConfig(); return true; } catch (e) { // Clear config event if we get an error methods.clearConfig(); Interact.error(e.message); } } }, clearConfig() { NAPI.clearConfig(); fuse({ registered: false, apiKey: undefined, privateKey: undefined, }); }, async forget(): Promise<boolean> { const ask = await Interact.confirm( "Forget the API Key and Private Key?", `The API key will still remain valid on the server, and you can use it later. But you'll need to restore using the api/private key.` ); if (ask) { // const cleared = await clearArchives(); // console.log("Cleared?", cleared); methods.clearConfig(); Interact.toast(`API config forgotten`); } else { return false; } }, async getLogs(): Promise<Array<NapiLog>> { // Get logs from API let logs: Array<NapiLog> = await NAPI.logs(); // Get Saved / Cached Logs from Side Storage const stored: Array<NapiLog> = methods.getArchivesLogs(); // Loop over logs from API logs.forEach((log: NapiLog) => { // Does it exist in Stored array? const fromStorage = stored.find((l) => l.id == log.id); // If not, it's new - lets add it if (!fromStorage) { // Mar it as not saved log.saved = false; // Pushed to Stored stored.push(log); } }); // Save to Storage setArchives(stored); // Update State so UI can react const state = fuse({ items : stored.filter((l) => !l.saved && !l.discarded), inArchive : stored, inAPI : stored.filter(l=>!l.saved && !l.discarded), }) if(state.inAPI.length == 0 && logs.length > 0) { console.log("🔥 we have a pointless logs in the API. DELETE THEM!"); await NAPI.clear(); } // Return Array of Items stored; return stored; }, toLog(apiLog:NapiLog): NLog { let log: NLog = new NLog(apiLog); log.end = apiLog.date ? new Date(apiLog.date).getTime() : new Date().getTime(); return log; }, async restoreKeys() { // Prepare user for needed info const ask = await Interact.confirm( `Restore your API Key`, `To restore, you'll be asked to provide your API Key and Private Key. Continue?` ); if (ask) { try { // Ask for API KEY const apiKey = prompt(`API Key`); // Ask for Private key const privateKey = prompt("Private Key"); // If we are missing either - rerun this method again if (!privateKey || !apiKey) { methods.restoreKeys(); } else { // Test if the combo is valid const test = await NAPI.testAndSave(apiKey, privateKey); if (test === true) { methods.init(); Interact.alert(Lang.t('general.success','Success!'), `👍 API Successfully Restored`); } else { Interact.error("Unable to verify that API Key and Private Key combination"); } } } catch (e) { Interact.error(e.message); } } }, /** * Restore a Discarded Log * @param log */ restoreLog(log:NapiLog) { // Remove saved and discarded log.saved = false; log.discarded = false; // Get the latest archives const archives = getArchives(); // SEt the archives with an updated log setArchives(archives.map((loopLog:NapiLog)=>{ if(loopLog.id == log.id) { return log; } else { return loopLog } })) }, async autoImport() { // Get all the logs from the API and Stored Locally // Filter out Saved and Discarded let allLogs: Array<NapiLog> = (await methods.getLogs()) || []; let logs: Array<NapiLog> = allLogs.filter((l) => !l.saved && !l.discarded); // If we have logs lets import them if (logs.length) { // Save the Logs let results: MassNapiLogImport = await methods.import(logs); // If no errors - show a toast notification if (results.errors.length == 0 && results.success.length == logs.length) { // Interact.toast(`${logs.length} ${logs.length > 1 ? "notes" : "note"} imported`); Interact.toast(`${logs.length} ${logs.length > 1 ? "notes" : "note"} imported`); // Clear the Nomie API await NAPI.clear(); } else { await Interact.alert( "Import incomplete",`Imported ${results.success.length} of ${logs.length}. Please go to settings / data / nomie api / captured to see all notes current available.`); } // Refresh methods.getLogs(); } }, async import(logs: Array<NapiLog>): Promise<MassNapiLogImport> { let archives:Array<NapiLog> = getArchives(); // Block the UI Interact.blocker(`Importing ${logs.length} ${logs.length > 1 ? "notes" : "note"} from the API...`); await tick(500); // loop over each log let results: MassNapiLogImport = { errors: [], success: [], }; // For loop (for async) over logs for (let i = 0; i < logs.length; i++) { // Get log let log: NapiLog = logs[i]; try { // Add the Date // Convert it into an official Nomie Log // let nLog = methods.toLog(log); const nlog = methods.toLog(log); // Add a millsecond at the end to avoid duplicate IDs // await NoteStore.save(note); // Save the Log const saved = await LedgerStore.saveLog(nlog); log.saved = saved ? true : false; // Update the Archives for this Note / Log let foundInArchive:boolean = false; // Map map saved log in archive. archives = archives.map((loopLog:NapiLog)=>{ if(loopLog.id == log.id) { foundInArchive = true; loopLog.saved = true; } return loopLog; }); if(!foundInArchive) { log.saved = true; archives.push(log); } // Update the Archive setArchives(archives); // Push successful save to results results.success.push({ nlog, log }); } catch (e) { // An error has happened results.errors.push({ error: e.message, log, }); // Show error to console console.error(e.message); } } // Stop the blocker Interact.stopBlocker(); methods.getLogs(); // return the error, success arrays return results; }, /** * Register for a New API Key */ async register() { // Notify user we're generating fuse({ generating: true }); try { // Get new API key and private key const registered = await NAPI.register(); // If we're good if (registered) { fuse({ generating: false, registered: true, privateKey: NAPI.keyLocker.privateKey, apiKey: NAPI.keyLocker.apiKey, }); } else { // Something bad happened Interact.error("An unknown error occured while registering."); console.error(registered); } } catch (e) { // Something really bad happened Interact.error(e.message); fuse({ generating: false }); console.error(e); } }, /** * * Monitor API * * We will monitor the API from here - passing in the AutoImport is a way * to avoid having to bring the UserStore into here causing a circular * dependency - which outputs a console warning and is annoying. * But having to pass it in here is fucking annoying too. * * @param autoImport: boolean */ startMonitoringAPI(autoImport: boolean = false) { // Begin Monitoring console.log("🟢🟢🟢 Starting to Monitor the API"); // Clear the last Interval methods.stopMonitoring(); // Function to call each interval const monitor = () => { // If we're auto import or not if (autoImport) { // Get and Import methods.autoImport(); } else { // get logs only methods.getLogs(); } }; // Every N minutes monitorInterval = setInterval(monitor, API_PING_TIME); // Immediate monitor(); }, stopMonitoring() { clearInterval(monitorInterval); }, }; return { update, subscribe, set, ...methods, }; }; export const ApiStore = createApiStore();
the_stack
const filedrag = document.getElementById("filedrag"); const fileselect = document.getElementById("fileselect"); let fileName = null; interface FileReaderEventTarget extends EventTarget { result: string; } interface FileReaderEvent extends Event { target: FileReaderEventTarget; getMessage(): string; } interface Window { ga: any; Prism: { highlightElement(elem: HTMLElement): void }; } // file drag hover function fileDragHover(e) { e.stopPropagation(); e.preventDefault(); e.target.className = e.type === "dragover" ? "hover" : ""; } let linkedinToJsonResume; const downloadButton = <HTMLElement>document.querySelector(".download"); downloadButton.addEventListener("click", () => { import("./file").then((save) => { save.default( JSON.stringify(linkedinToJsonResume.getOutput(), undefined, 2), "resume.json" ); if (window.ga) { window.ga("send", "event", "linkedin-to-json-resume", "download-resume"); } }); }); downloadButton.style.display = "none"; // file selection function fileSelectHandler(e) { if (window.ga) { window.ga("send", "event", "linkedin-to-json-resume", "file-selected"); } Promise.all([ import("./converter"), import("moment"), import("isomorphic-unzip/zip-browser"), import("./csvtoarray"), ]).then((modules) => { const [LinkedInToJsonResume, Moment, Unzip, CsvToArray] = modules; const csvToArray = CsvToArray.default; const moment = Moment.default; linkedinToJsonResume = new LinkedInToJsonResume.default(); // cancel event and hover styling fileDragHover(e); const droppedFiles = e.target.files || e.dataTransfer.files; const file = droppedFiles[0]; fileName = file.name; const readBlob = (blob: Blob): Promise<string> => { return new Promise((resolve) => { let reader = new FileReader(); reader.onload = (e: FileReaderEvent) => { resolve(e.target.result); }; reader.readAsText(blob); }); }; const readEntryContents = (entry: any): Promise<string> => { return new Promise((resolve) => { Unzip.default.getEntryData(entry, (error, blob) => { readBlob(blob).then(resolve); }); }); }; let unzip = null; const getEntries = (file, onend) => { unzip = new Unzip.default(file); unzip.getEntries(function (error, entries) { onend(entries); }); }; getEntries(file, (entries) => { const promises = entries.map((entry) => { switch (true) { case entry.filename.indexOf("/Skills.csv") !== -1: return readEntryContents(entry).then((contents) => { contents = contents.replace(/"/g, ""); let elements = contents.split("\n"); elements = elements.slice(1, elements.length - 1); linkedinToJsonResume.processSkills(elements); return; }); case entry.filename.indexOf("/Education.csv") !== -1: return readEntryContents(entry).then((contents) => { const elements = csvToArray(contents); const education = elements .slice(1, elements.length - 1) .map((elem) => ({ schoolName: elem[0], startDate: moment(elem[1]).format("YYYY-MM-DD"), endDate: moment(elem[2]).format("YYYY-MM-DD"), notes: elem[3], degree: elem[4], activities: elem[5], })); linkedinToJsonResume.processEducation( education.sort( (e1, e2) => -e1.startDate.localeCompare(e2.startDate) ) ); return; }); case entry.filename.indexOf("/Positions.csv") !== -1: return readEntryContents(entry).then((contents) => { const elements = csvToArray(contents); const positions = elements .slice(1, elements.length - 1) .map((elem) => { return { companyName: elem[0], title: elem[1], description: elem[2], location: elem[3], startDate: moment(elem[4], "MMM YYYY").format("YYYY-MM-DD"), endDate: elem[5] ? moment(elem[5], "MMM YYYY").format("YYYY-MM-DD") : null, }; }); linkedinToJsonResume.processPosition( positions.sort( (p1, p2) => -p1.startDate.localeCompare(p2.startDate) ) ); return; }); case entry.filename.indexOf("/Languages.csv") !== -1: return readEntryContents(entry).then((contents) => { const elements = csvToArray(contents); const languages = elements .slice(1, elements.length - 1) .map((elem) => ({ name: elem[0], proficiency: elem[1], })); linkedinToJsonResume.processLanguages(languages); return; }); case entry.filename.indexOf("/Recommendations Received.csv") !== -1: return readEntryContents(entry).then((contents) => { const elements = csvToArray(contents); const recommendations = elements .slice(1, elements.length - 1) .map((elem) => ({ recommenderFirstName: elem[0], recommenderLastName: elem[1], recommenderCompany: elem[2], recommenderTitle: elem[3], recommendationBody: elem[4], recommendationDate: elem[5], displayStatus: elem[6], })) .filter( (recommendation) => recommendation.displayStatus === "VISIBLE" ); linkedinToJsonResume.processReferences(recommendations); return; }); case entry.filename.indexOf("/Profile.csv") !== -1: return readEntryContents(entry).then((contents) => { const elements = csvToArray(contents); const profile = { firstName: elements[1][0], lastName: elements[1][1], maidenName: elements[1][2], address: elements[1][3], birthDate: elements[1][4], headline: elements[1][5], summary: elements[1][6], industry: elements[1][7], zipCode: elements[1][8], geoLocation: elements[1][9], twitterHandles: elements[1][10], websites: elements[1][11], instantMessengers: elements[1][12], }; linkedinToJsonResume.processProfile(profile); return; }); case entry.filename.indexOf("/Email Addresses.csv") !== -1: return readEntryContents(entry).then((contents) => { const elements = csvToArray(contents, "\t"); // yes, recommendations use tab-delimiter const email = elements .slice(1, elements.length - 1) .map((elem) => ({ address: elem[0], status: elem[1], isPrimary: elem[2] === "Yes", dateAdded: elem[3], dateRemoved: elem[4], })) .filter((email) => email.isPrimary); if (email.length) { linkedinToJsonResume.processEmail(email[0]); } return; }); case entry.filename.indexOf("/Interests.csv") !== -1: return readEntryContents(entry).then((contents) => { const elements = csvToArray(contents); let interests = []; elements.slice(1, elements.length - 1).forEach((elem) => { interests = interests.concat(elem[0].split(",")); }); linkedinToJsonResume.processInterests(interests); return; }); case entry.filename.indexOf("/Projects.csv") !== -1: return readEntryContents(entry).then((contents) => { const elements = csvToArray(contents); const projects = elements .slice(1, elements.length - 1) .map((elem) => ({ title: elem[0], description: elem[1], url: elem[2], startDate: moment(elem[3]).format("YYYY-MM-DD"), endDate: elem[4] ? moment(elem[4]).format("YYYY-MM-DD") : null, })); linkedinToJsonResume.processProjects( projects.sort( (p1, p2) => -p1.startDate.localeCompare(p2.startDate) ) ); return; }); case entry.filename.indexOf("/Publications.csv") !== -1: return readEntryContents(entry).then((contents) => { const elements = csvToArray(contents); const publications = elements .slice(1, elements.length - 1) .map((elem) => ({ name: elem[0], date: moment(elem[1]).format("YYYY-MM-DD"), description: elem[2], publisher: elem[3], url: elem[4], })); linkedinToJsonResume.processPublications( publications.sort((p1, p2) => -p1.date.localeCompare(p2.date)) ); return; }); case entry.filename.indexOf("/PhoneNumbers.csv") !== -1: return readEntryContents(entry).then((contents) => { const elements = csvToArray(contents); elements.shift(); const elementsWithNumber = elements.filter( (element) => element[1] ); if (elementsWithNumber.length > 0) { const number = { extension: elementsWithNumber[0][0], number: elementsWithNumber[0][1], type: elementsWithNumber[0][2], }; linkedinToJsonResume.processPhoneNumber(number); } return; }); default: return Promise.resolve([]); } }); Promise.all(promises).then(() => { if (window.ga) { window.ga( "send", "event", "linkedin-to-json-resume", "file-parsed-success" ); } filedrag.innerHTML = "Dropped! See the resulting JSON Resume at the bottom."; const output = document.getElementById("output"); output.innerHTML = JSON.stringify( linkedinToJsonResume.getOutput(), undefined, 2 ); window.Prism.highlightElement(output); downloadButton.style.display = "block"; document.getElementById("result").style.display = "block"; }); }); }); } // file select fileselect.addEventListener("change", fileSelectHandler, false); const xhr = new XMLHttpRequest(); if (xhr.upload) { // file drop filedrag.addEventListener("dragover", fileDragHover, false); filedrag.addEventListener("dragleave", fileDragHover, false); filedrag.addEventListener("drop", fileSelectHandler, false); filedrag.style.display = "block"; } else { filedrag.style.display = "none"; } document.getElementById("select-file").addEventListener("click", () => { fileselect.click(); });
the_stack
import { TestClient } from '../../TestClient'; import { MatrixCall, CallErrorCode, CallEvent } from '../../../src/webrtc/call'; import { SDPStreamMetadataKey, SDPStreamMetadataPurpose } from '../../../src/webrtc/callEventTypes'; import { RoomMember } from "../../../src"; const DUMMY_SDP = ( "v=0\r\n" + "o=- 5022425983810148698 2 IN IP4 127.0.0.1\r\n" + "s=-\r\nt=0 0\r\na=group:BUNDLE 0\r\n" + "a=msid-semantic: WMS h3wAi7s8QpiQMH14WG3BnDbmlOqo9I5ezGZA\r\n" + "m=audio 9 UDP/TLS/RTP/SAVPF 111 103 104 9 0 8 106 105 13 110 112 113 126\r\n" + "c=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:hLDR\r\n" + "a=ice-pwd:bMGD9aOldHWiI+6nAq/IIlRw\r\n" + "a=ice-options:trickle\r\n" + "a=fingerprint:sha-256 E4:94:84:F9:4A:98:8A:56:F5:5F:FD:AF:72:B9:32:89:49:5C:4B:9A:" + "4A:15:8E:41:8A:F3:69:E4:39:52:DC:D6\r\n" + "a=setup:active\r\n" + "a=mid:0\r\n" + "a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\n" + "a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\n" + "a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\n" + "a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid\r\n" + "a=extmap:5 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\r\n" + "a=extmap:6 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\r\n" + "a=sendrecv\r\n" + "a=msid:h3wAi7s8QpiQMH14WG3BnDbmlOqo9I5ezGZA 4357098f-3795-4131-bff4-9ba9c0348c49\r\n" + "a=rtcp-mux\r\n" + "a=rtpmap:111 opus/48000/2\r\n" + "a=rtcp-fb:111 transport-cc\r\n" + "a=fmtp:111 minptime=10;useinbandfec=1\r\n" + "a=rtpmap:103 ISAC/16000\r\n" + "a=rtpmap:104 ISAC/32000\r\n" + "a=rtpmap:9 G722/8000\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:8 PCMA/8000\r\n" + "a=rtpmap:106 CN/32000\r\n" + "a=rtpmap:105 CN/16000\r\n" + "a=rtpmap:13 CN/8000\r\n" + "a=rtpmap:110 telephone-event/48000\r\n" + "a=rtpmap:112 telephone-event/32000\r\n" + "a=rtpmap:113 telephone-event/16000\r\n" + "a=rtpmap:126 telephone-event/8000\r\n" + "a=ssrc:3619738545 cname:2RWtmqhXLdoF4sOi\r\n" ); class MockRTCPeerConnection { localDescription: RTCSessionDescription; constructor() { this.localDescription = { sdp: DUMMY_SDP, type: 'offer', toJSON: function() {}, }; } addEventListener() {} createOffer() { return Promise.resolve({}); } setRemoteDescription() { return Promise.resolve(); } setLocalDescription() { return Promise.resolve(); } close() {} getStats() { return []; } } class MockMediaStream { constructor( public id: string, ) {} getTracks() { return []; } getAudioTracks() { return [{ enabled: true }]; } getVideoTracks() { return [{ enabled: true }]; } addEventListener() {} } class MockMediaDeviceInfo { constructor( public kind: "audio" | "video", ) {} } class MockMediaHandler { getUserMediaStream() { return new MockMediaStream("mock_stream_from_media_handler"); } stopUserMediaStream() {} } describe('Call', function() { let client; let call; let prevNavigator; let prevDocument; let prevWindow; beforeEach(function() { prevNavigator = global.navigator; prevDocument = global.document; prevWindow = global.window; global.navigator = { mediaDevices: { // @ts-ignore Mock getUserMedia: () => new MockMediaStream("local_stream"), // @ts-ignore Mock enumerateDevices: async () => [new MockMediaDeviceInfo("audio"), new MockMediaDeviceInfo("video")], }, }; global.window = { // @ts-ignore Mock RTCPeerConnection: MockRTCPeerConnection, // @ts-ignore Mock RTCSessionDescription: {}, // @ts-ignore Mock RTCIceCandidate: {}, getUserMedia: () => new MockMediaStream("local_stream"), }; // @ts-ignore Mock global.document = {}; client = new TestClient("@alice:foo", "somedevice", "token", undefined, {}); // We just stub out sendEvent: we're not interested in testing the client's // event sending code here client.client.sendEvent = () => {}; client.client.mediaHandler = new MockMediaHandler; client.client.getMediaHandler = () => client.client.mediaHandler; client.httpBackend.when("GET", "/voip/turnServer").respond(200, {}); call = new MatrixCall({ client: client.client, roomId: '!foo:bar', }); // call checks one of these is wired up call.on('error', () => {}); }); afterEach(function() { client.stop(); global.navigator = prevNavigator; global.window = prevWindow; global.document = prevDocument; }); it('should ignore candidate events from non-matching party ID', async function() { const callPromise = call.placeVoiceCall(); await client.httpBackend.flush(); await callPromise; await call.onAnswerReceived({ getContent: () => { return { version: 1, call_id: call.callId, party_id: 'the_correct_party_id', answer: { sdp: DUMMY_SDP, }, }; }, }); call.peerConn.addIceCandidate = jest.fn(); call.onRemoteIceCandidatesReceived({ getContent: () => { return { version: 1, call_id: call.callId, party_id: 'the_correct_party_id', candidates: [ { candidate: '', sdpMid: '', }, ], }; }, }); expect(call.peerConn.addIceCandidate.mock.calls.length).toBe(1); call.onRemoteIceCandidatesReceived({ getContent: () => { return { version: 1, call_id: call.callId, party_id: 'some_other_party_id', candidates: [ { candidate: '', sdpMid: '', }, ], }; }, }); expect(call.peerConn.addIceCandidate.mock.calls.length).toBe(1); // Hangup to stop timers call.hangup(CallErrorCode.UserHangup, true); }); it('should add candidates received before answer if party ID is correct', async function() { const callPromise = call.placeVoiceCall(); await client.httpBackend.flush(); await callPromise; call.peerConn.addIceCandidate = jest.fn(); call.onRemoteIceCandidatesReceived({ getContent: () => { return { version: 1, call_id: call.callId, party_id: 'the_correct_party_id', candidates: [ { candidate: 'the_correct_candidate', sdpMid: '', }, ], }; }, }); call.onRemoteIceCandidatesReceived({ getContent: () => { return { version: 1, call_id: call.callId, party_id: 'some_other_party_id', candidates: [ { candidate: 'the_wrong_candidate', sdpMid: '', }, ], }; }, }); expect(call.peerConn.addIceCandidate.mock.calls.length).toBe(0); await call.onAnswerReceived({ getContent: () => { return { version: 1, call_id: call.callId, party_id: 'the_correct_party_id', answer: { sdp: DUMMY_SDP, }, }; }, }); expect(call.peerConn.addIceCandidate.mock.calls.length).toBe(1); expect(call.peerConn.addIceCandidate).toHaveBeenCalledWith({ candidate: 'the_correct_candidate', sdpMid: '', }); }); it('should map asserted identity messages to remoteAssertedIdentity', async function() { const callPromise = call.placeVoiceCall(); await client.httpBackend.flush(); await callPromise; await call.onAnswerReceived({ getContent: () => { return { version: 1, call_id: call.callId, party_id: 'party_id', answer: { sdp: DUMMY_SDP, }, }; }, }); const identChangedCallback = jest.fn(); call.on(CallEvent.AssertedIdentityChanged, identChangedCallback); await call.onAssertedIdentityReceived({ getContent: () => { return { version: 1, call_id: call.callId, party_id: 'party_id', asserted_identity: { id: "@steve:example.com", display_name: "Steve Gibbons", }, }; }, }); expect(identChangedCallback).toHaveBeenCalled(); const ident = call.getRemoteAssertedIdentity(); expect(ident.id).toEqual("@steve:example.com"); expect(ident.displayName).toEqual("Steve Gibbons"); // Hangup to stop timers call.hangup(CallErrorCode.UserHangup, true); }); it("should map SDPStreamMetadata to feeds", async () => { const callPromise = call.placeVoiceCall(); await client.httpBackend.flush(); await callPromise; call.getOpponentMember = () => { return { userId: "@bob:bar.uk" }; }; await call.onAnswerReceived({ getContent: () => { return { version: 1, call_id: call.callId, party_id: 'party_id', answer: { sdp: DUMMY_SDP, }, [SDPStreamMetadataKey]: { "remote_stream": { purpose: SDPStreamMetadataPurpose.Usermedia, audio_muted: true, video_muted: false, }, }, }; }, }); call.pushRemoteFeed(new MockMediaStream("remote_stream")); const feed = call.getFeeds().find((feed) => feed.stream.id === "remote_stream"); expect(feed?.purpose).toBe(SDPStreamMetadataPurpose.Usermedia); expect(feed?.isAudioMuted()).toBeTruthy(); expect(feed?.isVideoMuted()).not.toBeTruthy(); }); it("should fallback to replaceTrack() if the other side doesn't support SPDStreamMetadata", async () => { const callPromise = call.placeVoiceCall(); await client.httpBackend.flush(); await callPromise; call.getOpponentMember = () => { return { userId: "@bob:bar.uk" } as RoomMember; }; await call.onAnswerReceived({ getContent: () => { return { version: 1, call_id: call.callId, party_id: 'party_id', answer: { sdp: DUMMY_SDP, }, }; }, }); call.setScreensharingEnabledWithoutMetadataSupport = jest.fn(); call.setScreensharingEnabled(true); expect(call.setScreensharingEnabledWithoutMetadataSupport).toHaveBeenCalled(); }); it("should fallback to answering with no video", async () => { await client.httpBackend.flush(); call.shouldAnswerWithMediaType = (wantedValue: boolean) => wantedValue; client.client.mediaHandler.getUserMediaStream = jest.fn().mockRejectedValue("reject"); await call.answer(true, true); expect(client.client.mediaHandler.getUserMediaStream).toHaveBeenNthCalledWith(1, true, true); expect(client.client.mediaHandler.getUserMediaStream).toHaveBeenNthCalledWith(2, true, false); }); });
the_stack
"use strict"; import * as assert from "assert"; import { CompletedPayload, Context, DidExecutedPayload, DispatchedPayload, Dispatcher, DispatcherPayloadMeta, Store, StoreGroup, UseCase, WillExecutedPayload } from "../src"; import { UseCaseExecutorImpl } from "../src/UseCaseExecutor"; import { createStore } from "./helper/create-new-store"; import { createEchoStore } from "./helper/EchoStore"; import { DispatchUseCase } from "./use-case/DispatchUseCase"; import { ParentUseCase } from "./use-case/NestingUseCase"; import { NotExecuteUseCase } from "./use-case/NotExecuteUseCase"; import { SinonStub } from "sinon"; import { UseCaseFunction } from "../src/FunctionalUseCaseContext"; import { createUpdatableStoreWithUseCase } from "./helper/create-update-store-usecase"; const sinon = require("sinon"); // payload class TestUseCase extends UseCase { execute() {} } class ThrowUseCase extends UseCase { execute() { this.dispatch({ type: "update", value: "value" }); this.throwError(new Error("test")); } } describe("Context", function () { context("Deprecated API", () => { let consoleErrorStub: SinonStub; beforeEach(() => { consoleErrorStub = sinon.stub(console, "warn"); }); afterEach(() => { consoleErrorStub.restore(); }); it("should be deprecated warn", function () { const aStore = createStore({ name: "test" }); const storeGroup = new StoreGroup({ a: aStore }); const dispatcher = new Dispatcher(); const context = new Context({ dispatcher, store: storeGroup }); context.onCompleteEachUseCase(() => {}); assert.strictEqual(consoleErrorStub.callCount, 1, "should be deprecated"); }); }); describe("UseCase can dispatch in Context", function () { it("should dispatch Store", function () { const dispatcher = new Dispatcher(); const DISPATCHED_EVENT = { type: "update", value: "value" }; // then class DispatchUseCase extends UseCase { execute() { this.dispatch(DISPATCHED_EVENT); } } const dispatchedPayload: [DispatchedPayload, DispatcherPayloadMeta][] = []; class ReceiveStore extends Store { constructor() { super(); this.onDispatch((payload, meta) => { if (payload.type === DISPATCHED_EVENT.type) { dispatchedPayload.push([payload, meta]); } }); } getState() { return {}; } } // when const store = new ReceiveStore(); const appContext = new Context({ dispatcher, store }); const useCase = new DispatchUseCase(); return appContext .useCase(useCase) .execute() .then(() => { const [payload, meta] = dispatchedPayload[0]; assert.deepEqual(payload, DISPATCHED_EVENT); assert.strictEqual(meta.useCase, useCase); assert.strictEqual(meta.isTrusted, false); assert.strictEqual(meta.parentUseCase, null); assert.strictEqual(typeof meta.timeStamp, "number"); }); }); }); describe("#getStates", function () { it("should get a single state from State", function () { const dispatcher = new Dispatcher(); const expectedMergedObject = { "1": 1 }; const store = createEchoStore({ echo: { "1": 1 } }); const appContext = new Context({ dispatcher, store }); const states = appContext.getState(); assert.deepEqual(states, expectedMergedObject); }); }); describe("#onChange", function () { it("should called when change some State", function (done) { const dispatcher = new Dispatcher(); const aStore = createStore({ name: "AStore" }); const storeGroup = new StoreGroup({ a: aStore }); const appContext = new Context({ dispatcher, store: storeGroup }); appContext.onChange((stores) => { assert.equal(stores.length, 1); assert.equal(stores[0], aStore); done(); }); aStore.updateState({ a: 1 }); }); it("should thin change events are happened at same time", function (done) { const dispatcher = new Dispatcher(); const aStore = createStore({ name: "AStore" }); const bStore = createStore({ name: "BStore" }); const storeGroup = new StoreGroup({ a: aStore, b: bStore }); const appContext = new Context({ dispatcher, store: storeGroup }); appContext.onChange((stores) => { assert.equal(stores.length, 2); done(); }); // catch multiple changes at one time aStore.updateStateWithoutEmit({ a: 1 }); bStore.updateStateWithoutEmit({ b: 1 }); storeGroup.emitChange(); }); }); describe("#onWillNotExecuteEachUseCase", () => { it("should be called when UseCase#shouldExecute() return false", (done) => { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createStore({ name: "test" }) }); const notExecuteUseCase = new NotExecuteUseCase(); // then appContext.events.onWillNotExecuteEachUseCase((payload, meta) => { assert.ok(Array.isArray(payload.args)); assert.ok(typeof meta.timeStamp === "number"); assert.equal(meta.useCase, notExecuteUseCase); assert.equal(meta.parentUseCase, null); assert.equal(meta.isUseCaseFinished, true); done(); }); // when appContext.useCase(notExecuteUseCase).execute(); }); }); describe("#onWillExecuteEachUseCase", function () { it("should not called onWillNotExecuteEachUseCase", function () { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createStore({ name: "test" }) }); const testUseCase = new TestUseCase(); // then let isOnWillNotExecuteEachUseCaseCalled = false; appContext.events.onWillNotExecuteEachUseCase(() => { isOnWillNotExecuteEachUseCaseCalled = true; }); // when return appContext .useCase(testUseCase) .execute() .then(() => { assert.ok(!isOnWillNotExecuteEachUseCaseCalled, "onWillNotExecuteEachUseCase should not called"); }); }); it("should called before UseCase will execute", function (done) { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createStore({ name: "test" }) }); const testUseCase = new TestUseCase(); // then appContext.events.onWillExecuteEachUseCase((payload, meta) => { assert.ok(Array.isArray(payload.args)); assert.ok(typeof meta.timeStamp === "number"); assert.equal(meta.useCase, testUseCase); assert.equal(meta.parentUseCase, null); done(); }); // when appContext.useCase(testUseCase).execute(); }); it("payload.args is the same with context.execute arguments", function (done) { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createStore({ name: "test" }) }); class OneArgumentUseCase extends UseCase { execute(_oneArgument: string) {} } const oneArgumentUseCase = new OneArgumentUseCase(); const expectedArguments = "param"; // then appContext.events.onWillExecuteEachUseCase((payload, _meta) => { assert.ok(payload.args.length === 1); const [arg] = payload.args; assert.ok(arg === expectedArguments); done(); }); // when return appContext.useCase(oneArgumentUseCase).execute(expectedArguments); }); }); describe("#onDispatch", function () { it("should called the other of built-in event", function () { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createStore({ name: "test" }) }); const expectedPayload = { type: "event" }; class EventUseCase extends UseCase { execute() { this.dispatch(expectedPayload); } } const eventUseCase = new EventUseCase(); const isCalled: { [index: string]: boolean } = { will: false, dispatch: false, did: false, complete: false }; // then appContext.events.onWillExecuteEachUseCase((payload, meta) => { isCalled.will = true; assert.ok(payload instanceof WillExecutedPayload); assert.equal(meta.useCase, eventUseCase); assert.equal(meta.parentUseCase, null); }); // onDispatch should not called when UseCase will/did execute. appContext.events.onDispatch((payload, _meta) => { isCalled.dispatch = true; assert.ok(typeof payload === "object"); assert.equal(payload, expectedPayload); }); appContext.events.onDidExecuteEachUseCase((payload, meta) => { isCalled.did = true; assert.ok(payload instanceof DidExecutedPayload); assert.equal(meta.isTrusted, true); assert.equal(meta.useCase, eventUseCase); assert.equal(meta.parentUseCase, null); }); appContext.events.onCompleteEachUseCase((payload, meta) => { isCalled.complete = true; assert.ok(payload instanceof CompletedPayload); assert.equal(meta.isTrusted, true); assert.equal(meta.useCase, eventUseCase); assert.equal(meta.parentUseCase, null); }); // when return appContext .useCase(eventUseCase) .execute() .then(() => { Object.keys(isCalled).forEach((key) => { assert.ok(isCalled[key] === true, `${key} should be called`); }); }); }); }); describe("#onDidExecuteEachUseCase", function () { it("should called after UseCase did execute", function (done) { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createStore({ name: "test" }) }); const testUseCase = new TestUseCase(); // then appContext.events.onDidExecuteEachUseCase((_payload, meta) => { assert.equal(meta.useCase, testUseCase); done(); }); // when appContext.useCase(testUseCase).execute(); }); }); describe("#onCompleteEachUseCase", function () { it("always should be called by async", function () { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createStore({ name: "test" }) }); const testUseCase = new TestUseCase(); // then let isCalled = false; appContext.events.onCompleteEachUseCase(() => { isCalled = true; }); // when const promise = appContext.useCase(testUseCase).execute(); // should not be called at time assert.ok(isCalled === false); return promise.then(() => { assert.ok(isCalled); }); }); }); describe("#onErrorDispatch", function () { it("should called after UseCase did execute", function (done) { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createStore({ name: "test" }) }); const throwUseCase = new ThrowUseCase(); // then appContext.events.onErrorDispatch((payload, meta) => { assert.ok(payload.error instanceof Error); assert.equal(typeof meta.timeStamp, "number"); assert.equal(meta.useCase, throwUseCase); assert.equal(meta.parentUseCase, null); done(); }); // when appContext.useCase(throwUseCase).execute(); }); }); describe("#useCase", function () { it("should return UseCaseExecutor", function () { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createEchoStore({ echo: { "1": 1 } }) }); const useCaseExecutor = appContext.useCase(new ThrowUseCase()); assert.ok(useCaseExecutor instanceof UseCaseExecutorImpl); useCaseExecutor.execute(); }); }); describe("#execute", function () { describe("when pass UseCase constructor", function () { it("should throw AssertionError", function () { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createEchoStore({ echo: { "1": 1 } }) }); assert.throws(() => { // @ts-ignore appContext.useCase(TestUseCase); }); }); }); }); describe("#release", () => { it("should release all handlers", () => { // add handler const dispatcher = new Dispatcher(); const store = createStore({ name: "test" }); const context = new Context({ dispatcher, store, options: { strict: true } }); const doneNotCall = () => { throw new Error("It should not called"); }; context.events.onBeginTransaction(() => { doneNotCall(); }); context.events.onEndTransaction(() => { doneNotCall(); }); context.events.onWillNotExecuteEachUseCase(() => { doneNotCall(); }); context.events.onWillExecuteEachUseCase(() => { doneNotCall(); }); context.events.onDidExecuteEachUseCase(() => { doneNotCall(); }); context.events.onDispatch(() => { doneNotCall(); }); context.onChange(() => { doneNotCall(); }); context.events.onErrorDispatch(() => { doneNotCall(); }); context.events.onCompleteEachUseCase(() => { doneNotCall(); }); // when context.release(); // then - does not call any handler return context .transaction("transaction name", (transactionContext) => { return transactionContext .useCase(new DispatchUseCase()) .execute({ type: "test" }) .then(() => { return transactionContext.useCase(new ThrowUseCase()).execute(); }) .then(() => { transactionContext.commit(); }); }) .then(() => { store.emitChange(); return context.useCase(new ParentUseCase()).execute(); }); }); }); it("should execute functional UseCase", function () { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createEchoStore({ echo: { "1": 1 } }) }); const callStack: DispatchedPayload[] = []; appContext.events.onDispatch((payload, _meta) => { callStack.push(payload); }); const useCase: UseCaseFunction = ({ dispatcher }) => { return (value) => { dispatcher.dispatch({ type: "Example", value }); }; }; return appContext .useCase(useCase) .execute("value") .then(() => { assert.deepEqual(callStack, [ { type: "Example", value: "value" } ]); }); }); it("should execute functional UseCase and lifecycle hook is called ", function () { const dispatcher = new Dispatcher(); const appContext = new Context({ dispatcher, store: createEchoStore({ echo: { "1": 1 } }) }); const callStack: DispatchedPayload[] = []; appContext.events.onDispatch((payload, _meta) => { callStack.push(payload); }); appContext.events.onWillExecuteEachUseCase((payload, _meta) => { callStack.push(payload); }); appContext.events.onDidExecuteEachUseCase((payload, _meta) => { callStack.push(payload); }); appContext.events.onCompleteEachUseCase((payload, _meta) => { callStack.push(payload); }); const useCase: UseCaseFunction = ({ dispatcher }) => { return (value) => { dispatcher.dispatch({ type: "Example", value }); }; }; return appContext .useCase(useCase) .execute("value") .then(() => { const expectedCallStackOfAUseCase = [ WillExecutedPayload, Object /* { type: "Example", value: "value" }*/, DidExecutedPayload, CompletedPayload ]; assert.equal(callStack.length, expectedCallStackOfAUseCase.length); expectedCallStackOfAUseCase.forEach((_payload, index) => { const ExpectedPayloadConstructor = expectedCallStackOfAUseCase[index]; assert.ok(callStack[index] instanceof ExpectedPayloadConstructor); }); }); }); describe("Dispatcher", () => { it("`dispatcher` is optional", () => { const { MockStore, MockUseCase } = createUpdatableStoreWithUseCase("test"); class UpdateUseCase extends MockUseCase { execute() { this.dispatchUpdateState({ value: "update" }); } } // Context class provide observing and communicating with **Store** and **UseCase** const store = new MockStore(); const storeGroup = new StoreGroup({ test: store }); const context = new Context({ dispatcher: new Dispatcher(), store: storeGroup }); return context .useCase(new UpdateUseCase()) .execute() .then(() => { assert.deepEqual(storeGroup.getState(), { test: { value: "update" } }); }); }); }); describe("Constructor with Store instance", () => { it("should Context delegate payload to Store#receivePayload", () => { class CounterStore extends Store { public receivePayloadList: any[]; constructor() { super(); this.receivePayloadList = []; } receivePayload(payload: any) { this.receivePayloadList.push(payload); } getState() { return {}; } } // UseCase class IncrementUseCase extends UseCase { execute() { this.dispatch({ type: "INCREMENT" }); } } // Context class provide observing and communicating with **Store** and **UseCase** const counterStore = new CounterStore(); const context = new Context({ dispatcher: new Dispatcher(), store: counterStore }); return context .useCase(new IncrementUseCase()) .execute() .then(() => { assert.ok(counterStore.receivePayloadList.length > 0); }); }); }); });
the_stack
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'; import { Course } from 'app/entities/course.model'; import { ExerciseGroup } from 'app/entities/exercise-group.model'; import { AnswerOption } from 'app/entities/quiz/answer-option.model'; import { DragAndDropMapping } from 'app/entities/quiz/drag-and-drop-mapping.model'; import { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model'; import { DragAndDropSubmittedAnswer } from 'app/entities/quiz/drag-and-drop-submitted-answer.model'; import { DragItem } from 'app/entities/quiz/drag-item.model'; import { DropLocation } from 'app/entities/quiz/drop-location.model'; import { MultipleChoiceQuestion } from 'app/entities/quiz/multiple-choice-question.model'; import { MultipleChoiceSubmittedAnswer } from 'app/entities/quiz/multiple-choice-submitted-answer.model'; import { QuizExercise } from 'app/entities/quiz/quiz-exercise.model'; import { QuizSubmission } from 'app/entities/quiz/quiz-submission.model'; import { ShortAnswerQuestion } from 'app/entities/quiz/short-answer-question.model'; import { ShortAnswerSubmittedAnswer } from 'app/entities/quiz/short-answer-submitted-answer.model'; import { ShortAnswerSubmittedText } from 'app/entities/quiz/short-answer-submitted-text.model'; import { QuizExamSubmissionComponent } from 'app/exam/participate/exercises/quiz/quiz-exam-submission.component'; import { IncludedInScoreBadgeComponent } from 'app/exercises/shared/exercise-headers/included-in-score-badge.component'; import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe'; import { ArtemisQuizService } from 'app/shared/quiz/quiz.service'; import { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks'; import { MultipleChoiceQuestionComponent } from 'app/exercises/quiz/shared/questions/multiple-choice-question/multiple-choice-question.component'; import { DragAndDropQuestionComponent } from 'app/exercises/quiz/shared/questions/drag-and-drop-question/drag-and-drop-question.component'; import { ShortAnswerQuestionComponent } from 'app/exercises/quiz/shared/questions/short-answer-question/short-answer-question.component'; describe('QuizExamSubmissionComponent', () => { let fixture: ComponentFixture<QuizExamSubmissionComponent>; let component: QuizExamSubmissionComponent; let quizSubmission: QuizSubmission; let exercise: QuizExercise; let multipleChoiceQuestion: MultipleChoiceQuestion; let dragAndDropQuestion: DragAndDropQuestion; let shortAnswerQuestion: ShortAnswerQuestion; let quizService: any; beforeEach(() => { quizSubmission = new QuizSubmission(); exercise = new QuizExercise(new Course(), new ExerciseGroup()); multipleChoiceQuestion = new MultipleChoiceQuestion(); multipleChoiceQuestion.id = 1; dragAndDropQuestion = new DragAndDropQuestion(); dragAndDropQuestion.id = 2; shortAnswerQuestion = new ShortAnswerQuestion(); shortAnswerQuestion.id = 3; return TestBed.configureTestingModule({ imports: [RouterTestingModule.withRoutes([])], declarations: [ QuizExamSubmissionComponent, MockDirective(NgbTooltip), MockPipe(ArtemisTranslatePipe), MockComponent(IncludedInScoreBadgeComponent), MockComponent(MultipleChoiceQuestionComponent), MockComponent(DragAndDropQuestionComponent), MockComponent(ShortAnswerQuestionComponent), ], providers: [MockProvider(ArtemisQuizService)], }) .compileComponents() .then(() => { fixture = TestBed.createComponent(QuizExamSubmissionComponent); component = fixture.componentInstance; quizService = TestBed.inject(ArtemisQuizService); }); }); afterEach(() => { jest.restoreAllMocks(); }); it('should initialize', () => { const quizServiceSpy = jest.spyOn(quizService, 'randomizeOrder'); exercise.quizQuestions = [multipleChoiceQuestion, dragAndDropQuestion]; component.exercise = exercise; fixture.detectChanges(); expect(fixture).toBeDefined(); expect(quizServiceSpy).toHaveBeenCalledOnce(); expect(component.selectedAnswerOptions.has(1)).toEqual(true); expect(component.selectedAnswerOptions.size).toEqual(1); expect(component.dragAndDropMappings.has(2)).toEqual(true); expect(component.dragAndDropMappings.size).toEqual(1); expect(component.shortAnswerSubmittedTexts.size).toEqual(0); }); it('should update view from submission and fill the dictionary accordingly when submitted answer', () => { exercise.quizQuestions = [multipleChoiceQuestion, dragAndDropQuestion]; component.exercise = exercise; const multipleChoiceSubmittedAnswer = new MultipleChoiceSubmittedAnswer(); const multipleChoiceSelectedOptions = new AnswerOption(); multipleChoiceSelectedOptions.id = 1; multipleChoiceSubmittedAnswer.id = 1; multipleChoiceSubmittedAnswer.quizQuestion = multipleChoiceQuestion; multipleChoiceSubmittedAnswer.selectedOptions = [multipleChoiceSelectedOptions]; const dragAndDropSubmittedAnswer = new DragAndDropSubmittedAnswer(); const dragAndDropMapping = new DragAndDropMapping(new DragItem(), new DropLocation()); dragAndDropMapping.id = 2; dragAndDropSubmittedAnswer.id = 2; dragAndDropSubmittedAnswer.quizQuestion = dragAndDropQuestion; dragAndDropSubmittedAnswer.mappings = [dragAndDropMapping]; quizSubmission.submittedAnswers = [multipleChoiceSubmittedAnswer, dragAndDropSubmittedAnswer]; component.studentSubmission = quizSubmission; component.updateViewFromSubmission(); fixture.detectChanges(); expect(JSON.stringify(component.selectedAnswerOptions.get(1))).toEqual(JSON.stringify([multipleChoiceSelectedOptions])); expect(JSON.stringify(component.dragAndDropMappings.get(2))).toEqual(JSON.stringify([dragAndDropMapping])); expect(component.shortAnswerSubmittedTexts.size).toEqual(0); /** * Test the return value of the getSubmission and getExercise */ expect(component.getSubmission()).toEqual(quizSubmission); expect(component.getExercise()).toEqual(exercise); /** * Change the isSynced value of studentSubmission to false when selection changed */ component.onSelectionChanged(); expect(component.studentSubmission.isSynced).toEqual(false); /** * Return the negated value of isSynced when there are unsaved changes */ expect(component.hasUnsavedChanges()).toEqual(true); }); it('should set answerOptions/mappings/submitted texts to empty array when not submitted answer', () => { exercise.quizQuestions = [multipleChoiceQuestion, dragAndDropQuestion, shortAnswerQuestion]; component.exercise = exercise; component.updateViewFromSubmission(); fixture.detectChanges(); expect(JSON.stringify(component.selectedAnswerOptions.get(1))).toEqual(JSON.stringify([])); expect(component.selectedAnswerOptions.has(1)).toEqual(true); expect(JSON.stringify(component.dragAndDropMappings.get(2))).toEqual(JSON.stringify([])); expect(component.dragAndDropMappings.has(2)).toEqual(true); expect(component.shortAnswerSubmittedTexts.size).toEqual(1); expect(component.shortAnswerSubmittedTexts.has(3)).toEqual(true); }); it('should trigger navigation towards the corrensponding question of the quiz', () => { const element = document.createElement('exam-navigation-bar'); const getNavigationStub = jest.spyOn(document, 'getElementById').mockReturnValue(element); const yOffsetRect = element.getBoundingClientRect() as DOMRect; const yOffsetStub = jest.spyOn(element, 'getBoundingClientRect').mockReturnValue(yOffsetRect); const windowSpy = jest.spyOn(window, 'scrollTo'); component.navigateToQuestion(1); component.exercise = exercise; fixture.detectChanges(); expect(getNavigationStub).toHaveBeenCalled(); expect(yOffsetStub).toHaveBeenCalled(); expect(windowSpy).toHaveBeenCalled(); }); it('should create multiple choice submission from users selection ', () => { exercise.quizQuestions = [multipleChoiceQuestion, dragAndDropQuestion, shortAnswerQuestion]; component.studentSubmission = new QuizSubmission(); component.exercise = exercise; const multipleChoiceSelectedOptions = new AnswerOption(); multipleChoiceSelectedOptions.id = 1; component.selectedAnswerOptions.set(1, [multipleChoiceSelectedOptions]); const dragAndDropMapping = new DragAndDropMapping(new DragItem(), new DropLocation()); dragAndDropMapping.id = 2; component.dragAndDropMappings.set(2, [dragAndDropMapping]); const shortAnswerSubmittedText = new ShortAnswerSubmittedText(); shortAnswerSubmittedText.id = 3; component.shortAnswerSubmittedTexts.set(3, [shortAnswerSubmittedText]); const multipleChoiceSubmittedAnswer = new MultipleChoiceSubmittedAnswer(); multipleChoiceSubmittedAnswer.quizQuestion = multipleChoiceQuestion; multipleChoiceSubmittedAnswer.selectedOptions = [multipleChoiceSelectedOptions]; const dragAndDropSubmittedAnswer = new DragAndDropSubmittedAnswer(); dragAndDropSubmittedAnswer.quizQuestion = dragAndDropQuestion; dragAndDropSubmittedAnswer.mappings = [dragAndDropMapping]; dragAndDropQuestion.correctMappings = [dragAndDropMapping]; const shortAnswerSubmittedAnswer = new ShortAnswerSubmittedAnswer(); shortAnswerSubmittedAnswer.quizQuestion = shortAnswerQuestion; shortAnswerSubmittedAnswer.submittedTexts = [shortAnswerSubmittedText]; component.updateSubmissionFromView(); fixture.detectChanges(); expect(component.studentSubmission.submittedAnswers?.length).toEqual(3); expect(JSON.stringify(component.studentSubmission.submittedAnswers)).toEqual( JSON.stringify([multipleChoiceSubmittedAnswer, dragAndDropSubmittedAnswer, shortAnswerSubmittedAnswer]), ); }); });
the_stack
import MongoMemoryReplSet, { MongoMemoryReplSetEvents, MongoMemoryReplSetStates, } from '../MongoMemoryReplSet'; import { MongoClient } from 'mongodb'; import MongoMemoryServer from '../MongoMemoryServer'; import * as utils from '../util/utils'; import { MongoMemoryInstanceOpts } from '../util/MongoInstance'; import { ReplsetCountLowError, StateError, WaitForPrimaryTimeoutError } from '../util/errors'; import { assertIsError } from './testUtils/test_utils'; jest.setTimeout(100000); // 10s afterEach(() => { jest.restoreAllMocks(); }); describe('single server replset', () => { it('should enter running state', async () => { const replSet = await MongoMemoryReplSet.create(); expect(replSet.getUri().split(',').length).toEqual(1); await replSet.stop(); }); it('"getUri" should be able to get connection string to specific db', async () => { const replSet = await MongoMemoryReplSet.create(); const uri = replSet.getUri('other'); expect(uri.split(',').length).toEqual(1); expect(uri.includes('/other')).toBeTruthy(); expect(uri.includes('replicaSet=testset')).toBeTruthy(); await replSet.stop(); }); it('"getUri" should be able to generate an dbName', async () => { jest.spyOn(utils, 'generateDbName'); const replSet = await MongoMemoryReplSet.create(); const port = replSet.servers[0].instanceInfo?.port; const uri = replSet.getUri(); expect(uri).toEqual(`mongodb://127.0.0.1:${port}/?replicaSet=testset`); expect(uri.split(',').length).toEqual(1); expect(utils.generateDbName).toHaveBeenCalledTimes(4); // once in "new MongoMemoryReplSet" (setter), once in "_startUpInstance", once in getUri await replSet.stop(); }); it('should be able to get dbName', async () => { const replSet = new MongoMemoryReplSet({ replSet: { dbName: 'static' } }); expect(replSet.replSetOpts.dbName).toEqual('static'); await replSet.stop(); }); it('should be possible to connect replicaset after waitUntilRunning resolves', async () => { const replSet = new MongoMemoryReplSet(); // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.init; const promise = replSet.waitUntilRunning(); // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.stopped; replSet.start(); await promise; const con = await MongoClient.connect(replSet.getUri(), { useNewUrlParser: true, useUnifiedTopology: true, }); await con.close(); await replSet.stop(); }); it('"new" should throw an error if replSet count is 0 or less', () => { try { new MongoMemoryReplSet({ replSet: { count: 0 } }); fail('Expected "new MongoMemoryReplSet" to throw an error'); } catch (err) { expect(err).toBeInstanceOf(ReplsetCountLowError); expect(err).toHaveProperty('count', 0); assertIsError(err); expect(err.message).toMatchSnapshot(); } }); it('"waitUntilRunning" should throw an error if _state is not "init"', async () => { const replSet = new MongoMemoryReplSet(); const timeout = setTimeout(() => { fail('Timeout - Expected "waitUntilRunning" to throw'); }, 100); try { await replSet.waitUntilRunning(); fail('Expected "waitUntilRunning" to throw'); } catch (err) { clearTimeout(timeout); expect(err).toBeInstanceOf(StateError); assertIsError(err); expect(err.message).toMatchSnapshot(); } }); it('"getUri" should throw an error if _state is not "running" or "init"', async () => { const replSet = new MongoMemoryReplSet(); const timeout = setTimeout(() => { fail('Timeout - Expected "getUri" to throw'); }, 100); // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.init; replSet.getUri(); // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.running; replSet.getUri(); // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.stopped; try { replSet.getUri(); fail('Expected "getUri" to throw'); } catch (err) { clearTimeout(timeout); expect(err).toBeInstanceOf(StateError); assertIsError(err); expect(err.message).toMatchSnapshot(); } }); it('"start" should throw an error if _state is not "stopped"', async () => { const replSet = new MongoMemoryReplSet(); const timeout = setTimeout(() => { fail('Timeout - Expected "start" to throw'); }, 100); // this case can normally happen if "start" is called again, without either an error or "stop" happened // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.running; // artificially set this to running try { await replSet.start(); fail('Expected "start" to throw'); } catch (err) { clearTimeout(timeout); expect(err).toBeInstanceOf(StateError); assertIsError(err); expect(err.message).toMatchSnapshot(); } }); it('start an replset with instanceOpts', async () => { const replSet = new MongoMemoryReplSet({ instanceOpts: [ { args: ['--quiet'], replicaMemberConfig: { priority: 2, }, }, ], }); await replSet.start(); expect( replSet.servers[0].opts.instance!.args!.findIndex((x) => x === '--quiet') > -1 ).toBeTruthy(); expect(replSet.servers[0].opts.instance?.replicaMemberConfig?.priority).toBe(2); await replSet.stop(); }); it('"waitUntilRunning" should return if state is "running"', async () => { const replSet = new MongoMemoryReplSet(); jest.spyOn(replSet, 'once'); // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.running; // artificially set this to running to not actually have to start an server (test-speedup) await replSet.waitUntilRunning(); expect(replSet.once).not.toHaveBeenCalled(); }); it('"_initReplSet" should throw an error if _state is not "init"', async () => { const replSet = new MongoMemoryReplSet(); const timeout = setTimeout(() => { fail('Timeout - Expected "_initReplSet" to throw'); }, 100); // this case can normally happen if "start" is called again, without either an error or "stop" happened // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.running; // artificially set this to running try { // @ts-expect-error because "_initReplSet" is protected await replSet._initReplSet(); fail('Expected "_initReplSet" to throw'); } catch (err) { clearTimeout(timeout); expect(err).toBeInstanceOf(StateError); assertIsError(err); expect(err.message).toMatchSnapshot(); } }); it('"_initReplSet" should throw if server count is 0 or less', async () => { const replSet = new MongoMemoryReplSet(); const timeout = setTimeout(() => { fail('Timeout - Expected "_initReplSet" to throw'); }, 100); // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.init; // artificially set this to init try { // @ts-expect-error because "_initReplSet" is protected await replSet._initReplSet(); fail('Expected "_initReplSet" to throw'); } catch (err) { clearTimeout(timeout); assertIsError(err); expect(err.message).toMatchSnapshot(); } }); it('should make use of "AutomaticAuth" (ephemeralForTest)', async () => { // @ts-expect-error because "initAllServers" is protected jest.spyOn(MongoMemoryReplSet.prototype, 'initAllServers'); jest.spyOn(console, 'warn').mockImplementationOnce(() => void 0); const replSet = await MongoMemoryReplSet.create({ replSet: { auth: {}, count: 3, storageEngine: 'ephemeralForTest' }, }); utils.assertion(!utils.isNullOrUndefined(replSet.replSetOpts.auth)); utils.assertion(typeof replSet.replSetOpts.auth === 'object'); utils.assertion(!utils.isNullOrUndefined(replSet.replSetOpts.auth.customRootName)); utils.assertion(!utils.isNullOrUndefined(replSet.replSetOpts.auth.customRootPwd)); const con: MongoClient = await MongoClient.connect(replSet.getUri(), { useNewUrlParser: true, useUnifiedTopology: true, authSource: 'admin', authMechanism: 'SCRAM-SHA-256', auth: { user: replSet.replSetOpts.auth.customRootName, password: replSet.replSetOpts.auth.customRootPwd, }, }); const db = con.db('admin'); const users: { users: { user: string }[] } = await db.command({ usersInfo: replSet.replSetOpts.auth.customRootName, }); expect(users.users).toHaveLength(1); expect(users.users[0].user).toEqual(replSet.replSetOpts.auth.customRootName); // @ts-expect-error because "initAllServers" is protected expect(MongoMemoryReplSet.prototype.initAllServers).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledTimes(1); { expect(replSet.servers[0].instanceInfo?.instance.instanceOpts.auth).toStrictEqual(false); expect(replSet.servers[1].instanceInfo?.instance.instanceOpts.auth).toStrictEqual(false); expect(replSet.servers[2].instanceInfo?.instance.instanceOpts.auth).toStrictEqual(false); } await con.close(); await replSet.stop(); }); it('should make use of "AutomaticAuth" (wiredTiger)', async () => { // @ts-expect-error because "initAllServers" is protected jest.spyOn(MongoMemoryReplSet.prototype, 'initAllServers'); const replSet = await MongoMemoryReplSet.create({ replSet: { auth: {}, count: 3, storageEngine: 'wiredTiger' }, }); utils.assertion(!utils.isNullOrUndefined(replSet.replSetOpts.auth)); utils.assertion(typeof replSet.replSetOpts.auth === 'object'); utils.assertion(!utils.isNullOrUndefined(replSet.replSetOpts.auth.customRootName)); utils.assertion(!utils.isNullOrUndefined(replSet.replSetOpts.auth.customRootPwd)); const con: MongoClient = await MongoClient.connect(replSet.getUri(), { useNewUrlParser: true, useUnifiedTopology: true, authSource: 'admin', authMechanism: 'SCRAM-SHA-256', auth: { user: replSet.replSetOpts.auth.customRootName, password: replSet.replSetOpts.auth.customRootPwd, }, }); const db = con.db('admin'); const users: { users: { user: string }[] } = await db.command({ usersInfo: replSet.replSetOpts.auth.customRootName, }); expect(users.users).toHaveLength(1); expect(users.users[0].user).toEqual(replSet.replSetOpts.auth.customRootName); // @ts-expect-error because "initAllServers" is protected expect(MongoMemoryReplSet.prototype.initAllServers).toHaveBeenCalledTimes(2); { expect(replSet.servers[0].instanceInfo?.instance.instanceOpts.auth).toStrictEqual(true); expect(replSet.servers[1].instanceInfo?.instance.instanceOpts.auth).toStrictEqual(true); expect(replSet.servers[2].instanceInfo?.instance.instanceOpts.auth).toStrictEqual(true); } await con.close(); await replSet.stop(); }); }); describe('MongoMemoryReplSet', () => { describe('getters & setters', () => { let replSet: MongoMemoryReplSet; beforeEach(() => { replSet = new MongoMemoryReplSet(); }); it('"get state" should match "_state"', () => { // @ts-expect-error because "_state" is protected expect(replSet.state).toEqual(replSet._state); expect(replSet.state).toEqual(MongoMemoryReplSetStates.stopped); // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.init; // @ts-expect-error because "_state" is protected expect(replSet.state).toEqual(replSet._state); expect(replSet.state).toEqual(MongoMemoryReplSetStates.init); }); it('"binaryOpts" should match "_binaryOpts"', () => { // @ts-expect-error because "_binaryOpts" is protected expect(replSet.binaryOpts).toEqual(replSet._binaryOpts); expect(replSet.binaryOpts).toEqual({}); replSet.binaryOpts = { arch: 'x86_64' }; // @ts-expect-error because "_binaryOpts" is protected expect(replSet.binaryOpts).toEqual(replSet._binaryOpts); expect(replSet.binaryOpts).toEqual({ arch: 'x86_64' }); }); it('"instanceOpts" should match "_instanceOpts"', () => { // @ts-expect-error because "_instanceOpts" is protected expect(replSet.instanceOpts).toEqual(replSet._instanceOpts); expect(replSet.instanceOpts).toEqual([]); replSet.instanceOpts = [{ port: 1001 }]; // @ts-expect-error because "_instanceOpts" is protected expect(replSet.instanceOpts).toEqual(replSet._instanceOpts); expect(replSet.instanceOpts).toEqual([{ port: 1001 }]); expect(replSet.instanceOpts).toHaveLength(1); }); it('"replSetOpts" should match "_replSetOpts"', () => { // @ts-expect-error because "_replSetOpts" is protected expect(replSet.replSetOpts).toEqual(replSet._replSetOpts); expect(replSet.replSetOpts).toEqual({ auth: false, args: [], name: 'testset', count: 1, dbName: replSet.replSetOpts.dbName, // not testing this value, because its generated "randomly" ip: '127.0.0.1', spawn: {}, storageEngine: 'ephemeralForTest', configSettings: {}, }); replSet.replSetOpts = { auth: true }; // @ts-expect-error because "_replSetOpts" is protected expect(replSet.replSetOpts).toEqual(replSet._replSetOpts); expect(replSet.replSetOpts).toEqual({ auth: true, args: [], name: 'testset', count: 1, dbName: replSet.replSetOpts.dbName, // not testing this value, because its generated "randomly" ip: '127.0.0.1', spawn: {}, storageEngine: 'ephemeralForTest', configSettings: {}, }); }); describe('state errors', () => { beforeEach(() => { // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.init; }); it('setter of "binaryOpts" should throw an error if state is not "stopped"', () => { try { replSet.binaryOpts = {}; fail('Expected assignment of "replSet.binaryOpts" to fail'); } catch (err) { expect(err).toBeInstanceOf(StateError); assertIsError(err); expect(err.message).toMatchSnapshot(); } }); it('setter of "instanceOpts" should throw an error if state is not "stopped"', () => { try { replSet.instanceOpts = []; fail('Expected assignment of "replSet.instanceOpts" to fail'); } catch (err) { expect(err).toBeInstanceOf(StateError); assertIsError(err); expect(err.message).toMatchSnapshot(); } }); it('setter of "replSetOpts" should throw an error if state is not "stopped"', () => { try { replSet.replSetOpts = {}; fail('Expected assignment of "replSet.instanceOpts" to fail'); } catch (err) { expect(err).toBeInstanceOf(StateError); assertIsError(err); expect(err.message).toMatchSnapshot(); } }); }); it('setter of "replSetOpts" should throw an error if count is 1 or above', () => { try { replSet.replSetOpts = { count: 0 }; fail('Expected assignment of "replSet.instanceOpts" to fail'); } catch (err) { expect(err).toBeInstanceOf(ReplsetCountLowError); expect(err).toHaveProperty('count', 0); assertIsError(err); expect(err.message).toMatchSnapshot(); } }); }); it('"stop" should return "false" if an error got thrown', async () => { // this test creates an mock-instance, so that no actual instance gets started const replSet = new MongoMemoryReplSet(); // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.running; const instance = new MongoMemoryServer(); jest.spyOn(instance, 'stop').mockRejectedValueOnce(new Error('Some Error')); replSet.servers = [instance]; expect(await replSet.stop()).toEqual(false); expect(instance.stop).toBeCalledTimes(1); }); it('"_waitForPrimary" should throw an error if timeout is reached', async () => { const replSet = new MongoMemoryReplSet(); try { // @ts-expect-error because "_waitForPrimary" is protected await replSet._waitForPrimary(1); // 1ms to be fast (0 and 1 are equal for "setTimeout" in js) fail('Expected "_waitForPrimary" to throw'); } catch (err) { expect(err).toBeInstanceOf(WaitForPrimaryTimeoutError); expect(JSON.stringify(err)).toMatchSnapshot(); // this is to test all the custom values on the error } }); it('"getInstanceOpts" should return "storageEngine" if in baseOpts', () => { const replSet = new MongoMemoryReplSet(); expect( // @ts-expect-error because "getInstanceOpts" is protected replSet.getInstanceOpts({ storageEngine: 'wiredTiger' }) ).toMatchObject<MongoMemoryInstanceOpts>({ // this is needed, otherwise no ts error when "storageEngine" might get changed storageEngine: 'wiredTiger', }); }); it('"cleanup" should run cleanup on all instances', async () => { const replSet = await MongoMemoryReplSet.create({ replSet: { count: 1 } }); const instance = replSet.servers[0]; const dbPath = instance.instanceInfo!.dbPath; jest.spyOn(instance, 'cleanup'); expect(await utils.statPath(dbPath)).toBeTruthy(); await replSet.stop(false); expect(await utils.statPath(dbPath)).toBeTruthy(); await replSet.cleanup(); expect(await utils.statPath(dbPath)).toBeFalsy(); expect(instance.cleanup).toHaveBeenCalledTimes(1); }); it('"waitUntilRunning" should clear stateChange listener', async () => { const replSet = new MongoMemoryReplSet(); // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.init; const promise = replSet.waitUntilRunning(); await utils.ensureAsync(); // ensure that "waitUntilRunning" has executed and setup the listener // @ts-expect-error because "_state" is protected replSet._state = MongoMemoryReplSetStates.stopped; expect(replSet.listeners(MongoMemoryReplSetEvents.stateChange).length).toEqual(1); replSet.start(); await promise; expect(replSet.listeners(MongoMemoryReplSetEvents.stateChange).length).toEqual(0); await replSet.stop(); }); });
the_stack
import { bundledModulesDirName, getStore, isServer, moduleLibBuildFileName, moduleMainBuildFileName, moduleMetaInfoFileName, moduleNodeBuildFileName, TCromwellNodeModules, TScriptMetaInfo, } from '@cromwell/core'; import { fetch } from './isomorphicFetch'; /** * Bundled node modules (Frontend dependencies) loading script */ export class Importer implements Required<TCromwellNodeModules> { public importStatuses = {}; public imports = {}; public moduleExternals = {}; public scriptStatuses = {}; public modules: Record<string, any>; public canShowInfo = false; public prefix: string; public hasBeenExecuted = false; private serverPublicDir?: string; private normalizePath: any; private nodeRequire: any; private resolve: any; private isServerSide = false; private log = (...args) => this.canShowInfo && console.log(args); // eslint-disable-line no-console constructor() { this.isServerSide = isServer(); const checkLib = (store, libName) => { if (!store[libName]) { store[libName] = { libName, }; } } this.modules = new Proxy({}, { get(obj, prop) { // checkLib(obj, prop); return obj[prop]; }, set(obj, prop, value) { checkLib(obj, prop); if (typeof value === 'object' && !value['default']) { value = { ...value, default: obj[prop]['default'] ?? obj[prop], } } // console.log('Set lib: ' + String(prop), obj[prop], 'new value: ', value); if (typeof value === 'object') { obj[prop] = Object.assign(obj[prop], value); } else if (typeof value === 'function') { obj[prop] = value; value.default = value; } else { obj[prop] = Object.assign(obj[prop], { default: value }); } return true; } }); } public setPrefix = (prefix) => this.prefix = prefix; public setServerPublicDir = (dir) => this.serverPublicDir = dir; public setIsServerSide = (isServerSide) => this.isServerSide = isServerSide; /** * Import single module with its dependencies * @param moduleName * @param namedExports * @returns */ public importModule(moduleName, namedExports = ['default']): Promise<boolean> | boolean { this.hasBeenExecuted = true; this.log('Cromwell:importer: importModule ' + moduleName + ' named: ' + namedExports); if (namedExports.includes('default')) { namedExports = ['default']; } const metaFilepath = `${this.prefix ? `${this.prefix}/` : ''}${bundledModulesDirName}/${moduleName}/${moduleMetaInfoFileName}`; const importerFilepath = `${this.prefix ? `/${this.prefix}` : ''}/${bundledModulesDirName}/${moduleName}/${moduleMainBuildFileName}`; const importerEntireLibFilepath = `${this.prefix ? `/${this.prefix}` : ''}/${bundledModulesDirName}/${moduleName}/${moduleLibBuildFileName}`; const importerNodeFilepath = `${bundledModulesDirName}/${moduleName}/${moduleNodeBuildFileName}`; let moduleVer: string | undefined; if (/@\d+\.\d+\.\d+/.test(moduleName)) { const modChunks = moduleName.split('@'); moduleVer = modChunks.pop(); moduleName = modChunks.join('@'); } this.log('moduleName', moduleName, 'moduleVer', moduleVer) if (this.isServerSide) { try { return this.serverImport({ moduleName, metaFilepath, importerNodeFilepath, }) } catch (error) { console.error(error); } return false; } else { return this.browserImport({ moduleName, moduleVer, metaFilepath, importerNodeFilepath, namedExports, importerEntireLibFilepath, importerFilepath, }).then(success => { this.log('Cromwell:importer: Processed module: ' + moduleName, success); return success; }); } } /** * Server-side import. Sync, require() */ private serverImport(options: { moduleName: string; metaFilepath: string; importerNodeFilepath: string; }) { const { moduleName, metaFilepath, importerNodeFilepath } = options; if (this.importStatuses[moduleName]) return true; if (!this.normalizePath) this.normalizePath = eval(`require('normalize-path');`); if (!this.nodeRequire) this.nodeRequire = (name) => eval(`require('${this.normalizePath(name)}');`); if (!this.resolve) this.resolve = this.nodeRequire('path').resolve; try { // Try to require from bundled modules try { const fullPath = this.resolve(this.serverPublicDir ? this.serverPublicDir : this.resolve(process.cwd(), 'public'), metaFilepath); const metaInfo: TScriptMetaInfo = this.nodeRequire(fullPath); // { [moduleName]: namedExports } if (metaInfo) this.importScriptExternals(metaInfo); } catch (e) { console.error('Cromwell:importer: Failed to require meta info of module server-side: ' + metaFilepath, e); } try { const fullPath = this.resolve(this.serverPublicDir ? this.serverPublicDir : this.resolve(process.cwd(), 'public'), importerNodeFilepath); this.nodeRequire(fullPath); const mock = Function('require', "return require('mock-require/index');")(this.nodeRequire) const reqModule = this.modules?.[moduleName]; if (!reqModule) throw new Error('!reqModule'); this.modules[moduleName] = reqModule; this.importStatuses[moduleName] = 'default'; mock(moduleName, reqModule); } catch (e) { console.error('Cromwell:importer: Failed to require module server-side: ' + importerNodeFilepath, e); this.importStatuses[moduleName] = 'failed'; throw new Error(); } } catch (e) { // If failed, try to use Node.js resolution const reqModule = this.nodeRequire(moduleName); this.log('reqModule: ' + moduleName + ' keys: ' + Object.keys(reqModule).length); this.modules[moduleName] = reqModule; this.importStatuses[moduleName] = 'default'; } this.log('Cromwell:importer: Successfully loaded module: ' + moduleName); return true; } /** * Browser-side import. Async, fetch */ private browserImport = async (options: { moduleName: string; moduleVer: string | undefined; metaFilepath: string; importerNodeFilepath: string; namedExports: string[]; importerEntireLibFilepath: string; importerFilepath: string; }): Promise<boolean> => { const { moduleName, moduleVer, metaFilepath, namedExports, importerEntireLibFilepath, importerFilepath } = options; let isDefaultImport = false; let isLibImport = false; if (namedExports.includes('default')) { isDefaultImport = true; } const useImporter = async (namedExport: string): Promise<boolean> => { if (!this.imports?.[moduleName]?.[namedExport]) { console.error(`loading:!Cromwell.imports[moduleName][namedExport]: import {${namedExport}} from ${moduleName}`); return false; } try { await this.imports[moduleName][namedExport](); return true; } catch (error) { console.error(`Cromwell:importer: An error occurred while loading the library: import { ${namedExport} } from '${moduleName}'`, error); return false; } return false; } const importAllNamed = async (): Promise<boolean[]> => { if (isLibImport) { return [true]; } const promises: Promise<boolean>[] = []; namedExports.forEach(named => { promises.push(useImporter(named)); }); const success = await Promise.all(promises); return success; } // Module has been requested for the first time. Load main importer script of the module. if (!this.importStatuses[moduleName]) { if (isDefaultImport) isLibImport = true; const scriptId = `${moduleName}@${moduleVer}-main-module-importer`; if (document.getElementById(scriptId)) return true; let onLoad; const importPromise = new Promise<"failed" | "ready" | "default">(done => onLoad = done); this.importStatuses[moduleName] = importPromise; // Load meta and externals if it has any try { const metaInfoStr = await fetch(`/${metaFilepath}`).then(res => res.text()); if (metaInfoStr) { const metaInfo: TScriptMetaInfo = JSON.parse(metaInfoStr); // { [moduleName]: namedExports } if (metaInfo) { if (metaInfo.import === 'lib') { isLibImport = true; } await this.importScriptExternals?.(metaInfo); this.log('Cromwell:importer: Successfully loaded all script externals for module: ' + moduleName, metaInfo); } } else { throw new Error('Failed to fetch file: /' + metaFilepath) } } catch (e) { console.error('Cromwell:importer: Failed to load meta info about importer of the module: ' + moduleName, e); } const filePath = isLibImport ? importerEntireLibFilepath : importerFilepath; try { const success = await new Promise(done => { const domScript = document.createElement('script'); domScript.id = scriptId; domScript.src = filePath; domScript.onload = () => done(true); domScript.onerror = (e) => { console.error('Cromwell:importer: Failed to load importer for module: ' + moduleName, e); done(false); } document.head.appendChild(domScript); }); if (!success) throw new Error(''); this.log(`Cromwell:importer: Importer for module "${moduleName}" executed`); if (isLibImport && this.modules?.[moduleName]) { this.imports[moduleName] = { 'default': () => null } as any; } this.log(`Cromwell:importer: isLibImport:`, isLibImport, 'Cromwell?.modules?.[moduleName]', this.modules?.[moduleName], ' Cromwell.imports[moduleName] ', this.imports[moduleName]); } catch (e) { console.error('Cromwell:importer: Failed to execute importer for module: ' + moduleName, e); this.importStatuses[moduleName] = 'failed'; onLoad('failed'); return false; } if (!this.imports[moduleName]) { console.error('Cromwell:importer: Failed to load importer for module: ' + moduleName); this.importStatuses[moduleName] = 'failed'; onLoad('failed'); return false; } this.log('Cromwell:importer: Successfully loaded importer for module: ' + moduleName); const success = await importAllNamed(); if (success.includes(false)) { console.error('Cromwell:importer: Failed to import one of named exports'); this.importStatuses[moduleName] = 'failed'; onLoad('failed'); return false; } else { this.log('Cromwell:importer: All initially requested named exports for module "' + moduleName + '" have been successfully loaded', namedExports); } if (isLibImport) { this.importStatuses[moduleName] = 'default'; onLoad('default'); } else { this.importStatuses[moduleName] = 'ready'; onLoad('ready'); } return true; } // check if this module is being imported by another async request // await for another and then start const importWithCheck = async () => { if (typeof this.importStatuses?.[moduleName] === 'object') { this.log('awaiting... ' + moduleName); const status = await this.importStatuses[moduleName]; if (status === 'default') return true; await importWithCheck(); } if (this.importStatuses?.[moduleName] === 'default') { return true; } if (typeof this.importStatuses[moduleName] === 'string') { if (!this.imports?.[moduleName]) throw new Error('ready:!Cromwell.imports[moduleName]' + moduleName); const lastStatus = this.importStatuses[moduleName]; let onLoad; const importPromise = new Promise<"failed" | "ready" | "default">(done => onLoad = done); this.importStatuses[moduleName] = importPromise; const success = await importAllNamed(); this.importStatuses[moduleName] = lastStatus; if (success.includes(false)) onLoad(lastStatus); else onLoad(lastStatus); return true; } return false; } return importWithCheck(); } public async importScriptExternals(metaInfo: TScriptMetaInfo | undefined): Promise<boolean> { this.hasBeenExecuted = true; this.log('Cromwell:importScriptExternals: ' + metaInfo?.name, metaInfo); const externals = metaInfo?.externalDependencies; if (!metaInfo || !externals) return false; if (metaInfo.name && typeof this.scriptStatuses[metaInfo.name] === 'object') { await this.scriptStatuses[metaInfo.name]; return true; } if (metaInfo.name && typeof this.scriptStatuses[metaInfo.name] === 'string') return true; if (metaInfo.name && this.modules?.[metaInfo.name]) { this.scriptStatuses[metaInfo.name] = 'failed'; return true; } if (typeof externals === 'object' && Object.keys(externals).length > 0) { this.log('Cromwell:importer: module ' + metaInfo.name + ' has externals: ' + JSON.stringify(externals, null, 4)); this.log('Cromwell:importer: loading externals first for module ' + metaInfo.name + ' ...'); const promises: Promise<boolean>[] = [] let success: boolean[] | undefined; Object.keys(externals).forEach(ext => { const result = this?.importModule?.(ext, externals[ext]); if (result !== undefined) { if (typeof result === 'object') { result.catch(e => { console.error('Cromwell:importer: Failed to load external ' + ext + ' for module: ' + metaInfo.name, e); }); promises.push(result); } else if (typeof result === 'boolean') { if (!success) success = []; success.push(result); } } }); try { if (!this.isServerSide) { success = await Promise.all(promises); } } catch (e) { console.error('Cromwell:importer: Failed to load externals for module: ' + metaInfo.name, e); } let successNum = 0; if (success) { success.forEach(s => s && successNum++); } this.log(`Cromwell:importer: ${successNum}/${Object.keys(externals).length} externals for module ${metaInfo.name} have been loaded`); if (metaInfo.name) this.scriptStatuses[metaInfo.name] = 'ready'; if (success && !success.includes(false)) return true; return true; } if (metaInfo.name) this.scriptStatuses[metaInfo.name] = 'failed'; return false; } } export const getModuleImporter = (serverPublicDir?: string, serverSide?: boolean): Importer => { const store = getStore(); const importer: Importer = store.nodeModules as Importer ?? new Importer(); if (!store.nodeModules) store.nodeModules = importer; if (serverPublicDir) { importer.setServerPublicDir(serverPublicDir); } if (typeof serverSide === 'boolean') { importer.setIsServerSide(serverSide); } return importer; }
the_stack
import { EventEmitter } from "events"; import PluginSDK, { Hooks } from "PluginSDK"; import { DCOS_CHANGE, MESOS_SUMMARY_CHANGE } from "../constants/EventTypes"; import { MARATHON_DEPLOYMENTS_CHANGE, MARATHON_GROUPS_CHANGE, MARATHON_QUEUE_CHANGE, MARATHON_SERVICE_VERSION_CHANGE, MARATHON_SERVICE_VERSIONS_CHANGE, } from "../../../plugins/services/src/js/constants/EventTypes"; import DeclinedOffersUtil from "../../../plugins/services/src/js/utils/DeclinedOffersUtil"; import DeploymentsList from "../../../plugins/services/src/js/structs/DeploymentsList"; import Item from "../structs/Item"; import Framework from "../../../plugins/services/src/js/structs/Framework"; import MarathonStore from "../../../plugins/services/src/js/stores/MarathonStore"; import MesosSummaryStore from "./MesosSummaryStore"; import NotificationStore from "./NotificationStore"; import ServiceTree from "../../../plugins/services/src/js/structs/ServiceTree"; import SummaryList from "../structs/SummaryList"; const EVENT_DEBOUNCE_TIME = 250; const events = { change: DCOS_CHANGE }; class DCOSStore extends EventEmitter { data = { marathon: { serviceTree: new ServiceTree(), queue: new Map(), deploymentsList: new DeploymentsList(), versions: new Map(), dataReceived: false, }, mesos: new SummaryList(), }; debouncedEvents = new Map(); constructor(...args) { super(...args); PluginSDK.addStoreConfig({ store: this, storeID: this.storeID, events, unmountWhen: () => false, }); } getTotalListenerCount() { return Object.values(events).reduce( (memo, name) => memo + this.listeners(name).length, 0 ); } getProxyListeners() { let proxyListeners = []; if (Hooks.applyFilter("hasCapability", false, "mesosAPI")) { proxyListeners.push({ event: MESOS_SUMMARY_CHANGE, handler: this.onMesosSummaryChange, store: MesosSummaryStore, }); } if (Hooks.applyFilter("hasCapability", false, "marathonAPI")) { proxyListeners = proxyListeners.concat([ { event: MARATHON_DEPLOYMENTS_CHANGE, handler: this.onMarathonDeploymentsChange, store: MarathonStore, }, { event: MARATHON_GROUPS_CHANGE, handler: this.onMarathonGroupsChange, store: MarathonStore, }, { event: MARATHON_QUEUE_CHANGE, handler: this.onMarathonQueueChange, store: MarathonStore, }, { event: MARATHON_SERVICE_VERSION_CHANGE, handler: this.onMarathonServiceVersionChange, store: MarathonStore, }, { event: MARATHON_SERVICE_VERSIONS_CHANGE, handler: this.onMarathonServiceVersionsChange, store: MarathonStore, }, ]); } return proxyListeners; } /** * Fetch service version/configuration from Marathon * @param {string} serviceID * @param {string} versionID */ fetchServiceVersion(serviceID, versionID) { MarathonStore.fetchServiceVersion(serviceID, versionID); } /** * Fetch service versions/configurations from Marathon * @param {string} serviceID */ fetchServiceVersions(serviceID) { MarathonStore.fetchServiceVersions(serviceID); } onMarathonDeploymentsChange = () => { if (!this.data.marathon.dataReceived) { return; } const deploymentsList = MarathonStore.get("deployments"); const serviceTree = MarathonStore.get("groups"); const deploymentListLength = deploymentsList.getItems().length; const currentDeploymentCount = NotificationStore.getNotificationCount( "services-deployments" ); if (deploymentListLength !== currentDeploymentCount) { NotificationStore.addNotification( "services-deployments", "deployment-count", deploymentListLength ); } // Populate deployments with affected services this.data.marathon.deploymentsList = deploymentsList.mapItems( (deployment) => { const ids = deployment.getAffectedServiceIds(); const services = ids.reduce( (memo, id) => { const service = serviceTree.findItemById(id); if (service != null) { memo.affected.push(service); } else { memo.stale.push(id); } return memo; }, { affected: [], stale: [] } ); return { affectedServices: services.affected, staleServiceIds: services.stale, ...deployment, }; } ); this.clearServiceTreeCache(); this.emit(DCOS_CHANGE); }; emit(eventType) { // Debounce specified events if ([DCOS_CHANGE].includes(eventType)) { clearTimeout(this.debouncedEvents.get(eventType)); this.debouncedEvents.set( eventType, setTimeout(super.emit.bind(this, ...arguments), EVENT_DEBOUNCE_TIME) ); return; } super.emit(eventType); } onMarathonGroupsChange = () => { const serviceTree = MarathonStore.get("groups"); if (!(serviceTree instanceof ServiceTree)) { return; } const { marathon } = this.data; // Update service tree and data received flag marathon.serviceTree = serviceTree; marathon.dataReceived = true; // Populate deployments with services data immediately this.onMarathonDeploymentsChange(); this.clearServiceTreeCache(); this.emit(DCOS_CHANGE); }; onMarathonQueueChange = (nextQueue) => { const { marathon: { queue }, } = this.data; const queuedAppIDs = []; nextQueue.forEach((entry) => { if (entry.app == null && entry.pod == null) { return; } let id = null; if (entry.pod != null) { id = entry.pod.id; } else { id = entry.app.id; } entry.declinedOffers = { summary: DeclinedOffersUtil.getSummaryFromQueue(entry), offers: DeclinedOffersUtil.getOffersFromQueue(entry), }; queuedAppIDs.push(id); queue.set(id, entry); }); queue.forEach((entry) => { let id = null; if (entry.pod != null) { id = entry.pod.id; } else { id = entry.app.id; } if (queuedAppIDs.indexOf(id) === -1) { queue.delete(id); } }); this.clearServiceTreeCache(); this.emit(DCOS_CHANGE); }; onMarathonServiceVersionChange = (event) => { const { serviceID, versionID, version } = event; const { marathon: { versions }, } = this.data; let currentVersions = versions.get(serviceID); if (!currentVersions) { currentVersions = new Map(); versions.set(serviceID, currentVersions); } currentVersions.set(versionID, version); this.clearServiceTreeCache(); this.emit(DCOS_CHANGE); }; onMarathonServiceVersionsChange = (event) => { let { serviceID, versions: nextVersions } = event; const { marathon: { versions }, } = this.data; const currentVersions = versions.get(serviceID); if (currentVersions) { nextVersions = new Map([...nextVersions, ...currentVersions]); } versions.set(serviceID, nextVersions); this.clearServiceTreeCache(); this.emit(DCOS_CHANGE); }; onMesosSummaryChange = () => { const states = MesosSummaryStore.get("states"); if (!(states instanceof SummaryList)) { return; } this.data.mesos = states; this.clearServiceTreeCache(); this.emit(DCOS_CHANGE); }; addProxyListeners() { this.getProxyListeners().forEach((item) => { item.store.addChangeListener(item.event, item.handler); }); } removeProxyListeners() { this.getProxyListeners().forEach((item) => { item.store.removeChangeListener(item.event, item.handler); }); } addChangeListener(eventName, callback) { this.on(eventName, callback); } removeChangeListener(eventName, callback) { this.removeListener(eventName, callback); } /** * Adds the listener for the specified event * @param {string} eventName * @param {Function} callback * @return {DCOSStore} DCOSStore instance * @override */ on(eventName, callback) { // Only add proxy listeners if not already listening if (this.getTotalListenerCount() === 0) { this.addProxyListeners(); } return super.on(eventName, callback); } /** * Remove the specified listener for the specified event * @param {string} eventName * @param {Function} callback * @return {DCOSStore} DCOSStore instance * @override */ removeListener(eventName, callback) { super.removeListener(eventName, callback); // Remove proxy listeners if no one is listening if (this.getTotalListenerCount() === 0) { this.removeProxyListeners(); } return this; } /** * @type {DeploymentsList} */ get deploymentsList() { return this.data.marathon.deploymentsList; } /** * @type {ServiceTree} */ get serviceTree() { if (!this._serviceTree) { this.serviceTree = this.buildServiceTree(); } return this._serviceTree; } set serviceTree(newValue) { this._serviceTree = newValue; } clearServiceTreeCache() { this.serviceTree = null; this._flatServiceTree = null; } buildServiceTree() { const { marathon: { serviceTree, queue, versions }, mesos, } = this.data; // Create framework dict from Mesos data const frameworks = mesos .lastSuccessful() .getServiceList() .reduceItems((memo, framework) => { if (framework instanceof Item) { memo[`/${framework.get("name")}`] = framework.get(); } return memo; }, {}); // Merge data by framework name, as Marathon doesn't know framework ids. return serviceTree.mapItems((item) => { if (item instanceof ServiceTree) { return item; } const serviceId = item.getId(); let options = { versions: versions.get(serviceId), queue: queue.get(serviceId), }; if (item instanceof Framework) { options = { ...options, ...frameworks[item.getId()] }; } if (item instanceof Item) { return new item.constructor({ ...options, ...item.get() }); } return new item.constructor({ ...options, ...item }); }); } get taskLookupTable() { if (!this._flatServiceTree) { this._flatServiceTree = this.buildFlatServiceTree(this.serviceTree); } return this._flatServiceTree; } buildFlatServiceTree(serviceTree) { return serviceTree.reduceItems((memo, item) => { if (item instanceof ServiceTree) { return memo; } if (item.tasks) { item.tasks.forEach((task) => { const taskData = { version: task.version, healthCheckResults: task.healthCheckResults, }; memo[task.id] = taskData; }); } return memo; }, {}); } get serviceDataReceived() { return this.data.marathon.dataReceived; } get storeID() { return "dcos"; } } export default new DCOSStore();
the_stack
/** * A collection's friendly name is defined by this field. You would want to set this field to a value that would allow you to easily identify this collection among a bunch of other collections, as such outlining its usage or content. */ export type NameOfTheCollection = string; /** * A Description can be a raw text, or be an object, which holds the description along with its format. */ export type DefinitionsDescription = Description | string | null; /** * Postman allows you to version your collections as they grow, and this field holds the version number. While optional, it is recommended that you use this field to its fullest extent! */ export type CollectionVersion = | { /** * Increment this number if you make changes to the collection that changes its behaviour. E.g: Removing or adding new test scripts. (partly or completely). */ major: number; /** * You should increment this number if you make changes that will not break anything that uses the collection. E.g: removing a folder. */ minor: number; /** * Ideally, minor changes to a collection should result in the increment of this number. */ patch: number; /** * A human friendly identifier to make sense of the version numbers. E.g: 'beta-3' */ identifier?: string; meta?: unknown; [k: string]: unknown; } | string; export type Items = Item | Folder; /** * Using variables in your Postman requests eliminates the need to duplicate requests, which can save a lot of time. Variables can be defined, and referenced to from any part of a request. */ export type Variable = Variable1 & Variable2; export type Variable1 = | { [k: string]: unknown; } | { [k: string]: unknown; } | { [k: string]: unknown; }; /** * Collection variables allow you to define a set of variables, that are a *part of the collection*, as opposed to environments, which are separate entities. * *Note: Collection variables must not contain any sensitive information.* */ export type VariableList = Variable[]; /** * If object, contains the complete broken-down URL for this request. If string, contains the literal request URL. */ export type Url = | { /** * The string representation of the request URL, including the protocol, host, path, hash, query parameter(s) and path variable(s). */ raw?: string; /** * The protocol associated with the request, E.g: 'http' */ protocol?: string; host?: Host; path?: | string | ( | string | { type?: string; value?: string; [k: string]: unknown; } )[]; /** * The port number present in this URL. An empty value implies 80/443 depending on whether the protocol field contains http/https. */ port?: string; /** * An array of QueryParams, which is basically the query string part of the URL, parsed into separate variables */ query?: QueryParam[]; /** * Contains the URL fragment (if any). Usually this is not transmitted over the network, but it could be useful to store this in some cases. */ hash?: string; /** * Postman supports path variables with the syntax `/path/:variableName/to/somewhere`. These variables are stored in this field. */ variable?: Variable1[]; [k: string]: unknown; } | string; /** * The host for the URL, E.g: api.yourdomain.com. Can be stored as a string or as an array of strings. */ export type Host = string | string[]; /** * Postman allows you to configure scripts to run when specific events occur. These scripts are stored here, and can be referenced in the collection by their ID. */ export type EventList = Event[]; /** * A request represents an HTTP request. If a string, the string is assumed to be the request URL and the method is assumed to be 'GET'. */ export type Request = Request1 | string; /** * A representation for a list of headers */ export type HeaderList = Header[]; export type FormParameter = | { key: string; value?: string; /** * When set to true, prevents this form data entity from being sent. */ disabled?: boolean; type?: 'text'; /** * Override Content-Type header of this form data entity. */ contentType?: string; description?: DefinitionsDescription; [k: string]: unknown; } | { key: string; src?: string | unknown[] | null; /** * When set to true, prevents this form data entity from being sent. */ disabled?: boolean; type?: 'file'; /** * Override Content-Type header of this form data entity. */ contentType?: string; description?: DefinitionsDescription; [k: string]: unknown; }; /** * The time taken by the request to complete. If a number, the unit is milliseconds. If the response is manually created, this can be set to `null`. */ export type ResponseTime = null | string | number; /** * Set of timing information related to request and response in milliseconds */ export type ResponseTimings = { [k: string]: unknown; } | null; export type Headers = Header1 | string | null; export type Header2 = string; /** * No HTTP request is complete without its headers, and the same is true for a Postman request. This field is an array containing all the headers. */ export type Header1 = (Header | Header2)[]; export type Responses = Response[]; export type Items1 = Item | Folder; export interface HttpsSchemaGetpostmanComJsonCollectionV200 { info: Information; /** * Items are the basic unit for a Postman collection. You can think of them as corresponding to a single API endpoint. Each Item has one request and may have multiple API responses associated with it. */ item: Items[]; event?: EventList; variable?: VariableList; auth?: null | Auth; protocolProfileBehavior?: ProtocolProfileBehavior; [k: string]: unknown; } /** * Detailed description of the info block */ export interface Information { name: NameOfTheCollection; /** * Every collection is identified by the unique value of this field. The value of this field is usually easiest to generate using a UID generator function. If you already have a collection, it is recommended that you maintain the same id since changing the id usually implies that is a different collection than it was originally. * *Note: This field exists for compatibility reasons with Collection Format V1.* */ _postman_id?: string; description?: DefinitionsDescription; version?: CollectionVersion; /** * This should ideally hold a link to the Postman schema that is used to validate this collection. E.g: https://schema.getpostman.com/collection/v1 */ schema: string; [k: string]: unknown; } export interface Description { /** * The content of the description goes here, as a raw string. */ content?: string; /** * Holds the mime type of the raw description content. E.g: 'text/markdown' or 'text/html'. * The type is used to correctly render the description when generating documentation, or in the Postman app. */ type?: string; /** * Description can have versions associated with it, which should be put in this property. */ version?: { [k: string]: unknown; }; [k: string]: unknown; } /** * Items are entities which contain an actual HTTP request, and sample responses attached to it. */ export interface Item { /** * A unique ID that is used to identify collections internally */ id?: string; /** * A human readable identifier for the current item. */ name?: string; description?: DefinitionsDescription; variable?: VariableList; event?: EventList; request: Request; response?: Responses; protocolProfileBehavior?: ProtocolProfileBehavior; [k: string]: unknown; } export interface Variable2 { /** * A variable ID is a unique user-defined value that identifies the variable within a collection. In traditional terms, this would be a variable name. */ id?: string; /** * A variable key is a human friendly value that identifies the variable within a collection. In traditional terms, this would be a variable name. */ key?: string; /** * The value that a variable holds in this collection. Ultimately, the variables will be replaced by this value, when say running a set of requests from a collection */ value?: { [k: string]: unknown; }; /** * A variable may have multiple types. This field specifies the type of the variable. */ type?: 'string' | 'boolean' | 'any' | 'number'; /** * Variable name */ name?: string; description?: DefinitionsDescription; /** * When set to true, indicates that this variable has been set by Postman */ system?: boolean; disabled?: boolean; [k: string]: unknown; } /** * Defines a script associated with an associated event name */ export interface Event { /** * A unique identifier for the enclosing event. */ id?: string; /** * Can be set to `test` or `prerequest` for test scripts or pre-request scripts respectively. */ listen: string; script?: Script; /** * Indicates whether the event is disabled. If absent, the event is assumed to be enabled. */ disabled?: boolean; [k: string]: unknown; } /** * A script is a snippet of Javascript code that can be used to to perform setup or teardown operations on a particular response. */ export interface Script { /** * A unique, user defined identifier that can be used to refer to this script from requests. */ id?: string; /** * Type of the script. E.g: 'text/javascript' */ type?: string; exec?: string[] | string; src?: Url; /** * Script name */ name?: string; [k: string]: unknown; } export interface QueryParam { key?: string | null; value?: string | null; /** * If set to true, the current query parameter will not be sent with the request. */ disabled?: boolean; description?: DefinitionsDescription; [k: string]: unknown; } export interface Request1 { url?: Url; auth?: null | Auth; proxy?: ProxyConfig; certificate?: Certificate; method?: | ( | 'GET' | 'PUT' | 'POST' | 'PATCH' | 'DELETE' | 'COPY' | 'HEAD' | 'OPTIONS' | 'LINK' | 'UNLINK' | 'PURGE' | 'LOCK' | 'UNLOCK' | 'PROPFIND' | 'VIEW' ) | string; description?: DefinitionsDescription; header?: HeaderList | string; body?: { /** * Postman stores the type of data associated with this request in this field. */ mode?: 'raw' | 'urlencoded' | 'formdata' | 'file' | 'graphql'; raw?: string; urlencoded?: UrlEncodedParameter[]; formdata?: FormParameter[]; file?: { src?: string | null; content?: string; [k: string]: unknown; }; graphql?: { [k: string]: unknown; }; /** * Additional configurations and options set for various body modes. */ options?: { [k: string]: unknown; }; /** * When set to true, prevents request body from being sent. */ disabled?: boolean; [k: string]: unknown; } | null; [k: string]: unknown; } /** * Represents authentication helpers provided by Postman */ export interface Auth { type: | 'apikey' | 'awsv4' | 'basic' | 'bearer' | 'digest' | 'edgegrid' | 'hawk' | 'ntlm' | 'noauth' | 'oauth1' | 'oauth2'; noauth?: unknown; apikey?: APIKeyAuthentication; awsv4?: AWSSignatureV4; basic?: BasicAuthentication; bearer?: BearerTokenAuthentication; digest?: DigestAuthentication; edgegrid?: EdgeGridAuthentication; hawk?: HawkAuthentication; ntlm?: NTLMAuthentication; oauth1?: OAuth1; oauth2?: OAuth2; [k: string]: unknown; } /** * The attributes for API Key Authentication. e.g. key, value, in. */ export interface APIKeyAuthentication { [k: string]: unknown; } /** * The attributes for [AWS Auth](http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html). e.g. accessKey, secretKey, region, service. */ export interface AWSSignatureV4 { [k: string]: unknown; } /** * The attributes for [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication). e.g. username, password. */ export interface BasicAuthentication { [k: string]: unknown; } /** * The attributes for [Bearer Token Authentication](https://tools.ietf.org/html/rfc6750). e.g. token. */ export interface BearerTokenAuthentication { [k: string]: unknown; } /** * The attributes for [Digest Authentication](https://en.wikipedia.org/wiki/Digest_access_authentication). e.g. username, password, realm, nonce, nonceCount, algorithm, qop, opaque, clientNonce. */ export interface DigestAuthentication { [k: string]: unknown; } /** * The attributes for [Akamai EdgeGrid Authentication](https://developer.akamai.com/legacy/introduction/Client_Auth.html). e.g. accessToken, clientToken, clientSecret, baseURL, nonce, timestamp, headersToSign. */ export interface EdgeGridAuthentication { [k: string]: unknown; } /** * The attributes for [Hawk Authentication](https://github.com/hueniverse/hawk). e.g. authId, authKey, algorith, user, nonce, extraData, appId, delegation, timestamp. */ export interface HawkAuthentication { [k: string]: unknown; } /** * The attributes for [NTLM Authentication](https://msdn.microsoft.com/en-us/library/cc237488.aspx). e.g. username, password, domain, workstation. */ export interface NTLMAuthentication { [k: string]: unknown; } /** * The attributes for [OAuth1](https://oauth.net/1/). e.g. consumerKey, consumerSecret, token, tokenSecret, signatureMethod, timestamp, nonce, version, realm, encodeOAuthSign. */ export interface OAuth1 { [k: string]: unknown; } /** * The attributes for [OAuth2](https://oauth.net/2/). e.g. accessToken, addTokenTo. */ export interface OAuth2 { [k: string]: unknown; } /** * Using the Proxy, you can configure your custom proxy into the postman for particular url match */ export interface ProxyConfig { /** * The Url match for which the proxy config is defined */ match?: string; /** * The proxy server host */ host?: string; /** * The proxy server port */ port?: number; /** * The tunneling details for the proxy config */ tunnel?: boolean; /** * When set to true, ignores this proxy configuration entity */ disabled?: boolean; [k: string]: unknown; } /** * A representation of an ssl certificate */ export interface Certificate { /** * A name for the certificate for user reference */ name?: string; /** * A list of Url match pattern strings, to identify Urls this certificate can be used for. */ matches?: string[]; /** * An object containing path to file containing private key, on the file system */ key?: { /** * The path to file containing key for certificate, on the file system */ src?: { [k: string]: unknown; }; [k: string]: unknown; }; /** * An object containing path to file certificate, on the file system */ cert?: { /** * The path to file containing key for certificate, on the file system */ src?: { [k: string]: unknown; }; [k: string]: unknown; }; /** * The passphrase for the certificate */ passphrase?: string; [k: string]: unknown; } /** * Represents a single HTTP Header */ export interface Header { /** * This holds the LHS of the HTTP Header, e.g ``Content-Type`` or ``X-Custom-Header`` */ key: string; /** * The value (or the RHS) of the Header is stored in this field. */ value: string; /** * If set to true, the current header will not be sent with requests. */ disabled?: boolean; description?: DefinitionsDescription; [k: string]: unknown; } export interface UrlEncodedParameter { key: string; value?: string; disabled?: boolean; description?: DefinitionsDescription; [k: string]: unknown; } /** * A response represents an HTTP response. */ export interface Response { /** * A unique, user defined identifier that can be used to refer to this response from requests. */ id?: string; originalRequest?: Request; responseTime?: ResponseTime; timings?: ResponseTimings; header?: Headers; cookie?: Cookie[]; /** * The raw text of the response. */ body?: null | string; /** * The response status, e.g: '200 OK' */ status?: string; /** * The numerical response code, example: 200, 201, 404, etc. */ code?: number; [k: string]: unknown; } /** * A Cookie, that follows the [Google Chrome format](https://developer.chrome.com/extensions/cookies) */ export interface Cookie { /** * The domain for which this cookie is valid. */ domain: string; /** * When the cookie expires. */ expires?: string | number; maxAge?: string; /** * True if the cookie is a host-only cookie. (i.e. a request's URL domain must exactly match the domain of the cookie). */ hostOnly?: boolean; /** * Indicates if this cookie is HTTP Only. (if True, the cookie is inaccessible to client-side scripts) */ httpOnly?: boolean; /** * This is the name of the Cookie. */ name?: string; /** * The path associated with the Cookie. */ path: string; /** * Indicates if the 'secure' flag is set on the Cookie, meaning that it is transmitted over secure connections only. (typically HTTPS) */ secure?: boolean; /** * True if the cookie is a session cookie. */ session?: boolean; /** * The value of the Cookie. */ value?: string; /** * Custom attributes for a cookie go here, such as the [Priority Field](https://code.google.com/p/chromium/issues/detail?id=232693) */ extensions?: unknown[]; [k: string]: unknown; } /** * Set of configurations used to alter the usual behavior of sending the request */ export interface ProtocolProfileBehavior { [k: string]: unknown; } /** * One of the primary goals of Postman is to organize the development of APIs. To this end, it is necessary to be able to group requests together. This can be achived using 'Folders'. A folder just is an ordered set of requests. */ export interface Folder { /** * A folder's friendly name is defined by this field. You would want to set this field to a value that would allow you to easily identify this folder. */ name?: string; description?: DefinitionsDescription; variable?: VariableList; /** * Items are entities which contain an actual HTTP request, and sample responses attached to it. Folders may contain many items. */ item: Items1[]; event?: EventList; auth?: null | Auth; protocolProfileBehavior?: ProtocolProfileBehavior; [k: string]: unknown; }
the_stack
import expect from "expect"; import { BigNumber } from "bignumber.js"; import invariant from "invariant"; import sample from "lodash/sample"; import type { Transaction } from "./types"; import { getCryptoCurrencyById, parseCurrencyUnit, findCompoundToken, } from "../../currencies"; import { makeCompoundSummaryForAccount, getAccountCapabilities, } from "../../compound/logic"; import { getSupplyMax } from "./modules/compound"; import { pickSiblings } from "../../bot/specs"; import type { AppSpec } from "../../bot/types"; import { getGasLimit } from "./transaction"; import { DeviceModelId } from "@ledgerhq/devices"; import { TokenCurrency } from "@ledgerhq/cryptoassets"; import { CompoundAccountSummary } from "../../compound/types"; const ethereumBasicMutations = ({ maxAccount }) => [ { name: "move 50%", maxRun: 2, transaction: ({ account, siblings, bridge }) => { const sibling = pickSiblings(siblings, maxAccount); const recipient = sibling.freshAddress; const amount = account.balance.div(2).integerValue(); return { transaction: bridge.createTransaction(account), updates: [ { recipient, amount, }, ], }; }, test: ({ account, accountBeforeTransaction, operation, transaction }) => { // workaround for buggy explorer behavior (nodes desync) invariant( Date.now() - operation.date > 60000, "operation time to be older than 60s" ); const estimatedGas = getGasLimit(transaction).times( transaction.gasPrice || 0 ); expect(operation.fee.toNumber()).toBeLessThanOrEqual( estimatedGas.toNumber() ); expect(account.balance.toString()).toBe( accountBeforeTransaction.balance.minus(operation.value).toString() ); }, }, ]; function findCompoundAccount(account, f: (...args: Array<any>) => any) { return sample( (account.subAccounts || []).filter((a) => { if ( a.type === "TokenAccount" && a.balance.gt(0) && findCompoundToken(a.token) ) { const c = getAccountCapabilities(a); return c && f(c, a); } return false; }) ); } function getCompoundResult({ account, transaction, accountBeforeTransaction }) { const a = account.subAccounts?.find((a) => a.id === transaction.subAccountId); const aBefore = accountBeforeTransaction.subAccounts?.find( (a) => a.id === transaction.subAccountId ); invariant( a && a.type === "TokenAccount", "account %s found", transaction.subAccountId ); invariant( aBefore && aBefore.type === "TokenAccount", "account %s found", transaction.subAccountId ); const capabilities = getAccountCapabilities(a); const summary = makeCompoundSummaryForAccount(a, account); const capabilitiesBefore = getAccountCapabilities(aBefore); const summaryBefore = makeCompoundSummaryForAccount( aBefore, accountBeforeTransaction ); invariant( capabilities, "account %s have no capabilities found", transaction.subAccountId ); return { a, capabilities, summary, previous: { summary: summaryBefore, capabilities: capabilitiesBefore, }, }; } const ethereum: AppSpec<Transaction> = { name: "Ethereum", currency: getCryptoCurrencyById("ethereum"), appQuery: { model: DeviceModelId.nanoS, appName: "Ethereum", appVersion: "1.5.0-rc3", }, testTimeout: 4 * 60 * 1000, transactionCheck: ({ maxSpendable }) => { invariant( maxSpendable.gt( parseCurrencyUnit(getCryptoCurrencyById("ethereum").units[0], "0.01") ), "balance is too low" ); }, // @ts-expect-error seriously we have to do somehting mutations: ethereumBasicMutations({ maxAccount: 3, }).concat([ { name: "allow MAX a compound token", maxRun: 1, transaction: ({ account, bridge }) => { // find an existing token which was not yet allowed const a = findCompoundAccount(account, (c) => c.enabledAmount.eq(0)); invariant(a, "no compound account to allow"); const ctoken = findCompoundToken(a.token); invariant(ctoken, "ctoken found"); return { transaction: bridge.createTransaction(account) as Transaction, updates: [ { mode: "erc20.approve", subAccountId: a.id, recipient: (ctoken as TokenCurrency).contractAddress, }, { useAllAmount: true, }, ] as Partial<Transaction>[], }; }, test: (arg) => { const { capabilities } = getCompoundResult(arg); expect((capabilities as any).enabledAmountIsUnlimited).toBe(true); }, }, { name: "supply some compound token", maxRun: 1, transaction: ({ account, bridge }) => { const a = findCompoundAccount(account, (c) => c.canSupply); invariant(a, "no compound account to supply"); const ctoken = findCompoundToken(a.token); invariant(ctoken, "ctoken found"); const amount = getSupplyMax(a) .times(0.5 + 0.5 * Math.random()) .integerValue(); return { transaction: bridge.createTransaction(account), updates: [ { mode: "compound.supply", subAccountId: a.id, amount, }, ], }; }, test: (arg) => { const { transaction } = arg; const { summary, previous } = getCompoundResult(arg); invariant( summary, "could not find compound summary for account %s", transaction.subAccountId ); expect( (summary as CompoundAccountSummary).totalSupplied.gt( previous.summary?.totalSupplied || new BigNumber(0) ) ).toBe(true); }, }, { name: "withdraw some compound token", maxRun: 1, transaction: ({ account, bridge }) => { const a = findCompoundAccount( account, (c, a) => c.canWithdraw && a.operations.length > 0 && // 7 days has passed since last operation Date.now() - a.operations[0].date > 7 * 24 * 60 * 60 * 1000 ); invariant(a, "no compound account to withdraw"); const ctoken = findCompoundToken(a.token); invariant(ctoken, "ctoken found"); const nonSpendableBalance = a.balance.minus(a.spendableBalance); return { transaction: bridge.createTransaction(account), updates: [ { mode: "compound.withdraw", subAccountId: a.id, }, Math.random() < 0.5 ? { useAllAmount: true, } : { amount: nonSpendableBalance .times(Math.random()) .integerValue(), }, ], }; }, test: (arg) => { const { transaction } = arg; const { summary, previous } = getCompoundResult(arg); invariant( summary, "could not find compound summary for account %s", transaction.subAccountId ); invariant( previous.summary, "could not find a previous compound summary for account %s", transaction.subAccountId ); if (arg.transaction.useAllAmount) { expect((summary as CompoundAccountSummary).totalSupplied.eq(0)).toBe( true ); } else { expect( (summary as CompoundAccountSummary).totalSupplied.lt( (previous.summary as CompoundAccountSummary).totalSupplied || new BigNumber(0) ) ).toBe(true); } }, }, { name: "disallow a compound token", maxRun: 1, transaction: ({ account, bridge }) => { // find an existing token which was allowed // set it back to zero // ? IDEA: only do it if there is nothing to withdraw const a = findCompoundAccount( account, (c) => !c.enabledAmount.gt(0) && c.enabledAmountIsUnlimited ); invariant(a, "no compound account to disallow"); const ctoken = findCompoundToken(a.token); invariant(ctoken, "ctoken found"); return { transaction: bridge.createTransaction(account), updates: [ { mode: "erc20.approve", subAccountId: a.id, recipient: (ctoken as TokenCurrency).contractAddress, }, { amount: new BigNumber(0), }, ], }; }, test: (arg) => { const { capabilities } = getCompoundResult(arg); expect((capabilities as any).enabledAmount.eq(0)).toBe(true); }, }, { name: "move some ERC20", maxRun: 1, transaction: ({ account, siblings, bridge }) => { const erc20Account = sample( (account.subAccounts || []).filter((a) => a.balance.gt(0)) ); invariant(erc20Account, "no erc20 account"); const sibling = pickSiblings(siblings, 3); const recipient = sibling.freshAddress; return { transaction: bridge.createTransaction(account), updates: [ { recipient, subAccountId: erc20Account.id, }, Math.random() < 0.5 ? { useAllAmount: true, } : { amount: erc20Account.balance .times(Math.random()) .integerValue(), }, ], }; }, test: ({ accountBeforeTransaction, account, transaction, operation }) => { // workaround for buggy explorer behavior (nodes desync) invariant( Date.now() - operation.date > 60000, "operation time to be older than 60s" ); invariant(accountBeforeTransaction.subAccounts, "sub accounts before"); const erc20accountBefore = accountBeforeTransaction.subAccounts.find( (s) => s.id === transaction.subAccountId ); invariant(erc20accountBefore, "erc20 acc was here before"); invariant(account.subAccounts, "sub accounts"); const erc20account = account.subAccounts.find( (s) => s.id === transaction.subAccountId ); invariant(erc20account, "erc20 acc is still here"); if (transaction.useAllAmount) { expect(erc20account.balance.toString()).toBe("0"); } else { expect(erc20account.balance.toString()).toBe( erc20accountBefore.balance.minus(transaction.amount).toString() ); } }, }, ]), }; const ethereumClassic: AppSpec<Transaction> = { name: "Ethereum Classic", currency: getCryptoCurrencyById("ethereum_classic"), appQuery: { model: DeviceModelId.nanoS, appName: "Ethereum Classic", }, dependency: "Ethereum", testTimeout: 2 * 60 * 1000, transactionCheck: ({ maxSpendable }) => { invariant( maxSpendable.gt( parseCurrencyUnit( getCryptoCurrencyById("ethereum_classic").units[0], "0.05" ) ), "balance is too low" ); }, mutations: ethereumBasicMutations({ maxAccount: 4, }), }; const ethereumRopsten: AppSpec<Transaction> = { name: "Ethereum Ropsten", currency: getCryptoCurrencyById("ethereum_ropsten"), appQuery: { model: DeviceModelId.nanoS, appName: "Ethereum", appVersion: "1.5.0-rc3", }, testTimeout: 2 * 60 * 1000, transactionCheck: ({ maxSpendable }) => { invariant( maxSpendable.gt( parseCurrencyUnit( getCryptoCurrencyById("ethereum_ropsten").units[0], "0.01" ) ), "balance is too low" ); }, mutations: ethereumBasicMutations({ maxAccount: 8, }), }; const bsc: AppSpec<Transaction> = { name: "BSC", currency: getCryptoCurrencyById("bsc"), appQuery: { model: DeviceModelId.nanoS, appName: "Binance Smart Chain", }, testTimeout: 2 * 60 * 1000, transactionCheck: ({ maxSpendable }) => { invariant( maxSpendable.gt( parseCurrencyUnit(getCryptoCurrencyById("bsc").units[0], "0.005") ), "balance is too low" ); }, mutations: ethereumBasicMutations({ maxAccount: 8 }).concat([ { name: "move some BEP20", maxRun: 1, // @ts-expect-error rxjs stuff transaction: ({ account, siblings, bridge }) => { const bep20Account = sample( (account.subAccounts || []).filter((a) => a.balance.gt(0)) ); invariant(bep20Account, "no bep20 account"); const sibling = pickSiblings(siblings, 3); const recipient = sibling.freshAddress; return { transaction: bridge.createTransaction(account), updates: [ { recipient, subAccountId: bep20Account.id }, Math.random() < 0.5 ? { useAllAmount: true } : { amount: bep20Account.balance .times(Math.random()) .integerValue(), }, ], }; }, }, ]), }; export default { bsc, ethereum, ethereumClassic, ethereumRopsten, };
the_stack
import ReactNativeViewViewConfigAndroid from "./ReactNativeViewViewConfigAndroid"; declare var ReactNativeViewConfig: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { uiViewClassName: string; baseModuleName: null; Manager: string; Commands: {}; Constants: {}; bubblingEventTypes: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ typeof ReactNativeViewViewConfigAndroid.bubblingEventTypes & { topBlur: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { phasedRegistrationNames: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { bubbled: string; captured: string; }; }; topChange: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { phasedRegistrationNames: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { bubbled: string; captured: string; }; }; topEndEditing: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { phasedRegistrationNames: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { bubbled: string; captured: string; }; }; topFocus: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { phasedRegistrationNames: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { bubbled: string; captured: string; }; }; topKeyPress: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { phasedRegistrationNames: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { bubbled: string; captured: string; }; }; topPress: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { phasedRegistrationNames: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { bubbled: string; captured: string; }; }; topSubmitEditing: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { phasedRegistrationNames: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { bubbled: string; captured: string; }; }; topTouchCancel: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { phasedRegistrationNames: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { bubbled: string; captured: string; }; }; topTouchEnd: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { phasedRegistrationNames: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { bubbled: string; captured: string; }; }; topTouchMove: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { phasedRegistrationNames: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { bubbled: string; captured: string; }; }; topTouchStart: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { phasedRegistrationNames: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { bubbled: string; captured: string; }; }; }; directEventTypes: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ typeof ReactNativeViewViewConfigAndroid.directEventTypes & { topAccessibilityAction: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { registrationName: string; }; topAccessibilityEscape: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { registrationName: string; }; topAccessibilityTap: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { registrationName: string; }; topLayout: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { registrationName: string; }; topMagicTap: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { registrationName: string; }; // Events for react-native-gesture-handler (T45765076) // Remove once this library can handle JS View Configs onGestureHandlerEvent: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { registrationName: string; }; onGestureHandlerStateChange: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { registrationName: string; }; }; validAttributes: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ typeof ReactNativeViewViewConfigAndroid.validAttributes & { accessibilityActions: boolean; accessibilityElementsHidden: boolean; accessibilityHint: boolean; accessibilityIgnoresInvertColors: boolean; accessibilityLabel: boolean; accessibilityLiveRegion: boolean; accessibilityRole: boolean; accessibilityStates: boolean; accessibilityState: boolean; accessibilityValue: boolean; accessibilityViewIsModal: boolean; accessible: boolean; alignContent: boolean; alignItems: boolean; alignSelf: boolean; aspectRatio: boolean; backfaceVisibility: boolean; backgroundColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $1; }; borderBottomColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $2; }; borderBottomEndRadius: boolean; borderBottomLeftRadius: boolean; borderBottomRightRadius: boolean; borderBottomStartRadius: boolean; borderBottomWidth: boolean; borderColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $3; }; borderEndColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $4; }; borderEndWidth: boolean; borderLeftColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $5; }; borderLeftWidth: boolean; borderRadius: boolean; borderRightColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $6; }; borderRightWidth: boolean; borderStartColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $7; }; borderStartWidth: boolean; borderStyle: boolean; borderTopColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $8; }; borderTopEndRadius: boolean; borderTopLeftRadius: boolean; borderTopRightRadius: boolean; borderTopStartRadius: boolean; borderTopWidth: boolean; borderWidth: boolean; bottom: boolean; clickable: boolean; collapsable: boolean; direction: boolean; display: boolean; elevation: boolean; end: boolean; flex: boolean; flexBasis: boolean; flexDirection: boolean; flexGrow: boolean; flexShrink: boolean; flexWrap: boolean; height: boolean; hitSlop: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { diff: any; }; importantForAccessibility: boolean; justifyContent: boolean; left: boolean; margin: boolean; marginBottom: boolean; marginEnd: boolean; marginHorizontal: boolean; marginLeft: boolean; marginRight: boolean; marginStart: boolean; marginTop: boolean; marginVertical: boolean; maxHeight: boolean; maxWidth: boolean; minHeight: boolean; minWidth: boolean; nativeID: boolean; needsOffscreenAlphaCompositing: boolean; onAccessibilityAction: boolean; onAccessibilityEscape: boolean; onAccessibilityTap: boolean; onLayout: boolean; onMagicTap: boolean; opacity: boolean; overflow: boolean; padding: boolean; paddingBottom: boolean; paddingEnd: boolean; paddingHorizontal: boolean; paddingLeft: boolean; paddingRight: boolean; paddingStart: boolean; paddingTop: boolean; paddingVertical: boolean; pointerEvents: boolean; position: boolean; removeClippedSubviews: boolean; renderToHardwareTextureAndroid: boolean; right: boolean; rotation: boolean; scaleX: boolean; scaleY: boolean; shadowColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $9; }; shadowOffset: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { diff: typeof $10; }; shadowOpacity: boolean; shadowRadius: boolean; shouldRasterizeIOS: boolean; start: boolean; style: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { alignContent: boolean; alignItems: boolean; alignSelf: boolean; aspectRatio: boolean; backfaceVisibility: boolean; backgroundColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $11; }; borderBottomColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $12; }; borderBottomEndRadius: boolean; borderBottomLeftRadius: boolean; borderBottomRightRadius: boolean; borderBottomStartRadius: boolean; borderBottomWidth: boolean; borderColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $13; }; borderEndColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $14; }; borderEndWidth: boolean; borderLeftColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $15; }; borderLeftWidth: boolean; borderRadius: boolean; borderRightColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $16; }; borderRightWidth: boolean; borderStartColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $17; }; borderStartWidth: boolean; borderStyle: boolean; borderTopColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $18; }; borderTopEndRadius: boolean; borderTopLeftRadius: boolean; borderTopRightRadius: boolean; borderTopStartRadius: boolean; borderTopWidth: boolean; borderWidth: boolean; bottom: boolean; color: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $19; }; decomposedMatrix: boolean; direction: boolean; display: boolean; elevation: boolean; end: boolean; flex: boolean; flexBasis: boolean; flexDirection: boolean; flexGrow: boolean; flexShrink: boolean; flexWrap: boolean; fontFamily: boolean; fontSize: boolean; fontStyle: boolean; fontVariant: boolean; fontWeight: boolean; height: boolean; includeFontPadding: boolean; justifyContent: boolean; left: boolean; letterSpacing: boolean; lineHeight: boolean; margin: boolean; marginBottom: boolean; marginEnd: boolean; marginHorizontal: boolean; marginLeft: boolean; marginRight: boolean; marginStart: boolean; marginTop: boolean; marginVertical: boolean; maxHeight: boolean; maxWidth: boolean; minHeight: boolean; minWidth: boolean; opacity: boolean; overflow: boolean; overlayColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $20; }; padding: boolean; paddingBottom: boolean; paddingEnd: boolean; paddingHorizontal: boolean; paddingLeft: boolean; paddingRight: boolean; paddingStart: boolean; paddingTop: boolean; paddingVertical: boolean; position: boolean; resizeMode: boolean; right: boolean; rotation: boolean; scaleX: boolean; scaleY: boolean; shadowColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $21; }; shadowOffset: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { diff: typeof $22; }; shadowOpacity: boolean; shadowRadius: boolean; start: boolean; textAlign: boolean; textAlignVertical: boolean; textDecorationColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $23; }; textDecorationLine: boolean; textDecorationStyle: boolean; textShadowColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $24; }; textShadowOffset: boolean; textShadowRadius: boolean; textTransform: boolean; tintColor: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { process: typeof $25; }; top: boolean; transform: any; transformMatrix: boolean; translateX: boolean; translateY: boolean; width: boolean; writingDirection: boolean; zIndex: boolean; }; testID: boolean; top: boolean; transform: any; translateX: boolean; translateY: boolean; width: boolean; zIndex: boolean; }; }; import $1 from "../../StyleSheet/processColor"; import $2 from "../../StyleSheet/processColor"; import $3 from "../../StyleSheet/processColor"; import $4 from "../../StyleSheet/processColor"; import $5 from "../../StyleSheet/processColor"; import $6 from "../../StyleSheet/processColor"; import $7 from "../../StyleSheet/processColor"; import $8 from "../../StyleSheet/processColor"; import $9 from "../../StyleSheet/processColor"; import $10 from "../../../TypeScriptSupplementals/sizesDiffer"; import $11 from "../../StyleSheet/processColor"; import $12 from "../../StyleSheet/processColor"; import $13 from "../../StyleSheet/processColor"; import $14 from "../../StyleSheet/processColor"; import $15 from "../../StyleSheet/processColor"; import $16 from "../../StyleSheet/processColor"; import $17 from "../../StyleSheet/processColor"; import $18 from "../../StyleSheet/processColor"; import $19 from "../../StyleSheet/processColor"; import $20 from "../../StyleSheet/processColor"; import $21 from "../../StyleSheet/processColor"; import $22 from "../../../TypeScriptSupplementals/sizesDiffer"; import $23 from "../../StyleSheet/processColor"; import $24 from "../../StyleSheet/processColor"; import $25 from "../../StyleSheet/processColor"; declare const $f2tExportDefault: typeof ReactNativeViewConfig; export default $f2tExportDefault;
the_stack
import { Code, Editor, Modification } from "../../../editor/editor"; import { Selection } from "../../../editor/selection"; import { Position } from "../../../editor/position"; import * as t from "../../../ast"; import { Variable, StringLiteralVariable, MemberExpressionVariable, ShorthandVariable } from "./variable"; import { Parts } from "./parts"; import { DestructureStrategy } from "./destructure-strategy"; import { DeclarationOnCommonAncestor, MergeDestructuredDeclaration, VariableDeclarationModification } from "./variable-declaration-modification"; import { last } from "../../../array"; export { createOccurrence, Occurrence }; function createOccurrence( path: t.NodePath, loc: t.SourceLocation, selection: Selection ): Occurrence { if (t.canBeShorthand(path)) { const variable = new ShorthandVariable(path); if (variable.isValid) { return new ShorthandOccurrence(path, loc, variable); } } if (path.isMemberExpression() && !path.node.computed) { return new MemberExpressionOccurrence( path, loc, new MemberExpressionVariable(path) ); } if (t.isOptionalMemberExpression(path.node)) { return new Occurrence( path, loc, new MemberExpressionVariable( path as t.NodePath<t.OptionalMemberExpression> ) ); } if (path.isStringLiteral()) { if (!selection.isEmpty() && selection.isStrictlyInsidePath(path)) { path.replaceWith(t.convertStringToTemplateLiteral(path.node, loc)); return createOccurrence(path, loc, selection); } if (path.parentPath.isJSX()) { return new JSXOccurrence( path, loc, new StringLiteralVariable(path, path.node.value) ); } return new Occurrence( path, loc, new StringLiteralVariable(path, path.node.value) ); } if ( path.isTemplateLiteral() && !selection.isEmpty() && PartialTemplateLiteralOccurrence.isValid(path, loc, selection) ) { return new PartialTemplateLiteralOccurrence(path, loc, selection); } if (path.isJSX()) { return new JSXOccurrence(path, loc, new Variable<t.JSX>(path)); } return new Occurrence(path, loc, new Variable(path)); } class Occurrence<T extends t.Node = t.Node> { constructor( public path: t.NodePath<T>, public loc: t.SourceLocation, protected variable: Variable ) {} get selection() { return Selection.fromAST(this.loc); } get modification(): Modification { return { code: this.variable.id, selection: this.selection }; } cursorOnIdentifier(extractedOccurrences: Occurrence[]): Position { return this.positionOnExtractedId .putAtSameCharacter(this.modification.selection.start) .removeCharacters(this.offsetFor(extractedOccurrences)); } protected offsetFor(extractedOccurrences: Occurrence<t.Node>[]) { return extractedOccurrences .map(({ modification }) => modification) .filter(({ selection }) => selection.isOneLine) .filter(({ selection }) => selection.startsBefore(this.modification.selection) ) .filter(({ selection }) => selection.start.isSameLineThan(this.modification.selection.start) ) .filter( ({ selection }) => !selection.isEqualTo(this.modification.selection) ) .map(({ code, selection }) => selection.width - code.length) .reduce((a, b) => a + b, 0); } protected get positionOnExtractedId(): Position { return new Position( this.selection.start.line + this.selection.height + 1, this.selection.start.character + this.variable.length ); } get parentScopePosition(): Position { const parentPath = t.findScopePath(this.path); const parent = parentPath ? parentPath.node : this.path.node; if (!parent.loc) return this.selection.start; return Position.fromAST(parent.loc.start); } toVariableDeclaration( extractedCode: Code, allOccurrences: Occurrence[] ): Modification { const { name, value } = this.variableDeclarationParts(extractedCode); const useTabs = t.isUsingTabs(this.path.node); if (allOccurrences.length > 1) { return new DeclarationOnCommonAncestor( name, value, useTabs, allOccurrences ); } return new VariableDeclarationModification( name, value, useTabs, Selection.cursorAtPosition(this.parentScopePosition) ); } protected variableDeclarationParts(code: Code): { name: Code; value: Code } { return { name: this.variable.name, value: t.isJSXText(this.path.node) ? `"${code}"` : code }; } askModificationDetails(_editor: Editor): Promise<void> { return Promise.resolve(); } } class JSXOccurrence extends Occurrence { cursorOnIdentifier(extractedOccurrences: Occurrence[]): Position { // Add 1 character to account for the extra `{` const extraChars = this.path.parentPath?.isJSX() ? 1 : 0; return super .cursorOnIdentifier(extractedOccurrences) .addCharacters(extraChars); } } class ShorthandOccurrence extends Occurrence<t.ObjectProperty> { private get keySelection(): Selection { if (!t.isSelectableNode(this.path.node.key)) { return this.selection; } return Selection.fromAST(this.path.node.key.loc); } get modification(): Modification { return { code: "", selection: this.selection.extendStartToEndOf(this.keySelection) }; } get positionOnExtractedId(): Position { return new Position( this.selection.start.line + this.selection.height + 1, this.keySelection.end.character ); } } class MemberExpressionOccurrence extends Occurrence<t.MemberExpression> { private destructureStrategy = DestructureStrategy.Destructure; toVariableDeclaration( extractedCode: Code, allOccurrences: Occurrence[] ): Modification { if (this.destructureStrategy === DestructureStrategy.Preserve) { return super.toVariableDeclaration(extractedCode, allOccurrences); } const existingDeclaration = t.findFirstExistingDeclaration( this.path.get("object") ); if (existingDeclaration) { const lastProperty = last(existingDeclaration.node.id.properties); if (lastProperty && t.isSelectableNode(lastProperty)) { return new MergeDestructuredDeclaration( this.variable.name, lastProperty ); } } const name = `{ ${this.variable.name} }`; const value = this.parentObject; const useTabs = t.isUsingTabs(this.path.node); if (allOccurrences.length > 1) { return new DeclarationOnCommonAncestor( name, value, useTabs, allOccurrences ); } return new VariableDeclarationModification( name, value, useTabs, Selection.cursorAtPosition(this.parentScopePosition) ); } async askModificationDetails(editor: Editor) { const choice = await editor.askUserChoice([ { label: `Destructure => \`const { ${this.variable.name} } = ${this.parentObject}\``, value: DestructureStrategy.Destructure }, { label: `Preserve => \`const ${this.variable.name} = ${this.parentObject}.${this.variable.name}\``, value: DestructureStrategy.Preserve } ]); if (choice) { this.destructureStrategy = choice.value; } } private get parentObject(): Code { return t.generate(this.path.node.object); } get positionOnExtractedId(): Position { if (this.destructureStrategy === DestructureStrategy.Preserve) { return super.positionOnExtractedId; } const existingDeclaration = t.findFirstExistingDeclaration( this.path.get("object") ); if (existingDeclaration) { return super.positionOnExtractedId.removeLines(1); } return super.positionOnExtractedId; } } class PartialTemplateLiteralOccurrence extends Occurrence<t.TemplateLiteral> { constructor( path: t.NodePath<t.TemplateLiteral>, loc: t.SourceLocation, private readonly userSelection: Selection ) { super(path, loc, new Variable(path)); // Override variable after `this` is set this.variable = new StringLiteralVariable(path, this.parts.selected); } static isValid( path: t.NodePath<t.TemplateLiteral>, loc: t.SourceLocation, userSelection: Selection ): boolean { // This doesn't work yet for multi-lines code because we don't support it. if (Selection.fromAST(loc).isMultiLines) return false; try { const occurrence = new PartialTemplateLiteralOccurrence( path, loc, userSelection ); // If any of these throws, Occurrence is invalid occurrence.variableDeclarationParts(); } catch { return false; } return true; } protected variableDeclarationParts(): { name: Code; value: Code } { return { name: this.variable.name, value: `"${this.parts.selected}"` }; } get modification(): Modification { const { before, after } = this.parts; const { quasis, expressions } = this.path.node; const { index } = this.selectedQuasi; const newQuasis = [t.templateElement(before), t.templateElement(after)]; const newTemplateLiteral = t.templateLiteral( // Replace quasi with the new truncated ones [...quasis.slice(0, index), ...newQuasis, ...quasis.slice(index + 1)], // Insert the new expression [ ...expressions.slice(0, index), t.identifier(this.variable.name), ...expressions.slice(index) ] ); return { code: t.print(newTemplateLiteral), selection: this.selection }; } private get parts(): Parts { const offset = Selection.fromAST(this.selectedQuasi.loc).start; return new Parts(this.selectedQuasi.value.raw, this.userSelection, offset); } private get selectedQuasi(): t.TemplateElement & t.SelectableNode & { index: number } { const index = this.path.node.quasis.findIndex((quasi) => this.userSelection.isInsideNode(quasi) ); if (index < 0) { throw new Error("I can't find selected text in template elements"); } const result = this.path.node.quasis[index]; if (!t.isSelectableNode(result)) { throw new Error("Template element is not selectable"); } return { ...result, index }; } get positionOnExtractedId(): Position { // ${ is inserted before the Identifier const openingInterpolationLength = 2; return new Position( this.selection.start.line + this.selection.height + 1, this.userSelection.start.character + openingInterpolationLength ); } cursorOnIdentifier(extractedOccurrences: Occurrence[]): Position { return this.positionOnExtractedId.removeCharacters( this.offsetFor(extractedOccurrences) ); } }
the_stack
import { sp } from '@pnp/sp'; import * as strings from 'ColumnFormatterWebPartStrings'; import { DefaultButton, PrimaryButton } from 'office-ui-fabric-react/lib/Button'; import { ChoiceGroup } from 'office-ui-fabric-react/lib/ChoiceGroup'; import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { Icon } from 'office-ui-fabric-react/lib/Icon'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; import { autobind } from 'office-ui-fabric-react/lib/Utilities'; import * as React from 'react'; import { connect } from 'react-redux'; import { Dispatch } from 'redux'; import { textForType, typeForTypeAsString } from '../helpers/ColumnTypeHelpers'; import { launchEditor, launchEditorWithCode } from '../state/Actions'; import { columnTypes, IApplicationState, IContext, ISaveDetails, saveMethod } from '../state/State'; import styles from './ColumnFormatter.module.scss'; import { FileUploader } from './FileUploader'; import { getWizardByName, getWizardsForColumnType, IWizard, standardWizardStartingCode } from './Wizards/WizardCommon'; export enum welcomeStage { start, new, open, upload, loadFromList, loadFromSiteColumn, loadFromLibrary } export interface IColumnFormatterWelcomeProps { context?: IContext; uiHeight?: number; launchEditor?: (wizardName:string, colType:columnTypes) => void; launchEditorWithCode?: (wizardName:string, colType:columnTypes, editorString:string, validationErrors:Array<string>, saveDetails: ISaveDetails) => void; } export interface IColumnFormatterWelcomeState { stage: welcomeStage; columnTypeForNew?: columnTypes; useWizardForNew: boolean; ChoosenWizardName?: string; loadChoiceForOpen?: string; columnTypeForOpen?: columnTypes; fileChoiceForOpen?: string; siteColumnsLoaded: boolean; siteColumns: Array<any>; selectedSiteColumnGroup?: string; selectedSiteColumn?: string; loadingFromSiteColumn: boolean; loadFromSiteColumnError?: string; listsLoaded: boolean; lists: Array<any>; selectedList?: string; selectedField?: string; loadingFromList: boolean; loadFromListError?: string; librariesLoaded: boolean; libraries: Array<any>; selectedLibraryUrl?: string; libraryFolderPath: string; libraryFileName: string; loadingFromLibrary: boolean; loadFromLibraryError?: string; } class ColumnFormatterWelcome_ extends React.Component<IColumnFormatterWelcomeProps, IColumnFormatterWelcomeState> { constructor(props:IColumnFormatterWelcomeProps) { super(props); this.state = { stage: welcomeStage.start, useWizardForNew: true, loadChoiceForOpen: 'list', listsLoaded: false, lists: new Array<any>(), loadingFromList: false, siteColumnsLoaded: false, siteColumns: new Array<any>(), loadingFromSiteColumn: false, librariesLoaded: false, libraries: new Array<any>(), libraryFolderPath: '', libraryFileName: strings.WizardDefaultField + '.json', loadingFromLibrary: false }; } public render(): React.ReactElement<IColumnFormatterWelcomeProps> { //TEMP (helpful for testing and skipping the welcome altogether) //this.props.launchEditor(undefined,columnTypes.text); //this.props.launchEditor('Donut', columnTypes.number); //this.props.launchEditor('Severity', columnTypes.text); //this.props.launchEditor('Start Flow', columnTypes.text); return ( <div className={styles.welcome} style={{height: this.props.uiHeight + 'px'}}> <div className={styles.welcomeBox}> {this.state.stage == welcomeStage.start && ( <div> <div className={styles.header}> <h1>{strings.Welcome_Title}</h1> <span>{strings.Welcome_SubTitle}</span> </div> <div className={styles.startButtons}> <div className={styles.startButton} onClick={() => {this.gotoStage(welcomeStage.new);}}> <div className={styles.icon}> <Icon iconName='Filters'/> </div> <div className={styles.words}> <h2>{strings.Welcome_NewHeader}</h2> <span>{strings.Welcome_NewDescription}</span> </div> </div> <div className={styles.startButton} onClick={() => {this.gotoStage(welcomeStage.open);}}> <div className={styles.icon}> <Icon iconName='OpenFolderHorizontal'/> </div> <div className={styles.words}> <h2>{strings.Welcome_OpenHeader}</h2> <span>{strings.Welcome_OpenDescription}</span> </div> </div> </div> </div> )} {this.state.stage == welcomeStage.new && ( <div className={styles.newForm}> <div className={styles.columnType}> <Label required={true}>{strings.Welcome_ColumnType}</Label> <Dropdown selectedKey={this.state.columnTypeForNew} onChanged={this.onChangeColumnTypeForNew} options={[ {key: columnTypes.choice, text: textForType(columnTypes.choice)}, {key: columnTypes.datetime, text: textForType(columnTypes.datetime)}, {key: columnTypes.link, text: textForType(columnTypes.link)}, {key: columnTypes.lookup, text: textForType(columnTypes.lookup)}, {key: columnTypes.number, text: textForType(columnTypes.number)}, {key: columnTypes.person, text: textForType(columnTypes.person)}, {key: columnTypes.picture, text: textForType(columnTypes.picture)}, {key: columnTypes.text, text: textForType(columnTypes.text)}, {key: columnTypes.boolean, text: textForType(columnTypes.boolean)} ]}/> </div> <ChoiceGroup disabled={this.state.columnTypeForNew == undefined} selectedKey={this.state.useWizardForNew ? 'wizard' : 'blank'} onChange={this.onNewStartWithChanged} options={[ {key:'wizard', text:strings.Welcome_NewWizardOption, onRenderField: (props, render) => { return( <div> { render!(props) } {this.wizardOptions()} </div> ); }}, {key:'blank', text:strings.Welcome_NewBlankOption} ]}/> <div className={styles.navigationButtons}> <div> <DefaultButton text={strings.Welcome_BackButton} onClick={() => {this.gotoStage(welcomeStage.start);}}/> </div> <div style={{textAlign: 'right'}}> <PrimaryButton text={strings.Welcome_OKButton} disabled={!this.okButtonEnabled()} onClick={this.onOkForNewClick}/> </div> </div> </div> )} {this.state.stage == welcomeStage.open && ( <div className={styles.openForm}> <ChoiceGroup selectedKey={this.state.loadChoiceForOpen} onChange={this.onLoadChoiceForOpenChanged} options={[ {key:'list', text: strings.Welcome_OpenLoadList}, {key:'sitecolumn', text: strings.Welcome_OpenLoadSiteColumn}, {key:'file', text: strings.Welcome_OpenLoadFile, onRenderField: (props, render) => { return ( <div> { render!(props) } <div className={styles.columnType}> <Label required={true}>{strings.Welcome_ColumnType}</Label> <Dropdown selectedKey={this.state.columnTypeForOpen} onChanged={this.onChangeColumnTypeForOpen} disabled={this.state.loadChoiceForOpen !== 'file'} options={[ {key: columnTypes.choice, text: textForType(columnTypes.choice)}, {key: columnTypes.datetime, text: textForType(columnTypes.datetime)}, {key: columnTypes.link, text: textForType(columnTypes.link)}, {key: columnTypes.lookup, text: textForType(columnTypes.lookup)}, {key: columnTypes.number, text: textForType(columnTypes.number)}, {key: columnTypes.person, text: textForType(columnTypes.person)}, {key: columnTypes.picture, text: textForType(columnTypes.picture)}, {key: columnTypes.text, text: textForType(columnTypes.text)}, {key: columnTypes.boolean, text: textForType(columnTypes.boolean)} ]}/> </div> <div className={styles.subChoice}> <ChoiceGroup selectedKey={this.state.fileChoiceForOpen} onChange={this.onFileChoiceForOpenChanged} disabled={this.state.loadChoiceForOpen !== 'file'} options={[ {key:'library', text: strings.Welcome_OpenLoadFileLibrary}, {key:'upload', text: strings.Welcome_OpenLoadFileUpload} ]}/> </div> </div> ); }} ]}/> <div className={styles.navigationButtons}> <div> <DefaultButton text={strings.Welcome_BackButton} onClick={() => {this.gotoStage(welcomeStage.start);}}/> </div> <div style={{textAlign: 'right'}}> <PrimaryButton text={strings.Welcome_NextButton} disabled={!this.okButtonEnabled()} onClick={this.onOkForOpenClick}/> </div> </div> </div> )} {this.state.stage == welcomeStage.upload && ( <div> <FileUploader onTextLoaded={this.onFileTextReceived}/> <div className={styles.navigationButtons}> <div> <DefaultButton text={strings.Welcome_BackButton} onClick={() => {this.gotoStage(welcomeStage.open);}}/> </div> </div> </div> )} {this.state.stage == welcomeStage.loadFromList && ( <div> {!this.props.context.isOnline && ( <span>{strings.FeatureUnavailableFromLocalWorkbench}</span> )} {!this.state.listsLoaded && this.props.context.isOnline && !this.state.loadingFromList && this.state.loadFromListError == undefined && ( <Spinner size={SpinnerSize.large} label={strings.ListField_LoadingLists}/> )} {this.state.listsLoaded && this.props.context.isOnline && !this.state.loadingFromList && this.state.loadFromListError == undefined && ( <div> <Dropdown label={strings.ListField_List} selectedKey={this.state.selectedList} onChanged={(item:IDropdownOption)=> {this.setState({selectedList: item.key.toString(),selectedField: undefined});}} required={true} options={this.listsToOptions()} /> <Dropdown label={strings.ListField_Field} selectedKey={this.state.selectedField} disabled={this.state.selectedList == undefined} onChanged={(item:IDropdownOption)=> {this.setState({selectedField: item.key.toString()});}} required={true} options={this.fieldsToOptions()} /> </div> )} {this.state.loadingFromList && this.state.loadFromListError == undefined &&( <Spinner size={SpinnerSize.large} label={strings.ListField_LoadingFromList}/> )} {this.state.loadFromListError !== undefined && ( <span className={styles.errorMessage}>{this.state.loadFromListError}</span> )} <div className={styles.navigationButtons}> <div> <DefaultButton text={strings.Welcome_BackButton} onClick={() => {this.gotoStage(welcomeStage.open);}}/> </div> <div style={{textAlign: 'right'}}> <PrimaryButton text={strings.Welcome_OKButton} disabled={!this.okButtonEnabled()} onClick={this.onOkForLoadFromListClick}/> </div> </div> </div> )} {this.state.stage == welcomeStage.loadFromSiteColumn && ( <div> {!this.props.context.isOnline && ( <span>{strings.FeatureUnavailableFromLocalWorkbench}</span> )} {!this.state.siteColumnsLoaded && this.props.context.isOnline && !this.state.loadingFromSiteColumn && this.state.loadFromSiteColumnError == undefined && ( <Spinner size={SpinnerSize.large} label={strings.SiteColumn_LoadingSiteColumns}/> )} {this.state.siteColumnsLoaded && this.props.context.isOnline && !this.state.loadingFromSiteColumn && this.state.loadFromSiteColumnError == undefined && ( <div> <Dropdown label={strings.SiteColumn_Group} selectedKey={this.state.selectedSiteColumnGroup} onChanged={(item:IDropdownOption)=> {this.setState({selectedSiteColumnGroup: item.key.toString(), selectedSiteColumn: undefined});}} required={true} options={this.siteColumnGroupsToOptions()} /> <Dropdown label={strings.SiteColumn_Field} selectedKey={this.state.selectedSiteColumn} disabled={this.state.selectedSiteColumnGroup == undefined} onChanged={(item:IDropdownOption)=> {this.setState({selectedSiteColumn: item.key.toString()});}} required={true} options={this.siteColumnsToOptions()} /> </div> )} {this.state.loadingFromSiteColumn && this.state.loadFromSiteColumnError == undefined &&( <Spinner size={SpinnerSize.large} label={strings.SiteColumn_LoadingFromSiteColumn}/> )} {this.state.loadFromSiteColumnError !== undefined && ( <span className={styles.errorMessage}>{this.state.loadFromSiteColumnError}</span> )} <div className={styles.navigationButtons}> <div> <DefaultButton text={strings.Welcome_BackButton} onClick={() => {this.gotoStage(welcomeStage.open);}}/> </div> <div style={{textAlign: 'right'}}> <PrimaryButton text={strings.Welcome_OKButton} disabled={!this.okButtonEnabled()} onClick={this.onOkForLoadFromSiteColumnClick}/> </div> </div> </div> )} {this.state.stage == welcomeStage.loadFromLibrary && ( <div> {!this.props.context.isOnline && ( <span>{strings.FeatureUnavailableFromLocalWorkbench}</span> )} {!this.state.librariesLoaded && this.props.context.isOnline && !this.state.loadingFromLibrary && this.state.loadFromLibraryError == undefined && ( <Spinner size={SpinnerSize.large} label={strings.Library_LoadingLibraries}/> )} {this.state.librariesLoaded && this.props.context.isOnline && !this.state.loadingFromLibrary && this.state.loadFromLibraryError == undefined && ( <div> <Dropdown label={strings.Library_Library} selectedKey={this.state.selectedLibraryUrl} onChanged={(item:IDropdownOption)=> {this.setState({selectedLibraryUrl: item.key.toString()});}} required={true} options={this.librariesToOptions()} /> <TextField label={strings.Library_FolderPath} value={this.state.libraryFolderPath} onChanged={(value:string) => {this.setState({libraryFolderPath: value});}}/> <TextField label={strings.Library_Filename} required={true} value={this.state.libraryFileName} onChanged={(value:string) => {this.setState({libraryFileName: value});}}/> </div> )} {this.state.loadingFromLibrary && this.state.loadFromLibraryError == undefined &&( <Spinner size={SpinnerSize.large} label={strings.Library_LoadingFromLibrary}/> )} {this.state.loadFromLibraryError !== undefined && ( <span className={styles.errorMessage}>{this.state.loadFromLibraryError}</span> )} <div className={styles.navigationButtons}> <div> <DefaultButton text={strings.Welcome_BackButton} onClick={() => {this.gotoStage(welcomeStage.open);}}/> </div> <div style={{textAlign: 'right'}}> <PrimaryButton text={strings.Welcome_OKButton} disabled={!this.okButtonEnabled()} onClick={this.onOkForLoadFromLibraryClick}/> </div> </div> </div> )} </div> </div> ); } @autobind private gotoStage(stage:welcomeStage): void { this.setState({ stage }); } private okButtonEnabled(): boolean { switch(this.state.stage) { case welcomeStage.new: return ( this.state.columnTypeForNew !== undefined && (!this.state.useWizardForNew || (this.state.useWizardForNew && this.state.ChoosenWizardName !== undefined)) ); case welcomeStage.open: return ( this.state.loadChoiceForOpen == 'list' || this.state.loadChoiceForOpen == 'sitecolumn' || (this.state.loadChoiceForOpen == 'file' && this.state.columnTypeForOpen !== undefined && this.state.fileChoiceForOpen !== undefined) ); case welcomeStage.loadFromList: return ( this.props.context.isOnline && this.state.selectedList !== undefined && this.state.selectedField !== undefined && this.state.loadFromListError == undefined ); case welcomeStage.loadFromSiteColumn: return ( this.props.context.isOnline && this.state.selectedSiteColumnGroup !== undefined && this.state.selectedSiteColumn !== undefined && this.state.loadFromSiteColumnError == undefined ); case welcomeStage.loadFromLibrary: return ( this.props.context.isOnline && this.state.selectedLibraryUrl !== undefined && this.state.libraryFileName.length > 0 && this.state.loadFromLibraryError == undefined ); default: return false; } } @autobind private onChangeColumnTypeForNew(item: IDropdownOption): void { let selectedWizard: IWizard = getWizardByName(this.state.ChoosenWizardName); let wizardName:string = undefined; if(selectedWizard !== undefined && (selectedWizard.fieldTypes.length == 0 || selectedWizard.fieldTypes.indexOf(+item.key) >= 0)) { wizardName = selectedWizard.name; } this.setState({ columnTypeForNew: +item.key, ChoosenWizardName: wizardName, useWizardForNew: (getWizardsForColumnType(+item.key).length > 0 && this.state.useWizardForNew) }); } @autobind private onNewStartWithChanged(ev: React.FormEvent<HTMLInputElement>, option: any) { this.setState({ useWizardForNew: option.key == 'wizard' }); } private wizardOptions(): JSX.Element { let filteredWizards = getWizardsForColumnType(this.state.columnTypeForNew); let topRowItemCount:number = filteredWizards.length > 0 ? Math.ceil(filteredWizards.length/2) : 0; let choicesWidth:number = Math.max(topRowItemCount * 64 + topRowItemCount * 4, 204); return ( <div className={styles.wizardChoiceSelection + (this.state.useWizardForNew && this.state.columnTypeForNew !== undefined ? '' : ' ' + styles.disabled)}> <div className={styles.wizardChoices} style={{width: choicesWidth.toString() + 'px'}}> {filteredWizards.map((value:IWizard, index: number) => { return ( <div className={styles.wizardChoiceBox + (this.state.useWizardForNew && this.state.ChoosenWizardName == value.name ? ' ' + styles.choosenWizard : '')} title={this.state.useWizardForNew ? value.description : ''} onClick={()=>{this.onWizardClick(value.name);}} key={value.name}> <Icon iconName={value.iconName}/> <span>{value.name}</span> </div> ); })} {filteredWizards.length == 0 && ( <span className={styles.noWizards}>{strings.Welcome_NewNoTemplates}</span> )} </div> </div> ); } @autobind private onWizardClick(wizardName:string){ if(this.state.useWizardForNew){ this.setState({ ChoosenWizardName: wizardName }); } } @autobind private onOkForNewClick(): void { this.props.launchEditor(this.state.useWizardForNew ? this.state.ChoosenWizardName : undefined, this.state.columnTypeForNew); } @autobind private onLoadChoiceForOpenChanged(ev: React.FormEvent<HTMLInputElement>, option: any) { this.setState({ loadChoiceForOpen: option.key }); } @autobind private onChangeColumnTypeForOpen(item: IDropdownOption): void { this.setState({ columnTypeForOpen: +item.key }); } @autobind private onFileChoiceForOpenChanged(ev: React.FormEvent<HTMLInputElement>, option: any) { this.setState({ fileChoiceForOpen: option.key }); } @autobind private onOkForOpenClick(): void { switch (this.state.loadChoiceForOpen) { case 'list': this.gotoLoadFromList(); break; case 'sitecolumn': this.gotoLoadFromSiteColumn(); break; default: if(this.state.fileChoiceForOpen == 'library'){ this.gotoLoadFromLibrary(); } else { this.gotoStage(welcomeStage.upload); } break; } } @autobind private onFileTextReceived(fileText:string) { this.launchEditorFromText(fileText, this.state.columnTypeForOpen || columnTypes.text); } private launchEditorFromText(text:string, type:columnTypes, loadMethod?:saveMethod): void { if(text == undefined || text.length == 0) { text = standardWizardStartingCode(type); } //TODO: Check for wizard details in file let validationErrors:Array<string> = new Array<string>(); try { let curObj:any = JSON.parse(text); } catch (e) { validationErrors.push(e.message); } //provide details of loading (if applicable) to intialize saving // this makes it easier to save back to the list loaded from, etc. let saveDetails:ISaveDetails = { activeSaveMethod: loadMethod, libraryUrl: (loadMethod == saveMethod.Library ? this.state.selectedLibraryUrl : undefined), libraryFolderPath: (loadMethod == saveMethod.Library ? this.state.libraryFolderPath : ''), libraryFilename: (loadMethod == saveMethod.Library ? this.state.libraryFileName : ''), list: (loadMethod == saveMethod.ListField ? this.state.selectedList : undefined), field: (loadMethod == saveMethod.ListField ? this.state.selectedField : undefined), siteColumnGroup: (loadMethod == saveMethod.SiteColumn ? this.state.selectedSiteColumnGroup : undefined), siteColumn: (loadMethod == saveMethod.SiteColumn ? this.state.selectedSiteColumn : undefined) }; this.props.launchEditorWithCode(undefined, type, text, validationErrors, saveDetails); } private gotoLoadFromList(): void { if(!this.state.listsLoaded) { if(this.props.context.isOnline) { sp.web.lists.filter('Hidden eq false').select('Id','Title','Fields/InternalName','Fields/TypeAsString','Fields/Hidden','Fields/Title','Fields/DisplayFormat').expand('Fields').get() .then((data:any) => { let listdata:Array<any> = new Array<any>(); for(var i=0; i<data.length; i++){ listdata.push({ Id: data[i].Id, Title: data[i].Title, Fields: data[i].Fields.map((field:any, index:number) => { if(!field.Hidden) { let ftype = typeForTypeAsString(field.TypeAsString, field.DisplayFormat); if(ftype !== undefined) { return { Title: field.Title, InternalName: field.InternalName, Type: ftype }; } } }).filter((field:any, index:number) => {return field !== undefined;}) }); } this.setState({ listsLoaded: true, lists: listdata }); }) .catch((error:any) => { this.setState({ loadFromListError: strings.ListField_ListLoadError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message }); }); } } this.gotoStage(welcomeStage.loadFromList); } private listsToOptions(): Array<IDropdownOption> { let items:Array<IDropdownOption> = new Array<IDropdownOption>(); for(var list of this.state.lists) { items.push({ key: list.Id, text: list.Title }); } return items; } private fieldsToOptions(): Array<IDropdownOption> { let items:Array<IDropdownOption> = new Array<IDropdownOption>(); for(var list of this.state.lists) { if(list.Id == this.state.selectedList) { for(var field of list.Fields) { items.push({ key: field.InternalName, text: field.Title + ' [' + textForType(field.Type) + ']' }); } break; } } return items; } @autobind private onOkForLoadFromListClick(): void { this.setState({ loadingFromList: true, loadFromListError: undefined }); sp.web.lists.getById(this.state.selectedList) .fields.getByInternalNameOrTitle(this.state.selectedField).select('CustomFormatter','TypeAsString','DisplayFormat').get() .then((data)=>{ this.launchEditorFromText(data.CustomFormatter, typeForTypeAsString(data.TypeAsString, data.DisplayFormat), saveMethod.ListField); this.setState({ loadingFromList: false, }); }) .catch((error:any) => { this.setState({ loadingFromList: false, loadFromListError: strings.Welcome_LoadingError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message }); }); } private gotoLoadFromSiteColumn(): void { if(!this.state.siteColumnsLoaded) { if(this.props.context.isOnline) { sp.web.fields.filter('ReadOnlyField eq false and Hidden eq false').select('Id','Group','Title','InternalName','TypeAsString','DisplayFormat').orderBy('Group').get() .then((data:any) => { let groupdata:Array<any> = new Array<any>(); var curGroupName:string; for(var i=0; i<data.length; i++){ let ftype = typeForTypeAsString(data[i].TypeAsString, data[i].DisplayFormat); if(ftype !== undefined) { if(curGroupName != data[i].Group) { groupdata.push({ Group: data[i].Group, Fields: [] }); curGroupName = data[i].Group; } groupdata[groupdata.length-1].Fields.push({ Id: data[i].Id, Title: data[i].Title, InternalName: data[i].InternalName, Type: ftype }); } } this.setState({ siteColumnsLoaded: true, siteColumns: groupdata }); }) .catch((error:any) => { this.setState({ loadFromSiteColumnError: strings.SiteColumn_SiteColumnsLoadError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message }); }); } } this.gotoStage(welcomeStage.loadFromSiteColumn); } private siteColumnGroupsToOptions(): Array<IDropdownOption> { let items:Array<IDropdownOption> = new Array<IDropdownOption>(); for(var group of this.state.siteColumns) { items.push({ key: group.Group, text: group.Group }); } return items; } private siteColumnsToOptions(): Array<IDropdownOption> { let items:Array<IDropdownOption> = new Array<IDropdownOption>(); for(var group of this.state.siteColumns) { if(group.Group == this.state.selectedSiteColumnGroup) { for(var field of group.Fields) { items.push({ key: field.InternalName, text: field.Title + ' [' + textForType(field.Type) + ']' }); } } } return items; } @autobind private onOkForLoadFromSiteColumnClick(): void { this.setState({ loadingFromSiteColumn: true, loadFromSiteColumnError: undefined }); sp.web.fields.getByInternalNameOrTitle(this.state.selectedSiteColumn).select('CustomFormatter','TypeAsString','DisplayFormat').get() .then((data)=>{ this.launchEditorFromText(data.CustomFormatter, typeForTypeAsString(data.TypeAsString, data.DisplayFormat), saveMethod.SiteColumn); this.setState({ loadingFromSiteColumn: false, }); }) .catch((error:any) => { this.setState({ loadingFromSiteColumn: false, loadFromSiteColumnError: strings.Welcome_LoadingError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message }); }); } private gotoLoadFromLibrary(): void { if(!this.state.librariesLoaded) { if(this.props.context.isOnline) { sp.site.getDocumentLibraries(this.props.context.webAbsoluteUrl) .then((data:any) => { this.setState({ librariesLoaded: true, libraries: data }); }) .catch((error:any) => { this.setState({ loadFromLibraryError: strings.Library_LibrariesLoadError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message }); }); } } this.gotoStage(welcomeStage.loadFromLibrary); } private librariesToOptions(): Array<IDropdownOption> { let items:Array<IDropdownOption> = new Array<IDropdownOption>(); for(var library of this.state.libraries) { items.push({ key: library.ServerRelativeUrl, text: library.Title }); } return items; } @autobind private onOkForLoadFromLibraryClick(): void { this.setState({ loadingFromLibrary: true, loadFromLibraryError: undefined }); sp.web.getFileByServerRelativeUrl(this.state.selectedLibraryUrl + (this.state.libraryFolderPath.length > 0 ? '/' + this.state.libraryFolderPath : '') + '/' + this.state.libraryFileName) .getText() .then((text:string)=>{ this.launchEditorFromText(text, this.state.columnTypeForOpen, saveMethod.Library); this.setState({ loadingFromLibrary: false }); }) .catch((error:any) => { this.setState({ loadingFromLibrary: false, loadFromLibraryError: strings.Welcome_LoadingError + ' ' + strings.TechnicalDetailsErrorHeader + ': ' + error.message }); }); } } function mapStateToProps(state: IApplicationState): IColumnFormatterWelcomeProps{ return { context: state.context, uiHeight: state.ui.height }; } function mapDispatchToProps(dispatch: Dispatch<IColumnFormatterWelcomeProps>): IColumnFormatterWelcomeProps{ return { launchEditor: (wizardName:string, colType:columnTypes) => { dispatch(launchEditor(wizardName, colType)); }, launchEditorWithCode: (wizardName:string, colType:columnTypes, editorString:string, validationErrors:Array<string>, saveDetails:ISaveDetails) => { dispatch(launchEditorWithCode(wizardName, colType, editorString, validationErrors, saveDetails)); } }; } export const ColumnFormatterWelcome = connect(mapStateToProps, mapDispatchToProps)(ColumnFormatterWelcome_);
the_stack
import { invariant } from '../../utilities/globals'; import { dep, OptimisticDependencyFunction } from 'optimism'; import { equal } from '@wry/equality'; import { Trie } from '@wry/trie'; import { isReference, StoreValue, StoreObject, Reference, makeReference, DeepMerger, maybeDeepFreeze, canUseWeakMap, isNonNullObject, } from '../../utilities'; import { NormalizedCache, NormalizedCacheObject } from './types'; import { hasOwn, fieldNameFromStoreName } from './helpers'; import { Policies, StorageType } from './policies'; import { Cache } from '../core/types/Cache'; import { SafeReadonly, Modifier, Modifiers, ReadFieldOptions, ToReferenceFunction, CanReadFunction, } from '../core/types/common'; const DELETE: any = Object.create(null); const delModifier: Modifier<any> = () => DELETE; const INVALIDATE: any = Object.create(null); export abstract class EntityStore implements NormalizedCache { protected data: NormalizedCacheObject = Object.create(null); constructor( public readonly policies: Policies, public readonly group: CacheGroup, ) {} public abstract addLayer( layerId: string, replay: (layer: EntityStore) => any, ): Layer; public abstract removeLayer(layerId: string): EntityStore; // Although the EntityStore class is abstract, it contains concrete // implementations of the various NormalizedCache interface methods that // are inherited by the Root and Layer subclasses. public toObject(): NormalizedCacheObject { return { ...this.data }; } public has(dataId: string): boolean { return this.lookup(dataId, true) !== void 0; } public get(dataId: string, fieldName: string): StoreValue { this.group.depend(dataId, fieldName); if (hasOwn.call(this.data, dataId)) { const storeObject = this.data[dataId]; if (storeObject && hasOwn.call(storeObject, fieldName)) { return storeObject[fieldName]; } } if (fieldName === "__typename" && hasOwn.call(this.policies.rootTypenamesById, dataId)) { return this.policies.rootTypenamesById[dataId]; } if (this instanceof Layer) { return this.parent.get(dataId, fieldName); } } protected lookup(dataId: string, dependOnExistence?: boolean): StoreObject | undefined { // The has method (above) calls lookup with dependOnExistence = true, so // that it can later be invalidated when we add or remove a StoreObject for // this dataId. Any consumer who cares about the contents of the StoreObject // should not rely on this dependency, since the contents could change // without the object being added or removed. if (dependOnExistence) this.group.depend(dataId, "__exists"); if (hasOwn.call(this.data, dataId)) { return this.data[dataId]; } if (this instanceof Layer) { return this.parent.lookup(dataId, dependOnExistence); } if (this.policies.rootTypenamesById[dataId]) { return Object.create(null); } } public merge( older: string | StoreObject, newer: StoreObject | string, ): void { let dataId: string | undefined; // Convert unexpected references to ID strings. if (isReference(older)) older = older.__ref; if (isReference(newer)) newer = newer.__ref; const existing: StoreObject | undefined = typeof older === "string" ? this.lookup(dataId = older) : older; const incoming: StoreObject | undefined = typeof newer === "string" ? this.lookup(dataId = newer) : newer; // If newer was a string ID, but that ID was not defined in this store, // then there are no fields to be merged, so we're done. if (!incoming) return; invariant( typeof dataId === "string", "store.merge expects a string ID", ); const merged: StoreObject = new DeepMerger(storeObjectReconciler).merge(existing, incoming); // Even if merged === existing, existing may have come from a lower // layer, so we always need to set this.data[dataId] on this level. this.data[dataId] = merged; if (merged !== existing) { delete this.refs[dataId]; if (this.group.caching) { const fieldsToDirty: Record<string, 1> = Object.create(null); // If we added a new StoreObject where there was previously none, dirty // anything that depended on the existence of this dataId, such as the // EntityStore#has method. if (!existing) fieldsToDirty.__exists = 1; // Now invalidate dependents who called getFieldValue for any fields // that are changing as a result of this merge. Object.keys(incoming).forEach(storeFieldName => { if (!existing || existing[storeFieldName] !== merged[storeFieldName]) { // Always dirty the full storeFieldName, which may include // serialized arguments following the fieldName prefix. fieldsToDirty[storeFieldName] = 1; // Also dirty fieldNameFromStoreName(storeFieldName) if it's // different from storeFieldName and this field does not have // keyArgs configured, because that means the cache can't make // any assumptions about how field values with the same field // name but different arguments might be interrelated, so it // must err on the side of invalidating all field values that // share the same short fieldName, regardless of arguments. const fieldName = fieldNameFromStoreName(storeFieldName); if (fieldName !== storeFieldName && !this.policies.hasKeyArgs(merged.__typename, fieldName)) { fieldsToDirty[fieldName] = 1; } // If merged[storeFieldName] has become undefined, and this is the // Root layer, actually delete the property from the merged object, // which is guaranteed to have been created fresh in this method. if (merged[storeFieldName] === void 0 && !(this instanceof Layer)) { delete merged[storeFieldName]; } } }); if (fieldsToDirty.__typename && !(existing && existing.__typename) && // Since we return default root __typename strings // automatically from store.get, we don't need to dirty the // ROOT_QUERY.__typename field if merged.__typename is equal // to the default string (usually "Query"). this.policies.rootTypenamesById[dataId] === merged.__typename) { delete fieldsToDirty.__typename; } Object.keys(fieldsToDirty).forEach( fieldName => this.group.dirty(dataId as string, fieldName)); } } } public modify( dataId: string, fields: Modifier<any> | Modifiers, ): boolean { const storeObject = this.lookup(dataId); if (storeObject) { const changedFields: Record<string, any> = Object.create(null); let needToMerge = false; let allDeleted = true; const sharedDetails = { DELETE, INVALIDATE, isReference, toReference: this.toReference, canRead: this.canRead, readField: <V = StoreValue>( fieldNameOrOptions: string | ReadFieldOptions, from?: StoreObject | Reference, ) => this.policies.readField<V>( typeof fieldNameOrOptions === "string" ? { fieldName: fieldNameOrOptions, from: from || makeReference(dataId), } : fieldNameOrOptions, { store: this }, ), }; Object.keys(storeObject).forEach(storeFieldName => { const fieldName = fieldNameFromStoreName(storeFieldName); let fieldValue = storeObject[storeFieldName]; if (fieldValue === void 0) return; const modify: Modifier<StoreValue> = typeof fields === "function" ? fields : fields[storeFieldName] || fields[fieldName]; if (modify) { let newValue = modify === delModifier ? DELETE : modify(maybeDeepFreeze(fieldValue), { ...sharedDetails, fieldName, storeFieldName, storage: this.getStorage(dataId, storeFieldName), }); if (newValue === INVALIDATE) { this.group.dirty(dataId, storeFieldName); } else { if (newValue === DELETE) newValue = void 0; if (newValue !== fieldValue) { changedFields[storeFieldName] = newValue; needToMerge = true; fieldValue = newValue; } } } if (fieldValue !== void 0) { allDeleted = false; } }); if (needToMerge) { this.merge(dataId, changedFields); if (allDeleted) { if (this instanceof Layer) { this.data[dataId] = void 0; } else { delete this.data[dataId]; } this.group.dirty(dataId, "__exists"); } return true; } } return false; } // If called with only one argument, removes the entire entity // identified by dataId. If called with a fieldName as well, removes all // fields of that entity whose names match fieldName according to the // fieldNameFromStoreName helper function. If called with a fieldName // and variables, removes all fields of that entity whose names match fieldName // and whose arguments when cached exactly match the variables passed. public delete( dataId: string, fieldName?: string, args?: Record<string, any>, ) { const storeObject = this.lookup(dataId); if (storeObject) { const typename = this.getFieldValue<string>(storeObject, "__typename"); const storeFieldName = fieldName && args ? this.policies.getStoreFieldName({ typename, fieldName, args }) : fieldName; return this.modify(dataId, storeFieldName ? { [storeFieldName]: delModifier, } : delModifier); } return false; } public evict( options: Cache.EvictOptions, limit: EntityStore, ): boolean { let evicted = false; if (options.id) { if (hasOwn.call(this.data, options.id)) { evicted = this.delete(options.id, options.fieldName, options.args); } if (this instanceof Layer && this !== limit) { evicted = this.parent.evict(options, limit) || evicted; } // Always invalidate the field to trigger rereading of watched // queries, even if no cache data was modified by the eviction, // because queries may depend on computed fields with custom read // functions, whose values are not stored in the EntityStore. if (options.fieldName || evicted) { this.group.dirty(options.id, options.fieldName || "__exists"); } } return evicted; } public clear(): void { this.replace(null); } public extract(): NormalizedCacheObject { const obj = this.toObject(); const extraRootIds: string[] = []; this.getRootIdSet().forEach(id => { if (!hasOwn.call(this.policies.rootTypenamesById, id)) { extraRootIds.push(id); } }); if (extraRootIds.length) { obj.__META = { extraRootIds: extraRootIds.sort() }; } return obj; } public replace(newData: NormalizedCacheObject | null): void { Object.keys(this.data).forEach(dataId => { if (!(newData && hasOwn.call(newData, dataId))) { this.delete(dataId); } }); if (newData) { const { __META, ...rest } = newData; Object.keys(rest).forEach(dataId => { this.merge(dataId, rest[dataId] as StoreObject); }); if (__META) { __META.extraRootIds.forEach(this.retain, this); } } } public abstract getStorage( idOrObj: string | StoreObject, ...storeFieldNames: (string | number)[] ): StorageType; // Maps root entity IDs to the number of times they have been retained, minus // the number of times they have been released. Retained entities keep other // entities they reference (even indirectly) from being garbage collected. private rootIds: { [rootId: string]: number; } = Object.create(null); public retain(rootId: string): number { return this.rootIds[rootId] = (this.rootIds[rootId] || 0) + 1; } public release(rootId: string): number { if (this.rootIds[rootId] > 0) { const count = --this.rootIds[rootId]; if (!count) delete this.rootIds[rootId]; return count; } return 0; } // Return a Set<string> of all the ID strings that have been retained by // this layer/root *and* any layers/roots beneath it. public getRootIdSet(ids = new Set<string>()) { Object.keys(this.rootIds).forEach(ids.add, ids); if (this instanceof Layer) { this.parent.getRootIdSet(ids); } else { // Official singleton IDs like ROOT_QUERY and ROOT_MUTATION are // always considered roots for garbage collection, regardless of // their retainment counts in this.rootIds. Object.keys(this.policies.rootTypenamesById).forEach(ids.add, ids); } return ids; } // The goal of garbage collection is to remove IDs from the Root layer of the // store that are no longer reachable starting from any IDs that have been // explicitly retained (see retain and release, above). Returns an array of // dataId strings that were removed from the store. public gc() { const ids = this.getRootIdSet(); const snapshot = this.toObject(); ids.forEach(id => { if (hasOwn.call(snapshot, id)) { // Because we are iterating over an ECMAScript Set, the IDs we add here // will be visited in later iterations of the forEach loop only if they // were not previously contained by the Set. Object.keys(this.findChildRefIds(id)).forEach(ids.add, ids); // By removing IDs from the snapshot object here, we protect them from // getting removed from the root store layer below. delete snapshot[id]; } }); const idsToRemove = Object.keys(snapshot); if (idsToRemove.length) { let root: EntityStore = this; while (root instanceof Layer) root = root.parent; idsToRemove.forEach(id => root.delete(id)); } return idsToRemove; } // Lazily tracks { __ref: <dataId> } strings contained by this.data[dataId]. private refs: { [dataId: string]: Record<string, true>; } = Object.create(null); public findChildRefIds(dataId: string): Record<string, true> { if (!hasOwn.call(this.refs, dataId)) { const found = this.refs[dataId] = Object.create(null); const root = this.data[dataId]; if (!root) return found; const workSet = new Set<Record<string | number, any>>([root]); // Within the store, only arrays and objects can contain child entity // references, so we can prune the traversal using this predicate: workSet.forEach(obj => { if (isReference(obj)) { found[obj.__ref] = true; // In rare cases, a { __ref } Reference object may have other fields. // This often indicates a mismerging of References with StoreObjects, // but garbage collection should not be fooled by a stray __ref // property in a StoreObject (ignoring all the other fields just // because the StoreObject looks like a Reference). To avoid this // premature termination of findChildRefIds recursion, we fall through // to the code below, which will handle any other properties of obj. } if (isNonNullObject(obj)) { Object.keys(obj).forEach(key => { const child = obj[key]; // No need to add primitive values to the workSet, since they cannot // contain reference objects. if (isNonNullObject(child)) { workSet.add(child); } }); } }); } return this.refs[dataId]; } // Used to compute cache keys specific to this.group. public makeCacheKey(...args: any[]): object; public makeCacheKey() { return this.group.keyMaker.lookupArray(arguments); } // Bound function that can be passed around to provide easy access to fields // of Reference objects as well as ordinary objects. public getFieldValue = <T = StoreValue>( objectOrReference: StoreObject | Reference | undefined, storeFieldName: string, ) => maybeDeepFreeze( isReference(objectOrReference) ? this.get(objectOrReference.__ref, storeFieldName) : objectOrReference && objectOrReference[storeFieldName] ) as SafeReadonly<T>; // Returns true for non-normalized StoreObjects and non-dangling // References, indicating that readField(name, objOrRef) has a chance of // working. Useful for filtering out dangling references from lists. public canRead: CanReadFunction = objOrRef => { return isReference(objOrRef) ? this.has(objOrRef.__ref) : typeof objOrRef === "object"; }; // Bound function that converts an id or an object with a __typename and // primary key fields to a Reference object. If called with a Reference object, // that same Reference object is returned. Pass true for mergeIntoStore to persist // an object into the store. public toReference: ToReferenceFunction = ( objOrIdOrRef, mergeIntoStore, ) => { if (typeof objOrIdOrRef === "string") { return makeReference(objOrIdOrRef); } if (isReference(objOrIdOrRef)) { return objOrIdOrRef; } const [id] = this.policies.identify(objOrIdOrRef); if (id) { const ref = makeReference(id); if (mergeIntoStore) { this.merge(id, objOrIdOrRef); } return ref; } }; } export type FieldValueGetter = EntityStore["getFieldValue"]; // A single CacheGroup represents a set of one or more EntityStore objects, // typically the Root store in a CacheGroup by itself, and all active Layer // stores in a group together. A single EntityStore object belongs to only // one CacheGroup, store.group. The CacheGroup is responsible for tracking // dependencies, so store.group is helpful for generating unique keys for // cached results that need to be invalidated when/if those dependencies // change. If we used the EntityStore objects themselves as cache keys (that // is, store rather than store.group), the cache would become unnecessarily // fragmented by all the different Layer objects. Instead, the CacheGroup // approach allows all optimistic Layer objects in the same linked list to // belong to one CacheGroup, with the non-optimistic Root object belonging // to another CacheGroup, allowing resultCaching dependencies to be tracked // separately for optimistic and non-optimistic entity data. class CacheGroup { private d: OptimisticDependencyFunction<string> | null = null; // Used by the EntityStore#makeCacheKey method to compute cache keys // specific to this CacheGroup. public keyMaker: Trie<object>; constructor( public readonly caching: boolean, private parent: CacheGroup | null = null, ) { this.resetCaching(); } public resetCaching() { this.d = this.caching ? dep<string>() : null; this.keyMaker = new Trie(canUseWeakMap); } public depend(dataId: string, storeFieldName: string) { if (this.d) { this.d(makeDepKey(dataId, storeFieldName)); const fieldName = fieldNameFromStoreName(storeFieldName); if (fieldName !== storeFieldName) { // Fields with arguments that contribute extra identifying // information to the fieldName (thus forming the storeFieldName) // depend not only on the full storeFieldName but also on the // short fieldName, so the field can be invalidated using either // level of specificity. this.d(makeDepKey(dataId, fieldName)); } if (this.parent) { this.parent.depend(dataId, storeFieldName); } } } public dirty(dataId: string, storeFieldName: string) { if (this.d) { this.d.dirty( makeDepKey(dataId, storeFieldName), // When storeFieldName === "__exists", that means the entity identified // by dataId has either disappeared from the cache or was newly added, // so the result caching system would do well to "forget everything it // knows" about that object. To achieve that kind of invalidation, we // not only dirty the associated result cache entry, but also remove it // completely from the dependency graph. For the optimism implementation // details, see https://github.com/benjamn/optimism/pull/195. storeFieldName === "__exists" ? "forget" : "setDirty", ); } } } function makeDepKey(dataId: string, storeFieldName: string) { // Since field names cannot have '#' characters in them, this method // of joining the field name and the ID should be unambiguous, and much // cheaper than JSON.stringify([dataId, fieldName]). return storeFieldName + '#' + dataId; } export function maybeDependOnExistenceOfEntity( store: NormalizedCache, entityId: string, ) { if (supportsResultCaching(store)) { // We use this pseudo-field __exists elsewhere in the EntityStore code to // represent changes in the existence of the entity object identified by // entityId. This dependency gets reliably dirtied whenever an object with // this ID is deleted (or newly created) within this group, so any result // cache entries (for example, StoreReader#executeSelectionSet results) that // depend on __exists for this entityId will get dirtied as well, leading to // the eventual recomputation (instead of reuse) of those result objects the // next time someone reads them from the cache. store.group.depend(entityId, "__exists"); } } export namespace EntityStore { // Refer to this class as EntityStore.Root outside this namespace. export class Root extends EntityStore { constructor({ policies, resultCaching = true, seed, }: { policies: Policies; resultCaching?: boolean; seed?: NormalizedCacheObject; }) { super(policies, new CacheGroup(resultCaching)); if (seed) this.replace(seed); } public readonly stump = new Stump(this); public addLayer( layerId: string, replay: (layer: EntityStore) => any, ): Layer { // Adding an optimistic Layer on top of the Root actually adds the Layer // on top of the Stump, so the Stump always comes between the Root and // any Layer objects that we've added. return this.stump.addLayer(layerId, replay); } public removeLayer(): Root { // Never remove the root layer. return this; } public readonly storageTrie = new Trie<StorageType>(canUseWeakMap); public getStorage(): StorageType { return this.storageTrie.lookupArray(arguments); } } } // Not exported, since all Layer instances are created by the addLayer method // of the EntityStore.Root class. class Layer extends EntityStore { constructor( public readonly id: string, public readonly parent: EntityStore, public readonly replay: (layer: EntityStore) => any, public readonly group: CacheGroup, ) { super(parent.policies, group); replay(this); } public addLayer( layerId: string, replay: (layer: EntityStore) => any, ): Layer { return new Layer(layerId, this, replay, this.group); } public removeLayer(layerId: string): EntityStore { // Remove all instances of the given id, not just the first one. const parent = this.parent.removeLayer(layerId); if (layerId === this.id) { if (this.group.caching) { // Dirty every ID we're removing. Technically we might be able to avoid // dirtying fields that have values in higher layers, but we don't have // easy access to higher layers here, and we're about to recreate those // layers anyway (see parent.addLayer below). Object.keys(this.data).forEach(dataId => { const ownStoreObject = this.data[dataId]; const parentStoreObject = parent["lookup"](dataId); if (!parentStoreObject) { // The StoreObject identified by dataId was defined in this layer // but will be undefined in the parent layer, so we can delete the // whole entity using this.delete(dataId). Since we're about to // throw this layer away, the only goal of this deletion is to dirty // the removed fields. this.delete(dataId); } else if (!ownStoreObject) { // This layer had an entry for dataId but it was undefined, which // means the entity was deleted in this layer, and it's about to // become undeleted when we remove this layer, so we need to dirty // all fields that are about to be reexposed. this.group.dirty(dataId, "__exists"); Object.keys(parentStoreObject).forEach(storeFieldName => { this.group.dirty(dataId, storeFieldName); }); } else if (ownStoreObject !== parentStoreObject) { // If ownStoreObject is not exactly the same as parentStoreObject, // dirty any fields whose values will change as a result of this // removal. Object.keys(ownStoreObject).forEach(storeFieldName => { if (!equal(ownStoreObject[storeFieldName], parentStoreObject[storeFieldName])) { this.group.dirty(dataId, storeFieldName); } }); } }); } return parent; } // No changes are necessary if the parent chain remains identical. if (parent === this.parent) return this; // Recreate this layer on top of the new parent. return parent.addLayer(this.id, this.replay); } public toObject(): NormalizedCacheObject { return { ...this.parent.toObject(), ...this.data, }; } public findChildRefIds(dataId: string): Record<string, true> { const fromParent = this.parent.findChildRefIds(dataId); return hasOwn.call(this.data, dataId) ? { ...fromParent, ...super.findChildRefIds(dataId), } : fromParent; } public getStorage(): StorageType { let p: EntityStore = this.parent; while ((p as Layer).parent) p = (p as Layer).parent; return p.getStorage.apply(p, arguments); } } // Represents a Layer permanently installed just above the Root, which allows // reading optimistically (and registering optimistic dependencies) even when // no optimistic layers are currently active. The stump.group CacheGroup object // is shared by any/all Layer objects added on top of the Stump. class Stump extends Layer { constructor(root: EntityStore.Root) { super( "EntityStore.Stump", root, () => {}, new CacheGroup(root.group.caching, root.group), ); } public removeLayer() { // Never remove the Stump layer. return this; } public merge() { // We never want to write any data into the Stump, so we forward any merge // calls to the Root instead. Another option here would be to throw an // exception, but the toReference(object, true) function can sometimes // trigger Stump writes (which used to be Root writes, before the Stump // concept was introduced). return this.parent.merge.apply(this.parent, arguments); } } function storeObjectReconciler( existingObject: StoreObject, incomingObject: StoreObject, property: string, ): StoreValue { const existingValue = existingObject[property]; const incomingValue = incomingObject[property]; // Wherever there is a key collision, prefer the incoming value, unless // it is deeply equal to the existing value. It's worth checking deep // equality here (even though blindly returning incoming would be // logically correct) because preserving the referential identity of // existing data can prevent needless rereading and rerendering. return equal(existingValue, incomingValue) ? existingValue : incomingValue; } export function supportsResultCaching(store: any): store is EntityStore { // When result caching is disabled, store.depend will be null. return !!(store instanceof EntityStore && store.group.caching); }
the_stack
import { MemoryGraph, NodeType } from "./types"; import type { Heap } from "../../structsGenerator/consts"; import { typeAndRc_refsCount_get, string_size, number_size, object_size, bigint_size, array_size, hashmap_size, hashmapNode_size, linkedList_size, linkedListItem_size, string_charsPointer_get, string_bytesLength_get, array_dataspacePointer_get, array_allocatedLength_get, typeOnly_type_get, hashmap_ARRAY_POINTER_get, hashmap_CAPACITY_get, hashmap_LINKED_LIST_POINTER_get, hashmapNode_KEY_POINTER_get, hashmapNode_LINKED_LIST_ITEM_POINTER_get, hashmapNode_VALUE_POINTER_get, object_pointerToHashMap_get, linkedList_END_POINTER_get, linkedListItem_VALUE_get, } from "../generatedStructs"; import { isKnownAddressValuePointer, createKnownTypeGuard } from "../utils"; import { ENTRY_TYPE } from "../entry-types"; import { assertNonNull } from "../assertNonNull"; import { hashmapNodesPointerIterator } from "../hashmap/hashmap"; import { linkedListLowLevelIterator } from "../linkedList/linkedList"; /** side notes: blocks with dynamic size: * string data space * arrays pointers space * hashmap buckets array space */ /** */ export function createMemoryGraph( heap: Heap, startPointer: number ): { graph: MemoryGraph; visitedPointers: Set<number> } { const graph: MemoryGraph = { nodes: [], edges: [], }; const visitedPointers = new Set<number>(); const entryTypeOfElement = typeOnly_type_get(heap, startPointer); const typeOfElement = entryTypeToNodeType(entryTypeOfElement); visitPointerIteration( heap, startPointer, typeOfElement, null, visitedPointers, graph ); if (graph.nodes.length !== visitedPointers.size) { throw new Error("graph.nodes.length must be === visitedPointers.size"); } return { graph, visitedPointers }; } function visitPointerIteration( heap: Heap, pointer: number, typeOfNode: MemoryGraph["nodes"][0]["type"], sizeOfBlock: number | null, visitedPointers: Set<number>, graph: MemoryGraph ) { if (isKnownAddressValuePointer(pointer)) { return; } if (visitedPointers.has(pointer)) { return; } visitedPointers.add(pointer); // const entryType = typeOnly_type_get(heap, pointer); // eslint-disable-next-line @typescript-eslint/no-use-before-define const refCount = isTypeWithRC(typeOfNode) ? typeAndRc_refsCount_get(heap, pointer) : undefined; switch (typeOfNode) { case "string": graph.nodes.push({ type: typeOfNode, pointer, size: string_size, refCount, }); graph.edges.push({ from: pointer, to: string_charsPointer_get(heap, pointer), }); visitPointerIteration( heap, string_charsPointer_get(heap, pointer), "stringData", string_bytesLength_get(heap, pointer), visitedPointers, graph ); break; case "number": graph.nodes.push({ type: typeOfNode, pointer, size: number_size, refCount, }); break; case "undefined": graph.nodes.push({ type: typeOfNode, pointer, size: 0, refCount }); break; case "null": graph.nodes.push({ type: typeOfNode, pointer, size: 0, refCount }); break; case "true": graph.nodes.push({ type: typeOfNode, pointer, size: 0, refCount }); break; case "stringData": assertNonNull(sizeOfBlock); graph.nodes.push({ type: typeOfNode, pointer, size: sizeOfBlock, refCount, }); break; case "bigintPositive": case "bigintNegative": graph.nodes.push({ type: typeOfNode, pointer, size: bigint_size, refCount, }); break; case "date": graph.nodes.push({ type: typeOfNode, pointer, size: bigint_size, refCount, }); break; case "array": graph.nodes.push({ type: typeOfNode, pointer, size: array_size, refCount, }); graph.edges.push({ from: pointer, to: array_dataspacePointer_get(heap, pointer), }); visitPointerIteration( heap, array_dataspacePointer_get(heap, pointer), "arrayPointers", array_allocatedLength_get(heap, pointer) * Uint32Array.BYTES_PER_ELEMENT, visitedPointers, graph ); break; case "arrayPointers": assertNonNull(sizeOfBlock); graph.nodes.push({ type: typeOfNode, pointer, size: sizeOfBlock, refCount, }); // Maybe pass also array length and not only allocated length for (let i = 0; i < sizeOfBlock; i += Uint32Array.BYTES_PER_ELEMENT) { const pointerToElement = heap.u32[(pointer + i) / Uint32Array.BYTES_PER_ELEMENT]; const entryTypeOfElement = typeOnly_type_get(heap, pointerToElement); const typeOfElement = entryTypeToNodeType(entryTypeOfElement); graph.edges.push({ from: pointer, to: pointerToElement, }); visitPointerIteration( heap, pointerToElement, typeOfElement, null, visitedPointers, graph ); } break; case "object": case "map": case "set": graph.nodes.push({ type: typeOfNode, pointer, size: object_size, refCount, }); graph.edges.push({ from: pointer, to: object_pointerToHashMap_get(heap, pointer), }); visitPointerIteration( heap, object_pointerToHashMap_get(heap, pointer), "hashmap", null, visitedPointers, graph ); break; case "hashmap": graph.nodes.push({ type: typeOfNode, pointer, size: hashmap_size, refCount, }); visitPointerIteration( heap, hashmap_ARRAY_POINTER_get(heap, pointer), "hashmapBuckets", hashmap_CAPACITY_get(heap, pointer) * Uint32Array.BYTES_PER_ELEMENT, visitedPointers, graph ); graph.edges.push({ from: pointer, to: hashmap_ARRAY_POINTER_get(heap, pointer), }); visitPointerIteration( heap, hashmap_LINKED_LIST_POINTER_get(heap, pointer), "linkedList", null, visitedPointers, graph ); graph.edges.push({ from: pointer, to: hashmap_LINKED_LIST_POINTER_get(heap, pointer), }); for (const nodePointer of hashmapNodesPointerIterator(heap, pointer)) { // Not accurate, as nodes are not referenced directly by the hashmap, // But hashmap -> buckets list -> bucket[x] => node1->node2 etc // We have something simplified graph.edges.push({ from: pointer, to: nodePointer, }); visitPointerIteration( heap, nodePointer, "hashmapNode", null, visitedPointers, graph ); } break; case "hashmapBuckets": assertNonNull(sizeOfBlock); graph.nodes.push({ type: typeOfNode, pointer, size: sizeOfBlock, refCount, }); break; case "hashmapNode": graph.nodes.push({ type: typeOfNode, pointer, size: hashmapNode_size, refCount, }); // key visitPointerIteration( heap, hashmapNode_KEY_POINTER_get(heap, pointer), entryTypeToNodeType( typeOnly_type_get(heap, hashmapNode_KEY_POINTER_get(heap, pointer)) ), null, visitedPointers, graph ); graph.edges.push({ from: pointer, to: hashmapNode_KEY_POINTER_get(heap, pointer), }); // linked list item visitPointerIteration( heap, hashmapNode_LINKED_LIST_ITEM_POINTER_get(heap, pointer), "linkedListItem", null, visitedPointers, graph ); graph.edges.push({ from: pointer, to: hashmapNode_LINKED_LIST_ITEM_POINTER_get(heap, pointer), }); // value visitPointerIteration( heap, hashmapNode_VALUE_POINTER_get(heap, pointer), entryTypeToNodeType( typeOnly_type_get(heap, hashmapNode_VALUE_POINTER_get(heap, pointer)) ), null, visitedPointers, graph ); graph.edges.push({ from: pointer, to: hashmapNode_VALUE_POINTER_get(heap, pointer), }); break; case "linkedList": graph.nodes.push({ type: typeOfNode, pointer, size: linkedList_size, refCount, }); // eslint-disable-next-line no-case-declarations let linkedListItemIterator = 0; while ( (linkedListItemIterator = linkedListLowLevelIterator( heap, pointer, linkedListItemIterator )) !== 0 ) { if (linkedListItemIterator === undefined) { throw new Error("WTF"); } graph.edges.push({ from: pointer, to: linkedListItemIterator, }); visitPointerIteration( heap, linkedListItemIterator, "linkedListItem", null, visitedPointers, graph ); } // end marker visitPointerIteration( heap, linkedList_END_POINTER_get(heap, pointer), "linkedListItem", null, visitedPointers, graph ); graph.edges.push({ from: pointer, to: linkedList_END_POINTER_get(heap, pointer), specialLabel: "linkedlist end marker", }); break; case "linkedListItem": graph.nodes.push({ type: typeOfNode, pointer, size: linkedListItem_size, refCount, }); // The value is always hashmap node atm visitPointerIteration( heap, linkedListItem_VALUE_get(heap, pointer), "hashmapNode", null, visitedPointers, graph ); graph.edges.push({ from: pointer, to: linkedListItem_VALUE_get(heap, pointer), }); break; } } const isTypeWithRC = createKnownTypeGuard([ "string", "array", "object", "set", "map", "date", ]); const nodeEntryToType = { [ENTRY_TYPE.BIGINT_NEGATIVE]: "bigintNegative", [ENTRY_TYPE.BIGINT_POSITIVE]: "bigintPositive", [ENTRY_TYPE.ARRAY]: "array", [ENTRY_TYPE.MAP]: "map", [ENTRY_TYPE.SET]: "set", [ENTRY_TYPE.OBJECT]: "object", [ENTRY_TYPE.STRING]: "string", [ENTRY_TYPE.NUMBER]: "number", [ENTRY_TYPE.DATE]: "date", } as const; function entryTypeToNodeType(entryType: ENTRY_TYPE): NodeType { return nodeEntryToType[entryType]; } export function mergeGraphs( graphA: MemoryGraph, graphB: MemoryGraph ): MemoryGraph { return { nodes: [...graphA.nodes, ...graphB.nodes], edges: [...graphA.edges, ...graphB.edges], }; } export function mergeGraphsNoIntersections(graphs: MemoryGraph[]): MemoryGraph { const fullPointers = graphs .map((graph) => graph.nodes.map((n) => n.pointer)) .flat(); const pointers = new Set(fullPointers); const fullEdgesList = graphs .map((graph) => graph.edges.map((e) => `${e.from}-${e.to}`)) .flat(); const edges = new Set(fullEdgesList); if (pointers.size !== fullPointers.length) { throw new Error("There are intersections in nodes"); } if (edges.size !== fullEdgesList.length) { throw new Error("There are intersections edges"); } return { nodes: graphs.map((g) => g.nodes).flat(), edges: graphs.map((g) => g.edges).flat(), }; }
the_stack
/* eslint-disable @typescript-eslint/class-name-casing */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-empty-interface */ /* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable no-irregular-whitespace */ import { OAuth2Client, JWT, Compute, UserRefreshClient, BaseExternalAccountClient, GaxiosPromise, GoogleConfigurable, createAPIRequest, MethodOptions, StreamMethodOptions, GlobalOptions, GoogleAuth, BodyResponseCallback, APIRequestContext, } from 'googleapis-common'; import {Readable} from 'stream'; export namespace gamesConfiguration_v1configuration { export interface Options extends GlobalOptions { version: 'v1configuration'; } interface StandardParameters { /** * Auth client or API Key for the request */ auth?: | string | OAuth2Client | JWT | Compute | UserRefreshClient | BaseExternalAccountClient | GoogleAuth; /** * V1 error format. */ '$.xgafv'?: string; /** * OAuth access token. */ access_token?: string; /** * Data format for response. */ alt?: string; /** * JSONP */ callback?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; } /** * Google Play Game Services Publishing API * * The Google Play Game Services Publishing API allows developers to configure their games in Game Services. * * @example * ```js * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * ``` */ export class Gamesconfiguration { context: APIRequestContext; achievementConfigurations: Resource$Achievementconfigurations; imageConfigurations: Resource$Imageconfigurations; leaderboardConfigurations: Resource$Leaderboardconfigurations; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.achievementConfigurations = new Resource$Achievementconfigurations( this.context ); this.imageConfigurations = new Resource$Imageconfigurations(this.context); this.leaderboardConfigurations = new Resource$Leaderboardconfigurations( this.context ); } } /** * An achievement configuration resource. */ export interface Schema$AchievementConfiguration { /** * The type of the achievement. */ achievementType?: string | null; /** * The draft data of the achievement. */ draft?: Schema$AchievementConfigurationDetail; /** * The ID of the achievement. */ id?: string | null; /** * The initial state of the achievement. */ initialState?: string | null; /** * Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#achievementConfiguration`. */ kind?: string | null; /** * The read-only published data of the achievement. */ published?: Schema$AchievementConfigurationDetail; /** * Steps to unlock. Only applicable to incremental achievements. */ stepsToUnlock?: number | null; /** * The token for this resource. */ token?: string | null; } /** * An achievement configuration detail. */ export interface Schema$AchievementConfigurationDetail { /** * Localized strings for the achievement description. */ description?: Schema$LocalizedStringBundle; /** * The icon url of this achievement. Writes to this field are ignored. */ iconUrl?: string | null; /** * Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#achievementConfigurationDetail`. */ kind?: string | null; /** * Localized strings for the achievement name. */ name?: Schema$LocalizedStringBundle; /** * Point value for the achievement. */ pointValue?: number | null; /** * The sort rank of this achievement. Writes to this field are ignored. */ sortRank?: number | null; } /** * A ListConfigurations response. */ export interface Schema$AchievementConfigurationListResponse { /** * The achievement configurations. */ items?: Schema$AchievementConfiguration[]; /** * Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#achievementConfigurationListResponse`. */ kind?: string | null; /** * The pagination token for the next page of results. */ nextPageToken?: string | null; } /** * A number affix resource. */ export interface Schema$GamesNumberAffixConfiguration { /** * When the language requires special treatment of "small" numbers (as with 2, 3, and 4 in Czech; or numbers ending 2, 3, or 4 but not 12, 13, or 14 in Polish). */ few?: Schema$LocalizedStringBundle; /** * When the language requires special treatment of "large" numbers (as with numbers ending 11-99 in Maltese). */ many?: Schema$LocalizedStringBundle; /** * When the language requires special treatment of numbers like one (as with the number 1 in English and most other languages; in Russian, any number ending in 1 but not ending in 11 is in this class). */ one?: Schema$LocalizedStringBundle; /** * When the language does not require special treatment of the given quantity (as with all numbers in Chinese, or 42 in English). */ other?: Schema$LocalizedStringBundle; /** * When the language requires special treatment of numbers like two (as with 2 in Welsh, or 102 in Slovenian). */ two?: Schema$LocalizedStringBundle; /** * When the language requires special treatment of the number 0 (as in Arabic). */ zero?: Schema$LocalizedStringBundle; } /** * A number format resource. */ export interface Schema$GamesNumberFormatConfiguration { /** * The curreny code string. Only used for CURRENCY format type. */ currencyCode?: string | null; /** * The formatting for the number. */ numberFormatType?: string | null; /** * The number of decimal places for number. Only used for NUMERIC format type. */ numDecimalPlaces?: number | null; /** * An optional suffix for the NUMERIC format type. These strings follow the same plural rules as all Android string resources. */ suffix?: Schema$GamesNumberAffixConfiguration; } /** * An image configuration resource. */ export interface Schema$ImageConfiguration { /** * The image type for the image. */ imageType?: string | null; /** * Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#imageConfiguration`. */ kind?: string | null; /** * The resource ID of resource which the image belongs to. */ resourceId?: string | null; /** * The url for this image. */ url?: string | null; } /** * An leaderboard configuration resource. */ export interface Schema$LeaderboardConfiguration { /** * The draft data of the leaderboard. */ draft?: Schema$LeaderboardConfigurationDetail; /** * The ID of the leaderboard. */ id?: string | null; /** * Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#leaderboardConfiguration`. */ kind?: string | null; /** * The read-only published data of the leaderboard. */ published?: Schema$LeaderboardConfigurationDetail; /** * Maximum score that can be posted to this leaderboard. */ scoreMax?: string | null; /** * Minimum score that can be posted to this leaderboard. */ scoreMin?: string | null; scoreOrder?: string | null; /** * The token for this resource. */ token?: string | null; } /** * A leaderboard configuration detail. */ export interface Schema$LeaderboardConfigurationDetail { /** * The icon url of this leaderboard. Writes to this field are ignored. */ iconUrl?: string | null; /** * Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#leaderboardConfigurationDetail`. */ kind?: string | null; /** * Localized strings for the leaderboard name. */ name?: Schema$LocalizedStringBundle; /** * The score formatting for the leaderboard. */ scoreFormat?: Schema$GamesNumberFormatConfiguration; /** * The sort rank of this leaderboard. Writes to this field are ignored. */ sortRank?: number | null; } /** * A ListConfigurations response. */ export interface Schema$LeaderboardConfigurationListResponse { /** * The leaderboard configurations. */ items?: Schema$LeaderboardConfiguration[]; /** * Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#leaderboardConfigurationListResponse`. */ kind?: string | null; /** * The pagination token for the next page of results. */ nextPageToken?: string | null; } /** * A localized string resource. */ export interface Schema$LocalizedString { /** * Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#localizedString`. */ kind?: string | null; /** * The locale string. */ locale?: string | null; /** * The string value. */ value?: string | null; } /** * A localized string bundle resource. */ export interface Schema$LocalizedStringBundle { /** * Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#localizedStringBundle`. */ kind?: string | null; /** * The locale strings. */ translations?: Schema$LocalizedString[]; } export class Resource$Achievementconfigurations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Delete the achievement configuration with the given ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/gamesConfiguration.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/androidpublisher'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await gamesConfiguration.achievementConfigurations.delete({ * // The ID of the achievement used by this method. * achievementId: 'placeholder-value', * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Achievementconfigurations$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Achievementconfigurations$Delete, options?: MethodOptions ): GaxiosPromise<void>; delete( params: Params$Resource$Achievementconfigurations$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Achievementconfigurations$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void> ): void; delete( params: Params$Resource$Achievementconfigurations$Delete, callback: BodyResponseCallback<void> ): void; delete(callback: BodyResponseCallback<void>): void; delete( paramsOrCallback?: | Params$Resource$Achievementconfigurations$Delete | BodyResponseCallback<void> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<void> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<void> | BodyResponseCallback<Readable> ): void | GaxiosPromise<void> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Achievementconfigurations$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Achievementconfigurations$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://gamesconfiguration.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/games/v1configuration/achievements/{achievementId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['achievementId'], pathParams: ['achievementId'], context: this.context, }; if (callback) { createAPIRequest<void>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<void>(parameters); } } /** * Retrieves the metadata of the achievement configuration with the given ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/gamesConfiguration.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/androidpublisher'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await gamesConfiguration.achievementConfigurations.get({ * // The ID of the achievement used by this method. * achievementId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "achievementType": "my_achievementType", * // "draft": {}, * // "id": "my_id", * // "initialState": "my_initialState", * // "kind": "my_kind", * // "published": {}, * // "stepsToUnlock": 0, * // "token": "my_token" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Achievementconfigurations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Achievementconfigurations$Get, options?: MethodOptions ): GaxiosPromise<Schema$AchievementConfiguration>; get( params: Params$Resource$Achievementconfigurations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Achievementconfigurations$Get, options: | MethodOptions | BodyResponseCallback<Schema$AchievementConfiguration>, callback: BodyResponseCallback<Schema$AchievementConfiguration> ): void; get( params: Params$Resource$Achievementconfigurations$Get, callback: BodyResponseCallback<Schema$AchievementConfiguration> ): void; get(callback: BodyResponseCallback<Schema$AchievementConfiguration>): void; get( paramsOrCallback?: | Params$Resource$Achievementconfigurations$Get | BodyResponseCallback<Schema$AchievementConfiguration> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$AchievementConfiguration> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$AchievementConfiguration> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$AchievementConfiguration> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Achievementconfigurations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Achievementconfigurations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://gamesconfiguration.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/games/v1configuration/achievements/{achievementId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['achievementId'], pathParams: ['achievementId'], context: this.context, }; if (callback) { createAPIRequest<Schema$AchievementConfiguration>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$AchievementConfiguration>(parameters); } } /** * Insert a new achievement configuration in this application. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/gamesConfiguration.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/androidpublisher'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await gamesConfiguration.achievementConfigurations.insert({ * // The application ID from the Google Play developer console. * applicationId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "achievementType": "my_achievementType", * // "draft": {}, * // "id": "my_id", * // "initialState": "my_initialState", * // "kind": "my_kind", * // "published": {}, * // "stepsToUnlock": 0, * // "token": "my_token" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "achievementType": "my_achievementType", * // "draft": {}, * // "id": "my_id", * // "initialState": "my_initialState", * // "kind": "my_kind", * // "published": {}, * // "stepsToUnlock": 0, * // "token": "my_token" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ insert( params: Params$Resource$Achievementconfigurations$Insert, options: StreamMethodOptions ): GaxiosPromise<Readable>; insert( params?: Params$Resource$Achievementconfigurations$Insert, options?: MethodOptions ): GaxiosPromise<Schema$AchievementConfiguration>; insert( params: Params$Resource$Achievementconfigurations$Insert, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; insert( params: Params$Resource$Achievementconfigurations$Insert, options: | MethodOptions | BodyResponseCallback<Schema$AchievementConfiguration>, callback: BodyResponseCallback<Schema$AchievementConfiguration> ): void; insert( params: Params$Resource$Achievementconfigurations$Insert, callback: BodyResponseCallback<Schema$AchievementConfiguration> ): void; insert( callback: BodyResponseCallback<Schema$AchievementConfiguration> ): void; insert( paramsOrCallback?: | Params$Resource$Achievementconfigurations$Insert | BodyResponseCallback<Schema$AchievementConfiguration> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$AchievementConfiguration> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$AchievementConfiguration> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$AchievementConfiguration> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Achievementconfigurations$Insert; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Achievementconfigurations$Insert; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://gamesconfiguration.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/games/v1configuration/applications/{applicationId}/achievements' ).replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['applicationId'], pathParams: ['applicationId'], context: this.context, }; if (callback) { createAPIRequest<Schema$AchievementConfiguration>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$AchievementConfiguration>(parameters); } } /** * Returns a list of the achievement configurations in this application. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/gamesConfiguration.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/androidpublisher'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await gamesConfiguration.achievementConfigurations.list({ * // The application ID from the Google Play developer console. * applicationId: 'placeholder-value', * // The maximum number of resource configurations to return in the response, used for paging. For any response, the actual number of resources returned may be less than the specified `maxResults`. * maxResults: 'placeholder-value', * // The token returned by the previous request. * pageToken: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "items": [], * // "kind": "my_kind", * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Achievementconfigurations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Achievementconfigurations$List, options?: MethodOptions ): GaxiosPromise<Schema$AchievementConfigurationListResponse>; list( params: Params$Resource$Achievementconfigurations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Achievementconfigurations$List, options: | MethodOptions | BodyResponseCallback<Schema$AchievementConfigurationListResponse>, callback: BodyResponseCallback<Schema$AchievementConfigurationListResponse> ): void; list( params: Params$Resource$Achievementconfigurations$List, callback: BodyResponseCallback<Schema$AchievementConfigurationListResponse> ): void; list( callback: BodyResponseCallback<Schema$AchievementConfigurationListResponse> ): void; list( paramsOrCallback?: | Params$Resource$Achievementconfigurations$List | BodyResponseCallback<Schema$AchievementConfigurationListResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$AchievementConfigurationListResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$AchievementConfigurationListResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$AchievementConfigurationListResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Achievementconfigurations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Achievementconfigurations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://gamesconfiguration.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/games/v1configuration/applications/{applicationId}/achievements' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['applicationId'], pathParams: ['applicationId'], context: this.context, }; if (callback) { createAPIRequest<Schema$AchievementConfigurationListResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$AchievementConfigurationListResponse>( parameters ); } } /** * Update the metadata of the achievement configuration with the given ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/gamesConfiguration.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/androidpublisher'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await gamesConfiguration.achievementConfigurations.update({ * // The ID of the achievement used by this method. * achievementId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "achievementType": "my_achievementType", * // "draft": {}, * // "id": "my_id", * // "initialState": "my_initialState", * // "kind": "my_kind", * // "published": {}, * // "stepsToUnlock": 0, * // "token": "my_token" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "achievementType": "my_achievementType", * // "draft": {}, * // "id": "my_id", * // "initialState": "my_initialState", * // "kind": "my_kind", * // "published": {}, * // "stepsToUnlock": 0, * // "token": "my_token" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ update( params: Params$Resource$Achievementconfigurations$Update, options: StreamMethodOptions ): GaxiosPromise<Readable>; update( params?: Params$Resource$Achievementconfigurations$Update, options?: MethodOptions ): GaxiosPromise<Schema$AchievementConfiguration>; update( params: Params$Resource$Achievementconfigurations$Update, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; update( params: Params$Resource$Achievementconfigurations$Update, options: | MethodOptions | BodyResponseCallback<Schema$AchievementConfiguration>, callback: BodyResponseCallback<Schema$AchievementConfiguration> ): void; update( params: Params$Resource$Achievementconfigurations$Update, callback: BodyResponseCallback<Schema$AchievementConfiguration> ): void; update( callback: BodyResponseCallback<Schema$AchievementConfiguration> ): void; update( paramsOrCallback?: | Params$Resource$Achievementconfigurations$Update | BodyResponseCallback<Schema$AchievementConfiguration> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$AchievementConfiguration> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$AchievementConfiguration> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$AchievementConfiguration> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Achievementconfigurations$Update; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Achievementconfigurations$Update; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://gamesconfiguration.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/games/v1configuration/achievements/{achievementId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'PUT', }, options ), params, requiredParams: ['achievementId'], pathParams: ['achievementId'], context: this.context, }; if (callback) { createAPIRequest<Schema$AchievementConfiguration>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$AchievementConfiguration>(parameters); } } } export interface Params$Resource$Achievementconfigurations$Delete extends StandardParameters { /** * The ID of the achievement used by this method. */ achievementId?: string; } export interface Params$Resource$Achievementconfigurations$Get extends StandardParameters { /** * The ID of the achievement used by this method. */ achievementId?: string; } export interface Params$Resource$Achievementconfigurations$Insert extends StandardParameters { /** * The application ID from the Google Play developer console. */ applicationId?: string; /** * Request body metadata */ requestBody?: Schema$AchievementConfiguration; } export interface Params$Resource$Achievementconfigurations$List extends StandardParameters { /** * The application ID from the Google Play developer console. */ applicationId?: string; /** * The maximum number of resource configurations to return in the response, used for paging. For any response, the actual number of resources returned may be less than the specified `maxResults`. */ maxResults?: number; /** * The token returned by the previous request. */ pageToken?: string; } export interface Params$Resource$Achievementconfigurations$Update extends StandardParameters { /** * The ID of the achievement used by this method. */ achievementId?: string; /** * Request body metadata */ requestBody?: Schema$AchievementConfiguration; } export class Resource$Imageconfigurations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Uploads an image for a resource with the given ID and image type. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/gamesConfiguration.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/androidpublisher'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await gamesConfiguration.imageConfigurations.upload({ * // Selects which image in a resource for this method. * imageType: 'placeholder-value', * // The ID of the resource used by this method. * resourceId: 'placeholder-value', * * requestBody: { * // request body parameters * }, * media: { * mimeType: 'placeholder-value', * body: 'placeholder-value', * }, * }); * console.log(res.data); * * // Example response * // { * // "imageType": "my_imageType", * // "kind": "my_kind", * // "resourceId": "my_resourceId", * // "url": "my_url" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ upload( params: Params$Resource$Imageconfigurations$Upload, options: StreamMethodOptions ): GaxiosPromise<Readable>; upload( params?: Params$Resource$Imageconfigurations$Upload, options?: MethodOptions ): GaxiosPromise<Schema$ImageConfiguration>; upload( params: Params$Resource$Imageconfigurations$Upload, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; upload( params: Params$Resource$Imageconfigurations$Upload, options: MethodOptions | BodyResponseCallback<Schema$ImageConfiguration>, callback: BodyResponseCallback<Schema$ImageConfiguration> ): void; upload( params: Params$Resource$Imageconfigurations$Upload, callback: BodyResponseCallback<Schema$ImageConfiguration> ): void; upload(callback: BodyResponseCallback<Schema$ImageConfiguration>): void; upload( paramsOrCallback?: | Params$Resource$Imageconfigurations$Upload | BodyResponseCallback<Schema$ImageConfiguration> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ImageConfiguration> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ImageConfiguration> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ImageConfiguration> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Imageconfigurations$Upload; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Imageconfigurations$Upload; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://gamesconfiguration.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/games/v1configuration/images/{resourceId}/imageType/{imageType}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, mediaUrl: ( rootUrl + '/upload/games/v1configuration/images/{resourceId}/imageType/{imageType}' ).replace(/([^:]\/)\/+/g, '$1'), requiredParams: ['resourceId', 'imageType'], pathParams: ['imageType', 'resourceId'], context: this.context, }; if (callback) { createAPIRequest<Schema$ImageConfiguration>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ImageConfiguration>(parameters); } } } export interface Params$Resource$Imageconfigurations$Upload extends StandardParameters { /** * Selects which image in a resource for this method. */ imageType?: string; /** * The ID of the resource used by this method. */ resourceId?: string; /** * Request body metadata */ requestBody?: {}; /** * Media metadata */ media?: { /** * Media mime-type */ mimeType?: string; /** * Media body contents */ body?: any; }; } export class Resource$Leaderboardconfigurations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Delete the leaderboard configuration with the given ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/gamesConfiguration.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/androidpublisher'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await gamesConfiguration.leaderboardConfigurations.delete({ * // The ID of the leaderboard. * leaderboardId: 'placeholder-value', * }); * console.log(res.data); * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Leaderboardconfigurations$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Leaderboardconfigurations$Delete, options?: MethodOptions ): GaxiosPromise<void>; delete( params: Params$Resource$Leaderboardconfigurations$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Leaderboardconfigurations$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void> ): void; delete( params: Params$Resource$Leaderboardconfigurations$Delete, callback: BodyResponseCallback<void> ): void; delete(callback: BodyResponseCallback<void>): void; delete( paramsOrCallback?: | Params$Resource$Leaderboardconfigurations$Delete | BodyResponseCallback<void> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<void> | BodyResponseCallback<Readable>, callback?: BodyResponseCallback<void> | BodyResponseCallback<Readable> ): void | GaxiosPromise<void> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Leaderboardconfigurations$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Leaderboardconfigurations$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://gamesconfiguration.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/games/v1configuration/leaderboards/{leaderboardId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['leaderboardId'], pathParams: ['leaderboardId'], context: this.context, }; if (callback) { createAPIRequest<void>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<void>(parameters); } } /** * Retrieves the metadata of the leaderboard configuration with the given ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/gamesConfiguration.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/androidpublisher'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await gamesConfiguration.leaderboardConfigurations.get({ * // The ID of the leaderboard. * leaderboardId: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "draft": {}, * // "id": "my_id", * // "kind": "my_kind", * // "published": {}, * // "scoreMax": "my_scoreMax", * // "scoreMin": "my_scoreMin", * // "scoreOrder": "my_scoreOrder", * // "token": "my_token" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Leaderboardconfigurations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Leaderboardconfigurations$Get, options?: MethodOptions ): GaxiosPromise<Schema$LeaderboardConfiguration>; get( params: Params$Resource$Leaderboardconfigurations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Leaderboardconfigurations$Get, options: | MethodOptions | BodyResponseCallback<Schema$LeaderboardConfiguration>, callback: BodyResponseCallback<Schema$LeaderboardConfiguration> ): void; get( params: Params$Resource$Leaderboardconfigurations$Get, callback: BodyResponseCallback<Schema$LeaderboardConfiguration> ): void; get(callback: BodyResponseCallback<Schema$LeaderboardConfiguration>): void; get( paramsOrCallback?: | Params$Resource$Leaderboardconfigurations$Get | BodyResponseCallback<Schema$LeaderboardConfiguration> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$LeaderboardConfiguration> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$LeaderboardConfiguration> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$LeaderboardConfiguration> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Leaderboardconfigurations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Leaderboardconfigurations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://gamesconfiguration.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/games/v1configuration/leaderboards/{leaderboardId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['leaderboardId'], pathParams: ['leaderboardId'], context: this.context, }; if (callback) { createAPIRequest<Schema$LeaderboardConfiguration>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$LeaderboardConfiguration>(parameters); } } /** * Insert a new leaderboard configuration in this application. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/gamesConfiguration.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/androidpublisher'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await gamesConfiguration.leaderboardConfigurations.insert({ * // The application ID from the Google Play developer console. * applicationId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "draft": {}, * // "id": "my_id", * // "kind": "my_kind", * // "published": {}, * // "scoreMax": "my_scoreMax", * // "scoreMin": "my_scoreMin", * // "scoreOrder": "my_scoreOrder", * // "token": "my_token" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "draft": {}, * // "id": "my_id", * // "kind": "my_kind", * // "published": {}, * // "scoreMax": "my_scoreMax", * // "scoreMin": "my_scoreMin", * // "scoreOrder": "my_scoreOrder", * // "token": "my_token" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ insert( params: Params$Resource$Leaderboardconfigurations$Insert, options: StreamMethodOptions ): GaxiosPromise<Readable>; insert( params?: Params$Resource$Leaderboardconfigurations$Insert, options?: MethodOptions ): GaxiosPromise<Schema$LeaderboardConfiguration>; insert( params: Params$Resource$Leaderboardconfigurations$Insert, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; insert( params: Params$Resource$Leaderboardconfigurations$Insert, options: | MethodOptions | BodyResponseCallback<Schema$LeaderboardConfiguration>, callback: BodyResponseCallback<Schema$LeaderboardConfiguration> ): void; insert( params: Params$Resource$Leaderboardconfigurations$Insert, callback: BodyResponseCallback<Schema$LeaderboardConfiguration> ): void; insert( callback: BodyResponseCallback<Schema$LeaderboardConfiguration> ): void; insert( paramsOrCallback?: | Params$Resource$Leaderboardconfigurations$Insert | BodyResponseCallback<Schema$LeaderboardConfiguration> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$LeaderboardConfiguration> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$LeaderboardConfiguration> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$LeaderboardConfiguration> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Leaderboardconfigurations$Insert; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Leaderboardconfigurations$Insert; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://gamesconfiguration.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/games/v1configuration/applications/{applicationId}/leaderboards' ).replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['applicationId'], pathParams: ['applicationId'], context: this.context, }; if (callback) { createAPIRequest<Schema$LeaderboardConfiguration>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$LeaderboardConfiguration>(parameters); } } /** * Returns a list of the leaderboard configurations in this application. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/gamesConfiguration.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/androidpublisher'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await gamesConfiguration.leaderboardConfigurations.list({ * // The application ID from the Google Play developer console. * applicationId: 'placeholder-value', * // The maximum number of resource configurations to return in the response, used for paging. For any response, the actual number of resources returned may be less than the specified `maxResults`. * maxResults: 'placeholder-value', * // The token returned by the previous request. * pageToken: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "items": [], * // "kind": "my_kind", * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Leaderboardconfigurations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Leaderboardconfigurations$List, options?: MethodOptions ): GaxiosPromise<Schema$LeaderboardConfigurationListResponse>; list( params: Params$Resource$Leaderboardconfigurations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Leaderboardconfigurations$List, options: | MethodOptions | BodyResponseCallback<Schema$LeaderboardConfigurationListResponse>, callback: BodyResponseCallback<Schema$LeaderboardConfigurationListResponse> ): void; list( params: Params$Resource$Leaderboardconfigurations$List, callback: BodyResponseCallback<Schema$LeaderboardConfigurationListResponse> ): void; list( callback: BodyResponseCallback<Schema$LeaderboardConfigurationListResponse> ): void; list( paramsOrCallback?: | Params$Resource$Leaderboardconfigurations$List | BodyResponseCallback<Schema$LeaderboardConfigurationListResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$LeaderboardConfigurationListResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$LeaderboardConfigurationListResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$LeaderboardConfigurationListResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Leaderboardconfigurations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Leaderboardconfigurations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://gamesconfiguration.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/games/v1configuration/applications/{applicationId}/leaderboards' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['applicationId'], pathParams: ['applicationId'], context: this.context, }; if (callback) { createAPIRequest<Schema$LeaderboardConfigurationListResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$LeaderboardConfigurationListResponse>( parameters ); } } /** * Update the metadata of the leaderboard configuration with the given ID. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/gamesConfiguration.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const gamesConfiguration = google.gamesConfiguration('v1configuration'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/androidpublisher'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await gamesConfiguration.leaderboardConfigurations.update({ * // The ID of the leaderboard. * leaderboardId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "draft": {}, * // "id": "my_id", * // "kind": "my_kind", * // "published": {}, * // "scoreMax": "my_scoreMax", * // "scoreMin": "my_scoreMin", * // "scoreOrder": "my_scoreOrder", * // "token": "my_token" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "draft": {}, * // "id": "my_id", * // "kind": "my_kind", * // "published": {}, * // "scoreMax": "my_scoreMax", * // "scoreMin": "my_scoreMin", * // "scoreOrder": "my_scoreOrder", * // "token": "my_token" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ update( params: Params$Resource$Leaderboardconfigurations$Update, options: StreamMethodOptions ): GaxiosPromise<Readable>; update( params?: Params$Resource$Leaderboardconfigurations$Update, options?: MethodOptions ): GaxiosPromise<Schema$LeaderboardConfiguration>; update( params: Params$Resource$Leaderboardconfigurations$Update, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; update( params: Params$Resource$Leaderboardconfigurations$Update, options: | MethodOptions | BodyResponseCallback<Schema$LeaderboardConfiguration>, callback: BodyResponseCallback<Schema$LeaderboardConfiguration> ): void; update( params: Params$Resource$Leaderboardconfigurations$Update, callback: BodyResponseCallback<Schema$LeaderboardConfiguration> ): void; update( callback: BodyResponseCallback<Schema$LeaderboardConfiguration> ): void; update( paramsOrCallback?: | Params$Resource$Leaderboardconfigurations$Update | BodyResponseCallback<Schema$LeaderboardConfiguration> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$LeaderboardConfiguration> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$LeaderboardConfiguration> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$LeaderboardConfiguration> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Leaderboardconfigurations$Update; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Leaderboardconfigurations$Update; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://gamesconfiguration.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/games/v1configuration/leaderboards/{leaderboardId}' ).replace(/([^:]\/)\/+/g, '$1'), method: 'PUT', }, options ), params, requiredParams: ['leaderboardId'], pathParams: ['leaderboardId'], context: this.context, }; if (callback) { createAPIRequest<Schema$LeaderboardConfiguration>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$LeaderboardConfiguration>(parameters); } } } export interface Params$Resource$Leaderboardconfigurations$Delete extends StandardParameters { /** * The ID of the leaderboard. */ leaderboardId?: string; } export interface Params$Resource$Leaderboardconfigurations$Get extends StandardParameters { /** * The ID of the leaderboard. */ leaderboardId?: string; } export interface Params$Resource$Leaderboardconfigurations$Insert extends StandardParameters { /** * The application ID from the Google Play developer console. */ applicationId?: string; /** * Request body metadata */ requestBody?: Schema$LeaderboardConfiguration; } export interface Params$Resource$Leaderboardconfigurations$List extends StandardParameters { /** * The application ID from the Google Play developer console. */ applicationId?: string; /** * The maximum number of resource configurations to return in the response, used for paging. For any response, the actual number of resources returned may be less than the specified `maxResults`. */ maxResults?: number; /** * The token returned by the previous request. */ pageToken?: string; } export interface Params$Resource$Leaderboardconfigurations$Update extends StandardParameters { /** * The ID of the leaderboard. */ leaderboardId?: string; /** * Request body metadata */ requestBody?: Schema$LeaderboardConfiguration; } }
the_stack
import { SpanStatusCode } from "@azure/core-tracing"; import { createSpan } from "../tracing"; import { PagedAsyncIterableIterator } from "@azure/core-paging"; import * as coreHttp from "@azure/core-http"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { DeviceUpdateClientContext } from "../deviceUpdateClientContext"; import { DeviceClass, UpdateId, Device, DevicesGetAllDevicesNextOptionalParams, DevicesGetAllDevicesOptionalParams, DeviceTag, Group, UpdatableDevices, DevicesGetGroupBestUpdatesNextOptionalParams, DevicesGetGroupBestUpdatesOptionalParams, DevicesGetAllDeviceClassesResponse, DevicesGetDeviceClassResponse, DevicesGetDeviceClassDeviceIdsResponse, DevicesGetDeviceClassInstallableUpdatesResponse, DevicesGetAllDevicesResponse, DevicesGetDeviceResponse, DevicesGetUpdateComplianceResponse, DevicesGetAllDeviceTagsResponse, DevicesGetDeviceTagResponse, DevicesGetAllGroupsResponse, DevicesGetGroupResponse, DevicesCreateOrUpdateGroupResponse, DevicesGetGroupUpdateComplianceResponse, DevicesGetGroupBestUpdatesResponse, DevicesGetAllDeviceClassesNextResponse, DevicesGetDeviceClassDeviceIdsNextResponse, DevicesGetDeviceClassInstallableUpdatesNextResponse, DevicesGetAllDevicesNextResponse, DevicesGetAllDeviceTagsNextResponse, DevicesGetAllGroupsNextResponse, DevicesGetGroupBestUpdatesNextResponse } from "../models"; /** Class representing a Devices. */ export class Devices { private readonly client: DeviceUpdateClientContext; /** * Initialize a new instance of the class Devices class. * @param client Reference to the service client */ constructor(client: DeviceUpdateClientContext) { this.client = client; } /** * Gets a list of all device classes (unique combinations of device manufacturer and model) for all * devices connected to Device Update for IoT Hub. * @param options The options parameters. */ public listAllDeviceClasses( options?: coreHttp.OperationOptions ): PagedAsyncIterableIterator<DeviceClass> { const iter = this.getAllDeviceClassesPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getAllDeviceClassesPagingPage(options); } }; } private async *getAllDeviceClassesPagingPage( options?: coreHttp.OperationOptions ): AsyncIterableIterator<DeviceClass[]> { let result = await this._getAllDeviceClasses(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getAllDeviceClassesNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *getAllDeviceClassesPagingAll( options?: coreHttp.OperationOptions ): AsyncIterableIterator<DeviceClass> { for await (const page of this.getAllDeviceClassesPagingPage(options)) { yield* page; } } /** * Gets a list of device identifiers in a device class. * @param deviceClassId Device class identifier. * @param options The options parameters. */ public listDeviceClassDeviceIds( deviceClassId: string, options?: coreHttp.OperationOptions ): PagedAsyncIterableIterator<string> { const iter = this.getDeviceClassDeviceIdsPagingAll(deviceClassId, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getDeviceClassDeviceIdsPagingPage(deviceClassId, options); } }; } private async *getDeviceClassDeviceIdsPagingPage( deviceClassId: string, options?: coreHttp.OperationOptions ): AsyncIterableIterator<string[]> { let result = await this._getDeviceClassDeviceIds(deviceClassId, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getDeviceClassDeviceIdsNext(deviceClassId, continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *getDeviceClassDeviceIdsPagingAll( deviceClassId: string, options?: coreHttp.OperationOptions ): AsyncIterableIterator<string> { for await (const page of this.getDeviceClassDeviceIdsPagingPage(deviceClassId, options)) { yield* page; } } /** * Gets a list of installable updates for a device class. * @param deviceClassId Device class identifier. * @param options The options parameters. */ public listDeviceClassInstallableUpdates( deviceClassId: string, options?: coreHttp.OperationOptions ): PagedAsyncIterableIterator<UpdateId> { const iter = this.getDeviceClassInstallableUpdatesPagingAll(deviceClassId, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getDeviceClassInstallableUpdatesPagingPage(deviceClassId, options); } }; } private async *getDeviceClassInstallableUpdatesPagingPage( deviceClassId: string, options?: coreHttp.OperationOptions ): AsyncIterableIterator<UpdateId[]> { let result = await this._getDeviceClassInstallableUpdates(deviceClassId, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getDeviceClassInstallableUpdatesNext( deviceClassId, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *getDeviceClassInstallableUpdatesPagingAll( deviceClassId: string, options?: coreHttp.OperationOptions ): AsyncIterableIterator<UpdateId> { for await (const page of this.getDeviceClassInstallableUpdatesPagingPage( deviceClassId, options )) { yield* page; } } /** * Gets a list of devices connected to Device Update for IoT Hub. * @param options The options parameters. */ public listAllDevices( options?: DevicesGetAllDevicesOptionalParams ): PagedAsyncIterableIterator<Device> { const iter = this.getAllDevicesPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getAllDevicesPagingPage(options); } }; } private async *getAllDevicesPagingPage( options?: DevicesGetAllDevicesOptionalParams ): AsyncIterableIterator<Device[]> { let result = await this._getAllDevices(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getAllDevicesNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *getAllDevicesPagingAll( options?: DevicesGetAllDevicesOptionalParams ): AsyncIterableIterator<Device> { for await (const page of this.getAllDevicesPagingPage(options)) { yield* page; } } /** * Gets a list of available group device tags for all devices connected to Device Update for IoT Hub. * @param options The options parameters. */ public listAllDeviceTags( options?: coreHttp.OperationOptions ): PagedAsyncIterableIterator<DeviceTag> { const iter = this.getAllDeviceTagsPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getAllDeviceTagsPagingPage(options); } }; } private async *getAllDeviceTagsPagingPage( options?: coreHttp.OperationOptions ): AsyncIterableIterator<DeviceTag[]> { let result = await this._getAllDeviceTags(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getAllDeviceTagsNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *getAllDeviceTagsPagingAll( options?: coreHttp.OperationOptions ): AsyncIterableIterator<DeviceTag> { for await (const page of this.getAllDeviceTagsPagingPage(options)) { yield* page; } } /** * Gets a list of all device groups. * @param options The options parameters. */ public listAllGroups(options?: coreHttp.OperationOptions): PagedAsyncIterableIterator<Group> { const iter = this.getAllGroupsPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getAllGroupsPagingPage(options); } }; } private async *getAllGroupsPagingPage( options?: coreHttp.OperationOptions ): AsyncIterableIterator<Group[]> { let result = await this._getAllGroups(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getAllGroupsNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *getAllGroupsPagingAll( options?: coreHttp.OperationOptions ): AsyncIterableIterator<Group> { for await (const page of this.getAllGroupsPagingPage(options)) { yield* page; } } /** * Get the best available updates for a group and a count of how many devices need each update. * @param groupId Group identifier. * @param options The options parameters. */ public listGroupBestUpdates( groupId: string, options?: DevicesGetGroupBestUpdatesOptionalParams ): PagedAsyncIterableIterator<UpdatableDevices> { const iter = this.getGroupBestUpdatesPagingAll(groupId, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getGroupBestUpdatesPagingPage(groupId, options); } }; } private async *getGroupBestUpdatesPagingPage( groupId: string, options?: DevicesGetGroupBestUpdatesOptionalParams ): AsyncIterableIterator<UpdatableDevices[]> { let result = await this._getGroupBestUpdates(groupId, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getGroupBestUpdatesNext(groupId, continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *getGroupBestUpdatesPagingAll( groupId: string, options?: DevicesGetGroupBestUpdatesOptionalParams ): AsyncIterableIterator<UpdatableDevices> { for await (const page of this.getGroupBestUpdatesPagingPage(groupId, options)) { yield* page; } } /** * Gets a list of all device classes (unique combinations of device manufacturer and model) for all * devices connected to Device Update for IoT Hub. * @param options The options parameters. */ private async _getAllDeviceClasses( options?: coreHttp.OperationOptions ): Promise<DevicesGetAllDeviceClassesResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getAllDeviceClasses", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getAllDeviceClassesOperationSpec ); return result as DevicesGetAllDeviceClassesResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Gets the properties of a device class. * @param deviceClassId Device class identifier. * @param options The options parameters. */ async getDeviceClass( deviceClassId: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetDeviceClassResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-getDeviceClass", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { deviceClassId, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getDeviceClassOperationSpec ); return result as DevicesGetDeviceClassResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Gets a list of device identifiers in a device class. * @param deviceClassId Device class identifier. * @param options The options parameters. */ private async _getDeviceClassDeviceIds( deviceClassId: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetDeviceClassDeviceIdsResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getDeviceClassDeviceIds", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { deviceClassId, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getDeviceClassDeviceIdsOperationSpec ); return result as DevicesGetDeviceClassDeviceIdsResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Gets a list of installable updates for a device class. * @param deviceClassId Device class identifier. * @param options The options parameters. */ private async _getDeviceClassInstallableUpdates( deviceClassId: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetDeviceClassInstallableUpdatesResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getDeviceClassInstallableUpdates", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { deviceClassId, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getDeviceClassInstallableUpdatesOperationSpec ); return result as DevicesGetDeviceClassInstallableUpdatesResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Gets a list of devices connected to Device Update for IoT Hub. * @param options The options parameters. */ private async _getAllDevices( options?: DevicesGetAllDevicesOptionalParams ): Promise<DevicesGetAllDevicesResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getAllDevices", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getAllDevicesOperationSpec ); return result as DevicesGetAllDevicesResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Gets the device properties and latest deployment status for a device connected to Device Update for * IoT Hub. * @param deviceId Device identifier in Azure IOT Hub. * @param options The options parameters. */ async getDevice( deviceId: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetDeviceResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-getDevice", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { deviceId, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getDeviceOperationSpec ); return result as DevicesGetDeviceResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Gets the breakdown of how many devices are on their latest update, have new updates available, or * are in progress receiving new updates. * @param options The options parameters. */ async getUpdateCompliance( options?: coreHttp.OperationOptions ): Promise<DevicesGetUpdateComplianceResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-getUpdateCompliance", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getUpdateComplianceOperationSpec ); return result as DevicesGetUpdateComplianceResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Gets a list of available group device tags for all devices connected to Device Update for IoT Hub. * @param options The options parameters. */ private async _getAllDeviceTags( options?: coreHttp.OperationOptions ): Promise<DevicesGetAllDeviceTagsResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getAllDeviceTags", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getAllDeviceTagsOperationSpec ); return result as DevicesGetAllDeviceTagsResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Gets a count of how many devices have a device tag. * @param tagName Tag name. * @param options The options parameters. */ async getDeviceTag( tagName: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetDeviceTagResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-getDeviceTag", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { tagName, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getDeviceTagOperationSpec ); return result as DevicesGetDeviceTagResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Gets a list of all device groups. * @param options The options parameters. */ private async _getAllGroups( options?: coreHttp.OperationOptions ): Promise<DevicesGetAllGroupsResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getAllGroups", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getAllGroupsOperationSpec ); return result as DevicesGetAllGroupsResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Gets the properties of a group. * @param groupId Group identifier. * @param options The options parameters. */ async getGroup( groupId: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetGroupResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-getGroup", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { groupId, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getGroupOperationSpec ); return result as DevicesGetGroupResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Create or update a device group. * @param groupId Group identifier. * @param group The group properties. * @param options The options parameters. */ async createOrUpdateGroup( groupId: string, group: Group, options?: coreHttp.OperationOptions ): Promise<DevicesCreateOrUpdateGroupResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-createOrUpdateGroup", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { groupId, group, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, createOrUpdateGroupOperationSpec ); return result as DevicesCreateOrUpdateGroupResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Deletes a device group. * @param groupId Group identifier. * @param options The options parameters. */ async deleteGroup( groupId: string, options?: coreHttp.OperationOptions ): Promise<coreHttp.RestResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-deleteGroup", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { groupId, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, deleteGroupOperationSpec ); return result as coreHttp.RestResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Get group update compliance information such as how many devices are on their latest update, how * many need new updates, and how many are in progress on receiving a new update. * @param groupId Group identifier. * @param options The options parameters. */ async getGroupUpdateCompliance( groupId: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetGroupUpdateComplianceResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-getGroupUpdateCompliance", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { groupId, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getGroupUpdateComplianceOperationSpec ); return result as DevicesGetGroupUpdateComplianceResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * Get the best available updates for a group and a count of how many devices need each update. * @param groupId Group identifier. * @param options The options parameters. */ private async _getGroupBestUpdates( groupId: string, options?: DevicesGetGroupBestUpdatesOptionalParams ): Promise<DevicesGetGroupBestUpdatesResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getGroupBestUpdates", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { groupId, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getGroupBestUpdatesOperationSpec ); return result as DevicesGetGroupBestUpdatesResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * GetAllDeviceClassesNext * @param nextLink The nextLink from the previous successful call to the GetAllDeviceClasses method. * @param options The options parameters. */ private async _getAllDeviceClassesNext( nextLink: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetAllDeviceClassesNextResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getAllDeviceClassesNext", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { nextLink, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getAllDeviceClassesNextOperationSpec ); return result as DevicesGetAllDeviceClassesNextResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * GetDeviceClassDeviceIdsNext * @param deviceClassId Device class identifier. * @param nextLink The nextLink from the previous successful call to the GetDeviceClassDeviceIds * method. * @param options The options parameters. */ private async _getDeviceClassDeviceIdsNext( deviceClassId: string, nextLink: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetDeviceClassDeviceIdsNextResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getDeviceClassDeviceIdsNext", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { deviceClassId, nextLink, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getDeviceClassDeviceIdsNextOperationSpec ); return result as DevicesGetDeviceClassDeviceIdsNextResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * GetDeviceClassInstallableUpdatesNext * @param deviceClassId Device class identifier. * @param nextLink The nextLink from the previous successful call to the * GetDeviceClassInstallableUpdates method. * @param options The options parameters. */ private async _getDeviceClassInstallableUpdatesNext( deviceClassId: string, nextLink: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetDeviceClassInstallableUpdatesNextResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getDeviceClassInstallableUpdatesNext", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { deviceClassId, nextLink, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getDeviceClassInstallableUpdatesNextOperationSpec ); return result as DevicesGetDeviceClassInstallableUpdatesNextResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * GetAllDevicesNext * @param nextLink The nextLink from the previous successful call to the GetAllDevices method. * @param options The options parameters. */ private async _getAllDevicesNext( nextLink: string, options?: DevicesGetAllDevicesNextOptionalParams ): Promise<DevicesGetAllDevicesNextResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getAllDevicesNext", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { nextLink, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getAllDevicesNextOperationSpec ); return result as DevicesGetAllDevicesNextResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * GetAllDeviceTagsNext * @param nextLink The nextLink from the previous successful call to the GetAllDeviceTags method. * @param options The options parameters. */ private async _getAllDeviceTagsNext( nextLink: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetAllDeviceTagsNextResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getAllDeviceTagsNext", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { nextLink, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getAllDeviceTagsNextOperationSpec ); return result as DevicesGetAllDeviceTagsNextResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * GetAllGroupsNext * @param nextLink The nextLink from the previous successful call to the GetAllGroups method. * @param options The options parameters. */ private async _getAllGroupsNext( nextLink: string, options?: coreHttp.OperationOptions ): Promise<DevicesGetAllGroupsNextResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getAllGroupsNext", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { nextLink, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getAllGroupsNextOperationSpec ); return result as DevicesGetAllGroupsNextResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } /** * GetGroupBestUpdatesNext * @param groupId Group identifier. * @param nextLink The nextLink from the previous successful call to the GetGroupBestUpdates method. * @param options The options parameters. */ private async _getGroupBestUpdatesNext( groupId: string, nextLink: string, options?: DevicesGetGroupBestUpdatesNextOptionalParams ): Promise<DevicesGetGroupBestUpdatesNextResponse> { const { span, updatedOptions } = createSpan( "DeviceUpdateClient-_getGroupBestUpdatesNext", coreHttp.operationOptionsToRequestOptionsBase(options || {}) ); const operationArguments: coreHttp.OperationArguments = { groupId, nextLink, options: updatedOptions }; try { const result = await this.client.sendOperationRequest( operationArguments, getGroupBestUpdatesNextOperationSpec ); return result as DevicesGetGroupBestUpdatesNextResponse; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } } } // Operation Specifications const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); const getAllDeviceClassesOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/deviceclasses", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfDeviceClasses } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId], headerParameters: [Parameters.accept], serializer }; const getDeviceClassOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/deviceclasses/{deviceClassId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeviceClass }, 404: { isError: true } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.deviceClassId], headerParameters: [Parameters.accept], serializer }; const getDeviceClassDeviceIdsOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/deviceclasses/{deviceClassId}/deviceids", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfStrings }, 404: { isError: true } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.deviceClassId], headerParameters: [Parameters.accept], serializer }; const getDeviceClassInstallableUpdatesOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/deviceclasses/{deviceClassId}/installableupdates", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfUpdateIds }, 404: { isError: true } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.deviceClassId], headerParameters: [Parameters.accept], serializer }; const getAllDevicesOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/devices", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfDevices } }, queryParameters: [Parameters.filter], urlParameters: [Parameters.accountEndpoint, Parameters.instanceId], headerParameters: [Parameters.accept], serializer }; const getDeviceOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/devices/{deviceId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.Device }, 404: { isError: true } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.deviceId], headerParameters: [Parameters.accept], serializer }; const getUpdateComplianceOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/updatecompliance", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UpdateCompliance } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId], headerParameters: [Parameters.accept], serializer }; const getAllDeviceTagsOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/devicetags", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfDeviceTags } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId], headerParameters: [Parameters.accept], serializer }; const getDeviceTagOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/devicetags/{tagName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeviceTag }, 404: { isError: true } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.tagName], headerParameters: [Parameters.accept], serializer }; const getAllGroupsOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/groups", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfGroups } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId], headerParameters: [Parameters.accept], serializer }; const getGroupOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/groups/{groupId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.Group }, 404: { isError: true } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.groupId], headerParameters: [Parameters.accept], serializer }; const createOrUpdateGroupOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/groups/{groupId}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.Group }, 400: { isError: true }, 404: { isError: true } }, requestBody: Parameters.group, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.groupId], headerParameters: [Parameters.contentType, Parameters.accept], mediaType: "json", serializer }; const deleteGroupOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/groups/{groupId}", httpMethod: "DELETE", responses: { 200: {}, 204: {} }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.groupId], serializer }; const getGroupUpdateComplianceOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/groups/{groupId}/updateCompliance", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UpdateCompliance }, 404: { isError: true } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.groupId], headerParameters: [Parameters.accept], serializer }; const getGroupBestUpdatesOperationSpec: coreHttp.OperationSpec = { path: "/deviceupdate/{instanceId}/v2/management/groups/{groupId}/bestUpdates", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfUpdatableDevices }, 404: { isError: true } }, queryParameters: [Parameters.filter], urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.groupId], headerParameters: [Parameters.accept], serializer }; const getAllDeviceClassesNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfDeviceClasses } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.nextLink], headerParameters: [Parameters.accept], serializer }; const getDeviceClassDeviceIdsNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfStrings }, 404: { isError: true } }, urlParameters: [ Parameters.accountEndpoint, Parameters.instanceId, Parameters.nextLink, Parameters.deviceClassId ], headerParameters: [Parameters.accept], serializer }; const getDeviceClassInstallableUpdatesNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfUpdateIds }, 404: { isError: true } }, urlParameters: [ Parameters.accountEndpoint, Parameters.instanceId, Parameters.nextLink, Parameters.deviceClassId ], headerParameters: [Parameters.accept], serializer }; const getAllDevicesNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfDevices } }, queryParameters: [Parameters.filter], urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.nextLink], headerParameters: [Parameters.accept], serializer }; const getAllDeviceTagsNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfDeviceTags } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.nextLink], headerParameters: [Parameters.accept], serializer }; const getAllGroupsNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfGroups } }, urlParameters: [Parameters.accountEndpoint, Parameters.instanceId, Parameters.nextLink], headerParameters: [Parameters.accept], serializer }; const getGroupBestUpdatesNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PageableListOfUpdatableDevices }, 404: { isError: true } }, queryParameters: [Parameters.filter], urlParameters: [ Parameters.accountEndpoint, Parameters.instanceId, Parameters.nextLink, Parameters.groupId ], headerParameters: [Parameters.accept], serializer };
the_stack
import { DopeSheetEntry } from './DopeSheetEntry'; import { Metrics } from '../constants/Metrics'; import { MouseComboBit, mouseCombo } from '../utils/mouseCombo'; import { RectSelectView } from './RectSelectView'; import { registerMouseEvent } from '../utils/registerMouseEvent'; import { useDispatch, useSelector } from '../states/store'; import { useRect } from '../utils/useRect'; import { useSelectAllEntities } from '../gui-operation-hooks/useSelectAll'; import { useTimeValueRangeFuncs } from '../utils/useTimeValueRange'; import { useWheelEvent } from '../utils/useWheelEvent'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import styled from 'styled-components'; // == rect select - interface ====================================================================== export interface DopeSheetRectSelectState { isSelecting: boolean; channels: string[]; t0: number; t1: number; } // == styles ======================================================================================= const StyledDopeSheetEntry = styled( DopeSheetEntry )` margin: 2px 0; `; const Root = styled.div` position: relative; overflow: hidden; `; // == props ======================================================================================== export interface DopeSheetProps { className?: string; intersectionRoot: HTMLElement | null; refScrollTop: React.RefObject<number>; } // == component ==================================================================================== const DopeSheet = ( { className, refScrollTop, intersectionRoot }: DopeSheetProps ): JSX.Element => { const dispatch = useDispatch(); const refRoot = useRef<HTMLDivElement>( null ); const rect = useRect( refRoot ); const { automaton, channelNames, range, } = useSelector( ( state ) => ( { automaton: state.automaton.instance, channelNames: state.automaton.channelNames, range: state.timeline.range, } ) ); const selectAllEntities = useSelectAllEntities(); const { x2t, t2x, dx2dt, snapTime, } = useTimeValueRangeFuncs( range, rect ); const timeRange = useMemo( () => ( { t0: range.t0, t1: range.t1, } ), [ range.t0, range.t1 ] ); const move = useCallback( ( dx: number ): void => { dispatch( { type: 'Timeline/MoveRange', size: rect, dx, dy: 0.0, } ); }, [ dispatch, rect ] ); const zoom = useCallback( ( cx: number, dx: number ): void => { dispatch( { type: 'Timeline/ZoomRange', size: rect, cx, cy: 0.0, dx, dy: 0.0, } ); }, [ dispatch, rect ] ); const startSeek = useCallback( ( x: number ): void => { if ( !automaton ) { return; } const isPlaying = automaton.isPlaying; automaton.pause(); const t0 = x2t( x - rect.left ); automaton.seek( t0 ); let dx = 0.0; let t = t0; registerMouseEvent( ( event, movementSum ) => { dx += movementSum.x; t = t0 + dx2dt( dx ); automaton.seek( t ); }, () => { automaton.seek( t ); if ( isPlaying ) { automaton.play(); } } ); }, [ automaton, x2t, rect.left, dx2dt ] ); const startSetLoopRegion = useCallback( ( x: number ): void => { if ( !automaton ) { return; } const t0Raw = x2t( x - rect.left ); const t0 = snapTime( t0Raw ); let dx = 0.0; let t = t0; registerMouseEvent( ( event, movementSum ) => { dx += movementSum.x; const tRaw = t0 + dx2dt( dx ); t = snapTime( tRaw ); if ( t - t0 === 0.0 ) { automaton.setLoopRegion( null ); } else { const begin = Math.min( t, t0 ); const end = Math.max( t, t0 ); automaton.setLoopRegion( { begin, end } ); } }, () => { if ( t - t0 === 0.0 ) { automaton.setLoopRegion( null ); } else { const begin = Math.min( t, t0 ); const end = Math.max( t, t0 ); automaton.setLoopRegion( { begin, end } ); } } ); }, [ automaton, x2t, rect.left, snapTime, dx2dt ] ); const refX2t = useRef( x2t ); useEffect( () => { refX2t.current = x2t; }, [ x2t ] ); const [ rectSelectState, setRectSelectState ] = useState<DopeSheetRectSelectState>( { isSelecting: false, channels: [], t0: Infinity, t1: -Infinity, } ); const [ rectSelectYRange, setRectSelectYRange ] = useState<[ number, number ]>( [ 0.0, 0.0 ] ); const startRectSelect = useCallback( ( x: number, y: number ) => { const t0 = refX2t.current( x - rect.left ); const y0 = y - rect.top - ( refScrollTop.current ?? 0.0 ); let t1 = t0; let y1 = y0; let channels = channelNames.slice( Math.max( 0, Math.floor( y0 / Metrics.channelListEntyHeight ) ), Math.ceil( y1 / Metrics.channelListEntyHeight ), ); setRectSelectState( { isSelecting: true, channels, t0, t1, } ); setRectSelectYRange( [ Math.min( y0, y1 ), Math.max( y0, y1 ), ] ); registerMouseEvent( ( event ) => { t1 = refX2t.current( event.clientX - rect.left ); y1 = event.clientY - rect.top - ( refScrollTop.current ?? 0.0 ); channels = channelNames.slice( Math.max( 0, Math.floor( Math.min( y0, y1 ) / Metrics.channelListEntyHeight ) ), Math.ceil( Math.max( y0, y1 ) / Metrics.channelListEntyHeight ), ); setRectSelectState( { isSelecting: true, channels, t0: Math.min( t0, t1 ), t1: Math.max( t0, t1 ), } ); setRectSelectYRange( [ Math.min( y0, y1 ), Math.max( y0, y1 ), ] ); }, () => { setRectSelectState( { isSelecting: false, channels: [], t0: Infinity, t1: -Infinity, } ); setRectSelectYRange( [ Infinity, -Infinity, ] ); }, ); }, [ channelNames, rect.left, rect.top, refScrollTop ] ); const handleMouseDown = useCallback( ( event ) => mouseCombo( event, { [ MouseComboBit.LMB ]: ( event ) => { dispatch( { type: 'Timeline/SelectItems', items: [], } ); startRectSelect( event.clientX, event.clientY ); }, [ MouseComboBit.LMB + MouseComboBit.Ctrl ]: ( event ) => { startRectSelect( event.clientX, event.clientY ); }, [ MouseComboBit.LMB + MouseComboBit.Alt ]: ( event ) => { startSeek( event.clientX ); }, [ MouseComboBit.LMB + MouseComboBit.Shift + MouseComboBit.Alt ]: ( event ) => { startSetLoopRegion( event.clientX ); }, [ MouseComboBit.MMB ]: () => { registerMouseEvent( ( event, movementSum ) => move( movementSum.x ) ); } } ), [ dispatch, move, startRectSelect, startSeek, startSetLoopRegion ] ); const createLabel = useCallback( ( x: number, y: number ): void => { if ( !automaton ) { return; } const time = x2t( x - rect.left ); dispatch( { type: 'TextPrompt/Open', position: { x, y }, placeholder: 'A name for the new label', checkValid: ( name: string ) => { if ( name === '' ) { return 'Create Label: Name cannot be empty.'; } if ( automaton.labels[ name ] != null ) { return 'Create Label: A label for the given name already exists.'; } return null; }, callback: ( name ) => { automaton.setLabel( name, time ); dispatch( { type: 'History/Push', description: 'Set Label', commands: [ { type: 'automaton/createLabel', name, time } ], } ); } } ); }, [ automaton, x2t, rect.left, dispatch ] ); const handleContextMenu = useCallback( ( event: React.MouseEvent ): void => { event.preventDefault(); const x = event.clientX; const y = event.clientY; dispatch( { type: 'ContextMenu/Push', position: { x, y }, commands: [ { name: 'Create Label', description: 'Create a label.', callback: () => createLabel( x, y ) }, { name: 'Select All...', description: 'Select all items or labels.', more: [ { name: 'Select All Items', description: 'Select all items.', callback: () => selectAllEntities( { items: true } ), }, { name: 'Select All Labels', description: 'Select all labels.', callback: () => selectAllEntities( { labels: true } ), }, { name: 'Select Everything', description: 'Select all items and labels.', callback: () => selectAllEntities( { items: true, labels: true } ), }, ], }, ] } ); }, [ dispatch, createLabel, selectAllEntities ] ); const handleWheel = useCallback( ( event: WheelEvent ): void => { if ( event.shiftKey ) { event.preventDefault(); zoom( event.clientX - rect.left, event.deltaY ); } else { if ( event.deltaX !== 0 ) { move( -event.deltaX ); } } }, [ rect, zoom, move ] ); useWheelEvent( refRoot, handleWheel ); const entries = useMemo( () => ( channelNames.map( ( channel ) => ( <StyledDopeSheetEntry key={ channel } channel={ channel } range={ timeRange } rectSelectState={ rectSelectState } intersectionRoot={ intersectionRoot } /> ) ) ), [ channelNames, intersectionRoot, rectSelectState, timeRange ] ); return ( <Root className={ className } ref={ refRoot } onMouseDown={ handleMouseDown } onContextMenu={ handleContextMenu } > { entries } { rectSelectState.isSelecting && ( <RectSelectView x0={ t2x( rectSelectState.t0 ) } x1={ t2x( rectSelectState.t1 ) } y0={ rectSelectYRange[ 0 ] } y1={ rectSelectYRange[ 1 ] } /> ) } </Root> ); }; export { DopeSheet };
the_stack
import { EventEmitter } from 'betsy' import isPlainObject from 'is-plain-obj' import * as proxyStateTree from 'proxy-state-tree' import { Derived, IS_DERIVED, IS_DERIVED_CONSTRUCTOR } from './derived' import { Devtools, DevtoolsMessage } from './Devtools' import * as internalTypes from './internalTypes' import { proxifyEffects } from './proxyfyEffects' import { rehydrate } from './rehydrate' import { IConfiguration, IReaction, IContext } from './types' import * as utils from './utils' const hotReloadingCache = {} export class Overmind<ThisConfig extends IConfiguration> implements IConfiguration { private proxyStateTreeInstance: proxyStateTree.ProxyStateTree<object> private actionReferences: { [path: string]: Function } = {} private nextExecutionId: number = 0 private mode: | internalTypes.DefaultMode | internalTypes.TestMode | internalTypes.SSRMode private reydrateMutationsForHotReloading: proxyStateTree.IMutation[] = [] private originalConfiguration private isStrict = false initialized: Promise<any> eventHub: EventEmitter<internalTypes.Events> devtools: Devtools actions: { [K in keyof ThisConfig['actions']]: internalTypes.ResolveAction< ThisConfig['actions'][K] > } state: ThisConfig['state'] effects: ThisConfig['effects'] & {} delimiter: string constructor( configuration: ThisConfig, options: internalTypes.Options = {}, mode: | internalTypes.DefaultMode | internalTypes.TestMode | internalTypes.SSRMode = { mode: utils.MODE_DEFAULT, } as internalTypes.DefaultMode ) { const name = options.name || 'OvermindApp' const devEnv = options.devEnv || 'development' const isNode = typeof process !== 'undefined' && process.title && process.title.includes('node') this.delimiter = options.delimiter || '.' this.isStrict = Boolean(options.strict) if ( utils.ENVIRONMENT === devEnv && mode.mode === utils.MODE_DEFAULT && options.hotReloading !== false && !isNode ) { if (hotReloadingCache[name]) { return hotReloadingCache[name].reconfigure(configuration) } else { hotReloadingCache[name] = this } } /* Set up an eventHub to trigger information from derived, computed and reactions */ const eventHub = mode.mode === utils.MODE_SSR ? new utils.MockedEventEmitter() : new EventEmitter<internalTypes.Events>() /* Create the proxy state tree instance with the state and a wrapper to expose the eventHub */ const proxyStateTreeInstance = this.createProxyStateTree( configuration, eventHub, mode.mode === utils.MODE_TEST || utils.ENVIRONMENT === devEnv, mode.mode === utils.MODE_SSR ) this.originalConfiguration = configuration this.state = proxyStateTreeInstance.state this.effects = configuration.effects || {} this.proxyStateTreeInstance = proxyStateTreeInstance this.eventHub = eventHub as EventEmitter<internalTypes.Events> this.mode = mode /* Expose the created actions */ this.actions = this.getActions(configuration.actions) if (mode.mode === utils.MODE_SSR) { return } if ( utils.ENVIRONMENT === devEnv && mode.mode === utils.MODE_DEFAULT && typeof window !== 'undefined' ) { let warning = 'OVERMIND: You are running in DEVELOPMENT mode.' if (options.logProxies !== true) { const originalConsoleLog = console.log console.log = (...args) => originalConsoleLog.apply( console, args.map((arg) => arg && arg[proxyStateTree.IS_PROXY] ? arg[proxyStateTree.VALUE] : arg ) ) warning += '\n\n - To improve debugging experience "console.log" will NOT log proxies from Overmind, but the actual value. Please see docs to turn off this behaviour' } if ( options.devtools || (typeof location !== 'undefined' && location.hostname === 'localhost' && options.devtools !== false) ) { const host = options.devtools === true ? 'localhost:3031' : options.devtools const name = options.name ? options.name : typeof document === 'undefined' ? 'NoName' : document.title || 'NoName' this.initializeDevtools( host, name, eventHub, proxyStateTreeInstance.sourceState, configuration.actions ) } else if (options.devtools !== false) { warning += '\n\n - You are not running on localhost. You will have to manually define the devtools option to connect' } if (!utils.IS_TEST) { console.warn(warning) } } if ( utils.ENVIRONMENT === 'production' && mode.mode === utils.MODE_DEFAULT ) { eventHub.on(internalTypes.EventType.OPERATOR_ASYNC, (execution) => { if ( !execution.parentExecution || !execution.parentExecution.isRunning ) { proxyStateTreeInstance.getMutationTree().flush(true) } }) eventHub.on(internalTypes.EventType.ACTION_END, (execution) => { if (!execution.parentExecution || !execution.parentExecution.isRunning) proxyStateTreeInstance.getMutationTree().flush() }) let nextTick const flushTree = () => { proxyStateTreeInstance.getMutationTree().flush(true) } this.proxyStateTreeInstance.onMutation(() => { nextTick && clearTimeout(nextTick) nextTick = setTimeout(flushTree, 0) }) } else if ( mode.mode === utils.MODE_DEFAULT || mode.mode === utils.MODE_TEST ) { if ( utils.ENVIRONMENT === 'test' || (this.devtools && options.hotReloading !== false) ) { eventHub.on(internalTypes.EventType.MUTATIONS, (execution) => { this.reydrateMutationsForHotReloading = this.reydrateMutationsForHotReloading.concat( execution.mutations ) }) } eventHub.on(internalTypes.EventType.OPERATOR_ASYNC, (execution) => { if ( !execution.parentExecution || !execution.parentExecution.isRunning ) { const flushData = execution.flush(true) if (this.devtools && flushData.mutations.length) { this.devtools.send({ type: 'flush', data: { ...execution, ...flushData, }, }) } } }) eventHub.on(internalTypes.EventType.ACTION_END, (execution) => { if ( !execution.parentExecution || !execution.parentExecution.isRunning ) { const flushData = execution.flush() if (this.devtools && flushData.mutations.length) { this.devtools.send({ type: 'flush', data: { ...execution, ...flushData, }, }) } } }) } if (mode.mode === utils.MODE_DEFAULT) { const onInitialize = this.createAction( 'onInitialize', utils.createOnInitialize() ) as any this.initialized = Promise.resolve(onInitialize(this)) } else { this.initialized = Promise.resolve(null) } } private createProxyStateTree( configuration: IConfiguration, eventHub: EventEmitter<any> | utils.MockedEventEmitter, devmode: boolean, ssr: boolean ) { const proxyStateTreeInstance = new proxyStateTree.ProxyStateTree( this.getState(configuration) as any, { devmode: devmode && !ssr, ssr, delimiter: this.delimiter, onSetFunction: (tree, path, target, prop, func) => { if (func[IS_DERIVED_CONSTRUCTOR]) { return new Derived(func) as any } return func }, onGetFunction: (tree, path, target, prop) => { const func = target[prop] if (func[IS_DERIVED]) { return func( eventHub, tree, proxyStateTreeInstance, path.split(this.delimiter) ) } if (func[IS_DERIVED_CONSTRUCTOR]) { const derived = new Derived(func) as any target[prop] = derived return derived( eventHub, tree, proxyStateTreeInstance, path.split(this.delimiter) ) } return func }, onGetter: devmode ? (path, value) => { this.eventHub.emitAsync(internalTypes.EventType.GETTER, { path, value, }) } : undefined, } ) return proxyStateTreeInstance } private createExecution(name, action, parentExecution) { const namespacePath = name.split('.') namespacePath.pop() if (utils.ENVIRONMENT === 'production') { return ({ [utils.EXECUTION]: true, parentExecution, namespacePath, actionName: name, getMutationTree: () => { return this.proxyStateTreeInstance.getMutationTree() }, getTrackStateTree: () => { return this.proxyStateTreeInstance.getTrackStateTree() }, emit: this.eventHub.emit.bind(this.eventHub), } as any) as internalTypes.Execution } const mutationTrees: any[] = [] const execution = { [utils.EXECUTION]: true, namespacePath, actionId: name, executionId: this.nextExecutionId++, actionName: name, operatorId: 0, isRunning: true, parentExecution, path: [], emit: this.eventHub.emit.bind(this.eventHub), send: this.devtools ? this.devtools.send.bind(this.devtools) : () => {}, trackEffects: this.trackEffects.bind(this, this.effects), getNextOperatorId: (() => { let currentOperatorId = 0 return () => ++currentOperatorId })(), flush: parentExecution ? parentExecution.flush : (isAsync?: boolean) => { return this.proxyStateTreeInstance.flush(mutationTrees, isAsync) }, getMutationTree: parentExecution ? parentExecution.getMutationTree : () => { const mutationTree = this.proxyStateTreeInstance.getMutationTree() mutationTrees.push(mutationTree) return mutationTree }, getTrackStateTree: () => { return this.proxyStateTreeInstance.getTrackStateTree() }, onFlush: (cb) => { return this.proxyStateTreeInstance.onFlush(cb) }, scopeValue: (value, tree) => { return this.scopeValue(value, tree) }, } return execution } private createContext(execution, tree) { return { state: tree.state, actions: utils.createActionsProxy(this.actions, (action) => { return (value) => action(value, execution.isRunning ? execution : null) }), execution, proxyStateTree: this.proxyStateTreeInstance, effects: this.trackEffects(this.effects, execution), addNamespace: this.addNamespace.bind(this), reaction: this.reaction.bind(this), addMutationListener: this.addMutationListener.bind(this), addFlushListener: this.addFlushListener.bind(this), } } private addNamespace( configuration: IConfiguration, path: string[], existingState?: any ) { const state = existingState || this.state const namespaceKey = path.pop()! if (configuration.state) { const stateTarget = path.reduce((aggr, key) => aggr[key], state) stateTarget[namespaceKey] = utils.processState(configuration.state) } if (configuration.actions) { const actionsTarget = path.reduce((aggr, key) => aggr[key], this.actions) actionsTarget[namespaceKey] = this.getActions(configuration.actions) } if (configuration.effects) { const effectsTarget = path.reduce((aggr, key) => aggr[key], this.effects) effectsTarget[namespaceKey] = configuration.effects } } private scopeValue(value: any, tree: proxyStateTree.TTree) { if (!value) { return value } if (value[proxyStateTree.IS_PROXY]) { return this.proxyStateTreeInstance.rescope(value, tree) } else if (isPlainObject(value)) { return Object.assign( {}, ...Object.keys(value).map((key) => ({ [key]: this.proxyStateTreeInstance.rescope(value[key], tree), })) ) } else { return value } } private addExecutionMutation(mutation: proxyStateTree.IMutation) { ;(this as any).mutations.push(mutation) } private createAction(name, originalAction) { this.actionReferences[name] = originalAction const actionFunc = (value?, boundExecution?: internalTypes.Execution) => { const action = this.actionReferences[name] // Developer might unintentionally pass more arguments, so have to ensure // that it is an actual execution boundExecution = boundExecution && boundExecution[utils.EXECUTION] ? boundExecution : undefined if ( utils.ENVIRONMENT === 'production' || action[utils.IS_OPERATOR] || this.mode.mode === utils.MODE_SSR ) { const execution = this.createExecution(name, action, boundExecution) this.eventHub.emit(internalTypes.EventType.ACTION_START, { ...execution, value, }) if (action[utils.IS_OPERATOR]) { return new Promise((resolve, reject) => { action( null, { ...this.createContext(execution, this.proxyStateTreeInstance), value, }, (err, finalContext) => { execution.isRunning = false finalContext && this.eventHub.emit(internalTypes.EventType.ACTION_END, { ...finalContext.execution, operatorId: finalContext.execution.operatorId - 1, }) if (err) reject(err) else { resolve(finalContext.value) } } ) }) } else { const mutationTree = execution.getMutationTree() if (this.isStrict) { mutationTree.blockMutations() } const returnValue = action( this.createContext(execution, mutationTree), value ) this.eventHub.emit(internalTypes.EventType.ACTION_END, execution) return returnValue } } else { const execution = { ...this.createExecution(name, action, boundExecution), operatorId: 0, type: 'action', } this.eventHub.emit(internalTypes.EventType.ACTION_START, { ...execution, value, }) this.eventHub.emit(internalTypes.EventType.OPERATOR_START, execution) const mutationTree = execution.getMutationTree() if (this.isStrict) { mutationTree.blockMutations() } mutationTree.onMutation((mutation) => { this.eventHub.emit(internalTypes.EventType.MUTATIONS, { ...execution, mutations: [mutation], }) }) const scopedValue = this.scopeValue(value, mutationTree) const context = this.createContext(execution, mutationTree) try { let pendingFlush mutationTree.onMutation((mutation) => { if (pendingFlush) { clearTimeout(pendingFlush) } if (this.mode.mode === utils.MODE_TEST) { this.addExecutionMutation(mutation) } else if (this.mode.mode === utils.MODE_DEFAULT) { pendingFlush = setTimeout(() => { pendingFlush = null const flushData = execution.flush(true) if (this.devtools && flushData.mutations.length) { this.devtools.send({ type: 'flush', data: { ...execution, ...flushData, mutations: flushData.mutations, }, }) } }) } }) let result = action(context, scopedValue) if (utils.isPromise(result)) { this.eventHub.emit( internalTypes.EventType.OPERATOR_ASYNC, execution ) result = result .then((promiseResult) => { execution.isRunning = false if (!boundExecution) { mutationTree.dispose() } this.eventHub.emit(internalTypes.EventType.OPERATOR_END, { ...execution, isAsync: true, result: undefined, }) this.eventHub.emit( internalTypes.EventType.ACTION_END, execution ) return promiseResult }) .catch((error) => { execution.isRunning = false if (!boundExecution) { mutationTree.dispose() } this.eventHub.emit(internalTypes.EventType.OPERATOR_END, { ...execution, isAsync: true, result: undefined, error: error.message, }) this.eventHub.emit( internalTypes.EventType.ACTION_END, execution ) throw error }) } else { execution.isRunning = false if (!boundExecution) { mutationTree.dispose() } this.eventHub.emit(internalTypes.EventType.OPERATOR_END, { ...execution, isAsync: false, result: undefined, }) this.eventHub.emit(internalTypes.EventType.ACTION_END, execution) } return result } catch (err) { this.eventHub.emit(internalTypes.EventType.OPERATOR_END, { ...execution, isAsync: false, result: undefined, error: err.message, }) this.eventHub.emit(internalTypes.EventType.ACTION_END, execution) throw err } } } return actionFunc } private trackEffects(effects = {}, execution) { if (utils.ENVIRONMENT === 'production') { return effects } return proxifyEffects(this.effects, (effect) => { let result try { if (this.mode.mode === utils.MODE_TEST) { const mode = this.mode as internalTypes.TestMode result = mode.options.effectsCallback(effect) } else { this.eventHub.emit(internalTypes.EventType.EFFECT, { ...execution, ...effect, args: effect.args, isPending: true, error: false, }) result = effect.func.apply(this, effect.args) } } catch (error) { this.eventHub.emit(internalTypes.EventType.EFFECT, { ...execution, ...effect, args: effect.args, isPending: false, error: error.message, }) throw error } if (utils.isPromise(result)) { this.eventHub.emit(internalTypes.EventType.EFFECT, { ...execution, ...effect, args: effect.args, isPending: true, error: false, }) return result .then((promisedResult) => { this.eventHub.emit(internalTypes.EventType.EFFECT, { ...execution, ...effect, args: effect.args, result: promisedResult, isPending: false, error: false, }) return promisedResult }) .catch((error) => { this.eventHub.emit(internalTypes.EventType.EFFECT, { ...execution, ...effect, args: effect.args, isPending: false, error: error && error.message, }) throw error }) } this.eventHub.emit(internalTypes.EventType.EFFECT, { ...execution, ...effect, args: effect.args, result: result, isPending: false, error: false, }) return result }) } private initializeDevtools(host, name, eventHub, initialState, actions) { if (utils.ENVIRONMENT === 'production') return const devtools = new Devtools(name) devtools.connect( host, (message: DevtoolsMessage) => { switch (message.type) { case 'refresh': { location.reload() break } case 'executeAction': { const action = message.data.name .split('.') .reduce((aggr, key) => aggr[key], this.actions) message.data.payload ? action(JSON.parse(message.data.payload)) : action() break } case 'mutation': { const tree = this.proxyStateTreeInstance.getMutationTree() const path = message.data.path.slice() const value = JSON.parse(`{ "value": ${message.data.value} }`).value const key = path.pop() const state = path.reduce((aggr, key) => aggr[key], tree.state) state[key] = value tree.flush(true) tree.dispose() this.devtools.send({ type: 'state', data: { path: message.data.path, value, }, }) break } } } ) for (const type in internalTypes.EventType) { eventHub.on( internalTypes.EventType[type], ((eventType) => (data) => { devtools.send({ type: internalTypes.EventType[type], data, }) if (eventType === internalTypes.EventType.MUTATIONS) { // We want to trigger property access when setting objects and arrays, as any derived set would // then trigger and update the devtools data.mutations.forEach((mutation) => { const value = mutation.path .split(this.delimiter) .reduce( (aggr, key) => aggr[key], this.proxyStateTreeInstance.state ) if (isPlainObject(value)) { Object.keys(value).forEach((key) => value[key]) } else if (Array.isArray(value)) { value.forEach((item) => { if (isPlainObject(item)) { Object.keys(item).forEach((key) => item[key]) } }) } }) } // Access the derived which will trigger calculation and devtools if (eventType === internalTypes.EventType.DERIVED_DIRTY) { data.derivedPath.reduce( (aggr, key) => aggr[key], this.proxyStateTreeInstance.state ) } })(internalTypes.EventType[type]) ) } devtools.send({ type: 'init', data: { state: this.proxyStateTreeInstance.state, actions: utils.getActionPaths(actions), delimiter: this.delimiter, }, }) this.devtools = devtools } private getState(configuration: IConfiguration) { let state = {} if (configuration.state) { state = utils.processState(configuration.state) } return state } private getActions(actions: any = {}, path: string[] = []) { return Object.keys(actions).reduce((aggr, name) => { if (typeof actions[name] === 'function') { const action = this.createAction( path.concat(name).join('.'), actions[name] ) as any action.displayName = path.concat(name).join('.') return Object.assign(aggr, { [name]: action, }) } return Object.assign(aggr, { [name]: this.getActions(actions[name], path.concat(name)), }) }, {}) as any } /* Related to hot reloading we update the existing action references and add any new actions. */ private updateActions(actions: any = {}, path: string[] = []) { Object.keys(actions).forEach((name) => { if (typeof actions[name] === 'function') { const actionName = path.concat(name).join('.') if (this.actionReferences[actionName]) { this.actionReferences[actionName] = actions[name] } else { const target = path.reduce((aggr, key) => { if (!aggr[key]) { aggr[key] = {} } return aggr[key] }, this.actions) target[name] = this.createAction(actionName, actions[name]) as any target[name].displayName = path.concat(name).join('.') } } else { this.updateActions(actions[name], path.concat(name)) } }, {}) as any } getTrackStateTree(): proxyStateTree.ITrackStateTree<any> { return this.proxyStateTreeInstance.getTrackStateTree() } getMutationTree(): proxyStateTree.IMutationTree<any> { return this.proxyStateTreeInstance.getMutationTree() } reaction: IReaction<IContext<ThisConfig>> = ( stateCallback, updateCallback, options = {} ) => { let disposer if (options.nested) { const value = stateCallback(this.state) if (!value || !value[proxyStateTree.IS_PROXY]) { throw new Error( 'You have to return an object or array from the Overmind state when using a "nested" reaction' ) } const path = value[proxyStateTree.PATH] disposer = this.addFlushListener((mutations) => { mutations.forEach((mutation) => { if (mutation.path.startsWith(path)) { updateCallback( path ? path .split(this.delimiter) .reduce((aggr, key) => aggr[key], this.state) : this.state ) } }) }) } else { const tree = this.proxyStateTreeInstance.getTrackStateTree() let returnValue const updateReaction = () => { tree.trackScope( () => (returnValue = stateCallback(tree.state as any)), () => { updateReaction() updateCallback(returnValue) } ) } updateReaction() disposer = () => { tree.dispose() } } if (options.immediate) { updateCallback(stateCallback(this.state as any)) } return disposer } addMutationListener = (cb: proxyStateTree.IMutationCallback) => { return this.proxyStateTreeInstance.onMutation(cb) } addFlushListener = (cb: proxyStateTree.IFlushCallback) => { return this.proxyStateTreeInstance.onFlush(cb) } reconfigure(configuration: IConfiguration) { const changeMutations = utils.getChangeMutations( this.originalConfiguration.state, configuration.state || {} ) this.updateActions(configuration.actions) this.effects = configuration.effects || {} const mutationTree = this.proxyStateTreeInstance.getMutationTree() // We change the state to match the new structure rehydrate(mutationTree.state as any, changeMutations) // We run any mutations ran during the session, it might fail though // as the state structure might have changed, but no worries we just // ignore that this.reydrateMutationsForHotReloading.forEach((mutation) => { try { rehydrate(mutationTree.state as any, [mutation]) } catch (error) { // No worries, structure changed and we do not want to mutate anyways } }) mutationTree.flush() mutationTree.dispose() if (this.devtools) { this.devtools.send({ type: 're_init', data: { state: this.state, actions: utils.getActionPaths(configuration.actions), }, }) } return this } }
the_stack
import { Address, Algorithm, ChainId, Identity, isBlockInfoPending, isConfirmedTransaction, isSendTransaction, PubkeyBytes, SendTransaction, TokenTicker, TransactionState, } from "@iov/bcp"; import { bnsCodec, createBnsConnector } from "@iov/bns"; import { Ed25519, Random } from "@iov/crypto"; import { fromHex } from "@iov/encoding"; import { createEthereumConnector, ethereumCodec } from "@iov/ethereum"; import { Ed25519HdWallet, HdPaths, Secp256k1HdWallet, UserProfile, WalletId } from "@iov/keycontrol"; import { MultiChainSigner } from "./multichainsigner"; // We assume the same bnsd context from iov-bns to run some simple tests // against that backend. // We can also add other backends as they are writen. function pendingWithoutBnsd(): void { if (!process.env.BNSD_ENABLED) { pending("Set BNSD_ENABLED to enable bnsd-based tests"); } } function pendingWithoutEthereum(): void { if (!process.env.ETHEREUM_ENABLED) { pending("Set ETHEREUM_ENABLED to enable ethereum-based tests"); } } async function randomBnsAddress(): Promise<Address> { const rawKeypair = await Ed25519.makeKeypair(Random.getBytes(32)); const randomIdentity: Identity = { chainId: "some-testnet" as ChainId, pubkey: { algo: Algorithm.Ed25519, data: rawKeypair.pubkey as PubkeyBytes, }, }; return bnsCodec.identityToAddress(randomIdentity); } describe("MultiChainSigner", () => { const bnsdTendermintUrl = "ws://localhost:23456"; const httpEthereumUrl = "http://localhost:8545"; it("works with no chains", () => { const profile = new UserProfile(); const signer = new MultiChainSigner(profile); expect(signer).toBeTruthy(); expect(signer.chainIds().length).toEqual(0); signer.shutdown(); }); // This uses setup from iov-bns... // Same secrets and assume the same blockchain scripts are running describe("BNS compatibility", () => { // Dev faucet // path: m/1229936198'/1'/0'/0' // pubkey: e05f47e7639b47625c23738e2e46d092819abd6039c5fc550d9aa37f1a2556a1 // IOV address: tiov1q5lyl7asgr2dcweqrhlfyexqpkgcuzrm4e0cku // This account has money in the genesis file (see scripts/bnsd/README.md). const faucetMnemonic = "degree tackle suggest window test behind mesh extra cover prepare oak script"; // tslint:disable-next-line: deprecation const faucetPath = HdPaths.iovFaucet(); const cash = "CASH" as TokenTicker; async function addWalletWithFaucet( profile: UserProfile, chainId: ChainId, ): Promise<{ readonly mainWalletId: WalletId; readonly faucet: Identity; }> { const wallet = profile.addWallet(Ed25519HdWallet.fromMnemonic(faucetMnemonic)); const faucet = await profile.createIdentity(wallet.id, chainId, faucetPath); return { mainWalletId: wallet.id, faucet: faucet }; } it("can send transaction", async () => { pendingWithoutBnsd(); const profile = new UserProfile(); const signer = new MultiChainSigner(profile); const { connection } = await signer.addChain(createBnsConnector(bnsdTendermintUrl)); expect(signer.chainIds().length).toEqual(1); const chainId = connection.chainId; const { faucet } = await addWalletWithFaucet(profile, chainId); const faucetAddress = bnsCodec.identityToAddress(faucet); const recipient = await randomBnsAddress(); // construct a sendtx, this mirrors the MultiChainSigner api const memo = `MultiChainSigner style (${Math.random()})`; const sendTx = await connection.withDefaultFee<SendTransaction>( { kind: "bcp/send", chainId: chainId, sender: faucetAddress, recipient: recipient, memo: memo, amount: { quantity: "11000000000777", fractionalDigits: 9, tokenTicker: cash, }, }, faucetAddress, ); const postResponse = await signer.signAndPost(faucet, sendTx); await postResponse.blockInfo.waitFor((info) => !isBlockInfoPending(info)); // we should be a little bit richer const updatedAccount = await connection.getAccount({ address: recipient }); expect(updatedAccount).toBeDefined(); expect(updatedAccount!.balance.length).toEqual(1); expect(updatedAccount!.balance[0].quantity).toEqual("11000000000777"); // find the transaction we sent by comparing the memo const results = (await connection.searchTx({ sentFromOrTo: recipient })).filter(isConfirmedTransaction); expect(results.length).toBeGreaterThanOrEqual(1); const last = results[results.length - 1].transaction; if (!isSendTransaction(last)) { throw new Error("Unexpected transaction kind"); } expect(last.memo).toEqual(memo); signer.shutdown(); }); it("can add two chains", async () => { // this requires both chains to check pendingWithoutBnsd(); pendingWithoutEthereum(); const profile = new UserProfile(); const signer = new MultiChainSigner(profile); expect(signer.chainIds().length).toEqual(0); // add the bov chain await signer.addChain(createBnsConnector(bnsdTendermintUrl)); expect(signer.chainIds().length).toEqual(1); const bovId = signer.chainIds()[0]; const { faucet } = await addWalletWithFaucet(profile, bovId); // add a ethereum chain await signer.addChain(createEthereumConnector(httpEthereumUrl, {})); const ethereumChainId = signer.chainIds()[1]; const twoChains = signer.chainIds(); // it should store both chains expect(twoChains.length).toEqual(2); expect(twoChains[0]).toBeDefined(); expect(twoChains[1]).toBeDefined(); expect(twoChains[0]).not.toEqual(twoChains[1]); // make sure we can query with multiple registered chains const faucetAddr = signer.identityToAddress(faucet); const connection = signer.connection(bovId); const account = await connection.getAccount({ address: faucetAddr }); expect(account).toBeDefined(); expect(account!.balance.length).toEqual(2); const ganacheMainIdentity: Identity = { chainId: ethereumChainId, pubkey: { algo: Algorithm.Secp256k1, data: fromHex( "04965fb72aad79318cd8c8c975cf18fa8bcac0c091605d10e89cd5a9f7cff564b0cb0459a7c22903119f7a42947c32c1cc6a434a86f0e26aad00ca2b2aff6ba381", ) as PubkeyBytes, }, }; const ganacheAddr = signer.identityToAddress(ganacheMainIdentity); const connection2 = signer.connection(ethereumChainId); const account2 = await connection2.getAccount({ address: ganacheAddr }); expect(account2).toBeDefined(); expect(account2!.balance.length).toEqual(1); signer.shutdown(); }); it("can add two chains and send on both of them", async () => { pendingWithoutBnsd(); pendingWithoutEthereum(); const profile = new UserProfile(); const signer = new MultiChainSigner(profile); expect(signer.chainIds().length).toEqual(0); const { connection: bnsConnection } = await signer.addChain(createBnsConnector(bnsdTendermintUrl)); await signer.addChain(createEthereumConnector(httpEthereumUrl, {})); const [bnsId, ethereumChainId] = signer.chainIds(); // Create sender identities const { faucet: bnsFaucet } = await addWalletWithFaucet(profile, bnsId); const bnsFaucetAddress = bnsCodec.identityToAddress(bnsFaucet); const secpWallet = profile.addWallet( Secp256k1HdWallet.fromMnemonic( "oxygen fall sure lava energy veteran enroll frown question detail include maximum", ), ); const ganacheMainIdentity = await profile.createIdentity( secpWallet.id, ethereumChainId, HdPaths.ethereum(0), ); { // Send on BNS const sendOnBns = await bnsConnection.withDefaultFee<SendTransaction>( { kind: "bcp/send", chainId: bnsFaucet.chainId, sender: bnsFaucetAddress, recipient: await randomBnsAddress(), memo: `MultiChainSigner style (${Math.random()})`, amount: { quantity: "11000000000777", fractionalDigits: 9, tokenTicker: cash, }, }, bnsFaucetAddress, ); const postResponse = await signer.signAndPost(bnsFaucet, sendOnBns); const blockInfo = await postResponse.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); } { // Send on Ethereum const sendOnEthereum: SendTransaction = { kind: "bcp/send", chainId: ethereumChainId, amount: { quantity: "1", tokenTicker: "ETH" as TokenTicker, fractionalDigits: 18, }, sender: ethereumCodec.identityToAddress(ganacheMainIdentity), recipient: "0x0000000000000000000000000000000000000000" as Address, memo: `MultiChainSigner style (${Math.random()})`, // TODO: shall we use getFeeQuote here? fee: { gasPrice: { quantity: "20000000000", fractionalDigits: 18, tokenTicker: "ETH" as TokenTicker, }, gasLimit: "2100000", }, }; const postResponse = await signer.signAndPost(ganacheMainIdentity, sendOnEthereum); const blockInfo = await postResponse.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); } signer.shutdown(); }); }); it("optionally enforces chainId", async () => { pendingWithoutBnsd(); const signer = new MultiChainSigner(new UserProfile()); const connector = createBnsConnector(bnsdTendermintUrl); // can add with unspecified expectedChainId const { connection } = await signer.addChain(connector); const chainId = connection.chainId; // this should error on second add to same signer await signer .addChain(connector) .then(() => fail("must not resolve")) .catch((error) => expect(error).toMatch(/is already registered/i)); // success if adding with proper expectedChainId const signer2 = new MultiChainSigner(new UserProfile()); const secureConnector = createBnsConnector(bnsdTendermintUrl, chainId); await signer2.addChain(secureConnector); // error if adding with false expectedChainId const signer3 = new MultiChainSigner(new UserProfile()); const invalidConnector = createBnsConnector(bnsdTendermintUrl, "chain-is-not-right" as ChainId); await signer3 .addChain(invalidConnector) .then(() => fail("must not resolve")) .catch((error) => expect(error).toMatch(/connected chain ID does not match/i)); signer.shutdown(); signer2.shutdown(); signer3.shutdown(); }); describe("isValidAddress", () => { it("can use isValidAddress for BNS and Ethereum", async () => { pendingWithoutBnsd(); pendingWithoutEthereum(); const signer = new MultiChainSigner(new UserProfile()); const bnsConnection = (await signer.addChain(createBnsConnector(bnsdTendermintUrl))).connection; const ethereumConnection = (await signer.addChain(createEthereumConnector(httpEthereumUrl, {}))) .connection; const bnsChainId = bnsConnection.chainId; const ethereumChainId = ethereumConnection.chainId; // valid expect(signer.isValidAddress(bnsChainId, "tiov142424242424242424242424242424242vmucnv")).toEqual(true); expect(signer.isValidAddress(ethereumChainId, "0x890b61ca61fa5b5336bb3ec142fa0da250592337")).toEqual( true, ); // invalid expect(signer.isValidAddress(bnsChainId, "")).toEqual(false); expect(signer.isValidAddress(ethereumChainId, "")).toEqual(false); expect(signer.isValidAddress(bnsChainId, "123")).toEqual(false); expect(signer.isValidAddress(ethereumChainId, "123")).toEqual(false); // wrong chains expect(signer.isValidAddress(ethereumChainId, "tiov142424242424242424242424242424242vmucnv")).toEqual( false, ); expect(signer.isValidAddress(bnsChainId, "0x890b61ca61fa5b5336bb3ec142fa0da250592337")).toEqual(false); signer.shutdown(); }); }); });
the_stack
require('module-alias/register'); import * as ABIDecoder from 'abi-decoder'; import * as chai from 'chai'; import { BigNumber } from 'bignumber.js'; import * as setProtocolUtils from 'set-protocol-utils'; import { Address } from 'set-protocol-utils'; import ChaiSetup from '@utils/chaiSetup'; import { BigNumberSetup } from '@utils/bigNumberSetup'; import { AddressToAddressWhiteListContract, CoreContract, RebalancingSetCTokenIssuanceModuleContract, RebalancingSetTokenContract, RebalancingSetTokenFactoryContract, SetTokenContract, SetTokenFactoryContract, StandardTokenMockContract, TransferProxyContract, VaultContract, WethMockContract, } from '@utils/contracts'; import { Blockchain } from '@utils/blockchain'; import { getWeb3, getGasUsageInEth } from '@utils/web3Helper'; import { expectRevertError } from '@utils/tokenAssertions'; import { DEFAULT_GAS, DEFAULT_REBALANCING_NATURAL_UNIT, DEPLOYED_TOKEN_QUANTITY, ONE_DAY_IN_SECONDS, UNLIMITED_ALLOWANCE_IN_BASE_UNITS } from '@utils/constants'; import { ether } from '@utils/units'; import { CompoundHelper } from '@utils/helpers/compoundHelper'; import { CoreHelper } from '@utils/helpers/coreHelper'; import { ERC20Helper } from '@utils/helpers/erc20Helper'; import { RebalancingHelper } from '@utils/helpers/rebalancingHelper'; import { UtilsHelper } from '@utils/helpers/utilsHelper'; import { LogRebalancingSetIssue, LogRebalancingSetRedeem } from '@utils/contract_logs/rebalancingSetIssuanceModule'; BigNumberSetup.configure(); ChaiSetup.configure(); const web3 = getWeb3(); const { expect } = chai; const blockchain = new Blockchain(web3); const { SetProtocolTestUtils: SetTestUtils, SetProtocolUtils: SetUtils } = setProtocolUtils; const { ZERO } = SetUtils.CONSTANTS; const setTestUtils = new SetTestUtils(web3); contract('RebalancingSetIssuanceModule', accounts => { const [ ownerAccount, functionCaller, whitelist, ] = accounts; let core: CoreContract; let transferProxy: TransferProxyContract; let vault: VaultContract; let rebalancingSetTokenFactory: RebalancingSetTokenFactoryContract; let setTokenFactory: SetTokenFactoryContract; let rebalancingCTokenIssuanceModule: RebalancingSetCTokenIssuanceModuleContract; let cTokenWhiteList: AddressToAddressWhiteListContract; let wethMock: WethMockContract; let cDAIInstance: StandardTokenMockContract; let daiInstance: StandardTokenMockContract; let badCDAIInstance: StandardTokenMockContract; const compoundHelper = new CompoundHelper(ownerAccount); const coreHelper = new CoreHelper(ownerAccount, ownerAccount); const erc20Helper = new ERC20Helper(ownerAccount); const rebalancingHelper = new RebalancingHelper( ownerAccount, coreHelper, erc20Helper, blockchain ); const utilsHelper = new UtilsHelper(ownerAccount); before(async () => { ABIDecoder.addABI(CoreContract.getAbi()); ABIDecoder.addABI(RebalancingSetCTokenIssuanceModuleContract.getAbi()); }); after(async () => { ABIDecoder.removeABI(CoreContract.getAbi()); ABIDecoder.removeABI(RebalancingSetCTokenIssuanceModuleContract.getAbi()); }); beforeEach(async () => { await blockchain.saveSnapshotAsync(); transferProxy = await coreHelper.deployTransferProxyAsync(); vault = await coreHelper.deployVaultAsync(); core = await coreHelper.deployCoreAsync(transferProxy, vault); wethMock = await erc20Helper.deployWrappedEtherAsync(ownerAccount); setTokenFactory = await coreHelper.deploySetTokenFactoryAsync(core.address); await coreHelper.setDefaultStateAndAuthorizationsAsync(core, vault, transferProxy, setTokenFactory); rebalancingSetTokenFactory = await coreHelper.deployRebalancingSetTokenFactoryAsync(core.address, whitelist); await coreHelper.addFactoryAsync(core, rebalancingSetTokenFactory); // Set up Compound DAI token daiInstance = await erc20Helper.deployTokenAsync( functionCaller, 18, ); const cDAIAddress = await compoundHelper.deployMockCDAI(daiInstance.address, ownerAccount); await compoundHelper.enableCToken(cDAIAddress); // Set the Borrow Rate await compoundHelper.setBorrowRate(cDAIAddress, new BigNumber('29313252165')); cDAIInstance = badCDAIInstance || await erc20Helper.getTokenInstanceAsync(cDAIAddress); cTokenWhiteList = await utilsHelper.deployAddressToAddressWhiteListAsync( [cDAIInstance.address], [daiInstance.address] ); rebalancingCTokenIssuanceModule = await coreHelper.deployRebalancingSetCTokenIssuanceModuleAsync( core.address, vault.address, transferProxy.address, wethMock.address, cTokenWhiteList.address ); await coreHelper.addModuleAsync(core, rebalancingCTokenIssuanceModule.address); }); afterEach(async () => { await blockchain.revertAsync(); }); describe('#constructor', async () => { it('should contain the correct address of the transfer proxy', async () => { const actualProxyAddress = await rebalancingCTokenIssuanceModule.transferProxy.callAsync(); expect(actualProxyAddress).to.equal(transferProxy.address); }); it('should have unlimited allowance for underlying to cToken contract', async () => { const underlyingDAIAllowance = await daiInstance.allowance.callAsync( rebalancingCTokenIssuanceModule.address, cDAIInstance.address, ); const expectedUnderlyingAllowance = UNLIMITED_ALLOWANCE_IN_BASE_UNITS; expect(underlyingDAIAllowance).to.bignumber.equal(expectedUnderlyingAllowance); }); it('should have unlimited allowance for underlying to transferProxy contract', async () => { const daiAllowance = await daiInstance.allowance.callAsync( rebalancingCTokenIssuanceModule.address, transferProxy.address, ); const expectedCTokenAllowance = UNLIMITED_ALLOWANCE_IN_BASE_UNITS; expect(daiAllowance).to.bignumber.equal(expectedCTokenAllowance); }); it('should have unlimited allowance for cToken to transferProxy contract', async () => { const cDAIAllowance = await cDAIInstance.allowance.callAsync( rebalancingCTokenIssuanceModule.address, transferProxy.address, ); const expectedCTokenAllowance = UNLIMITED_ALLOWANCE_IN_BASE_UNITS; expect(cDAIAllowance).to.bignumber.equal(expectedCTokenAllowance); }); }); describe('#issueRebalancingSet', async () => { let subjectCaller: Address; let subjectRebalancingSetAddress: Address; let subjectRebalancingSetQuantity: BigNumber; let subjectKeepChangeInVault: boolean; let baseSetComponent: StandardTokenMockContract; let baseSetUnderlyingComponent: StandardTokenMockContract; let baseSetComponent2: StandardTokenMockContract; let baseSetToken: SetTokenContract; let baseSetNaturalUnit: BigNumber; let rebalancingSetToken: RebalancingSetTokenContract; let rebalancingUnitShares: BigNumber; let baseSetComponentUnit: BigNumber; let baseSetIssueQuantity: BigNumber; let customRebalancingUnitShares: BigNumber; let customRebalancingSetQuantity: BigNumber; beforeEach(async () => { subjectCaller = functionCaller; baseSetUnderlyingComponent = daiInstance; baseSetComponent = cDAIInstance; // Create noncToken base set component 2 baseSetComponent2 = await erc20Helper.deployTokenAsync(subjectCaller); // Create the Set (1 component) const componentAddresses = [baseSetComponent.address, baseSetComponent2.address]; baseSetComponentUnit = ether(1); const componentUnits = [baseSetComponentUnit, baseSetComponentUnit]; baseSetNaturalUnit = ether(1); // Approve tokens await erc20Helper.approveTransferAsync(baseSetUnderlyingComponent, transferProxy.address, subjectCaller); await erc20Helper.approveTransferAsync(baseSetComponent2, transferProxy.address, subjectCaller); baseSetToken = await coreHelper.createSetTokenAsync( core, setTokenFactory.address, componentAddresses, componentUnits, baseSetNaturalUnit, ); // Create the Rebalancing Set rebalancingUnitShares = customRebalancingUnitShares || ether(1); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( core, rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, ONE_DAY_IN_SECONDS, rebalancingUnitShares, ); subjectRebalancingSetAddress = rebalancingSetToken.address; subjectRebalancingSetQuantity = customRebalancingSetQuantity || new BigNumber(10 ** 7); baseSetIssueQuantity = subjectRebalancingSetQuantity.mul(rebalancingUnitShares).div(DEFAULT_REBALANCING_NATURAL_UNIT); subjectKeepChangeInVault = false; }); async function subject(): Promise<string> { return rebalancingCTokenIssuanceModule.issueRebalancingSet.sendTransactionAsync( subjectRebalancingSetAddress, subjectRebalancingSetQuantity, subjectKeepChangeInVault, { from: subjectCaller, gas: DEFAULT_GAS, }, ); } it('issues the rebalancing Set', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.add(subjectRebalancingSetQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); it('uses the correct amount of underlying component tokens', async () => { const previousUnderlyingComponentBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); const expectedBaseComponentUsed = baseSetIssueQuantity.mul(baseSetComponentUnit).div(baseSetNaturalUnit); const expectedUnderlyingComponentUsed = await compoundHelper.cTokenToUnderlying(baseSetComponent.address, expectedBaseComponentUsed); const expectedComponentBalance = previousUnderlyingComponentBalance.sub(expectedUnderlyingComponentUsed); await subject(); const underlyingComponentBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); expect(expectedComponentBalance).to.bignumber.equal(underlyingComponentBalance); }); it('uses the correct amount of component 2 tokens', async () => { const previousComponentBalance = await baseSetComponent2.balanceOf.callAsync(subjectCaller); const expectedComponentUsed = baseSetIssueQuantity.mul(baseSetComponentUnit).div(baseSetNaturalUnit); const expectedComponentBalance = previousComponentBalance.sub(expectedComponentUsed); await subject(); const componentBalance = await baseSetComponent2.balanceOf.callAsync(subjectCaller); expect(expectedComponentBalance).to.bignumber.equal(componentBalance); }); it('emits correct LogRebalancingSetIssue event', async () => { const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = LogRebalancingSetIssue( subjectRebalancingSetAddress, subjectCaller, subjectRebalancingSetQuantity, rebalancingCTokenIssuanceModule.address ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('when the rebalancing Set address is not an approved Set', async () => { beforeEach(async () => { subjectRebalancingSetAddress = ownerAccount; }); it('reverts', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancing Set quantity is not a multiple of the natural unit', async () => { beforeEach(async () => { subjectRebalancingSetQuantity = subjectRebalancingSetQuantity.sub(1); }); it('reverts', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancing Set quantiy results in base Set change', async () => { before(async () => { customRebalancingSetQuantity = new BigNumber(1.5).mul(10 ** 7); customRebalancingUnitShares = new BigNumber(10 ** 17); }); after(async () => { customRebalancingSetQuantity = undefined; customRebalancingUnitShares = undefined; }); it('returns the correct quantity of base Set change', async () => { await subject(); const baseSetChange = baseSetIssueQuantity.mod(baseSetNaturalUnit); const baseSetBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); expect(baseSetBalance).to.bignumber.equal(baseSetChange); }); describe('when keepChangeInVault is true', async () => { beforeEach(async () => { subjectKeepChangeInVault = true; }); it('returns the correct quantity of base Set change in the Vault', async () => { await subject(); const baseSetChange = baseSetIssueQuantity.mod(baseSetNaturalUnit); const baseSetBalance = await vault.getOwnerBalance.callAsync( baseSetToken.address, subjectCaller, ); expect(baseSetBalance).to.bignumber.equal(baseSetChange); }); }); }); describe('when minting a cToken is returning a nonzero response', async () => { before(async () => { badCDAIInstance = await compoundHelper.deployCTokenWithInvalidMintAndRedeemAsync(ownerAccount); }); after(async () => { badCDAIInstance = undefined; }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('#issueRebalancingSetWrappingEther', async () => { let subjectCaller: Address; let subjectRebalancingSetAddress: Address; let subjectRebalancingSetQuantity: BigNumber; let subjectKeepChangeInVault: boolean; let subjectWethQuantity: BigNumber; let baseSetWethComponent: WethMockContract; let baseSetComponent: StandardTokenMockContract; let baseSetUnderlyingComponent: StandardTokenMockContract; let baseSetToken: SetTokenContract; let baseSetNaturalUnit: BigNumber; let rebalancingSetToken: RebalancingSetTokenContract; let rebalancingUnitShares: BigNumber; let baseSetComponentUnit: BigNumber; let baseSetIssueQuantity: BigNumber; let customBaseIssueQuantity: BigNumber; let customRebalancingUnitShares: BigNumber; let customRebalancingSetQuantity: BigNumber; let customWethMock: WethMockContract; beforeEach(async () => { subjectCaller = functionCaller; baseSetUnderlyingComponent = daiInstance; baseSetComponent = cDAIInstance; // Create noncToken base set component 2 baseSetWethComponent = customWethMock || wethMock; // Create the Set (1 component) const componentAddresses = [baseSetComponent.address, baseSetWethComponent.address]; baseSetComponentUnit = ether(1); const componentUnits = [baseSetComponentUnit, baseSetComponentUnit]; baseSetNaturalUnit = ether(1); // Approve tokens await erc20Helper.approveTransferAsync(baseSetUnderlyingComponent, transferProxy.address, subjectCaller); await erc20Helper.approveTransferAsync(baseSetWethComponent, transferProxy.address, subjectCaller); baseSetNaturalUnit = ether(1); baseSetToken = await coreHelper.createSetTokenAsync( core, setTokenFactory.address, componentAddresses, componentUnits, baseSetNaturalUnit, ); // Create the Rebalancing Set rebalancingUnitShares = customRebalancingUnitShares || ether(1); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( core, rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, ONE_DAY_IN_SECONDS, rebalancingUnitShares, ); subjectRebalancingSetAddress = rebalancingSetToken.address; subjectRebalancingSetQuantity = customRebalancingSetQuantity || new BigNumber(10 ** 7); baseSetIssueQuantity = customBaseIssueQuantity || subjectRebalancingSetQuantity.mul(rebalancingUnitShares).div(DEFAULT_REBALANCING_NATURAL_UNIT); subjectWethQuantity = baseSetIssueQuantity.mul(baseSetComponentUnit).div(baseSetNaturalUnit); subjectKeepChangeInVault = false; }); async function subject(): Promise<string> { return rebalancingCTokenIssuanceModule.issueRebalancingSetWrappingEther.sendTransactionAsync( subjectRebalancingSetAddress, subjectRebalancingSetQuantity, subjectKeepChangeInVault, { from: subjectCaller, gas: DEFAULT_GAS, value: subjectWethQuantity.toNumber(), }, ); } it('issues the rebalancing Set', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.add(subjectRebalancingSetQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); it('uses the correct amount of component tokens', async () => { const previousUnderlyingComponentBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); const expectedBaseComponentUsed = baseSetIssueQuantity.mul(baseSetComponentUnit).div(baseSetNaturalUnit); const expectedUnderlyingComponentUsed = await compoundHelper.cTokenToUnderlying(baseSetComponent.address, expectedBaseComponentUsed); const expectedComponentBalance = previousUnderlyingComponentBalance.sub(expectedUnderlyingComponentUsed); await subject(); const underlyingComponentBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); expect(expectedComponentBalance).to.bignumber.equal(underlyingComponentBalance); }); it('uses the correct amount of ETH from the caller', async () => { const previousEthBalance: BigNumber = new BigNumber(await web3.eth.getBalance(subjectCaller)); const txHash = await subject(); const totalGasInEth = await getGasUsageInEth(txHash); const expectedEthBalance = previousEthBalance .sub(subjectWethQuantity) .sub(totalGasInEth); const ethBalance = new BigNumber(await web3.eth.getBalance(subjectCaller)); expect(ethBalance).to.bignumber.equal(expectedEthBalance); }); it('emits correct LogRebalancingSetIssue event', async () => { const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = LogRebalancingSetIssue( subjectRebalancingSetAddress, subjectCaller, subjectRebalancingSetQuantity, rebalancingCTokenIssuanceModule.address ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('when the base SetToken components do not include wrapped Ether', async () => { before(async () => { customWethMock = await erc20Helper.deployWrappedEtherAsync(ownerAccount); }); after(async () => { customWethMock = undefined; }); it('reverts', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancing Set address is not an approved Set', async () => { beforeEach(async () => { subjectRebalancingSetAddress = ownerAccount; }); it('reverts', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancing Set quantity is not a multiple of the natural unit', async () => { beforeEach(async () => { subjectRebalancingSetQuantity = subjectRebalancingSetQuantity.sub(1); }); it('reverts', async () => { await expectRevertError(subject()); }); }); describe('when the eth sent is more than required', async () => { const extraWeth = ether(1); beforeEach(async () => { subjectWethQuantity = subjectWethQuantity.add(extraWeth); }); it('returns the change back to the user', async () => { const previousEthBalance: BigNumber = new BigNumber(await web3.eth.getBalance(subjectCaller)); const txHash = await subject(); const totalGasInEth = await getGasUsageInEth(txHash); const expectedEthBalance = previousEthBalance .sub(subjectWethQuantity) .add(extraWeth) .sub(totalGasInEth); const ethBalance = new BigNumber(await web3.eth.getBalance(subjectCaller)); expect(ethBalance).to.bignumber.equal(expectedEthBalance); }); }); describe('when the eth sent is less than required', async () => { const extraWeth = new BigNumber(10 ** 6); beforeEach(async () => { subjectWethQuantity = subjectWethQuantity.sub(extraWeth); }); it('reverts', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancing Set quantiy results in base Set change', async () => { before(async () => { customRebalancingSetQuantity = new BigNumber(1.5).mul(10 ** 7); customRebalancingUnitShares = new BigNumber(10 ** 17); customBaseIssueQuantity = ether(2); }); after(async () => { customRebalancingSetQuantity = undefined; customRebalancingUnitShares = undefined; customBaseIssueQuantity = undefined; }); it('returns the correct quantity of base Set change', async () => { await subject(); const expectedBaseSetChange = new BigNumber(5).mul(10 ** 17); const baseSetBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); expect(baseSetBalance).to.bignumber.equal(expectedBaseSetChange); }); describe('when keepChangeInVault is true', async () => { beforeEach(async () => { subjectKeepChangeInVault = true; }); it('returns the correct quantity of base Set change in the Vault', async () => { await subject(); const expectedBaseSetChange = new BigNumber(5).mul(10 ** 17); const baseSetBalance = await vault.getOwnerBalance.callAsync( baseSetToken.address, subjectCaller, ); expect(baseSetBalance).to.bignumber.equal(expectedBaseSetChange); }); }); }); describe('when minting a cToken is returning a nonzero response', async () => { before(async () => { badCDAIInstance = await compoundHelper.deployCTokenWithInvalidMintAndRedeemAsync(ownerAccount); }); after(async () => { badCDAIInstance = undefined; }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('#redeemRebalancingSet', async () => { let subjectCaller: Address; let subjectRebalancingSetAddress: Address; let subjectRebalancingSetQuantity: BigNumber; let subjectKeepChangeInVault: boolean; let baseSetIssueQuantity: BigNumber; let baseSetComponentUnit: BigNumber; let baseSetComponent: StandardTokenMockContract; let baseSetUnderlyingComponent: StandardTokenMockContract; let baseSetComponent2: StandardTokenMockContract; let baseSetToken: SetTokenContract; let baseSetNaturalUnit: BigNumber; let rebalancingSetToken: RebalancingSetTokenContract; let rebalancingUnitShares: BigNumber; let customBaseIssueQuantity: BigNumber; let customRebalancingUnitShares: BigNumber; let customRedeemQuantity: BigNumber; let customRebalancingSetIssueQuantity: BigNumber; beforeEach(async () => { subjectCaller = functionCaller; baseSetUnderlyingComponent = daiInstance; baseSetComponent = cDAIInstance; // Create noncToken base set component 2 baseSetComponent2 = await erc20Helper.deployTokenAsync(ownerAccount); const componentAddresses = [baseSetComponent.address, baseSetComponent2.address]; baseSetComponentUnit = ether(1); const componentUnits = [baseSetComponentUnit, baseSetComponentUnit]; baseSetNaturalUnit = ether(1); // Approve tokens await erc20Helper.approveTransferAsync(baseSetUnderlyingComponent, transferProxy.address); await erc20Helper.approveTransferAsync(baseSetUnderlyingComponent, baseSetComponent.address); await erc20Helper.approveTransferAsync(baseSetComponent, transferProxy.address); await erc20Helper.approveTransferAsync(baseSetComponent2, transferProxy.address); baseSetToken = await coreHelper.createSetTokenAsync( core, setTokenFactory.address, componentAddresses, componentUnits, baseSetNaturalUnit, ); await erc20Helper.approveTransferAsync(baseSetToken, transferProxy.address); // Create the Rebalancing Set rebalancingUnitShares = customRebalancingUnitShares || ether(1); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( core, rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, ONE_DAY_IN_SECONDS, rebalancingUnitShares, ); subjectRebalancingSetAddress = rebalancingSetToken.address; subjectRebalancingSetQuantity = customRedeemQuantity || new BigNumber(10 ** 7); baseSetIssueQuantity = customBaseIssueQuantity || subjectRebalancingSetQuantity.mul(rebalancingUnitShares).div(DEFAULT_REBALANCING_NATURAL_UNIT); // Mint cTokens from underlying const baseComponentUnits = baseSetIssueQuantity.mul(componentUnits[0]).div(baseSetNaturalUnit); const cTokensToMint = await compoundHelper.cTokenToUnderlying(baseSetComponent.address, baseComponentUnits); // Fund the owner account with underlying components to mint cToken await erc20Helper.transferTokenAsync( baseSetUnderlyingComponent, ownerAccount, DEPLOYED_TOKEN_QUANTITY, subjectCaller, ); await compoundHelper.mintCToken( baseSetComponent.address, cTokensToMint, ); await coreHelper.issueSetTokenAsync( core, baseSetToken.address, baseSetIssueQuantity, ); const rebalancingSetIssueQuantity = customRebalancingSetIssueQuantity || subjectRebalancingSetQuantity; // Issue the rebalancing Set Token await core.issueTo.sendTransactionAsync( functionCaller, rebalancingSetToken.address, rebalancingSetIssueQuantity, ); subjectKeepChangeInVault = false; }); async function subject(): Promise<string> { return rebalancingCTokenIssuanceModule.redeemRebalancingSet.sendTransactionAsync( subjectRebalancingSetAddress, subjectRebalancingSetQuantity, subjectKeepChangeInVault, { from: subjectCaller, gas: DEFAULT_GAS, }, ); } afterEach(async () => { customRedeemQuantity = undefined; customRebalancingUnitShares = undefined; customBaseIssueQuantity = undefined; customRebalancingSetIssueQuantity = undefined; }); it('redeems the rebalancing Set', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.sub(subjectRebalancingSetQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); it('redeems the base Set', async () => { await subject(); const currentBaseSetTokenBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); expect(currentBaseSetTokenBalance).to.bignumber.equal(ZERO); }); it('attributes the underlying CToken component to the caller', async () => { await subject(); const expectedBaseComponentBalance = baseSetIssueQuantity.mul(baseSetComponentUnit).div(baseSetNaturalUnit); const expectedUnderlyingComponentBalance = await compoundHelper.cTokenToUnderlying(baseSetComponent.address, expectedBaseComponentBalance); const baseSetUnderlyingComponentBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); expect(baseSetUnderlyingComponentBalance).to.bignumber.equal(expectedUnderlyingComponentBalance); }); it('attributes the base Set component 2 to the caller', async () => { await subject(); const expectedBaseComponentBalance = baseSetIssueQuantity.mul(baseSetComponentUnit).div(baseSetNaturalUnit); const baseSetComponentBalance = await baseSetComponent2.balanceOf.callAsync(subjectCaller); expect(baseSetComponentBalance).to.bignumber.equal(expectedBaseComponentBalance); }); it('emits correct LogRebalancingSetRedeem event', async () => { const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = LogRebalancingSetRedeem( subjectRebalancingSetAddress, subjectCaller, subjectRebalancingSetQuantity, rebalancingCTokenIssuanceModule.address ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('when the rebalancing Set address is not an approved Set', async () => { beforeEach(async () => { subjectRebalancingSetAddress = ownerAccount; }); it('reverts', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancing Set quantity is not a multiple of the natural unit', async () => { beforeEach(async () => { subjectRebalancingSetQuantity = subjectRebalancingSetQuantity.sub(1); }); it('reverts', async () => { await expectRevertError(subject()); }); }); describe('when the redeem quantity results in excess base Set', async () => { describe('when keep change in vault is false', async () => { before(async () => { customRebalancingUnitShares = new BigNumber(10 ** 17); customRedeemQuantity = new BigNumber(1.5).mul(10 ** 7); customBaseIssueQuantity = ether(2); customRebalancingSetIssueQuantity = new BigNumber(2).mul(10 ** 7); }); after(async () => { customRebalancingUnitShares = undefined; customRedeemQuantity = undefined; customBaseIssueQuantity = undefined; customRebalancingSetIssueQuantity = undefined; }); // It sends the change to the user it('sends the correct base set quantity to the user', async () => { await subject(); const expectedBalance = customRedeemQuantity .mul(rebalancingUnitShares) .div(DEFAULT_REBALANCING_NATURAL_UNIT) .mod(baseSetNaturalUnit); const currentBaseSetBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); expect(currentBaseSetBalance).to.bignumber.equal(expectedBalance); }); }); describe('when keep change in vault is true', async () => { before(async () => { customRebalancingUnitShares = new BigNumber(10 ** 17); customRedeemQuantity = new BigNumber(1.5).mul(10 ** 7); customBaseIssueQuantity = ether(2); customRebalancingSetIssueQuantity = new BigNumber(2).mul(10 ** 7); }); after(async () => { customRebalancingUnitShares = undefined; customRedeemQuantity = undefined; customBaseIssueQuantity = undefined; customRebalancingSetIssueQuantity = undefined; }); beforeEach(async () => { subjectKeepChangeInVault = true; }); it('sends the correct base set quantity to the user in the vault', async () => { await subject(); const expectedBalance = customRedeemQuantity .mul(rebalancingUnitShares) .div(DEFAULT_REBALANCING_NATURAL_UNIT) .mod(baseSetNaturalUnit); const currentBaseSetBalance = await vault.getOwnerBalance.callAsync( baseSetToken.address, subjectCaller, ); expect(currentBaseSetBalance).to.bignumber.equal(expectedBalance); }); }); }); describe('when redeeming a cToken is returning a nonzero response', async () => { before(async () => { badCDAIInstance = await compoundHelper.deployCTokenWithInvalidMintAndRedeemAsync(ownerAccount); }); after(async () => { badCDAIInstance = undefined; }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('#redeemRebalancingSetUnwrappingEther', async () => { let subjectCaller: Address; let subjectRebalancingSetAddress: Address; let subjectRebalancingSetQuantity: BigNumber; let subjectKeepChangeInVault: boolean; let baseSetIssueQuantity: BigNumber; let baseSetComponentUnit: BigNumber; let baseSetWethComponent: WethMockContract; let baseSetComponent: StandardTokenMockContract; let baseSetUnderlyingComponent: StandardTokenMockContract; let baseSetToken: SetTokenContract; let baseSetNaturalUnit: BigNumber; let rebalancingSetToken: RebalancingSetTokenContract; let rebalancingUnitShares: BigNumber; let customBaseIssueQuantity: BigNumber; let customRebalancingUnitShares: BigNumber; let customRedeemQuantity: BigNumber; let customRebalancingSetIssueQuantity: BigNumber; let customWethMock: WethMockContract; let wethRequiredToMintSet: BigNumber; beforeEach(async () => { subjectCaller = functionCaller; baseSetWethComponent = customWethMock || wethMock; baseSetUnderlyingComponent = daiInstance; baseSetComponent = cDAIInstance; // Approve tokens await erc20Helper.approveTransferAsync(baseSetWethComponent, transferProxy.address); await erc20Helper.approveTransferAsync(baseSetComponent, transferProxy.address); await erc20Helper.approveTransferAsync(baseSetUnderlyingComponent, transferProxy.address); await erc20Helper.approveTransferAsync(baseSetUnderlyingComponent, baseSetComponent.address); // Create the Set (2 component) const componentAddresses = [baseSetWethComponent.address, baseSetComponent.address]; baseSetComponentUnit = ether(1); const componentUnits = [baseSetComponentUnit, baseSetComponentUnit]; baseSetNaturalUnit = ether(1); baseSetToken = await coreHelper.createSetTokenAsync( core, setTokenFactory.address, componentAddresses, componentUnits, baseSetNaturalUnit, ); await erc20Helper.approveTransferAsync(baseSetToken, transferProxy.address); // Create the Rebalancing Set rebalancingUnitShares = customRebalancingUnitShares || ether(1); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( core, rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, ONE_DAY_IN_SECONDS, rebalancingUnitShares, ); subjectRebalancingSetAddress = rebalancingSetToken.address; subjectRebalancingSetQuantity = customRedeemQuantity || new BigNumber(10 ** 7); baseSetIssueQuantity = customBaseIssueQuantity || subjectRebalancingSetQuantity.mul(rebalancingUnitShares).div(DEFAULT_REBALANCING_NATURAL_UNIT); // Mint cTokens from underlying const baseComponentUnits = baseSetIssueQuantity.mul(componentUnits[0]).div(baseSetNaturalUnit); const cTokensToMint = await compoundHelper.cTokenToUnderlying(baseSetComponent.address, baseComponentUnits); // Fund the owner account with underlying components to mint cToken await erc20Helper.transferTokenAsync( baseSetUnderlyingComponent, ownerAccount, DEPLOYED_TOKEN_QUANTITY, subjectCaller, ); // Mint cToken await compoundHelper.mintCToken( baseSetComponent.address, cTokensToMint, ); // Wrap WETH wethRequiredToMintSet = baseSetIssueQuantity.mul(baseSetComponentUnit).div(baseSetNaturalUnit); await wethMock.deposit.sendTransactionAsync( { from: ownerAccount, gas: DEFAULT_GAS, value: wethRequiredToMintSet.toString() } ); await coreHelper.issueSetTokenAsync( core, baseSetToken.address, baseSetIssueQuantity, ); const rebalancingSetIssueQuantity = customRebalancingSetIssueQuantity || subjectRebalancingSetQuantity; // Issue the rebalancing Set Token await core.issueTo.sendTransactionAsync( functionCaller, rebalancingSetToken.address, rebalancingSetIssueQuantity, ); subjectKeepChangeInVault = false; }); async function subject(): Promise<string> { return rebalancingCTokenIssuanceModule.redeemRebalancingSetUnwrappingEther.sendTransactionAsync( subjectRebalancingSetAddress, subjectRebalancingSetQuantity, subjectKeepChangeInVault, { from: subjectCaller, gas: DEFAULT_GAS, }, ); } afterEach(async () => { customRebalancingUnitShares = undefined; customBaseIssueQuantity = undefined; customRedeemQuantity = undefined; customRebalancingSetIssueQuantity = undefined; }); it('redeems the rebalancing Set', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.sub(subjectRebalancingSetQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); it('redeems the base Set', async () => { await subject(); const currentBaseSetTokenBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); expect(currentBaseSetTokenBalance).to.bignumber.equal(ZERO); }); it('attributes the correct amount of ETH to the caller', async () => { const previousEthBalance: BigNumber = new BigNumber(await web3.eth.getBalance(subjectCaller)); const txHash = await subject(); const totalGasInEth = await getGasUsageInEth(txHash); const expectedEthBalance = previousEthBalance .add(wethRequiredToMintSet) .sub(totalGasInEth); const ethBalance = new BigNumber(await web3.eth.getBalance(subjectCaller)); expect(ethBalance).to.bignumber.equal(expectedEthBalance); }); it('attributes the underlying cToken component to the caller', async () => { await subject(); const expectedBaseComponentBalance = baseSetIssueQuantity.mul(baseSetComponentUnit).div(baseSetNaturalUnit); const expectedUnderlyingComponentBalance = await compoundHelper.cTokenToUnderlying(baseSetComponent.address, expectedBaseComponentBalance); const baseSetUnderlyingComponentBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); expect(baseSetUnderlyingComponentBalance).to.bignumber.equal(expectedUnderlyingComponentBalance); }); it('emits correct LogRebalancingSetRedeem event', async () => { const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = LogRebalancingSetRedeem( subjectRebalancingSetAddress, subjectCaller, subjectRebalancingSetQuantity, rebalancingCTokenIssuanceModule.address ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('when the base SetToken components do not include wrapped Ether', async () => { before(async () => { customWethMock = await erc20Helper.deployWrappedEtherAsync(ownerAccount); }); after(async () => { customWethMock = undefined; }); it('reverts', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancing Set address is not an approved Set', async () => { beforeEach(async () => { subjectRebalancingSetAddress = ownerAccount; }); it('reverts', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancing Set quantity is not a multiple of the natural unit', async () => { beforeEach(async () => { subjectRebalancingSetQuantity = subjectRebalancingSetQuantity.sub(1); }); it('reverts', async () => { await expectRevertError(subject()); }); }); describe('when the redeem quantity results in excess base Set', async () => { describe('when keep change in vault is false', async () => { before(async () => { customRebalancingUnitShares = new BigNumber(10 ** 17); customRedeemQuantity = new BigNumber(1.5).mul(10 ** 7); customBaseIssueQuantity = ether(2); customRebalancingSetIssueQuantity = new BigNumber(2).mul(10 ** 7); }); after(async () => { customRebalancingUnitShares = undefined; customRedeemQuantity = undefined; customBaseIssueQuantity = undefined; customRebalancingSetIssueQuantity = undefined; }); // It sends the change to the user it('sends the correct base set quantity to the user', async () => { await subject(); const expectedBalance = customRedeemQuantity .mul(rebalancingUnitShares) .div(DEFAULT_REBALANCING_NATURAL_UNIT) .mod(baseSetNaturalUnit); const currentBaseSetBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); expect(currentBaseSetBalance).to.bignumber.equal(expectedBalance); }); }); describe('when keep change in vault is true', async () => { before(async () => { customRebalancingUnitShares = new BigNumber(10 ** 17); customRedeemQuantity = new BigNumber(1.5).mul(10 ** 7); customBaseIssueQuantity = ether(2); customRebalancingSetIssueQuantity = new BigNumber(2).mul(10 ** 7); }); after(async () => { customRebalancingUnitShares = undefined; customRedeemQuantity = undefined; customBaseIssueQuantity = undefined; customRebalancingSetIssueQuantity = undefined; }); beforeEach(async () => { subjectKeepChangeInVault = true; }); it('sends the correct base set quantity to the user in the vault', async () => { await subject(); const expectedBalance = customRedeemQuantity .mul(rebalancingUnitShares) .div(DEFAULT_REBALANCING_NATURAL_UNIT) .mod(baseSetNaturalUnit); const currentBaseSetBalance = await vault.getOwnerBalance.callAsync( baseSetToken.address, subjectCaller, ); expect(currentBaseSetBalance).to.bignumber.equal(expectedBalance); }); }); }); describe('when redeeming a cToken is returning a nonzero response', async () => { before(async () => { badCDAIInstance = await compoundHelper.deployCTokenWithInvalidMintAndRedeemAsync(ownerAccount); }); after(async () => { badCDAIInstance = undefined; }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); });
the_stack
import { Component, OnInit, ChangeDetectorRef } from '@angular/core'; import { DataApiService } from '../../shared/data-api.service'; import { RestApiService } from '../../shared/rest-api.service'; import { PaginationInstance } from 'ngx-pagination'; import 'chartjs-plugin-streaming'; import { DatePipe } from '@angular/common'; import { ChartsModule } from 'ng2-charts'; import { BaseChartDirective } from 'ng2-charts'; @Component({ selector: 'app-insights', templateUrl: './insights.component.html', styleUrls: ['./insights.component.scss'] }) export class InsightsComponent implements OnInit { appList = []; demoList = []; timeMinute=0; timeHour=0; pipelineList={"ShoppingCart":["ShoppingCart"]}; insightsApplicationName=''; insightsPipelineName=''; anomalyDataResponse=false; backTimeHour=0; backTimeMinute=0; appName = ''; activatedTabs = {}; applicationList = []; exceptionCount = { 'totalException': 0, 'newException': 0, 'oldException': 0 } exceptionRange = { 'applicationName': '', 'sourceException': 0, 'targetException': 0 } public p = 1; public filter = ''; public maxSize = 7; public directionLinks = true; public config: PaginationInstance = { itemsPerPage: 5, currentPage: 1 }; public labels: any = { previousLabel: 'Previous', nextLabel: 'Next', screenReaderPaginationLabel: 'Pagination', screenReaderPageLabel: 'page', screenReaderCurrentLabel: `You're on page` }; anamolyException = []; ExceptionHighpref = []; Exceptionlowpref = []; chartColors = { red: 'rgb(255, 99, 132)', orange: 'rgb(255, 159, 64)', yellow: 'rgb(255, 205, 86)', green: 'rgb(75, 192, 192)', blue: 'rgb(54, 162, 235)', purple: 'rgb(153, 102, 255)', grey: 'rgb(201, 203, 207)' }; datasets = [{ label: 'Today', backgroundColor: this.chartColors.red, borderColor: this.chartColors.red, fill: false, lineTension: 0, borderDash: [8, 4], type: 'line', data: [], pointRadius: 5, pointHoverRadius: 15, pointHitRadius: 10, pointHoverBackgroundColor: this.chartColors.red }, { label: 'Yesterday', backgroundColor: this.chartColors.blue, borderColor: this.chartColors.blue, fill: false, cubicInterpolationMode: 'monotone', data: [] }]; options = { animation: { duration: 0 // general animation time }, responsiveAnimationDuration: 0, // animation duration after a resize scales: { xAxes: [{ type: 'realtime', // x axis will auto-scroll from right to left scaleLabel: { display: true, labelString: 'Time' } }], yAxes: [{ type: 'linear', display: true, scaleLabel: { display: true, labelString: 'Value' } }] }, tooltips: { mode: 'nearest', intersect: false }, hover: { mode: 'nearest', intersect: false, animationDuration: 0 // duration of animations when hovering an item }, plugins: { streaming: { // enabled by default duration: 180000, // data in the past 20000 ms will be displayed refresh: 10000, // onRefresh callback will be called every 1000 ms delay: 10000, // delay of 1000 ms, so upcoming values are known before plotting a line frameRate: 20, // chart is drawn n times every second pause: false, // chart is not paused } } }; loginData = { 'username' : '' }; checkinDetails = []; constructor( private restService: RestApiService, private dataService: DataApiService, private changeDetectorRef: ChangeDetectorRef, public datepipe: DatePipe ) {} ngOnInit() { this.dataService.anamolyException = []; this.anamolyException = []; this.activatedTabs = this.dataService.activatedTabs; //this.getUserAccessApplication(); this.getApplicationAndPipelineList(); // this.getCheckinDetails(this.loginData.username); if (this.appName) { this.getExceptionCountDetails(); this.getExceptionDetails(); } setInterval(() => { this.getExceptionrangeDetails(); }, 10000); } onPageChange(number: number) { console.log('change to page', number); this.config.currentPage = number; } setHour() { this.backTimeHour=this.timeHour; console.log(this.backTimeHour) console.log("consoel.g"+this.timeHour) } setMinute() { this.backTimeMinute=this.timeMinute; } getExceptionrangeDetails() { this.appName=this.insightsApplicationName.replace(/[_-]/g, "")+this.insightsPipelineName.replace(/[_-]/g, ""); if(this.insightsApplicationName==='' && this.insightsPipelineName===''){ return; } console.log("app name "+ this.appName); let currentdate = new Date(); console.log("horu"+ this.backTimeHour); currentdate.setMinutes(currentdate.getMinutes() - 5-this.backTimeMinute); // currentdate.setHours(currentdate.getHours()-this.backTimeHour); let currdate=this.datepipe.transform(currentdate, 'yyyy-MM-dd HH:mm:ss'); let ydaydate = new Date(); ydaydate.setMinutes(currentdate.getMinutes()); // ydaydate.setHours(currentdate.getHours()); ydaydate.setDate(currentdate.getDate() - 1); let ydaydat=this.datepipe.transform(ydaydate, 'yyyy-MM-dd HH:mm:ss'); const params = { 'applicationName' : this.appName, 'sourcePeriod' : currdate, 'targetPeriod' : ydaydat }; this.restService.getExceptionrangeDetails(params).then(res => { if (res) { if (res['status'] === 200) { this.exceptionRange = JSON.parse(res.text()); this.datasets[0].data.push({ x: Date.now(), y: this.exceptionRange.sourceException, }); this.datasets[1].data.push({ x: Date.now(), y: this.exceptionRange.targetException, }); } } }); } getApplicationAndPipelineList(){ this.restService.getApplicationListFromIdp().then(res=>{ if(res){ if(res['status']===200) { this.pipelineList=JSON.parse(res.json()['resource']); for(const key in this.pipelineList) { var arr=this.pipelineList[key]; arr=arr.sort(); var newarr = [arr[0]]; for (var i=1; i<arr.length; i++) { if (arr[i]!=arr[i-1]) newarr.push(arr[i]); } this.pipelineList[key]=newarr; this.applicationList.push(key); } } } }) } getExceptionCountDetails() { this.appName=this.insightsApplicationName.replace(/[_-]/g, "")+this.insightsPipelineName.replace(/[_-]/g, ""); const params = { 'applicationName' : this.appName, 'period' : 'Last1month' }; console.log(params); //We get the data which has exception name,class name etc this.restService.getExceptionCountDetails(params).then(res => { if (res) { if (res['status'] === 200) { this.exceptionCount = JSON.parse(res.text()); this.dataService.exceptionCount = this.exceptionCount; this.changeDetectorRef.detectChanges(); } } }); } getUserAccessApplication() { this.restService.getUserAccessApplication().then(res => { if (res) { if (res['status'] === 200) { console.log("response came") this.appList = JSON.parse(res.json()['resource'])['applications']; console.log(this.appList) } } this.getAppList() }); } getAppList(){ console.log("Inside getApp") for(let c of this.appList){ this.demoList.push(c.applicationName); console.log("********************") } console.log(this.demoList); this.restService.getApplist(this.demoList).then(res =>{ console.log(res) if (res) { if (res['status'] === 200) { console.log(res.json()) this.applicationList = res.json(); } } }); } getExceptionDetails() { this.anomalyDataResponse=false; this.anamolyException=[] this.appName=this.insightsApplicationName.replace(/[_-]/g, "")+this.insightsPipelineName.replace(/[_-]/g, ""); let exceptionDetails = []; console.log("inside 283") const params = { 'applicationName' : this.appName, 'period' : 'Last1month' }; let pref = 0; if (this.appName) { this.dataService.appName = this.appName; this.getExceptionCountDetails(); this.restService.getExceptionDetails(params).then(res => { console.log("inside this"+res); if (res) { if (res['status'] === 200) { exceptionDetails = JSON.parse(res.text())['resource'] if (exceptionDetails) { if (exceptionDetails.length > 0) { this.anamolyException = exceptionDetails; } else { this.anamolyException = []; } } else { this.anamolyException = []; } if(exceptionDetails===null) { this.anamolyException=[]; } for(let exceptionObj of this.anamolyException) { pref = 0 if(exceptionObj[5] == -1) { exceptionObj.push(exceptionObj[4]+'x Increase') } else{ exceptionObj.push(exceptionObj[4]+'x Decrease') } for(let val of this.checkinDetails){ console.log('classname' + exceptionObj[1]) if(exceptionObj[1].toLowerCase() === val.toLowerCase() && pref===0){ this.ExceptionHighpref.push(exceptionObj) pref = 1 break; } } if(pref === 0){ this.Exceptionlowpref.push(exceptionObj) console.log("Does not match") } } // this.anamolyException = this.ExceptionHighpref.concat(this.Exceptionlowpref); // this.dataService.anamolyException = this.anamolyException; console.log('anamolyException:' + this.anamolyException); this.changeDetectorRef.detectChanges(); } } else{ this.anamolyException=[] } this.anomalyDataResponse=true; }); } console.log(this.anamolyException); } getCheckinDetails(checkin) { checkin =this.loginData.username checkin = checkin+'@domain.com'; //console.log('see now' + checkin) const params = { committername : checkin }; this.restService.getCommitterCheckinDetails(params).then(res => { if (res) { if (res['status'] === 200) { this.checkinDetails = res.json().res; console.log('success checkins are:') console.log(this.checkinDetails); } } }); } }
the_stack
import { Inject, Injectable } from '@angular/core'; import { Actions, Effect, ofType } from '@ngrx/effects'; import { filter, map, mergeMap, switchMap, take } from 'rxjs/operators'; import { BehaviorSubject, Observable } from 'rxjs'; import { RelationshipService } from '../../../../../core/data/relationship.service'; import { getRemoteDataPayload, getFirstSucceededRemoteData, DEBOUNCE_TIME_OPERATOR } from '../../../../../core/shared/operators'; import { AddRelationshipAction, RelationshipAction, RelationshipActionTypes, UpdateRelationshipAction, UpdateRelationshipNameVariantAction } from './relationship.actions'; import { Item } from '../../../../../core/shared/item.model'; import { hasNoValue, hasValue, hasValueOperator } from '../../../../empty.util'; import { Relationship } from '../../../../../core/shared/item-relationships/relationship.model'; import { RelationshipType } from '../../../../../core/shared/item-relationships/relationship-type.model'; import { RelationshipTypeService } from '../../../../../core/data/relationship-type.service'; import { SubmissionObjectDataService } from '../../../../../core/submission/submission-object-data.service'; import { SaveSubmissionSectionFormSuccessAction } from '../../../../../submission/objects/submission-objects.actions'; import { SubmissionObject } from '../../../../../core/submission/models/submission-object.model'; import { SubmissionState } from '../../../../../submission/submission.reducers'; import { Store } from '@ngrx/store'; import { ObjectCacheService } from '../../../../../core/cache/object-cache.service'; import { RequestService } from '../../../../../core/data/request.service'; import { ServerSyncBufferActionTypes } from '../../../../../core/cache/server-sync-buffer.actions'; import { JsonPatchOperationsActionTypes } from '../../../../../core/json-patch/json-patch-operations.actions'; import { followLink } from '../../../../utils/follow-link-config.model'; import { RemoteData } from '../../../../../core/data/remote-data'; import { NotificationsService } from '../../../../notifications/notifications.service'; import { SelectableListService } from '../../../../object-list/selectable-list/selectable-list.service'; import { TranslateService } from '@ngx-translate/core'; const DEBOUNCE_TIME = 500; /** * NGRX effects for RelationshipEffects */ @Injectable() export class RelationshipEffects { /** * Map that keeps track of the latest RelationshipEffects for each relationship's composed identifier */ private debounceMap: { [identifier: string]: BehaviorSubject<string> } = {}; private nameVariantUpdates: { [identifier: string]: string } = {}; private initialActionMap: { [identifier: string]: string } = {}; private updateAfterPatchSubmissionId: string; /** * Effect that makes sure all last fired RelationshipActions' types are stored in the map of this service, with the object uuid as their key */ @Effect({ dispatch: false }) mapLastActions$ = this.actions$ .pipe( ofType(RelationshipActionTypes.ADD_RELATIONSHIP, RelationshipActionTypes.REMOVE_RELATIONSHIP), map((action: RelationshipAction) => { const { item1, item2, submissionId, relationshipType } = action.payload; const identifier: string = this.createIdentifier(item1, item2, relationshipType); if (hasNoValue(this.debounceMap[identifier])) { this.initialActionMap[identifier] = action.type; this.debounceMap[identifier] = new BehaviorSubject<string>(action.type); this.debounceMap[identifier].pipe( this.debounceTime(DEBOUNCE_TIME), take(1) ).subscribe( (type) => { if (this.initialActionMap[identifier] === type) { if (type === RelationshipActionTypes.ADD_RELATIONSHIP) { let nameVariant = (action as AddRelationshipAction).payload.nameVariant; if (hasValue(this.nameVariantUpdates[identifier])) { nameVariant = this.nameVariantUpdates[identifier]; delete this.nameVariantUpdates[identifier]; } this.addRelationship(item1, item2, relationshipType, submissionId, nameVariant); } else { this.removeRelationship(item1, item2, relationshipType, submissionId); } } delete this.debounceMap[identifier]; delete this.initialActionMap[identifier]; } ); } else { this.debounceMap[identifier].next(action.type); } } ) ); /** * Updates the namevariant in a relationship * If the relationship is currently being added or removed, it will add the name variant to an update map so it will be sent with the next add request instead * Otherwise the update is done immediately */ @Effect({ dispatch: false }) updateNameVariantsActions$ = this.actions$ .pipe( ofType(RelationshipActionTypes.UPDATE_NAME_VARIANT), map((action: UpdateRelationshipNameVariantAction) => { const { item1, item2, relationshipType, submissionId, nameVariant } = action.payload; const identifier: string = this.createIdentifier(item1, item2, relationshipType); const inProgress = hasValue(this.debounceMap[identifier]); if (inProgress) { this.nameVariantUpdates[identifier] = nameVariant; } else { this.relationshipService.updateNameVariant(item1, item2, relationshipType, nameVariant).pipe( filter((relationshipRD: RemoteData<Relationship>) => hasValue(relationshipRD.payload)), take(1) ).subscribe((c) => { this.updateAfterPatchSubmissionId = submissionId; this.relationshipService.refreshRelationshipItemsInCache(item1); this.relationshipService.refreshRelationshipItemsInCache(item2); }); } } ) ); /** * Save the latest submission ID, to make sure it's updated when the patch is finished */ @Effect({ dispatch: false }) updateRelationshipActions$ = this.actions$ .pipe( ofType(RelationshipActionTypes.UPDATE_RELATIONSHIP), map((action: UpdateRelationshipAction) => { this.updateAfterPatchSubmissionId = action.payload.submissionId; }) ); /** * Save the submission object with ID updateAfterPatchSubmissionId */ @Effect() saveSubmissionSection = this.actions$ .pipe( ofType(ServerSyncBufferActionTypes.EMPTY, JsonPatchOperationsActionTypes.COMMIT_JSON_PATCH_OPERATIONS), filter(() => hasValue(this.updateAfterPatchSubmissionId)), switchMap(() => this.refreshWorkspaceItemInCache(this.updateAfterPatchSubmissionId)), map((submissionObject) => new SaveSubmissionSectionFormSuccessAction(this.updateAfterPatchSubmissionId, [submissionObject], false)) ); constructor(private actions$: Actions, private relationshipService: RelationshipService, private relationshipTypeService: RelationshipTypeService, private submissionObjectService: SubmissionObjectDataService, private store: Store<SubmissionState>, private objectCache: ObjectCacheService, private requestService: RequestService, private notificationsService: NotificationsService, private translateService: TranslateService, private selectableListService: SelectableListService, @Inject(DEBOUNCE_TIME_OPERATOR) private debounceTime: <T>(dueTime: number) => (source: Observable<T>) => Observable<T>, ) { } private createIdentifier(item1: Item, item2: Item, relationshipType: string): string { return `${item1.uuid}-${item2.uuid}-${relationshipType}`; } private addRelationship(item1: Item, item2: Item, relationshipType: string, submissionId: string, nameVariant?: string) { const type1: string = item1.firstMetadataValue('dspace.entity.type'); const type2: string = item2.firstMetadataValue('dspace.entity.type'); return this.relationshipTypeService.getRelationshipTypeByLabelAndTypes(relationshipType, type1, type2) .pipe( mergeMap((type: RelationshipType) => { if (type === null) { return [null]; } else { const isSwitched = type.rightwardType === relationshipType; if (isSwitched) { return this.relationshipService.addRelationship(type.id, item2, item1, nameVariant, undefined); } else { return this.relationshipService.addRelationship(type.id, item1, item2, undefined, nameVariant); } } }), take(1), switchMap((rd: RemoteData<Relationship>) => { if (hasNoValue(rd) || rd.hasFailed) { // An error occurred, deselect the object from the selectable list and display an error notification const listId = `list-${submissionId}-${relationshipType}`; this.selectableListService.findSelectedByCondition(listId, (object: any) => hasValue(object.indexableObject) && object.indexableObject.uuid === item2.uuid).pipe( take(1), hasValueOperator() ).subscribe((selected) => { this.selectableListService.deselectSingle(listId, selected); }); let errorContent; if (hasNoValue(rd)) { errorContent = this.translateService.instant('relationships.add.error.relationship-type.content', { type: relationshipType }); } else { errorContent = this.translateService.instant('relationships.add.error.server.content'); } this.notificationsService.error(this.translateService.instant('relationships.add.error.title'), errorContent); } return this.refreshWorkspaceItemInCache(submissionId); }), ).subscribe((submissionObject: SubmissionObject) => this.store.dispatch(new SaveSubmissionSectionFormSuccessAction(submissionId, [submissionObject], false))); } private removeRelationship(item1: Item, item2: Item, relationshipType: string, submissionId: string) { this.relationshipService.getRelationshipByItemsAndLabel(item1, item2, relationshipType).pipe( mergeMap((relationship: Relationship) => this.relationshipService.deleteRelationship(relationship.id, 'none')), take(1), switchMap(() => this.refreshWorkspaceItemInCache(submissionId)), ).subscribe((submissionObject: SubmissionObject) => { this.store.dispatch(new SaveSubmissionSectionFormSuccessAction(submissionId, [submissionObject], false)); }); } /** * Make sure the SubmissionObject is refreshed in the cache after being used * @param submissionId The ID of the submission object */ private refreshWorkspaceItemInCache(submissionId: string): Observable<SubmissionObject> { return this.submissionObjectService.findById(submissionId, false, false, followLink('item')).pipe(getFirstSucceededRemoteData(), getRemoteDataPayload()); } }
the_stack
import { AppInstanceInfo, AppInstanceJson, AppInstanceProposal, IRpcNodeProvider, Node } from "@counterfactual/types"; import EventEmitter from "eventemitter3"; import { jsonRpcDeserialize, JsonRpcNotification, JsonRpcResponse, jsonRpcSerializeAsResponse } from "rpc-server"; import { AppInstance, AppInstanceEventType } from "./app-instance"; import { CounterfactualEvent, ErrorEventData, EventType, UninstallEventData, UpdateStateEventData } from "./types"; /** * Milliseconds until a method request to the Node is considered timed out. */ export const NODE_REQUEST_TIMEOUT = 20000; /** * Provides convenience methods for interacting with a Counterfactual node */ export class Provider { /** @ignore */ private readonly requestListeners: { [requestId: string]: (msg: JsonRpcResponse) => void; } = {}; /** @ignore */ private readonly eventEmitter = new EventEmitter(); /** @ignore */ private readonly appInstances: { [appInstanceId: string]: AppInstance } = {}; // private readonly validEventTypes = Object.keys(EventType).map( // key => EventType[key] // ); /** * Construct a new instance * @param nodeProvider NodeProvider instance that enables communication with the Counterfactual node */ constructor(readonly nodeProvider: IRpcNodeProvider) { this.nodeProvider.onMessage(this.onNodeMessage.bind(this)); this.setupAppInstanceEventListeners(); } /** * Get all currently installed app instances * * @async * @return Array of currently installed app instances */ async getAppInstances(): Promise<AppInstance[]> { const response = await this.callRawNodeMethod( Node.RpcMethodName.GET_APP_INSTANCES, {} ); const result = response.result as Node.GetAppInstancesResult; return Promise.all( result.appInstances.map(info => this.getOrCreateAppInstance(info.identityHash, info) ) ); } /** * Install a non-virtual app instance given its ID. * * @note * Installs non-virtual app instances i.e. in a direct channel between you and your peer. * For virtual app instances use [[installVirtual]]. * * @async * * @param appInstanceId ID of the app instance to be installed, generated using [[AppFactory.proposeInstall]] * @return Installed AppInstance */ async install(appInstanceId: string): Promise<AppInstance> { const response = await this.callRawNodeMethod(Node.RpcMethodName.INSTALL, { appInstanceId }); const { appInstance } = response.result as Node.InstallResult; return this.getOrCreateAppInstance(appInstanceId, appInstance); } /** * Install a virtual app instance given its ID and a list of intermediaryIdentifier. * * @note * Installs virtual app instances i.e. routed through at least one intermediary channel. * For non-virtual app instances use [[install]]. * * @async * * @param appInstanceId ID of the app instance to be installed, generated with [[AppFactory.proposeInstallVirtual]]. * @param intermediaryIdentifier Xpub of intermediary peer to route installation through * @return Installed AppInstance */ async installVirtual( appInstanceId: string, intermediaryIdentifier: string ): Promise<AppInstance> { const response = await this.callRawNodeMethod( Node.RpcMethodName.INSTALL_VIRTUAL, { appInstanceId, intermediaryIdentifier } ); const { appInstance } = response.result as Node.InstallVirtualResult; return this.getOrCreateAppInstance(appInstanceId, appInstance); } /** * Reject installation of a proposed app instance * * @async * * @param appInstanceId ID of the app instance to reject */ async rejectInstall(appInstanceId: string) { await this.callRawNodeMethod(Node.RpcMethodName.REJECT_INSTALL, { appInstanceId }); } /** * Subscribe to event. * * @async * * @param eventType Event type to subscribe to. * @param callback Function to be called when event is fired. */ on(eventType: EventType, callback: (e: CounterfactualEvent) => void) { // this.validateEventType(eventType); this.eventEmitter.on(eventType, callback); } /** * Subscribe to event. Unsubscribe once event is fired once. * * @param eventType Event type to subscribe to. * @param callback Function to be called when event is fired. */ once(eventType: EventType, callback: (e: CounterfactualEvent) => void) { // this.validateEventType(eventType); this.eventEmitter.once(eventType, callback); } /** * Unsubscribe from event. * * @param eventType Event type to unsubscribe from. * @param callback Original callback passed to subscribe call. */ off(eventType: EventType, callback: (e: CounterfactualEvent) => void) { // this.validateEventType(eventType); this.eventEmitter.off(eventType, callback); } /** * Call a Node method * * @param methodName Name of Node method to call * @param params Method-specific parameter object */ async callRawNodeMethod( methodName: Node.RpcMethodName, params: Node.MethodParams ): Promise<Node.MethodResponse> { const requestId = new Date().valueOf(); return new Promise<Node.MethodResponse>((resolve, reject) => { const request = jsonRpcDeserialize({ params, jsonrpc: "2.0", method: methodName, id: requestId }); if (!request.methodName) { return this.handleNodeError({ jsonrpc: "2.0", result: { type: EventType.ERROR, data: { errorName: "unexpected_event_type" } }, id: requestId }); } this.requestListeners[requestId] = response => { if (response.result.type === Node.ErrorType.ERROR) { return reject( jsonRpcSerializeAsResponse( { ...response.result, type: EventType.ERROR }, requestId ) ); } if (response.result.type !== methodName) { return reject( jsonRpcSerializeAsResponse( { type: EventType.ERROR, data: { errorName: "unexpected_message_type", message: `Unexpected response type. Expected ${methodName}, got ${response.result.type}` } }, requestId ) ); } resolve(response.result); }; setTimeout(() => { if (this.requestListeners[requestId] !== undefined) { reject({ type: EventType.ERROR, data: { errorName: "request_timeout", message: `Request timed out: ${JSON.stringify(request)}` } }); delete this.requestListeners[requestId]; } }, NODE_REQUEST_TIMEOUT); this.nodeProvider.sendMessage(request); }); } /** * Get app instance given its ID. * If one doesn't exist, it will be created and its details will be loaded from the Node. * * @param id ID of app instance * @param info Optional info to be used to create app instance if it doesn't exist * @return App instance */ async getOrCreateAppInstance( id: string, info?: AppInstanceInfo | AppInstanceJson | AppInstanceProposal ): Promise<AppInstance> { if (!(id in this.appInstances)) { let newInfo; if (info) { newInfo = info; } else { const { result } = await this.callRawNodeMethod( Node.RpcMethodName.GET_APP_INSTANCE_DETAILS, { appInstanceId: id } ); newInfo = (result as Node.GetAppInstanceDetailsResult).appInstance; } this.appInstances[id] = new AppInstance(newInfo, this); } return this.appInstances[id]; } // FIXME: Either implement this or remove it // private validateEventType(eventType: EventType) { // if (!this.validEventTypes.includes(eventType)) { // throw new Error(`"${eventType}" is not a valid event`); // } // } /** * @ignore */ private onNodeMessage( message: JsonRpcNotification | JsonRpcResponse | Node.Event ) { const type = message["jsonrpc"] ? (message as JsonRpcNotification | JsonRpcResponse).result.type : (message as Node.Event).type; if (Object.values(Node.ErrorType).indexOf(type) !== -1) { this.handleNodeError(message as JsonRpcResponse); } else if ("id" in message) { this.handleNodeMethodResponse(message as JsonRpcResponse); } else { this.handleNodeEvent(message as JsonRpcNotification | Node.Event); } } /** * @ignore */ private handleNodeError(error: JsonRpcResponse) { const requestId = error.id; if (requestId && this.requestListeners[requestId]) { this.requestListeners[requestId](error); delete this.requestListeners[requestId]; } this.eventEmitter.emit(error.result.type, error.result); } /** * @ignore */ private handleNodeMethodResponse(response: JsonRpcResponse) { const { id } = response; if (id in this.requestListeners) { this.requestListeners[id](response); delete this.requestListeners[id]; } else { const error = jsonRpcSerializeAsResponse( { type: EventType.ERROR, data: { errorName: "orphaned_response", message: `Response has no corresponding inflight request: ${JSON.stringify( response )}` } }, Number(id) ); this.eventEmitter.emit(error.result.type, error.result); } } /** * @ignore */ private async handleNodeEvent(event: JsonRpcNotification | Node.Event) { const nodeEvent = event["jsonrpc"] ? (event as JsonRpcNotification | JsonRpcResponse).result : (event as Node.Event); switch (nodeEvent.type) { case Node.EventName.REJECT_INSTALL: return this.handleRejectInstallEvent(nodeEvent); case Node.EventName.UPDATE_STATE: return this.handleUpdateStateEvent(nodeEvent); case Node.EventName.UNINSTALL: return this.handleUninstallEvent(nodeEvent); case Node.EventName.INSTALL: return this.handleInstallEvent(nodeEvent); case Node.EventName.INSTALL_VIRTUAL: return this.handleInstallVirtualEvent(nodeEvent); default: return this.handleUnexpectedEvent(nodeEvent); } } /** * @ignore */ private handleUnexpectedEvent(nodeEvent: Node.Event) { const event = { type: EventType.ERROR, data: { errorName: "unexpected_event_type", message: `Unexpected event type: ${nodeEvent.type}: ${JSON.stringify( nodeEvent )}` } }; return this.eventEmitter.emit(event.type, event); } /** * @ignore */ private async handleInstallEvent(nodeEvent: Node.Event) { const { appInstanceId } = nodeEvent.data as Node.InstallEventData; const appInstance = await this.getOrCreateAppInstance(appInstanceId); const event = { type: EventType.INSTALL, data: { appInstance } }; return this.eventEmitter.emit(event.type, event); } /** * @ignore */ private async handleInstallVirtualEvent(nodeEvent: Node.Event) { const { appInstanceId } = nodeEvent.data["params"]; const appInstance = await this.getOrCreateAppInstance(appInstanceId); const event = { type: EventType.INSTALL_VIRTUAL, data: { appInstance } }; return this.eventEmitter.emit(event.type, event); } /** * @ignore */ private async handleUninstallEvent(nodeEvent: Node.Event) { const { appInstanceId } = nodeEvent.data as Node.UninstallEventData; const appInstance = await this.getOrCreateAppInstance(appInstanceId); const event = { type: EventType.UNINSTALL, data: { appInstance } }; return this.eventEmitter.emit(event.type, event); } /** * @ignore */ private async handleUpdateStateEvent(nodeEvent: Node.Event) { const { appInstanceId, action, newState } = nodeEvent.data as Node.UpdateStateEventData; const appInstance = await this.getOrCreateAppInstance(appInstanceId); const event = { type: EventType.UPDATE_STATE, data: { appInstance, newState, action } }; return this.eventEmitter.emit(event.type, event); } /** * @ignore */ private async handleRejectInstallEvent(nodeEvent: Node.Event) { const data = nodeEvent.data as Node.RejectInstallEventData; const info = data.appInstance; const appInstance = await this.getOrCreateAppInstance( info.identityHash, info ); const event = { type: EventType.REJECT_INSTALL, data: { appInstance } }; return this.eventEmitter.emit(event.type, event); } /** * @ignore */ private setupAppInstanceEventListeners() { this.on(EventType.UPDATE_STATE, event => { const { appInstance } = event.data as UpdateStateEventData; appInstance.emit(AppInstanceEventType.UPDATE_STATE, event); }); this.on(EventType.UNINSTALL, event => { const { appInstance } = event.data as UninstallEventData; appInstance.emit(AppInstanceEventType.UNINSTALL, event); }); this.on(EventType.ERROR, async event => { const { appInstanceId } = event.data as ErrorEventData; if (appInstanceId) { const instance: AppInstance = await this.getOrCreateAppInstance( appInstanceId ); instance.emit(AppInstanceEventType.ERROR, event); } }); } }
the_stack
import {Injectable, ComponentRef, Injector, TemplateRef, Type} from '@angular/core'; import {Overlay, OverlayConfig, OverlayRef, PositionStrategy} from '@angular/cdk/overlay'; import {ComponentPortal, PortalInjector, TemplatePortal} from '@angular/cdk/portal'; import {HcToastComponent} from './hc-toast.component'; import {HcToastOptions} from './hc-toast-options'; import {HcToastRef} from './hc-toast-ref'; import {filter, take} from 'rxjs/operators'; export type ComponentSetup<T> = Partial<T> | ((instance: T) => void); export type ToastContentType<T> = Type<T> | TemplateRef<unknown>; /** Toasts provide users with instant feedback on actions they've taken. For more general information, * use a `hc-banner`. */ @Injectable() export class HcToasterService { _toasts: HcToastRef[] = []; // Inject overlay service constructor(private injector: Injector, private _overlay: Overlay) {} /** Displays a new toaster message with the settings included in `toastOptions`. `toastContent` can be used to * create entirely custom toasts, but only if the type in toastOptions is set to `custom`. Be sure to set `border-radius: 5px` * in the style of your custom content template so it matches the toast container. If your custom toast is * using a component, the `componentSetup` parameter accepts an object or function to configure that component. */ addToast<T>(toastOptions?: HcToastOptions, toastContent?: ToastContentType<T>, componentSetup?: ComponentSetup<T>): HcToastRef { const defaultOptions: HcToastOptions = { type: 'success', position: 'bottom-right', timeout: 5000, clickDismiss: false }; const options = {...defaultOptions, ...toastOptions}; // Returns an OverlayRef (which is a PortalHost) const _overlayRef = this._createOverlay(options); // Instantiate remote control const _toastRef = new HcToastRef(_overlayRef); const overlayComponent = this._attachToastContainer(_overlayRef, _toastRef); _toastRef.componentInstance = overlayComponent; if (options.type === 'custom' && toastContent) { if (toastContent instanceof TemplateRef) { _toastRef.componentInstance._toastPortal = new TemplatePortal(toastContent, _toastRef.componentInstance._viewContainerRef); } else { _toastRef.componentInstance._toastPortal = new ComponentPortal(toastContent); if (componentSetup) { _toastRef.componentInstance._componentInstance.pipe(filter(c => !!c)).subscribe(c => { if (componentSetup instanceof Function) { componentSetup(c); } else { Object.keys(componentSetup).forEach(k => (c[k] = componentSetup[k])); } }); } } } // Listen for click events to close the toast if the option is set if (options.clickDismiss) { _toastRef.componentInstance._canDismiss = options.clickDismiss; _toastRef.componentInstance._closeClick.subscribe(() => { _toastRef.close(); }); } // Set the class for the type set in options if (options.type) { if ( options.type === 'success' || options.type === 'info' || options.type === 'warning' || options.type === 'alert' || options.type === 'custom' ) { _toastRef.componentInstance._styleType = options.type; } else { throw Error('Unsupported toaster type: ' + options.type); } } // Set the header text if (options.header) { _toastRef.componentInstance._headerText = options.header; } // Set the toast width if (options.width || options.width === 0) { _toastRef.componentInstance._width = options.width; } // Set the body text if (options.body) { _toastRef.componentInstance._bodyText = options.body; } // Store the positioning of the toast _toastRef._toastPosition = String(options.position); // Set progress bar if (options.hasProgressBar) { _toastRef.componentInstance._hasProgressBar = options.hasProgressBar; } // Set the timeout interval to close the toast if non-zero if (options.timeout !== 0) { setTimeout(() => { if (_toastRef.componentInstance) { _toastRef.close(); } }, options.timeout); } // Cleanup functions called when the toast close animation is triggered _toastRef.componentInstance._animationStateChanged .pipe( filter(event => event.phaseName === 'done' && event.toState === 'leave'), take(1) ) .subscribe(() => { this._removeToastPointer(_toastRef); if (options.toastClosed) { options.toastClosed(); } this._updateToastPositions(); _toastRef.componentInstance._closeClick.unsubscribe(); }); _toastRef.componentInstance._changeRef.detectChanges(); this._toasts.push(_toastRef); return _toastRef; } /** Closes the most recent toast displayed */ closeLastToast(): void { if (this._toasts.length > 0) { const element = this._toasts[this._toasts.length - 1]; if (element) { element.close(); } } } /** Closes currently visible toasts */ closeAllToasts(): void { const len = this._toasts.length; for (let index = 0; index < len; index++) { const element = this._toasts[index]; if (element) { element.close(); } } } private _createOverlay(config: HcToastOptions) { const overlayConfig = this._getOverlayConfig(config); return this._overlay.create(overlayConfig); } private _attachToastContainer(overlayRef: OverlayRef, toastRef: HcToastRef) { const injector = this._createInjector(toastRef); const containerPortal = new ComponentPortal(HcToastComponent, null, injector); const containerRef: ComponentRef<HcToastComponent> = overlayRef.attach(containerPortal); return containerRef.instance; } private _createInjector(toastRef: HcToastRef): PortalInjector { const injectionTokens = new WeakMap(); injectionTokens.set(HcToastRef, toastRef); return new PortalInjector(this.injector, injectionTokens); } private _getOverlayConfig(config: HcToastOptions): OverlayConfig { let overlayConfig; const positionStrategy = this._getPositionStrategy(String(config.position), this._toasts.length); if (config.position === 'top-full-width' || config.position === 'bottom-full-width') { overlayConfig = new OverlayConfig({positionStrategy, width: '96%', panelClass: 'overlay-pointer-events'}); } else { overlayConfig = new OverlayConfig({positionStrategy, panelClass: 'overlay-pointer-events'}); } return overlayConfig; } private _getPositionStrategy(position: string, index: number): PositionStrategy { let positionStrategy: PositionStrategy; const toastIndex: number = this._getLastToast(position, index); switch (position) { case 'top-right': if (toastIndex !== -1) { positionStrategy = this._overlay .position() .flexibleConnectedTo(this._toasts[toastIndex].componentInstance._el.nativeElement.children[0]) .withPositions([ { overlayX: 'end', overlayY: 'top', originX: 'end', originY: 'bottom' } ]); } else { positionStrategy = this._overlay .position() .global() .right('10px'); } break; case 'top-center': if (toastIndex !== -1) { positionStrategy = this._overlay .position() .flexibleConnectedTo(this._toasts[toastIndex].componentInstance._el.nativeElement.children[0]) .withPositions([ { overlayX: 'center', overlayY: 'top', originX: 'center', originY: 'bottom' } ]); } else { positionStrategy = this._overlay .position() .global() .centerHorizontally(); } break; case 'top-left': if (toastIndex !== -1) { positionStrategy = this._overlay .position() .flexibleConnectedTo(this._toasts[toastIndex].componentInstance._el.nativeElement.children[0]) .withPositions([ { overlayX: 'start', overlayY: 'top', originX: 'start', originY: 'bottom' } ]); } else { positionStrategy = this._overlay .position() .global() .left('10px'); } break; case 'top-full-width': if (toastIndex !== -1) { positionStrategy = this._overlay .position() .flexibleConnectedTo(this._toasts[toastIndex].componentInstance._el.nativeElement.children[0]) .withFlexibleDimensions(false) .withPositions([ { overlayX: 'center', overlayY: 'top', originX: 'center', originY: 'bottom' } ]); } else { positionStrategy = this._overlay .position() .global() .centerHorizontally(); } break; case 'bottom-right': if (toastIndex !== -1) { positionStrategy = this._overlay .position() .flexibleConnectedTo(this._toasts[toastIndex].componentInstance._el.nativeElement.children[0]) .withPositions([ { overlayX: 'end', overlayY: 'bottom', originX: 'end', originY: 'top' } ]); } else { positionStrategy = this._overlay .position() .global() .bottom() .right('10px'); } break; case 'bottom-center': if (toastIndex !== -1) { positionStrategy = this._overlay .position() .flexibleConnectedTo(this._toasts[toastIndex].componentInstance._el.nativeElement.children[0]) .withPositions([ { overlayX: 'center', overlayY: 'bottom', originX: 'center', originY: 'top' } ]); } else { positionStrategy = this._overlay .position() .global() .bottom() .centerHorizontally(); } break; case 'bottom-left': if (toastIndex !== -1) { positionStrategy = this._overlay .position() .flexibleConnectedTo(this._toasts[toastIndex].componentInstance._el.nativeElement.children[0]) .withPositions([ { overlayX: 'start', overlayY: 'bottom', originX: 'start', originY: 'top' } ]); } else { positionStrategy = this._overlay .position() .global() .bottom() .left('10px'); } break; case 'bottom-full-width': if (toastIndex !== -1) { positionStrategy = this._overlay .position() .flexibleConnectedTo(this._toasts[toastIndex].componentInstance._el.nativeElement.children[0]) .withFlexibleDimensions(false) .withPositions([ { overlayX: 'center', overlayY: 'bottom', originX: 'center', originY: 'top' } ]); } else { positionStrategy = this._overlay .position() .global() .bottom() .centerHorizontally(); } break; default: throw Error('Unsupported toaster message position: ' + position); } return positionStrategy; } // Removes the toast that was closed from the storage array private _removeToastPointer(toastRef: HcToastRef) { for (let index = 0; index < this._toasts.length; index++) { if (this._toasts[index] === toastRef) { this._toasts.splice(index, 1); } } } // Returns one toast back from the index provided in the position provided private _getLastToast(toastPos: string, startIndex: number): number { let toastIndex = -1; for (let index = startIndex - 1; index >= 0; index--) { if (this._toasts[index]._toastPosition === toastPos) { toastIndex = index; break; } } return toastIndex; } // Updates the position strategy for what toasts are connected after one is closed private _updateToastPositions() { for (let index = 0; index < this._toasts.length; index++) { this._toasts[index]._overlayRef.updatePositionStrategy(this._getPositionStrategy(this._toasts[index]._toastPosition, index)); } } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages a Template Deployment at a Management Group Scope. * * > **Note:** Deleting a Deployment at the Management Group Scope will not delete any resources created by the deployment. * * > **Note:** Deployments to a Management Group are always Incrementally applied. Existing resources that are not part of the template will not be removed. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleGroup = azure.management.getGroup({ * name: "00000000-0000-0000-0000-000000000000", * }); * const exampleGroupTemplateDeployment = new azure.management.GroupTemplateDeployment("exampleGroupTemplateDeployment", { * location: "West Europe", * managementGroupId: exampleGroup.then(exampleGroup => exampleGroup.id), * templateContent: `{ * "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", * "contentVersion": "1.0.0.0", * "parameters": { * "policyAssignmentName": { * "type": "string", * "defaultValue": "[guid(parameters('policyDefinitionID'), resourceGroup().name)]", * "metadata": { * "description": "Specifies the name of the policy assignment, can be used defined or an idempotent name as the defaultValue provides." * } * }, * "policyDefinitionID": { * "type": "string", * "metadata": { * "description": "Specifies the ID of the policy definition or policy set definition being assigned." * } * } * }, * "resources": [ * { * "type": "Microsoft.Authorization/policyAssignments", * "name": "[parameters('policyAssignmentName')]", * "apiVersion": "2019-09-01", * "properties": { * "scope": "[subscriptionResourceId('Microsoft.Resources/resourceGroups', resourceGroup().name)]", * "policyDefinitionId": "[parameters('policyDefinitionID')]" * } * } * ] * } * `, * parametersContent: `{ * "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", * "contentVersion": "1.0.0.0", * "parameters": { * "policyDefinitionID": { * "value": "/providers/Microsoft.Authorization/policyDefinitions/0a914e76-4921-4c19-b460-a2d36003525a" * } * } * } * `, * }); * ``` * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * import * from "fs"; * * const exampleGroup = azure.management.getGroup({ * name: "00000000-0000-0000-0000-000000000000", * }); * const exampleGroupTemplateDeployment = new azure.management.GroupTemplateDeployment("exampleGroupTemplateDeployment", { * location: "West Europe", * managementGroupId: exampleGroup.then(exampleGroup => exampleGroup.id), * templateContent: fs.readFileSync("templates/example-deploy-template.json"), * parametersContent: fs.readFileSync("templates/example-deploy-params.json"), * }); * ``` * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleGroup = azure.management.getGroup({ * name: "00000000-0000-0000-0000-000000000000", * }); * const exampleTemplateSpecVersion = azure.core.getTemplateSpecVersion({ * name: "exampleTemplateForManagementGroup", * resourceGroupName: "exampleResourceGroup", * version: "v1.0.9", * }); * const exampleGroupTemplateDeployment = new azure.management.GroupTemplateDeployment("exampleGroupTemplateDeployment", { * location: "West Europe", * managementGroupId: exampleGroup.then(exampleGroup => exampleGroup.id), * templateSpecVersionId: exampleTemplateSpecVersion.then(exampleTemplateSpecVersion => exampleTemplateSpecVersion.id), * }); * ``` * * ## Import * * Management Group Template Deployments can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:management/groupTemplateDeployment:GroupTemplateDeployment example /providers/Microsoft.Management/managementGroups/my-management-group-id/providers/Microsoft.Resources/deployments/deploy1 * ``` */ export class GroupTemplateDeployment extends pulumi.CustomResource { /** * Get an existing GroupTemplateDeployment resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: GroupTemplateDeploymentState, opts?: pulumi.CustomResourceOptions): GroupTemplateDeployment { return new GroupTemplateDeployment(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:management/groupTemplateDeployment:GroupTemplateDeployment'; /** * Returns true if the given object is an instance of GroupTemplateDeployment. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is GroupTemplateDeployment { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === GroupTemplateDeployment.__pulumiType; } /** * The Debug Level which should be used for this Resource Group Template Deployment. Possible values are `none`, `requestContent`, `responseContent` and `requestContent, responseContent`. */ public readonly debugLevel!: pulumi.Output<string | undefined>; /** * The Azure Region where the Template should exist. Changing this forces a new Template to be created. */ public readonly location!: pulumi.Output<string>; public readonly managementGroupId!: pulumi.Output<string>; /** * The name which should be used for this Template Deployment. Changing this forces a new Template Deployment to be created. */ public readonly name!: pulumi.Output<string>; /** * The JSON Content of the Outputs of the ARM Template Deployment. */ public /*out*/ readonly outputContent!: pulumi.Output<string>; /** * The contents of the ARM Template parameters file - containing a JSON list of parameters. */ public readonly parametersContent!: pulumi.Output<string>; /** * A mapping of tags which should be assigned to the Template. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * The contents of the ARM Template which should be deployed into this Resource Group. Cannot be specified with `templateSpecVersionId`. */ public readonly templateContent!: pulumi.Output<string>; /** * The ID of the Template Spec Version to deploy. Cannot be specified with `templateContent`. */ public readonly templateSpecVersionId!: pulumi.Output<string | undefined>; /** * Create a GroupTemplateDeployment resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: GroupTemplateDeploymentArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: GroupTemplateDeploymentArgs | GroupTemplateDeploymentState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as GroupTemplateDeploymentState | undefined; inputs["debugLevel"] = state ? state.debugLevel : undefined; inputs["location"] = state ? state.location : undefined; inputs["managementGroupId"] = state ? state.managementGroupId : undefined; inputs["name"] = state ? state.name : undefined; inputs["outputContent"] = state ? state.outputContent : undefined; inputs["parametersContent"] = state ? state.parametersContent : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["templateContent"] = state ? state.templateContent : undefined; inputs["templateSpecVersionId"] = state ? state.templateSpecVersionId : undefined; } else { const args = argsOrState as GroupTemplateDeploymentArgs | undefined; if ((!args || args.managementGroupId === undefined) && !opts.urn) { throw new Error("Missing required property 'managementGroupId'"); } inputs["debugLevel"] = args ? args.debugLevel : undefined; inputs["location"] = args ? args.location : undefined; inputs["managementGroupId"] = args ? args.managementGroupId : undefined; inputs["name"] = args ? args.name : undefined; inputs["parametersContent"] = args ? args.parametersContent : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["templateContent"] = args ? args.templateContent : undefined; inputs["templateSpecVersionId"] = args ? args.templateSpecVersionId : undefined; inputs["outputContent"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(GroupTemplateDeployment.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering GroupTemplateDeployment resources. */ export interface GroupTemplateDeploymentState { /** * The Debug Level which should be used for this Resource Group Template Deployment. Possible values are `none`, `requestContent`, `responseContent` and `requestContent, responseContent`. */ debugLevel?: pulumi.Input<string>; /** * The Azure Region where the Template should exist. Changing this forces a new Template to be created. */ location?: pulumi.Input<string>; managementGroupId?: pulumi.Input<string>; /** * The name which should be used for this Template Deployment. Changing this forces a new Template Deployment to be created. */ name?: pulumi.Input<string>; /** * The JSON Content of the Outputs of the ARM Template Deployment. */ outputContent?: pulumi.Input<string>; /** * The contents of the ARM Template parameters file - containing a JSON list of parameters. */ parametersContent?: pulumi.Input<string>; /** * A mapping of tags which should be assigned to the Template. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The contents of the ARM Template which should be deployed into this Resource Group. Cannot be specified with `templateSpecVersionId`. */ templateContent?: pulumi.Input<string>; /** * The ID of the Template Spec Version to deploy. Cannot be specified with `templateContent`. */ templateSpecVersionId?: pulumi.Input<string>; } /** * The set of arguments for constructing a GroupTemplateDeployment resource. */ export interface GroupTemplateDeploymentArgs { /** * The Debug Level which should be used for this Resource Group Template Deployment. Possible values are `none`, `requestContent`, `responseContent` and `requestContent, responseContent`. */ debugLevel?: pulumi.Input<string>; /** * The Azure Region where the Template should exist. Changing this forces a new Template to be created. */ location?: pulumi.Input<string>; managementGroupId: pulumi.Input<string>; /** * The name which should be used for this Template Deployment. Changing this forces a new Template Deployment to be created. */ name?: pulumi.Input<string>; /** * The contents of the ARM Template parameters file - containing a JSON list of parameters. */ parametersContent?: pulumi.Input<string>; /** * A mapping of tags which should be assigned to the Template. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The contents of the ARM Template which should be deployed into this Resource Group. Cannot be specified with `templateSpecVersionId`. */ templateContent?: pulumi.Input<string>; /** * The ID of the Template Spec Version to deploy. Cannot be specified with `templateContent`. */ templateSpecVersionId?: pulumi.Input<string>; }
the_stack
import { GoslingTrackModel } from '../gosling-track-model'; import { IsChannelDeep } from '../gosling.schema.guards'; import colorToHex from '../utils/color-to-hex'; import { CompleteThemeDeep } from '../utils/theme'; import { Dimension } from '../utils/position'; import { ScaleLinear } from 'd3-scale'; import { getTextStyle } from '../utils/text-style'; export function drawColorLegend( HGC: any, trackInfo: any, tile: any, tm: GoslingTrackModel, theme: Required<CompleteThemeDeep> ) { const spec = tm.spec(); if (!IsChannelDeep(spec.color) || !spec.color.legend) { // This means we do not need to draw a legend return; } switch (spec.color.type) { case 'nominal': drawColorLegendCategories(HGC, trackInfo, tile, tm, theme); break; case 'quantitative': drawColorLegendQuantitative(HGC, trackInfo, tile, tm, theme); break; } } export function drawColorLegendQuantitative( HGC: any, trackInfo: any, tile: any, tm: GoslingTrackModel, theme: Required<CompleteThemeDeep> ) { const spec = tm.spec(); if (!IsChannelDeep(spec.color) || spec.color.type !== 'quantitative' || !spec.color.legend) { // This means we do not need to draw legend return; } /* track size */ const [trackX, trackY] = trackInfo.position; const [trackWidth, trackHeight] = trackInfo.dimensions; /* Visual Parameters */ const legendWidth = 80; const legendHeight = trackHeight - 2 > 110 ? 110 : Math.max(trackHeight - 2, 40 - 2); const colorBarDim: Dimension = { top: 10, left: 55, width: 20, height: legendHeight - 20 }; const legendX = trackX + trackWidth - legendWidth - 1; const legendY = trackY + 1; /* Legend Components */ const colorScale = tm.getChannelScale('color'); const colorDomain = tm.getChannelDomainArray('color'); if (!colorScale || !colorDomain) { // We do not have enough information for creating a color legend return; } /* render */ const graphics = trackInfo.pBorder; // use pBorder not to be affected by zoomming // Background graphics.beginFill(colorToHex(theme.legend.background), theme.legend.backgroundOpacity); graphics.lineStyle( 1, colorToHex(theme.legend.backgroundStroke), theme.legend.backgroundOpacity, // alpha 0 // alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) ); graphics.drawRect(legendX, legendY, legendWidth, legendHeight); // Color bar const [startValue, endValue] = colorDomain as [number, number]; const extent = endValue - startValue; [...Array(colorBarDim.height).keys()].forEach(y => { // For each pixel, draw a small rectangle with different color const value = ((colorBarDim.height - y) / colorBarDim.height) * extent + startValue; graphics.beginFill( colorToHex(colorScale(value)), 1 // alpha ); graphics.lineStyle( 1, colorToHex(theme.legend.backgroundStroke), 0, // alpha 0.5 // alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) ); graphics.drawRect(legendX + colorBarDim.left, legendY + colorBarDim.top + y, colorBarDim.width, 1); }); // Ticks & labels const tickCount = Math.max(Math.ceil(colorBarDim.height / 30), 2); let ticks = (colorScale as ScaleLinear<any, any>) .ticks(tickCount) .filter(v => colorDomain[0] <= v && v <= colorDomain[1]); if (ticks.length === 1) { // Sometimes, ticks() gives a single value, so use a larger tickCount. ticks = (colorScale as ScaleLinear<any, any>) .ticks(tickCount + 1) .filter(v => colorDomain[0] <= v && v <= colorDomain[1]); } const TICK_STROKE_SIZE = 1; graphics.lineStyle( TICK_STROKE_SIZE, colorToHex(theme.legend.tickColor), 1, // alpha 0.5 // alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) ); // label text style const labelTextStyle = getTextStyle({ color: theme.legend.labelColor, size: theme.legend.labelFontSize, fontWeight: theme.legend.labelFontWeight, fontFamily: theme.legend.labelFontFamily }); const tickEnd = legendX + colorBarDim.left; ticks.forEach(value => { let y = legendY + colorBarDim.top + colorBarDim.height - ((value - startValue) / extent) * colorBarDim.height; // Prevent ticks from exceeding outside of a color bar by the stroke size of ticks if (y === legendY + colorBarDim.top) { y += TICK_STROKE_SIZE / 2.0; } else if (y === legendY + colorBarDim.top + colorBarDim.height) { y -= TICK_STROKE_SIZE / 2.0; } // ticks graphics.moveTo(tickEnd - 3, y); graphics.lineTo(tickEnd, y); // labels const textGraphic = new HGC.libraries.PIXI.Text(value, labelTextStyle); textGraphic.anchor.x = 1; textGraphic.anchor.y = 0.5; textGraphic.position.x = tickEnd - 6; textGraphic.position.y = y; graphics.addChild(textGraphic); }); } export function drawColorLegendCategories( HGC: any, trackInfo: any, tile: any, tm: GoslingTrackModel, theme: Required<CompleteThemeDeep> ) { /* track spec */ const spec = tm.spec(); if (!IsChannelDeep(spec.color) || spec.color.type !== 'nominal' || !spec.color.legend) { // This means we do not need to draw legend return; } /* color separation */ const colorCategories: string[] = (tm.getChannelDomainArray('color') as string[]) ?? ['___SINGLE_COLOR___']; if (colorCategories.length === 0) { // We do not need to draw a legend for only one color return; } /* render */ const graphics = trackInfo.pBorder; // use pBorder not to be affected by zoomming const paddingX = 10; const paddingY = 4; let cumY = paddingY; let maxWidth = 0; const recipe: { x: number; y: number; color: string }[] = []; // label text style const labelTextStyle = getTextStyle({ color: theme.legend.labelColor, size: theme.legend.labelFontSize, fontWeight: theme.legend.labelFontWeight, fontFamily: theme.legend.labelFontFamily }); if (spec.style?.inlineLegend) { // Show legend in a single horizontal line // !! reversed to add the last category first from the right side colorCategories .map(d => d) .reverse() .forEach(category => { if (maxWidth > trackInfo.dimensions[0]) { // We do not draw labels overflow return; } const color = tm.encodedValue('color', category); const textGraphic = new HGC.libraries.PIXI.Text(category, labelTextStyle); textGraphic.anchor.x = 1; textGraphic.anchor.y = 0; textGraphic.position.x = trackInfo.position[0] + trackInfo.dimensions[0] - maxWidth - paddingX; textGraphic.position.y = trackInfo.position[1] + paddingY; graphics.addChild(textGraphic); const textStyleObj = new HGC.libraries.PIXI.TextStyle(labelTextStyle); const textMetrics = HGC.libraries.PIXI.TextMetrics.measureText(category, textStyleObj); if (cumY < textMetrics.height + paddingY * 3) { cumY = textMetrics.height + paddingY * 3; } recipe.push({ x: trackInfo.position[0] + trackInfo.dimensions[0] - textMetrics.width - maxWidth - paddingX * 2, y: trackInfo.position[1] + paddingY + textMetrics.height / 2.0, color }); maxWidth += textMetrics.width + paddingX * 3; }); } else { // Show legend vertically if (spec.style?.legendTitle) { const textGraphic = new HGC.libraries.PIXI.Text(spec.style?.legendTitle, { ...labelTextStyle, fontWeight: 'bold' }); textGraphic.anchor.x = 1; textGraphic.anchor.y = 0; textGraphic.position.x = trackInfo.position[0] + trackInfo.dimensions[0] - paddingX; textGraphic.position.y = trackInfo.position[1] + cumY; const textStyleObj = new HGC.libraries.PIXI.TextStyle({ ...labelTextStyle, fontWeight: 'bold' }); const textMetrics = HGC.libraries.PIXI.TextMetrics.measureText(spec.style?.legendTitle, textStyleObj); graphics.addChild(textGraphic); cumY += textMetrics.height + paddingY * 2; } colorCategories.forEach(category => { if (cumY > trackInfo.dimensions[1]) { // We do not draw labels overflow return; } const color = tm.encodedValue('color', category); const textGraphic = new HGC.libraries.PIXI.Text(category, labelTextStyle); textGraphic.anchor.x = 1; textGraphic.anchor.y = 0; textGraphic.position.x = trackInfo.position[0] + trackInfo.dimensions[0] - paddingX; textGraphic.position.y = trackInfo.position[1] + cumY; graphics.addChild(textGraphic); const textStyleObj = new HGC.libraries.PIXI.TextStyle(labelTextStyle); const textMetrics = HGC.libraries.PIXI.TextMetrics.measureText(category, textStyleObj); if (maxWidth < textMetrics.width + paddingX * 3) { maxWidth = textMetrics.width + paddingX * 3; } recipe.push({ x: trackInfo.position[0] + trackInfo.dimensions[0] - textMetrics.width - paddingX * 2, y: trackInfo.position[1] + cumY + textMetrics.height / 2.0, color }); cumY += textMetrics.height + paddingY * 2; }); } graphics.beginFill(colorToHex(theme.legend.background), theme.legend.backgroundOpacity); graphics.lineStyle( 1, colorToHex(theme.legend.backgroundStroke), theme.legend.backgroundOpacity, // alpha 0 // alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) ); graphics.drawRect( trackInfo.position[0] + trackInfo.dimensions[0] - maxWidth - 1, trackInfo.position[1] + 1, maxWidth, cumY - paddingY ); recipe.forEach(r => { graphics.lineStyle( 1, colorToHex('black'), 0, // alpha 0 // alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) ); graphics.beginFill(colorToHex(r.color), 1); graphics.drawCircle(r.x, r.y, 4); }); } export function drawRowLegend( HGC: any, trackInfo: any, tile: any, tm: GoslingTrackModel, theme: Required<CompleteThemeDeep> ) { /* track spec */ const spec = tm.spec(); if ( !IsChannelDeep(spec.row) || spec.row.type !== 'nominal' || !spec.row.legend // || (!IsChannelDeep(spec.y) || spec.y.type !== 'nominal' || !spec.y.legend) ) { // we do not need to draw a legend return; } /* track size */ // const trackHeight = trackInfo.dimensions[1]; /* row separation */ const rowCategories: string[] = (tm.getChannelDomainArray('row') as string[]) ?? ['___SINGLE_ROW___']; // const rowHeight = trackHeight / rowCategories.length; if (rowCategories.length === 0) { // We do not need to draw a legend for only one category return; } /* render */ const graphics = trackInfo.pBorder; // use pBorder not to affected by zoomming const paddingX = 4; const paddingY = 2; // label text style const labelTextStyle = getTextStyle({ color: theme.legend.labelColor, size: theme.legend.labelFontSize, fontWeight: theme.legend.labelFontWeight, fontFamily: theme.legend.labelFontFamily }); rowCategories.forEach(category => { const rowPosition = tm.encodedValue('row', category); const textGraphic = new HGC.libraries.PIXI.Text(category, labelTextStyle); textGraphic.anchor.x = 0; textGraphic.anchor.y = 0; textGraphic.position.x = trackInfo.position[0] + paddingX; textGraphic.position.y = trackInfo.position[1] + rowPosition + paddingY; graphics.addChild(textGraphic); const textStyleObj = new HGC.libraries.PIXI.TextStyle(labelTextStyle); const textMetrics = HGC.libraries.PIXI.TextMetrics.measureText(category, textStyleObj); graphics.beginFill(colorToHex(theme.legend.background), theme.legend.backgroundOpacity); graphics.lineStyle( 1, colorToHex(theme.legend.backgroundStroke), 0, // alpha 0 // alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) ); graphics.drawRect( trackInfo.position[0] + 1, trackInfo.position[1] + rowPosition + 1, textMetrics.width + paddingX * 2, textMetrics.height + paddingY * 2 ); }); }
the_stack
import { escapehtml, join } from ".."; import { AnyLiveContext, AnyLiveEvent, BaseLiveComponent, BaseLiveView, LiveComponent, LiveComponentMeta, LiveViewMeta, LiveViewTemplate, } from "../live"; import { html, HtmlSafeString, safe } from "./index"; describe("test escapeHtml", () => { it("combines statics and dynamics properly", () => { const result = html`a${1}b${2}c`; expect(result.toString()).toBe("a1b2c"); }); it("returns components of the template", () => { const result = html`a${1}b${2}c`; expect(result.partsTree()).toEqual({ 0: "1", 1: "2", s: ["a", "b", "c"], }); }); it("returns components of the template with templates", () => { const result = html`a${1}b${html`sub${"sub1"}`}c`; expect(result.partsTree()).toEqual({ 0: "1", 1: { 0: "sub1", s: ["sub", ""], }, s: ["a", "b", "c"], }); }); it("can apply different dynamics to a HtmlSafeString", () => { const result = html`before${"middle"}after`; expect(result.toString()).toBe("beforemiddleafter"); expect(new HtmlSafeString(result.statics, ["diffmid"]).toString()).toBe("beforediffmidafter"); }); it("Throws error if dynamics is zero and statics not one", () => { const result = new HtmlSafeString(["a", "b"], []); expect(() => result.partsTree()).toThrow(); }); it("works for if/then controls", () => { const template = (show: boolean) => html`before${show ? "show" : ""}after`; let result = template(true); expect(result.toString()).toBe("beforeshowafter"); result = template(false); expect(result.toString()).toBe("beforeafter"); }); it("can join array without commas", () => { const stuff = ["a", "b", "c"]; const result = html`${stuff}`; expect(result.toString()).toBe("abc"); }); it("can join zero length array", () => { const empty: string[] = []; const result = join(empty); expect(result.toString()).toBe(""); }); it("escapes unsafe child even if parent is rendered with safe", () => { const child = html`${"<foo>"}`; const parent = safe(`<span>${child}</span>`); expect(parent.toString()).toBe("<span>&lt;foo&gt;</span>"); }); it("more join array without commas on multiple levels", () => { const result = html`${html`<a>${1}${2}${3}</a>`}`; expect(result.toString()).toBe("<a>123</a>"); expect(result.partsTree()).toEqual({ 0: { 0: "1", 1: "2", 2: "3", s: ["<a>", "", "", "</a>"], }, s: ["", ""], }); }); it("non-interpolated literal should just be a single static", () => { const result = html`abc`; expect(result.partsTree()).toEqual({ s: ["abc"], }); }); it("array of dynamics maps to object with s and d attrs", () => { const strings = ["a", "b", "c"]; const result = html`1${strings.map((x) => html`${x}`)}2`; expect(result.partsTree()).toEqual({ 0: { s: ["", ""], d: [["a"], ["b"], ["c"]], }, s: ["1", "2"], }); }); it("tree of templates", () => { const result = html`3${html`2${html`1${1}1`}${2}2`}${3}3`; expect(result.partsTree()).toEqual({ 0: { 0: { 0: "1", s: ["1", "1"], }, 1: "2", s: ["2", "", "2"], }, 1: "3", s: ["3", "", "3"], }); }); it("render empty stores has the right parts", () => { const empty = renderStores("", [], false); expect(empty.partsTree()).toEqual({ "0": "", "1": "", "2": "", "3": "", s: [...empty.statics], }); }); it("render loading stores has the right parts", () => { const loading = renderStores("80204", [], true); expect(loading.partsTree()).toEqual({ "0": "80204", "1": "readonly", "2": { s: [`${renderLoading().statics}`] }, "3": "", s: [...loading.statics], } as any); }); it("render loaded stores has the right parts", () => { const loaded = renderStores("80204", stores.slice(3), false); // console.log('partsTree', JSON.stringify(loaded.partsTree(), null, 2)); expect(loaded.partsTree()).toEqual({ "0": "80204", "1": "", "2": "", "3": { d: [ [ stores[3].name, { s: renderStoreStatusWithoutEmojis(stores[3]).statics }, stores[3].street, stores[3].phone_number, ], [ stores[4].name, { s: renderStoreStatusWithoutEmojis(stores[4]).statics }, stores[4].street, stores[4].phone_number, ], [ stores[5].name, { s: renderStoreStatusWithoutEmojis(stores[5]).statics }, stores[5].street, stores[5].phone_number, ], [ stores[6].name, { s: renderStoreStatusWithoutEmojis(stores[6]).statics }, stores[6].street, stores[6].phone_number, ], ], s: renderStore(stores[3]).statics, }, s: [...loaded.statics], }); }); it("escapes a script tag in store name", () => { const xssStore: Store = { name: "<script>alert('xss')</script>", open: true, street: '123 Main"><span>hello</span> St', phone_number: "555-555-5555", zip: "80204", city: "Denver", hours: "9am-9pm", }; const loaded = renderStores("80204", [xssStore], false); // console.log('partsTree', JSON.stringify(loaded.partsTree(), null, 2)); expect(loaded.partsTree()).toEqual({ "0": "80204", "1": "", "2": "", "3": { d: [ [ escapehtml(xssStore.name), { s: renderStoreStatusWithoutEmojis(xssStore).statics }, escapehtml(xssStore.street), xssStore.phone_number, ], ], s: renderStore(xssStore).statics, }, s: [...loaded.statics], }); }); it("live component parts renders", () => { const liveComponentResult = new HtmlSafeString(["1"], [], true); const liveView = html`<div>${liveComponentResult}</div>`; expect(liveView.partsTree()).toEqual({ 0: 1, // LiveComponents result in a single number s: ["<div>", "</div>"], }); }); it("live component parts renders", async () => { const lv = new TestLiveView(); const url = new URL("http://example.com/foo"); const res = await lv.render( {}, { csrfToken: "", live_component: async ( liveComponent: LiveComponent<AnyLiveContext, AnyLiveEvent>, params?: Partial<AnyLiveContext & { id: number }> ) => { return new HtmlSafeString(["1"], [], true); }, url, } ); expect(res.partsTree()).toEqual({ 0: 1, // LiveComponents result in a single number s: ["", ""], }); }); it("optimizes single item statics with no dynamics into a string", () => { const result = html`a${"b"}`; expect(result.partsTree()).toEqual({ 0: "b", s: ["a", ""] }); }); }); class TestLiveComponent extends BaseLiveComponent { render(context: AnyLiveContext, meta: LiveComponentMeta): LiveViewTemplate { return html`<div>LiveComponent</div>`; } } class TestLiveView extends BaseLiveView { async render(context: AnyLiveContext, meta: LiveViewMeta): Promise<LiveViewTemplate> { return html`${await meta.live_component(new TestLiveComponent(), { id: 1 })}`; } } interface Store { name: string; street: string; city: string; zip: string; hours: string; phone_number: string; open: boolean; } const renderStoreStatusWithoutEmojis = (store: Store) => { if (store.open) { return html`<span class="open">Open</span>`; } else { return html`<span class="closed">Closed</span>`; } }; const renderStoreStatusWithEmojis = (store: Store) => { if (store.open) { return html`<span class="open">${statusEmojis(store)} Open</span>`; } else { return html`<span class="closed">${statusEmojis(store)} Closed</span>`; } }; const statusEmojis = (store: Store) => { if (store.open) { return html`🔓`; } else { return html`🔐`; } }; const renderLoading = () => { return html`<div class="loader">Loading...</div>`; }; const renderStore = (store: Store) => { return html` <li> <div class="first-line"> <div class="name">${store.name}</div> <div class="status">${renderStoreStatusWithoutEmojis(store)}</div> <div class="second-line"> <div class="street">📍 ${store.street}</div> <div class="phone_number">📞 ${store.phone_number}</div> </div> </div> </li>`; }; const renderStores = (zip: string, stores: Store[], loading: boolean) => { return html` <h1>Find a Store</h1> <div id="search"> <form phx-submit="zip-search"> <input type="text" name="zip" value="${zip}" placeholder="Zip Code" autofocus autocomplete="off" ${loading ? "readonly" : ""} /> <button type="submit">🔎</button> </form> ${loading ? renderLoading() : ""} <div class="stores"> <ul> ${stores.map((store) => renderStore(store))} </ul> </div> </div> `; }; const stores: Store[] = [ { name: "Downtown Helena", street: "312 Montana Avenue", phone_number: "406-555-0100", city: "Helena, MT", zip: "59602", open: true, hours: "8am - 10pm M-F", }, { name: "East Helena", street: "227 Miner's Lane", phone_number: "406-555-0120", city: "Helena, MT", zip: "59602", open: false, hours: "8am - 10pm M-F", }, { name: "Westside Helena", street: "734 Lake Loop", phone_number: "406-555-0130", city: "Helena, MT", zip: "59602", open: true, hours: "8am - 10pm M-F", }, { name: "Downtown Denver", street: "426 Aspen Loop", phone_number: "303-555-0140", city: "Denver, CO", zip: "80204", open: true, hours: "8am - 10pm M-F", }, { name: "Midtown Denver", street: "7 Broncos Parkway", phone_number: "720-555-0150", city: "Denver, CO", zip: "80204", open: false, hours: "8am - 10pm M-F", }, { name: "Denver Stapleton", street: "965 Summit Peak", phone_number: "303-555-0160", city: "Denver, CO", zip: "80204", open: true, hours: "8am - 10pm M-F", }, { name: "Denver West", street: "501 Mountain Lane", phone_number: "720-555-0170", city: "Denver, CO", zip: "80204", open: true, hours: "8am - 10pm M-F", }, ];
the_stack
import { Injectable } from '@angular/core'; import { CoreSyncBlockedError } from '@classes/base-sync'; import { CoreNetworkError } from '@classes/errors/network-error'; import { CoreCourseActivitySyncBaseProvider } from '@features/course/classes/activity-sync'; import { CoreCourse, CoreCourseAnyModuleData } from '@features/course/services/course'; import { CoreCourseLogHelper } from '@features/course/services/log-helper'; import { CoreApp } from '@services/app'; import { CoreSites, CoreSitesReadingStrategy } from '@services/sites'; import { CoreSync } from '@services/sync'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton, Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { AddonModFeedback, AddonModFeedbackProvider, AddonModFeedbackWSFeedback } from './feedback'; import { AddonModFeedbackOffline, AddonModFeedbackOfflineResponse } from './feedback-offline'; import { AddonModFeedbackPrefetchHandler, AddonModFeedbackPrefetchHandlerService } from './handlers/prefetch'; /** * Service to sync feedbacks. */ @Injectable({ providedIn: 'root' }) export class AddonModFeedbackSyncProvider extends CoreCourseActivitySyncBaseProvider<AddonModFeedbackSyncResult> { static readonly AUTO_SYNCED = 'addon_mod_feedback_autom_synced'; protected componentTranslatableString = 'feedback'; constructor() { super('AddonModFeedbackSyncProvider'); } /** * @inheritdoc */ prefetchAfterUpdate( prefetchHandler: AddonModFeedbackPrefetchHandlerService, module: CoreCourseAnyModuleData, courseId: number, regex?: RegExp, siteId?: string, ): Promise<void> { regex = regex || /^.*files$|^timers/; return super.prefetchAfterUpdate(prefetchHandler, module, courseId, regex, siteId); } /** * Try to synchronize all the feedbacks in a certain site or in all sites. * * @param siteId Site ID to sync. If not defined, sync all sites. * @param force Wether to force sync not depending on last execution. * @return Promise resolved if sync is successful, rejected if sync fails. */ syncAllFeedbacks(siteId?: string, force?: boolean): Promise<void> { return this.syncOnSites('all feedbacks', this.syncAllFeedbacksFunc.bind(this, !!force), siteId); } /** * Sync all pending feedbacks on a site. * * @param force Wether to force sync not depending on last execution. * @param siteId Site ID to sync. If not defined, sync all sites. * @param Promise resolved if sync is successful, rejected if sync fails. */ protected async syncAllFeedbacksFunc(force: boolean, siteId?: string): Promise<void> { // Sync all new responses. const responses = await AddonModFeedbackOffline.getAllFeedbackResponses(siteId); // Do not sync same feedback twice. const treated: Record<number, boolean> = {}; await Promise.all(responses.map(async (response) => { if (treated[response.feedbackid]) { return; } treated[response.feedbackid] = true; const result = force ? await this.syncFeedback(response.feedbackid, siteId) : await this.syncFeedbackIfNeeded(response.feedbackid, siteId); if (result?.updated) { // Sync successful, send event. CoreEvents.trigger(AddonModFeedbackSyncProvider.AUTO_SYNCED, { feedbackId: response.feedbackid, warnings: result.warnings, }, siteId); } })); } /** * Sync a feedback only if a certain time has passed since the last time. * * @param feedbackId Feedback ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the feedback is synced or if it doesn't need to be synced. */ async syncFeedbackIfNeeded(feedbackId: number, siteId?: string): Promise<AddonModFeedbackSyncResult | undefined> { siteId = siteId || CoreSites.getCurrentSiteId(); const needed = await this.isSyncNeeded(feedbackId, siteId); if (needed) { return this.syncFeedback(feedbackId, siteId); } } /** * Synchronize all offline responses of a feedback. * * @param feedbackId Feedback ID to be synced. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if sync is successful, rejected otherwise. */ syncFeedback(feedbackId: number, siteId?: string): Promise<AddonModFeedbackSyncResult> { siteId = siteId || CoreSites.getCurrentSiteId(); const currentSyncPromise = this.getOngoingSync(feedbackId, siteId); if (currentSyncPromise) { // There's already a sync ongoing for this feedback, return the promise. return currentSyncPromise; } // Verify that feedback isn't blocked. if (CoreSync.isBlocked(AddonModFeedbackProvider.COMPONENT, feedbackId, siteId)) { this.logger.debug(`Cannot sync feedback '${feedbackId}' because it is blocked.`); throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); } this.logger.debug(`Try to sync feedback '${feedbackId}' in site ${siteId}'`); return this.addOngoingSync(feedbackId, this.performSyncFeedback(feedbackId, siteId), siteId); } /** * Perform the feedback sync. * * @param feedbackId Feedback ID. * @param siteId Site ID. * @return Promise resolved in success. */ protected async performSyncFeedback(feedbackId: number, siteId: string): Promise<AddonModFeedbackSyncResult> { const result: AddonModFeedbackSyncResult = { warnings: [], updated: false, }; // Sync offline logs. await CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(AddonModFeedbackProvider.COMPONENT, feedbackId, siteId)); // Get offline responses to be sent. const responses = await CoreUtils.ignoreErrors(AddonModFeedbackOffline.getFeedbackResponses(feedbackId, siteId)); if (!responses || !responses.length) { // Nothing to sync. await CoreUtils.ignoreErrors(this.setSyncTime(feedbackId, siteId)); return result; } if (!CoreApp.isOnline()) { // Cannot sync in offline. throw new CoreNetworkError(); } const courseId = responses[0].courseid; const feedback = await AddonModFeedback.getFeedbackById(courseId, feedbackId, { siteId }); if (!feedback.multiple_submit) { // If it does not admit multiple submits, check if it is completed to know if we can submit. const isCompleted = await AddonModFeedback.isCompleted(feedbackId, { cmId: feedback.coursemodule, siteId }); if (isCompleted) { // Cannot submit again, delete resposes. await Promise.all(responses.map((data) => AddonModFeedbackOffline.deleteFeedbackPageResponses(feedbackId, data.page, siteId))); result.updated = true; this.addOfflineDataDeletedWarning( result.warnings, feedback.name, Translate.instant('addon.mod_feedback.this_feedback_is_already_submitted'), ); await CoreUtils.ignoreErrors(this.setSyncTime(feedbackId, siteId)); return result; } } const timemodified = await AddonModFeedback.getCurrentCompletedTimeModified(feedbackId, { readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK, siteId, }); // Sort by page. responses.sort((a, b) => a.page - b.page); const orderedData = responses.map((data) => ({ function: this.processPage.bind(this, feedback, data, siteId, timemodified, result), blocking: true, })); // Execute all the processes in order to solve dependencies. await CoreUtils.executeOrderedPromises(orderedData); if (result.updated) { // Data has been sent to server, update data. try { const module = await CoreCourse.getModuleBasicInfoByInstance(feedbackId, 'feedback', { siteId }); await this.prefetchAfterUpdate(AddonModFeedbackPrefetchHandler.instance, module, courseId, undefined, siteId); } catch { // Ignore errors. } } // Sync finished, set sync time. await CoreUtils.ignoreErrors(this.setSyncTime(feedbackId, siteId)); return result; } /** * Convenience function to sync process page calls. * * @param feedback Feedback object. * @param data Response data. * @param siteId Site Id. * @param timemodified Current completed modification time. * @param result Result object to be modified. * @return Resolve when done or rejected with error. */ protected async processPage( feedback: AddonModFeedbackWSFeedback, data: AddonModFeedbackOfflineResponse, siteId: string, timemodified: number, result: AddonModFeedbackSyncResult, ): Promise<void> { // Delete all pages that are submitted before changing website. if (timemodified > data.timemodified) { return AddonModFeedbackOffline.deleteFeedbackPageResponses(feedback.id, data.page, siteId); } try { await AddonModFeedback.processPageOnline(feedback.id, data.page, data.responses, false, siteId); result.updated = true; await AddonModFeedbackOffline.deleteFeedbackPageResponses(feedback.id, data.page, siteId); } catch (error) { if (!CoreUtils.isWebServiceError(error)) { // Couldn't connect to server, reject. throw error; } // The WebService has thrown an error, this means that responses cannot be submitted. Delete them. result.updated = true; await AddonModFeedbackOffline.deleteFeedbackPageResponses(feedback.id, data.page, siteId); // Responses deleted, add a warning. this.addOfflineDataDeletedWarning( result.warnings, feedback.name, error, ); } } } export const AddonModFeedbackSync = makeSingleton(AddonModFeedbackSyncProvider); /** * Data returned by a feedback sync. */ export type AddonModFeedbackSyncResult = { warnings: string[]; // List of warnings. updated: boolean; // Whether some data was sent to the server or offline data was updated. }; /** * Data passed to AUTO_SYNCED event. */ export type AddonModFeedbackAutoSyncData = { feedbackId: number; warnings: string[]; };
the_stack
import { extractRequestError, LogService, MatrixClient } from "matrix-bot-sdk"; import { ListRule } from "./ListRule"; export const RULE_USER = "m.policy.rule.user"; export const RULE_ROOM = "m.policy.rule.room"; export const RULE_SERVER = "m.policy.rule.server"; // README! The order here matters for determining whether a type is obsolete, most recent should be first. // These are the current and historical types for each type of rule which were used while MSC2313 was being developed // and were left as an artifact for some time afterwards. // Most rules (as of writing) will have the prefix `m.room.rule.*` as this has been in use for roughly 2 years. export const USER_RULE_TYPES = [RULE_USER, "m.room.rule.user", "org.matrix.mjolnir.rule.user"]; export const ROOM_RULE_TYPES = [RULE_ROOM, "m.room.rule.room", "org.matrix.mjolnir.rule.room"]; export const SERVER_RULE_TYPES = [RULE_SERVER, "m.room.rule.server", "org.matrix.mjolnir.rule.server"]; export const ALL_RULE_TYPES = [...USER_RULE_TYPES, ...ROOM_RULE_TYPES, ...SERVER_RULE_TYPES]; export const SHORTCODE_EVENT_TYPE = "org.matrix.mjolnir.shortcode"; export function ruleTypeToStable(rule: string, unstable = true): string|null { if (USER_RULE_TYPES.includes(rule)) return unstable ? USER_RULE_TYPES[USER_RULE_TYPES.length - 1] : RULE_USER; if (ROOM_RULE_TYPES.includes(rule)) return unstable ? ROOM_RULE_TYPES[ROOM_RULE_TYPES.length - 1] : RULE_ROOM; if (SERVER_RULE_TYPES.includes(rule)) return unstable ? SERVER_RULE_TYPES[SERVER_RULE_TYPES.length - 1] : RULE_SERVER; return null; } export enum ChangeType { Added = "ADDED", Removed = "REMOVED", Modified = "MODIFIED" } export interface ListRuleChange { readonly changeType: ChangeType, /** * State event that caused the change. * If the rule was redacted, this will be the redacted version of the event. */ readonly event: any, /** * The sender that caused the change. * The original event sender unless the change is because `event` was redacted. When the change is `event` being redacted * this will be the user who caused the redaction. */ readonly sender: string, /** * The current rule represented by the event. * If the rule has been removed, then this will show what the rule was. */ readonly rule: ListRule, /** * The previous state that has been changed. Only (and always) provided when the change type is `ChangeType.Removed` or `Modified`. * This will be a copy of the same event as `event` when a redaction has occurred and this will show its unredacted state. */ readonly previousState?: any, } /** * The BanList caches all of the rules that are active in a policy room so Mjolnir can refer to when applying bans etc. * This cannot be used to update events in the modeled room, it is a readonly model of the policy room. */ export default class BanList { private shortcode: string|null = null; // A map of state events indexed first by state type and then state keys. private state: Map<string, Map<string, any>> = new Map(); /** * Construct a BanList, does not synchronize with the room. * @param roomId The id of the policy room, i.e. a room containing MSC2313 policies. * @param roomRef A sharable/clickable matrix URL that refers to the room. * @param client A matrix client that is used to read the state of the room when `updateList` is called. */ constructor(public readonly roomId: string, public readonly roomRef, private client: MatrixClient) { } /** * The code that can be used to refer to this banlist in Mjolnir commands. */ public get listShortcode(): string { return this.shortcode || ''; } /** * Lookup the current rules cached for the list. * @param stateType The event type e.g. m.policy.rule.user. * @param stateKey The state key e.g. rule:@bad:matrix.org * @returns A state event if present or null. */ private getState(stateType: string, stateKey: string) { return this.state.get(stateType)?.get(stateKey); } /** * Store this state event as part of the active room state for this BanList (used to cache rules). * The state type should be normalised if it is obsolete e.g. m.room.rule.user should be stored as m.policy.rule.user. * @param stateType The event type e.g. m.room.policy.user. * @param stateKey The state key e.g. rule:@bad:matrix.org * @param event A state event to store. */ private setState(stateType: string, stateKey: string, event: any): void { let typeTable = this.state.get(stateType); if (typeTable) { typeTable.set(stateKey, event); } else { this.state.set(stateType, new Map().set(stateKey, event)); } } /** * Return all the active rules of a given kind. * @param kind e.g. RULE_SERVER (m.policy.rule.server) * @returns The active ListRules for the ban list of that kind. */ private rulesOfKind(kind: string): ListRule[] { const rules: ListRule[] = [] const stateKeyMap = this.state.get(kind); if (stateKeyMap) { for (const event of stateKeyMap.values()) { const rule = event?.unsigned?.rule; if (rule && rule.kind === kind) { rules.push(rule); } } } return rules; } public set listShortcode(newShortcode: string) { const currentShortcode = this.shortcode; this.shortcode = newShortcode; this.client.sendStateEvent(this.roomId, SHORTCODE_EVENT_TYPE, '', {shortcode: this.shortcode}).catch(err => { LogService.error("BanList", extractRequestError(err)); if (this.shortcode === newShortcode) this.shortcode = currentShortcode; }); } public get serverRules(): ListRule[] { return this.rulesOfKind(RULE_SERVER); } public get userRules(): ListRule[] { return this.rulesOfKind(RULE_USER); } public get roomRules(): ListRule[] { return this.rulesOfKind(RULE_ROOM); } public get allRules(): ListRule[] { return [...this.serverRules, ...this.userRules, ...this.roomRules]; } /** * Synchronise the model with the room representing the ban list by reading the current state of the room * and updating the model to reflect the room. * @returns A description of any rules that were added, modified or removed from the list as a result of this update. */ public async updateList(): Promise<ListRuleChange[]> { let changes: ListRuleChange[] = []; const state = await this.client.getRoomState(this.roomId); for (const event of state) { if (event['state_key'] === '' && event['type'] === SHORTCODE_EVENT_TYPE) { this.shortcode = (event['content'] || {})['shortcode'] || null; continue; } if (event['state_key'] === '' || !ALL_RULE_TYPES.includes(event['type'])) { continue; } let kind: string|null = null; if (USER_RULE_TYPES.includes(event['type'])) { kind = RULE_USER; } else if (ROOM_RULE_TYPES.includes(event['type'])) { kind = RULE_ROOM; } else if (SERVER_RULE_TYPES.includes(event['type'])) { kind = RULE_SERVER; } else { continue; // invalid/unknown } const previousState = this.getState(kind, event['state_key']); // Now we need to figure out if the current event is of an obsolete type // (e.g. org.matrix.mjolnir.rule.user) when compared to the previousState (which might be m.policy.rule.user). // We do not want to overwrite a rule of a newer type with an older type even if the event itself is supposedly more recent // as it may be someone deleting the older versions of the rules. if (previousState) { const logObsoleteRule = () => { LogService.info('BanList', `In BanList ${this.roomRef}, conflict between rules ${event['event_id']} (with obsolete type ${event['type']}) ` + `and ${previousState['event_id']} (with standard type ${previousState['type']}). Ignoring rule with obsolete type.`); } if (kind === RULE_USER && USER_RULE_TYPES.indexOf(event['type']) > USER_RULE_TYPES.indexOf(previousState['type'])) { logObsoleteRule(); continue; } else if (kind === RULE_ROOM && ROOM_RULE_TYPES.indexOf(event['type']) > ROOM_RULE_TYPES.indexOf(previousState['type'])) { logObsoleteRule(); continue; } else if (kind === RULE_SERVER && SERVER_RULE_TYPES.indexOf(event['type']) > SERVER_RULE_TYPES.indexOf(previousState['type'])) { logObsoleteRule(); continue; } } // The reason we set the state at this point is because it is valid to want to set the state to an invalid rule // in order to mark a rule as deleted. // We always set state with the normalised state type via `kind` to de-duplicate rules. this.setState(kind, event['state_key'], event); const changeType: null|ChangeType = (() => { if (!previousState) { return ChangeType.Added; } else if (previousState['event_id'] === event['event_id']) { if (event['unsigned']?.['redacted_because']) { return ChangeType.Removed; } else { // Nothing has changed. return null; } } else { // Then the policy has been modified in some other way, possibly 'soft' redacted by a new event with empty content... if (Object.keys(event['content']).length === 0) { return ChangeType.Removed; } else { return ChangeType.Modified; } } })(); // If we haven't got any information about what the rule used to be, then it wasn't a valid rule to begin with // and so will not have been used. Removing a rule like this therefore results in no change. if (changeType === ChangeType.Removed && previousState?.unsigned?.rule) { const sender = event.unsigned['redacted_because'] ? event.unsigned['redacted_because']['sender'] : event.sender; changes.push({changeType, event, sender, rule: previousState.unsigned.rule, ... previousState ? {previousState} : {} }); // Event has no content and cannot be parsed as a ListRule. continue; } // It's a rule - parse it const content = event['content']; if (!content) continue; const entity = content['entity']; const recommendation = content['recommendation']; const reason = content['reason'] || '<no reason>'; if (!entity || !recommendation) { continue; } const rule = new ListRule(entity, recommendation, reason, kind); event.unsigned.rule = rule; if (changeType) { changes.push({rule, changeType, event, sender: event.sender, ... previousState ? {previousState} : {} }); } } return changes; } }
the_stack