text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { Trans } from "@lingui/macro"; import { i18nMark } from "@lingui/react"; import classNames from "classnames"; import { Link } from "react-router"; import PropTypes from "prop-types"; import * as React from "react"; import { Icon, Tooltip } from "@dcos/ui-kit"; import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum"; import { Dropdown } from "reactjs-components"; import { greyDark, iconSizeXs, } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens"; import JobStates from "#PLUGINS/jobs/src/js/constants/JobStates"; import TaskStates from "#PLUGINS/services/src/js/constants/TaskStates"; import CollapsingString from "#SRC/js/components/CollapsingString"; import ExpandingTable from "#SRC/js/components/ExpandingTable"; import FilterBar from "#SRC/js/components/FilterBar"; import FilterHeadline from "#SRC/js/components/FilterHeadline"; import JobStopRunModal from "#SRC/js/components/modals/JobStopRunModal"; import MesosStateStore from "#SRC/js/stores/MesosStateStore"; import TimeAgo from "#SRC/js/components/TimeAgo"; import DateUtil from "#SRC/js/utils/DateUtil"; const columnClasses = { jobID: "job-run-history-table-column-id", status: "job-run-history-table-column-status", startedAt: "job-run-history-table-column-started", finishedAt: "job-run-history-table-column-finished", runTime: "job-run-history-table-column-run-time", actions: "job-run-history-table-column-actions", }; const STOP = "Stop"; function calculateRunTime(startedAt, finishedAt) { if (finishedAt == null) { return null; } return finishedAt - startedAt; } const colGroup = ( <colgroup> <col className={columnClasses.jobID} /> <col className={columnClasses.status} /> <col className={columnClasses.startedAt} /> <col className={columnClasses.finishedAt} /> <col className={columnClasses.runTime} /> <col className={columnClasses.actions} /> </colgroup> ); class JobRunHistoryTable extends React.Component<{ job: { id: string } }> { static propTypes = { params: PropTypes.object, }; state = { selectedID: null, mesosStateStoreLoaded: false }; constructor(props) { super(props); MesosStateStore.ready.then(() => { this.setState({ mesosStateStoreLoaded: true }); }); } handleItemSelect(id) { this.setState({ selectedID: id }); } handleStopJobRunModalClose = () => { this.setState({ selectedID: null }); }; getColumnHeading(prop, order, sortBy) { const caretClassNames = classNames("caret", { [`caret--${order}`]: order != null, "caret--visible": prop === sortBy.prop, }); const headingStrings = { jobID: i18nMark("Job ID"), status: i18nMark("Status"), startedAt: i18nMark("Started"), finishedAt: i18nMark("Finished"), runTime: i18nMark("Run Time"), }; return ( <span> <Trans render="span" id={headingStrings[prop]} /> <span className={caretClassNames} /> </span> ); } getColumnClassName(prop, sortBy, row) { return classNames(columnClasses[prop], { active: prop === sortBy.prop, clickable: row == null, }); } getColumns() { return [ { className: this.getColumnClassName, heading: this.getColumnHeading, prop: "jobID", render: this.renderJobIDColumn, sortable: true, }, { className: this.getColumnClassName, heading: this.getColumnHeading, prop: "status", render: this.renderStatusColumn, sortable: true, }, { className: this.getColumnClassName, heading: this.getColumnHeading, prop: "startedAt", render: this.renderTimeColumn, sortable: true, }, { className: this.getColumnClassName, heading: this.getColumnHeading, prop: "finishedAt", render: this.renderTimeColumn, sortable: true, }, { className: this.getColumnClassName, heading: this.getColumnHeading, prop: "runTime", render: this.renderRunTimeColumn, sortable: true, }, { className: this.getColumnClassName, heading: "", prop: "actions", render: this.renderActionsColumn, sortable: false, }, ]; } getData(job) { return job.jobRuns.nodes.map((jobRun) => { const children = jobRun.tasks.nodes.map((jobTask) => { const startedAt = jobTask.dateStarted; const finishedAt = jobTask.dateCompleted; const runTime = calculateRunTime(startedAt, finishedAt); return { taskID: jobTask.taskId, status: jobTask.status, startedAt, finishedAt, runTime, }; }); const startedAt = jobRun.dateCreated; const finishedAt = jobRun.dateFinished; const runTime = calculateRunTime(startedAt, finishedAt); return { finishedAt, id: jobRun.jobID, jobID: job.id, startedAt, status: jobRun.status, runTime, children, }; }); } getDisabledItemsMap(job) { return job.jobRuns.nodes.reduce((memo, jobRun) => { const isDisabled = ["ACTIVE", "INITIAL", "STARTING"].indexOf(jobRun.status) < 0; memo[jobRun.jobID] = isDisabled; return memo; }, {}); } renderJobIDColumn = (prop, row, rowOptions = {}) => { if (!rowOptions.isParent) { const taskID = row.taskID; if (!this.state.mesosStateStoreLoaded) { return <Trans>Loading...</Trans>; } // It may be that the data only *seems* to be present because we don't // remove tasks from the MesosStateStore when they're garbage collected in // the background. const dataSeemsStillPresent = !!MesosStateStore.getTaskFromTaskID(taskID); return ( <div className="expanding-table-primary-cell-heading text-overflow"> {dataSeemsStillPresent ? ( <Link className="table-cell-link-secondary" to={`/jobs/detail/${this.props.job.id}/tasks/${taskID}`} title={taskID} > <CollapsingString endLength={15} string={taskID} /> </Link> ) : ( <Tooltip preferredDirections={["bottom-left"]} trigger={<span>{taskID}</span>} > <Trans> The data related to this task has already been cleaned up. </Trans> </Tooltip> )} </div> ); } const cellContent = ( <span className="table-cell-flex-box"> <span className="icon-margin-right table-cell-icon"> <Icon color={greyDark} shape={SystemIcons.PageDocument} size={iconSizeXs} /> </span> <CollapsingString endLength={15} string={row[prop]} wrapperClassName="collapsing-string table-cell-value" /> </span> ); if (row.children && row.children.length > 0) { const classes = classNames("expanding-table-primary-cell is-expandable", { "is-expanded": rowOptions.isExpanded, }); const { clickHandler } = rowOptions; return ( <div className={classes} onClick={clickHandler}> {cellContent} </div> ); } return <div className="expanding-table-primary-cell">{cellContent}</div>; }; renderStatusColumn(prop, row, rowOptions = {}) { if (rowOptions.isParent) { const status = JobStates[row[prop]]; const statusClasses = classNames({ "text-success": status.stateTypes.includes("success") && !status.stateTypes.includes("failure"), "text-danger": status.stateTypes.includes("failure"), "text-neutral": status.stateTypes.includes("active"), }); return ( <Trans render="span" className={statusClasses} id={status.displayName} /> ); } const status = TaskStates[row[prop]]; const statusClasses = classNames({ "text-success": status.stateTypes.includes("success") && !status.stateTypes.includes("failure"), "text-danger": status.stateTypes.includes("failure"), }); return ( <Trans id={status.displayName} render="span" className={statusClasses} /> ); } renderRunTimeColumn(prop, row) { const time = row[prop]; if (time == null) { return <Trans render="div">N/A</Trans>; } // L10NTODO: Relative time const runTimeFormat = DateUtil.getDuration(time); return <div>{runTimeFormat}</div>; } renderActionsColumn = (prop, row) => { if (!["ACTIVE", "INITIAL", "STARTING"].includes(row.status)) { return; } const actions = [ { className: "hidden", id: "default", html: "", selectedHtml: ( <Icon shape={SystemIcons.EllipsisVertical} size={iconSizeXs} /> ), }, { id: STOP, html: <Trans render="span" className="text-danger" id={STOP} />, }, ]; return ( <Dropdown anchorRight={true} buttonClassName="button button-mini button-link" dropdownMenuClassName="dropdown-menu" dropdownMenuListClassName="dropdown-menu-list" dropdownMenuListItemClassName="clickable" wrapperClassName="dropdown flush-bottom table-cell-icon actions-dropdown" items={actions} persistentID={"default"} onItemSelection={this.handleItemSelect.bind(this, row.id)} scrollContainer=".gm-scroll-view" scrollContainerParentSelector=".gm-prevented" transition={true} transitionName="dropdown-menu" disabled={false} /> ); }; renderTimeColumn(prop, row) { // L10NTODO: Relative time return <TimeAgo time={row[prop]} autoUpdate={false} />; } render() { const { job } = this.props; const { selectedID } = this.state; const totalRunCount = job.jobRuns.nodes.length; const disabledIDs = this.getDisabledItemsMap(job); if (disabledIDs[selectedID]) { this.handleItemSelect(null); } return ( <div> <FilterBar> <FilterHeadline currentLength={totalRunCount} name={i18nMark("Run")} onReset={() => {}} totalLength={totalRunCount} /> </FilterBar> <ExpandingTable className="expanding-table table table-hover table-flush table-borderless-outer table-borderless-inner-columns flush-bottom" childRowClassName="expanding-table-child" columns={this.getColumns()} colGroup={colGroup} data={this.getData(job)} /> {selectedID && this.props.job.id ? ( <JobStopRunModal jobID={this.props.job.id} jobRunID={selectedID} onClose={this.handleStopJobRunModalClose} /> ) : null} </div> ); } } export default JobRunHistoryTable;
the_stack
* Defines the JVM opcodes, access flags and array type codes. This interface * does not define all the JVM opcodes because some opcodes are automatically * handled. For example, the xLOAD and xSTORE opcodes are automatically replaced * by xLOAD_n and xSTORE_n opcodes when possible. The xLOAD_n and xSTORE_n * opcodes are therefore not defined in this interface. Likewise for LDC, * automatically replaced by LDC_W or LDC2_W when necessary, WIDE, GOTO_W and * JSR_W. * * @author Eric Bruneton * @author Eugene Kuleshov */ export namespace Opcodes { export const ASM4 : number = 4 << 16 | 0 << 8 | 0; export const ASM5 : number = 5 << 16 | 0 << 8 | 0; export const V1_1 : number = 3 << 16 | 45; export const V1_2 : number = 0 << 16 | 46; export const V1_3 : number = 0 << 16 | 47; export const V1_4 : number = 0 << 16 | 48; export const V1_5 : number = 0 << 16 | 49; export const V1_6 : number = 0 << 16 | 50; export const V1_7 : number = 0 << 16 | 51; export const V1_8 : number = 0 << 16 | 52; export const ACC_PUBLIC : number = 1; export const ACC_PRIVATE : number = 2; export const ACC_PROTECTED : number = 4; export const ACC_STATIC : number = 8; export const ACC_FINAL : number = 16; export const ACC_SUPER : number = 32; export const ACC_SYNCHRONIZED : number = 32; export const ACC_VOLATILE : number = 64; export const ACC_BRIDGE : number = 64; export const ACC_VARARGS : number = 128; export const ACC_TRANSIENT : number = 128; export const ACC_NATIVE : number = 256; export const ACC_INTERFACE : number = 512; export const ACC_ABSTRACT : number = 1024; export const ACC_STRICT : number = 2048; export const ACC_SYNTHETIC : number = 4096; export const ACC_ANNOTATION : number = 8192; export const ACC_ENUM : number = 16384; export const ACC_MANDATED : number = 32768; export const ACC_DEPRECATED : number = 131072; export const T_BOOLEAN : number = 4; export const T_CHAR : number = 5; export const T_FLOAT : number = 6; export const T_DOUBLE : number = 7; export const T_BYTE : number = 8; export const T_SHORT : number = 9; export const T_INT : number = 10; export const T_LONG : number = 11; export const H_GETFIELD : number = 1; export const H_GETSTATIC : number = 2; export const H_PUTFIELD : number = 3; export const H_PUTSTATIC : number = 4; export const H_INVOKEVIRTUAL : number = 5; export const H_INVOKESTATIC : number = 6; export const H_INVOKESPECIAL : number = 7; export const H_NEWINVOKESPECIAL : number = 8; export const H_INVOKEINTERFACE : number = 9; /** * Represents an expanded frame. See {@link ClassReader#EXPAND_FRAMES}. */ export const F_NEW : number = -1; /** * Represents a compressed frame with compexport conste frame data. */ export const F_FULL : number = 0; /** * Represents a compressed frame where locals are the same as the locals in * the previous frame, except that additional 1-3 locals are defined, and * with an empty stack. */ export const F_APPEND : number = 1; /** * Represents a compressed frame where locals are the same as the locals in * the previous frame, except that the last 1-3 locals are absent and with * an empty stack. */ export const F_CHOP : number = 2; /** * Represents a compressed frame with exactly the same locals as the * previous frame and with an empty stack. */ export const F_SAME : number = 3; /** * Represents a compressed frame with exactly the same locals as the * previous frame and with a single value on the stack. */ export const F_SAME1 : number = 4; export const TOP : number = <number>new Number(0); export const INTEGER : number = <number>new Number(1); export const FLOAT : number = <number>new Number(2); export const DOUBLE : number = <number>new Number(3); export const LONG : number = <number>new Number(4); export const NULL : number = <number>new Number(5); export const UNINITIALIZED_THIS : number = <number>new Number(6); export const NOP : number = 0; export const ACONST_NULL : number = 1; export const ICONST_M1 : number = 2; export const ICONST_0 : number = 3; export const ICONST_1 : number = 4; export const ICONST_2 : number = 5; export const ICONST_3 : number = 6; export const ICONST_4 : number = 7; export const ICONST_5 : number = 8; export const LCONST_0 : number = 9; export const LCONST_1 : number = 10; export const FCONST_0 : number = 11; export const FCONST_1 : number = 12; export const FCONST_2 : number = 13; export const DCONST_0 : number = 14; export const DCONST_1 : number = 15; export const BIPUSH : number = 16; export const SIPUSH : number = 17; export const LDC : number = 18; export const ILOAD : number = 21; export const LLOAD : number = 22; export const FLOAD : number = 23; export const DLOAD : number = 24; export const ALOAD : number = 25; export const IALOAD : number = 46; export const LALOAD : number = 47; export const FALOAD : number = 48; export const DALOAD : number = 49; export const AALOAD : number = 50; export const BALOAD : number = 51; export const CALOAD : number = 52; export const SALOAD : number = 53; export const ISTORE : number = 54; export const LSTORE : number = 55; export const FSTORE : number = 56; export const DSTORE : number = 57; export const ASTORE : number = 58; export const IASTORE : number = 79; export const LASTORE : number = 80; export const FASTORE : number = 81; export const DASTORE : number = 82; export const AASTORE : number = 83; export const BASTORE : number = 84; export const CASTORE : number = 85; export const SASTORE : number = 86; export const POP : number = 87; export const POP2 : number = 88; export const DUP : number = 89; export const DUP_X1 : number = 90; export const DUP_X2 : number = 91; export const DUP2 : number = 92; export const DUP2_X1 : number = 93; export const DUP2_X2 : number = 94; export const SWAP : number = 95; export const IADD : number = 96; export const LADD : number = 97; export const FADD : number = 98; export const DADD : number = 99; export const ISUB : number = 100; export const LSUB : number = 101; export const FSUB : number = 102; export const DSUB : number = 103; export const IMUL : number = 104; export const LMUL : number = 105; export const FMUL : number = 106; export const DMUL : number = 107; export const IDIV : number = 108; export const LDIV : number = 109; export const FDIV : number = 110; export const DDIV : number = 111; export const IREM : number = 112; export const LREM : number = 113; export const FREM : number = 114; export const DREM : number = 115; export const INEG : number = 116; export const LNEG : number = 117; export const FNEG : number = 118; export const DNEG : number = 119; export const ISHL : number = 120; export const LSHL : number = 121; export const ISHR : number = 122; export const LSHR : number = 123; export const IUSHR : number = 124; export const LUSHR : number = 125; export const IAND : number = 126; export const LAND : number = 127; export const IOR : number = 128; export const LOR : number = 129; export const IXOR : number = 130; export const LXOR : number = 131; export const IINC : number = 132; export const I2L : number = 133; export const I2F : number = 134; export const I2D : number = 135; export const L2I : number = 136; export const L2F : number = 137; export const L2D : number = 138; export const F2I : number = 139; export const F2L : number = 140; export const F2D : number = 141; export const D2I : number = 142; export const D2L : number = 143; export const D2F : number = 144; export const I2B : number = 145; export const I2C : number = 146; export const I2S : number = 147; export const LCMP : number = 148; export const FCMPL : number = 149; export const FCMPG : number = 150; export const DCMPL : number = 151; export const DCMPG : number = 152; export const IFEQ : number = 153; export const IFNE : number = 154; export const IFLT : number = 155; export const IFGE : number = 156; export const IFGT : number = 157; export const IFLE : number = 158; export const IF_ICMPEQ : number = 159; export const IF_ICMPNE : number = 160; export const IF_ICMPLT : number = 161; export const IF_ICMPGE : number = 162; export const IF_ICMPGT : number = 163; export const IF_ICMPLE : number = 164; export const IF_ACMPEQ : number = 165; export const IF_ACMPNE : number = 166; export const GOTO : number = 167; export const JSR : number = 168; export const RET : number = 169; export const TABLESWITCH : number = 170; export const LOOKUPSWITCH : number = 171; export const IRETURN : number = 172; export const LRETURN : number = 173; export const FRETURN : number = 174; export const DRETURN : number = 175; export const ARETURN : number = 176; export const RETURN : number = 177; export const GETSTATIC : number = 178; export const PUTSTATIC : number = 179; export const GETFIELD : number = 180; export const PUTFIELD : number = 181; export const INVOKEVIRTUAL : number = 182; export const INVOKESPECIAL : number = 183; export const INVOKESTATIC : number = 184; export const INVOKEINTERFACE : number = 185; export const INVOKEDYNAMIC : number = 186; export const NEW : number = 187; export const NEWARRAY : number = 188; export const ANEWARRAY : number = 189; export const ARRAYLENGTH : number = 190; export const ATHROW : number = 191; export const CHECKCAST : number = 192; export const INSTANCEOF : number = 193; export const MONITORENTER : number = 194; export const MONITOREXIT : number = 195; export const MULTIANEWARRAY : number = 197; export const IFNULL : number = 198; export const IFNONNULL : number = 199; }
the_stack
import { IPdfPrimitive } from './../../interfaces/i-pdf-primitives'; import { IPdfWriter } from './../../interfaces/i-pdf-writer'; import { Dictionary } from './../collections/dictionary'; import { PdfName } from './pdf-name'; import { ObjectStatus } from './../input-output/enum'; import { PdfCrossTable } from './../input-output/pdf-cross-table'; import { Operators } from './../input-output/pdf-operators'; import { DictionaryProperties } from './../input-output/pdf-dictionary-properties'; import { PdfSectionCollection } from './../pages/pdf-section-collection'; import { PdfAnnotation } from './../annotations/annotation'; import { PdfSection, PageSettingsState } from './../pages/pdf-section'; import { PdfPage } from './../pages/pdf-page'; import { UnicodeTrueTypeFont } from './../graphics/fonts/unicode-true-type-font'; /** * `PdfDictionary` class is used to perform primitive operations. * @private */ export class PdfDictionary implements IPdfPrimitive { /** * Indicates if the object was `changed`. * @private */ private bChanged : boolean; /** * Internal variable to store the `position`. * @default -1 * @private */ private position7 : number = -1; /** * Flag is dictionary need to `encrypt`. * @private */ private encrypt : boolean; /** * The `IPdfSavable` with the specified key. * @private */ private primitiveItems : Dictionary<string, IPdfPrimitive> = new Dictionary<string, IPdfPrimitive>(); /** * `Start marker` for dictionary. * @private */ private readonly prefix : string = '<<'; /** * `End marker` for dictionary. * @private */ private readonly suffix : string = '>>'; /** * @hidden * @private */ private resources : Object[] = []; /** * Shows the type of object `status` whether it is object registered or other status. * @private */ private status7 : ObjectStatus; /** * Indicates if the object `is currently in saving state` or not. * @private */ private isSaving7 : boolean; /** * Holds the `index` number of the object. * @private */ private index7 : number; /** * Internal variable to hold `cloned object`. * @default null * @private */ private readonly object : IPdfPrimitive = null; /** * Flag for PDF file formar 1.5 is dictionary `archiving` needed. * @default true * @private */ private archive : boolean = true; /** * @hidden * @private */ private tempPageCount : number; /** * @hidden * @private */ protected dictionaryProperties : DictionaryProperties; //events /** * Event. Raise before the object saves. * @public */ public pageBeginDrawTemplate : SaveTemplateEventHandler; /** * Event. Raise `before the object saves`. * @private */ public beginSave : SaveSectionCollectionEventHandler; /** * Event. Raise `after the object saved`. * @private */ public endSave : SaveSectionCollectionEventHandler; /** * @hidden * @private */ public sectionBeginSave : SaveSectionEventHandler; /** * @hidden * @private */ public annotationBeginSave : SaveAnnotationEventHandler; /** * @hidden * @private */ public annotationEndSave : SaveAnnotationEventHandler; /** * Event. Raise `before the object saves`. * @private */ public descendantFontBeginSave : SaveDescendantFontEventHandler; /** * Event. Raise `before the object saves`. * @private */ public fontDictionaryBeginSave : SaveFontDictionaryEventHandler; /** * Represents the Font dictionary. * @hidden * @private */ public isFont : boolean = false; //Properties /** * Gets or sets the `IPdfSavable` with the specified key. * @private */ public get items() : Dictionary<string, IPdfPrimitive> { return this.primitiveItems; } /** * Gets or sets the `Status` of the specified object. * @private */ public get status() : ObjectStatus { return this.status7; } public set status(value : ObjectStatus) { this.status7 = value; } /** * Gets or sets a value indicating whether this document `is saving` or not. * @private */ public get isSaving() : boolean { return this.isSaving7; } public set isSaving(value : boolean) { this.isSaving7 = value; } /** * Gets or sets the `index` value of the specified object. * @private */ public get objectCollectionIndex() : number { return this.index7; } public set objectCollectionIndex(value : number) { this.index7 = value; } /** * Returns `cloned object`. * @private */ public get clonedObject() : IPdfPrimitive { return this.object; } /** * Gets or sets the `position` of the object. * @private */ public get position() : number { return this.position7; } public set position(value : number) { this.position7 = value; } /** * Gets the `count`. * @private */ public get Count() : number { return this.primitiveItems.size(); } /** * Collection of `items` in the object. * @private */ public get Dictionary() : PdfDictionary { return this; } /** * Get flag if need to `archive` dictionary. * @private */ public getArchive() : boolean { return this.archive; } /** * Set flag if need to `archive` dictionary. * @private */ public setArchive(value : boolean) : void { this.archive = value; } /** * Sets flag if `encryption` is needed. * @private */ public setEncrypt(value : boolean) : void { this.encrypt = value; this.modify(); } /** * Gets flag if `encryption` is needed. * @private */ public getEncrypt() : boolean { return this.encrypt; } //constructor /** * Initializes a new empty instance of the `PdfDictionary` class. * @private */ constructor() /** * Initializes a new empty instance of the `PdfDictionary` class. * @private */ constructor(dictionary : PdfDictionary) constructor(dictionary? : PdfDictionary) { if (typeof dictionary === 'undefined') { this.primitiveItems = new Dictionary<string, IPdfPrimitive>(); this.encrypt = true; this.dictionaryProperties = new DictionaryProperties(); } else { this.primitiveItems = new Dictionary<string, IPdfPrimitive>(); let keys : string[] = dictionary.items.keys(); let values : IPdfPrimitive[] = dictionary.items.values(); for (let index : number = 0; index < dictionary.items.size(); index++) { this.primitiveItems.setValue(keys[index], values[index]); } this.status = dictionary.status; this.freezeChanges(this); this.encrypt = true; this.dictionaryProperties = new DictionaryProperties(); } } /** * `Freezes` the changes. * @private */ public freezeChanges(freezer : Object) : void { this.bChanged = false; } /** * Creates a `copy of PdfDictionary`. * @private */ public clone(crossTable : PdfCrossTable) : IPdfPrimitive { //Need to add more codings let newDict : PdfDictionary = new PdfDictionary(); return newDict; } /** * `Mark` this instance modified. * @private */ public modify() : void { this.bChanged = true; } /** * `Removes` the specified key. * @private */ public remove(key : PdfName|string) : void { if (typeof key !== 'string') { this.primitiveItems.remove(key.value); this.modify(); } else { this.remove(new PdfName(key)); } } /** * `Determines` whether the dictionary contains the key. * @private */ public containsKey(key : string|PdfName) : boolean { let returnValue : boolean = false; returnValue = this.primitiveItems.containsKey(key.toString()); return returnValue; } /** * Raises event `BeginSave`. * @private */ protected onBeginSave() : void { (this.beginSave as SaveSectionCollectionEventHandler).sender.beginSave(); } /** * Raises event `Font Dictionary BeginSave`. * @private */ protected onFontDictionaryBeginSave() : void { (this.fontDictionaryBeginSave as SaveFontDictionaryEventHandler).sender.fontDictionaryBeginSave(); } /** * Raises event `Descendant Font BeginSave`. * @private */ protected onDescendantFontBeginSave() : void { (this.descendantFontBeginSave as SaveDescendantFontEventHandler).sender.descendantFontBeginSave(); } /** * Raises event 'BeginSave'. * @private */ protected onTemplateBeginSave() : void { (this.pageBeginDrawTemplate as SaveTemplateEventHandler).sender.pageBeginSave(); } /** * Raises event `BeginSave`. * @private */ protected onBeginAnnotationSave() : void { (this.annotationBeginSave as SaveAnnotationEventHandler).sender.beginSave(); } /** * Raises event `BeginSave`. * @private */ protected onSectionBeginSave(writer : IPdfWriter) : void { let saveEvent : SaveSectionEventHandler = this.sectionBeginSave as SaveSectionEventHandler; saveEvent.sender.beginSave(saveEvent.state, writer); } //IPdfSavableMembers /** * `Saves` the object using the specified writer. * @private */ public save(writer : IPdfWriter) : void /** * `Saves` the object using the specified writer. * @private */ public save(writer : IPdfWriter, bRaiseEvent : boolean) : void public save(writer : IPdfWriter, bRaiseEvent? : boolean) : void { if (typeof bRaiseEvent === 'undefined') { this.save(writer, true); } else { writer.write(this.prefix); if (typeof this.beginSave !== 'undefined') { this.onBeginSave(); } if (typeof this.descendantFontBeginSave !== 'undefined') { this.onDescendantFontBeginSave(); } if (typeof this.fontDictionaryBeginSave !== 'undefined') { this.onFontDictionaryBeginSave(); } if (typeof this.annotationBeginSave !== 'undefined') { this.onBeginAnnotationSave(); } if (typeof this.sectionBeginSave !== 'undefined') { this.onSectionBeginSave(writer); } if (typeof this.pageBeginDrawTemplate !== 'undefined') { this.onTemplateBeginSave(); } // } if (this.Count > 0) { this.saveItems(writer); } writer.write(this.suffix); writer.write(Operators.newLine); } } /** * `Save dictionary items`. * @private */ private saveItems(writer : IPdfWriter) : void { writer.write(Operators.newLine); let keys : string[] = this.primitiveItems.keys(); let values : IPdfPrimitive[] = this.primitiveItems.values(); for (let index : number = 0; index < keys.length; index++) { let key : string = keys[index]; let name : PdfName = new PdfName(key); name.save(writer); writer.write(Operators.whiteSpace); let resources : IPdfPrimitive = values[index]; resources.save(writer); writer.write(Operators.newLine); } } } export class SaveSectionCollectionEventHandler { /** * @hidden * @private */ public sender : PdfSectionCollection; /** * New instance for `save section collection event handler` class. * @private */ public constructor(sender : PdfSectionCollection) { this.sender = sender; } } export class SaveDescendantFontEventHandler { /** * @hidden * @private */ public sender : UnicodeTrueTypeFont; /** * New instance for `save section collection event handler` class. * @private */ public constructor(sender : UnicodeTrueTypeFont) { this.sender = sender; } } export class SaveFontDictionaryEventHandler { /** * @hidden * @private */ public sender : UnicodeTrueTypeFont; /** * New instance for `save section collection event handler` class. * @private */ public constructor(sender : UnicodeTrueTypeFont) { this.sender = sender; } } export class SaveAnnotationEventHandler { /** * @hidden * @private */ public sender : PdfAnnotation; /** * New instance for `save annotation event handler` class. * @private */ public constructor(sender : PdfAnnotation) { this.sender = sender; } } export class SaveSectionEventHandler { // Fields /** * @hidden * @private */ public sender : PdfSection; /** * @hidden * @private */ public state : PageSettingsState; // constructors /** * New instance for `save section event handler` class. * @private */ public constructor(sender : PdfSection, state : PageSettingsState) { this.sender = sender; this.state = state; } } /** * SaveTemplateEventHandler class used to store information about template elements. * @private * @hidden */ export class SaveTemplateEventHandler { /** * @public * @hidden */ public sender : PdfPage; /** * New instance for save section collection event handler class. * @public */ public constructor(sender : PdfPage) { this.sender = sender; } }
the_stack
import React from "react"; import { Callout, DefaultButton, Dropdown, DropdownMenuItemType, Fabric, IDropdownOption, Stack, PrimaryButton, TextField, mergeStyleSets, } from "office-ui-fabric-react"; import Cookies from "js-cookie"; type MarketplaceUriType = ("GitHub" | "DevOps" | null); interface IProtocolItem { name: string; uri: string; } interface IMarketplaceProps { defaultURI: string; defaultURIType: MarketplaceUriType; defaultURIToken: string; defaultOption: string | number | undefined; onSelectProtocol: ((text: string) => void); disabled: boolean; } interface IMarketplaceState { uri: string; uriType: MarketplaceUriType; uriToken: string; selectedOption: string | number | undefined; protocolOptions: IDropdownOption[]; uriConfigCallout: boolean; } const styles = mergeStyleSets({ dropdown: { width: 200, }, textfiled: { width: 480, }, }); const defaultProtocolOptions: IDropdownOption[] = [ { key: "None", text: "None" }, { key: "jobsDivider", text: "-", itemType: DropdownMenuItemType.Divider }, { key: "jobsHeader", text: "Protocol Jobs", itemType: DropdownMenuItemType.Header }, ]; export default class MarketplaceForm extends React.Component<IMarketplaceProps, IMarketplaceState> { public static defaultProps: Partial<IMarketplaceProps> = { defaultURI: "https://api.github.com/repos/Microsoft/pai/contents/marketplace-v2", defaultURIType: "GitHub", defaultURIToken: "", defaultOption: undefined, disabled: false, }; public state = { uri: this.props.defaultURI, uriType: this.props.defaultURIType, uriToken: this.props.defaultURIToken, selectedOption: this.props.defaultOption, protocolOptions: defaultProtocolOptions, uriConfigCallout: false, }; private uriConfigCalloutBtn = React.createRef<HTMLDivElement>(); public componentDidMount() { this.setProtocolOptions(); } public render() { return ( <Fabric> <Stack gap={5} wrap={true} horizontal={true} verticalAlign="center"> <Stack> <Dropdown className={styles.dropdown} placeholder="Select a protocol config file" selectedKey={this.state.selectedOption} options={this.state.protocolOptions} onChange={this.selectProtocol} disabled={this.props.disabled} /> </Stack> <Stack maxWidth="5px"> <div ref={this.uriConfigCalloutBtn}> <DefaultButton onClick={this.toggleConfigCallout} iconProps={{iconName: "ConfigurationSolid"}} text="URI" disabled={this.props.disabled} /> </div> <Callout role="alertdialog" target={this.uriConfigCalloutBtn.current} onDismiss={this.toggleConfigCallout} setInitialFocus={true} hidden={!this.state.uriConfigCallout} > <Stack padding={20}> <TextField className={styles.textfiled} label="Marketplace URI" prefix={this.state.uriType || undefined} value={this.state.uri} onChange={this.setMarketplaceURI} /> <TextField className={styles.textfiled} label="Personal Access Token" value={this.state.uriToken} onChange={this.setMarketplaceURIToken} /> <Stack gap={20} padding="15px auto 0" horizontalAlign="center" horizontal={true}> <PrimaryButton text="Apply" onClick={this.applyConfigCallout} /> <DefaultButton text="Discard" onClick={this.discardConfigCallout} /> </Stack> </Stack> </Callout> </Stack> </Stack> </Fabric> ); } private toggleConfigCallout = () => { this.setState({uriConfigCallout: !this.state.uriConfigCallout}); } private applyConfigCallout = () => { this.setProtocolOptions(); this.setState({uriConfigCallout: false}); } private discardConfigCallout = () => { const marketplaceCookie = Cookies.getJSON("marketplace"); if (marketplaceCookie) { this.setState({ uri: marketplaceCookie.uri, uriType: marketplaceCookie.type, uriToken: marketplaceCookie.token, uriConfigCallout: false, }); } else { this.setState({ uri: this.props.defaultURI, uriType: this.props.defaultURIType, uriToken: this.props.defaultURIToken, uriConfigCallout: false, }); } } private formatMarketplaceURI = async (uri: string) => { // regex for https://github.com/{owner}/{repo}/tree/{branch}/{path} const githubRegExp = /^(https:\/\/)?github\.com\/([^/\s]+)\/([^/\s]+)\/tree\/(.+)$/; // regex for https://{org}.visualstudio.com/{project}/_git/{repoId}?path={path}&version=GB{branch} const devopsRegExp = /^(https:\/\/)?([^/\s]+)\.visualstudio\.com\/([^/\s]*)\/?_git\/([^\?\s]+)\?(.+)$/; let match; match = githubRegExp.exec(uri); if (match !== null) { const owner = match[2]; const repo = match[3]; const paths = match[4].split("/"); let path; let branch; let refsData; try { const refs = await fetch(`https://api.github.com/repos/${owner}/${repo}/git/refs/heads/${paths[0]}`); refsData = await refs.json(); } catch (err) { alert(err.message); } if (Array.isArray(refsData)) { for (const i of refsData) { const ref = i.ref.replace(/^refs\/heads\//, ""); if (match[4].startsWith(ref)) { branch = ref.slice(0); path = match[4].slice(branch.length + 1); break; } } } else { branch = paths[0]; path = paths.slice(1).join("/"); } return `https://api.github.com/repos/${owner}/${repo}/contents/${path}?ref=${branch}`; } match = devopsRegExp.exec(uri); if (match !== null) { const org = match[2]; const project = match[3] ? match[3] : match[4]; const repo = match[4]; const path = new URLSearchParams(match[5]).get("path"); return `https://dev.azure.com/${org}/${project}/_apis/git/repositories/${repo}/items?path=${path}&api-version=5.0`; } return uri; } private setMarketplaceURI = (event: React.FormEvent<HTMLElement>, uri?: string) => { if (uri !== undefined) { if (uri.includes("github.com")) { // https://github.com/{owner}/{repo}/tree/{branch}/{path} // https://api.github.com/repos/{owner}/{repo}/contents/{path}?ref={branch} this.setState({uri, uriType: "GitHub"}); } else if (uri.includes("visualstudio.com") || uri.includes("dev.azure.com")) { // https://{org}.visualstudio.com/{project}/_git/{repoId}?path={path}&version=GB{branch} // https://dev.azure.com/{org}/{project}/_apis/git/repositories/{repoId}/items?path={path}&api-version=5.0 this.setState({uri, uriType: "DevOps"}); } else { this.setState({uri, uriType: null}); } } } private setMarketplaceURIToken = (event: React.FormEvent<HTMLElement>, uriToken?: string) => { if (uriToken !== undefined) { this.setState({uriToken}); } } private setProtocolOptions = async () => { const api = await this.formatMarketplaceURI(this.state.uri); const protocolList = await this.getProtocolList(api, this.state.uriType); if (protocolList) { const protocolOptions: IDropdownOption[] = [... defaultProtocolOptions]; for (const protocolItem of protocolList) { protocolOptions.push({ key: protocolItem.name, text: protocolItem.name, data: protocolItem.uri, }); } this.setState({ protocolOptions }); Cookies.set("marketplace", { uri: this.state.uri, type: this.state.uriType, token: this.state.uriToken, }); } } private selectProtocol = async (event: React.FormEvent<HTMLDivElement>, option?: IDropdownOption) => { if (option !== undefined) { if (option.data !== undefined) { const requestHeaders: HeadersInit = new Headers(); if (this.state.uriToken) { requestHeaders.set( "Authorization", `Basic ${new Buffer(this.state.uriToken).toString("base64")}`, ); } try { const res = await fetch(option.data, {headers: requestHeaders}); const data = await res.text(); this.props.onSelectProtocol(data); this.setState({selectedOption: option.key}); } catch (err) { alert(`Cannot get ${option.data}`); } } } } private getProtocolList = async (uri: string, uriType: MarketplaceUriType) => { const requestHeaders: HeadersInit = new Headers(); if (this.state.uriToken) { requestHeaders.set( "Authorization", `Basic ${new Buffer(this.state.uriToken).toString("base64")}`, ); } if (uriType === "GitHub") { try { const res = await fetch(uri, {headers: requestHeaders}); const data = await res.json(); if (Array.isArray(data)) { const protocolList: IProtocolItem[] = []; for (const item of data) { if (item.type === "file") { protocolList.push({ name: item.name, uri: item.download_url, }); } } return protocolList; } else { alert(`Cannot get data\nPlease provide a valid marketplace uri`); } } catch (err) { alert(`Cannot get ${uri}\nWrong uri or access token`); } } else if (uriType === "DevOps") { let res; try { res = await fetch(uri, {headers: requestHeaders}); let data = await res.json(); if (data.isFolder && "tree" in data._links) { res = await fetch(data._links.tree.href, {headers: requestHeaders}); data = await res.json(); } if ("treeEntries" in data && Array.isArray(data.treeEntries)) { const protocolList: IProtocolItem[] = []; for (const item of data.treeEntries) { if (item.gitObjectType === "blob") { protocolList.push({ name: item.relativePath, uri: item.url, }); } } return protocolList; } else { alert(`Cannot get data\nPlease provide a valid marketplace uri`); } } catch (err) { if (res) { if (res.status === 203) { alert("Please provide a valid personal access token from Azure DevOps"); } else { alert("Please provide a valid marketplace uri"); } } else { alert(`Cannot get ${uri}\nWrong uri or access token`); } } } else { alert(`Cannot recognize uri ${uri}`); } return null; } }
the_stack
import { FirestoreWhereFilterOp } from '../adaptor' import { DocId } from '../docId' export interface WhereQuery<_Model> { type: 'where' field: string | string[] | DocId filter: FirestoreWhereFilterOp value: any } export type BasicWhereFilter = Exclude< FirestoreWhereFilterOp, 'array-contains' | 'in' > // Basic filter variation function where<Model, Key extends keyof Model>( field: DocId, filter: BasicWhereFilter, value: string ): WhereQuery<Model> // in variation function where<Model, Key extends keyof Model>( field: Key | [Key] | DocId, filter: 'in', value: string[] ): WhereQuery<Model> // Basic filter variation function where<Model, Key extends keyof Model>( field: Key | [Key], filter: BasicWhereFilter, value: Model[Key] ): WhereQuery<Model> // array-contains variation function where< Model, Key extends keyof Model, ValueArray extends Model[Key], ValueType extends keyof ValueArray >( field: Key | [Key], filter: 'array-contains', value: ValueArray[ValueType] ): WhereQuery<Model> // in variation function where<Model, Key extends keyof Model>( field: Key | [Key], filter: 'in', value: Model[Key][] ): WhereQuery<Model> // Basic filter variation function where<Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1]>( field: [Key1, Key2], filter: BasicWhereFilter, value: Model[Key1][Key2] ): WhereQuery<Model> // array-contains variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], ValueArray extends Model[Key1][Key2], ValueType extends keyof ValueArray >( field: [Key1, Key2], filter: 'array-contains', value: ValueArray[ValueType] ): WhereQuery<Model> // in variation function where<Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1]>( field: [Key1, Key2], filter: 'in', value: Model[Key1][Key2][] ): WhereQuery<Model> // Basic filter variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2] >( field: [Key1, Key2, Key3], filter: BasicWhereFilter, value: Model[Key1][Key2][Key3] ): WhereQuery<Model> // array-contains variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], ValueArray extends Model[Key1][Key2][Key3], ValueType extends keyof ValueArray >( field: [Key1, Key2, Key3], filter: 'array-contains', value: ValueArray[ValueType] ): WhereQuery<Model> // in variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2] >( field: [Key1, Key2, Key3], filter: 'in', value: Model[Key1][Key2][Key3][] ): WhereQuery<Model> // Basic filter variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3] >( field: [Key1, Key2, Key3, Key4], filter: BasicWhereFilter, value: Model[Key1][Key2][Key3][Key4] ): WhereQuery<Model> // array-contains variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], ValueArray extends Model[Key1][Key2][Key3][Key4], ValueType extends keyof ValueArray >( field: [Key1, Key2, Key3, Key4], filter: 'array-contains', value: ValueArray[ValueType] ): WhereQuery<Model> // in variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3] >( field: [Key1, Key2, Key3, Key4], filter: 'in', value: Model[Key1][Key2][Key3][Key4][] ): WhereQuery<Model> // Basic filter variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4] >( field: [Key1, Key2, Key3, Key4, Key5], filter: BasicWhereFilter, value: Model[Key1][Key2][Key3][Key4][Key5] ): WhereQuery<Model> // array-contains variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], ValueArray extends Model[Key1][Key2][Key3][Key4][Key5], ValueType extends keyof ValueArray >( field: [Key1, Key2, Key3, Key4, Key5], filter: 'array-contains', value: ValueArray[ValueType] ): WhereQuery<Model> // in variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4] >( field: [Key1, Key2, Key3, Key4, Key5], filter: 'in', value: Model[Key1][Key2][Key3][Key4][Key5][] ): WhereQuery<Model> // Basic filter variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5] >( field: [Key1, Key2, Key3, Key4, Key5, Key6], filter: BasicWhereFilter, value: Model[Key1][Key2][Key3][Key4][Key5][Key6] ): WhereQuery<Model> // array-contains variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], ValueArray extends Model[Key1][Key2][Key3][Key4][Key5][Key6], ValueType extends keyof ValueArray >( field: [Key1, Key2, Key3, Key4, Key5, Key6], filter: 'array-contains', value: ValueArray[ValueType] ): WhereQuery<Model> // in variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5] >( field: [Key1, Key2, Key3, Key4, Key5, Key6], filter: 'in', value: Model[Key1][Key2][Key3][Key4][Key5][Key6][] ): WhereQuery<Model> // Basic filter variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6] >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7], filter: BasicWhereFilter, value: Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7] ): WhereQuery<Model> // array-contains variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6], ValueArray extends Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7], ValueType extends keyof ValueArray >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7], filter: 'array-contains', value: ValueArray[ValueType] ): WhereQuery<Model> // in variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6] >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7], filter: 'in', value: Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][] ): WhereQuery<Model> // Basic filter variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6], Key8 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7] >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8], filter: BasicWhereFilter, value: Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8] ): WhereQuery<Model> // array-contains variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6], Key8 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7], ValueArray extends Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8], ValueType extends keyof ValueArray >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8], filter: 'array-contains', value: ValueArray[ValueType] ): WhereQuery<Model> // in variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6], Key8 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7] >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8], filter: 'in', value: Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8][] ): WhereQuery<Model> // Basic filter variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6], Key8 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7], Key9 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8] >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8, Key9], filter: BasicWhereFilter, value: Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8][Key9] ): WhereQuery<Model> // array-contains variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6], Key8 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7], Key9 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8], ValueArray extends Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8][Key9], ValueType extends keyof ValueArray >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8, Key9], filter: 'array-contains', value: ValueArray[ValueType] ): WhereQuery<Model> // in variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6], Key8 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7], Key9 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8] >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8, Key9], filter: 'in', value: Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8][Key9][] ): WhereQuery<Model> // Basic filter variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6], Key8 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7], Key9 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8], Key10 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8][Key9] >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8, Key9, Key10], filter: BasicWhereFilter, value: Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8][Key9][Key10] ): WhereQuery<Model> // array-contains variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6], Key8 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7], Key9 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8], Key10 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8][Key9], ValueArray extends Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8][Key9][Key10], ValueType extends keyof ValueArray >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8, Key9, Key10], filter: BasicWhereFilter, value: ValueArray[ValueType] ): WhereQuery<Model> // in variation function where< Model, Key1 extends keyof Model, Key2 extends keyof Model[Key1], Key3 extends keyof Model[Key1][Key2], Key4 extends keyof Model[Key1][Key2][Key3], Key5 extends keyof Model[Key1][Key2][Key3][Key4], Key6 extends keyof Model[Key1][Key2][Key3][Key4][Key5], Key7 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6], Key8 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7], Key9 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8], Key10 extends keyof Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8][Key9] >( field: [Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8, Key9, Key10], filter: 'in', value: Model[Key1][Key2][Key3][Key4][Key5][Key6][Key7][Key8][Key9][Key10][] ): WhereQuery<Model> /** * Creates where query. * * ```ts * import { where, ref, query, collection, Ref } from 'typesaurus' * * type User = { name: string } * type Order = { user: Ref<User>, item: string } * const users = collection<User>('users') * const orders = collection<User>('orders') * * query(orders, [where('user', '==', ref(users, '00sHm46UWKObv2W7XK9e')]) * .then(userOrders => { * console.log(userOrders.length) * //=> 42 * }) * // Or using key paths: * query(orders, [where(['address', 'city'], '==', 'Moscow']) * ``` * * @param field - The field or key path to query * @param filter - The filter operation ('<', '<=', '==', '>=', '>', 'array-contains', 'in' or 'array-contains-any') * @param value - The value to pass to the operation * @returns The where query object */ function where<Model>( field: string | string[] | DocId, filter: FirestoreWhereFilterOp, value: any ): WhereQuery<Model> { return { type: 'where', field, filter, value } } export { where }
the_stack
import { ODataParser } from "../odata/core"; import { Util } from "../utils/util"; import { Logger, LogLevel } from "../utils/logging"; import { HttpClient } from "../net/httpclient"; import { mergeHeaders } from "../net/utils"; import { RuntimeConfig } from "../configuration/pnplibconfig"; import { TypedHash } from "../collections/collections"; import { BatchParseException } from "../utils/exceptions"; /** * Manages a batch of OData operations */ export class ODataBatch { private _dependencies: Promise<void>[]; private _requests: ODataBatchRequestInfo[]; /** * Parses the response from a batch request into an array of Response instances * * @param body Text body of the response from the batch request */ public static ParseResponse(body: string): Promise<Response[]> { return new Promise((resolve, reject) => { const responses: Response[] = []; const header = "--batchresponse_"; // Ex. "HTTP/1.1 500 Internal Server Error" const statusRegExp = new RegExp("^HTTP/[0-9.]+ +([0-9]+) +(.*)", "i"); const lines = body.split("\n"); let state = "batch"; let status: number; let statusText: string; for (let i = 0; i < lines.length; ++i) { const line = lines[i]; switch (state) { case "batch": if (line.substr(0, header.length) === header) { state = "batchHeaders"; } else { if (line.trim() !== "") { throw new BatchParseException(`Invalid response, line ${i}`); } } break; case "batchHeaders": if (line.trim() === "") { state = "status"; } break; case "status": const parts = statusRegExp.exec(line); if (parts.length !== 3) { throw new BatchParseException(`Invalid status, line ${i}`); } status = parseInt(parts[1], 10); statusText = parts[2]; state = "statusHeaders"; break; case "statusHeaders": if (line.trim() === "") { state = "body"; } break; case "body": responses.push((status === 204) ? new Response() : new Response(line, { status: status, statusText: statusText })); state = "batch"; break; } } if (state !== "status") { reject(new BatchParseException("Unexpected end of input")); } resolve(responses); }); } constructor(private baseUrl: string, private _batchId = Util.getGUID()) { this._requests = []; this._dependencies = []; } public get batchId(): string { return this._batchId; } /** * Adds a request to a batch (not designed for public use) * * @param url The full url of the request * @param method The http method GET, POST, etc * @param options Any options to include in the request * @param parser The parser that will hadle the results of the request */ public add<T>(url: string, method: string, options: any, parser: ODataParser<T>): Promise<T> { const info = { method: method.toUpperCase(), options: options, parser: parser, reject: <(reason?: any) => void>null, resolve: <(value?: T | PromiseLike<T>) => void>null, url: url, }; const p = new Promise<T>((resolve, reject) => { info.resolve = resolve; info.reject = reject; }); this._requests.push(info); return p; } /** * Adds a dependency insuring that some set of actions will occur before a batch is processed. * MUST be cleared using the returned resolve delegate to allow batches to run */ public addDependency(): () => void { let resolver: () => void; const promise = new Promise<void>((resolve) => { resolver = resolve; }); this._dependencies.push(promise); return resolver; } /** * Execute the current batch and resolve the associated promises * * @returns A promise which will be resolved once all of the batch's child promises have resolved */ public execute(): Promise<any> { // we need to check the dependencies twice due to how different engines handle things. // We can get a second set of promises added after the first set resolve return Promise.all(this._dependencies).then(() => Promise.all(this._dependencies)).then(() => this.executeImpl()); } private executeImpl(): Promise<any> { Logger.write(`[${this.batchId}] (${(new Date()).getTime()}) Executing batch with ${this._requests.length} requests.`, LogLevel.Info); // if we don't have any requests, don't bother sending anything // this could be due to caching further upstream, or just an empty batch if (this._requests.length < 1) { Logger.write(`Resolving empty batch.`, LogLevel.Info); return Promise.resolve(); } // creating the client here allows the url to be populated for nodejs client as well as potentially // any other hacks needed for other types of clients. Essentially allows the absoluteRequestUrl // below to be correct const client = new HttpClient(); // due to timing we need to get the absolute url here so we can use it for all the individual requests // and for sending the entire batch return Util.toAbsoluteUrl(this.baseUrl).then(absoluteRequestUrl => { // build all the requests, send them, pipe results in order to parsers const batchBody: string[] = []; let currentChangeSetId = ""; for (let i = 0; i < this._requests.length; i++) { const reqInfo = this._requests[i]; if (reqInfo.method === "GET") { if (currentChangeSetId.length > 0) { // end an existing change set batchBody.push(`--changeset_${currentChangeSetId}--\n\n`); currentChangeSetId = ""; } batchBody.push(`--batch_${this._batchId}\n`); } else { if (currentChangeSetId.length < 1) { // start new change set currentChangeSetId = Util.getGUID(); batchBody.push(`--batch_${this._batchId}\n`); batchBody.push(`Content-Type: multipart/mixed; boundary="changeset_${currentChangeSetId}"\n\n`); } batchBody.push(`--changeset_${currentChangeSetId}\n`); } // common batch part prefix batchBody.push(`Content-Type: application/http\n`); batchBody.push(`Content-Transfer-Encoding: binary\n\n`); const headers = new Headers(); // this is the url of the individual request within the batch const url = Util.isUrlAbsolute(reqInfo.url) ? reqInfo.url : Util.combinePaths(absoluteRequestUrl, reqInfo.url); Logger.write(`[${this.batchId}] (${(new Date()).getTime()}) Adding request ${reqInfo.method} ${url} to batch.`, LogLevel.Verbose); if (reqInfo.method !== "GET") { let method = reqInfo.method; if (reqInfo.hasOwnProperty("options") && reqInfo.options.hasOwnProperty("headers") && typeof reqInfo.options.headers["X-HTTP-Method"] !== "undefined") { method = reqInfo.options.headers["X-HTTP-Method"]; delete reqInfo.options.headers["X-HTTP-Method"]; } batchBody.push(`${method} ${url} HTTP/1.1\n`); headers.set("Content-Type", "application/json;odata=verbose;charset=utf-8"); } else { batchBody.push(`${reqInfo.method} ${url} HTTP/1.1\n`); } // merge global config headers mergeHeaders(headers, RuntimeConfig.spHeaders); // merge per-request headers if (reqInfo.options) { mergeHeaders(headers, reqInfo.options.headers); } // lastly we apply any default headers we need that may not exist if (!headers.has("Accept")) { headers.append("Accept", "application/json"); } if (!headers.has("Content-Type")) { headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8"); } if (!headers.has("X-ClientService-ClientTag")) { headers.append("X-ClientService-ClientTag", "PnPCoreJS:$$Version$$"); } // write headers into batch body headers.forEach((value: string, name: string) => { batchBody.push(`${name}: ${value}\n`); }); batchBody.push("\n"); if (reqInfo.options.body) { batchBody.push(`${reqInfo.options.body}\n\n`); } } if (currentChangeSetId.length > 0) { // Close the changeset batchBody.push(`--changeset_${currentChangeSetId}--\n\n`); currentChangeSetId = ""; } batchBody.push(`--batch_${this._batchId}--\n`); const batchHeaders: TypedHash<string> = { "Content-Type": `multipart/mixed; boundary=batch_${this._batchId}`, }; const batchOptions = { "body": batchBody.join(""), "headers": batchHeaders, "method": "POST", }; Logger.write(`[${this.batchId}] (${(new Date()).getTime()}) Sending batch request.`, LogLevel.Info); return client.fetch(Util.combinePaths(absoluteRequestUrl, "/_api/$batch"), batchOptions) .then(r => r.text()) .then(ODataBatch.ParseResponse) .then((responses: Response[]) => { if (responses.length !== this._requests.length) { throw new BatchParseException("Could not properly parse responses to match requests in batch."); } Logger.write(`[${this.batchId}] (${(new Date()).getTime()}) Resolving batched requests.`, LogLevel.Info); return responses.reduce((chain, response, index) => { const request = this._requests[index]; Logger.write(`[${this.batchId}] (${(new Date()).getTime()}) Resolving batched request ${request.method} ${request.url}.`, LogLevel.Verbose); return chain.then(_ => request.parser.parse(response).then(request.resolve).catch(request.reject)); }, Promise.resolve()); }); }); } } interface ODataBatchRequestInfo { url: string; method: string; options: any; parser: ODataParser<any>; resolve: (d: any) => void; reject: (error: any) => void; }
the_stack
import 'vs/css!./media/mergeEditor'; import './colors'; import { $, Dimension, reset } from 'vs/base/browser/dom'; import { Direction, Grid, IView, SerializableGrid } from 'vs/base/browser/ui/grid/grid'; import { Orientation, Sizing } from 'vs/base/browser/ui/splitview/splitview'; import { IAction } from 'vs/base/common/actions'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Color } from 'vs/base/common/color'; import { BugIndicatingError } from 'vs/base/common/errors'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget'; import { IEditorOptions as ICodeEditorOptions } from 'vs/editor/common/config/editorOptions'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfiguration'; import { localize } from 'vs/nls'; import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, MenuId } from 'vs/platform/actions/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IEditorOptions, ITextEditorOptions } from 'vs/platform/editor/common/editor'; import { IFileService } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ILabelService } from 'vs/platform/label/common/label'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { FloatingClickWidget } from 'vs/workbench/browser/codeeditor'; import { AbstractTextEditor } from 'vs/workbench/browser/parts/editor/textEditor'; import { IEditorOpenContext } from 'vs/workbench/common/editor'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { applyTextEditorOptions } from 'vs/workbench/common/editor/editorOptions'; import { autorunWithStore } from 'vs/workbench/contrib/audioCues/browser/observable'; import { MergeEditorInput } from 'vs/workbench/contrib/mergeEditor/browser/mergeEditorInput'; import { MergeEditorModel } from 'vs/workbench/contrib/mergeEditor/browser/model/mergeEditorModel'; import { DocumentMapping, getOppositeDirection, MappingDirection } from 'vs/workbench/contrib/mergeEditor/browser/model/mapping'; import { ReentrancyBarrier } from 'vs/workbench/contrib/mergeEditor/browser/utils'; import { settingsSashBorder } from 'vs/workbench/contrib/preferences/common/settingsEditorColorRegistry'; import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { InputCodeEditorView, ResultCodeEditorView } from './codeEditorView'; export const ctxIsMergeEditor = new RawContextKey<boolean>('isMergeEditor', false); export const ctxUsesColumnLayout = new RawContextKey<boolean>('mergeEditorUsesColumnLayout', false); export const ctxBaseResourceScheme = new RawContextKey<string>('baseResourceScheme', ''); export class MergeEditor extends AbstractTextEditor<any> { static readonly ID = 'mergeEditor'; private readonly _sessionDisposables = new DisposableStore(); private _grid!: Grid<IView>; private readonly input1View = this.instantiation.createInstance(InputCodeEditorView, 1, { readonly: !this.inputsWritable }); private readonly input2View = this.instantiation.createInstance(InputCodeEditorView, 2, { readonly: !this.inputsWritable }); private readonly inputResultView = this.instantiation.createInstance(ResultCodeEditorView, { readonly: false }); private readonly _ctxIsMergeEditor: IContextKey<boolean>; private readonly _ctxUsesColumnLayout: IContextKey<boolean>; private readonly _ctxBaseResourceScheme: IContextKey<string>; private _model: MergeEditorModel | undefined; public get model(): MergeEditorModel | undefined { return this._model; } private get inputsWritable(): boolean { return !!this._configurationService.getValue<boolean>('mergeEditor.writableInputs'); } constructor( @IInstantiationService private readonly instantiation: IInstantiationService, @ILabelService private readonly _labelService: ILabelService, @IMenuService private readonly _menuService: IMenuService, @IContextKeyService private readonly _contextKeyService: IContextKeyService, @ITelemetryService telemetryService: ITelemetryService, @IStorageService storageService: IStorageService, @IThemeService themeService: IThemeService, @ITextResourceConfigurationService textResourceConfigurationService: ITextResourceConfigurationService, @IConfigurationService private readonly _configurationService: IConfigurationService, @IEditorService editorService: IEditorService, @IEditorGroupsService editorGroupService: IEditorGroupsService, @IFileService fileService: IFileService ) { super(MergeEditor.ID, telemetryService, instantiation, storageService, textResourceConfigurationService, themeService, editorService, editorGroupService, fileService); this._ctxIsMergeEditor = ctxIsMergeEditor.bindTo(_contextKeyService); this._ctxUsesColumnLayout = ctxUsesColumnLayout.bindTo(_contextKeyService); this._ctxBaseResourceScheme = ctxBaseResourceScheme.bindTo(_contextKeyService); const reentrancyBarrier = new ReentrancyBarrier(); this._store.add( this.input1View.editor.onDidScrollChange( reentrancyBarrier.makeExclusive((c) => { if (c.scrollTopChanged) { const mapping = this.model?.input1ResultMapping.get(); synchronizeScrolling(this.input1View.editor, this.inputResultView.editor, mapping, MappingDirection.input); this.input2View.editor.setScrollTop(c.scrollTop, ScrollType.Immediate); } }) ) ); this._store.add( this.input2View.editor.onDidScrollChange( reentrancyBarrier.makeExclusive((c) => { if (c.scrollTopChanged) { const mapping = this.model?.input2ResultMapping.get(); synchronizeScrolling(this.input2View.editor, this.inputResultView.editor, mapping, MappingDirection.input); this.input1View.editor.setScrollTop(c.scrollTop, ScrollType.Immediate); } }) ) ); this._store.add( this.inputResultView.editor.onDidScrollChange( reentrancyBarrier.makeExclusive((c) => { if (c.scrollTopChanged) { const mapping1 = this.model?.input1ResultMapping.get(); synchronizeScrolling(this.inputResultView.editor, this.input1View.editor, mapping1, MappingDirection.output); const mapping2 = this.model?.input2ResultMapping.get(); synchronizeScrolling(this.inputResultView.editor, this.input2View.editor, mapping2, MappingDirection.output); } }) ) ); // TODO@jrieken make this proper: add menu id and allow extensions to contribute const toolbarMenu = this._menuService.createMenu(MenuId.MergeToolbar, this._contextKeyService); const toolbarMenuDisposables = new DisposableStore(); const toolbarMenuRender = () => { toolbarMenuDisposables.clear(); const actions: IAction[] = []; createAndFillInActionBarActions(toolbarMenu, { renderShortTitle: true, shouldForwardArgs: true }, actions); if (actions.length > 0) { const [first] = actions; const acceptBtn = this.instantiation.createInstance(FloatingClickWidget, this.inputResultView.editor, first.label, first.id); toolbarMenuDisposables.add(acceptBtn.onClick(() => first.run(this.inputResultView.editor.getModel()?.uri))); toolbarMenuDisposables.add(acceptBtn); acceptBtn.render(); } }; this._store.add(toolbarMenu); this._store.add(toolbarMenuDisposables); this._store.add(toolbarMenu.onDidChange(toolbarMenuRender)); toolbarMenuRender(); } override dispose(): void { this._sessionDisposables.dispose(); this._ctxIsMergeEditor.reset(); super.dispose(); } override getTitle(): string { if (this.input) { return this.input.getName(); } return localize('mergeEditor', "Text Merge Editor"); } protected createEditorControl(parent: HTMLElement, initialOptions: ICodeEditorOptions): void { parent.classList.add('merge-editor'); this._grid = SerializableGrid.from<any /*TODO@jrieken*/>({ orientation: Orientation.VERTICAL, size: 100, groups: [ { size: 38, groups: [{ data: this.input1View.view }, { data: this.input2View.view }] }, { size: 62, data: this.inputResultView.view }, ] }, { styles: { separatorBorder: this.theme.getColor(settingsSashBorder) ?? Color.transparent }, proportionalLayout: true }); reset(parent, this._grid.element); this._ctxUsesColumnLayout.set(false); this.applyOptions(initialOptions); } protected updateEditorControlOptions(options: ICodeEditorOptions): void { this.applyOptions(options); } private applyOptions(options: ICodeEditorOptions): void { this.input1View.editor.updateOptions({ ...options, readOnly: !this.inputsWritable }); this.input2View.editor.updateOptions({ ...options, readOnly: !this.inputsWritable }); this.inputResultView.editor.updateOptions(options); } protected getMainControl(): ICodeEditor | undefined { return this.inputResultView.editor; } layout(dimension: Dimension): void { this._grid.layout(dimension.width, dimension.height); } override async setInput(input: EditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> { if (!(input instanceof MergeEditorInput)) { throw new BugIndicatingError('ONLY MergeEditorInput is supported'); } await super.setInput(input, options, context, token); this._sessionDisposables.clear(); const model = await input.resolve(); this._model = model; this.input1View.setModel(model, model.input1, localize('yours', 'Yours'), model.input1Detail, model.input1Description); this.input2View.setModel(model, model.input2, localize('theirs', 'Theirs',), model.input2Detail, model.input2Description); this.inputResultView.setModel(model, model.result, localize('result', 'Result',), this._labelService.getUriLabel(model.result.uri, { relative: true }), undefined); this._ctxBaseResourceScheme.set(model.base.uri.scheme); this._sessionDisposables.add(autorunWithStore((reader, store) => { const input1ViewZoneIds: string[] = []; const input2ViewZoneIds: string[] = []; for (const m of model.modifiedBaseRanges.read(reader)) { const max = Math.max(m.input1Range.lineCount, m.input2Range.lineCount, 1); this.input1View.editor.changeViewZones(a => { input1ViewZoneIds.push(a.addZone({ afterLineNumber: m.input1Range.endLineNumberExclusive - 1, heightInLines: max - m.input1Range.lineCount, domNode: $('div.diagonal-fill'), })); }); this.input2View.editor.changeViewZones(a => { input2ViewZoneIds.push(a.addZone({ afterLineNumber: m.input2Range.endLineNumberExclusive - 1, heightInLines: max - m.input2Range.lineCount, domNode: $('div.diagonal-fill'), })); }); } store.add({ dispose: () => { this.input1View.editor.changeViewZones(a => { for (const zone of input1ViewZoneIds) { a.removeZone(zone); } }); this.input2View.editor.changeViewZones(a => { for (const zone of input2ViewZoneIds) { a.removeZone(zone); } }); } }); }, 'update alignment view zones')); } override setOptions(options: ITextEditorOptions | undefined): void { super.setOptions(options); if (options) { applyTextEditorOptions(options, this.inputResultView.editor, ScrollType.Smooth); } } override clearInput(): void { super.clearInput(); this._sessionDisposables.clear(); for (const { editor } of [this.input1View, this.input2View, this.inputResultView]) { editor.setModel(null); } } override focus(): void { (this.getControl() ?? this.inputResultView.editor).focus(); } override hasFocus(): boolean { for (const { editor } of [this.input1View, this.input2View, this.inputResultView]) { if (editor.hasTextFocus()) { return true; } } return super.hasFocus(); } protected override setEditorVisible(visible: boolean, group: IEditorGroup | undefined): void { super.setEditorVisible(visible, group); for (const { editor } of [this.input1View, this.input2View, this.inputResultView]) { if (visible) { editor.onVisible(); } else { editor.onHide(); } } this._ctxIsMergeEditor.set(visible); } // ---- interact with "outside world" via `getControl`, `scopedContextKeyService` override getControl(): ICodeEditor | undefined { for (const { editor } of [this.input1View, this.input2View, this.inputResultView]) { if (editor.hasWidgetFocus()) { return editor; } } return undefined; } override get scopedContextKeyService(): IContextKeyService | undefined { const control = this.getControl(); return isCodeEditor(control) ? control.invokeWithinContext(accessor => accessor.get(IContextKeyService)) : undefined; } // --- layout private _usesColumnLayout = false; toggleLayout(): void { if (!this._usesColumnLayout) { this._grid.moveView(this.inputResultView.view, Sizing.Distribute, this.input1View.view, Direction.Right); } else { this._grid.moveView(this.inputResultView.view, this._grid.height * .62, this.input1View.view, Direction.Down); this._grid.moveView(this.input2View.view, Sizing.Distribute, this.input1View.view, Direction.Right); } this._usesColumnLayout = !this._usesColumnLayout; this._ctxUsesColumnLayout.set(this._usesColumnLayout); } // --- view state (TODO@bpasero revisit with https://github.com/microsoft/vscode/issues/150804) protected computeEditorViewState(resource: URI): undefined { return undefined; } protected tracksEditorViewState(input: EditorInput): boolean { return false; } } function synchronizeScrolling(scrollingEditor: CodeEditorWidget, targetEditor: CodeEditorWidget, mapping: DocumentMapping | undefined, source: MappingDirection) { if (!mapping) { return; } const visibleRanges = scrollingEditor.getVisibleRanges(); if (visibleRanges.length === 0) { return; } const topLineNumber = visibleRanges[0].startLineNumber - 1; const result = mapping.getMappingContaining(topLineNumber, source); const sourceRange = result.getRange(source); const targetRange = result.getRange(getOppositeDirection(source)); const resultStartTopPx = targetEditor.getTopForLineNumber(targetRange.startLineNumber); const resultEndPx = targetEditor.getTopForLineNumber(targetRange.endLineNumberExclusive); const sourceStartTopPx = scrollingEditor.getTopForLineNumber(sourceRange.startLineNumber); const sourceEndPx = scrollingEditor.getTopForLineNumber(sourceRange.endLineNumberExclusive); const factor = Math.min((scrollingEditor.getScrollTop() - sourceStartTopPx) / (sourceEndPx - sourceStartTopPx), 1); const resultScrollPosition = resultStartTopPx + (resultEndPx - resultStartTopPx) * factor; targetEditor.setScrollTop(resultScrollPosition, ScrollType.Immediate); }
the_stack
import type { CompilerFileWatcherCallback, CompilerFsStats, CompilerSystem, CompilerSystemCreateDirectoryOptions, CompilerSystemCreateDirectoryResults, CompilerSystemRealpathResults, CompilerSystemRemoveDirectoryOptions, CompilerSystemRemoveDirectoryResults, CompilerSystemRemoveFileResults, CompilerSystemRenameResults, CompilerSystemWriteFileResults, CopyResults, CopyTask, Logger, } from '../../declarations'; import platformPath from 'path-browserify'; import { basename, dirname, join } from 'path'; import * as process from 'process'; import * as os from 'os'; import { buildEvents } from '../events'; import { createLogger } from './logger/console-logger'; import { createWebWorkerMainController } from './worker/web-worker-main'; import { HAS_WEB_WORKER, IS_BROWSER_ENV, IS_WEB_WORKER_ENV } from './environment'; import { isRootPath, normalizePath } from '@utils'; import { resolveModuleIdAsync } from './resolve/resolve-module-async'; import { version } from '../../version'; export const createSystem = (c?: { logger?: Logger }) => { const logger = c && c.logger ? c.logger : createLogger(); const items = new Map<string, FsItem>(); const destroys = new Set<() => Promise<void> | void>(); const addDestory = (cb: () => void) => destroys.add(cb); const removeDestory = (cb: () => void) => destroys.delete(cb); const events = buildEvents(); const hardwareConcurrency = (IS_BROWSER_ENV && navigator.hardwareConcurrency) || 1; const destroy = async () => { const waits: Promise<void>[] = []; destroys.forEach((cb) => { try { const rtn = cb(); if (rtn && rtn.then) { waits.push(rtn); } } catch (e) { logger.error(`stencil sys destroy: ${e}`); } }); await Promise.all(waits); destroys.clear(); }; const normalize = (p: string) => { if (p === '/' || p === '') { return '/'; } const dir = dirname(p); const base = basename(p); if (dir.endsWith('/')) { return normalizePath(`${dir}${base}`); } return normalizePath(`${dir}/${base}`); }; const accessSync = (p: string) => { const item = items.get(normalize(p)); return !!(item && (item.isDirectory || (item.isFile && typeof item.data === 'string'))); }; const access = async (p: string) => accessSync(p); const copyFile = async (src: string, dest: string) => { writeFileSync(dest, readFileSync(src)); return true; }; const isTTY = (): boolean => { return !!process?.stdout?.isTTY; }; const homeDir = () => { return os.homedir(); }; const createDirSync = (p: string, opts?: CompilerSystemCreateDirectoryOptions) => { p = normalize(p); const results: CompilerSystemCreateDirectoryResults = { basename: basename(p), dirname: dirname(p), path: p, newDirs: [], error: null, }; createDirRecursiveSync(p, opts, results); return results; }; const createDirRecursiveSync = ( p: string, opts: CompilerSystemCreateDirectoryOptions, results: CompilerSystemCreateDirectoryResults ) => { const parentDir = dirname(p); if (opts && opts.recursive && !isRootPath(parentDir)) { createDirRecursiveSync(parentDir, opts, results); } const item = items.get(p); if (!item) { items.set(p, { basename: basename(p), dirname: parentDir, isDirectory: true, isFile: false, watcherCallbacks: null, data: undefined, }); results.newDirs.push(p); emitDirectoryWatch(p, new Set()); } else { item.isDirectory = true; item.isFile = false; } }; const createDir = async (p: string, opts?: CompilerSystemCreateDirectoryOptions) => createDirSync(p, opts); const encodeToBase64 = (str: string) => btoa(unescape(encodeURIComponent(str))); const getCurrentDirectory = () => '/'; const getCompilerExecutingPath = () => { if (IS_WEB_WORKER_ENV) { return location.href; } return sys.getRemoteModuleUrl({ moduleId: '@stencil/core', path: 'compiler/stencil.min.js' }); }; const isSymbolicLink = async (_p: string) => false; const readDirSync = (p: string) => { p = normalize(p); const dirItems: string[] = []; const dir = items.get(p); if (dir && dir.isDirectory) { items.forEach((item, itemPath) => { if (itemPath !== '/' && (item.isDirectory || (item.isFile && typeof item.data === 'string'))) { if (p.endsWith('/') && `${p}${item.basename}` === itemPath) { dirItems.push(itemPath); } else if (`${p}/${item.basename}` === itemPath) { dirItems.push(itemPath); } } }); } return dirItems.sort(); }; const readDir = async (p: string) => readDirSync(p); const readFileSync = (p: string) => { p = normalize(p); const item = items.get(p); if (item && item.isFile) { return item.data; } return undefined; }; const readFile = async (p: string) => readFileSync(p); const realpathSync = (p: string) => { const results: CompilerSystemRealpathResults = { path: normalize(p), error: null, }; return results; }; const realpath = async (p: string) => realpathSync(p); const rename = async (oldPath: string, newPath: string) => { oldPath = normalizePath(oldPath); newPath = normalizePath(newPath); const results: CompilerSystemRenameResults = { oldPath, newPath, renamed: [], oldDirs: [], oldFiles: [], newDirs: [], newFiles: [], isFile: false, isDirectory: false, error: null, }; const stats = statSync(oldPath); if (!stats.error) { if (stats.isFile) { results.isFile = true; } else if (stats.isDirectory) { results.isDirectory = true; } renameNewRecursiveSync(oldPath, newPath, results); if (!results.error) { if (results.isDirectory) { const rmdirResults = removeDirSync(oldPath, { recursive: true }); if (rmdirResults.error) { results.error = rmdirResults.error; } else { results.oldDirs.push(...rmdirResults.removedDirs); results.oldFiles.push(...rmdirResults.removedFiles); } } else if (results.isFile) { const removeFileResults = removeFileSync(oldPath); if (removeFileResults.error) { results.error = removeFileResults.error; } else { results.oldFiles.push(oldPath); } } } } else { results.error = `${oldPath} does not exist`; } return results; }; const renameNewRecursiveSync = (oldPath: string, newPath: string, results: CompilerSystemRenameResults) => { const itemStat = statSync(oldPath); if (!itemStat.error && !results.error) { if (itemStat.isFile) { const newFileParentDir = dirname(newPath); const createDirResults = createDirSync(newFileParentDir, { recursive: true }); const fileContent = items.get(oldPath).data; const writeResults = writeFileSync(newPath, fileContent); results.newDirs.push(...createDirResults.newDirs); results.renamed.push({ oldPath, newPath, isDirectory: false, isFile: true, }); if (writeResults.error) { results.error = writeResults.error; } else { results.newFiles.push(newPath); } } else if (itemStat.isDirectory) { const oldDirItemChildPaths = readDirSync(oldPath); const createDirResults = createDirSync(newPath, { recursive: true }); results.newDirs.push(...createDirResults.newDirs); results.renamed.push({ oldPath, newPath, isDirectory: true, isFile: false, }); for (const oldDirItemChildPath of oldDirItemChildPaths) { const newDirItemChildPath = oldDirItemChildPath.replace(oldPath, newPath); renameNewRecursiveSync(oldDirItemChildPath, newDirItemChildPath, results); } } } }; const resolvePath = (p: string) => normalize(p); const removeDirSync = (p: string, opts: CompilerSystemRemoveDirectoryOptions = {}) => { const results: CompilerSystemRemoveDirectoryResults = { basename: basename(p), dirname: dirname(p), path: p, removedDirs: [], removedFiles: [], error: null, }; remoreDirSyncRecursive(p, opts, results); return results; }; const remoreDirSyncRecursive = ( p: string, opts: CompilerSystemRemoveDirectoryOptions, results: CompilerSystemRemoveDirectoryResults ) => { if (!results.error) { p = normalize(p); const dirItemPaths = readDirSync(p); if (opts && opts.recursive) { for (const dirItemPath of dirItemPaths) { const item = items.get(dirItemPath); if (item) { if (item.isDirectory) { remoreDirSyncRecursive(dirItemPath, opts, results); } else if (item.isFile) { const removeFileResults = removeFileSync(dirItemPath); if (removeFileResults.error) { results.error = removeFileResults.error; } else { results.removedFiles.push(dirItemPath); } } } } } else { if (dirItemPaths.length > 0) { results.error = `cannot delete directory that contains files/subdirectories`; return; } } items.delete(p); emitDirectoryWatch(p, new Set()); results.removedDirs.push(p); } }; const removeDir = async (p: string, opts: CompilerSystemRemoveDirectoryOptions = {}) => removeDirSync(p, opts); const statSync = (p: string): CompilerFsStats => { p = normalize(p); const item = items.get(p); if (item && (item.isDirectory || (item.isFile && typeof item.data === 'string'))) { return { isDirectory: item.isDirectory, isFile: item.isFile, isSymbolicLink: false, size: item.isFile && item.data ? item.data.length : 0, error: null, }; } return { isDirectory: false, isFile: false, isSymbolicLink: false, size: 0, error: `ENOENT: no such file or directory, statSync '${p}'`, }; }; const stat = async (p: string) => statSync(p); const removeFileSync = (p: string) => { p = normalize(p); const results: CompilerSystemRemoveFileResults = { basename: basename(p), dirname: dirname(p), path: p, error: null, }; const item = items.get(p); if (item) { if (item.watcherCallbacks) { for (const watcherCallback of item.watcherCallbacks) { watcherCallback(p, 'fileDelete'); } } items.delete(p); emitDirectoryWatch(p, new Set()); } return results; }; const removeFile = async (p: string) => removeFileSync(p); const watchDirectory = (p: string, dirWatcherCallback: CompilerFileWatcherCallback) => { p = normalize(p); const item = items.get(p); const close = () => { const closeItem = items.get(p); if (closeItem && closeItem.watcherCallbacks) { const index = closeItem.watcherCallbacks.indexOf(dirWatcherCallback); if (index > -1) { closeItem.watcherCallbacks.splice(index, 1); } } }; addDestory(close); if (item) { item.isDirectory = true; item.isFile = false; item.watcherCallbacks = item.watcherCallbacks || []; item.watcherCallbacks.push(dirWatcherCallback); } else { items.set(p, { basename: basename(p), dirname: dirname(p), isDirectory: true, isFile: false, watcherCallbacks: [dirWatcherCallback], data: undefined, }); } return { close() { removeDestory(close); close(); }, }; }; const watchFile = (p: string, fileWatcherCallback: CompilerFileWatcherCallback) => { p = normalize(p); const item = items.get(p); const close = () => { const closeItem = items.get(p); if (closeItem && closeItem.watcherCallbacks) { const index = closeItem.watcherCallbacks.indexOf(fileWatcherCallback); if (index > -1) { closeItem.watcherCallbacks.splice(index, 1); } } }; addDestory(close); if (item) { item.isDirectory = false; item.isFile = true; item.watcherCallbacks = item.watcherCallbacks || []; item.watcherCallbacks.push(fileWatcherCallback); } else { items.set(p, { basename: basename(p), dirname: dirname(p), isDirectory: false, isFile: true, watcherCallbacks: [fileWatcherCallback], data: undefined, }); } return { close() { removeDestory(close); close(); }, }; }; const emitDirectoryWatch = (p: string, emitted: Set<string>) => { const parentDir = normalize(dirname(p)); const dirItem = items.get(parentDir); if (dirItem && dirItem.isDirectory && dirItem.watcherCallbacks) { for (const watcherCallback of dirItem.watcherCallbacks) { watcherCallback(p, null); } } if (!emitted.has(parentDir)) { emitted.add(parentDir); emitDirectoryWatch(parentDir, emitted); } }; const writeFileSync = (p: string, data: string) => { p = normalize(p); const results: CompilerSystemWriteFileResults = { path: p, error: null, }; const item = items.get(p); if (item) { const hasChanged = item.data !== data; item.data = data; if (hasChanged && item.watcherCallbacks) { for (const watcherCallback of item.watcherCallbacks) { watcherCallback(p, 'fileUpdate'); } } } else { items.set(p, { basename: basename(p), dirname: dirname(p), isDirectory: false, isFile: true, watcherCallbacks: null, data, }); emitDirectoryWatch(p, new Set()); } return results; }; /** * `self` is the global namespace object used within a web worker. * `window` is the browser's global namespace object (I reorganized this to check the reference on that second) * `global` is Node's global namespace object. https://nodejs.org/api/globals.html#globals_global * * loading in this order should allow workers, which are most common, then browser, * then Node to grab the reference to fetch correctly. */ const fetch = typeof self !== 'undefined' ? self?.fetch : typeof window !== 'undefined' ? window?.fetch : typeof global !== 'undefined' ? global?.fetch : undefined; const writeFile = async (p: string, data: string) => writeFileSync(p, data); const tmpDirSync = () => '/.tmp'; const tick = Promise.resolve(); const nextTick = (cb: () => void) => tick.then(cb); const generateContentHash = async (content: string, hashLength: number) => { const arrayBuffer = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(content)); const hashArray = Array.from(new Uint8Array(arrayBuffer)); // convert buffer to byte array let hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string if (typeof hashLength === 'number') { hashHex = hashHex.substr(0, hashLength); } return hashHex; }; const copy = async (copyTasks: Required<CopyTask>[], srcDir: string) => { const results: CopyResults = { diagnostics: [], dirPaths: [], filePaths: [], }; logger.info('todo, copy task', copyTasks.length, srcDir); return results; }; const getEnvironmentVar = (key: string) => { return process?.env[key]; }; const getLocalModulePath = (opts: { rootDir: string; moduleId: string; path: string }) => join(opts.rootDir, 'node_modules', opts.moduleId, opts.path); const getRemoteModuleUrl = (opts: { moduleId: string; path: string; version?: string }) => { const npmBaseUrl = 'https://cdn.jsdelivr.net/npm/'; const path = `${opts.moduleId}${opts.version ? '@' + opts.version : ''}/${opts.path}`; return new URL(path, npmBaseUrl).href; }; const fileWatchTimeout = 32; createDirSync('/'); const sys: CompilerSystem = { name: 'in-memory', version, events, access, accessSync, addDestory, copyFile, createDir, createDirSync, homeDir, isTTY, getEnvironmentVar, destroy, encodeToBase64, exit: async (exitCode) => logger.warn(`exit ${exitCode}`), getCurrentDirectory, getCompilerExecutingPath, getLocalModulePath, getRemoteModuleUrl, hardwareConcurrency, isSymbolicLink, nextTick, normalizePath: normalize, platformPath, readDir, readDirSync, readFile, readFileSync, realpath, realpathSync, removeDestory, rename, fetch, resolvePath, removeDir, removeDirSync, stat, statSync, tmpDirSync, removeFile, removeFileSync, watchDirectory, watchFile, watchTimeout: fileWatchTimeout, writeFile, writeFileSync, generateContentHash, createWorkerController: HAS_WEB_WORKER ? (maxConcurrentWorkers) => createWebWorkerMainController(sys, maxConcurrentWorkers) : null, details: { cpuModel: '', freemem: () => 0, platform: '', release: '', totalmem: 0, }, copy, }; sys.resolveModuleId = (opts) => resolveModuleIdAsync(sys, null, opts); return sys; }; interface FsItem { data: string; basename: string; dirname: string; isFile: boolean; isDirectory: boolean; watcherCallbacks: CompilerFileWatcherCallback[]; }
the_stack
module LightSpeed { export class BaseEnemy { public value: number; public health: number; public maxHealth: number; public baseHealth: number; public healthIncrease: number; public enemyPointsMesh: BABYLON.Mesh; public damageAmount: number; public speed: number; public canRespawn: boolean; public size: number; public refreshtime: number; public lastupdate: number; public enemyMesh: BABYLON.AbstractMesh; public enemyPointsTexture: BABYLON.DynamicTexture; public enemyBullet: Array<any>; public enemyexplosion: BABYLON.ParticleSystem; public radar: BABYLON.Mesh; public toX: number; public toY: number; public toZ: number; public rotation: number; public setup() { return null; } public behavior() { return null; } public init() { return null; } constructor(public name: string, public level: number) { // after recopy all propreties call init(); if (this.init != null) this.init(); if (!this.enemyBullet) this.enemyBullet = []; this.value += level; this.health = this.baseHealth + (this.level * this.healthIncrease); this.maxHealth = this.baseHealth + (this.level * this.healthIncrease); this.enemyPointsMesh = BABYLON.Mesh.CreatePlane("enemyPoints", 20, scene); this.enemyPointsMesh.rotation.y = Math.PI; this.enemyPointsMesh.rotation.x = Math.PI / 2; this.enemyPointsMesh.rotation.z = Math.PI * 1.5; this.enemyPointsMesh.position.x = 10000; this.enemyPointsMesh.position.z = 10000; var enemyPointsMaterial = new BABYLON.StandardMaterial("background", scene); this.enemyPointsTexture = new BABYLON.DynamicTexture("dynamic texture", 512, scene, true); enemyPointsMaterial.diffuseTexture = this.enemyPointsTexture; this.enemyPointsMesh.material = enemyPointsMaterial; this.enemyPointsTexture.drawText("+" + this.value, null, 350, "bold 285px Arial", "white", "#555555"); this.enemyexplosion = new BABYLON.ParticleSystem("enemyexplosion", 250, scene); this.enemyexplosion.particleTexture = new BABYLON.Texture("images/Flare.png", scene); this.enemyexplosion.emitter = this.enemyPointsMesh; // the starting object, the emitter this.enemyexplosion.minEmitBox = new BABYLON.Vector3(-1, 0, -1); // Starting all From this.enemyexplosion.maxEmitBox = new BABYLON.Vector3(1, 0, 1); // To... this.enemyexplosion.color1 = new BABYLON.Color4(0.7, 0.7, .3, 1.0); this.enemyexplosion.color2 = new BABYLON.Color4(0.5, 0.5, .3, 1.0); this.enemyexplosion.colorDead = new BABYLON.Color4(0.5, 0.5, 0.3, 1.0); this.enemyexplosion.minSize = 2.0; this.enemyexplosion.maxSize = 5.5; this.enemyexplosion.minLifeTime = .15; this.enemyexplosion.maxLifeTime = .250; this.enemyexplosion.emitRate = 1000; this.enemyexplosion.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE; this.enemyexplosion.direction1 = new BABYLON.Vector3(-8, -8, 0); this.enemyexplosion.direction2 = new BABYLON.Vector3(8, 8, 0); this.enemyexplosion.minAngularSpeed = 0; this.enemyexplosion.maxAngularSpeed = Math.PI; this.enemyexplosion.targetStopDuration = .1; this.enemyexplosion.minEmitPower = 60; this.enemyexplosion.maxEmitPower = 75; this.enemyexplosion.updateSpeed = 0.005; this.enemyexplosion.disposeOnStop = false; // Setup will place the enemy at the correct position; if (this.setup != null) this.setup(); } public update() { this.behavior(); if (this.health <= 0) { this.explode(); } } public respawn(lvl?: number) { if (lvl == null) this.level += 1; else this.level = lvl; this.maxHealth = (this.baseHealth + (this.level * this.healthIncrease)); this.health = (this.baseHealth + (this.level * this.healthIncrease)); this.damageAmount = this.damageAmount + this.level; this.enemyMesh.setEnabled(true); this.enemyMesh.isVisible = true; this.setup(); } public getDamage(dmg: number) { GameSound.play("hit"); this.health -= dmg; if (this.health <= 0) { this.explode(); } } public explode() { GameSound.play("explode"); var spriteManager = new BABYLON.SpriteManager("playerManagr", "images/ExplosionAnimationClear2.png", 1, 150, scene); var fire = new BABYLON.Sprite("player", spriteManager); fire.disposeWhenFinishedAnimating = true; fire.size = 75; fire.position.z = this.enemyMesh.position.z; fire.position.x = this.enemyMesh.position.x; fire.position.y = 1; fire.playAnimation(0, 10, false, 70); playerShip.addResources(this.value); this.enemyMesh.animations = []; this.enemyMesh.setEnabled(false); this.enemyMesh.isVisible = false; this.enemyPointsMesh.position.x = this.enemyMesh.position.x; this.enemyPointsMesh.position.z = this.enemyMesh.position.z; this.enemyexplosion.start(); var animationBox3 = new BABYLON.Animation("xpmessage1", "material.alpha", 40, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE); var keys = []; keys.push({ frame: 0, value: 1.0 }); keys.push({ frame: 50, value: .5 }); keys.push({ frame: 100, value: .0 }); animationBox3.setKeys(keys); this.enemyPointsMesh.animations.push(animationBox3); var animationBox4 = new BABYLON.Animation("xpmessage2", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE); var keys = []; keys.push({ frame: 0, value: .0 }); keys.push({ frame: 50, value: -100 }); keys.push({ frame: 100, value: -200 }); animationBox4.setKeys(keys); this.enemyPointsMesh.animations.push(animationBox4); scene.beginAnimation(this.enemyPointsMesh, 0, 100, false); } public dispose() { this.enemyMesh.animations = []; this.enemyPointsTexture.dispose(); this.enemyexplosion.dispose(); this.enemyPointsMesh.animations = []; this.enemyPointsMesh.material.dispose(); this.enemyPointsMesh.dispose(); var totalB = this.enemyBullet.length; while (totalB--) { this.enemyBullet[totalB].graphic.dispose(); this.enemyBullet.splice(totalB, 1); } this.enemyMesh.dispose(); } public static SpawnOutside() { var rando = Math.round(Math.random() * 1); var x = ((Math.random() * 1500) - 750); var z = ((Math.random() * 1500) - 750); if (rando == 1) { if (x > 0) { x = height + 100; } else { x = -height - 100; } } else { if (z > 0) { z = width + 100; } else { z = -width - 100; } } return { 'x': x, 'z': z }; } public static SpawnInsideEdge() { var rando = Math.round(Math.random() * 1); var x = ((Math.random() * 1500) - 750); var z = ((Math.random() * 1500) - 750); if (rando == 1) { if (x > 0) { x = height - 100; } else { x = -height + 100; } } else { if (z > 0) { z = width - 100; } else { z = -width + 100; } } return { 'x': x, 'z': z }; } public static SpawnInside() { var x = ((Math.random() * 1500) - 750); var z = ((Math.random() * 1500) - 750); return { 'x': x, 'z': z }; } public static SpawnEnemies(level: number) { // get levels var levels = LightSpeed.BaseEnemy.GetLevels(); // get current level details var lvlDetails = levels.filter((value) => { return value.level == level; }); // just check if exists while (lvlDetails.length == 0) { level--; lvlDetails = levels.filter((value) => { return value.level == level; }); } var enemies = new Array<LightSpeed.BaseEnemy>(); // get all types in levels var typeAmount = lvlDetails[0].types.length; while (typeAmount--) { // enemies count var totalItems = lvlDetails[0].types[typeAmount].total; // enemy type var typeItem = lvlDetails[0].types[typeAmount].enemyType; while (totalItems--) { switch (typeItem) { case 0: enemies.push(new RockEnemy('rock_' + totalItems.toString(), level)); break; case 1: enemies.push(new MineEnemy('mine_' + totalItems.toString(), level)); break; case 2: enemies.push(new Rock2Enemy('rock2_' + totalItems.toString(), level)); break; case 3: enemies.push(new SpaceShipEnemy('spaceShip_' + totalItems.toString(), level)); break; case 4: enemies.push(new StaticMineEnemy('staticMine_' + totalItems.toString(), level)); break; } } } return enemies; } public static GetLevels() { var levels = [ { level: 0, types: [ { enemyType: 0, total: 10 }, { enemyType: 1, total: 10 }, { enemyType: 2, total: 10 }, { enemyType: 3, total: 1 }, { enemyType: 4, total: 5 } ] }, { level: 2, types: [ { enemyType: 0, total: 15 }, { enemyType: 1, total: 15 }, { enemyType: 2, total: 15 }, { enemyType: 3, total: 2 }, { enemyType: 4, total: 10 } ] }, { level: 4, types: [ { enemyType: 0, total: 100 }, { enemyType: 4, total: 20 }, { enemyType: 2, total: 100 }, { enemyType: 3, total: 20 } ] }, { level: 10, types: [ { enemyType: 0, total: 150 }, { enemyType: 4, total: 40 }, { enemyType: 2, total: 150 }, { enemyType: 3, total: 40 } ] }, { level: 50, types: [ { enemyType: 0, total: 250 }, { enemyType: 4, total: 60 }, { enemyType: 2, total: 250 }, { enemyType: 3, total: 60 } ] } ]; return levels; } } export class RockEnemy extends BaseEnemy { constructor(name: string, lvl: number) { this.baseHealth = 25; this.healthIncrease = 20; this.speed = 1.5; this.canRespawn = true; this.value = 5; this.size = 10; this.refreshtime = .30; this.lastupdate = 0; // call base constructor super(name, lvl); } public init() { this.enemyBullet = []; this.enemyMesh = rock.clone("rock", null); var m = Math.random(); var z = this.size; var actsize = m * z + 20; ///min size is 15 this.enemyMesh.scaling.x = actsize; this.enemyMesh.scaling.y = actsize; this.enemyMesh.scaling.z = actsize; this.speed = (Math.random() * this.speed) + .1; } public setup() { var loc = LightSpeed.BaseEnemy.SpawnOutside(); this.enemyMesh.position.x = loc.x; this.enemyMesh.position.z = loc.z; loc = LightSpeed.BaseEnemy.SpawnOutside(); this.toX = loc.x; this.toZ = loc.z; this.rotation = Math.random() * .02; } public behavior() { var dx = this.toX - this.enemyMesh.position.x; var dy = this.toZ - this.enemyMesh.position.z; if (dx < 5 && dy < 5) { this.setup(); } var direction = Math.atan2(dy, dx); this.enemyMesh.rotation.z += this.rotation * adjmovement; this.enemyMesh.rotation.x += this.rotation * adjmovement; this.enemyMesh.rotation.y += this.rotation * adjmovement; this.enemyMesh.position.x += Math.cos(direction) * (this.speed * adjmovement); this.enemyMesh.position.z += Math.sin(direction) * (this.speed * adjmovement); } } export class MineEnemy extends BaseEnemy { constructor(name: string, lvl: number) { this.baseHealth = 25; this.healthIncrease = 20; this.speed = .75; this.canRespawn = true; this.value = 5; this.size = 1; this.refreshtime = .30; this.lastupdate = 0; // call base constructor super(name, lvl); } public init() { this.enemyMesh = mine.clone("test", null); var actsize = (Math.random() * this.size) + 15; ///min size is 15 this.enemyMesh.scaling.x = actsize; this.enemyMesh.scaling.y = actsize; this.enemyMesh.scaling.z = actsize; this.speed = (Math.random() * this.speed) + .1; } public setup() { var loc = LightSpeed.BaseEnemy.SpawnInside(); this.enemyMesh.position.x = loc.x; this.enemyMesh.position.z = loc.z; loc = LightSpeed.BaseEnemy.SpawnOutside(); this.toX = loc.x; this.toZ = loc.z; this.rotation = Math.random() * .02; } public behavior() { // ship has explode or go to next level; if (!playerShip.canMove) return; var dx = playerShip.graphic.position.x - this.enemyMesh.position.x; var dy = playerShip.graphic.position.z - this.enemyMesh.position.z; //enemy ON ship if (dx <= 0.5 && dx >= -0.5 && dy <= 0.5 && dy >= -0.5) { return; } var direction = Math.atan2(dy, dx); this.enemyMesh.rotation.z += this.rotation * adjmovement; this.enemyMesh.rotation.x += this.rotation * adjmovement; //this.enemyMesh.rotation.y += this.rotation*adjmovement; this.enemyMesh.position.x += Math.cos(direction) * (this.speed * adjmovement); this.enemyMesh.position.z += Math.sin(direction) * (this.speed * adjmovement); } } export class Rock2Enemy extends BaseEnemy { // own rotation public rotationX: number; public rotationY: number; public rotationZ: number; public direction: number; constructor(name: string, lvl: number) { this.baseHealth = 50; this.healthIncrease = 30; this.speed = 2; this.canRespawn = true; this.value = 5; this.size = 15; this.refreshtime = .30; this.lastupdate = 0; // call base constructor super(name, lvl); } public init() { this.enemyMesh = rock2.clone("test", null); var actsize = (Math.random() * this.size) + 20; ///min size is 15 this.enemyMesh.scaling.x = actsize; this.enemyMesh.scaling.y = actsize; this.enemyMesh.scaling.z = actsize; this.speed = (Math.random() * this.speed) + .1; } public setup() { var loc = LightSpeed.BaseEnemy.SpawnOutside(); this.enemyMesh.position.x = loc.x; this.enemyMesh.position.z = loc.z; loc = LightSpeed.BaseEnemy.SpawnOutside(); this.toX = loc.x; this.toZ = loc.z; this.rotationX = Math.random() * .02; this.rotationY = Math.random() * .02; this.rotationZ = Math.random() * .02; var dx = this.toX - this.enemyMesh.position.x; var dy = this.toZ - this.enemyMesh.position.z; this.direction = Math.atan2(dy, dx); } public behavior() { var dx = this.toX - this.enemyMesh.position.x; var dy = this.toZ - this.enemyMesh.position.z; if (dx < 5 && dy < 5) { this.setup(); } this.enemyMesh.rotation.z += this.rotationZ * adjmovement; this.enemyMesh.rotation.x += this.rotationX * adjmovement; this.enemyMesh.rotation.y += this.rotationY * adjmovement; this.enemyMesh.position.x += Math.cos(this.direction) * (this.speed * adjmovement); this.enemyMesh.position.z += Math.sin(this.direction) * (this.speed * adjmovement); } } export class SpaceShipEnemy extends BaseEnemy { // this ship can cand do damages public damage: number; public direction: number; constructor(name: string, lvl: number) { this.baseHealth = 400; this.healthIncrease = 30; this.speed = .7; this.canRespawn = false; this.value = 15; this.size = 15; this.refreshtime = 1.0; this.lastupdate = 0; this.damage = 5; this.enemyBullet = null; this.enemyMesh = null; this.radar = null; // call base constructor super(name, lvl); } public init() { this.enemyBullet = []; this.enemyMesh = enemyship.clone("swship", null); // making a radar this.radar = radar.clone("radar", null); this.radar.parent = this.enemyMesh; this.radar.rotation.x += Math.PI / 2; this.radar.rotation.z += Math.PI * .5; this.speed = (Math.random() * this.speed) + .1; } public setup() { var loc = LightSpeed.BaseEnemy.SpawnInsideEdge(); this.enemyMesh.position.x = loc.x; this.enemyMesh.position.z = loc.z; this.radar.position.x = 0; this.radar.position.z = 0 loc = LightSpeed.BaseEnemy.SpawnInsideEdge(); this.toX = loc.x; this.toZ = loc.z; var dx = this.toX - this.enemyMesh.position.x; var dy = this.toZ - this.enemyMesh.position.z; this.direction = Math.atan2(dy, dx); } public behavior() { // ship has explode or go to next level; if (!playerShip.canMove) return; var dx = playerShip.graphic.position.x - this.enemyMesh.position.x; var dy = playerShip.graphic.position.z - this.enemyMesh.position.z; //enemy ON ship if (dx <= 0.5 && dx >= -0.5 && dy <= 0.5 && dy >= -0.5) { return; } // if radar intersect the player ship, the sw ship will follow him if (this.radar.intersectsMesh(playerShip.boundingBox, true)) { var dx = playerShip.graphic.position.x - this.enemyMesh.position.x; var dy = playerShip.graphic.position.z - this.enemyMesh.position.z; this.direction = Math.atan2(dy, dx); // stack a bullet ! if ((time - this.lastupdate) > this.refreshtime) { var newbullet2 = bulletobj3.clone("bullet", null); newbullet2.position.x = this.enemyMesh.position.x; newbullet2.position.z = this.enemyMesh.position.z; this.enemyBullet.push({ 'graphic': newbullet2, 'direction': this.direction }); this.lastupdate = time; } } // respawning ? if ((this.enemyMesh.position.x > height || this.enemyMesh.position.x < -height) || (this.enemyMesh.position.z > width || this.enemyMesh.position.z < -width)) { var loc = LightSpeed.BaseEnemy.SpawnInsideEdge(); var dx = loc.x - this.enemyMesh.position.x; var dy = loc.z - this.enemyMesh.position.z; this.direction = Math.atan2(dy, dx); } // show bullets var index = this.enemyBullet.length; while (index--) { var bullet = this.enemyBullet[index]; bullet.graphic.position.x += Math.cos(bullet.direction) * ((this.speed * adjmovement) + (2 * adjmovement)); bullet.graphic.position.z += Math.sin(bullet.direction) * ((this.speed * adjmovement) + (2 * adjmovement)); // bullet intersect player ship, do damages ! if (bullet.graphic.intersectsMesh(playerShip.boundingBox, true)) { playerShip.getDamage(this.damage); bullet.graphic.dispose(); this.enemyBullet.splice(index, 1); } // outside screen else if (bullet.graphic.position.z > width + 50 || bullet.graphic.position.z < -width - 50 || bullet.graphic.position.x > height + 50 || bullet.graphic.position.x < -height - 50) { bullet.graphic.dispose(); this.enemyBullet.splice(index, 1); } } this.enemyMesh.position.x += Math.cos(this.direction) * (this.speed * adjmovement); this.enemyMesh.position.z += Math.sin(this.direction) * (this.speed * adjmovement); this.enemyMesh.rotation.y = Math.PI - this.direction; } } export class StaticMineEnemy extends BaseEnemy { constructor(name: string, lvl: number) { this.baseHealth = 100; this.healthIncrease = 20; this.speed = .75; this.canRespawn = false; this.value = 5; this.size = 1; this.refreshtime = 1.0; this.lastupdate = 0; // call base constructor super(name, lvl); } public init() { this.enemyMesh = mine.clone("test", null); var actsize = (Math.random() * this.size) + 15; ///min size is 15 this.enemyMesh.scaling.x = actsize; this.enemyMesh.scaling.y = actsize; this.enemyMesh.scaling.z = actsize; this.radar = radar.clone("radar", null); this.radar.parent = this.enemyMesh; this.radar.position.x = 0;//this.enemyMesh.position.x; this.radar.position.z = 0;//this.enemyMesh.position.z; this.radar.scaling.x = .0010; this.radar.scaling.y = .0010; this.radar.scaling.z = .0010; this.radar.rotation.z += Math.PI * .5; // *1.5; } public setup() { var loc = LightSpeed.BaseEnemy.SpawnInside(); this.enemyMesh.position.x = loc.x; this.enemyMesh.position.z = loc.z; } public behavior() { if (this.radar.intersectsMesh(playerShip.boundingBox, true)) { if ((time - this.lastupdate) > this.refreshtime) { //this.explode(); playerShip.getDamage(this.maxHealth / 4); this.lastupdate = time; } } else { this.lastupdate = time; this.radar.scaling.x += .00015; this.radar.scaling.y += .00015; this.radar.scaling.z += .00015; if (this.radar.scaling.x >= .03) { this.radar.scaling.x = .001; this.radar.scaling.y = .001; this.radar.scaling.z = .001; } } } } }
the_stack
import { SpecPage } from '@stencil/core/testing'; import { flushTransitions } from './unit-test-utils'; export const generic_height_default_load = { prop: 'height', group: 'base', name: 'default height on load', testDefault: true, testProps: { height: 999999 }, testSelector: '[data-testid=chart-container] svg', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDHEIGHT = testProps['height'] || 999999; // if default is not sent cause error // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const SVGelement = page.doc.querySelector(testSelector); expect(SVGelement).toEqualAttribute('height', EXPECTEDHEIGHT); } }; export const generic_height_custom_load = { prop: 'height', group: 'base', name: 'set height on load', testProps: { height: 410 }, testSelector: '[data-testid=chart-container] svg', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE Object.keys(testProps).forEach(prop => { component[prop] = testProps[prop]; }); const EXPECTEDHEIGHT = testProps['height'] || 410; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const SVGelement = page.doc.querySelector(testSelector); expect(SVGelement).toEqualAttribute('height', EXPECTEDHEIGHT); } }; export const generic_height_custom_update = { prop: 'height', group: 'base', name: 'set height on update', testProps: { height: 500 }, testSelector: '[data-testid=chart-container] svg', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // render page.root.appendChild(component); await page.waitForChanges(); // ARRANGE UPDATE Object.keys(testProps).forEach(prop => { component[prop] = testProps[prop]; }); const EXPECTEDHEIGHT = testProps['height'] || 500; await page.waitForChanges(); // ASSERT const SVGelement = page.doc.querySelector(testSelector); flushTransitions(SVGelement); expect(SVGelement).toEqualAttribute('height', EXPECTEDHEIGHT); } }; export const generic_width_default_load = { prop: 'width', group: 'base', name: 'default width on load', testDefault: true, testProps: { width: 999999 }, testSelector: '[data-testid=chart-container] svg', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDWIDTH = testProps['width'] || 999999; // if default is not sent cause error // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const SVGelement = page.doc.querySelector(testSelector); expect(SVGelement).toEqualAttribute('width', EXPECTEDWIDTH); } }; export const generic_width_custom_load = { prop: 'width', group: 'base', name: 'set width on load', testProps: { width: 410 }, testSelector: '[data-testid=chart-container] svg', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE Object.keys(testProps).forEach(prop => { component[prop] = testProps[prop]; }); const EXPECTEDWIDTH = testProps['width'] || 410; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const SVGelement = page.doc.querySelector(testSelector); expect(SVGelement).toEqualAttribute('width', EXPECTEDWIDTH); } }; export const generic_width_custom_update = { prop: 'width', group: 'base', name: 'set width on update', testProps: { width: 625 }, testSelector: '[data-testid=chart-container] svg', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // render page.root.appendChild(component); await page.waitForChanges(); // ARRANGE UPDATE Object.keys(testProps).forEach(prop => { component[prop] = testProps[prop]; }); const EXPECTEDWIDTH = testProps['width'] || 625; await page.waitForChanges(); // ASSERT const SVGelement = page.doc.querySelector(testSelector); flushTransitions(SVGelement); expect(SVGelement).toEqualAttribute('width', EXPECTEDWIDTH); } }; export const generic_mainTitle_default_load = { prop: 'mainTitle', group: 'base', name: 'default mainTitle on load', testDefault: true, testProps: { mainTitle: 'This is a custom main title which causes an error' }, testSelector: '[data-testid=main-title]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDMAINTITLE = testProps['mainTitle'] || 'This is a custom main title which causes an error'; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const mainTitleElement = page.doc.querySelector(testSelector); expect(mainTitleElement).toEqualText(EXPECTEDMAINTITLE); } }; export const generic_mainTitle_custom_load = { prop: 'mainTitle', group: 'base', name: 'set mainTitle on load', testProps: { mainTitle: 'This is a custom main title' }, testSelector: '[data-testid=main-title]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE Object.keys(testProps).forEach(prop => { component[prop] = testProps[prop]; }); const EXPECTEDMAINTITLE = testProps['mainTitle'] || 'This is a custom main title'; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const mainTitleElement = page.doc.querySelector(testSelector); expect(mainTitleElement).toEqualText(EXPECTEDMAINTITLE); } }; export const generic_mainTitle_custom_update = { prop: 'mainTitle', group: 'base', name: 'set mainTitle on update', testProps: { mainTitle: 'This is an updated custom main title' }, testSelector: '[data-testid=main-title]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // render page.root.appendChild(component); await page.waitForChanges(); // ARRANGE Object.keys(testProps).forEach(prop => { component[prop] = testProps[prop]; }); const EXPECTEDMAINTITLE = testProps['mainTitle'] || 'This is an updated custom main title'; // ACT await page.waitForChanges(); // ASSERT const mainTitleElement = page.doc.querySelector(testSelector); expect(mainTitleElement).toEqualText(EXPECTEDMAINTITLE); } }; export const generic_subTitle_default_load = { prop: 'subTitle', group: 'base', name: 'default subTitle on load', testDefault: true, testProps: { mainTitle: 'This is a custom sub title which causes an error' }, testSelector: '[data-testid=sub-title]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDSUBTITLE = testProps['subTitle'] || 'This is a custom sub title which causes an error'; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const subTitleElement = page.doc.querySelector(testSelector); expect(subTitleElement).toEqualText(EXPECTEDSUBTITLE); } }; export const generic_subTitle_custom_load = { prop: 'subTitle', group: 'base', name: 'set subTitle on load', testProps: { subTitle: 'This is a custom sub title' }, testSelector: '[data-testid=sub-title]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE Object.keys(testProps).forEach(prop => { component[prop] = testProps[prop]; }); const EXPECTEDSUBTITLE = testProps['subTitle'] || 'This is a custom sub title'; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const subTitleElement = page.doc.querySelector(testSelector); expect(subTitleElement).toEqualText(EXPECTEDSUBTITLE); } }; export const generic_subTitle_custom_update = { prop: 'subTitle', group: 'base', name: 'set subTitle on update', testProps: { subTitle: 'This is an updated custom sub title' }, testSelector: '[data-testid=sub-title]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // render page.root.appendChild(component); await page.waitForChanges(); // ARRANGE Object.keys(testProps).forEach(prop => { component[prop] = testProps[prop]; }); const EXPECTEDSUBTITLE = testProps['subTitle'] || 'This is an updated custom sub title'; // ACT await page.waitForChanges(); // ASSERT const subTitleElement = page.doc.querySelector(testSelector); expect(subTitleElement).toEqualText(EXPECTEDSUBTITLE); } }; export const generic_margin_default_load = { prop: 'margin', group: 'margin', name: 'default margin on load', testDefault: true, testProps: { margin: { bottom: 100, left: 100, right: 100, top: 100 } }, testSelector: '[data-testid=margin-container]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDMARGIN = testProps['margin'] || { bottom: 100, left: 100, right: 100, top: 100 }; // if default is not sent cause error const MARGINMODIFIER = testProps['marginModifier'] || 0; const BASEHEIGHT = 600; const BASEWIDTH = 600; component.height = BASEHEIGHT; component.width = BASEWIDTH; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const marginG = page.doc.querySelector(testSelector); expect(marginG).toEqualAttribute( 'transform', `translate(${EXPECTEDMARGIN.left + MARGINMODIFIER}, ${EXPECTEDMARGIN.top + MARGINMODIFIER})` ); } }; export const generic_margin_custom_load = { prop: 'margin', group: 'margin', name: 'custom margin on load', testProps: { margin: { bottom: 25, left: 25, right: 25, top: 25 } }, testSelector: '[data-testid=margin-container]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDMARGIN = testProps['margin'] || { bottom: 25, left: 25, right: 25, top: 25 }; // if default is not sent cause error const BASEHEIGHT = 600; const BASEWIDTH = 600; const MARGINMODIFIER = testProps['marginModifier'] || 0; component.height = BASEHEIGHT; component.width = BASEWIDTH; component.margin = EXPECTEDMARGIN; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const marginG = page.doc.querySelector(testSelector); expect(marginG).toEqualAttribute( 'transform', `translate(${EXPECTEDMARGIN.left + MARGINMODIFIER}, ${EXPECTEDMARGIN.top + MARGINMODIFIER})` ); } }; export const generic_margin_custom_update = { prop: 'margin', group: 'margin', name: 'custom margin on update', testProps: { margin: { bottom: 25, left: 25, right: 25, top: 25 }, animationConfig: { disabled: true } }, testSelector: '[data-testid=margin-container]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDMARGIN = testProps['margin'] || { bottom: 25, left: 25, right: 25, top: 25 }; // if default is not sent cause error const BASEHEIGHT = 600; const BASEWIDTH = 600; const MARGINMODIFIER = testProps['marginModifier'] || 0; // ARRANGE Object.keys(testProps).forEach(prop => { component[prop] = testProps[prop]; }); component.height = BASEHEIGHT; component.width = BASEWIDTH; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UDPATE component.margin = EXPECTEDMARGIN; await page.waitForChanges(); // ASSERT const marginG = page.doc.querySelector(testSelector); expect(marginG).toEqualAttribute( 'transform', `translate(${EXPECTEDMARGIN.left + MARGINMODIFIER}, ${EXPECTEDMARGIN.top + MARGINMODIFIER})` ); } }; export const generic_padding_default_load = { prop: 'padding', group: 'padding', name: 'default padding on load', testDefault: true, testProps: { padding: { bottom: 100, left: 100, right: 100, top: 100 } }, testSelector: '[data-testid=padding-container]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDMARGIN = { bottom: 10, left: 10, right: 10, top: 10 }; const EXPECTEDPADDING = testProps['padding'] || { bottom: 100, left: 100, right: 100, top: 100 }; // if default is not sent cause error const BASEHEIGHT = 600; const BASEWIDTH = 600; component.height = BASEHEIGHT; component.width = BASEWIDTH; component.margin = EXPECTEDMARGIN; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const paddingG = page.doc.querySelector(testSelector); expect(paddingG).toEqualAttribute('transform', `translate(${EXPECTEDPADDING.left}, ${EXPECTEDPADDING.top})`); } }; export const generic_padding_custom_load = { prop: 'padding', group: 'padding', name: 'custom padding on load', testProps: { padding: { bottom: 25, left: 25, right: 25, top: 25 } }, testSelector: '[data-testid=padding-container]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDMARGIN = { bottom: 10, left: 10, right: 10, top: 10 }; const EXPECTEDPADDING = testProps['padding'] || { bottom: 100, left: 100, right: 100, top: 100 }; // if default is not sent cause error const BASEHEIGHT = 600; const BASEWIDTH = 600; component.height = BASEHEIGHT; component.width = BASEWIDTH; component.margin = EXPECTEDMARGIN; component.padding = EXPECTEDPADDING; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const paddingG = page.doc.querySelector(testSelector); expect(paddingG).toEqualAttribute('transform', `translate(${EXPECTEDPADDING.left}, ${EXPECTEDPADDING.top})`); } }; export const generic_padding_custom_update = { prop: 'padding', group: 'padding', name: 'custom padding on update', testProps: { padding: { bottom: 25, left: 25, right: 25, top: 25 }, animationConfig: { disabled: true } }, testSelector: '[data-testid=padding-container]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDMARGIN = { bottom: 10, left: 10, right: 10, top: 10 }; const EXPECTEDPADDING = testProps['padding'] || { bottom: 100, left: 100, right: 100, top: 100 }; // if default is not sent cause error const BASEHEIGHT = 600; const BASEWIDTH = 600; // ARRANGE Object.keys(testProps).forEach(prop => { component[prop] = testProps[prop]; }); component.height = BASEHEIGHT; component.width = BASEWIDTH; component.margin = EXPECTEDMARGIN; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UDPATE component.padding = EXPECTEDPADDING; await page.waitForChanges(); // ASSERT const paddingG = page.doc.querySelector(testSelector); expect(paddingG).toEqualAttribute('transform', `translate(${EXPECTEDPADDING.left}, ${EXPECTEDPADDING.top})`); } }; export const generic_uniqueID_default_load = { prop: 'uniqueID', group: 'data', name: 'default uniqueID on load', testDefault: true, testProps: { uniqueID: 'not_matching_id' }, testSelector: 'component-name', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const element = page.doc.querySelector(testSelector); expect(element.id).toEqual(expect.anything()); } }; export const generic_uniqueID_custom_load = { prop: 'uniqueID', group: 'data', name: 'custom uniqueID on load', testProps: { uniqueID: 'custom_unique_id' }, testSelector: 'component-name', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDUNIQUEID = testProps['uniqueID'] || 'custom_unique_id'; component.uniqueID = EXPECTEDUNIQUEID; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const element = page.doc.querySelector(testSelector); const margin = element.querySelector('[data-testid=margin-container]'); const padding = element.querySelector('[data-testid=padding-container]'); expect(element.id).toEqual(EXPECTEDUNIQUEID); expect(margin.id).toEqual(`visa-viz-margin-container-g-${EXPECTEDUNIQUEID}`); expect(padding.id).toEqual(`visa-viz-padding-container-g-${EXPECTEDUNIQUEID}`); } }; export const generic_uniqueID_custom_update = { prop: 'uniqueID', group: 'data', name: 'custom uniqueID on update', testProps: { uniqueID: 'custom_unique_id' }, testSelector: 'component-name', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDUNIQUEID = testProps['uniqueID'] || 'custom_unique_id'; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.uniqueID = EXPECTEDUNIQUEID; await page.waitForChanges(); // ASSERT const element = page.doc.querySelector(testSelector); const margin = element.querySelector('[data-testid=margin-container]'); const padding = element.querySelector('[data-testid=padding-container]'); expect(element.id).toEqual(EXPECTEDUNIQUEID); expect(margin.id).toEqual(`visa-viz-margin-container-g-${EXPECTEDUNIQUEID}`); expect(padding.id).toEqual(`visa-viz-padding-container-g-${EXPECTEDUNIQUEID}`); } }; export const generic_data_custom_load = { prop: 'data', group: 'data', name: 'custom data on load', testProps: { data: [] }, testSelector: '[data-testid=mark]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDDATA = testProps['data'] || []; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll(testSelector); elements.forEach((element, i) => { expect(element['__data__']).toEqual(EXPECTEDDATA[i]); // tslint:disable-line: no-string-literal }); } }; export const generic_data_custom_update_enter = { prop: 'data', group: 'data', name: 'custom data enter on update', testProps: { data: [] }, testSelector: '[data-testid=mark]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDDATA = testProps['data'] || []; const BEGINNINGDATA = [EXPECTEDDATA[0], EXPECTEDDATA[1]]; component.data = BEGINNINGDATA; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.data = EXPECTEDDATA; await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll(testSelector); elements.forEach((element, i) => { expect(element['__data__']).toEqual(EXPECTEDDATA[i]); // tslint:disable-line: no-string-literal }); } }; export const generic_data_custom_update_exit = { prop: 'data', group: 'data', name: 'custom data exit on update', testProps: { data: [] }, testSelector: '[data-testid=mark]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const EXPECTEDDATA = testProps['data'] || []; const EXITDATA = [EXPECTEDDATA[0], EXPECTEDDATA[1]]; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.data = EXITDATA; await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll(testSelector); elements.forEach((element, i) => { if (i + 1 <= EXITDATA.length) { expect(element['__data__']).toEqual(EXPECTEDDATA[i]); // tslint:disable-line: no-string-literal } else { const lastTransitionKey = Object.keys(element['__transition'])[Object.keys(element['__transition']).length - 1]; // tslint:disable-line: no-string-literal const transitionName = element['__transition'][lastTransitionKey].name; // tslint:disable-line: no-string-literal expect(transitionName).toEqual('exit'); } }); } }; export const generic_accessibility_validation_default_false_load = { prop: 'accessibility', group: 'accessibility', name: 'should print accessibility console warnings and logs when accessibility.disableValidation defaults to false', testProps: { disableValidation: false }, testSelector: 'N/A', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const spyWarn = jest.spyOn(console, 'warn').mockImplementation(); const spyLog = jest.spyOn(console, 'log').mockImplementation(); const spyGroup = jest.spyOn(console, 'groupCollapsed').mockImplementation(); const ENABLEACCESSIBILITYVALIDATION = testProps || { disableValidation: false }; component.accessibility = ENABLEACCESSIBILITYVALIDATION; // CLEAR spyWarn.mockClear(); spyLog.mockClear(); spyGroup.mockClear(); // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT expect(spyWarn.mock.calls).toMatchSnapshot(); expect(spyWarn.mock.calls.length).toBeGreaterThan(0); expect(spyLog.mock.calls).toMatchSnapshot(); expect(spyLog.mock.calls.length).toBeGreaterThan(0); expect(spyGroup.mock.calls).toMatchSnapshot(); expect(spyGroup.mock.calls.length).toBeGreaterThan(0); // RESTORE spyWarn.mockRestore(); spyLog.mockRestore(); spyGroup.mockRestore(); } }; export const generic_accessibility_validation_true_load = { prop: 'accessibility', group: 'accessibility', name: 'should not print accessibility console warnings and logs when accessibility.disableValidation set to true', testProps: { disableValidation: true }, testSelector: 'N/A', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string) => { // ARRANGE const spyWarn = jest.spyOn(console, 'warn').mockImplementation(); const spyLog = jest.spyOn(console, 'log').mockImplementation(); const spyGroup = jest.spyOn(console, 'groupCollapsed').mockImplementation(); const DISABLEACCESSIBILITYVALIDATION = testProps || { disableValidation: true }; component.accessibility = DISABLEACCESSIBILITYVALIDATION; // CLEAR spyWarn.mockClear(); spyLog.mockClear(); spyGroup.mockClear(); // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT expect(spyWarn.mock.calls).toMatchSnapshot(); expect(spyWarn.mock.calls.length).toBeLessThanOrEqual(0); expect(spyLog.mock.calls).toMatchSnapshot(); expect(spyLog.mock.calls.length).toBeLessThanOrEqual(0); expect(spyGroup.mock.calls).toMatchSnapshot(); expect(spyGroup.mock.calls.length).toBeLessThanOrEqual(0); // RESTORE spyWarn.mockRestore(); spyLog.mockRestore(); spyGroup.mockRestore(); } };
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Four different resources help you manage your IAM policy for a project. Each of these resources serves a different use case: * * * `gcp.projects.IAMPolicy`: Authoritative. Sets the IAM policy for the project and replaces any existing policy already attached. * * `gcp.projects.IAMBinding`: Authoritative for a given role. Updates the IAM policy to grant a role to a list of members. Other roles within the IAM policy for the project are preserved. * * `gcp.projects.IAMMember`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the project are preserved. * * `gcp.projects.IAMAuditConfig`: Authoritative for a given service. Updates the IAM policy to enable audit logging for the given service. * * > **Note:** `gcp.projects.IAMPolicy` **cannot** be used in conjunction with `gcp.projects.IAMBinding`, `gcp.projects.IAMMember`, or `gcp.projects.IAMAuditConfig` or they will fight over what your policy should be. * * > **Note:** `gcp.projects.IAMBinding` resources **can be** used in conjunction with `gcp.projects.IAMMember` resources **only if** they do not grant privilege to the same role. * * > **Note:** The underlying API method `projects.setIamPolicy` has a lot of constraints which are documented [here](https://cloud.google.com/resource-manager/reference/rest/v1/projects/setIamPolicy). In addition to these constraints, * IAM Conditions cannot be used with Basic Roles such as Owner. Violating these constraints will result in the API returning 400 error code so please review these if you encounter errors with this resource. * * ## google\_project\_iam\_policy * * > **Be careful!** You can accidentally lock yourself out of your project * using this resource. Deleting a `gcp.projects.IAMPolicy` removes access * from anyone without organization-level access to the project. Proceed with caution. * It's not recommended to use `gcp.projects.IAMPolicy` with your provider project * to avoid locking yourself out, and it should generally only be used with projects * fully managed by this provider. If you do use this resource, it is recommended to **import** the policy before * applying the change. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const admin = gcp.organizations.getIAMPolicy({ * bindings: [{ * role: "roles/editor", * members: ["user:jane@example.com"], * }], * }); * const project = new gcp.projects.IAMPolicy("project", { * project: "your-project-id", * policyData: admin.then(admin => admin.policyData), * }); * ``` * * With IAM Conditions: * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const admin = pulumi.output(gcp.organizations.getIAMPolicy({ * bindings: [{ * condition: { * description: "Expiring at midnight of 2019-12-31", * expression: "request.time < timestamp(\"2020-01-01T00:00:00Z\")", * title: "expires_after_2019_12_31", * }, * members: ["user:jane@example.com"], * role: "roles/compute.admin", * }], * })); * const project = new gcp.projects.IAMPolicy("project", { * policyData: admin.policyData, * project: "your-project-id", * }); * ``` * * ## google\_project\_iam\_binding * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const project = new gcp.projects.IAMBinding("project", { * members: ["user:jane@example.com"], * project: "your-project-id", * role: "roles/editor", * }); * ``` * * With IAM Conditions: * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const project = new gcp.projects.IAMBinding("project", { * condition: { * description: "Expiring at midnight of 2019-12-31", * expression: "request.time < timestamp(\"2020-01-01T00:00:00Z\")", * title: "expires_after_2019_12_31", * }, * members: ["user:jane@example.com"], * project: "your-project-id", * role: "roles/container.admin", * }); * ``` * * ## google\_project\_iam\_member * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const project = new gcp.projects.IAMMember("project", { * member: "user:jane@example.com", * project: "your-project-id", * role: "roles/editor", * }); * ``` * * With IAM Conditions: * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const project = new gcp.projects.IAMMember("project", { * condition: { * description: "Expiring at midnight of 2019-12-31", * expression: "request.time < timestamp(\"2020-01-01T00:00:00Z\")", * title: "expires_after_2019_12_31", * }, * member: "user:jane@example.com", * project: "your-project-id", * role: "roles/firebase.admin", * }); * ``` * * ## google\_project\_iam\_audit\_config * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const project = new gcp.projects.IAMAuditConfig("project", { * auditLogConfigs: [ * { * logType: "ADMIN_READ", * }, * { * exemptedMembers: ["user:joebloggs@hashicorp.com"], * logType: "DATA_READ", * }, * ], * project: "your-project-id", * service: "allServices", * }); * ``` * * ## Import * * IAM member imports use space-delimited identifiers; the resource in question, the role, and the account. * * This member resource can be imported using the `project_id`, role, and member e.g. * * ```sh * $ pulumi import gcp:projects/iAMBinding:IAMBinding my_project "your-project-id roles/viewer user:foo@example.com" * ``` * * IAM binding imports use space-delimited identifiers; the resource in question and the role. * * This binding resource can be imported using the `project_id` and role, e.g. * * ```sh * $ pulumi import gcp:projects/iAMBinding:IAMBinding my_project "your-project-id roles/viewer" * ``` * * IAM policy imports use the identifier of the resource in question. * * This policy resource can be imported using the `project_id`. * * ```sh * $ pulumi import gcp:projects/iAMBinding:IAMBinding my_project your-project-id * ``` * * IAM audit config imports use the identifier of the resource in question and the service, e.g. * * ```sh * $ pulumi import gcp:projects/iAMBinding:IAMBinding my_project "your-project-id foo.googleapis.com" * ``` * * -> **Custom Roles**If you're importing a IAM resource with a custom role, make sure to use the * * full name of the custom role, e.g. `[projects/my-project|organizations/my-org]/roles/my-custom-role`. */ export class IAMBinding extends pulumi.CustomResource { /** * Get an existing IAMBinding 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?: IAMBindingState, opts?: pulumi.CustomResourceOptions): IAMBinding { return new IAMBinding(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:projects/iAMBinding:IAMBinding'; /** * Returns true if the given object is an instance of IAMBinding. 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 IAMBinding { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === IAMBinding.__pulumiType; } /** * An [IAM Condition](https://cloud.google.com/iam/docs/conditions-overview) for a given binding. * Structure is documented below. */ public readonly condition!: pulumi.Output<outputs.projects.IAMBindingCondition | undefined>; /** * (Computed) The etag of the project's IAM policy. */ public /*out*/ readonly etag!: pulumi.Output<string>; public readonly members!: pulumi.Output<string[]>; /** * The project id of the target project. This is not * inferred from the provider. */ public readonly project!: pulumi.Output<string>; /** * The role that should be applied. Only one * `gcp.projects.IAMBinding` can be used per role. Note that custom roles must be of the format * `[projects|organizations]/{parent-name}/roles/{role-name}`. */ public readonly role!: pulumi.Output<string>; /** * Create a IAMBinding 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: IAMBindingArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: IAMBindingArgs | IAMBindingState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as IAMBindingState | undefined; inputs["condition"] = state ? state.condition : undefined; inputs["etag"] = state ? state.etag : undefined; inputs["members"] = state ? state.members : undefined; inputs["project"] = state ? state.project : undefined; inputs["role"] = state ? state.role : undefined; } else { const args = argsOrState as IAMBindingArgs | undefined; if ((!args || args.members === undefined) && !opts.urn) { throw new Error("Missing required property 'members'"); } if ((!args || args.project === undefined) && !opts.urn) { throw new Error("Missing required property 'project'"); } if ((!args || args.role === undefined) && !opts.urn) { throw new Error("Missing required property 'role'"); } inputs["condition"] = args ? args.condition : undefined; inputs["members"] = args ? args.members : undefined; inputs["project"] = args ? args.project : undefined; inputs["role"] = args ? args.role : undefined; inputs["etag"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(IAMBinding.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering IAMBinding resources. */ export interface IAMBindingState { /** * An [IAM Condition](https://cloud.google.com/iam/docs/conditions-overview) for a given binding. * Structure is documented below. */ condition?: pulumi.Input<inputs.projects.IAMBindingCondition>; /** * (Computed) The etag of the project's IAM policy. */ etag?: pulumi.Input<string>; members?: pulumi.Input<pulumi.Input<string>[]>; /** * The project id of the target project. This is not * inferred from the provider. */ project?: pulumi.Input<string>; /** * The role that should be applied. Only one * `gcp.projects.IAMBinding` can be used per role. Note that custom roles must be of the format * `[projects|organizations]/{parent-name}/roles/{role-name}`. */ role?: pulumi.Input<string>; } /** * The set of arguments for constructing a IAMBinding resource. */ export interface IAMBindingArgs { /** * An [IAM Condition](https://cloud.google.com/iam/docs/conditions-overview) for a given binding. * Structure is documented below. */ condition?: pulumi.Input<inputs.projects.IAMBindingCondition>; members: pulumi.Input<pulumi.Input<string>[]>; /** * The project id of the target project. This is not * inferred from the provider. */ project: pulumi.Input<string>; /** * The role that should be applied. Only one * `gcp.projects.IAMBinding` can be used per role. Note that custom roles must be of the format * `[projects|organizations]/{parent-name}/roles/{role-name}`. */ role: pulumi.Input<string>; }
the_stack
import {HasProps} from "../core/has_props" import {Data, Attrs} from "../core/types" import {Value, Field, Vector} from "../core/vectorization" import {VectorSpec, UnitsSpec, Property} from "../core/properties" import {Class, extend} from "../core/class" import {Location} from "../core/enums" import {is_equal, Comparator} from "../core/util/eq" import {includes, uniq} from "../core/util/array" import {clone, keys, entries, is_empty} from "../core/util/object" import {isNumber, isString, isArray, isArrayOf} from "../core/util/types" import {enumerate} from "core/util/iterator" import * as nd from "core/util/ndarray" import { Glyph, GlyphRenderer, Axis, Grid, Range, Range1d, DataRange1d, FactorRange, Scale, LinearScale, LogScale, CategoricalScale, LinearAxis, LogAxis, CategoricalAxis, DatetimeAxis, MercatorAxis, ColumnarDataSource, ColumnDataSource, CDSView, Plot, Tool, ContinuousTicker, CoordinateMapping, } from "./models" import {Legend} from "../models/annotations/legend" import {LegendItem} from "../models/annotations/legend_item" import {ToolAliases} from "../models/tools/tool" import {Figure as BaseFigure} from "../models/plots/figure" import {TypedGlyphRenderer, NamesOf, GlyphAPI, AuxGlyph} from "./glyph_api" const {hasOwnProperty} = Object.prototype export type ToolName = keyof ToolAliases const _default_tools: ToolName[] = ["pan", "wheel_zoom", "box_zoom", "save", "reset", "help"] // export type ExtMarkerType = MarkerType | "*" | "+" | "o" | "ox" | "o+" const _default_color = "#1f77b4" const _default_alpha = 1.0 function _with_default<T>(value: T | undefined, default_value: T): T { return value === undefined ? default_value : value } export type AxisType = "auto" | "linear" | "datetime" | "log" | "mercator" | null export namespace Figure { export type Attrs = Omit<Plot.Attrs, "x_range" | "y_range"> & { x_range: Range | [number, number] | ArrayLike<string> y_range: Range | [number, number] | ArrayLike<string> x_axis_type: AxisType y_axis_type: AxisType x_axis_location: Location y_axis_location: Location x_axis_label: Axis["axis_label"] y_axis_label: Axis["axis_label"] x_minor_ticks: number | "auto" y_minor_ticks: number | "auto" tools: (Tool | ToolName)[] | string } } type IModelProxy<T extends HasProps> = { each(fn: (model: T, i: number) => void): void [Symbol.iterator](): Generator<T, void, undefined> } class ModelProxy<T extends HasProps> implements IModelProxy<T> { constructor(readonly models: T[]) { const mapping: Map<string, Property<unknown>[]> = new Map() for (const model of models) { for (const prop of model) { const {attr} = prop if (!mapping.has(attr)) mapping.set(attr, []) mapping.get(attr)!.push(prop) } } for (const [name, props] of mapping) { Object.defineProperty(this, name, { get(this: Axis): never { throw new Error("only setting values is supported") }, set(this: Axis, value: unknown): Axis { for (const prop of props) { prop.obj.setv({[name]: value}) } return this }, }) } } each(fn: (model: T, i: number) => void): void { let i = 0 for (const model of this.models) { fn(model, i++) } } *[Symbol.iterator](): Generator<T, void, undefined> { yield* this.models } } type PropsOf<T extends HasProps> = { // TODO: writeonly/setter [K in keyof T["properties"]]: T["properties"][K] extends Property<infer P> ? P : never } type Proxied<T extends HasProps> = PropsOf<T> & IModelProxy<T> // TODO: derive this from CoordinateMapping export type ICoordinateMapping = { x_source?: Range y_source?: Range x_scale?: Scale y_scale?: Scale x_target: Range y_target: Range } export class SubFigure extends GlyphAPI { constructor(readonly coordinates: CoordinateMapping, readonly parent: Figure) { super() } _glyph<G extends Glyph>(cls: Class<G>, positional: NamesOf<G>, args: unknown[], overrides?: object): TypedGlyphRenderer<G> { const {coordinates} = this return this.parent._glyph(cls, positional, args, {coordinates, ...overrides}) } } export interface Figure extends GlyphAPI {} export class Figure extends BaseFigure { get xaxes(): Axis[] { return [...this.below, ...this.above].filter((r): r is Axis => r instanceof Axis) } get yaxes(): Axis[] { return [...this.left, ...this.right].filter((r): r is Axis => r instanceof Axis) } get axes(): Axis[] { return [...this.below, ...this.above, ...this.left, ...this.right].filter((r): r is Axis => r instanceof Axis) } get xaxis(): Proxied<Axis> { return new ModelProxy(this.xaxes) as any as Proxied<Axis> } get yaxis(): Proxied<Axis> { return new ModelProxy(this.yaxes) as any as Proxied<Axis> } get axis(): Proxied<Axis> { return new ModelProxy(this.axes) as any as Proxied<Axis> } get xgrids(): Grid[] { return this.center.filter((r): r is Grid => r instanceof Grid && r.dimension == 0) } get ygrids(): Grid[] { return this.center.filter((r): r is Grid => r instanceof Grid && r.dimension == 1) } get grids(): Grid[] { return this.center.filter((r): r is Grid => r instanceof Grid) } get xgrid(): Proxied<Grid> { return new ModelProxy(this.xgrids) as any as Proxied<Grid> } get ygrid(): Proxied<Grid> { return new ModelProxy(this.ygrids) as any as Proxied<Grid> } get grid(): Proxied<Grid> { return new ModelProxy(this.grids) as any as Proxied<Grid> } get legend(): Legend { const legends = this.panels.filter((r): r is Legend => r instanceof Legend) if (legends.length == 0) { const legend = new Legend() this.add_layout(legend) return legend } else { const [legend] = legends return legend } } static { extend(this, GlyphAPI) } constructor(attrs: Partial<Figure.Attrs> = {}) { attrs = {...attrs} const tools = _with_default(attrs.tools, _default_tools) delete attrs.tools const x_axis_type = _with_default(attrs.x_axis_type, "auto") const y_axis_type = _with_default(attrs.y_axis_type, "auto") delete attrs.x_axis_type delete attrs.y_axis_type const x_minor_ticks = attrs.x_minor_ticks != null ? attrs.x_minor_ticks : "auto" const y_minor_ticks = attrs.y_minor_ticks != null ? attrs.y_minor_ticks : "auto" delete attrs.x_minor_ticks delete attrs.y_minor_ticks const x_axis_location = attrs.x_axis_location != null ? attrs.x_axis_location : "below" const y_axis_location = attrs.y_axis_location != null ? attrs.y_axis_location : "left" delete attrs.x_axis_location delete attrs.y_axis_location const x_axis_label = attrs.x_axis_label != null ? attrs.x_axis_label : "" const y_axis_label = attrs.y_axis_label != null ? attrs.y_axis_label : "" delete attrs.x_axis_label delete attrs.y_axis_label const x_range = Figure._get_range(attrs.x_range) const y_range = Figure._get_range(attrs.y_range) delete attrs.x_range delete attrs.y_range const x_scale = attrs.x_scale != null ? attrs.x_scale : Figure._get_scale(x_range, x_axis_type) const y_scale = attrs.y_scale != null ? attrs.y_scale : Figure._get_scale(y_range, y_axis_type) delete attrs.x_scale delete attrs.y_scale super({...attrs, x_range, y_range, x_scale, y_scale}) this._process_axis_and_grid(x_axis_type, x_axis_location, x_minor_ticks, x_axis_label, x_range, 0) this._process_axis_and_grid(y_axis_type, y_axis_location, y_minor_ticks, y_axis_label, y_range, 1) this.add_tools(...this._process_tools(tools)) } get coordinates(): CoordinateMapping | null { return null } subplot(coordinates: ICoordinateMapping): SubFigure { const mapping = new CoordinateMapping(coordinates) return new SubFigure(mapping, this) } _pop_visuals(cls: Class<HasProps>, props: Attrs, prefix: string = "", defaults: Attrs = {}, override_defaults: Attrs = {}): Attrs { const _split_feature_trait = function(ft: string): string[] { const fta: string[] = ft.split("_", 2) return fta.length == 2 ? fta : fta.concat([""]) } const _is_visual = function(ft: string): boolean { const [feature, trait] = _split_feature_trait(ft) return includes(["line", "fill", "hatch", "text", "global"], feature) && trait !== "" } defaults = {...defaults} if (!hasOwnProperty.call(defaults, "text_color")) { defaults.text_color = "black" } if (!hasOwnProperty.call(defaults, "hatch_color")) { defaults.hatch_color = "black" } const trait_defaults: Attrs = {} if (!hasOwnProperty.call(trait_defaults, "color")) { trait_defaults.color = _default_color } if (!hasOwnProperty.call(trait_defaults, "alpha")) { trait_defaults.alpha = _default_alpha } const result: Attrs = {} const traits = new Set() for (const pname of keys(cls.prototype._props)) { if (_is_visual(pname)) { const trait = _split_feature_trait(pname)[1] if (hasOwnProperty.call(props, prefix + pname)) { result[pname] = props[prefix + pname] delete props[prefix + pname] } else if (!hasOwnProperty.call(cls.prototype._props, trait) && hasOwnProperty.call(props, prefix + trait)) { result[pname] = props[prefix + trait] } else if (hasOwnProperty.call(override_defaults, trait)) { result[pname] = override_defaults[trait] } else if (hasOwnProperty.call(defaults, pname)) { result[pname] = defaults[pname] } else if (hasOwnProperty.call(trait_defaults, trait)) { result[pname] = trait_defaults[trait] } if (!hasOwnProperty.call(cls.prototype._props, trait)) { traits.add(trait) } } } for (const name of traits) { delete props[prefix + name] } return result } _find_uniq_name(data: Data, name: string): string { let i = 1 while (true) { const new_name = `${name}__${i}` if (data[new_name] != null) { i += 1 } else { return new_name } } } _fixup_values(cls: Class<HasProps>, data: Data, attrs: Attrs): Set<string> { const unresolved_attrs = new Set<string>() for (const [name, value] of entries(attrs)) { const prop = cls.prototype._props[name] if (prop != null) { if (prop.type.prototype instanceof VectorSpec) { if (value != null) { if (isArray(value) || nd.is_NDArray(value)) { let field if (data[name] != null) { if (data[name] !== value) { field = this._find_uniq_name(data, name) data[field] = value } else { field = name } } else { field = name data[field] = value } attrs[name] = {field} } else if (isNumber(value) || isString(value)) { // or Date? attrs[name] = {value} } } if (prop.type.prototype instanceof UnitsSpec) { const units_attr = `${name}_units` const units = attrs[units_attr] if (units !== undefined) { attrs[name] = {...attrs[name] as any, units} unresolved_attrs.delete(units_attr) delete attrs[units_attr] } } } } else unresolved_attrs.add(name) } return unresolved_attrs } _glyph<G extends Glyph>(cls: Class<G>, positional: NamesOf<G>, args: unknown[], overrides: object = {}): TypedGlyphRenderer<G> { let attrs: Attrs & Partial<AuxGlyph> if (args.length == 0) { attrs = {} } else if (args.length == 1) { attrs = {...args[0] as Attrs} } else { if (args.length == positional.length) attrs = {} else attrs = {...args[args.length - 1] as Attrs} for (const [param, i] of enumerate(positional)) { attrs[param as string] = args[i] } } attrs = {...attrs, ...overrides} const source = (() => { const {source} = attrs if (source == null) return new ColumnDataSource() else if (source instanceof ColumnarDataSource) return source else return new ColumnDataSource({data: source}) })() const data = clone(source.data) delete attrs.source const view = attrs.view != null ? attrs.view : new CDSView({source}) delete attrs.view const legend = attrs.legend delete attrs.legend const legend_label = attrs.legend_label delete attrs.legend_label const legend_field = attrs.legend_field delete attrs.legend_field const legend_group = attrs.legend_group delete attrs.legend_group if ([legend, legend_label, legend_field, legend_group].filter((arg) => arg != null).length > 1) throw new Error("only one of legend, legend_label, legend_field, legend_group can be specified") const name = attrs.name delete attrs.name const level = attrs.level delete attrs.level const visible = attrs.visible delete attrs.visible const x_range_name = attrs.x_range_name delete attrs.x_range_name const y_range_name = attrs.y_range_name delete attrs.y_range_name const coordinates = attrs.coordinates delete attrs.coordinates const glyph_ca = this._pop_visuals(cls, attrs) const nglyph_ca = this._pop_visuals(cls, attrs, "nonselection_", glyph_ca, {alpha: 0.1}) const sglyph_ca = this._pop_visuals(cls, attrs, "selection_", glyph_ca) const hglyph_ca = this._pop_visuals(cls, attrs, "hover_", glyph_ca) const mglyph_ca = this._pop_visuals(cls, attrs, "muted_", glyph_ca, {alpha: 0.2}) this._fixup_values(cls, data, glyph_ca) this._fixup_values(cls, data, nglyph_ca) this._fixup_values(cls, data, sglyph_ca) this._fixup_values(cls, data, hglyph_ca) this._fixup_values(cls, data, mglyph_ca) this._fixup_values(cls, data, attrs) source.data = data const _make_glyph = (cls: Class<Glyph>, attrs: Attrs, extra_attrs: Attrs) => { return new cls({...attrs, ...extra_attrs}) } const glyph = _make_glyph(cls, attrs, glyph_ca) const nglyph = !is_empty(nglyph_ca) ? _make_glyph(cls, attrs, nglyph_ca) : "auto" const sglyph = !is_empty(sglyph_ca) ? _make_glyph(cls, attrs, sglyph_ca) : "auto" const hglyph = !is_empty(hglyph_ca) ? _make_glyph(cls, attrs, hglyph_ca) : undefined const mglyph = !is_empty(mglyph_ca) ? _make_glyph(cls, attrs, mglyph_ca) : "auto" const glyph_renderer = new GlyphRenderer({ data_source: source, view, glyph, nonselection_glyph: nglyph, selection_glyph: sglyph, hover_glyph: hglyph, muted_glyph: mglyph, name, level, visible, x_range_name, y_range_name, coordinates, }) if (legend_label != null) this._handle_legend_label(legend_label, this.legend, glyph_renderer) if (legend_field != null) this._handle_legend_field(legend_field, this.legend, glyph_renderer) if (legend_group != null) this._handle_legend_group(legend_group, this.legend, glyph_renderer) this.add_renderers(glyph_renderer) return glyph_renderer as TypedGlyphRenderer<G> } static _get_range(range?: Range | [number, number] | ArrayLike<string>): Range { if (range == null) { return new DataRange1d() } if (range instanceof Range) { return range } if (isArray(range)) { if (isArrayOf(range, isString)) { const factors = range return new FactorRange({factors}) } else { const [start, end] = range return new Range1d({start, end}) } } throw new Error(`unable to determine proper range for: '${range}'`) } static _get_scale(range_input: Range, axis_type: AxisType): Scale { if (range_input instanceof DataRange1d || range_input instanceof Range1d) { switch (axis_type) { case null: case "auto": case "linear": case "datetime": case "mercator": return new LinearScale() case "log": return new LogScale() } } if (range_input instanceof FactorRange) { return new CategoricalScale() } throw new Error(`unable to determine proper scale for: '${range_input}'`) } _process_axis_and_grid(axis_type: AxisType, axis_location: Location, minor_ticks: number | "auto" | undefined, axis_label: Axis["axis_label"], rng: Range, dim: 0 | 1): void { const axis = this._get_axis(axis_type, rng, dim) if (axis != null) { if (axis instanceof LogAxis) { if (dim == 0) { this.x_scale = new LogScale() } else { this.y_scale = new LogScale() } } if (axis.ticker instanceof ContinuousTicker) { axis.ticker.num_minor_ticks = this._get_num_minor_ticks(axis, minor_ticks) } axis.axis_label = axis_label const grid = new Grid({dimension: dim, ticker: axis.ticker}) if (axis_location !== null) { this.add_layout(axis, axis_location) } this.add_layout(grid) } } _get_axis(axis_type: AxisType, range: Range, dim: 0 | 1): Axis | null { switch (axis_type) { case null: return null case "linear": return new LinearAxis() case "log": return new LogAxis() case "datetime": return new DatetimeAxis() case "mercator": { const axis = new MercatorAxis() const dimension = dim == 0 ? "lon" : "lat" axis.ticker.dimension = dimension axis.formatter.dimension = dimension return axis } case "auto": if (range instanceof FactorRange) return new CategoricalAxis() else return new LinearAxis() // TODO: return DatetimeAxis (Date type) default: throw new Error("shouldn't have happened") } } _get_num_minor_ticks(axis: Axis, num_minor_ticks?: number | "auto"): number { if (isNumber(num_minor_ticks)) { if (num_minor_ticks <= 1) { throw new Error("num_minor_ticks must be > 1") } return num_minor_ticks } if (num_minor_ticks == null) { return 0 } if (num_minor_ticks === "auto") { return axis instanceof LogAxis ? 10 : 5 } throw new Error("shouldn't have happened") } _process_tools(tools: (Tool | string)[] | string): Tool[] { if (isString(tools)) tools = tools.split(/\s*,\s*/).filter((tool) => tool.length > 0) return tools.map((tool) => isString(tool) ? Tool.from_string(tool) : tool) } _update_legend(legend_item_label: Vector<string>, glyph_renderer: GlyphRenderer): void { const {legend} = this let added = false for (const item of legend.items) { if (item.label != null && is_equal(item.label, legend_item_label)) { // XXX: remove this when vectorable properties are refined const label = item.label as Value<string> | Field if ("value" in label) { item.renderers.push(glyph_renderer) added = true break } if ("field" in label && glyph_renderer.data_source == item.renderers[0].data_source) { item.renderers.push(glyph_renderer) added = true break } } } if (!added) { const new_item = new LegendItem({label: legend_item_label, renderers: [glyph_renderer]}) legend.items.push(new_item) } } protected _handle_legend_label(value: string, legend: Legend, glyph_renderer: GlyphRenderer): void { const label = {value} const item = this._find_legend_item(label, legend) if (item != null) item.renderers.push(glyph_renderer) else { const new_item = new LegendItem({label, renderers: [glyph_renderer]}) legend.items.push(new_item) } } protected _handle_legend_field(field: string, legend: Legend, glyph_renderer: GlyphRenderer): void { const label = {field} const item = this._find_legend_item(label, legend) if (item != null) item.renderers.push(glyph_renderer) else { const new_item = new LegendItem({label, renderers: [glyph_renderer]}) legend.items.push(new_item) } } protected _handle_legend_group(name: string, legend: Legend, glyph_renderer: GlyphRenderer): void { const source = glyph_renderer.data_source if (source == null) throw new Error("cannot use 'legend_group' on a glyph without a data source already configured") if (!(name in source.data)) throw new Error("column to be grouped does not exist in glyph data source") const column = [...source.data[name]] const values = uniq(column).sort() for (const value of values) { const label = {value: `${value}`} const index = column.indexOf(value) const new_item = new LegendItem({label, renderers: [glyph_renderer], index}) legend.items.push(new_item) } } protected _find_legend_item(label: Vector<string>, legend: Legend): LegendItem | null { const cmp = new Comparator() for (const item of legend.items) { if (cmp.eq(item.label, label)) return item } return null } } export function figure(attributes?: Partial<Figure.Attrs>): Figure { return new Figure(attributes) }
the_stack
import * as Table from 'cli-table3' import { produce } from 'immer' import * as ora from 'ora' import * as marked from 'marked' import * as TerminalRenderer from 'marked-terminal' import * as wrap from 'wordwrap' import * as logger from '../../logger' import { afterHooks, beforeHooks } from '../../hooks' import { askUserToPaginate, handlePagination } from '../../utils' import { printPullInfo, STATUSES, testing, getPullRequest } from './index' const SORT_COMPLEXITY = 'complexity' const DIRECTION_DESC = 'desc' const DIRECTION_ASC = 'asc' const SORT_CREATED = 'created' const spinner = ora({ text: 'Fetching Pull Requests', discardStdin: false }) export async function listHandler(options) { await beforeHooks('pull-request.list', { options }) let who options = produce(options, draft => { draft.sort = draft.sort || SORT_CREATED draft.direction = draft.direction || DIRECTION_DESC }) if (options.all) { who = options.user if (options.org) { who = options.org } logger.log(`Listing all ${options.state} pull requests for ${logger.colors.green(who)}`) try { await listFromAllRepositories(options) } catch (err) { throw new Error(`Can't list all pull requests from repos.\n${err}`) } } else { if (options.me) { logger.log( `Listing ${options.state} pull requests sent by ${logger.colors.green( options.loggedUser )} on ${logger.colors.green(`${options.user}/${options.repo}`)}` ) } else { logger.log( `Listing ${options.state} pull requests on ${logger.colors.green( `${options.user}/${options.repo}` )}` ) } try { await list(options) } catch (err) { throw new Error(`Can't list pull requests.\n${err}`) } } await afterHooks('pull-request.list', { options }) } async function list(options) { spinner.start() const { user, repo, page = 1, pageSize, config } = options let sortType = options.sort if (sortType === SORT_COMPLEXITY) { sortType = SORT_CREATED } const payload = { repo, sort: sortType, owner: user, direction: options.direction, state: options.state, page, per_page: pageSize, } const { data, hasNextPage } = await handlePagination({ options, listEndpoint: options.GitHub.pulls.list, payload, }) let pulls = data if (options.me) { pulls = filterPullsSentByMe_(options, pulls) } if (sortType && sortType === SORT_COMPLEXITY) { try { pulls = await addComplexityParamToPulls_(options, pulls) } catch (err) { throw new Error(`Error sorting by complexity\n${err}`) } pulls = sortPullsByComplexity_(pulls, options.direction) } pulls = await Promise.all( pulls.map(async function mapStatus(pull) { const statusPayload = { repo, owner: user, ref: pull.head.sha, } try { var { data } = await options.GitHub.repos.getCombinedStatusForRef(statusPayload) } catch (err) { throw new Error(`Error getting combined status for ref\n${err}`) } return { ...pull, combinedStatus: data.state } }) ) const json = getPullsTemplateJson_(options, pulls) const currentUserRepo = logger.colors.yellow(`${user}/${repo}`) spinner.stop() if (pulls.length) { logger.log(currentUserRepo) json.branches.forEach((branch, index, arr) => { logger.log(`${logger.colors.blue('Branch:')} ${branch.name} (${branch.total})`) const printTableView = config.pretty_print === undefined || Boolean(config.pretty_print) if (printTableView) { printPullsInfoTable_(options, branch.pulls) } else { branch.pulls.forEach(pull => printPullInfo(options, pull)) } if (index !== arr.length - 1) { logger.log('') } }) if (options.all) { logger.log('') } } if (hasNextPage) { const continuePaginating = await askUserToPaginate(`Pull Requests for ${currentUserRepo}`) continuePaginating && (await list({ ...options, user, repo, page: page + 1 })) } return } async function listFromAllRepositories(options) { let apiMethod const payload: any = { type: 'all', owner: options.user, } if (options.org) { apiMethod = 'listForOrg' payload.org = options.org } else { apiMethod = 'listForUser' payload.username = options.user } try { var repositories = await options.GitHub.paginate( options.GitHub.repos[apiMethod].endpoint(payload) ) } catch (err) { throw new Error(`Error listing repos`) } for (const repo of repositories) { await list({ ...options, user: repo.owner.login, repo: repo.name }) } } async function addComplexityParamToPulls_(options, pulls) { return Promise.all( pulls.map(async pull => { options = produce(options, draft => { draft.number = pull.number }) try { var { data } = await getPullRequest(options) } catch (err) { throw new Error(`Error getting PR\n${err}`) } const metrics = { additions: data.additions, changedFiles: data.changed_files, comments: data.comments, deletions: data.deletions, reviewComments: data.review_comments, } pull.complexity = calculateComplexity_(metrics) return pull }) ) } function calculateComplexity_(metrics): number { const weightAddition = 2 const weightChangedFile = 2 const weightComment = 2 const weightDeletion = 2 const weightReviewComment = 1 const complexity = metrics.additions * weightAddition + metrics.changedFiles * weightChangedFile + metrics.comments * weightComment + metrics.deletions * weightDeletion + metrics.reviewComments * weightReviewComment return complexity } function filterPullsSentByMe_(options, pulls) { return pulls.filter(pull => { if (options.loggedUser === pull.user.login) { return pull } }) } function getPullsTemplateJson_(options, pulls) { let branch const branches = {} const json = { branches: [], } pulls.forEach(pull => { branch = pull.base.ref if (!options.branch || options.branch === branch) { branches[branch] = branches[branch] || [] branches[branch].push(pull) } }) Object.keys(branches).forEach(branch => { json.branches.push({ name: branch, pulls: branches[branch], total: branches[branch].length, }) }) return json } function printPullsInfoTable_(options, pulls) { const showDetails = options.info || options.detailed logger.log(generateTable()) function generateTable(): string { const isCompact = process.stdout.columns < 100 && !testing const tableWidths = getColWidths(isCompact) const table = new Table({ colWidths: tableWidths, }) as Table.HorizontalTable type TCell = ( | string | { content: string hAlign: Table.HorizontalAlignment })[] let tableHead: TCell = [ { content: '#', hAlign: 'center' }, showDetails ? 'Details' : 'Title', 'Author', 'Opened', 'Status', ] if (isCompact) { tableHead = remove2ndItem(tableHead) } tableHead = tableHead.map(heading => { if (typeof heading === 'string') { return logger.colors.red(heading) } return { content: logger.colors.red(heading.content), hAlign: heading.hAlign } }) table.push(tableHead) pulls.forEach(pull => { const { createdTime, number, prInfo, user, status } = getColorizedFields( pull, isCompact ? getTotalWidth() : tableWidths[1], options.date ) const body: TCell = [ { content: number, hAlign: 'center' }, prInfo, user, createdTime, { content: status, hAlign: 'center' }, ] if (isCompact) { table.push(remove2ndItem(body)) const titleLabel = showDetails ? '' : logger.colors.blue('Title:') table.push([{ colSpan: 4, content: `${titleLabel} ${prInfo}\n`.trim() }]) } else { table.push(body) } }) return table.toString() } function getColorizedFields(pull, length, dateFormatter) { const createdTime = logger.getDuration(pull.created_at, dateFormatter) const number = logger.colors.green(`#${pull.number}`) const prInfo = formatPrInfo(pull, length) const user = logger.colors.magenta(`@${pull.user.login}`) const status = STATUSES[pull.combinedStatus] return { createdTime, number, prInfo, user, status } } function getTotalWidth(): number { const padding = 6 const terminalCols = process.stdout.columns - padding return testing ? 100 : terminalCols } function getColWidths(compact: boolean): number[] { const totalWidth = getTotalWidth() const dateCol = 15 const noCol = 9 const statusCol = 8 const authorCol = compact ? totalWidth - dateCol - noCol - statusCol : 21 const titleCol = totalWidth - authorCol - dateCol - noCol - statusCol let colWidths = [noCol, titleCol, authorCol, dateCol, statusCol] if (compact) { colWidths = remove2ndItem(colWidths) } return colWidths.map(col => Math.floor(col)) } function formatPrInfo(pull, length) { const paddedLength = length - 5 const title = wrap(paddedLength)(pull.title) const labels = pull.labels.length > 0 && pull.labels.map(label => label.name).join(', ') const singularOrPlural = labels && pull.labels.length > 1 ? 's' : '' const formattedLabels = labels ? logger.colors.yellow(`\nLabel${singularOrPlural}: ${labels}`) : '' let info = `${title}${formattedLabels}` if (showDetails) { marked.setOptions({ renderer: new TerminalRenderer({ reflowText: true, width: paddedLength, }), }) info = ` ${logger.colors.blue('Title:')} ${title} ${formattedLabels.split('\n')[1] || ''} ${logger.colors.blue('Body:')} ${marked(pull.body || 'N/A')} ` } if (options.link || showDetails) { info = ` ${info} ${logger.colors.cyan(pull.html_url)} ` } return info .replace(/ +/gm, '') .replace(/(\n\n\n)/gm, '\n') .trim() } function remove2ndItem(arr: any[]): any[] { return [arr[0], ...arr.slice(2)] } } function sortPullsByComplexity_(pulls, direction) { pulls.sort((a, b) => { if (a.complexity > b.complexity) { return -1 } if (a.complexity < b.complexity) { return +1 } return 0 }) if (direction === DIRECTION_ASC) { pulls.reverse() } return pulls }
the_stack
import { ValueCell } from '../../../mol-util'; import { Mat4, Vec3, Vec4 } from '../../../mol-math/linear-algebra'; import { transformPositionArray, GroupMapping, createGroupMapping } from '../../util'; import { GeometryUtils } from '../geometry'; import { createColors } from '../color-data'; import { createMarkers } from '../marker-data'; import { createSizes, getMaxSize } from '../size-data'; import { TransformData } from '../transform-data'; import { LocationIterator, PositionLocation } from '../../util/location-iterator'; import { ParamDefinition as PD } from '../../../mol-util/param-definition'; import { calculateInvariantBoundingSphere, calculateTransformBoundingSphere } from '../../../mol-gl/renderable/util'; import { Sphere3D } from '../../../mol-math/geometry'; import { Theme } from '../../../mol-theme/theme'; import { Color } from '../../../mol-util/color'; import { BaseGeometry } from '../base'; import { createEmptyOverpaint } from '../overpaint-data'; import { createEmptyTransparency } from '../transparency-data'; import { hashFnv32a } from '../../../mol-data/util'; import { createEmptyClipping } from '../clipping-data'; import { CylindersValues } from '../../../mol-gl/renderable/cylinders'; import { RenderableState } from '../../../mol-gl/renderable'; export interface Cylinders { readonly kind: 'cylinders', /** Number of cylinders */ cylinderCount: number, /** Mapping buffer as array of uvw values wrapped in a value cell */ readonly mappingBuffer: ValueCell<Float32Array>, /** Index buffer as array of vertex index triplets wrapped in a value cell */ readonly indexBuffer: ValueCell<Uint32Array>, /** Group buffer as array of group ids for each vertex wrapped in a value cell */ readonly groupBuffer: ValueCell<Float32Array>, /** Cylinder start buffer as array of xyz values wrapped in a value cell */ readonly startBuffer: ValueCell<Float32Array>, /** Cylinder end buffer as array of xyz values wrapped in a value cell */ readonly endBuffer: ValueCell<Float32Array>, /** Cylinder scale buffer as array of scaling factors wrapped in a value cell */ readonly scaleBuffer: ValueCell<Float32Array>, /** Cylinder cap buffer as array of cap flags wrapped in a value cell */ readonly capBuffer: ValueCell<Float32Array>, /** Bounding sphere of the cylinders */ readonly boundingSphere: Sphere3D /** Maps group ids to cylinder indices */ readonly groupMapping: GroupMapping setBoundingSphere(boundingSphere: Sphere3D): void } export namespace Cylinders { export function create(mappings: Float32Array, indices: Uint32Array, groups: Float32Array, starts: Float32Array, ends: Float32Array, scales: Float32Array, caps: Float32Array, cylinderCount: number, cylinders?: Cylinders): Cylinders { return cylinders ? update(mappings, indices, groups, starts, ends, scales, caps, cylinderCount, cylinders) : fromArrays(mappings, indices, groups, starts, ends, scales, caps, cylinderCount); } export function createEmpty(cylinders?: Cylinders): Cylinders { const mb = cylinders ? cylinders.mappingBuffer.ref.value : new Float32Array(0); const ib = cylinders ? cylinders.indexBuffer.ref.value : new Uint32Array(0); const gb = cylinders ? cylinders.groupBuffer.ref.value : new Float32Array(0); const sb = cylinders ? cylinders.startBuffer.ref.value : new Float32Array(0); const eb = cylinders ? cylinders.endBuffer.ref.value : new Float32Array(0); const ab = cylinders ? cylinders.scaleBuffer.ref.value : new Float32Array(0); const cb = cylinders ? cylinders.capBuffer.ref.value : new Float32Array(0); return create(mb, ib, gb, sb, eb, ab, cb, 0, cylinders); } function hashCode(cylinders: Cylinders) { return hashFnv32a([ cylinders.cylinderCount, cylinders.mappingBuffer.ref.version, cylinders.indexBuffer.ref.version, cylinders.groupBuffer.ref.version, cylinders.startBuffer.ref.version, cylinders.endBuffer.ref.version, cylinders.scaleBuffer.ref.version, cylinders.capBuffer.ref.version ]); } function fromArrays(mappings: Float32Array, indices: Uint32Array, groups: Float32Array, starts: Float32Array, ends: Float32Array, scales: Float32Array, caps: Float32Array, cylinderCount: number): Cylinders { const boundingSphere = Sphere3D(); let groupMapping: GroupMapping; let currentHash = -1; let currentGroup = -1; const cylinders = { kind: 'cylinders' as const, cylinderCount, mappingBuffer: ValueCell.create(mappings), indexBuffer: ValueCell.create(indices), groupBuffer: ValueCell.create(groups), startBuffer: ValueCell.create(starts), endBuffer: ValueCell.create(ends), scaleBuffer: ValueCell.create(scales), capBuffer: ValueCell.create(caps), get boundingSphere() { const newHash = hashCode(cylinders); if (newHash !== currentHash) { const s = calculateInvariantBoundingSphere(cylinders.startBuffer.ref.value, cylinders.cylinderCount * 6, 6); const e = calculateInvariantBoundingSphere(cylinders.endBuffer.ref.value, cylinders.cylinderCount * 6, 6); Sphere3D.expandBySphere(boundingSphere, s, e); currentHash = newHash; } return boundingSphere; }, get groupMapping() { if (cylinders.groupBuffer.ref.version !== currentGroup) { groupMapping = createGroupMapping(cylinders.groupBuffer.ref.value, cylinders.cylinderCount, 6); currentGroup = cylinders.groupBuffer.ref.version; } return groupMapping; }, setBoundingSphere(sphere: Sphere3D) { Sphere3D.copy(boundingSphere, sphere); currentHash = hashCode(cylinders); } }; return cylinders; } function update(mappings: Float32Array, indices: Uint32Array, groups: Float32Array, starts: Float32Array, ends: Float32Array, scales: Float32Array, caps: Float32Array, cylinderCount: number, cylinders: Cylinders) { if (cylinderCount > cylinders.cylinderCount) { ValueCell.update(cylinders.mappingBuffer, mappings); ValueCell.update(cylinders.indexBuffer, indices); } cylinders.cylinderCount = cylinderCount; ValueCell.update(cylinders.groupBuffer, groups); ValueCell.update(cylinders.startBuffer, starts); ValueCell.update(cylinders.endBuffer, ends); ValueCell.update(cylinders.scaleBuffer, scales); ValueCell.update(cylinders.capBuffer, caps); return cylinders; } export function transform(cylinders: Cylinders, t: Mat4) { const start = cylinders.startBuffer.ref.value; transformPositionArray(t, start, 0, cylinders.cylinderCount * 6); ValueCell.update(cylinders.startBuffer, start); const end = cylinders.endBuffer.ref.value; transformPositionArray(t, end, 0, cylinders.cylinderCount * 6); ValueCell.update(cylinders.endBuffer, end); } // export const Params = { ...BaseGeometry.Params, sizeFactor: PD.Numeric(1, { min: 0, max: 10, step: 0.1 }), sizeAspectRatio: PD.Numeric(1, { min: 0, max: 3, step: 0.01 }), doubleSided: PD.Boolean(false, BaseGeometry.CustomQualityParamInfo), ignoreLight: PD.Boolean(false, BaseGeometry.ShadingCategory), xrayShaded: PD.Boolean(false, BaseGeometry.ShadingCategory), }; export type Params = typeof Params export const Utils: GeometryUtils<Cylinders, Params> = { Params, createEmpty, createValues, createValuesSimple, updateValues, updateBoundingSphere, createRenderableState, updateRenderableState, createPositionIterator }; function createPositionIterator(cylinders: Cylinders, transform: TransformData): LocationIterator { const groupCount = cylinders.cylinderCount * 6; const instanceCount = transform.instanceCount.ref.value; const location = PositionLocation(); const p = location.position; const s = cylinders.startBuffer.ref.value; const e = cylinders.endBuffer.ref.value; const m = transform.aTransform.ref.value; const getLocation = (groupIndex: number, instanceIndex: number) => { const v = groupIndex % 6 === 0 ? s : e; if (instanceIndex < 0) { Vec3.fromArray(p, v, groupIndex * 3); } else { Vec3.transformMat4Offset(p, v, m, 0, groupIndex * 3, instanceIndex * 16); } return location; }; return LocationIterator(groupCount, instanceCount, 2, getLocation); } function createValues(cylinders: Cylinders, transform: TransformData, locationIt: LocationIterator, theme: Theme, props: PD.Values<Params>): CylindersValues { const { instanceCount, groupCount } = locationIt; const positionIt = createPositionIterator(cylinders, transform); const color = createColors(locationIt, positionIt, theme.color); const size = createSizes(locationIt, theme.size); const marker = createMarkers(instanceCount * groupCount); const overpaint = createEmptyOverpaint(); const transparency = createEmptyTransparency(); const clipping = createEmptyClipping(); const counts = { drawCount: cylinders.cylinderCount * 4 * 3, vertexCount: cylinders.cylinderCount * 6, groupCount, instanceCount }; const padding = getMaxSize(size) * props.sizeFactor; const invariantBoundingSphere = Sphere3D.clone(cylinders.boundingSphere); const boundingSphere = calculateTransformBoundingSphere(invariantBoundingSphere, transform.aTransform.ref.value, instanceCount); return { aMapping: cylinders.mappingBuffer, aGroup: cylinders.groupBuffer, aStart: cylinders.startBuffer, aEnd: cylinders.endBuffer, aScale: cylinders.scaleBuffer, aCap: cylinders.capBuffer, elements: cylinders.indexBuffer, boundingSphere: ValueCell.create(boundingSphere), invariantBoundingSphere: ValueCell.create(invariantBoundingSphere), uInvariantBoundingSphere: ValueCell.create(Vec4.ofSphere(invariantBoundingSphere)), ...color, ...size, ...marker, ...overpaint, ...transparency, ...clipping, ...transform, padding: ValueCell.create(padding), ...BaseGeometry.createValues(props, counts), uSizeFactor: ValueCell.create(props.sizeFactor * props.sizeAspectRatio), dDoubleSided: ValueCell.create(props.doubleSided), dIgnoreLight: ValueCell.create(props.ignoreLight), dXrayShaded: ValueCell.create(props.xrayShaded), }; } function createValuesSimple(cylinders: Cylinders, props: Partial<PD.Values<Params>>, colorValue: Color, sizeValue: number, transform?: TransformData) { const s = BaseGeometry.createSimple(colorValue, sizeValue, transform); const p = { ...PD.getDefaultValues(Params), ...props }; return createValues(cylinders, s.transform, s.locationIterator, s.theme, p); } function updateValues(values: CylindersValues, props: PD.Values<Params>) { BaseGeometry.updateValues(values, props); ValueCell.updateIfChanged(values.uSizeFactor, props.sizeFactor * props.sizeAspectRatio); ValueCell.updateIfChanged(values.dDoubleSided, props.doubleSided); ValueCell.updateIfChanged(values.dIgnoreLight, props.ignoreLight); ValueCell.updateIfChanged(values.dXrayShaded, props.xrayShaded); } function updateBoundingSphere(values: CylindersValues, cylinders: Cylinders) { const invariantBoundingSphere = Sphere3D.clone(cylinders.boundingSphere); const boundingSphere = calculateTransformBoundingSphere(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value); if (!Sphere3D.equals(boundingSphere, values.boundingSphere.ref.value)) { ValueCell.update(values.boundingSphere, boundingSphere); } if (!Sphere3D.equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) { ValueCell.update(values.invariantBoundingSphere, invariantBoundingSphere); ValueCell.update(values.uInvariantBoundingSphere, Vec4.fromSphere(values.uInvariantBoundingSphere.ref.value, invariantBoundingSphere)); } } function createRenderableState(props: PD.Values<Params>): RenderableState { const state = BaseGeometry.createRenderableState(props); updateRenderableState(state, props); return state; } function updateRenderableState(state: RenderableState, props: PD.Values<Params>) { BaseGeometry.updateRenderableState(state, props); state.opaque = state.opaque && !props.xrayShaded; state.writeDepth = state.opaque; } }
the_stack
import { User } from "../store/types"; type APIResourceType = | "user" | "matchmakingRequest" | "matchedUser" | "session" | "app" | "multisigDeploy"; type APIError = { status: HttpStatusCode; code: ErrorCode; title: string; detail: string; }; type APIResource<T = APIResourceAttributes> = { type: APIResourceType; id?: string; attributes: T; relationships?: APIResourceRelationships; }; type APIResourceAttributes = { [key: string]: string | number | boolean | undefined; }; type APIResourceRelationships = { [key in APIResourceType]?: APIDataContainer }; type APIDataContainer<T = APIResourceAttributes> = { data: APIResource<T> | APIResourceCollection<T>; }; type APIResourceCollection<T = APIResourceAttributes> = APIResource<T>[]; type APIResponse<T = APIResourceAttributes> = APIDataContainer<T> & { errors?: APIError[]; meta?: APIMetadata; included?: APIResourceCollection; }; enum ErrorCode { SignatureRequired = "signature_required", InvalidSignature = "invalid_signature", AddressAlreadyRegistered = "address_already_registered", AppRegistryNotAvailable = "app_registry_not_available", UserAddressRequired = "user_address_required", NoUsersAvailable = "no_users_available", UnhandledError = "unhandled_error", UserNotFound = "user_not_found", TokenRequired = "token_required", InvalidToken = "invalid_token", UsernameAlreadyExists = "username_already_exists" } export const CounterfactualErrorCodeDetail = { signature_required: { code: "signature_required", message: "A Signature is required", field: "" }, invalid_signature: { code: "invalid_signature", message: "Ups, something is wrong with the signature", field: "" }, address_already_registered: { code: "address_already_registered", message: "The address has already been registered, please login instead", field: "" }, app_registry_not_available: { code: "app_registry_not_available", message: "The registry is not available right now", field: "" }, user_address_required: { code: "user_address_required", message: "The user address is required for this operation", field: "" }, no_users_available: { code: "no_users_available", message: "No users are available", field: "" }, unhandled_error: { code: "unhandled_error", message: "Something broke! Error not handled", field: "" }, user_not_found: { code: "user_not_found", message: "The user is just not there", field: "" }, token_required: { code: "token_required", message: "A token is required", field: "" }, invalid_token: { code: "invalid_token", message: "Something is wrong with that token", field: "" }, username_already_exists: { code: "username_already_exists", message: "That username already exists, sorry", field: "username" } }; export const ErrorDetail = { "-32603": CounterfactualErrorCodeDetail.signature_required, ...CounterfactualErrorCodeDetail }; enum HttpStatusCode { OK = 200, Created = 201, BadRequest = 400, Unauthorized = 401, Forbidden = 403, InternalServerError = 500 } type APIMetadata = { [key: string]: string | number | boolean | APIMetadata; }; type APIRequest<T = APIResourceAttributes> = { data?: APIResource<T> | APIResourceCollection<T>; meta?: APIMetadata; }; const BASE_URL = process.env.REACT_APP_HUB_API_URL || `http://localhost:9000`; const API_TIMEOUT = 30000; function timeout(delay: number = API_TIMEOUT) { const handler = setTimeout(() => { throw new Error("Request timed out"); }, delay); return { cancel() { clearTimeout(handler); } }; } async function request( method: string, endpoint: string, data: APIResource, token?: string, authType: "Bearer" | "Signature" = "Signature" ) { return await fetch(`${BASE_URL}/api/${endpoint}`, { method, ...(["POST", "PUT"].includes(method) ? { body: JSON.stringify({ data } as APIRequest) } : {}), headers: { "Content-Type": "application/json; charset=utf-8", ...(token ? { Authorization: `${authType} ${token}` } : {}) } }); } // async function put( // endpoint: string, // data: APIResource, // token: string // ): Promise<APIResponse> { // const requestTimeout = timeout(); // const httpResponse = await request( // "PUT", // `${endpoint}/${data.id}`, // data, // token // ); // requestTimeout.cancel(); // const response = (await httpResponse.json()) as APIResponse; // if (response.errors) { // const error = response.errors[0] as APIError; // throw error; // } // return response; // } async function post( endpoint: string, data: APIResource, token?: string, authType: "Bearer" | "Signature" = "Signature" ): Promise<APIResponse> { const requestTimeout = timeout(); try { const httpResponse = await request("POST", endpoint, data, token, authType); requestTimeout.cancel(); const response = (await httpResponse.json()) as APIResponse; if (response.errors) { const error = response.errors[0] as APIError; throw error; } return response; } catch (error) { requestTimeout.cancel(); throw error; } } // async function remove( // endpoint: string, // data: APIResource, // token?: string, // authType: "Bearer" | "Signature" = "Signature" // ): Promise<APIResponse> { // const requestTimeout = timeout(); // const httpResponse = await fetch( // `${BASE_URL}/api/${endpoint}/${data.attributes.id}`, // { // method: "DELETE", // headers: { // "Content-Type": "application/json; charset=utf-8", // Authorization: `${authType} ${token}` // } // } // ); // requestTimeout.cancel(); // const response = (await httpResponse.json()) as APIResponse; // if (response.errors) { // const error = response.errors[0] as APIError; // throw error; // } // return response; // } // async function get(endpoint: string, token?: string): Promise<APIResponse> { // const requestTimeout = timeout(); // const httpResponse = await request( // "GET", // endpoint, // {} as APIResource<APIResourceAttributes>, // token, // "Bearer" // ); // requestTimeout.cancel(); // const response = (await httpResponse.json()) as APIResponse; // if (response.errors) { // const error = response.errors[0] as APIError; // throw error; // } // return response; // } // function fromAPIResource<TModel, TResource>( // resource: APIResource<TResource> // ): TModel { // return ({ // id: resource.id, // ...(resource.attributes as {}) // } as unknown) as TModel; // } function toAPIResource<TModel, TResource>( model: TModel ): APIResource<TResource> { return ({ ...(model["id"] ? { id: model["id"] } : {}), attributes: { ...Object.keys(model) .map(key => { return { [key]: model[key] }; }) .reduce((previous, current) => { return { ...previous, ...current }; }, {}) } } as unknown) as APIResource<TResource>; } export default class PlaygroundAPIClient { public static async createAccount( user: User, signature: string ): Promise<User> { try { const data = toAPIResource<User, User>(user); const json = (await post("users", data, signature)) as APIResponse; const resource = json.data as APIResource<User>; const jsonMultisig = (await post("multisig-deploys", { type: "multisigDeploy", attributes: { ethAddress: user.ethAddress } })) as APIResponse; const resourceMultisig = jsonMultisig.data as APIResource<Partial<User>>; resource.attributes.transactionHash = resourceMultisig.id as string; return { ...user, ...(json.data as APIResource).attributes }; } catch (e) { return Promise.reject(e); } } // public static async updateAccount(user: UserChangeset): Promise<UserSession> { // try { // const data = toAPIResource<UserChangeset, UserAttributes>(user); // const json = (await put("users", data, window.localStorage.getItem( // "playground:user:token" // ) as string)) as APIResponse; // const resource = json.data as APIResource<UserAttributes>; // return fromAPIResource<UserSession, UserAttributes>(resource); // } catch (e) { // return Promise.reject(e); // } // } // public static async deleteAccount(user: UserChangeset): Promise<void> { // try { // const data = toAPIResource<UserChangeset, UserAttributes>(user); // await remove("users", data, window.localStorage.getItem( // "playground:user:token" // ) as string); // } catch (e) { // return Promise.reject(e); // } // } public static async login( ethAddress: string, signature: string ): Promise<User> { try { const json = (await post( "session-requests", { type: "session", id: "", attributes: { ethAddress } } as APIResource, signature )) as APIResponse; return { id: (json.data as APIResource).id, ...((json.data as APIResource).attributes as User) }; } catch (e) { return Promise.reject(e); } } // public static async getUser(token: string): Promise<UserSession> { // if (!token) { // throw new Error("getUser(): token is required"); // } // try { // const json = (await get("users/me", token)) as APIResponse; // const resource = json.data[0] as APIResource<UserAttributes>; // return fromAPIResource<UserSession, UserAttributes>(resource); // } catch (e) { // return Promise.reject(e); // } // } // public static async getUserByNodeAddress( // ethAddress: string // ): Promise<UserSession> { // try { // const json = (await get( // `users?filter[node_address]=${ethAddress}` // )) as APIResponse; // const resource = json.data[0] as APIResource<UserAttributes>; // return fromAPIResource<UserSession, UserAttributes>(resource); // } catch (e) { // return Promise.reject(e); // } // } // public static async getApps(): Promise<AppDefinition[]> { // try { // const json = (await get("apps")) as APIResponse; // const resources = json.data as APIResourceCollection<AppAttributes>; // return resources.map(resource => // fromAPIResource<AppDefinition, AppAttributes>(resource) // ); // } catch (e) { // return Promise.reject(e); // } // } // public static async matchmake(token: string, matchmakeWith: string | null) { // try { // return await post( // "matchmaking-requests", // { // type: "matchmakingRequest", // attributes: matchmakeWith ? { matchmakeWith } : {} // }, // token, // "Bearer" // ); // } catch (e) { // return Promise.reject(e); // } // } }
the_stack
import { syntaxHighlighting } from "../documentation"; import { Primitives } from "../../../primitives"; import { ConfigurationGroup } from "../../../configuration-option-types"; import { PropertyLayoutVariants, PropertyTypes, } from "../../../configuration-property"; import { PluginMetadata } from "../../../plugin"; // // // // // React + Next + TS Website Starter // // // // // Landing Page const landingPageConfigurationGroup: ConfigurationGroup = new Primitives.ConfigurationGroup( { // identifier: "home", // content: { // label: "Landing Page", // description: "Configure the landing page of your website", // icon: "", // documentation: "", // }, identifier: "example-properties", content: { label: "Example Properties", description: "Example properties supported by Codotype", icon: "", documentation: "", }, properties: [ new Primitives.ConfigurationProperty({ identifier: "boolean", content: { label: "Boolean Property", description: "Boolean properties can be used to turn specific features on or off", icon: "", documentation: "", }, type: PropertyTypes.BOOLEAN, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), new Primitives.ConfigurationProperty({ identifier: "text", content: { label: "Text Property", description: "Text properties can be used to populate string values in your boilerplate code", icon: "", documentation: "", }, type: PropertyTypes.STRING, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), new Primitives.ConfigurationProperty({ identifier: "number", content: { label: "Number Property", description: "Number properties can be used to populate numeric values in your boilerplate code", icon: "", documentation: "", }, type: PropertyTypes.NUMBER, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), new Primitives.ConfigurationProperty({ identifier: "dropdown", content: { label: "Dropdown Property", description: "Dropdown properties can be used to select predefined values to change your boilerplate code", icon: "", documentation: "", }, type: PropertyTypes.DROPDOWN, selectOptions: [{ value: "one", label: "One" }], layoutVariant: PropertyLayoutVariants.CARD_COL_6, }), new Primitives.ConfigurationProperty({ identifier: "instance", content: { label: "Instance", description: "Instance properties can be used define nested key / value configuration", icon: "", documentation: "", }, type: PropertyTypes.INSTANCE, layoutVariant: PropertyLayoutVariants.CARD_COL_6, properties: [ new Primitives.ConfigurationProperty({ identifier: "text", content: { label: "Text Property", description: "Text properties can be used to populate string values in your boilerplate code", icon: "", documentation: "", }, type: PropertyTypes.STRING, }), new Primitives.ConfigurationProperty({ identifier: "boolean", content: { label: "Boolean Property", description: "Boolean properties can be used to turn specific features on or off", icon: "", documentation: "", }, type: PropertyTypes.BOOLEAN, }), ], }), new Primitives.ConfigurationProperty({ identifier: "collection", content: { label: "Collection", description: "Collection properties can be used define an array of nested key / value objects", icon: "", documentation: "", }, type: PropertyTypes.COLLECTION, layoutVariant: PropertyLayoutVariants.CARD_COL_6, properties: [ new Primitives.ConfigurationProperty({ identifier: "text", content: { label: "Text Property", description: "Text properties can be used to populate string values in your boilerplate code", icon: "", documentation: "", }, type: PropertyTypes.STRING, }), ], }), ], }, ); // // // // // Analytics const analyticsConfigurationGroup: ConfigurationGroup = new Primitives.ConfigurationGroup( { identifier: "analytics", content: { label: "Analytics", description: "Configure the analytics of your website", icon: "", documentation: "", }, properties: [ new Primitives.ConfigurationProperty({ identifier: "googleAnalytics", content: { label: "Include Google Analytics", description: "Include Google Analytics in your website", icon: "https://cdn.iconscout.com/icon/free/png-512/google-analytics-2038788-1721678.png", documentation: "", }, type: PropertyTypes.BOOLEAN, }), new Primitives.ConfigurationProperty({ identifier: "hotjar", content: { label: "Hotjar Analytics", description: "Include Hotjar Analytics in your website", icon: "https://cdn2.hubspot.net/hubfs/2069462/Hotjar_Flame-1-1.png", documentation: "", }, type: PropertyTypes.BOOLEAN, }), ], }, ); // // // // // Tooling const toolingConfigurationGroup: ConfigurationGroup = new Primitives.ConfigurationGroup( { identifier: "tooling", content: { label: "Tooling", description: "Configure the tooling of your codebase", icon: "", documentation: "", }, properties: [ new Primitives.ConfigurationProperty({ identifier: "jest", content: { label: "Include Jest", description: "Include Jest environment and snapshot tests for all your components", icon: "https://seeklogo.com/images/J/jest-logo-F9901EBBF7-seeklogo.com.png", documentation: "", }, type: PropertyTypes.BOOLEAN, }), new Primitives.ConfigurationProperty({ identifier: "prettier", content: { label: "Include Prettier", description: "Include Prettier .rc files and npm script for code formattting", icon: "https://seeklogo.com/images/P/prettier-logo-D5C5197E37-seeklogo.com.png", documentation: "", }, type: PropertyTypes.BOOLEAN, defaultValue: true, }), new Primitives.ConfigurationProperty({ identifier: "eslint", content: { label: "Eslint", description: "Include ESLint .rc files and npm script for code linting", icon: "https://cdn.freebiesupply.com/logos/large/2x/eslint-logo-png-transparent.png", documentation: "", }, type: PropertyTypes.BOOLEAN, defaultValue: true, }), new Primitives.ConfigurationProperty({ identifier: "storybook", content: { label: "Include Storybook", description: "Include Storybook environment and stories for all your components", icon: "https://pbs.twimg.com/profile_images/1100804485616566273/sOct-Txm.png", documentation: "", }, type: PropertyTypes.BOOLEAN, }), ], }, ); // // // // // SEO const seoConfigurationGroup: ConfigurationGroup = new Primitives.ConfigurationGroup( { identifier: "seo", content: { label: "SEO", description: "Configure the SEO of your website", icon: "", documentation: "", }, properties: [ new Primitives.ConfigurationProperty({ identifier: "twitter", content: { label: "Twitter", description: "Include meta tags linking your website to a Twitter handle", icon: "https://res.cloudinary.com/codotype/image/upload/v1558931014/product-logos/twitter-512.png", documentation: "", }, type: PropertyTypes.BOOLEAN, }), new Primitives.ConfigurationProperty({ identifier: "opengraph", content: { label: "OpenGraph", description: "Include OpenGraph meta tags for pretty previews when sharing your site on social media", icon: "https://ogp.me/logo.png", documentation: "", }, type: PropertyTypes.BOOLEAN, }), new Primitives.ConfigurationProperty({ identifier: "sitemap", content: { label: "Sitemap", description: "Include dynamic sitemap with your exported code", // icon: "https://blog.atj.me/assets/sitemap.png", icon: "https://i.pinimg.com/originals/8e/d4/21/8ed42172785c5f144d5df49998c00cd7.png", documentation: "", }, type: PropertyTypes.BOOLEAN, }), new Primitives.ConfigurationProperty({ identifier: "jsonLD", content: { label: "Include JSON-LD Metadata", description: "Include JSON-LD metadata for each of your pages", icon: // "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c9/JSON_vector_logo.svg/1200px-JSON_vector_logo.svg.png", // "https://www.innocreate.com/wp-content/uploads/2017/07/jsonlogo-300x300.png", "https://dinacon.ch/wp-content/uploads/sites/4/2018/05/rdf-icon-with-shadow.png", documentation: "", }, type: PropertyTypes.BOOLEAN, }), ], }, ); // // // // // Hosting const hostingConfigurationGroup: ConfigurationGroup = new Primitives.ConfigurationGroup( { identifier: "hosting", content: { label: "Hosting", description: "Configure the hosting of your website", icon: "", documentation: "", }, properties: [ new Primitives.ConfigurationProperty({ identifier: "platform", content: { label: "Platform", description: "How would you like to host your website?", icon: // "https://cdn1.iconfinder.com/data/icons/hawcons/32/699966-icon-1-cloud-512.png", "https://cdn4.iconfinder.com/data/icons/colicon/24/cloud-512.png", documentation: "", }, type: PropertyTypes.DROPDOWN, defaultValue: "vercel", selectOptions: [ { label: "Vercel", value: "vercel" }, { label: "Netlify", value: "netlify" }, { label: "Docker", value: "docker" }, { label: "GitHub Pages", value: "github_pages" }, { label: "None", value: "none" }, ], }), ], }, ); // // // // // Export Plugin // export const NextJsWebsiteStarterPlugin: PluginMetadata = new Primitives.Plugin( // { // identifier: "react-next-ts-website-starter", // project_path: "react-next-ts-starter", // content: { // label: "React + Next + TypeScript Website Starter", // description: "React + Next + TypeScript Website Starter", // icon: // "https://miro.medium.com/max/500/1*cPh7ujRIfcHAy4kW2ADGOw.png", // documentation: syntaxHighlighting, // }, // configurationGroups: [ // // landingPageConfigurationGroup, // toolingConfigurationGroup, // seoConfigurationGroup, // analyticsConfigurationGroup, // hostingConfigurationGroup, // ], // }, // ); // // // // // Export alternative variation of same plugin using grouped properties const toolingProperty = new Primitives.ConfigurationProperty({ identifier: "tooling", content: { label: "Tooling", description: "What tooling would you like to use?", icon: "", documentation: "", }, type: PropertyTypes.INSTANCE, layoutVariant: PropertyLayoutVariants.COL_12, defaultValue: {}, selectOptions: [], properties: [ ...toolingConfigurationGroup.properties.map((p) => { return { ...p, // layoutVariant: PropertyLayoutVariants.CARD_COL_4, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }; }), ], }); const analyticsProperty = new Primitives.ConfigurationProperty({ identifier: "analytics", content: { label: "Analytics", description: "Which SEO features would you like?", icon: "", documentation: "", }, type: PropertyTypes.INSTANCE, layoutVariant: PropertyLayoutVariants.COL_12, defaultValue: {}, selectOptions: [], properties: [ ...analyticsConfigurationGroup.properties.map((p) => { return { ...p, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }; }), ], }); const seoProperty = new Primitives.ConfigurationProperty({ identifier: "seo", content: { label: "SEO", description: "Which SEO features would you like?", icon: "", documentation: "", }, type: PropertyTypes.INSTANCE, layoutVariant: PropertyLayoutVariants.COL_12, defaultValue: {}, selectOptions: [], properties: [ ...seoConfigurationGroup.properties.map((p) => { return { ...p, layoutVariant: PropertyLayoutVariants.CARD_COL_6, }; }), ], }); const hostingProperty = new Primitives.ConfigurationProperty({ identifier: "hosting", content: { label: "Hosting", description: "What hosting would you like to use?", icon: "", documentation: "", }, type: PropertyTypes.INSTANCE, layoutVariant: PropertyLayoutVariants.COL_12, defaultValue: {}, selectOptions: [], properties: [ ...hostingConfigurationGroup.properties.map((p) => { return { ...p, layoutVariant: PropertyLayoutVariants.CARD_COL_12, }; }), ], }); // Other properties: // - Marketing - Mailchip // - Customer Engagement - Intercom // - Customer Engagement - Segment (Customer Data Platform) export const NextJsStarter = new Primitives.Plugin({ identifier: "react-next-ts-website-starter-variant", project_path: "react-next-ts-starter", content: { label: "React + Next + TypeScript Website Starter", description: "React + Next + TypeScript Website Starter", icon: "https://miro.medium.com/max/500/1*cPh7ujRIfcHAy4kW2ADGOw.png", documentation: syntaxHighlighting, }, configurationGroups: [ { ...toolingConfigurationGroup, identifier: "configure", content: { label: "Configure", description: "Configure your boilerplate code", icon: "", documentation: "", }, properties: [ toolingProperty, analyticsProperty, seoProperty, hostingProperty, ], }, landingPageConfigurationGroup, ], });
the_stack
"use strict"; // Override the jQuery Attr function to fix the checkbox checking which the method is no longer working in newer jQuery. // #8 https://github.com/louislam/vestacp-crossover-adminlte/issues/8 var oldAttr = $.fn.attr; $.fn.attr = function(name, value) { if (name === "checked") { return this.is(":checked"); } else { return oldAttr.apply(this, arguments); } }; class LouisAdminLTE { protected body : JQuery = $("body"); constructor() { } public check() : boolean { if ($(".l-stat .l-stat__col").size() > 0) { return true; } else { return false; } } private initUI() { var body = this.body; var wrapper; if (! this.check()) { alert("Cannot apply the theme. Please restore the \"templates/header.html\" and check if you are using VestaCP 0.9.8 (Release 15)."); body.show(); return; } body.addClass("sidebar-mini"); body.addClass(this.getSkin()); body.addClass(this.getLayoutBoxed()); // Wrap All Content first body.wrapInner('<div class="content-wrapper"></div>'); body.wrapInner('<div class="wrapper" />'); wrapper = $(".wrapper"); // Load Template $.get("/louislam/view/template.php", (html) => { body.show(); var template = $(html); var sidebar = template.find(".main-sidebar"); var sidebarMenu = sidebar.find(".sidebar-menu"); var header = template.find(".main-header"); var activeItem = null; var menuItem = $("<li><a href=''><i class='fa'></i> <span></span><small class='label pull-right bg-blue'></small></li>"); wrapper.prepend(header); wrapper.prepend(sidebar); header.find(".username").text($(".l-profile__username").text()); header.find(".btn-profile").attr("href", $(".l-profile__username").attr("href")); header.find(".btn-logout").attr("href", $(".l-profile__logout").attr("href")); // Menu items $(".l-stat .l-stat__col").each(function () { var name = LouisAdminLTE.ucFirst($(this).find(".l-stat__col-title").text()); var url = $(this).find("a").attr("href"); var number = LouisAdminLTE.ucFirst($(this).find("ul li:first-child span").text()); var item = menuItem.clone(); if ($(this).hasClass("l-stat__col--active")) { item.addClass("active"); activeItem = item; } item.find("a").attr("href", url); item.find(".label").text(number); if (url == "/list/user/") { item.find(".fa").addClass("fa-user"); item.find("span").text(name); } else if (url == "/list/web/") { item.find(".fa").addClass("fa-server"); item.find("span").text(name); } else if (url == "/list/dns/") { item.find(".fa").addClass("fa-share-square-o"); item.find("span").text(name.replace("Dns", "DNS")); } else if (url == "/list/mail/") { item.find(".fa").addClass("fa-envelope"); item.find("span").text(name); } else if (url == "/list/db/") { item.find(".fa").addClass("fa-database"); item.find("span").text(name.replace("Db", "Database")); } else if (url == "/list/cron/") { item.find(".fa").addClass("fa-clock-o"); item.find("span").text(name); } else if (url == "/list/backup/") { item.find(".fa").addClass("fa-ambulance"); item.find("span").text(name); } else { item.find(".fa").addClass("fa-th"); item.find("span").text(name); } sidebarMenu.append(item); }); // Admin Menu sidebarMenu.append('<li class="treeview admin-treeview"><a href="#"><i class="fa fa-th"></i><span>More</span></a><ul class="treeview-menu admin-menu"></ul></li>'); $(".l-menu__item a").each(function () { var item = $("<li><a><i class=\"fa\"></i><span></span></a></li>"); var a = item.find("a"); a.attr("href", $(this).attr("href")); var name = $(this).text(); if (name == "User") { } else { item.find(".fa").addClass("fa-circle-o"); a.find("span").append(name); } if ($(this).parent().hasClass("l-menu__item--active")) { item.addClass("active"); $(".admin-treeview").addClass("active"); activeItem = item; } $(".admin-menu").append(item); }); // AdminLTE Settings var item = menuItem.clone(); item.find(".fa").addClass("fa-cog"); item.find("a").attr("href", "#").click(() => { $('#modal-setting').modal('show'); }); item.find("span").text("AdminLTE Settings"); sidebarMenu.append(item); var modal = template.find(".modal-setting"); $("body").append(modal); modal.find(".skin-block").each((i, elem) => { var skinName = $(elem).data("skin"); $(elem).css("background-image", "url(/louislam/img/"+ skinName +".png)").click(() => { this.setSkin(skinName); }); }); $(".l-stat, .l-header").hide(); $(".l-separator").remove(); $(".l-sort").removeClass("l-sort").css("margin-top", 0); // Add Box to Listing var contentSection = $('<section class="content"></section>'); var row = $("<div class='row' />"); var col = $("<div class='col-xs-12 col-lg-11' />"); var box = $("<div class='box-list box-info box'><div class='box-header with-border'></div><div class='box-body'></div><div class='box-footer'></div></div>"); var units = $(".units"); if (units.size() == 0) { units = $('#vstobjects'); } contentSection.html(row); row.html(col); col.html(box); if (activeItem != null) box.find('.box-header').text(activeItem.find("span").text()); units.before(contentSection); box.find(".box-body").html(units); box.find(".box-footer").html($(".data-count")); if (location.href.indexOf("/dns/?domain") < 0 && location.href.indexOf("/list/rrd/") < 0) { $(".l-icon-shortcuts, .l-icon-to-top, .l-unit__stats, .l-unit__date, .l-sort-toolbar__search-box").hide(); } }); // Create Button re-style var createButton = $(".l-sort__create-btn"); createButton.removeClass("l-sort__create-btn").addClass("btn btn-info btn-flat"); createButton.text(createButton.attr('title')); createButton.css("margin-left", "15px"); $(".l-sort-toolbar").prepend(createButton); // For each Row $(".units .l-unit").each(function () { var row = $("<div class='row'><div class='col-xs-12 col-md-9 left'></div><div class='col-xs-12 col-md-3 right'></div></div>"); row.find(".left").append($(this).find(".l-unit-toolbar")); row.find(".left").append($(this).find(".l-unit__col--left")); row.find(".left").append($(this).find(".l-unit__col--right")); $(this).append(row); var stats = row.find(".l-unit__stats"); // Firewall only if (location.href.indexOf("/list/firewall/") >= 0) { row.find(".l-unit__col.l-unit__col--right").prepend('<div class="l-unit__name separate">' + row.find(".l-unit__stats").text() + '</div>'); row.find(".l-icon-star").css("margin-top", 0); } else { } row.find(".l-unit__name").click(() => { stats.toggle(); }); stats.find("td").each((i, e) => { if ($(e).text().trim() == "") { $(e).remove(); } }); // Action Panel var actionButtons = $(this).find(".actions-panel__col"); if (actionButtons.size() > 0) { var btnGroup = $('<div class="btn-group action-btn-group"><button type="button" class="btn btn-default btn-flat dropdown-toggle" data-toggle="dropdown"> ' + '<span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button><ul class="dropdown-menu" role="menu"></ul></div>'); row.find(".right").append(btnGroup); var dropdownMenuUL = btnGroup.find(".dropdown-menu"); actionButtons.each(function (i) { var oldA = $(this).find("a"); var inputURL = oldA.find("input[type=hidden]"); // If the action has confirmation dialog, add it back using sweetalert. if (inputURL.size() > 0) { oldA.click(function () { swal({ title: "Are you sure?", text: oldA.find(".confirmation").text(), type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes", closeOnConfirm: false }, function () { location.href = inputURL.val(); }); }); } if (i == 0) { oldA.addClass("btn-main-action btn btn-default btn-flat"); btnGroup.prepend(oldA); } else { var li = $('<li></li>'); li.append(oldA); dropdownMenuUL.append(li); } }); } }); // Add or edit $(".data-col1").parent().remove(); // $(".data-col2 input").addClass("form-control"); } public static ucFirst(str : string) { return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); } public setSkin(className) { this.body.removeClass("skin-blue skin-blue-light skin-yellow skin-yellow-light skin-green skin-green-light skin-purple skin-purple-light skin-red skin-red-light skin-black skin-black-light"); localStorage.setItem("louislam-skin", className); this.body.addClass(className); } public getSkin() { var skin = localStorage.getItem("louislam-skin"); if (skin == null) { return "skin-blue"; } return skin; } public setLayoutBoxed(val : boolean) { localStorage.setItem("louislam-layout-boxed", val.toString()); this.body.removeClass("layout-boxed").addClass(this.getLayoutBoxed()); } public getLayoutBoxed() { var val = localStorage.getItem("louislam-layout-boxed"); if (val != null && val == "true") { return "layout-boxed"; } return ""; } } $.ajaxSetup ({ cache: false }); var louisAdminLTE = null; $(document).ready(function () { louisAdminLTE = new LouisAdminLTE(); louisAdminLTE.initUI(); });
the_stack
import {Inject, Injectable} from '@angular/core'; import {Headers, Request, RequestOptions, RequestOptionsArgs, RequestMethod, Response} from '@angular/http'; import {NotificationService} from '../notification/notification.service'; import {ApiConnection} from '../connect/api-connection' import {ApiError, ApiErrorType} from '../error/api-error'; import {ConnectService} from '../connect/connect.service'; import {Runtime} from '../runtime/runtime'; import {HttpFacade} from './http-facade'; import {Observable, throwError, of} from 'rxjs'; import {finalize, catchError, mergeMap } from 'rxjs/operators'; @Injectable() export class HttpClient { private _headers: Headers= new Headers(); private _conn: ApiConnection; constructor(@Inject("Http") private _http: HttpFacade, private _notificationService: NotificationService, private _connectSvc: ConnectService, @Inject("Runtime") private runtime: Runtime) { this._connectSvc.active.subscribe(c => { if (c) { this._conn = c }}) } private get headers(): Headers { let headers = new Headers(); for (var key of this._headers.keys()) { headers.append(key, this._headers.get(key)); } return headers } public setHeader(key: string, value: string) { this._headers.set(key, value); } public get(url: string, options?: RequestOptionsArgs, warn: boolean = true): Promise<any> { let ops: RequestOptionsArgs = this.getOptions(RequestMethod.Get, url, options); return this.request(url, ops, warn) .then(res => res.status !== 204 ? res.json() : null); } public head(url: string, options?: RequestOptionsArgs, warn: boolean = true): Promise<any> { let ops: RequestOptionsArgs = this.getOptions(RequestMethod.Head, url, options); return this.request(url, ops, warn); } public post(url: string, body: string, options?: RequestOptionsArgs, warn: boolean = true): Promise<any> { options = this.setJsonContentType(options); let ops: RequestOptionsArgs = this.getOptions(RequestMethod.Post, url, options, body); return this.request(url, ops, warn) .then(res => res.status !== 204 ? res.json() : null); } public patch(url: string, body: string, options?: RequestOptionsArgs, warn: boolean = true): Promise<any> { options = this.setJsonContentType(options); let ops: RequestOptionsArgs = this.getOptions(RequestMethod.Patch, url, options, body); return this.request(url, ops, warn) .then(res => res.status !== 204 ? res.json() : null); } public delete(url: string, options?: RequestOptionsArgs, warn: boolean = true): Promise<any> { let ops: RequestOptionsArgs = this.getOptions(RequestMethod.Delete, url, options); return this.request(url, ops, warn); } public options(url: string): Promise<any> { let ops: RequestOptionsArgs = this.getOptions(RequestMethod.Options, url, null); return this.request(url, ops); } public endpoint(): ApiConnection { return this._conn; } public request(url: string, options?: RequestOptionsArgs, warn?: boolean): Promise<Response> { return new Promise<Response>((resolve, reject) => { this.requestOnConnection(url, options, warn).subscribe( v => resolve(v), e => { var unhandled = this.runtime.HandleConnectError(e); if (unhandled) { return reject(unhandled); } } ) }); } private setJsonContentType(options?: RequestOptionsArgs) { if (!options) { options = {}; } if (!options.headers) { options.headers = new Headers(); } options.headers.set("Content-Type", "application/json"); return options; } private requestOnConnection(url: string, options?: RequestOptionsArgs, warn?: boolean): Observable<Response> { if (this._conn) { return this.performRequest(this._conn, url, options, warn) } else { return this.runtime.ConnectToIISHost().pipe( mergeMap(connection => this.performRequest(connection, url, options, warn)) ) } } private performRequest(conn: ApiConnection, url: string, options?: RequestOptionsArgs, warn?: boolean): Observable<Response> { let reqOpt = new RequestOptions(options); if (url.toString().indexOf("/") != 0) { url = '/' + url; } reqOpt.url = conn.url + '/api' + url; let req = new Request(reqOpt); // // Set Access-Token req.headers.set('Access-Token', 'Bearer ' + conn.accessToken); return this._http.request(req).pipe( catchError(e => { // Status code 0 possible causes: // Untrusted certificate // Windows auth, prevents CORS headers from being accessed // Service not responding if (e instanceof Response) { if (e.status == 0) { return this._http.request(req).pipe( catchError(err => { // Check to see if connected return this._http.options(this._conn.url).pipe( catchError((e, _) => { this._connectSvc.reconnect(); return throwError(e) }), finalize(() => { this.handleHttpError(err); }) )}) ) } this.handleHttpError(e, warn); return throwError(e) } let apiError = <ApiError>({ title: "unknown error", detail: JSON.stringify(e), }) this._notificationService.apiError(apiError) return throwError(apiError) }) ) } private handleHttpError(err, warn?: boolean) { if (err.status == 403 && err.headers.get("WWW-Authenticate") === "Bearer") { this._connectSvc.reconnect(); throw "Not connected" } let apiError = this.apiErrorFromHttp(err); if (apiError && warn) { this._notificationService.apiError(apiError); } throw apiError; } public getOptions(method: RequestMethod, url: string, options: RequestOptionsArgs, body?: string): RequestOptionsArgs { let aBody = body ? body : options && options.body ? options.body : undefined let opts: RequestOptionsArgs = { method: method, url: url, headers: options && options.headers ? options.headers : this.headers, search: options && options.search ? options.search : undefined, body: aBody }; opts.headers.set("Accept", "application/hal+json"); return opts; } private apiErrorFromHttp(httpError): ApiError { let msg = ""; let apiError: ApiError = null; if ((httpError)._body) { try { apiError = JSON.parse(httpError._body); } catch (parseError) { } } if (apiError == null) { apiError = new ApiError(); apiError.status = httpError.status; } if (httpError.status === 400) { if (apiError && apiError.title == "Invalid parameter") { var parameterName = this.parseParameterName(apiError.name); msg = "An invalid value was given for " + parameterName + "."; if (apiError.detail) { msg += "\n" + apiError.detail; } } } if (httpError.status == 403) { // TODO: Invalid token if (apiError && apiError.title == "Object is locked") { apiError.type = ApiErrorType.SectionLocked; msg = "The feature's settings could not be loaded. This happens when the feature is locked at the current configuration level and the feature's settings have been modified. To fix this, manually remove any local changes to the feature or unlock the feature at the parent level."; } if (apiError && apiError.title == "Forbidden" && apiError.name) { if (apiError[apiError.name]) { msg = "Forbidden: '" + apiError[apiError.name] + "'"; } else { msg = "Forbidden: '" + apiError.name + "'"; } if (apiError.detail) { msg += "\n" + apiError.detail; } } } if (httpError.status == 404) { if (apiError && apiError.detail === "IIS feature not installed") { apiError.type = ApiErrorType.FeatureNotInstalled; msg = apiError.detail + "\n" + apiError.name; } else { msg = "The resource could not be found"; apiError.type = ApiErrorType.NotFound; } } if (httpError.status == 500) { // TODO: Invalid token if (apiError.detail == "Dism Error") { msg = "An error occured enabling " + apiError.feature; if (apiError.exit_code == 'B7') { msg += "\nThe specified image is currently being serviced by another DISM operation" } msg += "\nError code: " + apiError.exit_code; } else { msg = apiError.detail || ""; } } apiError.message = msg; return apiError; } private parseParameterName(pName: string) { if (!pName) { return ""; } while (pName.indexOf(".") != -1) { pName = pName.substr(pName.indexOf(".") + 1); } var parts = pName.split('_'); for (var i = 0; i < parts.length; i++) { parts[i] = parts[i].charAt(0).toUpperCase() + parts[i].slice(1); } return parts.join(" "); } }
the_stack
import { CompilerContext, isObject, toFastProperties } from '@deepkit/core'; import { typeSettings, UnpopulatedCheck } from './core.js'; import { ReflectionClass, ReflectionProperty } from './reflection/reflection.js'; import { ContainerAccessor, executeTemplates, noopTemplate, serializer, Serializer, TemplateRegistry, TemplateState } from './serializer.js'; import { ReflectionKind } from './reflection/type.js'; function createJITConverterForSnapshot( schema: ReflectionClass<any>, properties: ReflectionProperty[], registry: TemplateRegistry, ) { const compiler = new CompilerContext(); const setProperties: string[] = []; const state = new TemplateState('', '', compiler, registry); for (const property of properties) { // if (isExcluded(schema, property.name, 'json')) continue; const accessor = new ContainerAccessor('_value', JSON.stringify(property.getNameAsString())); const setter = new ContainerAccessor('_result', JSON.stringify(property.getNameAsString())); if (property.isReference()) { const referenceCode: string[] = []; for (const pk of property.getResolvedReflectionClass().getPrimaries()) { const deepAccessor = new ContainerAccessor(accessor, JSON.stringify(pk.getNameAsString())); const deepSetter = new ContainerAccessor(setter, JSON.stringify(pk.getNameAsString())); referenceCode.push(` //createJITConverterForSnapshot ${property.getNameAsString()}->${pk.getNameAsString()} class:snapshot:${property.type.kind} reference ${executeTemplates(state.fork(deepSetter, deepAccessor), pk.type)} `); } setProperties.push(` //createJITConverterForSnapshot ${property.getNameAsString()} class:snapshot:${property.getKind()} reference if (undefined === ${accessor} || null === ${accessor}) { ${setter} = null; } else { ${setter} = {}; ${referenceCode.join('\n')} } `); continue; } setProperties.push(` //createJITConverterForSnapshot ${property.getNameAsString()} class:snapshot:${property.getKind()} if (undefined === ${accessor} || null === ${accessor}) { ${setter} = null; } else { ${executeTemplates(state.fork(setter, accessor), property.type)} } `); } let circularCheckBeginning = ''; let circularCheckEnd = ''; if (schema.hasCircularReference()) { circularCheckBeginning = ` if (state._stack) { if (state._stack.includes(_value)) return undefined; } else { state._stack = []; } state._stack.push(_value); `; circularCheckEnd = `state._stack.pop();`; } const functionCode = ` var _result = {}; state = state || {}; ${circularCheckBeginning} var oldUnpopulatedCheck = _global.unpopulatedCheck; _global.unpopulatedCheck = UnpopulatedCheckNone; ${setProperties.join('\n')} _global.unpopulatedCheck = oldUnpopulatedCheck; ${circularCheckEnd} return _result; `; compiler.context.set('_global', typeSettings); compiler.context.set('UnpopulatedCheckNone', UnpopulatedCheck.None); return compiler.build(functionCode, '_value', 'state'); } class SnapshotSerializer extends Serializer { name = 'snapshot'; protected registerSerializers() { super.registerSerializers(); //we keep bigint as is this.serializeRegistry.register(ReflectionKind.bigint, noopTemplate); this.deserializeRegistry.register(ReflectionKind.bigint, noopTemplate); } } export const snapshotSerializer = new SnapshotSerializer; /** * Creates a new JIT compiled function to convert the class instance to a snapshot. * A snapshot is essentially the class instance as `plain` serialization while references are * stored only as their primary keys. * * Generated function is cached. */ export function getConverterForSnapshot( reflectionClass: ReflectionClass<any> ): (value: any) => any { const jit = reflectionClass.getJitContainer(); if (jit.snapshotConverter) return jit.snapshotConverter; jit.snapshotConverter = createJITConverterForSnapshot(reflectionClass, reflectionClass.getProperties(), snapshotSerializer.serializeRegistry); toFastProperties(jit); return jit.snapshotConverter; } /** * Creates a snapshot using getConverterForSnapshot(). */ export function createSnapshot<T>(reflectionClass: ReflectionClass<T>, item: T) { return getConverterForSnapshot(reflectionClass)(item); } /** * Extracts the primary key of a snapshot and converts to class type. */ export function getPrimaryKeyExtractor<T>( reflectionClass: ReflectionClass<T> ): (value: any) => Partial<T> { const jit = reflectionClass.getJitContainer(); if (jit.primaryKey) return jit.primaryKey; jit.primaryKey = createJITConverterForSnapshot(reflectionClass, reflectionClass.getPrimaries(), snapshotSerializer.deserializeRegistry); toFastProperties(jit); return jit.primaryKey; } /** * Creates a primary key hash generator that takes an item from any format * converts it to class format, then to plain, then uses the primitive values to create a string hash. * * This function is designed to work on the plain values (db records or json values) */ export function getPrimaryKeyHashGenerator( reflectionClass: ReflectionClass<any>, serializerToUse: Serializer = serializer ): (value: any) => string { const jit = reflectionClass.getJitContainer(); if (!jit.pkHash) { jit.pkHash = {}; toFastProperties(jit); } if (jit.pkHash[serializerToUse.name]) return jit.pkHash[serializerToUse.name]; jit.pkHash[serializerToUse.name] = createPrimaryKeyHashGenerator(reflectionClass, serializerToUse); toFastProperties(jit.pkHash); return jit.pkHash[serializerToUse.name]; } // export function getForeignKeyHash(row: any, property: PropertySchema): string { // const foreignSchema = property.getResolvedClassSchema(); // return getPrimaryKeyHashGenerator(foreignSchema)(row[property.name]); // } function simplePrimaryKeyHash(value: any): string { return '\0' + value; } export function getSimplePrimaryKeyHashGenerator(reflectionClass: ReflectionClass<any>) { return simplePrimaryKeyHash; } function createPrimaryKeyHashGenerator( reflectionClass: ReflectionClass<any>, serializer: Serializer ) { const context = new CompilerContext(); const setProperties: string[] = []; context.context.set('isObject', isObject); const state = new TemplateState('', '', context, serializer.serializeRegistry); for (const property of reflectionClass.getPrimaries()) { // if (property.isParentReference) continue; const accessor = new ContainerAccessor('_value', JSON.stringify(property.getNameAsString())); if (property.isReference()) { const referenceCode: string[] = []; for (const pk of property.getResolvedReflectionClass().getPrimaries()) { if (pk.type.kind === ReflectionKind.class && pk.type.types.length) { throw new Error(`Class as primary key (${property.getResolvedReflectionClass().getClassName()}.${pk.getNameAsString()}) is not supported`); } const deepAccessor = new ContainerAccessor(accessor, JSON.stringify(pk.getNameAsString())); referenceCode.push(` //getPrimaryKeyExtractor ${property.getNameAsString()}->${pk.getNameAsString()} class:snapshot:${property.getKind()} reference lastValue = ''; if (${deepAccessor} !== null && ${deepAccessor} !== undefined) { ${executeTemplates(state.fork('lastValue', deepAccessor).forRegistry(serializer.deserializeRegistry), pk.type)} ${executeTemplates(state.fork('lastValue', 'lastValue'), pk.type)} } _result += '\\0' + lastValue; `); } setProperties.push(` //getPrimaryKeyExtractor ${property.getNameAsString()} class:snapshot:${property.getKind()} reference if (undefined !== ${accessor} && null !== ${accessor}) { if (isObject(${accessor})) { ${referenceCode.join('\n')} } else { //might be a primary key directly lastValue = ''; ${executeTemplates(state.fork('lastValue', accessor).forRegistry(serializer.deserializeRegistry), property.getResolvedReflectionClass().getPrimary().type)} ${executeTemplates(state.fork('lastValue', 'lastValue'), property.getResolvedReflectionClass().getPrimary().type)} _result += '\\0' + lastValue; } } else { _result += '\\0'; } `); continue; } if (property.type.kind === ReflectionKind.class && property.type.types.length) { throw new Error(`Class as primary key (${reflectionClass.getClassName()}.${property.getNameAsString()}) is not supported`); } setProperties.push(` //getPrimaryKeyHashGenerator ${property.getNameAsString()} class:plain:${property.getKind()} lastValue = ''; if (${accessor} !== null && ${accessor} !== undefined) { ${executeTemplates(state.fork('lastValue', accessor).forRegistry(serializer.deserializeRegistry), property.type)} ${executeTemplates(state.fork('lastValue', 'lastValue'), property.type)} } _result += '\\0' + lastValue; `); } let circularCheckBeginning = ''; let circularCheckEnd = ''; if (reflectionClass.hasCircularReference()) { circularCheckBeginning = ` if (state._stack) { if (state._stack.includes(_value)) return undefined; } else { state._stack = []; } state._stack.push(_value); `; circularCheckEnd = `state._stack.pop();`; } const functionCode = ` var _result = ''; var lastValue; state = state || {}; ${circularCheckBeginning} ${setProperties.join('\n')} ${circularCheckEnd} return _result; `; return context.build(functionCode, '_value', 'state'); }
the_stack
import { LitElement, PropertyValues } from 'lit'; import { property } from 'lit/decorators.js'; import { provideContextRecord } from '../../base/context'; import { DiscoveryEvent, ElementDiscoveryController } from '../../base/elements'; import { DisposalBin, eventListener, listen, vdsEvent } from '../../base/events'; import { FullscreenChangeEvent, FullscreenController } from '../../base/fullscreen'; import { ElementLogger, LogLevelName, LogLevelNameMap } from '../../base/logger'; import { RequestQueue } from '../../base/queue'; import { ScreenOrientationController, ScreenOrientationLock } from '../../base/screen-orientation'; import { DEV_MODE } from '../../global/env'; import { clampNumber } from '../../utils/number'; import { notEqual } from '../../utils/unit'; import { CanPlay } from '../CanPlay'; import { mediaContext, MediaContextRecordValues } from '../context'; import { MediaEvents } from '../events'; import { MediaType } from '../MediaType'; import { ViewType } from '../ViewType'; /** * Fired when the media provider connects to the DOM. * * @event * @bubbles * @composed */ export type MediaProviderConnectEvent = DiscoveryEvent<MediaProviderElement>; /** * Base abstract media provider class that defines the interface to be implemented by * all concrete media providers. Extending this class enables provider-agnostic communication 💬 * */ export abstract class MediaProviderElement extends LitElement { constructor() { super(); } // ------------------------------------------------------------------------------------------- // Lifecycle // ------------------------------------------------------------------------------------------- /* c8 ignore next */ protected readonly _logger = DEV_MODE && new ElementLogger(this); protected readonly _disconnectDisposal = new DisposalBin( this, /* c8 ignore next */ DEV_MODE && { name: 'disconnectDisposal', owner: this } ); override connectedCallback() { /* c8 ignore start */ if (DEV_MODE) { if ('controller' in this) { // @ts-expect-error - re-init to consume log level because provider is a media controller // and log level context is created after this class has initialized. this._logger = new ElementLogger(this); } this._logMediaEvents(); } /* c8 ignore stop */ super.connectedCallback(); new ElementDiscoveryController(this, 'vds-media-provider-connect'); this._connectedQueue.flush(); this._connectedQueue.serveImmediately = true; } protected override updated(changedProperties: PropertyValues) { super.updated(changedProperties); /* c8 ignore start */ if (DEV_MODE) { changedProperties.forEach((_, prop) => { this._logger .infoGroup(`🧬 changed prop \`${String(prop)}\` to \`${this[prop]}\``) .appendWithLabel('Property', prop) .appendWithLabel('Value', this[prop]) .end(); }); } /* c8 ignore stop */ if (changedProperties.has('controls')) { this.ctx.controls = this.controls ?? false; } if (changedProperties.has('loop')) { this.ctx.loop = this.loop ?? false; } if (changedProperties.has('playsinline')) { this.ctx.playsinline = this.playsinline ?? false; } } protected override firstUpdated(changedProperties: PropertyValues) { super.firstUpdated(changedProperties); this.ctx.canRequestFullscreen = this.canRequestFullscreen; } override disconnectedCallback() { super.disconnectedCallback(); this._connectedQueue.destroy(); this.mediaRequestQueue.destroy(); this._shouldSkipNextSrcChangeReset = false; this._disconnectDisposal.empty(); } // ------------------------------------------------------------------------------------------- // Logging // ------------------------------------------------------------------------------------------- /** * Sets the providers log level. By default it'll follow the media controller's log level. Valid * values in order of level include `silent`, `error`, `warn`, `info` and `debug`. Set to special * value `auto` for it to continue following controller. * * @default `auto` */ @property({ attribute: 'log-level' }) get logLevel(): LogLevelName { /* c8 ignore next */ return DEV_MODE ? LogLevelNameMap[this._logger.level] : 'silent'; } set logLevel(newLevel: LogLevelName | 'auto') { /* c8 ignore next */ const numericLevel = DEV_MODE ? Object.values(LogLevelNameMap).findIndex((l) => l === newLevel) : 0; this._logger.level = numericLevel >= 0 ? numericLevel : undefined; } /* c8 ignore next */ protected _logMediaEvents() { /* c8 ignore start */ if (DEV_MODE) { const mediaEvents: (keyof MediaEvents)[] = [ 'vds-abort', 'vds-can-play', 'vds-can-play-through', 'vds-controls-change', 'vds-duration-change', 'vds-emptied', 'vds-ended', 'vds-error', 'vds-fullscreen-change', 'vds-idle-change', 'vds-loaded-data', 'vds-loaded-metadata', 'vds-load-start', 'vds-media-type-change', 'vds-pause', 'vds-play', 'vds-playing', 'vds-progress', 'vds-seeked', 'vds-seeking', 'vds-stalled', 'vds-started', 'vds-suspend', 'vds-replay', // 'vds-time-update', 'vds-view-type-change', 'vds-volume-change', 'vds-waiting' ]; mediaEvents.forEach((eventType) => { const dispose = listen(this, eventType, (event) => { this._logger .infoGroup(`📡 dispatching \`${eventType}\``) .appendWithLabel('Context', this.ctx) .appendWithLabel('Event', event) .appendWithLabel('Engine', this.engine) .end(); }); this._disconnectDisposal.add(dispose); }); } /* c8 ignore stop */ } // ------------------------------------------------------------------------------------------- // Properties // ------------------------------------------------------------------------------------------- /** * Whether playback should automatically begin as soon as enough media is available to do so * without interruption. * * Sites which automatically play audio (or videos with an audio track) can be an unpleasant * experience for users, so it should be avoided when possible. If you must offer autoplay * functionality, you should make it opt-in (requiring a user to specifically enable it). * * However, autoplay can be useful when creating media elements whose source will be set at a * later time, under user control. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/autoplay */ @property({ type: Boolean, reflect: true }) get autoplay() { return this.ctx.autoplay; } set autoplay(shouldAutoplay: boolean) { this.ctx.autoplay = shouldAutoplay; if (this.canPlay && !this._autoplayAttemptPending && shouldAutoplay) { this._autoplayAttemptPending = true; const onAttemptEnd = () => { this._autoplayAttemptPending = false; }; this._attemptAutoplay().then(onAttemptEnd).catch(onAttemptEnd); } } /** * Indicates whether a user interface should be shown for controlling the resource. Set this to * `false` when you want to provide your own custom controls, and `true` if you want the current * provider to supply its own default controls. Depending on the provider, changing this prop * may cause the player to completely reset. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/controls */ @property({ type: Boolean, reflect: true }) controls = false; /** * Whether media should automatically start playing from the beginning (replay) every time * it ends. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/loop */ @property({ type: Boolean, reflect: true }) loop = false; /** * Whether the video is to be played "inline", that is within the element's playback area. Note * that setting this to `false` does not imply that the video will always be played in fullscreen. * Depending on the provider, changing this prop may cause the player to completely reset. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-playsinline */ @property({ type: Boolean, reflect: true }) playsinline = false; // -- /** * An `int` between `0` (silent) and `1` (loudest) indicating the audio volume. Defaults to `1`. * * @default 1 * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/volume */ @property({ type: Number, reflect: true }) get volume() { return this.canPlay ? this._getVolume() : 1; } set volume(requestedVolume) { this.mediaRequestQueue.queue('volume', () => { const volume = clampNumber(0, requestedVolume, 1); if (notEqual(this.volume, volume)) { this._setVolume(volume); this.requestUpdate('volume'); } }); } protected abstract _getVolume(): number; protected abstract _setVolume(newVolume: number): void; // --- /** * Whether playback should be paused. Defaults to `true` if no media has loaded or playback has * not started. Setting this to `false` will begin/resume playback. * * @default true * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/paused */ @property({ type: Boolean, reflect: true }) get paused() { return this.canPlay ? this._getPaused() : true; } set paused(shouldPause) { this.mediaRequestQueue.queue('paused', () => { if (!shouldPause) { this.play(); } else { this.pause(); } this.requestUpdate('paused'); }); } protected abstract _getPaused(): boolean; // --- /** * A `double` indicating the current playback time in seconds. Defaults to `0` if the media has * not started to play and has not seeked. Setting this value seeks the media to the new * time. The value can be set to a minimum of `0` and maximum of the total length of the * media (indicated by the duration prop). * * @default 0 * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/currentTime */ @property({ attribute: 'current-time', type: Number }) get currentTime() { return this.canPlay ? this._getCurrentTime() : 0; } set currentTime(requestedTime) { this.mediaRequestQueue.queue('time', () => { if (notEqual(this.currentTime, requestedTime)) { this._setCurrentTime(requestedTime); this.requestUpdate('currentTime'); } }); } protected _getCurrentTime() { // Avoid errors where `currentTime` can have higher precision than duration. return Math.min(this.ctx.currentTime, this.duration); } protected abstract _setCurrentTime(newTime: number): void; // --- /** * Whether the audio is muted or not. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/muted */ @property({ type: Boolean, reflect: true }) get muted() { return this.canPlay ? this._getMuted() : false; } set muted(shouldMute) { this.mediaRequestQueue.queue('muted', () => { if (notEqual(this.muted, shouldMute)) { this._setMuted(shouldMute); this.requestUpdate('muted'); } }); } protected abstract _getMuted(): boolean; protected abstract _setMuted(isMuted: boolean): void; // ------------------------------------------------------------------------------------------- // Readonly Properties // ------------------------------------------------------------------------------------------- /** * The underlying engine that is actually responsible for rendering/loading media. Some examples * are: * * - The `VideoElement` engine is `HTMLVideoElement`. * - The `HlsElement` engine is the `hls.js` instance. * - The `YoutubeElement` engine is `HTMLIFrameElement`. * * Refer to the respective provider documentation to find out which engine is powering it. * * @abstract */ abstract get engine(): unknown; /** * A snapshot of the current media state. */ get mediaState(): Readonly<MediaContextRecordValues> { return Object.assign({}, this.ctx); } /** * Returns an `Error` object when autoplay has failed to begin playback. This * can be used to determine when to show a recovery UI in the event autoplay fails. * * @default undefined */ get autoplayError(): Error | undefined { return this.ctx.autoplayError; } /** * Returns a `TimeRanges` object that indicates the ranges of the media source that the * browser has buffered (if any) at the moment the buffered property is accessed. This is usually * contiguous but if the user jumps about while media is buffering, it may contain holes. * * @link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered * @default TimeRanges */ get buffered() { return this.ctx.buffered; } /** * Whether the user agent can play the media, but estimates that **not enough** data has been * loaded to play the media up to its end without having to stop for further buffering of * content. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplay_event */ get canPlay() { return this.ctx.canPlay; } /** * Whether the user agent can play the media, and estimates that enough data has been * loaded to play the media up to its end without having to stop for further buffering * of content. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplaythrough_event */ get canPlayThrough() { return this.ctx.canPlayThrough; } /** * The URL of the current poster. Defaults to `''` if no media/poster has been given or * loaded. * * @default '' */ get currentPoster() { return this.ctx.currentPoster; } /** * The absolute URL of the media resource that has been chosen. Defaults to `''` if no * media has been loaded. * * @default '' * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/currentSrc */ get currentSrc() { return this.ctx.currentSrc; } /** * A `double` indicating the total playback length of the media in seconds. If no media data is * available, the returned value is `NaN`. If the media is of indefinite length (such as * streamed live media, a WebRTC call's media, or similar), the value is `+Infinity`. * * @default NaN * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/duration */ get duration() { return this.ctx.duration; } /** * Whether media playback has reached the end. In other words it'll be true * if `currentTime === duration`. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ended */ get ended() { return this.ctx.ended; } /** * Contains the most recent error or undefined if there's been none. You can listen for * `vds-error` event updates and examine this object to debug further. The error could be a * native `MediaError` object or something else. * * @default undefined * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error */ get error() { return this.ctx.error; } /** * Whether the current media is a live stream. * * @default false */ get live() { return this.ctx.mediaType === MediaType.LiveVideo; } /** * The type of media that is currently active, whether it's audio or video. Defaults * to `unknown` when no media has been loaded or the type cannot be determined. * * @default MediaType.Unknown */ get mediaType() { return this.ctx.mediaType; } /** * Contains the ranges of the media source that the browser has played, if any. * * @default TimeRanges */ get played() { return this.ctx.played; } /** * Whether media is actively playing back. Defaults to `false` if no media has * loaded or playback has not started. * * @default false */ get playing() { return this.ctx.playing; } /** * Contains the time ranges that the user is able to seek to, if any. This tells us which parts * of the media can be played without delay; this is irrespective of whether that part has * been downloaded or not. * * Some parts of the media may be seekable but not buffered if byte-range * requests are enabled on the server. Byte range requests allow parts of the media file to * be delivered from the server and so can be ready to play almost immediately — thus they are * seekable. * * @default TimeRanges * @link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seekable */ get seekable() { return this.ctx.seekable; } /** * Whether media is actively seeking to an new playback position. * * @default false */ get seeking() { return this.ctx.seeking; } /** * Whether media playback has started. In other words it will be true if `currentTime > 0`. * * @default false */ get started() { return this.ctx.started; } /** * The type of player view that is being used, whether it's an audio player view or * video player view. Normally if the media type is of audio then the view is of type audio, but * in some cases it might be desirable to show a different view type. For example, when playing * audio with a poster. This is subject to the provider allowing it. Defaults to `unknown` * when no media has been loaded. * * @default ViewType.Unknown */ get viewType() { return this.ctx.viewType; } /** * Whether playback has temporarily stopped because of a lack of temporary data. * * @default false */ get waiting() { return this.ctx.waiting; } // ------------------------------------------------------------------------------------------- // Support Checks // ------------------------------------------------------------------------------------------- /** * Determines if the media provider can play the given `type`. The `type` is * generally the media resource identifier, URL or MIME type (optional Codecs parameter). * * @example `audio/mp3` * @example `video/mp4` * @example `video/webm; codecs="vp8, vorbis"` * @example `/my-audio-file.mp3` * @example `youtube/RO7VcUAsf-I` * @example `vimeo.com/411652396` * @example `https://www.youtube.com/watch?v=OQoz7FCWkfU` * @example `https://media.vidstack.io/hls/index.m3u8` * @example `https://media.vidstack.io/dash/index.mpd` * @link https://developer.mozilla.org/en-US/docs/Web/Media/Formats/codecs_parameter */ abstract canPlayType(type: string): CanPlay; /** * Determines if the media provider "should" play the given type. "Should" in this * context refers to the `canPlayType()` method returning `Maybe` or `Probably`. * * @param type refer to `canPlayType`. */ shouldPlayType(type: string): boolean { const canPlayType = this.canPlayType(type); return canPlayType === CanPlay.Maybe || canPlayType === CanPlay.Probably; } // ------------------------------------------------------------------------------------------- // Playback // ------------------------------------------------------------------------------------------- /** * Begins/resumes playback of the media. If this method is called programmatically before the * user has interacted with the player, the promise may be rejected subject to the browser's * autoplay policies. * * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play */ abstract play(): Promise<void>; /** * Pauses playback of the media. * * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause */ abstract pause(): Promise<void>; /** * @throws {Error} - Will throw if media is not ready for playback. */ protected _throwIfNotReadyForPlayback() { if (!this.canPlay) { throw Error(`Media is not ready - wait for \`vds-can-play\` event.`); } } protected async _resetPlayback(): Promise<void> { this._setCurrentTime(0); } protected async _resetPlaybackIfEnded(): Promise<void> { if (!this.ended || this.currentTime === 0) return; return this._resetPlayback(); } /** * @throws {Error} - Will throw if player is not in a video view. */ protected _throwIfNotVideoView() { if (this.viewType !== ViewType.Video) { throw Error('Player is currently not in a video view.'); } } protected async _handleMediaReady(event?: Event) { if (this.canPlay) return; this.ctx.canPlay = true; this.dispatchEvent(vdsEvent('vds-can-play', { originalEvent: event })); await this.mediaRequestQueue.flush(); this.mediaRequestQueue.serveImmediately = true; /* c8 ignore start */ if (DEV_MODE) { this._logger .infoGroup( '-------------------------- ✅ MEDIA READY -----------------------------------' ) .appendWithLabel('Context', this.mediaState) .appendWithLabel('Event', event) .appendWithLabel('Engine', this.engine) .end(); } /* c8 ignore stop */ this._autoplayRetryCount = 0; this.ctx.autoplayError = undefined; this._autoplayAttemptPending = true; await this._attemptAutoplay(); this._autoplayAttemptPending = false; } protected _autoplayRetryCount = 0; protected _maxAutoplayRetries = 2; protected _shouldMuteLastAutoplayAttempt = true; protected _autoplayAttemptPending = false; protected async _attemptAutoplay(): Promise<void> { if ( !this.canPlay || !this.autoplay || this.started || this._autoplayRetryCount >= this._maxAutoplayRetries ) { return; } // On last attempt try muted. const shouldTryMuted = !this.muted && this._shouldMuteLastAutoplayAttempt && this._autoplayRetryCount === this._maxAutoplayRetries - 1; /* c8 ignore start */ if (DEV_MODE && this._autoplayRetryCount > 0) { this._logger .warnGroup( `Seems like autoplay has failed, retrying [attempt ${ this._autoplayRetryCount }]${shouldTryMuted ? ' muted' : ''}...` ) .appendWithLabel('Engine', this.engine) .end(); } /* c8 ignore stop */ let didAttemptSucceed = false; try { if (shouldTryMuted) this.muted = true; await this.play(); didAttemptSucceed = true; /* c8 ignore start */ if (DEV_MODE) { this._logger.info('✅ Autoplay was successful.'); } /* c8 ignore stop */ } catch (error) { /* c8 ignore start */ if (DEV_MODE) { this._logger .errorGroup( `Autoplay retry [attempt ${this._autoplayRetryCount} out of ${this._maxAutoplayRetries}] failed.` ) .appendWithLabel('Engine', this.engine) .appendWithLabel('Error', error) .end(); } /* c8 ignore stop */ if (this._autoplayRetryCount === this._maxAutoplayRetries - 1) { this.ctx.autoplayError = error as Error; this.requestUpdate(); } } if (!didAttemptSucceed) { this._autoplayRetryCount += 1; return this._attemptAutoplay(); } } protected _shouldSkipNextSrcChangeReset = true; protected _handleMediaSrcChange() { if (!this.hasUpdated) return; // Skip first flush to ensure initial properties set make it to the provider. if (this._shouldSkipNextSrcChangeReset) { this._shouldSkipNextSrcChangeReset = false; return; } /* c8 ignore start */ if (DEV_MODE) { this._logger .infoGroup('📼 media src change') .appendWithLabel('Current src', this.currentSrc) .appendWithLabel('Engine', this.engine) .end(); } /* c8 ignore stop */ this.mediaRequestQueue.serveImmediately = false; this._softResetMediaContext(); } // ------------------------------------------------------------------------------------------- // Context // ------------------------------------------------------------------------------------------- /** * Any property updated inside this object will trigger a context update. The media controller * will provide (inject) the context record to be managed by this media provider. Any updates here * will flow down from the media controller to all components. * * @internal */ readonly ctx = provideContextRecord(this, mediaContext); /** * Media context properties that should be reset when media is changed. Override this * to include additional properties. */ protected _getMediaPropsToResetWhenSrcChanges(): Set<string> { return new Set([ 'autoplayError', 'buffered', 'buffering', 'canPlay', 'canPlayThrough', 'currentSrc', 'currentTime', 'duration', 'ended', 'mediaType', 'paused', 'canPlay', 'played', 'playing', 'seekable', 'seeking', 'started', 'waiting' ]); } /** * When the `currentSrc` is changed this method is called to update any context properties * that need to be reset. Important to note that not all properties are reset, only the * properties returned from `getSoftResettableMediaContextProps()`. */ protected _softResetMediaContext() { const propsToReset = this._getMediaPropsToResetWhenSrcChanges(); /* c8 ignore start */ if (DEV_MODE) { this._logger .infoGroup('soft context reset') .appendWithLabel('Engine', this.engine) .appendWithLabel('Context', this.mediaState) .appendWithLabel('Reset props', propsToReset) .end(); } /* c8 ignore stop */ Object.keys(mediaContext).forEach((prop) => { if (propsToReset.has(prop)) { this.ctx[prop] = mediaContext[prop].initialValue; } }); } // ------------------------------------------------------------------------------------------- // Request Queue // ------------------------------------------------------------------------------------------- /** * Queue actions to be applied safely after the element has connected to the DOM. */ readonly _connectedQueue = new RequestQueue( this, /* c8 ignore next */ DEV_MODE && { name: 'connectedQueue', owner: this } ); /** * Queue actions to be taken on the current media provider when it's ready for playback, marked * by the `canPlay` property. If the media provider is ready, actions will be invoked immediately. */ readonly mediaRequestQueue = new RequestQueue( this, /* c8 ignore next */ DEV_MODE && { name: 'mediaRequestQueue', owner: this } ); // ------------------------------------------------------------------------------------------- // Orientation // ------------------------------------------------------------------------------------------- readonly screenOrientationController = new ScreenOrientationController(this); // ------------------------------------------------------------------------------------------- // Fullscreen // ------------------------------------------------------------------------------------------- readonly fullscreenController = new FullscreenController( this, this.screenOrientationController ); /** * Whether the native browser fullscreen API is available, or the current provider can * toggle fullscreen mode. This does not mean that the operation is guaranteed to be successful, * only that it can be attempted. * * @default false * @link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API */ get canRequestFullscreen(): boolean { return this.fullscreenController.isSupported; } /** * Whether the player is currently in fullscreen mode. * * @default false */ get fullscreen(): boolean { return this.ctx.fullscreen; } /** * This will indicate the orientation to lock the screen to when in fullscreen mode and * the Screen Orientation API is available. The default is `undefined` which indicates * no screen orientation change. */ @property({ attribute: 'fullscreen-orientation' }) get fullscreenOrientation(): ScreenOrientationLock | undefined { return this.fullscreenController.screenOrientationLock; } set fullscreenOrientation(lockType) { this.fullscreenController.screenOrientationLock = lockType; } override async requestFullscreen(): Promise<void> { if (this.fullscreenController.isRequestingNativeFullscreen) { return super.requestFullscreen(); } return this.fullscreenController.requestFullscreen(); } exitFullscreen(): Promise<void> { return this.fullscreenController.exitFullscreen(); } @eventListener('vds-fullscreen-change') protected _handleFullscreenChange(event: FullscreenChangeEvent) { /* c8 ignore start */ if (DEV_MODE) { this._logger .infoGroup('fullscreen change') .appendWithLabel('Event', event) .appendWithLabel('Engine', this.engine) .end(); } /* c8 ignore stop */ this.ctx.fullscreen = event.detail; } }
the_stack
import { LocalDateTime } from '@js-joda/core'; import { deepEqual } from 'assert'; import { TransactionTypeDto } from 'catbuffer-typescript'; import { expect } from 'chai'; import { NamespaceRegistrationTypeEnum, NetworkTypeEnum, TransactionInfoDTO, TransactionTypeEnum, TransferTransactionDTO, } from 'symbol-openapi-typescript-fetch-client'; import { MosaicId, NamespaceId } from '../../..'; import { CreateTransactionFromDTO } from '../../../src/infrastructure/transaction'; import { Address } from '../../../src/model/account'; import { TransferTransaction } from '../../../src/model/transaction'; import ValidateTransaction from './ValidateTransaction'; describe('CreateTransactionFromDTO', () => { describe('TransferTransaction', () => { it('standalone', () => { const transactionDto = { size: 100, signature: '7442156D839A3AC900BC0299E8701ECDABA674DCF91283223450953B005DE72C538EA54236F5E089530074CE78067CD3325CF53750B9118154C08B20A5CDC00D', signerPublicKey: '2FC3872A792933617D70E02AFF8FBDE152821A0DF0CA5FB04CB56FC3D21C8863', version: 1, network: NetworkTypeEnum.NUMBER_104, type: 16724, maxFee: '0', deadline: '1000', recipientAddress: '9826D27E1D0A26CA4E316F901E23E55C8711DB20DFD26776', message: '00746573742D6D657373616765', mosaics: [ { id: '85BBEA6CC462B244', amount: '10', }, ], } as TransferTransactionDTO; const transferTransactionDTO: TransactionInfoDTO = { id: '5CD2B76B2B3F0F0001751380', meta: { height: '78', hash: '533243B8575C4058F894C453160AFF055A4A905978AC331460F44104D831E4AC', merkleComponentHash: '533243B8575C4058F894C453160AFF055A4A905978AC331460F44104D831E4AC', index: 0, }, transaction: transactionDto, }; const transferTransaction = CreateTransactionFromDTO(transferTransactionDTO) as TransferTransaction; deepEqual(transferTransaction.recipientAddress, Address.createFromEncoded(transactionDto.recipientAddress)); expect(transferTransaction.message.payload).to.be.equal('test-message'); expect(transferTransaction.size).to.be.equal(100); }); it('standalone without message', () => { const recipientAddress = '9826D27E1D0A26CA4E316F901E23E55C8711DB20DFD26776'; const transferTransactionDTO: TransactionInfoDTO = { id: '5CD2B76B2B3F0F0001751380', meta: { height: '78', hash: '533243B8575C4058F894C453160AFF055A4A905978AC331460F44104D831E4AC', merkleComponentHash: '533243B8575C4058F894C453160AFF055A4A905978AC331460F44104D831E4AC', index: 0, }, transaction: { size: 100, signature: '7442156D839A3AC900BC0299E8701ECDABA674DCF91283223450953B005DE72C538EA54236F5E089530074CE78067CD3325CF53750B9118154C08B20A5CDC00D', signerPublicKey: '2FC3872A792933617D70E02AFF8FBDE152821A0DF0CA5FB04CB56FC3D21C8863', version: 1, network: 144, type: 16724, maxFee: '0', deadline: '1000', recipientAddress: recipientAddress, mosaics: [ { id: '85BBEA6CC462B244', amount: '10', }, ], }, }; const transferTransaction = CreateTransactionFromDTO(transferTransactionDTO) as TransferTransaction; deepEqual(transferTransaction.recipientAddress, Address.createFromEncoded(recipientAddress)); expect(transferTransaction.message.payload).to.be.equal(''); expect(transferTransaction.size).to.be.equal(100); }); it('aggregate', () => { const aggregateTransferTransactionDTO = { id: '5A0069D83F17CF0001777E55', meta: { hash: '671653C94E2254F2A23EFEDB15D67C38332AED1FBD24B063C0A8E675582B6A96', height: '1860', index: 0, merkleComponentHash: '81E5E7AE49998802DABC816EC10158D3A7879702FF29084C2C992CD1289877A7', }, transaction: { size: 100, cosignatures: [ { version: '0', signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { id: '5A0069D83F17CF0001777E56', meta: { aggregateHash: '3D28C804EDD07D5A728E5C5FFEC01AB07AFA5766AE6997B38526D36015A4D006', aggregateId: '5A0069D83F17CF0001777E55', height: '1860', index: 0, }, transaction: { message: '00746573742D6D657373616765', mosaics: [ { amount: '1000', id: '85BBEA6CC462B244', }, ], recipientAddress: '9826D27E1D0A26CA4E316F901E23E55C8711DB20DFD26776', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16724, version: 1, network: 144, }, }, ], type: 16705, version: 1, network: 144, }, }; const aggregateTransferTransaction = CreateTransactionFromDTO(aggregateTransferTransactionDTO); expect(aggregateTransferTransaction.size).eq(100); ValidateTransaction.validateAggregateTx(aggregateTransferTransaction, aggregateTransferTransactionDTO); }); }); describe('Embedded transaction only', () => { it('standalone', () => { const transferTransactionDTO = { id: '5CD2B76B2B3F0F0001751380', meta: { height: '78', aggregateHash: 'D6A48BFD66920825D748D2CF92B025588F3A030C98633C442B4704BF407160B9', aggregateId: '5F729AA24655A25B54840CB7', index: 0, }, transaction: { signerPublicKey: '2FC3872A792933617D70E02AFF8FBDE152821A0DF0CA5FB04CB56FC3D21C8863', version: 1, network: 144, type: 16724, recipientAddress: '9826D27E1D0A26CA4E316F901E23E55C8711DB20DFD26776', message: '00746573742D6D657373616765', mosaics: [ { id: '85BBEA6CC462B244', amount: '10', }, ], }, }; const transferTransaction = CreateTransactionFromDTO(transferTransactionDTO) as TransferTransaction; deepEqual(transferTransaction.recipientAddress, Address.createFromEncoded(transferTransactionDTO.transaction.recipientAddress)); expect(transferTransaction.message.payload).to.be.equal('test-message'); expect(transferTransaction.deadline.adjustedValue).to.be.equal(LocalDateTime.MIN.second()); expect(transferTransaction.maxFee.toString()).to.be.equal('0'); }); }); describe('NamespaceRegistrationTransaction', () => { describe('namespace', () => { it('standalone', () => { const registerNamespaceTransactionDTO = { id: '59FDA0733F17CF0001772CA7', meta: { hash: '18C036C20B32348D63684E09A13128A2C18F6A75650D3A5FB43853D716E5E219', height: '1', index: 19, merkleComponentHash: '18C036C20B32348D63684E09A13128A2C18F6A75650D3A5FB43853D716E5E219', }, transaction: { size: 100, deadline: '1', duration: '1000', maxFee: '0', name: 'a2p1mg', id: '85BBEA6CC462B244', registrationType: NamespaceRegistrationTypeEnum.NUMBER_0, signature: '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E0' + '2F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16718, version: 1, network: 144, }, }; const transferTransaction = CreateTransactionFromDTO(registerNamespaceTransactionDTO); expect(transferTransaction.size).eq(100); ValidateTransaction.validateStandaloneTx(transferTransaction, registerNamespaceTransactionDTO); }); it('aggregate', () => { const aggregateNamespaceRegistrationTransactionDTO = { id: '5A0069D83F17CF0001777E55', meta: { hash: '671653C94E2254F2A23EFEDB15D67C38332AED1FBD24B063C0A8E675582B6A96', height: '1860', index: 0, merkleComponentHash: '81E5E7AE49998802DABC816EC10158D3A7879702FF29084C2C992CD1289877A7', }, transaction: { size: 100, cosignatures: [ { version: '0', signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { id: '5A0069D83F17CF0001777E56', meta: { aggregateHash: '3D28C804EDD07D5A728E5C5FFEC01AB07AFA5766AE6997B38526D36015A4D006', aggregateId: '5A0069D83F17CF0001777E55', height: '1860', index: 0, }, transaction: { duration: '1000', name: 'a2p1mg', id: '85BBEA6CC462B244', registrationType: 0, signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16718, version: 1, network: 144, }, }, ], type: 16705, version: 1, network: 144, }, }; const aggregateNamespaceRegistrationTransaction = CreateTransactionFromDTO(aggregateNamespaceRegistrationTransactionDTO); expect(aggregateNamespaceRegistrationTransaction.size).eq(100); ValidateTransaction.validateAggregateTx( aggregateNamespaceRegistrationTransaction, aggregateNamespaceRegistrationTransactionDTO, ); }); }); describe('subnamespace', () => { it('standalone', () => { const registerNamespaceTransactionDTO = { id: '59FDA0733F17CF0001772CA7', meta: { hash: '18C036C20B32348D63684E09A13128A2C18F6A75650D3A5FB43853D716E5E219', height: '1', index: 19, merkleComponentHash: '18C036C20B32348D63684E09A13128A2C18F6A75650D3A5FB43853D716E5E219', }, transaction: { size: 100, deadline: '1', maxFee: '0', name: '0unius', id: '99BBEA6CC462B244', registrationType: 1, parentId: '85BBEA6CC462B244', signature: '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9' + 'E02F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16718, version: 1, network: 144, }, }; const transferTransaction = CreateTransactionFromDTO(registerNamespaceTransactionDTO); expect(transferTransaction.size).eq(100); ValidateTransaction.validateStandaloneTx(transferTransaction, registerNamespaceTransactionDTO); }); it('aggregate', () => { const aggregateNamespaceRegistrationTransactionDTO = { id: '5A0069D83F17CF0001777E55', meta: { hash: '671653C94E2254F2A23EFEDB15D67C38332AED1FBD24B063C0A8E675582B6A96', height: '1860', index: 0, merkleComponentHash: '81E5E7AE49998802DABC816EC10158D3A7879702FF29084C2C992CD1289877A7', }, transaction: { size: 100, cosignatures: [ { version: '0', signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { id: '5A0069D83F17CF0001777E56', meta: { aggregateHash: '3D28C804EDD07D5A728E5C5FFEC01AB07AFA5766AE6997B38526D36015A4D006', aggregateId: '5A0069D83F17CF0001777E55', height: '1860', index: 0, }, transaction: { name: '0unius', id: '99BBEA6CC462B244', registrationType: 1, parentId: '85BBEA6CC462B244', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16718, version: 1, network: 144, }, }, ], type: 16705, version: 1, network: 144, }, }; const aggregateNamespaceRegistrationTransaction = CreateTransactionFromDTO(aggregateNamespaceRegistrationTransactionDTO); expect(aggregateNamespaceRegistrationTransaction.size).eq(100); ValidateTransaction.validateAggregateTx( aggregateNamespaceRegistrationTransaction, aggregateNamespaceRegistrationTransactionDTO, ); }); }); }); describe('MosaicDefinitionTransaction', () => { it('standalone', () => { const mosaicDefinitionTransactionDTO = { id: '59FDA0733F17CF0001772CA7', meta: { hash: '18C036C20B32348D63684E09A13128A2C18F6A75650D3A5FB43853D716E5E219', height: '1', index: 19, merkleComponentHash: '18C036C20B32348D63684E09A13128A2C18F6A75650D3A5FB43853D716E5E219', }, transaction: { size: 100, deadline: '1', maxFee: '0', id: '85BBEA6CC462B244', nonce: 1177824765, flags: 7, diversibility: 6, duration: '1000', signature: '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E02F6EE63025FE' + 'EBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16717, version: 1, network: 144, }, }; const mosaicDefinitionTransaction = CreateTransactionFromDTO(mosaicDefinitionTransactionDTO); expect(mosaicDefinitionTransaction.size).eq(100); ValidateTransaction.validateStandaloneTx(mosaicDefinitionTransaction, mosaicDefinitionTransactionDTO); }); it('aggregate', () => { const aggregateMosaicDefinitionTransactionDTO = { id: '5A0069D83F17CF0001777E55', meta: { hash: '671653C94E2254F2A23EFEDB15D67C38332AED1FBD24B063C0A8E675582B6A96', height: '1860', index: 0, merkleComponentHash: '81E5E7AE49998802DABC816EC10158D3A7879702FF29084C2C992CD1289877A7', }, transaction: { size: 100, cosignatures: [ { version: '0', signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { id: '5A0069D83F17CF0001777E56', meta: { aggregateHash: '3D28C804EDD07D5A728E5C5FFEC01AB07AFA5766AE6997B38526D36015A4D006', aggregateId: '5A0069D83F17CF0001777E55', height: '1860', index: 0, }, transaction: { id: '85BBEA6CC462B244', nonce: 1177824765, flags: 7, divisibility: 6, duration: '1000', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16717, version: 1, network: 144, }, }, ], type: 16705, version: 1, network: 144, }, }; const aggregateNamespaceRegistrationTransaction = CreateTransactionFromDTO(aggregateMosaicDefinitionTransactionDTO); expect(aggregateNamespaceRegistrationTransaction.size).eq(100); ValidateTransaction.validateAggregateTx(aggregateNamespaceRegistrationTransaction, aggregateMosaicDefinitionTransactionDTO); }); }); describe('MosaicSupplyChangeTransaction', () => { it('standalone', () => { const mosaicSupplyChangeTransactionDTO = { id: '59FDA0733F17CF0001772CA7', meta: { hash: '18C036C20B32348D63684E09A13128A2C18F6A75650D3A5FB43853D716E5E219', height: '1', index: 19, merkleComponentHash: '18C036C20B32348D63684E09A13128A2C18F6A75650D3A5FB43853D716E5E219', }, transaction: { size: 100, deadline: '1', delta: '1000', action: 1, maxFee: '0', mosaicId: '85BBEA6CC462B244', signature: '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E0' + '2F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16973, version: 1, network: 144, }, }; const mosaicSupplyChangeTransaction = CreateTransactionFromDTO(mosaicSupplyChangeTransactionDTO); expect(mosaicSupplyChangeTransaction.size).eq(100); ValidateTransaction.validateStandaloneTx(mosaicSupplyChangeTransaction, mosaicSupplyChangeTransactionDTO); }); it('aggregate', () => { const aggregateMosaicSupplyChangeTransactionDTO = { id: '5A0069D83F17CF0001777E55', meta: { hash: '671653C94E2254F2A23EFEDB15D67C38332AED1FBD24B063C0A8E675582B6A96', height: '1860', index: 0, merkleComponentHash: '81E5E7AE49998802DABC816EC10158D3A7879702FF29084C2C992CD1289877A7', }, transaction: { size: 100, cosignatures: [ { version: '0', signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { id: '5A0069D83F17CF0001777E56', meta: { aggregateHash: '3D28C804EDD07D5A728E5C5FFEC01AB07AFA5766AE6997B38526D36015A4D006', aggregateId: '5A0069D83F17CF0001777E55', height: '1860', index: 0, }, transaction: { delta: '1000', action: 1, mosaicId: '85BBEA6CC462B244', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16973, version: 1, network: 144, }, }, ], type: 16705, version: 1, network: 144, }, }; const aggregateMosaicSupplyChangeTransaction = CreateTransactionFromDTO(aggregateMosaicSupplyChangeTransactionDTO); expect(aggregateMosaicSupplyChangeTransaction.size).eq(100); ValidateTransaction.validateAggregateTx(aggregateMosaicSupplyChangeTransaction, aggregateMosaicSupplyChangeTransactionDTO); }); }); describe('MosaicSupplyRevocationTransaction', () => { it('standalone', () => { const dto: TransactionInfoDTO = { meta: { height: '212', hash: '700E495D9E57B5701B3009BF02F522A9C1D7B15ECBBA65B3BD6F52A79EBBC7EB', merkleComponentHash: '700E495D9E57B5701B3009BF02F522A9C1D7B15ECBBA65B3BD6F52A79EBBC7EB', index: 0, timestamp: '62955743775', feeMultiplier: 11904, }, transaction: { size: 168, signature: '6F2FE34C6F09E8C4FB98569831E46A274809CA2D18405E811A0480EEC424C8034D51B65C692CA36BC0533733E4C7B83076B9F9B2FE439314B74E4AD78B36100F', signerPublicKey: '5AB0BC217283542BF3BC45570FCC5C7232825B8DDDFBFF1F9CA06747BB939F92', version: 1, network: 152, type: 17229, maxFee: '2000000', deadline: '62962930644', sourceAddress: '986E584F3CE223A494D3444BDCA4A425AECED2B1C3318DF1', mosaicId: '6CEE17786759C983', amount: '1', }, id: '61894560E8034A392B5FD905', }; const transaction = CreateTransactionFromDTO(dto); expect(transaction.type).eq(TransactionTypeDto.MOSAIC_SUPPLY_REVOCATION); ValidateTransaction.validateStandaloneTx(transaction, dto); }); }); describe('MultisigAccountModificationTransaction', () => { it('standalone', () => { const modifyMultisigAccountTransactionDTO = { id: '59FDA0733F17CF0001772CA7', meta: { hash: '18C036C20B32348D63684E09A13128A2C18F6A75650D3A5FB43853D716E5E219', height: '1', index: 19, merkleComponentHash: '18C036C20B32348D63684E09A13128A2C18F6A75650D3A5FB43853D716E5E219', }, transaction: { size: 100, deadline: '1', maxFee: '0', minApprovalDelta: 1, minRemovalDelta: 1, addressAdditions: ['9826D27E1D0A26CA4E316F901E23E55C8711DB20DFD26776'], addressDeletions: [], signature: '553E696EB4A54E43A11D180EBA57E4B89D0048C9DD2604A9E0608120018B9E0' + '2F6EE63025FEEBCED3293B622AF8581334D0BDAB7541A9E7411E7EE4EF0BC5D0E', signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16725, version: 1, network: 144, }, }; const modifyMultisigAccountTransaction = CreateTransactionFromDTO(modifyMultisigAccountTransactionDTO); expect(modifyMultisigAccountTransaction.size).eq(100); ValidateTransaction.validateStandaloneTx(modifyMultisigAccountTransaction, modifyMultisigAccountTransactionDTO); }); it('aggregate', () => { const aggregateMultisigAccountModificationTransactionDTO = { id: '5A0069D83F17CF0001777E55', meta: { hash: '671653C94E2254F2A23EFEDB15D67C38332AED1FBD24B063C0A8E675582B6A96', height: '1860', index: 0, merkleComponentHash: '81E5E7AE49998802DABC816EC10158D3A7879702FF29084C2C992CD1289877A7', }, transaction: { size: 100, cosignatures: [ { version: '0', signature: '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07', signerPublicKey: 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630', }, ], deadline: '1000', maxFee: '0', signature: '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606', signerPublicKey: '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D', transactions: [ { id: '5A0069D83F17CF0001777E56', meta: { aggregateHash: '3D28C804EDD07D5A728E5C5FFEC01AB07AFA5766AE6997B38526D36015A4D006', aggregateId: '5A0069D83F17CF0001777E55', height: '1860', index: 0, }, transaction: { minApprovalDelta: 1, minRemovalDelta: 1, addressAdditions: ['9826D27E1D0A26CA4E316F901E23E55C8711DB20DFD26776'], addressDeletions: [], signerPublicKey: 'B4F12E7C9F6946091E2CB8B6D3A12B50D17CCBBF646386EA27CE2946A7423DCF', type: 16725, version: 1, network: 144, }, }, ], type: 16705, version: 1, network: 144, }, }; const aggregateMultisigAccountModificationTransaction = CreateTransactionFromDTO( aggregateMultisigAccountModificationTransactionDTO, ); expect(aggregateMultisigAccountModificationTransaction.size).eq(100); ValidateTransaction.validateAggregateTx( aggregateMultisigAccountModificationTransaction, aggregateMultisigAccountModificationTransactionDTO, ); }); }); describe('Metadata Transactions', () => { // standalone tx constants const testTxSignature = '7442156D839A3AC900BC0299E8701ECDABA674DCF91283223450953B005DE72C538EA54236F5E089530074CE78067CD3325CF53750B9118154C08B20A5CDC00D'; const testTxSignerPublicKey = '2FC3872A792933617D70E02AFF8FBDE152821A0DF0CA5FB04CB56FC3D21C8863'; const testTxDeadline = '71756535303'; const testTxHeight = '1'; const testTxHash = '533243B8575C4058F894C453160AFF055A4A905978AC331460F44104D831E4AC'; const testTxMerkleComponentHash = '533243B8575C4058F894C453160AFF055A4A905978AC331460F44104D831E4AC'; const testTxId = '5CD2B76B2B3F0F0001751380'; const testTxIndex = 0; const testTxSize = 100; const testTxMaxFee = '0'; // aggregate tx constants const testAggTxId = '5A0069D83F17CF0001777E55'; const testAggTxHash = '671653C94E2254F2A23EFEDB15D67C38332AED1FBD24B063C0A8E675582B6A96'; const testAggTxHeight = '1860'; const testAggTxIndex = 0; const testAggMerkleComponentHash = '81E5E7AE49998802DABC816EC10158D3A7879702FF29084C2C992CD1289877A7'; const testAggTxSize = 100; const testAggTxCosigSignature = '5780C8DF9D46BA2BCF029DCC5D3BF55FE1CB5BE7ABCF30387C4637DD' + 'EDFC2152703CA0AD95F21BB9B942F3CC52FCFC2064C7B84CF60D1A9E69195F1943156C07'; const testAggCosigSignerPublicKey = 'A5F82EC8EBB341427B6785C8111906CD0DF18838FB11B51CE0E18B5E79DFF630'; const testAggTxDeadline = '1000'; const testAggTxMaxFee = '0'; const testAggTxSignature = '939673209A13FF82397578D22CC96EB8516A6760C894D9B7535E3A1E0680' + '07B9255CFA9A914C97142A7AE18533E381C846B69D2AE0D60D1DC8A55AD120E2B606'; const testAggTxSignerPublicKey = '7681ED5023141D9CDCF184E5A7B60B7D466739918ED5DA30F7E71EA7B86EFF2D'; // metadata tx constants const testTargetAddress = 'TATNE7Q5BITMUTRRN6IB4I7FLSDRDWZA37JGO5Q'; const testScopedMedataKey = '00000000000003E8'; const prepBaseTxDto = (txType: TransactionTypeEnum) => ({ signerPublicKey: testTxSignerPublicKey, version: 1, network: NetworkTypeEnum.NUMBER_152, type: txType, maxFee: testTxMaxFee, deadline: testTxDeadline, }); const prepAggregateTxDto = (innerTransaction) => ({ id: testAggTxId, meta: { hash: testAggTxHash, height: testAggTxHeight, index: testAggTxIndex, merkleComponentHash: testAggMerkleComponentHash, }, transaction: { size: testAggTxSize, cosignatures: [ { version: '0', signature: testAggTxCosigSignature, signerPublicKey: testAggCosigSignerPublicKey, }, ], deadline: testAggTxDeadline, maxFee: testAggTxMaxFee, signature: testAggTxSignature, signerPublicKey: testAggTxSignerPublicKey, transactions: [ { id: testTxId, meta: { aggregateHash: testAggTxHash, aggregateId: testAggTxId, height: testAggTxHeight, index: testAggTxIndex, }, transaction: innerTransaction, }, ], type: 16705, version: 1, network: NetworkTypeEnum.NUMBER_152, }, }); const prepStandaloneTxDto = (transactionDto) => ({ id: testTxId, meta: { height: testTxHeight, hash: testTxHash, merkleComponentHash: testTxMerkleComponentHash, index: testTxIndex, }, transaction: transactionDto, }); const prepTransactionDto = (txDetails) => ({ size: testTxSize, signature: testTxSignature, ...txDetails, }); const testStandaloneAndAggregate = (baseMetadataTxDto, txType) => { it('standalone', () => { // arrange const metadataTransactionDto: TransactionInfoDTO = prepStandaloneTxDto(prepTransactionDto(baseMetadataTxDto)); // act const metadataTransaction = CreateTransactionFromDTO(metadataTransactionDto); // assert expect(metadataTransaction.type).eq(txType); expect(metadataTransaction.size).eq(testTxSize); ValidateTransaction.validateStandaloneTx(metadataTransaction, metadataTransactionDto); }); it('aggregate', () => { // arrange const aggregateMetadataTransactionDto = prepAggregateTxDto(baseMetadataTxDto); // act const aggregateMetadataTransaction = CreateTransactionFromDTO(aggregateMetadataTransactionDto); // assert expect(aggregateMetadataTransaction.size).eq(testAggTxSize); ValidateTransaction.validateAggregateTx(aggregateMetadataTransaction, aggregateMetadataTransactionDto); }); }; describe('AccountMetadataTransaction', () => { const baseAccountMetadataTxDto = { ...prepBaseTxDto(TransactionTypeEnum.NUMBER_16708), targetAddress: testTargetAddress, scopedMetadataKey: testScopedMedataKey, valueSizeDelta: 49, valueSize: 49, value: '5468697320697320746865206D65737361676520666F722074686973206163636F756E742120E6B189E5AD973839363634', }; testStandaloneAndAggregate(baseAccountMetadataTxDto, TransactionTypeDto.ACCOUNT_METADATA); }); describe('MosaicMetadataTransaction', () => { const baseMosaicMetadataTxDto = { ...prepBaseTxDto(TransactionTypeEnum.NUMBER_16964), targetAddress: testTargetAddress, scopedMetadataKey: testScopedMedataKey, targetMosaicId: new MosaicId([2262289484, 3405110546]).toHex(), valueSizeDelta: 48, valueSize: 48, value: '5468697320697320746865206D65737361676520666F722074686973206D6F736169632120E6B189E5AD973839363634', }; testStandaloneAndAggregate(baseMosaicMetadataTxDto, TransactionTypeDto.MOSAIC_METADATA); }); describe('NamespaceMetadataTransaction', () => { const baseNamespaceMetadataTxDto = { ...prepBaseTxDto(TransactionTypeEnum.NUMBER_17220), targetAddress: testTargetAddress, scopedMetadataKey: testScopedMedataKey, targetNamespaceId: new NamespaceId([929036875, 2226345261]).toHex(), valueSizeDelta: 51, valueSize: 51, value: '5468697320697320746865206D65737361676520666F722074686973206E616D6573706163652120E6B189E5AD973839363634', }; testStandaloneAndAggregate(baseNamespaceMetadataTxDto, TransactionTypeDto.NAMESPACE_METADATA); }); }); });
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages Security Center Automation and Continuous Export. This resource supports three types of destination in the `action`, Logic Apps, Log Analytics and Event Hubs * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const current = azure.core.getClientConfig({}); * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleEventHubNamespace = new azure.eventhub.EventHubNamespace("exampleEventHubNamespace", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * sku: "Standard", * capacity: 2, * }); * const exampleEventHub = new azure.eventhub.EventHub("exampleEventHub", { * namespaceName: exampleEventHubNamespace.name, * resourceGroupName: exampleResourceGroup.name, * partitionCount: 2, * messageRetention: 2, * }); * const exampleAuthorizationRule = new azure.eventhub.AuthorizationRule("exampleAuthorizationRule", { * namespaceName: exampleEventHubNamespace.name, * eventhubName: exampleEventHub.name, * resourceGroupName: exampleResourceGroup.name, * listen: true, * send: false, * manage: false, * }); * const exampleAutomation = new azure.securitycenter.Automation("exampleAutomation", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * actions: [{ * type: "EventHub", * resourceId: exampleEventHub.id, * connectionString: exampleAuthorizationRule.primaryConnectionString, * }], * sources: [{ * eventSource: "Alerts", * ruleSets: [{ * rules: [{ * propertyPath: "properties.metadata.severity", * operator: "Equals", * expectedValue: "High", * propertyType: "String", * }], * }], * }], * scopes: [current.then(current => `/subscriptions/${current.subscriptionId}`)], * }); * ``` * * ## Import * * Security Center Automations can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:securitycenter/automation:Automation example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Security/automations/automation1 * ``` */ export class Automation extends pulumi.CustomResource { /** * Get an existing Automation 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?: AutomationState, opts?: pulumi.CustomResourceOptions): Automation { return new Automation(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:securitycenter/automation:Automation'; /** * Returns true if the given object is an instance of Automation. 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 Automation { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Automation.__pulumiType; } /** * One or more `action` blocks as defined below. An `action` tells this automation where the data is to be sent to upon being evaluated by the rules in the `source`. */ public readonly actions!: pulumi.Output<outputs.securitycenter.AutomationAction[]>; /** * Specifies the description for the Security Center Automation. */ public readonly description!: pulumi.Output<string | undefined>; /** * Boolean to enable or disable this Security Center Automation. */ public readonly enabled!: pulumi.Output<boolean | undefined>; /** * The Azure Region where the Security Center Automation should exist. Changing this forces a new Security Center Automation to be created. */ public readonly location!: pulumi.Output<string>; /** * The name which should be used for this Security Center Automation. Changing this forces a new Security Center Automation to be created. */ public readonly name!: pulumi.Output<string>; /** * The name of the Resource Group where the Security Center Automation should exist. Changing this forces a new Security Center Automation to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * A list of scopes on which the automation logic is applied, at least one is required. Supported scopes are a subscription (in this format `/subscriptions/00000000-0000-0000-0000-000000000000`) or a resource group under that subscription (in the format `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example`). The automation will only apply on defined scopes. */ public readonly scopes!: pulumi.Output<string[]>; /** * One or more `source` blocks as defined below. A `source` defines what data types will be processed and a set of rules to filter that data. */ public readonly sources!: pulumi.Output<outputs.securitycenter.AutomationSource[]>; /** * A mapping of tags assigned to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * Create a Automation 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: AutomationArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: AutomationArgs | AutomationState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as AutomationState | undefined; inputs["actions"] = state ? state.actions : undefined; inputs["description"] = state ? state.description : undefined; inputs["enabled"] = state ? state.enabled : undefined; inputs["location"] = state ? state.location : undefined; inputs["name"] = state ? state.name : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["scopes"] = state ? state.scopes : undefined; inputs["sources"] = state ? state.sources : undefined; inputs["tags"] = state ? state.tags : undefined; } else { const args = argsOrState as AutomationArgs | undefined; if ((!args || args.actions === undefined) && !opts.urn) { throw new Error("Missing required property 'actions'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } if ((!args || args.scopes === undefined) && !opts.urn) { throw new Error("Missing required property 'scopes'"); } if ((!args || args.sources === undefined) && !opts.urn) { throw new Error("Missing required property 'sources'"); } inputs["actions"] = args ? args.actions : undefined; inputs["description"] = args ? args.description : undefined; inputs["enabled"] = args ? args.enabled : undefined; inputs["location"] = args ? args.location : undefined; inputs["name"] = args ? args.name : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["scopes"] = args ? args.scopes : undefined; inputs["sources"] = args ? args.sources : undefined; inputs["tags"] = args ? args.tags : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Automation.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Automation resources. */ export interface AutomationState { /** * One or more `action` blocks as defined below. An `action` tells this automation where the data is to be sent to upon being evaluated by the rules in the `source`. */ actions?: pulumi.Input<pulumi.Input<inputs.securitycenter.AutomationAction>[]>; /** * Specifies the description for the Security Center Automation. */ description?: pulumi.Input<string>; /** * Boolean to enable or disable this Security Center Automation. */ enabled?: pulumi.Input<boolean>; /** * The Azure Region where the Security Center Automation should exist. Changing this forces a new Security Center Automation to be created. */ location?: pulumi.Input<string>; /** * The name which should be used for this Security Center Automation. Changing this forces a new Security Center Automation to be created. */ name?: pulumi.Input<string>; /** * The name of the Resource Group where the Security Center Automation should exist. Changing this forces a new Security Center Automation to be created. */ resourceGroupName?: pulumi.Input<string>; /** * A list of scopes on which the automation logic is applied, at least one is required. Supported scopes are a subscription (in this format `/subscriptions/00000000-0000-0000-0000-000000000000`) or a resource group under that subscription (in the format `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example`). The automation will only apply on defined scopes. */ scopes?: pulumi.Input<pulumi.Input<string>[]>; /** * One or more `source` blocks as defined below. A `source` defines what data types will be processed and a set of rules to filter that data. */ sources?: pulumi.Input<pulumi.Input<inputs.securitycenter.AutomationSource>[]>; /** * A mapping of tags assigned to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; } /** * The set of arguments for constructing a Automation resource. */ export interface AutomationArgs { /** * One or more `action` blocks as defined below. An `action` tells this automation where the data is to be sent to upon being evaluated by the rules in the `source`. */ actions: pulumi.Input<pulumi.Input<inputs.securitycenter.AutomationAction>[]>; /** * Specifies the description for the Security Center Automation. */ description?: pulumi.Input<string>; /** * Boolean to enable or disable this Security Center Automation. */ enabled?: pulumi.Input<boolean>; /** * The Azure Region where the Security Center Automation should exist. Changing this forces a new Security Center Automation to be created. */ location?: pulumi.Input<string>; /** * The name which should be used for this Security Center Automation. Changing this forces a new Security Center Automation to be created. */ name?: pulumi.Input<string>; /** * The name of the Resource Group where the Security Center Automation should exist. Changing this forces a new Security Center Automation to be created. */ resourceGroupName: pulumi.Input<string>; /** * A list of scopes on which the automation logic is applied, at least one is required. Supported scopes are a subscription (in this format `/subscriptions/00000000-0000-0000-0000-000000000000`) or a resource group under that subscription (in the format `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example`). The automation will only apply on defined scopes. */ scopes: pulumi.Input<pulumi.Input<string>[]>; /** * One or more `source` blocks as defined below. A `source` defines what data types will be processed and a set of rules to filter that data. */ sources: pulumi.Input<pulumi.Input<inputs.securitycenter.AutomationSource>[]>; /** * A mapping of tags assigned to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import Player from "../models/Player"; import {IMission} from "./IMission"; import {TextChannel, User} from "discord.js"; import MissionSlot, {MissionSlots} from "../models/MissionSlot"; import {DailyMissions} from "../models/DailyMission"; import Mission, {Missions} from "../models/Mission"; import {hoursToMilliseconds} from "../utils/TimeUtils"; import {DraftBotEmbed} from "../messages/DraftBotEmbed"; import {MissionDifficulty} from "./MissionDifficulty"; import {Data} from "../Data"; import {Campaign} from "./Campaign"; import {Entities, Entity} from "../models/Entity"; import {CompletedMission, CompletedMissionType} from "./CompletedMission"; import {DraftBotCompletedMissions} from "../messages/DraftBotCompletedMissions"; import {draftBotClient} from "../bot"; import {Translations} from "../Translations"; import {Constants} from "../Constants"; import {RandomUtils} from "../utils/RandomUtils"; export class MissionsController { static getMissionInterface(missionId: string): IMission { try { return <IMission>(require("./interfaces/" + missionId).missionInterface); } catch { return require("./DefaultInterface").missionInterface; } } /** * update all the mission of the user * @param discordUserId * @param channel * @param language * @param missionId * @param count * @param params * @param set */// eslint-disable-next-line max-params static async update(discordUserId: string, channel: TextChannel, language: string, missionId: string, count = 1, params: { [key: string]: any } = {}, set = false): Promise<void> { if (!discordUserId) { console.error("Cannot update mission because discordUserId is not defined"); console.error("Data: discordUserId = " + discordUserId + "; channel = " + channel + "; missionId = " + missionId + "; count = " + count + "; params = " + params); return; } const [entity] = await Entities.getOrRegister(discordUserId); await MissionsController.handleExpiredMissions(entity.Player, draftBotClient.users.cache.get(discordUserId), channel, language); const [completedDaily, completedCampaign] = await MissionsController.updateMissionsCounts(entity.Player, missionId, count, params, set); const completedMissions = await MissionsController.completeAndUpdateMissions(entity.Player, completedDaily, completedCampaign, language); if (completedMissions.length !== 0) { await MissionsController.updatePlayerStats(entity, completedMissions, channel, language); await MissionsController.sendCompletedMissions(discordUserId, entity.Player, completedMissions, channel, language); } } /** * update the counts of the different mission the user has * @param player * @param missionId * @param count * @param params * @param set * @private * @return true if the daily mission is finished and needs to be said to the player */ private static async updateMissionsCounts(player: Player, missionId: string, count = 1, params: { [key: string]: any } = {}, set = false): Promise<boolean[]> { const missionInterface = this.getMissionInterface(missionId); let completedCampaign = false; completedCampaign = await this.checkMissionSlots(player, missionId, missionInterface, params, set, count, completedCampaign); if (!player.PlayerMissionsInfo.hasCompletedDailyMission()) { const dailyMission = await DailyMissions.getOrGenerate(); if (dailyMission.missionId === missionId) { if (missionInterface.areParamsMatchingVariant(dailyMission.variant, params)) { player.PlayerMissionsInfo.dailyMissionNumberDone += count; if (player.PlayerMissionsInfo.dailyMissionNumberDone > dailyMission.objective) { player.PlayerMissionsInfo.dailyMissionNumberDone = dailyMission.objective; } await player.PlayerMissionsInfo.save(); if (player.PlayerMissionsInfo.dailyMissionNumberDone >= dailyMission.objective) { player.PlayerMissionsInfo.lastDailyMissionCompleted = new Date(); await player.PlayerMissionsInfo.save(); return [true, completedCampaign]; } } } } return [false, completedCampaign]; } /** * updates the missions located in the mission slots of the player * @param player * @param missionId * @param missionInterface * @param params * @param set * @param count * @param completedCampaign * @private */// eslint-disable-next-line max-params private static async checkMissionSlots(player: Player, missionId: string, missionInterface: IMission, params: { [p: string]: any }, set: boolean, count: number, completedCampaign: boolean) { for (const mission of player.MissionSlots) { if (mission.missionId === missionId && missionInterface.areParamsMatchingVariant(mission.missionVariant, params) && !mission.hasExpired() && !mission.isCompleted()) { if (set) { mission.numberDone = count; } else { mission.numberDone += count; } if (mission.numberDone > mission.missionObjective) { mission.numberDone = mission.missionObjective; } if (mission.isCampaign() && mission.isCompleted()) { completedCampaign = true; } await mission.save(); } } return completedCampaign; } /** * complete and update mission of a user * @param player * @param completedDailyMission * @param completedCampaign * @param language */ static async completeAndUpdateMissions(player: Player, completedDailyMission: boolean, completedCampaign: boolean, language: string): Promise<CompletedMission[]> { const completedMissions: CompletedMission[] = []; completedMissions.push(...await Campaign.updatePlayerCampaign(completedCampaign, player, language)); for (const mission of player.MissionSlots) { if (mission.isCompleted() && !mission.isCampaign()) { completedMissions.push( new CompletedMission( mission.xpToWin, 0, // Don't win gems in secondary missions mission.moneyToWin, await mission.Mission.formatDescription(mission.missionObjective, mission.missionVariant, language), CompletedMissionType.NORMAL ) ); await mission.destroy(); } } if (completedDailyMission) { const dailyMission = await DailyMissions.getOrGenerate(); completedMissions.push(new CompletedMission( dailyMission.xpToWin, dailyMission.gemsToWin, Math.round(dailyMission.moneyToWin / Constants.MISSIONS.DAILY_MISSION_MONEY_PENALITY), // daily missions gives less money than secondary missions await dailyMission.Mission.formatDescription(dailyMission.objective, dailyMission.variant, language), CompletedMissionType.DAILY )); } return completedMissions; } static async sendCompletedMissions(discordUserId: string, player: Player, completedMissions: CompletedMission[], channel: TextChannel, language: string) { await channel.send({ embeds: [ new DraftBotCompletedMissions(draftBotClient.users.cache.get(discordUserId), completedMissions, language) ] }); } static async updatePlayerStats(entity: Entity, completedMissions: CompletedMission[], channel: TextChannel, language: string) { for (const completedMission of completedMissions) { entity.Player.PlayerMissionsInfo.gems += completedMission.gemsToWin; await entity.Player.addExperience(completedMission.xpToWin, entity, channel, language); await entity.Player.addMoney(entity, completedMission.moneyToWin, channel, language); } await entity.Player.PlayerMissionsInfo.save(); await entity.Player.save(); } static async handleExpiredMissions(player: Player, user: User, channel: TextChannel, language: string) { const expiredMissions: MissionSlot[] = []; for (const mission of player.MissionSlots) { if (mission.hasExpired()) { expiredMissions.push(mission); await mission.destroy(); } } if (expiredMissions.length === 0) { return; } player.MissionSlots = player.MissionSlots.filter(missionSlot => !missionSlot.hasExpired()); const tr = Translations.getModule("models.missions", language); let missionsExpiredDesc = ""; for (const mission of expiredMissions) { missionsExpiredDesc += "- " + await mission.Mission.formatDescription( mission.missionObjective, mission.missionVariant, language) + " (" + mission.numberDone + "/" + mission.missionObjective + ")\n"; } await channel.send({ embeds: [ new DraftBotEmbed() .setAuthor(tr.format( "missionsExpiredTitle", { missionsCount: expiredMissions.length, pseudo: await player.getPseudo(language) } ), user.displayAvatarURL()) .setDescription(tr.format( "missionsExpiredDesc", { missionsCount: expiredMissions.length, missionsExpired: missionsExpiredDesc } )) ] }); } public static async generateRandomDailyMissionProperties(): Promise<{ mission: Mission, index: number, variant: number }> { const mission = await Missions.getRandomDailyMission(); return this.generateMissionProperties(mission.id, MissionDifficulty.EASY, mission, true); } public static async generateMissionProperties(missionId: string, difficulty: MissionDifficulty, mission: Mission = null, daily = false) : Promise<{ mission: Mission, index: number, variant: number } | null> { if (!mission) { mission = await Missions.getById(missionId); if (!mission) { return null; } } const missionData = Data.getModule("missions." + missionId); let index; if (!daily) { switch (difficulty) { case MissionDifficulty.EASY: if (!mission.canBeEasy) { return null; } index = missionData.getRandomNumberFromArray("difficulties.easy"); break; case MissionDifficulty.MEDIUM: if (!mission.canBeMedium) { return null; } index = missionData.getRandomNumberFromArray("difficulties.medium"); break; case MissionDifficulty.HARD: if (!mission.canBeHard) { return null; } index = missionData.getRandomNumberFromArray("difficulties.hard"); break; default: return null; } } else { index = missionData.getRandomNumberFromArray("dailyIndexes"); } return { mission: mission, index, variant: await this.getMissionInterface(mission.id).generateRandomVariant(difficulty) }; } public static async addMissionToPlayer(player: Player, missionId: string, difficulty: MissionDifficulty, mission: Mission = null): Promise<MissionSlot> { const prop = await this.generateMissionProperties(missionId, difficulty, mission); const missionData = Data.getModule("missions." + missionId); const missionSlot = await MissionSlot.create({ playerId: player.id, missionId: prop.mission.id, missionVariant: prop.variant, missionObjective: missionData.getNumberFromArray("objectives", prop.index), expiresAt: new Date(Date.now() + hoursToMilliseconds(missionData.getNumberFromArray("expirations", prop.index))), numberDone: await this.getMissionInterface(missionId).initialNumberDone(player, prop.variant), gemsToWin: missionData.getNumberFromArray("gems", prop.index), xpToWin: missionData.getNumberFromArray("xp", prop.index), moneyToWin: missionData.getNumberFromArray("money", prop.index) }); return await MissionSlots.getById(missionSlot.id); } public static async addRandomMissionToPlayer(player: Player, difficulty: MissionDifficulty): Promise<MissionSlot> { const mission = await Missions.getRandomMission(difficulty); return await MissionsController.addMissionToPlayer(player, mission.id, difficulty, mission); } public static async getVariantFormatText(missionId: string, variant: number, objective: number, language: string) { return await this.getMissionInterface(missionId).getVariantFormatVariable(variant, objective, language); } public static getRandomDifficulty(player: Player): MissionDifficulty { for (let i = Constants.MISSIONS.SLOTS_LEVEL_PROBABILITIES.length - 1; i >= 0; i--) { const probability = Constants.MISSIONS.SLOTS_LEVEL_PROBABILITIES[i]; if (player.level >= probability.LEVEL) { const randomNumber = RandomUtils.draftbotRandom.realZeroToOneInclusive(); return randomNumber < probability.EASY ? MissionDifficulty.EASY : randomNumber < probability.MEDIUM + probability.EASY ? MissionDifficulty.MEDIUM : MissionDifficulty.HARD; } } } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { LabVirtualMachine, VirtualMachinesListOptionalParams, VirtualMachinesGetOptionalParams, VirtualMachinesGetResponse, VirtualMachinesCreateOrUpdateOptionalParams, VirtualMachinesCreateOrUpdateResponse, VirtualMachinesDeleteOptionalParams, LabVirtualMachineFragment, VirtualMachinesUpdateOptionalParams, VirtualMachinesUpdateResponse, DataDiskProperties, VirtualMachinesAddDataDiskOptionalParams, ApplyArtifactsRequest, VirtualMachinesApplyArtifactsOptionalParams, VirtualMachinesClaimOptionalParams, DetachDataDiskProperties, VirtualMachinesDetachDataDiskOptionalParams, VirtualMachinesGetRdpFileContentsOptionalParams, VirtualMachinesGetRdpFileContentsResponse, VirtualMachinesListApplicableSchedulesOptionalParams, VirtualMachinesListApplicableSchedulesResponse, VirtualMachinesRedeployOptionalParams, ResizeLabVirtualMachineProperties, VirtualMachinesResizeOptionalParams, VirtualMachinesRestartOptionalParams, VirtualMachinesStartOptionalParams, VirtualMachinesStopOptionalParams, VirtualMachinesTransferDisksOptionalParams, VirtualMachinesUnClaimOptionalParams } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a VirtualMachines. */ export interface VirtualMachines { /** * List virtual machines in a given lab. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param options The options parameters. */ list( resourceGroupName: string, labName: string, options?: VirtualMachinesListOptionalParams ): PagedAsyncIterableIterator<LabVirtualMachine>; /** * Get virtual machine. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ get( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesGetOptionalParams ): Promise<VirtualMachinesGetResponse>; /** * Create or replace an existing virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param labVirtualMachine A virtual machine. * @param options The options parameters. */ beginCreateOrUpdate( resourceGroupName: string, labName: string, name: string, labVirtualMachine: LabVirtualMachine, options?: VirtualMachinesCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<VirtualMachinesCreateOrUpdateResponse>, VirtualMachinesCreateOrUpdateResponse > >; /** * Create or replace an existing virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param labVirtualMachine A virtual machine. * @param options The options parameters. */ beginCreateOrUpdateAndWait( resourceGroupName: string, labName: string, name: string, labVirtualMachine: LabVirtualMachine, options?: VirtualMachinesCreateOrUpdateOptionalParams ): Promise<VirtualMachinesCreateOrUpdateResponse>; /** * Delete virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginDelete( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Delete virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginDeleteAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesDeleteOptionalParams ): Promise<void>; /** * Allows modifying tags of virtual machines. All other properties will be ignored. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param labVirtualMachine A virtual machine. * @param options The options parameters. */ update( resourceGroupName: string, labName: string, name: string, labVirtualMachine: LabVirtualMachineFragment, options?: VirtualMachinesUpdateOptionalParams ): Promise<VirtualMachinesUpdateResponse>; /** * Attach a new or existing data disk to virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param dataDiskProperties Request body for adding a new or existing data disk to a virtual machine. * @param options The options parameters. */ beginAddDataDisk( resourceGroupName: string, labName: string, name: string, dataDiskProperties: DataDiskProperties, options?: VirtualMachinesAddDataDiskOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Attach a new or existing data disk to virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param dataDiskProperties Request body for adding a new or existing data disk to a virtual machine. * @param options The options parameters. */ beginAddDataDiskAndWait( resourceGroupName: string, labName: string, name: string, dataDiskProperties: DataDiskProperties, options?: VirtualMachinesAddDataDiskOptionalParams ): Promise<void>; /** * Apply artifacts to virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param applyArtifactsRequest Request body for applying artifacts to a virtual machine. * @param options The options parameters. */ beginApplyArtifacts( resourceGroupName: string, labName: string, name: string, applyArtifactsRequest: ApplyArtifactsRequest, options?: VirtualMachinesApplyArtifactsOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Apply artifacts to virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param applyArtifactsRequest Request body for applying artifacts to a virtual machine. * @param options The options parameters. */ beginApplyArtifactsAndWait( resourceGroupName: string, labName: string, name: string, applyArtifactsRequest: ApplyArtifactsRequest, options?: VirtualMachinesApplyArtifactsOptionalParams ): Promise<void>; /** * Take ownership of an existing virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginClaim( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesClaimOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Take ownership of an existing virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginClaimAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesClaimOptionalParams ): Promise<void>; /** * Detach the specified disk from the virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param detachDataDiskProperties Request body for detaching data disk from a virtual machine. * @param options The options parameters. */ beginDetachDataDisk( resourceGroupName: string, labName: string, name: string, detachDataDiskProperties: DetachDataDiskProperties, options?: VirtualMachinesDetachDataDiskOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Detach the specified disk from the virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param detachDataDiskProperties Request body for detaching data disk from a virtual machine. * @param options The options parameters. */ beginDetachDataDiskAndWait( resourceGroupName: string, labName: string, name: string, detachDataDiskProperties: DetachDataDiskProperties, options?: VirtualMachinesDetachDataDiskOptionalParams ): Promise<void>; /** * Gets a string that represents the contents of the RDP file for the virtual machine * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ getRdpFileContents( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesGetRdpFileContentsOptionalParams ): Promise<VirtualMachinesGetRdpFileContentsResponse>; /** * Lists the applicable start/stop schedules, if any. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ listApplicableSchedules( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesListApplicableSchedulesOptionalParams ): Promise<VirtualMachinesListApplicableSchedulesResponse>; /** * Redeploy a virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginRedeploy( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesRedeployOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Redeploy a virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginRedeployAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesRedeployOptionalParams ): Promise<void>; /** * Resize Virtual Machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param resizeLabVirtualMachineProperties Request body for resizing a virtual machine. * @param options The options parameters. */ beginResize( resourceGroupName: string, labName: string, name: string, resizeLabVirtualMachineProperties: ResizeLabVirtualMachineProperties, options?: VirtualMachinesResizeOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Resize Virtual Machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param resizeLabVirtualMachineProperties Request body for resizing a virtual machine. * @param options The options parameters. */ beginResizeAndWait( resourceGroupName: string, labName: string, name: string, resizeLabVirtualMachineProperties: ResizeLabVirtualMachineProperties, options?: VirtualMachinesResizeOptionalParams ): Promise<void>; /** * Restart a virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginRestart( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesRestartOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Restart a virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginRestartAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesRestartOptionalParams ): Promise<void>; /** * Start a virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginStart( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesStartOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Start a virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginStartAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesStartOptionalParams ): Promise<void>; /** * Stop a virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginStop( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesStopOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Stop a virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginStopAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesStopOptionalParams ): Promise<void>; /** * Transfers all data disks attached to the virtual machine to be owned by the current user. This * operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginTransferDisks( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesTransferDisksOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Transfers all data disks attached to the virtual machine to be owned by the current user. This * operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginTransferDisksAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesTransferDisksOptionalParams ): Promise<void>; /** * Release ownership of an existing virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginUnClaim( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesUnClaimOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Release ownership of an existing virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ beginUnClaimAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesUnClaimOptionalParams ): Promise<void>; }
the_stack
import { codec } from '@liskhq/lisk-codec'; import { dataStructures } from '@liskhq/lisk-utils'; import { getRandomBytes, getAddressFromPublicKey } from '@liskhq/lisk-cryptography'; import { BlockHeader, CONSENSUS_STATE_FINALIZED_HEIGHT_KEY, Chain, CONSENSUS_STATE_VALIDATORS_KEY, validatorsSchema, StateStore, testing, } from '@liskhq/lisk-chain'; import { FinalityManager, CONSENSUS_STATE_VALIDATOR_LEDGER_KEY, BFTVotingLedgerSchema, } from '../../src/finality_manager'; import { BFTError } from '../../src/types'; import { createFakeBlockHeader } from '../fixtures/blocks'; import { BFTFinalizedHeightCodecSchema } from '../../src'; const generateValidHeaders = (count: number): any[] => { return [...Array(count)].map((_, index) => { return createFakeBlockHeader({ height: index + 1, asset: { maxHeightPreviouslyForged: index, }, }); }); }; describe('finality_manager', () => { const { StateStoreMock } = testing; describe('FinalityManager', () => { const finalizedHeight = 0; const threshold = 68; const preVoteThreshold = threshold; const preCommitThreshold = threshold; const processingThreshold = 308; const maxHeaders = 515; let finalityManager: FinalityManager; let chainStub: Chain; beforeEach(() => { chainStub = ({ slots: { getSlotNumber: jest.fn(), isWithinTimeslot: jest.fn(), timeSinceGenesis: jest.fn(), }, dataAccess: { getConsensusState: jest.fn(), }, numberOfValidators: 103, } as unknown) as Chain; finalityManager = new FinalityManager({ chain: chainStub, finalizedHeight, genesisHeight: 0, threshold, }); }); describe('constructor', () => { it('should initialize the object correctly', () => { expect(finalityManager).toBeInstanceOf(FinalityManager); expect(finalityManager.preVoteThreshold).toEqual(preVoteThreshold); expect(finalityManager.preCommitThreshold).toEqual(preCommitThreshold); expect(finalityManager.processingThreshold).toEqual(processingThreshold); expect(finalityManager.maxHeaders).toEqual(maxHeaders); }); it('should throw error if number of validator is not positive', () => { (chainStub as any).numberOfValidators = -3; expect( () => new FinalityManager({ chain: chainStub, finalizedHeight, genesisHeight: 0, threshold, }), ).toThrow('Invalid number of validators for BFT property'); }); it('should initialize maxHeightPrevoted to the the last maxHeightPrevoted', async () => { const validatorLedger = { validators: [], ledger: [ { height: 610, prevotes: 67, precommits: 0, }, { height: 611, prevotes: 67, precommits: 0, }, { height: 612, prevotes: 66, precommits: 0, }, ], }; jest .spyOn(chainStub.dataAccess, 'getConsensusState') .mockResolvedValue(codec.encode(BFTVotingLedgerSchema, validatorLedger)); const lastMaxHeightPrevoted = 30; await expect(finalityManager.getMaxHeightPrevoted(lastMaxHeightPrevoted)).resolves.toEqual( lastMaxHeightPrevoted, ); }); }); describe('verifyBlockHeaders', () => { let stateStore: StateStore; it('should throw error if maxHeightPrevoted is not accurate', async () => { // Add the header directly to list so verifyBlockHeaders can be validated against it const bftHeaders = generateValidHeaders(finalityManager.processingThreshold + 1); stateStore = (new StateStoreMock({ lastBlockHeaders: bftHeaders, }) as unknown) as StateStore; const header = createFakeBlockHeader({ asset: { maxHeightPrevoted: 12 }, }); expect.assertions(1); try { await finalityManager.verifyBlockHeaders(header, stateStore); } catch (error) { // eslint-disable-next-line jest/no-try-expect expect(error.message).toContain('Wrong maxHeightPrevoted in blockHeader.'); } }); it('should not throw error if maxHeightPrevoted is accurate', async () => { // Add the header directly to list so verifyBlockHeaders can be validated against it const bftHeaders = generateValidHeaders(finalityManager.processingThreshold + 1); const header = createFakeBlockHeader({ asset: { maxHeightPrevoted: 10 }, }); const validatorLedger = { validators: [ { address: getAddressFromPublicKey(header.generatorPublicKey), maxPreVoteHeight: 1, maxPreCommitHeight: 0, }, ], ledger: [ { height: 10, prevotes: 69, precommits: 0, }, ], }; const consensus = { [CONSENSUS_STATE_VALIDATOR_LEDGER_KEY]: codec.encode( BFTVotingLedgerSchema, validatorLedger, ), }; stateStore = (new StateStoreMock({ consensus, lastBlockHeaders: bftHeaders, }) as unknown) as StateStore; await expect(finalityManager.verifyBlockHeaders(header, stateStore)).resolves.toBeTrue(); }); it("should return true if validator didn't forge any block previously", async () => { const header = createFakeBlockHeader(); stateStore = (new StateStoreMock({ lastBlockHeaders: [] }) as unknown) as StateStore; await expect(finalityManager.verifyBlockHeaders(header, stateStore)).resolves.toBeTruthy(); }); it('should throw error if same validator forged block on different height', async () => { const maxHeightPrevoted = 10; const generatorPublicKey = getRandomBytes(32); const lastBlock = createFakeBlockHeader({ generatorPublicKey, asset: { maxHeightPreviouslyForged: 5, maxHeightPrevoted, }, height: 10, }); const currentBlock = createFakeBlockHeader({ generatorPublicKey, asset: { maxHeightPrevoted, maxHeightPreviouslyForged: 6, }, height: 9, }); stateStore = (new StateStoreMock({ lastBlockHeaders: [lastBlock], }) as unknown) as StateStore; await expect(finalityManager.verifyBlockHeaders(currentBlock, stateStore)).rejects.toThrow( BFTError, ); }); it('should throw error if validator forged block on same height', async () => { const maxHeightPreviouslyForged = 10; const generatorPublicKey = getRandomBytes(32); const lastBlock = createFakeBlockHeader({ generatorPublicKey, asset: { maxHeightPreviouslyForged, }, height: 10, }); const currentBlock = createFakeBlockHeader({ generatorPublicKey, asset: { maxHeightPreviouslyForged, }, height: 10, }); stateStore = (new StateStoreMock({ lastBlockHeaders: [lastBlock], }) as unknown) as StateStore; await expect(finalityManager.verifyBlockHeaders(currentBlock, stateStore)).rejects.toThrow( BFTError, ); }); it('should throw error if maxHeightPreviouslyForged has wrong value', async () => { const generatorPublicKey = getRandomBytes(32); const lastBlock = createFakeBlockHeader({ generatorPublicKey, height: 10, }); const currentBlock = createFakeBlockHeader({ generatorPublicKey, asset: { maxHeightPreviouslyForged: 9, }, }); stateStore = (new StateStoreMock({ lastBlockHeaders: [lastBlock], }) as unknown) as StateStore; await expect(finalityManager.verifyBlockHeaders(currentBlock, stateStore)).rejects.toThrow( BFTError, ); }); it('should throw error if maxHeightPrevoted has wrong value', async () => { const generatorPublicKey = getRandomBytes(32); const lastBlock = createFakeBlockHeader({ generatorPublicKey, height: 9, asset: { maxHeightPrevoted: 10, }, }); const currentBlock = createFakeBlockHeader({ generatorPublicKey, height: 10, asset: { maxHeightPreviouslyForged: 9, maxHeightPrevoted: 9, }, }); stateStore = (new StateStoreMock({ lastBlockHeaders: [lastBlock], }) as unknown) as StateStore; await expect(finalityManager.verifyBlockHeaders(currentBlock, stateStore)).rejects.toThrow( BFTError, ); }); it('should return true if headers are valid', async () => { const [lastBlock, currentBlock] = generateValidHeaders(2); stateStore = (new StateStoreMock({ lastBlockHeaders: [lastBlock], }) as unknown) as StateStore; await expect( finalityManager.verifyBlockHeaders(currentBlock, stateStore), ).resolves.toBeTruthy(); }); }); describe('addBlockHeader', () => { const validatorLedger = { validators: [], ledger: [], }; let stateStore: StateStore; let bftHeaders: Array<BlockHeader>; beforeEach(() => { bftHeaders = generateValidHeaders(finalityManager.processingThreshold + 1); const consensus = { [CONSENSUS_STATE_FINALIZED_HEIGHT_KEY]: codec.encode(BFTFinalizedHeightCodecSchema, { finalizedHeight: 5, }), [CONSENSUS_STATE_VALIDATOR_LEDGER_KEY]: codec.encode( BFTVotingLedgerSchema, validatorLedger, ), [CONSENSUS_STATE_VALIDATORS_KEY]: codec.encode(validatorsSchema, { validators: bftHeaders.slice(0, 103).map(h => ({ address: getAddressFromPublicKey(h.generatorPublicKey), isConsensusParticipant: true, minActiveHeight: 0, })), }), }; stateStore = (new StateStoreMock({ consensus, lastBlockHeaders: bftHeaders, }) as unknown) as StateStore; }); it('should call verifyBlockHeaders with the provided header', async () => { const header1 = createFakeBlockHeader({ height: 2, asset: { maxHeightPreviouslyForged: 0, }, generatorPublicKey: bftHeaders[102].generatorPublicKey, }); jest.spyOn(finalityManager, 'verifyBlockHeaders'); await finalityManager.addBlockHeader(header1, stateStore); expect(finalityManager.verifyBlockHeaders).toHaveBeenCalledTimes(1); expect(finalityManager.verifyBlockHeaders).toHaveBeenCalledWith(header1, stateStore); }); it('should call updatePrevotesPrecommits with the provided header', async () => { const header1 = createFakeBlockHeader({ height: 2, asset: { maxHeightPreviouslyForged: 0, }, generatorPublicKey: bftHeaders[102].generatorPublicKey, }); jest.spyOn(finalityManager, 'updatePrevotesPrecommits'); await finalityManager.addBlockHeader(header1, stateStore); expect(finalityManager.updatePrevotesPrecommits).toHaveBeenCalledTimes(1); expect(finalityManager.updatePrevotesPrecommits).toHaveBeenCalledWith( header1, stateStore, bftHeaders, ); }); it('should not update prevotes and precommits if validator does not have voting power', async () => { const header1 = createFakeBlockHeader({ height: 2, asset: { maxHeightPreviouslyForged: 0, }, }); const consensus = { [CONSENSUS_STATE_VALIDATORS_KEY]: codec.encode(validatorsSchema, { validators: [ { address: getAddressFromPublicKey(header1.generatorPublicKey), isConsensusParticipant: false, minActiveHeight: 104, }, ], }), }; stateStore = (new StateStoreMock({ consensus, lastBlockHeaders: bftHeaders, }) as unknown) as StateStore; jest.spyOn(finalityManager, 'updatePrevotesPrecommits'); await finalityManager.addBlockHeader(header1, stateStore); expect(finalityManager.updatePrevotesPrecommits).toHaveBeenCalledTimes(1); expect(finalityManager.updatePrevotesPrecommits).toHaveBeenCalledWith( header1, stateStore, bftHeaders, ); // Ignores a standby validator from prevotes and precommit calculations await expect( finalityManager.updatePrevotesPrecommits(header1, stateStore, bftHeaders), ).resolves.toEqual(false); }); it('should not update prevotes and precommits in case of a standby validator', async () => { const header1 = createFakeBlockHeader({ height: 2, asset: { maxHeightPreviouslyForged: 0, }, }); const consensus = { [CONSENSUS_STATE_VALIDATORS_KEY]: codec.encode(validatorsSchema, { validators: [ { address: getAddressFromPublicKey(header1.generatorPublicKey), isConsensusParticipant: false, minActiveHeight: 104, }, ], }), }; stateStore = (new StateStoreMock({ consensus, lastBlockHeaders: bftHeaders, }) as unknown) as StateStore; jest.spyOn(finalityManager, 'updatePrevotesPrecommits'); await finalityManager.addBlockHeader(header1, stateStore); expect(finalityManager.updatePrevotesPrecommits).toHaveBeenCalledTimes(1); expect(finalityManager.updatePrevotesPrecommits).toHaveBeenCalledWith( header1, stateStore, bftHeaders, ); // Ignores a standby validator from prevotes and precommit calculations await expect( finalityManager.updatePrevotesPrecommits(header1, stateStore, bftHeaders), ).resolves.toEqual(false); }); it('should throw error if blockheader has conflict (Violates disjointness condition)', async () => { const header1 = createFakeBlockHeader({ height: 34624, asset: { maxHeightPreviouslyForged: 34501, }, }); const header2 = createFakeBlockHeader({ height: 34666, generatorPublicKey: header1.generatorPublicKey, asset: { maxHeightPreviouslyForged: 34501, }, }); const headers = [header1]; for ( // eslint-disable-next-line @typescript-eslint/restrict-plus-operands let height = header1.height + 1; height < header2.height; height += 1 ) { const header = createFakeBlockHeader({ height, asset: { maxHeightPreviouslyForged: height - 129, }, }); headers.push(header); } headers.push(header2); const addressMap = new dataStructures.BufferMap<Buffer>(); for (const header of headers) { const addr = getAddressFromPublicKey(header.generatorPublicKey); addressMap.set(addr, addr); } const consensus = { [CONSENSUS_STATE_VALIDATORS_KEY]: codec.encode(validatorsSchema, { validators: addressMap .values() .map(addr => ({ address: addr, isConsensusParticipant: true, minActiveHeight: 0 })), }), }; stateStore = (new StateStoreMock({ consensus, lastBlockHeaders: bftHeaders, }) as unknown) as StateStore; try { for (const header of headers) { await finalityManager.addBlockHeader(header, stateStore); } } catch (error) { // eslint-disable-next-line jest/no-try-expect expect(error.message).toContain('Violation of disjointedness condition.'); } }); it('should not update finalized height if calculated value is lower', async () => { const header1 = createFakeBlockHeader({ height: 2, asset: { maxHeightPreviouslyForged: 0, maxHeightPrevoted: 200, }, }); const consensus = { [CONSENSUS_STATE_VALIDATORS_KEY]: codec.encode(validatorsSchema, { validators: [ { address: getAddressFromPublicKey(header1.generatorPublicKey), isConsensusParticipant: false, minActiveHeight: 104, }, ], }), [CONSENSUS_STATE_VALIDATOR_LEDGER_KEY]: codec.encode(BFTVotingLedgerSchema, { ...validatorLedger, ledger: [ { height: 200, prevotes: 99, precommits: 99, }, ], }), }; stateStore = (new StateStoreMock({ consensus, lastBlockHeaders: bftHeaders, }) as unknown) as StateStore; const originalFinalizedHeight = 999; finalityManager.finalizedHeight = originalFinalizedHeight; jest.spyOn(finalityManager, 'updateFinalizedHeight'); await finalityManager.addBlockHeader(header1, stateStore); // Ignores a standby validator from prevotes and precommit calculations expect(finalityManager.updateFinalizedHeight).toHaveBeenCalledTimes(1); expect(finalityManager.finalizedHeight).toEqual(originalFinalizedHeight); }); }); }); });
the_stack
import { PollerLike, PollOperationState } from "@azure/core-lro"; import { LrosaDsPutNonRetry400OptionalParams, LrosaDsPutNonRetry400Response, LrosaDsPutNonRetry201Creating400OptionalParams, LrosaDsPutNonRetry201Creating400Response, LrosaDsPutNonRetry201Creating400InvalidJsonOptionalParams, LrosaDsPutNonRetry201Creating400InvalidJsonResponse, LrosaDsPutAsyncRelativeRetry400OptionalParams, LrosaDsPutAsyncRelativeRetry400Response, LrosaDsDeleteNonRetry400OptionalParams, LrosaDsDeleteNonRetry400Response, LrosaDsDelete202NonRetry400OptionalParams, LrosaDsDelete202NonRetry400Response, LrosaDsDeleteAsyncRelativeRetry400OptionalParams, LrosaDsDeleteAsyncRelativeRetry400Response, LrosaDsPostNonRetry400OptionalParams, LrosaDsPostNonRetry400Response, LrosaDsPost202NonRetry400OptionalParams, LrosaDsPost202NonRetry400Response, LrosaDsPostAsyncRelativeRetry400OptionalParams, LrosaDsPostAsyncRelativeRetry400Response, LrosaDsPutError201NoProvisioningStatePayloadOptionalParams, LrosaDsPutError201NoProvisioningStatePayloadResponse, LrosaDsPutAsyncRelativeRetryNoStatusOptionalParams, LrosaDsPutAsyncRelativeRetryNoStatusResponse, LrosaDsPutAsyncRelativeRetryNoStatusPayloadOptionalParams, LrosaDsPutAsyncRelativeRetryNoStatusPayloadResponse, LrosaDsDelete204SucceededOptionalParams, LrosaDsDeleteAsyncRelativeRetryNoStatusOptionalParams, LrosaDsDeleteAsyncRelativeRetryNoStatusResponse, LrosaDsPost202NoLocationOptionalParams, LrosaDsPost202NoLocationResponse, LrosaDsPostAsyncRelativeRetryNoPayloadOptionalParams, LrosaDsPostAsyncRelativeRetryNoPayloadResponse, LrosaDsPut200InvalidJsonOptionalParams, LrosaDsPut200InvalidJsonResponse, LrosaDsPutAsyncRelativeRetryInvalidHeaderOptionalParams, LrosaDsPutAsyncRelativeRetryInvalidHeaderResponse, LrosaDsPutAsyncRelativeRetryInvalidJsonPollingOptionalParams, LrosaDsPutAsyncRelativeRetryInvalidJsonPollingResponse, LrosaDsDelete202RetryInvalidHeaderOptionalParams, LrosaDsDelete202RetryInvalidHeaderResponse, LrosaDsDeleteAsyncRelativeRetryInvalidHeaderOptionalParams, LrosaDsDeleteAsyncRelativeRetryInvalidHeaderResponse, LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingOptionalParams, LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingResponse, LrosaDsPost202RetryInvalidHeaderOptionalParams, LrosaDsPost202RetryInvalidHeaderResponse, LrosaDsPostAsyncRelativeRetryInvalidHeaderOptionalParams, LrosaDsPostAsyncRelativeRetryInvalidHeaderResponse, LrosaDsPostAsyncRelativeRetryInvalidJsonPollingOptionalParams, LrosaDsPostAsyncRelativeRetryInvalidJsonPollingResponse } from "../models"; /** Interface representing a LrosaDs. */ export interface LrosaDs { /** * Long running put request, service returns a 400 to the initial request * @param options The options parameters. */ beginPutNonRetry400( options?: LrosaDsPutNonRetry400OptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPutNonRetry400Response>, LrosaDsPutNonRetry400Response > >; /** * Long running put request, service returns a 400 to the initial request * @param options The options parameters. */ beginPutNonRetry400AndWait( options?: LrosaDsPutNonRetry400OptionalParams ): Promise<LrosaDsPutNonRetry400Response>; /** * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 * response code * @param options The options parameters. */ beginPutNonRetry201Creating400( options?: LrosaDsPutNonRetry201Creating400OptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPutNonRetry201Creating400Response>, LrosaDsPutNonRetry201Creating400Response > >; /** * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 * response code * @param options The options parameters. */ beginPutNonRetry201Creating400AndWait( options?: LrosaDsPutNonRetry201Creating400OptionalParams ): Promise<LrosaDsPutNonRetry201Creating400Response>; /** * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 * response code * @param options The options parameters. */ beginPutNonRetry201Creating400InvalidJson( options?: LrosaDsPutNonRetry201Creating400InvalidJsonOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPutNonRetry201Creating400InvalidJsonResponse>, LrosaDsPutNonRetry201Creating400InvalidJsonResponse > >; /** * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 * response code * @param options The options parameters. */ beginPutNonRetry201Creating400InvalidJsonAndWait( options?: LrosaDsPutNonRetry201Creating400InvalidJsonOptionalParams ): Promise<LrosaDsPutNonRetry201Creating400InvalidJsonResponse>; /** * Long running put request, service returns a 200 with ProvisioningState=’Creating’. Poll the endpoint * indicated in the Azure-AsyncOperation header for operation status * @param options The options parameters. */ beginPutAsyncRelativeRetry400( options?: LrosaDsPutAsyncRelativeRetry400OptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPutAsyncRelativeRetry400Response>, LrosaDsPutAsyncRelativeRetry400Response > >; /** * Long running put request, service returns a 200 with ProvisioningState=’Creating’. Poll the endpoint * indicated in the Azure-AsyncOperation header for operation status * @param options The options parameters. */ beginPutAsyncRelativeRetry400AndWait( options?: LrosaDsPutAsyncRelativeRetry400OptionalParams ): Promise<LrosaDsPutAsyncRelativeRetry400Response>; /** * Long running delete request, service returns a 400 with an error body * @param options The options parameters. */ beginDeleteNonRetry400( options?: LrosaDsDeleteNonRetry400OptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsDeleteNonRetry400Response>, LrosaDsDeleteNonRetry400Response > >; /** * Long running delete request, service returns a 400 with an error body * @param options The options parameters. */ beginDeleteNonRetry400AndWait( options?: LrosaDsDeleteNonRetry400OptionalParams ): Promise<LrosaDsDeleteNonRetry400Response>; /** * Long running delete request, service returns a 202 with a location header * @param options The options parameters. */ beginDelete202NonRetry400( options?: LrosaDsDelete202NonRetry400OptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsDelete202NonRetry400Response>, LrosaDsDelete202NonRetry400Response > >; /** * Long running delete request, service returns a 202 with a location header * @param options The options parameters. */ beginDelete202NonRetry400AndWait( options?: LrosaDsDelete202NonRetry400OptionalParams ): Promise<LrosaDsDelete202NonRetry400Response>; /** * Long running delete request, service returns a 202 to the initial request. Poll the endpoint * indicated in the Azure-AsyncOperation header for operation status * @param options The options parameters. */ beginDeleteAsyncRelativeRetry400( options?: LrosaDsDeleteAsyncRelativeRetry400OptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsDeleteAsyncRelativeRetry400Response>, LrosaDsDeleteAsyncRelativeRetry400Response > >; /** * Long running delete request, service returns a 202 to the initial request. Poll the endpoint * indicated in the Azure-AsyncOperation header for operation status * @param options The options parameters. */ beginDeleteAsyncRelativeRetry400AndWait( options?: LrosaDsDeleteAsyncRelativeRetry400OptionalParams ): Promise<LrosaDsDeleteAsyncRelativeRetry400Response>; /** * Long running post request, service returns a 400 with no error body * @param options The options parameters. */ beginPostNonRetry400( options?: LrosaDsPostNonRetry400OptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPostNonRetry400Response>, LrosaDsPostNonRetry400Response > >; /** * Long running post request, service returns a 400 with no error body * @param options The options parameters. */ beginPostNonRetry400AndWait( options?: LrosaDsPostNonRetry400OptionalParams ): Promise<LrosaDsPostNonRetry400Response>; /** * Long running post request, service returns a 202 with a location header * @param options The options parameters. */ beginPost202NonRetry400( options?: LrosaDsPost202NonRetry400OptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPost202NonRetry400Response>, LrosaDsPost202NonRetry400Response > >; /** * Long running post request, service returns a 202 with a location header * @param options The options parameters. */ beginPost202NonRetry400AndWait( options?: LrosaDsPost202NonRetry400OptionalParams ): Promise<LrosaDsPost202NonRetry400Response>; /** * Long running post request, service returns a 202 to the initial request Poll the endpoint indicated * in the Azure-AsyncOperation header for operation status * @param options The options parameters. */ beginPostAsyncRelativeRetry400( options?: LrosaDsPostAsyncRelativeRetry400OptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPostAsyncRelativeRetry400Response>, LrosaDsPostAsyncRelativeRetry400Response > >; /** * Long running post request, service returns a 202 to the initial request Poll the endpoint indicated * in the Azure-AsyncOperation header for operation status * @param options The options parameters. */ beginPostAsyncRelativeRetry400AndWait( options?: LrosaDsPostAsyncRelativeRetry400OptionalParams ): Promise<LrosaDsPostAsyncRelativeRetry400Response>; /** * Long running put request, service returns a 201 to the initial request with no payload * @param options The options parameters. */ beginPutError201NoProvisioningStatePayload( options?: LrosaDsPutError201NoProvisioningStatePayloadOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPutError201NoProvisioningStatePayloadResponse>, LrosaDsPutError201NoProvisioningStatePayloadResponse > >; /** * Long running put request, service returns a 201 to the initial request with no payload * @param options The options parameters. */ beginPutError201NoProvisioningStatePayloadAndWait( options?: LrosaDsPutError201NoProvisioningStatePayloadOptionalParams ): Promise<LrosaDsPutError201NoProvisioningStatePayloadResponse>; /** * Long running put request, service returns a 200 to the initial request, with an entity that contains * ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for * operation status * @param options The options parameters. */ beginPutAsyncRelativeRetryNoStatus( options?: LrosaDsPutAsyncRelativeRetryNoStatusOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPutAsyncRelativeRetryNoStatusResponse>, LrosaDsPutAsyncRelativeRetryNoStatusResponse > >; /** * Long running put request, service returns a 200 to the initial request, with an entity that contains * ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for * operation status * @param options The options parameters. */ beginPutAsyncRelativeRetryNoStatusAndWait( options?: LrosaDsPutAsyncRelativeRetryNoStatusOptionalParams ): Promise<LrosaDsPutAsyncRelativeRetryNoStatusResponse>; /** * Long running put request, service returns a 200 to the initial request, with an entity that contains * ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for * operation status * @param options The options parameters. */ beginPutAsyncRelativeRetryNoStatusPayload( options?: LrosaDsPutAsyncRelativeRetryNoStatusPayloadOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPutAsyncRelativeRetryNoStatusPayloadResponse>, LrosaDsPutAsyncRelativeRetryNoStatusPayloadResponse > >; /** * Long running put request, service returns a 200 to the initial request, with an entity that contains * ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for * operation status * @param options The options parameters. */ beginPutAsyncRelativeRetryNoStatusPayloadAndWait( options?: LrosaDsPutAsyncRelativeRetryNoStatusPayloadOptionalParams ): Promise<LrosaDsPutAsyncRelativeRetryNoStatusPayloadResponse>; /** * Long running delete request, service returns a 204 to the initial request, indicating success. * @param options The options parameters. */ beginDelete204Succeeded( options?: LrosaDsDelete204SucceededOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Long running delete request, service returns a 204 to the initial request, indicating success. * @param options The options parameters. */ beginDelete204SucceededAndWait( options?: LrosaDsDelete204SucceededOptionalParams ): Promise<void>; /** * Long running delete request, service returns a 202 to the initial request. Poll the endpoint * indicated in the Azure-AsyncOperation header for operation status * @param options The options parameters. */ beginDeleteAsyncRelativeRetryNoStatus( options?: LrosaDsDeleteAsyncRelativeRetryNoStatusOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsDeleteAsyncRelativeRetryNoStatusResponse>, LrosaDsDeleteAsyncRelativeRetryNoStatusResponse > >; /** * Long running delete request, service returns a 202 to the initial request. Poll the endpoint * indicated in the Azure-AsyncOperation header for operation status * @param options The options parameters. */ beginDeleteAsyncRelativeRetryNoStatusAndWait( options?: LrosaDsDeleteAsyncRelativeRetryNoStatusOptionalParams ): Promise<LrosaDsDeleteAsyncRelativeRetryNoStatusResponse>; /** * Long running post request, service returns a 202 to the initial request, without a location header. * @param options The options parameters. */ beginPost202NoLocation( options?: LrosaDsPost202NoLocationOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPost202NoLocationResponse>, LrosaDsPost202NoLocationResponse > >; /** * Long running post request, service returns a 202 to the initial request, without a location header. * @param options The options parameters. */ beginPost202NoLocationAndWait( options?: LrosaDsPost202NoLocationOptionalParams ): Promise<LrosaDsPost202NoLocationResponse>; /** * Long running post request, service returns a 202 to the initial request, with an entity that * contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation * header for operation status * @param options The options parameters. */ beginPostAsyncRelativeRetryNoPayload( options?: LrosaDsPostAsyncRelativeRetryNoPayloadOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPostAsyncRelativeRetryNoPayloadResponse>, LrosaDsPostAsyncRelativeRetryNoPayloadResponse > >; /** * Long running post request, service returns a 202 to the initial request, with an entity that * contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation * header for operation status * @param options The options parameters. */ beginPostAsyncRelativeRetryNoPayloadAndWait( options?: LrosaDsPostAsyncRelativeRetryNoPayloadOptionalParams ): Promise<LrosaDsPostAsyncRelativeRetryNoPayloadResponse>; /** * Long running put request, service returns a 200 to the initial request, with an entity that is not a * valid json * @param options The options parameters. */ beginPut200InvalidJson( options?: LrosaDsPut200InvalidJsonOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPut200InvalidJsonResponse>, LrosaDsPut200InvalidJsonResponse > >; /** * Long running put request, service returns a 200 to the initial request, with an entity that is not a * valid json * @param options The options parameters. */ beginPut200InvalidJsonAndWait( options?: LrosaDsPut200InvalidJsonOptionalParams ): Promise<LrosaDsPut200InvalidJsonResponse>; /** * Long running put request, service returns a 200 to the initial request, with an entity that contains * ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is invalid. * @param options The options parameters. */ beginPutAsyncRelativeRetryInvalidHeader( options?: LrosaDsPutAsyncRelativeRetryInvalidHeaderOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPutAsyncRelativeRetryInvalidHeaderResponse>, LrosaDsPutAsyncRelativeRetryInvalidHeaderResponse > >; /** * Long running put request, service returns a 200 to the initial request, with an entity that contains * ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is invalid. * @param options The options parameters. */ beginPutAsyncRelativeRetryInvalidHeaderAndWait( options?: LrosaDsPutAsyncRelativeRetryInvalidHeaderOptionalParams ): Promise<LrosaDsPutAsyncRelativeRetryInvalidHeaderResponse>; /** * Long running put request, service returns a 200 to the initial request, with an entity that contains * ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for * operation status * @param options The options parameters. */ beginPutAsyncRelativeRetryInvalidJsonPolling( options?: LrosaDsPutAsyncRelativeRetryInvalidJsonPollingOptionalParams ): Promise< PollerLike< PollOperationState< LrosaDsPutAsyncRelativeRetryInvalidJsonPollingResponse >, LrosaDsPutAsyncRelativeRetryInvalidJsonPollingResponse > >; /** * Long running put request, service returns a 200 to the initial request, with an entity that contains * ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for * operation status * @param options The options parameters. */ beginPutAsyncRelativeRetryInvalidJsonPollingAndWait( options?: LrosaDsPutAsyncRelativeRetryInvalidJsonPollingOptionalParams ): Promise<LrosaDsPutAsyncRelativeRetryInvalidJsonPollingResponse>; /** * Long running delete request, service returns a 202 to the initial request receing a reponse with an * invalid 'Location' and 'Retry-After' headers * @param options The options parameters. */ beginDelete202RetryInvalidHeader( options?: LrosaDsDelete202RetryInvalidHeaderOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsDelete202RetryInvalidHeaderResponse>, LrosaDsDelete202RetryInvalidHeaderResponse > >; /** * Long running delete request, service returns a 202 to the initial request receing a reponse with an * invalid 'Location' and 'Retry-After' headers * @param options The options parameters. */ beginDelete202RetryInvalidHeaderAndWait( options?: LrosaDsDelete202RetryInvalidHeaderOptionalParams ): Promise<LrosaDsDelete202RetryInvalidHeaderResponse>; /** * Long running delete request, service returns a 202 to the initial request. The endpoint indicated in * the Azure-AsyncOperation header is invalid * @param options The options parameters. */ beginDeleteAsyncRelativeRetryInvalidHeader( options?: LrosaDsDeleteAsyncRelativeRetryInvalidHeaderOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsDeleteAsyncRelativeRetryInvalidHeaderResponse>, LrosaDsDeleteAsyncRelativeRetryInvalidHeaderResponse > >; /** * Long running delete request, service returns a 202 to the initial request. The endpoint indicated in * the Azure-AsyncOperation header is invalid * @param options The options parameters. */ beginDeleteAsyncRelativeRetryInvalidHeaderAndWait( options?: LrosaDsDeleteAsyncRelativeRetryInvalidHeaderOptionalParams ): Promise<LrosaDsDeleteAsyncRelativeRetryInvalidHeaderResponse>; /** * Long running delete request, service returns a 202 to the initial request. Poll the endpoint * indicated in the Azure-AsyncOperation header for operation status * @param options The options parameters. */ beginDeleteAsyncRelativeRetryInvalidJsonPolling( options?: LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingOptionalParams ): Promise< PollerLike< PollOperationState< LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingResponse >, LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingResponse > >; /** * Long running delete request, service returns a 202 to the initial request. Poll the endpoint * indicated in the Azure-AsyncOperation header for operation status * @param options The options parameters. */ beginDeleteAsyncRelativeRetryInvalidJsonPollingAndWait( options?: LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingOptionalParams ): Promise<LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingResponse>; /** * Long running post request, service returns a 202 to the initial request, with invalid 'Location' and * 'Retry-After' headers. * @param options The options parameters. */ beginPost202RetryInvalidHeader( options?: LrosaDsPost202RetryInvalidHeaderOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPost202RetryInvalidHeaderResponse>, LrosaDsPost202RetryInvalidHeaderResponse > >; /** * Long running post request, service returns a 202 to the initial request, with invalid 'Location' and * 'Retry-After' headers. * @param options The options parameters. */ beginPost202RetryInvalidHeaderAndWait( options?: LrosaDsPost202RetryInvalidHeaderOptionalParams ): Promise<LrosaDsPost202RetryInvalidHeaderResponse>; /** * Long running post request, service returns a 202 to the initial request, with an entity that * contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is * invalid. * @param options The options parameters. */ beginPostAsyncRelativeRetryInvalidHeader( options?: LrosaDsPostAsyncRelativeRetryInvalidHeaderOptionalParams ): Promise< PollerLike< PollOperationState<LrosaDsPostAsyncRelativeRetryInvalidHeaderResponse>, LrosaDsPostAsyncRelativeRetryInvalidHeaderResponse > >; /** * Long running post request, service returns a 202 to the initial request, with an entity that * contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is * invalid. * @param options The options parameters. */ beginPostAsyncRelativeRetryInvalidHeaderAndWait( options?: LrosaDsPostAsyncRelativeRetryInvalidHeaderOptionalParams ): Promise<LrosaDsPostAsyncRelativeRetryInvalidHeaderResponse>; /** * Long running post request, service returns a 202 to the initial request, with an entity that * contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation * header for operation status * @param options The options parameters. */ beginPostAsyncRelativeRetryInvalidJsonPolling( options?: LrosaDsPostAsyncRelativeRetryInvalidJsonPollingOptionalParams ): Promise< PollerLike< PollOperationState< LrosaDsPostAsyncRelativeRetryInvalidJsonPollingResponse >, LrosaDsPostAsyncRelativeRetryInvalidJsonPollingResponse > >; /** * Long running post request, service returns a 202 to the initial request, with an entity that * contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation * header for operation status * @param options The options parameters. */ beginPostAsyncRelativeRetryInvalidJsonPollingAndWait( options?: LrosaDsPostAsyncRelativeRetryInvalidJsonPollingOptionalParams ): Promise<LrosaDsPostAsyncRelativeRetryInvalidJsonPollingResponse>; }
the_stack
import * as vscode from 'vscode'; import * as assert from 'assert'; import { describe, before, it } from 'mocha'; import { angularCollectionName } from '../../defaults'; import { WorkspaceFolderConfig } from '../../workspace'; import { COMPONENT_TYPE } from '../../workspace/shortcuts'; import { rootProjectName, ionicCollectionName, libProjectName, subAppProjectName, materialCollectionName } from './test-config'; describe('Workspace folder config', () => { describe('Defaults', () => { let workspaceFolder: WorkspaceFolderConfig; before(async () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion workspaceFolder = new WorkspaceFolderConfig(vscode.workspace.workspaceFolders![0]!); await workspaceFolder.init(); }); it('Angular default collections', () => { assert.strictEqual(angularCollectionName, workspaceFolder.getDefaultUserCollection()); assert.deepStrictEqual([angularCollectionName], workspaceFolder.getDefaultCollections()); }); it('Angular projects', () => { assert.strictEqual(1, workspaceFolder.getAngularProjects().size); const rootProject = workspaceFolder.getAngularProject(rootProjectName); assert.strictEqual('application', rootProject?.getType()); assert.strictEqual('', rootProject?.getRootPath()); assert.strictEqual('src', rootProject?.getSourcePath()); assert.strictEqual('src/app', rootProject?.getAppOrLibPath()); assert.strictEqual(true, workspaceFolder.isRootAngularProject(rootProjectName)); }); it('Angular schematics defaults', () => { assert.strictEqual(undefined, workspaceFolder.getSchematicsOptionDefaultValue(rootProjectName, `${angularCollectionName}:component`, 'flat')); }); it('TSLint component suffixes', () => { assert.strictEqual(false, workspaceFolder.hasComponentSuffix(rootProjectName, 'Page')); }); it('Modules types', () => { assert.strictEqual(3, workspaceFolder.getModuleTypes().size); }); it('Component types', () => { assert.strictEqual(4, workspaceFolder.getComponentTypes(rootProjectName).size); const pageComponentType = workspaceFolder.getComponentTypes(rootProjectName).get(COMPONENT_TYPE.PAGE); assert.strictEqual(false, pageComponentType?.options.has('type')); }); it('Collections', () => { assert.deepStrictEqual([angularCollectionName], workspaceFolder.collections.getCollectionsNames()); const angularCollection = workspaceFolder.collections.getCollection(angularCollectionName); assert.strictEqual(angularCollectionName, angularCollection?.getName()); assert.strictEqual(true, angularCollection?.getSchematicsNames().includes('component')); }); it('Schematics', () => { const angularComponentSchematic = workspaceFolder.collections.getCollection(angularCollectionName)?.getSchematic('component'); assert.strictEqual('component', angularComponentSchematic?.getName()); assert.strictEqual(0, angularComponentSchematic?.getRequiredOptions().size); assert.strictEqual(true, angularComponentSchematic?.hasNameAsFirstArg()); assert.strictEqual(true, angularComponentSchematic?.hasOption('changeDetection')); assert.strictEqual(false, angularComponentSchematic?.getOptionDefaultValue('flat')); assert.strictEqual(1, angularComponentSchematic?.getSomeOptions(['export', 'elmo']).size); }); }); describe('Customized', () => { let workspaceFolder: WorkspaceFolderConfig; before(async () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion workspaceFolder = new WorkspaceFolderConfig(vscode.workspace.workspaceFolders![1]!); await workspaceFolder.init(); }); it('Angular default collections', () => { assert.strictEqual(ionicCollectionName, workspaceFolder.getDefaultUserCollection()); assert.deepStrictEqual([ionicCollectionName, angularCollectionName], workspaceFolder.getDefaultCollections()); }); it('Angular projects', () => { assert.strictEqual(3, workspaceFolder.getAngularProjects().size); const rootProject = workspaceFolder.getAngularProject(rootProjectName); assert.strictEqual('application', rootProject?.getType()); assert.strictEqual('', rootProject?.getRootPath()); assert.strictEqual('src', rootProject?.getSourcePath()); assert.strictEqual('src/app', rootProject?.getAppOrLibPath()); assert.strictEqual(true, workspaceFolder.isRootAngularProject(rootProjectName)); const libProject = workspaceFolder.getAngularProject(libProjectName); assert.strictEqual('library', libProject?.getType()); assert.strictEqual('projects/my-lib', libProject?.getRootPath()); assert.strictEqual('projects/my-lib/src', libProject?.getSourcePath()); assert.strictEqual('projects/my-lib/src/lib', libProject?.getAppOrLibPath()); assert.strictEqual(false, workspaceFolder.isRootAngularProject(libProjectName)); const subAppProject = workspaceFolder.getAngularProject(subAppProjectName); assert.strictEqual('application', subAppProject?.getType()); assert.strictEqual('projects/other-app', subAppProject?.getRootPath()); assert.strictEqual('projects/other-app/src', subAppProject?.getSourcePath()); assert.strictEqual('projects/other-app/src/app', subAppProject?.getAppOrLibPath()); assert.strictEqual(false, workspaceFolder.isRootAngularProject(subAppProjectName)); }); it('Angular schematics defaults', () => { assert.strictEqual(true, workspaceFolder.getSchematicsOptionDefaultValue(rootProjectName, `${angularCollectionName}:component`, 'flat')); assert.strictEqual(true, workspaceFolder.getSchematicsOptionDefaultValue(libProjectName, `${angularCollectionName}:component`, 'flat')); assert.strictEqual(false, workspaceFolder.getSchematicsOptionDefaultValue(subAppProjectName, `${angularCollectionName}:component`, 'flat')); }); it('TSLint component suffixes', () => { assert.strictEqual(true, workspaceFolder.hasComponentSuffix(rootProjectName, 'Component')); assert.strictEqual(true, workspaceFolder.hasComponentSuffix(rootProjectName, 'Page')); assert.strictEqual(false, workspaceFolder.hasComponentSuffix(rootProjectName, 'Dialog')); assert.strictEqual(true, workspaceFolder.hasComponentSuffix(libProjectName, 'Component')); assert.strictEqual(true, workspaceFolder.hasComponentSuffix(libProjectName, 'Page')); assert.strictEqual(false, workspaceFolder.hasComponentSuffix(libProjectName, 'Dialog')); assert.strictEqual(true, workspaceFolder.hasComponentSuffix(subAppProjectName, 'Component')); assert.strictEqual(false, workspaceFolder.hasComponentSuffix(subAppProjectName, 'Page')); assert.strictEqual(true, workspaceFolder.hasComponentSuffix(subAppProjectName, 'Dialog')); }); it('Modules types', () => { assert.strictEqual(3, workspaceFolder.getModuleTypes().size); }); it('Component types', () => { assert.strictEqual(8, workspaceFolder.getComponentTypes(rootProjectName).size); const rootPageComponentType = workspaceFolder.getComponentTypes(rootProjectName).get(COMPONENT_TYPE.PAGE); assert.strictEqual('page', rootPageComponentType?.options.get('type')); const libPageComponentType = workspaceFolder.getComponentTypes(libProjectName).get(COMPONENT_TYPE.PAGE); assert.strictEqual('page', libPageComponentType?.options.get('type')); const subAppPageComponentType = workspaceFolder.getComponentTypes(subAppProjectName).get(COMPONENT_TYPE.PAGE); assert.strictEqual(false, subAppPageComponentType?.options.has('type')); }); it('Collections', () => { assert.deepStrictEqual([ionicCollectionName, angularCollectionName, materialCollectionName, '@angular/cdk'], workspaceFolder.collections.getCollectionsNames()); const angularCollection = workspaceFolder.collections.getCollection(angularCollectionName); assert.strictEqual(angularCollectionName, angularCollection?.getName()); assert.strictEqual(true, angularCollection?.getSchematicsNames().includes('component')); const materialCollection = workspaceFolder.collections.getCollection(materialCollectionName); assert.strictEqual(materialCollectionName, materialCollection?.getName()); assert.strictEqual(true, materialCollection?.getSchematicsNames().includes('table')); const ionicCollection = workspaceFolder.collections.getCollection(ionicCollectionName); assert.strictEqual(ionicCollectionName, ionicCollection?.getName()); assert.strictEqual(true, ionicCollection?.getSchematicsNames().includes('component')); assert.strictEqual(true, ionicCollection?.getSchematicsNames().includes('page')); }); it('Schematics', () => { const angularComponentSchematic = workspaceFolder.collections.getCollection(angularCollectionName)?.getSchematic('component'); assert.strictEqual('component', angularComponentSchematic?.getName()); assert.strictEqual(0, angularComponentSchematic?.getRequiredOptions().size); assert.strictEqual(true, angularComponentSchematic?.hasNameAsFirstArg()); assert.strictEqual(true, angularComponentSchematic?.hasOption('changeDetection')); assert.strictEqual(false, angularComponentSchematic?.getOptionDefaultValue('flat')); assert.strictEqual(1, angularComponentSchematic?.getSomeOptions(['export', 'elmo']).size); const materialSchematic = workspaceFolder.collections.getCollection(materialCollectionName)?.getSchematic('table'); assert.strictEqual('table', materialSchematic?.getName()); assert.strictEqual(true, materialSchematic?.hasNameAsFirstArg()); assert.strictEqual(true, materialSchematic?.hasOption('inlineTemplate')); }); }); describe('Angular ESLint', () => { let workspaceFolder: WorkspaceFolderConfig; before(async () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion workspaceFolder = new WorkspaceFolderConfig(vscode.workspace.workspaceFolders![2]!); await workspaceFolder.init(); }); it('ESLint component suffixes', () => { assert.strictEqual(true, workspaceFolder.hasComponentSuffix(rootProjectName, 'Component')); assert.strictEqual(true, workspaceFolder.hasComponentSuffix(rootProjectName, 'Page')); }); }); });
the_stack
import { MoveEvent, ResizeEvent } from '../events'; import { AspectRatio, Coordinates, Limits, PositionRestrictions, ResizeDirections, SizeRestrictions } from '../typings'; import { ALL_DIRECTIONS, HORIZONTAL_DIRECTIONS, VERTICAL_DIRECTIONS } from '../constants'; import { applyDirections, getBrokenRatio, getIntersections, ratio } from '../service'; import { move } from './move'; interface FitConditionsParams { directions: ResizeDirections; coordinates: Coordinates; positionRestrictions: Limits; sizeRestrictions: SizeRestrictions; preserveRatio?: boolean; compensate?: boolean; } export function fitConditions({ directions, coordinates, positionRestrictions = {}, sizeRestrictions, preserveRatio, compensate, }: FitConditionsParams): ResizeDirections { const fittedDirections = { ...directions }; let currentWidth = applyDirections(coordinates, fittedDirections).width; let currentHeight = applyDirections(coordinates, fittedDirections).height; // Prevent strange resizes when the width or height of stencil becomes smaller than 0 if (currentWidth < 0) { if (fittedDirections.left < 0 && fittedDirections.right < 0) { fittedDirections.left = -(coordinates.width - sizeRestrictions.minWidth) / (fittedDirections.left / fittedDirections.right); fittedDirections.right = -(coordinates.width - sizeRestrictions.minWidth) / (fittedDirections.right / fittedDirections.left); } else if (fittedDirections.left < 0) { fittedDirections.left = -(coordinates.width - sizeRestrictions.minWidth); } else if (fittedDirections.right < 0) { fittedDirections.right = -(coordinates.width - sizeRestrictions.minWidth); } } if (currentHeight < 0) { if (fittedDirections.top < 0 && fittedDirections.bottom < 0) { fittedDirections.top = -(coordinates.height - sizeRestrictions.minHeight) / (fittedDirections.top / fittedDirections.bottom); fittedDirections.bottom = -(coordinates.height - sizeRestrictions.minHeight) / (fittedDirections.bottom / fittedDirections.top); } else if (fittedDirections.top < 0) { fittedDirections.top = -(coordinates.height - sizeRestrictions.minHeight); } else if (fittedDirections.bottom < 0) { fittedDirections.bottom = -(coordinates.height - sizeRestrictions.minHeight); } } // Prevent breaking limits let breaks = getIntersections(applyDirections(coordinates, fittedDirections), positionRestrictions); if (compensate) { if (breaks.left && breaks.left > 0 && breaks.right === 0) { fittedDirections.right += breaks.left; fittedDirections.left -= breaks.left; } else if (breaks.right && breaks.right > 0 && breaks.left === 0) { fittedDirections.left += breaks.right; fittedDirections.right -= breaks.right; } if (breaks.top && breaks.top > 0 && breaks.bottom === 0) { fittedDirections.bottom += breaks.top; fittedDirections.top -= breaks.top; } else if (breaks.bottom && breaks.bottom > 0 && breaks.top === 0) { fittedDirections.top += breaks.bottom; fittedDirections.bottom -= breaks.bottom; } breaks = getIntersections(applyDirections(coordinates, fittedDirections), positionRestrictions); } const maxResize = { width: Infinity, height: Infinity, left: Infinity, right: Infinity, top: Infinity, bottom: Infinity, }; ALL_DIRECTIONS.forEach((direction) => { const intersection = breaks[direction]; if (intersection && fittedDirections[direction]) { maxResize[direction] = Math.max(0, 1 - intersection / fittedDirections[direction]); } }); if (preserveRatio) { const multiplier = Math.min(...ALL_DIRECTIONS.map((direction) => maxResize[direction])); if (multiplier !== Infinity) { ALL_DIRECTIONS.forEach((direction) => { fittedDirections[direction] *= multiplier; }); } } else { ALL_DIRECTIONS.forEach((direction) => { if (maxResize[direction] !== Infinity) { fittedDirections[direction] *= maxResize[direction]; } }); } currentWidth = applyDirections(coordinates, fittedDirections).width; currentHeight = applyDirections(coordinates, fittedDirections).height; if (fittedDirections.right + fittedDirections.left) { if (currentWidth > sizeRestrictions.maxWidth) { maxResize.width = (sizeRestrictions.maxWidth - coordinates.width) / (fittedDirections.right + fittedDirections.left); } else if (currentWidth < sizeRestrictions.minWidth) { maxResize.width = (sizeRestrictions.minWidth - coordinates.width) / (fittedDirections.right + fittedDirections.left); } } if (fittedDirections.bottom + fittedDirections.top) { if (currentHeight > sizeRestrictions.maxHeight) { maxResize.height = (sizeRestrictions.maxHeight - coordinates.height) / (fittedDirections.bottom + fittedDirections.top); } else if (currentHeight < sizeRestrictions.minHeight) { maxResize.height = (sizeRestrictions.minHeight - coordinates.height) / (fittedDirections.bottom + fittedDirections.top); } } if (preserveRatio) { const multiplier = Math.min(maxResize.width, maxResize.height); if (multiplier !== Infinity) { ALL_DIRECTIONS.forEach((direction) => { fittedDirections[direction] *= multiplier; }); } } else { if (maxResize.width !== Infinity) { HORIZONTAL_DIRECTIONS.forEach((direction) => { fittedDirections[direction] *= maxResize.width; }); } if (maxResize.height !== Infinity) { VERTICAL_DIRECTIONS.forEach((direction) => { fittedDirections[direction] *= maxResize.height; }); } } return fittedDirections; } export interface ResizeParams { event: ResizeEvent; coordinates: Coordinates; aspectRatio: AspectRatio; sizeRestrictions: SizeRestrictions; positionRestrictions: PositionRestrictions; } function distributeOverlap(overlap: number, first: number, second: number) { if (first == 0 && second == 0) { return overlap / 2; } else if (first == 0) { return 0; } else if (second == 0) { return overlap; } else { return overlap * Math.abs(first / (first + second)); } } export function resize(params: ResizeParams): Coordinates { const { event, coordinates, aspectRatio, positionRestrictions, sizeRestrictions } = params; const actualCoordinates = { ...coordinates, right: coordinates.left + coordinates.width, bottom: coordinates.top + coordinates.height, }; const eventParams = event.params || {}; let directions = { ...event.directions, }; const allowedDirections = eventParams.allowedDirections || { left: true, right: true, bottom: true, top: true, }; if (sizeRestrictions.widthFrozen) { directions.left = 0; directions.right = 0; } if (sizeRestrictions.heightFrozen) { directions.top = 0; directions.bottom = 0; } ALL_DIRECTIONS.forEach((direction) => { if (!allowedDirections[direction]) { directions[direction] = 0; } }); // 1. First step: determine the safe and desired area directions = fitConditions({ coordinates: actualCoordinates, directions, sizeRestrictions: sizeRestrictions, positionRestrictions, }); // 2. Second step: fix desired box to correspondent to aspect ratio let currentWidth = applyDirections(actualCoordinates, directions).width; let currentHeight = applyDirections(actualCoordinates, directions).height; // Checks ratio: let ratioBroken = eventParams.preserveRatio ? ratio(actualCoordinates) : getBrokenRatio(currentWidth / currentHeight, aspectRatio); if (ratioBroken) { let { respectDirection } = eventParams; if (!respectDirection) { if (actualCoordinates.width >= actualCoordinates.height || ratioBroken === 1) { respectDirection = 'width'; } else { respectDirection = 'height'; } } if (respectDirection === 'width') { const overlapHeight = currentWidth / ratioBroken - actualCoordinates.height; if (allowedDirections.top && allowedDirections.bottom) { const { top, bottom } = directions; directions.bottom = distributeOverlap(overlapHeight, bottom, top); directions.top = distributeOverlap(overlapHeight, top, bottom); } else if (allowedDirections.bottom) { directions.bottom = overlapHeight; } else if (allowedDirections.top) { directions.top = overlapHeight; } else if (allowedDirections.right) { directions.right = 0; } else if (allowedDirections.left) { directions.left = 0; } } else if (respectDirection === 'height') { const overlapWidth = actualCoordinates.width - currentHeight * ratioBroken; if (allowedDirections.left && allowedDirections.right) { const { left, right } = directions; directions.left = -distributeOverlap(overlapWidth, left, right); directions.right = -distributeOverlap(overlapWidth, right, left); } else if (allowedDirections.left) { directions.left = -overlapWidth; } else if (allowedDirections.right) { directions.right = -overlapWidth; } else if (allowedDirections.top) { directions.top = 0; } else if (allowedDirections.bottom) { directions.bottom = 0; } } // 3. Third step: check if desired box with correct aspect ratios break some limits and fit to this conditions directions = fitConditions({ directions, coordinates: actualCoordinates, sizeRestrictions: sizeRestrictions, positionRestrictions, preserveRatio: true, compensate: eventParams.compensate, }); } // 4. Check if ratio broken (temporary): currentWidth = applyDirections(actualCoordinates, directions).width; currentHeight = applyDirections(actualCoordinates, directions).height; ratioBroken = eventParams.preserveRatio ? ratio(actualCoordinates) : getBrokenRatio(currentWidth / currentHeight, aspectRatio); if (ratioBroken && Math.abs(ratioBroken - currentWidth / currentHeight) > 1e-3) { if (process.env.NODE_ENV !== 'production') { console.error( `Something went wrong and ratio was broken: ${currentWidth / currentHeight} instead of ${ratioBroken}`, ); } ALL_DIRECTIONS.forEach((direction) => { if (!allowedDirections[direction]) { directions[direction] = 0; } }); } return move({ event: new MoveEvent({ left: -directions.left, top: -directions.top, }), coordinates: { width: coordinates.width + directions.right + directions.left, height: coordinates.height + directions.top + directions.bottom, left: coordinates.left, top: coordinates.top, }, positionRestrictions, }); }
the_stack
import { parseMillis, isUndefined, untruncateYear, signedOffset, hasOwnProperty } from "./util.js"; import Formatter from "./formatter.js"; import FixedOffsetZone from "../zones/fixedOffsetZone.js"; import IANAZone from "../zones/IANAZone.js"; import DateTime from "../datetime.js"; import { digitRegex, parseDigits } from "./digits.js"; import { ConflictingSpecificationError } from "../errors.js"; const MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; function intUnit(regex, post = i => i) { return { regex, deser: ([s]) => post(parseDigits(s)) }; } const NBSP = String.fromCharCode(160); const spaceOrNBSP = `( |${NBSP})`; const spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); function fixListRegex(s) { // make dots optional and also make them literal // make space and non breakable space characters interchangeable return s.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); } function stripInsensitivities(s) { return s .replace(/\./g, "") // ignore dots that were made optional .replace(spaceOrNBSPRegExp, " ") // interchange space and nbsp .toLowerCase(); } function oneOf(strings, startIndex) { if (strings === null) { return null; } else { return { regex: RegExp(strings.map(fixListRegex).join("|")), deser: ([s]) => strings.findIndex(i => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex }; } } function offset(regex, groups) { return { regex, deser: ([, h, m]) => signedOffset(h, m), groups }; } function simple(regex) { return { regex, deser: ([s]) => s }; } function escapeToken(value) { // eslint-disable-next-line no-useless-escape return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); } function unitForToken(token, loc) { const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = t => ({ regex: RegExp(escapeToken(t.val)), deser: ([s]) => s, literal: true }), unitate = t => { if (token.literal) { return literal(t); } switch (t.val) { // era case "G": return oneOf(loc.eras("short", false), 0); case "GG": return oneOf(loc.eras("long", false), 0); // years case "y": return intUnit(oneToSix); case "yy": return intUnit(twoToFour, untruncateYear); case "yyyy": return intUnit(four); case "yyyyy": return intUnit(fourToSix); case "yyyyyy": return intUnit(six); // months case "M": return intUnit(oneOrTwo); case "MM": return intUnit(two); case "MMM": return oneOf(loc.months("short", true, false), 1); case "MMMM": return oneOf(loc.months("long", true, false), 1); case "L": return intUnit(oneOrTwo); case "LL": return intUnit(two); case "LLL": return oneOf(loc.months("short", false, false), 1); case "LLLL": return oneOf(loc.months("long", false, false), 1); // dates case "d": return intUnit(oneOrTwo); case "dd": return intUnit(two); // ordinals case "o": return intUnit(oneToThree); case "ooo": return intUnit(three); // time case "HH": return intUnit(two); case "H": return intUnit(oneOrTwo); case "hh": return intUnit(two); case "h": return intUnit(oneOrTwo); case "mm": return intUnit(two); case "m": return intUnit(oneOrTwo); case "q": return intUnit(oneOrTwo); case "qq": return intUnit(two); case "s": return intUnit(oneOrTwo); case "ss": return intUnit(two); case "S": return intUnit(oneToThree); case "SSS": return intUnit(three); case "u": return simple(oneToNine); // meridiem case "a": return oneOf(loc.meridiems(), 0); // weekYear (k) case "kkkk": return intUnit(four); case "kk": return intUnit(twoToFour, untruncateYear); // weekNumber (W) case "W": return intUnit(oneOrTwo); case "WW": return intUnit(two); // weekdays case "E": case "c": return intUnit(one); case "EEE": return oneOf(loc.weekdays("short", false, false), 1); case "EEEE": return oneOf(loc.weekdays("long", false, false), 1); case "ccc": return oneOf(loc.weekdays("short", true, false), 1); case "cccc": return oneOf(loc.weekdays("long", true, false), 1); // offset/zone case "Z": case "ZZ": return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); case "ZZZ": return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing // because we don't have any way to figure out what they are case "z": return simple(/[a-z_+-/]{1,256}?/i); default: return literal(t); } }; const unit = unitate(token) || { invalidReason: MISSING_FTP }; unit.token = token; return unit; } const partTypeStyleToTokenVal = { year: { "2-digit": "yy", numeric: "yyyyy" }, month: { numeric: "M", "2-digit": "MM", short: "MMM", long: "MMMM" }, day: { numeric: "d", "2-digit": "dd" }, weekday: { short: "EEE", long: "EEEE" }, dayperiod: "a", dayPeriod: "a", hour: { numeric: "h", "2-digit": "hh" }, minute: { numeric: "m", "2-digit": "mm" }, second: { numeric: "s", "2-digit": "ss" } }; function tokenForPart(part, locale, formatOpts) { const { type, value } = part; if (type === "literal") { return { literal: true, val: value }; } const style = formatOpts[type]; let val = partTypeStyleToTokenVal[type]; if (typeof val === "object") { val = val[style]; } if (val) { return { literal: false, val }; } return undefined; } function buildRegex(units) { const re = units.map(u => u.regex).reduce((f, r) => `${f}(${r.source})`, ""); return [`^${re}$`, units]; } function match(input, regex, handlers) { const matches = input.match(regex); if (matches) { const all = {}; let matchIndex = 1; for (const i in handlers) { if (hasOwnProperty(handlers, i)) { const h = handlers[i], groups = h.groups ? h.groups + 1 : 1; if (!h.literal && h.token) { all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups)); } matchIndex += groups; } } return [matches, all]; } else { return [matches, {}]; } } function dateTimeFromMatches(matches) { const toField = token => { switch (token) { case "S": return "millisecond"; case "s": return "second"; case "m": return "minute"; case "h": case "H": return "hour"; case "d": return "day"; case "o": return "ordinal"; case "L": case "M": return "month"; case "y": return "year"; case "E": case "c": return "weekday"; case "W": return "weekNumber"; case "k": return "weekYear"; case "q": return "quarter"; default: return null; } }; let zone; if (!isUndefined(matches.Z)) { zone = new FixedOffsetZone(matches.Z); } else if (!isUndefined(matches.z)) { zone = IANAZone.create(matches.z); } else { zone = null; } if (!isUndefined(matches.q)) { matches.M = (matches.q - 1) * 3 + 1; } if (!isUndefined(matches.h)) { if (matches.h < 12 && matches.a === 1) { matches.h += 12; } else if (matches.h === 12 && matches.a === 0) { matches.h = 0; } } if (matches.G === 0 && matches.y) { matches.y = -matches.y; } if (!isUndefined(matches.u)) { matches.S = parseMillis(matches.u); } const vals = Object.keys(matches).reduce((r, k) => { const f = toField(k); if (f) { r[f] = matches[k]; } return r; }, {}); return [vals, zone]; } let dummyDateTimeCache = null; function getDummyDateTime() { if (!dummyDateTimeCache) { dummyDateTimeCache = DateTime.fromMillis(1555555555555); } return dummyDateTimeCache; } function maybeExpandMacroToken(token, locale) { if (token.literal) { return token; } const formatOpts = Formatter.macroTokenToFormatOpts(token.val); if (!formatOpts) { return token; } const formatter = Formatter.create(locale, formatOpts); const parts = formatter.formatDateTimeParts(getDummyDateTime()); const tokens = parts.map(p => tokenForPart(p, locale, formatOpts)); if (tokens.includes(undefined)) { return token; } return tokens; } function expandMacroTokens(tokens, locale) { return Array.prototype.concat(...tokens.map(t => maybeExpandMacroToken(t, locale))); } /** * @private */ export function explainFromTokens(locale, input, format) { const tokens = expandMacroTokens(Formatter.parseFormat(format), locale), units = tokens.map(t => unitForToken(t, locale)), disqualifyingUnit = units.find(t => t.invalidReason); if (disqualifyingUnit) { return { input, tokens, invalidReason: disqualifyingUnit.invalidReason }; } else { const [regexString, handlers] = buildRegex(units), regex = RegExp(regexString, "i"), [rawMatches, matches] = match(input, regex, handlers), [result, zone] = matches ? dateTimeFromMatches(matches) : [null, null]; if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) { throw new ConflictingSpecificationError( "Can't include meridiem when specifying 24-hour format" ); } return { input, tokens, regex, rawMatches, matches, result, zone }; } } export function parseFromTokens(locale, input, format) { const { result, zone, invalidReason } = explainFromTokens(locale, input, format); return [result, zone, invalidReason]; }
the_stack
import { assert, expect } from "chai"; import { DbResult, Id64, Id64String } from "@itwin/core-bentley"; import { BriefcaseIdValue, Code, ColorDef, ElementAspectProps, GeometricElementProps, GeometryStreamProps, IModel, QueryRowFormat, SubCategoryAppearance, } from "@itwin/core-common"; import { Arc3d, Cone, IModelJson as GeomJson, Point2d, Point3d } from "@itwin/core-geometry"; import { ECSqlStatement, IModelDb, IModelJsFs, SnapshotDb, SpatialCategory } from "../../core-backend"; import { ElementRefersToElements } from "../../Relationship"; import { IModelTestUtils } from "../IModelTestUtils"; /* eslint-disable @typescript-eslint/naming-convention */ interface IPrimitiveBase { i?: number; l?: number; d?: number; b?: boolean; dt?: string; s?: string; bin?: Uint8Array; p2d?: Point2d; p3d?: Point3d; g?: GeometryStreamProps; } interface IPrimitive extends IPrimitiveBase { st?: ComplexStruct; } interface IPrimitiveArrayBase { array_i?: number[]; array_l?: number[]; array_d?: number[]; array_b?: boolean[]; array_dt?: string[]; array_s?: string[]; array_bin?: Uint8Array[]; array_p2d?: Point2d[]; array_p3d?: Point3d[]; array_g?: GeometryStreamProps[]; array_st?: ComplexStruct[]; } interface IPrimitiveArray extends IPrimitiveArrayBase { array_st?: ComplexStruct[]; } interface ComplexStruct extends IPrimitiveArrayBase, IPrimitiveBase { } interface TestElement extends IPrimitive, IPrimitiveArray, GeometricElementProps { } interface TestElementAspect extends IPrimitive, IPrimitiveArray, ElementAspectProps { } interface TestElementRefersToElements extends IPrimitive, IPrimitiveArray, ElementRefersToElements { } function verifyPrimitiveBase(actualValue: IPrimitiveBase, expectedValue: IPrimitiveBase) { if (expectedValue.i) assert.equal(actualValue.i, expectedValue.i, "'integer' type property did not roundtrip as expected"); if (expectedValue.l) assert.equal(actualValue.l, expectedValue.l, "'long' type property did not roundtrip as expected"); if (expectedValue.d) assert.equal(actualValue.d, expectedValue.d, "'double' type property did not roundtrip as expected"); if (expectedValue.b) assert.equal(actualValue.b, expectedValue.b, "'boolean' type property did not roundtrip as expected"); if (expectedValue.dt) assert.equal(actualValue.dt, expectedValue.dt, "'dateTime' type property did not roundtrip as expected"); if (expectedValue.s) assert.equal(actualValue.s, expectedValue.s, "'string' type property did not roundtrip as expected"); if (expectedValue.p2d) { assert.equal(actualValue.p2d?.x, expectedValue.p2d?.x, "'Point2d.x' type property did not roundtrip as expected"); assert.equal(actualValue.p2d?.y, expectedValue.p2d?.y, "'Point2d.y' type property did not roundtrip as expected"); } if (expectedValue.p3d) { assert.equal(actualValue.p3d?.x, expectedValue.p3d?.x, "'Point3d.x' type property did not roundtrip as expected"); assert.equal(actualValue.p3d?.y, expectedValue.p3d?.y, "'Point3d.y' type property did not roundtrip as expected"); assert.equal(actualValue.p3d?.z, expectedValue.p3d?.z, "'Point3d.z' type property did not roundtrip as expected"); } if (expectedValue.bin) assert.isTrue(blobEqual(actualValue.bin, expectedValue.bin), "'binary' type property did not roundtrip as expected"); if (expectedValue.g) expect(actualValue.g, "'geometry' type property did not roundtrip as expected.").to.deep.equal(expectedValue.g); } function verifyPrimitiveArrayBase(actualValue: IPrimitiveArrayBase, expectedValue: IPrimitiveArrayBase) { if (expectedValue.array_bin) { assert.equal(actualValue.array_bin!.length, expectedValue.array_bin.length, "'binary[].length' array length mismatch"); expectedValue.array_bin.forEach((value, index) => { assert.isTrue(blobEqual(actualValue.array_bin![index], value), "'binary[]' type property did not roundtrip as expected"); }); } if (expectedValue.array_i) { assert.equal(actualValue.array_i!.length, expectedValue.array_i.length, "'integer[].length' array length mismatch"); expectedValue.array_i.forEach((value, index) => { assert.equal(actualValue.array_i![index], value, "'integer[]' type property did not roundtrip as expected"); }); } if (expectedValue.array_l) { assert.equal(actualValue.array_l!.length, expectedValue.array_l.length, "'long[].length' array length mismatch"); expectedValue.array_l.forEach((value, index) => { assert.equal(actualValue.array_l![index], value, "'long[]' type property did not roundtrip as expected"); }); } if (expectedValue.array_d) { assert.equal(actualValue.array_d!.length, expectedValue.array_d.length, "'double[].length' array length mismatch"); expectedValue.array_d.forEach((value, index) => { assert.equal(actualValue.array_d![index], value, "'double[]' type property did not roundtrip as expected"); }); } if (expectedValue.array_b) { assert.equal(actualValue.array_b!.length, expectedValue.array_b.length, "'boolean[].length' array length mismatch"); expectedValue.array_b.forEach((value, index) => { assert.equal(actualValue.array_b![index], value, "'boolean[]' type property did not roundtrip as expected"); }); } if (expectedValue.array_dt) { assert.equal(actualValue.array_dt!.length, expectedValue.array_dt.length, "'dateTime[].length' array length mismatch"); expectedValue.array_dt.forEach((value, index) => { assert.equal(actualValue.array_dt![index], value, "'dateTime[]' type property did not roundtrip as expected"); }); } if (expectedValue.array_g) { assert.equal(actualValue.array_g!.length, expectedValue.array_g.length, "'geometry[].length' array length mismatch"); expectedValue.array_g.forEach((value, index) => { expect(actualValue.array_g![index], "'geometry[]' type property did not roundtrip as expected").to.deep.equal(value); }); } if (expectedValue.array_s) { assert.equal(actualValue.array_s!.length, expectedValue.array_s.length, "'string[].length' array length mismatch"); expectedValue.array_s.forEach((value, index) => { assert.equal(actualValue.array_s![index], value, "'string[]' type property did not roundtrip as expected"); }); } if (expectedValue.array_p2d) { assert.equal(actualValue.array_p2d!.length, expectedValue.array_p2d.length, "'point2d[].length' array length mismatch"); expectedValue.array_p2d.forEach((value, index) => { assert.equal(actualValue.array_p2d![index].x, value.x, "'point2d[].x' type property did not roundtrip as expected"); assert.equal(actualValue.array_p2d![index].y, value.y, "'point2d[].y' type property did not roundtrip as expected"); }); } if (expectedValue.array_p3d) { assert.equal(actualValue.array_p3d!.length, expectedValue.array_p3d.length, "'point3d[].length' array length mismatch"); expectedValue.array_p3d.forEach((value, index) => { assert.equal(actualValue.array_p3d![index].x, value.x, "'point3d[].x' type property did not roundtrip as expected"); assert.equal(actualValue.array_p3d![index].y, value.y, "'point3d[].y' type property did not roundtrip as expected"); assert.equal(actualValue.array_p3d![index].z, value.z, "'point3d[].z' type property did not roundtrip as expected"); }); } } function verifyPrimitive(actualValue: IPrimitive, expectedValue: IPrimitive) { verifyPrimitiveBase(actualValue, expectedValue); if (expectedValue.st) { verifyPrimitive(actualValue.st!, expectedValue.st); verifyPrimitiveArray(actualValue.st!, expectedValue.st); } } function verifyPrimitiveArray(actualValue: IPrimitiveArray, expectedValue: IPrimitiveArray) { verifyPrimitiveArrayBase(actualValue, expectedValue); if (expectedValue.array_st) { assert.equal(actualValue.array_st!.length, expectedValue.array_st.length, "'struct[].length' array length mismatch"); actualValue.array_st!.forEach((lhs: ComplexStruct, i: number) => { verifyPrimitiveBase(lhs, expectedValue.array_st![i]); verifyPrimitiveArrayBase(lhs, expectedValue.array_st![i]); }); } } function verifyTestElement(actualValue: TestElement, expectedValue: TestElement) { verifyPrimitive(actualValue, expectedValue); verifyPrimitiveArray(actualValue, expectedValue); } function verifyTestElementAspect(actualValue: TestElementAspect, expectedValue: TestElementAspect) { verifyPrimitive(actualValue, expectedValue); verifyPrimitiveArray(actualValue, expectedValue); } function initElemProps(className: string, _iModelName: IModelDb, modId: Id64String, catId: Id64String, autoHandledProp: any): GeometricElementProps { // add Geometry const geomArray: Arc3d[] = [ Arc3d.createXY(Point3d.create(0, 0), 5), Arc3d.createXY(Point3d.create(5, 5), 2), Arc3d.createXY(Point3d.create(-5, -5), 20), ]; const geometryStream: GeometryStreamProps = []; for (const geom of geomArray) { const arcData = GeomJson.Writer.toIModelJson(geom); geometryStream.push(arcData); } // Create props const elementProps: GeometricElementProps = { classFullName: `ElementRoundTripTest:${className}`, model: modId, category: catId, code: Code.createEmpty(), geom: geometryStream, }; if (autoHandledProp) Object.assign(elementProps, autoHandledProp); return elementProps; } function initElementAspectProps(className: string, _iModelName: IModelDb, elId: Id64String, autoHandledProp: any) { // Create props const elementProps: ElementAspectProps = { classFullName: `ElementRoundTripTest:${className}`, element: { id: elId }, }; if (autoHandledProp) Object.assign(elementProps, autoHandledProp); return elementProps; } function blobEqual(lhs: any, rhs: any) { if (!(lhs instanceof Uint8Array) || !(rhs instanceof Uint8Array)) throw new Error("expecting uint8array"); if (lhs.byteLength !== rhs.byteLength) return false; for (let i = 0; i < lhs.byteLength; i++) { if (lhs[i] !== rhs[i]) return false; } return true; } function initElementRefersToElementsProps(className: string, _iModelName: IModelDb, elId1: Id64String, elId2: Id64String, autoHandledProp: any): TestElementRefersToElements { // Create props const result: TestElementRefersToElements = { classFullName: `ElementRoundTripTest:${className}`, sourceId: elId1, targetId: elId2, } as TestElementRefersToElements; if (autoHandledProp) Object.assign(result, autoHandledProp); return result; } describe("Element and ElementAspect roundtrip test for all type of properties", () => { const testSchema = `<?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="ElementRoundTripTest" alias="ts" version="01.00.00" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECSchemaReference name="BisCore" version="01.00.04" alias="bis"/> <ECSchemaReference name="CoreCustomAttributes" version="01.00.03" alias="CoreCA"/> <ECEntityClass typeName="TestElement" modifier="None"> <BaseClass>bis:PhysicalElement</BaseClass> <BaseClass>IPrimitive</BaseClass> <BaseClass>IPrimitiveArray</BaseClass> </ECEntityClass> <ECEntityClass typeName="TestElementAspect" modifier="None"> <BaseClass>bis:ElementUniqueAspect</BaseClass> <BaseClass>IPrimitiveAspect</BaseClass> <BaseClass>IPrimitiveArrayAspect</BaseClass> </ECEntityClass> <ECRelationshipClass typeName="TestElementRefersToElements" strength="referencing" modifier="Sealed"> <BaseClass>bis:ElementRefersToElements</BaseClass> <Source multiplicity="(0..*)" roleLabel="refers to" polymorphic="true"> <Class class="TestElement"/> </Source> <Target multiplicity="(0..*)" roleLabel="is referenced by" polymorphic="true"> <Class class="TestElement"/> </Target> <ECProperty propertyName="i" typeName="int"/> <ECProperty propertyName="l" typeName="long"/> <ECProperty propertyName="d" typeName="double"/> <ECProperty propertyName="b" typeName="boolean"/> <ECProperty propertyName="dt" typeName="dateTime"/> <ECProperty propertyName="s" typeName="string"/> <ECProperty propertyName="bin" typeName="binary"/> <ECProperty propertyName="p2d" typeName="point2d"/> <ECProperty propertyName="p3d" typeName="point3d"/> <ECProperty propertyName="g" typeName="Bentley.Geometry.Common.IGeometry"/> <!--<ECStructProperty propertyName="st" typeName="ComplexStruct"/>--> <ECArrayProperty propertyName="array_i" typeName="int" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_l" typeName="long" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_d" typeName="double" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_b" typeName="boolean" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_dt" typeName="dateTime" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_s" typeName="string" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_bin" typeName="binary" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_p2d" typeName="point2d" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_p3d" typeName="point3d" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_g" typeName="Bentley.Geometry.Common.IGeometry" minOccurs="0" maxOccurs="unbounded"/> <!--<ECStructArrayProperty propertyName="array_st" typeName="ComplexStruct" minOccurs="0" maxOccurs="unbounded"/>--> </ECRelationshipClass> <ECEntityClass typeName="IPrimitive" modifier="Abstract"> <ECCustomAttributes> <IsMixin xmlns="CoreCustomAttributes.01.00.03"> <AppliesToEntityClass>bis:PhysicalElement</AppliesToEntityClass> </IsMixin> </ECCustomAttributes> <ECProperty propertyName="i" typeName="int"/> <ECProperty propertyName="l" typeName="long"/> <ECProperty propertyName="d" typeName="double"/> <ECProperty propertyName="b" typeName="boolean"/> <ECProperty propertyName="dt" typeName="dateTime"/> <ECProperty propertyName="s" typeName="string"/> <ECProperty propertyName="bin" typeName="binary"/> <ECProperty propertyName="p2d" typeName="point2d"/> <ECProperty propertyName="p3d" typeName="point3d"/> <ECProperty propertyName="g" typeName="Bentley.Geometry.Common.IGeometry"/> <ECStructProperty propertyName="st" typeName="ComplexStruct"/> </ECEntityClass> <ECEntityClass typeName="IPrimitiveAspect" modifier="Abstract"> <ECCustomAttributes> <IsMixin xmlns="CoreCustomAttributes.01.00.03"> <AppliesToEntityClass>bis:ElementUniqueAspect</AppliesToEntityClass> </IsMixin> </ECCustomAttributes> <ECProperty propertyName="i" typeName="int"/> <ECProperty propertyName="l" typeName="long"/> <ECProperty propertyName="d" typeName="double"/> <ECProperty propertyName="b" typeName="boolean"/> <ECProperty propertyName="dt" typeName="dateTime"/> <ECProperty propertyName="s" typeName="string"/> <ECProperty propertyName="bin" typeName="binary"/> <ECProperty propertyName="p2d" typeName="point2d"/> <ECProperty propertyName="p3d" typeName="point3d"/> <ECProperty propertyName="g" typeName="Bentley.Geometry.Common.IGeometry"/> <ECStructProperty propertyName="st" typeName="ComplexStruct"/> </ECEntityClass> <ECEntityClass typeName="IPrimitiveArray" modifier="Abstract"> <ECCustomAttributes> <IsMixin xmlns="CoreCustomAttributes.01.00.03"> <AppliesToEntityClass>bis:PhysicalElement</AppliesToEntityClass> </IsMixin> </ECCustomAttributes> <ECArrayProperty propertyName="array_i" typeName="int" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_l" typeName="long" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_d" typeName="double" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_b" typeName="boolean" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_dt" typeName="dateTime" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_s" typeName="string" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_bin" typeName="binary" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_p2d" typeName="point2d" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_p3d" typeName="point3d" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_g" typeName="Bentley.Geometry.Common.IGeometry" minOccurs="0" maxOccurs="unbounded"/> <ECStructArrayProperty propertyName="array_st" typeName="ComplexStruct" minOccurs="0" maxOccurs="unbounded"/> </ECEntityClass> <ECEntityClass typeName="IPrimitiveArrayAspect" modifier="Abstract"> <ECCustomAttributes> <IsMixin xmlns="CoreCustomAttributes.01.00.03"> <AppliesToEntityClass>bis:ElementUniqueAspect</AppliesToEntityClass> </IsMixin> </ECCustomAttributes> <ECArrayProperty propertyName="array_i" typeName="int" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_l" typeName="long" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_d" typeName="double" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_b" typeName="boolean" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_dt" typeName="dateTime" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_s" typeName="string" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_bin" typeName="binary" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_p2d" typeName="point2d" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_p3d" typeName="point3d" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_g" typeName="Bentley.Geometry.Common.IGeometry" minOccurs="0" maxOccurs="unbounded"/> <ECStructArrayProperty propertyName="array_st" typeName="ComplexStruct" minOccurs="0" maxOccurs="unbounded"/> </ECEntityClass> <ECStructClass typeName="ComplexStruct" modifier="None"> <ECProperty propertyName="i" typeName="int"/> <ECProperty propertyName="l" typeName="long"/> <ECProperty propertyName="d" typeName="double"/> <ECProperty propertyName="b" typeName="boolean"/> <ECProperty propertyName="dt" typeName="dateTime"/> <ECProperty propertyName="s" typeName="string"/> <ECProperty propertyName="bin" typeName="binary"/> <ECProperty propertyName="p2d" typeName="point2d"/> <ECProperty propertyName="p3d" typeName="point3d"/> <ECProperty propertyName="g" typeName="Bentley.Geometry.Common.IGeometry"/> <ECArrayProperty propertyName="array_i" typeName="int" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_l" typeName="long" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_d" typeName="double" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_b" typeName="boolean" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_dt" typeName="dateTime" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_s" typeName="string" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_bin" typeName="binary" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_p2d" typeName="point2d" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_p3d" typeName="point3d" minOccurs="0" maxOccurs="unbounded"/> <ECArrayProperty propertyName="array_g" typeName="Bentley.Geometry.Common.IGeometry" minOccurs="0" maxOccurs="unbounded"/> </ECStructClass> </ECSchema>`; const schemaFileName = "ElementRoundTripTest.01.00.00.xml"; const iModelFileName = "ElementRoundTripTest.bim"; const categoryName = "RoundTripCategory"; const subDirName = "ElementRoundTrip"; const iModelPath = IModelTestUtils.prepareOutputFile(subDirName, iModelFileName); const primInst1: IPrimitiveBase = { i: 101, l: 12334343434, d: 1023.34, b: true, dt: "2017-01-01T00:00:00.000", s: "Test string Inst1", bin: new Uint8Array([1, 2, 3]), g: GeomJson.Writer.toIModelJson(Cone.createAxisPoints(Point3d.create(0, 0, 0), Point3d.create(0, 0, 1), 0.5, 0.5, false)), p2d: new Point2d(1.034, 2.034), p3d: new Point3d(-1.0, 2.3, 3.0001), }; const primInst2: IPrimitiveBase = { i: 4322, l: 98283333, d: -2343.342, b: false, dt: "2010-01-01T11:11:11.000", s: "Test string Inst2", bin: new Uint8Array([11, 21, 31, 34, 53, 21, 14, 14, 55, 22]), g: GeomJson.Writer.toIModelJson(Cone.createAxisPoints(Point3d.create(0, 1, 0), Point3d.create(0, 0, 1), 0.5, 0.5, false)), p2d: new Point2d(1111.11, 2222.22), p3d: new Point3d(-111.11, -222.22, -333.33), }; const primArrInst1: IPrimitiveArrayBase = { array_i: [101, 202, -345], array_l: [12334343434, 3434343434, 12], array_d: [1023.34, 3023.34, -3432.033], array_b: [true, false, true, false], array_dt: ["2017-01-01T00:00:00.000", "2018-01-01T00:00:00.000"], array_s: ["Test string 1", "Test string 2", "Test string 3"], array_bin: [new Uint8Array([1, 2, 3]), new Uint8Array([4, 2, 3, 3, 4, 55, 6, 65])], array_p2d: [new Point2d(1, 2), new Point2d(2, 4)], array_p3d: [new Point3d(1, 2, 3), new Point3d(4, 5, 6)], array_g: [ GeomJson.Writer.toIModelJson(Cone.createAxisPoints(Point3d.create(0, 1, 0), Point3d.create(0, 0, 2), 0.5, 0.5, false)), GeomJson.Writer.toIModelJson(Cone.createAxisPoints(Point3d.create(0, 1, 1), Point3d.create(0, 0, 2), 0.5, 0.5, false)), ], }; const primArrInst2: IPrimitiveArrayBase = { array_i: [0, 1, 2, 3, 4, 5, 6666], array_l: [-23422, -343343434, -12333434, 23423423], array_d: [-21023.34, -33023.34, -34432.033], array_b: [false, true], array_dt: ["2017-01-01T00:00:00.000", "2018-01-01T00:00:00.000", "2011-01-01T00:00:00.000"], array_s: ["Test string 1 - inst2", "Test string 2 - inst2", "Test string 3 - inst2"], array_bin: [new Uint8Array([1, 2, 3, 3, 4]), new Uint8Array([0, 0, 0, 0]), new Uint8Array([1, 2, 3, 4])], array_p2d: [new Point2d(-123, 244.23232), new Point2d(232, 324.2323), new Point2d(322, 2324.23322)], array_p3d: [new Point3d(133, 2333, 333), new Point3d(4123, 5123, 6123)], array_g: [ GeomJson.Writer.toIModelJson(Cone.createAxisPoints(Point3d.create(0, 1, 0), Point3d.create(0, 0, 2), 0.5, 0.5, false)), GeomJson.Writer.toIModelJson(Cone.createAxisPoints(Point3d.create(0, 1, 1), Point3d.create(0, 0, 2), 0.5, 0.5, false)), ], }; before(async () => { // write schema to disk as we do not have api to import xml directly const testSchemaPath = IModelTestUtils.prepareOutputFile(subDirName, schemaFileName); IModelJsFs.writeFileSync(testSchemaPath, testSchema); const imodel = SnapshotDb.createEmpty(iModelPath, { rootSubject: { name: "RoundTripTest" } }); await imodel.importSchemas([testSchemaPath]); imodel.nativeDb.resetBriefcaseId(BriefcaseIdValue.Unassigned); IModelTestUtils.createAndInsertPhysicalPartitionAndModel(imodel, Code.createEmpty(), true); let spatialCategoryId = SpatialCategory.queryCategoryIdByName(imodel, IModel.dictionaryId, categoryName); if (undefined === spatialCategoryId) spatialCategoryId = SpatialCategory.insert(imodel, IModel.dictionaryId, categoryName, new SubCategoryAppearance({ color: ColorDef.create("rgb(255,0,0)").toJSON() })); imodel.saveChanges(); imodel.close(); }); it("Roundtrip all type of properties via ElementApi, ConcurrentQuery and ECSqlStatement via insert and update", async () => { const testFileName = IModelTestUtils.prepareOutputFile(subDirName, "roundtrip_correct_data.bim"); const imodel = IModelTestUtils.createSnapshotFromSeed(testFileName, iModelPath); const spatialCategoryId = SpatialCategory.queryCategoryIdByName(imodel, IModel.dictionaryId, categoryName); const [, newModelId] = IModelTestUtils.createAndInsertPhysicalPartitionAndModel(imodel, Code.createEmpty(), true); // create element with auto handled properties const expectedValue = initElemProps("TestElement", imodel, newModelId, spatialCategoryId!, { ...primInst1, ...primArrInst1, st: { ...primArrInst2, ...primInst1 }, array_st: [{ ...primInst1, ...primArrInst2 }, { ...primInst2, ...primArrInst1 }], }) as TestElement; // insert a element const geomElement = imodel.elements.createElement(expectedValue); const id = imodel.elements.insertElement(geomElement.toJSON()); assert.isTrue(Id64.isValidId64(id), "insert worked"); imodel.saveChanges(); // verify inserted element properties const actualValue = imodel.elements.getElementProps<TestElement>(id); verifyTestElement(actualValue, expectedValue); // verify via concurrent query let rowCount = 0; for await (const row of imodel.query("SELECT * FROM ts.TestElement", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { verifyTestElement(row as TestElement, expectedValue); rowCount++; } assert.equal(rowCount, 1); // verify via ecsql statement await imodel.withPreparedStatement("SELECT * FROM ts.TestElement", async (stmt: ECSqlStatement) => { assert.equal(stmt.step(), DbResult.BE_SQLITE_ROW); const stmtRow = stmt.getRow() as TestElement; verifyTestElement(stmtRow, expectedValue); }); // update the element autohandled properties Object.assign(actualValue, { ...primInst2, ...primArrInst2, st: { ...primArrInst1, ...primInst2 }, array_st: [{ ...primInst2, ...primArrInst2 }, { ...primInst1, ...primArrInst1 }], }); // update element imodel.elements.updateElement(actualValue); imodel.saveChanges(); // verify updated values const updatedValue = imodel.elements.getElementProps<TestElement>(id); verifyTestElement(updatedValue, actualValue); // verify via concurrent query rowCount = 0; for await (const row of imodel.query("SELECT * FROM ts.TestElement", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { verifyTestElement(row as TestElement, actualValue); rowCount++; } assert.equal(rowCount, 1); // verify via ecsql statement await imodel.withPreparedStatement("SELECT * FROM ts.TestElement", async (stmt: ECSqlStatement) => { assert.equal(stmt.step(), DbResult.BE_SQLITE_ROW); const stmtRow = stmt.getRow() as TestElement; verifyTestElement(stmtRow, actualValue); }); imodel.close(); }); it("Roundtrip all type of properties via ElementAspectApi, ConcurrentQuery and ECSqlStatement via insert and update", async () => { const testFileName = IModelTestUtils.prepareOutputFile(subDirName, "roundtrip_apsect_correct_data.bim"); const imodel = IModelTestUtils.createSnapshotFromSeed(testFileName, iModelPath); const spatialCategoryId = SpatialCategory.queryCategoryIdByName(imodel, IModel.dictionaryId, categoryName); const [, newModelId] = IModelTestUtils.createAndInsertPhysicalPartitionAndModel(imodel, Code.createEmpty(), true); // create element to use with the ElementAspects const expectedValue = initElemProps("TestElement", imodel, newModelId, spatialCategoryId!, {}) as TestElement; // insert a element const geomElement = imodel.elements.createElement(expectedValue); const elId = imodel.elements.insertElement(geomElement.toJSON()); assert.isTrue(Id64.isValidId64(elId), "insert worked"); const expectedAspectValue = initElementAspectProps("TestElementAspect", imodel, elId, { ...primInst1, ...primArrInst1, st: { ...primArrInst2, ...primInst1 }, array_st: [{ ...primInst1, ...primArrInst2 }, { ...primInst2, ...primArrInst1 }], }) as TestElementAspect; // insert a element aspect imodel.elements.insertAspect(expectedAspectValue); imodel.saveChanges(); // verify inserted element aspect properties const actualAspectValue: ElementAspectProps[] = imodel.elements.getAspects(elId, expectedAspectValue.classFullName).map((x) => x.toJSON()); assert.equal(actualAspectValue.length, 1); verifyTestElementAspect(actualAspectValue[0], expectedAspectValue); // verify via concurrent query let rowCount = 0; for await (const row of imodel.query("SELECT * FROM ts.TestElementAspect", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { verifyTestElementAspect(row as TestElementAspect, expectedAspectValue); rowCount++; } assert.equal(rowCount, 1); // verify via ecsql statement await imodel.withPreparedStatement("SELECT * FROM ts.TestElementAspect", async (stmt: ECSqlStatement) => { assert.equal(stmt.step(), DbResult.BE_SQLITE_ROW); const stmtRow = stmt.getRow() as TestElementAspect; verifyTestElementAspect(stmtRow, expectedAspectValue); }); // update the element autohandled properties Object.assign(actualAspectValue[0], { ...primInst2, ...primArrInst2, st: { ...primArrInst1, ...primInst2 }, array_st: [{ ...primInst2, ...primArrInst2 }, { ...primInst1, ...primArrInst1 }], }); // update element imodel.elements.updateAspect(actualAspectValue[0]); imodel.saveChanges(); // verify updated values const updatedAspectValue: ElementAspectProps[] = imodel.elements.getAspects(elId, expectedAspectValue.classFullName).map((x) => x.toJSON()); assert.equal(updatedAspectValue.length, 1); verifyTestElementAspect(updatedAspectValue[0], actualAspectValue[0]); // verify via concurrent query rowCount = 0; for await (const row of imodel.query("SELECT * FROM ts.TestElementAspect", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { verifyTestElementAspect(row as TestElementAspect, actualAspectValue[0]); rowCount++; } assert.equal(rowCount, 1); // verify via ecsql statement await imodel.withPreparedStatement("SELECT * FROM ts.TestElementAspect", async (stmt: ECSqlStatement) => { assert.equal(stmt.step(), DbResult.BE_SQLITE_ROW); const stmtRow = stmt.getRow() as TestElementAspect; verifyTestElementAspect(stmtRow, actualAspectValue[0]); }); imodel.close(); }); function verifyTestElementRefersToElements(actualValue: TestElementRefersToElements, expectedValue: TestElementRefersToElements) { assert.equal(actualValue.sourceId, expectedValue.sourceId, "'sourceId' type property did not roundtrip as expected"); assert.equal(actualValue.targetId, expectedValue.targetId, "'targetId' type property did not roundtrip as expected"); verifyPrimitiveBase(actualValue, expectedValue); verifyPrimitiveArrayBase(actualValue, expectedValue); } it("Roundtrip all type of properties via ElementRefersToElements, ConcurrentQuery and ECSqlStatement via insert and update", async () => { const testFileName = IModelTestUtils.prepareOutputFile(subDirName, "roundtrip_relationships_correct_data.bim"); const imodel = IModelTestUtils.createSnapshotFromSeed(testFileName, iModelPath); const spatialCategoryId = SpatialCategory.queryCategoryIdByName(imodel, IModel.dictionaryId, categoryName); const [, newModelId] = IModelTestUtils.createAndInsertPhysicalPartitionAndModel(imodel, Code.createEmpty(), true); // create elements to use const element1 = initElemProps("TestElement", imodel, newModelId, spatialCategoryId!, {}) as TestElement; const element2 = initElemProps("TestElement", imodel, newModelId, spatialCategoryId!, {}) as TestElement; const geomElement1 = imodel.elements.createElement(element1); const elId1 = imodel.elements.insertElement(geomElement1.toJSON()); assert.isTrue(Id64.isValidId64(elId1), "insert of element 1 worked"); const geomElement2 = imodel.elements.createElement(element2); const elId2 = imodel.elements.insertElement(geomElement2.toJSON()); assert.isTrue(Id64.isValidId64(elId2), "insert of element 2 worked"); // TODO: Skipping structs here, because of a bug that prevents querying from link tables that have an overflow table, by skipping the struct we reduce the amount of used columns const expectedRelationshipValue = initElementRefersToElementsProps("TestElementRefersToElements", imodel, elId1, elId2, { ...primInst1, ...primArrInst1, /* st: { ...primArrInst2, ...primInst1 }, array_st: [{ ...primInst1, ...primArrInst2 }, { ...primInst2, ...primArrInst1 }], */ }); const instance = expectedRelationshipValue; // imodel.relationships.createInstance(expectedRelationshipValue); const relationshipId: Id64String = imodel.relationships.insertInstance(instance as any); // initElementRefersToElementsProps lies about return type. imodel.saveChanges(); // verify inserted properties const actualRelationshipValue = imodel.relationships.getInstance<TestElementRefersToElements>(expectedRelationshipValue.classFullName, relationshipId); assert.exists(actualRelationshipValue); verifyTestElementRefersToElements(actualRelationshipValue, expectedRelationshipValue); // verify via concurrent query let rowCount = 0; for await (const row of imodel.query("SELECT * FROM ts.TestElementRefersToElements", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { const val = row as TestElementRefersToElements; verifyTestElementRefersToElements(val, expectedRelationshipValue); rowCount++; } assert.equal(rowCount, 1); // verify via ecsql statement614 await imodel.withPreparedStatement("SELECT * FROM ts.TestElementRefersToElements", async (stmt: ECSqlStatement) => { assert.equal(stmt.step(), DbResult.BE_SQLITE_ROW); const stmtRow = stmt.getRow() as TestElementRefersToElements; verifyTestElementRefersToElements(stmtRow, expectedRelationshipValue); }); const updatedExpectedValue = actualRelationshipValue; // update the element autohandled properties Object.assign(updatedExpectedValue, { ...primInst2, ...primArrInst2, /* st: { ...primArrInst1, ...primInst2 }, array_st: [{ ...primInst2, ...primArrInst2 }, { ...primInst1, ...primArrInst1 }],*/ }); // update imodel.relationships.updateInstance(updatedExpectedValue.toJSON()); imodel.saveChanges(); // verify updated values const updatedValue = imodel.relationships.getInstance<TestElementRefersToElements>(expectedRelationshipValue.classFullName, relationshipId); verifyTestElementRefersToElements(updatedValue, updatedExpectedValue); // verify via concurrent query rowCount = 0; for await (const row of imodel.query("SELECT * FROM ts.TestElementRefersToElements", undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })) { verifyTestElementRefersToElements(row as TestElementRefersToElements, updatedExpectedValue); rowCount++; } assert.equal(rowCount, 1); // verify via ecsql statement await imodel.withPreparedStatement("SELECT * FROM ts.TestElementRefersToElements", async (stmt: ECSqlStatement) => { assert.equal(stmt.step(), DbResult.BE_SQLITE_ROW); const stmtRow = stmt.getRow() as TestElementRefersToElements; verifyTestElementRefersToElements(stmtRow, updatedExpectedValue); }); imodel.close(); }); });
the_stack
import { ThemeProvider } from "@material-ui/core/styles" import { cleanup, fireEvent, render, waitForElement } from "@testing-library/react" import axios from "axios" import { createCanvas } from "canvas" import * as child from "child_process" import _ from "lodash" import * as React from "react" import { Provider } from "react-redux" import Session from "../../src/common/session" import { initSessionForTask } from "../../src/common/session_init" import { submissionTimeout } from "../../src/components/create_form" import TitleBar, { saveTimeout } from "../../src/components/title_bar" import { Endpoint } from "../../src/const/connection" import { Label2DHandler } from "../../src/drawable/2d/label2d_handler" import { Label2DList } from "../../src/drawable/2d/label2d_list" import { isStatusSaved } from "../../src/functional/selector" import { getShape } from "../../src/functional/state_util" import { Size2D } from "../../src/math/size2d" import { Vector2D } from "../../src/math/vector2d" import { scalabelTheme } from "../../src/styles/theme" import { IdType, RectType } from "../../src/types/state" import { getTestConfig, getTestConfigPath } from "../server/util/util" import { findNewLabelsFromState } from "../util/state" import { changeTestConfig, countTasks, deepDeleteTimestamp, deleteTestDir, getExport, getExportFromDisc, getProjectJson, getProjectJsonFromDisc, sleep, StyledIntegrationForm, testConfig, waitForSave } from "./util" // TODO: add testing with the actual canvas let launchProc: child.ChildProcessWithoutNullStreams beforeAll(async () => { Session.testMode = true // Port is also changed in test_config launchProc = child.spawn("node", [ "app/dist/main.js", "--config", getTestConfigPath() ]) // LaunchProc.stdout.on('data', (data) => { // process.stdout.write(data) // }) // LaunchProc.stderr.on('data', (data) => { // process.stdout.write(data) // }) window.alert = (): void => {} // Needed as buffer period for server to launch. The amount of time needed // is inconsistent so this is on the convservative side. await sleep(1500) }) beforeEach(() => { cleanup() }) afterEach(cleanup) afterAll(async () => { launchProc.kill() deleteTestDir() // Wait for server to shut down to clear port await sleep(50) }) test("project creation", async () => { const { getByTestId } = render( <ThemeProvider theme={scalabelTheme}> <StyledIntegrationForm /> </ThemeProvider> ) // Change project meta-data const projectNameInput = getByTestId("project-name") as HTMLInputElement fireEvent.change(projectNameInput, { target: { value: testConfig.projectName } }) expect(projectNameInput.value).toBe(testConfig.projectName) const itemSelect = getByTestId("item-type") as HTMLSelectElement fireEvent.change(itemSelect, { target: { value: "image" } }) expect(itemSelect.value).toBe("image") const labelSelect = getByTestId("label-type") as HTMLSelectElement fireEvent.change(labelSelect, { target: { value: "box2d" } }) expect(labelSelect.value).toBe("box2d") const tasksizeInput = getByTestId("tasksize-input") as HTMLInputElement fireEvent.change(tasksizeInput, { target: { value: "5" } }) expect(tasksizeInput.value).toBe("5") // Submit the project const submitButton = getByTestId("submit-button") fireEvent.click(submitButton) await Promise.race([ waitForElement(() => getByTestId("hidden-buttons")), sleep(submissionTimeout) ]) }) test("test project.json was properly created", () => { const projectJson = getProjectJson() const sampleProjectJson = getProjectJsonFromDisc() expect(projectJson).toEqual(sampleProjectJson) }) test( "test 2d-bounding-box annotation and save to disc", async () => { // Spawn a canvas and draw labels on this canvas // Uses similar code to drawable tests initSessionForTask( testConfig.taskIndex, testConfig.projectName, "fakeId", "", false ) const labelIds: IdType[] = [] const { getByTestId } = render( <ThemeProvider theme={scalabelTheme}> <Provider store={Session.store}> <TitleBar /> </Provider> </ThemeProvider> ) const saveButton = getByTestId("Save") const labelCanvas = createCanvas(200, 200) const labelContext = labelCanvas.getContext("2d") const controlCanvas = createCanvas(200, 200) const controlContext = controlCanvas.getContext("2d") const handleIndex = 0 const _labelIndex = -2 let state = Session.getState() const itemIndex = state.user.select.item const label2dList = new Label2DList() const label2dHandler = new Label2DHandler(Session.label2dList) Session.subscribe(() => { const newState = Session.getState() Session.label2dList.updateState(newState) label2dHandler.updateState(newState) }) const canvasSize = new Size2D(100, 100) label2dHandler.onMouseMove( new Vector2D(1, 1), canvasSize, _labelIndex, handleIndex ) label2dHandler.onMouseDown(new Vector2D(1, 1), _labelIndex, handleIndex) for (let i = 1; i <= 10; i += 1) { label2dHandler.onMouseMove( new Vector2D(i, i), canvasSize, _labelIndex, handleIndex ) label2dList.redraw(labelContext, controlContext, 1) } label2dHandler.onMouseUp(new Vector2D(10, 10), _labelIndex, handleIndex) label2dList.redraw(labelContext, controlContext, 1) labelIds.push(findNewLabelsFromState(Session.getState(), 0, labelIds)[0]) state = Session.getState() expect(_.size(state.task.items[itemIndex].labels)).toEqual(1) let rect = getShape(state, itemIndex, labelIds[0], 0) as RectType expect(rect.x1).toEqual(1) expect(rect.y1).toEqual(1) expect(rect.x2).toEqual(10) expect(rect.y2).toEqual(10) label2dHandler.onMouseMove( new Vector2D(20, 20), canvasSize, _labelIndex, handleIndex ) label2dHandler.onMouseDown(new Vector2D(20, 20), _labelIndex, handleIndex) for (let i = 20; i <= 40; i += 1) { label2dHandler.onMouseMove( new Vector2D(i, i), canvasSize, _labelIndex, handleIndex ) label2dList.redraw(labelContext, controlContext, 1) } label2dHandler.onMouseUp(new Vector2D(40, 40), _labelIndex, handleIndex) label2dList.redraw(labelContext, controlContext, 1) state = Session.getState() expect(_.size(state.task.items[itemIndex].labels)).toEqual(2) labelIds.push(findNewLabelsFromState(Session.getState(), 0, labelIds)[0]) rect = getShape(state, itemIndex, labelIds[1], 0) as RectType expect(rect.x1).toEqual(20) expect(rect.y1).toEqual(20) expect(rect.x2).toEqual(40) expect(rect.y2).toEqual(40) // Save to disc fireEvent.click(saveButton) await Promise.race([sleep(saveTimeout), waitForSave()]) expect(isStatusSaved(Session.store.getState())).toBe(true) }, saveTimeout ) test("test export of saved bounding boxes", async () => { const exportJson = await getExport() const trueExportJson = getExportFromDisc() const noTimestampExportJson = deepDeleteTimestamp(exportJson) const noTimestampTrueExportJson = deepDeleteTimestamp(trueExportJson) expect(noTimestampExportJson).toEqual(noTimestampTrueExportJson) changeTestConfig({ exportMode: true }) }) test("import exported json from saved bounding boxes", async () => { const { getByTestId } = render( <ThemeProvider theme={scalabelTheme}> <StyledIntegrationForm /> </ThemeProvider> ) // Change project meta-data const projectNameInput = getByTestId("project-name") as HTMLInputElement fireEvent.change(projectNameInput, { target: { value: testConfig.projectName + "_exported" } }) expect(projectNameInput.value).toBe(testConfig.projectName + "_exported") const itemSelect = getByTestId("item-type") as HTMLSelectElement fireEvent.change(itemSelect, { target: { value: "image" } }) expect(itemSelect.value).toBe("image") const labelSelect = getByTestId("label-type") as HTMLSelectElement fireEvent.change(labelSelect, { target: { value: "box2d" } }) expect(labelSelect.value).toBe("box2d") const tasksizeInput = getByTestId("tasksize-input") as HTMLInputElement fireEvent.change(tasksizeInput, { target: { value: "5" } }) expect(tasksizeInput.value).toBe("5") // Submit the project const submitButton = getByTestId("submit-button") fireEvent.click(submitButton) await Promise.race([ waitForElement(() => getByTestId("hidden-buttons")), sleep(submissionTimeout) ]) }) describe("2d bounding box integration test with programmatic api", () => { const axiosConfig = { headers: { "Content-Type": "application/json" } } const serverConfig = getTestConfig() const response400 = "Request failed with status code 400" test("Itemless project creation", async () => { // Make task size big enough to fit all the items in 1 task const projectName = "itemless-project" const createProjectBody = { fields: { project_name: projectName, item_type: "image", label_type: "box2d", task_size: 400 }, files: {} } const address = new URL("http://localhost") address.port = serverConfig.http.port.toString() address.pathname = Endpoint.POST_PROJECT_INTERNAL const response = await axios.post( address.toString(), createProjectBody, axiosConfig ) expect(response.status).toBe(200) expect(await countTasks(projectName)).toBe(0) // Trying to create a project with the same name fails await expect( axios.post(address.toString(), createProjectBody, axiosConfig) ).rejects.toThrow(response400) // Add items to the empty project; expect 1 task to be made address.pathname = Endpoint.POST_TASKS const addTasksBody = { projectName, items: "examples/image_list.yml" } await axios.post(address.toString(), addTasksBody, axiosConfig) expect(await countTasks(projectName)).toBe(1) /* Add items again, check that a new task is made * even though the items COULD all fit in one task */ await axios.post(address.toString(), addTasksBody, axiosConfig) expect(await countTasks(projectName)).toBe(2) }) })
the_stack
import { decimalStr, mweiStr, fromWei } from '../utils/Converter'; import { logGas } from '../utils/Log'; import { NFTContext, getDODONftContext } from '../utils/NFTContext'; import { assert } from 'chai'; import * as contracts from '../utils/Contracts'; const truffleAssert = require('truffle-assertions'); let author: string; let user1: string; let user2: string; let buyer: string; async function init(ctx: NFTContext): Promise<void> { author = ctx.SpareAccounts[1]; user1 = ctx.SpareAccounts[2]; user2 = ctx.SpareAccounts[3]; buyer = ctx.SpareAccounts[4]; await ctx.mintTestToken(user1, ctx.USDT, mweiStr("10000")); await ctx.mintTestToken(user2, ctx.USDT, mweiStr("10000")); await ctx.mintTestToken(buyer, ctx.USDT, mweiStr("1000000000")); await ctx.approveProxy(ctx.USDT, user1); await ctx.approveProxy(ctx.USDT, user2); await ctx.approveProxy(ctx.USDT, buyer); } // async function getFeeGlobalState(ctx: NFTContext, feeAddress: string, baseToken, quoteToken, stakeToken) { // let feeInstance = contracts.getContractWithAddress(contracts.NFT_FEE, feeAddress); // let baseReserve = await feeInstance.methods._BASE_RESERVE_().call(); // let quoteReserve = await feeInstance.methods._QUOTE_RESERVE_().call(); // let baseBalance = await baseToken.methods.balanceOf(feeAddress).call(); // let quoteBalance = await quoteToken.methods.balanceOf(feeAddress).call(); // let stakeVault = await feeInstance.methods._STAKE_VAULT_().call(); // let stakeBalance = await stakeToken.methods.balanceOf(stakeVault).call(); // let stakeReserve = await feeInstance.methods._STAKE_RESERVE_().call(); // let baseRatio = await feeInstance.methods._BASE_REWARD_RATIO_().call(); // let quoteRatio = await feeInstance.methods._QUOTE_REWARD_RATIO_().call(); // console.log("fee baseBalance:" + fromWei(baseBalance, 'ether') + " quoteBalance:" + fromWei(quoteBalance, 'mwei') + " vault stakeBalance:" + fromWei(stakeBalance, 'ether')); // console.log("fee baseReserve:" + fromWei(baseReserve, 'ether') + " quoteReserve:" + fromWei(quoteReserve, 'mwei') + " stakeReserve:" + fromWei(stakeReserve, 'ether')); // console.log("baseRatio:" + fromWei(baseRatio, 'ether') + " quoteRatio:" + fromWei(quoteRatio, 'mwei')); // return { // "baseReserve": baseReserve, // "quoteReserve": quoteReserve, // "stakeReserve": stakeReserve, // "baseBalance": baseBalance, // "quoteBalance": quoteBalance, // "stakeBalance": stakeBalance, // "baseRatio": baseRatio, // "quoteRatio": quoteRatio // } // } // async function getFeeUserState(ctx: NFTContext, feeAddress: string, userAddress: string) { // let feeInstance = contracts.getContractWithAddress(contracts.NFT_FEE, feeAddress); // let userShares = await feeInstance.methods._SHARES_(userAddress).call(); // let [baseRewards, quoteRewards] = await feeInstance.methods.getPendingReward(userAddress).call(); // let userBasePerShares = await feeInstance.methods._USER_BASE_PER_SHARE_(userAddress).call(); // let userQuotePerShares = await feeInstance.methods._USER_QUOTE_PER_SHARE_(userAddress).call(); // console.log("user shares:" + fromWei(userShares, 'ether')); // console.log("user baseRewards:" + fromWei(baseRewards, 'ether') + " userQuoteRewards:" + fromWei(quoteRewards, 'mwei')); // console.log("user basePerShares:" + fromWei(userBasePerShares, 'ether') + " userQuotePerShares:" + fromWei(userQuotePerShares, 'mwei')); // return { // "userShares": userShares, // "userBaseRewards": baseRewards, // "userQuoteRewards": quoteRewards, // "userBasePerShares": userBasePerShares, // "userQuotePerShares": userQuotePerShares // } // } async function mockTrade(ctx: NFTContext, dvmAddress: string, dvmInstance, fragInstance) { await ctx.transferQuoteToDVM(ctx.USDT, dvmAddress, user1, mweiStr("20")); await dvmInstance.methods.sellQuote(user1).send(ctx.sendParam(user1)); await ctx.transferBaseToDVM(fragInstance, dvmAddress, user1, decimalStr("10")); await dvmInstance.methods.sellBase(user1).send(ctx.sendParam(user1)); await ctx.transferQuoteToDVM(ctx.USDT, dvmAddress, user2, mweiStr("80")); await dvmInstance.methods.sellQuote(user2).send(ctx.sendParam(user2)); await ctx.transferBaseToDVM(fragInstance, dvmAddress, user2, decimalStr("20")); await dvmInstance.methods.sellBase(user2).send(ctx.sendParam(user2)); } async function getUserBalance(user: string, baseToken, quoteToken, logInfo: string) { var baseBalance = await baseToken.methods.balanceOf(user).call(); var quoteBalance = await quoteToken.methods.balanceOf(user).call(); console.log(logInfo + " baseBalance:" + fromWei(baseBalance, 'ether') + " quoteBalance:" + fromWei(quoteBalance, 'mwei')); return [baseBalance, quoteBalance]; } describe("DODONFT", () => { let snapshotId: string; let ctx: NFTContext; before(async () => { let ETH = await contracts.newContract( contracts.WETH_CONTRACT_NAME ); ctx = await getDODONftContext(ETH.options.address); await init(ctx); }); beforeEach(async () => { snapshotId = await ctx.EVM.snapshot(); }); afterEach(async () => { await ctx.EVM.reset(snapshotId); }); describe("DODONFTMainFlow", () => { it("createNFTVault", async () => { await logGas(await ctx.NFTProxy.methods.createNFTCollateralVault( "DODOVault", "https://app.dodoex.io" ), ctx.sendParam(author), "createNFTVault"); }); it("createTokenAndTransferToVault", async () => { var erc721Address = await ctx.createERC721(ctx, author); var vaultAddress = await ctx.createNFTVault(ctx, author); var nftVaultInstance = contracts.getContractWithAddress(contracts.NFT_VAULT, vaultAddress); var erc721Instance = contracts.getContractWithAddress(contracts.ERC721, erc721Address); await erc721Instance.methods.safeTransferFrom(author, vaultAddress, 0).send(ctx.sendParam(author)); // var nftIndex = await nftVaultInstance.methods.getIdByTokenIdAndAddr(erc721Address, 0).call(); // var nftInfo = await nftVaultInstance.methods.getNftInfoById(nftIndex).call(); // assert(nftInfo.amount, '1') // assert(nftInfo.tokenId, '0') }); it("createFragment", async () => { var erc721Address = await ctx.createERC721(ctx, author); var vaultAddress = await ctx.createNFTVault(ctx, author); var nftVaultInstance = contracts.getContractWithAddress(contracts.NFT_VAULT, vaultAddress); var erc721Instance = contracts.getContractWithAddress(contracts.ERC721, erc721Address); await erc721Instance.methods.safeTransferFrom(author, vaultAddress, 0).send(ctx.sendParam(author)); // var quoteToken = "0x156595bAF85D5C29E91d959889B022d952190A64"; // var vaultPreOwner = "0x7e83d9d94837eE82F0cc18a691da6f42F03F1d86"; var quoteToken = ctx.USDT.options.address; var vaultPreOwner = author; var symbol = "HAHA" var params = [ "0", //lpFeeRate mweiStr("1"), // I decimalStr("1"), // K decimalStr("100000000"), //totalSupply decimalStr("0.2"), //ownerRatio Math.floor(new Date().getTime() / 1000 + 60 * 60), //buyoutTimeStamp 1h later decimalStr("0") ] var isOpenTwap = false var callData = ctx.NFTProxy.methods.createFragment( [quoteToken,vaultPreOwner], params, isOpenTwap, symbol ).encodeABI(); console.log("data:", callData); await logGas(await nftVaultInstance.methods.createFragment( ctx.NFTProxy.options.address, callData ), ctx.sendParam(author), "createFragment"); let [fragAddress, , dvmAddress] = await ctx.getRegistry(ctx, vaultAddress); var dvmInstance = contracts.getContractWithAddress(contracts.DVM_NAME, dvmAddress); var midPrice = await dvmInstance.methods.getMidPrice().call(); assert(midPrice, mweiStr("1")); let newVaultOwner = await nftVaultInstance.methods._OWNER_().call(); assert(fragAddress, newVaultOwner); }); // it("stakeToFeeDistributor", async () => { // let [vaultAddress, fragAddress, feeAddress, dvmAddress] = await ctx.createFragment(ctx, author, null, null, null); // var nftFeeInstance = contracts.getContractWithAddress(contracts.NFT_FEE, feeAddress); // var dvmInstance = contracts.getContractWithAddress(contracts.DVM_NAME, dvmAddress); // var fragInstance = contracts.getContractWithAddress(contracts.NFT_FRAG, fragAddress); // await ctx.approveProxy(fragInstance, user1); // await ctx.approveProxy(fragInstance, user2); // //mock trading // //stake // await mockTrade(ctx, dvmAddress, dvmInstance, fragInstance); // await logGas(await ctx.NFTProxy.methods.stakeToFeeDistributor( // feeAddress, // decimalStr("5"), // 0 // ), ctx.sendParam(user1), "stakeToFeeDistributor"); // await logGas(await ctx.NFTProxy.methods.stakeToFeeDistributor( // feeAddress, // decimalStr("10"), // 0 // ), ctx.sendParam(user2), "stakeToFeeDistributor"); // await mockTrade(ctx, dvmAddress, dvmInstance, fragInstance); // await logGas(await ctx.NFTProxy.methods.stakeToFeeDistributor( // feeAddress, // decimalStr("10"), // 0 // ), ctx.sendParam(user1), "stakeToFeeDistributor"); // await logGas(await ctx.NFTProxy.methods.stakeToFeeDistributor( // feeAddress, // decimalStr("20"), // 0 // ), ctx.sendParam(user2), "stakeToFeeDistributor"); // let globalObj = await getFeeGlobalState(ctx, feeAddress, fragInstance, ctx.USDT, fragInstance); // assert(globalObj['quoteBalance'], mweiStr("0.6")); // assert(globalObj['stakeReserve'], decimalStr("45")); // let user1Obj = await getFeeUserState(ctx, feeAddress, user1); // assert(user1Obj['userQuoteRewards'], mweiStr("0.1")); // assert(user1Obj['userShares'], decimalStr("15")); // let user2Obj = await getFeeUserState(ctx, feeAddress, user2); // assert(user2Obj['userBaseRewards'], decimalStr("0.66666480000453957")); // assert(user2Obj['userShares'], decimalStr("30")); // //claim // var user1BaseBalanceStart = await fragInstance.methods.balanceOf(user1).call() // await logGas(await nftFeeInstance.methods.claim(user1), ctx.sendParam(user1), "claim"); // var user1BaseBalanceEnd = await fragInstance.methods.balanceOf(user1).call() // user1Obj = await getFeeUserState(ctx, feeAddress, user1); // await getFeeGlobalState(ctx, feeAddress, fragInstance, ctx.USDT, fragInstance); // assert(user1Obj['userQuoteRewards'], "0"); // assert(globalObj['quoteBalance'], mweiStr("0.5")); // assert(user1BaseBalanceEnd - user1BaseBalanceStart, "333332400002269700"); // //unstake // var user2BaseBalanceStart = await fragInstance.methods.balanceOf(user2).call() // await logGas(await nftFeeInstance.methods.unstake(decimalStr("30"), user2, true), ctx.sendParam(user2), "unstake"); // var user2BaseBalanceEnd = await fragInstance.methods.balanceOf(user2).call() // user2Obj = await getFeeUserState(ctx, feeAddress, user2); // await getFeeGlobalState(ctx, feeAddress, fragInstance, ctx.USDT, fragInstance); // assert(user2Obj['userQuoteRewards'], "0"); // assert(globalObj['quoteBalance'], mweiStr("0.3")); // assert(globalObj['stakeReserve'], mweiStr("15")); // assert(globalObj['stakeBalance'], mweiStr("15")); // assert(user2BaseBalanceEnd - user2BaseBalanceStart, "30666664800004540000"); // }); it("buyout and redeem", async () => { var fragParams = [ decimalStr("10000"), //totalSupply decimalStr("0.2"), //ownerRatio Math.floor(new Date().getTime() / 1000), //buyoutTimeStamp decimalStr("0") ] let [vaultAddress, fragAddress, , dvmAddress] = await ctx.createFragment(ctx, author, null, fragParams, null); var dvmInstance = contracts.getContractWithAddress(contracts.DVM_NAME, dvmAddress); var fragInstance = contracts.getContractWithAddress(contracts.NFT_FRAG, fragAddress); var vaultInstance = contracts.getContractWithAddress(contracts.NFT_VAULT, vaultAddress); await mockTrade(ctx, dvmAddress, dvmInstance, fragInstance); await fragInstance.methods.transfer(buyer, decimalStr("1002")).send(ctx.sendParam(author)); await getUserBalance(author, fragInstance, ctx.USDT, "Author Before"); await getUserBalance(buyer, fragInstance, ctx.USDT, "Buyer Before"); await getUserBalance(dvmAddress, fragInstance, ctx.USDT, "DVM Before"); await getUserBalance(fragAddress, fragInstance, ctx.USDT, "FRAG Before"); var requireQuote = await fragInstance.methods.getBuyoutRequirement().call(); await logGas(await ctx.NFTProxy.methods.buyout(fragAddress, requireQuote, 0, Math.floor(new Date().getTime() / 1000 + 60 * 10)), ctx.sendParam(buyer), "buyout"); let [authorFrag, authorQuote] = await getUserBalance(author, fragInstance, ctx.USDT, "Author After"); await getUserBalance(buyer, fragInstance, ctx.USDT, "Buyer After"); await getUserBalance(dvmAddress, fragInstance, ctx.USDT, "DVM After"); await getUserBalance(fragAddress, fragInstance, ctx.USDT, "FRAG After"); // assert(authorQuote, "2034932000"); assert(authorQuote, "10174055148"); assert(authorFrag, "0"); var vaultNewOwner = await vaultInstance.methods._OWNER_().call(); assert(vaultNewOwner, buyer); await getUserBalance(user1, fragInstance, ctx.USDT, "User1 Redeem Before"); await getUserBalance(user2, fragInstance, ctx.USDT, "User2 Redeem Before"); await logGas(await fragInstance.methods.redeem(user1, "0x"), ctx.sendParam(user1), "redeem"); await logGas(await fragInstance.methods.redeem(user2, "0x"), ctx.sendParam(user2), "redeem"); let [user1Frag, user1Quote] = await getUserBalance(user1, fragInstance, ctx.USDT, "User1 Redeem After"); await getUserBalance(user2, fragInstance, ctx.USDT, "User2 Redeem After"); await getUserBalance(fragAddress, fragInstance, ctx.USDT, "FRAG Redeem After"); assert(user1Quote, "99998580370") assert(user1Frag, "0") }); it("withdrawNFTFromVault", async () => { var erc721Address = await ctx.createERC721(ctx, author); var erc1155Address = await ctx.createERC1155(ctx, author,100); var vaultAddress = await ctx.createNFTVault(ctx, author); var nftVaultInstance = contracts.getContractWithAddress(contracts.NFT_VAULT, vaultAddress); var erc721Instance = contracts.getContractWithAddress(contracts.ERC721, erc721Address); var erc1155Instance = contracts.getContractWithAddress(contracts.ERC1155, erc1155Address); await erc721Instance.methods.safeTransferFrom(author, vaultAddress, 0).send(ctx.sendParam(author)); await erc1155Instance.methods.safeTransferFrom(author, vaultAddress, 0, 100, "0x").send(ctx.sendParam(author)); // var nftIndex = await nftVaultInstance.methods.getIdByTokenIdAndAddr(erc721Address, 0).call(); // var nftInfo = await nftVaultInstance.methods.getNftInfoById(nftIndex).call(); // assert(nftInfo.amount, '1') // assert(nftInfo.tokenId, '0') // nftIndex = await nftVaultInstance.methods.getIdByTokenIdAndAddr(erc1155Address, 0).call(); // nftInfo = await nftVaultInstance.methods.getNftInfoById(nftIndex).call(); // assert(nftInfo.amount, '100') // assert(nftInfo.tokenId, '0') await logGas(await nftVaultInstance.methods.withdrawERC721(erc721Address,[0]), ctx.sendParam(author), "withdrawERC721"); await logGas(await nftVaultInstance.methods.withdrawERC1155(erc1155Address,[0], [50]), ctx.sendParam(author), "withdrawERC1155"); // await truffleAssert.reverts( // nftVaultInstance.methods.getIdByTokenIdAndAddr(erc721Address, 0).call(), // "TOKEN_ID_NOT_FOUND" // ) // nftIndex = await nftVaultInstance.methods.getIdByTokenIdAndAddr(erc1155Address, 0).call(); // nftInfo = await nftVaultInstance.methods.getNftInfoById(nftIndex).call(); // assert(nftInfo.amount, '50') // assert(nftInfo.tokenId, '0') }); }); });
the_stack
import { EventEmitter } from 'events' import { engine, GLTFShape, Transform, Entity, Component, NFTShape, IEntity, Vector3, AvatarShape, Wearable } from 'decentraland-ecs' import * as ECS from 'decentraland-ecs' import { createChannel } from 'decentraland-builder-scripts/channel' import { createInventory } from 'decentraland-builder-scripts/inventory' import { DecentralandInterface } from 'decentraland-ecs/dist/decentraland/Types' import { EntityDefinition, AnyComponent, ComponentData, ComponentType, Scene } from 'modules/scene/types' import { toLegacyURN } from 'lib/urnLegacy' import { AssetParameterValues } from 'modules/asset/types' import { BODY_SHAPE_CATEGORY, WearableBodyShape } from 'modules/item/types' import { getEyeColors, getHairColors, getSkinColors } from 'modules/editor/avatar' const { Gizmos, SmartItem } = require('decentraland-ecs') as any declare var dcl: DecentralandInterface const inventory = createInventory(ECS.UICanvas, ECS.UIContainerStack, ECS.UIImage) class MockMessageBus { static emitter = new EventEmitter() on(message: string, callback: (value: any, sender: string) => void) { MockMessageBus.emitter.on(message, callback) } emit(message: string, payload: Record<any, any>) { MockMessageBus.emitter.emit(message, payload) } } MockMessageBus.emitter.setMaxListeners(1000) // BEGIN DRAGONS declare var provide: (name: string, value: any) => void declare var load: (id: string) => Promise<any> eval(require('raw-loader!./amd-loader.js.raw')) eval(`self.provide = function(name, value) { self[name] = value }`) eval(`self.load = function(id) { return new Promise(resolve => define('load', [id + '/item'], item => resolve(item.default))) }`) Object.keys(ECS).forEach(key => provide(key, (ECS as any)[key])) provide('MessageBus', MockMessageBus) // END DRAGONS let scriptBaseUrl: string | null = null const scriptPromises = new Map<string, Promise<string>>() const scriptInstances = new Map<string, IScript<any>>() /* After the migration of the assets table to use UUIDs and remove duplicates, we recreated all the assets' ids, and the legacy one was stored as a new property. This property is needed to load the AMD modules, since they have been namespaced with the old asset id, and has been uploaded to S3 (so the DB migration did not update them). */ const legacyIds = new Map<string, string>() @Component('org.decentraland.staticEntity') // @ts-ignore export class StaticEntity {} @Component('org.decentraland.script') // @ts-ignore export class Script { constructor(public assetId: string, public src: string, public values: AssetParameterValues) {} } const editorComponents: Record<string, any> = {} const staticEntity = new StaticEntity() const gizmo = new Gizmos() gizmo.position = true gizmo.rotation = true gizmo.scale = true gizmo.cycle = false const smartItemComponent = new SmartItem() function getComponentById(id: string) { if (id in editorComponents) { return editorComponents[id] } return null } function getScriptInstance(assetId: string) { const instance = scriptInstances.get(assetId) return instance ? Promise.resolve(instance) : scriptPromises .get(assetId)! .then(code => eval(code)) .then( // if this asset has a legacy id, use that one instead to load the AMD module () => load(legacyIds.get(assetId) || assetId) ) .then(Item => { const instance = new Item() scriptInstances.set(assetId, instance) return instance }) .catch(error => { console.error(error.message) // if something fails, return a dummy script console.warn(`Failed to load script for asset id ${assetId}`) return { init() {}, spawn() {} } }) } // avatar let avatar: Entity | null = null function getAvatar(): Entity { if (!avatar) { // create avatar avatar = new Entity() avatar.addComponent(new Transform({ position: new Vector3(8, 0, 8), scale: new Vector3(1, 1, 1) })) const avatarShape = new AvatarShape() // @TODO: Remove toLegacyURN when unity accepts urn avatarShape.bodyShape = toLegacyURN(WearableBodyShape.MALE.toString()) avatarShape.skinColor = getSkinColors()[0] avatarShape.hairColor = getHairColors()[0] avatarShape.eyeColor = getEyeColors()[0] avatarShape.name = 'Builder Avatar' avatarShape.wearables = [] avatar.addComponent(avatarShape) } return avatar } async function handleExternalAction(message: { type: string; payload: Record<string, any> }) { switch (message.type) { case 'Set script url': { const { url } = message.payload scriptBaseUrl = url break } case 'Update editor': { const { scene } = message.payload const { components, entities } = scene for (let id in components) { createComponent(components[id], scene) updateComponent(components[id]) } createEntities(entities) removeUnusedEntities(entities) removeUnusedComponents(components) break } case 'Toggle preview': { if (message.payload.isEnabled) { // init scripts const scriptGroup = engine.getComponentGroup(Script) const assetIds = scriptGroup.entities.reduce((ids, entity) => { const script = entity.getComponent(Script) return ids.add(script.assetId) }, new Set<string>()) const scripts = await Promise.all(Array.from(assetIds).map(getScriptInstance)) scripts.forEach(script => script.init({ inventory })) for (const entityId in engine.entities) { const entity = engine.entities[entityId] // remove gizmos if (entity.hasComponent(gizmo)) { entity.removeComponent(gizmo) } // if entity has script... if (scriptGroup.hasEntity(entity)) { // ...remove the placeholder entity.removeComponent(GLTFShape) // ...create the host entity const transform = entity.getComponent(Transform) const hostTransform = new Transform() hostTransform.position.copyFrom(transform.position) hostTransform.rotation.copyFrom(transform.rotation) hostTransform.scale.copyFrom(transform.scale) const name = (entity as any).name // TODO fix this on the kernel's side const placeholder = Object.values(engine.entities).find(entity => (entity as Entity).name === name) if (placeholder) { engine.removeEntity(placeholder) } const host = new Entity(name) engine.addEntity(host) host.addComponent(hostTransform) // ...and execute the script on the host entity const { assetId, values } = entity.getComponent(Script) const script = scriptInstances.get(assetId)! const channel = createChannel('channel-id', host as any, new MockMessageBus()) script.spawn(host, values, channel) } } } else { for (const entityId in engine.entities) { const entity = engine.entities[entityId] const staticEntities = engine.getComponentGroup(StaticEntity) if (!staticEntities.hasEntity(entity)) { entity.addComponentOrReplace(gizmo) } } } break } case 'Close editor': { for (const componentId in editorComponents) { removeComponent(componentId) } for (const entityId in engine.entities) { engine.removeEntity(engine.entities[entityId]) } break } case 'Update avatar': { const wearables: Wearable[] = message.payload.wearables const avatar = getAvatar() const avatarShape = avatar.getComponent(AvatarShape) const bodyShape = wearables.find(wearable => wearable.category === BODY_SHAPE_CATEGORY) const otherWearables = wearables.filter(wearable => wearable.category !== BODY_SHAPE_CATEGORY) avatarShape.bodyShape = bodyShape ? bodyShape.id : WearableBodyShape.MALE avatarShape.wearables = otherWearables.map(wearable => wearable.id) avatarShape.expressionTriggerId = message.payload.animation === 'idle' ? 'Idle' : message.payload.animation // the 'idle' animation is the only one that is capitalized :shrug: avatarShape.expressionTriggerTimestamp = Date.now() avatarShape.hairColor = message.payload.hairColor avatarShape.eyeColor = message.payload.eyeColor avatarShape.skinColor = message.payload.skinColor if (!avatar.isAddedToEngine()) { engine.addEntity(avatar) } break } } } function createComponent(component: AnyComponent, scene: Scene) { const { id, type, data } = component if (!getComponentById(id)) { switch (type) { case ComponentType.GLTFShape: { const { assetId } = data as ComponentData[ComponentType.GLTFShape] const asset = scene.assets[assetId] const url = `${assetId}/${asset.model}` editorComponents[id] = new GLTFShape(url) editorComponents[id].isPickable = true break } case ComponentType.Transform: editorComponents[id] = new Transform() break case ComponentType.NFTShape: editorComponents[id] = new NFTShape((data as ComponentData[ComponentType.NFTShape]).url) editorComponents[id].isPickable = true break case ComponentType.Script: { const { assetId, values } = data as ComponentData[ComponentType.Script] const asset = scene.assets[assetId] const src = asset.contents[asset.script!] editorComponents[id] = new Script(assetId, src, values) if (!scriptPromises.has(assetId)) { const url = scriptBaseUrl + src const promise = fetch(url).then(resp => resp.text()) scriptPromises.set(assetId, promise) // store the legacy id so we can retrieve it when loading the AMD module if (asset.legacyId) { legacyIds.set(assetId, asset.legacyId) } } break } } } } function updateComponent(component: AnyComponent) { const { id, type, data } = component if (type === ComponentType.Transform) { const transform = editorComponents[id] as Transform const transformData = data as ComponentData[ComponentType.Transform] transform.position.copyFrom(transformData.position) transform.rotation.set(transformData.rotation.x, transformData.rotation.y, transformData.rotation.z, transformData.rotation.w) transform.scale.copyFrom(transformData.scale) transform.data['nonce'] = Math.random() transform.dirty = true } else if (type === ComponentType.Script) { const script = editorComponents[id] as Script const scriptData = data as ComponentData[ComponentType.Script] script.values = { ...scriptData.values } } } function createEntities(entities: Record<string, EntityDefinition>) { for (let id in entities) { const builderEntity = entities[id] let entity: IEntity = engine.entities[id] if (!entity) { entity = new Entity(builderEntity.name) ;(entity as any).uuid = id if (!builderEntity.disableGizmos) { entity.addComponentOrReplace(gizmo) } else { entity.addComponentOrReplace(staticEntity) } engine.addEntity(entity) } for (let componentId of builderEntity.components) { const component = getComponentById(componentId) if (component) { entity.addComponentOrReplace(component) if (component instanceof Script) { entity.addComponentOrReplace(smartItemComponent) } } } } } function removeUnusedComponents(components: Record<string, AnyComponent>) { for (const componentId in editorComponents) { const inScene = componentId in components if (!inScene) { removeComponent(componentId) } } } function removeComponent(componentId: string) { const originalComponent = editorComponents[componentId] if (!originalComponent) return try { engine.disposeComponent(originalComponent) } catch (e) { // stub, non-disposable components fall here } for (const entityId in engine.entities) { const entity = engine.entities[entityId] if (entity.hasComponent(originalComponent)) { entity.removeComponent(originalComponent) } } delete editorComponents[componentId] } function removeUnusedEntities(entities: Record<string, EntityDefinition>) { for (const entityId in engine.entities) { const inScene = entityId in entities if (!inScene) { engine.removeEntity(engine.entities[entityId]) } } } function subscribeToExternalActions() { dcl.subscribe('externalAction') dcl.onEvent(e => { if ((e.type as any) === 'externalAction') { handleExternalAction(e.data as any) } }) } subscribeToExternalActions()
the_stack
import { ScenarioService } from './../shared/services/scenario/scenario.service'; import { BroadcastService } from './../shared/services/broadcast.service'; import { Component, OnDestroy, Input, Inject, ElementRef, Output, EventEmitter, ViewChild, ViewContainerRef, ComponentFactory, ComponentFactoryResolver, ComponentRef, } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { FunctionInfo } from '../shared/models/function-info'; import { UserService } from '../shared/services/user.service'; import { UtilitiesService } from '../shared/services/utilities.service'; import { AccessibilityHelper } from '../shared/Utilities/accessibility-helper'; import { FunctionAppContextComponent } from 'app/shared/components/function-app-context-component'; import { FunctionAppService } from 'app/shared/services/function-app.service'; import { Subject } from 'rxjs/Subject'; import { LogContentComponent } from './log-content.component'; import { Regex, LogLevel, ScenarioIds } from '../shared/models/constants'; import { PortalResources } from '../shared/models/portal-resources'; import { FunctionService } from 'app/shared/services/function.service'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'log-streaming', templateUrl: './log-streaming.component.html', styleUrls: ['./log-streaming.component.scss', '../function-dev/function-dev.component.scss'], }) export class LogStreamingComponent extends FunctionAppContextComponent implements OnDestroy { public log: string; public stopped: boolean; public timerInterval = 1000; public isExpanded = false; public popOverTimeout = 500; public logStreamingEnabled = false; private _isConnectionSuccessful = true; private _xhReq: XMLHttpRequest; private _timeouts: number[]; private _oldLength = 0; private _token: string; private _tokenSubscription: Subscription; private _functionInfo: FunctionInfo; private _pollingActive$: Subject<number>; private _logContentComponent: ComponentFactory<any>; private _logStreamIndex = 0; private _logComponents: ComponentRef<any>[] = []; private _functionName: string; @Input() isHttpLogs: boolean; @Output() closeClicked = new EventEmitter<any>(); @Output() expandClicked = new EventEmitter<boolean>(); @ViewChild('logs', { read: ViewContainerRef }) private _logElement: ViewContainerRef; constructor( broadcastService: BroadcastService, functionService: FunctionService, @Inject(ElementRef) private _elementRef: ElementRef, private _userService: UserService, private _functionAppService: FunctionAppService, private _utilities: UtilitiesService, private _componentFactoryResolver: ComponentFactoryResolver, private _ts: TranslateService, private _scenarioService: ScenarioService ) { super('log-streaming', _functionAppService, broadcastService, functionService); this._tokenSubscription = this._userService.getStartupInfo().subscribe(s => (this._token = s.token)); this.log = ''; this._timeouts = []; } setup(): Subscription { return this.viewInfoEvents.subscribe(view => { this.logStreamingEnabled = this._scenarioService.checkScenario(ScenarioIds.enableFunctionLogStreaming, { site: this.context.site }).status !== 'disabled'; this._functionInfo = view.functionInfo.isSuccessful && view.functionInfo.result.properties; this._functionName = (this._functionInfo && this._functionInfo.name) || ''; // clear logs on navigation to a new viewInfo this.log = ''; this._logContentComponent = this._componentFactoryResolver.resolveComponentFactory(LogContentComponent); this._initLogs(this.isHttpLogs); this.startLogs(); }); } ngOnDestroy() { if (this._xhReq) { this._timeouts.forEach(window.clearTimeout); this._timeouts = []; this._xhReq.abort(); } if (this._tokenSubscription) { this._tokenSubscription.unsubscribe(); delete this._tokenSubscription; } if (this._pollingActive$) { this._pollingActive$.next(); this._pollingActive$.complete(); this._pollingActive$ = null; } super.ngOnDestroy(); } startLogs() { this.stopped = false; } stopLogs() { this.stopped = true; } clearLogs() { this.log = ''; for (let i = this._logComponents.length; i > 0; --i) { this._logComponents.pop().destroy(); } } copyLogs() { this._utilities.copyContentToClipboard(this.log); } handleKeyPress(e: KeyboardEvent) { if ((e.which === 65 || e.keyCode === 65) && (e.ctrlKey || e.metaKey)) { e.preventDefault(); this._utilities.highlightText(this._elementRef.nativeElement.querySelector('pre')); } } close() { this.closeClicked.emit(null); } expand() { this.isExpanded = true; this.expandClicked.emit(true); } compress(preventEvent?: boolean) { this.isExpanded = false; if (!preventEvent) { this.expandClicked.emit(false); } } keyDown(KeyboardEvent: any, command: string) { if (AccessibilityHelper.isEnterOrSpace(event)) { switch (command) { case 'startLogs': this.startLogs(); break; case 'stopLogs': this.stopLogs(); break; case 'clearLogs': this.clearLogs(); break; case 'copyLogs': this.copyLogs(); break; case 'expand': this.expand(); break; case 'compress': this.compress(); break; case 'close': this.close(); break; } } } reconnect() { this._isConnectionSuccessful = false; if (this.canReconnect()) { this._isConnectionSuccessful = true; this._oldLength = 0; this._initLogs(this.isHttpLogs); } } canReconnect(): boolean { if (this._xhReq) { return this._xhReq.readyState === XMLHttpRequest.DONE; } return true; } getPopoverText(): string { if (this._isConnectionSuccessful) { return PortalResources.logStreaming_reconnectSuccess; } return PortalResources.logStreaming_connectionExists; } private _initLogs(createEmpty: boolean = true, log?: string) { if (!this.logStreamingEnabled) { this._writeUseAIMessage(); } else { this._startStreamingRequest(createEmpty, log); } } private _writeUseAIMessage() { this._addLogContent(this._ts.instant('viewLiveAppMetrics'), LogLevel.Info); } private _startStreamingRequest(createEmpty: boolean = true, log?: string) { const intervalIncreaseThreshold = 1000; const defaultInterval = 1000; const maxInterval = 10000; let oldLogs = ''; const promise = new Promise<string>(resolve => { if (this._xhReq) { this._timeouts.forEach(window.clearTimeout); this._timeouts = []; this.log = ''; this._xhReq.abort(); this._oldLength = 0; if (createEmpty && log) { this.log = oldLogs = log; this._oldLength = oldLogs.length; } } const scmUrl = this.context.scmUrl; this._xhReq = new XMLHttpRequest(); const url = `${scmUrl}/api/logstream/application/functions/function/${this._functionName}`; this._xhReq.open('GET', url, true); if (this._functionAppService._tryFunctionsBasicAuthToken) { // TODO: [ahmels] Fix token this._xhReq.setRequestHeader('Authorization', `Basic ${this._functionAppService._tryFunctionsBasicAuthToken}`); } else { this._xhReq.setRequestHeader('Authorization', `Bearer ${this._token}`); } this._xhReq.setRequestHeader('FunctionsPortal', '1'); this._xhReq.send(null); if (!createEmpty) { // Get the last 10 kb of the latest log file to prepend it to the streaming logs. // This is so that when you switch between functions, you can see some of the last logs // The ask for this was for users who have functions invoking each other in a chain // and wanting to see the logs for the last invocation for a function when switching to it. this._functionAppService.getLogs(this.context, this._functionName, 10000).subscribe(r => { oldLogs = r.result; if (!this.stopped) { this._addLogContent(oldLogs, LogLevel.Normal); } }); } const callBack = () => { const diff = this._xhReq.responseText.length + oldLogs.length - this._oldLength; if (!this.stopped && diff > 0) { resolve(null); let logStream = ''; logStream = this._xhReq.responseText.substring(this._xhReq.responseText.indexOf('\n') + 1); if (oldLogs === '' && this._oldLength === 0) { this._addLogContent(this._xhReq.responseText.substring(-1, this._xhReq.responseText.indexOf('\n') + 1), LogLevel.Normal); } this._processLogs(logStream.substring(this._logStreamIndex)); this.log = this._oldLength > 0 ? this.log + logStream.substring(this._logStreamIndex) : this._xhReq.responseText; this._logStreamIndex = logStream.length; this._oldLength = this._xhReq.responseText.length + oldLogs.length; window.setTimeout(() => { const el = document.getElementById('log-stream'); if (el) { el.scrollTop = el.scrollHeight; } }); const nextInterval = diff - oldLogs.length > intervalIncreaseThreshold ? this.timerInterval + defaultInterval : this.timerInterval - defaultInterval; if (nextInterval < defaultInterval) { this.timerInterval = defaultInterval; } else if (nextInterval > maxInterval) { this.timerInterval = defaultInterval; } else { this.timerInterval = nextInterval; } } else if (diff === 0) { this.timerInterval = defaultInterval; } if (this._xhReq.readyState !== XMLHttpRequest.DONE) { this._timeouts.push(window.setTimeout(callBack, this.timerInterval)); } }; callBack(); }); return promise; } /** * This checks if we are over the limit of displayed characters {maxCharactersInLog} and then adds the logs to the console. * Logs can get really large and it can impact the browser perf if this variable {this.log} * grows un-checked. * @param logStream string which contains the logs to be displayed */ private _processLogs(logStream: string) { const maxCharactersInLog = 500000; if (logStream.length > maxCharactersInLog) { logStream = logStream.substring(logStream.length - maxCharactersInLog); } const logArray = logStream.split('\n'); let logs = logArray[0]; let type = this._getLogType(logs); for (let i = 1; i < logArray.length - 1; ++i) { const currentLogType = this._getLogType(logArray[i]); if (currentLogType === -1) { logs += '\n' + logArray[i]; } else { this._addLogContent(logs, type); logs = logArray[i]; type = currentLogType; } } this._addLogContent(logs, type); } /** * Get the log type based on the given string * @param log string which contains a single log */ private _getLogType(log: string) { if (log.match(Regex.errorLog)) { return LogLevel.Error; } if (log.match(Regex.infoLog)) { return LogLevel.Info; } if (log.match(Regex.warningLog)) { return LogLevel.Warning; } if (log.match(Regex.log)) { return LogLevel.Normal; } return -1; } /** * This function adds the log content to the console giving it a color * according to the type specified * @param logs string which containts the log * @param type represents the particular type of the log */ private _addLogContent(logs: string, type: number) { if (type === -1 && this._logComponents.length > 0) { this._logComponents[this._logComponents.length - 1].instance.logs += logs; return; } type = type === -1 ? LogLevel.Normal : type; const component = this._logElement.createComponent(this._logContentComponent); component.instance.logs = logs; component.instance.type = type; this._logComponents.push(component); } }
the_stack
import { Data } from "./data"; import { BuilderType as B, VectorType as V } from "./interfaces"; import { BufferBuilder, BitmapBufferBuilder, DataBufferBuilder, OffsetsBufferBuilder } from "./builder/buffer"; import { DataType, Float, Int, Decimal, FixedSizeBinary, Date_, Time, Timestamp, Interval, Utf8, Binary, List, Map_ } from "./type"; /** * A set of options required to create a `Builder` instance for a given `DataType`. * @see {@link Builder} */ export interface BuilderOptions<T extends DataType = any, TNull = any> { type: T; nullValues?: TNull[] | ReadonlyArray<TNull> | null; children?: | { [key: string]: BuilderOptions; } | BuilderOptions[]; } /** * A set of options to create an Iterable or AsyncIterable `Builder` transform function. * @see {@link Builder.throughIterable} * @see {@link Builder.throughAsyncIterable} */ export interface IterableBuilderOptions<T extends DataType = any, TNull = any> extends BuilderOptions<T, TNull> { highWaterMark?: number; queueingStrategy?: "bytes" | "count"; dictionaryHashFunction?: (value: any) => string | number; valueToChildTypeId?: ( builder: Builder<T, TNull>, value: any, offset: number ) => number; } /** * An abstract base class for types that construct Arrow Vectors from arbitrary JavaScript values. * * A `Builder` is responsible for writing arbitrary JavaScript values * to ArrayBuffers and/or child Builders according to the Arrow specification * for each DataType, creating or resizing the underlying ArrayBuffers as necessary. * * The `Builder` for each Arrow `DataType` handles converting and appending * values for a given `DataType`. The high-level {@link Builder.new `Builder.new()`} convenience * method creates the specific `Builder` subclass for the supplied `DataType`. * * Once created, `Builder` instances support both appending values to the end * of the `Builder`, and random-access writes to specific indices * (`Builder.prototype.append(value)` is a convenience method for * `builder.set(builder.length, value)`). Appending or setting values beyond the * Builder's current length may cause the builder to grow its underlying buffers * or child Builders (if applicable) to accommodate the new values. * * After enough values have been written to a `Builder`, `Builder.prototype.flush()` * will commit the values to the underlying ArrayBuffers (or child Builders). The * internal Builder state will be reset, and an instance of `Data<T>` is returned. * Alternatively, `Builder.prototype.toVector()` will flush the `Builder` and return * an instance of `Vector<T>` instead. * * When there are no more values to write, use `Builder.prototype.finish()` to * finalize the `Builder`. This does not reset the internal state, so it is * necessary to call `Builder.prototype.flush()` or `toVector()` one last time * if there are still values queued to be flushed. * * Note: calling `Builder.prototype.finish()` is required when using a `DictionaryBuilder`, * because this is when it flushes the values that have been enqueued in its internal * dictionary's `Builder`, and creates the `dictionaryVector` for the `Dictionary` `DataType`. * * ```ts * import { Builder, Utf8 } from 'apache-arrow'; * * const utf8Builder = Builder.new({ * type: new Utf8(), * nullValues: [null, 'n/a'] * }); * * utf8Builder * .append('hello') * .append('n/a') * .append('world') * .append(null); * * const utf8Vector = utf8Builder.finish().toVector(); * * console.log(utf8Vector.toJSON()); * // > ["hello", null, "world", null] * ``` * * @typeparam T The `DataType` of this `Builder`. * @typeparam TNull The type(s) of values which will be considered null-value sentinels. */ export declare abstract class Builder<T extends DataType = any, TNull = any> { /** * Create a `Builder` instance based on the `type` property of the supplied `options` object. * @param {BuilderOptions<T, TNull>} options An object with a required `DataType` instance * and other optional parameters to be passed to the `Builder` subclass for the given `type`. * * @typeparam T The `DataType` of the `Builder` to create. * @typeparam TNull The type(s) of values which will be considered null-value sentinels. * @nocollapse */ static new<T extends DataType = any, TNull = any>( options: BuilderOptions<T, TNull> ): B<T, TNull>; /** @nocollapse */ static throughNode<T extends DataType = any, TNull = any>( options: import("./io/node/builder").BuilderDuplexOptions<T, TNull> ): import("stream").Duplex; /** @nocollapse */ static throughDOM<T extends DataType = any, TNull = any>( options: import("./io/whatwg/builder").BuilderTransformOptions<T, TNull> ): import("./io/whatwg/builder").BuilderTransform<T, TNull>; /** * Transform a synchronous `Iterable` of arbitrary JavaScript values into a * sequence of Arrow Vector<T> following the chunking semantics defined in * the supplied `options` argument. * * This function returns a function that accepts an `Iterable` of values to * transform. When called, this function returns an Iterator of `Vector<T>`. * * The resulting `Iterator<Vector<T>>` yields Vectors based on the * `queueingStrategy` and `highWaterMark` specified in the `options` argument. * * * If `queueingStrategy` is `"count"` (or omitted), The `Iterator<Vector<T>>` * will flush the underlying `Builder` (and yield a new `Vector<T>`) once the * Builder's `length` reaches or exceeds the supplied `highWaterMark`. * * If `queueingStrategy` is `"bytes"`, the `Iterator<Vector<T>>` will flush * the underlying `Builder` (and yield a new `Vector<T>`) once its `byteLength` * reaches or exceeds the supplied `highWaterMark`. * * @param {IterableBuilderOptions<T, TNull>} options An object of properties which determine the `Builder` to create and the chunking semantics to use. * @returns A function which accepts a JavaScript `Iterable` of values to * write, and returns an `Iterator` that yields Vectors according * to the chunking semantics defined in the `options` argument. * @nocollapse */ static throughIterable<T extends DataType = any, TNull = any>( options: IterableBuilderOptions<T, TNull> ): ThroughIterable<T, TNull>; /** * Transform an `AsyncIterable` of arbitrary JavaScript values into a * sequence of Arrow Vector<T> following the chunking semantics defined in * the supplied `options` argument. * * This function returns a function that accepts an `AsyncIterable` of values to * transform. When called, this function returns an AsyncIterator of `Vector<T>`. * * The resulting `AsyncIterator<Vector<T>>` yields Vectors based on the * `queueingStrategy` and `highWaterMark` specified in the `options` argument. * * * If `queueingStrategy` is `"count"` (or omitted), The `AsyncIterator<Vector<T>>` * will flush the underlying `Builder` (and yield a new `Vector<T>`) once the * Builder's `length` reaches or exceeds the supplied `highWaterMark`. * * If `queueingStrategy` is `"bytes"`, the `AsyncIterator<Vector<T>>` will flush * the underlying `Builder` (and yield a new `Vector<T>`) once its `byteLength` * reaches or exceeds the supplied `highWaterMark`. * * @param {IterableBuilderOptions<T, TNull>} options An object of properties which determine the `Builder` to create and the chunking semantics to use. * @returns A function which accepts a JavaScript `AsyncIterable` of values * to write, and returns an `AsyncIterator` that yields Vectors * according to the chunking semantics defined in the `options` * argument. * @nocollapse */ static throughAsyncIterable<T extends DataType = any, TNull = any>( options: IterableBuilderOptions<T, TNull> ): ThroughAsyncIterable<T, TNull>; /** * Construct a builder with the given Arrow DataType with optional null values, * which will be interpreted as "null" when set or appended to the `Builder`. * @param {{ type: T, nullValues?: any[] }} options A `BuilderOptions` object used to create this `Builder`. */ constructor({ type: type, nullValues: nulls }: BuilderOptions<T, TNull>); /** * The Builder's `DataType` instance. * @readonly */ type: T; /** * The number of values written to the `Builder` that haven't been flushed yet. * @readonly */ length: number; /** * A boolean indicating whether `Builder.prototype.finish()` has been called on this `Builder`. * @readonly */ finished: boolean; /** * The number of elements in the underlying values TypedArray that * represent a single logical element, determined by this Builder's * `DataType`. This is 1 for most types, but is larger when the `DataType` * is `Int64`, `Uint64`, `Decimal`, `DateMillisecond`, certain variants of * `Interval`, `Time`, or `Timestamp`, `FixedSizeBinary`, and `FixedSizeList`. * @readonly */ readonly stride: number; readonly children: Builder[]; /** * The list of null-value sentinels for this `Builder`. When one of these values * is written to the `Builder` (either via `Builder.prototype.set()` or `Builder.prototype.append()`), * a 1-bit is written to this Builder's underlying null BitmapBufferBuilder. * @readonly */ readonly nullValues?: TNull[] | ReadonlyArray<TNull> | null; /** * Flush the `Builder` and return a `Vector<T>`. * @returns {Vector<T>} A `Vector<T>` of the flushed values. */ toVector(): V<T>; readonly ArrayType: any; readonly nullCount: number; readonly numChildren: number; /** * @returns The aggregate length (in bytes) of the values that have been written. */ readonly byteLength: number; /** * @returns The aggregate number of rows that have been reserved to write new values. */ readonly reservedLength: number; /** * @returns The aggregate length (in bytes) that has been reserved to write new values. */ readonly reservedByteLength: number; protected _offsets: DataBufferBuilder<Int32Array>; readonly valueOffsets: Int32Array | null; protected _values: BufferBuilder<T["TArray"], any>; readonly values: T["TArray"]; protected _nulls: BitmapBufferBuilder; readonly nullBitmap: Uint8Array | null; protected _typeIds: DataBufferBuilder<Int8Array>; readonly typeIds: Int8Array | null; protected _isValid: (value: T["TValue"] | TNull) => boolean; protected _setValue: ( inst: Builder<T>, index: number, value: T["TValue"] ) => void; /** * Appends a value (or null) to this `Builder`. * This is equivalent to `builder.set(builder.length, value)`. * @param {T['TValue'] | TNull } value The value to append. */ append(value: T["TValue"] | TNull): this; /** * Validates whether a value is valid (true), or null (false) * @param {T['TValue'] | TNull } value The value to compare against null the value representations */ isValid(value: T["TValue"] | TNull): boolean; /** * Write a value (or null-value sentinel) at the supplied index. * If the value matches one of the null-value representations, a 1-bit is * written to the null `BitmapBufferBuilder`. Otherwise, a 0 is written to * the null `BitmapBufferBuilder`, and the value is passed to * `Builder.prototype.setValue()`. * @param {number} index The index of the value to write. * @param {T['TValue'] | TNull } value The value to write at the supplied index. * @returns {this} The updated `Builder` instance. */ set(index: number, value: T["TValue"] | TNull): this; /** * Write a value to the underlying buffers at the supplied index, bypassing * the null-value check. This is a low-level method that * @param {number} index * @param {T['TValue'] | TNull } value */ setValue(index: number, value: T["TValue"]): void; setValid(index: number, valid: boolean): boolean; addChild(child: Builder, name?: string): void; /** * Retrieve the child `Builder` at the supplied `index`, or null if no child * exists at that index. * @param {number} index The index of the child `Builder` to retrieve. * @returns {Builder | null} The child Builder at the supplied index or null. */ getChildAt<R extends DataType = any>(index: number): Builder<R> | null; /** * Commit all the values that have been written to their underlying * ArrayBuffers, including any child Builders if applicable, and reset * the internal `Builder` state. * @returns A `Data<T>` of the buffers and childData representing the values written. */ flush(): Data<T>; /** * Finalize this `Builder`, and child builders if applicable. * @returns {this} The finalized `Builder` instance. */ finish(): this; /** * Clear this Builder's internal state, including child Builders if applicable, and reset the length to 0. * @returns {this} The cleared `Builder` instance. */ clear(): this; } /** @ignore */ export declare abstract class FixedWidthBuilder< T extends | Int | Float | FixedSizeBinary | Date_ | Timestamp | Time | Decimal | Interval = any, TNull = any > extends Builder<T, TNull> { constructor(opts: BuilderOptions<T, TNull>); setValue(index: number, value: T["TValue"]): void; } /** @ignore */ export declare abstract class VariableWidthBuilder< T extends Binary | Utf8 | List | Map_, TNull = any > extends Builder<T, TNull> { protected _pendingLength: number; protected _offsets: OffsetsBufferBuilder; protected _pending: Map<number, any> | undefined; constructor(opts: BuilderOptions<T, TNull>); setValue(index: number, value: T["TValue"]): void; setValid(index: number, isValid: boolean): boolean; clear(): this; flush(): Data<T>; finish(): this; protected _flush(): this; protected abstract _flushPending( pending: Map<number, any>, pendingLength: number ): void; } /** @ignore */ declare type ThroughIterable<T extends DataType = any, TNull = any> = ( source: Iterable<T["TValue"] | TNull> ) => IterableIterator<V<T>>; /** @ignore */ declare type ThroughAsyncIterable<T extends DataType = any, TNull = any> = ( source: Iterable<T["TValue"] | TNull> | AsyncIterable<T["TValue"] | TNull> ) => AsyncIterableIterator<V<T>>; export {};
the_stack
* @packageDocumentation * @hidden */ import { AABB, Frustum, intersect, Sphere } from '../geometry'; import { Model } from '../renderer/scene/model'; import { Camera, SKYBOX_FLAG } from '../renderer/scene/camera'; import { Vec2, Vec3, Mat4, Quat, Vec4 } from '../math'; import { RenderPipeline } from './render-pipeline'; import { Pool } from '../memop'; import { IRenderObject, UBOShadow } from './define'; import { ShadowType, Shadows } from '../renderer/scene/shadows'; import { SphereLight, DirectionalLight, Light } from '../renderer/scene'; import { Layers } from '../scene-graph'; const _tempVec3 = new Vec3(); const _dir_negate = new Vec3(); const _vec3_p = new Vec3(); const _shadowPos = new Vec3(); const _mat4_trans = new Mat4(); const _castLightViewBounds = new AABB(); const _castWorldBounds = new AABB(); let _castBoundsInited = false; const _validLights: Light[] = []; const _sphere = Sphere.create(0, 0, 0, 1); const _cameraBoundingSphere = new Sphere(); const _validFrustum = new Frustum(); _validFrustum.accurate = true; let _lightViewFrustum = new Frustum(); _lightViewFrustum.accurate = true; const _dirLightFrustum = new Frustum(); const _matShadowTrans = new Mat4(); const _matShadowView = new Mat4(); const _matShadowViewInv = new Mat4(); const _matShadowProj = new Mat4(); const _matShadowViewProj = new Mat4(); const _matShadowViewProjArbitaryPos = new Mat4(); const _matShadowViewProjArbitaryPosInv = new Mat4(); const _projPos = new Vec3(); const _texelSize = new Vec2(); const _projSnap = new Vec3(); const _snap = new Vec3(); const _focus = new Vec3(0, 0, 0); const _ab = new AABB(); const roPool = new Pool<IRenderObject>(() => ({ model: null!, depth: 0 }), 128); const dirShadowPool = new Pool<IRenderObject>(() => ({ model: null!, depth: 0 }), 128); const castShadowPool = new Pool<IRenderObject>(() => ({ model: null!, depth: 0 }), 128); function getRenderObject (model: Model, camera: Camera) { let depth = 0; if (model.node) { Vec3.subtract(_tempVec3, model.node.worldPosition, camera.position); depth = Vec3.dot(_tempVec3, camera.forward); } const ro = roPool.alloc(); ro.model = model; ro.depth = depth; return ro; } function getDirShadowRenderObject (model: Model, camera: Camera) { let depth = 0; if (model.node) { Vec3.subtract(_tempVec3, model.node.worldPosition, camera.position); depth = Vec3.dot(_tempVec3, camera.forward); } const ro = dirShadowPool.alloc(); ro.model = model; ro.depth = depth; return ro; } function getCastShadowRenderObject (model: Model, camera: Camera) { let depth = 0; if (model.node) { Vec3.subtract(_tempVec3, model.node.worldPosition, camera.position); depth = Vec3.dot(_tempVec3, camera.forward); } const ro = castShadowPool.alloc(); ro.model = model; ro.depth = depth; return ro; } export function getShadowWorldMatrix (pipeline: RenderPipeline, rotation: Quat, dir: Vec3, out: Vec3) { const shadows = pipeline.pipelineSceneData.shadows; Vec3.negate(_dir_negate, dir); const distance: number = shadows.fixedSphere.radius * Shadows.COEFFICIENT_OF_EXPANSION; Vec3.multiplyScalar(_vec3_p, _dir_negate, distance); Vec3.add(_vec3_p, _vec3_p, shadows.fixedSphere.center); out.set(_vec3_p); Mat4.fromRT(_mat4_trans, rotation, _vec3_p); return _mat4_trans; } function updateSphereLight (pipeline: RenderPipeline, light: SphereLight) { const shadows = pipeline.pipelineSceneData.shadows; const pos = light.node!.worldPosition; const n = shadows.normal; const d = shadows.distance + 0.001; // avoid z-fighting const NdL = Vec3.dot(n, pos); const lx = pos.x; const ly = pos.y; const lz = pos.z; const nx = n.x; const ny = n.y; const nz = n.z; const m = shadows.matLight; m.m00 = NdL - d - lx * nx; m.m01 = -ly * nx; m.m02 = -lz * nx; m.m03 = -nx; m.m04 = -lx * ny; m.m05 = NdL - d - ly * ny; m.m06 = -lz * ny; m.m07 = -ny; m.m08 = -lx * nz; m.m09 = -ly * nz; m.m10 = NdL - d - lz * nz; m.m11 = -nz; m.m12 = lx * d; m.m13 = ly * d; m.m14 = lz * d; m.m15 = NdL; pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET, shadows.matLight); } function updateDirLight (pipeline: RenderPipeline, light: DirectionalLight) { const shadows = pipeline.pipelineSceneData.shadows; const dir = light.direction; const n = shadows.normal; const d = shadows.distance + 0.001; // avoid z-fighting const NdL = Vec3.dot(n, dir); const scale = 1 / NdL; const lx = dir.x * scale; const ly = dir.y * scale; const lz = dir.z * scale; const nx = n.x; const ny = n.y; const nz = n.z; const m = shadows.matLight; m.m00 = 1 - nx * lx; m.m01 = -nx * ly; m.m02 = -nx * lz; m.m03 = 0; m.m04 = -ny * lx; m.m05 = 1 - ny * ly; m.m06 = -ny * lz; m.m07 = 0; m.m08 = -nz * lx; m.m09 = -nz * ly; m.m10 = 1 - nz * lz; m.m11 = 0; m.m12 = lx * d; m.m13 = ly * d; m.m14 = lz * d; m.m15 = 1; pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET, shadows.matLight); } export function updatePlanarPROJ (shadowInfo: Shadows, light: DirectionalLight, shadowUBO: Float32Array) { const dir = light.direction; const n = shadowInfo.normal; const d = shadowInfo.distance + 0.001; // avoid z-fighting const NdL = Vec3.dot(n, dir); const scale = 1 / NdL; const lx = dir.x * scale; const ly = dir.y * scale; const lz = dir.z * scale; const nx = n.x; const ny = n.y; const nz = n.z; const m = shadowInfo.matLight; m.m00 = 1 - nx * lx; m.m01 = -nx * ly; m.m02 = -nx * lz; m.m03 = 0; m.m04 = -ny * lx; m.m05 = 1 - ny * ly; m.m06 = -ny * lz; m.m07 = 0; m.m08 = -nz * lx; m.m09 = -nz * ly; m.m10 = 1 - nz * lz; m.m11 = 0; m.m12 = lx * d; m.m13 = ly * d; m.m14 = lz * d; m.m15 = 1; Mat4.toArray(shadowUBO, m, UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET); } export function lightCollecting (camera: Camera, lightNumber: number) { _validLights.length = 0; const scene = camera.scene!; _validLights.push(scene.mainLight!); const spotLights = scene.spotLights; for (let i = 0; i < spotLights.length; i++) { const light = spotLights[i]; Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); if (intersect.sphereFrustum(_sphere, camera.frustum) && lightNumber > _validLights.length) { _validLights.push(light); } } return _validLights; } export function getCameraWorldMatrix (out: Mat4, camera: Camera) { if (!camera.node) { return; } const cameraNode = camera.node; const position = cameraNode.getWorldPosition(); const rotation = cameraNode.getWorldRotation(); Mat4.fromRT(out, rotation, position); out.m08 *= -1.0; out.m09 *= -1.0; out.m10 *= -1.0; } export function QuantizeDirLightShadowCamera (out: Frustum, pipeline: RenderPipeline, dirLight: DirectionalLight, camera: Camera, shadowInfo: Shadows) { const device = pipeline.device; const invisibleOcclusionRange = shadowInfo.invisibleOcclusionRange; const shadowMapWidth = shadowInfo.size.x; // Raw data getCameraWorldMatrix(_mat4_trans, camera); Frustum.split(_validFrustum, camera, _mat4_trans, 0.1, shadowInfo.shadowDistance); _lightViewFrustum = Frustum.clone(_validFrustum); // view matrix with range back Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _focus); Mat4.invert(_matShadowView, _matShadowTrans); Mat4.invert(_matShadowViewInv, _matShadowView); const shadowViewArbitaryPos = _matShadowView.clone(); _lightViewFrustum.transform(_matShadowView); // bounding box in light space AABB.fromPoints(_castLightViewBounds, new Vec3(10000000, 10000000, 10000000), new Vec3(-10000000, -10000000, -10000000)); _castLightViewBounds.mergeFrustum(_lightViewFrustum); const r = _castLightViewBounds.halfExtents.z * 2.0; _shadowPos.set(_castLightViewBounds.center.x, _castLightViewBounds.center.y, _castLightViewBounds.center.z + _castLightViewBounds.halfExtents.z + invisibleOcclusionRange); Vec3.transformMat4(_shadowPos, _shadowPos, _matShadowViewInv); Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _shadowPos); Mat4.invert(_matShadowView, _matShadowTrans); Mat4.invert(_matShadowViewInv, _matShadowView); // calculate projection matrix params // min value may lead to some shadow leaks const orthoSizeMin = Vec3.distance(_validFrustum.vertices[0], _validFrustum.vertices[6]); // max value is accurate but poor usage for shadowmap _cameraBoundingSphere.center.set(0, 0, 0); _cameraBoundingSphere.radius = -1.0; _cameraBoundingSphere.mergePoints(_validFrustum.vertices); const orthoSizeMax = _cameraBoundingSphere.radius * 2.0; // use lerp(min, accurate_max) to save shadowmap usage const orthoSize = orthoSizeMin * 0.8 + orthoSizeMax * 0.2; shadowInfo.shadowCameraFar = r + invisibleOcclusionRange; // snap to whole texels const halfOrthoSize = orthoSize * 0.5; Mat4.ortho(_matShadowProj, -halfOrthoSize, halfOrthoSize, -halfOrthoSize, halfOrthoSize, 0.1, shadowInfo.shadowCameraFar, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY); if (shadowMapWidth > 0.0) { Mat4.multiply(_matShadowViewProjArbitaryPos, _matShadowProj, shadowViewArbitaryPos); Vec3.transformMat4(_projPos, _shadowPos, _matShadowViewProjArbitaryPos); const invActualSize = 2.0 / shadowMapWidth; _texelSize.set(invActualSize, invActualSize); const modX = _projPos.x % _texelSize.x; const modY = _projPos.y % _texelSize.y; _projSnap.set(_projPos.x - modX, _projPos.y - modY, _projPos.z); Mat4.invert(_matShadowViewProjArbitaryPosInv, _matShadowViewProjArbitaryPos); Vec3.transformMat4(_snap, _projSnap, _matShadowViewProjArbitaryPosInv); Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _snap); Mat4.invert(_matShadowView, _matShadowTrans); Mat4.invert(_matShadowViewInv, _matShadowView); Frustum.createOrtho(out, orthoSize, orthoSize, 0.1, shadowInfo.shadowCameraFar, _matShadowViewInv); } else { for (let i = 0; i < 8; i++) { out.vertices[i].set(0.0, 0.0, 0.0); } out.updatePlanes(); } Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); shadowInfo.matShadowView = _matShadowView; shadowInfo.matShadowProj = _matShadowProj; shadowInfo.matShadowViewProj = _matShadowViewProj; } export function sceneCulling (pipeline: RenderPipeline, camera: Camera) { const scene = camera.scene!; const mainLight = scene.mainLight; const sceneData = pipeline.pipelineSceneData; const shadows = sceneData.shadows; const skybox = sceneData.skybox; const renderObjects = sceneData.renderObjects; roPool.freeArray(renderObjects); renderObjects.length = 0; const castShadowObjects = sceneData.castShadowObjects; castShadowPool.freeArray(castShadowObjects); castShadowObjects.length = 0; _castBoundsInited = false; let dirShadowObjects: IRenderObject[] | null = null; if (shadows.enabled) { pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor); if (shadows.type === ShadowType.ShadowMap) { dirShadowObjects = pipeline.pipelineSceneData.dirShadowObjects; dirShadowPool.freeArray(dirShadowObjects); dirShadowObjects.length = 0; // update dirLightFrustum if (mainLight && mainLight.node) { QuantizeDirLightShadowCamera(_dirLightFrustum, pipeline, mainLight, camera, shadows); } else { for (let i = 0; i < 8; i++) { _dirLightFrustum.vertices[i].set(0.0, 0.0, 0.0); } _dirLightFrustum.updatePlanes(); } } } if (mainLight) { if (shadows.type === ShadowType.Planar) { updateDirLight(pipeline, mainLight); } } if (skybox.enabled && skybox.model && (camera.clearFlag & SKYBOX_FLAG)) { renderObjects.push(getRenderObject(skybox.model, camera)); } const models = scene.models; const visibility = camera.visibility; for (let i = 0; i < models.length; i++) { const model = models[i]; // filter model by view visibility if (model.enabled) { if (model.castShadow) { castShadowObjects.push(getCastShadowRenderObject(model, camera)); } if (shadows.firstSetCSM && model.worldBounds) { if (!_castBoundsInited) { _castWorldBounds.copy(model.worldBounds); _castBoundsInited = true; } AABB.merge(_castWorldBounds, _castWorldBounds, model.worldBounds); } if (model.node && ((visibility & model.node.layer) === model.node.layer) || (visibility & model.visFlags)) { // shadow render Object if (dirShadowObjects != null && model.castShadow && model.worldBounds) { // frustum culling if (shadows.fixedArea) { AABB.transform(_ab, model.worldBounds, shadows.matLight); if (intersect.aabbFrustum(_ab, camera.frustum)) { dirShadowObjects.push(getDirShadowRenderObject(model, camera)); } } else { // eslint-disable-next-line no-lonely-if if (intersect.aabbFrustum(model.worldBounds, _dirLightFrustum)) { dirShadowObjects.push(getDirShadowRenderObject(model, camera)); } } } // frustum culling if (model.worldBounds && !intersect.aabbFrustum(model.worldBounds, camera.frustum)) { continue; } renderObjects.push(getRenderObject(model, camera)); } } } // FirstSetCSM flag Bit Control if (shadows.firstSetCSM) { shadows.shadowDistance = _castWorldBounds.halfExtents.length() * 2.0; shadows.firstSetCSM = false; } }
the_stack
import { zipObject, isUndefined, get, set, SCHEMA_OPTIONS_SYMBOL } from './helpers'; import { Schema, StrictSchema, Constructable, SourceFromSchema, Mapper, DestinationFromSchema } from './types'; import { MorphismSchemaTree, createSchema, SchemaOptions } from './MorphismTree'; import { MorphismRegistry, IMorphismRegistry } from './MorphismRegistry'; import { decorator } from './MorphismDecorator'; import { Reporter, reporter as defaultReporter, Formatter, targetHasErrors, ValidationErrors } from './validation/reporter'; import { Validation, IValidation } from './validation/Validation'; import { ValidatorError } from './validation/validators/ValidatorError'; import { Rule } from './validation/validators/types'; /** * Low Level transformer function. * Take a plain object as input and transform its values using a specified schema. * @param {Object} object * @param {Map<string, string> | Map<string, Function>} schema Transformation schema * @param {Array} items Items to be forwarded to Actions * @param {} objectToCompute Created tranformed object of a given type */ function transformValuesFromObject<Source, Target>( object: Source, tree: MorphismSchemaTree<Target, Source>, items: Source[], objectToCompute: Target ) { const options = tree.schemaOptions; const transformChunks = []; for (const node of tree.traverseBFS()) { const { preparedAction, targetPropertyPath } = node.data; if (preparedAction) transformChunks.push({ targetPropertyPath, preparedAction: preparedAction({ object, objectToCompute, items }), }); } return transformChunks.reduce((finalObject, chunk) => { const undefinedValueCheck = (destination: any, source: any) => { // Take the Object class value property if the incoming property is undefined if (isUndefined(source)) { if (!isUndefined(destination)) { return destination; } else { return; // No Black Magic Fuckery here, if the source and the destination are undefined, we don't do anything } } else { return source; } }; const finalValue = undefinedValueCheck(get(finalObject, chunk.targetPropertyPath), chunk.preparedAction); if (finalValue === undefined) { // strip undefined values if (options && options.undefinedValues && options.undefinedValues.strip) { if (options.undefinedValues.default) { set(finalObject, chunk.targetPropertyPath, options.undefinedValues.default(finalObject, chunk.targetPropertyPath)); } } else { // do not strip undefined values set(finalObject, chunk.targetPropertyPath, finalValue); } checkIfValidationShouldThrow<Target>(options, finalObject); return finalObject; } else { set(finalObject, chunk.targetPropertyPath, finalValue); checkIfValidationShouldThrow<Target>(options, finalObject); return finalObject; } }, objectToCompute); } function checkIfValidationShouldThrow<Target>(options: SchemaOptions<Target>, finalObject: Target) { if (options && options.validation && options.validation.throw) { if (targetHasErrors(finalObject)) { let errors: ValidationErrors | null; if (options.validation.reporter) { const reporter = options.validation.reporter; errors = reporter.extractErrors(finalObject); } else { errors = defaultReporter.extractErrors(finalObject); } if (errors) { throw errors; } } } } function transformItems<T, TSchema extends Schema<T | {}>>(schema: TSchema, type?: Constructable<T>) { const options = MorphismSchemaTree.getSchemaOptions<T>(schema); let tree: MorphismSchemaTree<any, any>; if (type && options.class && options.class.automapping) { const finalSchema = getSchemaForClass(type, schema); tree = new MorphismSchemaTree(finalSchema); } else { tree = new MorphismSchemaTree(schema); } const mapper: Mapper<TSchema> = (source: any) => { if (!source) { return source; } if (Array.isArray(source)) { return source.map(obj => { if (type) { const classObject = new type(); return transformValuesFromObject(obj, tree, source, classObject); } else { const jsObject = {}; return transformValuesFromObject(obj, tree, source, jsObject); } }); } else { const object = source; if (type) { const classObject = new type(); return transformValuesFromObject<any, T>(object, tree, [object], classObject); } else { const jsObject = {}; return transformValuesFromObject(object, tree, [object], jsObject); } } }; return mapper; } function getSchemaForClass<T>(type: Constructable<T>, baseSchema: Schema<T>): Schema<T> { let typeFields = Object.keys(new type()); let defaultSchema = zipObject(typeFields, typeFields); let finalSchema = Object.assign(defaultSchema, baseSchema); return finalSchema; } /** * Currying function that either outputs a mapping function or the transformed data. * * @example * ```js * // => Outputs a function when only a schema is provided const fn = morphism(schema); const result = fn(data); // => Outputs the transformed data when a schema and the input data is provided const result = morphism(schema, data); // => Outputs the transformed data as an ES6 Class Object when a schema, the input data and an ES6 Class are provided const result = morphism(schema, data, Foo); // result is type of Foo * ``` * @param {Schema} schema Structure-preserving object from a source data towards a target data * @param {} items Object or Collection to be mapped * @param {} type * */ function morphism< TSchema = Schema<DestinationFromSchema<Schema>, SourceFromSchema<Schema>>, Source extends SourceFromSchema<TSchema> = SourceFromSchema<TSchema> >(schema: TSchema, data: Source[]): DestinationFromSchema<TSchema>[]; function morphism< TSchema = Schema<DestinationFromSchema<Schema>, SourceFromSchema<Schema>>, Source extends SourceFromSchema<TSchema> = SourceFromSchema<TSchema> >(schema: TSchema, data: Source): DestinationFromSchema<TSchema>; function morphism<TSchema = Schema<DestinationFromSchema<Schema>, SourceFromSchema<Schema>>>(schema: TSchema): Mapper<TSchema>; // morphism({}) => mapper(S) => T function morphism<TSchema extends Schema, TDestination>( schema: TSchema, items: null, type: Constructable<TDestination> ): Mapper<TSchema, TDestination>; // morphism({}, null, T) => mapper(S) => T function morphism< TSchema = Schema<DestinationFromSchema<Schema>, SourceFromSchema<Schema>>, Target = never, Source extends SourceFromSchema<TSchema> = SourceFromSchema<TSchema> >(schema: TSchema, items: Source, type: Constructable<Target>): Target; // morphism({}, {}, T) => T function morphism< TSchema = Schema<DestinationFromSchema<Schema>, SourceFromSchema<Schema>>, Target = never, Source extends SourceFromSchema<TSchema> = SourceFromSchema<TSchema> >(schema: TSchema, items: Source[], type: Constructable<Target>): Target[]; // morphism({}, [], T) => T[] function morphism<Target, Source, TSchema extends Schema<Target, Source>>( schema: TSchema, items?: SourceFromSchema<TSchema> | null, type?: Constructable<Target> ) { switch (arguments.length) { case 1: { return transformItems(schema); } case 2: { return transformItems(schema)(items); } case 3: { if (type) { if (items !== null) return transformItems(schema, type)(items); // TODO: deprecate this option morphism(schema,null,Type) in favor of createSchema({},options={class: Type}) return transformItems(schema, type); } else { throw new Error(`When using morphism(schema, items, type), type should be defined but value received is ${type}`); } } } } // Decorators /** * Function Decorator transforming the return value of the targeted Function using the provided Schema and/or Type * * @param {Schema<Target>} schema Structure-preserving object from a source data towards a target data * @param {Constructable<Target>} [type] Target Class Type */ export function morph<Target>(schema: Schema<Target>, type?: Constructable<Target>) { const mapper = transformItems(schema, type); return decorator(mapper); } /** * Function Decorator transforming the return value of the targeted Function to JS Object(s) using the provided Schema * * @param {StrictSchema<Target>} schema Structure-preserving object from a source data towards a target data */ export function toJSObject<Target>(schema: StrictSchema<Target>) { const mapper = transformItems(schema); return decorator(mapper); } /** * Function Decorator transforming the return value of the targeted Function using the provided Schema and Class Type * * @param {Schema<Target>} schema Structure-preserving object from a source data towards a target data * @param {Constructable<Target>} [type] Target Class Type */ export function toClassObject<Target>(schema: Schema<Target>, type: Constructable<Target>) { const mapper = transformItems(schema, type); return decorator(mapper); } // Registry const morphismRegistry = new MorphismRegistry(); const morphismMixin: typeof morphism & any = morphism; morphismMixin.register = (t: any, s: any) => morphismRegistry.register(t, s); morphismMixin.map = (t: any, d: any) => morphismRegistry.map(t, d); morphismMixin.getMapper = (t: any) => morphismRegistry.getMapper(t); morphismMixin.setMapper = (t: any, s: any) => morphismRegistry.setMapper(t, s); morphismMixin.deleteMapper = (t: any) => morphismRegistry.deleteMapper(t); morphismMixin.mappers = morphismRegistry.mappers; const Morphism: typeof morphism & IMorphismRegistry = morphismMixin; export { morphism, createSchema, Schema, StrictSchema, SchemaOptions, Mapper, SCHEMA_OPTIONS_SYMBOL, Reporter, defaultReporter as reporter, Formatter, Validation, Rule, ValidatorError, IValidation, }; export default Morphism;
the_stack
jest.mock('../adminRequests'); jest.mock('../getCertPath'); jest.mock('../getProxyResponse'); jest.mock('../cleanupQueue'); jest.mock('get-port', function() { return { default: jest.fn().mockReturnValue(50001) }; }); jest.mock('../getCertForHost', function() { return { preloadCertForHost: jest.fn() }; }); jest.mock('../logger', function() { const logger: any = { log: jest.fn() }; logger.log.debug = jest.fn(); logger.log.info = jest.fn(); logger.log.warn = jest.fn(); logger.log.error = jest.fn(); return logger; }); import { applyConfigDefaults, ProxyConfigWithDefaults } from '../applyConfigDefaults'; import { createProxy } from '../createProxy'; import * as unexpected from 'unexpected'; import { ProxyConfig, WrappedRequest, ProxyResponse } from '../ProxyConfig'; import { getProxyResponse as getProxyResponseMock } from '../getProxyResponse'; import * as adminRequestsMock from '../adminRequests'; import * as cloneDeep from 'lodash/cloneDeep'; import { registerCleanup as registerCleanupMock } from '../cleanupQueue'; import { log as logMock } from '../logger'; interface AdminRequests { addHostEntry: (certFilename: string) => Promise<any>; removeHostEntry: (certFilename: string) => Promise<any>; portProxy: (target: string, localPort: number) => Promise<any>; } const adminRequests = (adminRequestsMock as any) as jest.Mocked<AdminRequests>; const registerCleanup = (registerCleanupMock as any) as jest.Mock; // Can't find a way to type this properly (mock of a function with function properties that are also mocked) const log: any = logMock; const expect = unexpected.clone(); const getProxyResponse = getProxyResponseMock as jest.Mock; const defaultProxyConfig: ProxyConfig = { target: 'http://foo:8000', targetHeaders: { 'X-override-header': 'foo' }, routes: { '/bar': { proxyDirect: true }, 'POST /bar': { postMessage: true }, '/func': (req, h, proxy) => { const res = h.response({ func: true }); res.header('x-foo', 'bar'); return res; }, '/proxy/direct': (req, h, proxy) => { return proxy(); }, '/proxy/urledit': (req, h, proxy) => { req.url.pathname = '/url-is-changed'; return proxy(); }, '/proxy/reqheader': (req, h, proxy) => { req.headers['x-foo'] = 'added'; return proxy(); }, '/proxy/resheader': async (req, h, proxy) => { const res = await proxy(); res.headers['x-response-foo'] = 'added'; return res; }, 'POST /proxy/editpost': async (req, h, proxy) => { req.payload.altered = true; return await proxy(); }, '/proxy/editoverride': (req, h, proxy) => { req.overrideHeaders['x-override-header'] = 'bar'; return proxy(); }, '/proxy/edittarget': (req, h, proxy) => { req.url.host = 'changed.test'; return proxy(); }, '/proxy/url/{urlparam}': (req, h, proxy) => { return { param: req.params.urlparam }; }, 'POST /proxy/error': (req, h, proxy) => { throw new Error('some handler error'); }, 'POST /proxy/reject': (req, h, proxy) => { return new Promise((resolve, reject) => { reject(new Error('some handler rejected promise')); }); } } }; let proxyConfig: ProxyConfig; function makeConfig(proxyConfig: ProxyConfig): ProxyConfigWithDefaults { return applyConfigDefaults(proxyConfig, '/tmp'); } expect.addAssertion('<object> to provide response <object>', function( expect, request, expected ) { if (!proxyConfig) { throw new Error('No config setup'); } return createProxy(makeConfig(proxyConfig)) .then((proxy) => { return proxy.inject(request); }) .then((res) => { let json: any; try { json = JSON.parse(res.payload); } catch { json = undefined; } const wrappedResponse = { statusCode: res.statusCode, statusMessage: res.statusMessage, json: json, payload: res.payload, rawPayload: res.rawPayload, headers: res.headers }; expect(wrappedResponse, 'to satisfy', expected); }); }); expect.addAssertion('<object> to provide result <any>', function( expect, request, expected ) { return expect(request, 'to provide response', { json: expected }); }); describe('createProxy', () => { beforeEach(() => { proxyConfig = cloneDeep(defaultProxyConfig); adminRequests.addHostEntry.mockClear(); adminRequests.removeHostEntry.mockClear(); adminRequests.portProxy.mockClear(); registerCleanup.mockClear(); log.mockClear(); log.debug.mockClear(); log.info.mockClear(); log.warn.mockClear(); log.error.mockClear(); }); it('replies to a plain JSON response', () => { return expect({ method: 'GET', url: '/bar' }, 'to provide result', { proxyDirect: true }); }); it('proxies a plain JSON response', () => { return expect( { method: 'GET', url: '/proxythrough' }, 'to provide result', { json: true, mocked: true } ); }); it('responds to a POST', () => { return expect({ method: 'POST', url: '/bar' }, 'to provide result', { postMessage: true }); }); it('uses a function route without calling proxy', () => { getProxyResponse.mockClear(); return expect({ method: 'GET', url: '/func' }, 'to provide response', { headers: { 'x-foo': 'bar' }, json: { func: true } }).then(() => { expect(getProxyResponse.mock.calls.length, 'to be', 0); }); }); it('can override the default route for all methods', () => { if (!proxyConfig.routes) { throw new Error( 'routes not set - will never happen but keeps typescript happy for the test' ); } proxyConfig.routes['* /{path*}'] = async (req, h, proxy) => { const res = await proxy(); res.headers['x-additional'] = 'foo'; return res; }; return expect( { method: 'PUT', url: '/some/random/url' }, 'to provide response', { headers: { 'x-additional': 'foo' } } ); }); it('doesn`t add host for localhost', () => { proxyConfig.localUrl = 'http://localhost:5000'; return expect({ method: 'GET', url: '/bar' }, 'to provide result', { proxyDirect: true }).then(() => { expect(adminRequests.addHostEntry.mock.calls, 'to have length', 0); }); }); it('registers a shutdown function to call', () => { const shutdownHandler = () => {}; proxyConfig.onShutdown = shutdownHandler; return expect({ method: 'GET', url: '/bar' }, 'to provide result', { proxyDirect: true }).then(() => { // Expect that the last registered cleanup is the shutdownHandler expect( registerCleanup.mock.calls[registerCleanup.mock.calls.length - 1], 'to satisfy', [shutdownHandler] ); }); }); it('starts a port proxy when using a privileged port', () => { proxyConfig.target = 'http://foo'; adminRequests.portProxy.mockResolvedValue({ data: { success: true } }); return createProxy(makeConfig(proxyConfig)).then((proxy) => { expect(adminRequests.portProxy.mock.calls, 'to satisfy', [ [ 'http://foo/', 50001, '/home/user/.dev-ssl-certs', { credentials: true, maxAge: 60 } ] ]); }); }); it('listens on the free port when using originally using a privileged port', () => { proxyConfig.target = 'http://foo'; adminRequests.portProxy.mockResolvedValue({ data: { success: true } }); return createProxy(makeConfig(proxyConfig)).then((proxy) => { expect(proxy.settings.port, 'to equal', 50001); }); }); it('starts a TLS port proxy when using a privileged port', () => { proxyConfig.target = 'https://foo'; adminRequests.portProxy.mockResolvedValue({ data: { success: true } }); return createProxy(makeConfig(proxyConfig)).then((proxy) => { expect(adminRequests.portProxy.mock.calls, 'to satisfy', [ [ 'https://foo/', 50001, '/home/user/.dev-ssl-certs', { credentials: true, maxAge: 60 } ] ]); }); }); it('listens on the free port when using originally using a privileged port', () => { proxyConfig.target = 'http://foo'; adminRequests.portProxy.mockResolvedValue({ data: { success: true } }); return createProxy(makeConfig(proxyConfig)).then((proxy) => { expect(proxy.settings.port, 'to equal', 50001); }); }); it('fails and throws an error if the privileged port proxying fails', () => { proxyConfig.target = 'http://foo'; adminRequests.portProxy.mockResolvedValue({ data: { success: false, code: 'EADDRINUSE' } }); return expect( createProxy(makeConfig(proxyConfig)), 'to be rejected with', /Error starting admin server/ ); }); it('fails CORS requests without Origin and Access-Control-Request-Method headers', () => { return expect( { method: 'OPTIONS', url: '/foo', headers: {} }, 'to provide response', { statusCode: 404, json: { message: 'CORS error: Missing Access-Control-Request-Method header' } } ); }); it('responds with CORS headers when Origin and Access-Control-Request-Method headers are set', () => { return expect( { method: 'OPTIONS', url: '/foo', headers: { Origin: 'https://example.com', 'Access-Control-Request-Method': 'POST' } }, 'to provide response', { statusCode: 204, headers: { 'access-control-allow-origin': 'https://example.com', 'access-control-allow-methods': 'POST', 'access-control-allow-headers': 'Accept,Authorization,Content-Type,If-None-Match', 'access-control-expose-headers': 'WWW-Authenticate,Server-Authorization', 'access-control-max-age': 60, 'access-control-allow-credentials': 'true' } } ); }); it('responds with CORS headers when config has a catch-all-route', () => { // @ts-ignore proxyConfig.routes['* /{path*}'] = 'hello'; return expect( { method: 'OPTIONS', url: '/foo', headers: { origin: 'http://example.com', 'access-control-request-method': 'POST' } }, 'to provide response', { headers: { 'access-control-allow-origin': 'http://example.com', 'access-control-allow-methods': 'POST', 'access-control-allow-headers': 'Accept,Authorization,Content-Type,If-None-Match', 'access-control-expose-headers': 'WWW-Authenticate,Server-Authorization', 'access-control-max-age': 60, 'access-control-allow-credentials': 'true' } } ); }); it('can override the default CORS handling', () => { proxyConfig.cors = { origin: ['http://some.origin'], additionalHeaders: ['X-Foo-Bar', 'X-Additional-Header'], additionalExposedHeaders: ['Some-Exposed-Header'], maxAge: 1234, credentials: true }; return expect( { method: 'OPTIONS', url: '/foo', headers: { origin: 'http://some.origin', 'access-control-request-method': 'PUT', 'access-control-request-headers': 'X-Foo-Bar, X-Additional-Header' } }, 'to provide response', { headers: { 'access-control-allow-origin': 'http://some.origin', 'access-control-allow-methods': 'PUT', 'access-control-allow-headers': 'Accept,Authorization,Content-Type,If-None-Match,X-Foo-Bar,X-Additional-Header', 'access-control-expose-headers': 'WWW-Authenticate,Server-Authorization,Some-Exposed-Header', 'access-control-max-age': 1234, 'access-control-allow-credentials': 'true' } } ); }); describe('proxy functions', () => { beforeEach(() => getProxyResponse.mockClear()); it('calls the proxy and responds', () => { return expect( { method: 'GET', url: '/proxy/direct' }, 'to provide result', { json: true, mocked: true } ); }); it('can edit the URL before proxying', () => { return expect( { method: 'GET', url: '/proxy/urledit' }, 'to provide result', { json: true, mocked: true } ).then(() => { expect(getProxyResponse.mock.calls[0], 'to satisfy', [ {}, { url: { pathname: '/url-is-changed' } } ]); }); }); it('can edit request headers before proxying', () => { return expect( { method: 'GET', url: '/proxy/reqheader' }, 'to provide result', { json: true, mocked: true } ).then(() => { expect(getProxyResponse.mock.calls[0], 'to satisfy', [ {}, { headers: { 'x-foo': 'added' } } ]); }); }); it('can edit response headers after proxying', () => { return expect( { method: 'GET', url: '/proxy/resheader' }, 'to provide response', { headers: { 'x-response-foo': 'added' } } ); }); it('can edit POST payload before proxying', () => { return expect( { method: 'POST', url: '/proxy/editpost', payload: { stuff: 'foo', altered: false } }, 'to provide result', { json: true, mocked: true } ).then(() => { expect(getProxyResponse.mock.calls, 'to satisfy', [ [{}, { payload: { altered: true } }] ]); }); }); it('can edit the override headers before proxying a request', () => { return expect( { method: 'GET', url: '/proxy/editoverride' }, 'to provide result', { json: true, mocked: true } ).then(() => { expect(getProxyResponse.mock.calls, 'to satisfy', [ [ {}, { overrideHeaders: expect.it('to equal', { 'x-override-header': 'bar' }) } ] ]); }); }); it('can edit the host', () => { return expect( { method: 'GET', url: '/proxy/edittarget' }, 'to provide result', { json: true, mocked: true } ).then(() => { expect(getProxyResponse.mock.calls, 'to satisfy', [ [ {}, { url: { host: 'changed.test', pathname: '/proxy/edittarget' } } ] ]); }); }); it('can access URL parameters', () => { return expect( { method: 'GET', url: '/proxy/url/foo' }, 'to provide result', { param: 'foo' } ); }); it('returns a 500 and logs if an error is thrown in the handler', () => { (log.error as any).mockReset(); return expect( { method: 'POST', url: '/proxy/error' }, 'to provide response', { statusCode: 500, json: { statusCode: 500, message: 'Error in intervene handler function for route POST /proxy/error', error: 'Error: some handler error' } } ).then(() => { expect((log.error as any).mock.calls, 'to satisfy', [ [ 'Error in handler for route POST /proxy/error: Error: some handler error', expect.it('to have message', /some handler error/) ] ]); }); }); it('returns a 500 and logs if a handler returns a rejected promise', () => { (log.error as any).mockReset(); return expect( { method: 'POST', url: '/proxy/reject' }, 'to provide response', { statusCode: 500, json: { statusCode: 500, message: 'Error in intervene handler function for route POST /proxy/reject', error: 'Error: some handler rejected promise' } } ).then(() => { expect((log.error as any).mock.calls, 'to satisfy', [ [ 'Error in handler for route POST /proxy/reject: Error: some handler rejected promise', expect.it('to have message', /some handler rejected promise/) ] ]); }); }); it('returns a 500 if the proxy call rejects', () => { const e: any = new Error('connect ECONNREFUSED 10.10.10.10:55555'); e.code = 'ECONNREFUSED'; getProxyResponse.mockRejectedValue(e); return expect( { method: 'GET', url: '/proxy/direct' }, 'to provide response', { statusCode: 500, json: { message: 'Proxy call to target failed for route GET /proxy/direct', error: 'Error: connect ECONNREFUSED 10.10.10.10:55555' } } ).then(() => { expect((log.error as any).mock.calls, 'to satisfy', [ [ 'Proxy call to target failed for route GET /proxy/direct: Error: connect ECONNREFUSED 10.10.10.10:55555', expect.it( 'to have message', 'connect ECONNREFUSED 10.10.10.10:55555' ) ] ]); }); }); it('returns a 500 if the catch-all route proxy call rejects', () => { const e: any = new Error('connect ECONNREFUSED 10.10.10.10:55555'); e.code = 'ECONNREFUSED'; getProxyResponse.mockRejectedValue(e); return expect( { method: 'GET', url: '/passthrough/to/catchall' }, 'to provide response', { statusCode: 500, json: { message: 'Proxy call to target failed in catch-all route', error: 'Error: connect ECONNREFUSED 10.10.10.10:55555' } } ).then(() => { expect((log.error as any).mock.calls, 'to satisfy', [ [ 'Proxy call to target failed in catch-all route: Error: connect ECONNREFUSED 10.10.10.10:55555', expect.it( 'to have message', 'connect ECONNREFUSED 10.10.10.10:55555' ) ] ]); }); }); }); });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { StorageAccount, StorageAccountsListOptionalParams, StorageAccountsListByResourceGroupOptionalParams, StorageAccountCheckNameAvailabilityParameters, StorageAccountsCheckNameAvailabilityOptionalParams, StorageAccountsCheckNameAvailabilityResponse, StorageAccountCreateParameters, StorageAccountsCreateOptionalParams, StorageAccountsCreateResponse, StorageAccountsDeleteOptionalParams, StorageAccountsGetPropertiesOptionalParams, StorageAccountsGetPropertiesResponse, StorageAccountUpdateParameters, StorageAccountsUpdateOptionalParams, StorageAccountsUpdateResponse, StorageAccountsListKeysOptionalParams, StorageAccountsListKeysResponse, StorageAccountRegenerateKeyParameters, StorageAccountsRegenerateKeyOptionalParams, StorageAccountsRegenerateKeyResponse, AccountSasParameters, StorageAccountsListAccountSASOptionalParams, StorageAccountsListAccountSASResponse, ServiceSasParameters, StorageAccountsListServiceSASOptionalParams, StorageAccountsListServiceSASResponse, StorageAccountsFailoverOptionalParams, StorageAccountsHierarchicalNamespaceMigrationOptionalParams, StorageAccountsAbortHierarchicalNamespaceMigrationOptionalParams, BlobRestoreParameters, StorageAccountsRestoreBlobRangesOptionalParams, StorageAccountsRestoreBlobRangesResponse, StorageAccountsRevokeUserDelegationKeysOptionalParams } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a StorageAccounts. */ export interface StorageAccounts { /** * Lists all the storage accounts available under the subscription. Note that storage keys are not * returned; use the ListKeys operation for this. * @param options The options parameters. */ list( options?: StorageAccountsListOptionalParams ): PagedAsyncIterableIterator<StorageAccount>; /** * Lists all the storage accounts available under the given resource group. Note that storage keys are * not returned; use the ListKeys operation for this. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param options The options parameters. */ listByResourceGroup( resourceGroupName: string, options?: StorageAccountsListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<StorageAccount>; /** * Checks that the storage account name is valid and is not already in use. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param options The options parameters. */ checkNameAvailability( accountName: StorageAccountCheckNameAvailabilityParameters, options?: StorageAccountsCheckNameAvailabilityOptionalParams ): Promise<StorageAccountsCheckNameAvailabilityResponse>; /** * Asynchronously creates a new storage account with the specified parameters. If an account is already * created and a subsequent create request is issued with different properties, the account properties * will be updated. If an account is already created and a subsequent create or update request is * issued with the exact same set of properties, the request will succeed. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param parameters The parameters to provide for the created account. * @param options The options parameters. */ beginCreate( resourceGroupName: string, accountName: string, parameters: StorageAccountCreateParameters, options?: StorageAccountsCreateOptionalParams ): Promise< PollerLike< PollOperationState<StorageAccountsCreateResponse>, StorageAccountsCreateResponse > >; /** * Asynchronously creates a new storage account with the specified parameters. If an account is already * created and a subsequent create request is issued with different properties, the account properties * will be updated. If an account is already created and a subsequent create or update request is * issued with the exact same set of properties, the request will succeed. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param parameters The parameters to provide for the created account. * @param options The options parameters. */ beginCreateAndWait( resourceGroupName: string, accountName: string, parameters: StorageAccountCreateParameters, options?: StorageAccountsCreateOptionalParams ): Promise<StorageAccountsCreateResponse>; /** * Deletes a storage account in Microsoft Azure. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param options The options parameters. */ delete( resourceGroupName: string, accountName: string, options?: StorageAccountsDeleteOptionalParams ): Promise<void>; /** * Returns the properties for the specified storage account including but not limited to name, SKU * name, location, and account status. The ListKeys operation should be used to retrieve storage keys. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param options The options parameters. */ getProperties( resourceGroupName: string, accountName: string, options?: StorageAccountsGetPropertiesOptionalParams ): Promise<StorageAccountsGetPropertiesResponse>; /** * The update operation can be used to update the SKU, encryption, access tier, or tags for a storage * account. It can also be used to map the account to a custom domain. Only one custom domain is * supported per storage account; the replacement/change of custom domain is not supported. In order to * replace an old custom domain, the old value must be cleared/unregistered before a new value can be * set. The update of multiple properties is supported. This call does not change the storage keys for * the account. If you want to change the storage account keys, use the regenerate keys operation. The * location and name of the storage account cannot be changed after creation. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param parameters The parameters to provide for the updated account. * @param options The options parameters. */ update( resourceGroupName: string, accountName: string, parameters: StorageAccountUpdateParameters, options?: StorageAccountsUpdateOptionalParams ): Promise<StorageAccountsUpdateResponse>; /** * Lists the access keys or Kerberos keys (if active directory enabled) for the specified storage * account. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param options The options parameters. */ listKeys( resourceGroupName: string, accountName: string, options?: StorageAccountsListKeysOptionalParams ): Promise<StorageAccountsListKeysResponse>; /** * Regenerates one of the access keys or Kerberos keys for the specified storage account. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param regenerateKey Specifies name of the key which should be regenerated -- key1, key2, kerb1, * kerb2. * @param options The options parameters. */ regenerateKey( resourceGroupName: string, accountName: string, regenerateKey: StorageAccountRegenerateKeyParameters, options?: StorageAccountsRegenerateKeyOptionalParams ): Promise<StorageAccountsRegenerateKeyResponse>; /** * List SAS credentials of a storage account. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param parameters The parameters to provide to list SAS credentials for the storage account. * @param options The options parameters. */ listAccountSAS( resourceGroupName: string, accountName: string, parameters: AccountSasParameters, options?: StorageAccountsListAccountSASOptionalParams ): Promise<StorageAccountsListAccountSASResponse>; /** * List service SAS credentials of a specific resource. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param parameters The parameters to provide to list service SAS credentials. * @param options The options parameters. */ listServiceSAS( resourceGroupName: string, accountName: string, parameters: ServiceSasParameters, options?: StorageAccountsListServiceSASOptionalParams ): Promise<StorageAccountsListServiceSASResponse>; /** * Failover request can be triggered for a storage account in case of availability issues. The failover * occurs from the storage account's primary cluster to secondary cluster for RA-GRS accounts. The * secondary cluster will become primary after failover. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param options The options parameters. */ beginFailover( resourceGroupName: string, accountName: string, options?: StorageAccountsFailoverOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Failover request can be triggered for a storage account in case of availability issues. The failover * occurs from the storage account's primary cluster to secondary cluster for RA-GRS accounts. The * secondary cluster will become primary after failover. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param options The options parameters. */ beginFailoverAndWait( resourceGroupName: string, accountName: string, options?: StorageAccountsFailoverOptionalParams ): Promise<void>; /** * Live Migration of storage account to enable Hns * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param requestType Required. Hierarchical namespace migration type can either be a hierarchical * namespace validation request 'HnsOnValidationRequest' or a hydration request * 'HnsOnHydrationRequest'. The validation request will validate the migration whereas the hydration * request will migrate the account. * @param options The options parameters. */ beginHierarchicalNamespaceMigration( resourceGroupName: string, accountName: string, requestType: string, options?: StorageAccountsHierarchicalNamespaceMigrationOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Live Migration of storage account to enable Hns * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param requestType Required. Hierarchical namespace migration type can either be a hierarchical * namespace validation request 'HnsOnValidationRequest' or a hydration request * 'HnsOnHydrationRequest'. The validation request will validate the migration whereas the hydration * request will migrate the account. * @param options The options parameters. */ beginHierarchicalNamespaceMigrationAndWait( resourceGroupName: string, accountName: string, requestType: string, options?: StorageAccountsHierarchicalNamespaceMigrationOptionalParams ): Promise<void>; /** * Abort live Migration of storage account to enable Hns * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param options The options parameters. */ beginAbortHierarchicalNamespaceMigration( resourceGroupName: string, accountName: string, options?: StorageAccountsAbortHierarchicalNamespaceMigrationOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Abort live Migration of storage account to enable Hns * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param options The options parameters. */ beginAbortHierarchicalNamespaceMigrationAndWait( resourceGroupName: string, accountName: string, options?: StorageAccountsAbortHierarchicalNamespaceMigrationOptionalParams ): Promise<void>; /** * Restore blobs in the specified blob ranges * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param parameters The parameters to provide for restore blob ranges. * @param options The options parameters. */ beginRestoreBlobRanges( resourceGroupName: string, accountName: string, parameters: BlobRestoreParameters, options?: StorageAccountsRestoreBlobRangesOptionalParams ): Promise< PollerLike< PollOperationState<StorageAccountsRestoreBlobRangesResponse>, StorageAccountsRestoreBlobRangesResponse > >; /** * Restore blobs in the specified blob ranges * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param parameters The parameters to provide for restore blob ranges. * @param options The options parameters. */ beginRestoreBlobRangesAndWait( resourceGroupName: string, accountName: string, parameters: BlobRestoreParameters, options?: StorageAccountsRestoreBlobRangesOptionalParams ): Promise<StorageAccountsRestoreBlobRangesResponse>; /** * Revoke user delegation keys. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param options The options parameters. */ revokeUserDelegationKeys( resourceGroupName: string, accountName: string, options?: StorageAccountsRevokeUserDelegationKeysOptionalParams ): Promise<void>; }
the_stack
import { ComponentFixture, TestBed, waitForAsync } from "@angular/core/testing"; import { MdlSelectComponent } from "./select.component"; import { Component } from "@angular/core"; import { By } from "@angular/platform-browser"; import { FormControl, FormGroup, ReactiveFormsModule } from "@angular/forms"; import { KEYS } from "./keyboard"; import { MdlSelectModule } from "./select.module"; @Component({ // eslint-disable-next-line selector: 'test-disabled-component', template: ` <form [formGroup]="form"> <mdl-select formControlName="personId"> <mdl-option *ngFor="let p of people" [value]="p.id">{{ p.name }}</mdl-option> </mdl-select> </form> `, }) class TestDisabledComponent { form: FormGroup; personId: FormControl = new FormControl({ value: 1, disabled: true }); people: unknown[] = [ { id: 1, name: "Bryan Cranston" }, { id: 2, name: "Aaron Paul" }, { id: 3, name: "Bob Odenkirk" }, ]; constructor() { this.form = new FormGroup({ personId: this.personId, }); } } @Component({ // eslint-disable-next-line selector: 'test-single-component', template: ` <mdl-select label="{{ label }}" floating-label [autocomplete]="true" [(ngModel)]="selectedValue" > <mdl-option *ngFor="let p of people" [value]="p.id">{{ p.name }}</mdl-option> </mdl-select> `, }) class TestAutoCompleteComponent { selectedValue: unknown = null; label = "floating label"; people: unknown[] = [ { id: 1, name: "Bryan Cranston" }, { id: 2, name: "Aaron Paul" }, { id: 3, name: "Bob Odenkirk" }, ]; } @Component({ // eslint-disable-next-line selector: 'test-single-component', template: ` <mdl-select label="{{ label }}" floating-label [(ngModel)]="personId"> <mdl-option *ngFor="let p of people" [value]="p.id">{{ p.name }}</mdl-option> </mdl-select> `, }) class TestSingleComponent { personId = 1; label = "floating label"; people: unknown[] = [ { id: 1, name: "Bryan Cranston" }, { id: 2, name: "Aaron Paul" }, { id: 3, name: "Bob Odenkirk" }, ]; } @Component({ // eslint-disable-next-line selector: 'test-single-component-no-model', template: ` <mdl-select placeholder="{{ placeholder }}"> <mdl-option value="first">Bryan Cranston</mdl-option> <mdl-option value="second">Aaron Paul</mdl-option> <mdl-option value="third">Bob Odenkirk</mdl-option> </mdl-select> `, }) class TestSingleComponentNoModelComponent { placeholder = "no model"; } @Component({ // eslint-disable-next-line selector: 'test-multiple-component', template: ` <mdl-select [(ngModel)]="personIds" [multiple]="true"> <mdl-option *ngFor="let p of people" [value]="p.id">{{ p.name }}</mdl-option> </mdl-select> `, }) class TestMultipleComponent { personIds: number[] = [1, 2]; people: unknown[] = [ { id: 1, name: "Bryan Cranston" }, { id: 2, name: "Aaron Paul" }, { id: 3, name: "Bob Odenkirk" }, ]; } @Component({ // eslint-disable-next-line selector: 'test-object-component', template: ` <mdl-select [(ngModel)]="personObjs" [multiple]="true"> <mdl-option *ngFor="let p of people" [value]="{ i: p.id, n: p.name }">{{ p.name }}</mdl-option> </mdl-select> `, }) class TestObjectComponent { personObjs: unknown[] = [ { i: 1, n: "Bryan Cranston" }, { i: 2, n: "Aaron Paul" }, ]; people: unknown[] = [ { id: 1, name: "Bryan Cranston" }, { id: 2, name: "Aaron Paul" }, { id: 3, name: "Bob Odenkirk" }, ]; } // based on @angular/cdk export const createKeyboardEvent = ( type: string, keyCode: number, target?: Element, key?: string ): KeyboardEvent => { // eslint-disable-next-line const event = document.createEvent('KeyboardEvent') as any; // Firefox does not support `initKeyboardEvent`, but supports `initKeyEvent`. if (event.initKeyEvent) { event.initKeyEvent(type, true, true, window, 0, 0, 0, 0, 0, keyCode); } else { // eslint-disable-next-line event.initKeyboardEvent(type, true, true, window, 0, key, 0, '', false); } // Webkit Browsers don't set the keyCode when calling the init function. // See related bug https://bugs.webkit.org/show_bug.cgi?id=16735 Object.defineProperties(event, { keyCode: { get: () => keyCode }, key: { get: () => key }, target: { get: () => target }, }); return event; }; // based on @angular/cdk export const dispatchEvent = (node: Node | Window, event: Event): Event => { node.dispatchEvent(event); return event; }; // eslint-disable-next-line export const dispatchKeydownEvent = (node: any, keycode: number) => dispatchEvent(node, createKeyboardEvent('keydown', keycode, node)); describe("MdlSelect", () => { describe("single", () => { let fixture: ComponentFixture<TestSingleComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [MdlSelectModule.forRoot()], declarations: [TestSingleComponent], }); TestBed.compileComponents().then(() => { fixture = TestBed.createComponent(TestSingleComponent); fixture.detectChanges(); }); }) ); it( "should support floating-label attr", waitForAsync(() => { const selectComponent = fixture.debugElement.query( By.directive(MdlSelectComponent) ); const selectNativeElement = selectComponent.nativeElement; expect( selectNativeElement.classList.contains("mdl-select--floating-label") ).toBe(true, "did not has css class mdl-select--floating-label"); expect( selectComponent.nativeElement.querySelector(".mdl-textfield__label") .innerText ).toBe( selectComponent.componentInstance.label, "did not set correct label text" ); }) ); it( "should create the component and add the mdl-select css class", waitForAsync(() => { const selectComponent = fixture.debugElement.query( By.directive(MdlSelectComponent) ); const selectNativeElement = selectComponent.nativeElement; expect(selectNativeElement.classList.contains("mdl-select")).toBe( true, "did not has css class mdl-select" ); }) ); it( "should support ngModel", waitForAsync(() => { const testInstance = fixture.componentInstance; const selectComponent = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; fixture.whenStable().then(() => { expect(selectComponent.ngModel).toEqual(1, "did not init ngModel"); testInstance.personId = 2; fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponent.ngModel).toEqual( 2, "did not update ngModel" ); }); }); }) ); it( "should reset ngModel", waitForAsync(() => { const selectComponentInstance = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( 1, "did not init ngModel" ); selectComponentInstance.reset(); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( "", "did not reset ngModel" ); }); }); }) ); it( "should bind options on options change", waitForAsync(() => { const testInstance = fixture.componentInstance; const selectComponentInstance = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; spyOn(selectComponentInstance, "bindOptions").and.callThrough(); testInstance.people.push({ id: 4, name: "Gary Cole" }); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.bindOptions).toHaveBeenCalled(); expect(selectComponentInstance.textByValue[4]).toEqual("Gary Cole"); }); }) ); it( "focus should have keyboard events", waitForAsync(() => { jasmine.clock().uninstall(); jasmine.clock().install(); const selectComponent = fixture.debugElement.query( By.directive(MdlSelectComponent) ); const selectNativeElement = selectComponent.nativeElement; const selectComponentInstance = selectComponent.componentInstance; spyOn(selectComponentInstance, "onKeyDown").and.callThrough(); spyOn(selectComponentInstance, "onArrow").and.callThrough(); // console.log(selectNativeElement.querySelector("span[tabindex]")); // document.body.appendChild(selectNativeElement); selectNativeElement.querySelector("span[tabindex]").focus(); jasmine.clock().tick(500); // onFocus timeout is cleared fixture.detectChanges(); expect(selectComponentInstance.popoverComponent.isVisible).toEqual( true, "toggle did not update isVisible to true" ); dispatchKeydownEvent( selectNativeElement.querySelector("span"), KEYS.downArrow ); dispatchKeydownEvent( selectNativeElement.querySelector("span"), KEYS.upArrow ); dispatchKeydownEvent( selectNativeElement.querySelector("span"), KEYS.tab ); fixture.detectChanges(); fixture.debugElement.nativeElement.click(); // click outside select to close fixture.detectChanges(); expect(selectComponentInstance.popoverComponent.isVisible).toEqual( false, "toggle did not update isVisible to false" ); expect(selectComponentInstance.onKeyDown).toHaveBeenCalled(); // eslint-disable-next-line expect(selectComponentInstance.onArrow.calls.allArgs().map((args: any) => args[1])).toEqual([1, -1]); jasmine.clock().uninstall(); }) ); it( "should auto-select searched options", waitForAsync(() => { jasmine.clock().uninstall(); jasmine.clock().install(); const selectComponent = fixture.debugElement.query( By.directive(MdlSelectComponent) ); const selectNativeElement = selectComponent.nativeElement; const selectComponentInstance = selectComponent.componentInstance; spyOn(selectComponentInstance, "onSelect").and.callThrough(); spyOn(selectComponentInstance, "onCharacterKeydown").and.callThrough(); selectNativeElement.querySelector("span[tabindex]").focus(); jasmine.clock().tick(500); // onFocus timeout is cleared fixture.detectChanges(); expect(selectComponentInstance.ngModel).toEqual(1); dispatchKeydownEvent(selectNativeElement, KEYS.b); fixture.detectChanges(); expect(selectComponentInstance.onSelect).not.toHaveBeenCalled(); expect(selectComponentInstance.onCharacterKeydown).toHaveBeenCalled(); expect(selectComponentInstance.ngModel).toEqual(1); dispatchKeydownEvent(selectNativeElement, KEYS.o); fixture.detectChanges(); expect(selectComponentInstance.onSelect).toHaveBeenCalled(); expect(selectComponentInstance.searchQuery).toEqual("bo"); expect(selectComponentInstance.ngModel).toEqual(3); // B and O typed, so 'Bob Odenkirk' selected jasmine.clock().tick(300); // search query timeout is cleared expect(selectComponentInstance.searchQuery).toEqual(""); dispatchKeydownEvent(selectNativeElement, KEYS.a); fixture.detectChanges(); expect(selectComponentInstance.onSelect).toHaveBeenCalled(); expect(selectComponentInstance.ngModel).toEqual(2); // A typed, so 'Aaron Paul' selected jasmine.clock().uninstall(); }) ); }); describe("single, without model", () => { let fixture: ComponentFixture<TestSingleComponentNoModelComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [MdlSelectModule.forRoot()], declarations: [TestSingleComponentNoModelComponent], }); TestBed.compileComponents().then(() => { fixture = TestBed.createComponent( TestSingleComponentNoModelComponent ); fixture.detectChanges(); }); }) ); it( "should select vlaue and display text", waitForAsync(() => { const selectComponentInstance = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; const noModelData = [ { value: "first", text: "Bryan Cranston" }, { value: "second", text: "Aaron Paul" }, { value: "third", text: "Bob Odenkirk" }, ]; selectComponentInstance.onSelect(noModelData[0].value); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.text).toEqual(noModelData[0].text); selectComponentInstance.onSelect(noModelData[1].value); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.text).toEqual(noModelData[1].text); }); }); }) ); }); describe("disabled", () => { let fixture: ComponentFixture<TestDisabledComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [MdlSelectModule.forRoot(), ReactiveFormsModule], declarations: [TestDisabledComponent], }); TestBed.compileComponents().then(() => { fixture = TestBed.createComponent(TestDisabledComponent); fixture.detectChanges(); }); }) ); it( "should create the component and make it disabled", waitForAsync(() => { const selectComponent = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; fixture.whenStable().then(() => { expect(selectComponent.disabled).toBe( true, "select field should be disabled" ); }); }) ); }); describe("autocomplete", () => { let fixture: ComponentFixture<TestAutoCompleteComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [MdlSelectModule.forRoot()], declarations: [TestAutoCompleteComponent], }); TestBed.compileComponents().then(() => { fixture = TestBed.createComponent(TestAutoCompleteComponent); fixture.detectChanges(); }); }) ); it( "should not make autoselection when it's on", waitForAsync(() => { const selectComponent = fixture.debugElement.query( By.directive(MdlSelectComponent) ); const selectNativeElement = selectComponent.nativeElement; const selectComponentInstance = selectComponent.componentInstance; spyOn(selectComponentInstance, "onSelect").and.callThrough(); spyOn(selectComponentInstance, "onCharacterKeydown").and.callThrough(); selectNativeElement.querySelector("input").focus(); fixture.detectChanges(); expect(selectComponentInstance.ngModel).toBeNull(); dispatchKeydownEvent(selectNativeElement, KEYS.b); fixture.detectChanges(); expect(selectComponentInstance.ngModel).toBeNull(); }) ); it( "should make autoselection on enter", waitForAsync(() => { const selectComponent = fixture.debugElement.query( By.directive(MdlSelectComponent) ); const selectNativeElement = selectComponent.nativeElement; const selectComponentInstance = selectComponent.componentInstance; const input = selectNativeElement.querySelector("input"); spyOn(selectComponentInstance, "onSelect").and.callThrough(); spyOn(selectComponentInstance, "onCharacterKeydown").and.callThrough(); input.focus(); fixture.detectChanges(); expect(selectComponentInstance.ngModel).toBeNull(); dispatchEvent(input, createKeyboardEvent("keyup", KEYS.b, input)); fixture.detectChanges(); expect(selectComponentInstance.ngModel).toBeNull(); dispatchEvent(input, createKeyboardEvent("keyup", KEYS.enter, input)); fixture.detectChanges(); expect(selectComponentInstance.ngModel).toEqual(1); }) ); it( "should make input writable when autoselection is off", waitForAsync(() => { const selectComponent = fixture.debugElement.query( By.directive(MdlSelectComponent) ); const selectNativeElement = selectComponent.nativeElement; expect(selectNativeElement.querySelector("input").readonly).toBeFalsy(); }) ); }); describe("multiple", () => { let fixture: ComponentFixture<TestMultipleComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [MdlSelectModule.forRoot()], declarations: [TestMultipleComponent], }); TestBed.compileComponents().then(() => { fixture = TestBed.createComponent(TestMultipleComponent); fixture.detectChanges(); }); }) ); it( "should create the component and add the mdl-select css class", waitForAsync(() => { const selectComponent = fixture.debugElement.query( By.directive(MdlSelectComponent) ); const selectNativeElement = selectComponent.nativeElement; expect(selectNativeElement.classList.contains("mdl-select")).toBe( true, "did not have css class mdl-select" ); }) ); it( "should support ngModel", waitForAsync(() => { const testInstance = fixture.componentInstance; const selectComponentInstance = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [1, 2], "did not init ngModel" ); testInstance.personIds = [1]; fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [1], "did not update ngModel" ); }); }); }) ); it( "should reset ngModel", waitForAsync(() => { const selectComponentInstance = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; spyOn(selectComponentInstance, "bindOptions"); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [1, 2], "did not init ngModel" ); selectComponentInstance.reset(); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [], "did not reset ngModel" ); }); }); }) ); it( "should select and deselect value", waitForAsync(() => { const selectComponentInstance = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; expect(selectComponentInstance.multiple).toBe(true, "is not multiple"); selectComponentInstance.onSelect(3); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [1, 2, 3], "did not update ngModel on select 3" ); selectComponentInstance.onSelect(3); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [1, 2], "did not update ngModel on deselect 3" ); }); }); }) ); it( "should bind options on options change", waitForAsync(() => { const testInstance = fixture.componentInstance; const selectComponentInstance = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; spyOn(selectComponentInstance, "bindOptions").and.callThrough(); testInstance.people.push({ id: 4, name: "Gary Cole" }); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.bindOptions).toHaveBeenCalled(); expect(selectComponentInstance.textByValue[4]).toEqual("Gary Cole"); }); }) ); }); describe("object", () => { let fixture: ComponentFixture<TestObjectComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [MdlSelectModule.forRoot()], declarations: [TestObjectComponent], }); TestBed.compileComponents().then(() => { fixture = TestBed.createComponent(TestObjectComponent); fixture.detectChanges(); }); }) ); it( "should support ngModel", waitForAsync(() => { const testInstance = fixture.componentInstance; const selectComponentInstance = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [ { i: 1, n: "Bryan Cranston" }, { i: 2, n: "Aaron Paul" }, ], "did not init ngModel" ); testInstance.personObjs = [{ i: 1, n: "Bryan Cranston" }]; fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [{ i: 1, n: "Bryan Cranston" }], "did not update ngModel" ); }); }); }) ); it( "should reset ngModel", waitForAsync(() => { const selectComponentInstance = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; spyOn(selectComponentInstance, "bindOptions"); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [ { i: 1, n: "Bryan Cranston" }, { i: 2, n: "Aaron Paul" }, ], "did not init ngModel" ); selectComponentInstance.reset(); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [], "did not reset ngModel" ); }); }); }) ); it( "should select and deselect value", waitForAsync(() => { const selectComponentInstance = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; const arrWith3Obj = [ { i: 1, n: "Bryan Cranston" }, { i: 2, n: "Aaron Paul" }, { i: 3, n: "Bob Odenkirk" }, ]; expect(selectComponentInstance.multiple).toBe(true, "is not multiple"); selectComponentInstance.onSelect(arrWith3Obj[2]); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( arrWith3Obj, "did not update ngModel on select 3" ); selectComponentInstance.onSelect(arrWith3Obj[2]); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [arrWith3Obj[0], arrWith3Obj[1]], "did not update ngModel on deselect 3" ); selectComponentInstance.onSelect(arrWith3Obj[1]); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.ngModel).toEqual( [arrWith3Obj[0]], "did not update ngModel on deselect 3" ); }); }); }); }) ); it( "should bind options on options change", waitForAsync(() => { const testInstance = fixture.componentInstance; const selectComponentInstance = fixture.debugElement.query( By.directive(MdlSelectComponent) ).componentInstance; spyOn(selectComponentInstance, "bindOptions").and.callThrough(); testInstance.people.push({ id: 4, name: "Gary Cole" }); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectComponentInstance.bindOptions).toHaveBeenCalled(); expect( selectComponentInstance.textByValue[ JSON.stringify({ i: 4, n: "Gary Cole" }) ] ).toEqual("Gary Cole"); }); }) ); }); });
the_stack
// Please don't change this file manually but run `prisma generate` to update it. // For more information, please read the docs: https://www.prisma.io/docs/prisma-client/ export const typeDefs = /* GraphQL */ `type AggregatePost { count: Int! } type AggregateUser { count: Int! } type BatchPayload { count: Long! } scalar DateTime scalar Long type Mutation { createPost(data: PostCreateInput!): Post! updatePost(data: PostUpdateInput!, where: PostWhereUniqueInput!): Post updateManyPosts(data: PostUpdateManyMutationInput!, where: PostWhereInput): BatchPayload! upsertPost(where: PostWhereUniqueInput!, create: PostCreateInput!, update: PostUpdateInput!): Post! deletePost(where: PostWhereUniqueInput!): Post deleteManyPosts(where: PostWhereInput): BatchPayload! createUser(data: UserCreateInput!): User! updateUser(data: UserUpdateInput!, where: UserWhereUniqueInput!): User updateManyUsers(data: UserUpdateManyMutationInput!, where: UserWhereInput): BatchPayload! upsertUser(where: UserWhereUniqueInput!, create: UserCreateInput!, update: UserUpdateInput!): User! deleteUser(where: UserWhereUniqueInput!): User deleteManyUsers(where: UserWhereInput): BatchPayload! } enum MutationType { CREATED UPDATED DELETED } interface Node { id: ID! } type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: String endCursor: String } type Post { id: ID! title: String! body: String author: User! createdAt: DateTime! updatedAt: DateTime! } type PostConnection { pageInfo: PageInfo! edges: [PostEdge]! aggregate: AggregatePost! } input PostCreateInput { id: ID title: String! body: String author: UserCreateOneWithoutPostInput! } input PostCreateManyWithoutAuthorInput { create: [PostCreateWithoutAuthorInput!] connect: [PostWhereUniqueInput!] } input PostCreateWithoutAuthorInput { id: ID title: String! body: String } type PostEdge { node: Post! cursor: String! } enum PostOrderByInput { id_ASC id_DESC title_ASC title_DESC body_ASC body_DESC createdAt_ASC createdAt_DESC updatedAt_ASC updatedAt_DESC } type PostPreviousValues { id: ID! title: String! body: String createdAt: DateTime! updatedAt: DateTime! } input PostScalarWhereInput { id: ID id_not: ID id_in: [ID!] id_not_in: [ID!] id_lt: ID id_lte: ID id_gt: ID id_gte: ID id_contains: ID id_not_contains: ID id_starts_with: ID id_not_starts_with: ID id_ends_with: ID id_not_ends_with: ID title: String title_not: String title_in: [String!] title_not_in: [String!] title_lt: String title_lte: String title_gt: String title_gte: String title_contains: String title_not_contains: String title_starts_with: String title_not_starts_with: String title_ends_with: String title_not_ends_with: String body: String body_not: String body_in: [String!] body_not_in: [String!] body_lt: String body_lte: String body_gt: String body_gte: String body_contains: String body_not_contains: String body_starts_with: String body_not_starts_with: String body_ends_with: String body_not_ends_with: String createdAt: DateTime createdAt_not: DateTime createdAt_in: [DateTime!] createdAt_not_in: [DateTime!] createdAt_lt: DateTime createdAt_lte: DateTime createdAt_gt: DateTime createdAt_gte: DateTime updatedAt: DateTime updatedAt_not: DateTime updatedAt_in: [DateTime!] updatedAt_not_in: [DateTime!] updatedAt_lt: DateTime updatedAt_lte: DateTime updatedAt_gt: DateTime updatedAt_gte: DateTime AND: [PostScalarWhereInput!] OR: [PostScalarWhereInput!] NOT: [PostScalarWhereInput!] } type PostSubscriptionPayload { mutation: MutationType! node: Post updatedFields: [String!] previousValues: PostPreviousValues } input PostSubscriptionWhereInput { mutation_in: [MutationType!] updatedFields_contains: String updatedFields_contains_every: [String!] updatedFields_contains_some: [String!] node: PostWhereInput AND: [PostSubscriptionWhereInput!] OR: [PostSubscriptionWhereInput!] NOT: [PostSubscriptionWhereInput!] } input PostUpdateInput { title: String body: String author: UserUpdateOneRequiredWithoutPostInput } input PostUpdateManyDataInput { title: String body: String } input PostUpdateManyMutationInput { title: String body: String } input PostUpdateManyWithoutAuthorInput { create: [PostCreateWithoutAuthorInput!] delete: [PostWhereUniqueInput!] connect: [PostWhereUniqueInput!] set: [PostWhereUniqueInput!] disconnect: [PostWhereUniqueInput!] update: [PostUpdateWithWhereUniqueWithoutAuthorInput!] upsert: [PostUpsertWithWhereUniqueWithoutAuthorInput!] deleteMany: [PostScalarWhereInput!] updateMany: [PostUpdateManyWithWhereNestedInput!] } input PostUpdateManyWithWhereNestedInput { where: PostScalarWhereInput! data: PostUpdateManyDataInput! } input PostUpdateWithoutAuthorDataInput { title: String body: String } input PostUpdateWithWhereUniqueWithoutAuthorInput { where: PostWhereUniqueInput! data: PostUpdateWithoutAuthorDataInput! } input PostUpsertWithWhereUniqueWithoutAuthorInput { where: PostWhereUniqueInput! update: PostUpdateWithoutAuthorDataInput! create: PostCreateWithoutAuthorInput! } input PostWhereInput { id: ID id_not: ID id_in: [ID!] id_not_in: [ID!] id_lt: ID id_lte: ID id_gt: ID id_gte: ID id_contains: ID id_not_contains: ID id_starts_with: ID id_not_starts_with: ID id_ends_with: ID id_not_ends_with: ID title: String title_not: String title_in: [String!] title_not_in: [String!] title_lt: String title_lte: String title_gt: String title_gte: String title_contains: String title_not_contains: String title_starts_with: String title_not_starts_with: String title_ends_with: String title_not_ends_with: String body: String body_not: String body_in: [String!] body_not_in: [String!] body_lt: String body_lte: String body_gt: String body_gte: String body_contains: String body_not_contains: String body_starts_with: String body_not_starts_with: String body_ends_with: String body_not_ends_with: String author: UserWhereInput createdAt: DateTime createdAt_not: DateTime createdAt_in: [DateTime!] createdAt_not_in: [DateTime!] createdAt_lt: DateTime createdAt_lte: DateTime createdAt_gt: DateTime createdAt_gte: DateTime updatedAt: DateTime updatedAt_not: DateTime updatedAt_in: [DateTime!] updatedAt_not_in: [DateTime!] updatedAt_lt: DateTime updatedAt_lte: DateTime updatedAt_gt: DateTime updatedAt_gte: DateTime AND: [PostWhereInput!] OR: [PostWhereInput!] NOT: [PostWhereInput!] } input PostWhereUniqueInput { id: ID } type Query { post(where: PostWhereUniqueInput!): Post posts(where: PostWhereInput, orderBy: PostOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Post]! postsConnection(where: PostWhereInput, orderBy: PostOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): PostConnection! user(where: UserWhereUniqueInput!): User users(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [User]! usersConnection(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): UserConnection! node(id: ID!): Node } type Subscription { post(where: PostSubscriptionWhereInput): PostSubscriptionPayload user(where: UserSubscriptionWhereInput): UserSubscriptionPayload } type User { id: ID! email: String! password: String! post(where: PostWhereInput, orderBy: PostOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Post!] createdAt: DateTime! updatedAt: DateTime! } type UserConnection { pageInfo: PageInfo! edges: [UserEdge]! aggregate: AggregateUser! } input UserCreateInput { id: ID email: String! password: String! post: PostCreateManyWithoutAuthorInput } input UserCreateOneWithoutPostInput { create: UserCreateWithoutPostInput connect: UserWhereUniqueInput } input UserCreateWithoutPostInput { id: ID email: String! password: String! } type UserEdge { node: User! cursor: String! } enum UserOrderByInput { id_ASC id_DESC email_ASC email_DESC password_ASC password_DESC createdAt_ASC createdAt_DESC updatedAt_ASC updatedAt_DESC } type UserPreviousValues { id: ID! email: String! password: String! createdAt: DateTime! updatedAt: DateTime! } type UserSubscriptionPayload { mutation: MutationType! node: User updatedFields: [String!] previousValues: UserPreviousValues } input UserSubscriptionWhereInput { mutation_in: [MutationType!] updatedFields_contains: String updatedFields_contains_every: [String!] updatedFields_contains_some: [String!] node: UserWhereInput AND: [UserSubscriptionWhereInput!] OR: [UserSubscriptionWhereInput!] NOT: [UserSubscriptionWhereInput!] } input UserUpdateInput { email: String password: String post: PostUpdateManyWithoutAuthorInput } input UserUpdateManyMutationInput { email: String password: String } input UserUpdateOneRequiredWithoutPostInput { create: UserCreateWithoutPostInput update: UserUpdateWithoutPostDataInput upsert: UserUpsertWithoutPostInput connect: UserWhereUniqueInput } input UserUpdateWithoutPostDataInput { email: String password: String } input UserUpsertWithoutPostInput { update: UserUpdateWithoutPostDataInput! create: UserCreateWithoutPostInput! } input UserWhereInput { id: ID id_not: ID id_in: [ID!] id_not_in: [ID!] id_lt: ID id_lte: ID id_gt: ID id_gte: ID id_contains: ID id_not_contains: ID id_starts_with: ID id_not_starts_with: ID id_ends_with: ID id_not_ends_with: ID email: String email_not: String email_in: [String!] email_not_in: [String!] email_lt: String email_lte: String email_gt: String email_gte: String email_contains: String email_not_contains: String email_starts_with: String email_not_starts_with: String email_ends_with: String email_not_ends_with: String password: String password_not: String password_in: [String!] password_not_in: [String!] password_lt: String password_lte: String password_gt: String password_gte: String password_contains: String password_not_contains: String password_starts_with: String password_not_starts_with: String password_ends_with: String password_not_ends_with: String post_every: PostWhereInput post_some: PostWhereInput post_none: PostWhereInput createdAt: DateTime createdAt_not: DateTime createdAt_in: [DateTime!] createdAt_not_in: [DateTime!] createdAt_lt: DateTime createdAt_lte: DateTime createdAt_gt: DateTime createdAt_gte: DateTime updatedAt: DateTime updatedAt_not: DateTime updatedAt_in: [DateTime!] updatedAt_not_in: [DateTime!] updatedAt_lt: DateTime updatedAt_lte: DateTime updatedAt_gt: DateTime updatedAt_gte: DateTime AND: [UserWhereInput!] OR: [UserWhereInput!] NOT: [UserWhereInput!] } input UserWhereUniqueInput { id: ID email: String } `
the_stack
import * as _ from 'lodash-es'; import * as React from 'react'; import { Trans, useTranslation } from 'react-i18next'; import { TextArea } from '@patternfly/react-core'; import { RadioInput } from '../../radio'; import { ExpandCollapse, ExternalLink } from '../../utils'; import { SaveAsDefaultCheckbox, SendResolvedAlertsCheckbox, FormProps, } from './alert-manager-receiver-forms'; const GLOBAL_FIELDS = [ 'slack_api_url', 'slack_send_resolved', 'slack_username', 'slack_icon_emoji', 'slack_icon_url', 'slack_link_names', 'slack_title', 'slack_text', ]; export const Form: React.FC<FormProps> = ({ globals, formValues, dispatchFormChange }) => { const { t } = useTranslation(); return ( <div data-test-id="slack-receiver-form"> <div className="form-group"> <label data-test-id="api-url-label" className="control-label co-required" htmlFor="slack-api-url" > {t('public~Slack API URL')} </label> <div className="row"> <div className="col-sm-7"> <input className="pf-c-form-control" type="text" id="slack-api-url" aria-describedby="slack-api-url-help" data-test-id="slack-api-url" value={formValues.slack_api_url} onChange={(e) => dispatchFormChange({ type: 'setFormValues', payload: { slack_api_url: e.target.value }, }) } /> </div> <div className="col-sm-5"> <SaveAsDefaultCheckbox formField="slackSaveAsDefault" disabled={formValues.slack_api_url === globals?.slack_api_url} label={t('public~Save as default Slack API URL')} formValues={formValues} dispatchFormChange={dispatchFormChange} tooltip={t( 'public~Checking this box will write the API URL to the global section of the configuration file where it will become the default API URL for future Slack receivers.', )} /> </div> </div> <div className="help-block" id="slack-api-url-help"> {t('public~The URL of the Slack webhook.')} </div> </div> <div className="form-group"> <label className="control-label co-required" htmlFor="slack-channel"> {t('public~Channel')} </label> <input className="pf-c-form-control" type="text" id="slack-channel" aria-describedby="slack-channel-help" data-test-id="slack-channel" value={formValues.slackChannel} onChange={(e) => dispatchFormChange({ type: 'setFormValues', payload: { slackChannel: e.target.value }, }) } /> <div className="help-block" id="slack-channel-help"> {t('public~The Slack channel or user to send notifications to.')} </div> </div> <div className="form-group"> <ExpandCollapse textCollapsed={t('public~Show advanced configuration')} textExpanded={t('public~Hide advanced configuration')} > <div className="co-form-subsection"> <div className="form-group"> <SendResolvedAlertsCheckbox formField="slack_send_resolved" formValues={formValues} dispatchFormChange={dispatchFormChange} /> </div> <div className="form-group"> <label className="control-label" htmlFor="slack-icon-type"> {t('public~Icon')} &nbsp; <RadioInput title={t('public~URL')} name="slackIconType" id="slack-icon-type" value="url" onChange={(e) => dispatchFormChange({ type: 'setFormValues', payload: { slackIconType: e.target.value }, }) } checked={formValues.slackIconType === 'url'} inline /> <RadioInput title={t('public~Emoji')} name="slackIconType" value="emoji" data-test-id="slack-icon-type-emoji" onChange={(e) => dispatchFormChange({ type: 'setFormValues', payload: { slackIconType: e.target.value }, }) } checked={formValues.slackIconType === 'emoji'} inline /> </label> {formValues.slackIconType === 'url' && ( <> <input className="pf-c-form-control" type="text" aria-describedby="slack-icon-url-help" aria-label={t('public~The URL of the icon.')} data-test-id="slack-icon-url" value={formValues.slack_icon_url} onChange={(e) => dispatchFormChange({ type: 'setFormValues', payload: { slack_icon_url: e.target.value }, }) } /> <div className="help-block" id="slack-icon-url-help"> {t('public~The URL of the icon.')} </div> </> )} {formValues.slackIconType === 'emoji' && ( <> <input className="pf-c-form-control" type="text" aria-describedby="slack-icon-emoji-help" aria-label={t('public~An emoji code to use in place of the default icon.')} name="slackIconEmoji" data-test-id="slack-icon-emoji" value={formValues.slack_icon_emoji} onChange={(e) => dispatchFormChange({ type: 'setFormValues', payload: { slack_icon_emoji: e.target.value }, }) } /> <div className="help-block" id="slack-icon-emoji-help"> <Trans ns="public"> An{' '} <ExternalLink href="https://www.webfx.com/tools/emoji-cheat-sheet/" text={t('public~emoji code')} />{' '} to use in place of the default icon. </Trans> </div> </> )} </div> <div className="form-group"> <label className="control-label" htmlFor="slack-username"> {t('public~Username')} </label> <input className="pf-c-form-control" type="text" aria-describedby="slack-username-help" id="slack-username" data-test-id="slack-username" value={formValues.slack_username} onChange={(e) => dispatchFormChange({ type: 'setFormValues', payload: { slack_username: e.target.value }, }) } /> <div className="help-block" id="slack-username-help"> {t('public~The displayed username.')} </div> </div> <div className="form-group"> <div className="checkbox"> <label className="control-label" htmlFor="slack-link-names"> <input type="checkbox" id="slack-link-names" data-test-id="slack-link-names" aria-describedby="slack-link-names-help" onChange={(e) => dispatchFormChange({ type: 'setFormValues', payload: { slack_link_names: e.target.checked }, }) } checked={formValues.slack_link_names} /> {t('public~Link names')} </label> </div> <div className="help-block" id="slack-link-names-help"> {t('public~Find and link channel names and usernames.')} </div> </div> <div className="form-group"> <label className="control-label" htmlFor="slack-title"> {t('public~Title')} </label> <TextArea id="slack-title" aria-describedby="slack-title-help" onChange={(value) => dispatchFormChange({ type: 'setFormValues', payload: { slack_title: value }, }) } value={formValues.slack_title} /> <div className="help-block" id="slack-title-help"> {t('public~The title of the Slack message.')} </div> </div> <div className="form-group"> <label className="control-label" htmlFor="slack-text"> {t('public~Text')} </label> <TextArea id="slack-text" aria-describedby="slack-text-help" onChange={(value) => dispatchFormChange({ type: 'setFormValues', payload: { slack_text: value }, }) } value={formValues.slack_text} /> <div className="help-block" id="slack-text-help"> {t('public~The text of the Slack message.')} </div> </div> </div> </ExpandCollapse> </div> </div> ); }; export const getInitialValues = (globals, receiverConfig) => { const initValues: any = { slackSaveAsDefault: false, slackChannel: _.get(receiverConfig, 'channel'), }; initValues.slackIconType = _.has(receiverConfig, 'icon_emoji') ? 'emoji' : 'url'; GLOBAL_FIELDS.forEach((fld) => { const configFieldName = fld.substring(fld.indexOf('_') + 1); //strip off leading 'slack_' prefix initValues[fld] = _.get(receiverConfig, configFieldName, globals[fld]); }); return initValues; }; export const isFormInvalid = (formValues): boolean => { return !formValues.slack_api_url || !formValues.slackChannel; }; export const updateGlobals = (globals, formValues) => { const updatedGlobals = {}; if (formValues.slackSaveAsDefault && formValues.slack_api_url) { _.set(updatedGlobals, 'slack_api_url', formValues.slack_api_url); } return updatedGlobals; }; export const createReceiverConfig = (globals, formValues, receiverConfig) => { _.set(receiverConfig, 'channel', formValues.slackChannel); // Only save these props in receiverConfig if different from global GLOBAL_FIELDS.forEach((fld) => { const formValue = formValues[fld]; const configFieldName = fld.substring(fld.indexOf('_') + 1); //strip off leading 'slack_' prefix if (formValue !== globals[fld]) { if (fld === 'slack_api_url' && formValues.slackSaveAsDefault) { _.unset(receiverConfig, 'api_url'); // saving as global so unset in config } else { _.set(receiverConfig, configFieldName, formValue); } } else { _.unset(receiverConfig, configFieldName); // equals global, unset in config so global is used } }); _.unset(receiverConfig, formValues.slackIconType === 'url' ? 'icon_emoji' : 'icon_url'); return receiverConfig; };
the_stack
import { h } from 'preact'; import { mount } from '../../../../test/utils/enzyme'; import { render, fireEvent } from '@testing-library/preact'; import SearchBox from '../SearchBox'; const defaultProps = { placeholder: '', cssClasses: { root: 'root', form: 'form', input: 'input', submit: 'submit', submitIcon: 'submitIcon', reset: 'reset', resetIcon: 'resetIcon', loadingIndicator: 'loadingIndicator', loadingIcon: 'loadingIcon', }, templates: { reset: 'reset', submit: 'submit', loadingIndicator: 'loadingIndicator', }, }; describe('SearchBox', () => { describe('Props', () => { describe('cssClasses', () => { test('sets all CSS classes', () => { const wrapper = mount(<SearchBox {...defaultProps} />); expect(wrapper.find('div').hasClass('root')).toEqual(true); expect(wrapper.find('form').hasClass('form')).toEqual(true); expect(wrapper.find('input').hasClass('input')).toEqual(true); expect( wrapper.find('button[type="submit"]').hasClass('submit') ).toEqual(true); expect(wrapper.find('button[type="reset"]').hasClass('reset')).toEqual( true ); expect(wrapper.find('span').hasClass('loadingIndicator')).toEqual(true); }); }); describe('query', () => { test('sets query', () => { const props = { ...defaultProps, query: 'Initial query', }; const wrapper = mount(<SearchBox {...props} />); expect(wrapper.find('input').props().value).toBe('Initial query'); }); }); describe('placeholder', () => { test('sets placeholder', () => { const props = { ...defaultProps, placeholder: 'Custom placeholder', }; const wrapper = mount(<SearchBox {...props} />); expect(wrapper.find('input').props().placeholder).toBe( 'Custom placeholder' ); }); }); describe('showSubmit', () => { test('show the submit button by default', () => { const props = { ...defaultProps, }; const wrapper = mount(<SearchBox {...props} />); expect(wrapper.find('.submit').props().hidden).toBe(false); }); test('hides the submit button when false', () => { const props = { ...defaultProps, showSubmit: false, }; const wrapper = mount(<SearchBox {...props} />); expect(wrapper.find('.submit').props().hidden).toBe(true); }); }); describe('showReset', () => { test('hides the reset button by default without query', () => { const props = { ...defaultProps, }; const wrapper = mount(<SearchBox {...props} />); expect(wrapper.find('.reset').props().hidden).toBe(true); }); test('shows the reset button by default with query', () => { const props = { ...defaultProps, query: 'query', }; const wrapper = mount(<SearchBox {...props} />); expect(wrapper.find('.reset').props().hidden).toBe(false); }); test('hides the reset button when false', () => { const props = { ...defaultProps, showReset: false, }; const wrapper = mount(<SearchBox {...props} />); expect(wrapper.find('.reset').props().hidden).toBe(true); }); }); describe('showLoadingIndicator', () => { test('removes loadingIndicator from DOM when false', () => { const props = { ...defaultProps, showLoadingIndicator: false, }; const wrapper = mount(<SearchBox {...props} />); expect(wrapper.exists('.loadingIndicator')).toBe(false); }); test('hides loadingIndicator when true but search is not stalled', () => { const props = { ...defaultProps, showLoadingIndicator: true, isSearchStalled: false, }; const wrapper = mount(<SearchBox {...props} />); expect(wrapper.find('.loadingIndicator').props().hidden).toBe(true); }); test('shows loadingIndicator when true and search is stalled', () => { const props = { ...defaultProps, showLoadingIndicator: true, isSearchStalled: true, }; const wrapper = mount(<SearchBox {...props} />); expect(wrapper.find('.loadingIndicator').props().hidden).toBe(false); }); }); test('sets focus with autofocus to true', () => { const props = { ...defaultProps, autofocus: true, }; const { container } = render(<SearchBox {...props} />); const input = container.querySelector('input'); // @TODO Since the Preact X migration and new testing environment, this // assertion doesn't work. Once it does, we can remove the // `toHaveAttribute` assertion. // expect(input).toHaveFocus(); expect(input).toHaveAttribute('autofocus', 'true'); }); test('disables the input with disabled to true', () => { const props = { ...defaultProps, disabled: true, }; const wrapper = mount(<SearchBox {...props} />); expect(wrapper.find('input').props().disabled).toBe(true); }); }); describe('Events', () => { describe('focus/blur', () => { test('does not derive value from prop when focused', () => { // This makes sure we don't override the user's input while they're typing. // This issue is more obvious when using queryHook to add debouncing. const props = { ...defaultProps, query: 'Initial query', }; const { container, rerender } = render(<SearchBox {...props} />); const input = container.querySelector('input')!; expect(input.value).toEqual('Initial query'); fireEvent.focus(input); rerender(<SearchBox {...props} query={'Query updated through prop'} />); expect(input.value).toEqual('Initial query'); }); test('derives value from prop when not focused', () => { const props = { ...defaultProps, query: 'Initial query', }; const { container, rerender } = render(<SearchBox {...props} />); const input = container.querySelector('input')!; expect(input.value).toEqual('Initial query'); fireEvent.blur(input); rerender(<SearchBox {...props} query={'Query updated through prop'} />); expect(input.value).toEqual('Query updated through prop'); }); }); describe('searchAsYouType to true', () => { test('refines input value on input', () => { const refine = jest.fn(); const props = { ...defaultProps, searchAsYouType: true, refine, }; const { container } = render(<SearchBox {...props} />); const input = container.querySelector('input')!; fireEvent.input(input, { target: { value: 'hello' }, }); expect(refine).toHaveBeenCalledTimes(1); expect(refine).toHaveBeenLastCalledWith('hello'); }); }); describe('searchAsYouType to false', () => { test('updates DOM input value on input', () => { const props = { ...defaultProps, query: 'Query 1', searchAsYouType: false, }; const { container } = render(<SearchBox {...props} />); const input = container.querySelector('input')!; expect(input.value).toEqual('Query 1'); fireEvent.input(input, { target: { value: 'Query 2' }, }); expect(input.value).toEqual('Query 2'); }); test('refines query on submit', () => { const refine = jest.fn(); const props = { ...defaultProps, searchAsYouType: false, refine, }; const { container } = render(<SearchBox {...props} />); const form = container.querySelector('form')!; const input = container.querySelector('input')!; fireEvent.input(input, { target: { value: 'hello' }, }); expect(refine).toHaveBeenCalledTimes(0); fireEvent.submit(form); expect(refine).toHaveBeenCalledTimes(1); expect(refine).toHaveBeenLastCalledWith('hello'); }); }); describe('onChange', () => { test('calls custom onChange', () => { const onChange = jest.fn(); const props = { ...defaultProps, onChange, }; const { container } = render(<SearchBox {...props} />); const input = container.querySelector('input')!; fireEvent.input(input, { target: { value: 'hello' }, }); expect(onChange).toHaveBeenCalledTimes(1); }); }); describe('onSubmit', () => { test('calls custom onSubmit', () => { const onSubmit = jest.fn(); const props = { ...defaultProps, onSubmit, }; const { container } = render(<SearchBox {...props} />); const form = container.querySelector('form')!; fireEvent.submit(form); expect(onSubmit).toHaveBeenCalledTimes(1); }); }); describe('onReset', () => { describe('with button click', () => { test('resets the input value with searchAsYouType to true', () => { const props = { ...defaultProps, searchAsYouType: true, }; const { container } = render(<SearchBox {...props} />); const input = container.querySelector('input')!; const resetButton = container.querySelector('button[type="reset"]')!; fireEvent.change(input, { target: { value: 'hello' }, }); expect(input.value).toEqual('hello'); fireEvent.click(resetButton); expect(input.value).toEqual(''); expect(input).toHaveFocus(); }); test('resets the input value with searchAsYouType to false', () => { const props = { ...defaultProps, searchAsYouType: false, }; const { container } = render(<SearchBox {...props} />); const form = container.querySelector('form')!; const input = container.querySelector('input')!; const resetButton = container.querySelector('button[type="reset"]')!; fireEvent.input(input, { target: { value: 'hello' } }); fireEvent.submit(form); expect(input.value).toEqual('hello'); fireEvent.click(resetButton); expect(input.value).toEqual(''); expect(input).toHaveFocus(); }); test('calls custom onReset', () => { const onReset = jest.fn(); const props = { ...defaultProps, onReset, }; const { container } = render(<SearchBox {...props} />); const resetButton = container.querySelector('button[type="reset"]')!; fireEvent.click(resetButton); expect(onReset).toHaveBeenCalledTimes(1); }); }); describe('when form is reset programmatically', () => { test('resets the input value with searchAsYouType to true', () => { const props = { ...defaultProps, searchAsYouType: true, }; const { container } = render(<SearchBox {...props} />); const input = container.querySelector('input')!; const form = container.querySelector('form')!; fireEvent.change(input, { target: { value: 'hello' }, }); expect(input.value).toEqual('hello'); fireEvent.reset(form); expect(input.value).toEqual(''); expect(input).toHaveFocus(); }); test('resets the input value with searchAsYouType to false', () => { const props = { ...defaultProps, searchAsYouType: false, }; const { container } = render(<SearchBox {...props} />); const form = container.querySelector('form')!; const input = container.querySelector('input')!; fireEvent.input(input, { target: { value: 'hello' } }); fireEvent.submit(form); expect(input.value).toEqual('hello'); fireEvent.reset(form); expect(input.value).toEqual(''); expect(input).toHaveFocus(); }); test('calls custom onReset', () => { const onReset = jest.fn(); const props = { ...defaultProps, onReset, }; const { container } = render(<SearchBox {...props} />); const form = container.querySelector('form')!; fireEvent.reset(form); expect(onReset).toHaveBeenCalledTimes(1); }); }); }); }); describe('Rendering', () => { test('with default props', () => { expect(mount(<SearchBox {...defaultProps} />)).toMatchSnapshot(); }); test('sets search input attributes', () => { const res = render( <SearchBox {...defaultProps} autofocus={true} query="sample query" /> ); const input = res.getByDisplayValue('sample query'); expect(input).toHaveAttribute('autofocus', 'true'); expect(input).toHaveAttribute('autocomplete', 'off'); expect(input).toHaveAttribute('autocorrect', 'off'); expect(input).toHaveAttribute('autocapitalize', 'off'); expect(input).toHaveAttribute('spellcheck', 'false'); expect(input).toHaveAttribute('maxlength', '512'); }); test('with custom templates', () => { const props = { ...defaultProps, templates: { reset: 'reset template', submit: 'submit template', loadingIndicator: 'loadingIndicator template', }, }; expect(mount(<SearchBox {...props} />)).toMatchSnapshot(); }); }); });
the_stack
import type { BigNumber } from "bignumber.js"; import type { TransactionCommon, TransactionCommonRaw, } from "../../types/transaction"; import type { Operation, OperationRaw } from "../../types/operation"; import type { CoreAmount, CoreBigInt, Spec } from "../../libcore/types"; export type CoreStatics = { CosmosLikeOperation: CoreCosmosLikeOperation; CosmosLikeAddress: CoreCosmosLikeAddress; CosmosLikeTransactionBuilder: CoreCosmosLikeTransactionBuilder; CosmosLikeTransaction: CoreCosmosLikeTransaction; CosmosLikeMessage: CoreCosmosLikeMessage; CosmosLikeMsgWithdrawDelegationReward: CosmosMsgWithdrawDelegationReward; CosmosLikeAmount: CoreCosmosLikeAmount; CosmosLikeMsgSend: CosmosMsgSend; CosmosLikeMsgDelegate: CosmosMsgDelegate; CosmosLikeMsgUndelegate: CosmosMsgUndelegate; CosmosLikeMsgBeginRedelegate: CosmosMsgRedelegate; CosmosGasLimitRequest: CoreCosmosGasLimitRequest; }; export type CoreAccountSpecifics = { asCosmosLikeAccount(): Promise<CoreCosmosLikeAccount>; }; export type CoreOperationSpecifics = { asCosmosLikeOperation(): Promise<CoreCosmosLikeOperation>; }; export type CoreCurrencySpecifics = Record<string, never>; export type CosmosDelegationStatus = | "bonded" // in the active set that generates rewards | "unbonding" // doesn't generate rewards. means the validator has been removed from the active set, but has its voting power "frozen" in case they misbehaved (just like a delegator undelegating). This last 21 days | "unbonded"; // doesn't generate rewards. means the validator has been removed from the active set for more than 21 days basically export type CosmosDelegation = { validatorAddress: string; amount: BigNumber; pendingRewards: BigNumber; status: CosmosDelegationStatus; }; export type CosmosRedelegation = { validatorSrcAddress: string; validatorDstAddress: string; amount: BigNumber; completionDate: Date; }; export type CosmosUnbonding = { validatorAddress: string; amount: BigNumber; completionDate: Date; }; export type CosmosResources = { delegations: CosmosDelegation[]; redelegations: CosmosRedelegation[]; unbondings: CosmosUnbonding[]; delegatedBalance: BigNumber; pendingRewardsBalance: BigNumber; unbondingBalance: BigNumber; withdrawAddress: string; }; export type CosmosDelegationRaw = { validatorAddress: string; amount: string; pendingRewards: string; status: CosmosDelegationStatus; }; export type CosmosUnbondingRaw = { validatorAddress: string; amount: string; completionDate: string; }; export type CosmosRedelegationRaw = { validatorSrcAddress: string; validatorDstAddress: string; amount: string; completionDate: string; }; export type CosmosResourcesRaw = { delegations: CosmosDelegationRaw[]; redelegations: CosmosRedelegationRaw[]; unbondings: CosmosUnbondingRaw[]; delegatedBalance: string; pendingRewardsBalance: string; unbondingBalance: string; withdrawAddress: string; }; // NB this must be serializable (no Date, no BigNumber) export type CosmosValidatorItem = { validatorAddress: string; name: string; votingPower: number; // value from 0.0 to 1.0 (normalized percentage) commission: number; // value from 0.0 to 1.0 (normalized percentage) estimatedYearlyRewardsRate: number; // value from 0.0 to 1.0 (normalized percentage) }; export type CosmosRewardsState = { targetBondedRatio: number; communityPoolCommission: number; assumedTimePerBlock: number; inflationRateChange: number; inflationMaxRate: number; inflationMinRate: number; actualBondedRatio: number; averageTimePerBlock: number; totalSupply: number; averageDailyFees: number; currentValueInflation: number; }; // by convention preload would return a Promise of CosmosPreloadData export type CosmosPreloadData = { validators: CosmosValidatorItem[]; }; export type CosmosOperationMode = | "send" | "delegate" | "undelegate" | "redelegate" | "claimReward" | "claimRewardCompound"; export type NetworkInfo = { family: "cosmos"; fees: BigNumber; }; export type NetworkInfoRaw = { family: "cosmos"; fees: string; }; export type CosmosOperation = Operation & { extra: CosmosExtraTxInfo; }; export type CosmosOperationRaw = OperationRaw & { extra: CosmosExtraTxInfo; }; export type CosmosExtraTxInfo = { validators?: CosmosDelegationInfo[]; cosmosSourceValidator?: string | null | undefined; validator?: CosmosDelegationInfo; }; export type CosmosDelegateTxInfo = { validators: CosmosDelegationInfo[]; }; export type CosmosUndelegateTxInfo = { validators: CosmosDelegationInfo[]; }; export type CosmosRedelegateTxInfo = { validators: CosmosDelegationInfo[]; cosmosSourceValidator: string | null | undefined; }; export type CosmosClaimRewardsTxInfo = { validator: CosmosDelegationInfo; }; export type CosmosDelegationInfo = { address: string; amount: BigNumber; }; export type CosmosDelegationInfoRaw = { address: string; amount: string; }; export type CosmosMessage = CoreCosmosLikeMessage; declare class CosmosMsgSend { init( fromAddress: string, toAddress: string, amount: CoreCosmosLikeAmount[] ): Promise<CosmosMsgSend>; fromAddress: string; toAddress: string; amount: Array<CoreCosmosLikeAmount>; } declare class CosmosMsgDelegate { init( delegatorAddress: string, validatorAddress: string, amount: CoreCosmosLikeAmount ): Promise<CosmosMsgDelegate>; getValidatorAddress(): Promise<string>; getAmount(): Promise<CosmosAmount>; delegatorAddress: string; validatorAddress: string; amount: CoreCosmosLikeAmount; } export type CosmosMsgUndelegate = CosmosMsgDelegate; type CosmosAmount = { getAmount(): Promise<string>; amount: string; denom: string; }; declare class CoreCosmosGasLimitRequest { init( memo: string, messages: CoreCosmosLikeMessage[], amplifier: string ): Promise<CoreCosmosGasLimitRequest>; } declare class CosmosMsgRedelegate { init( delegatorAddress: string, validatorSourceAddress: string, validatorDestinationAddress: string, amount: CoreCosmosLikeAmount ): Promise<CosmosMsgRedelegate>; getValidatorDestinationAddress(): Promise<string>; getValidatorSourceAddress(): Promise<string>; getAmount(): Promise<CosmosAmount>; delegatorAddress: string; validatorSourceAddress: string; validatorDestinationAddress: string; amount: CoreCosmosLikeAmount; } declare class CoreCosmosLikeAmount { init(amount: string, denom: string): Promise<CoreCosmosLikeAmount>; getAmount(): Promise<string>; amount: string; denom: string; } declare class CosmosMsgWithdrawDelegationReward { init( delegatorAddress: string, validatorAddress: string ): Promise<CosmosMsgWithdrawDelegationReward>; getValidatorAddress(): Promise<string>; delegatorAddress: string; validatorAddress: string; } type CosmosLikeEntry = { // Block height of the begin redelegate request getCreationHeight(): Promise<CoreBigInt>; // Timestamp of the redelegation completion getCompletionTime(): Date; // Balance requested to redelegate getInitialBalance(): Promise<CoreBigInt>; // Current amount being redelegated (i.e. less than initialBalance if slashed) getBalance(): Promise<CoreBigInt>; }; export type CosmosLikeRedelegation = { getDelegatorAddress(): string; getSrcValidatorAddress(): string; getDstValidatorAddress(): string; getEntries(): CosmosLikeEntry[]; }; export type CosmosLikeUnbonding = { getDelegatorAddress(): string; getValidatorAddress(): string; getEntries(): CosmosLikeEntry[]; }; export type CosmosLikeDelegation = { getDelegatorAddress(): string; getValidatorAddress(): string; getDelegatedAmount(): CoreAmount; }; declare class CoreCosmosLikeAddress { toBech32(): Promise<string>; } declare class CoreCosmosLikeOperation { getTransaction(): Promise<CoreCosmosLikeTransaction>; getMessage(): Promise<CoreCosmosLikeMessage>; } declare class CoreCosmosLikeMsgType {} declare class CoreCosmosLikeMessage { getIndex(): Promise<string>; getMessageType(): Promise<CoreCosmosLikeMsgType>; getRawMessageType(): Promise<string>; wrapMsgSend(message: CosmosMsgSend): Promise<CoreCosmosLikeMessage>; wrapMsgDelegate(message: CosmosMsgDelegate): Promise<CoreCosmosLikeMessage>; wrapMsgUndelegate( message: CosmosMsgUndelegate ): Promise<CoreCosmosLikeMessage>; wrapMsgBeginRedelegate( message: CosmosMsgRedelegate ): Promise<CoreCosmosLikeMessage>; wrapMsgWithdrawDelegationReward( message: CosmosMsgWithdrawDelegationReward ): Promise<CoreCosmosLikeMessage>; unwrapMsgDelegate(msg: CosmosMessage): Promise<CosmosMsgDelegate>; unwrapMsgBeginRedelegate(msg: CosmosMessage): Promise<CosmosMsgRedelegate>; unwrapMsgUndelegate(msg: CosmosMessage): Promise<CosmosMsgUndelegate>; unwrapMsgWithdrawDelegationReward( msg: CosmosMessage ): Promise<CosmosMsgWithdrawDelegationReward>; } declare class CoreCosmosLikeTransactionBuilder { setMemo(memo: string): Promise<CoreCosmosLikeTransactionBuilder>; setSequence(sequence: string): Promise<CoreCosmosLikeTransactionBuilder>; setAccountNumber( accountNumber: string ): Promise<CoreCosmosLikeTransactionBuilder>; addMessage( message: CoreCosmosLikeMessage ): Promise<CoreCosmosLikeTransactionBuilder>; setFee(fees: CoreAmount): Promise<CoreCosmosLikeTransactionBuilder>; setGas(gas: CoreAmount): Promise<CoreCosmosLikeTransactionBuilder>; build(): Promise<CoreCosmosLikeTransaction>; } declare class CoreCosmosLikeTransaction { toRawTransaction(): string; toSignatureBase(): Promise<string>; getHash(): Promise<string>; getMemo(): Promise<string>; getFee(): Promise<CoreAmount>; getGas(): Promise<CoreAmount>; serializeForSignature(): Promise<string>; serializeForBroadcast(type: "block" | "async" | "sync"): Promise<string>; setSignature(arg0: string, arg1: string): Promise<void>; setDERSignature(arg0: string): Promise<void>; } declare class CosmosLikeReward { getDelegatorAddress(): string; getValidatorAddress(): string; getRewardAmount(): CoreAmount; } export type CosmosLikeValidator = { activeStatus: string; getActiveStatus(): Promise<string>; }; export type CosmosBroadcastResponse = { code: number; raw_log: string; txhash: string; }; declare class CoreCosmosLikeAccount { buildTransaction(): Promise<CoreCosmosLikeTransactionBuilder>; broadcastRawTransaction(signed: string): Promise<string>; broadcastTransaction(signed: string): Promise<string>; getEstimatedGasLimit( transaction: CoreCosmosLikeTransaction ): Promise<CoreBigInt>; estimateGas(request: CoreCosmosGasLimitRequest): Promise<CoreBigInt>; getBaseReserve(): Promise<CoreAmount>; isAddressActivated(address: string): Promise<boolean>; getSequence(): Promise<string>; getAccountNumber(): Promise<string>; getPendingRewards(): Promise<CosmosLikeReward[]>; getRedelegations(): Promise<CosmosLikeRedelegation[]>; getUnbondings(): Promise<CosmosLikeUnbonding[]>; getDelegations(): Promise<CosmosLikeDelegation[]>; getValidatorInfo(validatorAddress: string): Promise<CosmosLikeValidator>; } export type { CoreCosmosLikeAccount, CoreCosmosLikeAddress, CoreCosmosLikeOperation, CoreCosmosLikeTransaction, CoreCosmosLikeTransactionBuilder, }; export type Transaction = TransactionCommon & { family: "cosmos"; mode: CosmosOperationMode; networkInfo: NetworkInfo | null | undefined; fees: BigNumber | null | undefined; gas: BigNumber | null | undefined; memo: string | null | undefined; validators: CosmosDelegationInfo[]; cosmosSourceValidator: string | null | undefined; }; export type TransactionRaw = TransactionCommonRaw & { family: "cosmos"; mode: CosmosOperationMode; networkInfo: NetworkInfoRaw | null | undefined; fees: string | null | undefined; gas: string | null | undefined; memo: string | null | undefined; validators: CosmosDelegationInfoRaw[]; cosmosSourceValidator: string | null | undefined; }; export type StatusErrorMap = { recipient?: Error; amount?: Error; fees?: Error; validators?: Error; delegate?: Error; redelegation?: Error; unbonding?: Error; claimReward?: Error; feeTooHigh?: Error; }; export type TransactionStatus = { errors: StatusErrorMap; warnings: StatusErrorMap; estimatedFees: BigNumber; amount: BigNumber; totalSpent: BigNumber; }; export type CosmosMappedDelegation = CosmosDelegation & { formattedAmount: string; formattedPendingRewards: string; rank: number; validator: CosmosValidatorItem | null | undefined; }; export type CosmosMappedUnbonding = CosmosUnbonding & { formattedAmount: string; validator: CosmosValidatorItem | null | undefined; }; export type CosmosMappedRedelegation = CosmosRedelegation & { formattedAmount: string; validatorSrc: CosmosValidatorItem | null | undefined; validatorDst: CosmosValidatorItem | null | undefined; }; export type CosmosMappedDelegationInfo = CosmosDelegationInfo & { validator: CosmosValidatorItem | null | undefined; formattedAmount: string; }; export type CosmosMappedValidator = { rank: number; validator: CosmosValidatorItem; }; export type CosmosSearchFilter = ( query: string ) => (delegation: CosmosMappedDelegation | CosmosMappedValidator) => boolean; export const reflect = ( declare: (arg0: string, arg1: Spec) => void ): { OperationMethods: { asCosmosLikeOperation: { returns: "CosmosLikeOperation"; }; }; AccountMethods: { asCosmosLikeAccount: { returns: "CosmosLikeAccount"; }; }; } => { declare("CosmosLikeTransactionBuilder", { methods: { addMessage: { params: ["CosmosLikeMessage"], }, build: { returns: "CosmosLikeTransaction", }, setMemo: {}, setSequence: {}, setAccountNumber: {}, setFee: { params: ["Amount"], }, setGas: { params: ["Amount"], }, }, }); declare("CosmosGasLimitRequest", { njsUsesPlainObject: true, statics: { init: { params: [null, ["CosmosLikeMessage"], null], returns: "CosmosGasLimitRequest", njsInstanciateClass: [ { memo: 0, messages: 1, amplifier: 2, }, ], }, }, }); declare("CosmosLikeAccount", { methods: { estimateGas: { params: ["CosmosGasLimitRequest"], returns: "BigInt", }, buildTransaction: { returns: "CosmosLikeTransactionBuilder", }, broadcastRawTransaction: {}, broadcastTransaction: {}, getEstimatedGasLimit: { params: ["CosmosLikeTransaction"], }, getSequence: {}, getAccountNumber: {}, getPendingRewards: { returns: ["CosmosLikeReward"], }, getRedelegations: { returns: ["CosmosLikeRedelegation"], }, getUnbondings: { returns: ["CosmosLikeUnbonding"], }, getDelegations: { returns: ["CosmosLikeDelegation"], }, getValidatorInfo: { returns: "CosmosLikeValidator", }, }, }); declare("CosmosLikeValidator", { njsUsesPlainObject: true, methods: { getActiveStatus: { njsField: "activeStatus", }, }, }); declare("CosmosLikeReward", { methods: { getDelegatorAddress: {}, getValidatorAddress: {}, getRewardAmount: { returns: "Amount", }, }, }); declare("CosmosLikeUnbonding", { methods: { getDelegatorAddress: {}, getValidatorAddress: {}, getEntries: { returns: ["CosmosLikeUnbondingEntry"], }, }, }); declare("CosmosLikeTransaction", { methods: { getHash: {}, getMemo: {}, setDERSignature: { params: ["hex"], }, getFee: { returns: "Amount", }, getGas: { returns: "Amount", }, serializeForSignature: {}, serializeForBroadcast: {}, }, }); declare("CosmosLikeOperation", { methods: { getTransaction: { returns: "CosmosLikeTransaction", }, getMessage: { returns: "CosmosLikeMessage", }, }, }); declare("CosmosLikeRedelegationEntry", { methods: { getInitialBalance: { returns: "BigInt", }, getCompletionTime: {}, }, }); declare("CosmosLikeUnbondingEntry", { methods: { getInitialBalance: { returns: "BigInt", }, getCompletionTime: {}, }, }); declare("CosmosLikeRedelegation", { methods: { getDelegatorAddress: { returns: "string", }, getSrcValidatorAddress: { returns: "string", }, getDstValidatorAddress: { returns: "string", }, getEntries: { returns: ["CosmosLikeRedelegationEntry"], }, }, }); declare("CosmosLikeDelegation", { methods: { getDelegatorAddress: {}, getValidatorAddress: {}, getDelegatedAmount: { returns: "Amount", }, }, }); declare("CosmosLikeMessage", { statics: { wrapMsgSend: { params: ["CosmosLikeMsgSend"], returns: "CosmosLikeMessage", njsBuggyMethodIsNotStatic: true, }, wrapMsgDelegate: { params: ["CosmosLikeMsgDelegate"], returns: "CosmosLikeMessage", njsBuggyMethodIsNotStatic: true, }, wrapMsgUndelegate: { params: ["CosmosLikeMsgUndelegate"], returns: "CosmosLikeMessage", njsBuggyMethodIsNotStatic: true, }, wrapMsgBeginRedelegate: { params: ["CosmosLikeMsgBeginRedelegate"], returns: "CosmosLikeMessage", njsBuggyMethodIsNotStatic: true, }, wrapMsgWithdrawDelegationReward: { params: ["CosmosLikeMsgWithdrawDelegationReward"], returns: "CosmosLikeMessage", njsBuggyMethodIsNotStatic: true, }, unwrapMsgDelegate: { params: ["CosmosLikeMessage"], returns: "CosmosLikeMsgDelegate", njsBuggyMethodIsNotStatic: true, }, unwrapMsgBeginRedelegate: { params: ["CosmosLikeMessage"], returns: "CosmosLikeMsgBeginRedelegate", njsBuggyMethodIsNotStatic: true, }, unwrapMsgUndelegate: { params: ["CosmosLikeMessage"], returns: "CosmosLikeMsgUndelegate", njsBuggyMethodIsNotStatic: true, }, unwrapMsgWithdrawDelegationReward: { params: ["CosmosLikeMessage"], returns: "CosmosLikeMsgWithdrawDelegationReward", njsBuggyMethodIsNotStatic: true, }, }, methods: { getMessageType: {}, getRawMessageType: {}, getIndex: {}, }, }); declare("CosmosLikeAmount", { njsUsesPlainObject: true, statics: { init: { params: [null, null], returns: "CosmosLikeAmount", njsInstanciateClass: [ { amount: 0, denom: 1, }, ], }, }, methods: { getAmount: { njsField: "amount", }, }, }); declare("CosmosLikeMsgSend", { njsUsesPlainObject: true, statics: { init: { params: [null, null, ["CosmosLikeAmount"]], returns: "CosmosLikeMsgSend", njsInstanciateClass: [ { fromAddress: 0, toAddress: 1, amount: 2, }, ], }, }, }); declare("CosmosLikeMsgDelegate", { njsUsesPlainObject: true, statics: { init: { params: [null, null, "CosmosLikeAmount"], returns: "CosmosLikeMsgDelegate", njsInstanciateClass: [ { delegatorAddress: 0, validatorAddress: 1, amount: 2, }, ], }, }, methods: { getValidatorAddress: { njsField: "validatorAddress", }, getAmount: { njsField: "amount", returns: "CosmosLikeAmount", }, }, }); declare("CosmosLikeMsgBeginRedelegate", { njsUsesPlainObject: true, statics: { init: { params: [null, null, null, "CosmosLikeAmount"], returns: "CosmosLikeMsgBeginRedelegate", njsInstanciateClass: [ { delegatorAddress: 0, validatorSourceAddress: 1, validatorDestinationAddress: 2, amount: 3, }, ], }, }, methods: { getValidatorDestinationAddress: { njsField: "validatorDestinationAddress", }, getValidatorSourceAddress: { njsField: "validatorSourceAddress", }, getAmount: { njsField: "amount", returns: "CosmosLikeAmount", }, }, }); declare("CosmosLikeMsgUndelegate", { njsUsesPlainObject: true, statics: { init: { params: [null, null, "CosmosLikeAmount"], returns: "CosmosLikeMsgUndelegate", njsInstanciateClass: [ { delegatorAddress: 0, validatorAddress: 1, amount: 2, }, ], }, }, methods: { getValidatorAddress: { njsField: "validatorAddress", }, getAmount: { njsField: "amount", returns: "CosmosLikeAmount", }, }, }); declare("CosmosLikeMsgWithdrawDelegationReward", { njsUsesPlainObject: true, statics: { init: { params: [null, null], returns: "CosmosLikeMsgWithdrawDelegationReward", njsInstanciateClass: [ { delegatorAddress: 0, validatorAddress: 1, }, ], }, }, methods: { getDelegatorAddress: { njsField: "delegatorAddress", }, getValidatorAddress: { njsField: "validatorAddress", }, }, }); return { OperationMethods: { asCosmosLikeOperation: { returns: "CosmosLikeOperation", }, }, AccountMethods: { asCosmosLikeAccount: { returns: "CosmosLikeAccount", }, }, }; };
the_stack
import * as spanner from '@google-cloud/spanner'; import * as express from 'express'; import * as config from './config'; import * as httpcodes from './http-status-codes'; import * as runtime_types from './runtime_types'; import * as db_types from './db_types'; export class NoResultsError extends Error {} const SEARCH_BY_TYPE = new runtime_types.RuntimeStringType<string>( 'SearchBy', /^(conversation_id|rev_id|page_id|page_title|id)$/); const SEARCH_OP_TYPE = new runtime_types.RuntimeStringType<string>('SearchBy', /^(=|LIKE)$/); // TODO(ldixon): in time we can maybe make this a bit smarter and support // escaped quotes. const SQL_SAFE_STRING = new runtime_types.RuntimeStringType<string>('SearchBy', /^[^"]+$/); const parentIdIndex = '_by_parent_id'; const usernameIndex = '_by_user_text'; const conversationIdIndex = '_by_conversation_id'; const toxicityIndex = '_by_toxicity'; const whereConditions = ['page_id', 'page_title', 'user_id', 'user_text', 'rev_id', 'comment_id', 'conversation_id', 'isAlive'] // TODO(ldixon): consider using passport auth // for google cloud project. export function setup( app: express.Express, conf: config.Config, spannerDatabase: spanner.Database) { const table = `\`${conf.spannerTableName}\``; app.get('/api/conversation-id/:conv_id', async (req, res) => { try { const conv_id: runtime_types.ConversationId = runtime_types.ConversationId.assert(req.params.conv_id); const index = conf.spannerTableName + conversationIdIndex; // TODO remove outer try wrapper unless it get used. // Force Spanner using particular indices to speed up performance. const sqlQuery = `SELECT * FROM ${table}@{FORCE_INDEX=${index}} WHERE conversation_id="${conv_id}" LIMIT 100`; // Query options list: // https://cloud.google.com/spanner/docs/getting-started/nodejs/#query_data_using_sql const query: spanner.Query = { sql: sqlQuery }; await spannerDatabase.run(query).then(results => { const rows = results[0]; res.status(httpcodes.OK).send(JSON.stringify(db_types.parseOutputRows<db_types.OutputRow>(rows), null, 2)); }); } catch (e) { console.error(`*** Failed: `, e); res.status(httpcodes.INTERNAL_SERVER_ERROR).send(JSON.stringify({ error: e.message })); } }); app.get('/api/toxicity/:options', async (req, res) => { try { console.log("RECEVED REQUEST") const options: runtime_types.apiRequest = runtime_types.assertAPIRequest(JSON.parse(decodeURI(req.params.options))); console.log(options); let index = conf.spannerTableName + toxicityIndex; if (options['user_text'] !== undefined) { index = conf.spannerTableName + usernameIndex; } if (options.order === 'ASC') { index = index + '_ASC'; } let whereQueryConditions : string[] = []; for (let condition of whereConditions) { if (options[condition] !== undefined) { if (condition !== 'isAlive' && condition !== 'rev_id') { whereQueryConditions.push(` and ${condition} = "${options[condition]}"`); } else { whereQueryConditions.push(` and ${condition} = ${options[condition]}`); } } } // TODO remove outer try wrapper unless it get used. const sqlQuery = `SELECT * FROM ${table}@{FORCE_INDEX=${index}} WHERE RockV6_1_TOXICITY < ${options.upper_score} and RockV6_1_TOXICITY > ${options.lower_score} and type != "DELETION"${whereQueryConditions.join('')} ORDER BY RockV6_1_TOXICITY ${options.order} LIMIT 20`; console.log(sqlQuery); // Query options list: // https://cloud.google.com/spanner/docs/getting-started/nodejs/#query_data_using_sql const query: spanner.Query = { sql: sqlQuery }; console.log("QUERY SPANNER"); await spannerDatabase.run(query).then(results => { const rows = results[0]; console.log("RECVED ANSWER FROM SPANNER"); try { res.status(httpcodes.OK).send(JSON.stringify(db_types.parseOutputRows<db_types.OutputRow>(rows), null, 2)); } catch (e) { console.log(`*** Failed: `, e); } }); } catch (e) { console.error(`*** Failed: `, e); res.status(httpcodes.INTERNAL_SERVER_ERROR).send(JSON.stringify({ error: e.message })); } }); app.get('/api/parent-id/:parent_id', async (req, res) => { try { const parent_id: runtime_types.CommentId = runtime_types.CommentId.assert(req.params.parent_id); const index = conf.spannerTableName + parentIdIndex; // TODO remove outer try wrapper unless it get used. // id field is unique. const sqlQuery = ` SELECT parent_id, type, timestamp FROM ${table}@{FORCE_INDEX=${index}} WHERE parent_id = "${parent_id}" ORDER BY timestamp DESC LIMIT 1`; // Query options list: // https://cloud.google.com/spanner/docs/getting-started/nodejs/#query_data_using_sql const query: spanner.Query = { sql: sqlQuery }; await spannerDatabase.run(query).then(results => { const rows = results[0]; res.status(httpcodes.OK).send(db_types.parseOutputRows<db_types.OutputRow>(rows)); }); } catch (e) { console.error(`*** Failed: `, e); res.status(httpcodes.INTERNAL_SERVER_ERROR).send(JSON.stringify({ error: e.message })); } }); app.get('/api/comment-id/:comment_id', async (req, res) => { try { console.log("COMMENT_ID RECVED REQUEST"); const comment_id: runtime_types.CommentId = runtime_types.CommentId.assert(req.params.comment_id); const index = conf.spannerTableName + conversationIdIndex; // TODO remove outer try wrapper unless it get used. // id field is unique. const sqlQuery = ` SELECT conv_r.* FROM ${table} conv_l JOIN ${table}@{FORCE_INDEX=${index}} conv_r ON conv_r.conversation_id = conv_l.conversation_id WHERE conv_l.id = "${comment_id}" and conv_r.timestamp <= conv_l.timestamp`; // Query options list: // https://cloud.google.com/spanner/docs/getting-started/nodejs/#query_data_using_sql const query: spanner.Query = { sql: sqlQuery }; console.log("QUERY TO SPANNER"); await spannerDatabase.run(query).then(results => { console.log("GOT ANSWER FROM SPANNER"); const rows = results[0]; res.status(httpcodes.OK).send(db_types.parseOutputRows<db_types.OutputRow>(rows)); }); } catch (e) { console.error(`*** Failed: `, e); res.status(httpcodes.INTERNAL_SERVER_ERROR).send(JSON.stringify({ error: e.message })); } }); app.get('/api/revision-id/:rev_id', async (req, res) => { try { const rev_id: runtime_types.RevisionId = runtime_types.RevisionId.assert(req.params.rev_id); // TODO remove outer try wrapper unless it get used. const sqlQuery = `SELECT * FROM ${table} WHERE rev_id=${rev_id} LIMIT 100`; // Query options list: // https://cloud.google.com/spanner/docs/getting-started/nodejs/#query_data_using_sql const query: spanner.Query = { sql: sqlQuery }; await spannerDatabase.run(query).then(results => { const rows = results[0]; res.status(httpcodes.OK).send(db_types.parseOutputRows<db_types.OutputRow>(rows)); }); } catch (e) { console.error(`*** Failed: `, e); res.status(httpcodes.INTERNAL_SERVER_ERROR).send(JSON.stringify({ error: e.message })); } }); app.get('/api/page-id/:page_id', async (req, res) => { try { const page_id: runtime_types.PageId = runtime_types.PageId.assert(req.params.page_id); // TODO remove outer try wrapper unless it get used. const sqlQuery = `SELECT * FROM ${table} WHERE page_id=${page_id} LIMIT 100`; // Query options list: // https://cloud.google.com/spanner/docs/getting-started/nodejs/#query_data_using_sql const query: spanner.Query = { sql: sqlQuery }; await spannerDatabase.run(query).then(results => { const rows = results[0]; res.status(httpcodes.OK).send(db_types.parseOutputRows<db_types.OutputRow>(rows)); }); } catch (e) { console.error(`*** Failed: `, e); res.status(httpcodes.INTERNAL_SERVER_ERROR).send(JSON.stringify({ error: e.message })); } }); app.get('/api/page-title/:page_title', async (req, res) => { try { const page_title: runtime_types.PageTitleSearch = runtime_types.PageTitleSearch.assert(req.params.page_title); // TODO remove outer try wrapper unless it get used. const sqlQuery = `SELECT * FROM ${table} WHERE page_title = "${page_title}" LIMIT 100`; // Query options list: // https://cloud.google.com/spanner/docs/getting-started/nodejs/#query_data_using_sql const query: spanner.Query= { sql: sqlQuery }; await spannerDatabase.run(query).then(results => { const rows = results[0]; res.status(httpcodes.OK).send(db_types.parseOutputRows<db_types.OutputRow>(rows)); }); } catch (e) { console.error(`*** Failed: `, e); res.status(httpcodes.INTERNAL_SERVER_ERROR).send(JSON.stringify({ error: e.message })); } }); app.get('/api/search/:search_by/:search_op/:search_for', async (req, res) => { if (!SEARCH_BY_TYPE.isValid(req.params.search_by)) { const errorMsg = `Error: Invalid searchBy string: ${req.params.search_by}` console.error(errorMsg); res.status(httpcodes.BAD_REQUEST).send(JSON.stringify({error: errorMsg})); return; } if (!SEARCH_OP_TYPE.isValid(req.params.search_op)) { const errorMsg = `Error: Invalid searchOp string: ${req.params.search_op}` console.error(errorMsg); res.status(httpcodes.BAD_REQUEST).send(JSON.stringify({error: errorMsg})); return; } if (!SQL_SAFE_STRING.isValid(req.params.search_for)) { const errorMsg = `Error: Invalid searchFor string: ${req.params.search_for}` console.error(errorMsg); res.status(httpcodes.BAD_REQUEST).send(JSON.stringify({error: errorMsg})); return; } try { // TODO remove outer try wrapper unless it get used. const sqlQuery = `SELECT * FROM ${table} WHERE ${req.params.search_by} ${req.params.search_op} "${ req.params.search_for}" LIMIT 100`; // Query options list: // https://cloud.google.com/spanner/docs/getting-started/nodejs/#query_data_using_sql const query: spanner.Query = { sql: sqlQuery }; await spannerDatabase.run(query).then(results => { const rows = results[0]; res.status(httpcodes.OK).send(db_types.parseOutputRows<db_types.OutputRow>(rows)); }); } catch (e) { console.error(`*** Failed: `, e); res.status(httpcodes.INTERNAL_SERVER_ERROR).send(JSON.stringify({ error: e.message })); } }); }
the_stack
import { stringifyAssertion, stringifyExpression, stringifyTestCode } from './codegen'; import { Syntax, TestCode, Visitor, id, isValidAssignmentTarget, nullLoc, removeTestCodePrefix, replaceVarAssertion as replaceJSVarAssertion, replaceVarFunction as replaceJSVarFunction, replaceVarBlock as replaceJSVarBlock, uniqueIdentifier, eqSourceLocation, compEndPosition } from './javascript'; import { A, Classes, FreeVars, Heap, Locs, P, Vars, and, eq, falsy, fls, heapEq, heapStore, implies, not, or, removePrefix, replaceResultWithCall, replaceVar, transformClassInvariant, transformEveryInvariant, transformSpec, tru, truthy, und, Syntax as Logic, compareType } from './logic'; import { eraseTriggersProp } from './qi'; import { isMutable } from './scopes'; import { flatMap } from './util'; import VerificationCondition, { Assumption } from './verification'; import { generatePreamble } from './preamble'; export type BreakCondition = P; export type AccessTriggers = Array<Logic.AccessTrigger>; export class VCGenerator extends Visitor<[A, AccessTriggers, Syntax.Expression], [P, AccessTriggers, Syntax.Expression, TestCode], [A, Syntax.Expression], BreakCondition> { classes: Classes; oldHeap: Heap; heap: Heap; locs: Locs; vars: Vars; prop: P; vcs: Array<VerificationCondition>; resVar: string | null; freeVars: FreeVars; testBody: TestCode; assertionPolarity: true | false | undefined; simpleAssertion: boolean; assumptions: Array<string>; heapHints: Array<[Syntax.SourceLocation, Heap]>; constructor (classes: Classes, oldHeap: Heap, heap: Heap, locs: Locs, vars: Vars, assumptions: Array<string>, heapHints: Array<[Syntax.SourceLocation, Heap]>, assertionPolarity: true | false | undefined, prop: P) { super(); this.classes = classes; this.oldHeap = oldHeap; this.heap = heap; this.locs = locs; this.vars = vars; this.prop = prop; this.vcs = []; this.resVar = null; this.freeVars = []; this.testBody = []; this.simpleAssertion = true; this.assumptions = assumptions; this.heapHints = heapHints; this.assertionPolarity = assertionPolarity; } have (p: P, t: TestCode = []): void { this.prop = and(this.prop, p); this.testBody = this.testBody.concat(t); } check (assertion: Syntax.Expression): Syntax.Statement { return { type: 'ExpressionStatement', expression: { type: 'CallExpression', callee: id('assert'), args: [assertion], loc: assertion.loc }, loc: assertion.loc }; } visitComplexAssertion (assertion: Syntax.Assertion): [P, AccessTriggers, Syntax.Expression] { const origSimpleAssertion = this.simpleAssertion; try { this.simpleAssertion = false; const [p, triggers, e, t] = this.visitAssertion(assertion); if (t.length > 0) throw new Error('specs in in complex assertions not supported yet'); return [p, triggers, e]; } finally { this.simpleAssertion = origSimpleAssertion; } } assert (assertion: Syntax.Assertion, oldHeap: Heap = this.oldHeap, heap: Heap = this.heap): [P, AccessTriggers, TestCode] { const origOldHeap = this.oldHeap; const origHeap = this.heap; const origSimpleAssertion = this.simpleAssertion; try { this.oldHeap = oldHeap; this.heap = heap; this.simpleAssertion = true; const [assertP, assertTriggers, assertE, assertT] = this.visitAssertion(assertion); const checkT: Array<Syntax.Statement> = []; if (this.assertionPolarity !== false && (assertE.type !== 'Literal' || assertE.value !== true)) { checkT.push(this.check(assertE)); } return [assertP, assertTriggers, checkT.concat(assertT)]; } finally { this.heap = origHeap; this.oldHeap = origOldHeap; this.simpleAssertion = origSimpleAssertion; } } assume (assertion: Syntax.Assertion, oldHeap: Heap = this.oldHeap, heap: Heap = this.heap): [P, AccessTriggers, TestCode] { try { if (this.assertionPolarity === true) { this.assertionPolarity = false; } else if (this.assertionPolarity === false) { this.assertionPolarity = true; } return this.assert(assertion, oldHeap, heap); } finally { if (this.assertionPolarity === true) { this.assertionPolarity = false; } else if (this.assertionPolarity === false) { this.assertionPolarity = true; } } } tryPre<T> (pre: P, fn: () => T): [Heap, P, TestCode, T] { const origPre = this.prop; const origHeap = this.heap; const origBody = this.testBody; try { this.have(pre); const r = fn(); return [this.heap, removePrefix(and(origPre, pre), this.prop), removeTestCodePrefix(origBody, this.testBody), r]; } finally { this.prop = origPre; this.heap = origHeap; this.testBody = origBody; } } tryExpression (pre: P, expr: Syntax.Expression): [Heap, P, A, Syntax.Expression] { const [heap, p, tc, [a, e]] = this.tryPre(pre, () => { return this.visitExpression(expr); }); if (tc.length > 0) throw new Error('expected no new test statements'); return [heap, p, a, e]; } freshVar (): string { let i = 0; while (this.vars.has(`_tmp_${i}`)) i++; this.vars.add(`_tmp_${i}`); return `_tmp_${i}`; } freshThisVar (): string { let i = 0; while (this.vars.has(`_this_${i}`)) i++; this.vars.add(`_this_${i}`); return `_this_${i}`; } testVar (loc: Syntax.SourceLocation): string { return `_tmp_${uniqueIdentifier(loc)}`; } smtPlaceholder (name: string) { return id(`__free__${name}`); } freeVar (name: string, loc: Syntax.SourceLocation) { this.freeVars.push(name); this.testBody = this.testBody.concat([{ type: 'VariableDeclaration', id: id(name), init: this.smtPlaceholder(name), kind: 'let', loc: nullLoc() }, { type: 'VariableDeclaration', id: id(`old_${name}`, loc), init: id(name), kind: 'const', loc: nullLoc() }]); } freeLoc (name: string, loc: Syntax.SourceLocation) { this.freeVars.push({ name, heap: this.heap }); this.testBody = this.testBody.concat([{ type: 'ExpressionStatement', expression: { type: 'AssignmentExpression', left: id(name), right: this.smtPlaceholder(name), loc: nullLoc() }, loc: nullLoc() }, { type: 'VariableDeclaration', id: id(`old_${name}`, loc), init: id(name), kind: 'const', loc: nullLoc() }]); } verify (vc: P, testBody: TestCode, loc: Syntax.SourceLocation, desc: string, aliases: { [from: string]: string } = {}) { const assumptions: Array<Assumption> = this.assumptions.map((source: string): Assumption => ({ source, prop: tru, canBeDeleted: false })); this.vcs.push(new VerificationCondition(this.classes, this.heap, this.locs, this.vars, this.prop, assumptions, vc, loc, desc, this.freeVars, this.testBody, testBody, this.heapHints, aliases)); } compareType (expr: Syntax.Expression, type: 'boolean' | 'number' | 'string'): Syntax.Expression { return { type: 'BinaryExpression', operator: '===', left: { type: 'UnaryExpression', operator: 'typeof', argument: expr, loc: expr.loc }, right: { type: 'Literal', value: type, loc: expr.loc }, loc: expr.loc }; } compareTypePropAndTest (exprA: A, exprE: Syntax.Expression, type: 'boolean' | 'number' | 'string' | 'number or string' | 'int'): [P, Syntax.Expression] { switch (type) { case 'boolean': return [ compareType(exprA, 'boolean'), this.compareType(exprE, 'boolean') ]; case 'number': return [ compareType(exprA, 'number'), this.compareType(exprE, 'number') ]; case 'string': return [ compareType(exprA, 'string'), this.compareType(exprE, 'string') ]; case 'number or string': return [ or(compareType(exprA, 'number'), compareType(exprA, 'string')), { type: 'LogicalExpression', operator: '||', left: this.compareType(exprE, 'number'), right: this.compareType(exprE, 'string'), loc: exprE.loc } ]; case 'int': return [truthy({ type: 'IsIntegerExpression', expression: exprA }), { type: 'CallExpression', callee: { type: 'MemberExpression', object: id('Number', exprE.loc), property: { type: 'Literal', value: 'isInteger', loc: exprE.loc }, loc: exprE.loc }, args: [exprE], loc: exprE.loc }]; } } verifyType (expr: Syntax.Expression, exprA: A, exprE: Syntax.Expression, op: string, type: 'boolean' | 'number' | 'string' | 'number or string' | 'int') { const [prop, test] = this.compareTypePropAndTest(exprA, exprE, type); const msg = op === 'if' ? 'if condition' : `operator ${op}`; this.verify(prop, [this.check(test)], expr.loc, `${msg} requires ${type}: ${stringifyExpression(expr)}`); } heapHint (loc: Syntax.SourceLocation): void { // find index of heap hint const idx = this.heapHints.findIndex(([loc2]) => eqSourceLocation(loc, loc2)); if (idx >= 0) { this.heapHints[idx][1] = this.heap; } else { // no such hint yet // find index of first heap hint that is not earlier const idx = this.heapHints.findIndex(([loc2]) => !compEndPosition(loc, loc2)); if (idx >= 0) { this.heapHints.splice(idx, 0, [loc, this.heap]); } else { // no heap hint found that is later, so append this.heapHints.push([loc, this.heap]); } } } visitTerm (term: Syntax.Term): [A, AccessTriggers, Syntax.Expression] { try { return super.visitTerm(term); } finally { this.heapHint(term.loc); } } visitIdentifierTerm (term: Syntax.Identifier): [A, AccessTriggers, Syntax.Expression] { if (isMutable(term)) { return [{ type: 'HeapReference', heap: this.heap, loc: term.name }, [], term]; } else { return [term.name, [], term]; } } visitOldIdentifierTerm (term: Syntax.OldIdentifier): [A, AccessTriggers, Syntax.Expression] { if (!isMutable(term.id)) { throw new Error('not mutable'); } return [ { type: 'HeapReference', heap: this.oldHeap, loc: term.id.name }, [], id(`old_${term.id.name}`, term.loc) ]; } visitLiteralTerm (term: Syntax.Literal): [A, AccessTriggers, Syntax.Expression] { return [term, [], term]; } visitUnaryTerm (term: Syntax.UnaryTerm): [A, AccessTriggers, Syntax.Expression] { const [argumentA, argumentTriggers, argumentE] = this.visitTerm(term.argument); return [ { type: 'UnaryExpression', operator: term.operator, argument: argumentA }, argumentTriggers, { type: 'UnaryExpression', operator: term.operator, argument: argumentE, loc: term.loc } ]; } visitBinaryTerm (term: Syntax.BinaryTerm): [A, AccessTriggers, Syntax.Expression] { const [leftA, leftTriggers, leftE] = this.visitTerm(term.left); const [rightA, rightTriggers, rightE] = this.visitTerm(term.right); return [ { type: 'BinaryExpression', operator: term.operator, left: leftA, right: rightA }, leftTriggers.concat(rightTriggers), { type: 'BinaryExpression', operator: term.operator, left: leftE, right: rightE, loc: term.loc } ]; } visitLogicalTerm (term: Syntax.LogicalTerm): [A, AccessTriggers, Syntax.Expression] { const [leftA, leftTriggers, leftE] = this.visitTerm(term.left); const [rightA, rightTriggers, rightE] = this.visitTerm(term.right); switch (term.operator) { case '&&': return [ { type: 'ConditionalExpression', test: truthy(leftA), consequent: rightA, alternate: leftA }, leftTriggers.concat(rightTriggers), { type: 'LogicalExpression', operator: '&&', left: leftE, right: rightE, loc: term.loc } ]; case '||': return [ { type: 'ConditionalExpression', test: truthy(leftA), consequent: leftA, alternate: rightA }, leftTriggers.concat(rightTriggers), { type: 'LogicalExpression', operator: '||', left: leftE, right: rightE, loc: term.loc } ]; } } visitConditionalTerm (term: Syntax.ConditionalTerm): [A, AccessTriggers, Syntax.Expression] { const [testA, testTriggers, testE] = this.visitTerm(term.test); const [consequentA, consequentTriggers, consequentE] = this.visitTerm(term.consequent); const [alternateA, alternateTriggers, alternateE] = this.visitTerm(term.alternate); return [ { type: 'ConditionalExpression', test: truthy(testA), consequent: consequentA, alternate: alternateA }, [...testTriggers, ...consequentTriggers, ...alternateTriggers], { type: 'ConditionalExpression', test: testE, consequent: consequentE, alternate: alternateE, loc: term.loc } ]; } visitCallTerm (term: Syntax.CallTerm): [A, AccessTriggers, Syntax.Expression] { const [calleeA, calleeTriggers, calleeE] = this.visitTerm(term.callee); const args = term.args.map(a => this.visitTerm(a)); let thisArg: A = (typeof calleeA !== 'string' && calleeA.type === 'MemberExpression') ? calleeA.object : und; return [ { type: 'CallExpression', callee: calleeA, heap: this.heap, thisArg, args: args.map(([argA]) => argA) }, calleeTriggers.concat(flatMap(args, ([, argTriggers]) => argTriggers)), { type: 'CallExpression', callee: calleeE, args: args.map(([, , argE]) => argE), loc: term.loc } ]; } visitMemberTerm (term: Syntax.MemberTerm): [A, AccessTriggers, Syntax.Expression] { const [objectA, objectTriggers, objectE] = this.visitTerm(term.object); const [propertyA, propertyTriggers, propertyE] = this.visitTerm(term.property); return [ { type: 'MemberExpression', object: objectA, property: propertyA }, objectTriggers.concat(propertyTriggers, [{ type: 'AccessTrigger', object: objectA, property: propertyA, heap: this.heap, fuel: 1 }]), { type: 'MemberExpression', object: objectE, property: propertyE, loc: term.loc } ]; } visitIsIntegerTerm (term: Syntax.IsIntegerTerm): [A, AccessTriggers, Syntax.Expression] { const [termA, termTriggers, termE] = this.visitTerm(term.term); return [{ type: 'IsIntegerExpression', expression: termA }, termTriggers, { type: 'CallExpression', callee: { type: 'MemberExpression', object: id('Number', term.loc), property: { type: 'Literal', value: 'isInteger', loc: term.loc }, loc: term.loc }, args: [termE], loc: term.loc }]; } visitToIntegerTerm (term: Syntax.ToIntegerTerm): [A, AccessTriggers, Syntax.Expression] { const [termA, termTriggers, termE] = this.visitTerm(term.term); return [{ type: 'ToIntegerExpression', expression: termA }, termTriggers, { type: 'CallExpression', callee: { type: 'MemberExpression', object: id('Math', term.loc), property: { type: 'Literal', value: 'trunc', loc: term.loc }, loc: term.loc }, args: [termE], loc: term.loc }]; } visitAssertion (assertion: Syntax.Assertion): [P, AccessTriggers, Syntax.Expression, TestCode] { try { return super.visitAssertion(assertion); } finally { this.heapHint(assertion.loc); } } visitTermAssertion (term: Syntax.Term): [P, AccessTriggers, Syntax.Expression, TestCode] { const [termA, termTriggers, termE] = this.visitTerm(term); return [truthy(termA), termTriggers, termE, []]; } visitPureAssertion (assertion: Syntax.PureAssertion): [P, AccessTriggers, Syntax.Expression, TestCode] { const tru: Syntax.Expression = { type: 'Literal', value: true, loc: assertion.loc }; return [heapEq(this.heap, this.oldHeap), [], tru, []]; } insertWrapper (callee: Syntax.Expression, loc: Syntax.SourceLocation, args: Array<Syntax.Identifier>, rT: TestCode, retName: Syntax.Identifier, sT: TestCode): Syntax.Expression { return { type: 'CallExpression', callee: id('spec'), args: [ callee, { type: 'Literal', value: uniqueIdentifier(callee.loc), loc }, { type: 'FunctionExpression', id: null, params: args, requires: [], ensures: [], body: { type: 'BlockStatement', body: rT.concat({ type: 'ReturnStatement', argument: { type: 'ArrayExpression', elements: args, loc }, loc }), loc }, freeVars: [], loc }, { type: 'FunctionExpression', id: null, params: args.concat(retName), requires: [], ensures: [], body: { type: 'BlockStatement', body: sT.concat({ type: 'ReturnStatement', argument: retName, loc }), loc }, freeVars: [], loc } ], loc }; } visitSpecAssertion (assertion: Syntax.SpecAssertion): [P, AccessTriggers, Syntax.Expression, TestCode] { const [calleeA,, calleeE] = this.visitTerm(assertion.callee); // reserve fresh name for 'this' const thisArg = this.freshThisVar(); // translate pre and post const [rP,, rT] = this.assume(assertion.pre, this.heap + 1, this.heap + 1); const [sP,, sT] = this.assert(assertion.post.expression, this.heap + 1, this.heap + 2); // remove 'this' name from scope again this.vars.delete(thisArg); // rename 'this' to the name reserved above in the generated propositions const rP2 = assertion.hasThis ? replaceVar('this', thisArg, rP) : rP; const sP2 = assertion.hasThis ? replaceVar('this', thisArg, sP) : sP; const sP3 = replaceResultWithCall(calleeA, this.heap + 1, thisArg, assertion.args, assertion.post.argument && assertion.post.argument.name, sP2); const specP = transformSpec(calleeA, thisArg, assertion.args, rP2, sP3, this.heap + 1); const retName = assertion.post.argument === null ? id(`_res_${uniqueIdentifier(assertion.loc)}`) : assertion.post.argument; const specE: Syntax.Expression = { type: 'BinaryExpression', operator: '===', left: { type: 'UnaryExpression', operator: 'typeof', argument: calleeE, loc: assertion.loc }, right: { type: 'Literal', value: 'function', loc: assertion.loc }, loc: assertion.loc }; const specT: Array<Syntax.Statement> = []; if (this.simpleAssertion && isValidAssignmentTarget(calleeE)) { if (rT.length + sT.length > 0) { specT.push({ type: 'ExpressionStatement', expression: { type: 'AssignmentExpression', left: calleeE, right: this.insertWrapper(calleeE, assertion.loc, assertion.args.map(a => id(a)), rT, retName, sT), loc: assertion.loc }, loc: assertion.loc }); } if (this.assertionPolarity !== false) { if (specP.type !== 'And' || specP.clauses.length !== 2) { throw new Error('expected spec to translate to [fnCheck, forAll]'); } const forAllP: P = specP.clauses[1]; if (forAllP.type !== 'ForAllCalls') { throw new Error('expected spec to translate to [fnCheck, forAll]'); } const callStmt: Syntax.ExpressionStatement = { type: 'ExpressionStatement', expression: calleeE, loc: assertion.loc }; let lifted = false; forAllP.liftCallback = (renamedThis: string, renamedArgs: Array<string>) => { if (lifted) return; lifted = true; if (assertion.hasThis) { callStmt.expression = { type: 'CallExpression', callee: { type: 'MemberExpression', object: callStmt.expression, property: { type: 'Literal', value: 'call', loc: assertion.loc }, loc: assertion.loc }, args: [id(renamedThis)].concat(renamedArgs.map(arg => this.smtPlaceholder(arg))), loc: assertion.loc }; } else { callStmt.expression = { type: 'CallExpression', callee: callStmt.expression, args: renamedArgs.map(arg => this.smtPlaceholder(arg)), loc: assertion.loc }; } }; specT.push(callStmt); } } return [specP, [], specE, specT]; } visitEveryAssertion (assertion: Syntax.EveryAssertion): [P, AccessTriggers, Syntax.Expression, TestCode] { const [arrayA,, arrayE] = this.visitTerm(assertion.array); this.heap++; const [invP,, invE] = this.visitComplexAssertion(assertion.expression); this.heap--; const index = assertion.indexArgument !== null ? assertion.indexArgument.name : null; const everyP = transformEveryInvariant(arrayA, assertion.argument.name, index, invP, this.heap + 1); const everyE: Syntax.Expression = { type: 'LogicalExpression', operator: '&&', left: { type: 'InstanceOfExpression', left: arrayE, right: id('Array'), loc: assertion.loc }, right: { type: 'CallExpression', callee: { type: 'MemberExpression', object: arrayE, property: { type: 'Literal', value: 'every', loc: assertion.loc }, loc: assertion.loc }, args: [{ type: 'FunctionExpression', id: null, params: assertion.indexArgument !== null ? [assertion.argument, assertion.indexArgument] : [assertion.argument], requires: [], ensures: [], body: { type: 'BlockStatement', body: [{ type: 'ReturnStatement', argument: invE, loc: assertion.expression.loc }], loc: assertion.expression.loc }, freeVars: [], loc: assertion.expression.loc }], loc: assertion.loc }, loc: assertion.loc }; return [everyP, [], everyE, []]; } visitInstanceOfAssertion (assertion: Syntax.InstanceOfAssertion): [P, AccessTriggers, Syntax.Expression, TestCode] { const [leftA, leftTriggers, leftE] = this.visitTerm(assertion.left); return [ { type: 'InstanceOf', left: leftA, right: assertion.right.name }, leftTriggers, { type: 'InstanceOfExpression', left: leftE, right: assertion.right, loc: assertion.loc }, [] ]; } visitInAssertion (assertion: Syntax.InAssertion): [P, AccessTriggers, Syntax.Expression, TestCode] { const [objectA, objectTriggers, objectE] = this.visitTerm(assertion.object); const [propertyA, propertyTriggers, propertyE] = this.visitTerm(assertion.property); return [ { type: 'HasProperty', object: objectA, property: propertyA }, objectTriggers.concat(propertyTriggers), { type: 'InExpression', property: propertyE, object: objectE, loc: assertion.loc }, [] ]; } visitUnaryAssertion (assertion: Syntax.UnaryAssertion): [P, AccessTriggers, Syntax.Expression, TestCode] { const [argP, argTriggers, argE] = this.visitComplexAssertion(assertion.argument); let retE: Syntax.Expression; if (argE.type === 'Literal' && argE.value === true) { retE = { type: 'Literal', value: false, loc: assertion.loc }; } else if (argE.type === 'Literal' && argE.value === false) { retE = { type: 'Literal', value: true, loc: assertion.loc }; } else { retE = { type: 'UnaryExpression', argument: argE, operator: '!', loc: assertion.loc }; } return [not(argP), argTriggers, retE, []]; } visitBinaryAssertion (assertion: Syntax.BinaryAssertion): [P, AccessTriggers, Syntax.Expression, TestCode] { switch (assertion.operator) { case '&&': { const [leftP, leftTriggers, leftE, leftT] = this.visitAssertion(assertion.left); const [rightP, rightTriggers, rightE, rightT] = this.visitAssertion(assertion.right); let retE: Syntax.Expression; if (leftE.type === 'Literal' && leftE.value === true) { retE = rightE; } else if (rightE.type === 'Literal' && rightE.value === true) { retE = leftE; } else { retE = { type: 'LogicalExpression', operator: '&&', left: leftE, right: rightE, loc: assertion.loc }; } return [and(leftP, rightP), leftTriggers.concat(rightTriggers), retE, leftT.concat(rightT)]; } case '||': { const [leftP, leftTriggers, leftE] = this.visitComplexAssertion(assertion.left); const [rightP, rightTriggers, rightE] = this.visitComplexAssertion(assertion.right); let retE: Syntax.Expression; if (leftE.type === 'Literal' && leftE.value === false) { retE = rightE; } else if (rightE.type === 'Literal' && rightE.value === false) { retE = leftE; } else { retE = { type: 'LogicalExpression', operator: '||', left: leftE, right: rightE, loc: assertion.loc }; } return [or(leftP, rightP), leftTriggers.concat(rightTriggers), retE, []]; } } } visitExpression (expr: Syntax.Expression): [A, Syntax.Expression] { try { return super.visitExpression(expr); } finally { this.heapHint(expr.loc); } } visitIdentifier (expr: Syntax.Identifier): [A, Syntax.Expression] { if (isMutable(expr)) { return [{ type: 'HeapReference', heap: this.heap, loc: expr.name }, expr]; } else { return [expr.name, expr]; } } visitLiteral (expr: Syntax.Literal): [A, Syntax.Expression] { return [expr, expr]; } visitUnaryExpression (expr: Syntax.UnaryExpression): [A, Syntax.Expression] { const [argumentA, argumentE] = this.visitExpression(expr.argument); switch (expr.operator) { case '-': this.verifyType(expr.argument, argumentA, argumentE, '-', 'number'); break; case '+': this.verifyType(expr.argument, argumentA, argumentE, '+', 'number'); break; case '!': this.verifyType(expr.argument, argumentA, argumentE, '!', 'boolean'); break; case '~': this.verifyType(expr.argument, argumentA, argumentE, '~', 'number'); break; } return [ { type: 'UnaryExpression', operator: expr.operator, argument: argumentA }, { type: 'UnaryExpression', operator: expr.operator, argument: argumentE, loc: expr.loc }]; } visitBinaryExpression (expr: Syntax.BinaryExpression): [A, Syntax.Expression] { const [leftA, leftE] = this.visitExpression(expr.left); const [rightA, rightE] = this.visitExpression(expr.right); switch (expr.operator) { case '<': this.verifyType(expr.left, leftA, leftE, '<', 'number'); this.verifyType(expr.right, rightA, rightE, '<', 'number'); break; case '<=': this.verifyType(expr.left, leftA, leftE, '<=', 'number'); this.verifyType(expr.right, rightA, rightE, '<=', 'number'); break; case '>': this.verifyType(expr.left, leftA, leftE, '>', 'number'); this.verifyType(expr.right, rightA, rightE, '>', 'number'); break; case '>=': this.verifyType(expr.left, leftA, leftE, '>=', 'number'); this.verifyType(expr.right, rightA, rightE, '>=', 'number'); break; case '<<': this.verifyType(expr.left, leftA, leftE, '<<', 'int'); this.verifyType(expr.right, rightA, rightE, '<<', 'int'); break; case '>>': this.verifyType(expr.left, leftA, leftE, '>>', 'int'); this.verifyType(expr.right, rightA, rightE, '>>', 'int'); break; case '>>>': this.verifyType(expr.left, leftA, leftE, '>>>', 'int'); this.verifyType(expr.right, rightA, rightE, '>>>', 'int'); break; case '+': this.verifyType(expr.left, leftA, leftE, '+', 'number or string'); this.verifyType(expr.right, rightA, rightE, '+', 'number or string'); break; case '-': this.verifyType(expr.left, leftA, leftE, '-', 'number'); this.verifyType(expr.right, rightA, rightE, '-', 'number'); break; case '*': this.verifyType(expr.left, leftA, leftE, '*', 'number'); this.verifyType(expr.right, rightA, rightE, '*', 'number'); break; case '/': this.verifyType(expr.left, leftA, leftE, '/', 'number'); this.verifyType(expr.right, rightA, rightE, '/', 'number'); break; case '%': this.verifyType(expr.left, leftA, leftE, '%', 'int'); this.verifyType(expr.right, rightA, rightE, '%', 'int'); break; case '|': this.verifyType(expr.left, leftA, leftE, '|', 'int'); this.verifyType(expr.right, rightA, rightE, '|', 'int'); break; case '^': this.verifyType(expr.left, leftA, leftE, '^', 'int'); this.verifyType(expr.right, rightA, rightE, '^', 'int'); break; case '&': this.verifyType(expr.left, leftA, leftE, '&', 'int'); this.verifyType(expr.right, rightA, rightE, '&', 'int'); break; } return [ { type: 'BinaryExpression', operator: expr.operator, left: leftA, right: rightA }, { type: 'BinaryExpression', operator: expr.operator, left: leftE, right: rightE, loc: expr.loc }]; } visitLogicalExpression (expr: Syntax.LogicalExpression): [A, Syntax.Expression] { const [leftA, leftE] = this.visitExpression(expr.left); if (expr.operator === '&&') { const [rightHeap, rightPost, rightA, rightE] = this.tryExpression(truthy(leftA), expr.right); this.have(implies(truthy(leftA), rightPost)); this.have(implies(falsy(leftA), heapEq(rightHeap, this.heap))); this.heap = rightHeap; return [ { type: 'ConditionalExpression', test: truthy(leftA), consequent: rightA, alternate: leftA }, { type: 'LogicalExpression', operator: expr.operator, left: leftE, right: rightE, loc: expr.loc }]; } else { const [rightHeap, rightPost, rightA, rightE] = this.tryExpression(falsy(leftA), expr.right); this.have(implies(falsy(leftA), rightPost)); this.have(implies(truthy(leftA), heapEq(rightHeap, this.heap))); this.heap = rightHeap; return [ { type: 'ConditionalExpression', test: falsy(leftA), consequent: rightA, alternate: leftA }, { type: 'LogicalExpression', operator: expr.operator, left: leftE, right: rightE, loc: expr.loc }]; } } visitConditionalExpression (expr: Syntax.ConditionalExpression): [A, Syntax.Expression] { const [testA, testE] = this.visitExpression(expr.test); const [lHeap, lPost, lVal, lExpr] = this.tryExpression(truthy(testA), expr.consequent); const [rHeap, rPost, rVal, rExpr] = this.tryExpression(falsy(testA), expr.alternate); const newHeap = Math.max(lHeap, rHeap); this.have(implies(truthy(testA), and(lPost, heapEq(newHeap, lHeap)))); this.have(implies(falsy(testA), and(rPost, heapEq(newHeap, rHeap)))); this.heap = newHeap; return [ { type: 'ConditionalExpression', test: truthy(testA), consequent: lVal, alternate: rVal }, { type: 'ConditionalExpression', test: testE, consequent: lExpr, alternate: rExpr, loc: expr.loc }]; } visitAssignmentExpression (expr: Syntax.AssignmentExpression): [A, Syntax.Expression] { if (expr.left.type !== 'Identifier') throw new Error('unsupported'); const [rightA, rightE] = this.visitExpression(expr.right); this.have(heapStore(this.heap++, expr.left.name, rightA)); return [rightA, { type: 'AssignmentExpression', left: expr.left, right: rightE, loc: expr.loc }]; } visitSequenceExpression (expr: Syntax.SequenceExpression): [A, Syntax.Expression] { let val = und; const seqExpr: Syntax.SequenceExpression = { type: 'SequenceExpression', expressions: [], loc: expr.loc }; for (const e of expr.expressions) { const [exprA, exprE] = this.visitExpression(e); val = exprA; seqExpr.expressions.push(exprE); } return [val, seqExpr]; } visitCallExpression (expr: Syntax.CallExpression): [A, Syntax.Expression] { // evaluate callee const [callee, calleeE] = this.visitExpression(expr.callee); // determine this argument let thisArg: A = (typeof callee !== 'string' && callee.type === 'MemberExpression') ? callee.object : und; // evaluate arguments const argsAE: Array<[A, Syntax.Expression]> = expr.args.map(e => this.visitExpression(e)); const args: Array<A> = argsAE.map(([a]) => a); const argsE: Array<Syntax.Expression> = argsAE.map(([, e]) => e); const heap = this.heap; // apply call trigger this.have({ type: 'CallTrigger', callee, heap, thisArg, args, fuel: 1 }); // verify precondition const pre: P = { type: 'Precondition', callee, heap, thisArg, args }; const callExpr: Syntax.Expression = { type: 'CallExpression', callee: calleeE, args: argsE, loc: expr.loc }; const callStmt: TestCode = [{ type: 'ExpressionStatement', expression: callExpr, loc: expr.loc }]; this.verify(pre, callStmt, expr.loc, `precondition ${stringifyExpression(expr)}`); // assume postcondition this.have({ type: 'Postcondition', callee, heap, thisArg, args }); // function call effect this.have(heapEq(this.heap + 1, { type: 'HeapEffect', callee, heap, thisArg, args })); this.heap++; return [{ type: 'CallExpression', callee, heap, thisArg, args }, callExpr]; } visitNewExpression (expr: Syntax.NewExpression): [A, Syntax.Expression] { const argsAE: Array<[A, Syntax.Expression]> = expr.args.map(e => this.visitExpression(e)); const args: Array<A> = argsAE.map(([a]) => a); const argsE: Array<Syntax.Expression> = argsAE.map(([, e]) => e); if (expr.callee.decl.type !== 'Class') throw new Error('Class not resolved'); const clz: Syntax.ClassDeclaration = expr.callee.decl.decl; const object: A = { type: 'NewExpression', className: clz.id.name, args }; const [invP] = this.assert(clz.invariant, this.heap, this.heap); const newCode: Syntax.Expression = { type: 'NewExpression', callee: expr.callee, args: argsE, loc: expr.loc }; const testCode: TestCode = [{ type: 'ExpressionStatement', expression: { type: 'CallExpression', callee: { type: 'MemberExpression', object: newCode, property: { type: 'Literal', value: 'checkInvariant', loc: expr.loc }, loc: expr.loc }, args: [], loc: expr.loc }, loc: expr.loc }]; this.verify(replaceVar('this', object, invP), testCode, expr.loc, `class invariant ${clz.id.name}`); return [object, newCode]; } visitArrayExpression (expr: Syntax.ArrayExpression): [A, Syntax.Expression] { const elemsAE: Array<[A, Syntax.Expression]> = expr.elements.map(e => this.visitExpression(e)); const elems: Array<A> = elemsAE.map(([a]) => a); const elemsE: Array<Syntax.Expression> = elemsAE.map(([, e]) => e); const object = this.freshVar(); this.have({ type: 'InstanceOf', left: object, right: 'Array' }); const lengthProp: A = { type: 'Literal', value: 'length' }; const lengthVal: A = { type: 'Literal', value: elems.length }; this.have(eq({ type: 'MemberExpression', object, property: lengthProp }, lengthVal)); elems.forEach((property, idx) => { this.have(eq({ type: 'ArrayIndexExpression', array: object, index: { type: 'Literal', value: idx } }, elems[idx])); }); return [object, { type: 'ArrayExpression', elements: elemsE, loc: expr.loc }]; } visitObjectExpression (expr: Syntax.ObjectExpression): [A, Syntax.Expression] { const valuesAE: Array<[A, Syntax.Expression]> = expr.properties.map(({ value }) => this.visitExpression(value)); const values: Array<A> = valuesAE.map(([a]) => a); const valuesE: Array<Syntax.Expression> = valuesAE.map(([, e]) => e); const object = this.freshVar(); this.have({ type: 'InstanceOf', left: object, right: 'ObjectLiteral' }); this.have({ type: 'HasProperties', object, properties: expr.properties.map(({ key }) => key) }); expr.properties.forEach(({ key }, idx) => { this.have(eq({ type: 'MemberExpression', object, property: { type: 'Literal', value: key } }, values[idx])); }); return [ object, { type: 'ObjectExpression', properties: expr.properties.map(({ key }, idx) => ({ key, value: valuesE[idx] })), loc: expr.loc } ]; } visitInstanceOfExpression (expr: Syntax.InstanceOfExpression): [A, Syntax.Expression] { const [leftA, leftE] = this.visitExpression(expr.left); const test: P = { type: 'InstanceOf', left: leftA, right: expr.right.name }; const consequent: A = { type: 'Literal', value: true }; const alternate: A = { type: 'Literal', value: false }; return [ { type: 'ConditionalExpression', test, consequent, alternate }, { type: 'InstanceOfExpression', left: leftE, right: expr.right, loc: expr.loc }]; } visitInExpression (expr: Syntax.InExpression): [A, Syntax.Expression] { const [objectA, objectE] = this.visitExpression(expr.object); const [propertyA, propertyE] = this.visitExpression(expr.property); const test: P = { type: 'HasProperty', object: objectA, property: propertyA }; const consequent: A = { type: 'Literal', value: true }; const alternate: A = { type: 'Literal', value: false }; return [ { type: 'ConditionalExpression', test, consequent, alternate }, { type: 'InExpression', object: objectE, property: propertyE, loc: expr.loc }]; } visitMemberExpression (expr: Syntax.MemberExpression): [A, Syntax.Expression] { const [objectA, objectE] = this.visitExpression(expr.object); const [propertyA, propertyE] = this.visitExpression(expr.property); this.have({ type: 'AccessTrigger', heap: this.heap, object: objectA, property: propertyA, fuel: 1 }); this.verify( { type: 'HasProperty', object: objectA, property: propertyA }, [this.check({ type: 'InExpression', object: objectE, property: propertyE, loc: expr.loc })], expr.loc, `${stringifyExpression(expr.object)} has property ${stringifyExpression(expr.property)}`); return [ { type: 'MemberExpression', object: objectA, property: propertyA }, { type: 'MemberExpression', object: objectE, property: propertyE, loc: expr.loc }]; } visitFunctionExpression (expr: Syntax.FunctionExpression): [A, Syntax.Expression] { const callee = expr.id ? expr.id.name : this.freshVar(); const [preTestCode, postTestCode, testBody, inlinedSpec, retVar] = this.visitFunction(expr, callee); this.have(inlinedSpec); const testFuncExpr: Syntax.Expression = { type: 'FunctionExpression', id: expr.id, params: expr.params, requires: [], ensures: [], body: testBody, freeVars: expr.freeVars, loc: expr.loc }; if (preTestCode.length + postTestCode.length > 0) { return [callee, this.insertWrapper(testFuncExpr, expr.loc, expr.params, preTestCode, retVar, postTestCode)]; } { return [callee, testFuncExpr]; } } visitStatement (stmt: Syntax.Statement): BreakCondition { try { return super.visitStatement(stmt); } finally { this.heapHint(stmt.loc); } } tryStatement (pre: P, stmt: Syntax.Statement): [Heap, P, TestCode, BreakCondition] { return this.tryPre(pre, () => { return this.visitStatement(stmt); }); } tryBlockStatement (pre: P, stmt: Syntax.BlockStatement): [Heap, P, Syntax.BlockStatement, BreakCondition] { const [heap, p, testCode, bc] = this.tryStatement(pre, stmt); if (testCode.length !== 1) throw new Error('expected single block statement'); const blockStmt = testCode[0]; if (blockStmt.type !== 'BlockStatement') throw new Error('expected single block statement'); return [heap, p, blockStmt, bc]; } visitVariableDeclaration (stmt: Syntax.VariableDeclaration): BreakCondition { const [initA, initE] = this.visitExpression(stmt.init); const testCode: TestCode = [{ type: 'VariableDeclaration', id: stmt.id, init: initE, kind: 'let', loc: stmt.loc }]; if (stmt.kind === 'const') { this.vars.add(stmt.id.name); this.have(eq(stmt.id.name, initA), testCode); } else { this.locs.add(stmt.id.name); this.have(heapStore(this.heap, stmt.id.name, initA), testCode); this.heap++; } this.heapHint(stmt.id.loc); return fls; } visitBlockStatement (stmt: Syntax.BlockStatement): BreakCondition { let bc = fls; const origBody = this.testBody; for (const s of stmt.body) { const [tHeap, tProp, tTC, tBC] = this.tryStatement(not(bc), s); this.have(implies(bc, heapEq(tHeap, this.heap))); this.have(implies(not(bc), tProp), tTC); this.heap = tHeap; bc = or(bc, tBC); } const newStatements = removeTestCodePrefix(origBody, this.testBody); this.testBody = origBody.concat({ type: 'BlockStatement', body: [...newStatements], loc: stmt.loc }); return bc; } visitExpressionStatement (stmt: Syntax.ExpressionStatement): BreakCondition { const [, exprE] = this.visitExpression(stmt.expression); this.testBody = this.testBody.concat({ type: 'ExpressionStatement', expression: exprE, loc: stmt.loc }); return fls; } visitAssertStatement (stmt: Syntax.AssertStatement): BreakCondition { const [assertP, assertTriggers, assertT] = this.assert(stmt.expression); this.tryPre(and(...assertTriggers), () => { this.verify(assertP, assertT, stmt.expression.loc, 'assert: ' + stringifyAssertion(stmt.expression)); }); const [assumeP,, assumeT] = this.assume(stmt.expression); this.assumptions.push(stringifyAssertion(stmt.expression)); this.have(assumeP, assumeT); return fls; } visitIfStatement (stmt: Syntax.IfStatement): BreakCondition { const origBody = this.testBody; const [testA, testE] = this.visitExpression(stmt.test); this.verifyType(stmt.test, testA, testE, 'if', 'boolean'); this.testBody = this.testBody.concat({ type: 'ExpressionStatement', expression: testE, loc: stmt.test.loc }); const [lHeap, lProp, lTC, lBC] = this.tryBlockStatement(truthy(testA), stmt.consequent); const [rHeap, rProp, rTC, rBC] = this.tryBlockStatement(falsy(testA), stmt.alternate); const newHeap = Math.max(lHeap, rHeap); this.have(implies(truthy(testA), and(lProp, heapEq(newHeap, lHeap)))); this.have(implies(falsy(testA), and(rProp, heapEq(newHeap, rHeap)))); this.heap = newHeap; this.testBody = origBody.concat({ type: 'IfStatement', test: testE, consequent: lTC, alternate: rTC, loc: stmt.loc }); return or(and(truthy(testA), lBC), and(falsy(testA), rBC)); } visitReturnStatement (stmt: Syntax.ReturnStatement): BreakCondition { const [argA, argE] = this.visitExpression(stmt.argument); if (!this.resVar) throw new Error('return outside function'); this.have(eq(this.resVar, argA), [{ type: 'ReturnStatement', argument: argE, loc: stmt.loc }]); return tru; } visitWhileStatement (stmt: Syntax.WhileStatement): BreakCondition { // verify invariants on entry for (const inv of stmt.invariants) { const [invP, invTriggers, invT] = this.assert(inv, this.heap, this.heap); this.tryPre(and(...invTriggers), () => { this.verify(invP, invT, inv.loc, 'invariant on entry: ' + stringifyAssertion(inv)); }); } // havoc heap this.heap++; const startBody = this.testBody; // free mutable variables within the loop for (const fv of stmt.freeVars) { this.freeLoc(fv.name, fv.loc); } const startHeap = this.heap; const startProp = this.prop; // assume loop condition true and invariants true for (const inv of stmt.invariants) { const [invP,, invT] = this.assume(inv, this.heap, this.heap); this.have(invP, invT); this.assumptions.push(stringifyAssertion(inv)); } let [testEnterA, testEnterE] = this.visitExpression(stmt.test); this.have(truthy(testEnterA), [{ type: 'ExpressionStatement', expression: testEnterE, loc: stmt.test.loc }]); // internal verification conditions const bcBody = this.visitStatement(stmt.body); // ensure invariants maintained for (const inv of stmt.invariants) { const [invP, invTriggers, invT] = this.assert(inv, this.heap, this.heap); this.tryPre(and(...invTriggers), () => { this.verify(invP, invT, inv.loc, 'invariant maintained: ' + stringifyAssertion(inv)); }); } // we are going to use the returned verification conditions and break condition // but we will ignore its effects this.heap = startHeap; this.prop = startProp; const whileBody = this.testBody[this.testBody.length - 1]; if (whileBody.type !== 'BlockStatement') { throw new Error('expected while body to be single block statement'); } this.testBody = startBody.concat([{ type: 'WhileStatement', test: testEnterE, body: whileBody, invariants: stmt.invariants, freeVars: stmt.freeVars, loc: stmt.loc }]); for (const inv of stmt.invariants) { const [invP,, invT] = this.assume(inv, this.heap, this.heap); this.have(invP, invT); } // assume loop condition false and invariants true const [testExitA, testExitE] = this.visitExpression(stmt.test); this.have(falsy(testExitA), [{ type: 'ExpressionStatement', expression: testExitE, loc: stmt.test.loc }]); return and(truthy(testEnterA), bcBody); } visitDebuggerStatement (stmt: Syntax.DebuggerStatement): BreakCondition { this.testBody = this.testBody.concat({ type: 'DebuggerStatement', loc: stmt.loc }); return fls; } functionAsSpec (f: Syntax.Function): Syntax.SpecAssertion { if (f.id === null) throw new Error('can only create specs for named functions'); const pre: Syntax.Assertion = f.requires.reduceRight( (prev, req) => ({ type: 'BinaryAssertion', operator: '&&', left: req, right: prev, loc: req.loc }), { type: 'Literal', value: true, loc: f.loc }); const retName = id(`_res_${uniqueIdentifier(f.loc)}`); const post: Syntax.Assertion = f.ensures.reduceRight( (prev: Syntax.Assertion, ens): Syntax.Assertion => ({ type: 'BinaryAssertion', operator: '&&', left: ens.argument !== null ? replaceJSVarAssertion(ens.argument.name, retName, retName, ens.expression) : ens.expression, right: prev, loc: ens.loc }), { type: 'Literal', value: true, loc: f.loc }); return { type: 'SpecAssertion', callee: f.id, hasThis: f.type === 'MethodDeclaration', args: f.params.map(param => param.name), pre, post: { argument: retName, expression: post, loc: f.loc }, loc: f.loc }; } visitFunctionBody (f: Syntax.Function, funcName: string, thisArg: string): [P, Syntax.BlockStatement] { // add "this" argument this.vars.add(thisArg); this.freeVar(thisArg, nullLoc()); // add arguments to scope const args: Array<A> = []; for (const p of f.params) { args.push(p.name); this.vars.add(p.name); this.freeVar(p.name, p.loc); this.heapHint(p.loc); } for (const fv of f.freeVars) { this.freeLoc(fv.name, fv.loc); } // add special result variable this.resVar = this.freshVar(); let startBody = this.testBody; const startHeap = this.heap; this.oldHeap = this.heap; // assume non-rec spec if named function if (f.type !== 'MethodDeclaration' && f.id !== null) { const [fP,, fT] = this.assume(this.functionAsSpec(f)); const funDecl: TestCode = [{ type: 'FunctionDeclaration', id: f.id, params: f.params, requires: [], ensures: [], body: f.body, freeVars: f.freeVars, loc: f.loc }]; this.have(fP, funDecl.concat(fT)); } // assume preconditions for (const r of f.requires) { const [rP,, rT] = this.assume(r); startBody = startBody.concat(rT); this.have(rP, rT); this.assumptions.push(stringifyAssertion(r)); } const preBodyCode = this.testBody; const preBodyProp = this.prop; // internal verification conditions this.visitBlockStatement(f.body); const blockBody = removeTestCodePrefix(preBodyCode, this.testBody); if (blockBody.length !== 1) throw new Error('expected single block statement'); const blockStmt = blockBody[0]; if (blockStmt.type !== 'BlockStatement') throw new Error('expected single block statement'); this.have(eq(this.resVar, { type: 'CallExpression', callee: funcName, heap: startHeap, thisArg, args })); // assume function body and call if (f.type === 'MethodDeclaration') { this.testBody = startBody.concat([{ type: 'VariableDeclaration', id: id(this.resVar, f.loc), init: { type: 'CallExpression', callee: { type: 'MemberExpression', object: id(thisArg), property: { type: 'Literal', value: f.id.name, loc: f.loc }, loc: f.loc }, args: f.params, loc: f.loc }, kind: 'let', loc: f.loc }]); } else { this.testBody = startBody.concat([{ type: 'FunctionDeclaration', id: id(funcName), params: f.params, requires: [], ensures: [], body: f.body, freeVars: f.freeVars, loc: f.loc }, { type: 'VariableDeclaration', id: id(this.resVar), init: { type: 'CallExpression', callee: id(funcName), args: f.params, loc: f.loc }, kind: 'let', loc: f.loc }]); } // ensure post conditions for (const ens of f.ensures) { const ens2 = ens.argument !== null ? replaceJSVarAssertion(ens.argument.name, id(this.resVar), id(this.resVar), ens.expression) : ens.expression; const aliases: { [from: string]: string } = ens.argument !== null ? { [ens.argument.name]: this.resVar } : {}; const [ensP, ensTriggers, ensT] = this.assert(ens2); this.tryPre(and(...ensTriggers), () => { this.verify(ensP, ensT, ens.loc, stringifyAssertion(ens.expression), aliases); }); } this.vcs.forEach(vc => { vc.setDescription((f.id ? f.id.name : 'func') + ': ' + vc.getDescription()); }); // remove context and preconditions from prop for purpose of inlining return [removePrefix(preBodyProp, this.prop), blockStmt]; } createFunctionBodyInliner (): VCGenerator { return new VCGenerator(this.classes, this.heap + 1, this.heap + 1, new Set([...this.locs]), new Set([...this.vars]), [...this.assumptions], this.heapHints, this.assertionPolarity, this.prop); } visitFunction (fun: Syntax.Function, funcName: string): [TestCode, TestCode, Syntax.BlockStatement, P, Syntax.Identifier] { if (fun.type !== 'MethodDeclaration') { this.vars.add(funcName); } const inliner = this.createFunctionBodyInliner(); inliner.testBody = this.testBody; const thisArg = this.freshThisVar(); const renamedFunc = replaceJSVarFunction('this', id(thisArg), id(thisArg), fun); let [inlinedP, inlinedBlock] = inliner.visitFunctionBody(renamedFunc, funcName, thisArg); inlinedBlock = replaceJSVarBlock(thisArg, id('this'), id('this'), inlinedBlock); inliner.vcs.forEach(vc => vc.setDescription(vc.getDescription().replace(thisArg, 'this'))); this.vcs = this.vcs.concat(inliner.vcs); const existsLocs = new Set([...inliner.locs].filter(l => !this.locs.has(l))); const existsVars = new Set([...inliner.vars].filter(v => { return !this.vars.has(v) && !fun.params.some(n => n.name === v); })); const pre: Array<[P, AccessTriggers, TestCode]> = fun.requires.map(req => this.assert(req, this.heap + 1, this.heap + 1)); const retVar = this.testVar(fun.loc); const post: Array<[P, AccessTriggers, TestCode]> = fun.ensures.map(ens => { let ens2 = ens.expression; if (ens.argument !== null) { ens2 = replaceJSVarAssertion(ens.argument.name, id(retVar, ens.argument.loc), id(retVar, ens.argument.loc), ens2); } return this.assume(ens2, this.heap + 1, inliner.heap); }); const args: Array<string> = fun.params.map(p => p.name); const preP = pre.reduceRight((prev, [p]) => and(prev, replaceVar('this', thisArg, p)), tru); const postP = post.reduceRight((post, [p]) => { const p2 = replaceVar('this', thisArg, p); return and(post, replaceResultWithCall(funcName, this.heap + 1, thisArg, args, retVar, p2)); }, eraseTriggersProp(inlinedP)); const inlinedSpec = transformSpec(funcName, thisArg, args, preP, postP, this.heap + 1, inliner.heap, existsLocs, existsVars); return [flatMap(pre, ([,,c]) => c), flatMap(post, ([,,c]) => c), inlinedBlock, inlinedSpec, id(retVar)]; } visitFunctionDeclaration (stmt: Syntax.FunctionDeclaration): BreakCondition { const [preTestCode, postTestCode, blockStmt, inlinedSpec, retVar] = this.visitFunction(stmt, stmt.id.name); const testCode: Array<Syntax.Statement> = [{ type: 'FunctionDeclaration', id: stmt.id, params: stmt.params, requires: [], ensures: [], body: blockStmt, freeVars: stmt.freeVars, loc: stmt.loc }]; if (preTestCode.length + postTestCode.length > 0) { testCode.push({ type: 'ExpressionStatement', expression: { type: 'AssignmentExpression', left: stmt.id, right: this.insertWrapper(stmt.id, stmt.loc, stmt.params, preTestCode, retVar, postTestCode), loc: stmt.loc }, loc: stmt.loc }); } this.have(inlinedSpec, testCode); return fls; } visitClassDeclaration (stmt: Syntax.ClassDeclaration): BreakCondition { const startProp = this.prop; const startBody = this.testBody; // first assume non-recursive specs of methods const methodNames: Array<string> = []; const methodSpecs: Array<P> = []; const methodTestBodies: Array<Syntax.MethodDeclaration> = []; for (const method of stmt.methods) { method.requires.push({ type: 'InstanceOfAssertion', left: id('this', stmt.id.loc), right: stmt.id, loc: method.loc }); const globalMethodName = `${stmt.id.name}.${method.id.name}`; methodNames.push(method.id.name); const [fP,, fT] = this.assume(this.functionAsSpec(method)); methodSpecs.push(replaceVar(method.id.name, globalMethodName, fP)); methodTestBodies.push({ type: 'MethodDeclaration', id: method.id, params: method.params, requires: [], ensures: [], body: { type: 'BlockStatement', body: [{ type: 'FunctionDeclaration', id: method.id, params: method.params, requires: [], ensures: [], body: method.body, freeVars: method.freeVars, loc: method.loc }, ...fT, { type: 'ReturnStatement', argument: { type: 'CallExpression', callee: { type: 'MemberExpression', object: method.id, property: { type: 'Literal', value: 'call', loc: method.loc }, loc: method.loc }, args: [id('this'), ...method.params], loc: method.loc }, loc: method.loc }], loc: method.loc }, freeVars: method.freeVars, className: stmt.id.name, loc: method.loc }); } const [invP,, invT] = this.assert(stmt.invariant, this.heap, this.heap); this.classes.add({ cls: stmt.id.name, fields: stmt.fields, methods: methodNames }); this.have(and(...methodSpecs), this.classDeclarationCode(stmt, methodTestBodies, invT)); this.have(transformClassInvariant(stmt.id.name, 'this', stmt.fields, invP, this.heap)); // verify inidivual function bodies const preMethodProp = this.prop; const preMethodBody = this.testBody; const inlinedMethodSpecs: Array<P> = []; const inlinedMethodTestBodies: Array<Syntax.MethodDeclaration> = []; for (const method of stmt.methods) { const globalMethodName = `${stmt.id.name}.${method.id.name}`; this.prop = preMethodProp; this.testBody = preMethodBody; const [preTestCode, postTestCode, blockStmt, inlinedSpec, retVar] = this.visitFunction(method, globalMethodName); inlinedMethodSpecs.push(inlinedSpec); inlinedMethodTestBodies.push({ type: 'MethodDeclaration', id: method.id, params: method.params, requires: [], ensures: [], body: preTestCode.length + postTestCode.length === 0 ? blockStmt : { type: 'BlockStatement', body: [{ type: 'FunctionDeclaration', id: method.id, params: method.params, requires: [], ensures: [], body: blockStmt, freeVars: method.freeVars, loc: method.loc }, { type: 'ExpressionStatement', expression: { type: 'AssignmentExpression', left: method.id, right: this.insertWrapper(method.id, method.loc, method.params, preTestCode, retVar, postTestCode), loc: stmt.loc }, loc: stmt.loc }, { type: 'ReturnStatement', argument: { type: 'CallExpression', callee: { type: 'MemberExpression', object: method.id, property: { type: 'Literal', value: 'call', loc: method.loc }, loc: method.loc }, args: [id('this'), ...method.params], loc: method.loc }, loc: method.loc }], loc: method.loc }, freeVars: method.freeVars, className: stmt.id.name, loc: method.loc }); } // now use rewritten function bodies and assume inlined specs for methods this.prop = startProp; this.testBody = startBody; this.have(and(...inlinedMethodSpecs), this.classDeclarationCode(stmt, inlinedMethodTestBodies, invT)); this.have(transformClassInvariant(stmt.id.name, 'this', stmt.fields, invP, this.heap)); return fls; } classDeclarationCode (clsDef: Syntax.ClassDeclaration, methods: Array<Syntax.MethodDeclaration>, invT: TestCode): TestCode { const checkInvariant: Array<Syntax.MethodDeclaration> = [{ type: 'MethodDeclaration', id: id('checkInvariant', clsDef.invariant.loc), params: [], requires: [], ensures: [], body: { type: 'BlockStatement', body: [...invT], loc: clsDef.invariant.loc }, freeVars: [], className: clsDef.id.name, loc: clsDef.invariant.loc }]; return [{ type: 'ClassDeclaration', id: clsDef.id, fields: clsDef.fields, invariant: { type: 'Literal', value: true, loc: clsDef.invariant.loc }, methods: checkInvariant.concat(methods), loc: clsDef.loc }]; } visitProgram (prog: Syntax.Program): BreakCondition { // go through all statements for (const stmt of prog.body) { if (stmt.type === 'FunctionDeclaration') { // function should maintain invariants prog.invariants.forEach(inv => { stmt.requires.push(inv); stmt.ensures.push({ argument: null, expression: inv, loc: inv.loc }); }); } this.visitStatement(stmt); } // main program body needs to establish invariants for (const inv of prog.invariants) { const [assertP, assertTriggers, assertT] = this.assert(inv); this.tryPre(and(...assertTriggers), () => { this.verify(assertP, assertT, inv.loc, 'initially: ' + stringifyAssertion(inv)); }); const [assumeP,, assumeT] = this.assume(inv); this.have(assumeP, assumeT); this.assumptions.push(stringifyAssertion(inv)); } return fls; } } export function vcgenProgram (prog: Syntax.Program): Array<VerificationCondition> { const { classes, heap, locs, vars, prop } = generatePreamble(); const vcgen = new VCGenerator(classes, heap, heap, locs, vars, [], [], true, prop); vcgen.visitProgram(prog); return vcgen.vcs; } export function transformProgram (prog: Syntax.Program): string { const { classes, heap, locs, vars, prop } = generatePreamble(); const vcgen = new VCGenerator(classes, heap, heap, locs, vars, [], [], undefined, prop); vcgen.visitProgram(prog); return stringifyTestCode(vcgen.testBody); }
the_stack
import { select } from 'd3-selection'; import { formatStats } from './formatStats'; import { manuallyWrapText } from './textHelpers'; import { easeCircleIn } from 'd3-ease'; import { timeFormat } from 'd3-time-format'; const tickArguments = []; let tickValues = null; let transitionDuration = 750; let orient = 1; let tickFormat = null; let tickSizeInner = 6; let tickSizeOuter = 6; let tickPadding = 3; let xOffset = 0; let yOffset = 0; let tickWidth = 0; let scale: any; let hideAxisPath: any; let k = 1; let x = 'x'; let transform = translateX; const orientTop = 1; const orientRight = 2; const orientBottom = 3; const orientLeft = 4; const epsilon = 1e-6; export const drawAxis = ({ root, height, width, axisScale, left, right, top, wrapLabel, format, dateFormat, tickInterval, label, padding, hide, markOffset, hidePath, ticks, duration }: { root?: any; height?: any; width?: any; axisScale?: any; left?: any; right?: any; top?: any; bottom?: any; wrapLabel?: any; format?: any; dateFormat?: '%b'; tickInterval?: any; label?: any; padding?: any; hide?: any; markOffset?: any; hidePath?: any; ticks?: any; duration?: number; }) => { transitionDuration = duration || duration === 0 ? duration : transitionDuration; scale = axisScale; hideAxisPath = hidePath; tickValues = ticks ? ticks : null; let opacity = 1; if (hide) { opacity = 0; } tickWidth = wrapLabel ? wrapLabel : 0; if (markOffset) { // mark line at x=0 if (left) { let axisBase = root.selectAll('.axis-mark-y'); if (axisBase.empty()) { transitionDuration = 0; axisBase = root.append('g').attr('class', 'axis-mark-y axis-mark'); } tickFormat = () => null; orient = orientLeft; setOrientation(); let context = axisBase.attr('data-testid', 'y-axis-mark'); // .attr('transform', markOffset > 0 ? `translate(${markOffset}, 0)` : '') if (transitionDuration) { context = context .transition('axis_base') .ease(easeCircleIn) .duration(transitionDuration); } context .attr('transform', markOffset > 0 ? `translate(${markOffset}, 0)` : '') .attr('opacity', opacity) .call(axis); } else { // mark line at y=0 let axisBase = root.selectAll('.axis-mark-x'); if (axisBase.empty()) { transitionDuration = 0; axisBase = root.append('g'); } tickFormat = () => null; orient = orientBottom; setOrientation(); let context = axisBase.attr('class', 'axis-mark-x axis-mark').attr('data-testid', 'x-axis-mark'); if (transitionDuration) { context = context .transition('axis_base') .ease(easeCircleIn) .duration(transitionDuration); } context .attr('transform', markOffset > 0 ? `translate(0, ${markOffset})` : '') .attr('opacity', opacity) .call(axis); } } else if (left) { // left y axis let axisNode = root .selectAll('.axis') .filter('.y') .filter('.left'); let axisLabel = root .selectAll('.axis-label') .filter('.y') .filter('.left'); if (axisNode.empty()) { transitionDuration = 0; axisNode = root.append('g'); axisLabel = root.append('text'); } tickFormat = (data, i) => { if (tickInterval && i % tickInterval !== 0) { return null; } else if (format && typeof data === 'number') { return formatStats(data, format); } else if (data instanceof Date) { const formatTime = timeFormat(dateFormat); return formatTime(data); } else { return data; } }; tickSizeInner = 0; tickSizeOuter = 0; tickPadding = 10; if (tickWidth) { xOffset = -8; yOffset = 0.6; } orient = orientLeft; setOrientation(); let context = axisNode.attr('class', 'y axis left').attr('data-testid', 'y-axis'); if (transitionDuration) { context = context .transition('axis_node') .ease(easeCircleIn) .duration(transitionDuration); } context.attr('opacity', opacity).call(axis); let labelContext = axisLabel .attr('class', 'y axis-label left') .attr('data-testid', 'y-axis-label') .attr('transform', `rotate(-90)`) .text(label); if (transitionDuration) { labelContext = labelContext .transition('axis_label') .ease(easeCircleIn) .duration(transitionDuration); } labelContext .attr('y', padding ? 0 - padding.left : -50) .attr('x', 0 - height / 2) .attr('dy', '1em'); // .attr("opacity",opacity); } else if (right) { // right y axis let axisNode = root .selectAll('.axis') .filter('.y') .filter('.right'); let axisLabel = root .selectAll('.axis-label') .filter('.y') .filter('.right'); if (axisNode.empty()) { transitionDuration = 0; axisNode = root.append('g'); axisLabel = root.append('text'); } tickFormat = (data, i) => { if (tickInterval && i % tickInterval !== 0) { return null; } else if (format && typeof data === 'number') { return formatStats(data, format); } else if (data instanceof Date) { const formatTime = timeFormat(dateFormat); return formatTime(data); } else { return data; } }; tickSizeInner = 0; tickSizeOuter = 0; tickPadding = 10; if (tickWidth) { xOffset = 8; yOffset = 0.6; } orient = orientRight; setOrientation(); let context = axisNode.attr('class', 'y axis right').attr('data-testid', 'sec-y-axis'); if (transitionDuration) { context = context .transition('axis_node') .ease(easeCircleIn) .duration(transitionDuration); } context .attr('transform', `translate(${width},0)`) .attr('opacity', opacity) .call(axis); let labelContext = axisLabel .attr('class', 'y axis-label right') .attr('data-testid', 'sec-y-axis-label') .attr('transform', `rotate(-90)`) .text(label || 'Cumulative Percentage'); if (transitionDuration) { labelContext = labelContext .transition('axis_label') .ease(easeCircleIn) .duration(transitionDuration); } labelContext .attr('y', padding ? width + padding.left + padding.right - 50 : width - 50) .attr('x', 0 - height / 2) .attr('dy', '1em'); // .attr("opacity",opacity); } else if (top) { // x axis on top let axisNode = root .selectAll('.axis') .filter('.x') .filter('.top'); let axisLabel = root .selectAll('.axis-label') .filter('.x') .filter('.top'); if (axisNode.empty()) { transitionDuration = 0; axisNode = root.append('g'); axisLabel = root.append('text'); } tickFormat = (data, i) => { if (tickInterval && i % tickInterval !== 0) { return null; } else if (format && typeof data === 'number') { return formatStats(data, format); } else if (data instanceof Date) { const formatTime = timeFormat(dateFormat); return formatTime(data); } else { return data; } }; tickSizeInner = 0; tickSizeOuter = 0; tickPadding = 10; if (tickWidth) { xOffset = 0; yOffset = 1; } orient = orientTop; setOrientation(); let context = axisNode.attr('class', 'x axis top').attr('data-testid', 'sec-x-axis'); if (transitionDuration) { context = context .transition('axis_node') .ease(easeCircleIn) .duration(transitionDuration); } context .attr('transform', `translate(0, 0)`) .attr('opacity', opacity) .call(axis); let labelContext = axisLabel .attr('class', 'x axis-label top') .attr('data-testid', 'sec-x-axis-label') .attr('transform', `translate(0, 0)`) .text(format && typeof label === 'number' ? formatStats(label, format) : label); if (transitionDuration) { labelContext = labelContext .transition('axis_label') .ease(easeCircleIn) .duration(transitionDuration); } labelContext .attr('x', width / 2) .attr('y', padding ? -padding.top : -50) .attr('dy', '1em'); // .attr("opacity",opacity); } else { // x axis at bottom let axisNode = root .selectAll('.axis') .filter('.x') .filter('.bottom'); let axisLabel = root .selectAll('.axis-label') .filter('.x') .filter('.bottom'); if (axisNode.empty()) { transitionDuration = 0; axisNode = root.append('g'); axisLabel = root.append('text'); } tickFormat = (data, i) => { if (tickInterval && i % tickInterval !== 0) { return null; } else if (format && typeof data === 'number') { return formatStats(data, format); } else if (data instanceof Date) { const formatTime = timeFormat(dateFormat); return formatTime(data); } else { return data; } }; tickSizeInner = 0; tickSizeOuter = 0; tickPadding = 10; if (tickWidth) { xOffset = 0; yOffset = 1; } orient = orientBottom; setOrientation(); let context = axisNode.attr('class', 'x axis bottom').attr('data-testid', 'x-axis'); if (transitionDuration) { context = context .transition('axis_node') .ease(easeCircleIn) .duration(transitionDuration); } context .attr('transform', `translate(0, ${height})`) .attr('opacity', opacity) .call(axis); let labelContext = axisLabel .attr('class', 'x axis-label bottom') .attr('data-testid', 'x-axis-label') .attr('transform', `translate(0, 0)`) .text(format && typeof label === 'number' ? formatStats(label, format) : label); if (transitionDuration) { labelContext = labelContext .transition('axis_node') .ease(easeCircleIn) .duration(transitionDuration); } labelContext.attr('x', width / 2).attr('y', padding ? height + padding.bottom : height); // .attr("opacity",opacity); } // transitionDuration = 750; }; function axis(context: any) { const values = tickValues == null ? (scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain()) : tickValues; const format = tickFormat == null ? (scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : identity) : tickFormat; const spacing = Math.max(tickSizeInner, 0) + tickPadding; const range = scale.range(); const range0 = +range[0] + 0.5; const range1 = +range[range.length - 1] + 0.5; const position = (scale.bandwidth ? center : number)(scale.copy()); const selection = context.selection ? context.selection() : context; let path = selection.selectAll('.domain').data([null]); let tick = selection .selectAll('.tick') .data(values, scale) .order(); let tickExit = tick.exit(); const tickEnter = tick .enter() .append('g') .attr('class', 'tick') .attr('data-testid', 'axis-tick'); let line = tick.select('line'); let text = tick.select('text'); path = path.merge( path .enter() .insert('path', '.tick') .attr('class', 'domain') .attr('stroke', 'currentColor') ); selection.selectAll('.domain').attr('class', hideAxisPath ? 'domain hidden' : 'domain'); tick = tick.merge(tickEnter); line = line.merge( tickEnter .append('line') .attr('data-testid', 'axis-tick-line') .attr('stroke', 'currentColor') .attr(x + '2', k * tickSizeInner) ); if (!scale.formattedTicks) { scale.formattedTicks = []; } text = text .merge( tickEnter .append('text') .attr('data-testid', 'axis-tick-text') .attr('fill', 'currentColor') .attr(x, k * spacing) .attr('dy', orient === orientTop ? '0em' : orient === orientBottom ? '0.71em' : '0.32em') ) .text((d, i) => { if (format(d, i)) { scale.formattedTicks.push(format(d, i)); } return format(d, i); }); if (tickWidth > 0) { text.call(wrap); } if (context !== selection && transitionDuration) { path = path .transition(context) .duration(transitionDuration) .ease(easeCircleIn); tick = tick .transition(context) .duration(transitionDuration) .ease(easeCircleIn); line = line .transition(context) .duration(transitionDuration) .ease(easeCircleIn); text = text .transition(context) .duration(transitionDuration) .ease(easeCircleIn); tickExit = tickExit .transition(context) .attr('opacity', epsilon) .attr('transform', function(d) { return isFinite((d = position(d))) ? transform(d) : this.getAttribute('transform'); }); tickEnter.attr('opacity', epsilon).attr('transform', function(d) { let p = this.parentNode.__axis; return transform(p && isFinite((p = p(d))) ? p : position(d)); }); } tickExit.remove(); path.attr( 'd', orient === orientLeft || orient === orientRight ? tickSizeOuter ? 'M' + k * tickSizeOuter + ',' + range0 + 'H0.5V' + range1 + 'H' + k * tickSizeOuter : 'M0.5,' + range0 + 'V' + range1 : tickSizeOuter ? 'M' + range0 + ',' + k * tickSizeOuter + 'V0.5H' + range1 + 'V' + k * tickSizeOuter : 'M' + range0 + ',0.5H' + range1 ); tick.attr('opacity', 1).attr('transform', d => transform(position(d))); line.attr(x + '2', k * tickSizeInner); text.attr(x, k * spacing); selection .filter(entering) .attr('fill', 'none') .attr('font-size', 10) .attr('font-family', 'sans-serif') .attr('text-anchor', orient === orientRight ? 'start' : orient === orientLeft ? 'end' : 'middle'); selection.each(function() { this.__axis = position; }); } export function wrap(selection: any) { selection.each(function() { const text = select(this); const words = manuallyWrapText({ text: text.text(), width: tickWidth, fontSize: 12, noPadding: false, wholeWords: false }); const lineHeight = yOffset; // ems let lineNumber = 0; const y = text.attr('y'); const dy = parseFloat(text.attr('dy')); text.text(null); words.forEach(word => { text .append('tspan') .attr('data-testid', 'axis-tick-text-tspan') .attr('x', xOffset) .attr('y', y) .attr('dy', lineNumber * lineHeight + dy + 'em') .text(word); lineNumber++; }); }); } function setOrientation() { k = orient === orientTop || orient === orientLeft ? -1 : 1; x = orient === orientLeft || orient === orientRight ? 'x' : 'y'; transform = orient === orientTop || orient === orientBottom ? translateX : translateY; } function identity(id) { return id; } function translateX(xPos) { return 'translate(' + (xPos + 0.5) + ',0)'; } function translateY(yPos) { return 'translate(0,' + (yPos + 0.5) + ')'; } function number(scaleFunction) { return d => { return +scaleFunction(d); }; } function center(scaleFunction) { let offset = Math.max(0, scaleFunction.bandwidth() - 1) / 2; // Adjust for 0.5px offset. if (scaleFunction.round()) { offset = Math.round(offset); } return d => { return +scaleFunction(d) + offset; }; } function entering() { return !this.__axis; }
the_stack
import { IContractInfo } from "./../../adapters/ethereum-blockchain/structs/contract-info"; import { ProcessCEMetadata } from "../../adapters/mongo-db/repo-models"; import { PromiseError, Component } from "./../../adapters/errors/promise-error"; import { AccountInfo } from "../../adapters/ethereum-blockchain/structs/account-info"; import { FunctionInfo } from "../../adapters/ethereum-blockchain/structs/function-info"; import { TypeMessage, print, printSeparator, } from "../../adapters/messages/console-log"; import { ContractInfo } from "../../adapters/ethereum-blockchain/structs/contract-info"; import * as ethereumAdapter from "../../adapters/ethereum-blockchain/ethereum-adapter"; import * as mongoDBAdapper from "../../adapters/mongo-db/mongo-db-adapter"; import { RepoType } from "../../adapters/mongo-db/repo-types"; let defaultAccount: AccountInfo; export let createProcessInstance = async ( processId: string, runtimeRegistry: ContractInfo, accessCtrolAddr: string, rbPolicyAddr: string, taskRoleMapAddr: string ) => { if (!defaultAccount) defaultAccount = await ethereumAdapter.defaultDeployment(); return await ethereumAdapter.execContractFunctionAsync( runtimeRegistry.address, runtimeRegistry.abi, new FunctionInfo("newRestrictedCInstanceFor", ["bytes32", "address", "address", "address", "address"]), defaultAccount, [ processId, "0x0000000000000000000000000000000000000000", accessCtrolAddr, rbPolicyAddr, taskRoleMapAddr ] ); }; export let handleNewInstance = ( contractName: string, repoId: string, transactionHash: string, processAddress: string, gasUsed: number ) => { print( `New Instance of contract ${contractName} (ID: ${repoId}) Created`, TypeMessage.success ); print(` TransactionHash: ${transactionHash}`, TypeMessage.info); print(` Address: ${processAddress}`, TypeMessage.info); print(` GasUsed: ${gasUsed} units`, TypeMessage.info); printSeparator(); }; export let handleWorkitemExecuted = ( taskName: string, workitemIndex: number, worklistAddress: string, transactionHash: string, gasUsed: number ) => { print( `Task ${taskName} (Workitem: ${workitemIndex} in worklist at ${worklistAddress}) executed successfully`, TypeMessage.success ); print(` TransactionHash: ${transactionHash}`, TypeMessage.info); print(` GasUsed: ${gasUsed} units`, TypeMessage.info); printSeparator(); }; export let queryProcessState = async ( pAddress: string, runtimeRegistry: ContractInfo ) => { if (!ethereumAdapter.isValidBlockchainAddress(pAddress)) return Promise.reject(`Invalid Process Instance Address ${pAddress}`); try { let defaultAccount = await ethereumAdapter.defaultDeployment(); let nestedContractsQueue = [pAddress]; let enabledWorkitems = []; for (let i = 0; i < nestedContractsQueue.length; i++) { pAddress = nestedContractsQueue[i]; let pId = await ethereumAdapter.callContractFunction( runtimeRegistry.address, runtimeRegistry.abi, new FunctionInfo("bundleFor", ["address"], "bytes32"), defaultAccount, [pAddress] ); let processInfo = await mongoDBAdapper.findModelMetadataById( RepoType.ProcessCompiledEngine, pId ); let worklistAddress = await ethereumAdapter.callContractFunction( pAddress, processInfo.contractInfo.abi, new FunctionInfo("getWorklistAddress", [], "address"), defaultAccount, [] ); let startedActivities = ethereumAdapter.toBinaryArray( await ethereumAdapter.callContractFunction( pAddress, processInfo.contractInfo.abi, new FunctionInfo("startedActivities", [], "uint"), defaultAccount, [] ) ); let dictionary = (processInfo as ProcessCEMetadata).indexToElementMap; let worklistAbi = (processInfo as ProcessCEMetadata).worklistABI; for (let bit = 0; bit < startedActivities.length; bit++) { if (startedActivities[bit] === "1") { if (dictionary[bit].type === "Workitem") { let reqInd = ethereumAdapter.toBinaryArray( await ethereumAdapter.callContractFunction( worklistAddress, worklistAbi, new FunctionInfo( "workItemsFor", ["uint256", "address"], "uint256" ), defaultAccount, [bit, pAddress] ) ); for (let l = 0; l < reqInd.length; l++) { if (reqInd[l] === "1") { let notFound = true; for (let m = 0; m < enabledWorkitems.length; m++) { if ( enabledWorkitems[m].elementId === dictionary[bit].id && enabledWorkitems[m].bundleId === pId ) { enabledWorkitems[m].hrefs.push( `/worklists/${worklistAddress}/workitems/${l}` ); enabledWorkitems[m].pCases.push( await ethereumAdapter.callContractFunction( worklistAddress, worklistAbi, new FunctionInfo( "processInstanceFor", ["uint"], "address" ), defaultAccount, [l] ) ); notFound = false; break; } } if (notFound) { enabledWorkitems.push({ elementId: dictionary[bit].id, elementName: dictionary[bit].name, input: findParameters(worklistAbi, dictionary[bit].name), bundleId: pId, processAddress: pAddress, pCases: [pAddress], hrefs: [`/worklists/${worklistAddress}/workitems/${l}`], }); } } } } else if (dictionary[bit].type === "Service") { // PENDING } else if (dictionary[bit].type === "Separate-Instance") { let startedInstances = ethereumAdapter.toBinaryArray( await ethereumAdapter.callContractFunction( pAddress, processInfo.contractInfo.abi, new FunctionInfo( "startedInstanceIndexFor", ["uint256"], "uint256" ), defaultAccount, [bit] ) ); let allInstances = await ethereumAdapter.callContractFunction( pAddress, processInfo.contractInfo.abi, new FunctionInfo("allInstanceAddresses", [], "address[]"), defaultAccount, [] ); for (let l = 0; l < startedInstances.length; l++) if (startedInstances[l] === "1") nestedContractsQueue.push(allInstances[l]); } } } } print("Started Workitems (Enabled Tasks) Info: "); print(JSON.stringify(enabledWorkitems), TypeMessage.data); printSeparator(); return enabledWorkitems; } catch (error) { return Promise.reject( new PromiseError( `Error Qerying the state of process instance at address ${pAddress}`, error, [new Component("execution-monitor", "queryProcessState")] ) ); } }; export let executeWorkitem = async ( wlAddress: string, wiIndex: number, inputParameters: Array<any>, runtimeRegistry: ContractInfo ) => { try { if (!ethereumAdapter.isValidBlockchainAddress(wlAddress)) return Promise.reject(`Invalid Worklist Instance Address ${wlAddress}`); let defaultAccount = await ethereumAdapter.defaultDeployment(); let pId = await ethereumAdapter.callContractFunction( runtimeRegistry.address, runtimeRegistry.abi, new FunctionInfo("worklistBundleFor", ["address"], "bytes32"), defaultAccount, [wlAddress] ); let processInfo = await mongoDBAdapper.findModelMetadataById( RepoType.ProcessCompiledEngine, pId ); let worklistAbi = (processInfo as ProcessCEMetadata).worklistABI; let nodeIndex = await ethereumAdapter.callContractFunction( wlAddress, worklistAbi, new FunctionInfo("elementIndexFor", ["uint256"], "uint256"), defaultAccount, [wiIndex] ); let taskInfo = (processInfo as ProcessCEMetadata).indexToElementMap[ nodeIndex ]; inputParameters = [wiIndex].concat(inputParameters); print( `Starting Execution of Task ${taskInfo.name}, on worklist ${wlAddress}`, TypeMessage.pending ); let transactionHash = await ethereumAdapter.execContractFunctionAsync( wlAddress, worklistAbi, new FunctionInfo(taskInfo.name, ["uint256", "bool"]), defaultAccount, inputParameters ); return { transactionHash: transactionHash, worklistAbi: worklistAbi, taskName: taskInfo.name, }; } catch (error) { return Promise.reject( new PromiseError( `Error Executing Workitme from Worklist at address ${wlAddress}`, error, [new Component("execution-monitor", "executeWorkitem")] ) ); } }; //////////////////////////////////////////////// /////////////// PRIVATE FUNCTIONS ////////////// //////////////////////////////////////////////// let findParameters = (contractAbi: string, functionName: string) => { let jsonAbi = JSON.parse(contractAbi); let candidates = []; jsonAbi.forEach((element: any) => { if (element.name === functionName) { candidates = element.inputs; } }); let res = []; candidates.forEach((element) => { if (element.name && element.name !== "workitemId") res.push(element); }); return res; };
the_stack
// This file was automatically generated by elastic/elastic-client-generator-js // DO NOT MODIFY IT BY HAND. Instead, modify the source open api file, // and elastic/elastic-client-generator-js to regenerate this file again. import { Transport, TransportRequestOptions, TransportRequestOptionsWithMeta, TransportRequestOptionsWithOutMeta, TransportResult } from '@elastic/transport' import * as T from '../types' import * as TB from '../typesWithBodyKey' interface That { transport: Transport } export default class Cat { transport: Transport constructor (transport: Transport) { this.transport = transport } async aliases (this: That, params?: T.CatAliasesRequest | TB.CatAliasesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatAliasesResponse> async aliases (this: That, params?: T.CatAliasesRequest | TB.CatAliasesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatAliasesResponse, unknown>> async aliases (this: That, params?: T.CatAliasesRequest | TB.CatAliasesRequest, options?: TransportRequestOptions): Promise<T.CatAliasesResponse> async aliases (this: That, params?: T.CatAliasesRequest | TB.CatAliasesRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['name'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.name != null) { method = 'GET' path = `/_cat/aliases/${encodeURIComponent(params.name.toString())}` } else { method = 'GET' path = '/_cat/aliases' } return await this.transport.request({ path, method, querystring, body }, options) } async allocation (this: That, params?: T.CatAllocationRequest | TB.CatAllocationRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatAllocationResponse> async allocation (this: That, params?: T.CatAllocationRequest | TB.CatAllocationRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatAllocationResponse, unknown>> async allocation (this: That, params?: T.CatAllocationRequest | TB.CatAllocationRequest, options?: TransportRequestOptions): Promise<T.CatAllocationResponse> async allocation (this: That, params?: T.CatAllocationRequest | TB.CatAllocationRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['node_id'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.node_id != null) { method = 'GET' path = `/_cat/allocation/${encodeURIComponent(params.node_id.toString())}` } else { method = 'GET' path = '/_cat/allocation' } return await this.transport.request({ path, method, querystring, body }, options) } async count (this: That, params?: T.CatCountRequest | TB.CatCountRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatCountResponse> async count (this: That, params?: T.CatCountRequest | TB.CatCountRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatCountResponse, unknown>> async count (this: That, params?: T.CatCountRequest | TB.CatCountRequest, options?: TransportRequestOptions): Promise<T.CatCountResponse> async count (this: That, params?: T.CatCountRequest | TB.CatCountRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['index'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.index != null) { method = 'GET' path = `/_cat/count/${encodeURIComponent(params.index.toString())}` } else { method = 'GET' path = '/_cat/count' } return await this.transport.request({ path, method, querystring, body }, options) } async fielddata (this: That, params?: T.CatFielddataRequest | TB.CatFielddataRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatFielddataResponse> async fielddata (this: That, params?: T.CatFielddataRequest | TB.CatFielddataRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatFielddataResponse, unknown>> async fielddata (this: That, params?: T.CatFielddataRequest | TB.CatFielddataRequest, options?: TransportRequestOptions): Promise<T.CatFielddataResponse> async fielddata (this: That, params?: T.CatFielddataRequest | TB.CatFielddataRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['fields'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.fields != null) { method = 'GET' path = `/_cat/fielddata/${encodeURIComponent(params.fields.toString())}` } else { method = 'GET' path = '/_cat/fielddata' } return await this.transport.request({ path, method, querystring, body }, options) } async health (this: That, params?: T.CatHealthRequest | TB.CatHealthRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatHealthResponse> async health (this: That, params?: T.CatHealthRequest | TB.CatHealthRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatHealthResponse, unknown>> async health (this: That, params?: T.CatHealthRequest | TB.CatHealthRequest, options?: TransportRequestOptions): Promise<T.CatHealthResponse> async health (this: That, params?: T.CatHealthRequest | TB.CatHealthRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = [] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } const method = 'GET' const path = '/_cat/health' return await this.transport.request({ path, method, querystring, body }, options) } async help (this: That, params?: T.CatHelpRequest | TB.CatHelpRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatHelpResponse> async help (this: That, params?: T.CatHelpRequest | TB.CatHelpRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatHelpResponse, unknown>> async help (this: That, params?: T.CatHelpRequest | TB.CatHelpRequest, options?: TransportRequestOptions): Promise<T.CatHelpResponse> async help (this: That, params?: T.CatHelpRequest | TB.CatHelpRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = [] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } const method = 'GET' const path = '/_cat' return await this.transport.request({ path, method, querystring, body }, options) } async indices (this: That, params?: T.CatIndicesRequest | TB.CatIndicesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatIndicesResponse> async indices (this: That, params?: T.CatIndicesRequest | TB.CatIndicesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatIndicesResponse, unknown>> async indices (this: That, params?: T.CatIndicesRequest | TB.CatIndicesRequest, options?: TransportRequestOptions): Promise<T.CatIndicesResponse> async indices (this: That, params?: T.CatIndicesRequest | TB.CatIndicesRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['index'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.index != null) { method = 'GET' path = `/_cat/indices/${encodeURIComponent(params.index.toString())}` } else { method = 'GET' path = '/_cat/indices' } return await this.transport.request({ path, method, querystring, body }, options) } async master (this: That, params?: T.CatMasterRequest | TB.CatMasterRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatMasterResponse> async master (this: That, params?: T.CatMasterRequest | TB.CatMasterRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatMasterResponse, unknown>> async master (this: That, params?: T.CatMasterRequest | TB.CatMasterRequest, options?: TransportRequestOptions): Promise<T.CatMasterResponse> async master (this: That, params?: T.CatMasterRequest | TB.CatMasterRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = [] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } const method = 'GET' const path = '/_cat/master' return await this.transport.request({ path, method, querystring, body }, options) } async mlDataFrameAnalytics (this: That, params?: T.CatMlDataFrameAnalyticsRequest | TB.CatMlDataFrameAnalyticsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatMlDataFrameAnalyticsResponse> async mlDataFrameAnalytics (this: That, params?: T.CatMlDataFrameAnalyticsRequest | TB.CatMlDataFrameAnalyticsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatMlDataFrameAnalyticsResponse, unknown>> async mlDataFrameAnalytics (this: That, params?: T.CatMlDataFrameAnalyticsRequest | TB.CatMlDataFrameAnalyticsRequest, options?: TransportRequestOptions): Promise<T.CatMlDataFrameAnalyticsResponse> async mlDataFrameAnalytics (this: That, params?: T.CatMlDataFrameAnalyticsRequest | TB.CatMlDataFrameAnalyticsRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['id'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.id != null) { method = 'GET' path = `/_cat/ml/data_frame/analytics/${encodeURIComponent(params.id.toString())}` } else { method = 'GET' path = '/_cat/ml/data_frame/analytics' } return await this.transport.request({ path, method, querystring, body }, options) } async mlDatafeeds (this: That, params?: T.CatMlDatafeedsRequest | TB.CatMlDatafeedsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatMlDatafeedsResponse> async mlDatafeeds (this: That, params?: T.CatMlDatafeedsRequest | TB.CatMlDatafeedsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatMlDatafeedsResponse, unknown>> async mlDatafeeds (this: That, params?: T.CatMlDatafeedsRequest | TB.CatMlDatafeedsRequest, options?: TransportRequestOptions): Promise<T.CatMlDatafeedsResponse> async mlDatafeeds (this: That, params?: T.CatMlDatafeedsRequest | TB.CatMlDatafeedsRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['datafeed_id'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.datafeed_id != null) { method = 'GET' path = `/_cat/ml/datafeeds/${encodeURIComponent(params.datafeed_id.toString())}` } else { method = 'GET' path = '/_cat/ml/datafeeds' } return await this.transport.request({ path, method, querystring, body }, options) } async mlJobs (this: That, params?: T.CatMlJobsRequest | TB.CatMlJobsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatMlJobsResponse> async mlJobs (this: That, params?: T.CatMlJobsRequest | TB.CatMlJobsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatMlJobsResponse, unknown>> async mlJobs (this: That, params?: T.CatMlJobsRequest | TB.CatMlJobsRequest, options?: TransportRequestOptions): Promise<T.CatMlJobsResponse> async mlJobs (this: That, params?: T.CatMlJobsRequest | TB.CatMlJobsRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['job_id'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.job_id != null) { method = 'GET' path = `/_cat/ml/anomaly_detectors/${encodeURIComponent(params.job_id.toString())}` } else { method = 'GET' path = '/_cat/ml/anomaly_detectors' } return await this.transport.request({ path, method, querystring, body }, options) } async mlTrainedModels (this: That, params?: T.CatMlTrainedModelsRequest | TB.CatMlTrainedModelsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatMlTrainedModelsResponse> async mlTrainedModels (this: That, params?: T.CatMlTrainedModelsRequest | TB.CatMlTrainedModelsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatMlTrainedModelsResponse, unknown>> async mlTrainedModels (this: That, params?: T.CatMlTrainedModelsRequest | TB.CatMlTrainedModelsRequest, options?: TransportRequestOptions): Promise<T.CatMlTrainedModelsResponse> async mlTrainedModels (this: That, params?: T.CatMlTrainedModelsRequest | TB.CatMlTrainedModelsRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['model_id'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.model_id != null) { method = 'GET' path = `/_cat/ml/trained_models/${encodeURIComponent(params.model_id.toString())}` } else { method = 'GET' path = '/_cat/ml/trained_models' } return await this.transport.request({ path, method, querystring, body }, options) } async nodeattrs (this: That, params?: T.CatNodeattrsRequest | TB.CatNodeattrsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatNodeattrsResponse> async nodeattrs (this: That, params?: T.CatNodeattrsRequest | TB.CatNodeattrsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatNodeattrsResponse, unknown>> async nodeattrs (this: That, params?: T.CatNodeattrsRequest | TB.CatNodeattrsRequest, options?: TransportRequestOptions): Promise<T.CatNodeattrsResponse> async nodeattrs (this: That, params?: T.CatNodeattrsRequest | TB.CatNodeattrsRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = [] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } const method = 'GET' const path = '/_cat/nodeattrs' return await this.transport.request({ path, method, querystring, body }, options) } async nodes (this: That, params?: T.CatNodesRequest | TB.CatNodesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatNodesResponse> async nodes (this: That, params?: T.CatNodesRequest | TB.CatNodesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatNodesResponse, unknown>> async nodes (this: That, params?: T.CatNodesRequest | TB.CatNodesRequest, options?: TransportRequestOptions): Promise<T.CatNodesResponse> async nodes (this: That, params?: T.CatNodesRequest | TB.CatNodesRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = [] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } const method = 'GET' const path = '/_cat/nodes' return await this.transport.request({ path, method, querystring, body }, options) } async pendingTasks (this: That, params?: T.CatPendingTasksRequest | TB.CatPendingTasksRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatPendingTasksResponse> async pendingTasks (this: That, params?: T.CatPendingTasksRequest | TB.CatPendingTasksRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatPendingTasksResponse, unknown>> async pendingTasks (this: That, params?: T.CatPendingTasksRequest | TB.CatPendingTasksRequest, options?: TransportRequestOptions): Promise<T.CatPendingTasksResponse> async pendingTasks (this: That, params?: T.CatPendingTasksRequest | TB.CatPendingTasksRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = [] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } const method = 'GET' const path = '/_cat/pending_tasks' return await this.transport.request({ path, method, querystring, body }, options) } async plugins (this: That, params?: T.CatPluginsRequest | TB.CatPluginsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatPluginsResponse> async plugins (this: That, params?: T.CatPluginsRequest | TB.CatPluginsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatPluginsResponse, unknown>> async plugins (this: That, params?: T.CatPluginsRequest | TB.CatPluginsRequest, options?: TransportRequestOptions): Promise<T.CatPluginsResponse> async plugins (this: That, params?: T.CatPluginsRequest | TB.CatPluginsRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = [] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } const method = 'GET' const path = '/_cat/plugins' return await this.transport.request({ path, method, querystring, body }, options) } async recovery (this: That, params?: T.CatRecoveryRequest | TB.CatRecoveryRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatRecoveryResponse> async recovery (this: That, params?: T.CatRecoveryRequest | TB.CatRecoveryRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatRecoveryResponse, unknown>> async recovery (this: That, params?: T.CatRecoveryRequest | TB.CatRecoveryRequest, options?: TransportRequestOptions): Promise<T.CatRecoveryResponse> async recovery (this: That, params?: T.CatRecoveryRequest | TB.CatRecoveryRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['index'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.index != null) { method = 'GET' path = `/_cat/recovery/${encodeURIComponent(params.index.toString())}` } else { method = 'GET' path = '/_cat/recovery' } return await this.transport.request({ path, method, querystring, body }, options) } async repositories (this: That, params?: T.CatRepositoriesRequest | TB.CatRepositoriesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatRepositoriesResponse> async repositories (this: That, params?: T.CatRepositoriesRequest | TB.CatRepositoriesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatRepositoriesResponse, unknown>> async repositories (this: That, params?: T.CatRepositoriesRequest | TB.CatRepositoriesRequest, options?: TransportRequestOptions): Promise<T.CatRepositoriesResponse> async repositories (this: That, params?: T.CatRepositoriesRequest | TB.CatRepositoriesRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = [] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } const method = 'GET' const path = '/_cat/repositories' return await this.transport.request({ path, method, querystring, body }, options) } async segments (this: That, params?: T.CatSegmentsRequest | TB.CatSegmentsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatSegmentsResponse> async segments (this: That, params?: T.CatSegmentsRequest | TB.CatSegmentsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatSegmentsResponse, unknown>> async segments (this: That, params?: T.CatSegmentsRequest | TB.CatSegmentsRequest, options?: TransportRequestOptions): Promise<T.CatSegmentsResponse> async segments (this: That, params?: T.CatSegmentsRequest | TB.CatSegmentsRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['index'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.index != null) { method = 'GET' path = `/_cat/segments/${encodeURIComponent(params.index.toString())}` } else { method = 'GET' path = '/_cat/segments' } return await this.transport.request({ path, method, querystring, body }, options) } async shards (this: That, params?: T.CatShardsRequest | TB.CatShardsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatShardsResponse> async shards (this: That, params?: T.CatShardsRequest | TB.CatShardsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatShardsResponse, unknown>> async shards (this: That, params?: T.CatShardsRequest | TB.CatShardsRequest, options?: TransportRequestOptions): Promise<T.CatShardsResponse> async shards (this: That, params?: T.CatShardsRequest | TB.CatShardsRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['index'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.index != null) { method = 'GET' path = `/_cat/shards/${encodeURIComponent(params.index.toString())}` } else { method = 'GET' path = '/_cat/shards' } return await this.transport.request({ path, method, querystring, body }, options) } async snapshots (this: That, params?: T.CatSnapshotsRequest | TB.CatSnapshotsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatSnapshotsResponse> async snapshots (this: That, params?: T.CatSnapshotsRequest | TB.CatSnapshotsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatSnapshotsResponse, unknown>> async snapshots (this: That, params?: T.CatSnapshotsRequest | TB.CatSnapshotsRequest, options?: TransportRequestOptions): Promise<T.CatSnapshotsResponse> async snapshots (this: That, params?: T.CatSnapshotsRequest | TB.CatSnapshotsRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['repository'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.repository != null) { method = 'GET' path = `/_cat/snapshots/${encodeURIComponent(params.repository.toString())}` } else { method = 'GET' path = '/_cat/snapshots' } return await this.transport.request({ path, method, querystring, body }, options) } async tasks (this: That, params?: T.CatTasksRequest | TB.CatTasksRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatTasksResponse> async tasks (this: That, params?: T.CatTasksRequest | TB.CatTasksRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatTasksResponse, unknown>> async tasks (this: That, params?: T.CatTasksRequest | TB.CatTasksRequest, options?: TransportRequestOptions): Promise<T.CatTasksResponse> async tasks (this: That, params?: T.CatTasksRequest | TB.CatTasksRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = [] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } const method = 'GET' const path = '/_cat/tasks' return await this.transport.request({ path, method, querystring, body }, options) } async templates (this: That, params?: T.CatTemplatesRequest | TB.CatTemplatesRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatTemplatesResponse> async templates (this: That, params?: T.CatTemplatesRequest | TB.CatTemplatesRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatTemplatesResponse, unknown>> async templates (this: That, params?: T.CatTemplatesRequest | TB.CatTemplatesRequest, options?: TransportRequestOptions): Promise<T.CatTemplatesResponse> async templates (this: That, params?: T.CatTemplatesRequest | TB.CatTemplatesRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['name'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.name != null) { method = 'GET' path = `/_cat/templates/${encodeURIComponent(params.name.toString())}` } else { method = 'GET' path = '/_cat/templates' } return await this.transport.request({ path, method, querystring, body }, options) } async threadPool (this: That, params?: T.CatThreadPoolRequest | TB.CatThreadPoolRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatThreadPoolResponse> async threadPool (this: That, params?: T.CatThreadPoolRequest | TB.CatThreadPoolRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatThreadPoolResponse, unknown>> async threadPool (this: That, params?: T.CatThreadPoolRequest | TB.CatThreadPoolRequest, options?: TransportRequestOptions): Promise<T.CatThreadPoolResponse> async threadPool (this: That, params?: T.CatThreadPoolRequest | TB.CatThreadPoolRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['thread_pool_patterns'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.thread_pool_patterns != null) { method = 'GET' path = `/_cat/thread_pool/${encodeURIComponent(params.thread_pool_patterns.toString())}` } else { method = 'GET' path = '/_cat/thread_pool' } return await this.transport.request({ path, method, querystring, body }, options) } async transforms (this: That, params?: T.CatTransformsRequest | TB.CatTransformsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.CatTransformsResponse> async transforms (this: That, params?: T.CatTransformsRequest | TB.CatTransformsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.CatTransformsResponse, unknown>> async transforms (this: That, params?: T.CatTransformsRequest | TB.CatTransformsRequest, options?: TransportRequestOptions): Promise<T.CatTransformsResponse> async transforms (this: That, params?: T.CatTransformsRequest | TB.CatTransformsRequest, options?: TransportRequestOptions): Promise<any> { const acceptedPath: string[] = ['transform_id'] const querystring: Record<string, any> = {} const body = undefined params = params ?? {} for (const key in params) { if (acceptedPath.includes(key)) { continue } else if (key !== 'body') { // @ts-expect-error querystring[key] = params[key] } } let method = '' let path = '' if (params.transform_id != null) { method = 'GET' path = `/_cat/transforms/${encodeURIComponent(params.transform_id.toString())}` } else { method = 'GET' path = '/_cat/transforms' } return await this.transport.request({ path, method, querystring, body }, options) } }
the_stack
import { $TSContext, CFNTemplateFormat, FeatureFlags, JSONUtilities, pathManager, readCFNTemplate, stateManager, writeCFNTemplate, } from 'amplify-cli-core'; import { Template, Fn } from 'cloudform-types'; import * as fs from 'fs-extra'; import * as path from 'path'; import { DeploymentResources, PackagedResourceDefinition, ResourceDefinition, ResourceDeployType, StackParameters, TransformedCfnResource, } from './types'; import { Constants } from './constants'; import { ResourcePackager } from './resource-packager'; import { getNetworkResourceCfn } from '../utils/env-level-constructs'; import _ from 'lodash'; import { printer } from 'amplify-prompts'; import { AUTH_TRIGGER_STACK } from '../utils/upload-auth-trigger-template'; import { S3 } from '../aws-utils/aws-s3'; import { downloadZip } from '../zip-util'; import { Ref } from 'cloudform-types/types/functions'; import { prePushCfnTemplateModifier } from '../pre-push-cfn-processor/pre-push-cfn-modifier'; import { getDefaultTemplateDescription } from '../template-description-utils'; const { API_CATEGORY, AUTH_CATEGORY, FUNCTION_CATEGORY, NOTIFICATIONS_CATEGORY, AMPLIFY_CFN_TEMPLATES, AMPLIFY_APPSYNC_FILES, PROVIDER_METADATA, NETWORK_STACK_S3_URL, AUTH_TRIGGER_TEMPLATE_FILE, AUTH_TRIGGER_TEMPLATE_URL, API_GATEWAY_AUTH_URL, APIGW_AUTH_STACK_FILE_NAME, APPSYNC_STACK_FOLDER, APPSYNC_BUILD_FOLDER, NETWORK_STACK_FILENAME, PROVIDER_NAME, PROVIDER, AMPLIFY_BUILDS, AUTH_ASSETS, AMPLIFY_AUXILIARY_LAMBDAS, AWS_CLOUDFORMATION_STACK_TYPE, AMPLIFY_AUTH_ASSETS, NETWORK_STACK_LOGICAL_ID, APIGW_AUTH_STACK_LOGICAL_ID, } = Constants; export class ResourceExport extends ResourcePackager { exportDirectoryPath: string; constructor(context: $TSContext, exportDirectoryPath: string) { super(context, ResourceDeployType.Export); this.exportDirectoryPath = exportDirectoryPath; } async packageBuildWriteResources(deploymentResources: DeploymentResources): Promise<PackagedResourceDefinition[]> { this.warnForNonExportable(deploymentResources.allResources); const resources = await this.filterResourcesToBeDeployed(deploymentResources); const preBuiltResources = await this.preBuildResources(resources); const builtResources = await this.buildResources(preBuiltResources); const packagedResources = await this.packageResources(builtResources); const postPackageResources = await this.postPackageResource(packagedResources); return postPackageResources; } async generateAndTransformCfnResources( packagedResources: PackagedResourceDefinition[], ): Promise<{ transformedResources: TransformedCfnResource[]; stackParameters: StackParameters }> { await this.generateCategoryCloudFormation(packagedResources); const transformedCfnResources = await this.postGenerateCategoryCloudFormation(packagedResources); const stackParameters = await this.writeCategoryCloudFormation(transformedCfnResources); return { transformedResources: transformedCfnResources, stackParameters }; } /** * The parameters are going to need to be read from the parameters json since the types are fixed there * @param transformedCfnResources * @param stackParameters * @returns */ fixNestedStackParameters(transformedCfnResources: TransformedCfnResource[], stackParameters: StackParameters): StackParameters { const projectPath = pathManager.findProjectRoot(); const { StackName: rootstackName } = this.amplifyMeta[PROVIDER][PROVIDER_NAME]; const nestedStack = stackParameters[rootstackName].nestedStacks; for (const resource of transformedCfnResources) { const fileParameters = stateManager.getResourceParametersJson(projectPath, resource.category, resource.resourceName, { default: {}, throwIfNotExist: false, }); const nestedStackName = resource.category + resource.resourceName; const usedParameters = nestedStack[nestedStackName].parameters; Object.keys(usedParameters).forEach(paramKey => { if (paramKey in fileParameters) { usedParameters[paramKey] = fileParameters[paramKey]; } }); } return stackParameters; } async generateAndWriteRootStack(stackParameters: StackParameters): Promise<StackParameters> { const { StackName: stackName, AuthRoleName, UnauthRoleName, DeploymentBucketName } = this.amplifyMeta[PROVIDER][PROVIDER_NAME]; const template = await this.generateRootStack(); const parameters = this.extractParametersFromTemplateNestedStack(template); const modifiedTemplate = await this.modifyRootStack(template, true); this.writeRootStackToPath(modifiedTemplate); stackParameters[stackName].destination = path.join(this.exportDirectoryPath, 'root-stack-template.json'); [...parameters.keys()].forEach((key: string) => { if (stackParameters[stackName].nestedStacks && stackParameters[stackName].nestedStacks[key]) { stackParameters[stackName].nestedStacks[key].parameters = parameters.get(key); } }); stackParameters[stackName].parameters = { AuthRoleName, UnauthRoleName, DeploymentBucketName, }; return stackParameters; } /** * warns for non exportable resources * @param resources */ warnForNonExportable(resources: ResourceDefinition[]) { const notificationsResources = this.filterResourceByCategoryService(resources, NOTIFICATIONS_CATEGORY.NAME); if (notificationsResources.length > 0) { printer.blankLine(); printer.warn( `The ${NOTIFICATIONS_CATEGORY.NAME} resource '${notificationsResources .map(r => r.resourceName) .join(', ')}' cannot be exported since it is managed using SDK`, ); } } /** * writes packaged files to export directory path * For AppSync API it copies the non cloudformation assets * * @param resources {PackagedResourceDefinition[]} */ async writeResourcesToDestination(resources: PackagedResourceDefinition[]): Promise<void> { for (const resource of resources) { if (resource.packagerParams && resource.packagerParams.newPackageCreated) { const destinationPath = path.join( this.exportDirectoryPath, resource.category, resource.resourceName, AMPLIFY_BUILDS, resource.packagerParams.zipFilename, ); await this.copyResource(resource.packagerParams.zipFilePath, destinationPath); } if (resource.category === FUNCTION_CATEGORY.NAME && resource.service === FUNCTION_CATEGORY.SERVICE.LAMBDA_LAYER) { await this.downloadLambdaLayerContent(resource); } // copy build directory for appsync if (resource.category === API_CATEGORY.NAME && resource.service === API_CATEGORY.SERVICE.APP_SYNC) { const backendFolder = pathManager.getBackendDirPath(); const foldersToCopy = ['functions', 'pipelineFunctions', 'resolvers', 'stacks', 'schema.graphql']; for (const folder of foldersToCopy) { const sourceFolder = path.join(backendFolder, resource.category, resource.resourceName, APPSYNC_BUILD_FOLDER, folder); const destinationFolder = path.join( this.exportDirectoryPath, resource.category, resource.resourceName, AMPLIFY_APPSYNC_FILES, folder, ); await this.copyResource(sourceFolder, destinationFolder); } } if (resource.category === AUTH_CATEGORY.NAME && resource.service === AUTH_CATEGORY.SERVICE.COGNITO) { const authResourceBackend = path.join(pathManager.getBackendDirPath(), resource.category, resource.resourceName); const authResourceAssets = path.join(authResourceBackend, AUTH_ASSETS); if (fs.existsSync(authResourceAssets)) { const destinationPath = path.join(this.exportDirectoryPath, resource.category, resource.resourceName, AMPLIFY_AUTH_ASSETS); await this.copyResource(authResourceAssets, destinationPath); } } } // write the pipeline awaiter and if (this.resourcesHasContainers(resources)) { for (const zipFile of this.elasticContainerZipFiles) { const destinationPath = path.join(this.exportDirectoryPath, AMPLIFY_AUXILIARY_LAMBDAS, zipFile); const sourceFile = path.join(__dirname, '../..', 'resources', zipFile); await this.copyResource(sourceFile, destinationPath); } } } /** * Download content for past layer versions * @param resource */ private async downloadLambdaLayerContent(resource: PackagedResourceDefinition) { const backendDir = pathManager.getBackendDirPath(); const cfnFilePath = path.join( backendDir, resource.category, resource.resourceName, `${resource.resourceName}-awscloudformation-template.json`, ); const template = JSONUtilities.readJson<Template>(cfnFilePath); const layerVersions = Object.keys(template.Resources).reduce((array, resourceKey) => { const layerVersionResource = template.Resources[resourceKey]; if (layerVersionResource.Type === 'AWS::Lambda::LayerVersion') { const path = _.get(layerVersionResource.Properties, ['Content', 'S3Key']); if (path && typeof path === 'string') { array.push({ logicalName: resourceKey, contentPath: path, }); } } return array; }, []); if (layerVersions.length > 0) { const s3instance = await S3.getInstance(this.context); for await (const lambdaLayer of layerVersions) { const exportPath = path.join(this.exportDirectoryPath, resource.category, resource.resourceName); await downloadZip(s3instance, exportPath, lambdaLayer.contentPath, this.envInfo.envName); //await downloadZip(s3instance, exportPath, ); } } } private async processAndWriteCfn(cfnFile: string, destinationPath: string, deleteParameters: boolean = true) { const { cfnTemplate, templateFormat } = readCFNTemplate(cfnFile); return await this.processAndWriteCfnTemplate(cfnTemplate, destinationPath, templateFormat, deleteParameters); } private async processAndWriteCfnTemplate( cfnTemplate: Template, destinationPath: string, templateFormat: CFNTemplateFormat, deleteParameters: boolean, ) { const parameters = this.extractParametersFromTemplateNestedStack(cfnTemplate); const template = await this.modifyRootStack(cfnTemplate, deleteParameters); await writeCFNTemplate(template, destinationPath, { templateFormat }); return parameters; } private async copyResource(sourcePath: string, destinationPath: string) { let dir = destinationPath; if(!fs.existsSync(sourcePath)){ return; } // if there is an extension then get the dir path // extension points to the fact that it's a file if (path.extname(destinationPath)) { dir = path.dirname(destinationPath); } await fs.ensureDir(dir); await fs.copy(sourcePath, destinationPath, { overwrite: true, preserveTimestamps: true, recursive: true }); } private async writeCategoryCloudFormation(resources: TransformedCfnResource[]): Promise<StackParameters> { const { StackName: stackName } = this.amplifyMeta[PROVIDER][PROVIDER_NAME]; const bucket = 'externalDeploymentBucketName'; const stackParameters: StackParameters = {}; stackParameters[stackName] = { destination: 'dummyPath', // is going to be populated when root stack is being written, parameters: {}, nestedStacks: {}, }; for await (const resource of resources) { const logicalId = resource.category + resource.resourceName; for (const cfnFile of resource.transformedCfnPaths) { const fileName = path.parse(cfnFile).base; const templateURL = this.createTemplateUrl(bucket, fileName, resource.category); const destination = path.join(this.exportDirectoryPath, resource.category, resource.resourceName, fileName); const nestedStack = { destination, nestedStacks: {}, }; // only expose nested stack for GraphQL API if (resource.category === API_CATEGORY.NAME && resource.service === API_CATEGORY.SERVICE.APP_SYNC) { const parameters = await this.processAndWriteCfn(cfnFile, destination, false); [...parameters.keys()].forEach(key => { const nestedStackPath = path.join( this.exportDirectoryPath, resource.category, resource.resourceName, AMPLIFY_APPSYNC_FILES, APPSYNC_STACK_FOLDER, key === 'CustomResourcesjson' ? 'CustomResources.json' : `${key}.json`, ); nestedStack.nestedStacks[key] = { destination: nestedStackPath, nestedStacks: {}, }; }); } else if (resource.category === FUNCTION_CATEGORY.NAME && resource.service === FUNCTION_CATEGORY.SERVICE.LAMBDA_LAYER) { const { cfnTemplate, templateFormat } = readCFNTemplate(cfnFile); Object.keys(cfnTemplate.Resources) .filter(key => cfnTemplate.Resources[key].Type === 'AWS::Lambda::LayerVersion') .forEach(layerVersionResourceKey => { const layerVersionResource = cfnTemplate.Resources[layerVersionResourceKey]; const s3Key = _.get(layerVersionResource.Properties, ['Content', 'S3Key']); layerVersionResource.Properties['Content']['S3Key'] = Fn.Join('/', [ Ref('s3Key'), typeof s3Key === 'string' ? path.basename(s3Key) : resource.packagerParams.zipFilename, ]); }); await this.processAndWriteCfnTemplate(cfnTemplate, destination, templateFormat, false); } else { this.copyResource(cfnFile, destination); } stackParameters[stackName].nestedStacks[logicalId] = nestedStack; _.set(this.amplifyMeta, [resource.category, resource.resourceName, PROVIDER_METADATA], { s3TemplateURL: templateURL, logicalId, }); } } if (this.resourcesHasContainers(resources)) { // create network resouce const template = (await getNetworkResourceCfn(this.context, stackName)) as Template; const destinationPath = path.join(this.exportDirectoryPath, AMPLIFY_CFN_TEMPLATES, NETWORK_STACK_FILENAME); stackParameters[stackName].nestedStacks[NETWORK_STACK_LOGICAL_ID] = { destination: destinationPath, }; JSONUtilities.writeJson(destinationPath, template); _.set(this.amplifyMeta, [PROVIDER, PROVIDER_NAME, NETWORK_STACK_S3_URL], this.createTemplateUrl(bucket, NETWORK_STACK_FILENAME)); } if (this.resourcesHasApiGatewaysButNotAdminQueries(resources)) { const apiGWAuthFile = path.join(pathManager.getBackendDirPath(), API_CATEGORY.NAME, APIGW_AUTH_STACK_FILE_NAME); // don't check for the api gateway rest api just check for the consolidated file if (fs.existsSync(apiGWAuthFile)) { const destination = path.join(this.exportDirectoryPath, AUTH_CATEGORY.NAME, APIGW_AUTH_STACK_FILE_NAME); stackParameters[stackName].nestedStacks[APIGW_AUTH_STACK_LOGICAL_ID] = { destination: destination, }; await this.copyResource(apiGWAuthFile, destination); _.set( this.amplifyMeta, [PROVIDER, PROVIDER_NAME, API_GATEWAY_AUTH_URL], this.createTemplateUrl(bucket, APIGW_AUTH_STACK_FILE_NAME, API_CATEGORY.NAME), ); } } const authResource = this.getAuthCognitoResource(resources); if (FeatureFlags.getBoolean('auth.breakCircularDependency') && authResource) { const pathToTriggerFile = path.join( pathManager.getBackendDirPath(), AUTH_CATEGORY.NAME, authResource.resourceName, AUTH_TRIGGER_TEMPLATE_FILE, ); if (fs.existsSync(pathToTriggerFile)) { const destination = path.join(this.exportDirectoryPath, AUTH_CATEGORY.NAME, AUTH_TRIGGER_TEMPLATE_FILE); stackParameters[stackName].nestedStacks[AUTH_TRIGGER_STACK] = { destination: destination, }; await this.copyResource(pathToTriggerFile, destination); _.set( this.amplifyMeta, [PROVIDER, PROVIDER_NAME, AUTH_TRIGGER_TEMPLATE_URL], this.createTemplateUrl(bucket, AUTH_TRIGGER_TEMPLATE_FILE, AUTH_CATEGORY.NAME), ); } } return stackParameters; } /** * Extracts stack parameters from root stack and return parameters * @param root stack template {Template} * @returns {Map<string, { [key: string]: any } | undefined>} by stackName and parameters */ private extractParametersFromTemplateNestedStack(template: Template): Map<string, { [key: string]: any } | undefined> { const map = Object.keys(template.Resources).reduce((map, resourceKey) => { const resource = template.Resources[resourceKey]; if (resource.Type === AWS_CLOUDFORMATION_STACK_TYPE) { const parameters = resource.Properties.Parameters || {}; if (parameters) { const otherParameters = this.extractParameters(parameters, true); map.set(resourceKey, otherParameters); } else { map.set(resourceKey, parameters); } } return map; }, new Map<string, { [key: string]: any } | undefined>()); return map; } private extractParameters(parameters: any, excludeObjectType: boolean) { return Object.keys(parameters).reduce((obj, key) => { const addParameter = excludeObjectType ? !(parameters[key] instanceof Object) : parameters[key] instanceof Object; if (addParameter) { obj[key] = parameters[key]; } return obj; }, {}); } /** * Modifies the template to remove some parameters and template url * @param template {Template} * @returns {Template} */ private async modifyRootStack(template: Template, deleteParameters: boolean): Promise<Template> { Object.keys(template.Resources).map(resourceKey => { const resource = template.Resources[resourceKey]; if (resource.Type === AWS_CLOUDFORMATION_STACK_TYPE) { // remove url parameters will set it in the construct // remove template URL the stack, CDK will update the URL if (deleteParameters) { const { Parameters, TemplateURL, ...others } = template.Resources[resourceKey].Properties; if (Parameters) { const params = this.extractParameters(Parameters, false); resource.Properties = { ...others, Parameters: params, }; } else { resource.Properties = others; } } else { const { TemplateURL, ...others } = template.Resources[resourceKey].Properties; resource.Properties = others; } } }); await prePushCfnTemplateModifier(template); template.Description = getDefaultTemplateDescription(this.context, 'root'); return template; } private getAuthCognitoResource(resources: ResourceDefinition[]): ResourceDefinition | undefined { return resources.find(resource => resource.category === AUTH_CATEGORY.NAME && resource.service === AUTH_CATEGORY.SERVICE.COGNITO); } private writeRootStackToPath(template: Template) { JSONUtilities.writeJson(path.join(this.exportDirectoryPath, 'root-stack-template.json'), template); } private createTemplateUrl(bucketName: string, fileName: string, categoryName?: string): { [x: string]: any } { const values = ['https://s3.amazonaws.com', Fn.Ref(bucketName).toJSON(), AMPLIFY_CFN_TEMPLATES]; if (categoryName) { values.push(categoryName); } values.push(fileName); return Fn.Join('/', values).toJSON(); } }
the_stack
import React, { useState } from 'react'; import { Button, FormControl, Input, ScrollView, Stack, Switch, Text, } from 'native-base'; import Picker from '../Picker'; import { PGS, TIER_CODES } from '../constants'; import { getMethods, getQuotas } from '../utils'; import type { StackScreenProps } from '@react-navigation/stack'; import type { RootStackParamList } from '../NavigationService'; import { IMPConst } from 'iamport-react-native'; import type { PaymentParams } from '../NavigationService'; import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context'; type Props = StackScreenProps<RootStackParamList, 'PaymentTest'>; function PaymentTest({ navigation }: Props) { const [pg, setPg] = useState('html5_inicis'); const [tierCode, setTierCode] = useState(undefined); const [method, setMethod] = useState('card'); const [cardQuota, setCardQuota] = useState(0); const [merchantUid, setMerchantUid] = useState(`mid_${new Date().getTime()}`); const [name, setName] = useState('아임포트 결제데이터분석'); const [amount, setAmount] = useState('39000'); const [buyerName, setBuyerName] = useState('홍길동'); const [buyerTel, setBuyerTel] = useState('01012341234'); const [buyerEmail, setBuyerEmail] = useState('example@example.com'); const [vbankDue, setVbankDue] = useState(''); const [bizNum, setBizNum] = useState(''); const [escrow, setEscrow] = useState(false); const [digital, setDigital] = useState(false); const insets = useSafeAreaInsets(); return ( <SafeAreaView style={{ flex: 1, justifyContent: 'center', backgroundColor: '#f5f5f5', paddingTop: -insets.top }} > <ScrollView m={2} backgroundColor={'#fff'}> <FormControl p={'5%'} borderRadius={3}> <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> PG사 </FormControl.Label> <Picker data={PGS} selectedValue={pg} onValueChange={(value) => { setPg(value); const methods = getMethods(value); setMethod(methods[0].value); }} /> </Stack> <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 티어 코드 </FormControl.Label> <Picker data={TIER_CODES} selectedValue={tierCode} onValueChange={(value) => setTierCode(value)} /> </Stack> <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 결제수단 </FormControl.Label> <Picker data={getMethods(pg)} selectedValue={method} onValueChange={(value) => setMethod(value)} /> </Stack> {method === 'card' && ( <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 할부개월수 </FormControl.Label> <Picker data={getQuotas(pg)} selectedValue={cardQuota} onValueChange={(value) => setCardQuota(parseInt(value, 10))} /> </Stack> )} {method === 'vbank' && ( <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 입금기한 </FormControl.Label> <Input mb={2} flex={1} value={vbankDue} onChangeText={(value) => setVbankDue(value)} /> </Stack> )} {method === 'vbank' && pg === 'danal_tpay' && ( <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 사업자번호 </FormControl.Label> <Input mb={2} flex={1} value={bizNum} keyboardType="number-pad" returnKeyType={'done'} onChangeText={(value) => setBizNum(value)} /> </Stack> )} {method === 'phone' && ( <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 실물컨텐츠 </FormControl.Label> <Switch mb={2} value={digital} onValueChange={(value) => setDigital(value)} /> </Stack> )} <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 에스크로 </FormControl.Label> <Switch mb={2} value={escrow} onValueChange={(value) => setEscrow(value)} /> </Stack> <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 주문명 </FormControl.Label> <Input mb={2} flex={1} value={name} onChangeText={(value) => setName(value)} /> </Stack> <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 결제금액 </FormControl.Label> <Input mb={2} flex={1} value={amount} keyboardType="number-pad" returnKeyType={'done'} onChangeText={(value) => setAmount(value)} /> </Stack> <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 주문번호 </FormControl.Label> <Input mb={2} flex={1} value={merchantUid} onChangeText={(value) => setMerchantUid(value)} /> </Stack> <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 이름 </FormControl.Label> <Input mb={2} flex={1} value={buyerName} onChangeText={(value) => setBuyerName(value)} /> </Stack> <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 전화번호 </FormControl.Label> <Input mb={2} flex={1} value={buyerTel} keyboardType="number-pad" returnKeyType={'done'} onChangeText={(value) => setBuyerTel(value)} /> </Stack> <Stack direction={'row'}> <FormControl.Label alignItems={'center'} mb={2} w={'18%'}> 이메일 </FormControl.Label> <Input mb={2} flex={1} value={buyerEmail} onChangeText={(value) => setBuyerEmail(value)} /> </Stack> <Button bgColor={'#344e81'} /* @ts-ignore */ onPress={() => { const data: PaymentParams = { params: { pg, pay_method: method, currency: undefined, notice_url: undefined, display: undefined, merchant_uid: merchantUid, name, amount, app_scheme: 'exampleforrn', tax_free: undefined, buyer_name: buyerName, buyer_tel: buyerTel, buyer_email: buyerEmail, buyer_addr: undefined, buyer_postcode: undefined, custom_data: undefined, vbank_due: undefined, popup: undefined, digital: undefined, language: undefined, biz_num: undefined, customer_uid: undefined, naverPopupMode: undefined, naverUseCfm: undefined, naverProducts: undefined, m_redirect_url: IMPConst.M_REDIRECT_URL, escrow, }, tierCode, }; // 신용카드의 경우, 할부기한 추가 if (method === 'card' && cardQuota !== 0) { data.params.display = { card_quota: cardQuota === 1 ? [] : [cardQuota], }; } // 가상계좌의 경우, 입금기한 추가 if (method === 'vbank' && vbankDue) { data.params.vbank_due = vbankDue; } // 다날 && 가상계좌의 경우, 사업자 등록번호 10자리 추가 if (method === 'vbank' && pg === 'danal_tpay') { data.params.biz_num = bizNum; } // 휴대폰 소액결제의 경우, 실물 컨텐츠 여부 추가 if (method === 'phone') { data.params.digital = digital; } // 정기결제의 경우, customer_uid 추가 if (pg === 'kcp_billing') { data.params.customer_uid = `cuid_${new Date().getTime()}`; } if (pg === 'naverpay') { const today = new Date(); const oneMonthLater = new Date( today.setMonth(today.getMonth() + 1) ); const dd = String(oneMonthLater.getDate()).padStart(2, '0'); const mm = String(oneMonthLater.getMonth() + 1).padStart( 2, '0' ); // January is 0! const yyyy = oneMonthLater.getFullYear(); data.params.naverPopupMode = false; data.params.naverUseCfm = `${yyyy}${mm}${dd}`; data.params.naverProducts = [ { categoryType: 'BOOK', categoryId: 'GENERAL', uid: '107922211', name: '한국사', payReferrer: 'NAVER_BOOK', count: 10, }, ]; } navigation.navigate('Payment', data); }} > <Text fontWeight={'bold'} color={'#fff'}> 결제하기 </Text> </Button> </FormControl> </ScrollView> </SafeAreaView> ); } export default PaymentTest;
the_stack
import { DType, INDArray, TypedArray } from '../types'; import { default as abs } from './abs'; import { default as acos } from './acos'; import { default as acosh } from './acosh'; import { default as add } from './add'; import { default as angle } from './angle'; import { default as asin } from './asin'; import { default as asinh } from './asinh'; import { default as atan } from './atan'; import { default as atanh } from './atanh'; import { default as augment } from './augment'; import { default as binOp } from './binOp'; import { default as cbrt } from './cbrt'; import { default as ceil } from './ceil'; import { default as check } from './check'; import { default as combine } from './combine'; import { default as copy } from './copy'; import { default as cos } from './cos'; import { default as cosh } from './cosh'; import { default as cross } from './cross'; import { default as det } from './det'; import { default as diagonal } from './diagonal'; import { default as dot } from './dot'; import { default as eig } from './eig'; import { default as equals } from './equals'; import { default as equidimensional } from './equidimensional'; import { default as equilateral } from './equilateral'; import { default as exp } from './exp'; import { default as expm1 } from './expm1'; import { default as fill } from './fill'; import { default as floor } from './floor'; import { default as forEach } from './forEach'; import { default as fround } from './fround'; import { default as gauss } from './gauss'; import { default as get } from './get'; import { default as inv } from './inv'; import { default as log } from './log'; import { default as log10 } from './log10'; import { default as log1p } from './log1p'; import { default as log2 } from './log2'; import { default as lu } from './lu'; import { default as lu_factor } from './lu_factor'; import { default as map } from './map'; import { default as max } from './max'; import { default as mean } from './mean'; import { default as min } from './min'; import { default as multiply } from './multiply'; import { default as norm } from './norm'; import { default as normalize } from './normalize'; import { default as pow } from './pow'; import { default as prod } from './prod'; import { default as product } from './product'; import { default as project } from './project'; import { default as push } from './push'; import { default as rank } from './rank'; import { default as reciprocal } from './reciprocal'; import { default as reduce } from './reduce'; import { default as reshape } from './reshape'; import { default as round } from './round'; import { default as row_add } from './row_add'; import { default as scale } from './scale'; import { default as set } from './set'; import { default as sign } from './sign'; import { default as sin } from './sin'; import { default as sinh } from './sinh'; import { default as slice } from './slice'; import { default as solve } from './solve'; import { default as sqrt } from './sqrt'; import { default as square } from './square'; import { default as subtract } from './subtract'; import { default as sum } from './sum'; import { default as swap } from './swap'; import { default as tan } from './tan'; import { default as tanh } from './tanh'; import { default as toArray } from './toArray'; import { default as toString } from './toString'; import { default as trace } from './trace'; import { default as transpose } from './transpose'; import { default as trunc } from './trunc'; declare const inspectSymbol: unique symbol; /** * @class NDArray * @description Constructs or copies an NDArray instance. * @param data * @param {Object} [options] * @param {Number[]} [options.shape] * @param {Number} [options.length] * @param {Number[]} [options.strides] * @param {string} [options.dtype] * @example * import { NDArray } from 'vectorious'; * * new NDArray() // => array([], dtype=float64) * new NDArray([]) // => array([], dtype=float64) * new NDArray([1, 2, 3]) // => array([1, 2, 3], dtype=float64) * new NDArray([[1, 2], [3, 4]]) // => array([ [ 1, 2 ], [ 3, 4 ] ], dtype=float64) * new NDArray(new Int32Array([1, 2, 3])) // => array([ 1, 2, 3 ], dtype=int32) * new NDArray([1, 2, 3, 4], { * shape: [2, 2], * dtype: 'uint32' * }) // => array([ [ 1, 2 ], [ 3, 4 ] ], dtype=uint32) */ export declare class NDArray implements INDArray { /** * @name data * @memberof NDArray.prototype * @type TypedArray * @default new Float64Array(0) */ data: TypedArray; /** * @name dtype * @memberof NDArray.prototype * @type String * @default 'float64' */ dtype: DType; /** * @name length * @memberof NDArray.prototype * @type Number * @default 0 */ length: number; /** * @name shape * @memberof NDArray.prototype * @type Number[] * @default [0] */ shape: number[]; /** * @name strides * @memberof NDArray.prototype * @type Number[] * @default [0] */ strides: number[]; [inspectSymbol]: () => string; abs: typeof abs; acos: typeof acos; acosh: typeof acosh; add: typeof add; angle: typeof angle; asin: typeof asin; asinh: typeof asinh; atan: typeof atan; atanh: typeof atanh; augment: typeof augment; binOp: typeof binOp; cbrt: typeof cbrt; ceil: typeof ceil; check: typeof check; combine: typeof combine; copy: typeof copy; cos: typeof cos; cosh: typeof cosh; cross: typeof cross; det: typeof det; diagonal: typeof diagonal; dot: typeof dot; eig: typeof eig; equals: typeof equals; equidimensional: typeof equidimensional; equilateral: typeof equilateral; exp: typeof exp; expm1: typeof expm1; fill: typeof fill; floor: typeof floor; forEach: typeof forEach; fround: typeof fround; gauss: typeof gauss; get: typeof get; inv: typeof inv; log: typeof log; log10: typeof log10; log1p: typeof log1p; log2: typeof log2; lu: typeof lu; lu_factor: typeof lu_factor; map: typeof map; max: typeof max; mean: typeof mean; min: typeof min; multiply: typeof multiply; norm: typeof norm; normalize: typeof normalize; pow: typeof pow; prod: typeof prod; product: typeof product; project: typeof project; push: typeof push; rank: typeof rank; reciprocal: typeof reciprocal; reduce: typeof reduce; reshape: typeof reshape; round: typeof round; row_add: typeof row_add; scale: typeof scale; set: typeof set; sign: typeof sign; sin: typeof sin; sinh: typeof sinh; slice: typeof slice; solve: typeof solve; sqrt: typeof sqrt; square: typeof square; subtract: typeof subtract; sum: typeof sum; swap: typeof swap; tan: typeof tan; tanh: typeof tanh; toArray: typeof toArray; toString: typeof toString; trace: typeof trace; transpose: typeof transpose; trunc: typeof trunc; constructor(data?: any, options?: { shape?: number[]; length?: number; strides?: number[]; dtype?: DType; }); /** * @name x * @memberof NDArray.prototype * @description Gets or sets the value at index 0 * @type Number */ get x(): number; set x(value: number); /** * @name y * @memberof NDArray.prototype * @description Gets or sets the value at index 1 * @type Number */ get y(): number; set y(value: number); /** * @name z * @memberof NDArray.prototype * @description Gets or sets the value at index 2 * @type Number */ get z(): number; set z(value: number); /** * @name w * @memberof NDArray.prototype * @description Gets or sets the value at index 3 * @type Number */ get w(): number; set w(value: number); /** * @name T * @memberof NDArray.prototype * @description Short for `this.copy().transpose()` * @type NDArray */ get T(): NDArray; } export { abs } from './abs'; export { acos } from './acos'; export { acosh } from './acosh'; export { add } from './add'; export { angle } from './angle'; export { array } from './array'; export { asin } from './asin'; export { asinh } from './asinh'; export { atan } from './atan'; export { atanh } from './atanh'; export { augment } from './augment'; export { binOp } from './binOp'; export { cbrt } from './cbrt'; export { ceil } from './ceil'; export { check } from './check'; export { combine } from './combine'; export { copy } from './copy'; export { cos } from './cos'; export { cosh } from './cosh'; export { cross } from './cross'; export { det } from './det'; export { diagonal } from './diagonal'; export { dot } from './dot'; export { eig } from './eig'; export { equals } from './equals'; export { equidimensional } from './equidimensional'; export { equilateral } from './equilateral'; export { exp } from './exp'; export { expm1 } from './expm1'; export { eye } from './eye'; export { fill } from './fill'; export { floor } from './floor'; export { forEach } from './forEach'; export { fround } from './fround'; export { gauss } from './gauss'; export { get } from './get'; export { inv } from './inv'; export { log } from './log'; export { log10 } from './log10'; export { log1p } from './log1p'; export { log2 } from './log2'; export { lu } from './lu'; export { lu_factor } from './lu_factor'; export { magic } from './magic'; export { map } from './map'; export { matrix } from './matrix'; export { max } from './max'; export { mean } from './mean'; export { min } from './min'; export { multiply } from './multiply'; export { norm } from './norm'; export { normalize } from './normalize'; export { ones } from './ones'; export { pow } from './pow'; export { prod } from './prod'; export { product } from './product'; export { project } from './project'; export { push } from './push'; export { random } from './random'; export { range } from './range'; export { rank } from './rank'; export { reciprocal } from './reciprocal'; export { reduce } from './reduce'; export { reshape } from './reshape'; export { round } from './round'; export { row_add } from './row_add'; export { scale } from './scale'; export { set } from './set'; export { sign } from './sign'; export { sin } from './sin'; export { sinh } from './sinh'; export { slice } from './slice'; export { solve } from './solve'; export { sqrt } from './sqrt'; export { square } from './square'; export { subtract } from './subtract'; export { sum } from './sum'; export { swap } from './swap'; export { tan } from './tan'; export { tanh } from './tanh'; export { toArray } from './toArray'; export { toString } from './toString'; export { trace } from './trace'; export { transpose } from './transpose'; export { trunc } from './trunc'; export { zeros } from './zeros';
the_stack
import chalk from "chalk"; import fs from "fs"; import marked from "marked"; import peg from "pegjs"; import seedrandom from "seedrandom"; if (typeof document === "undefined") { const { JSDOM } = require("jsdom"); globalThis.document = new JSDOM().window.document; } require("./raw-loader.js").register(/\.peg$/); const staticGrammar = require("./entish.peg"); let grammar: string; if (staticGrammar === "entish.peg") { // Just so jest can access non-js resources const fs = require("fs"); grammar = fs.readFileSync("./src/entish.peg").toString(); } else if (typeof staticGrammar === "string") { grammar = staticGrammar; } else { grammar = staticGrammar.default; } export type Statement = Comment | Command | Fact | Inference | Claim | Rolling | Query | Function; export type Comment = { type: "comment"; value: string; }; export type Command = { type: "command"; command: "load" | "set" | "get" | "verify"; arguments: Expression[]; }; export type Fact = { type: "fact"; table: string; fields: Expression[]; negative?: boolean; matches?: Fact[]; bindings?: Binding[]; }; export type Inference = { type: "inference"; left: Fact; right: Conjunction | Disjunction; }; export type Clause = Fact | Conjunction | Disjunction | ExclusiveDisjunction | Comparison; export type Conjunction = { type: "conjunction"; clauses: Clause[]; negative?: boolean; veracity?: boolean; bindings?: Binding[]; }; export type Disjunction = { type: "disjunction"; clauses: Clause[]; negative?: boolean; veracity?: boolean; bindings?: Binding[]; }; export type ExclusiveDisjunction = { type: "exclusive_disjunction"; clauses: Clause[]; negative?: boolean; veracity?: boolean; bindings?: Binding[]; }; export type Comparison = { type: "comparison"; operator: ComparisonOperator; left: Expression; right: Expression; veracity?: boolean; bindings?: Binding[]; }; export type ComparisonOperator = "=" | ">" | "<" | ">=" | "<=" | "!="; export type Claim = { type: "claim"; clause: Clause; }; export type Rolling = { type: "rolling"; clause: Clause; }; export type Query = { type: "query"; clause: Clause; }; export type Expression = Constant | Function | BinaryOperation | Variable | Comparison; export type Constant = Boolean | String | Number | Roll; export type BinaryOperation = { type: "binary_operation"; operator: "+" | "-" | "*" | "/" | "^"; left: Expression; right: Expression; }; export type Function = { type: "function"; function: "Floor" | "Ceil" | "Min" | "Max" | "Sum" | "Count" | "Pr"; arguments: Expression[]; }; export type Boolean = { type: "boolean"; value: boolean; }; const TRUE: Boolean = { type: "boolean", value: true, }; const FALSE: Boolean = { type: "boolean", value: true, }; export type String = { type: "string"; value: string; }; export type Variable = { type: "variable"; value: string; }; export type Number = { type: "number"; value: number; }; export type Roll = { type: "roll"; count: number; die: number; modifier: number; }; export type Binding = { [key: string]: Constant | undefined }; export class Entception extends Error {} export class BindingMismatch extends Error { type: string = "BindingMismatch"; } export class TODO extends Error {} function groupBy<T>(array: T[], f: (o: T) => string): T[][] { const groups: { [key: string]: T[] } = {}; array.forEach((o) => { const group = f(o); groups[group] = groups[group] || []; groups[group].push(o); }); return Object.keys(groups).map((group) => groups[group]); } function equal(expr1: Expression | Fact, expr2: Expression | Fact): boolean { if (expr1.type !== expr2.type) return false; if (expr1.type === "fact" && expr2.type === "fact") { if (expr1.fields.length !== expr2.fields.length) return false; return expr1.fields.every((f, i) => equal(f, expr2.fields[i])); } if (expr1.type === "roll" && expr2.type === "roll") return rollToString(expr1) === rollToString(expr2); if ("value" in expr1 && "value" in expr2) return expr1.value === expr2.value; throw new Entception(`incomparable types: ${expr1.type} and ${expr2.type}`); } function isConstant(expr: Expression): expr is Constant { return ["string", "number", "boolean", "roll"].includes(expr.type); } type TraceEvent = { type: string; rule: string; location: { start: { offset: number; line: number; column: number; }; end: { offset: number; line: number; column: number; }; }; }; export default class Interpreter { strict: boolean; parser: PEG.Parser; traceEvents: TraceEvent[] = []; tables: { [key: string]: Fact[] } = {}; inferences: Inference[] = []; claims: Clause[] = []; lastInput?: string; rng: () => number; constructor(seed: string, strict: boolean = true) { this.strict = strict; this.parser = peg.generate(grammar, { trace: true }); this.rng = seedrandom(seed); } exec(statement: Statement): Fact[] | Constant { switch (statement.type) { case "comment": return []; case "command": switch (statement.command) { case "load": if (statement.arguments[0].type !== "string") { throw new Entception(`expected load(<filename:string)>, got ${statement.arguments[0].type}`); } this.loadFromFile(statement.arguments[0].value); return TRUE; case "set": let key = statement.arguments[0]; const value = statement.arguments[1]; (this as any)[(key as any).value] = eval((value as any).value); return TRUE; case "get": key = statement.arguments[0]; return { type: "string", value: JSON.stringify((this as any)[(key as any).value], null, 2), }; case "verify": return { type: "boolean", value: this.claims.every((claim) => this.claim(claim)), }; default: throw new TODO(`can't handle command of type ${(statement as any).command}`); } case "fact": return this.loadFact(statement, []); case "inference": return this.loadInference(statement, []); case "claim": if (!this.claim(statement.clause)) { if (this.strict) { throw new Entception(`unable to verify ${clauseToString(statement.clause, true)}`); } return FALSE; } return TRUE; case "query": return this.query(statement.clause); case "rolling": return this.roll(statement); case "function": return this.evaluateFunction(statement, {}); default: throw new TODO(`unhandled statement type: ${(statement as any).type}`); } } parse(input: string): Statement[] { try { return this.parser.parse(input, { tracer: this }).filter((x: any) => x); } finally { this.traceEvents = []; } } trace(event: TraceEvent) { this.traceEvents.push(event); } load(input: string) { this.lastInput = input; const statements = this.parse(input); for (let line in statements) { const statement = statements[line]; this.exec(statement); } } loadFromFile(path: string) { if (path.endsWith(".ent")) { const rules = fs.readFileSync(path).toString(); this.load(rules); } else if (path.endsWith(".md")) { const markdown = fs.readFileSync(path).toString(); const block = document.createElement("div"); block.innerHTML = marked(markdown); Array.from(block.querySelectorAll("code.language-entish")).forEach((node) => { if (node.textContent) this.load(node.textContent); }); } else if (fs.existsSync(path) && fs.lstatSync(path).isDirectory()) { fs.readdirSync(path).forEach((f) => { this.loadFromFile(path + "/" + f); }); } } loadFact(fact: Fact, ignore: Inference[]): Fact[] { if (!this.tables[fact.table]) { this.tables[fact.table] = []; } if (fact.fields.some((expr) => !isConstant(expr))) { throw new Entception(`facts must be grounded with strings or numbers: ${factToString(fact)}`); } if (fact.negative) { this.tables[fact.table] = this.tables[fact.table].filter( (fact) => !fact.fields.every((col, i) => equal(fact.fields[i], col)) ); return []; } if (this.alreadyExists(fact)) { return []; } this.tables[fact.table].push(fact); return [fact].concat( this.inferences .filter((inf) => { return !ignore.includes(inf); }) .map((inf) => this.loadInference(inf, ignore)) .flat() ); } alreadyExists(thing: Fact | Inference): boolean { if (thing.type === "fact") { return this.tables[thing.table].some((existingFact) => equal(existingFact, thing)); } return this.inferences.some((inf) => inferenceToString(inf) === inferenceToString(thing)); } query(clause: Clause): Fact[] { this.search(clause); return []; /* return this.search(clause) .map((b) => b.facts) .flat(); */ } claim(clause: Clause): boolean { return false; /* if (clause.type === "function") { throw new Entception("can't verify functions"); } this.claims.push(clause); this.search(clause).forEach((binding) => { binding.comparisons.forEach((comparison) => { this.evaluateExpression(comparison, binding); }); }); if (clause.type === "fact") { const veracity = clause.matches !== undefined && clause.matches.length > 0; return (!!!clause.negative && veracity) || (!!clause.negative && !veracity); } this.evaluateVeracity(clause); return !!clause.veracity; */ } roll(roll: Rolling): Fact[] { return []; /* const newFacts: Fact[] = this.search(roll.clause) .map((b) => b.facts) .flat() .map((fact) => { return { type: "fact", table: fact.table, fields: fact.fields.map((f) => (f.type === "roll" ? this.generateRoll(f) : f)), }; }); newFacts.forEach((fact) => this.loadFact(fact, [])); return newFacts; */ } loadInference(inference: Inference, ignore: Inference[]): Fact[] { return []; /* const bindings = this.aggregate(inference.left, this.search(inference.right)); const facts: Fact[] = bindings.map((binding) => { return { type: "fact", table: inference.left.table, negative: inference.left.negative, fields: inference.left.fields.map((f) => this.evaluateExpression(f, binding)), }; }); if (!this.alreadyExists(inference)) { this.inferences.push(inference); } ignore.push(inference); const inferredFacts = facts.map((f) => this.loadFact(f, ignore)).flat(); return inferredFacts; */ } search(clause: Clause) { if (clause.type === "fact" && clause.matches === undefined) clause.matches = []; switch (clause.type) { case "fact": // facts return one binding per matching row of the table (this.tables[clause.table] || []).forEach((fact) => this.bind(fact, clause)); break; case "conjunction": case "disjunction": case "exclusive_disjunction": clause.clauses.forEach((child) => { this.search(child); if (clause.bindings === undefined) clause.bindings = []; clause.bindings = clause.bindings.concat(child.bindings || []); }); break; case "comparison": return []; default: throw new TODO(`can't handle ${(clause as any).type} in clause`); } } join(bindings: Binding[][], group: Binding[], result: Binding[][]) { if (bindings.length === 0) { result.push(group); return; } const first = bindings[0]; const rest = bindings.slice(1); for (let binding of first) { this.join(rest, group.concat([binding]), result); } } // reduce joins bindings together where same-named variables match // it discards non-matching bindings (i.e. bindings that "disagree on the facts") reduceBindings(bindings: Binding[]): Binding | undefined { try { return bindings.reduce((current, binding) => { Object.keys(current).forEach((key) => { const boundVariable = binding[key]; const currBoundVariable = current[key]; if (boundVariable === undefined || currBoundVariable === undefined) return; if (!equal(boundVariable, currBoundVariable)) { throw new BindingMismatch( `bindings disagree: ${expressionToString(boundVariable)} != ${expressionToString(currBoundVariable)}` ); } }); return Object.assign(current, binding); }, {}); } catch (e: any) { if (e.type === "BindingMismatch") return undefined; throw e; } } bind(fact: Fact, clause: Fact) { if (clause.bindings === undefined) clause.bindings = []; const entries: [string, Constant][] = []; for (let i = 0; i < fact.fields.length; i++) { const value = fact.fields[i]; if (!isConstant(value)) { throw new Entception(`can't bind non-constant field of type ${value.type} in ${factToString(fact)}`); } if (i >= clause.fields.length) break; const field = clause.fields[i]; if (field.type === "variable" && field.value !== "?") { entries.push([field.value, value]); } else if ( (field.type === "string" || field.type === "number" || field.type === "roll") && !equal(value, field) ) { return undefined; } } if (clause.matches === undefined) { clause.matches = []; } clause.matches.push(fact); clause.bindings.push(Object.fromEntries(entries)); } evaluateComparison(comparison: Comparison, binding: Binding): boolean { const left = this.evaluateExpression(comparison.left, binding); const right = this.evaluateExpression(comparison.right, binding); const l = left.type === "roll" ? this.averageRoll(left) : left.value; const r = right.type === "roll" ? this.averageRoll(right) : right.value; switch (comparison.operator) { case "=": return l === r; case "!=": return l !== r; case ">": return l > r; case ">=": return l >= r; case "<": return l < r; case "<=": return l <= r; } } probability(roll: Roll, op: ComparisonOperator, target: number): number { let outcomes = 0; let positive_outcomes = 0; for (let i = 0; i < roll.count; i++) { for (let j = 1; j <= roll.die; j++) { const r = j + roll.modifier; outcomes++; switch (op) { case "=": if (r === target) positive_outcomes++; break; case "!=": if (r !== target) positive_outcomes++; break; case ">=": if (r >= target) positive_outcomes++; break; case "<=": if (r <= target) positive_outcomes++; break; case ">": if (r > target) positive_outcomes++; break; case "<": if (r < target) positive_outcomes++; break; } } } return positive_outcomes / outcomes; } averageRoll(roll: Roll): number { let total = 0; for (let i = 0; i < roll.count; i++) { total += Math.floor(0.5 * roll.die) + 1 + roll.modifier; } return total; } generateRoll(roll: Roll): Number { let total = 0; for (let i = 0; i < roll.count; i++) { total += Math.floor(this.rng() * roll.die) + 1 + roll.modifier; } return { type: "number", value: total, }; } aggregate(variables: string[], bindings: Binding[]): Binding[][] { return groupBy(bindings, (b) => { const group = Object.fromEntries(variables.map((v) => [v, b[v]])); return JSON.stringify(group); }); } evaluateFunction(fn: Function, binding: Binding): Constant { let arg: Expression; switch (fn.function) { case "Floor": arg = this.evaluateExpression(fn.arguments[0], binding); if (arg.type !== "number") { throw new Entception(`Floor requires numeric argument, got ${arg.type}`); } return { type: "number", value: Math.floor(arg.value) }; case "Ceil": arg = this.evaluateExpression(fn.arguments[0], binding); if (arg.type !== "number") { throw new Entception(`Floor requires numeric argument, got ${arg.type}`); } return { type: "number", value: Math.floor(arg.value) }; case "Pr": if (fn.arguments[0].type === "comparison") { const roll = this.evaluateExpression(fn.arguments[0].left, binding); const operator = fn.arguments[0].operator; const target = this.evaluateExpression(fn.arguments[0].right, binding); if (roll.type !== "roll" || target.type !== "number") { throw new Entception(`can't compute probability for ${expressionToString(fn.arguments[0])}`); } return { type: "number", value: this.probability(roll, operator, target.value), }; } else { const roll = this.evaluateExpression(fn.arguments[0], binding); if (roll.type !== "roll") throw new Entception(`first argument to probability function must be a roll`); return roll; } default: throw new TODO(`can't handle function ${fn.function}`); } } evaluateAggregateFunction(fn: Function, bindings: Binding[]): Constant[] { if (fn.arguments[0].type !== "variable") { throw new Entception(`${fn.function} function requires a single variable argument, got ${fn.arguments[0].type}`); } const arg = fn.arguments[0]; const agg = this.aggregate([arg.value], bindings); switch (fn.function) { case "Count": return agg.map((group: Binding[]) => { return { type: "number", value: group.length, }; }); case "Sum": return agg.map((group: Binding[]) => { return { type: "number", value: group .map((b) => b[arg.value]) .reduce((total, curr) => { if (curr === undefined) return total; if (curr.type === "roll") return total; if (curr.type !== "number") throw new Entception(`Sum got a non-numerical argument, ${arg.value} = ${curr.type}`); return total + curr.value; }, 0), }; }); default: throw new TODO(`can't handle aggregate function "${fn.function}"`); } } evaluateBinaryOperation(op: BinaryOperation, binding: Binding): number { const left = this.evaluateExpression(op.left, binding); if (left.type !== "number") { throw new Entception(`binary operation requires number on left-hand side, got ${left.type}`); } const right = this.evaluateExpression(op.right, binding); if (right.type !== "number") { throw new Entception(`binary operation requires number on right-hand side, got ${right.type}`); } switch (op.operator) { case "+": return left.value + right.value; case "-": return left.value - right.value; case "/": return left.value / right.value; case "*": return left.value * right.value; case "^": return Math.pow(left.value, right.value); } } evaluateExpression(expr: Expression, binding: Binding): Constant { switch (expr.type) { case "binary_operation": return { type: "number", value: this.evaluateBinaryOperation(expr, binding), }; case "function": return this.evaluateFunction(expr, binding); case "variable": const boundVariable = binding[expr.value]; if (boundVariable === undefined) { throw new Entception(`variable ${expr.value} missing from binding`); } return boundVariable; case "comparison": return { type: "boolean", value: this.evaluateComparison(expr, binding) }; case "boolean": case "string": case "number": case "roll": return expr; default: throw new Entception(`unhandled expression type ${(expr as any).type}: ${expressionToString(expr)}`); } } searchExpression<T>(expr: Expression, fn: (expr: Expression) => T | undefined | false): T[] { const result = fn(expr); if (result === false) return []; const a = result === undefined ? [] : [result]; switch (expr.type) { case "boolean": case "number": case "roll": case "variable": case "string": return a; case "comparison": return a.concat(this.searchExpression(expr.left, fn).concat(this.searchExpression(expr.right, fn))); case "binary_operation": return a.concat(this.searchExpression(expr.left, fn).concat(this.searchExpression(expr.right, fn))); case "function": return a.concat(expr.arguments.map((e) => this.searchExpression(e, fn)).flat()); } } evaluateVeracity(clause: Clause): boolean { switch (clause.type) { case "fact": return ( (clause.negative && (clause.matches || []).length === 0) || (!clause.negative && (clause.matches || []).length > 0) ); case "comparison": if (clause.veracity === undefined) { throw new Entception(`expected comparison to have veracity: ${comparisonToString(clause)}`); } return clause.veracity; case "conjunction": clause.veracity = clause.clauses.every((c) => this.evaluateVeracity(c)); break; case "disjunction": clause.veracity = clause.clauses.some((c) => this.evaluateVeracity(c)); break; case "exclusive_disjunction": clause.veracity = clause.clauses.filter((c) => this.evaluateVeracity(c)).length === 1; break; default: throw new TODO(`can't evaluate veracity of ${(clause as any).type}`); } clause.veracity = (clause.negative && !clause.veracity) || (!clause.negative && clause.veracity); return clause.veracity; } } export function statementToString(stmt: Statement, color: boolean = false): string { switch (stmt.type) { case "claim": return claimToString(stmt, color); case "inference": return inferenceToString(stmt, color); case "query": return queryToString(stmt, color); case "comment": return `// ${stmt.value}`; case "command": return commandToString(stmt); default: return JSON.stringify(stmt, null, 2); } } export function inferenceToString(inf: Inference, color: boolean = false): string { return `${factToString(inf.left, color)} :- ${clauseToString(inf.right, color)}.`; } export function queryToString(q: Query, color: boolean = false): string { return `? ${clauseToString(q.clause, color)}`; } export function factToString(fact: Fact, color: boolean = false): string { const s = `${fact.negative ? "~" : ""}${fact.table}(${fact.fields.map((e) => expressionToString(e)).join(", ")})`; if (color) { if (fact.matches === undefined) { return chalk.yellow(s); } else if (fact.matches.length === 0) { return chalk.red(s); } else { return chalk.green(s); } } return s; } const JUNCTION_OPERATOR = { conjunction: "&", disjunction: "|", exclusive_disjunction: "^", }; export function clauseToString(clause: Clause, color: boolean = false): string { const neg = "negative" in clause && clause.negative ? "~" : ""; switch (clause.type) { case "fact": return factToString(clause, color); case "conjunction": case "disjunction": case "exclusive_disjunction": const op = " " + JUNCTION_OPERATOR[clause.type] + " "; let parens = ["(", ")"]; if (clause.veracity === true) { parens = parens.map((s) => chalk.green(s)); } else if (clause.veracity === false) { parens = parens.map((s) => chalk.red(s)); } else { parens = parens.map((s) => chalk.yellow(s)); } return neg + parens[0] + clause.clauses.map((c) => clauseToString(c, color)).join(op) + parens[1]; case "comparison": if (clause.veracity === true) { return chalk.green(comparisonToString(clause)); } else if (clause.veracity === false) { return chalk.red(comparisonToString(clause)); } else { return chalk.yellow(comparisonToString(clause)); } default: return JSON.stringify(clause, null, 2); } } export function expressionToString(expr: Expression): string { switch (expr.type) { case "boolean": return expr.value.toString(); case "string": return expr.value; case "number": return expr.value.toString(); case "roll": return rollToString(expr); case "variable": return expr.value; case "binary_operation": return `${expressionToString(expr.left)} ${expr.operator} ${expressionToString(expr.right)}`; case "function": return `${expr.function}(${expr.arguments.map((e) => expressionToString(e)).join(", ")})`; case "comparison": return comparisonToString(expr); default: return JSON.stringify(expr, null, 2); } } export function comparisonToString(comparison: Comparison): string { return `${expressionToString(comparison.left)} ${comparison.operator} ${expressionToString(comparison.right)}`; } export function rollToString(roll: Roll): string { const mod = roll.modifier > 0 ? `+${roll.modifier}` : roll.modifier < 0 ? `-${roll.modifier}` : ""; return `${roll.count}d${roll.die}${mod}`; } export function claimToString(claim: Claim, color: boolean = false): string { return `ergo ${clauseToString(claim.clause, color)}`; } export function rollingToString(roll: Rolling): string { return `roll ${clauseToString(roll.clause)}`; } export function commandToString(command: Command): string { return `${command.command}(${command.arguments.map((e) => expressionToString(e)).join(", ")})`; }
the_stack
namespace ts.projectSystem { describe("unittests:: tsserver:: with project references and compile on save", () => { const dependecyLocation = `${tscWatch.projectRoot}/dependency`; const usageLocation = `${tscWatch.projectRoot}/usage`; const dependencyTs: File = { path: `${dependecyLocation}/fns.ts`, content: `export function fn1() { } export function fn2() { } ` }; const dependencyConfig: File = { path: `${dependecyLocation}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true, declarationDir: "../decls" }, compileOnSave: true }) }; const usageTs: File = { path: `${usageLocation}/usage.ts`, content: `import { fn1, fn2, } from '../decls/fns' fn1(); fn2(); ` }; const usageConfig: File = { path: `${usageLocation}/tsconfig.json`, content: JSON.stringify({ compileOnSave: true, references: [{ path: "../dependency" }] }) }; const localChange = "function fn3() { }"; const change = `export ${localChange}`; const changeJs = `function fn3() { } exports.fn3 = fn3;`; const changeDts = "export declare function fn3(): void;"; function expectedAffectedFiles(config: File, fileNames: readonly File[]): protocol.CompileOnSaveAffectedFileListSingleProject { return { projectFileName: config.path, fileNames: fileNames.map(f => f.path), projectUsesOutFile: false }; } function expectedUsageEmitFiles(appendJsText?: string): readonly File[] { const appendJs = appendJsText ? `${appendJsText} ` : ""; return [{ path: `${usageLocation}/usage.js`, content: `"use strict"; exports.__esModule = true;${appendJsText === changeJs ? "\nexports.fn3 = void 0;" : ""} var fns_1 = require("../decls/fns"); (0, fns_1.fn1)(); (0, fns_1.fn2)(); ${appendJs}` }]; } function expectedEmitOutput(expectedFiles: readonly File[]): EmitOutput { return { outputFiles: expectedFiles.map(({ path, content }) => ({ name: path, text: content, writeByteOrderMark: false })), emitSkipped: false, diagnostics: emptyArray }; } function noEmitOutput(): EmitOutput { return { emitSkipped: true, outputFiles: [], diagnostics: emptyArray }; } function expectedDependencyEmitFiles(appendJsText?: string, appendDtsText?: string): readonly File[] { const appendJs = appendJsText ? `${appendJsText} ` : ""; const appendDts = appendDtsText ? `${appendDtsText} ` : ""; return [ { path: `${dependecyLocation}/fns.js`, content: `"use strict"; exports.__esModule = true; ${appendJsText === changeJs ? "exports.fn3 = " : ""}exports.fn2 = exports.fn1 = void 0; function fn1() { } exports.fn1 = fn1; function fn2() { } exports.fn2 = fn2; ${appendJs}` }, { path: `${tscWatch.projectRoot}/decls/fns.d.ts`, content: `export declare function fn1(): void; export declare function fn2(): void; ${appendDts}` } ]; } describe("when dependency project is not open", () => { describe("Of usageTs", () => { it("with initial file open, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with initial file open, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to dependency, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to dependency, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to usage, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(localChange); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to usage, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(localChange); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to dependency, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to dependency, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to usage, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(changeJs); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to usage, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(changeJs); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); }); describe("Of dependencyTs in usage project", () => { it("with initial file open, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with initial file open, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with local change to dependency, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with local change to dependency, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with local change to usage, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with local change to usage, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with change to dependency, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with change to dependency, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with change to usage, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with change to usage, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); }); }); describe("when the depedency file is open", () => { describe("Of usageTs", () => { it("with initial file open, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with initial file open, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to dependency, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: dependencyTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to dependency, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: dependencyTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to usage, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(localChange); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to usage, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(localChange); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to dependency, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: dependencyTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to dependency, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: dependencyTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to usage, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(changeJs); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to usage, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedUsageEmitFiles(changeJs); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: usageTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); }); describe("Of dependencyTs in usage project", () => { it("with initial file open, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with local change to dependency, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: dependencyTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with local change to usage, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with change to dependency, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: dependencyTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); it("with change to usage, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response; assert.isFalse(actualEmit, "Emit files"); assert.equal(host.writtenFiles.size, 0); // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); }); }); describe("Of dependencyTs", () => { it("with initial file open, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]), expectedAffectedFiles(dependencyConfig, [dependencyTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedDependencyEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with initial file open, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(dependencyConfig, [dependencyTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedDependencyEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to dependency, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: dependencyTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray), expectedAffectedFiles(dependencyConfig, [dependencyTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedDependencyEmitFiles(localChange); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to dependency, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: dependencyTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(dependencyConfig, [dependencyTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedDependencyEmitFiles(localChange); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to usage, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray), expectedAffectedFiles(dependencyConfig, [dependencyTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedDependencyEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with local change to usage, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: localChange } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(dependencyConfig, [dependencyTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedDependencyEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to dependency, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: dependencyTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]), expectedAffectedFiles(dependencyConfig, [dependencyTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedDependencyEmitFiles(changeJs, changeDts); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to dependency, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: dependencyTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(dependencyConfig, [dependencyTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedDependencyEmitFiles(changeJs, changeDts); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to usage, without specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, emptyArray), expectedAffectedFiles(dependencyConfig, [dependencyTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedDependencyEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); it("with change to usage, with specifying project file", () => { const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) ); const session = createSession(host); openFilesForSession([usageTs, dependencyTs], session); session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path } }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); session.executeCommandSeq<protocol.ChangeRequest>({ command: protocol.CommandTypes.Change, arguments: { file: usageTs.path, ...location, endLine: location.line, endOffset: location.offset, insertString: change } }); host.writtenFiles.clear(); // Verify CompileOnSaveAffectedFileList const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({ command: protocol.CommandTypes.CompileOnSaveAffectedFileList, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(dependencyConfig, [dependencyTs]) ], "Affected files"); // Verify CompileOnSaveEmit const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response; assert.isTrue(actualEmit, "Emit files"); const expectedFiles = expectedDependencyEmitFiles(); assert.equal(host.writtenFiles.size, expectedFiles.length); for (const file of expectedFiles) { assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); } // Verify EmitOutput const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({ command: protocol.CommandTypes.EmitOutput, arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } }).response as EmitOutput; assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); }); }); }); }); describe("unittests:: tsserver:: with project references and compile on save with external projects", () => { it("compile on save emits same output as project build", () => { const tsbaseJson: File = { path: `${tscWatch.projectRoot}/tsbase.json`, content: JSON.stringify({ compileOnSave: true, compilerOptions: { module: "none", composite: true } }) }; const buttonClass = `${tscWatch.projectRoot}/buttonClass`; const buttonConfig: File = { path: `${buttonClass}/tsconfig.json`, content: JSON.stringify({ extends: "../tsbase.json", compilerOptions: { outFile: "Source.js" }, files: ["Source.ts"] }) }; const buttonSource: File = { path: `${buttonClass}/Source.ts`, content: `module Hmi { export class Button { public static myStaticFunction() { } } }` }; const siblingClass = `${tscWatch.projectRoot}/SiblingClass`; const siblingConfig: File = { path: `${siblingClass}/tsconfig.json`, content: JSON.stringify({ extends: "../tsbase.json", references: [{ path: "../buttonClass/" }], compilerOptions: { outFile: "Source.js" }, files: ["Source.ts"] }) }; const siblingSource: File = { path: `${siblingClass}/Source.ts`, content: `module Hmi { export class Sibling { public mySiblingFunction() { } } }` }; const host = createServerHost([libFile, tsbaseJson, buttonConfig, buttonSource, siblingConfig, siblingSource], { useCaseSensitiveFileNames: true }); // ts build should succeed tscWatch.ensureErrorFreeBuild(host, [siblingConfig.path]); const sourceJs = changeExtension(siblingSource.path, ".js"); const expectedSiblingJs = host.readFile(sourceJs); const session = createSession(host); openFilesForSession([siblingSource], session); session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({ command: protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: siblingSource.path, projectFileName: siblingConfig.path } }); assert.equal(host.readFile(sourceJs), expectedSiblingJs); }); }); }
the_stack
// <copyright file="manage-categories.tsx" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> import * as React from "react"; import { Loader, Flex, Text, Image } from "@fluentui/react-northstar"; import { SeverityLevel } from "@microsoft/applicationinsights-web"; import { getApplicationInsightsInstance } from "../../helpers/app-insights"; import * as microsoftTeams from "@microsoft/teams-js"; import { createBrowserHistory } from "history"; import CommandBar from "./category-commandbar"; import CategoryTable from "./category-table"; import { getAllCategories } from "../../api/category-api"; import AddCategory from "./add-new-category"; import EditCategory from "./edit-category"; import DeleteCategory from "./delete-category"; import { WithTranslation, withTranslation } from "react-i18next"; import { ICategoryDetails } from "../models/category"; import "../../styles/curator.css" let moment = require('moment'); const browserHistory = createBrowserHistory({ basename: "" }); interface ICategoryState { loader: boolean; categories: ICategoryDetails[]; selectedCategories: string[]; filteredCategory: ICategoryDetails[]; showAddCategory: boolean; showEditCategory: boolean; editCategory: ICategoryDetails | undefined; message: string | undefined; showDeleteCategory: boolean; } /** Component for displaying on category details. */ class ManageCategory extends React.Component<WithTranslation, ICategoryState> { telemetry?: any = null; teamId?: string | null; userObjectId?: string = ""; appInsights: any; appUrl: string = (new URL(window.location.href)).origin; translate: any; constructor(props: any) { super(props); let search = window.location.search; let params = new URLSearchParams(search); this.telemetry = params.get("telemetry"); this.teamId = params.get("teamId"); this.state = { loader: true, filteredCategory: [], categories: [], selectedCategories: [], showAddCategory: false, showEditCategory: false, editCategory: undefined, message: undefined, showDeleteCategory: false } } /** * Used to initialize Microsoft Teams sdk */ async componentDidMount() { microsoftTeams.initialize(); microsoftTeams.getContext((context) => { this.userObjectId = context.userObjectId; // Initialize application insights for logging events and errors. this.appInsights = getApplicationInsightsInstance(this.telemetry, browserHistory); this.getCategory(); }); } /** *Get categories from API */ async getCategory() { this.appInsights.trackTrace({ message: `'getCategory' - Initiated request`, properties: { User: this.userObjectId }, severityLevel: SeverityLevel.Information }); let category = await getAllCategories(); if (category.status === 200 && category.data) { this.appInsights.trackTrace({ message: `'getCategory' - Request success`, properties: { User: this.userObjectId }, severityLevel: SeverityLevel.Information }); console.log(category); this.setState({ categories: category.data, filteredCategory: category.data }); } else { this.appInsights.trackTrace({ message: `'getCategory' - Request failed`, properties: { User: this.userObjectId }, severityLevel: SeverityLevel.Information }); } this.setState({ loader: false }); } /** * Handle back button click. */ onBackButtonClick = () => { this.setState({ showAddCategory: false, showEditCategory: false, selectedCategories: [], showDeleteCategory: false }); this.getCategory(); } /** *Filters table as per search text entered by user *@param {String} searchText Search text entered by user */ handleSearch = (searchText: string) => { if (searchText) { let filteredData = this.state.categories.filter(function (category) { return category.categoryName ?.toUpperCase().includes(searchText.toUpperCase()) || category.categoryDescription ?.toUpperCase().includes(searchText.toUpperCase()); }); this.setState({ filteredCategory: filteredData }); } else { this.setState({ filteredCategory: this.state.categories }); } } /** * Handle category selection change. */ onCategorySelected = (categoryId: string, isSelected: boolean) => { if (isSelected) { let selectCategory = this.state.selectedCategories; selectCategory.push(categoryId); this.setState({ selectedCategories: selectCategory }) } else { let filterCategory = this.state.selectedCategories.filter((Id) => { return Id !== categoryId; }); this.setState({ selectedCategories: filterCategory }) } } /** *Navigate to add new category page */ handleAddButtonClick = () => { this.setState({ showAddCategory: true }); } /** *Navigate to edit category page */ handleEditButtonClick = () => { let editCategory = this.state.categories.find(category => category.categoryId === this.state.selectedCategories[0]) this.setState({ showEditCategory: true, editCategory: editCategory }); } /** *Deletes selected categories */ handleDeleteButtonClick = () => { this.setState({ showDeleteCategory: true }); } onSuccess = (operation: string) => { if (operation === "add") { this.setState({ message: this.translate('successAddCategory'), showAddCategory: false, showEditCategory: false, selectedCategories: [], showDeleteCategory: false }); } else if (operation === "delete") { this.setState({ message: this.translate('successDeleteCategory'), showAddCategory: false, showEditCategory: false, selectedCategories: [], showDeleteCategory: false }); } else if (operation === "edit") { this.setState({ message: this.translate('successEditCategory'), showAddCategory: false, showEditCategory: false, selectedCategories: [], showDeleteCategory: false }); } this.getCategory(); } /** * Renders the component */ public render(): JSX.Element { return ( <div> {this.getWrapperPage()} </div> ); } /** *Get wrapper for page which acts as container for all child components */ private getWrapperPage = () => { const { t } = this.props; this.translate = t; if (this.state.loader) { return ( <div className="tab-container"> <Loader /> </div> ); } else { return ( <div className="module-container"> {(this.state.showAddCategory === false && this.state.showEditCategory === false && !this.state.showDeleteCategory) && <div className="tab-container"> <CommandBar isDeleteEnable={this.state.selectedCategories.length > 0} isEditEnable={this.state.selectedCategories.length > 0 && this.state.selectedCategories.length < 2} onAddButtonClick={this.handleAddButtonClick} onDeleteButtonClick={this.handleDeleteButtonClick} onEditButtonClick={this.handleEditButtonClick} handleTableFilter={this.handleSearch} isAddEnabled={!(this.state.categories.length >= 10)} /> <div> {this.state.categories.length !== 0 && <CategoryTable showCheckbox={true} categories={this.state.filteredCategory} onCheckBoxChecked={this.onCategorySelected} /> } </div> {this.state.categories.length === 0 && <Flex gap="gap.small" className="margin-top-medium" > <Flex.Item> <Image className="icon-size" fluid src={this.appUrl + "/Artifacts/helpIcon.png"} /> </Flex.Item> <Flex.Item> <Flex column gap="gap.small" > <Text weight="bold" content={t('noCategoryFoundText1')} /> <Text content={t('noCategoryFoundText2')} /> </Flex> </Flex.Item> </Flex>} </div>} {this.state.showAddCategory && <div> <AddCategory isNewAllowed={!(this.state.categories.length >= 10)} categories={this.state.categories} onBackButtonClick={this.onBackButtonClick} teamId={this.teamId!} onSuccess={this.onSuccess} /> </div>} {this.state.showEditCategory && <div> <EditCategory category={this.state.editCategory!} onBackButtonClick={this.onBackButtonClick} teamId={this.teamId!} onSuccess={this.onSuccess} /> </div>} {(this.state.showAddCategory === false && this.state.showEditCategory === false && !this.state.showDeleteCategory) && <div className="category-footer"> <Flex> {this.state.message !== undefined && <Flex vAlign="center" className=" margin-left-large"> <Image className="preview-image-icon" fluid src={this.appUrl + "/Artifacts/categoryIcon.png"} /> <Text className="margin-left-small" content={this.state.message} /> </Flex>} {this.state.categories.length > 0 && <Flex.Item push> <Text size="small" align="end" content={t('lastUpdatedOn', { time: moment(new Date(this.state.categories[0].timestamp)).format("llll") })} /> </Flex.Item>} </Flex> </div>} {this.state.showDeleteCategory && <div> <DeleteCategory categories={this.state.categories} selectedCategories={this.state.selectedCategories} onBackButtonClick={this.onBackButtonClick} teamId={this.teamId!} onSuccess={this.onSuccess} /> </div>} </div> ); } } } export default withTranslation()(ManageCategory);
the_stack
import autobind from 'autobind-decorator'; import { ACCInputEvent, ACCInputEventInit } from '../events/input-event'; import { ACCErrorEvent } from '../events/error-event'; import { add, copy, scale, sub, distance, equal } from './../vec2'; import { scalemap } from './../utils'; import { html, LitElement } from '@polymer/lit-element'; import { property } from './decorators'; import { InputType } from './types'; export interface InputProperties { selected:boolean; initialized:boolean; controls:boolean; contentSelector: string; } export const isAbstractInputElement = (el:any): el is AbstractInputElement => ['selected', 'initialized', 'controls'].every(prop=> typeof el[prop] !== 'undefined'); /** * AbstractInputElement is the base abstract class for all inputs */ export abstract class AbstractInputElement extends LitElement { /** * setting this property or attribute will display the input's calibration */ @property({ type:Boolean }) public controls:boolean = false; /** * a higher smoothing value (0-1) results in a slower and smoother * interpolation towards the current position. This creates less jitter * from an input but a high value can make the input feel slow. */ @property({ type: Number }) public smoothing:number = 0; /** * this attribute is used on the HTML node to denote it is the selected input * and to begin initializing */ @property({ type:Boolean }) public selected:boolean = false; @property({ type: String }) public contentSelector:string = ''; @property({ type: Boolean }) public disableClamp: boolean = false; /////////////////////////////////// /** * the current X position as mapped to the contentElement */ public get contentX() { return this.targetPosition[0]; } /** * the current Y position as mapped to the contentElement */ public get contentY() { return this.targetPosition[1]; } /** * does the current input have a control modal */ public get hasControls() { return false; } /** * the type of input this instance is, i.e. 'mouse', 'pose' */ public inputType:InputType; public targetPosition:[number, number] = [0, 0]; /** * the input's vector that is updated whenever there is new input data */ public position:[number, number] = [-1, -1]; /** * is the input currently in the phase of initializing itself? */ public get isInitializing(){ return this.__isInitializing; } /** * has the input completed initialization and is currently in operation? */ public get isReady(){ return this.__isReady; } public set contentElement(element: HTMLElement | null) { const changed = this.__contentEl !== element; const prev = this.__contentEl; this.__contentEl = element; //provide a hook if(changed) { this._handleContentElementChanged(element, prev); } } public get contentElement(): HTMLElement | null { if (!this.__contentEl && this.contentSelector) { this.contentElement = document.querySelector(this.contentSelector); } return this.__contentEl; } /** * the input's current target vector, this could be different if smoothing * is more than 0 */ protected _lastFoundPosition:[number, number] = [-1, -1]; protected _lastFoundTargetPosition:[number, number] = [0, 0]; /** * the main element of content, set through 'target' or 'targetSelector' */ private __contentEl: HTMLElement; private __isInitializing:boolean = false; private __isReady:boolean = false; private __hasTickedSinceReady:boolean = false; protected _wasAborted:boolean = false; /** * Must be called to begin using input mode, listen to 'ready' to know when completed */ abstract initialize():void; abstract stop():void /** * apply smoothing to the current position, * moving towards the _targetPosition according to smoothing * @returns true if the position value changed */ protected _stepTowardsTarget(): boolean { const pos = this.position; const last = this._lastFoundPosition; const targPos = this.targetPosition; const lastTarg = this._lastFoundTargetPosition; const { smoothing } = this; if ( equal(pos, last) ) { return false; } //if theres no smoothing //or this is the first tick since ready //or its really really close, set to target if(smoothing === 0 || !this.__hasTickedSinceReady || distance(pos, last) < 0.00001){ copy(last, pos); copy(lastTarg, targPos); } else { const ease = scalemap(smoothing, 0, 1, 0.95, 0); this.position = add(pos, scale(sub(last, pos), ease)); this.targetPosition = add(targPos, scale(sub(lastTarg, targPos), ease)); } return true; } /** * should an 'input' event be dispatched as well on this tick * this method exists so you can override in other inputs to consider other variables */ protected _shouldDispatchInput(): boolean { return this._stepTowardsTarget(); } /** * is it ok to initialize this input? * no if it is already initializing or it was aborted mid-initialization */ public get canInitialize(): boolean { //TODO should also if fail if input cant be supported, like if wasm isnt supported return !this._wasAborted && !this.__isInitializing; } /** * the Event that will be provided in every dispatched event from an input * Most input's will override this to provide even more data unique to their input * Input implementations can override this to provide extra details * @param type * @param bubbles * @param composed */ protected _createEvent(type: string, bubbles: boolean= true, composed: boolean= true): ACCInputEvent { const eventInit:ACCInputEventInit = { detail: { inputType: this.inputType, position: this.position }, bubbles, //send outside of shadow to parent element composed }; return new ACCInputEvent(type, eventInit); } //overriding to ensure consistent event types dispatchEvent(evt:ACCInputEvent | ACCErrorEvent){ return super.dispatchEvent(evt); } @autobind protected _dispatchChange(): void { this.dispatchEvent(this._createEvent(ACCInputEvent.CHANGE)); } @autobind protected _dispatchError(error: Error):void { this.dispatchEvent(new ACCErrorEvent(error)); } /** * when the input BEGINS to load any required resources, ask for any permissions etc * @event */ @autobind protected _dispatchInitializing():void { this.__isInitializing = true; this.dispatchEvent(this._createEvent(ACCInputEvent.INITIALIZING)); } /** * when the input has successfully began * @event */ @autobind protected _dispatchReady():void { this.__isInitializing = false; this.__isReady = true; this.__hasTickedSinceReady = false; this.dispatchEvent(this._createEvent(ACCInputEvent.READY)); } /** * when the input has stopped operation */ @autobind protected _dispatchStop():void { if(this.__isInitializing){ this._wasAborted = true; } //TODO should this be set false here or inside each inputs initializing where it completes or fails? this.__isInitializing = false; this.__isReady = false; this.dispatchEvent(this._createEvent(ACCInputEvent.STOP)) } /** * when the input has performed any new effort, * even if there is no new input found. * i.e. webcam updated but no face was found, this still triggers * @event AbstractInputElement#tick dispatched every time the input updates, even if no changes */ @autobind protected _dispatchTick():void { if (this._shouldDispatchInput()) { // the position value changed this.__dispatchInput(); } /** * Tick event, occurs on every update * @event AbstractInput#tick */ this.dispatchEvent(this._createEvent(ACCInputEvent.TICK)); this.__hasTickedSinceReady = true; } /** * when the input has new tracking data to announce */ @autobind private __dispatchInput():void { this.dispatchEvent(this._createEvent(ACCInputEvent.INPUT)); } public _propertiesChanged(props: InputProperties, changedProps: InputProperties, prevProps: InputProperties): void { super._propertiesChanged(props, changedProps, prevProps); if(!changedProps || !prevProps){ //this can happen as a result from changing an attribute directly return; } if (changedProps.contentSelector) { this.contentElement = null; // query the new selector to get the element this.contentElement; //if the document isn't ready yet the selector element might not yet be in dom if (document.readyState !== 'complete') { const waitUntilReady = () => { this.contentElement; if(this.contentElement || document.readyState === 'complete') { document.removeEventListener('readystatechange', waitUntilReady); } }; document.addEventListener('readystatechange', waitUntilReady); } } //update controls as attribute because CSS if(changedProps.controls && !prevProps.controls){ this.setAttribute('controls', 'true'); this.dispatchEvent(this._createEvent(ACCInputEvent.CONTROLS_OPEN)); } else if(!changedProps.controls && prevProps.controls) { this.removeAttribute('controls'); this.dispatchEvent(this._createEvent(ACCInputEvent.CONTROLS_CLOSE)); } if(!changedProps.selected && prevProps.selected){ this.stop(); } else if(changedProps.selected && !prevProps.selected){ this.initialize(); } } /** * Hook to handle any changes whenever the contentElement has changed * @param contentElement * @param previous */ protected _handleContentElementChanged(contentElement: HTMLElement, previous: HTMLElement) { } _render(_props:any){ return html``; } setTargetPosition([x, y]: [number, number]) { this._lastFoundTargetPosition[0] = x; this._lastFoundTargetPosition[1] = y; const bcr = this.contentElement.getBoundingClientRect(); const nx = scalemap(x, 0, bcr.width, -1, 1); const ny = scalemap(y, 0, bcr.height, -1, 1); this._lastFoundPosition[0] = nx; this._lastFoundPosition[1] = ny; this._dispatchTick(); } setPosition([x, y]: [number, number]) { this._lastFoundPosition[0] = x; this._lastFoundPosition[1] = y; const bcr = this.contentElement.getBoundingClientRect() const sx = scalemap(x, -1, 1, 0, bcr.width); const sy = scalemap(y, -1, 1, 0, bcr.height); this._lastFoundTargetPosition[0] = sx; this._lastFoundTargetPosition[1] = sy; this._dispatchTick(); } _shouldPropertyChange(property:string, value:any, old:any) { if(property === 'smoothing'){ //constrain smoothing to 0>= value <= 1 const v = value as number; if( v < 0 || v > 1){ return false; } } return super._shouldPropertyChange(property, value, old); } }
the_stack
import { ethers, network } from 'hardhat'; import { BigNumber, Signer } from 'ethers'; import { expect } from 'chai'; import { TestERC20__factory, TestERC20, BatchPayments, ERC20FeeProxy } from '../../src/types'; import { batchPaymentsArtifact, erc20FeeProxyArtifact } from '../../src/lib'; const logGasInfos = false; describe('contract: BatchPayments: ERC20', () => { let payee1: string; let payee2: string; let payee3: string; let ownerAddress: string; let spender1Address: string; let spender2Address: string; let spender3Address: string; let feeAddress: string; let token1: TestERC20; let token2: TestERC20; let token3: TestERC20; let batch: BatchPayments; let erc20FeeProxy: ERC20FeeProxy; let token1Address: string; let token2Address: string; let token3Address: string; let batchAddress: string; let owner: Signer; let spender1: Signer; let spender2: Signer; let spender3: Signer; let beforeERC20Balance1: BigNumber; let afterERC20Balance1: BigNumber; let beforeERC20Balance2: BigNumber; let afterERC20Balance2: BigNumber; let beforeERC20Balance3: BigNumber; let afterERC20Balance3: BigNumber; const referenceExample1 = '0xaaaa'; const referenceExample2 = '0xbbbb'; const referenceExample3 = '0xcccc'; const erc20Decimal = BigNumber.from('1000000000000000000'); before(async () => { [, payee1, payee2, payee3, feeAddress] = (await ethers.getSigners()).map((s) => s.address); [owner, spender1, spender2, spender3] = await ethers.getSigners(); erc20FeeProxy = erc20FeeProxyArtifact.connect(network.name, owner); batch = batchPaymentsArtifact.connect(network.name, owner); token1 = await new TestERC20__factory(owner).deploy(erc20Decimal.mul(10000)); token2 = await new TestERC20__factory(owner).deploy(erc20Decimal.mul(10000)); token3 = await new TestERC20__factory(owner).deploy(erc20Decimal.mul(10000)); ownerAddress = await owner.getAddress(); spender1Address = await spender1.getAddress(); spender2Address = await spender2.getAddress(); spender3Address = await spender3.getAddress(); token1Address = token1.address; token2Address = token2.address; token3Address = token3.address; batchAddress = batch.address; await batch.connect(owner).setBatchFee(100); }); beforeEach(async () => { // reset every amount of tokens and approvals. await token1.connect(spender1).transfer(ownerAddress, await token1.balanceOf(spender1Address)); await token1.connect(spender2).transfer(ownerAddress, await token1.balanceOf(spender2Address)); await token1.connect(spender3).transfer(ownerAddress, await token1.balanceOf(spender3Address)); await token1.connect(spender1).approve(batchAddress, 0); await token1.connect(spender3).approve(batchAddress, 0); // 2nd token await token2.connect(spender3).transfer(ownerAddress, await token2.balanceOf(spender3Address)); await token1.connect(spender3).approve(batchAddress, 0); // 3nd token await token3.connect(spender3).transfer(ownerAddress, await token3.balanceOf(spender3Address)); await token3.connect(spender3).approve(batchAddress, 0); }); after(async () => { await batch.connect(owner).setBatchFee(10); }); describe('Batch working well: right args, and approvals', () => { it('Should pay 3 ERC20 payments with paymentRef and pay batch fee', async function () { await token1.connect(owner).transfer(spender3Address, 1000); await token1.connect(spender3).approve(batchAddress, 1000); beforeERC20Balance1 = await token1.balanceOf(payee1); beforeERC20Balance2 = await token1.balanceOf(payee2); beforeERC20Balance3 = await token1.balanceOf(spender3Address); await expect( batch .connect(spender3) .batchERC20PaymentsWithReference( token1Address, [payee1, payee2, payee2], [200, 30, 40], [referenceExample1, referenceExample2, referenceExample3], [20, 2, 3], feeAddress, ), ) .to.emit(token1, 'Transfer') .withArgs(spender3Address, batchAddress, 200 + 30 + 40 + 20 + 2 + 3) .to.emit(erc20FeeProxy, 'TransferWithReferenceAndFee') .withArgs( token1Address, payee1, '200', ethers.utils.keccak256(referenceExample1), '20', feeAddress, ) .to.emit(token1, 'Transfer') .to.emit(erc20FeeProxy, 'TransferWithReferenceAndFee') .withArgs( token1Address, payee2, '30', ethers.utils.keccak256(referenceExample2), '2', feeAddress, ) .to.emit(token1, 'Transfer') .to.emit(erc20FeeProxy, 'TransferWithReferenceAndFee') .withArgs( token1Address, payee2, '40', ethers.utils.keccak256(referenceExample3), '3', feeAddress, ) // batch fee amount from the spender to feeAddress .to.emit(token1, 'Transfer') .withArgs( spender3Address, feeAddress, 27, // batch fee amount = (200+30+40)*10% ); afterERC20Balance1 = await token1.balanceOf(payee1); expect(afterERC20Balance1).to.be.equal(beforeERC20Balance1.add(200)); afterERC20Balance2 = await token1.balanceOf(payee2); expect(afterERC20Balance2).to.be.equal(beforeERC20Balance2.add(30 + 40)); afterERC20Balance3 = await token1.balanceOf(spender3Address); expect(beforeERC20Balance3).to.be.equal( afterERC20Balance3.add(200 + 20 + 20 + (30 + 2 + 3) + (40 + 3 + 4)), ); }); it('Should pay 3 ERC20 payments Multi tokens with paymentRef and pay batch fee', async function () { await token1.connect(owner).transfer(spender3Address, 1000); await token2.connect(owner).transfer(spender3Address, 1000); await token3.connect(owner).transfer(spender3Address, 1000); await token1.connect(spender3).approve(batchAddress, 1000); await token2.connect(spender3).approve(batchAddress, 1000); await token3.connect(spender3).approve(batchAddress, 1000); beforeERC20Balance1 = await token1.balanceOf(payee1); const beforeERC20Balance2_token2 = await token2.balanceOf(payee2); const beforeERC20Balance2_token3 = await token3.balanceOf(payee2); beforeERC20Balance3 = await token1.balanceOf(spender3Address); const beforeFeeAddress_token1 = await token1.balanceOf(feeAddress); const beforeFeeAddress_token2 = await token2.balanceOf(feeAddress); const beforeFeeAddress_token3 = await token3.balanceOf(feeAddress); await expect( batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( [token1Address, token2Address, token3Address], [payee1, payee2, payee2], [500, 300, 400], [referenceExample1, referenceExample2, referenceExample3], [60, 20, 30], feeAddress, ), ) // Transfer event of each token from the spender to the batch proxy .to.emit(token1, 'Transfer') .withArgs(spender3Address, batchAddress, 500 + 60) .to.emit(token2, 'Transfer') .withArgs(spender3Address, batchAddress, 300 + 20) .to.emit(token3, 'Transfer') .withArgs(spender3Address, batchAddress, 400 + 30) .to.emit(erc20FeeProxy, 'TransferWithReferenceAndFee') .withArgs( token1Address, payee1, '500', ethers.utils.keccak256(referenceExample1), '60', feeAddress, ) .to.emit(token2, 'Transfer') .to.emit(erc20FeeProxy, 'TransferWithReferenceAndFee') .withArgs( token2Address, payee2, '300', ethers.utils.keccak256(referenceExample2), '20', feeAddress, ) .to.emit(token3, 'Transfer') .to.emit(erc20FeeProxy, 'TransferWithReferenceAndFee') .withArgs( token3Address, payee2, '400', ethers.utils.keccak256(referenceExample3), '30', feeAddress, ) // batch fee amount from the spender to feeAddress for each token .to.emit(token1, 'Transfer') .withArgs( spender3Address, feeAddress, 50, // batch fee amount = 500*10% ) .to.emit(token2, 'Transfer') .withArgs(spender3Address, feeAddress, 30) .to.emit(token3, 'Transfer') .withArgs(spender3Address, feeAddress, 40); expect(await token1.balanceOf(payee1)).to.be.equal(beforeERC20Balance1.add(500)); expect(await token2.balanceOf(payee2)).to.be.equal(beforeERC20Balance2_token2.add(300)); expect(await token3.balanceOf(payee2)).to.be.equal(beforeERC20Balance2_token3.add(400)); expect(beforeERC20Balance3).to.be.equal( (await token1.balanceOf(spender3Address)).add(500 + 60 + 50), ); expect(await token1.balanceOf(feeAddress)).to.be.equal(beforeFeeAddress_token1.add(50 + 60)); expect(await token2.balanceOf(feeAddress)).to.be.equal(beforeFeeAddress_token2.add(20 + 30)); expect(await token3.balanceOf(feeAddress)).to.be.equal( beforeFeeAddress_token3.add((30 + 40) * 1), ); }); it('Should pay 3 ERC20 payments Multi tokens, with one payment of 0 token', async function () { await token1.connect(owner).transfer(spender3Address, 1000); await token2.connect(owner).transfer(spender3Address, 1000); await token3.connect(owner).transfer(spender3Address, 1000); await token1.connect(spender3).approve(batchAddress, 1000); await token2.connect(spender3).approve(batchAddress, 1000); await token3.connect(spender3).approve(batchAddress, 1000); beforeERC20Balance1 = await token1.balanceOf(payee1); const beforeERC20Balance2_token2 = await token2.balanceOf(payee2); const beforeERC20Balance2_token3 = await token3.balanceOf(payee2); beforeERC20Balance3 = await token1.balanceOf(spender3Address); const beforeFeeAddress_token1 = await token1.balanceOf(feeAddress); const beforeFeeAddress_token2 = await token2.balanceOf(feeAddress); const beforeFeeAddress_token3 = await token3.balanceOf(feeAddress); const tx = await batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( [token1Address, token2Address, token3Address], [payee1, payee2, payee2], [500, 0, 400], [referenceExample1, referenceExample2, referenceExample3], [60, 0, 30], feeAddress, ); await tx.wait(); expect(await token1.balanceOf(payee1)).to.be.equal(beforeERC20Balance1.add(500)); expect(await token2.balanceOf(payee2)).to.be.equal(beforeERC20Balance2_token2.add(0)); expect(await token3.balanceOf(payee2)).to.be.equal(beforeERC20Balance2_token3.add(400)); expect(beforeERC20Balance3).to.be.equal( (await token1.balanceOf(spender3Address)).add(500 + 60 + 50), ); expect(await token1.balanceOf(feeAddress)).to.be.equal(beforeFeeAddress_token1.add(50 + 60)); expect(await token2.balanceOf(feeAddress)).to.be.equal(beforeFeeAddress_token2.add(0)); expect(await token3.balanceOf(feeAddress)).to.be.equal( beforeFeeAddress_token3.add((30 + 40) * 1), ); }); it('Should pay 4 ERC20 payments on 2 tokens', async function () { await token1.connect(owner).transfer(spender3Address, 1000); await token2.connect(owner).transfer(spender3Address, 1000); await token1.connect(spender3).approve(batchAddress, 1000); await token2.connect(spender3).approve(batchAddress, 1000); beforeERC20Balance1 = await token1.balanceOf(payee2); beforeERC20Balance2 = await token2.balanceOf(payee2); beforeERC20Balance3 = await token1.balanceOf(spender3Address); const beforeERC20Balance3Token2 = await token2.balanceOf(spender3Address); const amount = 20; const feeAmount = 1; const nbTxs = 4; const [tokenAddresses, recipients, amounts, paymentReferences, feeAmounts] = getBatchPaymentsInputs(nbTxs, token1Address, payee2, amount, referenceExample1, feeAmount); tokenAddresses[2] = token2Address; tokenAddresses[3] = token2Address; const tx = await batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( tokenAddresses, recipients, amounts, paymentReferences, feeAmounts, feeAddress, ); await tx.wait(); afterERC20Balance1 = await token1.balanceOf(payee2); expect(afterERC20Balance1).to.be.equal(beforeERC20Balance1.add(amount * 2)); afterERC20Balance2 = await token2.balanceOf(payee2); expect(afterERC20Balance2).to.be.equal(beforeERC20Balance2.add(amount * 2)); afterERC20Balance3 = await token1.balanceOf(spender3Address); expect(beforeERC20Balance3).to.be.equal(afterERC20Balance3.add((20 + 1 + 2) * 2)); const afterERC20Balance3Token2 = await token2.balanceOf(spender3Address); expect(beforeERC20Balance3Token2).to.be.equal(afterERC20Balance3Token2.add((20 + 1 + 2) * 2)); }); it('Should pay 10 ERC20 payments', async function () { await token1.connect(owner).transfer(spender3Address, 1000); await token1.connect(spender3).approve(batchAddress, 1000); beforeERC20Balance1 = await token1.balanceOf(payee1); const beforeFeeAddress_token1 = await token1.balanceOf(feeAddress); const amount = 20; const feeAmount = 10; const nbTxs = 10; const [token1Addresses, recipients, amounts, paymentReferences, feeAmounts] = getBatchPaymentsInputs(nbTxs, token1Address, payee1, amount, referenceExample1, feeAmount); const tx = await batch .connect(spender3) .batchERC20PaymentsWithReference( token1Addresses[0], recipients, amounts, paymentReferences, feeAmounts, feeAddress, ); await tx.wait(); const receipt = await tx.wait(); if (logGasInfos) { console.log(`nbTxs= ${nbTxs}, gas consumption: `, receipt.gasUsed.toString()); } afterERC20Balance1 = await token1.balanceOf(payee1); expect(afterERC20Balance1).to.be.equal(beforeERC20Balance1.add(amount * nbTxs)); const afterFeeAddress_token1 = await token1.balanceOf(feeAddress); expect(afterFeeAddress_token1).to.be.equal( beforeFeeAddress_token1.add(feeAmount * nbTxs + (amount * nbTxs) / 10), ); }); it('Should pay 10 ERC20 payments on multiple tokens', async function () { await token1.connect(owner).transfer(spender3Address, 1000); await token2.connect(owner).transfer(spender3Address, 1000); await token1.connect(spender3).approve(batchAddress, 1000); await token2.connect(spender3).approve(batchAddress, 1000); beforeERC20Balance1 = await token1.balanceOf(payee1); beforeERC20Balance2 = await token2.balanceOf(payee1); const amount = 20; const feeAmount = 10; const nbTxs = 10; const [tokenAddresses, recipients, amounts, paymentReferences, feeAmounts] = getBatchPaymentsInputs(nbTxs, token1Address, payee1, amount, referenceExample1, feeAmount); for (let i = 0; i < 5; i++) { tokenAddresses[i] = token2Address; } const tx = await batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( tokenAddresses, recipients, amounts, paymentReferences, feeAmounts, feeAddress, ); const receipt = await tx.wait(); if (logGasInfos) { console.log(`nbTxs= ${nbTxs}, gas consumption: `, receipt.gasUsed.toString()); } afterERC20Balance1 = await token1.balanceOf(payee1); expect(afterERC20Balance1).to.be.equal(beforeERC20Balance1.add(amount * 5)); // 5 txs on token1 afterERC20Balance2 = await token2.balanceOf(payee1); expect(afterERC20Balance2).to.be.equal(beforeERC20Balance2.add(amount * 5)); // 5 txs on token2 }); }); describe('Batch revert, issues with: args, or funds, or approval', () => { it('Should revert batch if not enough funds to pay the request', async function () { await token1.connect(owner).transfer(spender3Address, 100); await token1.connect(spender3).approve(batchAddress, 1000); await expect( batch .connect(spender3) .batchERC20PaymentsWithReference( token1Address, [payee1, payee2, payee3], [5, 30, 400], [referenceExample1, referenceExample2, referenceExample3], [1, 2, 3], feeAddress, ), ).revertedWith('revert not enough funds'); }); it('Should revert batch if not enough funds to pay the batch fee', async function () { await token1.connect(owner).transfer(spender3Address, 303); await token1.connect(spender3).approve(batchAddress, 1000); await expect( batch .connect(spender3) .batchERC20PaymentsWithReference( token1Address, [payee1, payee2], [100, 200], [referenceExample1, referenceExample2], [1, 2], feeAddress, ), ).revertedWith('not enough funds for the batch fee'); }); it('Should revert batch without approval', async function () { await token1.connect(owner).transfer(spender3Address, 303); await token1.connect(spender3).approve(batchAddress, 10); await expect( batch .connect(spender3) .batchERC20PaymentsWithReference( token1Address, [payee1, payee2, payee3], [20, 30, 40], [referenceExample1, referenceExample2, referenceExample3], [1, 2, 3], feeAddress, ), ).revertedWith('revert Not sufficient allowance for batch to pay'); }); it('Should revert batch multi tokens if not enough funds', async function () { await token1.connect(owner).transfer(spender3Address, 400); await token1.connect(spender3).approve(batchAddress, 1000); await expect( batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( [token1Address, token1Address, token1Address], [payee1, payee2, payee3], [5, 30, 400], [referenceExample1, referenceExample2, referenceExample3], [1, 2, 3], feeAddress, ), ).revertedWith('revert not enough funds'); }); it('Should revert batch multi tokens if not enough funds to pay the batch fee', async function () { await token1.connect(owner).transfer(spender3Address, 607); await token1.connect(spender3).approve(batchAddress, 1000); await expect( batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( [token1Address, token1Address, token1Address], [payee1, payee2, payee2], [100, 200, 300], [referenceExample1, referenceExample2, referenceExample3], [1, 2, 3], feeAddress, ), ).revertedWith('revert not enough funds'); }); it('Should revert batch multi tokens without approval', async function () { await token1.connect(owner).transfer(spender3Address, 1000); await token1.connect(spender3).approve(batchAddress, 10); await expect( batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( [token1Address, token1Address, token1Address], [payee1, payee2, payee3], [100, 200, 300], [referenceExample1, referenceExample2, referenceExample3], [1, 2, 3], feeAddress, ), ).revertedWith('revert Not sufficient allowance for batch to pay'); }); it('Should revert batch multi tokens if input s arrays do not have same size', async function () { await expect( batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( [token1Address, token1Address], [payee1, payee2, payee3], [5, 30, 40], [referenceExample1, referenceExample2, referenceExample3], [1, 2, 3], feeAddress, ), ).revertedWith('the input arrays must have the same length'); await expect( batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( [token1Address, token1Address, token1Address], [payee1, payee2], [5, 30, 40], [referenceExample1, referenceExample2, referenceExample3], [1, 2, 3], feeAddress, ), ).revertedWith('the input arrays must have the same length'); await expect( batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( [token1Address, token1Address, token1Address], [payee1, payee2, payee3], [5, 30], [referenceExample1, referenceExample2, referenceExample3], [1, 2, 3], feeAddress, ), ).revertedWith('the input arrays must have the same length'); await expect( batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( [token1Address, token1Address, token1Address], [payee1, payee2, payee3], [5, 30, 40], [referenceExample1, referenceExample2], [1, 2, 3], feeAddress, ), ).revertedWith('the input arrays must have the same length'); await expect( batch .connect(spender3) .batchERC20PaymentsMultiTokensWithReference( [token1Address, token1Address, token1Address], [payee1, payee2, payee3], [5, 30, 40], [referenceExample1, referenceExample2, referenceExample3], [1, 2], feeAddress, ), ).revertedWith('the input arrays must have the same length'); }); it('Should revert batch if input s arrays do not have same size', async function () { await expect( batch .connect(spender3) .batchERC20PaymentsWithReference( token1Address, [payee1, payee2, payee3], [5, 30, 40], [referenceExample1, referenceExample2, referenceExample3], [1, 2], feeAddress, ), ).revertedWith('the input arrays must have the same length'); await expect( batch .connect(spender3) .batchERC20PaymentsWithReference( token1Address, [payee1, payee2], [5, 30, 40], [referenceExample1, referenceExample2, referenceExample3], [1, 2, 3], feeAddress, ), ).revertedWith('the input arrays must have the same length'); await expect( batch .connect(spender3) .batchERC20PaymentsWithReference( token1Address, [payee1, payee2, payee3], [5, 30], [referenceExample1, referenceExample2, referenceExample3], [1, 2, 3], feeAddress, ), ).revertedWith('the input arrays must have the same length'); await expect( batch .connect(spender3) .batchERC20PaymentsWithReference( token1Address, [payee1, payee2, payee3], [5, 30, 40], [referenceExample1, referenceExample2], [1, 2, 3], feeAddress, ), ).revertedWith('the input arrays must have the same length'); }); }); }); // Allow to create easly BatchPayments input, especially for gas optimization const getBatchPaymentsInputs = function ( nbTxs: number, tokenAddress: string, recipient: string, amount: number, referenceExample1: string, feeAmount: number, ): [Array<string>, Array<string>, Array<number>, Array<string>, Array<number>] { let tokenAddresses = []; let recipients = []; let amounts = []; let paymentReferences = []; let feeAmounts = []; for (let i = 0; i < nbTxs; i++) { tokenAddresses.push(tokenAddress); recipients.push(recipient); amounts.push(amount); paymentReferences.push(referenceExample1); feeAmounts.push(feeAmount); } return [tokenAddresses, recipients, amounts, paymentReferences, feeAmounts]; };
the_stack
jest.mock('fs'); import fs from 'fs'; import {ConfigError, loadConfigSync} from '../source'; describe('loadConfig', () => { it('can load empty configurations.', () => { const config = loadConfigSync({}); expect(config).toEqual({}); }); describe('invariants', () => { it('throws if a property config of "configMap" has neither "filePath" nor "variableName".', () => { // @ts-expect-error expect(() => loadConfigSync({property: {}})).toThrow( '"configMap.property" must be a string, EnvironmentConfig object, or FileConfig object. Neither "filePath" nor "variableName" are defined.', ); }); it('throws if a property config of "configMap" has both "filePath" and "variableName".', () => { expect(() => loadConfigSync({ property: { filePath: './path/file.extension', variableName: 'VARIABLE_NAME', }, }), ).toThrow( 'Cannot determine whether "configMap.property" is an EnvironmentConfig object or a FileConfig object. Both "filePath" and "variableName" are defined.', ); }); }); describe('loading environment variables', () => { const variableName = 'VARIABLE_NAME'; describe('when the environment variable is present', () => { const variableValue = 'The value of this environment variable.'; beforeEach(() => { process.env[variableName] = variableValue; }); it('equals the environment variable.', () => { const config = loadConfigSync({ variableProperty: { variableName, }, }); expect(config.variableProperty).toEqual(variableValue); }); it('equals the environment variable (using shorthand syntax).', () => { const config = loadConfigSync({variableProperty: variableName}); expect(config.variableProperty).toEqual(variableValue); }); it('does not use the default value.', () => { const defaultValue = 'SOMETHING_ELSE'; const config = loadConfigSync({ variableProperty: { defaultValue, variableName, }, }); expect(config.variableProperty).not.toEqual(defaultValue); expect(config.variableProperty).toEqual(variableValue); }); it('is passed to the formatter.', () => { const formatter = jest.fn(); loadConfigSync({ variableProperty: { format: formatter, variableName, }, }); expect(formatter).toHaveBeenCalledWith(variableValue); }); }); describe('when the environment variable is not present', () => { beforeEach(() => { delete process.env[variableName]; }); describe('without a default value', () => { it('throws by default.', () => { try { loadConfigSync({ variableProperty: { variableName, }, }); } catch (error) { const {errors} = error as ConfigError<{variableProperty: Error}>; expect(errors.variableProperty.message).toEqual( 'VARIABLE_NAME is not defined.', ); } }); it('throws by default (using shorthand syntax).', () => { try { loadConfigSync({ variableProperty: variableName, }); } catch (error) { const {errors} = error as ConfigError<{variableProperty: Error}>; expect(errors.variableProperty.message).toEqual( 'VARIABLE_NAME is not defined.', ); } }); it('throws if explicitly required.', () => { try { loadConfigSync({ variableProperty: { required: true, variableName, }, }); } catch (error) { const {errors} = error as ConfigError<{variableProperty: Error}>; expect(errors.variableProperty.message).toEqual( 'VARIABLE_NAME is not defined.', ); } }); it('is undefined if not required.', () => { const config = loadConfigSync({ variableProperty: { required: false, variableName, }, }); expect(config.variableProperty).toBeUndefined(); }); it('is not passed to the formatter.', () => { const formatter = jest.fn(); loadConfigSync({ variableProperty: { format: formatter, required: false, variableName, }, }); expect(formatter).not.toHaveBeenCalled(); }); }); describe('with a default value', () => { const defaultValue = 'SOMETHING_ELSE'; it('equals the default value.', () => { const config = loadConfigSync({ variableProperty: { defaultValue, variableName, }, }); expect(config.variableProperty).toEqual(defaultValue); }); it('equals the default value if explicitly required.', () => { const config = loadConfigSync({ variableProperty: { defaultValue, required: true, variableName, }, }); expect(config.variableProperty).toEqual(defaultValue); }); it('equals the default value if not required.', () => { const config = loadConfigSync({ variableProperty: { defaultValue, required: false, variableName, }, }); expect(config.variableProperty).toEqual(defaultValue); }); it('is not passed the formatter.', () => { const formatter = jest.fn(); loadConfigSync({ variableProperty: { defaultValue, format: formatter, variableName, }, }); expect(formatter).not.toHaveBeenCalled(); }); }); }); }); describe('loading files', () => { const filePath = '/path/file.extension'; describe('when the file is present', () => { const fileContent = 'The content of this file.'; it('equals the file content decoded as UTF-8 if no encoding is defined.', () => { // @ts-expect-error-ignore fs._setFiles({[filePath]: Buffer.from(fileContent, 'utf8')}); const config = loadConfigSync({ fileProperty: { filePath, }, }); expect(config.fileProperty).toEqual(fileContent); }); it('equals the file content decoded using the given encoding, if defined.', () => { // @ts-expect-error-ignore fs._setFiles({[filePath]: Buffer.from(fileContent, 'ascii')}); const config = loadConfigSync({ fileProperty: { encoding: 'ascii', filePath, }, }); expect(config.fileProperty).toEqual(fileContent); }); it('does not use the default value.', () => { // @ts-expect-error-ignore fs._setFiles({[filePath]: Buffer.from(fileContent, 'utf8')}); const defaultValue = 'SOMETHING_ELSE'; const config = loadConfigSync({ variableProperty: { defaultValue, filePath, }, }); expect(config.variableProperty).not.toEqual(defaultValue); expect(config.variableProperty).toEqual(fileContent); }); it('is passed to the formatter.', () => { // @ts-expect-error-ignore fs._setFiles({[filePath]: Buffer.from(fileContent, 'utf8')}); const formatter = jest.fn(); loadConfigSync({ fileProperty: { filePath, format: formatter, }, }); expect(formatter).toHaveBeenCalledWith(fileContent); }); }); describe('when the file is not present', () => { beforeEach(() => { // @ts-expect-error-ignore fs._setFiles({}); }); describe('without a default value', () => { it('throws by default.', () => { try { loadConfigSync({ fileProperty: { filePath, }, }); } catch (error) { const {errors} = error as ConfigError<{fileProperty: Error}>; expect(errors.fileProperty.message).toEqual('File not found.'); } }); it('throws if explicitly required.', () => { try { loadConfigSync({ fileProperty: { filePath, required: true, }, }); } catch (error) { const {errors} = error as ConfigError<{fileProperty: Error}>; expect(errors.fileProperty.message).toEqual('File not found.'); } }); it('is undefined if not required.', () => { const config = loadConfigSync({ fileProperty: { filePath, required: false, }, }); expect(config.fileProperty).toBeUndefined(); }); it('is not passed to the formatter.', () => { const formatter = jest.fn(); loadConfigSync({ fileProperty: { filePath, required: false, }, }); expect(formatter).not.toHaveBeenCalled(); }); }); describe('with a default value', () => { const defaultValue = 'SOMETHING_ELSE'; it('equals the default value.', () => { const config = loadConfigSync({ fileProperty: { defaultValue, filePath, }, }); expect(config.fileProperty).toEqual(defaultValue); }); it('equals the default value if explicitly required.', () => { const config = loadConfigSync({ fileProperty: { defaultValue, filePath, required: true, }, }); expect(config.fileProperty).toEqual(defaultValue); }); it('equals the default value if not required.', () => { const config = loadConfigSync({ fileProperty: { defaultValue, filePath, required: false, }, }); expect(config.fileProperty).toEqual(defaultValue); }); it('is not passed the formatter.', () => { const formatter = jest.fn(); loadConfigSync({ variableProperty: { defaultValue, format: formatter, filePath, }, }); expect(formatter).not.toHaveBeenCalled(); }); }); }); }); describe('formatting properties', () => { const fileContent = 'The content of this file.'; const filePath = '/path/file.extension'; const variableName = 'VARIABLE_NAME'; const variableValue = 'The value of this environment variable.'; beforeEach(() => { process.env[variableName] = variableValue; // @ts-expect-error-ignore fs._setFiles({[filePath]: Buffer.from(fileContent, 'utf8')}); }); it('returns the formatted value.', () => { // eslint-disable-next-line unicorn/consistent-function-scoping const formatter = (value: string): number => value.length; const config = loadConfigSync({ fileProperty: { filePath, format: formatter, }, variableProperty: { format: formatter, variableName, }, }); expect(config.fileProperty).toEqual(formatter(fileContent)); expect(config.variableProperty).toEqual(formatter(variableValue)); }); it('returns the formatted value if explicitly required.', () => { // eslint-disable-next-line unicorn/consistent-function-scoping const formatter = (value: string): number => value.length; const config = loadConfigSync({ fileProperty: { filePath, format: formatter, required: true, }, variableProperty: { format: formatter, required: true, variableName, }, }); expect(config.fileProperty).toEqual(formatter(fileContent)); expect(config.variableProperty).toEqual(formatter(variableValue)); }); it('returns the formatted value if not required.', () => { // eslint-disable-next-line unicorn/consistent-function-scoping const formatter = (value: string): number => value.length; const config = loadConfigSync({ fileProperty: { filePath, format: formatter, required: false, }, variableProperty: { format: formatter, required: false, variableName, }, }); expect(config.fileProperty).toEqual(formatter(fileContent)); expect(config.variableProperty).toEqual(formatter(variableValue)); }); it('throws if the formatter throws.', () => { // eslint-disable-next-line unicorn/consistent-function-scoping const formatter = (value: string): number => { const integer = Number.parseInt(value, 10); if (Number.isNaN(integer)) { throw new TypeError('Not a number.'); } return integer; }; try { loadConfigSync({ fileProperty: { filePath, format: formatter, }, variableProperty: { format: formatter, variableName, }, }); } catch (error) { const {errors} = error as ConfigError<{ fileProperty: Error; variableProperty: Error; }>; expect(errors.fileProperty.message).toEqual('Not a number.'); expect(errors.variableProperty.message).toEqual('Not a number.'); } }); }); describe('loading errors', () => { const filePath = '/path/file.extension'; const variableName = 'VARIABLE_NAME'; beforeEach(() => { delete process.env[variableName]; // @ts-expect-error-ignore fs._setFiles({}); }); it('stringifies to include all messages.', () => { try { loadConfigSync({ fileProperty: { filePath, }, variableProperty: { variableName, }, }); } catch (error) { const errorMessage = JSON.stringify(error); expect(errorMessage).toMatch('File not found.'); expect(errorMessage).toMatch('VARIABLE_NAME is not defined.'); } }); it('includes unloaded properties in the message.', () => { try { loadConfigSync({ fileProperty: { filePath, }, variableProperty: { variableName, }, }); } catch (error) { expect(error.message).toMatch('fileProperty: File not found.'); expect(error.message).toMatch( 'variableProperty: VARIABLE_NAME is not defined.', ); } }); }); });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormWorkflow_Information { interface tab_notes_Sections { notes: DevKit.Controls.Section; } interface tab_notes extends DevKit.Controls.ITab { Section: tab_notes_Sections; } interface Tabs { notes: tab_notes; } interface Body { Tab: Tabs; /** Description of the process. */ Description: DevKit.Controls.String; /** Name of the process. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Unique identifier of the user or team who owns the process. */ OwnerId: DevKit.Controls.Lookup; } } class FormWorkflow_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Workflow_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Workflow_Information */ Body: DevKit.FormWorkflow_Information.Body; } class WorkflowApi { /** * DynamicsCrm.DevKit WorkflowApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the latest activation record for the process. */ ActiveWorkflowId: DevKit.WebApi.LookupValueReadonly; /** Indicates whether the asynchronous system job is automatically deleted on completion. */ AsyncAutoDelete: DevKit.WebApi.BooleanValue; /** Business Process Type. */ BusinessProcessType: DevKit.WebApi.OptionSetValue; /** Category of the process. */ Category: DevKit.WebApi.OptionSetValue; /** Business logic converted into client data */ ClientData: DevKit.WebApi.StringValue; /** For internal use only. */ ComponentState: DevKit.WebApi.OptionSetValueReadonly; /** Unique identifier of the user who created the process. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the process was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the process. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Stage of the process when triggered on Create. */ CreateStage: DevKit.WebApi.OptionSetValue; /** Stage of the process when triggered on Delete. */ DeleteStage: DevKit.WebApi.OptionSetValue; /** Description of the process. */ Description: DevKit.WebApi.StringValue; /** Shows the default image for the record. */ EntityImage: DevKit.WebApi.StringValue; EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly; EntityImage_URL: DevKit.WebApi.StringValueReadonly; /** For internal use only. */ EntityImageId: DevKit.WebApi.GuidValueReadonly; /** Unique identifier of the associated form. */ FormId: DevKit.WebApi.GuidValue; /** Input parameters to the process. */ InputParameters: DevKit.WebApi.StringValue; /** Version in which the form is introduced. */ IntroducedVersion: DevKit.WebApi.StringValue; /** Indicates whether the process was created using the Microsoft Dynamics 365 Web application. */ IsCrmUIWorkflow: DevKit.WebApi.BooleanValueReadonly; /** Information that specifies whether this component can be customized. */ IsCustomizable: DevKit.WebApi.ManagedPropertyValue; /** Defines whether other publishers can attach custom processing steps to this action */ IsCustomProcessingStepAllowedForOtherPublishers: DevKit.WebApi.ManagedPropertyValue; /** Indicates whether the solution component is part of a managed solution. */ IsManaged: DevKit.WebApi.BooleanValueReadonly; /** Whether or not the steps in the process are executed in a single transaction. */ IsTransacted: DevKit.WebApi.BooleanValue; /** Language of the process. */ LanguageCode: DevKit.WebApi.IntegerValue; /** Shows the mode of the process. */ Mode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the user who last modified the process. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the process was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the process. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Name of the process. */ Name: DevKit.WebApi.StringValue; /** Indicates whether the process is able to run as an on-demand process. */ OnDemand: DevKit.WebApi.BooleanValue; /** For internal use only. */ OverwriteTime_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier of the business unit that owns the process. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team who owns the process. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the process. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the definition for process activation. */ ParentWorkflowId: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the plug-in type. */ PluginTypeId: DevKit.WebApi.LookupValueReadonly; /** Type the business process flow order. */ ProcessOrder: DevKit.WebApi.IntegerValue; /** Contains the role assignment for the process. */ ProcessRoleAssignment: DevKit.WebApi.StringValue; /** Unique identifier of the associated form for process trigger. */ ProcessTriggerFormId: DevKit.WebApi.GuidValue; /** Scope of the process trigger. */ ProcessTriggerScope: DevKit.WebApi.OptionSetValue; /** Indicates the rank for order of execution for the synchronous workflow. */ Rank: DevKit.WebApi.IntegerValue; /** Specifies the system user account under which a workflow executes. */ RunAs: DevKit.WebApi.OptionSetValue; /** Scope of the process. */ Scope: DevKit.WebApi.OptionSetValue; /** Unique identifier of the SDK Message associated with this workflow. */ SdkMessageId: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the associated solution. */ SolutionId: DevKit.WebApi.GuidValueReadonly; /** Status of the process. */ StateCode: DevKit.WebApi.OptionSetValue; /** Additional information about status of the process. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Indicates whether the process can be included in other processes as a child process. */ Subprocess: DevKit.WebApi.BooleanValue; /** For internal use only. */ SupportingSolutionId: DevKit.WebApi.GuidValueReadonly; /** Select whether synchronous workflow failures will be saved to log files. */ SyncWorkflowLogOnFailure: DevKit.WebApi.BooleanValue; /** Indicates whether the process will be triggered when the primary entity is created. */ TriggerOnCreate: DevKit.WebApi.BooleanValue; /** Indicates whether the process will be triggered on deletion of the primary entity. */ TriggerOnDelete: DevKit.WebApi.BooleanValue; /** Attributes that trigger the process when updated. */ TriggerOnUpdateAttributeList: DevKit.WebApi.StringValue; /** Type of the process. */ Type: DevKit.WebApi.OptionSetValue; /** For internal use only. */ UIData: DevKit.WebApi.StringValueReadonly; /** Type of the UI Flow process. */ UIFlowType: DevKit.WebApi.OptionSetValue; /** Unique name of the process */ UniqueName: DevKit.WebApi.StringValue; /** Select the stage a process will be triggered on update. */ UpdateStage: DevKit.WebApi.OptionSetValue; VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** Unique identifier of the process. */ WorkflowId: DevKit.WebApi.GuidValue; /** For internal use only. */ WorkflowIdUnique: DevKit.WebApi.GuidValueReadonly; /** XAML that defines the process. */ Xaml: DevKit.WebApi.StringValue; } } declare namespace OptionSet { namespace Workflow { enum BusinessProcessType { /** 0 */ Business_Flow, /** 1 */ Task_Flow } enum Category { /** 3 */ Action, /** 4 */ Business_Process_Flow, /** 2 */ Business_Rule, /** 6 */ Desktop_Flow, /** 1 */ Dialog, /** 5 */ Modern_Flow, /** 0 */ Workflow } enum ComponentState { /** 2 */ Deleted, /** 3 */ Deleted_Unpublished, /** 0 */ Published, /** 1 */ Unpublished } enum CreateStage { /** 40 */ Post_operation, /** 20 */ Pre_operation } enum DeleteStage { /** 40 */ Post_operation, /** 20 */ Pre_operation } enum Mode { /** 0 */ Background, /** 1 */ Real_time } enum ProcessTriggerScope { /** 2 */ Entity, /** 1 */ Form } enum RunAs { /** 1 */ Calling_User, /** 0 */ Owner } enum Scope { /** 2 */ Business_Unit, /** 4 */ Organization, /** 3 */ Parent_Child_Business_Units, /** 1 */ User } enum StateCode { /** 1 */ Activated, /** 0 */ Draft } enum StatusCode { /** 2 */ Activated, /** 1 */ Draft } enum Type { /** 2 */ Activation, /** 1 */ Definition, /** 3 */ Template } enum UIFlowType { /** 2 */ Power_Automate_Desktop, /** 101 */ Recording, /** 1 */ Selenium_IDE, /** 0 */ Windows_recorder_V1 } enum UpdateStage { /** 40 */ Post_operation, /** 20 */ Pre_operation } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import * as R from 'ramda'; import {X86_REGISTERS} from './constants/x86'; import {X86Unit} from './X86Unit'; import {X86CPU, X86RegRMCallback, X86MemRMCallback} from './X86CPU'; import {X86ALUOperator} from './X86ALU'; import {VGARenderLoopDriver} from './devices/Video/HTML/VGARenderLoopDriver'; import { X86BitsMode, X86Flags, RMByte, X86AbstractCPU, X86Interrupt, X86InterruptType, } from './types'; type X86FlagCondition = (flags: X86Flags) => boolean|number; type SwitchOpcodeOperator = (num: number, mode: X86BitsMode, byte: RMByte, register: boolean) => any; type SwitchOpcodeOperators = {[offset: number]: SwitchOpcodeOperator} & { default?: SwitchOpcodeOperator, nonRMMatch?(byte: number): number, }; /** * Basic CPU instruction set without ALU/IO instructions * * @export * @class X86InstructionSet * @extends {X86Unit} */ export class X86InstructionSet extends X86Unit { /* eslint-disable class-methods-use-this */ /** * Initialize CPU IO ports handlers opcodes * * @protected * @param {X86CPU} cpu * @memberof X86IO */ protected init(cpu: X86CPU): void { X86InstructionSet.initBaseOpcodes(cpu); X86InstructionSet.initBranchOpcodes(cpu); } /* eslint-enable class-methods-use-this */ /** * Switches instruction by RM reg byte * * @see * If provided mode is null it will: * - provide address in memCallback * - provide register as null in regCallback * * @static * @param {X86CPU} cpu * @param {X86BitsMode} defaultMode * @param {SwitchOpcodeOperators} operators * @returns * @memberof X86InstructionSet */ static switchRMOpcodeInstruction(cpu: X86CPU, defaultMode: X86BitsMode, operators: SwitchOpcodeOperators) { const {memIO, registers} = cpu; const operatorExecutor: SwitchOpcodeOperator = (val, mode, byte, register) => { const operator = operators[byte.reg] || operators.default; if (operator) return operator(val, mode, byte, register); throw new Error(`Unsupported operator! ${byte.reg}`); }; const regCallback: X86RegRMCallback = (reg: string, _, byte, mode) => { const result = operatorExecutor( reg === null ? null : registers[reg], mode, byte, true, ); if (result !== undefined) registers[reg] = result; }; const memCallback: X86MemRMCallback = (address, _, byte, mode) => { // read only address if (mode === null) { operatorExecutor(address, null, byte, false); return; } const result = operatorExecutor( memIO.read[mode](address), mode, byte, false, ); if (result !== undefined) memIO.write[mode](result, address); }; const {nonRMMatch} = operators; return (mode?: X86BitsMode) => { if (nonRMMatch) { const byte = cpu.fetchOpcode(0x1, false, true); const matchBytes = nonRMMatch(byte); if (matchBytes !== 0) { cpu.incrementIP(matchBytes); return true; } } return cpu.parseRmByte( regCallback, memCallback, mode || defaultMode, ); }; } /** * Adds non-branch base cpu instructions * * @static * @param {X86CPU} cpu * @memberof X86InstructionSet */ static initBaseOpcodes(cpu: X86CPU): void { const {alu, stack, memIO, registers, opcodes} = cpu; Object.assign(opcodes, { /** MOV r/m8, reg8 */ 0x88: (bits: X86BitsMode = 0x1) => { cpu.parseRmByte( (reg: string, modeReg) => { registers[reg] = registers[X86_REGISTERS[bits][modeReg]]; }, (address, src: string) => { memIO.write[bits](registers[src], address); }, bits, ); }, /** MOV r/m16, sreg */ 0x8C: () => { cpu.parseRmByte( (reg: string, modeReg) => { registers[reg] = registers[X86_REGISTERS.sreg[modeReg]]; }, (address, _, byte) => { memIO.write[0x2](registers[<string> X86_REGISTERS.sreg[byte.reg]], address); }, 0x2, ); }, /** MOV sreg, r/m16 */ 0x8E: () => { cpu.parseRmByte( (reg, modeReg) => { registers[<string> X86_REGISTERS.sreg[modeReg]] = registers[reg]; }, (address, _, byte) => { registers[<string> X86_REGISTERS.sreg[byte.reg]] = memIO.read[0x2](address); }, 0x2, ); }, /** MOV r8, r/m8 */ 0x8A: (bits: X86BitsMode = 0x1) => { cpu.parseRmByte( (reg, modeReg) => { registers[<string> X86_REGISTERS[bits][modeReg]] = registers[reg]; }, (address, reg: string) => { registers[reg] = memIO.read[bits](address); }, bits, ); }, /** MOV al, m16 */ 0xA0: (bits = 0x1) => { registers[X86_REGISTERS[bits][0]] = memIO.read[bits]( cpu.getMemAddress(cpu.segmentReg, cpu.fetchOpcode(0x2)), ); }, /** MOV ax, m16 */ 0xA1: () => cpu.opcodes[0xA0](0x2), /** MOV m8, al */ 0xA2: (bits = 0x1) => { memIO.write[bits]( registers[X86_REGISTERS[bits][0x0]], cpu.getMemAddress(cpu.segmentReg, cpu.fetchOpcode(0x2)), ); }, /** MOV m16, ax */ 0xA3: () => opcodes[0xA2](0x2), /** MOV r/m8, imm8 */ 0xC6: (bits: X86BitsMode = 0x1) => { cpu.parseRmByte( () => { /** todo */ throw new Error('0xC6: Fix me!'); }, (address) => { memIO.write[bits](cpu.fetchOpcode(bits), address); }, bits, ); }, /** MOV r/m16, reg16 */ 0x89: () => opcodes[0x88](0x2), /** MOV r16, r/m16 */ 0x8B: () => opcodes[0x8A](0x2), /** MOV r/m16, imm16 */ 0xC7: () => opcodes[0xC6](0x2), /** PUSH/INC/DEC reg8 */ 0xFE: (bits: X86BitsMode = 0x1) => { cpu.parseRmByte( (_, modeReg, mode) => { const reg: string = X86_REGISTERS[bits][mode.rm]; if (mode.reg === 0x6) stack.push(registers[reg]); else { registers[reg] = alu.exec( alu.operators.extra[mode.reg === 0x1 ? 'decrement' : 'increment'], registers[reg], null, bits, ); } }, (address, reg, mode) => { const memVal = memIO.read[bits](address); if (mode.reg === 0x6) stack.push(memVal); else { memIO.write[bits]( alu.exec( alu.operators.extra[mode.reg === 0x1 ? 'decrement' : 'increment'], memVal, null, bits, ), address, ); } }, bits, ); }, /** INC/DEC/CALL/CALLF/JMP/JMPF/PUSH */ 0xFF: () => { cpu.parseRmByte( (reg, modeReg) => { const regValue = <number> registers[reg]; switch (modeReg) { /** INC r16 */ case 0x0: registers[<string> reg] = alu.exec(alu.operators.extra.increment, regValue, null, 0x2); break; /** DEC r16 */ case 0x1: registers[<string> reg] = alu.exec(alu.operators.extra.decrement, regValue, null, 0x2); break; /** CALL r16 */ case 0x2: stack.push(registers.ip); registers.ip = regValue; break; /** JMP r16 */ case 0x4: registers.ip = regValue; break; /** PUSH r16 */ case 0x6: stack.push(regValue); break; default: throw new Error('Unimplemented 0xFF reg rm instruction!'); } }, (address, reg, byte) => { const memVal = cpu.memIO.read[0x2](address); // call 0x3 switch (byte.reg) { /** INC m16 */ case 0x0: memIO.write[0x2]( alu.exec(alu.operators.extra.increment, memVal, null, 0x2), address, ); break; /** DEC m16 */ case 0x1: memIO.write[0x2]( alu.exec(alu.operators.extra.decrement, memVal, null, 0x2), address, ); break; /** CALL m16 */ case 0x2: stack.push(registers.ip); registers.ip = memVal; break; /** CALL FAR */ case 0x3: stack .push(registers.cs) .push(registers.ip); cpu.absoluteJump( memVal, cpu.memIO.read[0x2](address + 0x2), ); break; /** JMP m16 */ case 0x4: registers.ip = memVal; break; /** JMP FAR */ case 0x5: cpu.absoluteJump( memVal, cpu.memIO.read[0x2](address + 0x2), ); break; /** PUSH m16 */ case 0x6: stack.push(memVal); break; default: throw new Error('Unimplemented 0xFF mem rm instruction!'); } }, 0x2, ); }, /** PUSHA */ 0x60: () => { const temp = registers.sp; for (let i = 0; i <= 0x7; ++i) { stack.push( i === 0x4 ? temp : registers[<string> X86_REGISTERS[0x2][i]], ); } }, /** POPA */ 0x61: () => { /** Skip SP */ for (let i = 0x7; i >= 0; --i) { const val = stack.pop(); if (i !== 0x4) registers[<string> X86_REGISTERS[0x2][i]] = val; } }, /** PUSH imm8 */ 0x6A: () => stack.push(cpu.fetchOpcode(), 0x2), /** PUSH imm16 */ 0x68: () => stack.push(cpu.fetchOpcode(0x2), 0x2), /** PUSHF */ 0x9C: () => stack.push(registers.flags), /** POPF */ 0x9D: () => { registers.flags = stack.pop(); }, /** LOOPNE */ 0xE0: () => { const relativeAddress = cpu.fetchOpcode(); if (--registers.cx && !registers.status.zf) cpu.relativeJump(0x1, relativeAddress); }, /** LOOP 8bit rel */ 0xE2: () => { const relativeAddress = cpu.fetchOpcode(); if (--registers.cx) cpu.relativeJump(0x1, relativeAddress); }, /** IRET 48b */ 0xCF: () => { Object.assign( registers, { ip: stack.pop(), cs: stack.pop(), flags: stack.pop(), }, ); }, /** RET far */ 0xCB: () => { registers.ip = stack.pop(); registers.cs = stack.pop(); }, /** RET near */ 0xC3: (bits: X86BitsMode = 0x2) => { registers.ip = stack.pop(bits); }, /** RET 16b */ 0xC2: (bits: X86BitsMode = 0x2) => { const items = cpu.fetchOpcode(bits, false); registers.ip = stack.pop(); stack.pop(items, false); }, /** CALL 16bit/32bit dis */ 0xE8: () => { stack.push( X86AbstractCPU.toUnsignedNumber(registers.ip + 0x2, 0x2), ); cpu.relativeJump(0x2); }, /** JMP rel 8bit */ 0xEB: () => cpu.relativeJump(0x1), /** JMP rel 16bit */ 0xE9: () => cpu.relativeJump(0x2), // todo: check me /** FAR JMP 32bit */ 0xEA: () => { cpu.absoluteJump( cpu.fetchOpcode(0x2), cpu.fetchOpcode(0x2), ); }, /** STOSB */ 0xAA: (bits: X86BitsMode = 0x1) => { memIO.write[bits]( registers[<string> X86_REGISTERS[bits][0]], cpu.getMemAddress('es', 'di'), ); cpu.dfIncrement(bits, 'di'); }, /** STOSW */ 0xAB: () => opcodes[0xAA](0x2), /* SCAS 8bit */ 0xAE: (bits: X86BitsMode = 0x1) => { alu.exec( alu.operators[X86ALUOperator.SUB], registers[<string> X86_REGISTERS[bits][0x0]], memIO.read[bits](cpu.getMemAddress('es', 'di')), bits, ); cpu.dfIncrement(bits, 'di'); }, /* SCAS 16bit */ 0xAF: () => opcodes[0xAE](0x2), /** CLI */ 0xFA: () => { registers.status.if = 0x0; }, /** STI */ 0xFB: () => { registers.status.if = 0x1; }, /** CLC */ 0xF8: () => { registers.status.cf = 0x0; }, /** STC */ 0xF9: () => { registers.status.cf = 0x1; }, /** CLD */ 0xFC: () => { registers.status.df = 0x0; }, /** STD */ 0xFD: () => { registers.status.df = 0x1; }, /** MOVSB */ 0xA4: (bits: X86BitsMode = 0x1) => { memIO.write[bits]( memIO.read[bits](cpu.getMemAddress(cpu.segmentReg, 'si')), cpu.getMemAddress('es', 'di'), ); /** Increment indexes */ cpu.dfIncrement(bits, 'si', 'di'); }, /** MOVSW */ 0xA5: () => opcodes[0xA4](0x2), /** LODSB */ 0xAC: (bits: X86BitsMode = 0x1) => { registers[<string> X86_REGISTERS[bits][0x0]] = memIO.read[bits]( cpu.getMemAddress(cpu.segmentReg, 'si'), ); cpu.dfIncrement(bits, 'si'); }, /** LODSW */ 0xAD: () => opcodes[0xAC](0x2), /** LDS r16, m16:16 */ 0xC5: (segment = 'ds') => { const {reg} = X86AbstractCPU.decodeRmByte(cpu.fetchOpcode()); const addr = X86AbstractCPU.getSegmentedAddress(cpu.fetchOpcode(0x2, false)); registers[<string> X86_REGISTERS[0x2][reg]] = addr.offset; registers[segment] = addr.segment; }, /** LES r16, m16:16 */ 0xC4: () => opcodes[0xC5]('es'), /** LEA r16, mem */ 0x8D: () => { cpu.parseRmByte( null, (address, reg: string) => { registers[reg] = address; }, 0x2, null, ); }, /** INT3 debug trap */ 0xCC: () => { cpu.interrupt( X86Interrupt.raise.debug(X86InterruptType.TRAP), ); }, /** INT imm8 */ 0xCD: () => { const code = cpu.fetchOpcode(); cpu.interrupt( X86Interrupt.raise.software(code), ); }, /** ROL/SHR/SHL */ 0xD0: X86InstructionSet.switchRMOpcodeInstruction(cpu, 0x1, { /** ROL */ 0x0: (val, bits) => cpu.rol(val, 0x1, bits), /** ROR */ 0x1: (val, bits) => cpu.rol(val, -0x1, bits), /** RCL */ 0x2: (val, bits) => cpu.rcl(val, 0x1, bits), /** RCR */ 0x3: (val, bits) => cpu.rcl(val, -0x1, bits), /** SHL */ 0x4: (val, bits) => cpu.shl(val, 0x1, bits), /** SHR */ 0x5: (val, bits) => cpu.shr(val, 0x1, bits), // /** SAL */ 0x6: (val, bits) => cpu.sal(val, 0x1, bits), // /** SAR */ 0x7: (val, bits) => cpu.sar(val, 0x1, bits), }), /** ROL/SHR/SHL r/m8, 1 */ 0xD1: X86InstructionSet.switchRMOpcodeInstruction(cpu, 0x2, { /** ROL */ 0x0: (val, bits) => cpu.rol(val, 0x1, bits), /** ROR */ 0x1: (val, bits) => cpu.rol(val, -0x1, bits), /** RCL */ 0x2: (val, bits) => cpu.rcl(val, 0x1, bits), /** RCR */ 0x3: (val, bits) => cpu.rcl(val, -0x1, bits), /** SHL */ 0x4: (val, bits) => cpu.shl(val, 0x1, bits), /** SHR */ 0x5: (val, bits) => cpu.shr(val, 0x1, bits), // /** SAL */ 0x6: (val, bits) => cpu.sal(val, 0x1, bits), // /** SAR */ 0x7: (val, bits) => cpu.sar(val, 0x1, bits), }), /** ROL/SHR/SHL r/m8, cl */ 0xD2: X86InstructionSet.switchRMOpcodeInstruction(cpu, 0x1, { /** ROL */ 0x0: (val, bits) => cpu.rol(val, registers.cl, bits), /** ROR */ 0x1: (val, bits) => cpu.rol(val, -registers.cl, bits), /** RCL */ 0x2: (val, bits) => cpu.rcl(val, registers.cl, bits), /** RCR */ 0x3: (val, bits) => cpu.rcl(val, -registers.cl, bits), /** SHL */ 0x4: (val, bits) => cpu.shl(val, registers.cl, bits), /** SHR */ 0x5: (val, bits) => cpu.shr(val, registers.cl, bits), // /** SAL */ 0x6: (val, bits) => cpu.sal(val, registers.cl, bits), // /** SAR */ 0x7: (val, bits) => cpu.sar(val, registers.cl, bits), }), /** ROL/SHR/SHL r/m8, cl */ 0xD3: X86InstructionSet.switchRMOpcodeInstruction(cpu, 0x2, { /** ROL */ 0x0: (val, bits) => cpu.rol(val, registers.cl, bits), /** ROR */ 0x1: (val, bits) => cpu.rol(val, -registers.cl, bits), /** RCL */ 0x2: (val, bits) => cpu.rcl(val, registers.cl, bits), /** RCR */ 0x3: (val, bits) => cpu.rcl(val, -registers.cl, bits), /** SHL */ 0x4: (val, bits) => cpu.shl(val, registers.cl, bits), /** SHR */ 0x5: (val, bits) => cpu.shr(val, registers.cl, bits), // /** SAL */ 0x6: (val, bits) => cpu.sal(val, registers.cl, bits), // /** SAR */ 0x7: (val, bits) => cpu.sar(val, registers.cl, bits), }), /** ROL/SHR/SHL r/m8 */ 0xC0: X86InstructionSet.switchRMOpcodeInstruction(cpu, 0x1, { /** ROL */ 0x0: (val, bits) => cpu.rol(val, cpu.fetchOpcode(), bits), /** ROR */ 0x1: (val, bits) => cpu.rol(val, -cpu.fetchOpcode(), bits), /** RCL */ 0x2: (val, bits) => cpu.rcl(val, cpu.fetchOpcode(), bits), /** RCR */ 0x3: (val, bits) => cpu.rcl(val, -cpu.fetchOpcode(), bits), /** SHL IMM8 */ 0x4: (val, bits) => cpu.shl(val, cpu.fetchOpcode(), bits), /** SHR IMM8 */ 0x5: (val, bits) => cpu.shr(val, cpu.fetchOpcode(), bits), // /** SAL */ 0x6: (val, bits) => cpu.sal(val, cpu.fetchOpcode(), bits), // /** SAR */ 0x7: (val, bits) => cpu.sar(val, cpu.fetchOpcode(), bits), }), /** ROL/SHR/SHL r/m16 */ 0xC1: X86InstructionSet.switchRMOpcodeInstruction(cpu, 0x2, { /** ROL */ 0x0: (val, bits) => cpu.rol(val, cpu.fetchOpcode(), bits), /** ROR */ 0x1: (val, bits) => cpu.rol(val, -cpu.fetchOpcode(), bits), /** RCL */ 0x2: (val, bits) => cpu.rcl(val, cpu.fetchOpcode(), bits), /** RCR */ 0x3: (val, bits) => cpu.rcl(val, -cpu.fetchOpcode(), bits), /** SHL IMM8 */ 0x4: (val, bits) => cpu.shl(val, cpu.fetchOpcode(), bits), /** SHR IMM8 */ 0x5: (val, bits) => cpu.shr(val, cpu.fetchOpcode(), bits), // /** SAL */ 0x6: (val, bits) => cpu.sal(val, cpu.fetchOpcode(), 0x2), // /** SAR */ 0x7: (val, bits) => cpu.sar(val, cpu.fetchOpcode(), 0x2), }), /** CBW */ 0x98: () => { registers.ah = (registers.al & 0x80) === 0x80 ? 0xFF : 0x0; }, /** CWD */ 0x99: () => { registers.dx = (registers.ax & 0x8000) === 0x8000 ? 0xFFFF : 0x0; }, /** SALC */ 0xD6: () => { registers.al = registers.status.cf ? 0xFF : 0x0; }, /** XLAT */ 0xD7: () => { registers.al = memIO.read[0x1]( (registers[<string> cpu.segmentReg] << 4) + X86AbstractCPU.toUnsignedNumber(registers.bx + registers.al, 0x2), ); }, /** XCHG bx, bx */ 0x87: () => { const arg = cpu.fetchOpcode(0x1, false, true); switch (arg) { case 0xDB: // xchg bx, bx case 0xD2: // xchg dx, dx cpu.incrementIP(0x1); cpu.debugDumpRegisters(); if (arg === 0xDB) { // xchg bx, bx const loop = (<VGARenderLoopDriver> cpu.devices.vgaRenderLoop); if (loop) loop.redraw(); debugger; // eslint-disable-line no-debugger } break; default: cpu.parseRmByte( (reg, reg2) => { [ registers[<string> X86_REGISTERS[0x2][reg2]], registers[<string> reg], ] = [ registers[reg], registers[X86_REGISTERS[0x2][reg2]], ]; }, () => { throw new Error('todo: xchg in mem address'); }, 0x2, ); } }, /** HLT */ 0xF4: cpu.halt.bind(cpu), /** ICE BreakPoint */ 0xF1: () => {}, /** NOP */ 0x90: () => {}, }); /** General usage registers opcodes */ for (let opcode = 0; opcode < Object.keys(X86_REGISTERS[0x1]).length; ++opcode) { /** MOV register opcodes */ ((_opcode) => { const _r8: string = X86_REGISTERS[0x1][_opcode]; const _r16: string = X86_REGISTERS[0x2][_opcode]; /** XCHG AX, r16 */ opcodes[0x90 + _opcode] = () => { const dest = X86_REGISTERS[0x2][_opcode], temp = <number> cpu.registers[dest]; registers[<string> dest] = registers.ax; registers.ax = temp; }; /** MOV reg8, imm8 $B0 + reg8 code */ opcodes[0xB0 + _opcode] = () => { registers[_r8] = cpu.fetchOpcode(); }; /** MOV reg16, imm16 $B8 + reg16 code */ opcodes[0xB8 + _opcode] = () => { registers[_r16] = cpu.fetchOpcode(0x2); }; /** INC reg16 */ opcodes[0x40 + _opcode] = () => { registers[_r16] = alu.exec(alu.operators.extra.increment, registers[_r16], null, 0x2); }; /** DEC reg16 */ opcodes[0x48 + _opcode] = () => { registers[_r16] = alu.exec(alu.operators.extra.decrement, registers[_r16], null, 0x2); }; /** PUSH reg16 */ opcodes[0x50 + _opcode] = () => stack.push(registers[_r16]); /** POP reg16 */ opcodes[0x58 + _opcode] = () => { registers[_r16] = stack.pop(); }; })(opcode); } } /** * Inits opcodes that are related to jumps * * @static * @param {X86CPU} cpu * @memberof X86InstructionSet */ static initBranchOpcodes(cpu: X86CPU): void { const {registers, opcodes} = cpu; const jmpOpcodes: {[offset: number]: X86FlagCondition} = { /** JO */ 0x70: (f) => f.of, /** JNO */ 0x71: (f) => !f.of, /** JB */ 0x72: (f) => f.cf, /** JAE */ 0x73: (f) => !f.cf, /** JZ */ 0x74: (f) => f.zf, /** JNE */ 0x75: (f) => !f.zf, /** JBE */ 0x76: (f) => f.cf || f.zf, /** JA */ 0x77: (f) => !f.cf && !f.zf, /** JS */ 0x78: (f) => f.sf, /** JNS */ 0x79: (f) => !f.sf, /** JP */ 0x7A: (f) => f.pf, /** JNP */ 0x7B: (f) => !f.pf, /** JG */ 0x7F: (f) => !f.zf && f.sf === f.of, /** JGE */ 0x7D: (f) => f.sf === f.of, /** JL */ 0x7C: (f) => f.sf !== f.of, /** JLE */ 0x7E: (f) => f.zf || f.sf !== f.of, }; const jumpIf = (flagCondition: X86FlagCondition, bits: X86BitsMode = 0x1) => { const relative = cpu.fetchOpcode(bits); if (flagCondition(registers.status)) cpu.relativeJump(bits, relative); }; R.forEachObjIndexed( (jmpFn, opcode) => { opcodes[opcode] = () => jumpIf(jmpFn); opcodes[(0x0F << 0x8) | (+opcode + 0x10)] = () => jumpIf(jmpFn, 0x2); }, jmpOpcodes, ); } }
the_stack
import {UserBase} from '../database-models/user-base'; import {ActingUserBase} from '../database-models/acting-user-base'; import {BidResultTypeMaskBase} from '../database-models/bid-result-type-mask-base'; import {BrandBase} from '../database-models/brand-base'; import {CompanyBase} from '../database-models/company-base'; import {CurrencyFormatMaskBase} from '../database-models/currency-format-mask-base'; import {CurrencyBase} from '../database-models/currency-base'; import {DateFormatMaskBase} from '../database-models/date-format-mask-base'; import {DepartmentBase} from '../database-models/department-base'; import {JobGroupBase} from '../database-models/job-group-base'; import {LanguageBase} from '../database-models/language-base'; import {MemberStatuBase} from '../database-models/member-statu-base'; import {MemberTypeNameNavigationBase} from '../database-models/member-type-name-navigation-base'; import {ParentidNavigationBase} from '../database-models/parentid-navigation-base'; import {ReportAccessBase} from '../database-models/report-access-base'; import {TerritoryBase} from '../database-models/territory-base'; import {TimezoneBase} from '../database-models/timezone-base'; import {VendorBackgroundBase} from '../database-models/vendor-background-base'; import {FileDownloadAuditBase} from '../database-models/file-download-audit-base'; import {FileDownloadAuditsDownloadUserBase} from '../database-models/file-download-audits-download-user-base'; import {ServiceFeeInvoiceBase} from '../database-models/service-fee-invoice-base'; import {ServiceFeeInvoicesUpdatedByNavigationBase} from '../database-models/service-fee-invoices-updated-by-navigation-base'; import {TopicBase} from '../database-models/topic-base'; import {TopicsCreateUserBase} from '../database-models/topics-create-user-base'; import {ContractBase} from '../database-models/contract-base'; import {ServiceFeeBatchBase} from '../database-models/service-fee-batch-base'; import {ServiceFeeBatchesProcessedByUserBase} from '../database-models/service-fee-batches-processed-by-user-base'; import {EmailRegistrationBase} from '../database-models/email-registration-base'; import {LogicalFileBase} from '../database-models/logical-file-base'; import {ServiceFeeBase} from '../database-models/service-fee-base'; import {ServiceFeesCompletedByUserBase} from '../database-models/service-fees-completed-by-user-base'; import {ServiceFeesCreatedByLoginBase} from '../database-models/service-fees-created-by-login-base'; import {ServiceFeesCreatedByUserBase} from '../database-models/service-fees-created-by-user-base'; import {NoteDeliveryBase} from '../database-models/note-delivery-base'; import {EstimateTermAcceptanceBase} from '../database-models/estimate-term-acceptance-base'; import {EstimateTermAcceptancesAcceptUserBase} from '../database-models/estimate-term-acceptances-accept-user-base'; import {ResourceAcquiredJobBase} from '../database-models/resource-acquired-job-base'; import {ResourceAcquiredJobsResourceUserBase} from '../database-models/resource-acquired-jobs-resource-user-base'; import {SupportLogBase} from '../database-models/support-log-base'; import {SupportLogsUserBase} from '../database-models/support-logs-user-base'; import {DataItemBase} from '../database-models/data-item-base'; import {BidSessionBidderBase} from '../database-models/bid-session-bidder-base'; import {EventLogBase} from '../database-models/event-log-base'; import {EventLogsEventUserBase} from '../database-models/event-logs-event-user-base'; import {EventLogsTargetUserBase} from '../database-models/event-logs-target-user-base'; import {ProjectBase} from '../database-models/project-base'; import {JobTeamBase} from '../database-models/job-team-base'; import {ResourceGroupMemberBase} from '../database-models/resource-group-member-base'; import {ResourceGroupMembersResourceUserBase} from '../database-models/resource-group-members-resource-user-base'; import {VendorPoolBase} from '../database-models/vendor-pool-base'; import {ProjectTaskBase} from '../database-models/project-task-base'; import {VendorAssignedTeamMemberBase} from '../database-models/vendor-assigned-team-member-base'; import {VendorBase} from '../database-models/vendor-base'; import {VendorsVendorNavigationBase} from '../database-models/vendors-vendor-navigation-base'; import {UserAbilityOptionBase} from '../database-models/user-ability-option-base'; import {JobBase} from '../database-models/job-base'; import {JobsBuyerDepartmentBase} from '../database-models/jobs-buyer-department-base'; import {JobsBuyerUserBase} from '../database-models/jobs-buyer-user-base'; import {JobsOriginatingDepartmentBase} from '../database-models/jobs-originating-department-base'; import {JobsVendorCompanyBase} from '../database-models/jobs-vendor-company-base'; import {JobsVendorDepartmentBase} from '../database-models/jobs-vendor-department-base'; import {JobsVendorUserBase} from '../database-models/jobs-vendor-user-base'; import {UserRightOptionBase} from '../database-models/user-right-option-base'; import {BulkNotifyBase} from '../database-models/bulk-notify-base'; import {BulkNotifyCreationUserBase} from '../database-models/bulk-notify-creation-user-base'; import {TermSetBase} from '../database-models/term-set-base'; import {VendorTeamMemberBase} from '../database-models/vendor-team-member-base'; import {LogicalFileInstanceBase} from '../database-models/logical-file-instance-base'; import {LogicalFileInstancesActionUserBase} from '../database-models/logical-file-instances-action-user-base'; import {BuyerFeatureMappingBase} from '../database-models/buyer-feature-mapping-base'; import {VendorTermAcceptanceBase} from '../database-models/vendor-term-acceptance-base'; import {VendorTermAcceptancesAcceptUserBase} from '../database-models/vendor-term-acceptances-accept-user-base'; import {SampleEvaluationBase} from '../database-models/sample-evaluation-base'; import {SampleEvaluationsEvaluationLoginBase} from '../database-models/sample-evaluations-evaluation-login-base'; import {SampleEvaluationsEvaluationUserBase} from '../database-models/sample-evaluations-evaluation-user-base'; import {MailRecipientBase} from '../database-models/mail-recipient-base'; import {MessageBase} from '../database-models/message-base'; import {MessagesAuthorUserBase} from '../database-models/messages-author-user-base'; import {PaymentTransferLogBase} from '../database-models/payment-transfer-log-base'; import {MessageRecipientBase} from '../database-models/message-recipient-base'; import {MessageRecipientsRecipientUserBase} from '../database-models/message-recipients-recipient-user-base'; import {ReconcileLogBase} from '../database-models/reconcile-log-base'; import {ReconcileLogsReconcileUserBase} from '../database-models/reconcile-logs-reconcile-user-base'; import {ShipmentBase} from '../database-models/shipment-base'; import {ShipmentsShipperUserBase} from '../database-models/shipments-shipper-user-base'; import {SpecDestinationDetailBase} from '../database-models/spec-destination-detail-base'; import {SpecDestinationDetailsDefaultReceiveUserBase} from '../database-models/spec-destination-details-default-receive-user-base'; import {VendorPoolSubscriptionBase} from '../database-models/vendor-pool-subscription-base'; import {ComponentCustomFieldBase} from '../database-models/component-custom-field-base'; import {AddressBase} from '../database-models/address-base'; import {JobDeleteReasonBase} from '../database-models/job-delete-reason-base'; import {SetupRequestBase} from '../database-models/setup-request-base'; import {SetupRequestsCloneCompBase} from '../database-models/setup-requests-clone-comp-base'; import {SetupRequestsProductAgentBase} from '../database-models/setup-requests-product-agent-base'; import {SetupRequestsProviderDeptBase} from '../database-models/setup-requests-provider-dept-base'; import {SetupRequestsRequestedByDeptBase} from '../database-models/setup-requests-requested-by-dept-base'; import {SetupRequestsRequestedByUserBase} from '../database-models/setup-requests-requested-by-user-base'; import {SetupRequestsRequestedUserBase} from '../database-models/setup-requests-requested-user-base'; import {PhoneBase} from '../database-models/phone-base'; import {UserDataItemBase} from '../database-models/user-data-item-base'; import {ReceiveLogBase} from '../database-models/receive-log-base'; import {ReceiveLogsReceiveUserBase} from '../database-models/receive-logs-receive-user-base'; import {ComponentEvaluationBase} from '../database-models/component-evaluation-base'; import {ComponentEvaluationsEvaluationLoginBase} from '../database-models/component-evaluations-evaluation-login-base'; import {ComponentEvaluationsEvaluationUserBase} from '../database-models/component-evaluations-evaluation-user-base'; import {CustomTextMemberBase} from '../database-models/custom-text-member-base'; import {MailBase} from '../database-models/mail-base'; import {SetupMemberSequenceBase} from '../database-models/setup-member-sequence-base'; import {SetupMemberSequencesSecondaryBase} from '../database-models/setup-member-sequences-secondary-base'; import {ChangeOrderBase} from '../database-models/change-order-base'; import {JobUnInvitedBidderBase} from '../database-models/job-un-invited-bidder-base'; import {NonDisclosureAgreementEstimateAcceptBase} from '../database-models/non-disclosure-agreement-estimate-accept-base'; import {VendorQualifierBase} from '../database-models/vendor-qualifier-base'; import {ApproveLogBase} from '../database-models/approve-log-base'; import {ApproveLogsApproveUserBase} from '../database-models/approve-logs-approve-user-base'; import {BidSessionNonDisclosureAgreementBase} from '../database-models/bid-session-non-disclosure-agreement-base'; import {BidSessionNonDisclosureAgreementUserBase} from '../database-models/bid-session-non-disclosure-agreement-user-base'; import {MemberPortfolioBase} from '../database-models/member-portfolio-base'; import {AdvertisingSpecialtyInstituteMemberBase} from '../database-models/advertising-specialty-institute-member-base'; import {DirectJobLoginBase} from '../database-models/direct-job-login-base'; import {DirectJobLoginsUserBase} from '../database-models/direct-job-logins-user-base'; import {FinancialXferPreferenceBase} from '../database-models/financial-xfer-preference-base'; import {DepartmentServiceBase} from '../database-models/department-service-base'; import {DepartmentServicesProviderAgentBase} from '../database-models/department-services-provider-agent-base'; import {DepartmentServicesProviderDepartmentBase} from '../database-models/department-services-provider-department-base'; import {DirectLoginBase} from '../database-models/direct-login-base'; import {DirectLoginsLoginUserBase} from '../database-models/direct-logins-login-user-base'; import {DirectLoginsUserBase} from '../database-models/direct-logins-user-base'; import {BidSessionPriceBase} from '../database-models/bid-session-price-base'; import {BidSessionPricesBidderUserBase} from '../database-models/bid-session-prices-bidder-user-base'; import {JobStepBase} from '../database-models/job-step-base'; import {JobStepsClosedUserBase} from '../database-models/job-steps-closed-user-base'; import {JobStepsProviderUserBase} from '../database-models/job-steps-provider-user-base'; import {BidTermAcceptanceBase} from '../database-models/bid-term-acceptance-base'; import {BidTermAcceptancesAcceptUserBase} from '../database-models/bid-term-acceptances-accept-user-base'; import {SetupMemberBase} from '../database-models/setup-member-base'; import {SetupMembersSecondaryBase} from '../database-models/setup-members-secondary-base'; import {BuyerBase} from '../database-models/buyer-base'; import {ElectronicDataInterchangeInvoiceBase} from '../database-models/electronic-data-interchange-invoice-base'; import {NoteBase} from '../database-models/note-base'; import {UserDepartmentRoleBase} from '../database-models/user-department-role-base'; import {UsersCompanyBase} from '../database-models/users-company-base'; import {UsersDepartmentBase} from '../database-models/users-department-base'; import {UsersParentidNavigationBase} from '../database-models/users-parentid-navigation-base'; //Generated Imports export class User extends UserBase { //#region Generated Reference Properties //#region actingUser Prop actingUser : UserBase; //#endregion actingUser Prop //#region bidResultTypeMask Prop bidResultTypeMask : BidResultTypeMaskBase; //#endregion bidResultTypeMask Prop //#region brand Prop brand : BrandBase; //#endregion brand Prop //#region company Prop company : UserBase; //#endregion company Prop //#region currencyFormatMask Prop currencyFormatMask : CurrencyFormatMaskBase; //#endregion currencyFormatMask Prop //#region currency Prop currency : CurrencyBase; //#endregion currency Prop //#region dateFormatMask Prop dateFormatMask : DateFormatMaskBase; //#endregion dateFormatMask Prop //#region department Prop department : UserBase; //#endregion department Prop //#region jobGroup Prop jobGroup : JobGroupBase; //#endregion jobGroup Prop //#region language Prop language : SupportedLanguageBase; //#endregion language Prop //#region memberStatus Prop memberStatus : MemberStatusBase; //#endregion memberStatus Prop //#region memberTypeNameNavigation Prop memberTypeNameNavigation : MemberTypeBase; //#endregion memberTypeNameNavigation Prop //#region parentidNavigation Prop parentidNavigation : UserBase; //#endregion parentidNavigation Prop //#region reportAccess Prop reportAccess : ReportAccessBase; //#endregion reportAccess Prop //#region territory Prop territory : TerritoryBase; //#endregion territory Prop //#region timezone Prop timezone : TimeZoneBase; //#endregion timezone Prop //#region vendorBackgrounds Prop vendorBackgrounds : VendorBackgroundBase[]; //#endregion vendorBackgrounds Prop //#region fileDownloadAudits Prop fileDownloadAudits : FileDownloadAuditBase[]; //#endregion fileDownloadAudits Prop //#region fileDownloadAuditsDownloadUser Prop fileDownloadAuditsDownloadUser : FileDownloadAuditBase[]; //#endregion fileDownloadAuditsDownloadUser Prop //#region serviceFeeInvoices Prop serviceFeeInvoices : ServiceFeeInvoiceBase[]; //#endregion serviceFeeInvoices Prop //#region serviceFeeInvoicesUpdatedByNavigation Prop serviceFeeInvoicesUpdatedByNavigation : ServiceFeeInvoiceBase[]; //#endregion serviceFeeInvoicesUpdatedByNavigation Prop //#region topics Prop topics : TopicBase[]; //#endregion topics Prop //#region topicsCreateUser Prop topicsCreateUser : TopicBase[]; //#endregion topicsCreateUser Prop //#region contracts Prop contracts : ContractBase[]; //#endregion contracts Prop //#region serviceFeeBatches Prop serviceFeeBatches : ServiceFeeBatchBase[]; //#endregion serviceFeeBatches Prop //#region serviceFeeBatchesProcessedByUser Prop serviceFeeBatchesProcessedByUser : ServiceFeeBatchBase[]; //#endregion serviceFeeBatchesProcessedByUser Prop //#region emailRegistrations Prop emailRegistrations : EmailRegistrationBase[]; //#endregion emailRegistrations Prop //#region logicalFiles Prop logicalFiles : LogicalFileBase[]; //#endregion logicalFiles Prop //#region serviceFees Prop serviceFees : ServiceFeeBase[]; //#endregion serviceFees Prop //#region serviceFeesCompletedByUser Prop serviceFeesCompletedByUser : ServiceFeeBase[]; //#endregion serviceFeesCompletedByUser Prop //#region serviceFeesCreatedByLogin Prop serviceFeesCreatedByLogin : ServiceFeeBase[]; //#endregion serviceFeesCreatedByLogin Prop //#region serviceFeesCreatedByUser Prop serviceFeesCreatedByUser : ServiceFeeBase[]; //#endregion serviceFeesCreatedByUser Prop //#region noteDeliveries Prop noteDeliveries : NoteDeliveryBase[]; //#endregion noteDeliveries Prop //#region estimateTermAcceptances Prop estimateTermAcceptances : EstimateTermAcceptanceBase[]; //#endregion estimateTermAcceptances Prop //#region estimateTermAcceptancesAcceptUser Prop estimateTermAcceptancesAcceptUser : EstimateTermAcceptanceBase[]; //#endregion estimateTermAcceptancesAcceptUser Prop //#region resourceAcquiredJobs Prop resourceAcquiredJobs : ResourceAcquiredJobBase[]; //#endregion resourceAcquiredJobs Prop //#region resourceAcquiredJobsResourceUser Prop resourceAcquiredJobsResourceUser : ResourceAcquiredJobBase[]; //#endregion resourceAcquiredJobsResourceUser Prop //#region supportLogs Prop supportLogs : SupportLogBase[]; //#endregion supportLogs Prop //#region supportLogsUser Prop supportLogsUser : SupportLogBase[]; //#endregion supportLogsUser Prop //#region dataItems Prop dataItems : DataItemBase[]; //#endregion dataItems Prop //#region bidSessionBidders Prop bidSessionBidders : BidSessionBidderBase[]; //#endregion bidSessionBidders Prop //#region eventLogs Prop eventLogs : EventLogBase[]; //#endregion eventLogs Prop //#region eventLogsEventUser Prop eventLogsEventUser : EventLogBase[]; //#endregion eventLogsEventUser Prop //#region eventLogsTargetUser Prop eventLogsTargetUser : EventLogBase[]; //#endregion eventLogsTargetUser Prop //#region projects Prop projects : ProjectBase[]; //#endregion projects Prop //#region jobTeams Prop jobTeams : JobTeamBase[]; //#endregion jobTeams Prop //#region resourceGroupMembers Prop resourceGroupMembers : ResourceGroupMemberBase[]; //#endregion resourceGroupMembers Prop //#region resourceGroupMembersResourceUser Prop resourceGroupMembersResourceUser : ResourceGroupMemberBase[]; //#endregion resourceGroupMembersResourceUser Prop //#region vendorPools Prop vendorPools : VendorPoolBase[]; //#endregion vendorPools Prop //#region projectTasks Prop projectTasks : ProjectTaskBase[]; //#endregion projectTasks Prop //#region vendorAssignedTeamMembers Prop vendorAssignedTeamMembers : VendorAssignedTeamMemberBase[]; //#endregion vendorAssignedTeamMembers Prop //#region vendors Prop vendors : VendorBase[]; //#endregion vendors Prop //#region vendorsVendorNavigation Prop vendorsVendorNavigation : VendorBase[]; //#endregion vendorsVendorNavigation Prop //#region userAbilityOptions Prop userAbilityOptions : UserAbilityOptionBase[]; //#endregion userAbilityOptions Prop //#region jobs Prop jobs : JobBase[]; //#endregion jobs Prop //#region jobsBuyerDepartment Prop jobsBuyerDepartment : JobBase[]; //#endregion jobsBuyerDepartment Prop //#region jobsBuyerUser Prop jobsBuyerUser : JobBase[]; //#endregion jobsBuyerUser Prop //#region jobsOriginatingDepartment Prop jobsOriginatingDepartment : JobBase[]; //#endregion jobsOriginatingDepartment Prop //#region jobsVendorCompany Prop jobsVendorCompany : JobBase[]; //#endregion jobsVendorCompany Prop //#region jobsVendorDepartment Prop jobsVendorDepartment : JobBase[]; //#endregion jobsVendorDepartment Prop //#region jobsVendorUser Prop jobsVendorUser : JobBase[]; //#endregion jobsVendorUser Prop //#region userRightOptions Prop userRightOptions : UserRightOptionBase[]; //#endregion userRightOptions Prop //#region bulkNotify Prop bulkNotify : BulkNotifyBase[]; //#endregion bulkNotify Prop //#region bulkNotifyCreationUser Prop bulkNotifyCreationUser : BulkNotifyBase[]; //#endregion bulkNotifyCreationUser Prop //#region termSets Prop termSets : TermSetBase[]; //#endregion termSets Prop //#region vendorTeamMembers Prop vendorTeamMembers : VendorTeamMemberBase[]; //#endregion vendorTeamMembers Prop //#region logicalFileInstances Prop logicalFileInstances : LogicalFileInstanceBase[]; //#endregion logicalFileInstances Prop //#region logicalFileInstancesActionUser Prop logicalFileInstancesActionUser : LogicalFileInstanceBase[]; //#endregion logicalFileInstancesActionUser Prop //#region buyerFeatureMappings Prop buyerFeatureMappings : BuyerFeatureMappingBase[]; //#endregion buyerFeatureMappings Prop //#region vendorTermAcceptances Prop vendorTermAcceptances : VendorTermAcceptanceBase[]; //#endregion vendorTermAcceptances Prop //#region vendorTermAcceptancesAcceptUser Prop vendorTermAcceptancesAcceptUser : VendorTermAcceptanceBase[]; //#endregion vendorTermAcceptancesAcceptUser Prop //#region sampleEvaluations Prop sampleEvaluations : SampleEvaluationBase[]; //#endregion sampleEvaluations Prop //#region sampleEvaluationsEvaluationLogin Prop sampleEvaluationsEvaluationLogin : SampleEvaluationBase[]; //#endregion sampleEvaluationsEvaluationLogin Prop //#region sampleEvaluationsEvaluationUser Prop sampleEvaluationsEvaluationUser : SampleEvaluationBase[]; //#endregion sampleEvaluationsEvaluationUser Prop //#region mailRecipients Prop mailRecipients : MailRecipientBase[]; //#endregion mailRecipients Prop //#region messages Prop messages : MessageBase[]; //#endregion messages Prop //#region messagesAuthorUser Prop messagesAuthorUser : MessageBase[]; //#endregion messagesAuthorUser Prop //#region paymentTransferLogs Prop paymentTransferLogs : PaymentTransferLogBase[]; //#endregion paymentTransferLogs Prop //#region messageRecipients Prop messageRecipients : MessageRecipientBase[]; //#endregion messageRecipients Prop //#region messageRecipientsRecipientUser Prop messageRecipientsRecipientUser : MessageRecipientBase[]; //#endregion messageRecipientsRecipientUser Prop //#region reconcileLogs Prop reconcileLogs : ReconcileLogBase[]; //#endregion reconcileLogs Prop //#region reconcileLogsReconcileUser Prop reconcileLogsReconcileUser : ReconcileLogBase[]; //#endregion reconcileLogsReconcileUser Prop //#region shipments Prop shipments : ShipmentBase[]; //#endregion shipments Prop //#region shipmentsShipperUser Prop shipmentsShipperUser : ShipmentBase[]; //#endregion shipmentsShipperUser Prop //#region specDestinationDetails Prop specDestinationDetails : SpecDestinationDetailBase[]; //#endregion specDestinationDetails Prop //#region specDestinationDetailsDefaultReceiveUser Prop specDestinationDetailsDefaultReceiveUser : SpecDestinationDetailBase[]; //#endregion specDestinationDetailsDefaultReceiveUser Prop //#region vendorPoolSubscriptions Prop vendorPoolSubscriptions : VendorPoolSubscriptionBase[]; //#endregion vendorPoolSubscriptions Prop //#region componentCustomFields Prop componentCustomFields : ComponentCustomFieldBase[]; //#endregion componentCustomFields Prop //#region addresses Prop addresses : AddressBase[]; //#endregion addresses Prop //#region jobDeleteReasons Prop jobDeleteReasons : JobDeleteReasonBase[]; //#endregion jobDeleteReasons Prop //#region setupRequests Prop setupRequests : SetupRequestBase[]; //#endregion setupRequests Prop //#region setupRequestsCloneComp Prop setupRequestsCloneComp : SetupRequestBase[]; //#endregion setupRequestsCloneComp Prop //#region setupRequestsProductAgent Prop setupRequestsProductAgent : SetupRequestBase[]; //#endregion setupRequestsProductAgent Prop //#region setupRequestsProviderDept Prop setupRequestsProviderDept : SetupRequestBase[]; //#endregion setupRequestsProviderDept Prop //#region setupRequestsRequestedByDept Prop setupRequestsRequestedByDept : SetupRequestBase[]; //#endregion setupRequestsRequestedByDept Prop //#region setupRequestsRequestedByUser Prop setupRequestsRequestedByUser : SetupRequestBase[]; //#endregion setupRequestsRequestedByUser Prop //#region setupRequestsRequestedUser Prop setupRequestsRequestedUser : SetupRequestBase[]; //#endregion setupRequestsRequestedUser Prop //#region phones Prop phones : PhoneBase[]; //#endregion phones Prop //#region userDataItems Prop userDataItems : UserDataItemBase[]; //#endregion userDataItems Prop //#region receiveLogs Prop receiveLogs : ReceiveLogBase[]; //#endregion receiveLogs Prop //#region receiveLogsReceiveUser Prop receiveLogsReceiveUser : ReceiveLogBase[]; //#endregion receiveLogsReceiveUser Prop //#region componentEvaluations Prop componentEvaluations : ComponentEvaluationBase[]; //#endregion componentEvaluations Prop //#region componentEvaluationsEvaluationLogin Prop componentEvaluationsEvaluationLogin : ComponentEvaluationBase[]; //#endregion componentEvaluationsEvaluationLogin Prop //#region componentEvaluationsEvaluationUser Prop componentEvaluationsEvaluationUser : ComponentEvaluationBase[]; //#endregion componentEvaluationsEvaluationUser Prop //#region customTextMembers Prop customTextMembers : CustomTextMemberBase[]; //#endregion customTextMembers Prop //#region mails Prop mails : MailBase[]; //#endregion mails Prop //#region setupMemberSequences Prop setupMemberSequences : SetupMemberSequenceBase[]; //#endregion setupMemberSequences Prop //#region setupMemberSequencesSecondary Prop setupMemberSequencesSecondary : SetupMemberSequenceBase[]; //#endregion setupMemberSequencesSecondary Prop //#region changeOrders Prop changeOrders : ChangeOrderBase[]; //#endregion changeOrders Prop //#region jobUnInvitedBidders Prop jobUnInvitedBidders : JobUnInvitedBidderBase[]; //#endregion jobUnInvitedBidders Prop //#region nonDisclosureAgreementEstimateAccept Prop nonDisclosureAgreementEstimateAccept : NonDisclosureAgreementEstimateAcceptBase[]; //#endregion nonDisclosureAgreementEstimateAccept Prop //#region vendorQualifiers Prop vendorQualifiers : VendorQualifierBase[]; //#endregion vendorQualifiers Prop //#region approveLogs Prop approveLogs : ApproveLogBase[]; //#endregion approveLogs Prop //#region approveLogsApproveUser Prop approveLogsApproveUser : ApproveLogBase[]; //#endregion approveLogsApproveUser Prop //#region bidSessionNonDisclosureAgreement Prop bidSessionNonDisclosureAgreement : BidSessionNonDisclosureAgreementBase[]; //#endregion bidSessionNonDisclosureAgreement Prop //#region bidSessionNonDisclosureAgreementUser Prop bidSessionNonDisclosureAgreementUser : BidSessionNonDisclosureAgreementBase[]; //#endregion bidSessionNonDisclosureAgreementUser Prop //#region memberPortfolios Prop memberPortfolios : MemberPortfolioBase[]; //#endregion memberPortfolios Prop //#region advertisingSpecialtyInstituteMembers Prop advertisingSpecialtyInstituteMembers : AdvertisingSpecialtyInstituteMemberBase[]; //#endregion advertisingSpecialtyInstituteMembers Prop //#region directJobLogins Prop directJobLogins : DirectJobLoginBase[]; //#endregion directJobLogins Prop //#region directJobLoginsUser Prop directJobLoginsUser : DirectJobLoginBase[]; //#endregion directJobLoginsUser Prop //#region financialXferPreferences Prop financialXferPreferences : FinancialXferPreferenceBase[]; //#endregion financialXferPreferences Prop //#region departmentServices Prop departmentServices : DepartmentServiceBase[]; //#endregion departmentServices Prop //#region departmentServicesProviderAgent Prop departmentServicesProviderAgent : DepartmentServiceBase[]; //#endregion departmentServicesProviderAgent Prop //#region departmentServicesProviderDepartment Prop departmentServicesProviderDepartment : DepartmentServiceBase[]; //#endregion departmentServicesProviderDepartment Prop //#region directLogins Prop directLogins : DirectLoginBase[]; //#endregion directLogins Prop //#region directLoginsLoginUser Prop directLoginsLoginUser : DirectLoginBase[]; //#endregion directLoginsLoginUser Prop //#region directLoginsUser Prop directLoginsUser : DirectLoginBase[]; //#endregion directLoginsUser Prop //#region bidSessionPrices Prop bidSessionPrices : BidSessionPriceBase[]; //#endregion bidSessionPrices Prop //#region bidSessionPricesBidderUser Prop bidSessionPricesBidderUser : BidSessionPriceBase[]; //#endregion bidSessionPricesBidderUser Prop //#region jobSteps Prop jobSteps : JobStepBase[]; //#endregion jobSteps Prop //#region jobStepsClosedUser Prop jobStepsClosedUser : JobStepBase[]; //#endregion jobStepsClosedUser Prop //#region jobStepsProviderUser Prop jobStepsProviderUser : JobStepBase[]; //#endregion jobStepsProviderUser Prop //#region bidTermAcceptances Prop bidTermAcceptances : BidTermAcceptanceBase[]; //#endregion bidTermAcceptances Prop //#region bidTermAcceptancesAcceptUser Prop bidTermAcceptancesAcceptUser : BidTermAcceptanceBase[]; //#endregion bidTermAcceptancesAcceptUser Prop //#region setupMembers Prop setupMembers : SetupMemberBase[]; //#endregion setupMembers Prop //#region setupMembersSecondary Prop setupMembersSecondary : SetupMemberBase[]; //#endregion setupMembersSecondary Prop //#region buyers Prop buyers : BuyerBase[]; //#endregion buyers Prop //#region electronicDataInterchangeInvoices Prop electronicDataInterchangeInvoices : ElectronicDataInterchangeInvoiceBase[]; //#endregion electronicDataInterchangeInvoices Prop //#region notes Prop notes : NoteBase[]; //#endregion notes Prop //#region userDepartmentRoles Prop userDepartmentRoles : UserDepartmentRoleBase[]; //#endregion userDepartmentRoles Prop //#region users Prop users : UserBase[]; //#endregion users Prop //#region usersCompany Prop usersCompany : UserBase[]; //#endregion usersCompany Prop //#region usersDepartment Prop usersDepartment : UserBase[]; //#endregion usersDepartment Prop //#region usersParentidNavigation Prop usersParentidNavigation : UserBase[]; //#endregion usersParentidNavigation Prop //#endregion Generated Reference Properties }
the_stack
* This file contains various useful functions and classes. */ import {ErrorReporter} from "./ui/errReporter"; import {DragEventKind, HtmlString, pageReferenceFormat, Resolution, Size} from "./ui/ui"; import { AggregateDescription, BucketsInfo, Comparison, ComparisonFilterDescription, ContentsKind, Groups, IColumnDescription, kindIsNumeric, kindIsString, NextKList, RangeFilterArrayDescription, RangeFilterDescription, RecordOrder, RowFilterDescription, RowValue, SampleSet, StringFilterDescription } from "./javaBridge"; import {AxisData} from "./dataViews/axisData"; import {SchemaClass} from "./schemaClass"; export interface Pair<T1, T2> { first: T1; second: T2; } export interface Triple<T1, T2, T3> extends Pair<T1, T2> { third: T3; } export interface Two<T> extends Pair<T, T> {} export function assert(condition: boolean, message?: string): asserts condition { console.assert(condition, message); // tslint:disable-line } export function allBuckets<R>(data: Groups<R>): R[] { const result = cloneArray(data.perBucket); result.push(data.perMissing); return result; } export function zip<T, S, R>(a: T[], b: S[], f: (ae: T, be: S) => R): R[] { return a.map((ae, i) => f(ae, b[i])); } /** * Find el in the array a. If found returns the index. If not found returns the negative of * the index where the element would be inserted. * @param a Sorted array of values. * @param el Value to search. * @param comparator Comparator function for two values of type T. */ export function binarySearch<T>(a: T[], el: T, comparator: (e1: T, e2: T) => number): number { let m = 0; let n = a.length - 1; while (m <= n) { const k = (n + m) >> 1; const cmp = comparator(el, a[k]); if (cmp > 0) { m = k + 1; } else if (cmp < 0) { n = k - 1; } else { return k; } } return -m - 1; } export function dataRange(data: RowValue[], cd: IColumnDescription): BucketsInfo { const present = data.filter((e) => e !== null); let b: BucketsInfo = { allStringsKnown: false, max: 0, maxBoundary: "", min: 0, missingCount: data.length - present.length, presentCount: present.length, stringQuantiles: [] }; if (present.length === 0) return b; if (kindIsNumeric(cd.kind)) { const numbers = present.map((v) => v as number); b.min = numbers.reduce((a, b) => Math.min(a, b)); b.max = numbers.reduce((a, b) => Math.max(a, b)); } else { const strings = present.map((v) => v as string); const sorted = strings.sort(); const unique = []; let previous = null; for (const c of sorted) { if (c == previous) continue; previous = c; unique.push(c); } if (unique.length < Resolution.max2DBucketCount) { b.stringQuantiles = unique; b.allStringsKnown = true; } else { for (let i = 0; i < Resolution.max2DBucketCount; i++) b.stringQuantiles!.push(unique[Math.round(i * unique.length / Resolution.max2DBucketCount)]); b.allStringsKnown = false; } } return b; } /** * A few static methods to export data to CSV formats. */ export class Exporter { public static histogram2DAsCsv( data: Groups<Groups<number>>, schema: SchemaClass, axis: AxisData[]): string[] { const lines: string[] = []; const yAxis = axis[1].description!.name; const xAxis = axis[0].description!.name; let line = ""; for (let y = 0; y < axis[1].bucketCount; y++) { const by = axis[1].bucketDescription(y, 0); line += "," + JSON.stringify(yAxis + " " + by); } line += ",missing"; lines.push(line); for (let x = 0; x < axis[0].bucketCount; x++) { const d = data.perBucket[x]; const bx = axis[0].bucketDescription(x, 0); let l = JSON.stringify(xAxis + " " + bx); for (const y of d.perBucket) l += "," + y; l += "," + d.perMissing; lines.push(l); } line = "mising"; for (const y of data.perMissing.perBucket) line += "," + y; line += "," + data.perMissing.perMissing; lines.push(line); return lines; } public static tableAsCsv(order: RecordOrder, schema: SchemaClass, aggregates: AggregateDescription[] | null, nextKList: NextKList): string[] { let lines = []; let line = "count"; for (const o of order.sortOrientationList) line += "," + JSON.stringify(o.columnDescription.name); if (aggregates != null) for (const a of aggregates) { // noinspection UnnecessaryLocalVariableJS const dn = a.cd.name; line += "," + JSON.stringify(a.agkind + "(" + dn + "))"); } lines.push(line); for (let i = 0; i < nextKList.rows.length; i++) { const row = nextKList.rows[i]; line = row.count.toString(); for (let j = 0; j < row.values.length; j++) { const kind = order.sortOrientationList[j].columnDescription.kind; let a = Converters.valueToString(row.values[j], kind, false); if (kindIsString(kind)) a = JSON.stringify(a); line += "," + a; } if (nextKList.aggregates != null) { const agg = nextKList.aggregates[i]; for (const v of agg) { line += "," + v; } } lines.push(line); } return lines; } public static histogramAsCsv(data: Groups<number>, schema: SchemaClass, axis: AxisData): string[] { const lines: string[] = []; const colName = axis.description.name; let line = JSON.stringify(colName) + ",count"; lines.push(line); for (let x = 0; x < data.perBucket.length; x++) { const bx = axis.bucketDescription(x, 0); const l = "" + JSON.stringify(bx) + "," + data.perBucket[x]; lines.push(l); } line = "missing," + data.perMissing; lines.push(line); return lines; } public static histogram3DAsCsv( data: Groups<Groups<Groups<number>>>, schema: SchemaClass, axis: AxisData[]): string[] { let lines: string[] = []; const gAxis = axis[2].description!.name; for (let g = 0; g < axis[2].bucketCount; g++) { const gl = Exporter.histogram2DAsCsv(data.perBucket[g], schema, axis); const first = gl[0]; const tail = gl.slice(1); if (g == 0) { // This is the header line lines.push("," + first); } const by = axis[2].bucketDescription(g, 0); lines = lines.concat(tail.map(l => JSON.stringify(gAxis + " " + by) + "," + l)); } const by = "missing"; const gl = Exporter.histogram2DAsCsv(data.perMissing, schema, axis); lines.concat(gl.map(l => JSON.stringify(gAxis + " " + by) + "," + l)); return lines; } public static quartileAsCsv(g: Groups<SampleSet>, schema: SchemaClass, axis: AxisData): string[] { const lines: string[] = []; let line = ""; const axisName = axis.description.name; for (let x = 0; x < axis.bucketCount; x++) { const bx = axis.bucketDescription(x, 0); const l = JSON.stringify(axisName + " " + bx); line += "," + l; } line += ",missing" lines.push(line); const data = allBuckets(g); line = "min"; for (const d of data) { line += "," + ((d.count === 0) ? "" : d.min); } lines.push(line); line = "q1"; for (const d of data) { line += "," + ((d.count === 0) ? "" : (d.samples.length > 0 ? d.samples[0] : "")); } lines.push(line); line = "median"; for (const d of data) { line += "," + ((d.count === 0) ? "" : (d.samples.length > 1 ? d.samples[1] : "")); } lines.push(line); line = "q3"; for (const d of data) { line += "," + ((d.count === 0) ? "" : (d.samples.length > 2 ? d.samples[2] : "")); } lines.push(line); line = "max"; for (const d of data) { line += "," + ((d.count === 0) ? "" : d.max); } lines.push(line); line = "missing"; for (const d of data) { line += "," + d.missing; } lines.push(line); return lines; } } export function describeQuartiles(data: SampleSet): string[] { if (data.count == 0) { return ["0", "", "", "", "", "", ""]; } const count = significantDigits(data.count); const min = significantDigits(data.min); const max = significantDigits(data.max); const q1 = significantDigits(data.samples[0]); const q2 = data.samples.length > 1 ? significantDigits(data.samples[1]) : q1; const q3 = data.samples.length > 2 ? significantDigits(data.samples[2]) : q2; const missing = significantDigits(data.missing); return [count, missing, min, q1, q2, q3, max]; } /** * Direct counterpart of corresponding Java class */ export class Converters { public static dateFromDouble(value: number | null): Date | null { if (value == null) return null; return new Date(value); } // Javascript dates are always UTC public static localDateFromDouble(value: number | null): Date | null { if (value == null) return null; const offset = new Date(value).getTimezoneOffset(); return new Date(value + offset * 60 * 1000); } public static timeFromDouble(value: number | null): Date | null { return Converters.localDateFromDouble(value); } public static doubleFromDate(value: Date | null): number | null { if (value === null) return null; return value.getTime(); } public static doubleFromLocalDate(value: Date | null): number | null { if (value === null) return null; const offset = value.getTimezoneOffset(); return value.getTime() - offset * 60 * 1000; } /** * Convert a value expressed in milliseconds to a time duration. */ public static durationFromDouble(val: number): string { if (val === 0) return "0"; const ms = Math.round(val % 1000); val = Math.floor(val / 1000); const sec = val % 60; val = Math.floor(val / 60); const min = val % 60; val = Math.floor(val / 60); const hours = val % 24; const days = Math.floor(val / 24); let result: string = ""; if (days > 0) result = significantDigits(days) + " days"; if (days > 1000) return result; if (hours > 0) { if (result.length !== 0) result += " "; result += hours.toString() + "H"; } if (min > 0) { if (result.length !== 0) result += " "; result += " " + min.toString() + "M"; } let addedSec = false; if (sec > 0) { if (result.length !== 0) result += " "; addedSec = true; result += sec.toString(); } if (ms > 0 && days === 0) { if (!addedSec) result += " 0"; addedSec = true; result += "." + ms.toString(); } if (addedSec) result += "s"; return result; } /** * Convert a value in a table cell to a string representation. * @param val Value to convert. * @param kind Type of value. * @param human If true this is for human consumption, else it is for machine consumption. */ public static valueToString(val: RowValue | null, kind: ContentsKind, human: boolean): string { if (val == null) // This should probably not happen return "missing"; if (kindIsNumeric(kind)) { if (human) return significantDigits(val as number); else return String(val); } else if (kind === "Date") { return formatDate(Converters.dateFromDouble(val as number)); } else if (kind === "Time" || kind === "Duration") { const time = Converters.timeFromDouble(val as number); return formatTime(time, true); } else if (kindIsString(kind)) { return val as string; } else if (kind == "Interval") { const arr = val as number[]; return "[" + this.valueToString(arr[0], "Double", human) + ":" + this.valueToString(arr[1], "Double", human) + "]"; } else if (kind === "LocalDate") { const date = Converters.localDateFromDouble(val as number); return formatDate(date); } else { assert(false); } } /** * Human-readable description of a filter. * @param f: filter to describe */ public static filterDescription(f: RangeFilterDescription): string { const min = kindIsNumeric(f.cd.kind) ? f.min : f.minString; const max = kindIsNumeric(f.cd.kind) ? f.max : f.maxString; return "Filtered on " + f.cd.name + " in range " + Converters.valueToString(min, f.cd.kind, true) + " - " + Converters.valueToString(max, f.cd.kind, true); } public static filterArrayDescription(f: RangeFilterArrayDescription): string { let result = ""; if (f.complement) result = "not "; for (const filter of f.filters) result += Converters.filterDescription(filter); return result; } public static stringFilterDescription(f: StringFilterDescription): string { let result = ""; if ((f.asSubString || f.asRegEx) && !f.complement) result += " contains "; else if ((f.asSubString || f.asRegEx) && f.complement) result += " does not contain "; else if (!(f.asSubString || f.asRegEx) && !f.complement) result += " equals "; else if (!(f.asSubString || f.asRegEx) && f.complement) result += " does not equal "; result += f.compareValue; return result; } public static rowFilterDescription(f: RowFilterDescription): string { let result = "Filter rows that are " + f.comparison + " than ["; result += f.data.join(","); result += "]"; result += " compared " + f.order.sortOrientationList.map(c => c.isAscending ? "asc" : "desc").join(","); return result; } /** * Human-readable description of a drag event. * @param pageId Page where drag event originated. * @param event Event kind. */ public static eventToString(pageId: string, event: DragEventKind): string { let result = "Drag-and-drop "; switch (event) { case "Title": result += " contents "; break; case "XAxis": result += " X axis "; break; case "YAxis": result += " Y axis "; break; case "GAxis": result += " Grouping " break; default: assertNever(event); } return result + " from " + pageReferenceFormat(pageId); } static comparisonFilterDescription(filter: ComparisonFilterDescription): string { const kind = filter.column.kind; let str; switch (kind) { case "Json": case "String": str = this.valueToString(filter.stringValue, kind, true); break; case "Integer": case "Double": case "Date": case "Time": case "Duration": case "LocalDate": str = this.valueToString(filter.doubleValue, kind, true); break; case "Interval": str = this.valueToString([filter.doubleValue!, filter.intervalEnd!], kind, true); break; case "None": str = null; break; default: assertNever(kind); } return filter.column.name + " " + filter.comparison + " " + str; } } /** * Retrieves a node from the DOM starting from a CSS selector specification. * @param cssselector Node specification as a CSS selector. * @returns The unique selected node. */ export function findElementAny(cssselector: string): HTMLElement | null { const val = document.querySelector(cssselector); return val as HTMLElement; } export function findElement(cssselector: string): HTMLElement { return findElementAny(cssselector)!; } /** * Returns an input box element containing the specified text. * @param text Text to insert as the value. */ export function makeInputBox(text: string | null): HTMLElement { const inputBox = document.createElement("input"); if (text != null) inputBox.value = text; return inputBox; } /** * Returns a span element containing the specified text. * @param text Text to insert in span. * @param highlight If true the span has class highlight. */ export function makeSpan(text: string | null, highlight: boolean = false): HTMLElement { const span = document.createElement("span"); if (text != null) span.textContent = text; if (highlight) span.className = "highlight"; return span; } export function valueWithConfidence(value: number, confidence: number | null): [number, number] { if (confidence != null) { return [Math.round(value - confidence), Math.round(value + confidence)]; } else { return [value, value]; } } export function makeInterval(value: [number, number]): string { if (value[0] >= value[1]) return significantDigits(value[0]); else return significantDigits(value[0]) + ":" + significantDigits(value[1]); } /** * Creates an HTML element that displays as missing data. */ export function makeMissing(): HTMLElement { const span = document.createElement("span"); span.textContent = "missing"; span.className = "missingData"; return span; } /** * Interface which is implemented by classes that know * how to serialize and deserialize themselves from objects. * T in general will be the class itself. */ export interface Serializable<T> { /** * Save the data into a javascript object. */ serialize(): object; /** * Initialize the current object from the specified object. * @returns The same object if deserialization is successful, null otherwise. */ deserialize(data: object): T | null; } /** * Load the contents of a text file. * @param file File to load. * @param onsuccess method called with the file contents when successful. * @param reporter Used to report errors. */ export function loadFile(file: File, onsuccess: (s: string) => void, reporter: ErrorReporter): void { const reader = new FileReader(); reader.onloadend = () => onsuccess(reader.result as string); reader.onabort = () => reporter.reportError("Read of file " + file.name + " aborted"); reader.onerror = (e) => reporter.reportError(e.toString()); if (file) reader.readAsText(file); else reporter.reportError("Invalid file"); } /** * Random seed management */ export class Seed { public static instance: Seed = new Seed(); constructor() {} // noinspection JSMethodCanBeStatic public get(): number { return Math.round(Math.random() * 1024 * 1024); } public getSampled(samplingRate: number): number { if (samplingRate >= 1.0) return 0; return this.get(); } } /** * Converts a number to a more readable representation. */ export function formatNumber(n: number): string { return n.toLocaleString(); } export function prefixSum(n: number[]): number[] { let s = 0; const result = []; for (const c of n) { s += c; result.push(s); } return result; } export function percent(numerator: number, denominator: number): number { if (denominator <= 0) return 0; return (numerator / denominator) * 100; } /** * Convert n to a string representing a percent value * where we keep at most one digit after the decimal point */ export function percentString(n: number): string { n = Math.round(n * 1000) / 10; return significantDigits(n) + "%"; } export function createComparisonFilter(cd: IColumnDescription, value: RowValue, comparison: Comparison): ComparisonFilterDescription { let stringValue = null; let doubleValue = null; let intervalEnd = null; switch (cd.kind) { case "Json": case "String": stringValue = value as string; break; case "Integer": case "Double": case "Date": case "Duration": case "LocalDate": case "Time": doubleValue = value as number; break; case "Interval": const a = value as number[]; doubleValue = a[0]; intervalEnd = a[1]; break; case "None": stringValue = null; break; default: assertNever(cd.kind); } return { column: cd, stringValue, doubleValue, intervalEnd, comparison, }; } export function fractionToPercent(n: number): string { return (n * 100) + "%"; } /** * convert a number to a string and prepend zeros if necessary to * bring the integer part to the specified number of digits */ function zeroPad(num: number, length: number): string { const n = Math.abs(num); const zeros = Math.max(0, length - Math.floor(n).toString().length ); let zeroString = Math.pow(10, zeros).toString().substr(1); if (num < 0) { zeroString = "-" + zeroString; } return zeroString + n; } /** * Write a date into a format like * 2017/03/05 10:05:30.243 * The suffix may be omitted if it is zero. * This should match the algorithm in the Java Converters.toString(Instant) method. */ export function formatDate(d: Date | null): string { if (d == null) return "missing"; const year = d.getFullYear(); const month = d.getMonth() + 1; const day = d.getDate(); const df = String(year) + "/" + zeroPad(month, 2) + "/" + zeroPad(day, 2); const time = formatTime(d, false); if (time != "") return df + " " + time; return df; } export function addSeconds(d: Date, seconds: number): Date { return new Date(d.getTime() + seconds * 1000); } export function assertNever(x: never): never { throw new Error("Unexpected object: " + x); } export function disableSuggestions(visible: boolean): void { const vis = visible ? "block" : "none"; const suggestions = document.getElementById("suggestions"); if (suggestions !== null) suggestions.style.display = vis; const anchor = document.getElementById("suggestions-anchor"); if (anchor !== null) anchor.style.display = vis; } /** * This is a time encoded as a date. Ignore the date part and just * return the time. * @param d date that only has a time component. * @param nonEmpty if true return 00:00 when the result is empty. */ export function formatTime(d: Date | null, nonEmpty: boolean): string { if (d === null) return "missing"; const hour = d.getHours(); const minutes = d.getMinutes(); const seconds = d.getSeconds(); const ms = d.getMilliseconds(); let time = ""; if (ms !== 0) time = "." + zeroPad(ms, 3); if (seconds !== 0 || time !== "") time = ":" + zeroPad(seconds, 2) + time; if (minutes !== 0 || time !== "") time = ":" + zeroPad(minutes, 2) + time; if (hour !== 0 || time !== "") { if (time === "") time = ":00"; time = zeroPad(hour, 2) + time; } if (nonEmpty) { if (time == "") return "00:00"; } return time; } /** * Parses a string encoding a duration in the format [hh:[mm:]]ss[.ms] into a number of milliseconds. */ export function parseDuration(d: string | null): number | null { if (d == null) return null; const re = /(((\d{1,2}):)?(\d{1,2}):)?(\d{1,2})([.](\d{1,3}))?/; const m = d.match(re); console.debug(m); if (m == null) return null; const hour = m[3] ?? "0"; const minutes = m[4] ?? "0"; const seconds = m[5] ?? "0"; const fraction = ((m[7] ?? "") + "000").substr(0, 3); return (1000 * (60 * (60 * parseInt(hour)) + parseInt(minutes)) + parseInt(seconds)) + parseInt(fraction); } /** * Converts a string into another string which can be used as a legal ID * for an element. * @param {string} text Text to convert. * @returns {string} A similar text where each non-alphabetic or numeric character * is replaced with an underscore. */ export function makeId(text: string): string { text = text.replace(/[^a-zA-Z0-9]/g, "_"); if (!(text[0].match(/[a-z_]/i))) text = "I" + text; return text; } /** * Convert a number to an html string by keeping only the most significant digits * and adding a suffix. */ export function significantDigitsHtml(n: number): HtmlString { let suffix = ""; if (n === 0) return new HtmlString("0"); const absn = Math.abs(n); if (absn > 1e12) { suffix = "T"; n = n / 1e12; } else if (absn > 1e9) { suffix = "B"; n = n / 1e9; } else if (absn > 1e6) { suffix = "M"; n = n / 1e6; } else if (absn > 1e4) { // Using 10^4 will prevent many year values from being converted suffix = "K"; n = n / 1e3; } else if (absn < .001) { let expo = 0; while (n < .1) { n = n * 10; expo++; } suffix = "&times;10<sup>-" + expo + "</sup>"; } if (absn > 1) n = Math.round(n * 100) / 100; else n = Math.round(n * 1000) / 1000; const result = new HtmlString(String(n)); result.appendSafeString(suffix); return result; } export function add(a: number, b: number): number { return a + b; } export function all<T>(a: T[], f: (x: T) => boolean): boolean { return a.map(e => f(e)).reduce((a, b) => a && b); } export class GroupsClass<T> { constructor(public groups: Groups<T>) {} public map<S>(func: (t: T, index: number) => S): GroupsClass<S> { const m = func(this.groups.perMissing, this.groups.perBucket.length); const buckets = this.groups.perBucket.map(func); return new GroupsClass<S>({ perBucket: buckets, perMissing: m }); } public reduce<S>(func: (s: S, t: T) => S, start: S): S { return func(this.groups.perBucket.reduce(func, start), this.groups.perMissing); } } export class Heatmap { constructor(public data: GroupsClass<GroupsClass<number>>) {} static create(g: Groups<Groups<number>>): Heatmap { return new Heatmap(new GroupsClass(g).map(g1 => new GroupsClass(g1).map(c => c))); } public bitmap(f: (a: number, i: number) => boolean): Heatmap { return new Heatmap(this.data.map(g => g.map((e, i) => f(e, i) ? 1 : 0))); } public map(f: (a: number) => number): Heatmap { // noinspection JSUnusedLocalSymbols return new Heatmap(this.data.map(g => g.map((e, i) => f(e)))); } public sum(): number { return this.data.reduce( (n1, g) => n1 + g.reduce( (n0: number, n1: number) => n0 + n1, 0), 0); } /** * Keep only the buckets whose indexes are in this range. * @param yMin minimum index. * @param yMax maximum index; EXCLUSIVE. */ public bucketsInRange(yMin: number, yMax: number): Heatmap { return new Heatmap(this.data.map( (g, _) => g.map( (n, i1) => ((yMin <= i1) && (i1 < yMax)) ? n : 0 ))); } } /** * Convert a number to an string by keeping only the most significant digits * and adding a suffix. Similar to the previous function, but returns a pure string. */ export function significantDigits(n: number): string { let suffix = ""; if (n === 0) return "0"; const absn = Math.abs(n); if (absn > 1e12) { suffix = "T"; n = n / 1e12; } else if (absn > 1e9) { suffix = "B"; n = n / 1e9; } else if (absn > 1e6) { suffix = "M"; n = n / 1e6; } else if (absn > 1e4) { // Using 10^4 will prevent many year values from being converted suffix = "K"; n = n / 1e3; } else if (absn < .001) { let expo = 0; while (n < 1) { n = n * 10; expo++; } suffix = " * 10e-" + expo; } if (absn > 1) n = Math.round(n * 100) / 100; else n = Math.round(n * 1000) / 1000; return String(n) + suffix; } /** * Order two numbers such that the smaller one comes first */ export function reorder(m: number, n: number): [number, number] { if (m < n) return [m, n]; else return [n, m]; } interface NameValue<T> { name: string; value: T; } export function sameAggregate(a: AggregateDescription, b: AggregateDescription): boolean { return a.agkind === b.agkind && a.cd.name === b.cd.name && a.cd.kind === b.cd.kind; } /** * Find a value in an array using a specified equality function. Return index in array. * @param value Value to search. * @param array Array to search in. * @param comparison Comparison function, returns true if two values are equal. */ export function find<T>(value: T, array: T[], comparison: (l: T, r: T) => boolean): number { for (let i = 0; i < array.length; i++) if (comparison(value, array[i])) return i; return -1; } /** * This class builds some useful iterators over typescript enums. * In all these methods enumType is an enum *type* */ export class EnumIterators { public static getNamesAndValues<T extends number>(enumType: any): Array<NameValue<T>> { return EnumIterators.getNames(enumType).map((n) => ({ name: n, value: enumType[n] as T })); } public static getNames(enumType: any): string[] { return EnumIterators.getObjValues(enumType).filter((v) => typeof v === "string") as string[]; } public static getValues<T extends number>(enumType: any): T[] { return EnumIterators.getObjValues(enumType).filter((v) => typeof v === "number") as T[]; } private static getObjValues(enumType: any): Array<number | string> { return Object.keys(enumType).map((k) => enumType[k]); } } /** * Transpose a matrix. */ export function transpose<D>(m: D[][]): D[][] { const w = m.length; if (w === 0) return m; const h = m[0].length; const result: D[][] = []; for (let i = 0; i < h; i++) { const v = []; for (let j = 0; j < w; j++) v.push(m[j][i]); result.push(v); } return result; } /** * Given a set of values in a heatmap this computes two coefficients for a * linear regression from X to Y. The result is an array with two numbers, the * two coefficients. If the regression is undefined, the coefficients array is empty. */ export function regression(data: number[][]): number[] { const width = data.length; const height = data[0].length; let sumt = 0; let sumt2 = 0; let sumb = 0; let sumtb = 0; let size = 0; for (let i = 0; i < width; i++) { for (let j = 0; j < height; j++) { sumt += i * data[i][j]; sumt2 += i * i * data[i][j]; sumb += j * data[i][j]; sumtb += i * j * data [i][j]; size += data[i][j]; } } const denom = ((size * sumt2) - (sumt * sumt)); if (denom === 0) // TODO: should we use here some epsilon? return []; const a = 1 / denom; const alpha = a * ((sumt2 * sumb) - (sumt * sumtb)); const beta = a * ((size * sumtb) - (sumt * sumb)); // estimation is alpha + beta * i return [alpha, beta]; } /** * True if the specified element is visible on the screen. * @param e A DOM element. */ export function visible(e: HTMLElement): boolean { const screenHeight = Math.max(document.documentElement.clientHeight, window.innerHeight); const rect = e.getBoundingClientRect(); return !(rect.bottom < 0 || rect.top >= screenHeight); } /** * This is actually just a guess on the width of the vertical scroll-bar, * which we would like to always be visible. */ export const scrollBarWidth = 15; /** * Browser window size excluding scrollbars. */ export function browserWindowSize(): Size { return { width: window.innerWidth - scrollBarWidth, height: window.innerHeight, }; } export function openInNewTab(url: string): void { const win = window.open(url, "_blank"); if (win != null) win.focus(); } /** * Truncate a string to the specified length, adding ellipses if it was too long. * @param str String to truncate. * @param length Maximum length; if zero there is no truncation. */ export function truncate(str: string, length: number): string { if (length > 0 && str.length > length) { return str.slice(0, length) + "..."; } else { return str; } } export function roughTimeSpan(min: number, max: number): [number, string] { const start = Converters.dateFromDouble(min); const end = Converters.dateFromDouble(max); if (start == null || end == null) return [0, "none"]; // In milliseconds const ms_per_day = 86_400_000; const distance = end.getTime() - start.getTime(); const years = distance / (365 * ms_per_day); if (years >= 5) return [Math.ceil(years), "years"]; const months = distance / (30 * ms_per_day); if (months >= 5) return [Math.ceil(months), "months"]; const days = distance / ms_per_day; if (days >= 5) return [Math.ceil(days), "days"]; const hours = distance / 3_600_000; if (hours >= 5) return [Math.ceil(hours), "hours"]; const minutes = distance / 60_000; if (minutes >= 5) return [Math.ceil(minutes), "minutes"]; const seconds = distance / 1_000; if (seconds >= 5) return [Math.ceil(seconds), "seconds"]; const ms = distance; if (ms >= 1) return [Math.ceil(ms), "ms"]; const ns = distance * 1000_000; return [Math.ceil(ns), "ns"]; } export function optionToBoolean(value: boolean | undefined): boolean { if (value === undefined) return false; return value; } export function clamp(value: number, min: number, max: number): number { return Math.max(Math.min(value, max), min); } export function isInteger(n: number): boolean { return Math.floor(n) === n; } /** * Copy an array. */ export function cloneArray<T>(arr: T[]): T[] { return arr.slice(0); } export function cloneToSet<T>(arr: T[]): Set<T> { const result = new Set<T>(); arr.forEach((e) => result.add(e)); return result; } export function last<T>(arr: T[]): T | null { if (arr.length == 0) return null; return arr[arr.length - 1]; } export function getUUID(): string { // From https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; const v = c === "x" ? r : (r & 0x3 | 0x8); return v.toString(16); }); } export function readableTime(millisec: number): string { let seconds = Math.floor(millisec / 1000); let minutes = Math.floor(seconds / 60); const hours = Math.floor(seconds / 3600); seconds = seconds % 60; minutes = minutes % 60; function pad(n: number): string { if (n < 10) return "0" + n; else return n.toString(); } const min = pad(minutes); const sec = pad(seconds); if (hours > 0) { return `${hours}:${min}:${sec}`; } return `${min}:${sec}`; } /** * Convert a set to an array */ export function cloneSet<T>(set: Set<T>): T[] { const ret: T[] = []; set.forEach((val) => ret.push(val)); return ret; } export function exponentialDistribution(lambda: number): number { return -Math.log(1 - Math.random()) / lambda; } export class PartialResult<T> { constructor(public done: number, public data: T) {} } export interface RpcReply { result: string; // JSON or error message. requestId: number; // Request that is being replied. isError: boolean; // Indicates that the message contains an error. isCompleted: boolean; // If true this message is the last one. } // untyped cancellable export interface IRawCancellable { /** * return 'true' if cancellation succeeds. * Cancellation may fail if the computation is terminated. */ cancel(): boolean; /** time when operation was initiated */ startTime(): Date; } // Typed version of the cancellable API, makes it easy to do // strong typing. interface ISimpleCancellable<T> extends IRawCancellable { unused: T; // this is here just to force the typescript typechecker to check T // I don't understand why otherwise it doesn't } export interface ICancellable<T> extends ISimpleCancellable<PartialResult<T>> {} export function px(dim: number): string { if (dim === 0) return dim.toString(); return dim.toString() + "px"; } /** * A color triple normalized in the range 0-1 for each component. */ export class Color { public constructor(public readonly r: number, public readonly g: number, public readonly b: number) { if (r < 0 || r > 1 || g < 0 || g > 1 || b < 0 || b > 1) throw new Error("Color out of range: " + r +"," + g + "," + b) } private static colorReg = new RegExp(/rgb\(\s*(\d+),\s*(\d+),\s*(\d+)\s*\)/); public toString(): string { return "rgb(" + Math.round(this.r * 255) + "," + Math.round(this.g * 255) + "," + Math.round(this.b * 255) + ")"; } /** * Parse a color in the format rgb(r, g, b). */ public static parse(s: string): Color | null { const m = Color.colorReg.exec(s); if (m == null) return null; return new Color(+m[1]/255, +m[2]/255, +m[3]/255); } /** * Amount is a factor which is "multiplied" with the color. * Below 1 it leaves the color unchanged. */ public brighten(amount: number): Color { if (amount <= 1) return this; return new Color( (this.r + (amount - 1)) / amount, (this.g + (amount - 1)) / amount, (this.b + (amount - 1)) / amount); } } /** * Given some strings returns a subset of them. * @param data A set of strings. * @param count Number of strings to return. * @returns At most count strings equi-spaced. */ export function periodicSamples(data: string[], count: number): string[] | null { if (data == null) return null; if (count >= data.length) return data; const boundaries: string[] = []; for (let i = 0; i < count; i++) { // This formula sets the first bucket left boundary at .5 and the last at (data.length - 1)+ .5 const index = Math.ceil(i * data.length / count - .5); console.assert(index >= 0 && index < data.length); boundaries.push(data[index]); } return boundaries; } export type ColorMap = (d: number) => string; // Return the index in the array data for which func returns the minimum value export function argmin<T>(data: T[], func: (x: T) => number): number { if (data.length == 0) return -1; let min = func(data[0]); let result = 0; for (let i = 1; i < data.length; i++) { if (func(data[i]) < min) result = i; } return result; } export function desaturateOutsideRange(c: ColorMap, x0: number, x1: number): ColorMap { const [min, max] = reorder(x0, x1); return (value) => { const color = c(value); if (value < min || value > max) { const cValue = Color.parse(color); if (cValue != null) { const b = cValue.brighten(4); return b.toString(); } } return color; } }
the_stack
import CameraClass from './core/camera/camera'; import GameClass from './core/game'; import SceneClass from './core/scene'; import TextClass from './core/gameobjects/interactive/text'; import StaticLightClass from './core/lights/staticLight'; import ColliderClass from './core/physics/collider'; import GameObjectClass from './core/gameobjects/gameObject'; import CutsceneClass from './core/cutscene/cutscene'; import CircleClass from './core/gameobjects/circle'; import RectClass from './core/gameobjects/rect'; import RoundRectClass from './core/gameobjects/roundrect'; import SpriteClass from './core/gameobjects/sprite'; import GroupClass from './core/group/group'; import InputClass from './core/input/input'; import LoaderClass from './core/loader/loader'; import TileMapClass from './core/map/tilemap'; import ParticleClass from './core/gameobjects/particles/particle'; import ParticleEmitterClass from './core/gameobjects/particles/particleEmitter'; import SoundPlayerClass from './core/sound/soundPlayer'; import OnceClass from './base/once'; import RenderClass from './base/render'; import ButtonClass from './core/gameobjects/interactive/button'; import EffectClass from './core/effect/effect'; import ExplosionEffectClass from './core/effect/preset/explosion'; import SmokeEffectClass from './core/effect/preset/smoke'; import Vector2Class from './core/math/vector2'; import DisplayListClass from './core/models/displayList'; import CanvasModulateClass from './core/gameobjects/misc/canvasModulate'; import MapClass from './core/map/map'; import AmountClass from './base/amount'; import TextureClass from './core/models/texture'; import PhysicsServerClass from './core/physics/server/physicsServer'; import PhysicsBodyClass from './core/physics/physicsBody'; import HitboxClass from './core/physics/models/hitbox'; import KeyboardInputClass from './core/input/keyboardInput'; import MouseInputClass from './core/input/mouseInput'; import KeyClass from './core/input/models/key'; import MouseClass from './core/input/models/mouse'; import CacheManagerClass from './core/storage/cacheManager'; import AreaClass from './core/physics/models/area'; import PhysicsListClass from './core/models/physicsList'; import PluginManagerClass from './core/misc/pluginManager'; import AnimationClass from './core/animation/animation'; import AnimationFrameClass from './core/animation/animationFrame'; import AnimationManagerClass from './core/animation/animationManager'; import AnimationStateClass from './core/animation/animationState'; import StateMachineClass from './core/animation/stateMachine'; // main // spec /** * @namespace Duck * @description All Types, Type Classes, Classes, Layers, and Configurations are stored here. * @since 1.0.0-beta */ export namespace Duck { /** * @memberof Duck * @description Returns a HTMLCanvasElement and CanvasRenderingContext2D, finds a canvas, if none exist, * it creates and appends one * @returns {{canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D}} */ export const AutoCanvas = () => { let canvas: HTMLCanvasElement = document.querySelector( 'canvas' ) as HTMLCanvasElement; let ctx: CanvasRenderingContext2D = canvas.getContext( '2d' ) as CanvasRenderingContext2D; // check if canvas exists on document if (document.querySelector('canvas')) { canvas = document.querySelector('canvas') as HTMLCanvasElement; ctx = canvas.getContext('2d') as CanvasRenderingContext2D; } else { canvas = document.createElement('canvas') as HTMLCanvasElement; document.body.appendChild(canvas); ctx = canvas.getContext('2d') as CanvasRenderingContext2D; } return { canvas, ctx, }; }; /** * @namespace Duck.Classes * @memberof Duck * @description All classes are stored here so that it can be extended. * @since 2.0.0 */ export namespace Classes { export const Game = GameClass; export const Scene = SceneClass; export namespace GameObjects { export const GameObject = GameObjectClass; export const Circle = CircleClass; export const Rect = RectClass; export const RoundRect = RoundRectClass; export const Sprite = SpriteClass; export namespace Particles { export const Particle = ParticleClass; export const ParticleEmitter = ParticleEmitterClass; } export namespace Interactive { export const Button = ButtonClass; export const Text = TextClass; } export namespace Misc { export const CanvasModulate = CanvasModulateClass; } } export namespace Effects { export const Effect = EffectClass; export namespace Presets { export const ExplosionEffect = ExplosionEffectClass; export const SmokeEffect = SmokeEffectClass; } } export namespace Misc { export const Loader = LoaderClass; export const Group = GroupClass; export const Cutscene = CutsceneClass; export const CacheManager = CacheManagerClass; export const PluginManager = PluginManagerClass; } export namespace Base { export const Amount = AmountClass; export const Once = OnceClass; export const Render = RenderClass; } export namespace Sound { export const SoundPlayer = SoundPlayerClass; } export namespace Cameras { export const Camera = CameraClass; } export namespace Physics { export const Collider = ColliderClass; export const PhysicsServer = PhysicsServerClass; export const PhysicsBody = PhysicsBodyClass; export namespace Models { export const Hitbox = HitboxClass; export const Area = AreaClass; } } export namespace Models { export const DisplayList = DisplayListClass; export const PhysicsList = PhysicsListClass; export const Texture = TextureClass; } export namespace Map { export const Map = MapClass; export const TileMap = TileMapClass; } export namespace Math { export const Vector2 = Vector2Class; } export namespace Lights { export const StaticLight = StaticLightClass; } export namespace Input { export const Input = InputClass; export const KeyboardInput = KeyboardInputClass; export const MouseInput = MouseInputClass; export namespace Models { export const Key = KeyClass; export const Mouse = MouseClass; } } export namespace Animation { export const Animation = AnimationClass; export const AnimationFrame = AnimationFrameClass; export const AnimationManager = AnimationManagerClass; export const AnimationState = AnimationStateClass; export const StateMachine = StateMachineClass; } } /** * @namespace Duck.TypeClasses * @memberof Duck * @description All type classes are stored here so that it can be referenced. * @since 2.0.0 */ export namespace TypeClasses { export type Game = GameClass; export type Scene = SceneClass; export namespace GameObjects { export type GameObject<t extends Duck.Types.Texture.Type> = GameObjectClass<t>; export type Circle = CircleClass; export type Rect = RectClass; export type RoundRect = RoundRectClass; export type Sprite = SpriteClass; export namespace Particles { export type Particle = ParticleClass; export type ParticleEmitter = ParticleEmitterClass; } export namespace Interactive { export type Button = ButtonClass; export type Text = TextClass; } export namespace Misc { export type CanvasModulate = CanvasModulateClass; } } export namespace Effects { export type Effect = EffectClass; export namespace Presets { export type ExplosionEffect = ExplosionEffectClass; export type SmokeEffect = SmokeEffectClass; } } export namespace Misc { export type Loader = LoaderClass; export type Group<t extends Duck.Types.Group.StackItem> = GroupClass<t>; export type Cutscene = CutsceneClass; export type CacheManager = CacheManagerClass; export type PluginManager = PluginManagerClass; } export namespace Base { export type Amount = AmountClass; export type Once = OnceClass; export type Render = RenderClass; } export namespace Sound { export type SoundPlayer = SoundPlayerClass; } export namespace Cameras { export type Camera = CameraClass; } export namespace Physics { export type Collider = ColliderClass; export type PhysicsServer = PhysicsServerClass; export type PhysicsBody<t extends Duck.Types.Texture.Type> = PhysicsBodyClass<t>; export namespace Models { export type Hitbox = HitboxClass; export type Area = AreaClass; } } export namespace Models { export type DisplayList = DisplayListClass; export type PhysicsList = PhysicsListClass; export type Texture<t extends Duck.Types.Texture.Type> = TextureClass<t>; } export namespace Map { export type Map = MapClass; export type TileMap = TileMapClass; } export namespace Math { export type Vector2 = Vector2Class; } export namespace Lights { export type StaticLight = StaticLightClass; } export namespace Input { export type Input = InputClass; export type KeyboardInput = KeyboardInputClass; export type MouseInput = MouseInputClass; export namespace Models { export type Key = KeyClass; export type Mouse = MouseClass; } } export namespace Animation { export type Animation = AnimationClass; export type AnimationFrame = AnimationFrameClass; export type AnimationManager = AnimationManagerClass; export type AnimationState = AnimationStateClass; export type StateMachine = StateMachineClass; } } /** * @namespace Duck.Layers * @memberof Duck * @description All rendering zIndexes are stored here. * @since 2.0.0 */ export namespace Layers { export namespace Rendering { export const zIndex = { canvasModulate: 1, gameobject: 2, particle: 3, button: 4, text: 5, graphicDebug: 6, }; } } /** * @namespace Duck.Types * @memberof Duck * @description All Class configs and types for that class are stored here. All types are here. * @since 2.0.0 */ export namespace Types { export type GameObject<textureType extends Duck.Types.Texture.Type> = GameObjectClass<textureType>; export type Renderable = | GameObjectClass<Duck.Types.Texture.Type> | HitboxClass | Duck.TypeClasses.Effects.Effect | Duck.TypeClasses.Map.TileMap; export type PhysicsProcessMember = PhysicsBodyClass<Duck.Types.Texture.Type>; export namespace Game { export interface Config { /** * @memberof Duck.Types.Game.Config * @description Canvas element to render to or return value from Duck.AutoCanvas() * @type HTMLCanvasElement | { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D; } * @since 1.0.0-beta */ canvas: | HTMLCanvasElement | { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D; }; /** * @memberof Duck.Types.Game.Config * @description Key of scene that is defaulted to be visible * @type string * @since 1.0.0-beta */ defaultScene: string; /** * @memberof Duck.Types.Game.Config * @description Rounds pixels from floats to integers, effects gameobjects (excluding particles) * @type boolean * @since 2.0.0 */ roundPixels?: boolean; /** * @memberof Duck.Types.Game.Config * @description Determines if window.focus is called on load or not * @type boolean * @since 2.0.0 */ focus?: boolean; /** * @memberof Duck.Types.Game.Config * @description Determines if window.blur is called on load or not * @type boolean * @since 2.0.0 */ blur?: boolean; /** * @memberof Duck.Types.Game.Config * @description Determines if rendering renderable objects is paused if tab is not focused, uses window.onblur and window.onfocus * @type boolean * @since 2.0.0 */ pauseRenderingOnBlur?: boolean; /** * @memberof Duck.Types.Game.Config * @description Physics Options * @type boolean * @since 2.0.0 */ physics?: { enabled: boolean; gravity?: Duck.Types.Math.Vector2Like; customTick?: boolean; debug?: boolean; }; /** * @memberof Duck.Types.Game.Config * @description Function to call when rendering is paused, rendering pauses when this.stop is called or * if pauseRenderingOnBlur is true and the window.blur event was fired * @type (reason: 'windowBlur' | 'gameStop' | 'gameConfigBlur') => void * @since 2.0.0 */ onPauseRendering?: ( reason: 'windowBlur' | 'gameStop' | 'gameConfigBlur' ) => void; /** * @memberof Duck.Types.Game.Config * @description Function to call when rendering is resumed/started, rendering resumes/starts when this.start is called or * if the window.focus event was fired * @type (reason: 'windowFocus' | 'gameStart' | 'gameConfigFocus') => void * @since 2.0.0 */ onResumeRendering?: ( reason: 'windowFocus' | 'gameStart' | 'gameConfigFocus' ) => void; /** * @memberof Duck.Types.Game.Config * @description Scale of the canvas, the size of the canvas * @type Duck.Types.Misc.Scale * @since 1.0.0-beta */ scale?: Misc.Scale; /** * @memberof Duck.Types.Game.Config * @description Determines if DuckEngine logs out events that are occurring * @type boolean * @since 1.0.0-beta */ debug?: boolean; /** * @memberof Duck.Types.Game.Config * @description Determines if DuckEngine silences/prevents pauseRenderingOnBlur, onPauseRendering, and onResumeRendering configurations * @type boolean * @since 2.0.0 */ debugRendering?: boolean; /** * @memberof Duck.Types.Game.Config * @description Custom splash screen options, shows while the game is starting/loading, default img: https://i.ibb.co/bdN4CCN/Logo-Splash.png * default extraDuration: 500 * @type { img: string | 'default'; extraDuration?: number; } * @since 2.0.0 */ splashScreen?: { img?: string | 'default'; extraDuration?: number; }; /** * @memberof Duck.Types.Game.Config * @description CSS background color of the canvas (hint: to fill a scene with a background color, use scene.add.misc.canvasModulate) * @type string * @since 1.0.0-beta */ background?: string; /** * @memberof Duck.Types.Game.Config * @description Determines if the canvas is scaled down to the window size if the window size is smaller than the canvas * @type boolean * @since 1.0.0 */ smartScale?: boolean; /** * @memberof Duck.Types.Game.Config * @description Uses the device pixel ratio to scale the canvas accordingly * @type boolean * @since 1.0.0 */ dprScale?: boolean; } export interface Stack { scenes: SceneClass[]; defaultScene: string; } export interface Plugin { func: (...args: unknown[]) => unknown; args: unknown[]; name: string; } } export namespace Misc { export interface Scale { width?: number; height?: number; } } export namespace Collider { export type ShapeString = | 'rect' | 'circle' | 'roundrect' | 'sprite'; export type CollisionResponseType = | 'none' | 'top' | 'left' | 'right' | 'bottom'; } export namespace Sound { export interface Sprite { startSeconds: number; endSeconds: number; key: string; } export interface Config { autoplay?: Helper.DefaultValue<undefined, false>; volume?: Helper.DefaultValue<undefined, number>; sprites?: Helper.DefaultValue<undefined, Sprite[]>; } } export namespace GamepadInput { export type MappingType = 'Xbox' | 'Playstation'; export type Mapping = | typeof XboxMapping | typeof PlaystationMapping; export enum XboxMapping { A = 0, B = 1, X = 2, Y = 3, LB = 4, RB = 5, LT = 6, RT = 7, SHOW_ADDRESS_BAR = 8, SHOW_MENU = 9, LEFT_STICK_PRESS = 10, RIGHT_STICK_PRESS = 11, D_PAD_UP = 12, D_PAD_DOWN = 13, D_PAD_LEFT = 14, D_PAD_RIGHT = 15, LOGO = 16, } export enum PlaystationMapping { X = 0, CIRCLE = 1, SQUARE = 2, TRIANGLE = 3, L1 = 4, R1 = 5, L2 = 6, R2 = 7, SHARE = 8, OPTIONS = 9, LEFT_STICK_PRESS = 10, RIGHT_STICK_PRESS = 11, D_PAD_UP = 12, D_PAD_DOWN = 13, D_PAD_LEFT = 14, D_PAD_RIGHT = 15, LOGO = 16, } } export namespace Interactive { export namespace Text { export interface Config { x: number; y: number; method: 'draw' | 'stroke' | 'draw-stroke'; styles: { fontCSS: string; strokeWidth?: number; strokeColor?: string; fillColor?: string; maxWidth?: number; }; } } export namespace Button { export type Shape = 'rect' | 'roundrect' | 'sprite'; export type ListenerType = 'CLICK' | 'HOVER' | 'NOTHOVER'; export interface ListenerReturn { x: number; y: number; type: ListenerType; } export type ListenerFunc = (e: ListenerReturn) => void; export interface Listener { type: ListenerType; func: ListenerFunc; } } } export namespace Group { export type StackItem = | GameObject<Duck.Types.Texture.Type> | PhysicsBodyClass<Duck.Types.Texture.Type> | CameraClass | TextClass | StaticLightClass | ColliderClass | HitboxClass; export type Filter = | 'gameobject' | 'lights' | 'interactive' | 'physics' | 'cameras'; export type ListenerType = 'ADD' | 'REMOVE'; export interface Listener { func: (item: StackItem) => unknown; type: ListenerType; } } export namespace ParticleEmitter { export type Range = Helper.FixedLengthArray<[number, number]>; export interface Offloaders { maxAmount: () => void; maxAge: () => void; maxBounds: () => void; } } export namespace Cutscene { export type OnListenerType = 'END' | 'START' | 'NEXT'; export interface OnListener { type: OnListenerType; func: Function; } export type StepType = | 'MOVE' | 'DRAW' | 'FUNC' | 'CAMERA_ZOOM' | 'CAMERA_FOV' | 'CAMERA_MOVE' | 'CAMERA_SHAKE' | 'CAMERA_START_FOLLOW' | 'CAMERA_STOP_FOLLOW'; export interface Step { type: StepType; affect?: GameObject<Duck.Types.Texture.Type> | CameraClass; moveTo?: { x?: number; y?: number; }; func?: Function; cameraValue?: number; cameraIntervalMS?: number; cameraTimeMS?: number; sleepValue?: number; cameraFollow?: GameObject<Duck.Types.Texture.Type>; cameraFollowLerpX?: number; cameraFollowLerpY?: number; } export interface Instructions { init: { mainObjectPos: { x: number; y: number; }; otherObjectPos: { x: number; y: number; }[]; cameraSettings?: { FOV: number; follow?: GameObject<Duck.Types.Texture.Type>; zoom: number; pos?: { x: number; y: number; }; followLerpX: number; followLerpY: number; }; otherCameraSettings?: { FOV: number; follow?: GameObject<Duck.Types.Texture.Type>; zoom: number; pos?: { x: number; y: number; }; followLerpX: number; followLerpY: number; }[]; }; steps: Step[]; } export interface Config { mainCamera: CameraClass; otherCameras?: CameraClass[]; otherObjects?: GameObject<Duck.Types.Texture.Type>[]; mainObject: GameObject<Duck.Types.Texture.Type>; } } export namespace Tilemap { export type Map = number[][]; export interface Atlas { [key: number]: HTMLImageElement | string; } } export namespace ParticleContainer { export interface Bounds { position: { x: number; y: number; }; w: number; h: number; } export interface Physics { bounciness: number; } } export namespace Raycast { export interface State { colliding: StateValue | false; collidingTop: StateValue | false; collidingBottom: StateValue | false; collidingLeft: StateValue | false; collidingRight: StateValue | false; } export interface StateValue { with: GameObject<Duck.Types.Texture.Type>; } } export namespace Loader { export type StackItemType = | 'texture' | 'json' | 'font' | 'html' | 'xml' | 'audio'; export interface StackItem<t> { type: StackItemType; value: t; key: string; } } export namespace Texture { export type Type = 'image' | 'color' | 'either'; } export namespace PhysicsBody { export type Type = RigidBody | StaticBody | KinematicBody; export interface Config { type: Type; } export interface AttachedBody { body: PhysicsBodyClass<Duck.Types.Texture.Type>; offset: Vector2Class; } /** * @memberof Duck.Types.PhysicsBody.KinematicBody * @description A type of PhysicsBody that can be moved and can be effected by gravity and friction. * @since 2.0.0 */ export type KinematicBody = 'KinematicBody'; /** * @memberof Duck.Types.PhysicsBody.KinematicBody * @description A type of PhysicsBody that cannot be moved but can be effected by gravity and friction. * @since 2.0.0 */ export type RigidBody = 'RigidBody'; /** * @memberof Duck.Types.PhysicsBody.KinematicBody * @description A type of PhysicsBody that cannot be moved and cannot be effected by gravity and friction. * @since 2.0.0 */ export type StaticBody = 'StaticBody'; } export namespace Animation { export interface Config { /** * @memberof Duck.Types.Animation.Config * @description Key / Name of Animation * @type string * @since 2.0.0 */ key: string; /** * @memberof Duck.Types.Animation.Config * @description Frames of the Animation, objects that are later converted to AnimationFrame * @type Duck.Types.Animation.FrameBase[] * @since 2.0.0 */ frames: FrameBase[]; /** * @memberof Duck.Types.Animation.Config * @description The frame rate of the animation * @type number * @since 2.0.0 */ frameRate: number; /** * @memberof Duck.Types.Animation.Config * @description Determines the amount of times the Animation loops, optional -> defaults: 1 * @type number * @since 2.0.0 */ repeat?: number; /** * @memberof Duck.Types.Animation.Config * @description Determines if the animation plays in the opposite direction of its current direction and switches on end, like a yoyo * optional -> defaults: false * @type boolean * @since 2.0.0 */ yoyo?: boolean; /** * @memberof Duck.Types.Animation.Config * @description The amount of milliseconds that is waited for before playing the animation, optional -> defaults: 0 * @type number * @since 2.0.0 */ delay?: number; /** * @memberof Duck.Types.Animation.Config * @description Determines if the Animation timers count by the Game.deltaTime, set to true if used in the Scene.update method, and false * otherwise, optional -> defaults: false * @type boolean * @since 2.0.0 */ useDelta?: boolean; } export interface FrameBase { col: number; row: number; } } export namespace StateMachine { export interface ConnectionBase { from: ConnectionBaseValue; to: ConnectionBaseValue; connType: 'one' | 'loop'; } export interface ConnectionBaseValue { key: string; vector: Vector2Class; autoAdvance?: boolean; } export interface Config { defaultState: string; connections: ConnectionBase[]; } } export namespace KeyboardInput { export interface KeyBase { keyCode: number; descriptor: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any keyDown?: (e: KeyboardEvent) => any; // eslint-disable-next-line @typescript-eslint/no-explicit-any keyUp?: (e: KeyboardEvent) => any; // eslint-disable-next-line @typescript-eslint/no-explicit-any keyJustPressed?: (e: KeyboardEvent) => any; // eslint-disable-next-line @typescript-eslint/no-explicit-any keyState?: (e: KeyboardEvent) => any; } } export namespace MouseInput { export interface MouseBase { button: 0 | 1 | 2 | 3 | 4; descriptor: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any mouseDown?: (e: MouseEvent) => any; // eslint-disable-next-line @typescript-eslint/no-explicit-any mouseUp?: (e: MouseEvent) => any; // eslint-disable-next-line @typescript-eslint/no-explicit-any mouseMove?: (e: MouseEvent) => any; } } export namespace Math { export interface Vector2Like { x: number; y: number; } export interface Vector2LikeOptional { x?: number; y?: number; } export interface BoundsLike extends Vector2Like { w: number; h: number; } } export namespace Helper { type ArrayLengthMutationKeys = | 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number; type ArrayItems<T extends Array<unknown>> = T extends Array< infer TItems > ? TItems : never; export type FixedLengthArray<T extends unknown[]> = Pick< T, Exclude<keyof T, ArrayLengthMutationKeys> > & { [Symbol.iterator]: () => IterableIterator<ArrayItems<T>> }; export type NonNullable<T> = T extends null | undefined ? never : T; export type DefaultValue< Type, Default, ExtraRule = null > = Type extends null | undefined | false | 0 | ExtraRule | '' ? Default : Type; //#region Long Type export type AlphaRange = | 0 | 0.01 | 0.02 | 0.03 | 0.04 | 0.05 | 0.06 | 0.07 | 0.08 | 0.09 | 0.1 | 0.11 | 0.12 | 0.13 | 0.14 | 0.15 | 0.16 | 0.17 | 0.18 | 0.19 | 0.2 | 0.21 | 0.22 | 0.23 | 0.24 | 0.25 | 0.26 | 0.27 | 0.28 | 0.29 | 0.3 | 0.31 | 0.32 | 0.33 | 0.34 | 0.35 | 0.36 | 0.37 | 0.38 | 0.39 | 0.4 | 0.41 | 0.42 | 0.43 | 0.44 | 0.45 | 0.46 | 0.47 | 0.48 | 0.49 | 0.5 | 0.51 | 0.52 | 0.53 | 0.54 | 0.55 | 0.56 | 0.57 | 0.58 | 0.59 | 0.6 | 0.61 | 0.62 | 0.63 | 0.64 | 0.65 | 0.66 | 0.67 | 0.68 | 0.69 | 0.7 | 0.71 | 0.72 | 0.73 | 0.74 | 0.75 | 0.76 | 0.77 | 0.78 | 0.79 | 0.8 | 0.81 | 0.82 | 0.83 | 0.84 | 0.85 | 0.86 | 0.87 | 0.88 | 0.89 | 0.9 | 0.91 | 0.92 | 0.93 | 0.94 | 0.95 | 0.96 | 0.97 | 0.98 | 0.99 | 1; //#endregion Long Type } } } // export /** * @namespace * @property {Game} game Game Class * @property {Scene} scene Scene Class * @description Main Export of DuckEngine * @since 1.0.0-beta */ const DuckEngine = { Game: GameClass, Scene: SceneClass, }; export default DuckEngine;
the_stack
import { ServiceType } from "@protobuf-ts/runtime-rpc"; import { WireType } from "@protobuf-ts/runtime"; import type { BinaryWriteOptions } from "@protobuf-ts/runtime"; import type { IBinaryWriter } from "@protobuf-ts/runtime"; import { UnknownFieldHandler } from "@protobuf-ts/runtime"; import type { BinaryReadOptions } from "@protobuf-ts/runtime"; import type { IBinaryReader } from "@protobuf-ts/runtime"; import type { PartialMessage } from "@protobuf-ts/runtime"; import { reflectionMergePartial } from "@protobuf-ts/runtime"; import { MESSAGE_TYPE } from "@protobuf-ts/runtime"; import { MessageType } from "@protobuf-ts/runtime"; import { Line } from "../../metastore/v1alpha1/metastore"; import { Function } from "../../metastore/v1alpha1/metastore"; import { Mapping } from "../../metastore/v1alpha1/metastore"; import { Location } from "../../metastore/v1alpha1/metastore"; import { LabelSet } from "../../profilestore/v1alpha1/profilestore"; import { Timestamp } from "../../../google/protobuf/timestamp"; /** * ProfileTypesRequest is the request to retrieve the list of available profile types. * * @generated from protobuf message parca.query.v1alpha1.ProfileTypesRequest */ export interface ProfileTypesRequest { } /** * ProfileTypesResponse is the response to retrieve the list of available profile types. * * @generated from protobuf message parca.query.v1alpha1.ProfileTypesResponse */ export interface ProfileTypesResponse { /** * types is the list of available profile types. * * @generated from protobuf field: repeated parca.query.v1alpha1.ProfileType types = 1; */ types: ProfileType[]; } /** * ProfileType is the type of a profile as well as the units the profile type is available in. * * @generated from protobuf message parca.query.v1alpha1.ProfileType */ export interface ProfileType { /** * name is the name of the profile type. * * @generated from protobuf field: string name = 1; */ name: string; /** * sample_type is the type of the samples in the profile. * * @generated from protobuf field: string sample_type = 2; */ sampleType: string; /** * sample_unit is the unit of the samples in the profile. * * @generated from protobuf field: string sample_unit = 3; */ sampleUnit: string; /** * period_type is the type of the periods in the profile. * * @generated from protobuf field: string period_type = 4; */ periodType: string; /** * period_unit is the unit of the periods in the profile. * * @generated from protobuf field: string period_unit = 5; */ periodUnit: string; /** * delta describes whether the profile is a delta profile. * * @generated from protobuf field: bool delta = 6; */ delta: boolean; } /** * QueryRangeRequest is the request for a set of profiles matching a query over a time window * * @generated from protobuf message parca.query.v1alpha1.QueryRangeRequest */ export interface QueryRangeRequest { /** * query is the query string to match profiles against * * @generated from protobuf field: string query = 1; */ query: string; /** * start is the start of the query time window * * @generated from protobuf field: google.protobuf.Timestamp start = 2; */ start?: Timestamp; /** * end is the end of the query time window * * @generated from protobuf field: google.protobuf.Timestamp end = 3; */ end?: Timestamp; /** * limit is the max number of profiles to include in the response * * @generated from protobuf field: uint32 limit = 4; */ limit: number; } /** * QueryRangeResponse is the set of matching profile values * * @generated from protobuf message parca.query.v1alpha1.QueryRangeResponse */ export interface QueryRangeResponse { /** * series is the set of metrics series that satisfy the query range request * * @generated from protobuf field: repeated parca.query.v1alpha1.MetricsSeries series = 1; */ series: MetricsSeries[]; } /** * MetricsSeries is a set of labels and corresponding sample values * * @generated from protobuf message parca.query.v1alpha1.MetricsSeries */ export interface MetricsSeries { /** * labelset is the set of key value pairs * * @generated from protobuf field: parca.profilestore.v1alpha1.LabelSet labelset = 1; */ labelset?: LabelSet; /** * samples is the set of top-level cumulative values of the corresponding profiles * * @generated from protobuf field: repeated parca.query.v1alpha1.MetricsSample samples = 2; */ samples: MetricsSample[]; /** * period_type is the value type of profile period * * @generated from protobuf field: parca.query.v1alpha1.ValueType period_type = 3; */ periodType?: ValueType; /** * sample_type is the value type of profile sample * * @generated from protobuf field: parca.query.v1alpha1.ValueType sample_type = 4; */ sampleType?: ValueType; } /** * MetricsSample is a cumulative value and timestamp of a profile * * @generated from protobuf message parca.query.v1alpha1.MetricsSample */ export interface MetricsSample { /** * timestamp is the time the profile was ingested * * @generated from protobuf field: google.protobuf.Timestamp timestamp = 1; */ timestamp?: Timestamp; /** * value is the cumulative value for the profile * * @generated from protobuf field: int64 value = 2; */ value: string; } /** * MergeProfile contains parameters for a merge request * * @generated from protobuf message parca.query.v1alpha1.MergeProfile */ export interface MergeProfile { /** * query is the query string to match profiles for merge * * @generated from protobuf field: string query = 1; */ query: string; /** * start is the beginning of the evaluation time window * * @generated from protobuf field: google.protobuf.Timestamp start = 2; */ start?: Timestamp; /** * end is the end of the evaluation time window * * @generated from protobuf field: google.protobuf.Timestamp end = 3; */ end?: Timestamp; } /** * SingleProfile contains parameters for a single profile query request * * @generated from protobuf message parca.query.v1alpha1.SingleProfile */ export interface SingleProfile { /** * time is the point in time to perform the profile request * * @generated from protobuf field: google.protobuf.Timestamp time = 1; */ time?: Timestamp; /** * query is the query string to retrieve the profile * * @generated from protobuf field: string query = 2; */ query: string; } /** * DiffProfile contains parameters for a profile diff request * * @generated from protobuf message parca.query.v1alpha1.DiffProfile */ export interface DiffProfile { /** * a is the first profile to diff * * @generated from protobuf field: parca.query.v1alpha1.ProfileDiffSelection a = 1; */ a?: ProfileDiffSelection; /** * b is the second profile to diff * * @generated from protobuf field: parca.query.v1alpha1.ProfileDiffSelection b = 2; */ b?: ProfileDiffSelection; } /** * ProfileDiffSelection contains the parameters of a diff selection * * @generated from protobuf message parca.query.v1alpha1.ProfileDiffSelection */ export interface ProfileDiffSelection { /** * mode is the selection of the diff mode * * @generated from protobuf field: parca.query.v1alpha1.ProfileDiffSelection.Mode mode = 1; */ mode: ProfileDiffSelection_Mode; /** * @generated from protobuf oneof: options */ options: { oneofKind: "merge"; /** * merge contains options for a merge request * * @generated from protobuf field: parca.query.v1alpha1.MergeProfile merge = 2; */ merge: MergeProfile; } | { oneofKind: "single"; /** * single contains options for a single profile request * * @generated from protobuf field: parca.query.v1alpha1.SingleProfile single = 3; */ single: SingleProfile; } | { oneofKind: undefined; }; } /** * Mode specifies the type of diff * * @generated from protobuf enum parca.query.v1alpha1.ProfileDiffSelection.Mode */ export enum ProfileDiffSelection_Mode { /** * MODE_SINGLE_UNSPECIFIED default unspecified * * @generated from protobuf enum value: MODE_SINGLE_UNSPECIFIED = 0; */ SINGLE_UNSPECIFIED = 0, /** * MODE_MERGE merge profile * * @generated from protobuf enum value: MODE_MERGE = 1; */ MERGE = 1 } /** * QueryRequest is a request for a profile query * * @generated from protobuf message parca.query.v1alpha1.QueryRequest */ export interface QueryRequest { /** * mode indicates the type of query performed * * @generated from protobuf field: parca.query.v1alpha1.QueryRequest.Mode mode = 1; */ mode: QueryRequest_Mode; /** * @generated from protobuf oneof: options */ options: { oneofKind: "diff"; /** * diff contains the diff query options * * @generated from protobuf field: parca.query.v1alpha1.DiffProfile diff = 2; */ diff: DiffProfile; } | { oneofKind: "merge"; /** * merge contains the merge query options * * @generated from protobuf field: parca.query.v1alpha1.MergeProfile merge = 3; */ merge: MergeProfile; } | { oneofKind: "single"; /** * single contains the single query options * * @generated from protobuf field: parca.query.v1alpha1.SingleProfile single = 4; */ single: SingleProfile; } | { oneofKind: undefined; }; /** * report_type is the type of report to return * * @generated from protobuf field: parca.query.v1alpha1.QueryRequest.ReportType report_type = 5; */ reportType: QueryRequest_ReportType; } /** * Mode is the type of query request * * @generated from protobuf enum parca.query.v1alpha1.QueryRequest.Mode */ export enum QueryRequest_Mode { /** * MODE_SINGLE_UNSPECIFIED query unspecified * * @generated from protobuf enum value: MODE_SINGLE_UNSPECIFIED = 0; */ SINGLE_UNSPECIFIED = 0, /** * MODE_DIFF is a diff query * * @generated from protobuf enum value: MODE_DIFF = 1; */ DIFF = 1, /** * MODE_MERGE is a merge query * * @generated from protobuf enum value: MODE_MERGE = 2; */ MERGE = 2 } /** * ReportType is the type of report to return * * @generated from protobuf enum parca.query.v1alpha1.QueryRequest.ReportType */ export enum QueryRequest_ReportType { /** * REPORT_TYPE_FLAMEGRAPH_UNSPECIFIED unspecified * * @generated from protobuf enum value: REPORT_TYPE_FLAMEGRAPH_UNSPECIFIED = 0; */ FLAMEGRAPH_UNSPECIFIED = 0, /** * REPORT_TYPE_PPROF unspecified * * @generated from protobuf enum value: REPORT_TYPE_PPROF = 1; */ PPROF = 1, /** * REPORT_TYPE_TOP unspecified * * @generated from protobuf enum value: REPORT_TYPE_TOP = 2; */ TOP = 2 } /** * Top is the top report type * * @generated from protobuf message parca.query.v1alpha1.Top */ export interface Top { /** * list are the list of ordered elements of the table * * @generated from protobuf field: repeated parca.query.v1alpha1.TopNode list = 1; */ list: TopNode[]; /** * reported is the number of lines reported * * @generated from protobuf field: int32 reported = 2; */ reported: number; /** * total is the number of lines that exist in the report * * @generated from protobuf field: int32 total = 3; */ total: number; /** * unit is the unit represented by top table * * @generated from protobuf field: string unit = 4; */ unit: string; } /** * TopNode is a node entry in a top list * * @generated from protobuf message parca.query.v1alpha1.TopNode */ export interface TopNode { /** * meta is the metadata about the node * * @generated from protobuf field: parca.query.v1alpha1.TopNodeMeta meta = 1; */ meta?: TopNodeMeta; /** * cumulative is the cumulative value of the node * * @generated from protobuf field: int64 cumulative = 2; */ cumulative: string; /** * flat is the flat value of the node * * @generated from protobuf field: int64 flat = 3; */ flat: string; /** * diff is the diff value between two profiles * * @generated from protobuf field: int64 diff = 4; */ diff: string; } /** * TopNodeMeta is the metadata for a given node * * @generated from protobuf message parca.query.v1alpha1.TopNodeMeta */ export interface TopNodeMeta { /** * location is the location for the code * * @generated from protobuf field: parca.metastore.v1alpha1.Location location = 1; */ location?: Location; /** * mapping is the mapping into code * * @generated from protobuf field: parca.metastore.v1alpha1.Mapping mapping = 2; */ mapping?: Mapping; /** * function is the function information * * @generated from protobuf field: parca.metastore.v1alpha1.Function function = 3; */ function?: Function; /** * line is the line location * * @generated from protobuf field: parca.metastore.v1alpha1.Line line = 4; */ line?: Line; } /** * Flamegraph is the flame graph report type * * @generated from protobuf message parca.query.v1alpha1.Flamegraph */ export interface Flamegraph { /** * root is the root of the flame graph * * @generated from protobuf field: parca.query.v1alpha1.FlamegraphRootNode root = 1; */ root?: FlamegraphRootNode; /** * total is the total weight of the flame graph * * @generated from protobuf field: int64 total = 2; */ total: string; /** * unit is the unit represented by the flame graph * * @generated from protobuf field: string unit = 3; */ unit: string; /** * height is the max height of the graph * * @generated from protobuf field: int32 height = 4; */ height: number; } /** * FlamegraphRootNode is a root node of a flame graph * * @generated from protobuf message parca.query.v1alpha1.FlamegraphRootNode */ export interface FlamegraphRootNode { /** * cumulative is the cumulative value of the graph * * @generated from protobuf field: int64 cumulative = 1; */ cumulative: string; /** * diff is the diff * * @generated from protobuf field: int64 diff = 2; */ diff: string; /** * children are the list of the children of the root node * * @generated from protobuf field: repeated parca.query.v1alpha1.FlamegraphNode children = 3; */ children: FlamegraphNode[]; } /** * FlamegraphNode represents a node in the graph * * @generated from protobuf message parca.query.v1alpha1.FlamegraphNode */ export interface FlamegraphNode { /** * meta is the metadata about the node * * @generated from protobuf field: parca.query.v1alpha1.FlamegraphNodeMeta meta = 1; */ meta?: FlamegraphNodeMeta; /** * cumulative is the cumulative value of the node * * @generated from protobuf field: int64 cumulative = 2; */ cumulative: string; /** * diff is the diff * * @generated from protobuf field: int64 diff = 3; */ diff: string; /** * children are the child nodes * * @generated from protobuf field: repeated parca.query.v1alpha1.FlamegraphNode children = 4; */ children: FlamegraphNode[]; } /** * FlamegraphNodeMeta is the metadata for a given node * * @generated from protobuf message parca.query.v1alpha1.FlamegraphNodeMeta */ export interface FlamegraphNodeMeta { /** * location is the location for the code * * @generated from protobuf field: parca.metastore.v1alpha1.Location location = 1; */ location?: Location; /** * mapping is the mapping into code * * @generated from protobuf field: parca.metastore.v1alpha1.Mapping mapping = 2; */ mapping?: Mapping; /** * function is the function information * * @generated from protobuf field: parca.metastore.v1alpha1.Function function = 3; */ function?: Function; /** * line is the line location * * @generated from protobuf field: parca.metastore.v1alpha1.Line line = 4; */ line?: Line; } /** * QueryResponse is the returned report for the given query * * @generated from protobuf message parca.query.v1alpha1.QueryResponse */ export interface QueryResponse { /** * @generated from protobuf oneof: report */ report: { oneofKind: "flamegraph"; /** * flamegraph is a flamegraph representation of the report * * @generated from protobuf field: parca.query.v1alpha1.Flamegraph flamegraph = 5; */ flamegraph: Flamegraph; } | { oneofKind: "pprof"; /** * pprof is a pprof profile as compressed bytes * * @generated from protobuf field: bytes pprof = 6; */ pprof: Uint8Array; } | { oneofKind: "top"; /** * top is a top list representation of the report * * @generated from protobuf field: parca.query.v1alpha1.Top top = 7; */ top: Top; } | { oneofKind: undefined; }; } /** * SeriesRequest is unimplemented * * @generated from protobuf message parca.query.v1alpha1.SeriesRequest */ export interface SeriesRequest { /** * match ... * * @generated from protobuf field: repeated string match = 1; */ match: string[]; /** * start ... * * @generated from protobuf field: google.protobuf.Timestamp start = 2; */ start?: Timestamp; /** * end ... * * @generated from protobuf field: google.protobuf.Timestamp end = 3; */ end?: Timestamp; } /** * SeriesResponse is unimplemented * * @generated from protobuf message parca.query.v1alpha1.SeriesResponse */ export interface SeriesResponse { } /** * LabelsRequest are the request values for labels * * @generated from protobuf message parca.query.v1alpha1.LabelsRequest */ export interface LabelsRequest { /** * match are the set of matching strings * * @generated from protobuf field: repeated string match = 1; */ match: string[]; /** * start is the start of the time window to perform the query * * @generated from protobuf field: google.protobuf.Timestamp start = 2; */ start?: Timestamp; /** * end is the end of the time window to perform the query * * @generated from protobuf field: google.protobuf.Timestamp end = 3; */ end?: Timestamp; } /** * LabelsResponse is the set of matching label names * * @generated from protobuf message parca.query.v1alpha1.LabelsResponse */ export interface LabelsResponse { /** * / label_names are the set of matching label names * * @generated from protobuf field: repeated string label_names = 1; */ labelNames: string[]; /** * warnings is unimplemented * * @generated from protobuf field: repeated string warnings = 2; */ warnings: string[]; } /** * ValuesRequest are the request values for a values request * * @generated from protobuf message parca.query.v1alpha1.ValuesRequest */ export interface ValuesRequest { /** * label_name is the label name to match values against * * @generated from protobuf field: string label_name = 1; */ labelName: string; /** * match are the set of matching strings to match values against * * @generated from protobuf field: repeated string match = 2; */ match: string[]; /** * start is the start of the time window to perform the query * * @generated from protobuf field: google.protobuf.Timestamp start = 3; */ start?: Timestamp; /** * end is the end of the time window to perform the query * * @generated from protobuf field: google.protobuf.Timestamp end = 4; */ end?: Timestamp; } /** * ValuesResponse are the set of matching values * * @generated from protobuf message parca.query.v1alpha1.ValuesResponse */ export interface ValuesResponse { /** * label_values are the set of matching label values * * @generated from protobuf field: repeated string label_values = 1; */ labelValues: string[]; /** * warnings is unimplemented * * @generated from protobuf field: repeated string warnings = 2; */ warnings: string[]; } /** * ValueType represents a value, including its type and unit * * @generated from protobuf message parca.query.v1alpha1.ValueType */ export interface ValueType { /** * type is the type of the value * * @generated from protobuf field: string type = 1; */ type: string; /** * unit is the unit of the value * * @generated from protobuf field: string unit = 2; */ unit: string; } // @generated message type with reflection information, may provide speed optimized methods class ProfileTypesRequest$Type extends MessageType<ProfileTypesRequest> { constructor() { super("parca.query.v1alpha1.ProfileTypesRequest", []); } create(value?: PartialMessage<ProfileTypesRequest>): ProfileTypesRequest { const message = {}; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<ProfileTypesRequest>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ProfileTypesRequest): ProfileTypesRequest { return target ?? this.create(); } internalBinaryWrite(message: ProfileTypesRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.ProfileTypesRequest */ export const ProfileTypesRequest = new ProfileTypesRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class ProfileTypesResponse$Type extends MessageType<ProfileTypesResponse> { constructor() { super("parca.query.v1alpha1.ProfileTypesResponse", [ { no: 1, name: "types", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => ProfileType } ]); } create(value?: PartialMessage<ProfileTypesResponse>): ProfileTypesResponse { const message = { types: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<ProfileTypesResponse>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ProfileTypesResponse): ProfileTypesResponse { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* repeated parca.query.v1alpha1.ProfileType types */ 1: message.types.push(ProfileType.internalBinaryRead(reader, reader.uint32(), options)); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: ProfileTypesResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* repeated parca.query.v1alpha1.ProfileType types = 1; */ for (let i = 0; i < message.types.length; i++) ProfileType.internalBinaryWrite(message.types[i], writer.tag(1, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.ProfileTypesResponse */ export const ProfileTypesResponse = new ProfileTypesResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class ProfileType$Type extends MessageType<ProfileType> { constructor() { super("parca.query.v1alpha1.ProfileType", [ { no: 1, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "sample_type", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, name: "sample_unit", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 4, name: "period_type", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 5, name: "period_unit", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 6, name: "delta", kind: "scalar", T: 8 /*ScalarType.BOOL*/ } ]); } create(value?: PartialMessage<ProfileType>): ProfileType { const message = { name: "", sampleType: "", sampleUnit: "", periodType: "", periodUnit: "", delta: false }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<ProfileType>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ProfileType): ProfileType { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* string name */ 1: message.name = reader.string(); break; case /* string sample_type */ 2: message.sampleType = reader.string(); break; case /* string sample_unit */ 3: message.sampleUnit = reader.string(); break; case /* string period_type */ 4: message.periodType = reader.string(); break; case /* string period_unit */ 5: message.periodUnit = reader.string(); break; case /* bool delta */ 6: message.delta = reader.bool(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: ProfileType, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* string name = 1; */ if (message.name !== "") writer.tag(1, WireType.LengthDelimited).string(message.name); /* string sample_type = 2; */ if (message.sampleType !== "") writer.tag(2, WireType.LengthDelimited).string(message.sampleType); /* string sample_unit = 3; */ if (message.sampleUnit !== "") writer.tag(3, WireType.LengthDelimited).string(message.sampleUnit); /* string period_type = 4; */ if (message.periodType !== "") writer.tag(4, WireType.LengthDelimited).string(message.periodType); /* string period_unit = 5; */ if (message.periodUnit !== "") writer.tag(5, WireType.LengthDelimited).string(message.periodUnit); /* bool delta = 6; */ if (message.delta !== false) writer.tag(6, WireType.Varint).bool(message.delta); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.ProfileType */ export const ProfileType = new ProfileType$Type(); // @generated message type with reflection information, may provide speed optimized methods class QueryRangeRequest$Type extends MessageType<QueryRangeRequest> { constructor() { super("parca.query.v1alpha1.QueryRangeRequest", [ { no: 1, name: "query", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "start", kind: "message", T: () => Timestamp }, { no: 3, name: "end", kind: "message", T: () => Timestamp }, { no: 4, name: "limit", kind: "scalar", T: 13 /*ScalarType.UINT32*/ } ]); } create(value?: PartialMessage<QueryRangeRequest>): QueryRangeRequest { const message = { query: "", limit: 0 }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<QueryRangeRequest>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: QueryRangeRequest): QueryRangeRequest { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* string query */ 1: message.query = reader.string(); break; case /* google.protobuf.Timestamp start */ 2: message.start = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.start); break; case /* google.protobuf.Timestamp end */ 3: message.end = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.end); break; case /* uint32 limit */ 4: message.limit = reader.uint32(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: QueryRangeRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* string query = 1; */ if (message.query !== "") writer.tag(1, WireType.LengthDelimited).string(message.query); /* google.protobuf.Timestamp start = 2; */ if (message.start) Timestamp.internalBinaryWrite(message.start, writer.tag(2, WireType.LengthDelimited).fork(), options).join(); /* google.protobuf.Timestamp end = 3; */ if (message.end) Timestamp.internalBinaryWrite(message.end, writer.tag(3, WireType.LengthDelimited).fork(), options).join(); /* uint32 limit = 4; */ if (message.limit !== 0) writer.tag(4, WireType.Varint).uint32(message.limit); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.QueryRangeRequest */ export const QueryRangeRequest = new QueryRangeRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class QueryRangeResponse$Type extends MessageType<QueryRangeResponse> { constructor() { super("parca.query.v1alpha1.QueryRangeResponse", [ { no: 1, name: "series", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => MetricsSeries } ]); } create(value?: PartialMessage<QueryRangeResponse>): QueryRangeResponse { const message = { series: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<QueryRangeResponse>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: QueryRangeResponse): QueryRangeResponse { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* repeated parca.query.v1alpha1.MetricsSeries series */ 1: message.series.push(MetricsSeries.internalBinaryRead(reader, reader.uint32(), options)); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: QueryRangeResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* repeated parca.query.v1alpha1.MetricsSeries series = 1; */ for (let i = 0; i < message.series.length; i++) MetricsSeries.internalBinaryWrite(message.series[i], writer.tag(1, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.QueryRangeResponse */ export const QueryRangeResponse = new QueryRangeResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class MetricsSeries$Type extends MessageType<MetricsSeries> { constructor() { super("parca.query.v1alpha1.MetricsSeries", [ { no: 1, name: "labelset", kind: "message", T: () => LabelSet }, { no: 2, name: "samples", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => MetricsSample }, { no: 3, name: "period_type", kind: "message", T: () => ValueType }, { no: 4, name: "sample_type", kind: "message", T: () => ValueType } ]); } create(value?: PartialMessage<MetricsSeries>): MetricsSeries { const message = { samples: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<MetricsSeries>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: MetricsSeries): MetricsSeries { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.profilestore.v1alpha1.LabelSet labelset */ 1: message.labelset = LabelSet.internalBinaryRead(reader, reader.uint32(), options, message.labelset); break; case /* repeated parca.query.v1alpha1.MetricsSample samples */ 2: message.samples.push(MetricsSample.internalBinaryRead(reader, reader.uint32(), options)); break; case /* parca.query.v1alpha1.ValueType period_type */ 3: message.periodType = ValueType.internalBinaryRead(reader, reader.uint32(), options, message.periodType); break; case /* parca.query.v1alpha1.ValueType sample_type */ 4: message.sampleType = ValueType.internalBinaryRead(reader, reader.uint32(), options, message.sampleType); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: MetricsSeries, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.profilestore.v1alpha1.LabelSet labelset = 1; */ if (message.labelset) LabelSet.internalBinaryWrite(message.labelset, writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* repeated parca.query.v1alpha1.MetricsSample samples = 2; */ for (let i = 0; i < message.samples.length; i++) MetricsSample.internalBinaryWrite(message.samples[i], writer.tag(2, WireType.LengthDelimited).fork(), options).join(); /* parca.query.v1alpha1.ValueType period_type = 3; */ if (message.periodType) ValueType.internalBinaryWrite(message.periodType, writer.tag(3, WireType.LengthDelimited).fork(), options).join(); /* parca.query.v1alpha1.ValueType sample_type = 4; */ if (message.sampleType) ValueType.internalBinaryWrite(message.sampleType, writer.tag(4, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.MetricsSeries */ export const MetricsSeries = new MetricsSeries$Type(); // @generated message type with reflection information, may provide speed optimized methods class MetricsSample$Type extends MessageType<MetricsSample> { constructor() { super("parca.query.v1alpha1.MetricsSample", [ { no: 1, name: "timestamp", kind: "message", T: () => Timestamp }, { no: 2, name: "value", kind: "scalar", T: 3 /*ScalarType.INT64*/ } ]); } create(value?: PartialMessage<MetricsSample>): MetricsSample { const message = { value: "0" }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<MetricsSample>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: MetricsSample): MetricsSample { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* google.protobuf.Timestamp timestamp */ 1: message.timestamp = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.timestamp); break; case /* int64 value */ 2: message.value = reader.int64().toString(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: MetricsSample, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* google.protobuf.Timestamp timestamp = 1; */ if (message.timestamp) Timestamp.internalBinaryWrite(message.timestamp, writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* int64 value = 2; */ if (message.value !== "0") writer.tag(2, WireType.Varint).int64(message.value); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.MetricsSample */ export const MetricsSample = new MetricsSample$Type(); // @generated message type with reflection information, may provide speed optimized methods class MergeProfile$Type extends MessageType<MergeProfile> { constructor() { super("parca.query.v1alpha1.MergeProfile", [ { no: 1, name: "query", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "start", kind: "message", T: () => Timestamp }, { no: 3, name: "end", kind: "message", T: () => Timestamp } ]); } create(value?: PartialMessage<MergeProfile>): MergeProfile { const message = { query: "" }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<MergeProfile>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: MergeProfile): MergeProfile { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* string query */ 1: message.query = reader.string(); break; case /* google.protobuf.Timestamp start */ 2: message.start = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.start); break; case /* google.protobuf.Timestamp end */ 3: message.end = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.end); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: MergeProfile, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* string query = 1; */ if (message.query !== "") writer.tag(1, WireType.LengthDelimited).string(message.query); /* google.protobuf.Timestamp start = 2; */ if (message.start) Timestamp.internalBinaryWrite(message.start, writer.tag(2, WireType.LengthDelimited).fork(), options).join(); /* google.protobuf.Timestamp end = 3; */ if (message.end) Timestamp.internalBinaryWrite(message.end, writer.tag(3, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.MergeProfile */ export const MergeProfile = new MergeProfile$Type(); // @generated message type with reflection information, may provide speed optimized methods class SingleProfile$Type extends MessageType<SingleProfile> { constructor() { super("parca.query.v1alpha1.SingleProfile", [ { no: 1, name: "time", kind: "message", T: () => Timestamp }, { no: 2, name: "query", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value?: PartialMessage<SingleProfile>): SingleProfile { const message = { query: "" }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<SingleProfile>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: SingleProfile): SingleProfile { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* google.protobuf.Timestamp time */ 1: message.time = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.time); break; case /* string query */ 2: message.query = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: SingleProfile, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* google.protobuf.Timestamp time = 1; */ if (message.time) Timestamp.internalBinaryWrite(message.time, writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* string query = 2; */ if (message.query !== "") writer.tag(2, WireType.LengthDelimited).string(message.query); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.SingleProfile */ export const SingleProfile = new SingleProfile$Type(); // @generated message type with reflection information, may provide speed optimized methods class DiffProfile$Type extends MessageType<DiffProfile> { constructor() { super("parca.query.v1alpha1.DiffProfile", [ { no: 1, name: "a", kind: "message", T: () => ProfileDiffSelection }, { no: 2, name: "b", kind: "message", T: () => ProfileDiffSelection } ]); } create(value?: PartialMessage<DiffProfile>): DiffProfile { const message = {}; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<DiffProfile>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: DiffProfile): DiffProfile { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.query.v1alpha1.ProfileDiffSelection a */ 1: message.a = ProfileDiffSelection.internalBinaryRead(reader, reader.uint32(), options, message.a); break; case /* parca.query.v1alpha1.ProfileDiffSelection b */ 2: message.b = ProfileDiffSelection.internalBinaryRead(reader, reader.uint32(), options, message.b); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: DiffProfile, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.query.v1alpha1.ProfileDiffSelection a = 1; */ if (message.a) ProfileDiffSelection.internalBinaryWrite(message.a, writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* parca.query.v1alpha1.ProfileDiffSelection b = 2; */ if (message.b) ProfileDiffSelection.internalBinaryWrite(message.b, writer.tag(2, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.DiffProfile */ export const DiffProfile = new DiffProfile$Type(); // @generated message type with reflection information, may provide speed optimized methods class ProfileDiffSelection$Type extends MessageType<ProfileDiffSelection> { constructor() { super("parca.query.v1alpha1.ProfileDiffSelection", [ { no: 1, name: "mode", kind: "enum", T: () => ["parca.query.v1alpha1.ProfileDiffSelection.Mode", ProfileDiffSelection_Mode, "MODE_"] }, { no: 2, name: "merge", kind: "message", oneof: "options", T: () => MergeProfile }, { no: 3, name: "single", kind: "message", oneof: "options", T: () => SingleProfile } ]); } create(value?: PartialMessage<ProfileDiffSelection>): ProfileDiffSelection { const message = { mode: 0, options: { oneofKind: undefined } }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<ProfileDiffSelection>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ProfileDiffSelection): ProfileDiffSelection { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.query.v1alpha1.ProfileDiffSelection.Mode mode */ 1: message.mode = reader.int32(); break; case /* parca.query.v1alpha1.MergeProfile merge */ 2: message.options = { oneofKind: "merge", merge: MergeProfile.internalBinaryRead(reader, reader.uint32(), options, (message.options as any).merge) }; break; case /* parca.query.v1alpha1.SingleProfile single */ 3: message.options = { oneofKind: "single", single: SingleProfile.internalBinaryRead(reader, reader.uint32(), options, (message.options as any).single) }; break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: ProfileDiffSelection, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.query.v1alpha1.ProfileDiffSelection.Mode mode = 1; */ if (message.mode !== 0) writer.tag(1, WireType.Varint).int32(message.mode); /* parca.query.v1alpha1.MergeProfile merge = 2; */ if (message.options.oneofKind === "merge") MergeProfile.internalBinaryWrite(message.options.merge, writer.tag(2, WireType.LengthDelimited).fork(), options).join(); /* parca.query.v1alpha1.SingleProfile single = 3; */ if (message.options.oneofKind === "single") SingleProfile.internalBinaryWrite(message.options.single, writer.tag(3, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.ProfileDiffSelection */ export const ProfileDiffSelection = new ProfileDiffSelection$Type(); // @generated message type with reflection information, may provide speed optimized methods class QueryRequest$Type extends MessageType<QueryRequest> { constructor() { super("parca.query.v1alpha1.QueryRequest", [ { no: 1, name: "mode", kind: "enum", T: () => ["parca.query.v1alpha1.QueryRequest.Mode", QueryRequest_Mode, "MODE_"] }, { no: 2, name: "diff", kind: "message", oneof: "options", T: () => DiffProfile }, { no: 3, name: "merge", kind: "message", oneof: "options", T: () => MergeProfile }, { no: 4, name: "single", kind: "message", oneof: "options", T: () => SingleProfile }, { no: 5, name: "report_type", kind: "enum", T: () => ["parca.query.v1alpha1.QueryRequest.ReportType", QueryRequest_ReportType, "REPORT_TYPE_"] } ]); } create(value?: PartialMessage<QueryRequest>): QueryRequest { const message = { mode: 0, options: { oneofKind: undefined }, reportType: 0 }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<QueryRequest>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: QueryRequest): QueryRequest { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.query.v1alpha1.QueryRequest.Mode mode */ 1: message.mode = reader.int32(); break; case /* parca.query.v1alpha1.DiffProfile diff */ 2: message.options = { oneofKind: "diff", diff: DiffProfile.internalBinaryRead(reader, reader.uint32(), options, (message.options as any).diff) }; break; case /* parca.query.v1alpha1.MergeProfile merge */ 3: message.options = { oneofKind: "merge", merge: MergeProfile.internalBinaryRead(reader, reader.uint32(), options, (message.options as any).merge) }; break; case /* parca.query.v1alpha1.SingleProfile single */ 4: message.options = { oneofKind: "single", single: SingleProfile.internalBinaryRead(reader, reader.uint32(), options, (message.options as any).single) }; break; case /* parca.query.v1alpha1.QueryRequest.ReportType report_type */ 5: message.reportType = reader.int32(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: QueryRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.query.v1alpha1.QueryRequest.Mode mode = 1; */ if (message.mode !== 0) writer.tag(1, WireType.Varint).int32(message.mode); /* parca.query.v1alpha1.DiffProfile diff = 2; */ if (message.options.oneofKind === "diff") DiffProfile.internalBinaryWrite(message.options.diff, writer.tag(2, WireType.LengthDelimited).fork(), options).join(); /* parca.query.v1alpha1.MergeProfile merge = 3; */ if (message.options.oneofKind === "merge") MergeProfile.internalBinaryWrite(message.options.merge, writer.tag(3, WireType.LengthDelimited).fork(), options).join(); /* parca.query.v1alpha1.SingleProfile single = 4; */ if (message.options.oneofKind === "single") SingleProfile.internalBinaryWrite(message.options.single, writer.tag(4, WireType.LengthDelimited).fork(), options).join(); /* parca.query.v1alpha1.QueryRequest.ReportType report_type = 5; */ if (message.reportType !== 0) writer.tag(5, WireType.Varint).int32(message.reportType); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.QueryRequest */ export const QueryRequest = new QueryRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class Top$Type extends MessageType<Top> { constructor() { super("parca.query.v1alpha1.Top", [ { no: 1, name: "list", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => TopNode }, { no: 2, name: "reported", kind: "scalar", T: 5 /*ScalarType.INT32*/ }, { no: 3, name: "total", kind: "scalar", T: 5 /*ScalarType.INT32*/ }, { no: 4, name: "unit", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value?: PartialMessage<Top>): Top { const message = { list: [], reported: 0, total: 0, unit: "" }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<Top>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Top): Top { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* repeated parca.query.v1alpha1.TopNode list */ 1: message.list.push(TopNode.internalBinaryRead(reader, reader.uint32(), options)); break; case /* int32 reported */ 2: message.reported = reader.int32(); break; case /* int32 total */ 3: message.total = reader.int32(); break; case /* string unit */ 4: message.unit = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: Top, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* repeated parca.query.v1alpha1.TopNode list = 1; */ for (let i = 0; i < message.list.length; i++) TopNode.internalBinaryWrite(message.list[i], writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* int32 reported = 2; */ if (message.reported !== 0) writer.tag(2, WireType.Varint).int32(message.reported); /* int32 total = 3; */ if (message.total !== 0) writer.tag(3, WireType.Varint).int32(message.total); /* string unit = 4; */ if (message.unit !== "") writer.tag(4, WireType.LengthDelimited).string(message.unit); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.Top */ export const Top = new Top$Type(); // @generated message type with reflection information, may provide speed optimized methods class TopNode$Type extends MessageType<TopNode> { constructor() { super("parca.query.v1alpha1.TopNode", [ { no: 1, name: "meta", kind: "message", T: () => TopNodeMeta }, { no: 2, name: "cumulative", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, { no: 3, name: "flat", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, { no: 4, name: "diff", kind: "scalar", T: 3 /*ScalarType.INT64*/ } ]); } create(value?: PartialMessage<TopNode>): TopNode { const message = { cumulative: "0", flat: "0", diff: "0" }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<TopNode>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: TopNode): TopNode { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.query.v1alpha1.TopNodeMeta meta */ 1: message.meta = TopNodeMeta.internalBinaryRead(reader, reader.uint32(), options, message.meta); break; case /* int64 cumulative */ 2: message.cumulative = reader.int64().toString(); break; case /* int64 flat */ 3: message.flat = reader.int64().toString(); break; case /* int64 diff */ 4: message.diff = reader.int64().toString(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: TopNode, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.query.v1alpha1.TopNodeMeta meta = 1; */ if (message.meta) TopNodeMeta.internalBinaryWrite(message.meta, writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* int64 cumulative = 2; */ if (message.cumulative !== "0") writer.tag(2, WireType.Varint).int64(message.cumulative); /* int64 flat = 3; */ if (message.flat !== "0") writer.tag(3, WireType.Varint).int64(message.flat); /* int64 diff = 4; */ if (message.diff !== "0") writer.tag(4, WireType.Varint).int64(message.diff); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.TopNode */ export const TopNode = new TopNode$Type(); // @generated message type with reflection information, may provide speed optimized methods class TopNodeMeta$Type extends MessageType<TopNodeMeta> { constructor() { super("parca.query.v1alpha1.TopNodeMeta", [ { no: 1, name: "location", kind: "message", T: () => Location }, { no: 2, name: "mapping", kind: "message", T: () => Mapping }, { no: 3, name: "function", kind: "message", T: () => Function }, { no: 4, name: "line", kind: "message", T: () => Line } ]); } create(value?: PartialMessage<TopNodeMeta>): TopNodeMeta { const message = {}; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<TopNodeMeta>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: TopNodeMeta): TopNodeMeta { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.metastore.v1alpha1.Location location */ 1: message.location = Location.internalBinaryRead(reader, reader.uint32(), options, message.location); break; case /* parca.metastore.v1alpha1.Mapping mapping */ 2: message.mapping = Mapping.internalBinaryRead(reader, reader.uint32(), options, message.mapping); break; case /* parca.metastore.v1alpha1.Function function */ 3: message.function = Function.internalBinaryRead(reader, reader.uint32(), options, message.function); break; case /* parca.metastore.v1alpha1.Line line */ 4: message.line = Line.internalBinaryRead(reader, reader.uint32(), options, message.line); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: TopNodeMeta, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.metastore.v1alpha1.Location location = 1; */ if (message.location) Location.internalBinaryWrite(message.location, writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* parca.metastore.v1alpha1.Mapping mapping = 2; */ if (message.mapping) Mapping.internalBinaryWrite(message.mapping, writer.tag(2, WireType.LengthDelimited).fork(), options).join(); /* parca.metastore.v1alpha1.Function function = 3; */ if (message.function) Function.internalBinaryWrite(message.function, writer.tag(3, WireType.LengthDelimited).fork(), options).join(); /* parca.metastore.v1alpha1.Line line = 4; */ if (message.line) Line.internalBinaryWrite(message.line, writer.tag(4, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.TopNodeMeta */ export const TopNodeMeta = new TopNodeMeta$Type(); // @generated message type with reflection information, may provide speed optimized methods class Flamegraph$Type extends MessageType<Flamegraph> { constructor() { super("parca.query.v1alpha1.Flamegraph", [ { no: 1, name: "root", kind: "message", T: () => FlamegraphRootNode }, { no: 2, name: "total", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, { no: 3, name: "unit", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 4, name: "height", kind: "scalar", T: 5 /*ScalarType.INT32*/ } ]); } create(value?: PartialMessage<Flamegraph>): Flamegraph { const message = { total: "0", unit: "", height: 0 }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<Flamegraph>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Flamegraph): Flamegraph { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.query.v1alpha1.FlamegraphRootNode root */ 1: message.root = FlamegraphRootNode.internalBinaryRead(reader, reader.uint32(), options, message.root); break; case /* int64 total */ 2: message.total = reader.int64().toString(); break; case /* string unit */ 3: message.unit = reader.string(); break; case /* int32 height */ 4: message.height = reader.int32(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: Flamegraph, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.query.v1alpha1.FlamegraphRootNode root = 1; */ if (message.root) FlamegraphRootNode.internalBinaryWrite(message.root, writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* int64 total = 2; */ if (message.total !== "0") writer.tag(2, WireType.Varint).int64(message.total); /* string unit = 3; */ if (message.unit !== "") writer.tag(3, WireType.LengthDelimited).string(message.unit); /* int32 height = 4; */ if (message.height !== 0) writer.tag(4, WireType.Varint).int32(message.height); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.Flamegraph */ export const Flamegraph = new Flamegraph$Type(); // @generated message type with reflection information, may provide speed optimized methods class FlamegraphRootNode$Type extends MessageType<FlamegraphRootNode> { constructor() { super("parca.query.v1alpha1.FlamegraphRootNode", [ { no: 1, name: "cumulative", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, { no: 2, name: "diff", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, { no: 3, name: "children", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => FlamegraphNode } ]); } create(value?: PartialMessage<FlamegraphRootNode>): FlamegraphRootNode { const message = { cumulative: "0", diff: "0", children: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<FlamegraphRootNode>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: FlamegraphRootNode): FlamegraphRootNode { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* int64 cumulative */ 1: message.cumulative = reader.int64().toString(); break; case /* int64 diff */ 2: message.diff = reader.int64().toString(); break; case /* repeated parca.query.v1alpha1.FlamegraphNode children */ 3: message.children.push(FlamegraphNode.internalBinaryRead(reader, reader.uint32(), options)); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: FlamegraphRootNode, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* int64 cumulative = 1; */ if (message.cumulative !== "0") writer.tag(1, WireType.Varint).int64(message.cumulative); /* int64 diff = 2; */ if (message.diff !== "0") writer.tag(2, WireType.Varint).int64(message.diff); /* repeated parca.query.v1alpha1.FlamegraphNode children = 3; */ for (let i = 0; i < message.children.length; i++) FlamegraphNode.internalBinaryWrite(message.children[i], writer.tag(3, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.FlamegraphRootNode */ export const FlamegraphRootNode = new FlamegraphRootNode$Type(); // @generated message type with reflection information, may provide speed optimized methods class FlamegraphNode$Type extends MessageType<FlamegraphNode> { constructor() { super("parca.query.v1alpha1.FlamegraphNode", [ { no: 1, name: "meta", kind: "message", T: () => FlamegraphNodeMeta }, { no: 2, name: "cumulative", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, { no: 3, name: "diff", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, { no: 4, name: "children", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => FlamegraphNode } ]); } create(value?: PartialMessage<FlamegraphNode>): FlamegraphNode { const message = { cumulative: "0", diff: "0", children: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<FlamegraphNode>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: FlamegraphNode): FlamegraphNode { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.query.v1alpha1.FlamegraphNodeMeta meta */ 1: message.meta = FlamegraphNodeMeta.internalBinaryRead(reader, reader.uint32(), options, message.meta); break; case /* int64 cumulative */ 2: message.cumulative = reader.int64().toString(); break; case /* int64 diff */ 3: message.diff = reader.int64().toString(); break; case /* repeated parca.query.v1alpha1.FlamegraphNode children */ 4: message.children.push(FlamegraphNode.internalBinaryRead(reader, reader.uint32(), options)); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: FlamegraphNode, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.query.v1alpha1.FlamegraphNodeMeta meta = 1; */ if (message.meta) FlamegraphNodeMeta.internalBinaryWrite(message.meta, writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* int64 cumulative = 2; */ if (message.cumulative !== "0") writer.tag(2, WireType.Varint).int64(message.cumulative); /* int64 diff = 3; */ if (message.diff !== "0") writer.tag(3, WireType.Varint).int64(message.diff); /* repeated parca.query.v1alpha1.FlamegraphNode children = 4; */ for (let i = 0; i < message.children.length; i++) FlamegraphNode.internalBinaryWrite(message.children[i], writer.tag(4, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.FlamegraphNode */ export const FlamegraphNode = new FlamegraphNode$Type(); // @generated message type with reflection information, may provide speed optimized methods class FlamegraphNodeMeta$Type extends MessageType<FlamegraphNodeMeta> { constructor() { super("parca.query.v1alpha1.FlamegraphNodeMeta", [ { no: 1, name: "location", kind: "message", T: () => Location }, { no: 2, name: "mapping", kind: "message", T: () => Mapping }, { no: 3, name: "function", kind: "message", T: () => Function }, { no: 4, name: "line", kind: "message", T: () => Line } ]); } create(value?: PartialMessage<FlamegraphNodeMeta>): FlamegraphNodeMeta { const message = {}; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<FlamegraphNodeMeta>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: FlamegraphNodeMeta): FlamegraphNodeMeta { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.metastore.v1alpha1.Location location */ 1: message.location = Location.internalBinaryRead(reader, reader.uint32(), options, message.location); break; case /* parca.metastore.v1alpha1.Mapping mapping */ 2: message.mapping = Mapping.internalBinaryRead(reader, reader.uint32(), options, message.mapping); break; case /* parca.metastore.v1alpha1.Function function */ 3: message.function = Function.internalBinaryRead(reader, reader.uint32(), options, message.function); break; case /* parca.metastore.v1alpha1.Line line */ 4: message.line = Line.internalBinaryRead(reader, reader.uint32(), options, message.line); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: FlamegraphNodeMeta, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.metastore.v1alpha1.Location location = 1; */ if (message.location) Location.internalBinaryWrite(message.location, writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* parca.metastore.v1alpha1.Mapping mapping = 2; */ if (message.mapping) Mapping.internalBinaryWrite(message.mapping, writer.tag(2, WireType.LengthDelimited).fork(), options).join(); /* parca.metastore.v1alpha1.Function function = 3; */ if (message.function) Function.internalBinaryWrite(message.function, writer.tag(3, WireType.LengthDelimited).fork(), options).join(); /* parca.metastore.v1alpha1.Line line = 4; */ if (message.line) Line.internalBinaryWrite(message.line, writer.tag(4, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.FlamegraphNodeMeta */ export const FlamegraphNodeMeta = new FlamegraphNodeMeta$Type(); // @generated message type with reflection information, may provide speed optimized methods class QueryResponse$Type extends MessageType<QueryResponse> { constructor() { super("parca.query.v1alpha1.QueryResponse", [ { no: 5, name: "flamegraph", kind: "message", oneof: "report", T: () => Flamegraph }, { no: 6, name: "pprof", kind: "scalar", oneof: "report", T: 12 /*ScalarType.BYTES*/ }, { no: 7, name: "top", kind: "message", oneof: "report", T: () => Top } ]); } create(value?: PartialMessage<QueryResponse>): QueryResponse { const message = { report: { oneofKind: undefined } }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<QueryResponse>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: QueryResponse): QueryResponse { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.query.v1alpha1.Flamegraph flamegraph */ 5: message.report = { oneofKind: "flamegraph", flamegraph: Flamegraph.internalBinaryRead(reader, reader.uint32(), options, (message.report as any).flamegraph) }; break; case /* bytes pprof */ 6: message.report = { oneofKind: "pprof", pprof: reader.bytes() }; break; case /* parca.query.v1alpha1.Top top */ 7: message.report = { oneofKind: "top", top: Top.internalBinaryRead(reader, reader.uint32(), options, (message.report as any).top) }; break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: QueryResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.query.v1alpha1.Flamegraph flamegraph = 5; */ if (message.report.oneofKind === "flamegraph") Flamegraph.internalBinaryWrite(message.report.flamegraph, writer.tag(5, WireType.LengthDelimited).fork(), options).join(); /* bytes pprof = 6; */ if (message.report.oneofKind === "pprof") writer.tag(6, WireType.LengthDelimited).bytes(message.report.pprof); /* parca.query.v1alpha1.Top top = 7; */ if (message.report.oneofKind === "top") Top.internalBinaryWrite(message.report.top, writer.tag(7, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.QueryResponse */ export const QueryResponse = new QueryResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class SeriesRequest$Type extends MessageType<SeriesRequest> { constructor() { super("parca.query.v1alpha1.SeriesRequest", [ { no: 1, name: "match", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "start", kind: "message", T: () => Timestamp }, { no: 3, name: "end", kind: "message", T: () => Timestamp } ]); } create(value?: PartialMessage<SeriesRequest>): SeriesRequest { const message = { match: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<SeriesRequest>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: SeriesRequest): SeriesRequest { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* repeated string match */ 1: message.match.push(reader.string()); break; case /* google.protobuf.Timestamp start */ 2: message.start = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.start); break; case /* google.protobuf.Timestamp end */ 3: message.end = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.end); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: SeriesRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* repeated string match = 1; */ for (let i = 0; i < message.match.length; i++) writer.tag(1, WireType.LengthDelimited).string(message.match[i]); /* google.protobuf.Timestamp start = 2; */ if (message.start) Timestamp.internalBinaryWrite(message.start, writer.tag(2, WireType.LengthDelimited).fork(), options).join(); /* google.protobuf.Timestamp end = 3; */ if (message.end) Timestamp.internalBinaryWrite(message.end, writer.tag(3, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.SeriesRequest */ export const SeriesRequest = new SeriesRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class SeriesResponse$Type extends MessageType<SeriesResponse> { constructor() { super("parca.query.v1alpha1.SeriesResponse", []); } create(value?: PartialMessage<SeriesResponse>): SeriesResponse { const message = {}; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<SeriesResponse>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: SeriesResponse): SeriesResponse { return target ?? this.create(); } internalBinaryWrite(message: SeriesResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.SeriesResponse */ export const SeriesResponse = new SeriesResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class LabelsRequest$Type extends MessageType<LabelsRequest> { constructor() { super("parca.query.v1alpha1.LabelsRequest", [ { no: 1, name: "match", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "start", kind: "message", T: () => Timestamp }, { no: 3, name: "end", kind: "message", T: () => Timestamp } ]); } create(value?: PartialMessage<LabelsRequest>): LabelsRequest { const message = { match: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<LabelsRequest>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: LabelsRequest): LabelsRequest { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* repeated string match */ 1: message.match.push(reader.string()); break; case /* google.protobuf.Timestamp start */ 2: message.start = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.start); break; case /* google.protobuf.Timestamp end */ 3: message.end = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.end); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: LabelsRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* repeated string match = 1; */ for (let i = 0; i < message.match.length; i++) writer.tag(1, WireType.LengthDelimited).string(message.match[i]); /* google.protobuf.Timestamp start = 2; */ if (message.start) Timestamp.internalBinaryWrite(message.start, writer.tag(2, WireType.LengthDelimited).fork(), options).join(); /* google.protobuf.Timestamp end = 3; */ if (message.end) Timestamp.internalBinaryWrite(message.end, writer.tag(3, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.LabelsRequest */ export const LabelsRequest = new LabelsRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class LabelsResponse$Type extends MessageType<LabelsResponse> { constructor() { super("parca.query.v1alpha1.LabelsResponse", [ { no: 1, name: "label_names", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "warnings", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ } ]); } create(value?: PartialMessage<LabelsResponse>): LabelsResponse { const message = { labelNames: [], warnings: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<LabelsResponse>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: LabelsResponse): LabelsResponse { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* repeated string label_names */ 1: message.labelNames.push(reader.string()); break; case /* repeated string warnings */ 2: message.warnings.push(reader.string()); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: LabelsResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* repeated string label_names = 1; */ for (let i = 0; i < message.labelNames.length; i++) writer.tag(1, WireType.LengthDelimited).string(message.labelNames[i]); /* repeated string warnings = 2; */ for (let i = 0; i < message.warnings.length; i++) writer.tag(2, WireType.LengthDelimited).string(message.warnings[i]); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.LabelsResponse */ export const LabelsResponse = new LabelsResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class ValuesRequest$Type extends MessageType<ValuesRequest> { constructor() { super("parca.query.v1alpha1.ValuesRequest", [ { no: 1, name: "label_name", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "match", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ }, { no: 3, name: "start", kind: "message", T: () => Timestamp }, { no: 4, name: "end", kind: "message", T: () => Timestamp } ]); } create(value?: PartialMessage<ValuesRequest>): ValuesRequest { const message = { labelName: "", match: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<ValuesRequest>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ValuesRequest): ValuesRequest { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* string label_name */ 1: message.labelName = reader.string(); break; case /* repeated string match */ 2: message.match.push(reader.string()); break; case /* google.protobuf.Timestamp start */ 3: message.start = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.start); break; case /* google.protobuf.Timestamp end */ 4: message.end = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.end); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: ValuesRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* string label_name = 1; */ if (message.labelName !== "") writer.tag(1, WireType.LengthDelimited).string(message.labelName); /* repeated string match = 2; */ for (let i = 0; i < message.match.length; i++) writer.tag(2, WireType.LengthDelimited).string(message.match[i]); /* google.protobuf.Timestamp start = 3; */ if (message.start) Timestamp.internalBinaryWrite(message.start, writer.tag(3, WireType.LengthDelimited).fork(), options).join(); /* google.protobuf.Timestamp end = 4; */ if (message.end) Timestamp.internalBinaryWrite(message.end, writer.tag(4, WireType.LengthDelimited).fork(), options).join(); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.ValuesRequest */ export const ValuesRequest = new ValuesRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class ValuesResponse$Type extends MessageType<ValuesResponse> { constructor() { super("parca.query.v1alpha1.ValuesResponse", [ { no: 1, name: "label_values", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "warnings", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ } ]); } create(value?: PartialMessage<ValuesResponse>): ValuesResponse { const message = { labelValues: [], warnings: [] }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<ValuesResponse>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ValuesResponse): ValuesResponse { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* repeated string label_values */ 1: message.labelValues.push(reader.string()); break; case /* repeated string warnings */ 2: message.warnings.push(reader.string()); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: ValuesResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* repeated string label_values = 1; */ for (let i = 0; i < message.labelValues.length; i++) writer.tag(1, WireType.LengthDelimited).string(message.labelValues[i]); /* repeated string warnings = 2; */ for (let i = 0; i < message.warnings.length; i++) writer.tag(2, WireType.LengthDelimited).string(message.warnings[i]); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.ValuesResponse */ export const ValuesResponse = new ValuesResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class ValueType$Type extends MessageType<ValueType> { constructor() { super("parca.query.v1alpha1.ValueType", [ { no: 1, name: "type", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "unit", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value?: PartialMessage<ValueType>): ValueType { const message = { type: "", unit: "" }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<ValueType>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ValueType): ValueType { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* string type */ 1: message.type = reader.string(); break; case /* string unit */ 2: message.unit = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: ValueType, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* string type = 1; */ if (message.type !== "") writer.tag(1, WireType.LengthDelimited).string(message.type); /* string unit = 2; */ if (message.unit !== "") writer.tag(2, WireType.LengthDelimited).string(message.unit); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.query.v1alpha1.ValueType */ export const ValueType = new ValueType$Type(); /** * @generated ServiceType for protobuf service parca.query.v1alpha1.QueryService */ export const QueryService = new ServiceType("parca.query.v1alpha1.QueryService", [ { name: "QueryRange", options: { "google.api.http": { get: "/profiles/query_range" } }, I: QueryRangeRequest, O: QueryRangeResponse }, { name: "Query", options: { "google.api.http": { get: "/profiles/query" } }, I: QueryRequest, O: QueryResponse }, { name: "Series", options: { "google.api.http": { get: "/profiles/series" } }, I: SeriesRequest, O: SeriesResponse }, { name: "ProfileTypes", options: { "google.api.http": { get: "/profiles/types" } }, I: ProfileTypesRequest, O: ProfileTypesResponse }, { name: "Labels", options: { "google.api.http": { get: "/profiles/labels" } }, I: LabelsRequest, O: LabelsResponse }, { name: "Values", options: { "google.api.http": { get: "/profiles/labels/{label_name}/values" } }, I: ValuesRequest, O: ValuesResponse } ]);
the_stack
export const UV_COORDS: Array<[number, number]> = [ [0.499976992607117, 0.652534008026123], [0.500025987625122, 0.547487020492554], [0.499974012374878, 0.602371990680695], [0.482113003730774, 0.471979022026062], [0.500150978565216, 0.527155995368958], [0.499909996986389, 0.498252987861633], [0.499523013830185, 0.40106201171875], [0.289712011814117, 0.380764007568359], [0.499954998493195, 0.312398016452789], [0.499987006187439, 0.269918978214264], [0.500023007392883, 0.107050001621246], [0.500023007392883, 0.666234016418457], [0.5000159740448, 0.679224014282227], [0.500023007392883, 0.692348003387451], [0.499976992607117, 0.695277988910675], [0.499976992607117, 0.70593398809433], [0.499976992607117, 0.719385027885437], [0.499976992607117, 0.737019002437592], [0.499967992305756, 0.781370997428894], [0.499816000461578, 0.562981009483337], [0.473773002624512, 0.573909997940063], [0.104906998574734, 0.254140973091125], [0.365929991006851, 0.409575998783112], [0.338757991790771, 0.41302502155304], [0.311120003461838, 0.409460008144379], [0.274657994508743, 0.389131009578705], [0.393361985683441, 0.403706014156342], [0.345234006643295, 0.344011008739471], [0.370094001293182, 0.346076011657715], [0.319321990013123, 0.347265005111694], [0.297903001308441, 0.353591024875641], [0.24779200553894, 0.410809993743896], [0.396889001131058, 0.842755019664764], [0.280097991228104, 0.375599980354309], [0.106310002505779, 0.399955987930298], [0.2099249958992, 0.391353011131287], [0.355807989835739, 0.534406006336212], [0.471751004457474, 0.65040397644043], [0.474155008792877, 0.680191993713379], [0.439785003662109, 0.657229006290436], [0.414617002010345, 0.66654098033905], [0.450374007225037, 0.680860996246338], [0.428770989179611, 0.682690978050232], [0.374971002340317, 0.727805018424988], [0.486716985702515, 0.547628998756409], [0.485300987958908, 0.527395009994507], [0.257764995098114, 0.314490020275116], [0.401223003864288, 0.455172002315521], [0.429818987846375, 0.548614978790283], [0.421351999044418, 0.533740997314453], [0.276895999908447, 0.532056987285614], [0.483370006084442, 0.499586999416351], [0.33721199631691, 0.282882988452911], [0.296391993761063, 0.293242990970612], [0.169294998049736, 0.193813979625702], [0.447580009698868, 0.302609980106354], [0.392390012741089, 0.353887975215912], [0.354490011930466, 0.696784019470215], [0.067304998636246, 0.730105042457581], [0.442739009857178, 0.572826027870178], [0.457098007202148, 0.584792017936707], [0.381974011659622, 0.694710969924927], [0.392388999462128, 0.694203019142151], [0.277076005935669, 0.271932005882263], [0.422551989555359, 0.563233017921448], [0.385919004678726, 0.281364023685455], [0.383103013038635, 0.255840003490448], [0.331431001424789, 0.119714021682739], [0.229923993349075, 0.232002973556519], [0.364500999450684, 0.189113974571228], [0.229622006416321, 0.299540996551514], [0.173287004232407, 0.278747975826263], [0.472878992557526, 0.666198015213013], [0.446828007698059, 0.668527007102966], [0.422762006521225, 0.673889994621277], [0.445307999849319, 0.580065965652466], [0.388103008270264, 0.693961024284363], [0.403039008378983, 0.706539988517761], [0.403629004955292, 0.693953037261963], [0.460041999816895, 0.557139039039612], [0.431158006191254, 0.692366003990173], [0.452181994915009, 0.692366003990173], [0.475387006998062, 0.692366003990173], [0.465828001499176, 0.779190003871918], [0.472328990697861, 0.736225962638855], [0.473087012767792, 0.717857003211975], [0.473122000694275, 0.704625964164734], [0.473033010959625, 0.695277988910675], [0.427942007780075, 0.695277988910675], [0.426479011774063, 0.703539967536926], [0.423162013292313, 0.711845993995667], [0.4183090031147, 0.720062971115112], [0.390094995498657, 0.639572978019714], [0.013953999616206, 0.560034036636353], [0.499913990497589, 0.58014702796936], [0.413199990987778, 0.69539999961853], [0.409626007080078, 0.701822996139526], [0.468080013990402, 0.601534962654114], [0.422728985548019, 0.585985004901886], [0.463079988956451, 0.593783974647522], [0.37211999297142, 0.47341400384903], [0.334562003612518, 0.496073007583618], [0.411671012639999, 0.546965003013611], [0.242175996303558, 0.14767599105835], [0.290776997804642, 0.201445996761322], [0.327338010072708, 0.256527006626129], [0.399509996175766, 0.748921036720276], [0.441727995872498, 0.261676013469696], [0.429764986038208, 0.187834024429321], [0.412198007106781, 0.108901023864746], [0.288955003023148, 0.398952007293701], [0.218936994671822, 0.435410976409912], [0.41278201341629, 0.398970007896423], [0.257135003805161, 0.355440020561218], [0.427684992551804, 0.437960982322693], [0.448339998722076, 0.536936044692993], [0.178560003638268, 0.45755398273468], [0.247308000922203, 0.457193970680237], [0.286267012357712, 0.467674970626831], [0.332827985286713, 0.460712015628815], [0.368755996227264, 0.447206974029541], [0.398963987827301, 0.432654976844788], [0.476410001516342, 0.405806005001068], [0.189241006970406, 0.523923993110657], [0.228962004184723, 0.348950982093811], [0.490725994110107, 0.562400996685028], [0.404670000076294, 0.485132992267609], [0.019469000399113, 0.401564002037048], [0.426243007183075, 0.420431017875671], [0.396993011236191, 0.548797011375427], [0.266469985246658, 0.376977026462555], [0.439121007919312, 0.51895797252655], [0.032313998788595, 0.644356966018677], [0.419054001569748, 0.387154996395111], [0.462783008813858, 0.505746960639954], [0.238978996872902, 0.779744982719421], [0.198220998048782, 0.831938028335571], [0.107550002634525, 0.540755033493042], [0.183610007166862, 0.740257024765015], [0.134409993886948, 0.333683013916016], [0.385764002799988, 0.883153975009918], [0.490967005491257, 0.579378008842468], [0.382384985685349, 0.508572995662689], [0.174399003386497, 0.397670984268188], [0.318785011768341, 0.39623498916626], [0.343364000320435, 0.400596976280212], [0.396100014448166, 0.710216999053955], [0.187885001301765, 0.588537991046906], [0.430987000465393, 0.944064974784851], [0.318993002176285, 0.898285031318665], [0.266247987747192, 0.869701027870178], [0.500023007392883, 0.190576016902924], [0.499976992607117, 0.954452991485596], [0.366169989109039, 0.398822009563446], [0.393207013607025, 0.39553701877594], [0.410373002290726, 0.391080021858215], [0.194993004202843, 0.342101991176605], [0.388664990663528, 0.362284004688263], [0.365961998701096, 0.355970978736877], [0.343364000320435, 0.355356991291046], [0.318785011768341, 0.35834002494812], [0.301414996385574, 0.363156020641327], [0.058132998645306, 0.319076001644135], [0.301414996385574, 0.387449026107788], [0.499987989664078, 0.618434011936188], [0.415838003158569, 0.624195992946625], [0.445681989192963, 0.566076993942261], [0.465844005346298, 0.620640993118286], [0.49992299079895, 0.351523995399475], [0.288718998432159, 0.819945991039276], [0.335278987884521, 0.852819979190826], [0.440512001514435, 0.902418971061707], [0.128294005990028, 0.791940987110138], [0.408771991729736, 0.373893976211548], [0.455606997013092, 0.451801002025604], [0.499877005815506, 0.908990025520325], [0.375436991453171, 0.924192011356354], [0.11421000212431, 0.615022003650665], [0.448662012815475, 0.695277988910675], [0.4480200111866, 0.704632043838501], [0.447111994028091, 0.715808033943176], [0.444831997156143, 0.730794012546539], [0.430011987686157, 0.766808986663818], [0.406787008047104, 0.685672998428345], [0.400738000869751, 0.681069016456604], [0.392399996519089, 0.677703022956848], [0.367855995893478, 0.663918972015381], [0.247923001646996, 0.601333022117615], [0.452769994735718, 0.420849978923798], [0.43639200925827, 0.359887003898621], [0.416164010763168, 0.368713974952698], [0.413385987281799, 0.692366003990173], [0.228018000721931, 0.683571994304657], [0.468268007040024, 0.352671027183533], [0.411361992359161, 0.804327011108398], [0.499989002943039, 0.469825029373169], [0.479153990745544, 0.442654013633728], [0.499974012374878, 0.439637005329132], [0.432112008333206, 0.493588984012604], [0.499886006116867, 0.866917014122009], [0.49991300702095, 0.821729004383087], [0.456548988819122, 0.819200992584229], [0.344549000263214, 0.745438992977142], [0.37890899181366, 0.574010014533997], [0.374292999505997, 0.780184984207153], [0.319687992334366, 0.570737957954407], [0.357154995203018, 0.604269981384277], [0.295284003019333, 0.621580958366394], [0.447750002145767, 0.862477004528046], [0.410986006259918, 0.508723020553589], [0.31395098567009, 0.775308012962341], [0.354128003120422, 0.812552988529205], [0.324548006057739, 0.703992962837219], [0.189096003770828, 0.646299958229065], [0.279776990413666, 0.71465802192688], [0.1338230073452, 0.682700991630554], [0.336768001317978, 0.644733011722565], [0.429883986711502, 0.466521978378296], [0.455527991056442, 0.548622965812683], [0.437114000320435, 0.558896005153656], [0.467287987470627, 0.529924988746643], [0.414712011814117, 0.335219979286194], [0.37704598903656, 0.322777986526489], [0.344107985496521, 0.320150971412659], [0.312875986099243, 0.32233202457428], [0.283526003360748, 0.333190023899078], [0.241245999932289, 0.382785975933075], [0.102986000478268, 0.468762993812561], [0.267612010240555, 0.424560010433197], [0.297879010438919, 0.433175981044769], [0.333433985710144, 0.433878004550934], [0.366427004337311, 0.426115989685059], [0.396012008190155, 0.416696012020111], [0.420121014118195, 0.41022801399231], [0.007561000064015, 0.480777025222778], [0.432949006557465, 0.569517970085144], [0.458638995885849, 0.479089021682739], [0.473466008901596, 0.545744001865387], [0.476087987422943, 0.563830018043518], [0.468472003936768, 0.555056989192963], [0.433990985155106, 0.582361996173859], [0.483518004417419, 0.562983989715576], [0.482482999563217, 0.57784903049469], [0.42645001411438, 0.389798998832703], [0.438998997211456, 0.39649498462677], [0.450067013502121, 0.400434017181396], [0.289712011814117, 0.368252992630005], [0.276670008897781, 0.363372981548309], [0.517862021923065, 0.471948027610779], [0.710287988185883, 0.380764007568359], [0.526226997375488, 0.573909997940063], [0.895093023777008, 0.254140973091125], [0.634069979190826, 0.409575998783112], [0.661242008209229, 0.41302502155304], [0.688880026340485, 0.409460008144379], [0.725341975688934, 0.389131009578705], [0.606630027294159, 0.40370500087738], [0.654766023159027, 0.344011008739471], [0.629905998706818, 0.346076011657715], [0.680678009986877, 0.347265005111694], [0.702096998691559, 0.353591024875641], [0.75221198797226, 0.410804986953735], [0.602918028831482, 0.842862963676453], [0.719901978969574, 0.375599980354309], [0.893692970275879, 0.399959981441498], [0.790081977844238, 0.391354024410248], [0.643998026847839, 0.534487962722778], [0.528249025344849, 0.65040397644043], [0.525849997997284, 0.680191040039062], [0.560214996337891, 0.657229006290436], [0.585384011268616, 0.66654098033905], [0.549625992774963, 0.680860996246338], [0.57122802734375, 0.682691991329193], [0.624852001667023, 0.72809898853302], [0.513050019741058, 0.547281980514526], [0.51509702205658, 0.527251958847046], [0.742246985435486, 0.314507007598877], [0.598631024360657, 0.454979002475739], [0.570338010787964, 0.548575043678284], [0.578631997108459, 0.533622980117798], [0.723087012767792, 0.532054007053375], [0.516445994377136, 0.499638974666595], [0.662801027297974, 0.282917976379395], [0.70362401008606, 0.293271005153656], [0.830704987049103, 0.193813979625702], [0.552385985851288, 0.302568018436432], [0.607609987258911, 0.353887975215912], [0.645429015159607, 0.696707010269165], [0.932694971561432, 0.730105042457581], [0.557260990142822, 0.572826027870178], [0.542901992797852, 0.584792017936707], [0.6180260181427, 0.694710969924927], [0.607590973377228, 0.694203019142151], [0.722943007946014, 0.271963000297546], [0.577413976192474, 0.563166975975037], [0.614082992076874, 0.281386971473694], [0.616907000541687, 0.255886018276215], [0.668509006500244, 0.119913995265961], [0.770092010498047, 0.232020974159241], [0.635536015033722, 0.189248979091644], [0.77039098739624, 0.299556016921997], [0.826722025871277, 0.278755009174347], [0.527121007442474, 0.666198015213013], [0.553171992301941, 0.668527007102966], [0.577238023281097, 0.673889994621277], [0.554691970348358, 0.580065965652466], [0.611896991729736, 0.693961024284363], [0.59696102142334, 0.706539988517761], [0.596370995044708, 0.693953037261963], [0.539958000183105, 0.557139039039612], [0.568841993808746, 0.692366003990173], [0.547818005084991, 0.692366003990173], [0.52461302280426, 0.692366003990173], [0.534089982509613, 0.779141008853912], [0.527670979499817, 0.736225962638855], [0.526912987232208, 0.717857003211975], [0.526877999305725, 0.704625964164734], [0.526966989040375, 0.695277988910675], [0.572058022022247, 0.695277988910675], [0.573521018028259, 0.703539967536926], [0.57683801651001, 0.711845993995667], [0.581691026687622, 0.720062971115112], [0.609944999217987, 0.639909982681274], [0.986046016216278, 0.560034036636353], [0.5867999792099, 0.69539999961853], [0.590372025966644, 0.701822996139526], [0.531915009021759, 0.601536989212036], [0.577268004417419, 0.585934996604919], [0.536915004253387, 0.593786001205444], [0.627542972564697, 0.473352015018463], [0.665585994720459, 0.495950996875763], [0.588353991508484, 0.546862006187439], [0.757824003696442, 0.14767599105835], [0.709249973297119, 0.201507985591888], [0.672684013843536, 0.256581008434296], [0.600408971309662, 0.74900496006012], [0.55826598405838, 0.261672019958496], [0.570303976535797, 0.187870979309082], [0.588165998458862, 0.109044015407562], [0.711045026779175, 0.398952007293701], [0.781069993972778, 0.435405015945435], [0.587247014045715, 0.398931980133057], [0.742869973182678, 0.355445981025696], [0.572156012058258, 0.437651991844177], [0.55186802148819, 0.536570012569427], [0.821442008018494, 0.457556009292603], [0.752701997756958, 0.457181990146637], [0.71375697851181, 0.467626988887787], [0.66711300611496, 0.460672974586487], [0.631101012229919, 0.447153985500336], [0.6008620262146, 0.432473003864288], [0.523481011390686, 0.405627012252808], [0.810747981071472, 0.523926019668579], [0.771045982837677, 0.348959028720856], [0.509127020835876, 0.562718033790588], [0.595292985439301, 0.485023975372314], [0.980530977249146, 0.401564002037048], [0.573499977588654, 0.420000016689301], [0.602994978427887, 0.548687994480133], [0.733529984951019, 0.376977026462555], [0.560611009597778, 0.519016981124878], [0.967685997486115, 0.644356966018677], [0.580985009670258, 0.387160003185272], [0.537728011608124, 0.505385041236877], [0.760966002941132, 0.779752969741821], [0.801778972148895, 0.831938028335571], [0.892440974712372, 0.54076099395752], [0.816350996494293, 0.740260004997253], [0.865594983100891, 0.333687007427216], [0.614073991775513, 0.883246004581451], [0.508952975273132, 0.579437971115112], [0.617941975593567, 0.508316040039062], [0.825608015060425, 0.397674977779388], [0.681214988231659, 0.39623498916626], [0.656635999679565, 0.400596976280212], [0.603900015354156, 0.710216999053955], [0.81208598613739, 0.588539004325867], [0.56801301240921, 0.944564998149872], [0.681007981300354, 0.898285031318665], [0.733752012252808, 0.869701027870178], [0.633830010890961, 0.398822009563446], [0.606792986392975, 0.39553701877594], [0.589659988880157, 0.391062021255493], [0.805015981197357, 0.342108011245728], [0.611334979534149, 0.362284004688263], [0.634037971496582, 0.355970978736877], [0.656635999679565, 0.355356991291046], [0.681214988231659, 0.35834002494812], [0.698584973812103, 0.363156020641327], [0.941866993904114, 0.319076001644135], [0.698584973812103, 0.387449026107788], [0.584177017211914, 0.624107003211975], [0.554318010807037, 0.566076993942261], [0.534153997898102, 0.62064003944397], [0.711217999458313, 0.819975018501282], [0.664629995822906, 0.852871000766754], [0.559099972248077, 0.902631998062134], [0.871706008911133, 0.791940987110138], [0.591234028339386, 0.373893976211548], [0.544341027736664, 0.451583981513977], [0.624562978744507, 0.924192011356354], [0.88577002286911, 0.615028977394104], [0.551338016986847, 0.695277988910675], [0.551980018615723, 0.704632043838501], [0.552887976169586, 0.715808033943176], [0.555167973041534, 0.730794012546539], [0.569944024085999, 0.767035007476807], [0.593203008174896, 0.685675978660583], [0.599261999130249, 0.681069016456604], [0.607599973678589, 0.677703022956848], [0.631937980651855, 0.663500010967255], [0.752032995223999, 0.601315021514893], [0.547226011753082, 0.420395016670227], [0.563543975353241, 0.359827995300293], [0.583841025829315, 0.368713974952698], [0.586614012718201, 0.692366003990173], [0.771915018558502, 0.683578014373779], [0.531597018241882, 0.352482974529266], [0.588370978832245, 0.804440975189209], [0.52079701423645, 0.442565023899078], [0.567984998226166, 0.493479013442993], [0.543282985687256, 0.819254994392395], [0.655317008495331, 0.745514988899231], [0.621008992195129, 0.574018001556396], [0.625559985637665, 0.78031200170517], [0.680198013782501, 0.570719003677368], [0.64276397228241, 0.604337990283966], [0.704662978649139, 0.621529996395111], [0.552012026309967, 0.862591981887817], [0.589071989059448, 0.508637011051178], [0.685944974422455, 0.775357007980347], [0.645735025405884, 0.812640011310577], [0.675342977046967, 0.703978002071381], [0.810858011245728, 0.646304965019226], [0.72012197971344, 0.714666962623596], [0.866151988506317, 0.682704985141754], [0.663187026977539, 0.644596993923187], [0.570082008838654, 0.466325998306274], [0.544561982154846, 0.548375964164734], [0.562758982181549, 0.558784961700439], [0.531987011432648, 0.530140042304993], [0.585271000862122, 0.335177004337311], [0.622952997684479, 0.32277899980545], [0.655896008014679, 0.320163011550903], [0.687132000923157, 0.322345972061157], [0.716481983661652, 0.333200991153717], [0.758756995201111, 0.382786989212036], [0.897013008594513, 0.468769013881683], [0.732392013072968, 0.424547016620636], [0.70211398601532, 0.433162987232208], [0.66652500629425, 0.433866024017334], [0.633504986763, 0.426087975502014], [0.603875994682312, 0.416586995124817], [0.579657971858978, 0.409945011138916], [0.992439985275269, 0.480777025222778], [0.567192018032074, 0.569419980049133], [0.54136598110199, 0.478899002075195], [0.526564002037048, 0.546118021011353], [0.523913025856018, 0.563830018043518], [0.531529009342194, 0.555056989192963], [0.566035985946655, 0.582329034805298], [0.51631098985672, 0.563053965568542], [0.5174720287323, 0.577877044677734], [0.573594987392426, 0.389806985855103], [0.560697972774506, 0.395331978797913], [0.549755990505219, 0.399751007556915], [0.710287988185883, 0.368252992630005], [0.723330020904541, 0.363372981548309] ];
the_stack
import * as coreClient from "@azure/core-client"; import * as coreRestPipeline from "@azure/core-rest-pipeline"; /** Document analysis parameters. */ export interface AnalyzeDocumentRequest { /** Document URL to analyze */ urlSource?: string; /** Base64 encoding of the document to analyze */ base64Source?: Uint8Array; } /** Error response object. */ export interface ErrorResponse { /** Error info. */ error: ErrorModel; } /** Error info. */ export interface ErrorModel { /** Error code. */ code: string; /** Error message. */ message: string; /** Target of the error. */ target?: string; /** List of detailed errors. */ details?: ErrorModel[]; /** Detailed error. */ innererror?: InnerError; } /** Detailed error. */ export interface InnerError { /** Error code. */ code: string; /** Error message. */ message?: string; /** Detailed error. */ innererror?: InnerError; } /** Status and result of the analyze operation. */ export interface AnalyzeResultOperation { /** Operation status. */ status: AnalyzeResultOperationStatus; /** Date and time (UTC) when the analyze operation was submitted. */ createdDateTime: Date; /** Date and time (UTC) when the status was last updated. */ lastUpdatedDateTime: Date; /** Encountered error during document analysis. */ error?: ErrorModel; /** Document analysis result. */ analyzeResult?: AnalyzeResult; } /** Document analysis result. */ export interface AnalyzeResult { /** API version used to produce this result. */ apiVersion: ApiVersion; /** Model ID used to produce this result. */ modelId: string; /** Method used to compute string offset and length. */ stringIndexType: StringIndexType; /** Concatenate string representation of all textual and visual elements in reading order. */ content: string; /** Analyzed pages. */ pages: DocumentPage[]; /** Extracted tables. */ tables?: DocumentTable[]; /** Extracted key-value pairs. */ keyValuePairs?: DocumentKeyValuePair[]; /** Extracted entities. */ entities?: DocumentEntity[]; /** Extracted font styles. */ styles?: DocumentStyle[]; /** Extracted documents. */ documents?: Document[]; } /** Content and layout elements extracted from a page from the input. */ export interface DocumentPage { /** 1-based page number in the input document. */ pageNumber: number; /** The general orientation of the content in clockwise direction, measured in degrees between (-180, 180]. */ angle: number; /** The width of the image/PDF in pixels/inches, respectively. */ width: number; /** The height of the image/PDF in pixels/inches, respectively. */ height: number; /** The unit used by the width, height, and boundingBox properties. For images, the unit is "pixel". For PDF, the unit is "inch". */ unit: LengthUnit; /** Location of the page in the reading order concatenated content. */ spans: DocumentSpan[]; /** Extracted words from the page. */ words: DocumentWord[]; /** Extracted selection marks from the page. */ selectionMarks?: DocumentSelectionMark[]; /** Extracted lines from the page, potentially containing both textual and visual elements. */ lines: DocumentLine[]; } /** Contiguous region of the concatenated content property, specified as an offset and length. */ export interface DocumentSpan { /** Zero-based index of the content represented by the span. */ offset: number; /** Number of characters in the content represented by the span. */ length: number; } /** A word object consisting of a contiguous sequence of characters. For non-space delimited languages, such as Chinese, Japanese, and Korean, each character is represented as its own word. */ export interface DocumentWord { /** Text content of the word. */ content: string; /** Bounding box of the word. */ boundingBox?: number[]; /** Location of the word in the reading order concatenated content. */ span: DocumentSpan; /** Confidence of correctly extracting the word. */ confidence: number; } /** A selection mark object representing check boxes, radio buttons, and other elements indicating a selection. */ export interface DocumentSelectionMark { /** State of the selection mark. */ state: SelectionMarkState; /** Bounding box of the selection mark. */ boundingBox?: number[]; /** Location of the selection mark in the reading order concatenated content. */ span: DocumentSpan; /** Confidence of correctly extracting the selection mark. */ confidence: number; } /** A content line object consisting of an adjacent sequence of content elements, such as words and selection marks. */ export interface DocumentLine { /** Concatenated content of the contained elements in reading order. */ content: string; /** Bounding box of the line. */ boundingBox?: number[]; /** Location of the line in the reading order concatenated content. */ spans: DocumentSpan[]; } /** A table object consisting table cells arranged in a rectangular layout. */ export interface DocumentTable { /** Number of rows in the table. */ rowCount: number; /** Number of columns in the table. */ columnCount: number; /** Cells contained within the table. */ cells: DocumentTableCell[]; /** Bounding regions covering the table. */ boundingRegions?: BoundingRegion[]; /** Location of the table in the reading order concatenated content. */ spans: DocumentSpan[]; } /** An object representing the location and content of a table cell. */ export interface DocumentTableCell { /** Table cell kind. */ kind?: DocumentTableCellKind; /** Row index of the cell. */ rowIndex: number; /** Column index of the cell. */ columnIndex: number; /** Number of rows spanned by this cell. */ rowSpan?: number; /** Number of columns spanned by this cell. */ columnSpan?: number; /** Concatenated content of the table cell in reading order. */ content: string; /** Bounding regions covering the table cell. */ boundingRegions?: BoundingRegion[]; /** Location of the table cell in the reading order concatenated content. */ spans: DocumentSpan[]; } /** Bounding box on a specific page of the input. */ export interface BoundingRegion { /** 1-based page number of page containing the bounding region. */ pageNumber: number; /** Bounding box on the page, or the entire page if not specified. */ boundingBox: number[]; } /** An object representing a form field with distinct field label (key) and field value (may be empty). */ export interface DocumentKeyValuePair { /** Field label of the key-value pair. */ key: DocumentKeyValueElement; /** Field value of the key-value pair. */ value?: DocumentKeyValueElement; /** Confidence of correctly extracting the key-value pair. */ confidence: number; } /** An object representing the field key or value in a key-value pair. */ export interface DocumentKeyValueElement { /** Concatenated content of the key-value element in reading order. */ content: string; /** Bounding regions covering the key-value element. */ boundingRegions?: BoundingRegion[]; /** Location of the key-value element in the reading order concatenated content. */ spans: DocumentSpan[]; } /** An object representing various categories of entities. */ export interface DocumentEntity { /** Entity type. */ category: string; /** Entity sub type. */ subCategory?: string; /** Entity content. */ content: string; /** Bounding regions covering the entity. */ boundingRegions?: BoundingRegion[]; /** Location of the entity in the reading order concatenated content. */ spans: DocumentSpan[]; /** Confidence of correctly extracting the entity. */ confidence: number; } /** An object representing observed text styles. */ export interface DocumentStyle { /** Is content handwritten? */ isHandwritten?: boolean; /** Location of the text elements in the concatenated content the style applies to. */ spans: DocumentSpan[]; /** Confidence of correctly identifying the style. */ confidence: number; } /** An object describing the location and semantic content of a document. */ export interface Document { /** Document type. */ docType: string; /** Bounding regions covering the document. */ boundingRegions?: BoundingRegion[]; /** Location of the document in the reading order concatenated content. */ spans: DocumentSpan[]; /** Dictionary of named field values. */ fields: { [propertyName: string]: DocumentField }; /** Confidence of correctly extracting the document. */ confidence: number; } /** An object representing the content and location of a field value. */ export interface DocumentField { /** Data type of the field value. */ type: DocumentFieldType; /** String value. */ valueString?: string; /** Date value in YYYY-MM-DD format (ISO 8601). */ valueDate?: Date; /** * Time value in hh:mm:ss format (ISO 8601). * This value should be an ISO-8601 formatted string representing time. E.g. "HH:MM:SS" or "HH:MM:SS.mm". */ valueTime?: string; /** Phone number value in E.164 format (ex. +19876543210). */ valuePhoneNumber?: string; /** Floating point value. */ valueNumber?: number; /** Integer value. */ valueInteger?: number; /** Selection mark value. */ valueSelectionMark?: SelectionMarkState; /** Presence of signature. */ valueSignature?: DocumentSignatureType; /** 3-letter country code value (ISO 3166-1 alpha-3). */ valueCountryRegion?: string; /** Array of field values. */ valueArray?: DocumentField[]; /** Dictionary of named field values. */ valueObject?: { [propertyName: string]: DocumentField }; /** Field content. */ content?: string; /** Bounding regions covering the field. */ boundingRegions?: BoundingRegion[]; /** Location of the field in the reading order concatenated content. */ spans?: DocumentSpan[]; /** Confidence of correctly extracting the field. */ confidence?: number; } /** Request body to build a new custom model. */ export interface BuildDocumentModelRequest { /** Unique model name. */ modelId: string; /** Model description. */ description?: string; /** Azure Blob Storage location containing the training data. */ azureBlobSource?: AzureBlobContentSource; } /** Azure Blob Storage content. */ export interface AzureBlobContentSource { /** Azure Blob Storage container URL. */ containerUrl: string; /** Blob name prefix. */ prefix?: string; } /** Request body to create a composed model from component models. */ export interface ComposeDocumentModelRequest { /** Unique model name. */ modelId: string; /** Model description. */ description?: string; /** List of component models to compose. */ componentModels: ComponentModelInfo[]; } /** A component of a composed model. */ export interface ComponentModelInfo { /** Unique model name. */ modelId: string; } /** Request body to authorize model copy. */ export interface AuthorizeCopyRequest { /** Unique model name. */ modelId: string; /** Model description. */ description?: string; } /** Authorization to copy a model to the specified target resource and modelId. */ export interface CopyAuthorization { /** ID of the target Azure resource where the model should be copied to. */ targetResourceId: string; /** Location of the target Azure resource where the model should be copied to. */ targetResourceRegion: string; /** Identifier of the target model. */ targetModelId: string; /** URL of the copied model in the target account. */ targetModelLocation: string; /** Token used to authorize the request. */ accessToken: string; /** Date/time when the access token expires. */ expirationDateTime: Date; } /** List Operations response object. */ export interface GetOperationsResponse { /** List of operations. */ value: OperationInfo[]; /** Link to the next page of operations. */ nextLink?: string; } /** Operation info. */ export interface OperationInfo { /** Operation ID */ operationId: string; /** Operation status. */ status: OperationStatus; /** Operation progress (0-100). */ percentCompleted?: number; /** Date and time (UTC) when the operation was created. */ createdDateTime: Date; /** Date and time (UTC) when the status was last updated. */ lastUpdatedDateTime: Date; /** Type of operation. */ kind: OperationKind; /** URL of the resource targeted by this operation. */ resourceLocation: string; } /** Model summary. */ export interface ModelSummary { /** Unique model name. */ modelId: string; /** Model description. */ description?: string; /** Date and time (UTC) when the model was created. */ createdDateTime: Date; } /** Document type info. */ export interface DocTypeInfo { /** Model description. */ description?: string; /** Description of the document semantic schema using a JSON Schema style syntax. */ fieldSchema: { [propertyName: string]: DocumentFieldSchema }; /** Estimated confidence for each field. */ fieldConfidence?: { [propertyName: string]: number }; } /** Description of the field semantic schema using a JSON Schema style syntax. */ export interface DocumentFieldSchema { /** Semantic data type of the field value. */ type: DocumentFieldType; /** Field description. */ description?: string; /** Example field content. */ example?: string; /** Field type schema of each array element. */ items?: DocumentFieldSchema; /** Named sub-fields of the object field. */ properties?: { [propertyName: string]: DocumentFieldSchema }; } /** List Models response object. */ export interface GetModelsResponse { /** List of models. */ value: ModelSummary[]; /** Link to the next page of models. */ nextLink?: string; } /** General information regarding the current resource. */ export interface GetInfoResponse { /** Info regarding custom document models. */ customDocumentModels: CustomDocumentModelsInfo; } /** Info regarding custom document models. */ export interface CustomDocumentModelsInfo { /** Number of custom models in the current resource. */ count: number; /** Maximum number of custom models supported in the current resource. */ limit: number; } /** Get Operation response object. */ export type GetOperationResponse = OperationInfo & { /** Encountered error. */ error?: ErrorModel; /** Operation result upon success. */ result?: ModelInfo; }; /** Model info. */ export type ModelInfo = ModelSummary & { /** Supported document types. */ docTypes?: { [propertyName: string]: DocTypeInfo }; }; /** Defines headers for GeneratedClient_analyzeDocument operation. */ export interface GeneratedClientAnalyzeDocumentHeaders { /** URL used to track the progress and obtain the result of the analyze operation. */ operationLocation?: string; } /** Defines headers for GeneratedClient_buildDocumentModel operation. */ export interface GeneratedClientBuildDocumentModelHeaders { /** Operation result URL. */ operationLocation?: string; } /** Defines headers for GeneratedClient_composeDocumentModel operation. */ export interface GeneratedClientComposeDocumentModelHeaders { /** Operation result URL. */ operationLocation?: string; } /** Defines headers for GeneratedClient_copyDocumentModelTo operation. */ export interface GeneratedClientCopyDocumentModelToHeaders { /** Operation result URL. */ operationLocation?: string; } /** Known values of {@link StringIndexType} that the service accepts. */ export enum KnownStringIndexType { TextElements = "textElements", UnicodeCodePoint = "unicodeCodePoint", Utf16CodeUnit = "utf16CodeUnit" } /** * Defines values for StringIndexType. \ * {@link KnownStringIndexType} can be used interchangeably with StringIndexType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **textElements** \ * **unicodeCodePoint** \ * **utf16CodeUnit** */ export type StringIndexType = string; /** Known values of {@link ApiVersion} that the service accepts. */ export enum KnownApiVersion { TwoThousandTwentyOne0930Preview = "2021-09-30-preview" } /** * Defines values for ApiVersion. \ * {@link KnownApiVersion} can be used interchangeably with ApiVersion, * this enum contains the known values that the service supports. * ### Known values supported by the service * **2021-09-30-preview** */ export type ApiVersion = string; /** Known values of {@link LengthUnit} that the service accepts. */ export enum KnownLengthUnit { Pixel = "pixel", Inch = "inch" } /** * Defines values for LengthUnit. \ * {@link KnownLengthUnit} can be used interchangeably with LengthUnit, * this enum contains the known values that the service supports. * ### Known values supported by the service * **pixel** \ * **inch** */ export type LengthUnit = string; /** Known values of {@link SelectionMarkState} that the service accepts. */ export enum KnownSelectionMarkState { Selected = "selected", Unselected = "unselected" } /** * Defines values for SelectionMarkState. \ * {@link KnownSelectionMarkState} can be used interchangeably with SelectionMarkState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **selected** \ * **unselected** */ export type SelectionMarkState = string; /** Known values of {@link DocumentTableCellKind} that the service accepts. */ export enum KnownDocumentTableCellKind { Content = "content", RowHeader = "rowHeader", ColumnHeader = "columnHeader", StubHead = "stubHead", Description = "description" } /** * Defines values for DocumentTableCellKind. \ * {@link KnownDocumentTableCellKind} can be used interchangeably with DocumentTableCellKind, * this enum contains the known values that the service supports. * ### Known values supported by the service * **content** \ * **rowHeader** \ * **columnHeader** \ * **stubHead** \ * **description** */ export type DocumentTableCellKind = string; /** Known values of {@link DocumentFieldType} that the service accepts. */ export enum KnownDocumentFieldType { String = "string", Date = "date", Time = "time", PhoneNumber = "phoneNumber", Number = "number", Integer = "integer", SelectionMark = "selectionMark", CountryRegion = "countryRegion", Signature = "signature", Array = "array", Object = "object" } /** * Defines values for DocumentFieldType. \ * {@link KnownDocumentFieldType} can be used interchangeably with DocumentFieldType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **string** \ * **date** \ * **time** \ * **phoneNumber** \ * **number** \ * **integer** \ * **selectionMark** \ * **countryRegion** \ * **signature** \ * **array** \ * **object** */ export type DocumentFieldType = string; /** Known values of {@link DocumentSignatureType} that the service accepts. */ export enum KnownDocumentSignatureType { Signed = "signed", Unsigned = "unsigned" } /** * Defines values for DocumentSignatureType. \ * {@link KnownDocumentSignatureType} can be used interchangeably with DocumentSignatureType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **signed** \ * **unsigned** */ export type DocumentSignatureType = string; /** Known values of {@link OperationKind} that the service accepts. */ export enum KnownOperationKind { DocumentModelBuild = "documentModelBuild", DocumentModelCompose = "documentModelCompose", DocumentModelCopyTo = "documentModelCopyTo" } /** * Defines values for OperationKind. \ * {@link KnownOperationKind} can be used interchangeably with OperationKind, * this enum contains the known values that the service supports. * ### Known values supported by the service * **documentModelBuild** \ * **documentModelCompose** \ * **documentModelCopyTo** */ export type OperationKind = string; /** Defines values for ContentType. */ export type ContentType = | "application/octet-stream" | "application/pdf" | "image/bmp" | "image/jpeg" | "image/png" | "image/tiff"; /** Defines values for AnalyzeResultOperationStatus. */ export type AnalyzeResultOperationStatus = | "notStarted" | "running" | "failed" | "succeeded"; /** Defines values for OperationStatus. */ export type OperationStatus = | "notStarted" | "running" | "failed" | "succeeded" | "canceled"; /** Optional parameters. */ export interface GeneratedClientAnalyzeDocument$binaryOptionalParams extends coreClient.OperationOptions { /** Analyze request parameters. */ analyzeRequest?: coreRestPipeline.RequestBodyType; /** List of 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ pages?: string; /** Locale hint for text recognition and document analysis. Value may contain only the language code (ex. "en", "fr") or BCP 47 language tag (ex. "en-US"). */ locale?: string; } /** Optional parameters. */ export interface GeneratedClientAnalyzeDocument$jsonOptionalParams extends coreClient.OperationOptions { /** Analyze request parameters. */ analyzeRequest?: AnalyzeDocumentRequest; /** List of 1-based page numbers to analyze. Ex. "1-3,5,7-9" */ pages?: string; /** Locale hint for text recognition and document analysis. Value may contain only the language code (ex. "en", "fr") or BCP 47 language tag (ex. "en-US"). */ locale?: string; } /** Contains response data for the analyzeDocument operation. */ export type GeneratedClientAnalyzeDocumentResponse = GeneratedClientAnalyzeDocumentHeaders; /** Optional parameters. */ export interface GeneratedClientGetAnalyzeDocumentResultOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAnalyzeDocumentResult operation. */ export type GeneratedClientGetAnalyzeDocumentResultResponse = AnalyzeResultOperation; /** Optional parameters. */ export interface GeneratedClientBuildDocumentModelOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the buildDocumentModel operation. */ export type GeneratedClientBuildDocumentModelResponse = GeneratedClientBuildDocumentModelHeaders; /** Optional parameters. */ export interface GeneratedClientComposeDocumentModelOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the composeDocumentModel operation. */ export type GeneratedClientComposeDocumentModelResponse = GeneratedClientComposeDocumentModelHeaders; /** Optional parameters. */ export interface GeneratedClientAuthorizeCopyDocumentModelOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the authorizeCopyDocumentModel operation. */ export type GeneratedClientAuthorizeCopyDocumentModelResponse = CopyAuthorization; /** Optional parameters. */ export interface GeneratedClientCopyDocumentModelToOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the copyDocumentModelTo operation. */ export type GeneratedClientCopyDocumentModelToResponse = GeneratedClientCopyDocumentModelToHeaders; /** Optional parameters. */ export interface GeneratedClientGetOperationsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getOperations operation. */ export type GeneratedClientGetOperationsResponse = GetOperationsResponse; /** Optional parameters. */ export interface GeneratedClientGetOperationOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getOperation operation. */ export type GeneratedClientGetOperationResponse = GetOperationResponse; /** Optional parameters. */ export interface GeneratedClientGetModelsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getModels operation. */ export type GeneratedClientGetModelsResponse = GetModelsResponse; /** Optional parameters. */ export interface GeneratedClientGetModelOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getModel operation. */ export type GeneratedClientGetModelResponse = ModelInfo; /** Optional parameters. */ export interface GeneratedClientDeleteModelOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface GeneratedClientGetInfoOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getInfo operation. */ export type GeneratedClientGetInfoResponse = GetInfoResponse; /** Optional parameters. */ export interface GeneratedClientGetOperationsNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getOperationsNext operation. */ export type GeneratedClientGetOperationsNextResponse = GetOperationsResponse; /** Optional parameters. */ export interface GeneratedClientGetModelsNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getModelsNext operation. */ export type GeneratedClientGetModelsNextResponse = GetModelsResponse; /** Optional parameters. */ export interface GeneratedClientOptionalParams extends coreClient.ServiceClientOptions { /** Method used to compute string offset and length. */ stringIndexType?: StringIndexType; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import {shallow, mount} from 'enzyme'; import toJson from 'enzyme-to-json'; import {Slider} from '..'; import {h, noop} from '../../util'; const mountSlider = (props = {}) => mount( <Slider onScrub={jest.fn()} onScrubStart={jest.fn()} onScrubStop={jest.fn()} value={0.5} {...props}> {({value}) => <div>{value}</div> } </Slider> ); const simulate = (instance, events, assertions) => new Promise((resolve, reject) => { events.sort(([timeout1], [timeout2]) => { if (timeout1 > timeout2) { return 1; } else { return -1; } }); for (const [timeout, eventNameOrCallback, event] of events) { if (typeof eventNameOrCallback === 'function') { setTimeout(eventNameOrCallback, timeout); } else { setTimeout(() => { let method = ''; switch (eventNameOrCallback) { case 'mousedown': method = 'onMouseDown'; instance[method]()(event); return; case 'mousemove': method = 'onMouseMove'; break; case 'mouseup': method = 'onMouseUp'; break; case 'touchstart': method = 'onTouchStart'; instance[method]()(event); return; case 'touchmove': method = 'onTouchMove'; break; case 'touchend': method = 'onTouchEnd'; break; default: throw new Error(`Event "${eventNameOrCallback}" not supported.`); } instance[method](event); }, timeout); } } const lastTimeout = events[events.length - 1][0]; setTimeout(() => { try { assertions(); resolve(undefined); } catch (error) { reject(error); } }, lastTimeout + 200); }); const mouseEventX = (clientX) => ({clientX}); const mouseEventY = (clientY) => ({clientY}); const touchEventX = (clientX) => ({changedTouches: [{clientX}]}); const rect = { bottom: 200, height: 200, left: 0, right: 100, top: 0, width: 100 }; const getBoundingClientRectReal = Element.prototype.getBoundingClientRect; describe('<Slider>', () => { beforeEach(() => { const fn = jest.fn(); Object.defineProperty(Element.prototype, 'getBoundingClientRect', { value: fn, writable: true }); fn.mockImplementation(() => rect); }); afterEach(() => { Object.defineProperty(Element.prototype, 'getBoundingClientRect', { value: getBoundingClientRectReal, writable: true }); }); it('renders without crashing', () => { mount( <Slider onScrub={noop} onScrubStart={noop} onScrubStop={noop} value={0.2}> {({value}) => <div>{value}</div> } </Slider> ); }); it('renders as expected', () => { const wrapper = shallow( <Slider onScrub={noop} onScrubStart={noop} onScrubStop={noop} value={0.2}> {({value}) => <div>{value}</div> } </Slider> ); expect(toJson(wrapper)).toMatchSnapshot(); }); it('passes through FaCC child', () => { const wrapper = shallow( <Slider onScrub={noop} onScrubStart={noop} onScrubStop={noop} value={0.2}> {({value}) => <div>{value}</div> } </Slider> ); expect(wrapper.find('div').props().children).toBe(0.2); }); // Currently, `jsdom` does not support `clientY`, so we create fake event objects. // https://github.com/tmpvar/jsdom/issues/1911 describe('mouse events', () => { it('call onScrub on mousedown', () => { const onScrub = jest.fn(); const wrapper = mount( <Slider onScrub={onScrub} onScrubStart={noop} onScrubStop={noop} value={0.5}> {({value}) => <div>{value}</div> } </Slider> ); const instance = wrapper.instance(); instance.onMouseDown()(mouseEventX(20)); expect(onScrub).toHaveBeenCalledTimes(1); expect(onScrub.mock.calls[0]).toEqual([0.20]); expect(onScrub.mock.calls[0]).not.toEqual([0.21]); }); it('passes through new value to FaCC on mousedown', () => { const onScrub = jest.fn(); const wrapper = mount( <Slider onScrub={onScrub} onScrubStart={noop} onScrubStop={noop} value={0.5}> {({value}) => <div>{value}</div> } </Slider> ); const instance = wrapper.instance(); expect(wrapper.find('div').props().children).toBe(0.5); instance.onMouseDown()(mouseEventX(30)); wrapper.update(); expect(wrapper.find('div').props().children).toBe(0.3); }); describe('mouse event slider', () => { describe('horizontal', () => { describe('adjusts slider value to the latest position', () => { it('only mousedown event', () => { const wrapper = mountSlider(); const instance = wrapper.instance(); const FINAL_VALUE = 25; return simulate(instance, [ [10, 'mousedown', mouseEventX(FINAL_VALUE)] ], () => { const calls = wrapper.props().onScrub.mock.calls; expect(calls[calls.length - 1]).toEqual([FINAL_VALUE / 100]); }); }); it('only one mousemove event', () => { const wrapper = mountSlider(); const instance = wrapper.instance(); const FINAL_VALUE = 25; return simulate(instance, [ [10, 'mousedown', mouseEventX(0)], [20, 'mousemove', mouseEventX(FINAL_VALUE)] ], () => { const calls = wrapper.props().onScrub.mock.calls; expect(calls[calls.length - 1]).toEqual([FINAL_VALUE / 100]); }); }); describe('many mousemove events fired in a single 50ms throttle frame', () => { it('sets the last value', () => { const wrapper = mountSlider(); const instance = wrapper.instance(); const FINAL_VALUE = 25; return simulate(instance, [ [10, 'mousedown', mouseEventX(0)], [22, 'mousemove', mouseEventX(1)], [25, 'mousemove', mouseEventX(2)], [27, 'mousemove', mouseEventX(3)], [29, 'mousemove', mouseEventX(4)], [30, 'mousemove', mouseEventX(5)], [33, 'mousemove', mouseEventX(FINAL_VALUE)] ], () => { const calls = wrapper.props().onScrub.mock.calls; expect(calls[calls.length - 1]).toEqual([FINAL_VALUE / 100]); }); }); it('throttles, calls .onScrub() only once for mousemove event', () => { const wrapper = mountSlider(); const instance = wrapper.instance(); const FINAL_VALUE = 25; return simulate(instance, [ [10, 'mousedown', mouseEventX(0)], [22, 'mousemove', mouseEventX(1)], [25, 'mousemove', mouseEventX(2)], [27, 'mousemove', mouseEventX(3)], [29, 'mousemove', mouseEventX(4)], [30, 'mousemove', mouseEventX(5)], [33, 'mousemove', mouseEventX(FINAL_VALUE)] ], () => { expect(wrapper.props().onScrub).toHaveBeenCalledTimes(2); }); }); }); describe('mousemove events fired across throttle 50ms frames', () => { it('sets the last value', () => { const wrapper = mountSlider(); const instance = wrapper.instance(); const FINAL_VALUE = 60; return simulate(instance, [ [10, 'mousedown', mouseEventX(0)], [30, 'mousemove', mouseEventX(77)], [66, 'mousemove', mouseEventX(23)], [99, 'mousemove', mouseEventX(3)], [120, 'mousemove', mouseEventX(4)], [200, 'mousemove', mouseEventX(5)], [230, 'mousemove', mouseEventX(FINAL_VALUE)] ], () => { const calls = wrapper.props().onScrub.mock.calls; expect(calls[calls.length - 1]).toEqual([FINAL_VALUE / 100]); }); }); it('throttles by 50ms', () => { const wrapper = mountSlider(); const instance = wrapper.instance(); const FINAL_VALUE = 60; return simulate(instance, [ [10, 'mousedown', mouseEventX(0)], [30, 'mousemove', mouseEventX(77)], [31, 'mousemove', mouseEventX(78)], [50, 'mousemove', mouseEventX(44)], [66, 'mousemove', mouseEventX(23)], [77, 'mousemove', mouseEventX(23)], [99, 'mousemove', mouseEventX(3)], [100, 'mousemove', mouseEventX(44)], [120, 'mousemove', mouseEventX(4)], [123, 'mousemove', mouseEventX(4)], [130, 'mousemove', mouseEventX(43)], [134, 'mousemove', mouseEventX(41)], [156, 'mousemove', mouseEventX(42)], [176, 'mousemove', mouseEventX(43)], [186, 'mousemove', mouseEventX(44)], [200, 'mousemove', mouseEventX(4)], [212, 'mousemove', mouseEventX(3)], [234, 'mousemove', mouseEventX(5)], [230, 'mousemove', mouseEventX(FINAL_VALUE)] ], () => { expect(wrapper.props().onScrub).toHaveBeenCalledTimes(6); }); }); }); }); describe('does not set value if dimensions of slider collapse', () => { // Useful when slider is hidden by CSS, its dimensions collapse. it('works', () => { const wrapper = mountSlider(); const instance = wrapper.instance(); const FINAL_VALUE = 25; return simulate(instance, [ [10, 'mousedown', mouseEventX(10)], [20, 'mousemove', mouseEventX(FINAL_VALUE)], [70, () => { (Element.prototype.getBoundingClientRect as any).mockImplementation(() => ({ bottom: 0, height: 0, left: 0, right: 0, top: 0, width: 0 })); }], [100, 'mousemove', mouseEventX(75)] ], () => { const calls = wrapper.props().onScrub.mock.calls; expect(calls[calls.length - 1]).toEqual([FINAL_VALUE / 100]); }); }); }); }); describe('vertical', () => { it('fires correctly onScrub on mousedown', () => { const wrapper = mountSlider({vertical: true}); const instance = wrapper.instance(); const onScrub = wrapper.props().onScrub; instance.onMouseDown()(mouseEventY(20)); expect(onScrub).toHaveBeenCalledTimes(1); expect(onScrub.mock.calls[0]).toEqual([20 / 200]); }); describe('limits value to [0, 1]', () => { it('when mouse moves over 1', () => { const wrapper = mountSlider({vertical: true}); const instance = wrapper.instance(); const onScrub = wrapper.props().onScrub; return simulate(instance, [ [1, 'mousedown', mouseEventY(50)], [20, 'mousemove', mouseEventY(100)], [30, 'mousemove', mouseEventY(140)], [40, 'mousemove', mouseEventY(170)], [50, 'mousemove', mouseEventY(220)] ], () => { const {calls} = onScrub.mock; const lastValue = calls[calls.length - 1][0]; expect(lastValue).toBe(1); }); }); it('when mouse moves below 0', () => { const wrapper = mountSlider({vertical: true}); const instance = wrapper.instance(); const onScrub = wrapper.props().onScrub; return simulate(instance, [ [1, 'mousedown', mouseEventY(50)], [20, 'mousemove', mouseEventY(40)], [30, 'mousemove', mouseEventY(30)], [40, 'mousemove', mouseEventY(-10)], [50, 'mousemove', mouseEventY(-111)] ], () => { const {calls} = onScrub.mock; const lastValue = calls[calls.length - 1][0]; expect(lastValue).toBe(0); }); }); it('when mouse moves out of range all the time', () => { const wrapper = mountSlider({vertical: true}); const instance = wrapper.instance(); const onScrub = wrapper.props().onScrub; return simulate(instance, [ [1, 'mousedown', mouseEventY(50)], [20, 'mousemove', mouseEventY(220)], [30, 'mousemove', mouseEventY(250)], [40, 'mousemove', mouseEventY(-10)], [50, 'mousemove', mouseEventY(-200)], [60, 'mousemove', mouseEventY(-400)], [80, 'mousemove', mouseEventY(500)] ], () => { const {calls} = onScrub.mock; for (const [value] of calls) { expect(value >= 0).toBe(true); expect(value <= 1).toBe(true); } }); }); }); describe('stops on mouseup', () => { it('works', () => { const wrapper = mountSlider({vertical: true}); const instance = wrapper.instance(); return simulate(instance, [ [1, 'mousedown', mouseEventY(50)], [20, 'mousemove', mouseEventY(90)], [35, 'mouseup', mouseEventY(120)] ], () => { expect(wrapper.state().isSliding).toBe(false); }); }); }); }); }); }); describe('touch events', () => { it('calls onScrub on touchstart', () => { const wrapper = mountSlider(); const instance = wrapper.instance(); instance.onTouchStart()(touchEventX(10)); const onScrub = wrapper.props().onScrub; expect(onScrub).toHaveBeenCalledTimes(1); expect(onScrub.mock.calls[0]).toEqual([10 / 100]); }); it('moves slider on touchmove', () => { const wrapper = mountSlider(); const instance = wrapper.instance(); simulate(instance, [ [10, 'touchstart', touchEventX(10)], [20, 'touchmove', touchEventX(20)], [30, 'touchmove', touchEventX(30)] ], () => { const onScrub = wrapper.props().onScrub; const calls = onScrub.mock.calls; const lastCall = calls[calls.length - 1]; expect(lastCall).toEqual([30 / 100]); }); }); }); });
the_stack
import '@cds/core/accordion/register.js'; import { CdsAccordionPanel } from '@cds/core/accordion'; import { spreadProps, getElementStorybookArgs } from '@cds/core/internal'; import { html } from 'lit'; export default { title: 'Stories/Accordion', component: 'cds-accordion', parameters: { options: { showPanel: true }, design: { type: 'figma', url: 'https://www.figma.com/file/v2mkhzKQdhECXOx8BElgdA/Clarity-UI-Library---light-2.2.0?node-id=1007%3A0', }, }, }; export function API(args: any) { return html` <cds-accordion ...="${spreadProps(getElementStorybookArgs(args))}"> <cds-accordion-panel expanded> <cds-accordion-header>accordion header</cds-accordion-header> <cds-accordion-content>accordion content</cds-accordion-content> </cds-accordion-panel> </cds-accordion> `; } /** @website */ export function basicAccordion() { return html` <cds-accordion> <cds-accordion-panel expanded> <cds-accordion-header>Expanded accordion panel</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Expanded accordion content</p> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel disabled> <cds-accordion-header>Disabled accordion panel</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Disabled accordion content</p> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel> <cds-accordion-header>Collapsed accordion panel</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Collapsed accordion content</p> </cds-accordion-content> </cds-accordion-panel> </cds-accordion> `; } export const asyncAccordion = () => { function onExpandedChange() { const asyncPanel = document.getElementById('async-panel') as CdsAccordionPanel; const asyncPanelContent = asyncPanel.querySelector('cds-accordion-content'); asyncPanelContent.innerHTML = `<div cds-layout="horizontal align:center"><cds-progress-circle size="md"></cds-progress-circle></div>`; asyncPanel.expanded = !asyncPanel.expanded; if (asyncPanel.expanded) { setTimeout( () => (asyncPanelContent.innerHTML = `<p cds-text="body">Asynchronously loaded panel content</p>`), 3000 ); } } return html` <cds-accordion> <cds-accordion-panel expanded> <cds-accordion-header>Expanded accordion panel</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Expanded accordion panel content</p> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel id="async-panel" @expandedChange="${onExpandedChange}"> <cds-accordion-header>Async accordion panel</cds-accordion-header> <cds-accordion-content></cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel disabled> <cds-accordion-header>Disabled accordion panel</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Disabled accordion content</p> </cds-accordion-content> </cds-accordion-panel> </cds-accordion> `; }; export const interactive = () => { const onExpandedChange = { // handleEvent method is required. handleEvent(e: any) { const myPanel = e.target as any; if (!myPanel.disabled) { if (e.target.id === 'async' && e.detail === true) { const asyncPanel = e.target.querySelector('cds-accordion-content'); asyncPanel.innerHTML = `<div cds-layout="horizontal align:center"><cds-progress-circle size="md"></cds-progress-circle></div>`; const timerId = setTimeout(() => { asyncPanel.innerHTML = `<p cds-text="body">Paroxysm of global death quasar citizens of distant epochs dispassionate extraterrestrial observer laws of physics colonies. How far away stirred by starlight bits of moving fluff as a patch of light descended from astronomers across the centuries. Invent the universe finite but unbounded the ash of stellar alchemy made in the interiors of collapsing stars not a sunrise but a galaxyrise hearts of the stars. Citizens of distant epochs a still more glorious dawn awaits the carbon in our apple pies hearts of the stars a very small stage in a vast cosmic arena the carbon in our apple pies and billions upon billions upon billions upon billions upon billions upon billions upon billions.</p>`; clearTimeout(timerId); }, 3000); } myPanel.expanded = e.detail; } }, // event listener objects can also define zero or more of the event // listener options: capture, passive, and once. capture: true, }; return html` <cds-accordion> <cds-accordion-panel cds-motion="off" expanded @expandedChange="${onExpandedChange}"> <cds-accordion-header>Static panel #1</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Expanded accordion panel content</p> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel cds-motion="off" @expandedChange="${onExpandedChange}"> <cds-accordion-header>Static panel #2</cds-accordion-header> <cds-accordion-content> <p cds-text="body" cds-layout="m-b:md"> Rogue rich in heavy atoms Vangelis preserve and cherish that pale blue dot venture intelligent beings. Encyclopaedia galactica encyclopaedia galactica the carbon in our apple pies not a sunrise but a galaxyrise vanquish the impossible encyclopaedia galactica. </p> <p cds-text="body"> Encyclopaedia galactica across the centuries with pretty stories for which there's little good evidence extraordinary claims require extraordinary evidence dream of the mind's eye bits of moving fluff? Extraordinary claims require extraordinary evidence the sky calls to us made in the interiors of collapsing stars citizens of distant epochs Sea of Tranquility concept of the number one and billions upon billions upon billions upon billions upon billions upon billions upon billions. </p> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel cds-motion="off" disabled @expandedChange="${onExpandedChange}"> <cds-accordion-header>Disabled accordion panel</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Disabled accordion content</p> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel cds-motion="off" @expandedChange="${onExpandedChange}"> <cds-accordion-header>Static panel #3</cds-accordion-header> <cds-accordion-content> <p cds-text="body"> Finite but unbounded stirred by starlight vanquish the impossible the ash of stellar alchemy two ghostly white figures in coveralls and helmets are softly dancing muse. </p> </cds-accordion-content> </cds-accordion-panel> </cds-accordion> <p>&nbsp;</p> <cds-accordion> <cds-accordion-panel cds-motion="on" expanded @expandedChange="${onExpandedChange}"> <cds-accordion-header>Accordion panel #1</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Expanded accordion panel content</p> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel cds-motion="on" @expandedChange="${onExpandedChange}"> <cds-accordion-header>Accordion panel #2</cds-accordion-header> <cds-accordion-content> <p cds-text="body" cds-layout="m-b:md"> Rogue rich in heavy atoms Vangelis preserve and cherish that pale blue dot venture intelligent beings. Encyclopaedia galactica encyclopaedia galactica the carbon in our apple pies not a sunrise but a galaxyrise vanquish the impossible encyclopaedia galactica. </p> <p cds-text="body"> Encyclopaedia galactica across the centuries with pretty stories for which there's little good evidence extraordinary claims require extraordinary evidence dream of the mind's eye bits of moving fluff? Extraordinary claims require extraordinary evidence the sky calls to us made in the interiors of collapsing stars citizens of distant epochs Sea of Tranquility concept of the number one and billions upon billions upon billions upon billions upon billions upon billions upon billions. </p> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel id="async" @expandedChange="${onExpandedChange}"> <cds-accordion-header>Async accordion panel</cds-accordion-header> <cds-accordion-content></cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel cds-motion="on" disabled @expandedChange="${onExpandedChange}"> <cds-accordion-header>Disabled accordion panel</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Disabled accordion content</p> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel cds-motion="on" @expandedChange="${onExpandedChange}"> <cds-accordion-header>Accordion panel #3</cds-accordion-header> <cds-accordion-content> <p cds-text="body"> Finite but unbounded stirred by starlight vanquish the impossible the ash of stellar alchemy two ghostly white figures in coveralls and helmets are softly dancing muse. </p> </cds-accordion-content> </cds-accordion-panel> </cds-accordion> `; }; /** @website */ export function darkTheme() { return html` <div cds-theme="dark"> <cds-accordion> <cds-accordion-panel expanded> <cds-accordion-header>Expanded accordion panel</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Expanded accordion content</p> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel> <cds-accordion-header>Collapsed accordion panel</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Collapsed accordion content</p> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel disabled> <cds-accordion-header>Disabled accordion panel</cds-accordion-header> <cds-accordion-content> <p cds-text="body">Disabled accordion content</p> </cds-accordion-content> </cds-accordion-panel> </cds-accordion> </div> `; } /** @website */ export function customStyles() { return html` <style> .app-custom { --border-color: midnightblue; --border-radius: 0; --border-width: 2px; --cds-alias-object-interaction-background-selected: lightskyblue; --cds-alias-object-interaction-background-hover: lightskyblue; --cds-alias-object-interaction-background-active: cornflowerblue; } </style> <cds-accordion class="app-custom"> <cds-accordion-panel expanded> <cds-accordion-header>Item 1</cds-accordion-header> <cds-accordion-content>Content 1</cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel> <cds-accordion-header>Item 2</cds-accordion-header> <cds-accordion-content>Content 2</cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel> <cds-accordion-header>Item 3</cds-accordion-header> <cds-accordion-content>Content 3</cds-accordion-content> </cds-accordion-panel> </cds-accordion> `; } export function stackview() { return html` <style> #stackview-demo cds-divider { margin: 0 calc(var(--cds-global-space-11) * -1); width: calc(100% + calc(var(--cds-global-space-11) * 2)); } </style> <cds-accordion id="stackview-demo"> <cds-accordion-panel> <cds-accordion-header> <div cds-layout="grid cols:6"> <p cds-text="secondary">Panel One</p> <p cds-text="secondary">Content One</p> </div> </cds-accordion-header> <cds-accordion-content></cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel expanded> <cds-accordion-header> <div cds-layout="grid cols:6"> <p cds-text="secondary">Panel Two</p> <p cds-text="secondary">Content Two</p> </div> </cds-accordion-header> <cds-accordion-content> <div cds-layout="vertical gap:md"> <div cds-layout="grid cols:6 gap:lg"> <p cds-text="secondary">Panel Two</p> <p cds-text="secondary">Content Two</p> </div> <cds-divider></cds-divider> <div cds-layout="grid cols:6 gap:lg"> <p cds-text="secondary">Panel Two</p> <p cds-text="secondary">Content Two</p> </div> <cds-divider></cds-divider> <div cds-layout="grid cols:6 gap:lg"> <p cds-text="secondary">Panel Two</p> <p cds-text="secondary">Content Two</p> </div> </div> </cds-accordion-content> </cds-accordion-panel> <cds-accordion-panel> <cds-accordion-header> <div cds-layout="grid cols:6"> <p cds-text="secondary">Panel Three</p> <p cds-text="secondary">Content Three</p> </div> </cds-accordion-header> <cds-accordion-content></cds-accordion-content> </cds-accordion-panel> </cds-accordion> `; }
the_stack
declare module "planet" { /** * One of the planets, asteroids, the sun or moon */ export class Planet { /** * The planet name, e.g. Mercury * @type {string} */ name: string; /** * A planet's longitude identifies what sign * it is in * @type {number} */ longitude: number; /** * A planet's latitude describes it's distance * from the ecliptic, and can be used to * determine if it is out of bounds * @type {number} */ latitude: number; /** * A planet's speed allows us to know if it is * retrograde, and to calculate whether an * aspect is applying or separating * @type {number} */ speed: number; /** * The symbol for this planet as represented in * the Kairon Semiserif font * @type {string} */ symbol: string; /** * Dictionary of symbols for the planets for * use with the Kairon Semiserif font * @type {Object} */ private symbols; /** * Instantiate a new planet object. * @param {string} name The planet's name * @param {number} lon The planet's longitude * @param {number} lat The planet's latitude * @param {number} spd The planet's speed relative to earth */ constructor(name: string, lon: number, lat: number, spd: number); /** * A planet is retrograde when it's speed relative * to earth is less than zero * @return {boolean} Whether or not the planet is retrograde */ isRetrograde(): boolean; /** * Is this one of the major planets typically included in a chart? * @return {boolean} Returns true if it is a major planet */ isMajor(): boolean; } } declare module "rp" { export interface RequestPromiseOptions { uri: string; qs: { [name: string]: string | number | boolean; }; } const rp: (options: RequestPromiseOptions) => Promise<any>; export default rp; } declare module "person" { export interface GoogleLocation { lat: number; lng: number; } export type Point = GoogleLocation; /** * Represents a person or event for whom a chart will be created */ export class Person { name: string; date: string; location: Point; /** * Google API key * @type {string} */ private static _key; /** * Creates a Person object * @param {string} public name Name of the person or event * @param {string} public date UTC date in ISO 8601 format, i.e. YYYY-MM-DDTHH:mmZ (caller must convert to UTC) * @param {Point} location The [lat: number, lon: number] of the event or person's birthplace */ constructor(name: string, date: string, location: Point); /** * Asynchronous factory function for creating people or events * @param {string} name Name of the person or event * @param {Date | string} date Exact datetime for the chart, preferably UTC date in ISO 8601 format, i.e. YYYY-MM-DDTHH:mmZ (caller must convert to UTC) * @param {Point | string} location Either an address or a lat/lng combination * @return {Promise<Person>} The Person object that was created */ static create(name: string, date: Date | string, location: Point | string): Promise<Person>; /** * Gets a timezone given a latitude and longitude * @param {Point} p Contains the latitude and longitude in decimal format */ static getTimezone(p: Point): Promise<string>; /** * Get a latitude and longitude given an address * @param {string} address The address of the desired lat/lon */ static getLatLon(address: string): Promise<Point>; } } declare module "aspect" { import { Planet } from "planet"; /** * Represents an aspect between two planets */ export class Aspect { p1: Planet; p2: Planet; /** * A label naming the aspect type, e.g. trine * @type {string} */ private _type; /** * Number of degrees away from being perfectly in aspect * @type {number} */ private _orb; /** * Is the aspect applying or separating * @type {boolean} */ private _applying; /** * Catalog of all of the aspect types available in our system * @type {AspectTypeArray} */ private _types; /** * Creates a new Aspect or throws an error if no aspect exists * between the planets * @param {Planet} public p1 First planet in the relationship * @param {Planet} public p2 Second planet in the relationship */ constructor(p1: Planet, p2: Planet); /** * Get the type assigned to this aspect * @return {string} One of the aspect type names */ readonly type: string; /** * Get the number of degrees away from being in perfect aspect * @return {number} The number of degrees (absolute value) */ readonly orb: number; /** * Get the character that will produce the correct symbol for * this aspect in the Kairon Semiserif font * @return {string} A character representing a symbol */ readonly symbol: string; /** * Is the aspect applying or separating? * @return {boolean} True if the aspect is applying */ isApplying(): boolean; /** * Is this a "major" aspect? i.e. one of those you usually * hear about in astrological forecasts * @return {boolean} True if this is a "major" aspect */ isMajor(): boolean; } } declare module "chart" { import { Person, Point } from "person"; import { Planet } from "planet"; import { Aspect } from "aspect"; export enum ChartType { Basic = 0, Transits = 1, Synastry = 2, Combined = 3, Davison = 4, CombinedTransits = 5, DavisonTransits = 6, } export interface PlanetData { name: string; lon: number; lat: number; spd: number; r: number; } export interface PlanetDataArray { [name: string]: PlanetData; } export interface ChartData { planets: PlanetDataArray; houses: Array<number>; ascendant: number; mc: number; } export interface ChartDataArray { [index: number]: ChartData; } export class Chart { name: string; p1: Person; p2: Person; type: ChartType; _planets1: Array<Planet>; _planets2: Array<Planet>; _aspects: Array<Aspect>; _ascendant: number; _houses: Array<number>; _debug: boolean; _signs: { name: string; symbol: string; v: number; }[]; constructor(name: string, p1: Person, cdata: ChartDataArray, p2?: Person, type?: ChartType); /** * Extracts planet data from ChartData and creates Planet objects for each one * @param {ChartData} cdata JSON data returned from morphemeris REST API * @return {Array<Planet>} An array of Planet objects */ getPlanets(cdata: ChartData): Array<Planet>; /** * Calculates the aspects between planets in the chart */ calculateAspects(): void; /** * Calculates longitudes for a combined chart * @param {ChartData} p1 Planet data from person one * @param {ChartData} p2 Planet data from person two */ calculateCombinedPlanets(cdata: ChartDataArray): ChartData; /** * Finds the midpoint between two planets on the "short" side * @param {number} l1 Longitude of planet one * @param {number} l2 Longitude of planet two * @return {number} Longitude of the midpoint */ getLonMidpoint(l1: number, l2: number): number; /** * Gets chart data from the online ephemeris * @param {string} date A UTC datetime string in ISO 8601 format * @param {Point} p An object with numeric lat and lng properties * @return {Promise<ChartData>} A JSON object with the data needed to implement a chart */ static getChartData(date: string, p: Point): Promise<ChartData>; /** * Refresh or set the transits to a new time * @param {string} date (Optional) Target datetime for transits in ISO 8601 format; defaults to now() */ refreshTransits(date?: string): Promise<void>; readonly houses: Array<number>; readonly aspects: Array<Aspect>; readonly ascendant: number; readonly innerPlanets: Array<Planet>; readonly outerPlanets: Array<Planet>; } } declare module "chart-factory" { import { Person, Point } from "person"; import { Chart, ChartType } from "chart"; /** * Usage: let chart: Chart = ChartFactory.create("my chart", person); */ export class ChartFactory { static create(name: string, p1: Person, p2?: Person, type?: ChartType): Promise<Chart>; /** * Calculates the lat/lon of the geographic midpoint between two lat/lon pairs * @param {Point} p1 Latitude/longitude of first location * @param {Point} p2 Latitude/longitude of second location * @return {Point} The latitude/longitude of the geographic midpoint */ static getGeoMidpoint(p1: Point, p2: Point): Point; /** * Finds the exact midpoint between two dates * @param {string} date1 The first date * @param {string} date2 The second date * @return {string} The midpoint date as an ISO 8601 string */ static getDatetimeMidpoint(date1: string, date2: string): string; /** * Converts decimal degrees to radians * @param {number} degrees Decimal representation of degrees to be converted * @return {number} Returns radians */ static toRadians: (degrees: number) => number; /** * Converts radians to decimal degrees * @param {number} radians Radians to be converted * @return {number} Returns decimal degrees */ static toDegrees: (radians: number) => number; } } declare module "astrologyjs" { export { Planet } from "planet"; export { Person, Point } from "person"; export { Aspect } from "aspect"; export { Chart, ChartType } from "chart"; export { ChartFactory } from "chart-factory"; }
the_stack
import * as angular from 'angular'; import { OrgChartPresenceEnum } from './orgChartPresenceEnum'; import { OrgChartStyleEnum } from './orgChartStyleEnum'; import { OrgChartSelectModeEnum } from './orgChartSelectModeEnum'; export interface IOrgChartScope extends angular.IScope { selectMode?: OrgChartSelectModeEnum; items: IOrgChartPersonaScope[]; selectedItems: any[]; } class OrgChartController { public static $inject: string[] = ['$scope', '$log']; public selectMode: OrgChartSelectModeEnum; constructor(public $scope: IOrgChartScope, public $log: angular.ILogService) { this.$scope.selectMode = null; this.$scope.items = []; } get items(): IOrgChartPersonaScope[] { return this.$scope.items; } set items(items: IOrgChartPersonaScope[]) { this.$scope.items = items; } get selectedItems(): IOrgChartPersonaScope[] { return this.$scope.selectedItems; } set selectedItems(selectedItems: IOrgChartPersonaScope[]) { this.$scope.selectedItems = selectedItems; } } export interface IOrgChartAttributes extends angular.IAttributes { uifSelectMode?: string; } /** * @ngdoc directive * @name uifOrgChart * @module officeuifabric.components.orgchart * * @restrict E * * @description * `<uif-org-chart />` is the main directive of the module. Renders a list of persons * grouped by a property of your choice using the uifOrgChartGroupBy-filter. The directive * supports a single- and multiple-selectionmode allowing to select and unselect by * clicking each person. The selected items can be retrieved by supplying an array in * the 'uif-selected-items'-attribute. * * See <uif-org-chart-persona /> directive to see valid presence values. * * @see {link http://dev.office.com/fabric/components/orgchart} * * @usage * * <uif-org-chart uif-select-mode="single|multiple" * uif-selected-items="selectedItems"> * <uif-org-chart-group ng-repeat="group in items | uifOrgChartGroupBy: 'department'"> * <uif-org-chart-group-title>{{group}}</uif-org-chart-group-title> * <uif-org-chart-list> * <uif-org-chart-persona uif-style="standarx(default)square" * ng-repeat="item in vm.items | filter: {'department': group}" * uif-item="item" * uif-presence="item.presence" * uif-selected="item.selected"> * <uif-org-chart-image ng-src="item.imageUrl"></uif-org-chart-image> * <uif-org-chart-presence></uif-org-chart-presence> * <uif-org-chart-details> * <uif-org-chart-primary-text>{{item.name}}</uif-org-chart-primary-text> * <uif-org-chart-secondary-text>{{item.title}}</uif-org-chart-secondary-text> * </uif-org-chart-details> * </uif-org-chart-persona> * </uif-org-chart-list> * </uif-org-chart-group> * </uif-org-chart> * * About presence: valid presence values are * */ export class OrgChartDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public template: string = '<div class="ms-OrgChart" ng-transclude ></div>'; public controller: any = OrgChartController; public scope: {} = { selectedItems: '=?uifSelectedItems' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new OrgChartDirective(); return directive; } public link(scope: IOrgChartScope, elem: angular.IAugmentedJQuery, attrs: IOrgChartAttributes, ctrl: OrgChartController): void { if (attrs.uifSelectMode) { switch (OrgChartSelectModeEnum[attrs.uifSelectMode]) { case OrgChartSelectModeEnum.single: case OrgChartSelectModeEnum.multiple: ctrl.selectMode = OrgChartSelectModeEnum[attrs.uifSelectMode]; break; default: ctrl.$log.error('Error [ngOfficeUIFabric] officeuifabric.components.orgchart - Unsupported select-mode: ' + 'The select-mode (\'' + attrs.uifSelectMode + '\) is not supperted. ' + 'Supported options are: single, multiple'); break; } } } } /** * @ngdoc directive * @name uifOrgChartGroup * @module officeuifabric.components.orgchart * * @restrict E * * @description * `<uif-org-chart-group />` is a directive used within <uif-org-chart/> directive * even * * @see {link http://dev.office.com/fabric/components/orgchart} * * @usage * * <uif-org-chart-group> * <uif-org-chart-group-title>{{group.title}}</uif-org-chart-group-title> * <uif-org-chart-list> * <uif-org-chart-persona>...</uif-org-chart-persona> * <uif-org-chart-persona>...</uif-org-chart-persona> * </uif-org-chart-list> * </uif-org-chart-group > * */ export class OrgChartGroupDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public template: string = '<div class="ms-OrgChart-group" ng-transclude ></div>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new OrgChartGroupDirective(); return directive; } } /** * @ngdoc directive * @name uifOrgChartGroupTitle * @module officeuifabric.components.orgchart * * @restrict E * * @description * `<uif-org-chart-group-title />` is a directive used within <uif-org-chart-group/> directive * * @see {link http://dev.office.com/fabric/components/orgchart} * * @usage * * <uif-org-chart-group-title>{{group}}</uif-org-chart-group-title> * */ export class OrgChartGroupTitleDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public template: string = '<div class="ms-OrgChart-groupTitle" ng-transclude ></div>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new OrgChartGroupTitleDirective(); return directive; } } /** * @ngdoc directive * @name uifOrgChartList * @module officeuifabric.components.orgchart * * @restrict E * * @description * `<uif-org-chart-list />` is a directive used within <uif-org-chart-group/> directive * * @see {link http://dev.office.com/fabric/components/orgchart} * * @usage * * <uif-org-chart-list> * <uif-org-chart-persona>...</uif-org-chart-persona> * <uif-org-chart-persona>...</uif-org-chart-persona> * </uif-org-chart-list> * */ export class OrgChartListDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public template: string = '<ul class="ms-OrgChart-list" ng-transclude ></ul>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new OrgChartListDirective(); return directive; } } export interface IOrgChartPersonaScope extends angular.IScope { item: any; personaClick: (event: any) => void; selected: boolean; presence: string; } export interface IOrgChartPersonaAttributes extends angular.IAttributes { uifStyle: string; uifPresence: string; } /** * @ngdoc directive * @name uifOrgChartPersona * @module officeuifabric.components.orgchart * * @restrict E * * @description * `<uif-org-chart-persona />` is a directive used within `<uif-org-chart-list/>` directive * * @see {link http://dev.office.com/fabric/components/orgchart} * * @usage * * <uif-org-chart-persona uif-style="standard(default)|square" * uif-item="item" * uif-presence="item.presence" * uif-selected="item.selected"> * <uif-org-chart-image ng-src="item.imageUrl"></uif-org-chart-image> * <uif-org-chart-presence></uif-org-chart-presence> * <uif-org-chart-details> * <uif-org-chart-primary-text>{{item.name}}</uif-org-chart-primary-text> * <uif-org-chart-secondary-text>{{item.title}}}</uif-org-chart-secondary-text> * </uif-org-chart-details> * </uif-org-chart-persona> * * uif-presence: Valid options are available|busy|away|blocked|dnd|offline * uif-selected: A boolean value. Allows to preselect the item * */ export class OrgChartPersonaDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public template: string = '<li class="ms-OrgChart-listItem"><div class="ms-Persona" ng-transclude ></div></li>'; public require: string = '^uifOrgChart'; public scope: {} = { item: '=?uifItem', presence: '=?uifPresence', selected: '=?uifSelected' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = ($log: angular.ILogService) => new OrgChartPersonaDirective($log); directive.$inject = ['$log']; return directive; } constructor(private $log: angular.ILogService) { } public compile( elem: angular.IAugmentedJQuery, attrs: IOrgChartPersonaAttributes, transclude: angular.ITranscludeFunction): angular.IDirectivePrePost { return { post: this.postLink }; } private postLink( scope: IOrgChartPersonaScope, elem: angular.IAugmentedJQuery, attrs: IOrgChartPersonaAttributes, ctrl: OrgChartController, transclude: angular.ITranscludeFunction): void { // handle selection if (scope.selected === undefined) { scope.selected = false; } // handle status-attribute if (scope.presence) { switch (OrgChartPresenceEnum[scope.presence]) { case OrgChartPresenceEnum.available: elem.children().eq(0).addClass('ms-Persona--available'); break; case OrgChartPresenceEnum.busy: elem.children().eq(0).addClass('ms-Persona--busy'); break; case OrgChartPresenceEnum.away: elem.children().eq(0).addClass('ms-Persona--away'); break; case OrgChartPresenceEnum.blocked: elem.children().eq(0).addClass('ms-Persona--blocked'); break; case OrgChartPresenceEnum.dnd: elem.children().eq(0).addClass('ms-Persona--dnd'); break; case OrgChartPresenceEnum.offline: elem.children().eq(0).addClass('ms-Persona--offline'); break; default: ctrl.$log.error('Error [ngOfficeUIFabric] officeuifabric.components.orgchart - Unsupported presence: ' + 'The presence (\'' + scope.presence + '\') is not supperted by the Office UI Fabric. ' + 'Supported options are: available, busy, away, blocked, dnd, offline.'); break; } } // handle style if (attrs.uifStyle) { switch (OrgChartStyleEnum[attrs.uifStyle]) { case OrgChartStyleEnum.square: elem.children().eq(0).addClass('ms-Persona--square'); break; case OrgChartStyleEnum.standard: break; default: ctrl.$log.error('Error [ngOfficeUIFabric] officeuifabric.components.orgchart - Unsupported style: ' + 'The style (\'' + attrs.uifStyle + '\) is not supperted by the Office UI Fabric. ' + 'Supported options are: standard(default), square'); break; } } // handle selectmode (from OrgChart-controller) if (ctrl.selectMode !== undefined) { elem.children().eq(0).addClass('ms-Persona--selectable'); } // set up watch to change class according to selection scope.$watch('selected', (newValue: boolean, oldValue: boolean): void => { if (ctrl.selectMode !== undefined) { if (newValue === true) { elem.children().eq(0).addClass('is-selected'); } else { elem.children().eq(0).removeClass('is-selected'); } } }); // keep track of the scopes if (scope.item) { ctrl.items.push(scope); } // initial selection if (ctrl.selectMode === OrgChartSelectModeEnum.single || ctrl.selectMode === OrgChartSelectModeEnum.multiple) { if (scope.selected) { if (ctrl.selectMode === OrgChartSelectModeEnum.single) { if (ctrl.selectedItems) { ctrl.selectedItems = []; } for (let i: number = 0; i < ctrl.items.length; i++) { if (ctrl.items[i] !== scope) { ctrl.items[i].selected = false; } } } elem.children().eq(0).addClass('is-selected'); if (ctrl.selectedItems) { ctrl.selectedItems.push(scope.item); } } } // handle click on persona LI scope.personaClick = (event: any): void => { // flip selected scope.selected = !scope.selected; // if selected if (scope.selected) { // single if (ctrl.selectMode === OrgChartSelectModeEnum.single) { if (ctrl.items) { for (let i: number = 0; i < ctrl.items.length; i++) { if (ctrl.items[i] !== scope) { ctrl.items[i].selected = false; } } } elem.children().eq(0).addClass('is-selected'); ctrl.selectedItems = []; ctrl.selectedItems.push(scope.item); } // multiple if (ctrl.selectMode === OrgChartSelectModeEnum.multiple) { elem.children().eq(0).addClass('is-selected'); if (ctrl.selectedItems) { ctrl.selectedItems.push(scope.item); } } } else { elem.children().eq(0).removeClass('is-selected'); if (ctrl.selectedItems) { let index: number = ctrl.selectedItems.indexOf(scope.item); if (index > -1) { ctrl.selectedItems.splice(index, 1); } } } scope.$apply(); }; // create event for click on LI element if any selection mode if ((ctrl.selectMode === OrgChartSelectModeEnum.single || ctrl.selectMode === OrgChartSelectModeEnum.multiple) && scope.item) { elem.children().eq(0).on('click', scope.personaClick); } } } /** * @ngdoc directive * @name uifOrgChartImage * @module officeuifabric.components.orgchart * * @restrict E * * @description * `<uif-org-chart-image />` is a directive used within <uif-org-chart-persona/> directive * * @see {link http://dev.office.com/fabric/components/orgchart} * * @usage * * <uif-org-chart-image ng-src="item.imageUrl"></uif-org-chart-image> * */ export class OrgChartImageDirective implements angular.IDirective { public restrict: string = 'E'; public replace: boolean = true; public template: string = ` <div class="ms-Persona-imageArea"> <i class="ms-Persona-placeholder ms-Icon ms-Icon--person"></i> <img class="ms-Persona-image" ng-src="{{ngSrc}}" /> </div> `; public scope: {} = { ngSrc: '=' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new OrgChartImageDirective(); return directive; } } /** * @ngdoc directive * @name uifOrgChartPresence * @module officeuifabric.components.orgchart * * @restrict E * * @description * `<uif-org-chart-presence />` is a directive used within <uif-org-chart-persona/> directive * * @see {link http://dev.office.com/fabric/components/orgchart} * * @usage * * <uif-org-chart-presence></uif-org-chart-presence> * */ export class OrgChartPresenceDirective implements angular.IDirective { public restrict: string = 'E'; public replace: boolean = true; public template: string = '<div class="ms-Persona-presence" ></div>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new OrgChartPresenceDirective(); return directive; } public link(scope: any, elem: angular.IAugmentedJQuery, attrs: any, ctrl: any): void { if (!scope.$parent.presence) { elem.css('display', 'none'); } } } /** * @ngdoc directive * @name uifOrgChartDetails * @module officeuifabric.components.orgchart * * @restrict E * * @description * `<uif-org-chart-details />` is a directive used within <uif-org-chart-persona/> directive * * @see {link http://dev.office.com/fabric/components/orgchart} * * @usage * * <uif-org-chart-details> * <uif-org-chart-primary-text>Lorem Ipsum</uif-org-chart-primary-text> * <uif-org-chart-secondary-text>Lorem Ipsum</uif-org-chart-secondary-text> * </uif-org-chart-details> * */ export class OrgChartDetailsDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public template: string = '<div class="ms-Persona-details" ng-transclude ></div>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new OrgChartDetailsDirective(); return directive; } } /** * @ngdoc directive * @name uifOrgChartPrimaryText * @module officeuifabric.components.orgchart * * @restrict E * * @description * `<uif-org-chart-primary-text />` is a directive used within <uif-org-chart-details/> directive * * @see {link http://dev.office.com/fabric/components/orgchart} * * @usage * * <uif-org-chart-primary-text>{{item.name}}</uif-org-chart-primary-text> * */ export class OrgChartPrimaryTextDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public template: string = '<div class="ms-Persona-primaryText" ng-transclude ></div>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new OrgChartPrimaryTextDirective(); return directive; } } /** * @ngdoc directive * @name uifOrgChartSecondaryText * @module officeuifabric.components.orgchart * * @restrict E * * @description * `<uif-org-chart-secondary-text />` is a directive used within <uif-org-chart-details/> directive * * @see {link http://dev.office.com/fabric/components/orgchart} * * @usage * * <uif-org-chart-secondary-text>item.title</uif-org-chart-secondary-text> * */ export class OrgChartSecondaryTextDirective implements angular.IDirective { public restrict: string = 'E'; public transclude: boolean = true; public replace: boolean = true; public template: string = '<div class="ms-Persona-secondaryText" ng-transclude ></div>'; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new OrgChartSecondaryTextDirective(); return directive; } } /** * @ngdoc filter * @name OrgChartGroupByFilter * @module officeuifabric.components.orgchart * * @description * Filter used by the the OrgChartDirective to group items * * @usage * * * * */ export class OrgChartGroupByFilter { public static factory(): any { return function (collection: any[], key: string): any[] { let result: any[] = []; if (!collection) { return; } for (let i: number = 0; i < collection.length; i++) { let value: string = collection[i][key]; if (result.indexOf(value) === -1) { result.push(value); } } return result; }; } } /** * @ngdoc module * @name officeuifabric.components.orgchart * * @description * OrgChart */ export let module: angular.IModule = angular.module('officeuifabric.components.orgchart', [ 'officeuifabric.components' ]) .directive('uifOrgChart', OrgChartDirective.factory()) .directive('uifOrgChartGroup', OrgChartGroupDirective.factory()) .directive('uifOrgChartGroupTitle', OrgChartGroupTitleDirective.factory()) .directive('uifOrgChartList', OrgChartListDirective.factory()) .directive('uifOrgChartPersona', OrgChartPersonaDirective.factory()) .directive('uifOrgChartImage', OrgChartImageDirective.factory()) .directive('uifOrgChartPresence', OrgChartPresenceDirective.factory()) .directive('uifOrgChartDetails', OrgChartDetailsDirective.factory()) .directive('uifOrgChartPrimaryText', OrgChartPrimaryTextDirective.factory()) .directive('uifOrgChartSecondaryText', OrgChartSecondaryTextDirective.factory()) .filter('uifOrgChartGroupBy', OrgChartGroupByFilter.factory);
the_stack
import * as React from 'react'; import { Dispatch, useEffect, useReducer, useState } from 'react'; import { Provider } from 'react-redux'; import { Redirect, Route, Switch } from 'react-router'; import { ConnectedRouter } from 'connected-react-router'; import { ProtectedRoute } from './components/organisms'; import { AboutPage, AddRepositoryPage, CustomResourcePage, JsonStorePage, LoginPage, LogoutPage, NewProjectPage, NewSecretPage, NewTeamPage, NotFoundPage, OrganizationListPage, OrganizationPage, ProcessFormPage, ProcessListPage, ProcessPage, ProcessWizardPage, ProfilePage, ProjectPage, RepositoryPage, SecretPage, TeamPage, UnauthorizedPage, UserActivityPage } from './components/pages'; import { Layout } from './components/templates'; import { history, store } from './store'; import NewStorageQueryPage from './components/pages/JsonStorePage/NewStorageQueryPage'; import EditStoreQueryPage from './components/pages/JsonStorePage/EditStoreQueryPage'; import { initialState, LoadingAction, reducer } from './reducers/loading'; import NewStorePage from './components/pages/JsonStorePage/NewStorePage'; import NodeRosterPage from './components/pages/NodeRoster/NodeRosterPage'; import HostPage from './components/pages/NodeRoster/HostPage'; import { UserSessionContext, checkSession, UserInfo } from './session'; export const LoadingDispatch = React.createContext<Dispatch<LoadingAction>>( {} as Dispatch<LoadingAction> ); export const ReduxStore = React.createContext(store); export const LoadingState = React.createContext(false); const App = () => { const [state, dispatch] = useReducer(reducer, initialState); const [userInfo, setUserInfo] = useState<UserInfo | undefined>(); const [loggingIn, setLoggingIn] = useState(true); useEffect(() => { checkSession({ userInfo, setUserInfo, loggingIn: false, setLoggingIn }); }, [userInfo]); return ( <Provider store={store}> <LoadingState.Provider value={state.loading}> <LoadingDispatch.Provider value={dispatch}> <ConnectedRouter history={history}> <UserSessionContext.Provider value={{ userInfo, setUserInfo, loggingIn, setLoggingIn, history }}> <Switch> <Route exact={true} path="/"> <Redirect to="/activity" /> </Route> <Route path="/login"> <LoginPage/> </Route> <Route path="/logout/done"> <LogoutPage/> </Route> <Route path="/unauthorized"> <UnauthorizedPage/> </Route> <Layout> <Switch> <ProtectedRoute path="/activity" exact={true} component={UserActivityPage} /> <ProtectedRoute path="/org"> <Switch> <Route path="/org" exact={true} component={OrganizationListPage} /> <Route path="/org/:orgName/project/:projectName/repository/_new" exact={true} component={AddRepositoryPage} /> <Route path="/org/:orgName/project/:projectName/repository/:repoName" component={RepositoryPage} /> <Route path="/org/:orgName/project/_new" exact={true} component={NewProjectPage} /> <Route path="/org/:orgName/project/:projectName" component={ProjectPage} /> <Route path="/org/:orgName/secret/_new" exact={true} component={NewSecretPage} /> <Route path="/org/:orgName/secret/:secretName" component={SecretPage} /> <Route path="/org/:orgName/team/_new" exact={true} component={NewTeamPage} /> <Route path="/org/:orgName/team/:teamName" component={TeamPage} /> <Route path="/org/:orgName/jsonstore/_new" exact={true} component={NewStorePage} /> <Route path="/org/:orgName/jsonstore/:storeName/query/_new" exact={true} component={NewStorageQueryPage} /> <Route path="/org/:orgName/jsonstore/:storeName/query/:queryName/edit" exact={true} component={EditStoreQueryPage} /> <Route path="/org/:orgName/jsonstore/:storeName" component={JsonStorePage} /> <Route path="/org/:orgName" component={OrganizationPage} /> </Switch> </ProtectedRoute> <ProtectedRoute path="/process"> <Switch> <Route path="/process" exact={true} component={ProcessListPage} /> <Route path="/process/:processInstanceId/form/:formName/:mode" component={ProcessFormPage} /> <ProtectedRoute path="/process/:instanceId/wizard" exact={true} component={ProcessWizardPage} /> <Route path="/process/:instanceId" component={ProcessPage} /> </Switch> </ProtectedRoute> <ProtectedRoute path="/noderoster"> <Switch> <Route path="/noderoster/host/:id" component={HostPage} /> <Route path="/noderoster" component={NodeRosterPage} /> </Switch> </ProtectedRoute> <ProtectedRoute path="/about" exact={true} component={AboutPage} /> <ProtectedRoute path="/profile" component={ProfilePage} /> <ProtectedRoute path="/custom"> <Switch> <Route path="/custom/:resourceName" component={CustomResourcePage} /> </Switch> </ProtectedRoute> <Route component={NotFoundPage} /> </Switch> </Layout> </Switch> </UserSessionContext.Provider> </ConnectedRouter> </LoadingDispatch.Provider> </LoadingState.Provider> </Provider> ); // } }; export default App;
the_stack
import { store, afterChange, initStore } from '../..'; import { propPathChanges, TaskType } from '../testUtils'; declare module '../..' { interface Store { // Add a few things used in this file taskList?: TaskType[]; longArrayToCompareSort?: TaskType[]; shortArrayToCompareSort?: TaskType[]; } } const handleChange = jest.fn(); afterChange(handleChange); afterEach(() => { initStore(); // empty the store handleChange.mockClear(); }); it('should add a string', () => { store.newString = 'test'; expect(handleChange).toHaveBeenCalledTimes(1); const changeEvent = handleChange.mock.calls[0][0]; expect(changeEvent.store.newString).toBe('test'); }); it('should add null', () => { store.newNull = null; expect(handleChange).toHaveBeenCalledTimes(1); const changeEvent = handleChange.mock.calls[0][0]; expect(changeEvent.store.newNull).toBe(null); }); it('should add an object', () => { store.newObject = { someProp: 'someValue', }; expect(handleChange).toHaveBeenCalledTimes(1); const changeEvent = handleChange.mock.calls[0][0]; expect(changeEvent.store.newObject).toEqual( expect.objectContaining({ someProp: 'someValue', }) ); }); it('should Object.assign() just fine', () => { store.level1 = { level2: 'text', }; Object.assign(store.level1, { level2B: 'new text', }); expect(store).toEqual({ level1: { level2: 'text', level2B: 'new text', }, }); Object.assign(store.level1, { level2: 'new text', }); expect(store).toEqual({ level1: { level2: 'new text', level2B: 'new text', }, }); Object.assign(store, { level1B: 'new text', }); expect(store).toEqual({ level1: { level2: 'new text', level2B: 'new text', }, level1B: 'new text', }); }); it('should allow uncommon prop types', () => { store.interestingObject = { level1: {}, }; store.interestingObject.level1[0] = 'numeric key'; const sym = Symbol('My symbol'); store.interestingObject.level1[sym] = 'symbol key'; expect(propPathChanges(handleChange)).toEqual([ '', 'interestingObject.level1', 'interestingObject.level1.Symbol(My symbol)', ]); expect(handleChange).toHaveBeenCalledTimes(3); }); it('should allow prop types that are methods', () => { // There is logic with special treatment for methods. We want to make sure // this doesn't interfere with reading good old property names on an object. store.methodNames = { // Array mutator methods copyWithin: { foo: 'copyWithin' }, fill: { foo: 'fill' }, pop: { foo: 'pop' }, push: { foo: 'push' }, reverse: { foo: 'reverse' }, shift: { foo: 'shift' }, sort: { foo: 'sort' }, splice: { foo: 'splice' }, unshift: { foo: 'unshift' }, // Array read methods concat: { foo: 'concat' }, includes: { foo: 'includes' }, indexOf: { foo: 'indexOf' }, join: { foo: 'join' }, lastIndexOf: { foo: 'lastIndexOf' }, slice: { foo: 'slice' }, toSource: { foo: 'toSource' }, toString: { foo: 'toString' }, toLocaleString: { foo: 'toLocaleString' }, // Array props length: { foo: 'length' }, // Map and set mutator methods add: { foo: 'add' }, clear: { foo: 'clear' }, delete: { foo: 'delete' }, set: { foo: 'set' }, // Map and set read methods entries: { foo: 'entries' }, forEach: { foo: 'forEach' }, get: { foo: 'get' }, has: { foo: 'has' }, keys: { foo: 'keys' }, values: { foo: 'values' }, // Map and set prop size: { foo: 'size' }, }; expect(store.methodNames.copyWithin.foo).toBe('copyWithin'); expect(store.methodNames.fill.foo).toBe('fill'); expect(store.methodNames.pop.foo).toBe('pop'); expect(store.methodNames.push.foo).toBe('push'); expect(store.methodNames.reverse.foo).toBe('reverse'); expect(store.methodNames.shift.foo).toBe('shift'); expect(store.methodNames.sort.foo).toBe('sort'); expect(store.methodNames.splice.foo).toBe('splice'); expect(store.methodNames.unshift.foo).toBe('unshift'); expect(store.methodNames.concat.foo).toBe('concat'); expect(store.methodNames.includes.foo).toBe('includes'); expect(store.methodNames.indexOf.foo).toBe('indexOf'); expect(store.methodNames.join.foo).toBe('join'); expect(store.methodNames.lastIndexOf.foo).toBe('lastIndexOf'); expect(store.methodNames.slice.foo).toBe('slice'); expect(store.methodNames.toSource.foo).toBe('toSource'); expect(store.methodNames.toString.foo).toBe('toString'); expect(store.methodNames.toLocaleString.foo).toBe('toLocaleString'); expect(store.methodNames.length.foo).toBe('length'); expect(store.methodNames.set.foo).toBe('set'); expect(store.methodNames.add.foo).toBe('add'); expect(store.methodNames.delete.foo).toBe('delete'); expect(store.methodNames.clear.foo).toBe('clear'); expect(store.methodNames.entries.foo).toBe('entries'); expect(store.methodNames.forEach.foo).toBe('forEach'); expect(store.methodNames.get.foo).toBe('get'); expect(store.methodNames.has.foo).toBe('has'); expect(store.methodNames.keys.foo).toBe('keys'); expect(store.methodNames.values.foo).toBe('values'); expect(store.methodNames.size.foo).toBe('size'); }); it('should allow dates', () => { const dateObject = new Date('2007-07-07T07:07:07'); store.data = { dateObject, foo: 'bar', }; const date = store.data.dateObject; store.data.foo = 'baz'; expect(date).toBe(dateObject); }); it('should allow regex', () => { const regExLiteral = /(.*)\.js$/; store.data = { regExLiteral, foo: 'bar', }; const regEx = store.data.regExLiteral; store.data.foo = 'baz'; expect(regEx).toBe(regExLiteral); expect('filename.js'.match(store.data.regExLiteral)![1]).toBe('filename'); }); it('should add an array', () => { store.newArray = []; expect(handleChange).toHaveBeenCalledTimes(1); const changeEvent = handleChange.mock.calls[0][0]; expect(changeEvent.store.newArray).toEqual([]); }); it('should add an array with numbers', () => { store.newArray = [1]; expect(handleChange).toHaveBeenCalledTimes(1); const changeEvent = handleChange.mock.calls[0][0]; expect(changeEvent.store.newArray).toEqual([1]); }); it("should add an array that's a real mixed bag", () => { store.newMixedArray = [ 1, 2, undefined, null, 'cats', false, true, { prop: 'val' }, ]; expect(handleChange).toHaveBeenCalledTimes(1); const changeEvent = handleChange.mock.calls[0][0]; expect(changeEvent.store.newMixedArray).toEqual([ 1, 2, undefined, null, 'cats', false, true, { prop: 'val' }, ]); }); it('should update an item in an array', () => { store.arrToUpdate = [1, 2, 3]; store.arrToUpdate[1] = 'cats'; expect(store.arrToUpdate).toEqual([1, 'cats', 3]); expect(propPathChanges(handleChange)).toEqual(['', 'arrToUpdate.1']); }); it('should update an object in an array', () => { store.arrToDeepUpdate = [ { name: 'David' }, { name: 'Erica' }, { name: 'Sam' }, ]; store.arrToDeepUpdate[1].name = 'Kerry'; expect(store.arrToDeepUpdate[1].name).toEqual('Kerry'); expect(propPathChanges(handleChange)).toEqual(['', 'arrToDeepUpdate.1.name']); }); it('should delete a string', () => { store.deletionTest = { animal: 'cat', name: { first: 'Professor', last: 'Everywhere', }, }; delete store.deletionTest.name; expect(store.deletionTest).toHaveProperty('animal'); expect(store.deletionTest).not.toHaveProperty('name'); expect(propPathChanges(handleChange)).toEqual(['', 'deletionTest']); }); it('should perform read operations without triggering changes', () => { store.arrayToRead = [1, 2, 3, 4]; handleChange.mockReset(); expect(store.arrayToRead.find((item: number) => item > 2)).toBe(3); expect(store.arrayToRead.findIndex((item: number) => item > 2)).toBe(2); expect(store.arrayToRead.concat([5, 6])).toEqual([1, 2, 3, 4, 5, 6]); expect(store.arrayToRead.join('~')).toBe('1~2~3~4'); expect(store.arrayToRead.toString()).toBe('1,2,3,4'); expect(store.arrayToRead.indexOf(2)).toBe(1); expect(store.arrayToRead.lastIndexOf(2)).toBe(1); expect(store.arrayToRead.includes(2)).toBe(true); expect(store.arrayToRead.includes(22)).toBe(false); expect(store.arrayToRead.slice()).not.toBe(store.arrayToRead); // None of these should trigger a change expect(handleChange).not.toHaveBeenCalled(); }); /* -- Mutating arrays -- */ it('should sort()', () => { store.arrayToSort = [3, 4, 2, 1]; store.arrayToSort.sort(); expect(store.arrayToSort).toEqual([1, 2, 3, 4]); // We don't know the order or these (in practice, Node 10 is different to Node 12) expect(propPathChanges(handleChange)).toEqual( expect.arrayContaining(['arrayToSort']) ); // V8 uses a different algorithm for < and > 10 items, so we test both store.longArrayToCompareSort = [ { id: 3, name: 'Task 3' }, { id: 4, name: 'Task 4' }, { id: 11, name: 'Task 11' }, { id: 2, name: 'Task 2' }, { id: 1, name: 'Task 1' }, { id: 5, name: 'Task 5' }, { id: 10, name: 'Task 10' }, { id: 6, name: 'Task 6' }, { id: 7, name: 'Task 7' }, { id: 8, name: 'Task 8' }, { id: 9, name: 'Task 9' }, { id: 12, name: 'Task 12' }, ]; store.longArrayToCompareSort.sort((a, b) => a.id - b.id); expect(store.longArrayToCompareSort).toEqual([ { id: 1, name: 'Task 1' }, { id: 2, name: 'Task 2' }, { id: 3, name: 'Task 3' }, { id: 4, name: 'Task 4' }, { id: 5, name: 'Task 5' }, { id: 6, name: 'Task 6' }, { id: 7, name: 'Task 7' }, { id: 8, name: 'Task 8' }, { id: 9, name: 'Task 9' }, { id: 10, name: 'Task 10' }, { id: 11, name: 'Task 11' }, { id: 12, name: 'Task 12' }, ]); store.shortArrayToCompareSort = [ { id: 3, name: 'Task 3' }, { id: 4, name: 'Task 4' }, { id: 2, name: 'Task 2' }, { id: 1, name: 'Task 1' }, ]; store.shortArrayToCompareSort.sort((a, b) => a.id - b.id); expect(store.shortArrayToCompareSort).toEqual([ { id: 1, name: 'Task 1' }, { id: 2, name: 'Task 2' }, { id: 3, name: 'Task 3' }, { id: 4, name: 'Task 4' }, ]); }); it('should update the paths in a sorted array', () => { store.taskList = [ { id: 3, name: 'Task 3' }, { id: 4, name: 'Task 4' }, { id: 2, name: 'Task 2' }, { id: 1, name: 'Task 1' }, ]; const { taskList } = store; taskList.sort((a, b) => a.id - b.id); jest.resetAllMocks(); // Check the sort works expect(taskList[0].id).toBe(1); taskList[0].name = 'A new name'; expect(propPathChanges(handleChange)).toEqual(['taskList.0.name']); }); it('should not allow setting of a deleted thing', () => { store.test = { animal: 'cat', name: 'Steven2', }; delete store.test; handleChange.mockClear(); expect(() => { store.test.animal = 'dog'; }).toThrowError(); expect(handleChange).toHaveBeenCalledTimes(0); }); it('calls listeners with the changed path', () => { store.deepObject = { objectProp: { arr: [ 1, 2, { name: 'David', }, ], }, }; // Doesn't matter how the item is referenced const { arr } = store.deepObject.objectProp; const secondItem = arr[2]; secondItem.name = 'Sam'; expect(propPathChanges(handleChange)).toEqual([ '', 'deepObject.objectProp.arr.2.name', ]); }); it('should handle deep Maps', () => { const taskList: TaskType[] = [ { id: 0, name: 'Task zero', done: false, }, { id: 1, name: 'Task one', done: false, }, ]; store.deepMap = new Map([['taskList', taskList]]); store.deepMap.get('taskList')[1].done = true; expect(propPathChanges(handleChange)).toEqual([ '', 'deepMap.taskList.1.done', ]); }); it('should handle Sets', () => { store.set = new Set([ { id: 0, name: 'Task zero', done: false, }, { id: 1, name: 'Task one', done: false, }, ]); store.set.forEach((task: TaskType) => { // eslint-disable-next-line no-param-reassign task.done = true; }); expect(propPathChanges(handleChange)).toEqual([ '', // TODO (davidg): clearly this is not ideal 'set.[object Object].done', 'set.[object Object].done', ]); });
the_stack
import { ColorRGBA64, parseColor } from "@microsoft/fast-colors"; import { AppliedDesignTokens, AppliedRecipes, PluginNodeData, RecipeEvaluation, } from "../core/model"; import { PluginNode } from "../core/node"; import { DesignTokenType } from "../core/ui/design-token-registry"; function isNodeType<T extends BaseNode>(type: NodeType): (node: BaseNode) => node is T { return (node: BaseNode): node is T => node.type === type; } export const isDocumentNode = isNodeType<DocumentNode>("DOCUMENT"); export const isPageNode = isNodeType<PageNode>("PAGE"); export const isSliceNode = isNodeType<SliceNode>("SLICE"); export const isFrameNode = isNodeType<FrameNode>("FRAME"); export const isGroupNode = isNodeType<GroupNode>("GROUP"); export const isComponentNode = isNodeType<ComponentNode>("COMPONENT"); export const isComponentSetNode = isNodeType<ComponentNode>("COMPONENT_SET"); export const isInstanceNode = isNodeType<InstanceNode>("INSTANCE"); export const isBooleanOperationNode = isNodeType<BooleanOperationNode>( "BOOLEAN_OPERATION" ); export const isVectorNode = isNodeType<VectorNode>("VECTOR"); export const isStarNode = isNodeType<StarNode>("STAR"); export const isLineNode = isNodeType<LineNode>("LINE"); export const isEllipseNode = isNodeType<EllipseNode>("ELLIPSE"); export const isPolygonNode = isNodeType<PolygonNode>("POLYGON"); export const isRectangleNode = isNodeType<RectangleNode>("RECTANGLE"); export const isTextNode = isNodeType<TextNode>("TEXT"); export function isSceneNode(node: BaseNode): node is SceneNode { return [ isSliceNode, isFrameNode, isGroupNode, isComponentNode, isComponentSetNode, isInstanceNode, isBooleanOperationNode, isVectorNode, isStarNode, isLineNode, isEllipseNode, isPolygonNode, isRectangleNode, isTextNode, ].some((test: (node: BaseNode) => boolean) => test(node)); } export function canHaveChildren( node: BaseNode ): node is | DocumentNode | PageNode | FrameNode | GroupNode | BooleanOperationNode | InstanceNode | ComponentNode | ComponentSetNode { return [ isDocumentNode, isPageNode, isFrameNode, isGroupNode, isBooleanOperationNode, isInstanceNode, isComponentNode, isComponentSetNode, ].some((test: (node: BaseNode) => boolean) => test(node)); } export class FigmaPluginNode extends PluginNode { public id: string; public type: string; private node: BaseNode; constructor(node: BaseNode) { super(); // Controller.nodeCount++; // console.log(" new FigmaPluginNode", node.id, node.name, node); this.node = node; this.id = node.id; this.type = node.type; this.loadLocalDesignTokens(); this.loadRecipes(); this.loadRecipeEvaluations(); // If it's an instance node, the `recipes` may also include main component settings. Deduplicate them. if (isInstanceNode(this.node)) { const mainComponentNode = (this.node as InstanceNode).mainComponent; if (mainComponentNode) { this.deduplicateComponentDesignTokens(mainComponentNode); this.deduplicateComponentRecipes(mainComponentNode); } } // if (this._recipes.size) { // console.log(" final recipes", this._recipes.serialize()); // } // TODO This isn't working and is causing a lot of token evaluation issues. It would be nice if _some_ layers // in the design tool could have a fixed color and provide that to the tokens, but the logic for _which_ // layers turns out to be pretty complicated. // For now the requirement is basing the adaptive design with a "layer" recipe. // this.setupFillColor(); } private deduplicateComponentDesignTokens(node: BaseNode) { this._componentDesignTokens = new AppliedDesignTokens(); const componentDesignTokensJson = node.getSharedPluginData( "fast", "designTokens" ); this._componentDesignTokens.deserialize(componentDesignTokensJson); this._componentDesignTokens.forEach((token, tokenId) => { this._localDesignTokens.delete(tokenId); }); } private deduplicateComponentRecipes(node: BaseNode) { this._componentRecipes = new AppliedRecipes(); const componentRecipesJson = node.getSharedPluginData("fast", "recipes"); this._componentRecipes.deserialize(componentRecipesJson); this._componentRecipes.forEach((recipe, recipeId) => { this._recipes.delete(recipeId); }); } public canHaveChildren(): boolean { return canHaveChildren(this.node); } public children(): FigmaPluginNode[] { if (canHaveChildren(this.node)) { const children: FigmaPluginNode[] = []; // console.log(" get children"); for (const child of this.node.children) { children.push(new FigmaPluginNode(child)); } return children; } else { return []; } } public supports(): Array<DesignTokenType> { return Object.keys(DesignTokenType).filter((key: string) => { switch (key) { case DesignTokenType.layerFill: case DesignTokenType.backgroundFill: return [ isDocumentNode, isPageNode, isFrameNode, isRectangleNode, isEllipseNode, isPolygonNode, isStarNode, isBooleanOperationNode, isVectorNode, isComponentNode, isInstanceNode, ].some((test: (node: BaseNode) => boolean) => test(this.node)); case DesignTokenType.strokeFill: case DesignTokenType.strokeWidth: return [ isFrameNode, isRectangleNode, isEllipseNode, isPolygonNode, isStarNode, isLineNode, isVectorNode, isComponentNode, isInstanceNode, ].some((test: (node: BaseNode) => boolean) => test(this.node)); case DesignTokenType.cornerRadius: return [ isFrameNode, isRectangleNode, isEllipseNode, isPolygonNode, isStarNode, isComponentNode, isInstanceNode, ].some((test: (node: BaseNode) => boolean) => test(this.node)); case DesignTokenType.foregroundFill: return [ isFrameNode, isRectangleNode, isEllipseNode, isPolygonNode, isLineNode, isStarNode, isBooleanOperationNode, isVectorNode, isComponentNode, isInstanceNode, isTextNode, ].some((test: (node: BaseNode) => boolean) => test(this.node)); case DesignTokenType.fontName: case DesignTokenType.fontSize: case DesignTokenType.lineHeight: return isTextNode(this.node); case DesignTokenType.designToken: return true; default: return false; } }) as Array<DesignTokenType>; } public paint(data: RecipeEvaluation): void { switch (data.type) { case DesignTokenType.strokeFill: case DesignTokenType.layerFill: case DesignTokenType.backgroundFill: case DesignTokenType.foregroundFill: this.paintColor(data); break; case DesignTokenType.strokeWidth: this.paintStrokeWidth(data); break; case DesignTokenType.cornerRadius: this.paintCornerRadius(data); break; case DesignTokenType.fontName: { // TODO Handle font list better and font weight const families = data.value.split(","); const fontName = { family: families[0], style: "Regular" }; figma.loadFontAsync(fontName).then(x => { (this.node as TextNode).fontName = fontName; }); } break; case DesignTokenType.fontSize: { const textNode = this.node as TextNode; figma.loadFontAsync(textNode.fontName as FontName).then(x => { textNode.fontSize = Number.parseFloat(data.value); }); } break; case DesignTokenType.lineHeight: { const textNode = this.node as TextNode; figma.loadFontAsync(textNode.fontName as FontName).then(x => { textNode.lineHeight = { value: Number.parseFloat(data.value), unit: "PIXELS", }; }); } break; default: throw new Error(`Recipe could not be painted ${JSON.stringify(data)}`); } } public parent(): FigmaPluginNode | null { const parent = this.node.parent; if (parent === null) { return null; } // console.log(" get parent"); return new FigmaPluginNode(parent); } public getEffectiveFillColor(): ColorRGBA64 | null { let node: BaseNode | null = this.node; while (node !== null) { if ((node as GeometryMixin).fills) { const fills = (node as GeometryMixin).fills; if (Array.isArray(fills)) { const paints: SolidPaint[] = fills.filter( (fill: Paint) => fill.type === "SOLID" && fill.visible ); // TODO: how do we process multiple paints? if (paints.length === 1) { const parsed = ColorRGBA64.fromObject(paints[0].color); if (parsed instanceof ColorRGBA64) { return parsed; } } } } node = node.parent; } return null; } protected getPluginData<K extends keyof PluginNodeData>(key: K): string | undefined { let value: string | undefined = this.node.getSharedPluginData( "fast", key as string ); if (value === "") { value = undefined; } // console.log(" getPluginData", this.node.id, this.node.type, key, value); return value; } protected setPluginData<K extends keyof PluginNodeData>(key: K, value: string): void { // console.log(" setPluginData", this.node.id, this.node.type, key, value); this.node.setSharedPluginData("fast", key, value); } protected deletePluginData<K extends keyof PluginNodeData>(key: K): void { // console.log(" deletePluginData", this.node.id, this.node.type, key); this.node.setSharedPluginData("fast", key, ""); } private paintColor(data: RecipeEvaluation): void { let paint: Paint | null = null; if (data.value.startsWith("linear-gradient")) { const linearMatch = /linear-gradient\((?<params>.+)\)/; const matches = data.value.match(linearMatch); if (matches && matches.groups) { const array = matches.groups.params.split(",").map(p => p.trim()); let degrees: number = 90; if (array[0].endsWith("deg")) { const angle = array.shift()?.replace("deg", "") || "90"; degrees = Number.parseFloat(angle); } const radians: number = degrees * (Math.PI / 180); const paramMatch = /(?<color>#[\w\d]+)( (?<pos>.+))?/; const stops = array.map((p, index, array) => { const paramMatches = p.match(paramMatch); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const color = parseColor(paramMatches?.groups?.color || "FF00FF")!; let position: number = 0; if (paramMatches?.groups && paramMatches?.groups?.pos) { if (paramMatches.groups.pos.endsWith("%")) { position = Number.parseFloat(paramMatches.groups.pos) / 100; } else if (paramMatches.groups.pos.startsWith("calc(100% - ")) { const px = Number.parseFloat( paramMatches.groups.pos .replace("calc(100% - ", "") .replace("px)", "") ); const size = degrees === 90 || degrees === 270 ? (this.node as LayoutMixin).height : (this.node as LayoutMixin).width; position = (size - px) / size; } } else if (index === array.length - 1) { position = 1; } const stop: ColorStop = { position, color: { r: color.r, g: color.g, b: color.b, a: color.a, }, }; return stop; }); const gradientPaint: GradientPaint = { type: "GRADIENT_LINEAR", gradientStops: stops, gradientTransform: [ [Math.cos(radians), Math.sin(radians), 0], [Math.sin(radians) * -1, Math.cos(radians), 1], ], }; paint = gradientPaint; } } else { // Assume it's solid const color = parseColor(data.value); if (color === null) { throw new Error( `The value "${data.value}" could not be converted to a ColorRGBA64` ); } const colorObject = color.toObject(); const solidPaint: SolidPaint = { type: "SOLID", visible: true, opacity: colorObject.a, blendMode: "NORMAL", color: { r: colorObject.r, g: colorObject.g, b: colorObject.b, }, }; paint = solidPaint; } switch (data.type) { case DesignTokenType.layerFill: case DesignTokenType.backgroundFill: case DesignTokenType.foregroundFill: (this.node as any).fills = [paint]; break; case DesignTokenType.strokeFill: (this.node as any).strokes = [paint]; break; } } private paintStrokeWidth(data: RecipeEvaluation): void { (this.node as any).strokeWeight = Number.parseFloat(data.value); } private paintCornerRadius(data: RecipeEvaluation): void { (this.node as any).cornerRadius = data.value; } }
the_stack
namespace Linqer { export interface Enumerable extends Iterable<any> { /** * Applies an accumulator function over a sequence. * The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value. * * @param {*} accumulator * @param {(acc: any, item: any) => any} aggregator * @returns {*} * @memberof Enumerable */ aggregate(accumulator: any, aggregator: (acc: any, item: any) => any): any; /** * Determines whether all elements of a sequence satisfy a condition. * @param condition * @returns true if all */ all(condition: IFilter): boolean; /** * Determines whether any element of a sequence exists or satisfies a condition. * * @param {IFilter} condition * @returns {boolean} * @memberof Enumerable */ any(condition: IFilter): boolean; /** * Appends a value to the end of the sequence. * * @param {*} item * @returns {Enumerable} * @memberof Enumerable */ append(item: any): Enumerable; /** * Computes the average of a sequence of numeric values. * * @returns {(number | undefined)} * @memberof Enumerable */ average(): number | undefined; /** * Returns itself * * @returns {Enumerable} * @memberof Enumerable */ asEnumerable(): Enumerable; /** * Checks the elements of a sequence based on their type * If type is a string, it will check based on typeof, else it will use instanceof. * Throws if types are different. * @param {(string | Function)} type * @returns {Enumerable} * @memberof Enumerable */ cast(type: string | Function): Enumerable; /** * Determines whether a sequence contains a specified element. * A custom function can be used to determine equality between elements. * * @param {*} item * @param {IEqualityComparer} equalityComparer * @returns {boolean} * @memberof Enumerable */ contains(item: any, equalityComparer: IEqualityComparer): boolean; defaultIfEmpty(): never; /** * Produces the set difference of two sequences * WARNING: using the comparer is slower * * @param {IterableType} iterable * @param {IEqualityComparer} equalityComparer * @returns {Enumerable} * @memberof Enumerable */ except(iterable: IterableType, equalityComparer: IEqualityComparer): Enumerable; /** * Produces the set intersection of two sequences. * WARNING: using a comparer is slower * * @param {IterableType} iterable * @param {IEqualityComparer} equalityComparer * @returns {Enumerable} * @memberof Enumerable */ intersect(iterable: IterableType, equalityComparer: IEqualityComparer): Enumerable; /** * Same as count * * @returns {number} * @memberof Enumerable */ longCount(): number; /** * Filters the elements of a sequence based on their type * If type is a string, it will filter based on typeof, else it will use instanceof * * @param {(string | Function)} type * @returns {Enumerable} * @memberof Enumerable */ ofType(type: string | Function): Enumerable; /** * Adds a value to the beginning of the sequence. * * @param {*} item * @returns {Enumerable} * @memberof Enumerable */ prepend(item: any): Enumerable; /** * Inverts the order of the elements in a sequence. * * @returns {Enumerable} * @memberof Enumerable */ reverse(): Enumerable; /** * Projects each element of a sequence to an iterable and flattens the resulting sequences into one sequence. * * @param {ISelector<IterableType>} selector * @returns {Enumerable} * @memberof Enumerable */ selectMany(selector: ISelector<IterableType>): Enumerable; /** * Determines whether two sequences are equal and in the same order according to an optional equality comparer. * * @param {IterableType} iterable * @param {IEqualityComparer} equalityComparer * @returns {boolean} * @memberof Enumerable */ sequenceEqual(iterable: IterableType, equalityComparer: IEqualityComparer): boolean; /** * Returns the single element of a sequence and throws if it doesn't have exactly one * * @returns {*} * @memberof Enumerable */ single(): any; /** * Returns the single element of a sequence or undefined if none found. It throws if the sequence contains multiple items. * * @returns {(any | undefined)} * @memberof Enumerable */ singleOrDefault(): any | undefined; /** * Returns a new enumerable collection that contains the elements from source with the last nr elements of the source collection omitted. * * @param {number} nr * @returns {Enumerable} * @memberof Enumerable */ skipLast(nr: number): Enumerable; /** * Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. * * @param {IFilter} condition * @returns {Enumerable} * @memberof Enumerable */ skipWhile(condition: IFilter): Enumerable; /** * Selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. * @param start * @param end * @returns slice */ slice(start: number | undefined, end: number | undefined) : Enumerable; /** * Returns a new enumerable collection that contains the last nr elements from source. * * @param {number} nr * @returns {Enumerable} * @memberof Enumerable */ takeLast(nr: number): Enumerable; /** * Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements. * * @param {IFilter} condition * @returns {Enumerable} * @memberof Enumerable */ takeWhile(condition: IFilter): Enumerable; toDictionary(): never; /** * creates a Map from an Enumerable * * @param {ISelector} keySelector * @param {ISelector} valueSelector * @returns {Map<any, any>} * @memberof Enumerable */ toMap(keySelector: ISelector, valueSelector: ISelector): Map<any, any>; /** * creates an object from an Enumerable * * @param {ISelector} keySelector * @param {ISelector} valueSelector * @returns {{ [key: string]: any }} * @memberof Enumerable */ toObject(keySelector: ISelector, valueSelector: ISelector): { [key: string]: any }; toHashSet(): never; /** * creates a Set from an enumerable * * @returns {Set<any>} * @memberof Enumerable */ toSet(): Set<any>; /** * Produces the set union of two sequences. * * @param {IterableType} iterable * @param {IEqualityComparer} equalityComparer * @returns {Enumerable} * @memberof Enumerable */ union(iterable: IterableType, equalityComparer: IEqualityComparer): Enumerable; /** * Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results. * * @param {IterableType} iterable * @param {(item1: any, item2: any, index: number) => any} zipper * @returns {*} * @memberof Enumerable */ zip(iterable: IterableType, zipper: (item1: any, item2: any, index: number) => any): any; } /// Applies an accumulator function over a sequence. /// The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value. Enumerable.prototype.aggregate = function (accumulator: any, aggregator: (acc: any, item: any) => any): any { _ensureFunction(aggregator); for (const item of this) { accumulator = aggregator(accumulator, item); } return accumulator; } /// Determines whether all elements of a sequence satisfy a condition. Enumerable.prototype.all = function (condition: IFilter): boolean { _ensureFunction(condition); return !this.any(x => !condition(x)); } /// Determines whether any element of a sequence exists or satisfies a condition. Enumerable.prototype.any = function (condition: IFilter): boolean { _ensureFunction(condition); let index = 0; for (const item of this) { if (condition(item, index)) return true; index++; } return false; } /// Appends a value to the end of the sequence. Enumerable.prototype.append = function (item: any): Enumerable { return this.concat([item]); } /// Computes the average of a sequence of numeric values. Enumerable.prototype.average = function (): number | undefined { const stats = this.sumAndCount(); return stats.count === 0 ? undefined : stats.sum / stats.count; } /// Returns the same enumerable Enumerable.prototype.asEnumerable = function (): Enumerable { return this; } /// Checks the elements of a sequence based on their type /// If type is a string, it will check based on typeof, else it will use instanceof. /// Throws if types are different. Enumerable.prototype.cast = function (type: string | Function): Enumerable { const f: ((x: any) => boolean) = typeof type === 'string' ? x => typeof x === type : x => x instanceof type; return this.select(item => { if (!f(item)) throw new Error(item + ' not of type ' + type); return item; }); } /// Determines whether a sequence contains a specified element. /// A custom function can be used to determine equality between elements. Enumerable.prototype.contains = function (item: any, equalityComparer: IEqualityComparer = EqualityComparer.default): boolean { _ensureFunction(equalityComparer); return this.any(x => equalityComparer(x, item)); } Enumerable.prototype.defaultIfEmpty = function (): never { throw new Error('defaultIfEmpty not implemented for Javascript'); } /// Produces the set difference of two sequences WARNING: using the comparer is slower Enumerable.prototype.except = function (iterable: IterableType, equalityComparer: IEqualityComparer = EqualityComparer.default): Enumerable { _ensureIterable(iterable); const self: Enumerable = this; // use a Set for performance if the comparer is not set const gen = equalityComparer === EqualityComparer.default ? function* () { const distinctValues = Enumerable.from(iterable).toSet(); for (const item of self) { if (!distinctValues.has(item)) yield item; } } // use exceptByHash from Linqer.extra for better performance : function* () { const values = _toArray(iterable); for (const item of self) { let unique = true; for (let i=0; i<values.length; i++) { if (equalityComparer(item, values[i])) { unique = false; break; } } if (unique) yield item; } }; return new Enumerable(gen); } /// Produces the set intersection of two sequences. WARNING: using a comparer is slower Enumerable.prototype.intersect = function (iterable: IterableType, equalityComparer: IEqualityComparer = EqualityComparer.default): Enumerable { _ensureIterable(iterable); const self: Enumerable = this; // use a Set for performance if the comparer is not set const gen = equalityComparer === EqualityComparer.default ? function* () { const distinctValues = new Set(Enumerable.from(iterable)); for (const item of self) { if (distinctValues.has(item)) yield item; } } // use intersectByHash from Linqer.extra for better performance : function* () { const values = _toArray(iterable); for (const item of self) { let unique = true; for (let i=0; i<values.length; i++) { if (equalityComparer(item, values[i])) { unique = false; break; } } if (!unique) yield item; } }; return new Enumerable(gen); } /// same as count Enumerable.prototype.longCount = function (): number { return this.count(); } /// Filters the elements of a sequence based on their type /// If type is a string, it will filter based on typeof, else it will use instanceof Enumerable.prototype.ofType = function (type: string | Function): Enumerable { const condition: IFilter = typeof type === 'string' ? x => typeof x === type : x => x instanceof type; return this.where(condition); } /// Adds a value to the beginning of the sequence. Enumerable.prototype.prepend = function (item: any): Enumerable { return new Enumerable([item]).concat(this); } /// Inverts the order of the elements in a sequence. Enumerable.prototype.reverse = function (): Enumerable { _ensureInternalTryGetAt(this); const self: Enumerable = this; // if it can seek, just read the enumerable backwards const gen = this._canSeek ? function* () { const length = self.count(); for (let index = length - 1; index >= 0; index--) { yield self.elementAt(index); } } // else enumerate it all into an array, then read it backwards : function* () { const arr = self.toArray(); for (let index = arr.length - 1; index >= 0; index--) { yield arr[index]; } }; // the count is the same when reversed const result = new Enumerable(gen); _ensureInternalCount(this); result._count = this._count; _ensureInternalTryGetAt(this); // have a custom indexer only if the original enumerable could seek if (this._canSeek) { const self = this; result._canSeek = true; result._tryGetAt = index => self._tryGetAt!(self.count() - index - 1); } return result; } /// Projects each element of a sequence to an iterable and flattens the resulting sequences into one sequence. Enumerable.prototype.selectMany = function (selector: ISelector<IterableType>): Enumerable { if (typeof selector !== 'undefined') { _ensureFunction(selector); } else { selector = x => x; } const self: Enumerable = this; const gen = function* () { let index = 0; for (const item of self) { const iter = selector(item, index); _ensureIterable(iter); for (const child of iter) { yield child; } index++; } }; return new Enumerable(gen); } /// Determines whether two sequences are equal and in the same order according to an equality comparer. Enumerable.prototype.sequenceEqual = function (iterable: IterableType, equalityComparer: IEqualityComparer = EqualityComparer.default): boolean { _ensureIterable(iterable); _ensureFunction(equalityComparer); const iterator1 = this[Symbol.iterator](); const iterator2 = Enumerable.from(iterable)[Symbol.iterator](); let done = false; do { const val1 = iterator1.next(); const val2 = iterator2.next(); const equal = (val1.done && val2.done) || (!val1.done && !val2.done && equalityComparer(val1.value, val2.value)); if (!equal) return false; done = !!val1.done; } while (!done); return true; } /// Returns the single element of a sequence and throws if it doesn't have exactly one Enumerable.prototype.single = function (): any { const iterator = this[Symbol.iterator](); let val = iterator.next(); if (val.done) throw new Error('Sequence contains no elements'); const result = val.value; val = iterator.next(); if (!val.done) throw new Error('Sequence contains more than one element'); return result; } /// Returns the single element of a sequence or undefined if none found. It throws if the sequence contains multiple items. Enumerable.prototype.singleOrDefault = function (): any | undefined { const iterator = this[Symbol.iterator](); let val = iterator.next(); if (val.done) return undefined; const result = val.value; val = iterator.next(); if (!val.done) throw new Error('Sequence contains more than one element'); return result; } /// Selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. Enumerable.prototype.slice = function (start: number = 0, end: number | undefined): Enumerable { let enumerable: Enumerable = this; // when the end is defined and positive and start is negative, // the only way to compute the last index is to know the count if (end !== undefined && end >= 0 && (start || 0) < 0) { enumerable = enumerable.toList(); start = enumerable.count() + start; } if (start !== 0) { if (start > 0) { enumerable = enumerable.skip(start); } else { enumerable = enumerable.takeLast(-start); } } if (end !== undefined) { if (end >= 0) { enumerable = enumerable.take(end - start); } else { enumerable = enumerable.skipLast(-end); } } return enumerable; } /// Returns a new enumerable collection that contains the elements from source with the last nr elements of the source collection omitted. Enumerable.prototype.skipLast = function (nr: number): Enumerable { const self: Enumerable = this; // the generator is using a buffer to cache nr values // and only yields the values that overflow from it const gen = function* () { let nrLeft = nr; const buffer = Array(nrLeft); let index = 0; let offset = 0; for (const item of self) { const value = buffer[index - offset]; buffer[index - offset] = item; index++; if (index - offset >= nrLeft) { offset += nrLeft; } if (index > nrLeft) { yield value; } } buffer.length = 0; }; const result = new Enumerable(gen); // the count is the original count minus the skipped items and at least 0 result._count = () => Math.max(0, self.count() - nr); _ensureInternalTryGetAt(this); result._canSeek = this._canSeek; // it has an indexer only if the original enumerable can seek if (this._canSeek) { result._tryGetAt = index => { if (index >= result.count()) return null; return self._tryGetAt!(index); } } return result; } /// Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. Enumerable.prototype.skipWhile = function (condition: IFilter): Enumerable { _ensureFunction(condition); const self: Enumerable = this; let skip = true; const gen = function* () { let index = 0; for (const item of self) { if (skip && !condition(item, index)) { skip = false; } if (!skip) { yield item; } index++; } }; return new Enumerable(gen); } /// Returns a new enumerable collection that contains the last nr elements from source. Enumerable.prototype.takeLast = function (nr: number): Enumerable { _ensureInternalTryGetAt(this); const self: Enumerable = this; const gen = this._canSeek // taking the last items is easy if the enumerable can seek ? function* () { let nrLeft = nr; const length = self.count(); for (let index = length - nrLeft; index < length; index++) { yield self.elementAt(index); } } // else the generator uses a buffer to fill with values // and yields them after the entire thing has been iterated : function* () { let nrLeft = nr; let index = 0; const buffer = Array(nrLeft); for (const item of self) { buffer[index % nrLeft] = item; index++; } for (let i = 0; i < nrLeft && i < index; i++) { yield buffer[(index + i) % nrLeft]; } }; const result = new Enumerable(gen); // the count is the minimum between nr and the enumerable count result._count = () => Math.min(nr, self.count()); result._canSeek = self._canSeek; // this can seek only if the original enumerable could seek if (self._canSeek) { result._tryGetAt = index => { if (index < 0 || index >= result.count()) return null; return self._tryGetAt!(self.count() - nr + index); }; } return result; } /// Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements. Enumerable.prototype.takeWhile = function (condition: IFilter): Enumerable { _ensureFunction(condition); const self: Enumerable = this; const gen = function* () { let index = 0; for (const item of self) { if (condition(item, index)) { yield item; } else { break; } index++; } }; return new Enumerable(gen); } Enumerable.prototype.toDictionary = function (): never { throw new Error('use toMap or toObject instead of toDictionary'); } /// creates a map from an Enumerable Enumerable.prototype.toMap = function (keySelector: ISelector, valueSelector: ISelector = x => x): Map<any, any> { _ensureFunction(keySelector); _ensureFunction(valueSelector); const result = new Map<any, any>(); let index = 0; for (const item of this) { result.set(keySelector(item, index), valueSelector(item, index)); index++; } return result; } /// creates an object from an enumerable Enumerable.prototype.toObject = function (keySelector: ISelector, valueSelector: ISelector = x => x): { [key: string]: any } { _ensureFunction(keySelector); _ensureFunction(valueSelector); const result: { [key: string]: any } = {}; let index = 0; for (const item of this) { result[keySelector(item, index)] = valueSelector(item); index++; } return result; } Enumerable.prototype.toHashSet = function (): never { throw new Error('use toSet instead of toHashSet'); } /// creates a set from an enumerable Enumerable.prototype.toSet = function (): Set<any> { const result = new Set<any>(); for (const item of this) { result.add(item); } return result; } /// Produces the set union of two sequences. Enumerable.prototype.union = function (iterable: IterableType, equalityComparer: IEqualityComparer = EqualityComparer.default): Enumerable { _ensureIterable(iterable); return this.concat(iterable).distinct(equalityComparer); } /// Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results. Enumerable.prototype.zip = function (iterable: IterableType, zipper: (item1: any, item2: any, index: number) => any): any { _ensureIterable(iterable); if (!zipper) { zipper = (i1,i2)=>[i1,i2]; } else { _ensureFunction(zipper); } const self: Enumerable = this; const gen = function* () { let index = 0; const iterator1 = self[Symbol.iterator](); const iterator2 = Enumerable.from(iterable)[Symbol.iterator](); let done = false; do { const val1 = iterator1.next(); const val2 = iterator2.next(); done = !!(val1.done || val2.done); if (!done) { yield zipper(val1.value, val2.value, index); } index++; } while (!done); }; return new Enumerable(gen); } }
the_stack
import { ident } from "../../Data/Function" import { fmapF } from "../../Data/Functor" import { any, elem, insertAt, List, snocF } from "../../Data/List" import { Just, Maybe, maybe, Nothing } from "../../Data/Maybe" import { Record } from "../../Data/Record" import { uncurry3 } from "../../Data/Tuple/Curry" import { SubTab } from "../Models/Hero/heroTypeHelpers" import { NavigationBarTabOptions } from "../Models/View/NavigationBarTabOptions" import { createMaybeSelector } from "../Utilities/createMaybeSelector" import { translate } from "../Utilities/I18n" import { isHeroSectionTab, isMainSectionTab, TabId } from "../Utilities/LocationUtils" import { pipe, pipe_ } from "../Utilities/pipe" import { isBookEnabled, sourceBooksPairToTuple } from "../Utilities/RulesUtils" import { getIsLiturgicalChantsTabAvailable } from "./liturgicalChantsSelectors" import { getIsRemovingEnabled } from "./phaseSelectors" import { getRuleBooksEnabledM } from "./rulesSelectors" import { getIsSpellsTabAvailable } from "./spellsSelectors" import { getCurrentCultureId, getCurrentPhase, getCurrentTab, getRaceIdM, getWiki } from "./stateSelectors" export const getIsMainSection = createMaybeSelector ( getCurrentTab, isMainSectionTab ) export const getIsHeroSection = createMaybeSelector ( getCurrentTab, isHeroSectionTab ) export const PHASE_1_PROFILE_TABS = List (TabId.Profile, TabId.PersonalData, TabId.Pact, TabId.Rules) export const PHASE_1_RCP_TABS = List (TabId.Races, TabId.Cultures, TabId.Professions) export const getTabs = createMaybeSelector ( getWiki, getIsMainSection, getIsHeroSection, getCurrentPhase, getIsRemovingEnabled, ( staticData, isMainSection, isHeroSection, phase, isRemovingEnabled ): List<Record<NavigationBarTabOptions>> => { if (isMainSection) { return List<Record<NavigationBarTabOptions>> ( NavigationBarTabOptions ({ id: TabId.Herolist, label: translate (staticData) ("header.tabs.heroes"), subTabs: List (), }), // NavigationBarTabOptions ({ // id: TabId.Grouplist, // label: translate (staticData) ("header.tabs.groups"), // subTabs: List (), // }), NavigationBarTabOptions ({ id: TabId.Wiki, label: translate (staticData) ("header.tabs.wiki"), subTabs: List (), }), NavigationBarTabOptions ({ id: TabId.Faq, label: translate (staticData) ("header.tabs.faq"), subTabs: List (), }), NavigationBarTabOptions ({ id: TabId.Imprint, label: translate (staticData) ("header.tabs.about"), subTabs: List (TabId.Imprint, TabId.ThirdPartyLicenses, TabId.LastChanges), }) ) } if (isHeroSection) { if (Maybe.elem (1) (phase)) { return List<Record<NavigationBarTabOptions>> ( NavigationBarTabOptions ({ id: TabId.Profile, label: translate (staticData) ("header.tabs.profile"), subTabs: PHASE_1_PROFILE_TABS, }), NavigationBarTabOptions ({ id: TabId.Races, label: translate (staticData) ("header.tabs.racecultureandprofession"), subTabs: PHASE_1_RCP_TABS, }) ) } if (isRemovingEnabled) { return List<Record<NavigationBarTabOptions>> ( NavigationBarTabOptions ({ id: TabId.Profile, label: translate (staticData) ("header.tabs.profile"), subTabs: List ( TabId.Profile, TabId.PersonalData, TabId.CharacterSheet, TabId.Pact, TabId.Rules ), }), NavigationBarTabOptions ({ id: TabId.Attributes, label: translate (staticData) ("header.tabs.attributes"), subTabs: List (), }), NavigationBarTabOptions ({ id: TabId.Advantages, label: translate (staticData) ("header.tabs.advantagesanddisadvantages"), subTabs: List (TabId.Advantages, TabId.Disadvantages), }), NavigationBarTabOptions ({ id: TabId.Skills, label: translate (staticData) ("header.tabs.abilities"), subTabs: List ( TabId.Skills, TabId.CombatTechniques, TabId.SpecialAbilities, TabId.Spells, TabId.LiturgicalChants ), }), NavigationBarTabOptions ({ id: TabId.Equipment, label: translate (staticData) ("header.tabs.belongings"), subTabs: List (TabId.Equipment, TabId.ZoneArmor, TabId.Pets), }) ) } return List<Record<NavigationBarTabOptions>> ( NavigationBarTabOptions ({ id: TabId.Profile, label: translate (staticData) ("header.tabs.profile"), subTabs: List ( TabId.Profile, TabId.PersonalData, TabId.CharacterSheet, TabId.Pact, TabId.Rules ), }), NavigationBarTabOptions ({ id: TabId.Attributes, label: translate (staticData) ("header.tabs.attributes"), subTabs: List (), }), NavigationBarTabOptions ({ id: TabId.Skills, label: translate (staticData) ("header.tabs.abilities"), subTabs: List ( TabId.Skills, TabId.CombatTechniques, TabId.SpecialAbilities, TabId.Spells, TabId.LiturgicalChants ), }), NavigationBarTabOptions ({ id: TabId.Equipment, label: translate (staticData) ("header.tabs.belongings"), subTabs: List (TabId.Equipment, TabId.ZoneArmor, TabId.Pets), }) ) } return List<Record<NavigationBarTabOptions>> () } ) export const getSubtabs = createMaybeSelector ( getWiki, getCurrentTab, getIsMainSection, getIsHeroSection, getCurrentPhase, getRaceIdM, getCurrentCultureId, getIsSpellsTabAvailable, getIsLiturgicalChantsTabAvailable, getRuleBooksEnabledM, ( staticData, tab, isMainSection, isHeroSection, phase, raceId, cultureId, isSpellsTabAvailable, isLiturgicalChantsTabAvailable, mruleBooksEnabled ): Maybe<List<SubTab>> => { if (isMainSection) { const aboutSubTabs = List (TabId.Imprint, TabId.ThirdPartyLicenses, TabId.LastChanges) if (elem (tab) (aboutSubTabs)) { return Just (List<SubTab> ( { id: TabId.Imprint, label: translate (staticData) ("header.tabs.imprint"), disabled: false, }, { id: TabId.ThirdPartyLicenses, label: translate (staticData) ("header.tabs.thirdpartylicenses"), disabled: false, }, { id: TabId.LastChanges, label: translate (staticData) ("header.tabs.lastchanges"), disabled: false, } )) } } else if (isHeroSection) { if (Maybe.elem (1) (phase)) { const profileSubTabs = List (TabId.Profile, TabId.PersonalData, TabId.Pact, TabId.Rules) const rcpSubTabs = List (TabId.Races, TabId.Cultures, TabId.Professions) if (elem (tab) (profileSubTabs)) { const tabs = List<SubTab> ( { id: TabId.Profile, label: translate (staticData) ("header.tabs.overview"), disabled: false, }, // { // id: TabId.PersonalData, // label: translate (staticData) ("header.tabs.personaldata"), // disabled: true, // }, { id: TabId.Rules, label: translate (staticData) ("header.tabs.rules"), disabled: false, } ) if (maybe (false) (pipe ( sourceBooksPairToTuple, ruleBooksEnabled => any (uncurry3 (isBookEnabled) (ruleBooksEnabled)) (List ("US25102", "US25008")) )) (mruleBooksEnabled)) { return Just (insertAt (2) <SubTab> ({ id: TabId.Pact, label: translate (staticData) ("header.tabs.pact"), disabled: false, }) (tabs)) } else { return Just (tabs) } } if (elem (tab) (rcpSubTabs)) { const racesTab: SubTab = { id: TabId.Races, label: translate (staticData) ("header.tabs.race"), disabled: false, } const culturesTab: SubTab = { id: TabId.Cultures, label: translate (staticData) ("header.tabs.culture"), disabled: false, } const professionsTab: SubTab = { id: TabId.Professions, label: translate (staticData) ("header.tabs.profession"), disabled: false, } if (Maybe.isJust (cultureId)) { return Just (List<SubTab> ( racesTab, culturesTab, professionsTab )) } if (Maybe.isJust (raceId)) { return Just (List<SubTab> ( racesTab, culturesTab )) } return Just (List<SubTab> ( racesTab )) } } else { const profileSubTabs = List ( TabId.Profile, TabId.PersonalData, TabId.CharacterSheet, TabId.Pact, TabId.Rules ) const abilitiesSubTabs = List ( TabId.Skills, TabId.CombatTechniques, TabId.SpecialAbilities, TabId.Spells, TabId.LiturgicalChants ) const disadvSubTabs = List (TabId.Advantages, TabId.Disadvantages) const belongingsSubTabs = List (TabId.Equipment, TabId.ZoneArmor, TabId.Pets) if (elem (tab) (profileSubTabs)) { return pipe_ ( List<SubTab> ( { id: TabId.Profile, label: translate (staticData) ("header.tabs.overview"), disabled: false, }, // { // id: TabId.PersonalData, // label: translate (staticData) ("header.tabs.personaldata"), // disabled: true, // }, { id: TabId.Rules, label: translate (staticData) ("header.tabs.rules"), disabled: false, } ), Maybe.elem (3) (phase) ? insertAt (1) <SubTab> ({ id: TabId.CharacterSheet, label: translate (staticData) ("header.tabs.charactersheet"), disabled: false, }) : ident, maybe (false) (pipe ( sourceBooksPairToTuple, ruleBooksEnabled => any (uncurry3 (isBookEnabled) (ruleBooksEnabled)) (List ("US25102", "US25008")) )) (mruleBooksEnabled) ? insertAt (Maybe.elem (3) (phase) ? 2 : 1) <SubTab> ({ id: TabId.Pact, label: translate (staticData) ("header.tabs.pact"), disabled: false, }) : ident, Just ) } if (elem (tab) (disadvSubTabs)) { return Just (List<SubTab> ( { id: TabId.Advantages, label: translate (staticData) ("header.tabs.advantages"), disabled: false, }, { id: TabId.Disadvantages, label: translate (staticData) ("header.tabs.disadvantages"), disabled: false, } )) } if (elem (tab) (abilitiesSubTabs)) { return Just ( pipe_ ( List<SubTab> ( { id: TabId.Skills, label: translate (staticData) ("header.tabs.skills"), disabled: false, }, { id: TabId.CombatTechniques, label: translate (staticData) ("header.tabs.combattechniques"), disabled: false, }, { id: TabId.SpecialAbilities, label: translate (staticData) ("header.tabs.specialabilities"), disabled: false, } ), isSpellsTabAvailable ? snocF<SubTab> ({ id: TabId.Spells, label: translate (staticData) ("header.tabs.spells"), disabled: false, }) : ident, isLiturgicalChantsTabAvailable ? snocF<SubTab> ({ id: TabId.LiturgicalChants, label: translate (staticData) ("header.tabs.liturgicalchants"), disabled: false, }) : ident ) ) } if (elem (tab) (belongingsSubTabs)) { const baseTabs = List<SubTab> ( { id: TabId.Equipment, label: translate (staticData) ("header.tabs.equipment"), disabled: false, }, { id: TabId.Pets, label: translate (staticData) ("header.tabs.pets"), disabled: false, } ) if (Maybe.elem (true) (fmapF (mruleBooksEnabled) (pipe ( sourceBooksPairToTuple, ruleBooksEnabled => uncurry3 (isBookEnabled) (ruleBooksEnabled) ("US25208") )))) { return Just (insertAt (1) <SubTab> ({ id: TabId.ZoneArmor, label: translate (staticData) ("header.tabs.hitzonearmor"), disabled: false, }) (baseTabs)) } return Just (baseTabs) } } } return Nothing } )
the_stack
import { BottomSheetBackdrop, BottomSheetModal, BottomSheetModalProvider, BottomSheetScrollView, } from '@gorhom/bottom-sheet'; import { useTheme } from '@react-navigation/native'; import LottieView from 'lottie-react-native'; import React, { useCallback, useContext, useEffect, useRef } from 'react'; import { Image, ImageStyle, ScrollView, StatusBar, StyleProp, StyleSheet, TouchableHighlight, TouchableOpacity, TouchableWithoutFeedback, View, ViewStyle, } from 'react-native'; import { clamp } from 'react-native-awesome-slider/src/utils'; import { Gesture, GestureDetector } from 'react-native-gesture-handler'; import InkWell from 'react-native-inkwell'; import Animated, { interpolate, runOnJS, useAnimatedProps, useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, withTiming, } from 'react-native-reanimated'; import VideoPlayer, { VideoPlayerRef } from 'react-native-reanimated-player'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import { Text, ThemeView } from '../components'; import { Icon } from '../components/icon'; import type { IconNames } from '../components/iconfont'; import { springConfig, videoInfo, VIDEO_MIN_HEIGHT } from '../constants'; import { PlayerContext } from '../state/context'; import { setPlayerPaused, setPlayerPoint } from '../state/reducer'; import { palette } from '../theme/palette'; import { height, isIos, width } from '../utils'; import { mb, mr, mt, px2dp } from '../utils/ui-tools'; const AnimatedLottieView = Animated.createAnimatedComponent(LottieView); const sliderTranslateY = 6; const VIDEO_DEFAULT_HEIGHT = width * (9 / 16); const flexRow: ViewStyle = { flexDirection: 'row', alignItems: 'center', }; const StatusBarHeight = isIos ? 0 : StatusBar?.currentHeight ?? 0 + 5; const Avatar = ({ size, style, }: { size: number; style?: StyleProp<ImageStyle>; }) => ( <Image source={videoInfo.avatar} style={[{ width: size, height: size, borderRadius: size }, style]} /> ); const options: { icon: IconNames; title: string }[] = [ { icon: 'feedback', title: 'Help & feedback', }, { icon: 'flagoutline', title: 'Report', }, { icon: 'setting', title: 'Setting', }, ]; export const VideoScreen = ({ videoTranslateY, }: { videoTranslateY: Animated.SharedValue<number>; }) => { const insets = useSafeAreaInsets(); const insetsRefs = useRef(insets); const { store, dispatch } = useContext(PlayerContext); const DISMISS_POINT = height - 45 - insets.bottom; const SNAP_POINT = [ 0, height + StatusBarHeight - 40 - VIDEO_MIN_HEIGHT - insets.bottom, ]; const diasbled = Boolean(store.snapPoint > SNAP_POINT[0]); const paused = Boolean(store.paused || store.snapPoint === -1); const { colors, dark } = useTheme(); const descModalRef = useRef<BottomSheetModal>(null); const optionsModalRef = useRef<BottomSheetModal>(null); const fullViewHeight = height - VIDEO_DEFAULT_HEIGHT - insets.top; const indexDesc = useRef(0); const indexOptions = useRef(0); const isOpened = useRef(false); const isTapPaused = useRef(paused); const sheetPrevIndex = useRef(-1); const indexValue = useSharedValue(0); const sheetTranslationY = useSharedValue(0); const panTranslationY = useSharedValue(0); const videoScale = useSharedValue(1); const videoTransY = useSharedValue(0); const videoPlayerRef = useRef<VideoPlayerRef>(null); const videoHeight = useSharedValue(VIDEO_DEFAULT_HEIGHT); const videoWidth = useSharedValue(width); const isFullScreen = useSharedValue(false); const panIsVertical = useSharedValue(false); const snapPointIndex = useSharedValue(store.snapPoint); const pageStyle = useAnimatedStyle(() => { const y = panTranslationY.value + sheetTranslationY.value; return { transform: [ { translateY: clamp(y, 0, height - insets.bottom - 48), }, ], backgroundColor: isFullScreen.value ? '#000' : 'transparent', }; }, [panTranslationY, sheetTranslationY]); const getVideoContainerStyle = useAnimatedStyle(() => { const y = panTranslationY.value + sheetTranslationY.value; return { backgroundColor: isFullScreen.value ? '#000' : colors.background, opacity: interpolate(y, [SNAP_POINT[1], DISMISS_POINT], [1, 0]), }; }, [panTranslationY, sheetTranslationY]); const customAnimationStyle = useAnimatedStyle(() => { const y = panTranslationY.value + sheetTranslationY.value; const targetHeight = videoHeight.value * ((height - y) / height); let targetWidth = videoWidth.value; if (targetHeight < VIDEO_MIN_HEIGHT) { const widthScale = clamp((height - y) / y, 0, 1); targetWidth = videoWidth.value * widthScale; } return { transform: [ { scale: videoScale.value, }, { translateY: videoTransY.value, }, ], height: isFullScreen.value ? width : clamp(targetHeight, 67.5, VIDEO_DEFAULT_HEIGHT), width: isFullScreen.value ? height - insetsRefs.current?.top - insetsRefs.current?.bottom : clamp(targetWidth, 120, width), }; }, [panTranslationY, sheetTranslationY]); const getHeaderBackdropStyle = useAnimatedStyle(() => { return { opacity: indexValue.value, }; }); const getBodyBackdropStyle = useAnimatedStyle(() => { return { opacity: 1 + indexValue.value, }; }); const getBackdropStyle = useAnimatedStyle(() => { const y = panTranslationY.value + sheetTranslationY.value; return { opacity: interpolate( y, [VIDEO_MIN_HEIGHT, height - VIDEO_DEFAULT_HEIGHT], [0, 1], ), }; }, [panTranslationY, sheetTranslationY]); const getViewBackdropStyle = useAnimatedStyle(() => { const y = panTranslationY.value + sheetTranslationY.value; return { opacity: interpolate(y, [-100, height - VIDEO_DEFAULT_HEIGHT], [1, 0]), }; }, [panTranslationY, sheetTranslationY]); const videoThumbInfo = useAnimatedStyle(() => { const y = panTranslationY.value + sheetTranslationY.value; const opacity = interpolate( y, [VIDEO_DEFAULT_HEIGHT + VIDEO_MIN_HEIGHT, height - VIDEO_MIN_HEIGHT], [0, 1], ); return { opacity: isFullScreen.value ? 0 : opacity, }; }); const playAnimated = useDerivedValue(() => { return paused ? 0.5 : 0; }, [paused]); const playAnimatedProps = useAnimatedProps(() => { return { progress: withTiming(playAnimated.value), }; }); const translationBySnapPointIndex = useCallback( (snapIndex: number) => { 'worklet'; snapPointIndex.value = snapIndex; switch (snapIndex) { case -1: sheetTranslationY.value = videoTranslateY.value = withSpring( DISMISS_POINT, springConfig, ); break; default: sheetTranslationY.value = videoTranslateY.value = withSpring( SNAP_POINT[snapIndex], springConfig, ); break; } }, // eslint-disable-next-line react-hooks/exhaustive-deps [DISMISS_POINT, SNAP_POINT], ); useEffect(() => { translationBySnapPointIndex(store.snapPoint); }, [store.snapPoint, translationBySnapPointIndex]); const openModal = () => { descModalRef.current?.present(); }; const closeDescModal = () => { descModalRef.current?.dismiss(); }; const renderBackdrop = useCallback(props => { return ( <Animated.View style={[ { height, width, }, props.style, ]} pointerEvents="none"> <Animated.View style={[ // eslint-disable-next-line react-native/no-inline-styles { height: VIDEO_DEFAULT_HEIGHT + insets.top, width, backgroundColor: palette.B(1), top: 0, position: 'absolute', }, getHeaderBackdropStyle, ]} pointerEvents="none" /> <Animated.View style={[ // eslint-disable-next-line react-native/no-inline-styles { height: fullViewHeight, width, backgroundColor: palette.B(1), bottom: 0, position: 'absolute', }, getBodyBackdropStyle, ]} pointerEvents="none" /> </Animated.View> ); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const renderOptionsBackdrop = useCallback(props => { return ( <BottomSheetBackdrop disappearsOnIndex={-1} appearsOnIndex={0} {...props} /> ); }, []); const getDividerStyle = (): ViewStyle => { return { borderBottomWidth: px2dp(0.5), borderColor: colors.border, }; }; const onSheetChange = (index: number) => { if (isOpened.current && !isTapPaused.current) { videoPlayerRef.current?.setPlay(); } switch (index) { case 1: videoPlayerRef.current?.setPause(); break; case 0: isOpened.current = true; break; default: isOpened.current = false; break; } sheetPrevIndex.current = index; }; const handleComponent = () => ( <ThemeView style={styles.modalHeader}> <View style={styles.header}> <View style={[ styles.block, { backgroundColor: dark ? palette.G5(1) : palette.G2(1) }, ]} /> </View> <View style={[styles.handleTitle, getDividerStyle()]}> <Text tx="Description" h3 color={dark ? palette.W(1) : palette.G9(1)} /> <Text tx={videoInfo.createTime} t3 color={colors.text} /> </View> </ThemeView> ); const renderBubble = useCallback(() => { return ( <Image source={require('../assets/snapshot.png')} style={styles.snapshot} /> ); }, []); /** * on pan event */ const onHandlerEndOnJS = (point: number) => { dispatch(setPlayerPoint(point)); }; const onStartOnJS = () => { videoPlayerRef.current?.toggleControlViewOpacity(false); closeDescModal(); }; /** * Toggle player full screen state on <Video> component */ const enterFullScreen = () => { videoPlayerRef.current?.toggleFullSreen(true); }; const exitFullScreen = () => { videoPlayerRef.current?.toggleFullSreen(false); }; const panGesture = Gesture.Pan() .onStart(({ velocityY, velocityX }) => { panIsVertical.value = Math.abs(velocityY) > Math.abs(velocityX); runOnJS(onStartOnJS)(); }) .onUpdate(({ translationY }) => { if (!panIsVertical.value) { return; } 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 && snapPointIndex.value === 0 ) { videoScale.value = Math.abs(translationY) * 0.012 + 1; } panTranslationY.value = translationY; videoTranslateY.value = sheetTranslationY.value + translationY; } }) .onEnd(({ velocityY, translationY }, success) => { if (!panIsVertical.value) { return; } videoPlayerRef.current?.toggleControlViewOpacity(false); if (isFullScreen.value) { if (translationY >= 100) { runOnJS(exitFullScreen)(); } } else { if (-translationY >= 40 && snapPointIndex.value === 0) { runOnJS(enterFullScreen)(); } const dragToss = 0.2; const endOffsetY = sheetTranslationY.value + panTranslationY.value + velocityY * dragToss; if ( !success && endOffsetY < SNAP_POINT[SNAP_POINT.length - 1] && store.snapPoint < endOffsetY ) { return; } let destSnapPoint = SNAP_POINT[0]; let pointIndex = 0; if (snapPointIndex.value === 1 && translationY > 0) { const y = sheetTranslationY.value + panTranslationY.value + velocityY * 0.05; if (y > DISMISS_POINT - VIDEO_MIN_HEIGHT / 2) { destSnapPoint = DISMISS_POINT; pointIndex = -1; } else { destSnapPoint = SNAP_POINT[1]; pointIndex = 1; } } else { pointIndex = SNAP_POINT.findIndex(point => { const distFromSnap = Math.abs(point - endOffsetY); return distFromSnap < Math.abs(destSnapPoint - endOffsetY); }); if (pointIndex > -1) { destSnapPoint = SNAP_POINT[pointIndex]; } else { pointIndex = 0; } } snapPointIndex.value = pointIndex; const finalSheetValue = sheetTranslationY.value + panTranslationY.value; panTranslationY.value = 0; sheetTranslationY.value = videoTranslateY.value = finalSheetValue; sheetTranslationY.value = videoTranslateY.value = withSpring( destSnapPoint, springConfig, ); runOnJS(onHandlerEndOnJS)(pointIndex); } videoTransY.value = 0; videoScale.value = withTiming(1); }); const foldVideo = () => { videoPlayerRef.current?.toggleControlViewOpacity(false); translationBySnapPointIndex(1); dispatch(setPlayerPoint(1)); }; return ( <BottomSheetModalProvider> <Animated.View pointerEvents={'none'} style={[ styles.backdrop, { backgroundColor: palette.B(1) }, getViewBackdropStyle, ]} /> <Animated.View style={[ styles.pageView, { paddingLeft: insets.left, paddingRight: insets.right, paddingTop: insets.top, }, pageStyle, ]}> <GestureDetector gesture={panGesture}> <Animated.View style={getVideoContainerStyle}> <Animated.View style={[styles.videoThumbInfo, videoThumbInfo]}> <View> <Text tx={`${videoInfo.author} - ${videoInfo.title}`} numberOfLines={1} color={colors.text} /> <Text tx={videoInfo.author} style={mt(0.5)} numberOfLines={1} t3 color={palette.G4(1)} /> </View> <TouchableWithoutFeedback onPress={() => { dispatch(setPlayerPaused(!paused)); }}> <AnimatedLottieView animatedProps={playAnimatedProps} source={require('../assets/lottie-play.json')} style={styles.playIcon} /> </TouchableWithoutFeedback> <TouchableOpacity activeOpacity={0.8} onPress={() => { dispatch(setPlayerPoint(-1)); }}> <Icon name="close-bold" size={30} color={colors.text} /> </TouchableOpacity> </Animated.View> <VideoPlayer source={videoInfo.source} playWhenInactive posterResizeMode="cover" ignoreSilentSwitch="ignore" headerBarTitle={`${videoInfo.author} - ${videoInfo.title}`} onTapBack={foldVideo} paused={paused} onPausedChange={state => { dispatch(setPlayerPaused(state)); }} onTapPause={state => { isTapPaused.current = state; }} onTapMore={() => { optionsModalRef.current?.present(); }} onToggleAutoPlay={(state: boolean) => { console.log(`onToggleAutoPlay state: ${state}`); }} videoDefaultHeight={VIDEO_DEFAULT_HEIGHT} ref={videoPlayerRef} sliderProps={{ renderBubble: renderBubble, bubbleTranslateY: -60, bubbleWidth: 120, bubbleMaxWidth: 120, disable: diasbled, }} videoHeight={videoHeight} customAnimationStyle={customAnimationStyle} onCustomPanGesture={panGesture} style={{ marginBottom: sliderTranslateY }} resizeMode="cover" isFullScreen={isFullScreen} disableControl={diasbled} renderBackIcon={() => ( <Icon name="a-ic_chevrondown_16" size={24} color={palette.W(1)} /> )} /> </Animated.View> </GestureDetector> <Animated.View style={[ { backgroundColor: colors.background, }, styles.sliderTranslate, ]} /> <View style={[ styles.flex1, { backgroundColor: colors.background, width, }, ]}> <ScrollView contentContainerStyle={styles.flex1}> <TouchableHighlight underlayColor={dark ? palette.G5(0.6) : palette.G2(0.6)} onPress={openModal}> <View style={[styles.titleContainer, getDividerStyle()]}> <Text h4 tx={`${videoInfo.author} - ${videoInfo.title}`} style={styles.title} /> <Icon name="a-ic_chevrondown_16" size={16} color={colors.text} /> </View> </TouchableHighlight> <View style={[flexRow, styles.authors, getDividerStyle()]}> <View style={flexRow}> <Avatar size={40} style={mr(3)} /> <View> <Text tx={videoInfo.author} t1 /> <Text> <Text tx={'44.7M '} t4 color={dark ? palette.G3(1) : palette.G5(1)} /> <Text tx={'subscribers'} t5 color={dark ? palette.G3(1) : palette.G5(1)} /> </Text> </View> </View> <Text tx={'SUBSCRIBED'} h5 color={dark ? palette.G3(1) : palette.G5(1)} /> </View> </ScrollView> <BottomSheetModal ref={descModalRef} index={indexDesc.current} snapPoints={[fullViewHeight, height - insets.top]} backdropComponent={renderBackdrop} animatedIndex={indexValue} backgroundStyle={{ backgroundColor: colors.background }} onChange={onSheetChange} onDismiss={() => { isOpened.current = false; }} handleComponent={handleComponent}> <BottomSheetScrollView contentContainerStyle={[ styles.desc, { paddingBottom: insets.bottom + 44, backgroundColor: colors.background, }, ]}> <Text tx={videoInfo.title} t3 tBold style={mt(3)} /> <View style={[styles.descInfo, getDividerStyle()]}> <Avatar size={20} style={styles.avatar} /> <Text tx={videoInfo.author} t3 tBold /> </View> <Text tx={videoInfo.desc} h4 style={[mt(3), mb(3)]} /> </BottomSheetScrollView> </BottomSheetModal> <BottomSheetModal ref={optionsModalRef} index={indexOptions.current} snapPoints={[210 - StatusBarHeight]} backdropComponent={renderOptionsBackdrop} backgroundStyle={[ styles.backgroundStyle, { backgroundColor: colors.background }, ]} footerComponent={() => ( <InkWell onTap={() => { optionsModalRef.current?.close(); }} contentContainerStyle={[styles.inkWell, mt(1)]} style={[ styles.inkWellView, { marginBottom: insets.bottom + 10, borderTopColor: colors.border, borderTopWidth: px2dp(0.5), }, ]}> <View style={[styles.item]}> <Icon name="close" size={24} color={colors.text} /> <Text tx={'Cancel'} style={styles.text} t2 /> </View> </InkWell> )} handleComponent={() => null}> <BottomSheetScrollView> {options.map(item => ( <InkWell onTap={() => { optionsModalRef.current?.close(); }} contentContainerStyle={styles.inkWell} style={styles.inkWellView} key={item.title}> <View style={styles.item}> <Icon name={item.icon} size={24} color={colors.text} /> <Text tx={item.title} t2 style={styles.text} color={colors.text} /> </View> </InkWell> ))} </BottomSheetScrollView> </BottomSheetModal> <Animated.View pointerEvents={store.snapPoint === SNAP_POINT[0] ? 'none' : 'auto'} style={[ styles.backdrop, { backgroundColor: colors.background }, getBackdropStyle, ]} /> </View> </Animated.View> </BottomSheetModalProvider> ); }; const styles = StyleSheet.create({ flex1: { flex: 1, minHeight: height, }, backgroundStyle: { borderTopLeftRadius: 0, borderTopRightRadius: 0, }, authors: { justifyContent: 'space-between', marginTop: 12, flexDirection: 'row', paddingHorizontal: 20, paddingBottom: 12, }, avatar: { marginRight: 6, }, boards: { flexDirection: 'row', flexWrap: 'wrap', }, container: { backgroundColor: palette.transparent, flex: 1, paddingBottom: 20, paddingTop: 20, }, desc: { paddingHorizontal: 20, }, descInfo: { flexDirection: 'row', marginTop: 12, alignItems: 'center', paddingBottom: 12, }, full: { backgroundColor: palette.B(1), flex: 1, }, handleTitle: { justifyContent: 'space-between', paddingBottom: 8, paddingHorizontal: 20, flexDirection: 'row', alignItems: 'center', }, modalHeader: { borderTopLeftRadius: 20, borderTopRightRadius: 20, }, options: { justifyContent: 'space-between', marginTop: 32, }, title: { flex: 1, }, titleContainer: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 20, paddingTop: 10, paddingBottom: 8, justifyContent: 'center', minHeight: 60, }, view: { backgroundColor: palette.B(1), flex: 1, }, pageView: { flex: 1, width: '100%', position: 'absolute', }, backdrop: { ...StyleSheet.absoluteFillObject, marginTop: -sliderTranslateY, }, header: { alignItems: 'center', height: 20, justifyContent: 'center', width, }, block: { borderRadius: 2, height: 3, width: 40, }, item: { paddingHorizontal: 20, flexDirection: 'row', alignItems: 'center', }, text: { marginLeft: 20, }, inkWell: { justifyContent: 'center', }, inkWellFooter: { width: '100%', }, inkWellView: { width: '100%', height: 40, }, snapshot: { width: 120, height: 67, }, sliderTranslate: { height: sliderTranslateY, marginTop: -sliderTranslateY, zIndex: -1, elevation: -1, }, videoThumbInfo: { marginBottom: 14, flex: 1, flexDirection: 'row', justifyContent: 'space-between', position: 'absolute', right: 20, width: width - 160, bottom: 4, }, playIcon: { height: 30, width: 30, }, });
the_stack
import Dockerode from 'dockerode'; import { SettingsStore } from '../stores/SettingsStore'; import { readFileSync } from 'fs'; import { autorun } from 'mobx/lib/mobx'; import { inject, provideSingleton, kernel } from './IOC'; import { NOTIFICATION_TYPE, NotificationStore } from '../stores/NotificationStore'; import { CONFIG_TYPE, PROTOCOL } from '../models/ConnectionParametersModel'; export interface DockerConfig { protocol?: string; host?: string; port?: number; socketPath?: string; ca?: Buffer; cert?: Buffer; key?: Buffer; } export interface Version { Version: string; Os: string; KernelVersion: string; GoVersion: string; GitCommit: string; Arch: string; ApiVersion: string; BuildTime: Date; } export interface SummarizedImage { RepoTags: Array<string>; Id: string; Created: Date; Size: number; VirtualSize: number; Labels: { [key: string]: string; }; } export interface SummarizedContainer { Command: string; Created: number; HostConfig: Object; Id: string; Image: string; ImageID: string; Labels: Object; Names: Array<string>; NetworkSettings: Object; Ports: Array<any>; Status: string; } export interface TopModel { Processes: Array<Array<string>>; Titles: Array<string>; } export interface DockerEvent { Action: 'create' | 'attach' | 'connect' | 'start' | 'resize' | 'kill' | 'die' | 'disconnect' | 'destroy' | 'top' | 'pause' | 'unpause' | 'pull' | 'untag' | 'tag' | 'delete'; Type: 'container' | 'network' | 'image'; from: string id: string; status: string; time: number; } export interface DockerSwarmEvent { status: 'create' | 'attach' | 'connect' | 'start' | 'resize' | 'kill' | 'die' | 'disconnect' | 'destroy' | 'top' | 'pause' | 'unpause' | 'pull' | 'untag' | 'tag' | 'delete'; id: string; from: string; time: number; node: { Addr: string; Id: string; Ip: string; Name: string; }; } export class Container { Id: string; Name: string; Created: string; State: { Error: string, ExitCode: number, FinishedAt: string, OOMKilled: boolean, Dead: boolean, Paused: boolean, Pid: number, Restarting: boolean, Running: boolean, StartedAt: string, Status: string }; Config: { AttachStderr: boolean; AttachStdin: boolean; AttachStdout: boolean; Cmd: Array<string>; Domainname: string; Entrypoint: string, Env: Array<string>; ExposedPorts: Object; Hostname: string; Image: string; Labels: Object; MacAddress: string; NetworkDisabled: boolean; OnBuild: string; OpenStdin: boolean; StdinOnce: boolean; Tty: boolean; User: string; Volumes: Object; WorkingDir: string; StopSignal: string; }; NetworkSettings: { Bridge: string; SandboxID: string; HairpinMode: boolean; LinkLocalIPv6Address: string; LinkLocalIPv6PrefixLen: number; Ports: any; SandboxKey: string; SecondaryIPAddresses: string; SecondaryIPv6Addresses: string; EndpointID: string; Gateway: string; GlobalIPv6Address: string; GlobalIPv6PrefixLen: number; IPAddress: string; IPPrefixLen: number; IPv6Gateway: string; MacAddress: string; Networks: any; }; Node: { Addr: string; Cpus: number; ID: string; IP: string; Memory: number; Name: string; }; constructor (data: any, private container: any) { Object.assign(this, data); } top (): Promise<TopModel> { return new Promise<TopModel>((resolve, reject) => { this.container.top((err: any, data: TopModel) => { if (err) { return reject(err); } resolve(data); }); }); } stats (): Promise<any> { return new Promise<any>((resolve, reject) => { this.container.stats((err: any, stream: any) => { if (err) { return reject(err); } resolve(stream); }); }); } unpause (): Promise<void> { return new Promise<void>((resolve, reject) => { this.container.unpause((err: any) => { if (err) { return reject(err); } resolve(); }); }); } pause (): Promise<void> { return new Promise<void>((resolve, reject) => { this.container.pause((err: any) => { if (err) { return reject(err); } resolve(); }); }); } start (): Promise<void> { return new Promise<void>((resolve, reject) => { this.container.start((err: any) => { if (err) { return reject(err); } resolve(); }); }); } stop (): Promise<void> { return new Promise<void>((resolve, reject) => { this.container.stop((err: any) => { if (err) { return reject(err); } resolve(); }); }); } } export class Image { Id: string; Container: string; Comment: string; Os: string; Architecture: string; Parent: string; ContainerConfig: { Tty: boolean; Hostname: string; Volumes: { [key: string]: { [key: string]: string; }; }; Domainname: string; AttachStdout: boolean; PublishService: string; AttachStdin: boolean; OpenStdin: boolean; StdinOnce: boolean; NetworkDisabled: boolean; OnBuild: Array<string>; Image: string; User: string; WorkingDir: string; Entrypoint: Array<string>; MacAddress: string; AttachStderr: boolean; Labels: { [key: string]: string }, Env: Array<string>; ExposedPorts: Object; Cmd: Array<string>; }; DockerVersion: string; VirtualSize: number; Size: number; Author: string; Created: string; // "GraphDriver" : { // "Name" : "aufs", // "Data" : null // }, // "RepoDigests" : [ // "localhost:5000/test/busybox/example@sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf" // ], RepoTags: Array<string>; Config: { Image: string; NetworkDisabled: boolean; OnBuild: Array<string>; StdinOnce: boolean; PublishService: string; AttachStdin: boolean; OpenStdin: boolean; Domainname: string; AttachStdout: boolean; Tty: boolean; Hostname: string; Volumes: { [key: string]: { [key: string]: string; }; }; Cmd: Array<string>; ExposedPorts: Object; Env: Array<string>; Labels: { [key: string]: string; }; Entrypoint: Array<string>; MacAddress: string; AttachStderr: boolean; WorkingDir: string; User: string; }; // "RootFS": { // "Type": "layers", // "Layers": [ // "sha256:1834950e52ce4d5a88a1bbd131c537f4d0e56d10ff0dd69e66be3b7dfa9df7e6", // "sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef" // ] // } constructor (data: any, private image: any) { Object.assign(this, data); } history (): Promise<any> { return new Promise<any>((resolve, reject) => { this.image.history((err: any, stream: any) => { if (err) { return reject(err); } resolve(stream); }); }); } } @provideSingleton(DockerFacade) export class DockerFacade { private dockerode: Dockerode; private eventListeners: Array<(event: DockerEvent | DockerSwarmEvent) => void> = []; private eventStream: any; @inject(SettingsStore) private settingsStore: SettingsStore; @inject(NotificationStore) private notificationStore: NotificationStore; constructor () { let dockerConfig: DockerConfig = null; autorun(() => { switch (this.settingsStore.connectionSettings.configType) { case CONFIG_TYPE.SOCKET: dockerConfig = { socketPath: this.settingsStore.connectionSettings.socketPath }; break; case CONFIG_TYPE.HOST: try { dockerConfig = { host: this.settingsStore.connectionSettings.host, port: this.settingsStore.connectionSettings.port, protocol: this.settingsStore.connectionSettings.protocol === PROTOCOL.HTTP ? 'http' : 'https', ca: this.settingsStore.connectionSettings.caFile ? readFileSync(this.settingsStore.connectionSettings.caFile) : null, cert: this.settingsStore.connectionSettings.certFile ? readFileSync(this.settingsStore.connectionSettings.certFile) : null, key: this.settingsStore.connectionSettings.keyFile ? readFileSync(this.settingsStore.connectionSettings.keyFile) : null }; } catch (e) { } break; default: throw new Error('no suitable config type'); } this.dockerode = new (kernel.get(Dockerode))(dockerConfig); if(this.eventStream != null) { this.eventStream.destroy(); } this.listenForEvents((error, event) => { if (error != null) { this.notificationStore.notifications.push({ type: NOTIFICATION_TYPE.ERROR, message: error.message || 'Error while processing docker events', }); return; } this.eventListeners.forEach(cb => cb(event)); }); }); } onEvent(cb: (event: DockerEvent | DockerSwarmEvent) => void): void { this.eventListeners.push(cb); } listAllContainers (): Promise<Array<Container>> { return this.fetchContainers({ all: true }); } getContainer (containerId: string): Promise<Container> { return new Promise<Container>((resolve, reject) => { const container = this.dockerode.getContainer(containerId); container.inspect({}, (err: Error, data: any) => { if (err) { return reject(err); } resolve(new Container(data, container)); }); }); } removeContainer (containerId: string): Promise<void> { return new Promise<void>((resolve, reject) => { this.dockerode.getContainer(containerId).remove({}, (err: any) => { if (err) { return reject(err); } resolve(); }); }); } listImages(): Promise<Array<Image>> { return this.fetchImages(); } listDanglingImages(): Promise<Array<Image>> { return this.fetchImages({ filters: { dangling: [ 'true' ] } }); } getImage(imageId: string): Promise<Image> { return new Promise<Image>((resolve, reject) => { const image = this.dockerode.getImage(imageId); image.inspect((err: Error, data: any) => { if (err) { return reject(err); } resolve(new Image(data, image)); }); }); } removeImage (imageId: string): Promise<void> { return new Promise<void>((resolve, reject) => { this.dockerode.getImage(imageId).remove({}, (err: any) => { if (err) { return reject(err); } resolve(); }); }); } version(): Promise<Version> { return new Promise<Version>((resolve, reject) => { this.dockerode.version((err, data) => { if(err) { return reject(err); } resolve(data); }) }); } // info(): Promise<any> { // return new Promise<any>((resolve, reject) => { // this.dockerode.info((err, data) => { // if(err) { // return reject(err); // } // // resolve(data); // }) // }); // }x // getNetworks(query: Object = {} = {}): Promise<Array<Object>> { // return new Promise((resolve, reject) => { // this.dockerode.listNetworks(query, (err, networks) => { // if (err) { // return reject(); // } // // resolve(networks); // }); // }); // } private async fetchImages(options: Object = {}): Promise<Array<Image>> { return Promise.all( (await new Promise<Array<SummarizedImage>>((resolve, reject) => { this.dockerode.listImages(options, (err: any, images: Array<SummarizedImage>) => { if (err) { return reject(err); } resolve(images); }); })) .map((image: SummarizedImage) => this.getImage(image.Id))); } private async fetchContainers (options: Object = {}): Promise<Array<Container>> { return Promise.all( (await new Promise<Array<SummarizedContainer>>((resolve, reject) => { this.dockerode.listContainers(options, (err: any, containers: Array<SummarizedContainer>) => { if (err) { return reject(err); } resolve(containers); }) })) .map((container: SummarizedContainer) => this.getContainer(container.Id))); } private listenForEvents (cb: (err: any, event?: DockerEvent | DockerSwarmEvent) => void): void { const options = { path: '/events', method: 'GET', isStream: true, statusCodes: { 200: true, 500: 'server error' } }; this.dockerode.modem.dial(options, (err, stream) => { if (err) { return cb(err); } this.eventStream = stream; this.dockerode.modem.followProgress(stream, cb, event => cb(null, event)); }); } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { IntegrationAccountMaps } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { LogicManagementClient } from "../logicManagementClient"; import { IntegrationAccountMap, IntegrationAccountMapsListNextOptionalParams, IntegrationAccountMapsListOptionalParams, IntegrationAccountMapsListResponse, IntegrationAccountMapsGetOptionalParams, IntegrationAccountMapsGetResponse, IntegrationAccountMapsCreateOrUpdateOptionalParams, IntegrationAccountMapsCreateOrUpdateResponse, IntegrationAccountMapsDeleteOptionalParams, GetCallbackUrlParameters, IntegrationAccountMapsListContentCallbackUrlOptionalParams, IntegrationAccountMapsListContentCallbackUrlResponse, IntegrationAccountMapsListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing IntegrationAccountMaps operations. */ export class IntegrationAccountMapsImpl implements IntegrationAccountMaps { private readonly client: LogicManagementClient; /** * Initialize a new instance of the class IntegrationAccountMaps class. * @param client Reference to the service client */ constructor(client: LogicManagementClient) { this.client = client; } /** * Gets a list of integration account maps. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param options The options parameters. */ public list( resourceGroupName: string, integrationAccountName: string, options?: IntegrationAccountMapsListOptionalParams ): PagedAsyncIterableIterator<IntegrationAccountMap> { const iter = this.listPagingAll( resourceGroupName, integrationAccountName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage( resourceGroupName, integrationAccountName, options ); } }; } private async *listPagingPage( resourceGroupName: string, integrationAccountName: string, options?: IntegrationAccountMapsListOptionalParams ): AsyncIterableIterator<IntegrationAccountMap[]> { let result = await this._list( resourceGroupName, integrationAccountName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, integrationAccountName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, integrationAccountName: string, options?: IntegrationAccountMapsListOptionalParams ): AsyncIterableIterator<IntegrationAccountMap> { for await (const page of this.listPagingPage( resourceGroupName, integrationAccountName, options )) { yield* page; } } /** * Gets a list of integration account maps. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param options The options parameters. */ private _list( resourceGroupName: string, integrationAccountName: string, options?: IntegrationAccountMapsListOptionalParams ): Promise<IntegrationAccountMapsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, options }, listOperationSpec ); } /** * Gets an integration account map. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param mapName The integration account map name. * @param options The options parameters. */ get( resourceGroupName: string, integrationAccountName: string, mapName: string, options?: IntegrationAccountMapsGetOptionalParams ): Promise<IntegrationAccountMapsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, mapName, options }, getOperationSpec ); } /** * Creates or updates an integration account map. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param mapName The integration account map name. * @param map The integration account map. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, integrationAccountName: string, mapName: string, map: IntegrationAccountMap, options?: IntegrationAccountMapsCreateOrUpdateOptionalParams ): Promise<IntegrationAccountMapsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, mapName, map, options }, createOrUpdateOperationSpec ); } /** * Deletes an integration account map. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param mapName The integration account map name. * @param options The options parameters. */ delete( resourceGroupName: string, integrationAccountName: string, mapName: string, options?: IntegrationAccountMapsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, mapName, options }, deleteOperationSpec ); } /** * Get the content callback url. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param mapName The integration account map name. * @param listContentCallbackUrl The callback url parameters. * @param options The options parameters. */ listContentCallbackUrl( resourceGroupName: string, integrationAccountName: string, mapName: string, listContentCallbackUrl: GetCallbackUrlParameters, options?: IntegrationAccountMapsListContentCallbackUrlOptionalParams ): Promise<IntegrationAccountMapsListContentCallbackUrlResponse> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, mapName, listContentCallbackUrl, options }, listContentCallbackUrlOperationSpec ); } /** * ListNext * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, integrationAccountName: string, nextLink: string, options?: IntegrationAccountMapsListNextOptionalParams ): Promise<IntegrationAccountMapsListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/maps", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IntegrationAccountMapListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.top, Parameters.filter], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.integrationAccountName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/maps/{mapName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IntegrationAccountMap }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.integrationAccountName, Parameters.mapName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/maps/{mapName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.IntegrationAccountMap }, 201: { bodyMapper: Mappers.IntegrationAccountMap }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.map, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.integrationAccountName, Parameters.mapName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/maps/{mapName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.integrationAccountName, Parameters.mapName ], headerParameters: [Parameters.accept], serializer }; const listContentCallbackUrlOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/maps/{mapName}/listContentCallbackUrl", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.WorkflowTriggerCallbackUrl }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.listContentCallbackUrl, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.integrationAccountName, Parameters.mapName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IntegrationAccountMapListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.top, Parameters.filter], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.nextLink, Parameters.integrationAccountName ], headerParameters: [Parameters.accept], serializer };
the_stack
import pako from "pako"; import JSZip from "jszip"; import * as deckgl from "./Deckgl"; const FILENAME_MASK1 = "olhwjsktri"; // const FILENAME_MASK2 = "eizxdwknmo"; const FILENAME_ENCODING: { [key: string]: number } = {}; for (let i = 0; i < FILENAME_MASK1.length; i++) { FILENAME_ENCODING[FILENAME_MASK1.charAt(i)] = i; } const MAP_WIDTH = 512; export const TILE_WIDTH_OFFSET = 7; export const TILE_WIDTH = 1 << TILE_WIDTH_OFFSET; const TILE_HEADER_LEN = TILE_WIDTH ** 2; const TILE_HEADER_SIZE = TILE_HEADER_LEN * 2; const BLOCK_BITMAP_SIZE = 512; const BLOCK_EXTRA_DATA = 3; const BLOCK_SIZE = BLOCK_BITMAP_SIZE + BLOCK_EXTRA_DATA; export const BITMAP_WIDTH_OFFSET = 6; export const BITMAP_WIDTH = 1 << BITMAP_WIDTH_OFFSET; // TODO: figure out a better way to imeplement immutable data structure // we encountered performance issue when using `immutable.js` // SAD: Type Aliases do not seem to give us type safety export type TileID = number; export type XYKey = string; export class FogMap { readonly tiles: { [key: XYKey]: Tile }; static empty = new FogMap({}); private constructor(tiles: { [key: XYKey]: Tile }) { Object.freeze(tiles); this.tiles = tiles; } // It is so silly that tuple cannot be used as key static makeKeyXY(x: number, y: number): XYKey { return `${x}-${y}`; } // TODO: merge instead of override addFiles(files: [string, ArrayBuffer][]): FogMap { if (files.length === 0) { return this; } const mutableTiles = { ...this.tiles }; files.forEach(([filename, data]) => { try { const tile = Tile.create(filename, data); // just in case the imported data doesn't hold this invariant if (Object.entries(tile.blocks).length !== 0) { mutableTiles[FogMap.makeKeyXY(tile.x, tile.y)] = tile; } } catch (e) { // TODO: handle error properly console.log(`${filename} is not a valid tile file.`); console.log(e); } }); return new FogMap(mutableTiles); } async exportArchive(): Promise<Blob | null> { const zip = new JSZip(); const syncZip = zip.folder("Sync"); if (!syncZip) { // TODO: handle error console.log("unable to create archive"); return null; } Object.values(this.tiles).forEach((tile) => { // just in case if (Object.entries(tile.blocks).length !== 0) { syncZip.file("Sync/" + tile.filename, tile.dump()); } }); return syncZip.generateAsync({ type: "blob" }); } // we only provide interface for clearing a bbox, because we think it make no sense to add paths for whole bbox clearBbox(bbox: deckgl.Bbox): FogMap { const nw = Tile.LngLatToXY(bbox.west, bbox.north); const se = Tile.LngLatToXY(bbox.east, bbox.south); const xMin = nw[0]; const xMax = se[0]; const yMin = nw[1]; const yMax = se[1]; // TODO: what if lng=0 const xMinInt = Math.floor(xMin); const xMaxInt = Math.floor(xMax); const yMinInt = Math.floor(yMin); const yMaxInt = Math.floor(yMax); let mutableTiles: { [key: XYKey]: Tile } | null = null; for (let x = xMinInt; x <= xMaxInt; x++) { for (let y = yMinInt; y <= yMaxInt; y++) { const key = FogMap.makeKeyXY(x, y); const tile = this.tiles[key]; if (tile) { const xp0 = Math.max(xMin - tile.x, 0) * TILE_WIDTH; const yp0 = Math.max(yMin - tile.y, 0) * TILE_WIDTH; const xp1 = Math.min(xMax - tile.x, 1) * TILE_WIDTH; const yp1 = Math.min(yMax - tile.y, 1) * TILE_WIDTH; const newTile = tile.clearRect(xp0, yp0, xp1 - xp0, yp1 - yp0); if (tile !== newTile) { if (!mutableTiles) { mutableTiles = { ...this.tiles }; } if (newTile) { mutableTiles[key] = newTile; } else { delete mutableTiles[key]; } } } } } if (mutableTiles) { return new FogMap(mutableTiles); } else { return this; } } } export class Tile { readonly filename: string; readonly id: TileID; readonly x: number; readonly y: number; readonly blocks: { [key: XYKey]: Block }; private constructor( filename: string, id: TileID, x: number, y: number, blocks: { [key: XYKey]: Block } ) { Object.freeze(blocks); this.filename = filename; this.id = id; this.x = x; this.y = y; this.blocks = blocks; } static create(filename: string, data: ArrayBuffer): Tile { // TODO: try catch const id = Number.parseInt( filename .slice(4, -2) .split("") .map((idMasked) => FILENAME_ENCODING[idMasked]) .join("") ); const x = id % MAP_WIDTH; const y = Math.floor(id / MAP_WIDTH); console.log(`Loading tile. id: ${id}, x: ${x}, y: ${y}`); // TODO: try catch const actualData = pako.inflate(new Uint8Array(data)); const header = new Uint16Array( actualData.slice(0, TILE_HEADER_SIZE).buffer ); const blocks = {} as { [key: XYKey]: Block }; for (let i = 0; i < header.length; i++) { const blockIdx = header[i]; if (blockIdx > 0) { const blockX = i % TILE_WIDTH; const blockY = Math.floor(i / TILE_WIDTH); const startOffset = TILE_HEADER_SIZE + (blockIdx - 1) * BLOCK_SIZE; const endOffset = startOffset + BLOCK_SIZE; const blockData = actualData.slice(startOffset, endOffset); const block = Block.create(blockX, blockY, blockData); block.check(); blocks[FogMap.makeKeyXY(blockX, blockY)] = block; } } return new Tile(filename, id, x, y, blocks); } dump(): Uint8Array { const header = new Uint8Array(TILE_HEADER_SIZE); const headerView = new DataView(header.buffer, 0, TILE_HEADER_SIZE); const blockDataSize = BLOCK_SIZE * Object.entries(this.blocks).length; const blockData = new Uint8Array(blockDataSize); let activeBlockIdx = 1; Object.values(this.blocks) .map((block) => { const i = block.x + block.y * TILE_WIDTH; return [i, block] as [number, Block]; }) .sort((a, b) => { return a[0] - b[0]; }) .forEach(([i, block]) => { headerView.setUint16(i * 2, activeBlockIdx, true); blockData.set(block.dump(), (activeBlockIdx - 1) * BLOCK_SIZE); activeBlockIdx++; }); const data = new Uint8Array(TILE_HEADER_SIZE + blockDataSize); data.set(header); data.set(blockData, TILE_HEADER_SIZE); return pako.deflate(data); } static XYToLngLat(x: number, y: number): number[] { const lng = (x / 512) * 360 - 180; const lat = (Math.atan(Math.sinh(Math.PI - (2 * Math.PI * y) / 512)) * 180) / Math.PI; return [lng, lat]; } static LngLatToXY(lng: number, lat: number): number[] { const x = ((lng + 180) / 360) * 512; const y = ((Math.PI - Math.asinh(Math.tan((lat / 180) * Math.PI))) * 512) / (2 * Math.PI); return [x, y]; } bounds(): number[][] { const sw = Tile.XYToLngLat(this.x, this.y + 1); const se = Tile.XYToLngLat(this.x + 1, this.y + 1); const ne = Tile.XYToLngLat(this.x + 1, this.y); const nw = Tile.XYToLngLat(this.x, this.y); return [nw, ne, se, sw]; } bbox(): deckgl.Bbox { const [west, south] = Tile.XYToLngLat(this.x, this.y + 1); const [east, north] = Tile.XYToLngLat(this.x + 1, this.y); const bbox = new deckgl.Bbox(west, south, east, north); return bbox; } clearRect(x: number, y: number, width: number, height: number): Tile | null { const xMin = x; const yMin = y; const xMax = x + width; const yMax = y + height; const xMinInt = Math.floor(xMin); const xMaxInt = Math.floor(xMax); const yMinInt = Math.floor(yMin); const yMaxInt = Math.floor(yMax); let mutableBlocks: { [key: XYKey]: Block } | null = null; for (let x = xMinInt; x <= xMaxInt; x++) { for (let y = yMinInt; y <= yMaxInt; y++) { const key = FogMap.makeKeyXY(x, y); const block = this.blocks[key]; if (block) { const xp0 = Math.round(Math.max(xMin - block.x, 0) * BITMAP_WIDTH); const yp0 = Math.round(Math.max(yMin - block.y, 0) * BITMAP_WIDTH); const xp1 = Math.round(Math.min(xMax - block.x, 1) * BITMAP_WIDTH); const yp1 = Math.round(Math.min(yMax - block.y, 1) * BITMAP_WIDTH); const newBlock = block.clearRect(xp0, yp0, xp1 - xp0, yp1 - yp0); if (newBlock !== block) { if (!mutableBlocks) { mutableBlocks = { ...this.blocks }; } if (newBlock) { mutableBlocks[key] = newBlock; } else { delete mutableBlocks[key]; } } } } } // Immutable.js avoids creating new objects for updates where no change in value occurred if (mutableBlocks) { if (Object.entries(mutableBlocks).length === 0) { return null; } else { Object.freeze(mutableBlocks); return new Tile(this.filename, this.id, this.x, this.y, mutableBlocks); } } else { return this; } } } export class Block { readonly x: number; readonly y: number; readonly bitmap: Uint8Array; readonly extraData: Uint8Array; private constructor( x: number, y: number, bitmap: Uint8Array, extraData: Uint8Array ) { this.x = x; this.y = y; this.bitmap = bitmap; this.extraData = extraData; } static create(x: number, y: number, data: Uint8Array): Block { const bitmap = data.slice(0, BLOCK_BITMAP_SIZE); const extraData = data.slice(BLOCK_BITMAP_SIZE, BLOCK_SIZE); return new Block(x, y, bitmap, extraData); } check(): boolean { let count = 0; for (let i = 0; i < BITMAP_WIDTH; i++) { for (let j = 0; j < BITMAP_WIDTH; j++) { if (this.isVisited(i, j)) { count++; } } } const isCorrect = count === this.count(); if (!isCorrect) { console.warn(`block check sum error!`); } return isCorrect; } dump(): Uint8Array { const data = new Uint8Array(BLOCK_SIZE); let count = 0; for (let i = 0; i < BITMAP_WIDTH; i++) { for (let j = 0; j < BITMAP_WIDTH; j++) { if (this.isVisited(i, j)) { count++; } } } const checksumDataview = new DataView(this.extraData.buffer, 1, 2); checksumDataview.setUint16( 0, (checksumDataview.getUint16(0, false) & 0xc000) | ((count << 1) + 1), false ); data.set(this.bitmap); data.set(this.extraData, BLOCK_BITMAP_SIZE); return data; } region(): string { const regionChar0 = String.fromCharCode( (this.extraData[0] >> 3) + "?".charCodeAt(0) ); const regionChar1 = String.fromCharCode( (((this.extraData[0] & 0x7) << 2) | ((this.extraData[1] & 0xc0) >> 6)) + "?".charCodeAt(0) ); return regionChar0 + regionChar1; } count(): number { return ( (new DataView(this.extraData.buffer, 1, 2).getUint16(0, false) & 0x3fff) >> 1 ); } isVisited(x: number, y: number): boolean { const bitOffset = 7 - (x % 8); const i = Math.floor(x / 8); const j = y; return (this.bitmap[i + j * 8] & (1 << bitOffset)) !== 0; } private static setPoint( mutableBitmap: Uint8Array, x: number, y: number, val: boolean ): void { const bitOffset = 7 - (x % 8); const i = Math.floor(x / 8); const j = y; const valNumber = val ? 1 : 0; mutableBitmap[i + j * 8] = (mutableBitmap[i + j * 8] & ~(1 << bitOffset)) | (valNumber << bitOffset); } private static bitmapEqual(a: Uint8Array, b: Uint8Array): boolean { if (a.byteLength !== b.byteLength) { return false; } for (let i = 0; i != a.byteLength; i++) { if (a[i] !== b[i]) { return false; } } return true; } clearRect(x: number, y: number, width: number, height: number): Block | null { const mutableBitmap = new Uint8Array(this.bitmap); for (let i = 0; i < width; i++) { for (let j = 0; j < height; j++) { Block.setPoint(mutableBitmap, x + i, y + j, false); } } if (mutableBitmap.every((v) => v === 0)) { return null; } if (Block.bitmapEqual(mutableBitmap, this.bitmap)) { return this; } else { return new Block(this.x, this.y, mutableBitmap, this.extraData); } } }
the_stack
import {moveCursorToOffset} from '@deckdeckgo/utils'; import containerStore from '../stores/container.store'; import undoRedoStore from '../stores/undo-redo.store'; import { UndoRedoAddRemoveParagraph, UndoRedoChange, UndoRedoChanges, UndoRedoInput, UndoRedoSelection, UndoRedoUpdateParagraph } from '../types/undo-redo'; import {findNodeAtDepths, isTextNode, toHTMLElement} from './node.utils'; import {redoSelection, toUndoRedoSelection} from './undo-redo-selection.utils'; export const stackUndoInput = ({ container, data }: { container: HTMLElement; data: UndoRedoInput[]; }) => { if (!undoRedoStore.state.undo) { undoRedoStore.state.undo = []; } undoRedoStore.state.undo.push({ changes: data.map((undoRedoInput: UndoRedoInput) => ({ type: 'input', target: container, data: undoRedoInput })) }); undoRedoStore.state.redo = []; }; export const stackUndoParagraphs = ({ container, addRemoveParagraphs, updateParagraphs, selection }: { container: HTMLElement; addRemoveParagraphs: UndoRedoAddRemoveParagraph[]; updateParagraphs: UndoRedoUpdateParagraph[]; selection?: UndoRedoSelection; }) => { if (addRemoveParagraphs.length <= 0 && updateParagraphs.length <= 0) { return; } if (!undoRedoStore.state.undo) { undoRedoStore.state.undo = []; } const changes: UndoRedoChanges = { changes: [ { type: 'paragraph', target: container, data: addRemoveParagraphs.map( ({outerHTML, index, mutation}: UndoRedoAddRemoveParagraph) => ({ outerHTML, mutation, index }) ) }, { type: 'update', target: container, data: updateParagraphs } ], selection }; undoRedoStore.state.undo.push(changes); undoRedoStore.state.redo = []; }; export const nextUndoChanges = (): UndoRedoChanges | undefined => nextChange(undoRedoStore.state.undo); export const nextRedoChanges = (): UndoRedoChanges | undefined => nextChange(undoRedoStore.state.redo); const nextChange = (changes: UndoRedoChanges[] | undefined): UndoRedoChanges | undefined => { if (!changes) { return undefined; } return changes[changes.length - 1]; }; export const undo = async () => undoRedo({ popFrom: () => (undoRedoStore.state.undo = [ ...undoRedoStore.state.undo.slice(0, undoRedoStore.state.undo.length - 1) ]), pushTo: (value: UndoRedoChanges) => undoRedoStore.state.redo.push(value), undoChanges: nextUndoChanges() }); export const redo = async () => undoRedo({ popFrom: () => (undoRedoStore.state.redo = [ ...undoRedoStore.state.redo.slice(0, undoRedoStore.state.redo.length - 1) ]), pushTo: (value: UndoRedoChanges) => undoRedoStore.state.undo.push(value), undoChanges: nextRedoChanges() }); const undoRedo = async ({ popFrom, pushTo, undoChanges }: { popFrom: () => void; pushTo: (value: UndoRedoChanges) => void; undoChanges: UndoRedoChanges | undefined; }) => { if (!undoChanges) { return; } const currentSelection: UndoRedoSelection = toUndoRedoSelection(containerStore.state.ref); const {changes, selection}: UndoRedoChanges = undoChanges; let redoChanges: UndoRedoChange[] = []; for (const undoChange of changes) { redoChanges = [await undoRedoChange({undoChange}), ...redoChanges]; } redoSelection({container: containerStore.state.ref, selection}); pushTo({changes: redoChanges, selection: currentSelection}); popFrom(); }; const undoRedoChange = async ({ undoChange }: { undoChange: UndoRedoChange; }): Promise<UndoRedoChange> => { const {type} = undoChange; if (type === 'input') { return undoRedoInput({undoChange}); } if (type === 'paragraph') { return undoRedoParagraph({undoChange}); } return undoRedoUpdate({undoChange}); }; const undoRedoInput = async ({ undoChange }: { undoChange: UndoRedoChange; }): Promise<UndoRedoChange> => { const {data, target} = undoChange; const container: HTMLElement = toHTMLElement(target); const {oldValue, offset: newCaretPosition, index, indexDepths} = data as UndoRedoInput; const paragraph: Element | undefined = container.children[index]; let text: Node | undefined = findNodeAtDepths({parent: paragraph, indexDepths}); if (!text || !isTextNode(text)) { // We try to find sibling in case the parent does not yet exist. If we find it, we can replicate such parent for the new text. // Useful notably when reverting lists and li. const cloneIndexDepths: number[] = [...indexDepths]; cloneIndexDepths.pop(); let parent: Node | undefined = cloneIndexDepths.length <= 0 ? text ? text.parentNode : undefined : findNodeAtDepths({parent: paragraph, indexDepths: [...cloneIndexDepths]}); if (!parent && isTextNode(toHTMLElement(paragraph)?.lastChild)) { text = toHTMLElement(paragraph).lastChild; } if (!text) { if (!parent) { parent = await createLast({paragraph: toHTMLElement(paragraph) || container, container}); } text = await prependText({parent: toHTMLElement(parent), container}); } } const {previousValue} = await updateNodeValue({text, oldValue, container}); moveCursorToOffset({ element: text, offset: Math.min( oldValue.length > newCaretPosition ? newCaretPosition : oldValue.length, text.nodeValue.length ) }); return { type: 'input', target: container, data: { index, indexDepths, oldValue: previousValue, offset: newCaretPosition + (previousValue.length - oldValue.length) } }; }; const undoRedoParagraph = async ({ undoChange }: { undoChange: UndoRedoChange; }): Promise<UndoRedoChange> => { const {data, target} = undoChange; const container: HTMLElement = toHTMLElement(target); const paragraphs: UndoRedoAddRemoveParagraph[] = data as UndoRedoAddRemoveParagraph[]; let to: UndoRedoAddRemoveParagraph[] = []; for (const paragraph of paragraphs) { const {index, outerHTML, mutation} = paragraph; if (mutation === 'add') { await removeNode({container, index}); to = [ { outerHTML, index, mutation: 'remove' }, ...to ]; } if (mutation === 'remove') { await insertNode({container, index, outerHTML}); to = [ { outerHTML, mutation: 'add', index }, ...to ]; } } return { ...undoChange, data: to }; }; const undoRedoUpdate = async ({ undoChange }: { undoChange: UndoRedoChange; }): Promise<UndoRedoChange> => { const {data, target} = undoChange; const paragraphs: UndoRedoUpdateParagraph[] = data as UndoRedoUpdateParagraph[]; const container: HTMLElement = toHTMLElement(target); const to: UndoRedoUpdateParagraph[] = []; for (const paragraph of paragraphs) { const {index, outerHTML} = paragraph; const {previousOuterHTML} = await updateNode({ container, index, outerHTML }); to.push({index, outerHTML: previousOuterHTML}); } return { ...undoChange, data: to }; }; /** * Because we are using indexes to add or remove back and forth elements, we have to wait for changes to be applied to the DOM before iterating to next element to process. * That's why the mutation observer and promises. */ const insertNode = ({ container, index, outerHTML }: { outerHTML: string; index: number; container: HTMLElement; }): Promise<void> => new Promise<void>((resolve) => { const changeObserver: MutationObserver = new MutationObserver( (_mutations: MutationRecord[]) => { changeObserver.disconnect(); resolve(); } ); changeObserver.observe(container, {childList: true, subtree: true}); const previousSiblingIndex: number = index - 1; if (previousSiblingIndex === -1) { container.insertAdjacentHTML('afterbegin', outerHTML); return; } container.children[ Math.min(previousSiblingIndex, container.children.length - 1) ].insertAdjacentHTML('afterend', outerHTML); }); const removeNode = ({container, index}: {index: number; container: HTMLElement}): Promise<void> => new Promise<void>((resolve) => { const changeObserver: MutationObserver = new MutationObserver(() => { changeObserver.disconnect(); resolve(); }); changeObserver.observe(container, {childList: true, subtree: true}); const element: Element | undefined = container.children[Math.min(index, container.children.length - 1)]; element?.parentElement.removeChild(element); }); const updateNode = ({ container, index, outerHTML }: { outerHTML: string; index: number; container: HTMLElement; }): Promise<{previousOuterHTML: string}> => new Promise<{previousOuterHTML: string}>((resolve) => { const paragraph: Element = container.children[Math.min(index, container.children.length - 1)]; const previousOuterHTML: string = paragraph.outerHTML; const changeObserver: MutationObserver = new MutationObserver( (_mutations: MutationRecord[]) => { changeObserver.disconnect(); resolve({previousOuterHTML}); } ); changeObserver.observe(container, {childList: true, subtree: true}); paragraph.outerHTML = outerHTML; }); const prependText = ({ parent, container }: { parent: HTMLElement; container: HTMLElement; }): Promise<Node> => new Promise<Node>((resolve) => { const text: Node = document.createTextNode(''); const changeObserver: MutationObserver = new MutationObserver(() => { changeObserver.disconnect(); resolve(text); }); changeObserver.observe(container, {childList: true, subtree: true}); parent.prepend(text); }); const updateNodeValue = ({ container, oldValue, text }: { oldValue: string; text: Node; container: HTMLElement; }): Promise<{previousValue: string}> => new Promise<{previousValue: string}>((resolve) => { const previousValue: string = text.nodeValue; const changeObserver: MutationObserver = new MutationObserver(() => { changeObserver.disconnect(); resolve({previousValue}); }); changeObserver.observe(container, {characterData: true, subtree: true}); text.nodeValue = oldValue; }); const createLast = ({ container, paragraph }: { container: HTMLElement; paragraph: HTMLElement; }): Promise<HTMLElement> => new Promise<HTMLElement>((resolve) => { const anchor: HTMLElement = paragraph.lastElementChild?.nodeName.toLowerCase() !== 'br' ? toHTMLElement(paragraph.lastElementChild) : document.createElement('span'); const parent: HTMLElement = toHTMLElement(anchor.cloneNode()); parent.innerHTML = ''; const changeObserver: MutationObserver = new MutationObserver(() => { changeObserver.disconnect(); resolve(parent); }); changeObserver.observe(container, {childList: true, subtree: true}); anchor.after(parent); });
the_stack
import {Change, Prefix, EvaluationContext, GlobalInterner, printPrefix} from "./runtime"; import * as Runtime from "./runtime"; import {Renderer} from "../microReact"; import {PerformanceTracker} from "./performance" function isID(v: any) { return typeof v === "string" && (v.indexOf("|") > -1 || (v[8] === "-" && v.length === 36)) } //------------------------------------------------------------------------ // UI helpers //------------------------------------------------------------------------ function handleArgs(args:any[]) { if(typeof args[0] === "object" && args[0].constructor !== Array) return args; args.unshift({}); return args; } function $row(...args:any[]) { let [elem, children] = handleArgs(args); elem.t = "row"; elem.children = children; return elem; } function $col(...args:any[]) { let [elem, children] = handleArgs(args); elem.t = "column"; elem.children = children; return elem; } function $text(...args:any[]) { let [elem, text] = handleArgs(args); elem.t = "text"; elem.text = text; return elem; } function $button(...args:any[]) { let [elem, click, content] = handleArgs(args); elem.t = "button"; if(typeof content === "string") { elem.text = content; } else { elem.children = [content]; } elem.click = click; return elem; } function $spacer(...args:any[]) { let [elem] = handleArgs(args); elem.t = "spacer"; return elem; } //------------------------------------------------------------------------ // Tracer //------------------------------------------------------------------------ export enum TraceNode { Join, Choose, Union, LinearFlow, BinaryJoin, AntiJoin, AntiJoinPresolvedRight, Aggregate, AggregateOuterLookup, Output, Watch, } export enum TraceFrameType { Program, Transaction, Input, Block, Node, MaybeOutput, MaybeExternalInput, } let typeToParentField = { [TraceFrameType.Transaction]: "transactions", [TraceFrameType.Input]: "inputs", [TraceFrameType.Block]: "blocks", [TraceFrameType.Node]: "nodes", [TraceFrameType.MaybeOutput]: "outputs", [TraceFrameType.MaybeExternalInput]: "externalInputs", } export interface Frame {type:TraceFrameType}; export interface ProgramFrame extends Frame {transactions: TransactionFrame[]} export interface TransactionFrame extends Frame {id:number, externalInputs:any[], inputs:any[]} export class Tracer { stack:any[] = [{type:TraceFrameType.Program, transactions: []}]; _currentInput:Change|undefined; inputsToOutputs:any = {}; outputsToInputs:any = {}; eToChange:any = {}; renderer:Renderer; activeBlock = ""; tracker = new PerformanceTracker(); constructor(public context:EvaluationContext, shouldDraw = true) { if(typeof window !== "undefined" && shouldDraw) { let renderer = this.renderer = new Renderer(); document.body.appendChild(renderer.content); } } changeKey(change:Change) { let {e,a,v,n,round,transaction,count} = change; return `${e}|${a}|${v}|${n}|${round}|${transaction}|${count}`; } current() { return this.stack[this.stack.length - 1]; } transaction(id:number) { this.stack.push({type:TraceFrameType.Transaction, id, externalInputs: [], inputs: []}) this.tracker.time("transaction"); } frame(commits:Change[]) { // @TODO } indexChange(change:Change) { let found = this.eToChange[change.e]; if(!found) found = this.eToChange[change.e] = []; found.push(change); } input(input:Change) { this._currentInput = input; this.indexChange(input); this.stack.push({type:TraceFrameType.Input, input, blocks: []}) } block(name:string) { this.activeBlock = name; this.stack.push({type:TraceFrameType.Block, name, nodes: []}) this.tracker.block(name); } node(node:Runtime.Node, inputPrefix:Prefix) { this.stack.push({type:TraceFrameType.Node, nodeType:node.traceType, node, inputPrefix:inputPrefix.slice(), nodes: [], prefixes: [], outputs: [], commits: []}) } capturePrefix(prefix:Prefix) { let parent = this.current(); parent.prefixes.push(prefix.slice()); } _mapOutput(output:Change) { let {_currentInput} = this; if(_currentInput) { let outKey = this.changeKey(output); let inKey = this.changeKey(_currentInput); this.outputsToInputs[outKey] = _currentInput; let inList = this.inputsToOutputs[inKey]; if(!inList) inList = this.inputsToOutputs[inKey] = []; inList.push(output); } } maybeOutput(change:Change) { // this._mapOutput(change); let cur = this.current(); let type = TraceFrameType.MaybeOutput; if(cur.type === TraceFrameType.Transaction) { type = TraceFrameType.MaybeExternalInput; } let counts = (this.context.distinctIndex.getCounts(change) || []).slice(); this.stack.push({type, distinct: {pre: counts, post: undefined}, change, outputs: []}) } postDistinct() { let cur = this.current(); let counts = this.context.distinctIndex.getCounts(cur.change)!.slice(); cur.distinct.post = counts; } output(output:Change) { let safe = output.clone(); this._mapOutput(safe); let parent = this.current(); parent.outputs.push(safe); } commit(commit:Change) { let safe = commit.clone(); this._mapOutput(safe); let parent = this.current(); parent.commits.push(safe); } distinctCheck() { let error = false; let {index} = this.context.distinctIndex; for(let key in index) { let counts = index[key]!; let sum = 0; for(let c of counts) { if(!c) continue; sum += c; if(sum < 0) { console.error("Negative postDistinct: ", key, counts.slice()) error = true; // throw new Error("Negative postDistinct at the end of a transaction") } } } return error; } pop(type:TraceFrameType) { let {stack} = this; let cur = stack.pop(); if(cur.type !== type) { if(cur.type !== TraceFrameType.MaybeExternalInput || type !== TraceFrameType.MaybeOutput) { throw new Error(`Popping the wrong type! expected: ${TraceFrameType[type]}, actual: ${TraceFrameType[cur.type]}`) } } let parent = this.current(); if(!parent) { throw new Error("Removed everything from the stack"); } if(cur.type === TraceFrameType.Transaction) { parent = this.stack[0]; parent.transactions[cur.id] = cur; } else { let field = typeToParentField[cur.type]; if(!parent[field]) throw new Error(`Trying to write trace field '${field}', but ${TraceFrameType[parent.type]} doesn't have it`); parent[field].push(cur); } if(cur.type === TraceFrameType.Block) this.tracker.blockEnd(cur.name); if(cur.type === TraceFrameType.Input) this._currentInput = undefined; if(cur.type === TraceFrameType.Transaction) { this.tracker.timeEnd("transaction"); let error = this.distinctCheck(); this.draw(); } } //------------------------------------------------------------------------ // UI //------------------------------------------------------------------------ activeSearch:string = ""; activeInput:Change|undefined; draw() { let {renderer} = this; if(!renderer) return; renderer.render([this.$interface()]) } $interface = () => { let program = this.stack[0]; return $row({c: "trace"}, [ this.$searcher(program), this.$visualization(program) ]) } makeSearch = (query:string) => { let [e,a,v] = query.split(",").map((v) => v.trim()); let conditions = []; if(e && e !== "?") { conditions.push(`input.e == ${+e}`); } if(a && a !== "?") { conditions.push(`input.a === ${GlobalInterner.intern(a)}`); } if(v && v !== "?") { if(this.eToChange[+v]) { conditions.push(`input.v == ${+v}`); } else { conditions.push(`input.v == ${GlobalInterner.intern(isNaN(+v) ? v : +v)}`); } } if(!conditions.length) { conditions.push("true"); } return new Function("input", `return ${conditions.join(" && ")}`) as (input:Change) => boolean; } inSearch = (input:Change) => { return true; } $searcher = (program:ProgramFrame) => { let inputs = []; outer: for(let transaction of program.transactions) { if(!transaction) continue; for(let input of transaction.inputs) { if(this.inSearch(input.input)) { inputs.push(this.$changeLink(input.input)); if(inputs.length === 500) { break outer; } } } } return $col({c: "searcher"}, [ {t: "input", type: "text", placeholder:"search", keydown: (e:any) => { if(e.keyCode === 13) { this.activeSearch = e.target.value.trim(); this.inSearch = this.makeSearch(this.activeSearch); this.draw(); } }}, $col(inputs) ]) } getInputFrame(program:ProgramFrame, input:Change) { let trans = program.transactions[input.transaction]; for(let frame of trans.inputs) { if(frame.input === input) return frame; } } $visualization = (program:ProgramFrame) => { let {$changeLink, activeInput, getInputFrame, $block} = this; if(activeInput) { let frame = getInputFrame(program, activeInput); let key = this.changeKey(activeInput); let from = this.outputsToInputs[key]; let to = this.inputsToOutputs[key]; let fromInfo; if(from) { fromInfo = $col([ $text("generated by: "), $changeLink(from), ]); } else { fromInfo = $col([ $text("generated by: "), $text("unknown"), ]); } let toInfo; if(to) { toInfo = $col([ $text("causes output:"), $col(to.map($changeLink)), ]); } let counts = this.context.distinctIndex.getCounts(activeInput)!; console.log(frame); return $col({c: "vis"}, [ $changeLink(activeInput), fromInfo, $col(frame.blocks.map($block)), toInfo, $text(`counts: [${counts.join(", ")}]`) ]) } return $text("select an input"); // return $col({c: "program"}, program.transactions.map(this.$transaction)); } $block = (block:any) => { return $col({c: "block"}, [ $text({c: "name"}, block.name), $col(block.nodes.map(this.$node)), ]); } $node = (node:any) => { let {$prefix, $node, $changeLink} = this; let subs = node.nodes.map($node); let out; if(node.prefixes.length) { out = $row([ $text("out: "), $col(node.prefixes.map($prefix)), ]); } if(node.outputs.length) { let outs = []; for(let output of node.outputs) { outs.push( $col([ $row([ $text("maybe out: "), $changeLink(output.change), ]), $text(`pre: ${output.distinct.pre}`), $text(`post: ${output.distinct.post}`), $row([ $text("distinct out: "), $col(output.outputs.map($changeLink)), ]), ]) ); } out = $col(outs); } return $col({c: "node"}, [ $text(TraceNode[node.nodeType]), $row([ $text("in: "), $prefix(node.inputPrefix), ]), $row(subs), out, ]); } $prefix = (prefix:Prefix) => { let items = []; let hasValue = false; for(let ix = 0; ix < prefix.length - 2; ix++) { let value:any = prefix[ix]; if(value === undefined) { value = "?"; } else if(!isID(GlobalInterner.reverse(value))) { hasValue = true; value = GlobalInterner.reverse(value); } else { hasValue = true; } items.push(value); } if(!hasValue) { return $text("(empty)"); } let round = prefix[prefix.length - 2]; let count = prefix[prefix.length - 1]; return $text(`(${items.join(", ")}) [${round}, ${count}]`); } setLink = (e:any, elem:any) => { this.activeInput = elem.input; this.draw(); } $changeLink = (change:Change) => { let {e,a,v}:any = change; a = GlobalInterner.reverse(a); v = GlobalInterner.reverse(v); if(typeof v === "string" && (v.indexOf("|") > -1 || (v[8] === "-" && v.length === 36))) { v = change.v; } return $button({c: "change-link", input:change}, this.setLink, $row([ $text(`${e}, ${a}, ${v}`), $spacer(), $text(` [${change.transaction}, ${change.round}, ${change.count}]`), ])); } } export class NoopTracer extends Tracer { activeBlock = ""; constructor(public context:EvaluationContext) { super(context, false); } transaction(id:number) { } frame(commits:Change[]) { } input(input:Change) { } block(name:string) { this.activeBlock = name; } node(node:Runtime.Node, inputPrefix:Prefix) { } capturePrefix(prefix:Prefix) { } maybeOutput(change:Change) { } postDistinct() { } output(output:Change) { } commit(commit:Change) { } distinctCheck() { return false; } pop(type:TraceFrameType) { } }
the_stack
import { HardhatRuntimeEnvironment } from "hardhat/types"; import { DeployFunction } from "hardhat-deploy/types"; import { ethers, upgrades } from "hardhat"; import { MdexRestrictedStrategyAddBaseTokenOnly__factory, MdexRestrictedStrategyAddTwoSidesOptimal__factory, MdexRestrictedStrategyLiquidate__factory, MdexRestrictedStrategyPartialCloseLiquidate__factory, MdexRestrictedStrategyPartialCloseMinimizeTrading__factory, MdexRestrictedStrategyWithdrawMinimizeTrading__factory, MdexWorker02, MdexWorker02__factory, Timelock__factory, } from "../../../../typechain"; import { ConfigEntity } from "../../../entities"; interface IMdexWorkerInput { VAULT_SYMBOL: string; WORKER_NAME: string; REINVEST_BOT: string; POOL_ID: number; REINVEST_BOUNTY_BPS: string; REINVEST_PATH: Array<string>; REINVEST_THRESHOLD: string; WORK_FACTOR: string; KILL_FACTOR: string; MAX_PRICE_DIFF: string; EXACT_ETA: string; } interface IMdexWorkerInfo { WORKER_NAME: string; VAULT_CONFIG_ADDR: string; WORKER_CONFIG_ADDR: string; REINVEST_BOT: string; POOL_ID: number; VAULT_ADDR: string; BASE_TOKEN_ADDR: string; BSC_POOL: string; MDEX_ROUTER_ADDR: string; ADD_STRAT_ADDR: string; LIQ_STRAT_ADDR: string; TWO_SIDES_STRAT_ADDR: string; PARTIAL_CLOSE_LIQ_STRAT_ADDR: string; PARTIAL_CLOSE_MINIMIZE_STRAT_ADDR: string; MINIMIZE_TRADE_STRAT_ADDR: string; REINVEST_BOUNTY_BPS: string; REINVEST_PATH: Array<string>; REINVEST_THRESHOLD: string; WORK_FACTOR: string; KILL_FACTOR: string; MAX_PRICE_DIFF: string; TIMELOCK: string; EXACT_ETA: string; } const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) { /* ░██╗░░░░░░░██╗░█████╗░██████╗░███╗░░██╗██╗███╗░░██╗░██████╗░ ░██║░░██╗░░██║██╔══██╗██╔══██╗████╗░██║██║████╗░██║██╔════╝░ ░╚██╗████╗██╔╝███████║██████╔╝██╔██╗██║██║██╔██╗██║██║░░██╗░ ░░████╔═████║░██╔══██║██╔══██╗██║╚████║██║██║╚████║██║░░╚██╗ ░░╚██╔╝░╚██╔╝░██║░░██║██║░░██║██║░╚███║██║██║░╚███║╚██████╔╝ ░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚══╝╚═╝╚═╝░░╚══╝░╚═════╝░ Check all variables below before execute the deployment script */ const shortWorkerInfos: IMdexWorkerInput[] = [ { VAULT_SYMBOL: "ibBTCB", WORKER_NAME: "ETH-BTCB MdexWorker", REINVEST_BOT: "0xe45216Ac4816A5Ec5378B1D13dE8aA9F262ce9De", POOL_ID: 30, REINVEST_BOUNTY_BPS: "300", REINVEST_PATH: ["MDX", "WBNB", "BTCB"], REINVEST_THRESHOLD: "0", WORK_FACTOR: "7000", KILL_FACTOR: "8333", MAX_PRICE_DIFF: "11000", EXACT_ETA: "1633584600", }, { VAULT_SYMBOL: "ibETH", WORKER_NAME: "BTCB-ETH MdexWorker", REINVEST_BOT: "0xe45216Ac4816A5Ec5378B1D13dE8aA9F262ce9De", POOL_ID: 30, REINVEST_BOUNTY_BPS: "300", REINVEST_PATH: ["MDX", "ETH"], REINVEST_THRESHOLD: "0", WORK_FACTOR: "7000", KILL_FACTOR: "8333", MAX_PRICE_DIFF: "11000", EXACT_ETA: "1633584600", }, { VAULT_SYMBOL: "ibUSDT", WORKER_NAME: "USDC-USDT MdexWorker", REINVEST_BOT: "0xe45216Ac4816A5Ec5378B1D13dE8aA9F262ce9De", POOL_ID: 33, REINVEST_BOUNTY_BPS: "300", REINVEST_PATH: ["MDX", "USDT"], REINVEST_THRESHOLD: "0", WORK_FACTOR: "7800", KILL_FACTOR: "9000", MAX_PRICE_DIFF: "10500", EXACT_ETA: "1633584600", }, { VAULT_SYMBOL: "ibBTCB", WORKER_NAME: "WBNB-BTCB MdexWorker", REINVEST_BOT: "0xe45216Ac4816A5Ec5378B1D13dE8aA9F262ce9De", POOL_ID: 55, REINVEST_BOUNTY_BPS: "300", REINVEST_PATH: ["MDX", "WBNB", "BTCB"], REINVEST_THRESHOLD: "0", WORK_FACTOR: "7000", KILL_FACTOR: "8333", MAX_PRICE_DIFF: "10500", EXACT_ETA: "1633584600", }, { VAULT_SYMBOL: "ibWBNB", WORKER_NAME: "BTCB-WBNB MdexWorker", REINVEST_BOT: "0xe45216Ac4816A5Ec5378B1D13dE8aA9F262ce9De", POOL_ID: 55, REINVEST_BOUNTY_BPS: "300", REINVEST_PATH: ["MDX", "WBNB"], REINVEST_THRESHOLD: "0", WORK_FACTOR: "7000", KILL_FACTOR: "8333", MAX_PRICE_DIFF: "10500", EXACT_ETA: "1633584600", }, { VAULT_SYMBOL: "ibUSDT", WORKER_NAME: "DAI-USDT MdexWorker", REINVEST_BOT: "0xe45216Ac4816A5Ec5378B1D13dE8aA9F262ce9De", POOL_ID: 37, REINVEST_BOUNTY_BPS: "300", REINVEST_PATH: ["MDX", "USDT"], REINVEST_THRESHOLD: "0", WORK_FACTOR: "7800", KILL_FACTOR: "9000", MAX_PRICE_DIFF: "10500", EXACT_ETA: "1633584600", }, ]; const config = ConfigEntity.getConfig(); const workerInfos: IMdexWorkerInfo[] = shortWorkerInfos.map((n) => { const vault = config.Vaults.find((v) => v.symbol === n.VAULT_SYMBOL); if (vault === undefined) { throw `error: unable to find vault from ${n.VAULT_SYMBOL}`; } const tokenList: any = config.Tokens; const reinvestPath: Array<string> = n.REINVEST_PATH.map((p) => { const addr = tokenList[p]; if (addr === undefined) { throw `error: path: unable to find address of ${p}`; } return addr; }); return { WORKER_NAME: n.WORKER_NAME, VAULT_CONFIG_ADDR: vault.config, WORKER_CONFIG_ADDR: config.SharedConfig.WorkerConfig, REINVEST_BOT: n.REINVEST_BOT, POOL_ID: n.POOL_ID, VAULT_ADDR: vault.address, BASE_TOKEN_ADDR: vault.baseToken, BSC_POOL: config.Exchanges.Mdex.BSCPool, MDEX_ROUTER_ADDR: config.Exchanges.Mdex.MdexRouter, ADD_STRAT_ADDR: config.SharedStrategies.Mdex.StrategyAddBaseTokenOnly, LIQ_STRAT_ADDR: config.SharedStrategies.Mdex.StrategyLiquidate, TWO_SIDES_STRAT_ADDR: vault.StrategyAddTwoSidesOptimal.Mdex, PARTIAL_CLOSE_LIQ_STRAT_ADDR: config.SharedStrategies.Mdex.StrategyPartialCloseLiquidate, PARTIAL_CLOSE_MINIMIZE_STRAT_ADDR: config.SharedStrategies.Mdex.StrategyPartialCloseMinimizeTrading, MINIMIZE_TRADE_STRAT_ADDR: config.SharedStrategies.Mdex.StrategyWithdrawMinimizeTrading, REINVEST_BOUNTY_BPS: n.REINVEST_BOUNTY_BPS, REINVEST_PATH: reinvestPath, REINVEST_THRESHOLD: ethers.utils.parseEther(n.REINVEST_THRESHOLD).toString(), WORK_FACTOR: n.WORK_FACTOR, KILL_FACTOR: n.KILL_FACTOR, MAX_PRICE_DIFF: n.MAX_PRICE_DIFF, TIMELOCK: config.Timelock, EXACT_ETA: n.EXACT_ETA, }; }); for (let i = 0; i < workerInfos.length; i++) { console.log("==================================================================================="); console.log(`>> Deploying an upgradable MdexWorker02 contract for ${workerInfos[i].WORKER_NAME}`); const MdexWorker02 = (await ethers.getContractFactory( "MdexWorker02", ( await ethers.getSigners() )[0] )) as MdexWorker02__factory; const mdexWorker02 = (await upgrades.deployProxy(MdexWorker02, [ workerInfos[i].VAULT_ADDR, workerInfos[i].BASE_TOKEN_ADDR, workerInfos[i].BSC_POOL, workerInfos[i].MDEX_ROUTER_ADDR, workerInfos[i].POOL_ID, workerInfos[i].ADD_STRAT_ADDR, workerInfos[i].LIQ_STRAT_ADDR, workerInfos[i].REINVEST_BOUNTY_BPS, workerInfos[i].REINVEST_BOT, workerInfos[i].REINVEST_PATH, workerInfos[i].REINVEST_THRESHOLD, ])) as MdexWorker02; await mdexWorker02.deployed(); console.log(`>> Deployed at ${mdexWorker02.address}`); console.log(`>> Adding REINVEST_BOT`); await mdexWorker02.setReinvestorOk([workerInfos[i].REINVEST_BOT], true); console.log("✅ Done"); console.log(`>> Adding Strategies`); const okStrats = [workerInfos[i].TWO_SIDES_STRAT_ADDR, workerInfos[i].MINIMIZE_TRADE_STRAT_ADDR]; if (workerInfos[i].PARTIAL_CLOSE_LIQ_STRAT_ADDR != "") { okStrats.push(workerInfos[i].PARTIAL_CLOSE_LIQ_STRAT_ADDR); } if (workerInfos[i].PARTIAL_CLOSE_MINIMIZE_STRAT_ADDR != "") { okStrats.push(workerInfos[i].PARTIAL_CLOSE_MINIMIZE_STRAT_ADDR); } await mdexWorker02.setStrategyOk(okStrats, true); console.log("✅ Done"); console.log(`>> Whitelisting a worker on strats`); const addStrat = MdexRestrictedStrategyAddBaseTokenOnly__factory.connect( workerInfos[i].ADD_STRAT_ADDR, (await ethers.getSigners())[0] ); await addStrat.setWorkersOk([mdexWorker02.address], true); const liqStrat = MdexRestrictedStrategyLiquidate__factory.connect( workerInfos[i].LIQ_STRAT_ADDR, (await ethers.getSigners())[0] ); await liqStrat.setWorkersOk([mdexWorker02.address], true); const twoSidesStrat = MdexRestrictedStrategyAddTwoSidesOptimal__factory.connect( workerInfos[i].TWO_SIDES_STRAT_ADDR, (await ethers.getSigners())[0] ); await twoSidesStrat.setWorkersOk([mdexWorker02.address], true); const minimizeStrat = MdexRestrictedStrategyWithdrawMinimizeTrading__factory.connect( workerInfos[i].MINIMIZE_TRADE_STRAT_ADDR, (await ethers.getSigners())[0] ); await minimizeStrat.setWorkersOk([mdexWorker02.address], true); if (workerInfos[i].PARTIAL_CLOSE_LIQ_STRAT_ADDR != "") { console.log(">> partial close liquidate is deployed"); const partialCloseLiquidate = MdexRestrictedStrategyPartialCloseLiquidate__factory.connect( workerInfos[i].PARTIAL_CLOSE_LIQ_STRAT_ADDR, (await ethers.getSigners())[0] ); await partialCloseLiquidate.setWorkersOk([mdexWorker02.address], true); } if (workerInfos[i].PARTIAL_CLOSE_MINIMIZE_STRAT_ADDR != "") { console.log(">> partial close minimize is deployed"); const partialCloseMinimize = MdexRestrictedStrategyPartialCloseMinimizeTrading__factory.connect( workerInfos[i].PARTIAL_CLOSE_MINIMIZE_STRAT_ADDR, (await ethers.getSigners())[0] ); await partialCloseMinimize.setWorkersOk([mdexWorker02.address], true); } console.log("✅ Done"); const timelock = Timelock__factory.connect(workerInfos[i].TIMELOCK, (await ethers.getSigners())[0]); console.log(">> Timelock: Setting WorkerConfig via Timelock"); const setConfigsTx = await timelock.queueTransaction( workerInfos[i].WORKER_CONFIG_ADDR, "0", "setConfigs(address[],(bool,uint64,uint64,uint64)[])", ethers.utils.defaultAbiCoder.encode( ["address[]", "(bool acceptDebt,uint64 workFactor,uint64 killFactor,uint64 maxPriceDiff)[]"], [ [mdexWorker02.address], [ { acceptDebt: true, workFactor: workerInfos[i].WORK_FACTOR, killFactor: workerInfos[i].KILL_FACTOR, maxPriceDiff: workerInfos[i].MAX_PRICE_DIFF, }, ], ] ), workerInfos[i].EXACT_ETA ); console.log(`queue setConfigs at: ${setConfigsTx.hash}`); console.log("generate timelock.executeTransaction:"); console.log( `await timelock.executeTransaction('${workerInfos[i].WORKER_CONFIG_ADDR}', '0', 'setConfigs(address[],(bool,uint64,uint64,uint64)[])', ethers.utils.defaultAbiCoder.encode(['address[]','(bool acceptDebt,uint64 workFactor,uint64 killFactor,uint64 maxPriceDiff)[]'],[['${mdexWorker02.address}'], [{acceptDebt: true, workFactor: ${workerInfos[i].WORK_FACTOR}, killFactor: ${workerInfos[i].KILL_FACTOR}, maxPriceDiff: ${workerInfos[i].MAX_PRICE_DIFF}}]]), ${workerInfos[i].EXACT_ETA})` ); console.log("✅ Done"); console.log(">> Timelock: Linking VaultConfig with WorkerConfig via Timelock"); const setWorkersTx = await timelock.queueTransaction( workerInfos[i].VAULT_CONFIG_ADDR, "0", "setWorkers(address[],address[])", ethers.utils.defaultAbiCoder.encode( ["address[]", "address[]"], [[mdexWorker02.address], [workerInfos[i].WORKER_CONFIG_ADDR]] ), workerInfos[i].EXACT_ETA ); console.log(`queue setWorkers at: ${setWorkersTx.hash}`); console.log("generate timelock.executeTransaction:"); console.log( `await timelock.executeTransaction('${workerInfos[i].VAULT_CONFIG_ADDR}', '0','setWorkers(address[],address[])', ethers.utils.defaultAbiCoder.encode(['address[]','address[]'],[['${mdexWorker02.address}'], ['${workerInfos[i].WORKER_CONFIG_ADDR}']]), ${workerInfos[i].EXACT_ETA})` ); console.log("✅ Done"); } }; export default func; func.tags = ["MdexWorkers02"];
the_stack
import express = require('express'); declare namespace e { } declare function e(): express.RequestHandler; export = e; /** * Type augmentation for express */ /** * Based on Sandeep K Nair gist: https://gist.github.com/sandeepsuvit/2486c99c0346db87de24539472f34451 * And https://github.com/hapijs/boom */ declare global { namespace Express { interface Boom { // Add boom's properties in here wrap(error: Error, statusCode?: number, message?: string): BoomError<null>; create<Data = null>(statusCode: number, message?: string, data?: Data): BoomError<Data>; /** * Decorates an error with the boom properties * @param error the error object to wrap. If error is already a boom object, it defaults to overriding the object with the new status code and message. * @param options optional additional options * @see {@link https://github.com/hapijs/boom#boomifyerror-options} */ boomify(error: Error, options?: { statusCode?: number, message?: string, override?: boolean }): BoomError<null>; // 4xx /** * Respond a 400 Bad Request error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadrequestmessage-data} */ badRequest<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 401 Unauthorized error * @param message optional message. * @param scheme can be one of the following: * * an authentication scheme name * * an array of string values. These values will be separated by ', ' and set to the 'WWW-Authenticate' header. * @param attributes an object of values to use while setting the 'WWW-Authenticate' header. * This value is only used when scheme is a string, otherwise it is ignored. * Every key/value pair will be included in the 'WWW-Authenticate' in the format of * 'key="value"' as well as in the response payload under the attributes key. * Alternatively value can be a string which is use to set the value of the scheme, * for example setting the token value for negotiate header. * If string is used message parameter must be null. * null and undefined will be replaced with an empty string. If attributes is set, * message will be used as the 'error' segment of the 'WWW-Authenticate' header. * If message is unset, the 'error' segment of the header will not be present and isMissing will be true on the error object. * @see {@link https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes} */ unauthorized(message?: string, scheme?: string, attributes?: { [index: string]: string }): BoomError<null>; unauthorized(message?: string, scheme?: string[]): BoomError<null>; unauthorized(message?: null, scheme?: string, attributes?: { [index: string]: string } | string): BoomError<null>; /** * Respond a 402 Payment Required error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boompaymentrequiredmessage-data} */ paymentRequired<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 403 Forbidden error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomforbiddenmessage-data} */ forbidden<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 404 Not Found error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomnotfoundmessage-data} */ notFound<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 405 Method Not Allowed error * @param message optional message. * @param data optional additional error data. * @param allow optional string or array of strings (to be combined and separated by ', ') which is set to the 'Allow' header. * @see {@link https://github.com/hapijs/boom#boommethodnotallowedmessage-data-allow} */ methodNotAllowed<Data = null>(message?: string, data?: Data, allow?: string | string[]): BoomError<Data>; /** * Respond a 406 Not Acceptable error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomnotacceptablemessage-data} */ notAcceptable<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 407 Proxy Authentication Required error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomproxyauthrequiredmessage-data} */ proxyAuthRequired<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 408 Request Time-out error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomclienttimeoutmessage-data} */ clientTimeout<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 409 Conflict error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomconflictmessage-data} */ conflict<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 410 Gone error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomresourcegonemessage-data} */ resourceGone<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 411 Length Required error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomlengthrequiredmessage-data} */ lengthRequired<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 412 Precondition Failed error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boompreconditionfailedmessage-data} */ preconditionFailed<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 413 Request Entity Too Large error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomentitytoolargemessage-data} */ entityTooLarge<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 414 Request-URI Too Large error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomuritoolongmessage-data} */ uriTooLong<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 415 Unsupported Media Type error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomunsupportedmediatypemessage-data} */ unsupportedMediaType<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 416 Requested Range Not Satisfiable error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomrangenotsatisfiablemessage-data} */ rangeNotSatisfiable<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 417 Expectation Failed error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomexpectationfailedmessage-data} */ expectationFailed<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 418 I'm a Teapot error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomteapotmessage-data} */ teapot<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 422 Unprocessable Entity error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombaddatamessage-data} */ badData<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 423 Locked error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomlockedmessage-data} */ locked<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 424 Failed Dependency error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomfaileddependencymessage-data} */ failedDependency<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 428 Precondition Required error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boompreconditionrequiredmessage-data} */ preconditionRequired<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 429 Too Many Requests error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomtoomanyrequestsmessage-data} */ tooManyRequests<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 451 Unavailable For Legal Reasons error * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomillegalmessage-data} */ illegal<Data = null>(message?: string, data?: Data): BoomError<Data>; // 5xx /** * Respond a 500 Internal Server Error error * Only 500 errors will hide your message from the end user. Your message is recorded in the server log. * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadimplementationmessage-data---alias-internal} */ badImplementation<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 500 Internal Server Error error * Only 500 errors will hide your message from the end user. Your message is recorded in the server log. * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadimplementationmessage-data---alias-internal} */ internal<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 501 Not Implemented error with your error message to the user * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomnotimplementedmessage-data} */ notImplemented<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 502 Bad Gateway error with your error message to the user * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadgatewaymessage-data} */ badGateway<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 503 Service Unavailable error with your error message to the user * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomserverunavailablemessage-data} */ serverUnavailable<Data = null>(message?: string, data?: Data): BoomError<Data>; /** * Respond a 504 Gateway Time-out error with your error message to the user * @param message optional message. * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomgatewaytimeoutmessage-data} */ gatewayTimeout<Data = null>(message?: string, data?: Data): BoomError<Data>; } interface BoomError<Data> { data: Data; reformat: () => void; isBoom: boolean; isServer: boolean; message: string; output: Output; } interface Output { /** statusCode - the HTTP status code (typically 4xx or 5xx). */ statusCode: number; /** * headers - an object containing any HTTP headers where each key is a header name and * value is the header content. (Limited value type to string * https://github.com/hapijs/boom/issues/151 ) */ headers: { [index: string]: string }; /** * payload - the formatted object used as the response payload (stringified). * Can be directly manipulated but any changes will be lost if reformat() is called. * Any content allowed and by default includes the following content: */ payload: Payload; } interface Payload { /** statusCode - the HTTP status code, derived from error.output.statusCode. */ statusCode: number; /** error - the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */ error: string; /** message - the error message derived from error.message. */ message: string; /** * "Every key/value pair will be included ... in the response payload under the attributes key." * [see docs](https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes) */ attributes?: any; // Excluded this to aid typing of the other values. Use payload as to define precise typing // [anyContent: string]: any; } interface Response { boom: Boom; } } }
the_stack
import * as b2 from "@box2d"; import * as testbed from "@testbed"; /** * Tracks instances of RadialEmitter and destroys them after a * specified period of time. */ export declare class EmitterTracker { m_emitterLifetime: Array<{ emitter: testbed.RadialEmitter; lifetime: number; }>; /** * Delete all emitters. */ __dtor__(): void; /** * Add an emitter to the tracker. * This assumes emitter was allocated using "new" and ownership * of the object is handed to this class. */ Add(emitter: testbed.RadialEmitter, lifetime: number): void; /** * Update all emitters destroying those who are too old. */ Step(dt: number): void; } /** * Keep track of particle groups in a set, removing them when * they're destroyed. */ export declare class ParticleGroupTracker extends b2.DestructionListener { m_particleGroups: b2.ParticleGroup[]; /** * Called when any particle group is about to be destroyed. */ SayGoodbyeParticleGroup(group: b2.ParticleGroup): void; /** * Add a particle group to the tracker. */ AddParticleGroup(group: b2.ParticleGroup): void; /** * Remove a particle group from the tracker. */ RemoveParticleGroup(group: b2.ParticleGroup): void; GetParticleGroups(): b2.ParticleGroup[]; } export declare class FrackerSettings { /** * Width and height of the world in tiles. */ static readonly k_worldWidthTiles = 24; static readonly k_worldHeightTiles = 16; /** * Total number of tiles. */ static readonly k_worldTiles: number; /** * Center of the world in world coordinates. */ static readonly k_worldCenterX = 0; static readonly k_worldCenterY = 2; /** * Size of each tile in world units. */ static readonly k_tileWidth = 0.2; static readonly k_tileHeight = 0.2; /** * Half width and height of tiles in world units. */ static readonly k_tileHalfWidth: number; static readonly k_tileHalfHeight: number; /** * Half width and height of the world in world coordinates. */ static readonly k_worldHalfWidth: number; static readonly k_worldHalfHeight: number; /** * Colors of tiles. */ static readonly k_playerColor: b2.Color; static readonly k_playerFrackColor: b2.Color; static readonly k_wellColor: b2.Color; static readonly k_oilColor: b2.Color; static readonly k_waterColor: b2.Color; static readonly k_frackingFluidColor: b2.Color; /** * Default density of each body. */ static readonly k_density = 0.1; /** * Radius of oil / water / fracking fluid particles. */ static readonly k_particleRadius: number; /** * Probability (0..100%) of generating each tile (must sum to * 1.0). */ static readonly k_dirtProbability = 80; static readonly k_emptyProbability = 10; static readonly k_oilProbability = 7; static readonly k_waterProbability = 3; /** * Lifetime of a fracking fluid emitter in seconds. */ static readonly k_frackingFluidEmitterLifetime = 5; /** * Speed particles are sucked up the well. */ static readonly k_wellSuckSpeedInside: number; /** * Speed particle are sucket towards the well bottom. */ static readonly k_wellSuckSpeedOutside: number; /** * Time mouse button must be held before emitting fracking * fluid. */ static readonly k_frackingFluidChargeTime = 1; /** * Scores. */ static readonly k_scorePerOilParticle = 1; static readonly k_scorePerWaterParticle = -1; static readonly k_scorePerFrackingParticle = 0; static readonly k_scorePerFrackingDeployment = -10; } /** * Oil Fracking simulator. * * Dig down to move the oil (red) to the well (gray). Try not to * contaminate the ground water (blue). To deploy fracking fluid * press 'space'. Fracking fluid can be used to push other * fluids to the well head and ultimately score points. */ export declare class Fracker extends testbed.Test { m_player: b2.Body; m_wellX: number; m_wellTop: number; m_wellBottom: number; m_tracker: EmitterTracker; m_allowInput: boolean; m_frackingFluidChargeTime: number; m_material: Fracker_Material[]; m_bodies: Array<b2.Body | null>; /** * Set of particle groups the well has influence over. */ m_listener: Fracker_DestructionListener; constructor(); __dtor__(): void; /** * Initialize the data structures used to track the material in * each tile and the bodies associated with each tile. */ InitializeLayout(): void; /** * Get the material of the tile at the specified tile position. */ GetMaterial(x: number, y: number): Fracker_Material; /** * Set the material of the tile at the specified tile position. */ SetMaterial(x: number, y: number, material: Fracker_Material): void; /** * Get the body associated with the specified tile position. */ GetBody(x: number, y: number): b2.Body | null; /** * Set the body associated with the specified tile position. */ SetBody(x: number, y: number, body: b2.Body | null): void; /** * Create the player. */ CreatePlayer(): void; /** * Create the geography / features of the world. */ CreateGeo(): void; /** * Create the boundary of the world. */ CreateGround(): void; /** * Create a dirt block at the specified world position. */ CreateDirtBlock(x: number, y: number): void; /** * Create particles in a tile with resources. */ CreateReservoirBlock(x: number, y: number, material: Fracker_Material): void; /** * Create a well and the region which applies negative pressure * to suck out fluid. */ CreateWell(): void; /** * Create a fracking fluid emitter. */ CreateFrackingFluidEmitter(position: b2.Vec2): void; /** * Update the player's position. */ SetPlayerPosition(playerX: number, playerY: number): void; /** * Try to deploy fracking fluid at the player's position, * returning true if successful. */ DeployFrackingFluid(): boolean; /** * Destroy all particles in the box specified by a set of tile * coordinates. */ DestroyParticlesInTiles(startX: number, startY: number, endX: number, endY: number): void; JointDestroyed(joint: b2.Joint): void; ParticleGroupDestroyed(group: b2.ParticleGroup): void; BeginContact(contact: b2.Contact): void; EndContact(contact: b2.Contact): void; PreSolve(contact: b2.Contact, oldManifold: b2.Manifold): void; PostSolve(contact: b2.Contact, impulse: b2.ContactImpulse): void; /** * a = left, d = right, a = up, s = down, e = deploy fracking * fluid. */ Keyboard(key: string): void; KeyboardUp(key: string): void; MouseDown(p: b2.Vec2): void; /** * Try to deploy the fracking fluid or move the player. */ MouseUp(p: b2.Vec2): void; MouseMove(p: b2.Vec2): void; Step(settings: testbed.Settings): void; /** * Render the well. */ DrawWell(): void; /** * Render the player / fracker. */ DrawPlayer(): void; /** * Render the score and the instructions / keys. */ DrawScore(): void; /** * Draw a quad at position of color that is either just an * outline (fill = false) or solid (fill = true). */ DrawQuad(position: b2.Vec2, color: b2.Color, fill?: boolean): void; GetDefaultViewZoom(): number; static Create(): testbed.Test; /** * Get the bottom left position of the world in world units. */ static GetBottomLeft(bottomLeft: b2.Vec2): void; /** * Get the extents of the world in world units. */ static GetExtents(bottomLeft: b2.Vec2, topRight: b2.Vec2): void; static WorldToTile(position: b2.Vec2, x: [number], y: [number]): void; /** * Convert a tile position to a point in world coordinates. */ static TileToWorld(x: number, y: number, out?: b2.Vec2): b2.Vec2; /** * Calculate the offset within an array of all world tiles using * the specified tile coordinates. */ static TileToArrayOffset(x: number, y: number): number; /** * Calculate the center of a tile position in world units. */ static CenteredPosition(position: b2.Vec2, out?: b2.Vec2): b2.Vec2; /** * Interpolate between color a and b using t. */ static LerpColor(a: b2.Color, b: b2.Color, t: number): b2.Color; /** * Interpolate between a and b using t. */ static Lerp(a: number, b: number, t: number): number; } /** * Type of material in a tile. */ export declare enum Fracker_Material { EMPTY = 0, DIRT = 1, ROCK = 2, OIL = 3, WATER = 4, WELL = 5, PUMP = 6 } /** * Keep track of particle groups which are drawn up the well and * tracks the score of the game. */ export declare class Fracker_DestructionListener extends ParticleGroupTracker { m_score: number; m_oil: number; m_world: b2.World; m_previousListener: b2.DestructionListener | null; /** * Initialize the score. */ __ctor__(): void; /** * Initialize the particle system and world, setting this class * as a destruction listener for the world. */ constructor(world: b2.World); __dtor__(): void; /** * Add to the current score. */ AddScore(score: number): void; /** * Get the current score. */ GetScore(): number; /** * Add to the remaining oil. */ AddOil(oil: number): void; /** * Get the total oil. */ GetOil(): number; /** * Update the score when certain particles are destroyed. */ SayGoodbyeParticle(particleSystem: b2.ParticleSystem, index: number): void; } export declare const testIndex: number;
the_stack
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Pipe, PipeTransform, Injectable, CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, Directive, Input, Output } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { Observable, of as observableOf, throwError } from 'rxjs'; import { Component } from '@angular/core'; import { Example6Component } from './example6.component'; import { ServiceThree, ServiceEight } from './my-components'; import { DomSanitizer } from '@angular/platform-browser'; import { ServiceFour } from './four.service'; import { Service61 } from '../sixty-one.service'; import { serviceOne } from '../one.service'; import { Router, ActivatedRoute } from '@angular/router'; import { ServiceEleven } from '../../evleven.service'; import { ServiceFive } from '@ngx-tranalste/core'; import { Service62 } from './sixty-two.service'; @Injectable() class MockServiceThree { open = function() {}; close = function() {}; } @Injectable() class MockServiceFour { catchError = function() { return observableOf({}); }; getFooing = function() {}; loadBbbUuuu = function() {}; } @Injectable() class MockService61 {} @Injectable() class MockserviceOne {} @Injectable() class MockServiceEight { language = {}; ssssMmmm = {}; } @Injectable() class MockRouter { navigate() {}; } @Injectable() class MockServiceEleven {} @Injectable() class MockService62 { toshowBarXxx = function() {}; } @Directive({ selector: '[oneviewPermitted]' }) class OneviewPermittedDirective { @Input() oneviewPermitted; } @Pipe({name: 'translate'}) class TranslatePipe implements PipeTransform { transform(value) { return value; } } @Pipe({name: 'phoneNumber'}) class PhoneNumberPipe implements PipeTransform { transform(value) { return value; } } @Pipe({name: 'safeHtml'}) class SafeHtmlPipe implements PipeTransform { transform(value) { return value; } } describe('Example6Component', () => { let fixture; let component; beforeEach(() => { TestBed.configureTestingModule({ imports: [ FormsModule, ReactiveFormsModule ], declarations: [ Example6Component, TranslatePipe, PhoneNumberPipe, SafeHtmlPipe, OneviewPermittedDirective ], schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ], providers: [ { provide: ServiceThree, useClass: MockServiceThree }, DomSanitizer, { provide: ServiceFour, useClass: MockServiceFour }, { provide: Service61, useClass: MockService61 }, { provide: serviceOne, useClass: MockserviceOne }, { provide: ServiceEight, useClass: MockServiceEight }, { provide: Router, useClass: MockRouter }, { provide: ActivatedRoute, useValue: { snapshot: {url: 'url', params: {}, queryParams: {}, data: {}}, url: observableOf('url'), params: observableOf({}), queryParams: observableOf({}), fragment: observableOf('fragment'), data: observableOf({}) } }, { provide: ServiceEleven, useClass: MockServiceEleven }, ServiceFive, { provide: Service62, useClass: MockService62 } ] }).overrideComponent(Example6Component, { }).compileComponents(); fixture = TestBed.createComponent(Example6Component); component = fixture.debugElement.componentInstance; }); afterEach(() => { component.ngOnDestroy = function() {}; fixture.destroy(); }); it('should run #constructor()', async () => { expect(component).toBeTruthy(); }); it('should run SetterDeclaration #mySelection', async () => { component.mySelection = {}; }); it('should run GetterDeclaration #mySelection', async () => { const mySelection = component.mySelection; }); it('should run #ngOnInit()', async () => { component.serviceEleven = component.serviceEleven || {}; component.serviceEleven.isFffPppRrrr = 'isFffPppRrrr'; component.router = component.router || {}; component.router.events = observableOf({}); component.service64 = component.service64 || {}; component.service64.getPppIiiAaaa = jest.fn().mockReturnValue(observableOf({ dddPpp: { length: {} } })); component.setbbbHhhPTPMessage = jest.fn(); component.serviceOne = component.serviceOne || {}; component.serviceOne.getHhhPppp = jest.fn().mockReturnValue(observableOf({})); component.serviceFour = component.serviceFour || {}; component.serviceFour.getmyConfig = jest.fn().mockReturnValue(observableOf({})); component.ngOnInit(); // expect(component.service64.getPppIiiAaaa).toHaveBeenCalled(); // expect(component.setbbbHhhPTPMessage).toHaveBeenCalled(); // expect(component.serviceOne.getHhhPppp).toHaveBeenCalled(); // expect(component.serviceFour.getmyConfig).toHaveBeenCalled(); }); it('should run #getIiiFooPppBar()', async () => { component.service64 = component.service64 || {}; component.service64.getIiiFooPppBar = jest.fn().mockReturnValue(observableOf({ fooFuz: { length: {} } })); component.getIiiFooPppBar({ detail: { PId: {} } }); // expect(component.service64.getIiiFooPppBar).toHaveBeenCalled(); }); it('should run #setbbbHhhPTPMessage()', async () => { component.serviceFour = component.serviceFour || {}; component.serviceFour.getIdFffHhhP = jest.fn(); component.service64 = component.service64 || {}; component.service64.getIiiFooPppBar = jest.fn().mockReturnValue(observableOf({ fooFuz: { length: {} } })); component.setbbbHhhPTPMessage(); // expect(component.serviceFour.getIdFffHhhP).toHaveBeenCalled(); // expect(component.service64.getIiiFooPppBar).toHaveBeenCalled(); }); it('should run #setTranslations()', async () => { component.serviceFour = component.serviceFour || {}; component.serviceFour.getmyType = jest.fn().mockReturnValue(observableOf({})); component.service62 = component.service62 || {}; component.service62.getCccEchoDtCcc = jest.fn(); component.mySelection = component.mySelection || {}; component.mySelection.issue_date = 'issue_date'; component.serviceFive = component.serviceFive || {}; component.serviceFive.instant = jest.fn().mockReturnValue('ngentest'); component.setTranslations(); // expect(component.serviceFour.getmyType).toHaveBeenCalled(); // expect(component.service62.getCccEchoDtCcc).toHaveBeenCalled(); // expect(component.serviceFive.instant).toHaveBeenCalled(); }); it('should run #doBbbAaaDddd()', async () => { component.serviceThree = component.serviceThree || {}; component.serviceThree.open = jest.fn(); component.fetchMee = jest.fn().mockReturnValue(observableOf({})); component.doBbbAaaDddd({}); // expect(component.serviceThree.open).toHaveBeenCalled(); // expect(component.fetchMee).toHaveBeenCalled(); }); it('should run #fetchMee()', async () => { component.serviceFour = component.serviceFour || {}; component.serviceFour.betSssEeeMee = jest.fn().mockReturnValue(observableOf({})); component.serviceFour.fetchBar = jest.fn().mockReturnValue(observableOf({})); component.serviceFour.doFoo = jest.fn(); component.mySelection = component.mySelection || {}; component.mySelection.id = 'id'; component.mySelection.date = 'date'; component.serviceThree = component.serviceThree || {}; component.serviceThree.close = jest.fn(); component.serviceThree.open = jest.fn(); component.fetchMee({}); // expect(component.serviceFour.betSssEeeMee).toHaveBeenCalled(); // expect(component.serviceFour.fetchBar).toHaveBeenCalled(); // expect(component.serviceFour.doFoo).toHaveBeenCalled(); // expect(component.serviceThree.close).toHaveBeenCalled(); // expect(component.serviceThree.open).toHaveBeenCalled(); }); it('should run #printBar()', async () => { component.serviceThree = component.serviceThree || {}; component.serviceThree.open = jest.fn(); component.serviceThree.close = jest.fn(); component.serviceFour = component.serviceFour || {}; component.serviceFour.betSssEeeMee = jest.fn().mockReturnValue(observableOf({})); component.serviceFour.resolveMyUrl = jest.fn(); component.sanitize = component.sanitize || {}; component.sanitize.bypassSecurityTrustResourceUrl = jest.fn(); component.mySelection = component.mySelection || {}; component.mySelection.link = 'link'; component.printBar(); // expect(component.serviceThree.open).toHaveBeenCalled(); // expect(component.serviceThree.close).toHaveBeenCalled(); // expect(component.serviceFour.betSssEeeMee).toHaveBeenCalled(); // expect(component.serviceFour.resolveMyUrl).toHaveBeenCalled(); // expect(component.sanitize.bypassSecurityTrustResourceUrl).toHaveBeenCalled(); }); it('should run #saveFoo()', async () => { component.serviceThree = component.serviceThree || {}; component.serviceThree.open = jest.fn(); component.serviceThree.close = jest.fn(); component.serviceFour = component.serviceFour || {}; component.serviceFour.betSssEeeMee = jest.fn().mockReturnValue(observableOf({})); component.serviceFour.resolveMyUrl = jest.fn(); component.mySelection = component.mySelection || {}; component.mySelection.link = 'link'; window.open = jest.fn(); component.saveFoo(); // expect(component.serviceThree.open).toHaveBeenCalled(); // expect(component.serviceThree.close).toHaveBeenCalled(); // expect(component.serviceFour.betSssEeeMee).toHaveBeenCalled(); // expect(component.serviceFour.resolveMyUrl).toHaveBeenCalled(); // expect(window.open).toHaveBeenCalled(); }); it('should run #setFuz()', async () => { component.iFrameBill = component.iFrameBill || {}; component.iFrameBill.first = { nativeElement: {} }; component.iFrameBill.contentDocument = { body: { scrollHeight: {} } }; component.iFrameBill.style = { height: {} }; component.setFuz({}); }); it('should run #schFooClicked()', async () => { component.schFooClicked({}); }); it('should run #barSelected()', async () => { component.service64 = component.service64 || {}; component.service64.checkFoo = jest.fn().mockReturnValue(observableOf({ x: {} })); component.details = component.details || {}; component.details.x = 'x'; component.serviceThree = component.serviceThree || {}; component.serviceThree.open = jest.fn(); component.checkTyEl = jest.fn(); component.openFoo = jest.fn(); component.barSelected({}); // expect(component.service64.checkFoo).toHaveBeenCalled(); // expect(component.serviceThree.open).toHaveBeenCalled(); // expect(component.checkTyEl).toHaveBeenCalled(); // expect(component.openFoo).toHaveBeenCalled(); }); it('should run #checkTyEl()', async () => { component.service64 = component.service64 || {}; component.service64.checkEeePppMe1 = jest.fn().mockReturnValue(observableOf({ x: {} })); component.details = component.details || {}; component.details.x = 'x'; component.showBar1 = jest.fn(); component.serviceThree = component.serviceThree || {}; component.serviceThree.open = jest.fn(); component.openFoo = jest.fn(); component.checkTyEl(); // expect(component.service64.checkEeePppMe1).toHaveBeenCalled(); // expect(component.showBar1).toHaveBeenCalled(); // expect(component.serviceThree.open).toHaveBeenCalled(); // expect(component.openFoo).toHaveBeenCalled(); }); it('should run #showBar1()', async () => { component.service64 = component.service64 || {}; component.service64.getFooLink = jest.fn().mockReturnValue(observableOf({ x: { fr: {}, en: {} } })); component.service8 = component.service8 || {}; component.service8.language = 'language'; component.serviceThree = component.serviceThree || {}; component.serviceThree.open = jest.fn().mockReturnValue({ foo$: observableOf({}) }); component.details = component.details || {}; component.details.x = 'x'; component.saveFuz = jest.fn(); component.openFoo = jest.fn(); component.showBar1(); // expect(component.service64.getFooLink).toHaveBeenCalled(); // expect(component.serviceThree.open).toHaveBeenCalled(); // expect(component.saveFuz).toHaveBeenCalled(); // expect(component.openFoo).toHaveBeenCalled(); }); it('should run #saveFuz()', async () => { component.serviceFive = component.serviceFive || {}; component.serviceFive.instant = jest.fn(); component.service64 = component.service64 || {}; component.service64.schedulePTP = jest.fn().mockReturnValue(observableOf({ status: {} })); component.serviceThree = component.serviceThree || {}; component.serviceThree.open = jest.fn(); component.openFoo = jest.fn(); component.saveFuz({}); // expect(component.serviceFive.instant).toHaveBeenCalled(); // expect(component.service64.schedulePTP).toHaveBeenCalled(); // expect(component.serviceThree.open).toHaveBeenCalled(); // expect(component.openFoo).toHaveBeenCalled(); }); it('should run #openFoo()', async () => { component.serviceFive = component.serviceFive || {}; component.serviceFive.instant = jest.fn(); component.serviceThree = component.serviceThree || {}; component.serviceThree.open = jest.fn(); component.openFoo({}); // expect(component.serviceFive.instant).toHaveBeenCalled(); // expect(component.serviceThree.open).toHaveBeenCalled(); }); it('should run #handleError()', async () => { component.handleError({ error: {} }); }); });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { MetricAlerts } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { MonitorClient } from "../monitorClient"; import { MetricAlertResource, MetricAlertsListBySubscriptionOptionalParams, MetricAlertsListByResourceGroupOptionalParams, MetricAlertsListBySubscriptionResponse, MetricAlertsListByResourceGroupResponse, MetricAlertsGetOptionalParams, MetricAlertsGetResponse, MetricAlertsCreateOrUpdateOptionalParams, MetricAlertsCreateOrUpdateResponse, MetricAlertResourcePatch, MetricAlertsUpdateOptionalParams, MetricAlertsUpdateResponse, MetricAlertsDeleteOptionalParams } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing MetricAlerts operations. */ export class MetricAlertsImpl implements MetricAlerts { private readonly client: MonitorClient; /** * Initialize a new instance of the class MetricAlerts class. * @param client Reference to the service client */ constructor(client: MonitorClient) { this.client = client; } /** * Retrieve alert rule definitions in a subscription. * @param options The options parameters. */ public listBySubscription( options?: MetricAlertsListBySubscriptionOptionalParams ): PagedAsyncIterableIterator<MetricAlertResource> { const iter = this.listBySubscriptionPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listBySubscriptionPagingPage(options); } }; } private async *listBySubscriptionPagingPage( options?: MetricAlertsListBySubscriptionOptionalParams ): AsyncIterableIterator<MetricAlertResource[]> { let result = await this._listBySubscription(options); yield result.value || []; } private async *listBySubscriptionPagingAll( options?: MetricAlertsListBySubscriptionOptionalParams ): AsyncIterableIterator<MetricAlertResource> { for await (const page of this.listBySubscriptionPagingPage(options)) { yield* page; } } /** * Retrieve alert rule definitions in a resource group. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: MetricAlertsListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<MetricAlertResource> { 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?: MetricAlertsListByResourceGroupOptionalParams ): AsyncIterableIterator<MetricAlertResource[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: MetricAlertsListByResourceGroupOptionalParams ): AsyncIterableIterator<MetricAlertResource> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Retrieve alert rule definitions in a subscription. * @param options The options parameters. */ private _listBySubscription( options?: MetricAlertsListBySubscriptionOptionalParams ): Promise<MetricAlertsListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec ); } /** * Retrieve alert rule definitions in a resource group. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: MetricAlertsListByResourceGroupOptionalParams ): Promise<MetricAlertsListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * Retrieve an alert rule definition. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param ruleName The name of the rule. * @param options The options parameters. */ get( resourceGroupName: string, ruleName: string, options?: MetricAlertsGetOptionalParams ): Promise<MetricAlertsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, ruleName, options }, getOperationSpec ); } /** * Create or update an metric alert definition. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param ruleName The name of the rule. * @param parameters The parameters of the rule to create or update. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, ruleName: string, parameters: MetricAlertResource, options?: MetricAlertsCreateOrUpdateOptionalParams ): Promise<MetricAlertsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, ruleName, parameters, options }, createOrUpdateOperationSpec ); } /** * Update an metric alert definition. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param ruleName The name of the rule. * @param parameters The parameters of the rule to update. * @param options The options parameters. */ update( resourceGroupName: string, ruleName: string, parameters: MetricAlertResourcePatch, options?: MetricAlertsUpdateOptionalParams ): Promise<MetricAlertsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, ruleName, parameters, options }, updateOperationSpec ); } /** * Delete an alert rule definition. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param ruleName The name of the rule. * @param options The options parameters. */ delete( resourceGroupName: string, ruleName: string, options?: MetricAlertsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, ruleName, options }, deleteOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listBySubscriptionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/metricAlerts", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.MetricAlertResourceCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion6], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.MetricAlertResourceCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion6], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.MetricAlertResource }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion6], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.ruleName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.MetricAlertResource }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters4, queryParameters: [Parameters.apiVersion6], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.ruleName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.MetricAlertResource }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters5, queryParameters: [Parameters.apiVersion6], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.ruleName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion6], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.ruleName ], headerParameters: [Parameters.accept], serializer };
the_stack
import { ES6Achieve } from "../../utility/algorithm/es6-achieve"; // ? ES6Achieve describe('ES6Achieve tests', () => { // ? _reflect describe('ES6Achieve._reflect tests', () => { const _reflect = ES6Achieve._reflect; test('_reflect.get should return the value of the special key from target object', () => { const obj = { name: 'ddzy', age: 21, }; const received = [ 'name', 0, 'skill', ]; const expected = [ 'ddzy', undefined, undefined, ]; for (const [i, v] of received.entries()) { const temp = _reflect.get(obj, v); expect(temp).toBe(expected[i]); } }); test('_reflect.set should set the new value to the designative key', () => { const obj = { name: 'ddzy', age: 21, }; const received = [ { key: 'skill', value: 'program', }, { key: 'hobby', value: ['run', 'play-game'], }, ]; const expected = [ true, true, ]; for (const [i, v] of received.entries()) { const temp = _reflect.set(obj, v.key, v.value); expect(temp).toBe(expected[i]); } expect(obj['skill' as keyof typeof obj]).toBe('program'); expect(Array.isArray(obj['hobby' as keyof typeof obj])).toBeTruthy(); }); test('_reflect.has should return `true` when the designative key was in target object, otherwise `false`', () => { const obj = { name: 'ddzy', age: 21, }; const received = [ 'name', 'age', 'skill', 'hobby', ]; const expected = [ true, true, false, false, ]; for (const [i, v] of received.entries()) { const temp = _reflect.has(obj, v); expect(temp).toBe(expected[i]); } }); test('_reflect.apply should be called same as native API named `apply`', () => { const obj = { name: 'ddzy', age: 21, }; function func1() { return 'Hello world'; } function func2(...args: any[]) { return args[0]; } function func3() { return this; } const received = [ func1, func2, func3, ]; const expected = [ 'Hello world', 'Hello ddzy', obj, ]; for (const [i, v] of received.entries()) { const temp = _reflect.apply(v, obj, ['Hello ddzy']); expect(temp).toBe(expected[i]); } }); test('_reflect.construct should return the `instance` of the designative function', () => { function Person1() { } const Person2 = () => { }; const received = [ Person1, Person2, ]; const expected = [ true, true, ]; for (const [i, v] of received.entries()) { const temp = _reflect.construct(v, []); expect(temp instanceof v).toBe(expected[i]); } }); test('_reflect.deleteProperty should remove the designative `key` from target object', () => { const obj = { name: 'ddzy', age: 21, }; const received = [ 'name', 'skill', ]; const expected = [ true, true, ]; for (const [i, v] of received.entries()) { const temp = _reflect.deleteProperty(obj, v); expect(temp).toBe(expected[i]); expect(v in obj).toBeFalsy(); } const temp = _reflect.deleteProperty(function () { }, 'name'); expect(temp).toBeTruthy(); }); test('_reflect.getPrototypeOf should return the `__proto__` of the designative instance', () => { const obj = {}; function Person1() { } const person = _reflect.construct(Person1, []); const str = ''; const arr: any[] = []; const num = 0; const received = [ obj, person, str, arr, num, ]; const expected = [ obj.__proto__, person.__proto__, str.__proto__, arr.__proto__, num.__proto__, ]; for (const [i, v] of received.entries()) { const temp = _reflect.getPrototypeOf(v); expect(temp).toBe(expected[i]); } }); test('_reflect.setPrototypeOf should set the new prototype to the designative instance', () => { function Person1() { } Person1.prototype = { constructor: Person1, say() { }, }; const p1 = new Person1(); const p2 = { run() { }, }; const received = [ null, p2, ]; const expected = [ true, true, ]; for (const [i, v] of received.entries()) { const temp = _reflect.setPrototypeOf(p1, v); expect(temp).toBe(expected[i]); } }); }); // ? _map describe('ES6Achieve._map tests', () => { const _map = ES6Achieve._map; test('_map should handle each of value which were in `source array` with `callback`', () => { const received = [ [1, 2, 3, 4, 5, 6], [24, 42, 4, 1, 2, 9, 58], ]; const expected = [ [2, 4, 6, 8, 10, 12], [48, 84, 8, 2, 4, 18, 116], ]; for (const [outerI, outerV] of received.entries()) { const result = _map<number, number>( outerV, (outerVV) => { return outerVV * 2; }, ); for (const [innerI, innerV] of result.entries()) { expect(innerV).toBe(expected[outerI][innerI]); } } }); test('_map should handle `callback` with customized `this` context', () => { interface IContext { name: string, age: number, }; const context: IContext = { name: 'ddzy', age: 21, }; const received = [ ['', 'd', 'dd', 'ddz', 'ddzy'], ]; const expected = [ [' 980808', 'd 980808', 'dd 980808', 'ddz 980808', 'ddzy 980808'], ]; for (const [outerI, outerV] of received.entries()) { const result = _map<string, string, IContext>( outerV, (outerVV, _outerII, __this__) => { // ? test `this` context expect(__this__).toBe(context); return outerVV + ' 980808'; }, context, ); for (const [innerI, innerV] of result.entries()) { expect(innerV).toBe(expected[outerI][innerI]); } } }); test('_map should return a `new` array and cannot modify the `origin` array', () => { interface IContext { uuid: number, age: number, }; const received = [ [ { uuid: 1, age: 10 }, { uuid: 2, age: 20 }, { uuid: 3, age: 30 }, ], ]; const expected = [ [ { uuid: 1, age: 110 }, { uuid: 2, age: 120 }, { uuid: 3, age: 130 }, ], ]; for (const [outerI, outerV] of received.entries()) { const result = _map<IContext, IContext>( outerV, (outerVV) => { return { uuid: outerVV.uuid, age: outerVV.age + 100, }; }, ); for (const [innerI, innerV] of result.entries()) { expect(innerV.uuid).toBe(expected[outerI][innerI].uuid); expect(innerV.age).toBe(expected[outerI][innerI].age); } // ? result.push({ uuid: 4, age: 140, }); expect(outerV.length).toBe(3); expect(result.length).toBe(4); } }); }); // ? _reduce describe('ES6Achieve._reduce tests', () => { const _reduce = ES6Achieve._reduce; test('_reduce should return `undefined` when received an empty array', () => { const received: any[] = []; const result = _reduce(received, (total, current) => { return total + current; }); expect(result).toBeUndefined(); }); test('_reduce should return `number` when received an array being composed of `number`', () => { const received = [1, 2, 3, 4, 5]; const expected = 15; const result = _reduce<number, number>(received, (total, current) => { return total + current; }); expect(result).toBe(expected); }); test('_reduce should return `number` when received an array being composed of `number` and an `initialValue`', () => { const received = [1, 2, 3, 4, 5]; const expected = 25; const result = _reduce<number, number>(received, (total, current) => { return total + current; }, 10); expect(result).toBe(expected); }); test('_reduce should return `number` when received an array being composed of `object`', () => { const received = [ { uuid: 1, name: 'duan', age: 10 }, { uuid: 2, name: 'duan', age: 20 }, { uuid: 3, name: 'duan', age: 30 }, ]; const expected = 60; const result = _reduce<typeof received[0], number>(received, (total, current) => { return total + current.age; }, 0); expect(result).toBe(expected); }); test('_reduce should return `string` when received an array being composed of `number`', () => { const received = [1, 2, 3, 4, 5]; const expected = '12345'; const result = _reduce<number, string>(received, (total, current) => { return total + current; }, ''); expect(result).toBe(expected); }); }); // ? _filter describe('ES6Achieve._filter tests', () => { const _filter = ES6Achieve._filter; test('_filter should return a new empty array when receive an empty array', () => { const received: number[] = []; const result = _filter<number>(received, (v) => { return !!v; }); expect(result.length).toBe(0); received.push(2); received.push(3); expect(received.length).toBe(2); expect(result.length).toBe(0); }); test('_filter should return the eligible array when receive an array composed of number', () => { const received: number[] = [1, 2, 3, 4, 5, 6, 7, 8]; const expected: number[] = [2, 4, 6, 8]; const result = _filter<number>(received, (v) => { return v % 2 === 0; }); for (const [i, v] of result.entries()) { expect(v).toBe(expected[i]); } }); test('_filter should return the eligible array when receive an array composed of plain object', () => { interface User { name: string, age: number, }; const received: User[] = [ { name: 'duan', age: 20 }, { name: 'zhao', age: 30 }, { name: 'yang', age: 40 }, ]; const expected: User[] = [ { name: 'zhao', age: 30 }, { name: 'yang', age: 40 }, ]; const result = _filter<User>(received, (v) => { return v.age >= 30; }); for (const [i, v] of result.entries()) { expect(v.name).toBe(expected[i].name); expect(v.age).toBe(expected[i].age); } }); test('_filter should return the aligible array and print the truthy context when receive an array composed of number', () => { interface Obj { secret: string, say: (secret: string) => void, }; const obj: Obj = { secret: '980808', say() { console.log(this.secret); }, }; const received = [-1, 1, -2, 2, -3, 3]; const expected = { context: obj, arr: [1, 2, 3], }; const result = _filter<number, Obj>(received, function (v) { expect(this).toBe(expected.context); return v > 0; }, obj); for (const [i, v] of result.entries()) { expect(v).toBe(expected.arr[i]); } }); }); // ? _every describe('ES6Achieve._every tests', () => { const _every = ES6Achieve._every; test('_every should always return `true` when receive an empty array', () => { const received: number[] = []; const expected = true; const result = _every<number>(received, (v) => { return v > 0; }); expect(result).toBe(expected); }); test('_every should return `true` when receive an array composed of `number` that accord with condition', () => { const received: number[] = [1, 2, 3, 4, 5]; const expected = true; const result = _every<number, null>(received, (v) => { return v < 10; }); expect(result).toBe(expected); }); test('_every should return `false` when receive an array composed of `object` that not accord with condition', () => { interface IPair { name: string; age: number; }; const received: IPair[] = [ { name: 'duan', age: 21 }, { name: 'zhao', age: 31 }, { name: 'yang', age: 41 }, ]; const expected = false; const result = _every<IPair, null>(received, (v) => { return v.age < 0; }); expect(result).toBe(expected); }); test('_every should called by custom `this` context', () => { const context = { name: 'ddzy', printName() { return this.name; }, }; const received: number[] = [1, 2, 3, 4, 5]; const expected = { context, result: true, }; const result = _every<number, typeof context>(received, function (v) { expect(this).toBe(expected.context); return v < 6; }, context); expect(result).toBe(expected.result); }); }); // ? _find describe('ES6Achieve._find tests', () => { const _find = ES6Achieve._find; test('_every should always return `undefined` when receive an empty array', () => { const received: number[] = []; const expected = undefined; const result = _find<number>(received, (v) => { return v > 0; }); expect(result).toBe(expected); }); test('_every should return first value that has been found when receive an array composed of `number`', () => { const received: number[] = [-1, -2, 1, 2, 3]; const expected = 1; const result = _find<number, null>(received, (v) => { return v > 0; }); expect(result).toBe(expected); }); test('_every should return the first that has been found when receive an array composed of `object`', () => { interface IPair { name: string; age: number; }; const received: IPair[] = [ { name: 'duan', age: 21 }, { name: 'zhao', age: 31 }, { name: 'yang', age: 41 }, ]; const expected = received[1]; const result = _find<IPair, null>(received, (v) => { return v.age >= 31; }); expect(result).toBe(expected); }); test('_every should called by custom `this` context', () => { const context = { secret: 'duanzhaoyang', printSecret() { return this.secret; }, }; const received: number[] = [1, 2, 3, 4, 5]; const expected = { context, result: 5, }; const result = _find<number, typeof context>(received, function (v) { expect(this).toBe(expected.context); return v === 5; }, context); expect(result).toBe(expected.result); }); }); // ? _startsWith describe('ES6Achieve._startsWith tests', () => { const _startsWith = ES6Achieve._startsWith; test('_startsWith should return whether the `origin` string is composed of `target`', () => { const origin = 'ddzy'; const received = ['d', 'yang', 'ddzyy']; const expected = [true, false, false]; for (const [i, v] of received.entries()) { const result = _startsWith(origin, v); expect(result).toBe(expected[i]); } }); test('_startsWith should return whether the `origin` string is composed of `target` at special `index`', () => { const origin = 'ddzy'; const received = ['ddz', 'dzy']; const expected = [false, false]; for (const [i, v] of received.entries()) { const result = _startsWith(origin, v, 1); expect(result).toBe(expected[i]); } }); }); // ? _some describe('ES6Achieve._some tests', () => { const _some = ES6Achieve._some; test('_some should always return `false` when receive an empty array', () => { const received: number[] = []; const expected = false; const result = _some<number>(received, (v) => { return v > 0; }); expect(result).toBe(expected); }); test('_some should return `true` when receive an array composed of `number` that at least one accord with condition', () => { const received: number[] = [1, 2, 3, 4, 5]; const expected = true; const result = _some<number, null>(received, (v) => { return v < 10; }); expect(result).toBe(expected); }); test('_some should return `false` when receive an array composed of `object` that nobody accord with condition', () => { interface IPair { name: string; age: number; }; const received: IPair[] = [ { name: 'duan', age: 21 }, { name: 'zhao', age: 31 }, { name: 'yang', age: 41 }, ]; const expected = false; const result = _some<IPair, null>(received, (v) => { return v.age < 0; }); expect(result).toBe(expected); }); test('_some should called by custom `this` context', () => { const context = { name: 'ddzy', printName() { return this.name; }, }; const received: number[] = [1, 2, 3, 4, 5]; const expected = { context, result: true, }; const result = _some<number, typeof context>(received, function (v) { expect(this).toBe(expected.context); return v < 6; }, context); expect(result).toBe(expected.result); }); }); // ? _includes describe('ES6Achieve._includes tests', () => { const _includes = ES6Achieve._includes; test('_includes should always return `false` when receive an empty array', () => { const received: number[] = []; const expected = false; const result = _includes<number>(received, 2); expect(result).toBe(expected); }); test('_includes should return `false` when receive an array composed of `number` that no one accord with condition', () => { const received: number[] = [1, 2, 3, 4, 5]; const expected = false; const result = _includes<number>(received, 6); expect(result).toBe(expected); }); test('_includes should return `true` when receive an array composed of `number` that at least one accord with condition', () => { const received: number[] = [1, 2, 3, 4, 5]; const expected = true; const result = _includes<number>(received, 3); expect(result).toBe(expected); }); test('_includes should return `false` when receive an array composed of `object` that nobody accord with condition', () => { interface IPair { name: string; age: number; }; const received: IPair[] = [ { name: 'duan', age: 21 }, { name: 'zhao', age: 31 }, { name: 'yang', age: 41 }, ]; const expected = false; const result = _includes<IPair>(received, { name: 'duan', age: 21, }); expect(result).toBe(expected); }); test('_includes should return `true` when receive `NaN` and also in origin array', () => { const received: number[] = [1, 2, NaN, 4, 5]; const expected = true; const result = _includes<number>(received, NaN); expect(result).toBe(expected); }); }); // ? _findIndex describe('ES6Achieve._findIndex tests', () => { const _findIndex = ES6Achieve._findIndex; test('_findIndex should always return `-1` when receive an empty array', () => { const received: number[] = []; const expected = -1; const result = _findIndex<number>(received, (v) => { return v > 0; }); expect(result).toBe(expected); }); test('_findIndex should return `-1` when not found', () => { const received: number[] = [23, 4, 56, 73, 1]; const expected = -1; const result = _findIndex<number>(received, (v) => { return v < 0; }); expect(result).toBe(expected); }); test('_findIndex should return the place of the first value which was eligible', () => { const received: number[] = [444, 45, -4, 78, -5]; const expected = 2; const result = _findIndex<number>(received, (v) => { return v < 0; }); expect(result).toBe(expected); }); test('_findIndex should be called by custom `context`', () => { const context = { secret: 'ddzy', }; const received: number[] = [45, 2, 1, 33, -5]; const expected = { place: 0, context, }; const result = _findIndex<number, typeof context>(received, function (v) { expect(this).toBe(expected.context); return v > 40; }, context); expect(result).toBe(expected.place); }); }); // ? Dictionary describe('ES6Achieve.Dictionary tests', () => { const map = new ES6Achieve.Dictionary(); test('Dictionary should work friendly', () => { const str1 = 'duanzhaoyang'; const num1 = 19980808; const bool1 = true; const arr1 = [1, 2, 3]; const obj1 = { skill: 'program' }; const func1 = function () { }; const obj2 = { name: 'duan', age: 21 }; // map.set() map.set(str1, str1); map.set(num1, num1); map.set(bool1, bool1); map.set(arr1, arr1); map.set(obj1, obj1); map.set(func1, func1); expect(map.size()).toBe(6); // map.set() -> for twice map.set(bool1, false); map.set(obj1, obj2); expect(map.size()).toBe(6); // map.set() => for three times map.set([], []); expect(map.size()).toBe(7); // map.get() expect(map.get(arr1)).toBe(arr1); expect(map.get(obj1)).toBe(obj2); expect(map.size()).toBe(7); // map.delete() expect(map.delete(bool1)).toBeTruthy(); expect(map.size()).toBe(6); // map.traversal() map.traversal(function (value, key) { expect(this).toBe(map); if (key === bool1) { return false; } }); }); }); // ? _Promise describe('ES6Achieve._Promise tests', () => { const _Promise = ES6Achieve._Promise; test('_Promise should work fine', () => { const result1 = new _Promise((resolve) => { setTimeout(() => { resolve(1); }, 0); }); result1.then((value) => { expect(value).toBe(1); return value + 1; }).then((value) => { expect(value).toBe(2); }); const result2 = new _Promise((resolve) => { resolve(100); }); result2.then((value) => { expect(value).toBe(100); return value / 5; }).then((value) => { expect(value).toBe(20); }); }); }); });
the_stack
import { AutoIncrement, BackReference, BinaryBigInt, cast, copyAndSetParent, createReference, Embedded, hasCircularReference, hasEmbedded, integer, MapName, MongoId, PrimaryKey, ReceiveType, Reference, ReflectionClass, ReflectionKind, resolveReceiveType, SignedBinaryBigInt, Type, typeOf, TypePropertySignature, UUID } from '@deepkit/type'; import { expect, test } from '@jest/globals'; import { deserializeBSON } from '../src/bson-deserializer'; import { deserializeBSONWithoutOptimiser } from '../src/bson-parser'; import { serializeBSON, serializeWithoutOptimiser } from '../src/bson-serializer'; (BigInt.prototype as any).toJSON = function () { return this.toString(); }; Error.stackTraceLimit = 150; /** * @reflection never */ function needsWrapper(type: Type): boolean { return hasEmbedded(type) || (type.kind == ReflectionKind.class && type.types.length === 0) || (type.kind !== ReflectionKind.class && type.kind !== ReflectionKind.objectLiteral); } /** * @reflection never */ export function roundTrip<T>(value: T | any, type?: ReceiveType<T>): T { type = resolveReceiveType(type); if (needsWrapper(type)) { const t: Type = copyAndSetParent({ kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'v', type: { kind: ReflectionKind.never } }] }); //important to not give `type` a parent, so the code acts as if it was not in `v` (t.types[0] as TypePropertySignature).type = type; const bson = serializeBSON({ v: value }, undefined, t); const res = (deserializeBSON<T>(bson, 0, undefined, t) as any).v; return res; } else { const bson = serializeBSON(value, undefined, type); const res = deserializeBSON<T>(bson, 0, undefined, type); return res; } } /** * @reflection never */ export function serializeToJson<T>(value: T | any, type?: ReceiveType<T>): T { type = resolveReceiveType(type); if (needsWrapper(type)) { const t: Type = copyAndSetParent({ kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'v', type: { kind: ReflectionKind.never } }] }); //important to not give `type` a parent, so the code acts as if it was not in `v` (t.types[0] as TypePropertySignature).type = type; const bson = serializeBSON({ v: value }, undefined, t); return deserializeBSONWithoutOptimiser(bson).v as any; } else { const bson = serializeBSON(value, undefined, type); return deserializeBSONWithoutOptimiser(bson) as any; } } /** * @reflection never */ export function deserializeFromJson<T>(value: any, type?: ReceiveType<T>): T { type = resolveReceiveType(type); if (needsWrapper(type)) { const t: Type = copyAndSetParent({ kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'v', type: { kind: ReflectionKind.never } }] }); //important to not give `type` a parent, so the code acts as if it was not in `v` (t.types[0] as TypePropertySignature).type = type; const bson = serializeWithoutOptimiser({ v: value }); const res = (deserializeBSON<T>(bson, 0, undefined, t) as any).v; return res; } else { const bson = serializeWithoutOptimiser(value); const res = deserializeBSON<T>(bson, 0, undefined, type); return res; } } enum MyEnum { a, b, c } class Config { color: string = '#fff'; big: boolean = false; } class Model { id: number = 0; title: string = ''; config?: Config; } test('basics with value', () => { expect(serializeToJson<string>('asd')).toBe('asd'); expect(deserializeFromJson<string>('asd')).toBe('asd'); expect(roundTrip<string>('asd')).toBe('asd'); expect(roundTrip<number>(22)).toBe(22); expect(roundTrip<boolean>(false)).toBe(false); expect(roundTrip<Date>(new Date)).toBeInstanceOf(Date); }); test('model', () => { { const item = new Model; item.id = 23; item.title = '2322'; const back = roundTrip<Model>(item); expect(back).toEqual({ id: 23, title: '2322' }); expect(back).toBeInstanceOf(Model); } }); test('with implicit default value', () => { const defaultDate = new Date; class Product { id: number = 0; created: Date = defaultDate; } //having a default value doesn't mean we are optional; expect(ReflectionClass.from(Product).getProperty('created')!.isOptional()).toBe(false); expect(roundTrip<Product>({ id: 23 } as any)).toEqual({ id: 23, created: defaultDate }); expect(deserializeFromJson<Product>({ id: 23, created: undefined } as any)).toEqual({ id: 23, created: defaultDate }); expect(deserializeFromJson<Product>({ id: 23, created: null } as any)).toEqual({ id: 23, created: defaultDate }); expect(roundTrip<Product>({ id: 23, created: undefined } as any)).toEqual({ id: 23, created: defaultDate }); expect(roundTrip<Partial<Product>>({ id: 23 } as any)).toEqual({ id: 23 }); expect(roundTrip<Partial<Product>>({ id: 23, created: undefined } as any)).toEqual({ id: 23 }); //not set properties are omitted expect('created' in roundTrip<Partial<Product>>({ id: 23 } as any)).toEqual(false); //we need to keep undefined values otherwise there is no way to reset a value //for JSON/BSON on the transport layer is null used to communicate the fact that we set explicitly `created` to undefined expect(deserializeFromJson<Partial<Product>>({ id: 23, created: null } as any)).toEqual({ id: 23, created: undefined }); expect('created' in serializeToJson<Partial<Product>>({ id: 23, created: undefined } as any)).toEqual(true); expect('created' in roundTrip<Partial<Product>>({ id: 23, created: undefined } as any)).toEqual(true); }); test('partial keeps explicitely undefined fields', () => { expect(roundTrip<Partial<Model>>({})).toEqual({}); expect('name' in roundTrip<Partial<Model>>({})).toBe(false); expect(roundTrip<Partial<Model>>({ title: undefined })).toEqual({ title: undefined }); { const item = serializeToJson<Partial<Model>>({ title: undefined }); } { const item = roundTrip<Partial<Model>>({ title: undefined }); expect('title' in item).toBe(true); //all fields in partial become optional } { const item = roundTrip<Partial<Model>>({}); expect('title' in item).toBe(false); } class Purchase { id: number & PrimaryKey & AutoIncrement = 0; sentAt?: Date; canceledAt?: Date; } expect(roundTrip<Partial<Purchase>>({ sentAt: undefined })).toEqual({ sentAt: undefined }); expect('sentAt' in roundTrip<Partial<Purchase>>({ sentAt: undefined })).toEqual(true); }); test('record removes undefined when not allowed', () => { expect(roundTrip<Record<string, string>>({})).toEqual({}); expect(roundTrip<Record<string, string>>({ foo: 'bar' })).toEqual({ foo: 'bar' }); expect(deserializeFromJson<Record<string, string>>({ foo: undefined } as any)).toEqual({}); expect(serializeToJson<Record<string, string>>({ foo: undefined } as any)).toEqual({}); expect(roundTrip<Record<string, string>>({ foo: undefined } as any)).toEqual({}); expect('foo' in roundTrip<Record<string, string>>({ foo: undefined } as any)).toEqual(false); }); test('record allows undefined when allowed', () => { expect(serializeToJson<Record<string, string | undefined>>({})).toEqual({}); expect(serializeToJson<Record<string, string | undefined>>({ foo: 'bar' })).toEqual({ foo: 'bar' }); expect(serializeToJson<Record<string, string | undefined>>({ foo: undefined } as any)).toEqual({ foo: null }); expect(deserializeFromJson<Record<string, string | undefined>>({ foo: null } as any)).toEqual({ foo: undefined }); expect('foo' in deserializeFromJson<Record<string, string | undefined>>({ foo: null } as any)).toEqual(true); expect(roundTrip<Record<string, string | undefined>>({})).toEqual({}); expect(roundTrip<Record<string, string | undefined>>({ foo: 'bar' })).toEqual({ foo: 'bar' }); expect(roundTrip<Record<string, string | undefined>>({ foo: undefined } as any)).toEqual({ foo: undefined }); expect('foo' in roundTrip<Record<string, string | undefined>>({ foo: undefined } as any)).toEqual(true); }); test('bigint', () => { expect(roundTrip<bigint>(0n)).toEqual(0n); expect(roundTrip<bigint>(5n)).toEqual(5n); expect(roundTrip<bigint>(12n)).toEqual(12n); expect(roundTrip<bigint>(9223372036854775807n)).toEqual(9223372036854775807n); expect(roundTrip<BinaryBigInt>(12012020202020202020202020202020202020n)).toEqual(12012020202020202020202020202020202020n); expect(roundTrip<BinaryBigInt>(16n ** 16n ** 2n)).toEqual(16n ** 16n ** 2n); expect(roundTrip<BinaryBigInt>(16n ** 16n ** 3n)).toEqual(16n ** 16n ** 3n); expect(roundTrip<SignedBinaryBigInt>(12012020202020202020202020202020202020n)).toEqual(12012020202020202020202020202020202020n); expect(roundTrip<SignedBinaryBigInt>(-12012020202020202020202020202020202020n)).toEqual(-12012020202020202020202020202020202020n); expect(roundTrip<SignedBinaryBigInt>(16n ** 16n ** 2n)).toEqual(16n ** 16n ** 2n); expect(roundTrip<SignedBinaryBigInt>(16n ** 16n ** 3n)).toEqual(16n ** 16n ** 3n); }); test('union basics', () => { expect(roundTrip<string | number>('asd')).toEqual('asd'); expect(roundTrip<string | number>(23)).toEqual(23); expect(roundTrip<boolean | number>(true)).toEqual(true); expect(roundTrip<boolean | number>(23)).toEqual(23); expect(roundTrip<bigint | number>(23)).toEqual(23n); expect(roundTrip<bigint | number>(23n)).toEqual(23n); expect(roundTrip<string | Model>(new Model)).toBeInstanceOf(Model); { const item = new Model; item.id = 23; item.title = '23'; const back = roundTrip<string | Model>(item); expect(back).toEqual({ id: 23, title: '23' }); } { const item = new Model; item.id = 23; item.title = '23'; const back = roundTrip<Model>(item); expect(back).toEqual({ id: 23, title: '23' }); } expect(roundTrip<string | Model>('asd')).toEqual('asd'); expect(roundTrip<string | Model | undefined>(undefined)).toEqual(undefined); expect(serializeToJson<string | Model | undefined>(null)).toEqual(null); expect(deserializeFromJson<string | Model | undefined>(null)).toEqual(undefined); expect(roundTrip<string | Model | undefined>(null)).toEqual(undefined); expect(roundTrip<string | Model | null>(undefined)).toEqual(null); expect(roundTrip<string | Model | null>(null)).toEqual(null); }); test('union 2', () => { interface s { type: 'm'; name: string; } expect(deserializeFromJson<undefined | s>({ type: 'm', name: 'Peter' })).toEqual({ type: 'm', name: 'Peter' }); expect(serializeToJson<undefined | s>({ type: 'm', name: 'Peter' })).toEqual({ type: 'm', name: 'Peter' }); expect(roundTrip<undefined | s>({ type: 'm', name: 'Peter' })).toEqual({ type: 'm', name: 'Peter' }); }); test('union 3', () => { expect(deserializeFromJson<string | Model>('asd')).toBe('asd'); expect(deserializeFromJson<string | Model>({ title: 'foo' } as any)).toEqual({ id: 0, title: 'foo' }); expect(deserializeFromJson<string | Model | undefined>(undefined)).toBe(undefined); expect(deserializeFromJson<string | Model | null>(null)).toBe(null); expect(serializeToJson<string | Model>('asd')).toBe('asd'); expect(serializeToJson<string | Model>({ id: 0, title: 'foo' } as any)).toEqual({ id: 0, title: 'foo' }); expect(serializeToJson<string | Model | undefined>(undefined)).toBe(null); expect(serializeToJson<string | Model | null>(null)).toBe(null); expect(roundTrip<string | Model>('asd')).toBe('asd'); expect(roundTrip<string | Model>({ id: 0, title: 'foo' } as any)).toBeInstanceOf(Model); }); test('model 1', () => { class Model { //filter is not used yet filter?: Record<string, string | number | boolean | RegExp>; skip?: number; itemsPerPage: number = 50; limit?: number; parameters: { [name: string]: string } = {}; sort?: Record<any, any>; } { const model = { filter: { $regex: /Peter/ }, itemsPerPage: 50, parameters: {} }; expect(roundTrip<Model>(model as any)).toEqual(model); } { const o = { parameters: { teamName: 'Team a' } }; expect(serializeToJson<Model>(o)).toEqual(o); } { const model = { itemsPerPage: 50, parameters: { teamName: 'Team a' }, filter: undefined, skip: undefined, limit: undefined, sort: undefined }; expect(roundTrip<Model>(model as any)).toEqual(model); } }); class Team { id: number & PrimaryKey & AutoIncrement = 0; version: number = 0; lead?: User & Reference; constructor(public name: string) { } } class User { id: number & PrimaryKey & AutoIncrement = 0; version: number = 0; teams: Team[] & BackReference<{ via: typeof UserTeam }> = []; constructor(public name: string) { } } class UserTeam { id: number & PrimaryKey & AutoIncrement = 0; version: number = 0; constructor( public team: Team & Reference, public user: User & Reference, ) { } } test('relation 1', () => { { const user = new User('foo'); expect(roundTrip<User>(user)).toEqual(user); } { const team = new Team('foo'); expect(roundTrip<Team>(team)).toEqual(team); } { const team = new Team('foo'); const user = new User('foo'); user.id = 12; team.lead = user; expect(serializeToJson<Team>(team)).toEqual(team); expect(deserializeFromJson<Team>(team)).toEqual(team); expect(roundTrip<Team>(team)).toEqual(team); } { const team = new Team('foo'); team.id = 1; team.version = 2; team.lead = createReference(User, { id: 12 }); const json = { id: 1, version: 2, name: 'foo', lead: 12 as any }; expect(serializeToJson<Team>(team)).toEqual(json); const back = deserializeFromJson<Team>(json); expect(back).toEqual(team); expect(back.lead).toBeInstanceOf(User); expect(back.lead!.id).toBe(12); expect(roundTrip<Team>(team)).toEqual(team); } }); test('relation 2', () => { // { // const user = new User('foo'); // user.teams = unpopulatedSymbol as any; //emulates an unpopulated relation // const user2 = cloneClass(user); // user2.teams = []; // expect(roundTrip<User>(user)).toEqual(user2); // } { const user = new User('foo'); user.teams.push(new Team('bar')); expect(serializeToJson<User>(user)).toEqual(user); expect(roundTrip<User>(user)).toEqual(user); } { const items: User[] = [ cast<User>({ name: 'Peter 1', id: 1, version: 0, }), cast<User>({ name: 'Peter 2', id: 2, version: 0, }), cast<User>({ name: 'Marc 1', id: 3, version: 0, }) ]; expect(roundTrip<User[]>(items)).toEqual(items); } }); // test('invalid', () => { // expect(roundTrip<UUID>(new Model as any)).toEqual(RoundTripExcluded); // }); test('regex', () => { expect(roundTrip<RegExp>(/foo/)).toEqual(/foo/); }); test('explicitly set undefined on optional triggers default value', () => { class Product { id: number = 0; created?: Date = new Date; } //no value means the default triggers expect(roundTrip<Product>({ id: 23 }).created).toBeInstanceOf(Date); //this is important for database patches expect(roundTrip<Product>({ id: 23, created: undefined }).created).toBe(undefined); expect('created' in roundTrip<Product>({ id: 23, created: undefined })).toBe(true); }); test('partial explicitly set undefined on optional is handled', () => { class Product { id: number = 0; created?: Date = new Date; } //no value means the default triggers expect(roundTrip<Partial<Product>>({ id: 23 }).created).toBe(undefined); //this is important for database patches expect(roundTrip<Partial<Product>>({ id: 23, created: undefined }).created).toBe(undefined); expect('created' in roundTrip<Partial<Product>>({ id: 23, created: undefined })).toBe(true); }); test('partial explicitly set undefined on required is not ignored', () => { class Product { id: number = 0; created: Date = new Date; } //no value means the default triggers expect(roundTrip<Partial<Product>>({ id: 23 }).created).toBe(undefined); //this is important for database patches //important to keep undefined, as t.partial() makes all properties optional, no matter what it originally was, otherwise it would be a partial expect(roundTrip<Partial<Product>>({ id: 23, created: undefined }).created).toBe(undefined); expect('created' in roundTrip<Partial<Product>>({ id: 23, created: undefined } as any)).toBe(true); }); test('explicitely set undefined on required is ignored', () => { class Product { id: number = 0; created: Date = new Date; } expect(roundTrip<Product>({ id: 23 } as any).created).toBeInstanceOf(Date); expect(roundTrip<Product>({ id: 23, created: undefined } as any).created).toBeInstanceOf(Date); }); test('partial does not return the model on root', () => { expect(roundTrip<Partial<Model>>({ id: 23 } as any)).toEqual({ id: 23 }); expect(roundTrip<Partial<Model>>({ id: 23 } as any)).not.toBeInstanceOf(Model); }); test('partial returns the model at second level', () => { const config = new Config; config.color = 'red'; expect(roundTrip<Partial<Model>>({ id: 23, config: config } as any)).toEqual({ id: 23, config: { big: false, color: 'red' } }); expect(roundTrip<Partial<Model>>({ id: 23, config: config } as any).config).toBeInstanceOf(Config); }); test('partial allowed undefined', () => { class Product { id: number = 0; created?: Date; } expect(roundTrip<Partial<Product>>({ id: 23, created: undefined } as any)).not.toBeInstanceOf(Product); expect(roundTrip<Partial<Product>>({ id: 23 } as any).created).toBe(undefined); expect('created' in roundTrip<Partial<Product>>({ id: 23 } as any)).toBe(false); //important for database patches expect(roundTrip<Partial<Product>>({ id: 23, created: undefined } as any).created).toBe(undefined); expect('created' in roundTrip<Partial<Product>>({ id: 23, created: undefined } as any)).toBe(true); }); test('optional basics', () => { expect(roundTrip<string | undefined>(undefined)).toBe(undefined); expect(roundTrip<string | undefined>(null)).toBe(undefined); expect(roundTrip<number | undefined>(undefined)).toBe(undefined); expect(roundTrip<number | undefined>(null)).toBe(undefined); expect(roundTrip<boolean | undefined>(undefined)).toBe(undefined); expect(roundTrip<boolean | undefined>(null)).toBe(undefined); expect(roundTrip<UUID | undefined>(undefined)).toBe(undefined); expect(roundTrip<UUID | undefined>(null)).toBe(undefined); expect(roundTrip<MongoId | undefined>(undefined)).toBe(undefined); expect(roundTrip<MongoId | undefined>(null)).toBe(undefined); expect(roundTrip<Date | undefined>(undefined)).toBe(undefined); expect(roundTrip<Date | undefined>(null)).toBe(undefined); expect(roundTrip<Record<string, string> | undefined>(undefined)).toBe(undefined); expect(roundTrip<Record<string, string> | undefined>(null)).toBe(undefined); expect(roundTrip<any[] | undefined>(undefined)).toBe(undefined); expect(roundTrip<any[] | undefined>(null)).toBe(undefined); expect(roundTrip<Partial<{ a: string }> | undefined>(undefined)).toBe(undefined); expect(roundTrip<Partial<{ a: string }> | undefined>(null)).toBe(undefined); // expect(roundTrip(t.patch({a: t.string}).optional, undefined)).toBe(undefined); // expect(roundTrip(t.patch({a: t.string}).optional, null)).toBe(undefined); expect(roundTrip<'a' | undefined>(undefined)).toBe(undefined); expect(roundTrip<'a' | undefined>(null)).toBe(undefined); expect(roundTrip<MyEnum | undefined>(undefined)).toBe(undefined); expect(roundTrip<MyEnum | undefined>(null)).toBe(undefined); expect(roundTrip<Model | undefined>(undefined)).toBe(undefined); expect(roundTrip<Model | undefined>(null)).toBe(undefined); expect(roundTrip<ArrayBuffer | undefined>(undefined)).toBe(undefined); expect(roundTrip<ArrayBuffer | undefined>(null)).toBe(undefined); expect(roundTrip<Uint8Array | undefined>(undefined)).toBe(undefined); expect(roundTrip<Uint8Array | undefined>(null)).toBe(undefined); }); test('nullable container', () => { interface s { tags: string[] | null; tagMap: Record<string, string> | null; tagPartial: Partial<{ name: string }> | null; } expect(roundTrip<s>({ tags: null, tagMap: null, tagPartial: null })).toEqual({ tags: null, tagMap: null, tagPartial: null }); expect(roundTrip<s>({} as any)).toEqual({ tags: null, tagMap: null, tagPartial: null }); expect(serializeToJson<s>({} as any)).toEqual({ tags: null, tagMap: null, tagPartial: null }); }); test('nullable basics', () => { expect(roundTrip<string | null>(undefined)).toBe(null); expect(roundTrip<string | null>(null)).toBe(null); expect(roundTrip<number | null>(undefined)).toBe(null); expect(roundTrip<number | null>(null)).toBe(null); expect(roundTrip<boolean | null>(undefined)).toBe(null); expect(roundTrip<boolean | null>(null)).toBe(null); expect(roundTrip<Date | null>(undefined)).toBe(null); expect(roundTrip<Date | null>(null)).toBe(null); expect(roundTrip<UUID | null>(undefined)).toBe(null); expect(roundTrip<UUID | null>(null)).toBe(null); expect(roundTrip<MongoId | null>(undefined)).toBe(null); expect(roundTrip<MongoId | null>(null)).toBe(null); expect(roundTrip<Record<string, string> | null>(undefined)).toBe(null); expect(roundTrip<Record<string, string> | null>(null)).toBe(null); expect(roundTrip<any[] | null>(undefined)).toBe(null); expect(roundTrip<any[] | null>(null)).toBe(null); expect(roundTrip<Partial<{ a: string }> | null>(undefined)).toBe(null); expect(roundTrip<Partial<{ a: string }> | null>(null)).toBe(null); expect(roundTrip<'a' | null>(undefined)).toBe(null); expect(roundTrip<'a' | null>(null)).toBe(null); expect(roundTrip<MyEnum | null>(undefined)).toBe(null); expect(roundTrip<MyEnum | null>(null)).toBe(null); expect(roundTrip<Model | null>(undefined)).toBe(null); expect(roundTrip<Model | null>(null)).toBe(null); expect(roundTrip<ArrayBuffer | null>(undefined)).toBe(null); expect(roundTrip<ArrayBuffer | null>(null)).toBe(null); expect(roundTrip<Uint8Array | null>(undefined)).toBe(null); expect(roundTrip<Uint8Array | null>(null)).toBe(null); }); test('constructor argument', () => { class Product { id: number = 0; constructor(public title: string) { } } class Purchase { id: number = 0; constructor(public product: Product) { } } { const item = roundTrip<Purchase>({ id: 4, product: new Product('asd') }); expect(item.product).toBeInstanceOf(Product); } }); test('omit circular reference 1', () => { class Model { another?: Model; constructor( public id: number = 0 ) { } } expect(ReflectionClass.from(Model).hasCircularReference()).toBe(true); { const model = new Model(1); const model2 = new Model(2); model.another = model2; const plain = serializeToJson<Model>(model); expect(plain.another).toBeInstanceOf(Object); expect(plain.another!.id).toBe(2); } { const model = new Model(1); model.another = model; const plain = serializeToJson<Model>(model); expect(plain.another).toBe(undefined); } }); test('omit circular reference 1 interface', () => { interface Model { id: number; another?: Model; } expect(hasCircularReference(typeOf<Model>())).toBe(true); { const model: Model = { id: 1 }; const model2: Model = { id: 2 }; model.another = model2; const plain = serializeToJson<Model>(model); expect(plain.another!.id).toBe(2); } { const model: Model = { id: 1 }; model.another = model; const plain = serializeToJson<Model>(model); expect(plain.another).toBe(undefined); } }); test('omit circular reference 2', () => { class Config { constructor(public model: Model) { } } class Model { id: number = 0; config?: Config; } expect(ReflectionClass.from(Model).hasCircularReference()).toBe(true); expect(ReflectionClass.from(Config).hasCircularReference()).toBe(true); { const model = new Model; const config = new Config(model); model.config = config; const plain = serializeToJson<Model>(model); expect(plain.config).toBeInstanceOf(Object); expect(plain.config!.model).toBe(undefined); } { const model = new Model; const model2 = new Model; const config = new Config(model2); model.config = config; const plain = serializeToJson<Model>(model); expect(plain.config).toBeInstanceOf(Object); expect(plain.config!.model).toBeInstanceOf(Object); } }); test('omit circular reference 3', () => { class User { id: number = 0; public images: Image[] = []; constructor(public name: string) { } } class Image { id: number = 0; constructor( public user: User, public title: string, ) { if (user.images && !user.images.includes(this)) { user.images.push(this); } } } expect(ReflectionClass.from(User).hasCircularReference()).toBe(true); expect(ReflectionClass.from(Image).hasCircularReference()).toBe(true); { const user = new User('foo'); const image = new Image(user, 'bar'); { const plain = serializeToJson<User>(user); expect(plain.images.length).toBe(1); expect(plain.images[0]).toBeInstanceOf(Object); expect(plain.images[0].title).toBe('bar'); } { const plain = serializeToJson<Image>(image); expect(plain.user).toBeInstanceOf(Object); expect(plain.user.name).toBe('foo'); } } { const user = new User('foo'); const plain = serializeToJson<User>(user); expect(plain.images.length).toBe(0); } }); test('promise', () => { //make sure promise is automatically forwarded to its first generic type expect(serializeToJson<Promise<string>>('1')).toBe('1'); expect(deserializeFromJson<Promise<string>>('1' as any)).toBe('1'); expect(roundTrip<Promise<string>>('1' as any)).toBe('1'); }); test('embedded single', () => { class Price { constructor(public amount: integer) { } } class Product { constructor(public title: string, public price: Embedded<Price>) { } } expect(serializeToJson<Embedded<Price>>(new Price(34))).toEqual({ amount: 34 }); // expect(serialize<Embedded<Price>>(new Price(34))).toEqual(34); // expect(serialize<Embedded<Price>[]>([new Price(34)])).toEqual([34]); // expect(serialize<Embedded<Price, { prefix: '' }>[]>([new Price(34)])).toEqual([34]); // expect(serialize<Embedded<Price, { prefix: 'price_' }>[]>([new Price(34)])).toEqual([34]); // expect(serialize<{ a: Embedded<Price> }>({ a: new Price(34) })).toEqual({ a: 34 }); // expect(serialize<{ a: Embedded<Price, { prefix: '' }> }>({ a: new Price(34) })).toEqual({ amount: 34 }); // expect(serialize<{ a: Embedded<Price, { prefix: 'price_' }> }>({ a: new Price(34) })).toEqual({ price_amount: 34 }); // expect(serialize<Product>(new Product('Brick', new Price(34)))).toEqual({ title: 'Brick', price: 34 }); // // expect(deserialize<Embedded<Price>>(34)).toEqual(new Price(34)); // expect(deserialize<(Embedded<Price> | string)[]>([34])).toEqual([new Price(34)]); // expect(deserialize<(Embedded<Price> | string)[]>(['abc'])).toEqual(['abc']); // // expect(deserialize<Embedded<Price, { prefix: '' }>[]>([34])).toEqual([new Price(34)]); // expect(deserialize<Embedded<Price, { prefix: 'price_' }>[]>([34])).toEqual([new Price(34)]); // expect(deserialize<{ a: Embedded<Price> }>({ a: 34 })).toEqual({ a: new Price(34) }); // expect(deserialize<{ a: Embedded<Price, { prefix: '' }> }>({ amount: 34 })).toEqual({ a: new Price(34) }); // expect(deserialize<{ a: Embedded<Price, { prefix: 'price_' }> }>({ price_amount: 34 })).toEqual({ a: new Price(34) }); // expect(deserialize<Product>({ title: 'Brick', price: 34 })).toEqual(new Product('Brick', new Price(34))); // // // check if union works correctly // expect(serialize<{ v: Embedded<Price> | string }>({ v: new Price(34) })).toEqual({ v: 34 }); // expect(serialize<{ v: Embedded<Price> | string }>({ v: '123' })).toEqual({ v: '123' }); // expect(serialize<{ v: Embedded<Price, { prefix: '' }> | string }>({ v: new Price(34) })).toEqual({ amount: 34 }); // expect(serialize<{ v: Embedded<Price, { prefix: '' }> | string }>({ v: '34' })).toEqual({ v: '34' }); // expect(serialize<{ v: Embedded<Price, { prefix: 'price_' }> | string }>({ v: new Price(34) })).toEqual({ price_amount: 34 }); // expect(serialize<{ v: Embedded<Price, { prefix: 'price_' }> | string }>({ v: '34' })).toEqual({ v: '34' }); // expect(deserialize<{ v: Embedded<Price> | string }>({ v: 34 })).toEqual({ v: new Price(34) }); //todo: embedded type guards are complicated and not yet completely implemented // expect(deserialize<{ v: Embedded<Price> | string }>({ v: '123' })).toEqual({ v: '123' }); // expect(deserialize<{ v: Embedded<Price, { prefix: '' }> | string }>({ amount: 34 })).toEqual({ v: new Price(34) }); // expect(deserialize<{ v: Embedded<Price, { prefix: '' }> | string }>({ v: '34' })).toEqual({ v: '34' }); // expect(deserialize<{ v: Embedded<Price, { prefix: 'price_' }> | string }>({ price_amount: 34 })).toEqual({ v: new Price(34) }); // expect(deserialize<{ v: Embedded<Price, { prefix: 'price_' }> | string }>({ v: '34' })).toEqual({ v: '34' }); }); test('embedded single optional', () => { class Price { constructor(public amount: integer) { } } //for the moment, bson does not support emebbed structures. it's serialized as is. expect(deserializeFromJson<{ v?: Embedded<Price> }>({ v: { amount: 34 } })).toEqual({ v: new Price(34) }); // expect(deserialize<{ v?: Embedded<Price> }>({})).toEqual({}); // expect(deserialize<{ v?: Embedded<Price, { prefix: '' }> }>({ amount: 34 })).toEqual({ v: new Price(34) }); // expect(deserialize<{ v?: Embedded<Price, { prefix: '' }> }>({})).toEqual({}); // expect(deserialize<{ v?: Embedded<Price, { prefix: 'price_' }> }>({ price_amount: 34 })).toEqual({ v: new Price(34) }); // expect(deserialize<{ v?: Embedded<Price, { prefix: 'price_' }> }>({})).toEqual({}); // class Product1 { // constructor(public title: string, public price: Embedded<Price> = new Price(15)) { // } // } // // class Product2 { // constructor(public title: string, public price?: Embedded<Price>) { // } // } // // class Product3 { // public price: Embedded<Price> | undefined = new Price(15); // } // // class Product4 { // public price: Embedded<Price> | null = new Price(15); // } // expect(deserialize<{ a?: Embedded<Price> }>({})).toEqual({}); // expect(deserialize<{ a?: Embedded<Price> }>({ a: undefined })).toEqual({}); // expect(deserialize<{ a?: Embedded<Price, { prefix: '' }> }>({})).toEqual({}); // expect(deserialize<{ a?: Embedded<Price, { prefix: '' }> }>({ amount: undefined })).toEqual({}); // expect(deserialize<{ a?: Embedded<Price, { prefix: 'price_' }> }>({})).toEqual({}); // expect(deserialize<{ a?: Embedded<Price, { prefix: 'price_' }> }>({ price_amount: undefined })).toEqual({}); // expect(deserialize<Product1>({ title: 'Brick' })).toEqual(new Product1('Brick')); // expect(deserialize<Product2>({ title: 'Brick' })).toEqual(new Product2('Brick')); // expect(deserialize<Product3>({})).toEqual({ price: new Price(15) }); // expect(deserialize<Product3>({ price: null })).toEqual({ price: undefined }); // expect(deserialize<Product4>({})).toEqual({ price: new Price(15) }); // expect(deserialize<Product4>({ price: null })).toEqual({ price: null }); }); // // test('embedded multi parameter', () => { // class Price { // constructor(public amount: integer, public currency: string = 'EUR') { // } // } // // class Product { // constructor(public title: string, public price: Embedded<Price>) { // } // } // // expect(serialize<Embedded<Price>>(new Price(34))).toEqual({ amount: 34, currency: 'EUR' }); // expect(serialize<Embedded<Price>[]>([new Price(34)])).toEqual([{ amount: 34, currency: 'EUR' }]); // expect(serialize<Embedded<Price, { prefix: '' }>[]>([new Price(34)])).toEqual([{ amount: 34, currency: 'EUR' }]); // expect(serialize<Embedded<Price, { prefix: 'price_' }>[]>([new Price(34)])).toEqual([{ price_amount: 34, price_currency: 'EUR' }]); // expect(serialize<{ a: Embedded<Price> }>({ a: new Price(34) })).toEqual({ a_amount: 34, a_currency: 'EUR' }); // expect(serialize<{ a: Embedded<Price, { prefix: '' }> }>({ a: new Price(34) })).toEqual({ amount: 34, currency: 'EUR' }); // expect(serialize<{ a: Embedded<Price, { prefix: 'price_' }> }>({ a: new Price(34) })).toEqual({ price_amount: 34, price_currency: 'EUR' }); // expect(serialize<Product>(new Product('Brick', new Price(34)))).toEqual({ title: 'Brick', price_amount: 34, price_currency: 'EUR' }); // // expect(deserialize<Embedded<Price>>({ amount: 34 })).toEqual(new Price(34)); // expect(deserialize<Embedded<Price>>({ amount: 34, currency: '$' })).toEqual(new Price(34, '$')); // expect(deserialize<Embedded<Price>[]>([{ amount: 34 }])).toEqual([new Price(34)]); // expect(deserialize<Embedded<Price>[]>([{ amount: 34, currency: '$' }])).toEqual([new Price(34, '$')]); // expect(deserialize<Embedded<Price, { prefix: '' }>[]>([{ amount: 34 }])).toEqual([new Price(34)]); // expect(deserialize<Embedded<Price, { prefix: 'price_' }>[]>([{ price_amount: 34 }])).toEqual([new Price(34)]); // expect(deserialize<{ a: Embedded<Price> }>({ a_amount: 34 })).toEqual({ a: new Price(34) }); // expect(deserialize<{ a: Embedded<Price, { prefix: '' }> }>({ amount: 34 })).toEqual({ a: new Price(34) }); // expect(deserialize<{ a: Embedded<Price, { prefix: '' }> }>({ amount: 34, currency: '$' })).toEqual({ a: new Price(34, '$') }); // expect(deserialize<{ a: Embedded<Price, { prefix: '' }> }>({ amount: 34, currency: undefined })).toEqual({ a: new Price(34) }); // expect(deserialize<{ a: Embedded<Price, { prefix: 'price_' }> }>({ price_amount: 34 })).toEqual({ a: new Price(34) }); // expect(deserialize<{ a: Embedded<Price, { prefix: 'price_' }> }>({ price_amount: 34, price_currency: '$' })).toEqual({ a: new Price(34, '$') }); // expect(deserialize<Product>({ title: 'Brick', price_amount: 34 })).toEqual(new Product('Brick', new Price(34))); // // //check if union works correctly // expect(serialize<{ v: Embedded<Price> | string }>({ v: new Price(34) })).toEqual({ v_amount: 34, v_currency: 'EUR' }); // expect(serialize<{ v: Embedded<Price> | string }>({ v: new Price(34, '$') })).toEqual({ v_amount: 34, v_currency: '$' }); // expect(serialize<{ v: Embedded<Price> | string }>({ v: '123' })).toEqual({ v: '123' }); // expect(serialize<{ v: Embedded<Price, { prefix: '' }> | string }>({ v: new Price(34) })).toEqual({ amount: 34, currency: 'EUR' }); // expect(serialize<{ v: Embedded<Price, { prefix: '' }> | string }>({ v: '34' })).toEqual({ v: '34' }); // expect(serialize<{ v: Embedded<Price, { prefix: 'price_' }> | string }>({ v: new Price(34) })).toEqual({ price_amount: 34, price_currency: 'EUR' }); // expect(serialize<{ v: Embedded<Price, { prefix: 'price_' }> | string }>({ v: '34' })).toEqual({ v: '34' }); // // expect(deserialize<{ v: Embedded<Price> | string }>({ v_amount: 34 })).toEqual({ v: new Price(34) }); // expect(deserialize<{ v: Embedded<Price> | string }>({ v_amount: 34, v_currency: '$' })).toEqual({ v: new Price(34, '$') }); // expect(deserialize<{ v: Embedded<Price> | string }>({ v: '123' })).toEqual({ v: '123' }); // expect(deserialize<{ v: Embedded<Price, { prefix: '' }> | string }>({ amount: 34 })).toEqual({ v: new Price(34) }); // expect(deserialize<{ v: Embedded<Price, { prefix: '' }> | string }>({ v: '34' })).toEqual({ v: '34' }); // expect(deserialize<{ v: Embedded<Price, { prefix: 'price_' }> | string }>({ price_amount: 34 })).toEqual({ v: new Price(34) }); // expect(deserialize<{ v: Embedded<Price, { prefix: 'price_' }> | string }>({ v: '34' })).toEqual({ v: '34' }); // }); test('class inheritance', () => { class A { id: number = 0; } class B extends A { username: string = ''; } expect(deserializeFromJson<A>({ id: 2 })).toEqual({ id: 2 }); expect(serializeToJson<A>({ id: 2 })).toEqual({ id: 2 }); expect(deserializeFromJson<B>({ id: 2, username: 'Peter' })).toEqual({ id: 2, username: 'Peter' }); expect(serializeToJson<B>({ id: 2, username: 'Peter' })).toEqual({ id: 2, username: 'Peter' }); }); test('mapName interface', () => { interface A { type: string & MapName<'~type'>; } expect(deserializeFromJson<A>({ '~type': 'abc' })).toEqual({ 'type': 'abc' }); expect(serializeToJson<A>({ 'type': 'abc' })).toEqual({ '~type': 'abc' }); expect(deserializeFromJson<A | string>({ '~type': 'abc' })).toEqual({ 'type': 'abc' }); expect(serializeToJson<A | string>({ 'type': 'abc' })).toEqual({ '~type': 'abc' }); expect(serializeToJson<A | string>('abc')).toEqual('abc'); }); test('mapName class', () => { class A { id: string & MapName<'~id'> = ''; constructor(public type: string & MapName<'~type'>) { } } expect(deserializeFromJson<A>({ '~id': '1', '~type': 'abc' })).toEqual({ 'id': '1', 'type': 'abc' }); expect(serializeToJson<A>({ id: '1', 'type': 'abc' })).toEqual({ '~id': '1', '~type': 'abc' }); expect(deserializeFromJson<A | string>({ '~id': '', '~type': 'abc' })).toEqual({ id: '', 'type': 'abc' }); expect(serializeToJson<A | string>({ id: '1', 'type': 'abc' })).toEqual({ '~id': '1', '~type': 'abc' }); expect(serializeToJson<A | string>('abc')).toEqual('abc'); }); test('dynamic properties', () => { class A { [index: string]: any; getType(): string { return String(this['~type'] || this['type'] || ''); } } const back1 = deserializeFromJson<A>({'~type': 'abc'}); expect(back1.getType()).toBe('abc'); const back2 = deserializeFromJson<A>({'type': 'abc'}); expect(back2.getType()).toBe('abc'); });
the_stack
import Fs = require("fs"); import _ = require("lodash"); import Path = require("path"); /** * This plugin (SubAppWebpackPlugin) add hooks for webpack's compiler and parser, and listen * for any code that call the SubApp APIs declareSubApp or createDynamicComponent. * * It then take the parser's AST to analyze the arguments passed to the APIs to extract subapp * import module and name. * * It also injects webpack's magic comment to name the subapp dynamic bundle. * * In dev mode, it will inject hot module reload code. * * Finally, it saves all the subapp info captured as a webpack emit asset subapps.json. * */ const ModuleDependency = require("webpack/lib/dependencies/ModuleDependency"); const pluginName = "SubAppPlugin"; const findWebpackVersion = (): number => { const webpackPkg = JSON.parse( Fs.readFileSync(require.resolve("webpack/package.json")).toString() ); const webpackVersion = parseInt(webpackPkg.version.split(".")[0]); return webpackVersion; }; const assert = (ok: boolean, fail: string | Function) => { if (!ok) { const x = typeof fail === "function" ? fail() : fail; if (typeof x === "string") { throw new Error(x); } throw x; } }; const SHIM_parseCommentOptions = Symbol("parseCommentOptions"); const SYM_HMR_INJECT = Symbol("sym-hmr-inject"); import { hmrSetup } from "../client/hmr-accept"; /** * subapp hot module reload accept dependency. When SubAppWebpackPlugin detects a module * has declareSubApp, it will add this as a dependency to that module. Webpack will invoke * this dep's template (below), which will inject the HMR code for the module. * * References: * - `webpack/lib/dependencies/ModuleHotAcceptDependency.js` * - `webpack/lib/HotModuleReplacementPlugin.js` * */ class SubAppHotAcceptDependency extends ModuleDependency { parent: any; subapp: any; constructor(request, parent, subapp: any) { super(request); this.parent = parent; this.subapp = subapp; this.optional = true; // important to set this else code splitting stop working this.weak = true; } get type() { return "xarc.subapp.hot.accept"; } get hasInject() { return Boolean(this.parent[SYM_HMR_INJECT]); } initInject() { if (!this.parent[SYM_HMR_INJECT]) { this.parent[SYM_HMR_INJECT] = {}; } return this.parent[SYM_HMR_INJECT]; } get injected() { return this.parent[SYM_HMR_INJECT]; } } const where = (source, loc) => { return `${source}:${loc.start.line}:${loc.start.column + 1}`; }; const noCwd = x => x.replace(process.cwd(), "."); /** * subapp hot accept template, this will insert HMR code from ../client/hmr-accept.ts * into the module that declareSubApp. * */ class SubAppHotAcceptTemplate { apply(dep: SubAppHotAcceptDependency, source: any, { runtimeTemplate, moduleGraph, chunkGraph }) { if (!(dep instanceof SubAppHotAcceptDependency)) { return; } const content = runtimeTemplate.moduleId({ module: moduleGraph.getModule(dep), chunkGraph, request: dep.request, weak: dep.weak }); const script = []; if (!dep.hasInject) { dep.initInject(); // // injecting code from ../client/hmr-accept.ts: it's using the function // exported and its toString to get the code. So it's important the // function is fully self contained without external dependencies. // // TODO: update subapp-plugin to make module used? script.push(` /* subapp HMR accept */ var __xarcHmr__ = (${hmrSetup.toString()})(window, (typeof __unused_webpack_module !== "undefined" ? __unused_webpack_module : module).hot);`); } if (!dep.injected[content]) { script.push(`__xarcHmr__.addSubApp(${content}, "${dep.subapp.name}");`); } if (script.length > 0) { source.insert( source.size() + 0.5, ` ${script.join("\n")} /***/` ); } } } /** * This plugin will look for `declareSubApp` calls and do these: * * 1. instruct webpack to name the dynamic import bundle as `subapp-<name>` * 2. collect the subapp meta info and save them as `subapps.json` * */ export class SubAppWebpackPlugin { _declareApiNames: string[]; _subApps: Record<string, any>; _webpackMajorVersion: number; _makeIdentifierBEE: Function; _tapAssets: Function; _assetsFile: string; _hasHmr: (compilation: any) => boolean; _foundSubApps: string; /** * * @param options - subapp plugin options */ constructor({ declareApiName = ["declareSubApp", "createDynamicComponent"], webpackVersion = findWebpackVersion(), assetsFile = "subapps.json" }: { /** * The API names for declaring subapp and components */ declareApiName?: string | string[]; /** * Webpack version * * minimum 5 */ webpackVersion?: number; /** * Filename to output the subapp assets JSON file * **default**: `subapps.json` */ assetsFile?: string; } = {}) { this._declareApiNames = [].concat(declareApiName); this._subApps = {}; this._webpackMajorVersion = webpackVersion; const { makeIdentifierBEE, tapAssets, hasHmr } = this[ `initWebpackVer${this._webpackMajorVersion}` ](); this._makeIdentifierBEE = makeIdentifierBEE; this._tapAssets = tapAssets; this._assetsFile = assetsFile; this._hasHmr = hasHmr; this._foundSubApps = ""; } initWebpackVer5() { const BEE = require("webpack/lib/javascript/BasicEvaluatedExpression"); return { BasicEvaluatedExpression: BEE, makeIdentifierBEE: expr => { return new BEE() .setIdentifier(expr.name, {}, () => []) .setRange(expr.range) .setExpression(expr); }, tapAssets: compiler => { compiler.hooks.compilation.tap(pluginName, compilation => { compilation.hooks.processAssets.tap(pluginName, assets => this.updateAssets(assets)); }); }, // TODO: detect HMR from compilation hasHmr: () => Boolean(process.env.WEBPACK_DEV) }; } updateAssets(assets) { let subappMeta = {}; const keys = Object.keys(this._subApps); if (keys.length > 0) { subappMeta = keys.reduce( (acc, k) => { acc[k] = _.pick(this._subApps[k], ["name", "source", "module"]); return acc; }, { "//about": "Subapp meta information collected during webpack compile", "//count": keys.length } ); const subapps = JSON.stringify(subappMeta, null, 2) + "\n"; assets[this._assetsFile] = { source: () => subapps, size: () => subapps.length }; const found = keys.join(", "); if (this._foundSubApps !== found) { this._foundSubApps = found; console.log("version 2 subapps found:", found); // eslint-disable-line } } } private findImportCall(ast, source) { switch (ast.type) { case "CallExpression": const arg = _.get(ast, "arguments[0]", {}); if (ast.callee.type === "Import" && arg.type === "Literal") { return arg.value; } case "ReturnStatement": return this.findImportCall(ast.argument, source); case "BlockStatement": for (const n of ast.body) { const res = this.findImportCall(n, source); if (res) { return res; } } // webpack 5 case "ImportExpression": assert( ast.source.type === "Literal", `${where( noCwd(source), ast.source.loc )}: subapp module import must use literal string, got ${ast.source.type}` ); return ast.source.value; } return undefined; } /** * Webpack 5 Reference: * - lib/HotModuleReplacementPlugin.js * * @param compiler */ _applyHmrInject(compiler) { compiler.hooks.compilation.tap(pluginName, (compilation, { normalModuleFactory }) => { // This applies the HMR injection only to the targeted compiler // It should not affect child compilations if (compilation.compiler !== compiler) return; if (!this._hasHmr(compilation)) { return; } compilation.dependencyFactories.set(SubAppHotAcceptDependency, normalModuleFactory); compilation.dependencyTemplates.set(SubAppHotAcceptDependency, new SubAppHotAcceptTemplate()); }); } apply(compiler) { this._tapAssets(compiler); const findGetModule = props => { const prop = props.find(p => p.key.name === "getModule"); const funcBody = prop.value.body; return funcBody; }; this._applyHmrInject(compiler); compiler.hooks.normalModuleFactory.tap(pluginName, factory => { factory.hooks.parser.for("javascript/auto").tap(pluginName, (parser, options) => { parser[SHIM_parseCommentOptions] = parser.parseCommentOptions; assert( parser.parseCommentOptions, `webpack parser doesn't have method 'parseCommentOptions' - not compatible with this plugin` ); const xl = parser.parseCommentOptions.length; assert( xl === 1, `webpack parser.parseCommentOptions takes ${xl} arguments - but expecting 1 so not compatible with this plugin` ); parser.parseCommentOptions = range => { for (const k in this._subApps) { const subapp = this._subApps[k]; const gmod = subapp.getModule; if (range[0] >= gmod.range[0] && gmod.range[1] >= range[1]) { const name = subapp.name.toLowerCase().replace(/ /g, "_"); return { options: { webpackChunkName: `subapp-${name}` }, errors: [] }; } } return parser[SHIM_parseCommentOptions](range); }; const parseForSubApp = (expression, apiName) => { const currentSource = _.get(parser, "state.current.resource", ""); const props = _.get(expression, "arguments[0].properties"); const cw = () => where(noCwd(currentSource), expression.loc); if (!props && apiName === "createDynamicComponent") { return; } assert(props, () => `${cw()}: you must pass an Object literal as argument to ${apiName}`); const nameProp = props.find(p => p.key.name === "name"); assert(nameProp, () => `${cw()}: argument for ${apiName} doesn't have a name property`); const nameVal = nameProp.value.value; assert( nameVal && typeof nameVal === "string", () => `${cw()}: subapp name must be specified as an inlined literal string` ); // the following breaks hot recompiling in dev mode // const exist = this._subApps[nameVal]; // assert( // !exist, // () => // `${cw()}: subapp '${nameVal}' is already declared at ${where( // noCwd(exist.source), // exist.loc // )}` // ); const gm = findGetModule(props); // try to figure out the module that's being imported for this subapp // getModule function: () => import("./subapp-module") // getModule function: function () { return import("./subapp-module") } const mod = this.findImportCall(gm, currentSource); assert(mod, `${cw()}: unable to find the request of the subapp's module import call`); this._subApps[nameVal] = { name: nameVal, source: Path.relative(process.cwd(), currentSource), loc: expression.loc, range: expression.range, getModule: gm, module: mod }; if (this._hasHmr(parser.state.compilation)) { const dep = new SubAppHotAcceptDependency( mod, parser.state.module, this._subApps[nameVal] ); parser.state.module.addDependency(dep); parser.state.module[SYM_HMR_INJECT] = null; } }; const apiNames = [].concat(this._declareApiNames); [].concat(apiNames).forEach(apiName => { parser.hooks.call.for(apiName).tap(pluginName, expr => parseForSubApp(expr, apiName)); }); parser.hooks.evaluate .for("CallExpression") .tap({ name: pluginName, before: "Parser" }, expression => { const calleeName = _.get(expression, "callee.property.name"); if (apiNames.includes(calleeName)) { return parseForSubApp(expression, calleeName); } return undefined; }); parser.hooks.evaluate .for("Identifier") .tap({ name: pluginName, before: "Parser" }, expression => { if (apiNames.includes(expression.name)) { return this._makeIdentifierBEE(expression); } return undefined; }); }); }); } }
the_stack
export type conststring = string & {} | ""; /** A type useful as a base constraint for a number that should be inferred as a number literal type. */ export type constnumber = number & {} | 0; /** A type useful as a base constraint for a symbol that should be inferred as a unique symbol type. */ export type constsymbol = symbol & {} | typeof kIgnore; declare const kIgnore: unique symbol; /** A type useful as a base constraint for an array that should be inferred as a tuple. */ export type consttuple<T> = readonly T[] | readonly []; type numbers255 = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, ]; type strings255 = numbers255 extends infer T ? { [P in keyof T]: P } : never; /** * Gets a union of the number and numeric string value for a number or numeric string index between 0 and 255 */ export type numstr<I extends keyof any> = I extends numbers255[number] ? I | strings255[I] : I extends strings255[number] ? I | numbers255[I] : never; /** * A union of all of the primitive types in TypeScript. */ export type Primitive = string | symbol | boolean | number | bigint; /** * A union of all of the falsy types in TypeScript. */ export type Falsy = null | undefined | false | 0 | 0n | ''; /** @deprecated Use {@link Falsy} instead. */ export type Falsey = Falsy; /** * A PropertyDescriptor constrained to the valid attributes for an accessor. */ export interface AccessorPropertyDescriptor<T = any> { enumerable?: boolean; configurable?: boolean; get?(): T; set?(v: T): void; } /** * A PropertyDescriptor constrained to the valid attributes for a method. */ export interface MethodPropertyDescriptor<T extends (...args: any[]) => any = (...args: any[]) => any> { enumerable?: boolean; configurable?: boolean; writable?: boolean; value: T; } /** * Indicates a type that may be `undefined`. */ export type Optional<T> = T | undefined; /** * Strips `undefined` from a type. */ export type NonOptional<T> = T extends undefined ? never : T; /** * Indicates a type that may be `null` or `undefined`. */ export type Nullable<T> = T | undefined | null; /** * Strips `null` or `undefined` from a type. */ export import NonNullable = globalThis.NonNullable; /** * Gets a union of `keyof T'` of each constituent `T'` of `T`. */ export type AnyKeyof<T> = T extends unknown ? keyof T : never; /** * Gets a union of `Extract<T', U>` for each constituent `T'` of `T`. */ export type AnyExtract<T, U> = T extends unknown ? Extract<T, U> : never; /** * Gets a union of `Exclude<T', U>` for each constituent `T'` of `T`. */ export type AnyExclude<T, U> = T extends unknown ? Exclude<T, U> : never; /** * Represents a concrete ECMAScript constructor object. */ export type Constructor<T = {}, A extends any[] = any[]> = new (...args: A) => T; /** * Represents an abstract class constructor. */ export type AbstractConstructor<T = {}, A extends any[] = any[]> = abstract new (...args: A) => T; /** * Gets the type yielded by an Iterable. */ export type IteratedType<T> = T extends { [Symbol.iterator](): { next(...args: any): infer R } } ? R extends { done?: boolean, value: any } ? R["done"] extends true ? never : R["value"] : never : never; /** * Gets the type that can be returned from a generator when it has finished executing. */ export type GeneratorReturnType<T> = T extends { [Symbol.iterator](): { next(...args: any): infer R } } ? R extends { done?: boolean, value: any } ? R["done"] extends false | undefined ? never : R["value"] : never : never; /** * Gets the type that can be sent to a generator via its `next` method. */ export type GeneratorNextType<T> = T extends { [Symbol.iterator](): { next(value?: infer U): any } } ? U : never; /** * Gets the type yielded by an AsyncIterable. */ export type AsyncIteratedType<T> = T extends { [Symbol.asyncIterator](): { next(...args: any): PromiseLike<infer R> } } ? R extends { done?: boolean, value?: any } ? R["done"] extends true ? never : Await<R["value"]> : never : never; /** * Gets the type that can be sent to a generator via its `next` method. */ export type AsyncGeneratorNextType<T> = T extends { [Symbol.asyncIterator](): { next(value?: infer U): any } } ? U : never; /** * Gets the type that can be returned from a generator when it has finished executing. */ export type AsyncGeneratorReturnType<T> = T extends { [Symbol.asyncIterator](): { next(...args: any): PromiseLike<infer R> } } ? R extends { done?: boolean, value?: any } ? R["done"] extends false | undefined ? never : Await<R["value"]> : never : never; /** * Gets the promised type of a Promise. */ export type PromisedType<T> = T extends { then(onfulfilled: infer U): any } ? U extends ((value: infer V) => any) ? V : never : never; /** * Maps an ordered tuple of types into an intersection of those types. */ export type Intersection<A extends any[]> = A extends [infer H, ...infer T] ? H & Intersection<T> : unknown; /** * Maps an ordered tuple of types into a union of those types. */ export type Union<A extends any[]> = A[number]; // TODO(rbuckton): Investigate whether UnionToIntersection should be kept. Intersections are ordered // while unions are unordered. // /** // * Maps a union of types into an intersection of types. // */ // export type UnionToIntersection<U> = ((U extends unknown ? (u: U) => void : never) extends ((i: infer I) => void) ? I : never) | never; /** * Maps to `true` if `A` is precisely the `any` type; otherwise, `false`. */ export type IsAny<A> = (1 | 2) extends (A extends never ? 1 : 2) ? true : false; /** * Maps to `true` if `A` is precisely the `never` type; otherwise, `false`. */ export type IsNever<A> = (A extends never ? true : false) extends true ? true : false; /** * Maps to `true` if `A` is precisely the `unknown` type; otherwise, `false`. */ export type IsUnknown<A> = IsAny<A> extends true ? false : unknown extends A ? true : false; /** * Maps to `true` if `T` is a union of multiple types; otherwise, `false`. */ export type IsUnion<T> = IsNever<T> extends true ? false : __IsUnionRest<T, [T]>; type __IsUnionRest<T, Q> = T extends unknown ? Not<SameType<[T], Q>> : never; /** * Maps to `true` if `Sub` is a subtype of `Super`; otherwise, `false`. */ export type IsSubtypeOf<Sub, Super> = IsNever<Super> extends true ? IsNever<Sub> : IsNever<Sub> extends true ? true : IsAny<Super> extends true ? true : IsAny<Sub> extends true ? true : Sub extends Super ? true : false; /** * Maps to `true` if `Super` is a supertype of `Sub`; otherwise, `false`. */ export type IsSupertypeOf<Super, Sub> = IsSubtypeOf<Sub, Super>; /** * Maps to `true` if the type has a call signature; otherwise, `false`. */ export type IsCallable<T> = IsAny<T> extends true ? boolean : IsNever<T> extends true ? never : SameType<T, Function> extends true ? true : [T] extends [(...args: any) => any] ? true : false; /** * Maps to `true` if the type has a construct signature; otherwise, `false`. */ export type IsConstructable<T> = IsAny<T> extends true ? boolean : IsNever<T> extends true ? never : SameType<T, Function> extends true ? true : [T] extends [new (...args: any) => any] ? true : false; /** * Maps to `true` if `A` is `false`, otherwise `true`. */ export type Not<A extends boolean> = IsNever<A> extends true ? never : A extends false ? true : false; /** * Maps to `true` if both `A` and `B` are `true`; otherwise, `false`. */ export type And<A extends boolean, B extends boolean> = IsNever<A> extends true ? never : IsNever<B> extends true ? never : A extends false ? false : B extends false ? false : true; /** * Maps to `true` if either `A` or `B` are `true`; otherwise, `false`. */ export type Or<A extends boolean, B extends boolean> = IsNever<A> extends true ? never : IsNever<B> extends true ? never : A extends true ? true : B extends true ? true : false; /** * Maps to `true` if only one of either `A` or `B` are `true`; otherwise, `false`. */ export type XOr<A extends boolean, B extends boolean> = IsNever<A> extends true ? never : IsNever<B> extends true ? never : A extends true ? Not<B> : B extends true ? Not<A> : false; /** * Maps to `true` if every element of the tuple `L` is `true`; otherwise, `false`. */ export type Every<L extends boolean[]> = L extends [] ? never : __EveryRest<{ [P in keyof L]: IsNever<L[P]> extends true ? "never" : IsAny<L[P]> extends true ? "boolean" : boolean extends L[P] ? "boolean" : L[P] extends false ? "false" : never; }[number]>; type __EveryRest<R> = "never" extends R ? never : // an element was `never` "false" extends R ? false : // at least one element was `false` "boolean" extends R ? boolean : // an element was `any` or `boolean` true; // no elements were false /** * Maps to `true` if any element of the tuple `L` is `true`; otherwise, `false`. */ export type Some<L extends boolean[]> = L extends [] ? never : __SomeRest<{ [P in keyof L]: IsNever<L[P]> extends true ? "never" : IsAny<L[P]> extends true ? "boolean" : boolean extends L[P] ? "boolean" : L[P] extends true ? "true" : never; }[number]>; type __SomeRest<R> = "never" extends R ? never : // an element was `never` "true" extends R ? true : // at least one element was `true` "boolean" extends R ? boolean : // an element was `any` or `boolean` false; // no elements were true /** * Maps to `true` if exactly one element of the tuple `L` is `true`; otherwise, `false`. */ export type One<L extends boolean[]> = L extends [] ? never : __OneRest<{ [P in keyof L]: IsNever<L[P]> extends true ? "never" : IsAny<L[P]> extends true ? "boolean" : boolean extends L[P] ? "boolean" : L[P] extends true ? [P] : never; }[number]>; type __OneRest<R> = "never" extends R ? never : // an element was `never` "boolean" extends R ? boolean : // an element was `any` or `boolean` IsNever<R> extends true ? false : // no elements were `true` IsUnion<R> extends true ? false : // multiple elements were `true` true; // only one element was `true` /** * Maps to `true` if both `A` and `B` are assignable to each other; otherwise, `false`. */ export type SameType<A, B> = IsNever<A> extends true ? IsNever<B> : IsNever<B> extends true ? false : [A, B] extends [B, A] ? true : false; /** * Maps to `true` if all elements of the tuple `L` are assignable to each other; otherwise, `false`. */ export type SameTypes<L extends any[]> = L extends [] ? never : SameType<{ [P in keyof L]: SameType<L[P], L[number]> }[number], true>; /** * Maps to `true` if either `A` or `B` are relatable to each other. */ export type Relatable<A, B> = IsNever<A> extends true ? false : IsNever<B> extends true ? false : IsAny<A> extends true ? true : IsAny<B> extends true ? true : [A] extends [B] ? true : [B] extends [A] ? true : false; /** * Maps to `true` if any type in `A` is assignable to any type in `B`; otherwise, `false`. */ export type Overlaps<A, B> = IsNever<A> extends true ? false : IsNever<B> extends true ? false : IsAny<A> extends true ? true : IsAny<B> extends true ? true : 1 extends (A extends unknown ? A extends B ? 1 : 2 : 3) ? true : 1 extends (B extends unknown ? B extends A ? 1 : 2 : 3) ? true : false; /** * Maps to `true` if `Sub` is a subset of `Super`; otherwise, `false`. */ export type IsSubsetOf<Sub, Super> = IsAny<Sub> extends true ? boolean : // Nothing can be determined about a subset of `any` IsAny<Super> extends true ? boolean : // Nothing can be determined about a superset of `any` __IsSubsetOf<Sub, Super>; type __IsSubsetOf<Sub, Super> = IsNever<Sub> extends true ? true : // The empty set is a subset of all sets IsNever<Super> extends true ? false : // No other set is a subset of the empty set IsUnknown<Sub> extends true ? false : // The set of all types cannot be a proper subset of itself IsUnknown<Super> extends true ? true : // All other sets are the subset of the set of all types [Sub] extends [Super] ? true : false; /** * Maps to `true` if `Super` is a superset of `Sub`; otherwise, `false`. */ export type IsSupersetOf<Super, Sub> = IsSubsetOf<Sub, Super>; /** * Maps to `true` if `Sub` is a proper subset of `Super`; otherwise, `false`. */ export type IsProperSubsetOf<Sub, Super> = IsAny<Sub> extends true ? boolean : // Nothing can be determined about a subset of `any` IsAny<Super> extends true ? boolean : // Nothing can be determined about a superset of `any` SameType<Sub, Super> extends true ? false : // A set cannot be a proper subset of itself __IsSubsetOf<Sub, Super>; /** * Maps to `true` if `Super` is a proper superset of `Sub`; otherwise, `false`. */ export type IsProperSupersetOf<Super, Sub> = IsProperSubsetOf<Sub, Super>; /** * Maps to the keys of `T` whose values match `TMatch`. */ export type MatchingKeys<T, TMatch> = { [P in keyof T]: T[P] extends TMatch ? P : never }[keyof T]; /** * Maps to the keys of `T` whose values do not match `TMatch`. */ export type NonMatchingKeys<T, TMatch> = Exclude<keyof T, MatchingKeys<T, TMatch>>; /** * Maps to the keys of `T` whose values are functions. */ export type FunctionKeys<T, F extends Function = Function> = MatchingKeys<T, F>; /** * Maps to the keys of `T` whose values are not functions. */ export type NonFunctionKeys<T, F extends Function = Function> = NonMatchingKeys<T, F>; /** * Maps `T` to its awaited type if `T` is a promise. */ export type Await<T> = T extends { then(onfulfilled: infer U): any } ? U extends ((value: infer V) => any) ? Await<V> : never : T; /** * Maps each element of `T` to its awaited type if the element is a promise. */ export type AwaitAll<T extends any[]> = { [P in keyof T]: Await<T[P]>; }; /** * Maps to a tuple where the first element is the first element of `L` and the second element are the remaining elements of `L`. */ export type Shift<L extends any[]> = L extends [infer H, ...infer T] ? [H, T] : [never, never]; /** * Inserts an element at the start of a tuple. */ export type Unshift<T extends any[], H> = [H, ...T]; /** * Reverse the order of the elements of a tuple. */ export type Reverse<L extends any[]> = L extends [infer H, ...infer T] ? [...Reverse<T>, H] : []; /** * Maps to a tuple where the first element is the last element of `L` and the second element are the remaining elements of `L`. */ export type Pop<L extends any[]> = L extends [...infer H, infer T] ? [T, H] : [never, never]; /** * Push an element on to the end of a tuple. */ export type Push<H extends any[], T> = [...H, T]; /** * Split an object into a union of objects for each key/value pair. */ export type Disjoin<T extends object> = IsNever<T> extends true ? never : IsAny<T> extends true ? any : __DisjoinRest<{ [K in keyof T]: { [P in K]: T[P] }; }[keyof T]>; type __DisjoinRest<T> = IsNever<T> extends true ? {} : T; /** * Map an intersection of object types into a single object type. */ export type Reshape<T extends object> = Pick<T, keyof T>; /** * Joins a union of disjoint object types into a single object type. */ export type Conjoin<T extends object> = { [P in AnyKeyof<T>]: AnyExtract<T, { readonly [U in P]: unknown }>[P]; }; /** * Maps to `true` if any type in `A` is assignable to or shares a property with any type in `B`; otherwise, `false`. * This is similar to `Overlaps`, except object types in `A` and `B` are mapped through `Disjoin`. */ export type DisjoinOverlaps<A, B> = Overlaps< A extends object ? Disjoin<A> : A, B extends object ? Disjoin<B> : B >; /** * Maps to `true` if `T` is an empty object (`{}`). */ export type IsEmpty<T extends object> = IsNever<keyof T>; /** * Remove from `T` all keys in `K`. */ export import Omit = globalThis.Omit; /** * Remove from `A` all properties with the same types that exist in `B`. */ export type Diff<A extends object, B extends object> = Omit<A, keyof B>; /** * Pick from `A` all properties with the same types that exist in `B`. */ export type Intersect<A extends object, B extends object> = Pick<A & B, Extract<keyof A, keyof B> & Extract<keyof B, keyof A>>; /** * Combine the properties of `A` and `B`, chosing the properties in `B` if the types differ. */ export type Assign<A extends object, B extends object> = Reshape<Diff<A, B> & B>; /** * Maps to a mutable copy of T. */ export type Mutable<T> = { -readonly [P in keyof T]: T[P]; }
the_stack
import * as assert from "assert"; import { BatchType } from "../../../src/common/batch/BatchOperation"; import BatchRequestHeaders from "../../../src/common/batch/BatchRequestHeaders"; import { BatchSerialization } from "../../../src/common/batch/BatchSerialization"; import { TableBatchSerialization } from "../../../src/table/batch/TableBatchSerialization"; import SerializationRequestMockStrings from "./mock.request.serialization.strings"; describe("batch deserialization unit tests, these are not the API integration tests:", () => { it("deserializes, mock table batch request containing 3 insert requests correctly", (done) => { const requestString = SerializationRequestMockStrings.Sample3InsertsUsingSDK; const serializer = new TableBatchSerialization(); const batchOperationArray = serializer.deserializeBatchRequest( requestString ); assert.equal( batchOperationArray.length, 3, "failed to deserialize correct number of operations" ); assert.equal(batchOperationArray[0].batchType, BatchType.table); assert.equal( batchOperationArray[0].httpMethod, "POST", "wrong HTTP Method parsed" ); assert.equal( batchOperationArray[0].path, "table160837408807101776", "wrong path parsed" ); assert.equal( batchOperationArray[0].uri, "http://127.0.0.1:11002/devstoreaccount1/table160837408807101776", "wrong url parsed" ); assert.equal( batchOperationArray[0].jsonRequestBody, '{"PartitionKey":"part1","RowKey":"row160837408812000231","myValue":"value1"}', "wrong jsonBody parsed" ); // Second Batch Operation assert.equal(batchOperationArray[1].batchType, BatchType.table); assert.equal( batchOperationArray[1].httpMethod, "POST", "wrong HTTP Method parsed" ); assert.equal( batchOperationArray[1].path, "table160837408807101776", "wrong path parsed" ); assert.equal( batchOperationArray[1].uri, "http://127.0.0.1:11002/devstoreaccount1/table160837408807101776", "wrong url parsed" ); assert.equal( batchOperationArray[1].jsonRequestBody, '{"PartitionKey":"part1","RowKey":"row160837408812008370","myValue":"value1"}', "wrong jsonBody parsed" ); // Third Batch Operation assert.equal(batchOperationArray[2].batchType, BatchType.table); assert.equal( batchOperationArray[2].httpMethod, "POST", "wrong HTTP Method parsed" ); assert.equal( batchOperationArray[2].path, "table160837408807101776", "wrong path parsed" ); assert.equal( batchOperationArray[2].uri, "http://127.0.0.1:11002/devstoreaccount1/table160837408807101776", "wrong url parsed" ); assert.equal( batchOperationArray[2].jsonRequestBody, '{"PartitionKey":"part1","RowKey":"row160837408812003154","myValue":"value1"}', "wrong jsonBody parsed" ); done(); }); it("deserializes, mock table batch request containing a query correctly", (done) => { const requestString = SerializationRequestMockStrings.Sample1QueryUsingSDK; const serializer = new TableBatchSerialization(); const batchOperationArray = serializer.deserializeBatchRequest( requestString ); // this first test is currently a stupid test, as I control the type within the code // we want to test that we have deserialized the operation. assert.equal(batchOperationArray[0].batchType, BatchType.table); assert.equal( batchOperationArray[0].httpMethod, "GET", "wrong HTTP Method parsed" ); assert.equal( batchOperationArray[0].path, "table160837567141205013", "wrong path parsed" ); assert.equal( batchOperationArray[0].uri, "http://127.0.0.1:11002/devstoreaccount1/table160837567141205013(PartitionKey=%27part1%27,RowKey=%27row160837567145205850%27)", "wrong url parsed" ); assert.equal( batchOperationArray[0].jsonRequestBody, "", "wrong jsonBody parsed" ); done(); }); it("deserializes, mock table batch request containing insert and merge correctly", (done) => { const requestString = SerializationRequestMockStrings.SampleInsertThenMergeUsingSDK; const serializer = new TableBatchSerialization(); const batchOperationArray = serializer.deserializeBatchRequest( requestString ); // First Batch Operation is an insert. assert.equal(batchOperationArray[0].batchType, BatchType.table); assert.equal( batchOperationArray[0].httpMethod, "POST", "wrong HTTP Method parsed" ); assert.equal( batchOperationArray[0].path, "table160837770303307822", "wrong path parsed" ); assert.equal( batchOperationArray[0].uri, "http://127.0.0.1:11002/devstoreaccount1/table160837770303307822", "wrong url parsed" ); assert.equal( batchOperationArray[0].jsonRequestBody, '{"PartitionKey":"part1","RowKey":"row160837770307508823","myValue":"value2"}', "wrong jsonBody parsed" ); // Second Batch Operation is a merge assert.equal(batchOperationArray[1].batchType, BatchType.table); assert.equal( batchOperationArray[1].httpMethod, "MERGE", "wrong HTTP Method parsed" ); assert.equal( batchOperationArray[1].path, "table160837770303307822", "wrong path parsed" ); assert.equal( batchOperationArray[1].uri, "http://127.0.0.1:11002/devstoreaccount1/table160837770303307822(PartitionKey=%27part1%27,RowKey=%27row160837770307508823%27)", "wrong url parsed" ); assert.equal( batchOperationArray[1].jsonRequestBody, '{"PartitionKey":"part1","RowKey":"row160837770307508823","myValue":"valueMerge"}', "wrong jsonBody parsed" ); done(); }); it("deserializes, mock table batch request containing 3 deletes correctly", (done) => { const requestString = SerializationRequestMockStrings.Sample3DeletesUsingSDK; const serializer = new TableBatchSerialization(); const batchOperationArray = serializer.deserializeBatchRequest( requestString ); // First Batch Operation is an insert. assert.equal(batchOperationArray[0].batchType, BatchType.table); assert.equal( batchOperationArray[0].httpMethod, "DELETE", "wrong HTTP Method parsed" ); assert.equal( batchOperationArray[0].path, "table161216830457901592", "wrong path parsed" ); assert.equal( batchOperationArray[0].uri, "http://127.0.0.1:11002/devstoreaccount1/table161216830457901592(PartitionKey=%27part1%27,RowKey=%27row161216830462208585%27)", "wrong url parsed" ); assert.equal( batchOperationArray[0].jsonRequestBody, "", "wrong jsonBody parsed" ); // Second Batch Operation is a Delete assert.equal(batchOperationArray[1].batchType, BatchType.table); assert.equal( batchOperationArray[1].httpMethod, "DELETE", "wrong HTTP Method parsed" ); assert.equal( batchOperationArray[1].path, "table161216830457901592", "wrong path parsed" ); assert.equal( batchOperationArray[1].uri, "http://127.0.0.1:11002/devstoreaccount1/table161216830457901592(PartitionKey=%27part1%27,RowKey=%27row161216830462204546%27)", "wrong url parsed" ); assert.equal( batchOperationArray[1].jsonRequestBody, "", "wrong jsonBody parsed" ); done(); }); it("deserializes, mock durable function request correctly", (done) => { const requestString = SerializationRequestMockStrings.BatchDurableE1HelloRequestString; const serializer = new TableBatchSerialization(); const batchOperationArray = serializer.deserializeBatchRequest( requestString ); // There are 5 operations in the batch assert.equal(batchOperationArray.length, 5); // First Batch Operation is an insert. assert.equal(batchOperationArray[0].batchType, BatchType.table); done(); }); // boundary tests it("finds the \\r\\n line ending boundary in a durable functions call", (done) => { const serializationBase = new BatchSerialization(); // extract batchBoundary serializationBase.extractLineEndings( SerializationRequestMockStrings.BatchDurableE1HelloRequestString ); assert.equal(serializationBase.lineEnding, "\r\n"); done(); }); it("finds the \\n line ending boundary in an SDK call", (done) => { const serializationBase = new BatchSerialization(); // extract batchBoundary serializationBase.extractLineEndings( SerializationRequestMockStrings.Sample3InsertsUsingSDK ); assert.equal(serializationBase.lineEnding, "\n"); done(); }); it("finds the batch boundary in a durable functions call", (done) => { const serializationBase = new BatchSerialization(); // extract batchBoundary serializationBase.extractBatchBoundary( SerializationRequestMockStrings.BatchDurableE1HelloRequestString ); assert.equal( serializationBase.batchBoundary, "--batch_35c74636-e91e-4c4f-9ab1-906881bf7d9d" ); done(); }); it("finds the changeset boundary in a durable functions call", (done) => { const serializationBase = new BatchSerialization(); serializationBase.extractChangeSetBoundary( SerializationRequestMockStrings.BatchDurableE1HelloRequestString ); assert.equal( serializationBase.changesetBoundary, "changeset_0ac4036e-9ea9-4dfc-90c3-66a95213b6b0" ); done(); }); it("finds the batch boundary in a single retrieve entity call", (done) => { const serializationBase = new BatchSerialization(); // extract batchBoundary serializationBase.extractBatchBoundary( SerializationRequestMockStrings.BatchQueryWithPartitionKeyAndRowKeyRequest ); assert.equal( serializationBase.batchBoundary, "--batch_d54a6553104c5b65f259aa178d324ebf" ); done(); }); it("finds the changeset boundary in a single retrieve entity call", (done) => { const serializationBase = new BatchSerialization(); serializationBase.extractChangeSetBoundary( SerializationRequestMockStrings.BatchQueryWithPartitionKeyAndRowKeyRequest ); assert.equal( serializationBase.changesetBoundary, "--batch_d54a6553104c5b65f259aa178d324ebf" ); done(); }); it("finds the changeset boundary in a non guid form", (done) => { const serializationBase = new BatchSerialization(); serializationBase.extractChangeSetBoundary( SerializationRequestMockStrings.BatchNonGuidBoundaryShortString ); assert.equal(serializationBase.changesetBoundary, "blahblah"); done(); }); it("deserializes the headers correctly for a batch request", (done) => { const sampleHeaders = [ "HTTP/1.1\r", "Accept: application/json;odata=minimalmetadata\r", "Content-Type: application/json\r", "Prefer: return-no-content\r", "DataServiceVersion: 3.0;\r", "\r", "" ]; // const headers1 = new BatchRequestHeaders(sampleHeaders1); const headers = new BatchRequestHeaders(sampleHeaders); assert.equal(headers.header("prefer"), "return-no-content"); done(); }); it("correctly parses paths from URIs", (done) => { // Account must be alphanumeric, and between 3 and 24 chars long // Table name must be alphanumeric, cannot begin with a number, // and must be between 3 and 63 characters long const uris = [ { uri: "http://127.0.0.1:10002/queuesdev/funcpcappdevHistory(PartitionKey='2d2c8fe4-d3a6-438f-aa83-382d93ee9569:ca',RowKey='0000000000000000')", path: "/queuesdev/funcpcappdevHistory" }, { uri: "http://127.0.0.1:10002/devaccountstore1/myTable(PartitionKey='1',RowKey='1ab')", path: "/devaccountstore1/myTable" }, { uri: "http://127.0.0.1:9999/my1accountstore99/my1Table(PartitionKey='2',RowKey='2')", path: "/my1accountstore99/my1Table" }, { uri: "http://127.0.0.1:9999/my1/my1Table9999999999999999999999999999999999999999999999999qw9999(PartitionKey='2',RowKey='2')", path: "/my1/my1Table9999999999999999999999999999999999999999999999999qw9999" } ]; const serializationBase = new BatchSerialization(); uris.forEach((value) => { const extractedPath = serializationBase.extractPath(value.uri); if (extractedPath !== null) { assert.strictEqual( extractedPath[0], value.path, "Uri path did not parse correctly!" ); } else { assert.notStrictEqual( null, extractedPath, "Unable to extract path, regex did not match!" ); } }); done(); }); });
the_stack
import * as protos from 'fabric-protos'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import * as chaiAsPromised from 'chai-as-promised'; import { EndorsementPolicy } from '../src/Policy'; chai.should(); chai.use(sinonChai); chai.use(chaiAsPromised); // tslint:disable:no-unused-expression describe('Policy', () => { let policy: EndorsementPolicy; let principalMemberA: protos.common.MSPPrincipal; let principalMemberB: protos.common.MSPPrincipal; let principalMemberC: protos.common.MSPPrincipal; let principalMemberD: protos.common.MSPPrincipal; let principalClientA: protos.common.MSPPrincipal; let principalPeerA: protos.common.MSPPrincipal; let principalPeerB: protos.common.MSPPrincipal; let principalAdminB: protos.common.MSPPrincipal; let principalAdminC: protos.common.MSPPrincipal; let principalOrdererC: protos.common.MSPPrincipal; let principalClientD: protos.common.MSPPrincipal; let signedByA: protos.common.SignaturePolicy; let signedByB: protos.common.SignaturePolicy; let signedByC: protos.common.SignaturePolicy; let signedByD: protos.common.SignaturePolicy; beforeEach(() => { policy = new EndorsementPolicy(); principalMemberA = new protos.common.MSPPrincipal(); principalMemberA.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleMemberA: protos.common.IMSPRole = {}; newRoleMemberA.role = protos.common.MSPRole.MSPRoleType.MEMBER; newRoleMemberA.msp_identifier = 'A'; principalMemberA.principal = protos.common.MSPRole.encode(newRoleMemberA).finish(); principalMemberB = new protos.common.MSPPrincipal(); principalMemberB.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleMemberB: protos.common.IMSPRole = {}; newRoleMemberB.role = protos.common.MSPRole.MSPRoleType.MEMBER; newRoleMemberB.msp_identifier = 'B'; principalMemberB.principal = protos.common.MSPRole.encode(newRoleMemberB).finish(); principalMemberC = new protos.common.MSPPrincipal(); principalMemberC.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleMemberC: protos.common.IMSPRole = {}; newRoleMemberC.role = protos.common.MSPRole.MSPRoleType.MEMBER; newRoleMemberC.msp_identifier = 'C'; principalMemberC.principal = protos.common.MSPRole.encode(newRoleMemberC).finish(); principalMemberD = new protos.common.MSPPrincipal(); principalMemberD.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleMemberD: protos.common.IMSPRole = {}; newRoleMemberD.role = protos.common.MSPRole.MSPRoleType.MEMBER; newRoleMemberD.msp_identifier = 'D'; principalMemberD.principal = protos.common.MSPRole.encode(newRoleMemberD).finish(); principalClientA = new protos.common.MSPPrincipal(); principalClientA.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleClientA: protos.common.IMSPRole = {}; newRoleClientA.role = protos.common.MSPRole.MSPRoleType.CLIENT; newRoleClientA.msp_identifier = 'A'; principalClientA.principal = protos.common.MSPRole.encode(newRoleClientA).finish(); principalPeerA = new protos.common.MSPPrincipal(); principalPeerA.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRolePeerA: protos.common.IMSPRole = {}; newRolePeerA.role = protos.common.MSPRole.MSPRoleType.PEER; newRolePeerA.msp_identifier = 'A'; principalPeerA.principal = protos.common.MSPRole.encode(newRolePeerA).finish(); principalPeerB = new protos.common.MSPPrincipal(); principalPeerB.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRolePeerB: protos.common.IMSPRole = {}; newRolePeerB.role = protos.common.MSPRole.MSPRoleType.PEER; newRolePeerB.msp_identifier = 'B'; principalPeerB.principal = protos.common.MSPRole.encode(newRolePeerB).finish(); principalAdminB = new protos.common.MSPPrincipal(); principalAdminB.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleAdminB: protos.common.IMSPRole = {}; newRoleAdminB.role = protos.common.MSPRole.MSPRoleType.ADMIN; newRoleAdminB.msp_identifier = 'B'; principalAdminB.principal = protos.common.MSPRole.encode(newRoleAdminB).finish(); principalAdminC = new protos.common.MSPPrincipal(); principalAdminC.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleAdminC: protos.common.IMSPRole = {}; newRoleAdminC.role = protos.common.MSPRole.MSPRoleType.ADMIN; newRoleAdminC.msp_identifier = 'C'; principalAdminC.principal = protos.common.MSPRole.encode(newRoleAdminC).finish(); principalOrdererC = new protos.common.MSPPrincipal(); principalOrdererC.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleOrdererC: protos.common.IMSPRole = {}; newRoleOrdererC.role = protos.common.MSPRole.MSPRoleType.ORDERER; newRoleOrdererC.msp_identifier = 'C'; principalOrdererC.principal = protos.common.MSPRole.encode(newRoleOrdererC).finish(); principalClientD = new protos.common.MSPPrincipal(); principalClientD.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleClientD: protos.common.IMSPRole = {}; newRoleClientD.role = protos.common.MSPRole.MSPRoleType.CLIENT; newRoleClientD.msp_identifier = 'D'; principalClientD.principal = protos.common.MSPRole.encode(newRoleClientD).finish(); signedByA = new protos.common.SignaturePolicy(); signedByA.signed_by = 0; signedByB = new protos.common.SignaturePolicy(); signedByB.signed_by = 1; signedByC = new protos.common.SignaturePolicy(); signedByC.signed_by = 2; signedByD = new protos.common.SignaturePolicy(); signedByD.signed_by = 3; }); it(`should parse "OutOf(1, 'A.member', 'B.member')" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`OutOf(1, 'A.member', 'B.member')`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalMemberA); principals.push(principalMemberB); const nOutOf: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOf.n = 1; const signaturePolicies: protos.common.SignaturePolicy[] = []; signaturePolicies.push(signedByA); signaturePolicies.push(signedByB); nOutOf.rules = signaturePolicies; const nOf: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOf.n_out_of = nOutOf; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOf; envelope.identities = principals; result.should.deep.equal(envelope); }); it(`should parse "OutOf(2, 'A.member', 'B.member')" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`OutOf(2, 'A.member', 'B.member')`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalMemberA); principals.push(principalMemberB); const nOutOf: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOf.n = 2; const signaturePolicies: protos.common.SignaturePolicy[] = []; signaturePolicies.push(signedByA); signaturePolicies.push(signedByB); nOutOf.rules = signaturePolicies; const nOf: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOf.n_out_of = nOutOf; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOf; envelope.identities = principals; result.should.deep.equal(envelope); }); it(`should parse "AND('A.member', 'B.member')" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`AND('A.member', 'B.member')`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalMemberA); principals.push(principalMemberB); const nOutOf: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOf.n = 2; const signaturePolicies: protos.common.SignaturePolicy[] = []; signaturePolicies.push(signedByA); signaturePolicies.push(signedByB); nOutOf.rules = signaturePolicies; const nOf: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOf.n_out_of = nOutOf; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOf; envelope.identities = principals; result.should.deep.equal(envelope); }); it(`should parse "AND('A.client', 'B.peer')" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`AND('A.client', 'B.peer')`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalClientA); principals.push(principalPeerB); const nOutOf: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOf.n = 2; const signaturePolicies: protos.common.SignaturePolicy[] = []; signaturePolicies.push(signedByA); signaturePolicies.push(signedByB); nOutOf.rules = signaturePolicies; const nOf: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOf.n_out_of = nOutOf; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOf; envelope.identities = principals; result.should.deep.equal(envelope); }); it(`should parse "OR('A.member', 'B.member')" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`OR('A.member', 'B.member')`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalMemberA); principals.push(principalMemberB); const nOutOf: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOf.n = 1; const signaturePolicies: protos.common.SignaturePolicy[] = []; signaturePolicies.push(signedByA); signaturePolicies.push(signedByB); nOutOf.rules = signaturePolicies; const nOf: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOf.n_out_of = nOutOf; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOf; envelope.identities = principals; result.should.deep.equal(envelope); }); it(`should parse "OR('A.member', AND('B.member', 'C.member'))" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`OR('A.member', AND('B.member', 'C.member'))`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalMemberA); principals.push(principalMemberB); principals.push(principalMemberC); const nOutOfAnd: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOfAnd.n = 2; const signaturePoliciesAnd: protos.common.SignaturePolicy[] = []; signaturePoliciesAnd.push(signedByB); signaturePoliciesAnd.push(signedByC); nOutOfAnd.rules = signaturePoliciesAnd; const nOfAnd: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOfAnd.n_out_of = nOutOfAnd; const nOutOfOr: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOfOr.n = 1; const signaturePoliciesOr: protos.common.SignaturePolicy[] = []; signaturePoliciesOr.push(signedByA); signaturePoliciesOr.push(nOfAnd); nOutOfOr.rules = signaturePoliciesOr; const nOfOr: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOfOr.n_out_of = nOutOfOr; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOfOr; envelope.identities = principals; result.should.deep.equal(envelope); }); it(`should parse "AND(OR('A.member', 'B.member'), OR('B.member', 'C.member'))" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`AND(OR('A.member', 'B.member'), OR('B.member', 'C.member'))`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalMemberA); principals.push(principalMemberB); principals.push(principalMemberC); const nOutOfFirstOr: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOfFirstOr.n = 1; const signaturePoliciesFirstOr: protos.common.SignaturePolicy[] = []; signaturePoliciesFirstOr.push(signedByA); signaturePoliciesFirstOr.push(signedByB); nOutOfFirstOr.rules = signaturePoliciesFirstOr; const nOfFirstOr: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOfFirstOr.n_out_of = nOutOfFirstOr; const nOutOfSecondOr: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOfSecondOr.n = 1; const signaturePoliciesSecondOr: protos.common.SignaturePolicy[] = []; signaturePoliciesSecondOr.push(signedByB); signaturePoliciesSecondOr.push(signedByC); nOutOfSecondOr.rules = signaturePoliciesSecondOr; const nOfSecondOr: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOfSecondOr.n_out_of = nOutOfSecondOr; const nOutOfAnd: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOfAnd.n = 2; const signaturePoliciesAnd: protos.common.SignaturePolicy[] = []; signaturePoliciesAnd.push(nOfFirstOr); signaturePoliciesAnd.push(nOfSecondOr); nOutOfAnd.rules = signaturePoliciesAnd; const nOfAnd: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOfAnd.n_out_of = nOutOfAnd; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOfAnd; envelope.identities = principals; result.should.deep.equal(envelope); }); it(`should parse "OR(AND('A.member', 'B.member'), OR('C.admin', 'D.member'))" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`OR(AND('A.member', 'B.member'), OR('C.admin', 'D.member'))`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalMemberA); principals.push(principalMemberB); principals.push(principalAdminC); principals.push(principalMemberD); const nOutOfAnd: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOfAnd.n = 2; const signaturePoliciesAnd: protos.common.SignaturePolicy[] = []; signaturePoliciesAnd.push(signedByA); signaturePoliciesAnd.push(signedByB); nOutOfAnd.rules = signaturePoliciesAnd; const nOfAnd: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOfAnd.n_out_of = nOutOfAnd; const nOutOfOr: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOfOr.n = 1; const signaturePoliciesOr: protos.common.SignaturePolicy[] = []; signaturePoliciesOr.push(signedByC); signaturePoliciesOr.push(signedByD); nOutOfOr.rules = signaturePoliciesOr; const nOfOr: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOfOr.n_out_of = nOutOfOr; const nOutOfOuterOr: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOfOuterOr.n = 1; const signaturePoliciesOuterOr: protos.common.SignaturePolicy[] = []; signaturePoliciesOuterOr.push(nOfAnd); signaturePoliciesOuterOr.push(nOfOr); nOutOfOuterOr.rules = signaturePoliciesOuterOr; const nOfOuterOr: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOfOuterOr.n_out_of = nOutOfOuterOr; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOfOuterOr; envelope.identities = principals; result.should.deep.equal(envelope); }); it(`should parse "OR('MSP.member', 'MSP.WITH.DOTS.member', 'MSP-WITH-DASHES.member')" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`OR('MSP.member', 'MSP.WITH.DOTS.member', 'MSP-WITH-DASHES.member')`); const principals: protos.common.MSPPrincipal[] = []; const principalMemberMSP: protos.common.MSPPrincipal = new protos.common.MSPPrincipal(); principalMemberMSP.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleMemberMSP: protos.common.IMSPRole = {}; newRoleMemberMSP.role = protos.common.MSPRole.MSPRoleType.MEMBER; newRoleMemberMSP.msp_identifier = 'MSP'; principalMemberMSP.principal = protos.common.MSPRole.encode(newRoleMemberMSP).finish(); principals.push(principalMemberMSP); const principalMemberMSPWithDots: protos.common.MSPPrincipal = new protos.common.MSPPrincipal(); principalMemberMSPWithDots.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleMemberMSPWithDots: protos.common.IMSPRole = {}; newRoleMemberMSPWithDots.role = protos.common.MSPRole.MSPRoleType.MEMBER; newRoleMemberMSPWithDots.msp_identifier = 'MSP.WITH.DOTS'; principalMemberMSPWithDots.principal = protos.common.MSPRole.encode(newRoleMemberMSPWithDots).finish(); principals.push(principalMemberMSPWithDots); const principalMemberMSPWithDashes: protos.common.MSPPrincipal = new protos.common.MSPPrincipal(); principalMemberMSPWithDashes.principal_classification = protos.common.MSPPrincipal.Classification.ROLE; const newRoleMemberMSPWithDashes: protos.common.IMSPRole = {}; newRoleMemberMSPWithDashes.role = protos.common.MSPRole.MSPRoleType.MEMBER; newRoleMemberMSPWithDashes.msp_identifier = 'MSP-WITH-DASHES'; principalMemberMSPWithDashes.principal = protos.common.MSPRole.encode(newRoleMemberMSPWithDashes).finish(); principals.push(principalMemberMSPWithDashes); const nOutOf: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOf.n = 1; const signaturePolicies: protos.common.SignaturePolicy[] = []; const signedByMSP: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); signedByMSP.signed_by = 0; const signedByMSPWithDots: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); signedByMSPWithDots.signed_by = 1; const signedByMSPWithDashes: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); signedByMSPWithDashes.signed_by = 2; signaturePolicies.push(signedByMSP); signaturePolicies.push(signedByMSPWithDots); signaturePolicies.push(signedByMSPWithDashes); nOutOf.rules = signaturePolicies; const nOf: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOf.n_out_of = nOutOf; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOf; envelope.identities = principals; result.should.deep.equal(envelope); }); it(`should parse "OR('A.peer', 'B.admin', 'C.orderer', 'D.client')" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`OR('A.peer', 'B.admin', 'C.orderer', 'D.client')`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalPeerA); principals.push(principalAdminB); principals.push(principalOrdererC); principals.push(principalClientD); const nOutOf: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOf.n = 1; const signaturePolicies: protos.common.SignaturePolicy[] = []; signaturePolicies.push(signedByA); signaturePolicies.push(signedByB); signaturePolicies.push(signedByC); signaturePolicies.push(signedByD); nOutOf.rules = signaturePolicies; const nOf: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOf.n_out_of = nOutOf; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOf; envelope.identities = principals; result.should.deep.equal(envelope); }); it(`should parse "OutOf('1', 'A.member', 'B.member')" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`OutOf('1', 'A.member', 'B.member')`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalMemberA); principals.push(principalMemberB); const nOutOf: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOf.n = 1; const signaturePolicies: protos.common.SignaturePolicy[] = []; signaturePolicies.push(signedByA); signaturePolicies.push(signedByB); nOutOf.rules = signaturePolicies; const nOf: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOf.n_out_of = nOutOf; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOf; envelope.identities = principals; result.should.deep.equal(envelope); }); it('should error if no mspid', () => { (() => policy.buildPolicy(`OR('A.member', Bmember)`)).should.throw(`Expected "'", "AND", "OR", or "OutOf" but "B" found`); }); it('should error if empty policy', () => { (() => policy.buildPolicy(``)).should.throw('Expected "AND", "OR", or "OutOf" but end of input found'); }); it('should error if not enough args for out of', () => { (() => policy.buildPolicy(`OutOf(1)`)).should.throw('Expected "," but ")" found'); }); it('should error if second arg is not a string for out of', () => { (() => policy.buildPolicy(`OutOf(1, 2)`)).should.throw(`Expected "'", "AND", "OR", or "OutOf" but "2" found`); }); it('should error if second arg is not a expression for out of', () => { (() => policy.buildPolicy(`OutOf(1, true)`)).should.throw(`Expected "'", "AND", "OR", or "OutOf" but "t" found`); }); it('should error if bad value for count for out of', () => { (() => policy.buildPolicy(`OutOf(-1, 'A.member', 'B.member')`)).should.throw('Expected integer but "-" found'); }); it(`should parse "OutOf(0, 'A.member', 'B.member')" correctly`, () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`OutOf(0, 'A.member', 'B.member')`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalMemberA); principals.push(principalMemberB); const nOutOf: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOf.n = 0; const signaturePolicies: protos.common.SignaturePolicy[] = []; signaturePolicies.push(signedByA); signaturePolicies.push(signedByB); nOutOf.rules = signaturePolicies; const nOf: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOf.n_out_of = nOutOf; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOf; envelope.identities = principals; result.should.deep.equal(envelope); }); it('should parse "OutOf(3, \'A.member\', \'B.member\')" correctly', () => { const result: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(`OutOf(3, 'A.member', 'B.member')`); const principals: protos.common.MSPPrincipal[] = []; principals.push(principalMemberA); principals.push(principalMemberB); const nOutOf: protos.common.SignaturePolicy.NOutOf = new protos.common.SignaturePolicy.NOutOf(); nOutOf.n = 3; const signaturePolicies: protos.common.SignaturePolicy[] = []; signaturePolicies.push(signedByA); signaturePolicies.push(signedByB); nOutOf.rules = signaturePolicies; const nOf: protos.common.SignaturePolicy = new protos.common.SignaturePolicy(); nOf.n_out_of = nOutOf; const envelope: protos.common.SignaturePolicyEnvelope = new protos.common.SignaturePolicyEnvelope(); envelope.version = 0; envelope.rule = nOf; envelope.identities = principals; result.should.deep.equal(envelope); }); it('should error count for out of is > n+1', () => { (() => policy.buildPolicy(`OutOf(4, 'A.member', 'B.member')`)).should.throw(`Expected OutOf count is too large but "OutOf(4, 'A.member', 'B.member')" found`); }); });
the_stack
import './index'; import { $, $$ } from 'common-sk/modules/dom'; import fetchMock from 'fetch-mock'; import { expect } from 'chai'; import { eventPromise, expectQueryStringToEqual, setQueryString, setUpElementUnderTest, } from '../../../infra-sk/modules/test_util'; import { sampleByTestList } from './test_data'; import { testOnlySetSettings } from '../settings'; import { ListPageSk } from './list-page-sk'; import { CorpusSelectorSk } from '../corpus-selector-sk/corpus-selector-sk'; import { QueryDialogSk } from '../query-dialog-sk/query-dialog-sk'; import { QueryDialogSkPO } from '../query-dialog-sk/query-dialog-sk_po'; import { CorpusSelectorSkPO } from '../corpus-selector-sk/corpus-selector-sk_po'; describe('list-page-sk', () => { const newInstance = setUpElementUnderTest<ListPageSk>('list-page-sk'); let listPageSk: ListPageSk; let queryDialogSkPO: QueryDialogSkPO; let corpusSelectorSkPO: CorpusSelectorSkPO; beforeEach(async () => { // Clear out any query params we might have to not mess with our current state. setQueryString(''); testOnlySetSettings({ defaultCorpus: 'gm', }); // These will get called on page load. fetchMock.get('/json/v2/list?corpus=gm', sampleByTestList); // We only need a few params to make sure the edit-ignore-rule-dialog works properly and it // does not matter really what they are, so we use a small subset of actual params. const someParams = { alpha_type: ['Opaque', 'Premul'], arch: ['arm', 'arm64', 'x86', 'x86_64'], source_type: ['canvaskit', 'gm', 'corpus with spaces'], }; fetchMock.get('/json/v2/paramset', someParams); const event = eventPromise('end-task'); listPageSk = newInstance(); await event; queryDialogSkPO = new QueryDialogSkPO(listPageSk.querySelector<QueryDialogSk>('query-dialog-sk')!); corpusSelectorSkPO = new CorpusSelectorSkPO( listPageSk.querySelector<CorpusSelectorSk<string>>('corpus-selector-sk')!, ); }); afterEach(() => { expect(fetchMock.done()).to.be.true; // All mock RPCs called at least once. // Completely remove the mocking which allows each test // to be able to mess with the mocked routes w/o impacting other tests. fetchMock.reset(); }); describe('html layout', () => { it('should make a table with 2 rows in the body', () => { const rows = $('table tbody tr', listPageSk); expect(rows).to.have.length(2); }); it('should have 3 corpora loaded in, with the default selected', async () => { expect(await corpusSelectorSkPO.getCorpora()).to.have.length(3); expect(await corpusSelectorSkPO.getSelectedCorpus()).to.equal('gm'); }); it('does not have source_type (corpus) in the params', () => { // Field "paramset" is private, thus the cast to any. Is this test really necessary? expect((listPageSk as any).paramset.source_type).to.be.undefined; }); const expectedSearchPageHref = (opts: { positive: boolean, negative: boolean, untriaged: boolean, disregardIgnoreRules: boolean }): string => `/search?${[ 'corpus=gm', `include_ignored=${opts.disregardIgnoreRules}`, 'left_filter=name%3Dthis_is_another_test', 'max_rgba=0', 'min_rgba=0', `negative=${opts.negative}`, 'not_at_head=false', `positive=${opts.positive}`, 'reference_image_required=false', 'right_filter=', 'sort=descending', `untriaged=${opts.untriaged}`, ].join('&')}`; const expectedClusterPageHref = (opts: {disregardIgnoreRules: boolean}): string => `/cluster?${[ 'corpus=gm', 'grouping=this_is_another_test', `include_ignored=${opts.disregardIgnoreRules}`, 'left_filter=', 'max_rgba=0', 'min_rgba=0', 'negative=true', 'not_at_head=false', 'positive=true', 'reference_image_required=false', 'right_filter=', 'sort=descending', 'untriaged=true', ].join('&')}`; it('should have links for searching and the cluster view', () => { const secondRow = $$<HTMLTableRowElement>('table tbody tr:nth-child(2)', listPageSk)!; const links = $<HTMLAnchorElement>('a', secondRow)!; expect(links).to.have.length(6); // First link should be to the search results for all digests. expect(links[0].getAttribute('href')).to.equal(expectedSearchPageHref({ positive: true, negative: true, untriaged: true, disregardIgnoreRules: false, })); // Second link should be just positive digests. expect(links[1].getAttribute('href')).to.equal(expectedSearchPageHref({ positive: true, negative: false, untriaged: false, disregardIgnoreRules: false, })); // Third link should be just negative digests. expect(links[2].getAttribute('href')).to.equal(expectedSearchPageHref({ positive: false, negative: true, untriaged: false, disregardIgnoreRules: false, })); // Fourth link should be just untriaged digests. expect(links[3].getAttribute('href')).to.equal(expectedSearchPageHref({ positive: false, negative: false, untriaged: true, disregardIgnoreRules: false, })); // Fifth link is the total count, and should be the same as the first link. expect(links[4].getAttribute('href')).to.equal(expectedSearchPageHref({ positive: true, negative: true, untriaged: true, disregardIgnoreRules: false, })); // Sixth link should be to cluster view expect(links[5].getAttribute('href')).to.equal( expectedClusterPageHref({ disregardIgnoreRules: false }), ); }); it('updates the links based on toggle positions', async () => { fetchMock.get('/json/v2/list?corpus=gm&include_ignored_traces=true', sampleByTestList); await clickDisregardIgnoreRulesCheckbox(listPageSk); const secondRow = $$<HTMLTableRowElement>('table tbody tr:nth-child(2)', listPageSk)!; const links = $('a', secondRow); expect(links).to.have.length(6); // First link should be to the search results for all digests. expect(links[0].getAttribute('href')).to.equal(expectedSearchPageHref({ positive: true, negative: true, untriaged: true, disregardIgnoreRules: true, })); // Second link should be just positive digests. expect(links[1].getAttribute('href')).to.equal(expectedSearchPageHref({ positive: true, negative: false, untriaged: false, disregardIgnoreRules: true, })); // Third link should be just negative digests. expect(links[2].getAttribute('href')).to.equal(expectedSearchPageHref({ positive: false, negative: true, untriaged: false, disregardIgnoreRules: true, })); // Fourth link should be just untriaged digests. expect(links[3].getAttribute('href')).to.equal(expectedSearchPageHref({ positive: false, negative: false, untriaged: true, disregardIgnoreRules: true, })); // Fifth link is the total count, and should be the same as the first link. expect(links[4].getAttribute('href')).to.equal(expectedSearchPageHref({ positive: true, negative: true, untriaged: true, disregardIgnoreRules: true, })); // Sixth link should be to cluster view expect(links[5].getAttribute('href')).to.equal( expectedClusterPageHref({ disregardIgnoreRules: true }), ); }); it('updates the sort order by clicking on sort-toggle-sk', async () => { let firstRow = $$<HTMLTableRowElement>('table tbody tr:nth-child(1)', listPageSk)!; expect($$<HTMLTableDataCellElement>('td', firstRow)!.innerText).to.equal('this_is_a_test'); // After first click, it will be sorting in descending order by number of negatives. clickOnNegativeHeader(listPageSk); firstRow = $$<HTMLTableRowElement>('table tbody tr:nth-child(1)', listPageSk)!; expect($$<HTMLTableDataCellElement>('td', firstRow)!.innerText) .to.equal('this_is_another_test'); // After second click, it will be sorting in ascending order by number of negatives. clickOnNegativeHeader(listPageSk); firstRow = $$<HTMLTableRowElement>('table tbody tr:nth-child(1)', listPageSk)!; expect($$<HTMLTableDataCellElement>('td', firstRow)!.innerText).to.equal('this_is_a_test'); }); }); // end describe('html layout') describe('RPC calls', () => { it('has a checkbox to toggle use of ignore rules', async () => { fetchMock.get( '/json/v2/list?corpus=gm&include_ignored_traces=true', sampleByTestList, ); await clickDisregardIgnoreRulesCheckbox(listPageSk); expectQueryStringToEqual('?corpus=gm&disregard_ignores=true'); }); it('changes the corpus based on an event from corpus-selector-sk', async () => { fetchMock.get( '/json/v2/list?corpus=corpus%20with%20spaces', sampleByTestList, ); const event = eventPromise('end-task'); await corpusSelectorSkPO.clickCorpus('corpus with spaces'); await event; expectQueryStringToEqual('?corpus=corpus%20with%20spaces'); }); it('changes the search params based on an event from query-dialog-sk', async () => { fetchMock.get( '/json/v2/list?' + 'corpus=gm&trace_values=alpha_type%3DOpaque%26arch%3Darm64', sampleByTestList, ); const event = eventPromise('end-task'); $$<HTMLButtonElement>('.show_query_dialog', listPageSk)!.click(); await queryDialogSkPO.setSelection({ alpha_type: ['Opaque'], arch: ['arm64'] }); await queryDialogSkPO.clickShowMatchesBtn(); await event; expectQueryStringToEqual('?corpus=gm&query=alpha_type%3DOpaque%26arch%3Darm64'); }); }); }); function clickOnNegativeHeader(ele: ListPageSk) { $$<HTMLTableHeaderCellElement>('table > thead > tr > th:nth-child(3)', ele)!.click(); } async function clickDisregardIgnoreRulesCheckbox(listPageSk: ListPageSk) { const checkbox = $$<HTMLInputElement>('checkbox-sk.ignore_rules input', listPageSk)!; const event = eventPromise('end-task'); checkbox.click(); await event; }
the_stack
import {Component, ElementRef, ViewChild, AfterViewInit, Input, ChangeDetectorRef} from '@angular/core'; import * as ts from 'typescript'; import {FileConfig} from '../codelab/file-config'; import {StateService, selectedExercise} from '../codelab/state.service'; import {LoopProtectionService} from '../loop-protection.service'; import {ScriptLoaderService} from '../script-loader.service'; import {Subscription} from 'rxjs'; import {AppConfigService} from '../app-config.service'; import {ExerciseConfig} from '../codelab/exercise-config'; let cachedIframes = {}; function jsInjector(iframe) { return function (script) { iframe.contentWindow.eval(script); } } function jsScriptInjector(iframe) { return function (code) { const script = document.createElement('script'); script.type = "text/javascript"; script.innerHTML = code; iframe.contentWindow.document.head.appendChild(script); } } function cssInjector(iframe) { return function (css) { const s = iframe.contentDocument.createElement("style"); s.innerHTML = css; iframe.contentDocument.getElementsByTagName("head")[0].appendChild(s); } } interface IframeConfig { id: string, url: string, restart?: boolean, hidden?: boolean } function createIframe(config: IframeConfig) { const iframe = document.createElement('iframe'); iframe.setAttribute('sandbox', 'allow-modals allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts'); iframe.setAttribute('frameBorder', '0'); iframe.setAttribute('src', config.url); iframe.setAttribute('class', config.id); iframe.setAttribute('style', 'width: 500px; height: 100%'); return iframe; } function injectIframe(element: any, config: IframeConfig, runner: RunnerComponent): Promise<{ setHtml: Function, register: Function, runMultipleFiles: Function, runSingleFile: Function, runSingleScriptFile: Function, loadSystemJS: Function, injectSystemJs: Function }> { if (cachedIframes[config.id]) { cachedIframes[config.id].remove(); delete cachedIframes[config.id]; } const iframe = createIframe(config); cachedIframes[config.id] = iframe; element.appendChild(iframe); const runJs = jsScriptInjector(iframe); let index = 0; return new Promise((resolve, reject) => { if (!iframe.contentWindow) { return reject('iframe is gone'); } iframe.contentWindow.onload = () => { iframe.contentWindow.console.log = function () { console.log.apply(console, arguments); }; const setHtml = (html) => { iframe.contentDocument.body.innerHTML = html; }; const displayError = (error, info) => { if (!runner.appConfig.config.noerrors) { console.log(info, error); } const escaped = (document.createElement('a').appendChild( document.createTextNode(error)).parentNode as any).innerHTML; setHtml(` <div style = "border-top: 1px #888 dotted; padding-top: 4px; margin-top: 4px">Check out your browser console to see the full error!</div> <pre>${escaped}</pre>`); }; iframe.contentWindow.console.error = function (error, message) { // handle angular error 1/3 displayError(error, 'Angular Error'); }; function register(name, code) { (iframe.contentWindow as any).System.register(name, [], function (exports) { return { setters: [], execute: function () { exports(code); } } }); } resolve({ register: register, injectSystemJs: () => { const systemCode = runner.scriptLoaderService.getScript('SystemJS'); // SystemJS expects document.baseURI to be set on the document. // Since it's a readonly property, I'm faking whole document property. const wrappedSystemCode = ` (function(document){ ${systemCode} }({ getElementsByTagName: document.getElementsByTagName.bind(document), head:document.head, body: document.body, documentElement: document.documentElement, createElement: document.createElement.bind(document), baseURI: '${document.baseURI}' })); `; jsScriptInjector(iframe)(wrappedSystemCode); }, runSingleScriptFile: jsScriptInjector(iframe), runSingleFile: runJs, setHtml: setHtml, loadSystemJS: (name) => { (iframe.contentWindow as any).loadSystemModule(name, runner.scriptLoaderService.getScript(name)); }, runMultipleFiles: (files: Array<FileConfig>) => { index++; (iframe.contentWindow as any).System.register('code', [], function (exports) { return { setters: [], execute: function () { exports('ts', ts); files.forEach((file) => { exports(file.path.replace(/[\/\.-]/gi, '_'), file.code); exports(file.path.replace(/[\/\.-]/gi, '_') + '_AST', ts.createSourceFile(file.path, file.code, ts.ScriptTarget.ES5)); }); } } }); files.map(file => { if (!file.path) { debugger } }); files.filter(file => file.path.indexOf('index.html') >= 0).map((file => { setHtml(file.code) })); files.filter(file => file.type === 'typescript').map((file) => { // Update module names let code = file.code; code = runner.loopProtectionService.protect(file.path, code); if (file.before) { code = file.before + ';\n' + code; } if (file.after) { code = ';\n' + code + file.after; } const moduleName = file.moduleName; // TODO(kirjs): Add source maps. const result = ts.transpileModule(code, { compilerOptions: { module: ts.ModuleKind.System, target: ts.ScriptTarget.ES5, experimentalDecorators: true, emitDecoratorMetadata: true, noImplicitAny: true, declaration: true, // TODO: figure out why this doesn't work inlineSourceMap: true, inlineSources: true, sourceMap: true }, fileName: moduleName, moduleName: moduleName, reportDiagnostics: true }); return result; }).map((compiled) => { runJs(compiled.outputText); }); files.filter((file) => file.bootstrap).map((file) => { const moduleName = file.moduleName; runJs(`System.import('${moduleName}')`); }); } }); }; if (config.url === 'about:blank') { iframe.contentWindow.onload({} as any); } }); } @Component({ selector: 'app-runner', templateUrl: './runner.component.html', styleUrls: ['./runner.component.css'] }) export class RunnerComponent implements AfterViewInit { @Input() files: Array<FileConfig>; @Input() runnerType: string; html = `<my-app></my-app>`; @ViewChild('runner') element: ElementRef; private stateSubscription: Subscription; private handleMessageBound: any; public System: any; constructor(private changeDetectionRef: ChangeDetectorRef, private state: StateService, public loopProtectionService: LoopProtectionService, public scriptLoaderService: ScriptLoaderService, public appConfig: AppConfigService) { this.handleMessageBound = this.handleMessage.bind(this); window.addEventListener("message", this.handleMessageBound, false); } handleMessage(event) { if (!event.data || !event.data.type) { return; } if (event.data.type === 'testList') { this.state.setTestList(event.data.tests); } if (event.data.type === 'testEnd') { this.state.endTests(); } if (event.data.type === 'testResult') { this.state.updateSingleTestResult({ title: event.data.test.title, pass: event.data.pass, result: event.data.result }); } this.changeDetectionRef.detectChanges(); } runCode(exercise: ExerciseConfig) { const time = (new Date()).getTime(); const runner = exercise.runner; const files = exercise.files; if (runner === 'Angular') { injectIframe(this.element.nativeElement, { id: 'preview', 'url': 'about:blank' }, this).then((sandbox) => { sandbox.setHtml(this.html); sandbox.runSingleFile(this.scriptLoaderService.getScript('shim')); sandbox.runSingleFile(this.scriptLoaderService.getScript('zone')); sandbox.injectSystemJs(); sandbox.runSingleScriptFile(this.scriptLoaderService.getScript('system-config')); sandbox.loadSystemJS('ng-bundle'); sandbox.register('reflect-metadata', Reflect); sandbox.runMultipleFiles(files.filter(file => !file.test)); }); injectIframe(this.element.nativeElement, { id: 'testing', 'url': 'about:blank' }, this).then((sandbox) => { sandbox.setHtml(this.html); sandbox.runSingleFile(this.scriptLoaderService.getScript('shim')); sandbox.runSingleFile(this.scriptLoaderService.getScript('zone')); sandbox.runSingleScriptFile(this.scriptLoaderService.getScript('chai')); sandbox.injectSystemJs(); sandbox.runSingleScriptFile(this.scriptLoaderService.getScript('system-config')); sandbox.runSingleScriptFile(this.scriptLoaderService.getScript('mocha')); sandbox.runSingleFile(this.scriptLoaderService.getScript('test-bootstrap')); sandbox.loadSystemJS('ng-bundle'); sandbox.register('reflect-metadata', Reflect); const testFiles = files .filter(file => !file.excludeFromTesting); sandbox.runMultipleFiles(testFiles); }); } else if (runner === 'TypeScript') { injectIframe(this.element.nativeElement, { id: 'preview', 'url': 'about:blank' }, this).then((sandbox) => { sandbox.injectSystemJs(); sandbox.runMultipleFiles(files.filter(file => !file.test)); }); injectIframe(this.element.nativeElement, { id: 'testing', 'url': 'about:blank' }, this).then((sandbox) => { console.log('FRAME CREATED', (new Date()).getTime() - time); sandbox.injectSystemJs(); sandbox.runSingleScriptFile(this.scriptLoaderService.getScript('mocha')); sandbox.runSingleScriptFile(this.scriptLoaderService.getScript('chai')); sandbox.runSingleScriptFile(this.scriptLoaderService.getScript('test-bootstrap')); const testFiles = files .filter(file => !file.excludeFromTesting); sandbox.runMultipleFiles(testFiles); }); } } ngOnDestroy() { Object.keys(cachedIframes).map(key => cachedIframes[key].remove()); window.removeEventListener("message", this.handleMessageBound, false); this.stateSubscription.unsubscribe(); } ngAfterViewInit() { this.stateSubscription = this.state.update .distinctUntilChanged((a, b) => a === b, e => e.local.runId) .subscribe((state) => { this.runCode(selectedExercise(state)) }, () => { debugger }); } }
the_stack
import type { Participations } from '@guardian/ab-core'; import { clearPermutiveSegments, getPermutiveSegments, } from '@guardian/commercial-core'; import { cmp, onConsentChange } from '@guardian/consent-management-platform'; import type { ConsentState } from '@guardian/consent-management-platform/dist/types'; import type { TCFv2ConsentList } from '@guardian/consent-management-platform/dist/types/tcfv2'; import type { CountryCode } from '@guardian/libs'; import { getCookie, isObject, isString, log, storage } from '@guardian/libs'; import { once } from 'lodash-es'; import config from '../../../../lib/config'; import { getReferrer as detectGetReferrer } from '../../../../lib/detect'; import { getTweakpoint, getViewport } from '../../../../lib/detect-viewport'; import { getCountryCode } from '../../../../lib/geolocation'; import { removeFalseyValues } from '../../../commercial/modules/header-bidding/utils'; import { getSynchronousParticipations } from '../experiments/ab'; import { isUserLoggedIn } from '../identity/api'; import { commercialFeatures } from './commercial-features'; // https://admanager.google.com/59666047#inventory/custom_targeting/list type TrueOrFalse = 't' | 'f'; type PartialWithNulls<T> = { [P in keyof T]?: T[P] | null }; const frequency = [ '0', '1', '2', '3', '4', '5', '6-9', '10-15', '16-19', '20-29', '30plus', ] as const; const adManagerGroups = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', ] as const; type Frequency = typeof frequency[number]; type AdManagerGroup = typeof adManagerGroups[number]; type ContentType = | 'video' | 'tag' | 'section' | 'network-front' | 'liveblog' | 'interactive' | 'gallery' | 'crossword' | 'audio' | 'article'; type PageTargeting = PartialWithNulls<{ ab: string[]; at: string; // Ad Test bl: string[]; // BLog tags bp: 'mobile' | 'tablet' | 'desktop'; // BreakPoint cc: CountryCode; // Country Code co: string; // COntributor ct: ContentType; dcre: TrueOrFalse; // DotCom-Rendering Eligible edition: 'uk' | 'us' | 'au' | 'int'; k: string[]; // Keywords p: 'r2' | 'ng' | 'app' | 'amp'; // Platform (web) pa: TrueOrFalse; // Personalised Ads consent permutive: string[]; // predefined segment values pv: string; // ophan Page View id rp: 'dotcom-rendering' | 'dotcom-platform'; // Rendering Platform sens: TrueOrFalse; // SenSitive si: TrueOrFalse; // Signed In skinsize: 'l' | 's'; su: string; // SUrging article tn: string; // ToNe url: string; urlkw: string[]; // URL KeyWords vl: string; // Video Length rdp: string; consent_tcfv2: string; cmp_interaction: string; se: string; // SEries ob: 't'; // OBserver content br: 's' | 'p' | 'f'; // BRanding af: 't'; // Ad Free fr: Frequency; // FRequency ref: string; // REFerrer inskin: TrueOrFalse; // InSkin amtgrp: AdManagerGroup; s: string; // site Section // And more [_: string]: string | string[]; }>; let myPageTargeting: PageTargeting = {}; let latestCmpHasInitialised: boolean; let latestCMPState: ConsentState | null = null; const AMTGRP_STORAGE_KEY = 'gu.adManagerGroup'; const findBreakpoint = (): 'mobile' | 'tablet' | 'desktop' => { const width = getViewport().width; switch (getTweakpoint(width)) { case 'mobile': case 'mobileMedium': case 'mobileLandscape': return 'mobile'; case 'phablet': case 'tablet': return 'tablet'; case 'desktop': case 'leftCol': case 'wide': return 'desktop'; } }; const skinsizeTargeting = () => { const vp = getViewport(); return vp.width >= 1560 ? 'l' : 's'; }; const inskinTargeting = (): TrueOrFalse => { // Don’t show inskin if we cannot tell if a privacy message will be shown if (!cmp.hasInitialised()) return 'f'; return cmp.willShowPrivacyMessageSync() ? 'f' : 't'; }; const abParam = (): string[] => { const abParticipations: Participations = getSynchronousParticipations(); const abParams: string[] = []; const pushAbParams = (testName: string, testValue: unknown): void => { if (typeof testValue === 'string' && testValue !== 'notintest') { const testData = `${testName}-${testValue}`; // DFP key-value pairs accept value strings up to 40 characters long abParams.push(testData.substring(0, 40)); } }; Object.keys(abParticipations).forEach((testKey: string): void => { const testValue: { variant: string; } = abParticipations[testKey]; pushAbParams(testKey, testValue.variant); }); const tests = window.guardian.config.tests; if (isObject(tests)) { Object.entries(tests).forEach(([testName, testValue]) => { pushAbParams(testName, testValue); }); } return abParams; }; const getFrequencyValue = (): Frequency => { const visitCount: number = parseInt( storage.local.getRaw('gu.alreadyVisited') ?? '0', 10, ); if (visitCount <= 5) { return frequency[visitCount]; } else if (visitCount >= 6 && visitCount <= 9) { return '6-9'; } else if (visitCount >= 10 && visitCount <= 15) { return '10-15'; } else if (visitCount >= 16 && visitCount <= 19) { return '16-19'; } else if (visitCount >= 20 && visitCount <= 29) { return '20-29'; } else if (visitCount >= 30) { return '30plus'; } return '0'; }; const getReferrer = (): string | null => { type MatchType = { id: string; match: string; }; const referrerTypes: MatchType[] = [ { id: 'facebook', match: 'facebook.com', }, { id: 'twitter', match: 't.co/', }, // added (/) because without slash it is picking up reddit.com too { id: 'reddit', match: 'reddit.com', }, { id: 'google', match: 'www.google', }, ]; const matchedRef: MatchType = referrerTypes.filter((referrerType) => detectGetReferrer().includes(referrerType.match), )[0] || {}; return matchedRef.id; }; const getUrlKeywords = (pageId?: string): string[] => { if (!pageId) return []; const segments = pageId.split('/'); const noEmptyStrings = segments.filter(Boolean); // This handles a trailing slash const keywords = noEmptyStrings.length > 0 ? noEmptyStrings[noEmptyStrings.length - 1].split('-') : []; return keywords; }; const formatAppNexusTargeting = (obj: Record<string, string | string[]>) => { const asKeyValues = Object.entries(obj).map((entry) => { const [key, value] = entry; return Array.isArray(value) ? value.map((nestedValue) => `${key}=${nestedValue}`) : `${key}=${value}`; }); const flattenDeep = Array.prototype.concat.apply([], asKeyValues); return flattenDeep.join(','); }; const buildAppNexusTargetingObject = once( (pageTargeting: PageTargeting): Record<string, string | string[]> => removeFalseyValues({ sens: pageTargeting.sens, pt1: pageTargeting.url, pt2: pageTargeting.edition, pt3: pageTargeting.ct, pt4: pageTargeting.p, pt5: pageTargeting.k, pt6: pageTargeting.su, pt7: pageTargeting.bp, pt9: [pageTargeting.pv, pageTargeting.co, pageTargeting.tn].join( '|', ), permutive: pageTargeting.permutive, }), ); const buildAppNexusTargeting = once((pageTargeting: PageTargeting): string => formatAppNexusTargeting(buildAppNexusTargetingObject(pageTargeting)), ); const getRdpValue = (ccpaState: boolean | null): string => { if (ccpaState === null) { return 'na'; } return ccpaState ? 't' : 'f'; }; const consentedToAllPurposes = (consents: TCFv2ConsentList): boolean => { return ( Object.keys(consents).length > 0 && Object.values(consents).every(Boolean) ); }; const getTcfv2ConsentValue = (state: ConsentState | null): string => { if (!state || !state.tcfv2) return 'na'; return consentedToAllPurposes(state.tcfv2.consents) ? 't' : 'f'; }; const getAdConsentFromState = (state: ConsentState | null): boolean => { if (!state) return false; if (state.ccpa) { // CCPA mode return !state.ccpa.doNotSell; } else if (state.tcfv2) { // TCFv2 mode return consentedToAllPurposes(state.tcfv2.consents); } else if (state.aus) { // AUS mode return state.aus.personalisedAdvertising; } // Unknown mode return false; }; const isAdManagerGroup = (s: string | null): s is AdManagerGroup => adManagerGroups.some((g) => g === s); const getAdManagerGroup = (consented = true): AdManagerGroup | null => { if (!consented) return null; const existingGroup = storage.local.getRaw(AMTGRP_STORAGE_KEY); return isAdManagerGroup(existingGroup) ? existingGroup : createAdManagerGroup(); }; const createAdManagerGroup = (): AdManagerGroup => { const group = adManagerGroups[Math.floor(Math.random() * adManagerGroups.length)]; storage.local.setRaw(AMTGRP_STORAGE_KEY, group); return group; }; const filterEmptyValues = (pageTargets: Record<string, unknown>) => { const filtered: Record<string, string | string[]> = {}; for (const key in pageTargets) { const value = pageTargets[key]; if (isString(value)) { filtered[key] = value; } else if ( Array.isArray(value) && value.length > 0 && value.every(isString) ) { filtered[key] = value; } } return filtered; }; const rebuildPageTargeting = () => { latestCmpHasInitialised = cmp.hasInitialised(); const adConsentState = getAdConsentFromState(latestCMPState); const ccpaState = latestCMPState?.ccpa ? latestCMPState.ccpa.doNotSell : null; const tcfv2EventStatus = latestCMPState?.tcfv2 ? latestCMPState.tcfv2.eventStatus : 'na'; const { page } = window.guardian.config; const amtgrp = latestCMPState?.tcfv2 ? getAdManagerGroup(adConsentState) : getAdManagerGroup(); // personalised ads targeting if (!adConsentState) clearPermutiveSegments(); // flowlint-next-line sketchy-null-bool:off const paTargeting: PageTargeting = { pa: adConsentState ? 't' : 'f' }; const adFreeTargeting: PageTargeting = commercialFeatures.adFree ? { af: 't' } : {}; const pageTargets: PageTargeting = { ...{ ab: abParam(), amtgrp, at: getCookie({ name: 'adtest', shouldMemoize: true }), bp: findBreakpoint(), cc: getCountryCode(), // if turned async, we could use getLocale() cmp_interaction: tcfv2EventStatus, consent_tcfv2: getTcfv2ConsentValue(latestCMPState), // dcre: DCR eligible // when the page is DCR eligible and was rendered by DCR or // when the page is DCR eligible but rendered by frontend for a user not in the DotcomRendering experiment dcre: window.guardian.config.isDotcomRendering || config.get<boolean>('page.dcrCouldRender', false) ? 't' : 'f', fr: getFrequencyValue(), inskin: inskinTargeting(), permutive: getPermutiveSegments(), pv: window.guardian.config.ophan.pageViewId, rdp: getRdpValue(ccpaState), ref: getReferrer(), // rp: rendering platform rp: window.guardian.config.isDotcomRendering ? 'dotcom-rendering' : 'dotcom-platform', // s: section // for reference in a macro, so cannot be extracted from ad unit s: page.section, sens: page.isSensitive ? 't' : 'f', si: isUserLoggedIn() ? 't' : 'f', skinsize: skinsizeTargeting(), urlkw: getUrlKeywords(page.pageId), // vl: video length // round video duration up to nearest 30 multiple vl: page.videoDuration ? (Math.ceil(page.videoDuration / 30.0) * 30).toString() : null, }, ...page.sharedAdTargeting, ...paTargeting, ...adFreeTargeting, }; // filter out empty values const pageTargeting: Record<string, string | string[]> = filterEmptyValues(pageTargets); // third-parties wish to access our page targeting, before the googletag script is loaded. page.appNexusPageTargeting = buildAppNexusTargeting(pageTargeting); // This can be removed once we get sign-off from third parties who prefer to use appNexusPageTargeting. page.pageAdTargeting = pageTargeting; log('commercial', 'pageTargeting object:', pageTargeting); return pageTargeting; }; const getPageTargeting = (): PageTargeting => { if (Object.keys(myPageTargeting).length !== 0) { // If CMP was initialised since the last time myPageTargeting was built - rebuild if (latestCmpHasInitialised !== cmp.hasInitialised()) { myPageTargeting = rebuildPageTargeting(); } return myPageTargeting; } // First call binds to onConsentChange and returns {} onConsentChange((state) => { // On every consent change we rebuildPageTargeting latestCMPState = state; myPageTargeting = rebuildPageTargeting(); }); return myPageTargeting; }; const resetPageTargeting = (): void => { myPageTargeting = {}; }; export { getPageTargeting, buildAppNexusTargeting, buildAppNexusTargetingObject, }; export const _ = { resetPageTargeting, };
the_stack
import { compareBy, CompareResult, tieBreakComparators, equals, numberComparator } from 'vs/base/common/arrays'; import { BugIndicatingError } from 'vs/base/common/errors'; import { splitLines } from 'vs/base/common/strings'; import { Constants } from 'vs/base/common/uint'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; import { IEditorWorkerService } from 'vs/editor/common/services/editorWorker'; import { EditorModel } from 'vs/workbench/common/editor/editorModel'; import { autorunHandleChanges, derivedObservable, derivedObservableWithCache, IObservable, ITransaction, keepAlive, ObservableValue, transaction, waitForState } from 'vs/workbench/contrib/audioCues/browser/observable'; import { EditorWorkerServiceDiffComputer } from 'vs/workbench/contrib/mergeEditor/browser/model/diffComputer'; import { DetailedLineRangeMapping, DocumentMapping, LineRangeMapping } from 'vs/workbench/contrib/mergeEditor/browser/model/mapping'; import { LineRangeEdit, RangeEdit } from 'vs/workbench/contrib/mergeEditor/browser/model/editing'; import { LineRange } from 'vs/workbench/contrib/mergeEditor/browser/model/lineRange'; import { TextModelDiffChangeReason, TextModelDiffs, TextModelDiffState } from 'vs/workbench/contrib/mergeEditor/browser/model/textModelDiffs'; import { concatArrays, leftJoin, elementAtOrUndefined } from 'vs/workbench/contrib/mergeEditor/browser/utils'; import { ModifiedBaseRange, ModifiedBaseRangeState } from './modifiedBaseRange'; export const enum MergeEditorModelState { initializing = 1, upToDate = 2, updating = 3, } export class MergeEditorModel extends EditorModel { private readonly diffComputer = new EditorWorkerServiceDiffComputer(this.editorWorkerService); private readonly input1TextModelDiffs = new TextModelDiffs(this.base, this.input1, this.diffComputer); private readonly input2TextModelDiffs = new TextModelDiffs(this.base, this.input2, this.diffComputer); private readonly resultTextModelDiffs = new TextModelDiffs(this.base, this.result, this.diffComputer); public readonly state = derivedObservable('state', reader => { const states = [ this.input1TextModelDiffs, this.input2TextModelDiffs, this.resultTextModelDiffs, ].map((s) => s.state.read(reader)); if (states.some((s) => s === TextModelDiffState.initializing)) { return MergeEditorModelState.initializing; } if (states.some((s) => s === TextModelDiffState.updating)) { return MergeEditorModelState.updating; } return MergeEditorModelState.upToDate; }); public readonly isUpToDate = derivedObservable('isUpdating', reader => this.state.read(reader) === MergeEditorModelState.upToDate); public readonly onInitialized = waitForState(this.state, state => state === MergeEditorModelState.upToDate); public readonly modifiedBaseRanges = derivedObservableWithCache<ModifiedBaseRange[]>('modifiedBaseRanges', (reader, lastValue) => { if (this.state.read(reader) !== MergeEditorModelState.upToDate) { return lastValue || []; } const input1Diffs = this.input1TextModelDiffs.diffs.read(reader); const input2Diffs = this.input2TextModelDiffs.diffs.read(reader); return ModifiedBaseRange.fromDiffs(input1Diffs, input2Diffs, this.base, this.input1, this.input2); }); public readonly input1LinesDiffs = this.input1TextModelDiffs.diffs; public readonly input2LinesDiffs = this.input2TextModelDiffs.diffs; public readonly resultDiffs = this.resultTextModelDiffs.diffs; private readonly modifiedBaseRangeStateStores = derivedObservable('modifiedBaseRangeStateStores', reader => { const map = new Map( this.modifiedBaseRanges.read(reader).map(s => ([s, new ObservableValue(ModifiedBaseRangeState.default, 'State')])) ); return map; }); public readonly input1ResultMapping = derivedObservable('input1ResultMapping', reader => { const resultDiffs = this.resultDiffs.read(reader); const modifiedBaseRanges = DocumentMapping.betweenOutputs(this.input1LinesDiffs.read(reader), resultDiffs, this.input1.getLineCount()); return new DocumentMapping( modifiedBaseRanges.lineRangeMappings.map((m) => m.inputRange.isEmpty || m.outputRange.isEmpty ? new LineRangeMapping( m.inputRange.deltaStart(-1), m.outputRange.deltaStart(-1) ) : m ), modifiedBaseRanges.inputLineCount ); }); public readonly input2ResultMapping = derivedObservable('input2ResultMapping', reader => { const resultDiffs = this.resultDiffs.read(reader); const modifiedBaseRanges = DocumentMapping.betweenOutputs(this.input2LinesDiffs.read(reader), resultDiffs, this.input2.getLineCount()); return new DocumentMapping( modifiedBaseRanges.lineRangeMappings.map((m) => m.inputRange.isEmpty || m.outputRange.isEmpty ? new LineRangeMapping( m.inputRange.deltaStart(-1), m.outputRange.deltaStart(-1) ) : m ), modifiedBaseRanges.inputLineCount ); }); constructor( readonly base: ITextModel, readonly input1: ITextModel, readonly input1Detail: string | undefined, readonly input1Description: string | undefined, readonly input2: ITextModel, readonly input2Detail: string | undefined, readonly input2Description: string | undefined, readonly result: ITextModel, @IEditorWorkerService private readonly editorWorkerService: IEditorWorkerService ) { super(); this._register(keepAlive(this.modifiedBaseRangeStateStores)); this._register(keepAlive(this.input1ResultMapping)); this._register(keepAlive(this.input2ResultMapping)); this._register( autorunHandleChanges( 'Recompute State', { handleChange: (ctx) => ctx.didChange(this.resultTextModelDiffs.diffs) // Ignore non-text changes as we update the state directly ? ctx.change === TextModelDiffChangeReason.textChange : true, }, (reader) => { if (!this.isUpToDate.read(reader)) { return; } const resultDiffs = this.resultTextModelDiffs.diffs.read(reader); const stores = this.modifiedBaseRangeStateStores.read(reader); this.recomputeState(resultDiffs, stores); } ) ); this.onInitialized.then(() => { this.resetUnknown(); }); } private recomputeState(resultDiffs: DetailedLineRangeMapping[], stores: Map<ModifiedBaseRange, ObservableValue<ModifiedBaseRangeState>>): void { transaction(tx => { const baseRangeWithStoreAndTouchingDiffs = leftJoin( stores, resultDiffs, (baseRange, diff) => baseRange[0].baseRange.touches(diff.inputRange) ? CompareResult.neitherLessOrGreaterThan : LineRange.compareByStart( baseRange[0].baseRange, diff.inputRange ) ); for (const row of baseRangeWithStoreAndTouchingDiffs) { row.left[1].set(this.computeState(row.left[0], row.rights), tx); } }); } public resetUnknown(): void { transaction(tx => { for (const range of this.modifiedBaseRanges.get()) { if (this.getState(range).get().conflicting) { this.setState(range, ModifiedBaseRangeState.default, tx); } } }); } public mergeNonConflictingDiffs(): void { transaction((tx) => { for (const m of this.modifiedBaseRanges.get()) { if (m.isConflicting) { continue; } this.setState( m, m.input1Diffs.length > 0 ? ModifiedBaseRangeState.default.withInput1(true) : ModifiedBaseRangeState.default.withInput2(true), tx ); } }); } public getState(baseRange: ModifiedBaseRange): IObservable<ModifiedBaseRangeState> { const existingState = this.modifiedBaseRangeStateStores.get().get(baseRange); if (!existingState) { throw new BugIndicatingError('object must be from this instance'); } return existingState; } public setState( baseRange: ModifiedBaseRange, state: ModifiedBaseRangeState, transaction: ITransaction ): void { if (!this.isUpToDate.get()) { throw new BugIndicatingError('Cannot set state while updating'); } const existingState = this.modifiedBaseRangeStateStores.get().get(baseRange); if (!existingState) { throw new BugIndicatingError('object must be from this instance'); } const conflictingDiffs = this.resultTextModelDiffs.findTouchingDiffs( baseRange.baseRange ); if (conflictingDiffs) { this.resultTextModelDiffs.removeDiffs(conflictingDiffs, transaction); } const { edit, effectiveState } = getEditForBase(baseRange, state); existingState.set(effectiveState, transaction); if (edit) { this.resultTextModelDiffs.applyEditRelativeToOriginal(edit, transaction); } } private computeState(baseRange: ModifiedBaseRange, conflictingDiffs: DetailedLineRangeMapping[]): ModifiedBaseRangeState { if (conflictingDiffs.length === 0) { return ModifiedBaseRangeState.default; } const conflictingEdits = conflictingDiffs.map((d) => d.getLineEdit()); function editsAgreeWithDiffs(diffs: readonly DetailedLineRangeMapping[]): boolean { return equals( conflictingEdits, diffs.map((d) => d.getLineEdit()), (a, b) => a.equals(b) ); } if (editsAgreeWithDiffs(baseRange.input1Diffs)) { return ModifiedBaseRangeState.default.withInput1(true); } if (editsAgreeWithDiffs(baseRange.input2Diffs)) { return ModifiedBaseRangeState.default.withInput2(true); } const states = [ ModifiedBaseRangeState.default.withInput1(true).withInput2(true), ModifiedBaseRangeState.default.withInput2(true).withInput1(true), ]; for (const s of states) { const { edit } = getEditForBase(baseRange, s); if (edit) { const resultRange = this.resultTextModelDiffs.getResultRange(baseRange.baseRange); const existingLines = resultRange.getLines(this.result); if (equals(edit.newLines, existingLines, (a, b) => a === b)) { return s; } } } return ModifiedBaseRangeState.conflicting; } } function getEditForBase(baseRange: ModifiedBaseRange, state: ModifiedBaseRangeState): { edit: LineRangeEdit | undefined; effectiveState: ModifiedBaseRangeState } { const diffs = concatArrays( state.input1 && baseRange.input1CombinedDiff ? [{ diff: baseRange.input1CombinedDiff, inputNumber: 1 as const }] : [], state.input2 && baseRange.input2CombinedDiff ? [{ diff: baseRange.input2CombinedDiff, inputNumber: 2 as const }] : [], ); if (state.input2First) { diffs.reverse(); } const firstDiff = elementAtOrUndefined(diffs, 0); const secondDiff = elementAtOrUndefined(diffs, 1); if (!firstDiff) { return { edit: undefined, effectiveState: ModifiedBaseRangeState.default }; } if (!secondDiff) { return { edit: firstDiff.diff.getLineEdit(), effectiveState: ModifiedBaseRangeState.default.withInputValue(firstDiff.inputNumber, true) }; } const result = combineInputs(baseRange, state.input2First ? 2 : 1); if (result) { return { edit: result, effectiveState: state }; } return { edit: secondDiff.diff.getLineEdit(), effectiveState: ModifiedBaseRangeState.default.withInputValue( secondDiff.inputNumber, true ), }; } function combineInputs(baseRange: ModifiedBaseRange, firstInput: 1 | 2): LineRangeEdit | undefined { const combinedDiffs = concatArrays( baseRange.input1Diffs.flatMap((diffs) => diffs.rangeMappings.map((diff) => ({ diff, input: 1 as const })) ), baseRange.input2Diffs.flatMap((diffs) => diffs.rangeMappings.map((diff) => ({ diff, input: 2 as const })) ) ).sort( tieBreakComparators( compareBy((d) => d.diff.inputRange, Range.compareRangesUsingStarts), compareBy((d) => (d.input === firstInput ? 1 : 2), numberComparator) ) ); const sortedEdits = combinedDiffs.map(d => { const sourceTextModel = d.input === 1 ? baseRange.input1TextModel : baseRange.input2TextModel; return new RangeEdit(d.diff.inputRange, sourceTextModel.getValueInRange(d.diff.outputRange)); }); return editsToLineRangeEdit(baseRange.baseRange, sortedEdits, baseRange.baseTextModel); } function editsToLineRangeEdit(range: LineRange, sortedEdits: RangeEdit[], textModel: ITextModel): LineRangeEdit | undefined { let text = ''; const startsLineBefore = range.startLineNumber > 1; let currentPosition = startsLineBefore ? new Position( range.startLineNumber - 1, Constants.MAX_SAFE_SMALL_INTEGER ) : new Position(range.startLineNumber, 1); for (const edit of sortedEdits) { const diffStart = edit.range.getStartPosition(); if (!currentPosition.isBeforeOrEqual(diffStart)) { return undefined; } const originalText = textModel.getValueInRange(Range.fromPositions(currentPosition, diffStart)); text += originalText; text += edit.newText; currentPosition = edit.range.getEndPosition(); } const endsLineAfter = range.endLineNumberExclusive <= textModel.getLineCount(); const end = endsLineAfter ? new Position( range.endLineNumberExclusive, 1 ) : new Position(range.endLineNumberExclusive - 1, Constants.MAX_SAFE_SMALL_INTEGER); const originalText = textModel.getValueInRange( Range.fromPositions(currentPosition, end) ); text += originalText; const lines = splitLines(text); if (startsLineBefore) { lines.shift(); } if (endsLineAfter) { lines.pop(); } return new LineRangeEdit(range, lines); }
the_stack
declare function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R>; declare class MapOperator<T, R> implements Operator<T, R> { private project; private thisArg; constructor(project: (value: T, index: number) => R, thisArg: any); call(subscriber: Subscriber<R>, source: any): any; } declare function from<O extends ObservableInput<any>>(input: O, scheduler?: SchedulerLike): Observable<ObservedValueOf<O>>; declare function of<T>(a: T, scheduler?: SchedulerLike): Observable<T>; declare function of<T, T2>(a: T, b: T2, scheduler?: SchedulerLike): Observable<T | T2>; declare function of<T, T2, T3>(a: T, b: T2, c: T3, scheduler?: SchedulerLike): Observable<T | T2 | T3>; declare function of<T, T2, T3, T4>(a: T, b: T2, c: T3, d: T4, scheduler?: SchedulerLike): Observable<T | T2 | T3 | T4>; declare function of<T, T2, T3, T4, T5>(a: T, b: T2, c: T3, d: T4, e: T5, scheduler?: SchedulerLike): Observable<T | T2 | T3 | T4 | T5>; declare function of<T, T2, T3, T4, T5, T6>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, scheduler?: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6>; declare function of<T, T2, T3, T4, T5, T6, T7>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, scheduler?: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6 | T7>; declare function of<T, T2, T3, T4, T5, T6, T7, T8>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, scheduler?: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8>; declare function of<T, T2, T3, T4, T5, T6, T7, T8, T9>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, i: T9, scheduler?: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>; declare function of<T>(...args: Array<T | SchedulerLike>): Observable<T>; /** * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items. * * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the * source observable directly with an equality check against previous values. * * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking. * * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct` * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so * that the internal `Set` can be "flushed", basically clearing it of values. * * ## Examples * A simple example with numbers * ```javascript * import { of } from 'rxjs'; * import { distinct } from 'rxjs/operators'; * * of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1).pipe( * distinct(), * ) * .subscribe(x => console.log(x)); // 1, 2, 3, 4 * ``` * * An example using a keySelector function * ```typescript * import { of } from 'rxjs'; * import { distinct } from 'rxjs/operators'; * * interface Person { * age: number, * name: string * } * * of<Person>( * { age: 4, name: 'Foo'}, * { age: 7, name: 'Bar'}, * { age: 5, name: 'Foo'}, * ).pipe( * distinct((p: Person) => p.name), * ) * .subscribe(x => console.log(x)); * * // displays: * // { age: 4, name: 'Foo' } * // { age: 7, name: 'Bar' } * ``` * @see {@link distinctUntilChanged} * @see {@link distinctUntilKeyChanged} * * @param {function} [keySelector] Optional function to select which value you want to check as distinct. * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator. * @return {Observable} An Observable that emits items from the source Observable with distinct values. * @method distinct * @owner Observable */ declare function distinct<T, K>(keySelector?: (value: T) => K, flushes?: Observable<any>): MonoTypeOperatorFunction<T>; /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ declare class DistinctSubscriber<T, K> extends OuterSubscriber<T, T> { private keySelector; private values; constructor(destination: Subscriber<T>, keySelector: (value: T) => K, flushes: Observable<any>); notifyNext(outerValue: T, innerValue: T, outerIndex: number, innerIndex: number, innerSub: InnerSubscriber<T, T>): void; notifyError(error: any, innerSub: InnerSubscriber<T, T>): void; protected _next(value: T): void; private _useKeySelector; private _finalizeNext; } /** * Implements the {@link Observer} interface and extends the * {@link Subscription} class. While the {@link Observer} is the public API for * consuming the values of an {@link Observable}, all Observers get converted to * a Subscriber, in order to provide Subscription-like capabilities such as * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for * implementing operators, but it is rarely used as a public API. * * @class Subscriber<T> */ declare class Subscriber<T> extends Subscription implements Observer<T> { /** * A static factory for a Subscriber, given a (potentially partial) definition * of an Observer. * @param {function(x: ?T): void} [next] The `next` callback of an Observer. * @param {function(e: ?any): void} [error] The `error` callback of an * Observer. * @param {function(): void} [complete] The `complete` callback of an * Observer. * @return {Subscriber<T>} A Subscriber wrapping the (partially defined) * Observer represented by the given arguments. * @nocollapse */ static create<T>(next?: (x?: T) => void, error?: (e?: any) => void, complete?: () => void): Subscriber<T>; /** @internal */ syncErrorValue: any; /** @internal */ syncErrorThrown: boolean; /** @internal */ syncErrorThrowable: boolean; protected isStopped: boolean; protected destination: PartialObserver<any> | Subscriber<any>; /** * @param {Observer|function(value: T): void} [destinationOrNext] A partially * defined Observer or a `next` callback function. * @param {function(e: ?any): void} [error] The `error` callback of an * Observer. * @param {function(): void} [complete] The `complete` callback of an * Observer. */ constructor(destinationOrNext?: PartialObserver<any> | ((value: T) => void), error?: (e?: any) => void, complete?: () => void); /** * The {@link Observer} callback to receive notifications of type `next` from * the Observable, with a value. The Observable may call this method 0 or more * times. * @param {T} [value] The `next` value. * @return {void} */ next(value?: T): void; /** * The {@link Observer} callback to receive notifications of type `error` from * the Observable, with an attached `Error`. Notifies the Observer that * the Observable has experienced an error condition. * @param {any} [err] The `error` exception. * @return {void} */ error(err?: any): void; /** * The {@link Observer} callback to receive a valueless notification of type * `complete` from the Observable. Notifies the Observer that the Observable * has finished sending push-based notifications. * @return {void} */ complete(): void; unsubscribe(): void; protected _next(value: T): void; protected _error(err: any): void; protected _complete(): void; /** @deprecated This is an internal implementation detail, do not use. */ _unsubscribeAndRecycle(): Subscriber<T>; } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ declare class SafeSubscriber<T> extends Subscriber<T> { private _parentSubscriber; private _context; constructor(_parentSubscriber: Subscriber<T>, observerOrNext?: PartialObserver<T> | ((value: T) => void), error?: (e?: any) => void, complete?: () => void); next(value?: T): void; error(err?: any): void; complete(): void; private __tryOrUnsub; private __tryOrSetError; /** @internal This is an internal implementation detail, do not use. */ _unsubscribe(): void; } interface Operator<T, R> { call(subscriber: Subscriber<R>, source: any): TeardownLogic; } /** * A representation of any set of values over any amount of time. This is the most basic building block * of RxJS. * * @class Observable<T> */ declare class Observable<T> implements Subscribable<T> { /** Internal implementation detail, do not use directly. */ _isScalar: boolean; /** @deprecated This is an internal implementation detail, do not use. */ source: Observable<any>; /** @deprecated This is an internal implementation detail, do not use. */ operator: Operator<any, T>; /** * @constructor * @param {Function} subscribe the function that is called when the Observable is * initially subscribed to. This function is given a Subscriber, to which new values * can be `next`ed, or an `error` method can be called to raise an error, or * `complete` can be called to notify of a successful completion. */ constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic); /** * Creates a new cold Observable by calling the Observable constructor * @static true * @owner Observable * @method create * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor * @return {Observable} a new cold observable * @nocollapse * @deprecated use new Observable() instead */ static create: Function; /** * Creates a new Observable, with this Observable as the source, and the passed * operator defined as the new observable's operator. * @method lift * @param {Operator} operator the operator defining the operation to take on the observable * @return {Observable} a new observable with the Operator applied */ lift<R>(operator: Operator<T, R>): Observable<R>; subscribe(observer?: PartialObserver<T>): Subscription; /** @deprecated Use an observer instead of a complete callback */ subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription; /** @deprecated Use an observer instead of an error callback */ subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription; /** @deprecated Use an observer instead of a complete callback */ subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription; subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription; /** @deprecated This is an internal implementation detail, do not use. */ _trySubscribe(sink: Subscriber<T>): TeardownLogic; /** * @method forEach * @param {Function} next a handler for each value emitted by the observable * @param {PromiseConstructor} [promiseCtor] a constructor function used to instantiate the Promise * @return {Promise} a promise that either resolves on observable completion or * rejects with the handled error */ forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void>; /** @internal This is an internal implementation detail, do not use. */ _subscribe(subscriber: Subscriber<any>): TeardownLogic; /** * @nocollapse * @deprecated In favor of iif creation function: import { iif } from 'rxjs'; */ static if: typeof iif; /** * @nocollapse * @deprecated In favor of throwError creation function: import { throwError } from 'rxjs'; */ static throw: typeof throwError; pipe(): Observable<T>; pipe<A>(op1: OperatorFunction<T, A>): Observable<A>; pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>; pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>; pipe<A, B, C, D>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>): Observable<D>; pipe<A, B, C, D, E>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>): Observable<E>; pipe<A, B, C, D, E, F>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>): Observable<F>; pipe<A, B, C, D, E, F, G>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>): Observable<G>; pipe<A, B, C, D, E, F, G, H>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>): Observable<H>; pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>): Observable<I>; pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>, ...operations: OperatorFunction<any, any>[]): Observable<{}>; toPromise<T>(this: Observable<T>): Promise<T>; toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>; toPromise<T>(this: Observable<T>, PromiseCtor: PromiseConstructorLike): Promise<T>; } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ declare class OuterSubscriber<T, R> extends Subscriber<T> { notifyNext(outerValue: T, innerValue: R, outerIndex: number, innerIndex: number, innerSub: InnerSubscriber<T, R>): void; notifyError(error: any, innerSub: InnerSubscriber<T, R>): void; notifyComplete(innerSub: InnerSubscriber<T, R>): void; } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ declare class InnerSubscriber<T, R> extends Subscriber<R> { private parent; outerValue: T; outerIndex: number; private index; constructor(parent: OuterSubscriber<T, R>, outerValue: T, outerIndex: number); protected _next(value: R): void; protected _error(error: any): void; protected _complete(): void; } /** OPERATOR INTERFACES */ interface UnaryFunction<T, R> { (source: T): R; } interface OperatorFunction<T, R> extends UnaryFunction<Observable<T>, Observable<R>> { } declare type FactoryOrValue<T> = T | (() => T); interface MonoTypeOperatorFunction<T> extends OperatorFunction<T, T> { } interface Timestamp<T> { value: T; timestamp: number; } interface TimeInterval<T> { value: T; interval: number; } /** SUBSCRIPTION INTERFACES */ interface Unsubscribable { unsubscribe(): void; } declare type TeardownLogic = Unsubscribable | Function | void; interface SubscriptionLike extends Unsubscribable { unsubscribe(): void; readonly closed: boolean; } declare type SubscribableOrPromise<T> = Subscribable<T> | Subscribable<never> | PromiseLike<T> | InteropObservable<T>; /** OBSERVABLE INTERFACES */ interface Subscribable<T> { subscribe(observer?: PartialObserver<T>): Unsubscribable; /** @deprecated Use an observer instead of a complete callback */ subscribe(next: null | undefined, error: null | undefined, complete: () => void): Unsubscribable; /** @deprecated Use an observer instead of an error callback */ subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Unsubscribable; /** @deprecated Use an observer instead of a complete callback */ subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Unsubscribable; subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Unsubscribable; } declare type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T> | Iterable<T>; /** @deprecated use {@link InteropObservable } */ declare type ObservableLike<T> = InteropObservable<T>; declare type InteropObservable<T> = { [Symbol.observable]: () => Subscribable<T>; }; /** OBSERVER INTERFACES */ interface NextObserver<T> { closed?: boolean; next: (value: T) => void; error?: (err: any) => void; complete?: () => void; } interface ErrorObserver<T> { closed?: boolean; next?: (value: T) => void; error: (err: any) => void; complete?: () => void; } interface CompletionObserver<T> { closed?: boolean; next?: (value: T) => void; error?: (err: any) => void; complete: () => void; } declare type PartialObserver<T> = NextObserver<T> | ErrorObserver<T> | CompletionObserver<T>; interface Observer<T> { closed?: boolean; next: (value: T) => void; error: (err: any) => void; complete: () => void; } /** SCHEDULER INTERFACES */ interface SchedulerLike { now(): number; schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay?: number, state?: T): Subscription; } interface SchedulerAction<T> extends Subscription { schedule(state?: T, delay?: number): Subscription; } declare type ObservedValueOf<O> = O extends ObservableInput<infer T> ? T : never; /** * Represents a disposable resource, such as the execution of an Observable. A * Subscription has one important method, `unsubscribe`, that takes no argument * and just disposes the resource held by the subscription. * * Additionally, subscriptions may be grouped together through the `add()` * method, which will attach a child Subscription to the current Subscription. * When a Subscription is unsubscribed, all its children (and its grandchildren) * will be unsubscribed as well. * * @class Subscription */ declare class Subscription implements SubscriptionLike { /** @nocollapse */ static EMPTY: Subscription; /** * A flag to indicate whether this Subscription has already been unsubscribed. * @type {boolean} */ closed: boolean; /** @internal */ protected _parent: Subscription; /** @internal */ protected _parents: Subscription[]; /** @internal */ private _subscriptions; /** * @param {function(): void} [unsubscribe] A function describing how to * perform the disposal of resources when the `unsubscribe` method is called. */ constructor(unsubscribe?: () => void); /** * Disposes the resources held by the subscription. May, for instance, cancel * an ongoing Observable execution or cancel any other type of work that * started when the Subscription was created. * @return {void} */ unsubscribe(): void; /** * Adds a tear down to be called during the unsubscribe() of this * Subscription. Can also be used to add a child subscription. * * If the tear down being added is a subscription that is already * unsubscribed, is the same reference `add` is being called on, or is * `Subscription.EMPTY`, it will not be added. * * If this subscription is already in an `closed` state, the passed * tear down logic will be executed immediately. * * When a parent subscription is unsubscribed, any child subscriptions that were added to it are also unsubscribed. * * @param {TeardownLogic} teardown The additional logic to execute on * teardown. * @return {Subscription} Returns the Subscription used or created to be * added to the inner subscriptions list. This Subscription can be used with * `remove()` to remove the passed teardown logic from the inner subscriptions * list. */ add(teardown: TeardownLogic): Subscription; /** * Removes a Subscription from the internal list of subscriptions that will * unsubscribe during the unsubscribe process of this Subscription. * @param {Subscription} subscription The subscription to remove. * @return {void} */ remove(subscription: Subscription): void; /** @internal */ private _addParent; } /** * Creates an Observable that emits no items to the Observer and immediately * emits an error notification. * * <span class="informal">Just emits 'error', and nothing else. * </span> * * ![](throw.png) * * This static operator is useful for creating a simple Observable that only * emits the error notification. It can be used for composing with other * Observables, such as in a {@link mergeMap}. * * ## Examples * ### Emit the number 7, then emit an error * ```javascript * import { throwError, concat, of } from 'rxjs'; * * const result = concat(of(7), throwError(new Error('oops!'))); * result.subscribe(x => console.log(x), e => console.error(e)); * * // Logs: * // 7 * // Error: oops! * ``` * * --- * * ### Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 2 * ```javascript * import { throwError, interval, of } from 'rxjs'; * import { mergeMap } from 'rxjs/operators'; * * interval(1000).pipe( * mergeMap(x => x === 2 * ? throwError('Twos are bad') * : of('a', 'b', 'c') * ), * ).subscribe(x => console.log(x), e => console.error(e)); * * // Logs: * // a * // b * // c * // a * // b * // c * // Twos are bad * ``` * * @see {@link Observable} * @see {@link empty} * @see {@link never} * @see {@link of} * * @param {any} error The particular Error to pass to the error notification. * @param {SchedulerLike} [scheduler] A {@link SchedulerLike} to use for scheduling * the emission of the error notification. * @return {Observable} An error Observable: emits only the error notification * using the given error argument. * @static true * @name throwError * @owner Observable */ declare function throwError(error: any, scheduler?: SchedulerLike): Observable<never>; /** * Decides at subscription time which Observable will actually be subscribed. * * <span class="informal">`If` statement for Observables.</span> * * `iif` accepts a condition function and two Observables. When * an Observable returned by the operator is subscribed, condition function will be called. * Based on what boolean it returns at that moment, consumer will subscribe either to * the first Observable (if condition was true) or to the second (if condition was false). Condition * function may also not return anything - in that case condition will be evaluated as false and * second Observable will be subscribed. * * Note that Observables for both cases (true and false) are optional. If condition points to an Observable that * was left undefined, resulting stream will simply complete immediately. That allows you to, rather * then controlling which Observable will be subscribed, decide at runtime if consumer should have access * to given Observable or not. * * If you have more complex logic that requires decision between more than two Observables, {@link defer} * will probably be a better choice. Actually `iif` can be easily implemented with {@link defer} * and exists only for convenience and readability reasons. * * * ## Examples * ### Change at runtime which Observable will be subscribed * ```javascript * import { iif, of } from 'rxjs'; * * let subscribeToFirst; * const firstOrSecond = iif( * () => subscribeToFirst, * of('first'), * of('second'), * ); * * subscribeToFirst = true; * firstOrSecond.subscribe(value => console.log(value)); * * // Logs: * // "first" * * subscribeToFirst = false; * firstOrSecond.subscribe(value => console.log(value)); * * // Logs: * // "second" * * ``` * * ### Control an access to an Observable * ```javascript * let accessGranted; * const observableIfYouHaveAccess = iif( * () => accessGranted, * of('It seems you have an access...'), // Note that only one Observable is passed to the operator. * ); * * accessGranted = true; * observableIfYouHaveAccess.subscribe( * value => console.log(value), * err => {}, * () => console.log('The end'), * ); * * // Logs: * // "It seems you have an access..." * // "The end" * * accessGranted = false; * observableIfYouHaveAccess.subscribe( * value => console.log(value), * err => {}, * () => console.log('The end'), * ); * * // Logs: * // "The end" * ``` * * @see {@link defer} * * @param {function(): boolean} condition Condition which Observable should be chosen. * @param {Observable} [trueObservable] An Observable that will be subscribed if condition is true. * @param {Observable} [falseObservable] An Observable that will be subscribed if condition is false. * @return {Observable} Either first or second Observable, depending on condition. * @static true * @name iif * @owner Observable */ declare function iif<T, F>(condition: () => boolean, trueResult?: SubscribableOrPromise<T>, falseResult?: SubscribableOrPromise<F>): Observable<T | F>; /** * Emits only the first `count` values emitted by the source Observable. * * <span class="informal">Takes the first `count` values from the source, then * completes.</span> * * ![](take.png) * * `take` returns an Observable that emits only the first `count` values emitted * by the source Observable. If the source emits fewer than `count` values then * all of its values are emitted. After that, it completes, regardless if the * source completes. * * ## Example * Take the first 5 seconds of an infinite 1-second interval Observable * ```ts * import { interval } from 'rxjs'; * import { take } from 'rxjs/operators'; * * const intervalCount = interval(1000); * const takeFive = intervalCount.pipe(take(5)); * takeFive.subscribe(x => console.log(x)); * * // Logs: * // 0 * // 1 * // 2 * // 3 * // 4 * ``` * * @see {@link takeLast} * @see {@link takeUntil} * @see {@link takeWhile} * @see {@link skip} * * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`. * * @param {number} count The maximum number of `next` values to emit. * @return {Observable<T>} An Observable that emits only the first `count` * values emitted by the source Observable, or all of the values from the source * if the source emits fewer than `count` values. * @method take * @owner Observable */ declare function take<T>(count: number): MonoTypeOperatorFunction<T>; declare function filter<T, S extends T>(predicate: (value: T, index: number) => value is S, thisArg?: any): OperatorFunction<T, S>; declare function filter<T>(predicate: (value: T, index: number) => boolean, thisArg?: any): MonoTypeOperatorFunction<T>; /** * The same Observable instance returned by any call to {@link empty} without a * `scheduler`. It is preferrable to use this over `empty()`. */ declare const EMPTY: Observable<never>; declare function toConveyorBelt(fruit: string): void; declare function tap<T>(next: (x: T) => void): MonoTypeOperatorFunction<T>; declare function tap<T>(observer: PartialObserver<T>): MonoTypeOperatorFunction<T>; declare function distinctUntilChanged<T>(compare?: (x: T, y: T) => boolean): MonoTypeOperatorFunction<T>; declare function distinctUntilChanged<T, K>(compare: (x: K, y: K) => boolean, keySelector: (x: T) => K): MonoTypeOperatorFunction<T>; /** * Returns an Observable that skips the first `count` items emitted by the source Observable. * * ![](skip.png) * * @param {Number} count - The number of times, items emitted by source Observable should be skipped. * @return {Observable} An Observable that skips values emitted by the source Observable. * * @method skip * @owner Observable */ declare function skip<T>(count: number): MonoTypeOperatorFunction<T>; declare function merge<T>(v1: ObservableInput<T>): Observable<T>; declare function merge<T>(v1: ObservableInput<T>, concurrent?: number): Observable<T>; declare function merge<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>): Observable<T | T2>; declare function merge<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>, concurrent?: number): Observable<T | T2>; declare function merge<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>): Observable<T | T2 | T3>; declare function merge<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, concurrent?: number): Observable<T | T2 | T3>; declare function merge<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): Observable<T | T2 | T3 | T4>; declare function merge<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, concurrent?: number): Observable<T | T2 | T3 | T4>; declare function merge<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): Observable<T | T2 | T3 | T4 | T5>; declare function merge<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, concurrent?: number): Observable<T | T2 | T3 | T4 | T5>; declare function merge<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): Observable<T | T2 | T3 | T4 | T5 | T6>; declare function merge<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, concurrent?: number): Observable<T | T2 | T3 | T4 | T5 | T6>; declare function merge<T>(...observables: (ObservableInput<T> | number)[]): Observable<T>; declare function merge<T, R>(...observables: (ObservableInput<any> | number)[]): Observable<R>; /** * Emits only the last `count` values emitted by the source Observable. * * <span class="informal">Remembers the latest `count` values, then emits those * only when the source completes.</span> * * ![](takeLast.png) * * `takeLast` returns an Observable that emits at most the last `count` values * emitted by the source Observable. If the source emits fewer than `count` * values then all of its values are emitted. This operator must wait until the * `complete` notification emission from the source in order to emit the `next` * values on the output Observable, because otherwise it is impossible to know * whether or not more values will be emitted on the source. For this reason, * all values are emitted synchronously, followed by the complete notification. * * ## Example * Take the last 3 values of an Observable with many values * ```ts * import { range } from 'rxjs'; * import { takeLast } from 'rxjs/operators'; * * const many = range(1, 100); * const lastThree = many.pipe(takeLast(3)); * lastThree.subscribe(x => console.log(x)); * ``` * * @see {@link take} * @see {@link takeUntil} * @see {@link takeWhile} * @see {@link skip} * * @throws {ArgumentOutOfRangeError} When using `takeLast(i)`, it delivers an * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`. * * @param {number} count The maximum number of values to emit from the end of * the sequence of values emitted by the source Observable. * @return {Observable<T>} An Observable that emits at most the last count * values emitted by the source Observable. * @method takeLast * @owner Observable */ declare function takeLast<T>(count: number): MonoTypeOperatorFunction<T>; /** * Skip the last `count` values emitted by the source Observable. * * ![](skipLast.png) * * `skipLast` returns an Observable that accumulates a queue with a length * enough to store the first `count` values. As more values are received, * values are taken from the front of the queue and produced on the result * sequence. This causes values to be delayed. * * ## Example * Skip the last 2 values of an Observable with many values * ```ts * import { range } from 'rxjs'; * import { skipLast } from 'rxjs/operators'; * * const many = range(1, 5); * const skipLastTwo = many.pipe(skipLast(2)); * skipLastTwo.subscribe(x => console.log(x)); * * // Results in: * // 1 2 3 * ``` * * @see {@link skip} * @see {@link skipUntil} * @see {@link skipWhile} * @see {@link take} * * @throws {ArgumentOutOfRangeError} When using `skipLast(i)`, it throws * ArgumentOutOrRangeError if `i < 0`. * * @param {number} count Number of elements to skip from the end of the source Observable. * @returns {Observable<T>} An Observable that skips the last count values * emitted by the source Observable. * @method skipLast * @owner Observable */ declare function skipLast<T>(count: number): MonoTypeOperatorFunction<T>; /** * Returns an Observable that will resubscribe to the source stream when the source stream completes, at most count times. * * <span class="informal">Repeats all values emitted on the source. It's like {@link retry}, but for non error cases.</span> * * ![](repeat.png) * * Similar to {@link retry}, this operator repeats the stream of items emitted by the source for non error cases. * Repeat can be useful for creating observables that are meant to have some repeated pattern or rhythm. * * Note: `repeat(0)` returns an empty observable and `repeat()` will repeat forever * * ## Example * Repeat a message stream * ```ts * import { of } from 'rxjs'; * import { repeat, delay } from 'rxjs/operators'; * * const source = of('Repeat message'); * const example = source.pipe(repeat(3)); * example.subscribe(x => console.log(x)); * * // Results * // Repeat message * // Repeat message * // Repeat message * ``` * * Repeat 3 values, 2 times * ```ts * import { interval } from 'rxjs'; * import { repeat, take } from 'rxjs/operators'; * * const source = interval(1000); * const example = source.pipe(take(3), repeat(2)); * example.subscribe(x => console.log(x)); * * // Results every second * // 0 * // 1 * // 2 * // 0 * // 1 * // 2 * ``` * * @see {@link repeatWhen} * @see {@link retry} * * @param {number} [count] The number of times the source Observable items are repeated, a count of 0 will yield * an empty Observable. * @return {Observable} An Observable that will resubscribe to the source stream when the source stream completes * , at most count times. * @method repeat * @owner Observable */ declare function repeat<T>(count?: number): MonoTypeOperatorFunction<T>; declare function takeWhile<T, S extends T>(predicate: (value: T, index: number) => value is S): OperatorFunction<T, S>; declare function takeWhile<T, S extends T>(predicate: (value: T, index: number) => value is S, inclusive: false): OperatorFunction<T, S>; declare function takeWhile<T>(predicate: (value: T, index: number) => boolean, inclusive?: boolean): MonoTypeOperatorFunction<T>; /** * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given * as a number parameter) rather than propagating the `error` call. * * ![](retry.png) * * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications * would be: [1, 2, 1, 2, 3, 4, 5, `complete`]. * * ## Example * ```ts * import { interval, of, throwError } from 'rxjs'; * import { mergeMap, retry } from 'rxjs/operators'; * * const source = interval(1000); * const example = source.pipe( * mergeMap(val => { * if(val > 5){ * return throwError('Error!'); * } * return of(val); * }), * //retry 2 times on error * retry(2) * ); * * const subscribe = example.subscribe({ * next: val => console.log(val), * error: val => console.log(`${val}: Retried 2 times then quit!`) * }); * * // Output: * // 0..1..2..3..4..5.. * // 0..1..2..3..4..5.. * // 0..1..2..3..4..5.. * // "Error!: Retried 2 times then quit!" * ``` * * @param {number} count - Number of retry attempts before failing. * @return {Observable} The source Observable modified with the retry logic. * @method retry * @owner Observable */ declare function retry<T>(count?: number): MonoTypeOperatorFunction<T>; declare function catchError<T, O extends ObservableInput<any>>(selector: (err: any, caught: Observable<T>) => O): OperatorFunction<T, T | ObservedValueOf<O>>; declare function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>; declare function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>; declare function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>; declare function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>; declare function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>; declare function zip<O extends ObservableInput<any>>(array: O[]): Observable<ObservedValueOf<O>[]>; declare function zip<R>(array: ObservableInput<any>[]): Observable<R>; declare function zip<O extends ObservableInput<any>>(...observables: O[]): Observable<ObservedValueOf<O>[]>; declare function zip<O extends ObservableInput<any>, R>(...observables: Array<O | ((...values: ObservedValueOf<O>[]) => R)>): Observable<R>; declare function zip<R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R>; declare class ZipOperator<T, R> implements Operator<T, R> { resultSelector: (...values: Array<any>) => R; constructor(resultSelector?: (...values: Array<any>) => R); call(subscriber: Subscriber<R>, source: any): any; } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ declare class ZipSubscriber<T, R> extends Subscriber<T> { private values; private resultSelector; private iterators; private active; constructor(destination: Subscriber<R>, resultSelector?: (...values: Array<any>) => R, values?: any); protected _next(value: any): void; protected _complete(): void; notifyInactive(): void; checkIterators(): void; protected _tryresultSelector(args: any[]): void; } declare function concatMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O): OperatorFunction<T, ObservedValueOf<O>>;
the_stack
import { BackSide, BufferGeometry, DoubleSide, Float32BufferAttribute, FrontSide, Mesh, MeshBasicMaterial, NearestFilter, OrthographicCamera, PlaneBufferGeometry, Scene, ShaderLib, ShaderMaterial, sRGBEncoding, Texture, TextureLoader, UniformsUtils, Vector4, WebGLRenderer, } from 'three'; import { Helper } from '../utils'; import { Engine } from './engine'; type Block = { redLightLevel: number; greenLightLevel: number; blueLightLevel: number; isBlock: boolean; isEmpty: boolean; isFluid: boolean; isLight: boolean; isPlant: boolean; isPlantable: boolean; isSolid: boolean; isTransparent: boolean; name: string; textures: { [key: string]: string }; transparentStandalone: boolean; }; type Range = { [key: string]: { startU: number; endU: number; startV: number; endV: number; }; }; type RegistryOptionsType = { focusDist: number; focusBlockSize: number; focusPlantSize: number; resolution: number; countPerSide?: number; textureSize?: number; packs?: string[]; blocks?: Block[]; ranges?: Range[]; }; const TRANSPARENT_SIDES = [FrontSide, BackSide]; class Registry { public texturePack: string; public atlasUniform: { value: Texture | null }; public aoUniform: { value: Vector4 }; public opaqueChunkMaterial: ShaderMaterial; public transparentChunkMaterials: ShaderMaterial[]; public focuses: { [id: string]: string } = {}; private canvas: HTMLCanvasElement; private camera: OrthographicCamera; private bufferScene: Scene; private material: MeshBasicMaterial; private renderer: WebGLRenderer; private blockGeometry: BufferGeometry; private plantGeometry: BufferGeometry; constructor(public engine: Engine, public options: RegistryOptionsType) { const { focusDist, focusBlockSize, focusPlantSize, resolution } = options; this.texturePack = this.options.packs.length > 0 ? this.options.packs[1] : this.options.packs[0]; this.aoUniform = { value: new Vector4(100.0, 170.0, 210.0, 255.0) }; // set near to -10 to render the whole block without cutting the edge this.camera = new OrthographicCamera(-focusDist, focusDist, focusDist, -focusDist, -focusPlantSize); this.bufferScene = new Scene(); this.canvas = document.createElement('canvas'); this.canvas.width = resolution; this.canvas.height = resolution; this.renderer = new WebGLRenderer({ powerPreference: 'high-performance', canvas: this.canvas, alpha: true, // stencil: false, depth: false, }); this.renderer.setSize(resolution, resolution); this.renderer.outputEncoding = sRGBEncoding; this.blockGeometry = new BufferGeometry(); this.plantGeometry = new PlaneBufferGeometry(focusPlantSize, focusPlantSize); this.plantGeometry.rotateZ(-Math.PI / 2); this.blockGeometry.setAttribute( 'position', new Float32BufferAttribute( Helper.flatten([ // nx [0, 1, 0], [0, 0, 0], [0, 1, 1], [0, 0, 1], // px [1, 1, 1], [1, 0, 1], [1, 1, 0], [1, 0, 0], // ny [1, 0, 1], [0, 0, 1], [1, 0, 0], [0, 0, 0], // py [0, 1, 1], [1, 1, 1], [0, 1, 0], [1, 1, 0], // nz [1, 0, 0], [0, 0, 0], [1, 1, 0], [0, 1, 0], // pz [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1], ]).map((e) => e * focusBlockSize), 3, ), ); const base = [0, 1, 3, 3, 2, 0]; this.blockGeometry.setIndex( Helper.flatten([ base, base.map((e) => e + 4), base.map((e) => e + 8), base.map((e) => e + 12), base.map((e) => e + 16), base.map((e) => e + 20), ]), ); engine.on('ready', () => { this.atlasUniform = { value: null, }; this.setTexturePack(this.texturePack, () => { engine.emit('texture-loaded'); }); this.opaqueChunkMaterial = this.makeShaderMaterial(); this.transparentChunkMaterials = TRANSPARENT_SIDES.map((side) => { const material = this.makeShaderMaterial(); material.side = side; material.transparent = true; material.alphaTest = 0.3; return material; }); }); engine.on('texture-loaded', () => { Object.keys(options.blocks).forEach((idStr) => { const id = +idStr; this.focuses[idStr] = this.focus(id); }); engine.emit('focus-loaded'); }); } setTexturePack = (packName: string, onFinish?: () => void) => { this.atlasUniform.value = new TextureLoader().load( `${this.engine.network.cleanURL}atlas/${packName}-atlas.png`, () => { if (onFinish) onFinish(); Object.keys(this.options.blocks).forEach((idStr) => { const id = +idStr; this.focuses[idStr] = this.focus(id); }); this.engine.inventory.updateDOM(); }, ); const atlas = this.atlasUniform.value; atlas.minFilter = NearestFilter; atlas.magFilter = NearestFilter; atlas.generateMipmaps = false; atlas.encoding = sRGBEncoding; this.material = new MeshBasicMaterial({ map: this.atlasUniform.value, side: DoubleSide }); }; focus = (id: number) => { const { isBlock, isPlant } = this.options.blocks[id]; if (isBlock) { return this.focusBlock(id); } else if (isPlant) { return this.focusPlant(id); } }; focusBlock = (id: number) => { const { focusDist } = this.options; this.camera.position.set(focusDist, focusDist, focusDist); this.camera.lookAt(0, 0, 0); const { px, py, pz, nx, ny, nz } = this.getUV(id); const uvs = Helper.flatten([...nx[0], ...px[0], ...ny[0], ...py[0], ...nz[0], ...pz[0]]); this.blockGeometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); const mesh = new Mesh(this.blockGeometry, this.material); mesh.frustumCulled = false; while (this.bufferScene.children.length > 0) { this.bufferScene.remove(this.bufferScene.children[0]); } this.bufferScene.add(mesh); this.renderer.render(this.bufferScene, this.camera); return this.canvas.toDataURL(); }; focusPlant = (id: number) => { const { focusDist } = this.options; this.camera.position.set(0, 0, -focusDist); this.camera.lookAt(0, 1, 0); const { one } = this.getUV(id); const uvs = Helper.flatten(one[0]); this.plantGeometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); const mesh = new Mesh(this.plantGeometry, this.material); mesh.frustumCulled = false; while (this.bufferScene.children.length > 0) { this.bufferScene.remove(this.bufferScene.children[0]); } this.bufferScene.add(mesh); this.renderer.render(this.bufferScene, this.camera); return this.canvas.toDataURL(); }; getUV = (id: number): { [key: string]: [any[][], number] } => { const getUVInner = (file: string, uv: number[]): number[] => { const range = this.options.ranges[file]; if (!range) { console.error(`Range not found for: ${file}`); return; } const { startU, endU, startV, endV } = range; return [uv[0] * (endU - startU) + startU, uv[1] * (startV - endV) + endV]; }; const { isBlock, isPlant, textures } = this.options.blocks[id]; if (isBlock) { // ny const bottomUVs = [ [1, 0], [0, 0], [1, 1], [0, 1], ].map((uv) => getUVInner(textures['all'] ? textures['all'] : textures['bottom'] ? textures['bottom'] : textures['ny'], uv), ); // py const topUVs = [ [1, 1], [0, 1], [1, 0], [0, 0], ].map((uv) => getUVInner(textures['all'] ? textures['all'] : textures['top'] ? textures['top'] : textures['py'], uv), ); // nx const side1UVs = [ [0, 1], [0, 0], [1, 1], [1, 0], ].map((uv) => getUVInner(textures['all'] ? textures['all'] : textures['side'] ? textures['side'] : textures['nx'], uv), ); // px const side2UVs = [ [0, 1], [0, 0], [1, 1], [1, 0], ].map((uv) => getUVInner(textures['all'] ? textures['all'] : textures['side'] ? textures['side'] : textures['px'], uv), ); // nz const side3UVs = [ [0, 0], [1, 0], [0, 1], [1, 1], ].map((uv) => getUVInner(textures['all'] ? textures['all'] : textures['side'] ? textures['side'] : textures['nz'], uv), ); // pz const side4UVs = [ [0, 0], [1, 0], [0, 1], [1, 1], ].map((uv) => getUVInner(textures['all'] ? textures['all'] : textures['side'] ? textures['side'] : textures['pz'], uv), ); return { px: [side2UVs, 1], py: [topUVs, 3], pz: [side4UVs, 0], nx: [side1UVs, 1], ny: [bottomUVs, 1], nz: [side3UVs, 0], }; } else if (isPlant) { const oneUVs = [ [0, 1], [0, 0], [1, 1], [1, 0], ].map((uv) => getUVInner(textures['one'], uv)); return { one: [oneUVs, 1] }; } return {}; }; getFocus = (id: number) => { return this.focuses[id.toString()]; }; getBlock = (id) => { return this.options.blocks[id]; }; isPlant = (id: number) => { return this.getBlock(id) && this.getBlock(id).isPlant; }; isFluid = (id: number) => { return this.getBlock(id) && this.getBlock(id).isFluid; }; hasBlock = (id: number) => { return !!this.options.blocks[id]; }; private makeShaderMaterial = () => { const material = new ShaderMaterial({ vertexColors: true, fragmentShader: ShaderLib.basic.fragmentShader .replace( '#include <common>', ` #include <common> uniform vec3 uFogColor; uniform vec3 uFogNearColor; uniform float uFogNear; uniform float uFogFar; uniform float uSunlightIntensity; varying float vAO; varying vec4 vLight; `, ) .replace( '#include <envmap_fragment>', ` #include <envmap_fragment> float s = max(vLight.a * uSunlightIntensity * 0.8, 0.02); float scale = 1.0; outgoingLight.rgb *= vec3(s + pow(vLight.r, scale), s + pow(vLight.g, scale), s + pow(vLight.b, scale)); // outgoingLight.rgb *= vec3(s + scale / sqrt(vLight.r), s + scale / sqrt(vLight.g), s + scale / sqrt(vLight.b)); outgoingLight *= 0.88 * vAO; `, ) .replace( '#include <fog_fragment>', ` float depth = gl_FragCoord.z / gl_FragCoord.w; float fogFactor = smoothstep(uFogNear, uFogFar, depth); gl_FragColor.rgb = mix(gl_FragColor.rgb, mix(uFogNearColor, uFogColor, fogFactor), fogFactor); `, ), vertexShader: ShaderLib.basic.vertexShader .replace( '#include <common>', ` attribute int ao; attribute int light; varying float vAO; varying vec4 vLight; uniform vec4 uAOTable; vec4 unpackLight(int l) { float r = float((l >> 8) & 0xF) / 15.0; float g = float((l >> 4) & 0xF) / 15.0; float b = float(l & 0xF) / 15.0; float s = float((l >> 12) & 0xF) / 15.0; return vec4(r, g, b, s); } #include <common> `, ) .replace( '#include <color_vertex>', ` #include <color_vertex> vAO = ((ao == 0) ? uAOTable.x : (ao == 1) ? uAOTable.y : (ao == 2) ? uAOTable.z : uAOTable.w) / 255.0; vLight = unpackLight(light); `, ), uniforms: { ...UniformsUtils.clone(ShaderLib.basic.uniforms), map: this.atlasUniform, uSunlightIntensity: this.engine.world.uSunlightIntensity, uAOTable: this.aoUniform, ...this.engine.rendering.fogUniforms, }, }); // @ts-ignore material.map = this.atlasUniform.value; return material; }; } export { Registry, RegistryOptionsType };
the_stack
import { BlockInstance } from '@wordpress/blocks'; import { EditorBlockListSettings, EditorBlockMode, EditorInserterItem, EditorSelection, EditorSettings } from '../'; /** * Determines if the given block type is allowed to be inserted into the block list. * * @param blockName - The name of the block type, e.g.' core/paragraph'. * @param rootClientId - Optional root client ID of block list. * * @returns Whether the given block type is allowed to be inserted. */ export function canInsertBlockType(blockName: string, rootClientId?: string): boolean; /** * Returns the client ID of the block adjacent one at the given reference `startClientId` and modifier * directionality. Defaults start `startClientId` to the selected block, and direction as next block. * Returns `null` if there is no adjacent block. * * @param startClientId - Optional client ID of block from which to search. * @param modifier - Directionality multiplier (1 next, -1 previous). * * @returns Return the client ID of the block, or null if none exists. */ export function getAdjacentBlockClientId(startClientId?: string, modifier?: 1 | -1): string | null; /** * Returns a block given its client ID. This is a parsed copy of the block, containing its * `blockName`, `clientId`, and current `attributes` state. This is not the block's registration * settings, which must be retrieved from the blocks module registration store. * * @param clientId - Block client ID. * * @returns Parsed block object. */ export function getBlock(clientId: string): BlockInstance | null; /** * Returns a block's attributes given its client ID, or null if no block exists with the client ID. * * @param clientId - Block client ID. * * @returns Block attributes. */ export function getBlockAttributes(clientId: string): Record<string, any> | null; /** * Returns the number of blocks currently present in the post. * * @param rootClientId - Optional root client ID of block list. * * @returns Number of blocks in the post. */ export function getBlockCount(rootClientId?: string): number; /** * Given a block client ID, returns the root of the hierarchy from which the block is nested, return * the block itself for root level blocks. * * @param clientId - Block from which to find root client ID. * * @returns Root client ID */ export function getBlockHierarchyRootClientId(clientId: string): string; /** * Returns the index at which the block corresponding to the specified client ID occurs within the * block order, or `-1` if the block does not exist. * * @param clientId - Block client ID. * @param rootClientId - Optional root client ID of block list. * * @returns Index at which block exists in order. */ export function getBlockIndex(clientId: string, rootClientId?: string): number; /** * Returns the insertion point, the index at which the new inserted block would * be placed. Defaults to the last index. */ export function getBlockInsertionPoint(): { index: number; rootClientId?: string | undefined }; /** * Returns the Block List settings of a block, if any exist. * * @param clientId - Block client ID. * * @returns Block settings of the block if set. */ export function getBlockListSettings(clientId?: string): EditorBlockListSettings | undefined; /** * Returns the block's editing mode, defaulting to `"visual"` if not explicitly assigned. * * @param clientId - Block client ID. * * @returns Block editing mode. */ export function getBlockMode(clientId: string): EditorBlockMode; /** * Returns a block's name given its client ID, or `null` if no block exists with the client ID. * * @param clientId - Block client ID. * * @returns Block name. */ export function getBlockName(clientId: string): string | null; /** * Returns an array containing all block client IDs in the editor in the order they appear. * Optionally accepts a root client ID of the block list for which the order should be returned, * defaulting to the top-level block order. * * @param rootClientId - Optional root client ID of block list. * * @returns Ordered client IDs of editor blocks. */ export function getBlockOrder(rootClientId?: string): string[]; /** * Given a block client ID, returns the root block from which the block is nested, an empty string * for top-level blocks, or `null` if the block does not exist. * * @param clientId - Block from which to find root client ID. * * @returns Root client ID, if exists */ export function getBlockRootClientId(clientId: string): string | null; /** * Returns the current block selection end. This value may be `undefined`, and it may represent either a * singular block selection or multi-selection end. A selection is singular if its start and end * match. * * @returns Client ID of block selection end. */ export function getBlockSelectionEnd(): string | undefined; /** * Returns the current block selection start. This value may be `undefined`, and it may represent * either a singular block selection or multi-selection start. A selection is singular if its start * and end match. * * @returns Client ID of block selection start. */ export function getBlockSelectionStart(): string | undefined; /** * Returns all block objects for the current post being edited as an array in the order they appear * in the post. * * Note: It's important to memoize this selector to avoid return a new instance * on each call * * @param rootClientId - Optional root client ID of block list. * * @returns Post blocks. */ export function getBlocks(rootClientId?: string): BlockInstance[]; /** * Given an array of block client IDs, returns the corresponding array of block objects or `null`. * * @param clientIds - Client IDs for which blocks are to be returned. */ export function getBlocksByClientId(clientIds: string | string[]): Array<BlockInstance | null>; /** * Returns an array containing the clientIds of all descendants of the blocks given. * * @param clientIds - Array of block ids to inspect. * * @returns ids of descendants. */ export function getClientIdsOfDescendants(clientIds: string[]): string[]; /** * Returns an array containing the `clientIds` of the top-level blocks and their descendants of any * depth (for nested blocks). * * @returns ids of top-level and descendant blocks. */ export function getClientIdsWithDescendants(): string[]; /** * Returns the client ID of the first block in the multi-selection set, or `null` if there is no * multi-selection. * * @returns First block client ID in the multi-selection set. */ export function getFirstMultiSelectedBlockClientId(): string | null; /** * Returns the total number of blocks, or the total number of blocks with a specific name in a post. * The number returned includes nested blocks. * * @param blockName - Optional block name, if specified only blocks of that type will be counted. * * @returns Number of blocks in the post, or number of blocks with name equal to `blockName`. */ export function getGlobalBlockCount(blockName?: string): number; /** * Determines the items that appear in the inserter. Includes both static items (e.g. a regular * block type) and dynamic items (e.g. a reusable block). * * @remarks * Each item object contains what's necessary to display a button in the inserter and handle its * selection. * * The `utility` property indicates how useful we think an item will be to the user. There are 4 * levels of utility: * * 1. Blocks that are contextually useful (utility = 3) * 2. Blocks that have been previously inserted (utility = 2) * 3. Blocks that are in the common category (utility = 1) * 4. All other blocks (utility = 0) * * The `frecency` property is a heuristic (https://en.wikipedia.org/wiki/Frecency) * that combines block usage frequenty and recency. * * Items are returned ordered descendingly by their `utility` and `frecency`. * * @param rootClientId - Optional root client ID of block list. * * @returns Items that appear in inserter. */ export function getInserterItems(rootClientId?: string): EditorInserterItem[]; /** * Returns the client ID of the last block in the multi-selection set, or `null` if there is no * multi-selection. * * @returns Last block client ID in the multi-selection set. */ export function getLastMultiSelectedBlockClientId(): string | null; /** * Returns the current multi-selection set of block client IDs, or an empty array if there is no * multi-selection. * * @returns Multi-selected block client IDs. */ export function getMultiSelectedBlockClientIds(): string[]; /** * Returns the current multi-selection set of blocks, or an empty array if there is no * multi-selection. * * @returns Multi-selected block objects. */ export function getMultiSelectedBlocks(): BlockInstance[]; /** * Returns the client ID of the block which ends the multi-selection set, or `null` if there is no * multi-selection. * * This is not necessarily the last client ID in the selection. * * @see getLastMultiSelectedBlockClientId * * @returns Client ID of block ending multi-selection. */ export function getMultiSelectedBlocksEndClientId(): string | null; /** * Returns the client ID of the block which begins the multi-selection set, or `null` if there is no * multi-selection. * * This is not necessarily the first client ID in the selection. * * @see getFirstMultiSelectedBlockClientId * * @returns Client ID of block beginning multi-selection. */ export function getMultiSelectedBlocksStartClientId(): string | null; /** * Returns the next block's client ID from the given reference start ID. Defaults start to the * selected block. Returns `null` if there is no next block. * * @param startClientId - Optional client ID of block from which to search. * * @returns Adjacent block's client ID, or `null` if none exists. */ export function getNextBlockClientId(startClientId?: string): string | null; /** * Returns the previous block's client ID from the given reference start ID. Defaults start to the * selected block. Returns `null` if there is no previous block. * * @param startClientId - Optional client ID of block from which to search. * * @returns Adjacent block's client ID, or `null` if none exists. */ export function getPreviousBlockClientId(startClientId?: string): string | null; /** * Returns the currently selected block, or `null` if there is no selected block. * * @returns Selected block. */ export function getSelectedBlock(): BlockInstance | null; /** * Returns the currently selected block client ID, or `null` if there is no selected block. * * @returns Selected block client ID. */ export function getSelectedBlockClientId(): string | null; /** * Returns the current selection set of block client IDs (multiselection or single selection). * * @returns Multi-selected block client IDs. */ export function getSelectedBlockClientIds(): string[]; /** * Returns the number of blocks currently selected in the post. * * @returns Number of blocks selected in the post. */ export function getSelectedBlockCount(): number; /** * Returns the initial caret position for the selected block. This position is to used to position * the caret properly when the selected block changes. */ export function getSelectedBlocksInitialCaretPosition(): number | null; /** * Returns the current selection end. * * @returns Selection end information. */ export function getSelectionEnd(): EditorSelection; /** * Returns the current selection start. * * @returns Selection start information. */ export function getSelectionStart(): EditorSelection; /** * Returns the editor settings. */ export function getSettings(): EditorSettings; // FIXME: This is poorly documented. It's not clear what this is. /** * Returns the defined block template. */ export function getTemplate(): any; /** * Returns the defined block template lock. Optionally accepts a root block client ID as context, * otherwise defaulting to the global context. * * @param rootClientId - Optional block root client ID. * * @returns Block Template Lock */ export function getTemplateLock(rootClientId?: string): string | undefined; /** * Determines whether there are items to show in the inserter. * * @param rootClientId - Optional root client ID of block list. * * @returns Items that appear in inserter. */ export function hasInserterItems(rootClientId?: string): boolean; /** * Returns `true` if a multi-selection has been made, or `false` otherwise. * * @returns Whether multi-selection has been made. */ export function hasMultiSelection(): boolean; /** * Returns `true` if there is a single selected block, or `false` otherwise. * * @returns Whether a single block is selected. */ export function hasSelectedBlock(): boolean; /** * Returns `true` if one of the block's inner blocks is selected. * * @param clientId - Block client ID. * @param deep - Perform a deep check. (default: `true`) * * @returns Whether the block as an inner block selected */ export function hasSelectedInnerBlock(clientId: string, deep?: boolean): boolean; /** * Returns `true` if an ancestor of the block is multi-selected, or `false` otherwise. * * @param clientId - Block client ID. * * @returns Whether an ancestor of the block is in multi-selection set. */ export function isAncestorMultiSelected(clientId: string): boolean; /** * Returns `true` if we should show the block insertion point. * * @returns Whether the insertion point is visible or not. */ export function isBlockInsertionPointVisible(): boolean; /** * Returns `true` if the client ID occurs within the block multi-selection, or `false` otherwise. * * @param clientId - Block client ID. * * @returns Whether block is in multi-selection set. */ export function isBlockMultiSelected(clientId: string): boolean; /** * Returns `true` if the block corresponding to the specified client ID is currently selected and no * multi-selection exists, or `false` otherwise. * * @param clientId - Block client ID. * * @returns Whether block is selected and multi-selection exists. */ export function isBlockSelected(clientId: string): boolean; /** * Returns whether a block is valid or not. * * @param clientId - Block client ID. * * @returns Is Valid. */ export function isBlockValid(clientId: string): boolean; /** * Returns `true` if the block corresponding to the specified client ID is currently selected but * isn't the last of the selected blocks. Here "last" refers to the block sequence in the document, * _not_ the sequence of multi-selection, which is why `state.blockSelection.end` isn't used. * * @param clientId - Block client ID. * * @returns Whether block is selected and not the last in the selection. */ export function isBlockWithinSelection(clientId: string): boolean; /** * Returns `true` if the caret is within formatted text, or `false` otherwise. * * @returns Whether the caret is within formatted text. */ export function isCaretWithinFormattedText(): boolean; /** * Returns `true` if a multi-selection exists, and the block corresponding to the specified client * ID is the first block of the multi-selection set, or `false` otherwise. * * @param clientId - Block client ID. * * @returns Whether block is first in multi-selection. */ export function isFirstMultiSelectedBlock(clientId: string): boolean; /** * Returns `true` if the most recent block change is be considered persistent, or `false` otherwise. * A persistent change is one committed by BlockEditorProvider via its `onChange` callback, in * addition to `onInput`. * * @returns Whether the most recent block change was persistent. */ export function isLastBlockChangePersistent(): boolean; /** * Whether in the process of multi-selecting or not. This flag is only `true` while the * multi-selection is being selected (by mouse move), and is `false` once the multi-selection has * been settled. * * @see hasMultiSelection * * @returns `true` if multi-selecting, `false` if not. */ export function isMultiSelecting(): boolean; /** * Selector that returns if multi-selection is enabled or not. * * @returns `true` if it should be possible to multi-select blocks, `false` if multi-selection is * disabled. */ export function isSelectionEnabled(): boolean; /** * Returns `true` if the user is typing, or `false` otherwise. * * @returns Whether user is typing. */ export function isTyping(): boolean; /** * Returns whether the blocks matches the template or not. * * @returns Whether the template is valid or not. */ export function isValidTemplate(): boolean;
the_stack
import { ANTLRv4ParserListener } from "../parser/ANTLRv4ParserListener"; import { LexerRuleSpecContext, ParserRuleSpecContext, TokensSpecContext, ChannelsSpecContext, ModeSpecContext, DelegateGrammarContext, TerminalRuleContext, RulerefContext, BlockContext, AlternativeContext, RuleBlockContext, EbnfSuffixContext, OptionsSpecContext, ActionBlockContext, ArgActionBlockContext, LabeledElementContext, LexerRuleBlockContext, LexerAltContext, ElementContext, LexerElementContext, NamedActionContext, LexerCommandContext, OptionContext, OptionValueContext, ANTLRv4Parser, } from "../parser/ANTLRv4Parser"; import { ContextSymbolTable, FragmentTokenSymbol, TokenSymbol, TokenReferenceSymbol, RuleSymbol, RuleReferenceSymbol, VirtualTokenSymbol, TokenChannelSymbol, LexerModeSymbol, ImportSymbol, AlternativeSymbol, EbnfSuffixSymbol, ArgumentSymbol, OperatorSymbol, GlobalNamedActionSymbol, ExceptionActionSymbol, FinallyActionSymbol, ParserActionSymbol, LexerActionSymbol, OptionsSymbol, OptionSymbol, LexerPredicateSymbol, ParserPredicateSymbol, LocalNamedActionSymbol, LexerCommandSymbol, TerminalSymbol, } from "./ContextSymbolTable"; import { SourceContext } from "./SourceContext"; import { LiteralSymbol, BlockSymbol, Symbol, VariableSymbol } from "antlr4-c3"; import { ParseTree, TerminalNode } from "antlr4ts/tree"; import { ANTLRv4Lexer } from "../parser/ANTLRv4Lexer"; export class DetailsListener implements ANTLRv4ParserListener { private symbolStack: Symbol[] = []; public constructor(private symbolTable: ContextSymbolTable, private imports: string[]) { } public enterParserRuleSpec(ctx: ParserRuleSpecContext): void { this.pushNewSymbol(RuleSymbol, ctx, ctx.RULE_REF().text); } public exitParserRuleSpec(ctx: ParserRuleSpecContext): void { this.popSymbol(); } public enterRuleBlock(ctx: RuleBlockContext): void { this.pushNewSymbol(BlockSymbol, ctx, ""); } public exitRuleBlock(): void { this.popSymbol(); } public enterLexerRuleSpec(ctx: LexerRuleSpecContext): void { if (ctx.FRAGMENT()) { this.pushNewSymbol(FragmentTokenSymbol, ctx, ctx.TOKEN_REF().text); } else { this.pushNewSymbol(TokenSymbol, ctx, ctx.TOKEN_REF().text); } } public exitLexerRuleSpec(): void { this.popSymbol(); } public enterLexerRuleBlock(ctx: LexerRuleBlockContext): void { this.pushNewSymbol(BlockSymbol, ctx, ""); } public exitLexerRuleBlock(ctx: LexerRuleBlockContext): void { this.popSymbol(); } public enterBlock(ctx: BlockContext): void { this.pushNewSymbol(BlockSymbol, ctx, ""); } public exitBlock(ctx: BlockContext): void { this.popSymbol(); } public enterAlternative(ctx: AlternativeContext): void { this.pushNewSymbol(AlternativeSymbol, ctx, ""); } public exitAlternative(ctx: AlternativeContext): void { this.popSymbol(); } public enterLexerAlt(ctx: LexerAltContext): void { this.pushNewSymbol(AlternativeSymbol, ctx, ""); } public exitLexerAlt(ctx: LexerAltContext): void { this.popSymbol(); } public exitTokensSpec(ctx: TokensSpecContext): void { const idList = ctx.idList(); if (idList) { for (const identifier of idList.identifier()) { this.addNewSymbol(VirtualTokenSymbol, ctx, identifier.text); } } } public exitChannelsSpec(ctx: ChannelsSpecContext): void { const idList = ctx.idList(); if (idList) { for (const identifier of idList.identifier()) { this.addNewSymbol(TokenChannelSymbol, ctx, identifier.text); } } } public exitTerminalRule(ctx: TerminalRuleContext): void { let token = ctx.TOKEN_REF(); if (token) { this.addNewSymbol(TokenReferenceSymbol, ctx, token.text); } else { // Must be a string literal then. token = ctx.STRING_LITERAL(); if (token) { const refName = unquote(token.text, "'"); this.addNewSymbol(LiteralSymbol, token, refName, refName); } } } public exitRuleref(ctx: RulerefContext): void { const token = ctx.RULE_REF(); if (token) { this.addNewSymbol(RuleReferenceSymbol, ctx, token.text); } } public exitModeSpec(ctx: ModeSpecContext): void { this.addNewSymbol(LexerModeSymbol, ctx, ctx.identifier().text); } public exitDelegateGrammar(ctx: DelegateGrammarContext): void { const context = ctx.identifier()[ctx.identifier().length - 1]; if (context) { const name = SourceContext.definitionForContext(context, false)!.text; this.addNewSymbol(ImportSymbol, context, name); this.imports.push(name); } } public enterOptionsSpec(ctx: OptionsSpecContext): void { this.pushNewSymbol(OptionsSymbol, ctx, "options"); } public exitOptionsSpec(ctx: OptionsSpecContext): void { this.popSymbol(); } public exitOption(ctx: OptionContext): void { const option = ctx.identifier().text; const valueContext = ctx.tryGetRuleContext(0, OptionValueContext); if (valueContext && valueContext.childCount > 0) { const symbol = this.addNewSymbol(OptionSymbol, valueContext.getChild(0), option); symbol.value = valueContext.text; if (option === "tokenVocab") { this.imports.push(valueContext.text); } } } /** * Handles all types of native actions in various locations, instead of doing that in individual listener methods. * * @param ctx The parser context for the action block. */ public exitActionBlock(ctx: ActionBlockContext): void { let run = ctx.parent; while (run) { switch (run.ruleIndex) { case ANTLRv4Parser.RULE_optionValue: { // The grammar allows to assign a native action block to an option variable, but ANTLR4 itself // doesn't accept that. So we ignore it here too. return; } case ANTLRv4Parser.RULE_namedAction: { // Global level named action, like @parser. const localContext = run as NamedActionContext; let prefix = ""; if (localContext.actionScopeName()) { prefix = localContext.actionScopeName()?.text + "::"; } const symbol = this.addNewSymbol(GlobalNamedActionSymbol, ctx, prefix + localContext.identifier().text); this.symbolTable.defineNamedAction(symbol); return; } case ANTLRv4Parser.RULE_exceptionHandler: { this.addNewSymbol(ExceptionActionSymbol, ctx); return; } case ANTLRv4Parser.RULE_finallyClause: { this.addNewSymbol(FinallyActionSymbol, ctx); return; } case ANTLRv4Parser.RULE_ruleAction: { // Rule level named actions, like @init. const symbol = this.addNewSymbol(LocalNamedActionSymbol, ctx, this.ruleName); this.symbolTable.defineNamedAction(symbol); return; } case ANTLRv4Parser.RULE_lexerElement: { // Lexer inline action or predicate. const localContext = run as LexerElementContext; if (localContext.QUESTION()) { const symbol = this.addNewSymbol(LexerPredicateSymbol, ctx); this.symbolTable.definePredicate(symbol); } else { const symbol = this.addNewSymbol(LexerActionSymbol, ctx); this.symbolTable.defineLexerAction(symbol); } return; } case ANTLRv4Parser.RULE_element: { // Parser inline action or predicate. const localContext = run as ElementContext; if (localContext.QUESTION()) { const symbol = this.addNewSymbol(ParserPredicateSymbol, ctx); this.symbolTable.definePredicate(symbol); } else { const symbol = this.addNewSymbol(ParserActionSymbol, ctx); this.symbolTable.defineParserAction(symbol); } return; } default: { run = run.parent; break; } } } } /** * Handles argument action code blocks. * * @param ctx The parser context for the action block. */ public exitArgActionBlock(ctx: ArgActionBlockContext): void { if (this.symbolStack.length === 0) { return; } let run = ctx.parent; while (run && run !== this.symbolStack[0].context) { run = run.parent; } if (run) { switch (run.ruleIndex) { case ANTLRv4Parser.RULE_exceptionHandler: { this.addNewSymbol(ArgumentSymbol, ctx, "exceptionHandler"); break; } case ANTLRv4Parser.RULE_finallyClause: { this.addNewSymbol(ArgumentSymbol, ctx, "finallyClause"); break; } case ANTLRv4Parser.RULE_ruleReturns: { this.addNewSymbol(ArgumentSymbol, ctx, "ruleReturns"); break; } case ANTLRv4Parser.RULE_localsSpec: { this.addNewSymbol(ArgumentSymbol, ctx, "localsSpec"); break; } case ANTLRv4Parser.RULE_ruleref: { this.addNewSymbol(ArgumentSymbol, ctx, "ruleRef"); break; } case ANTLRv4Parser.RULE_parserRuleSpec: { this.addNewSymbol(ArgumentSymbol, ctx, "parserRuleSpec"); break; } default: { break; } } } } public exitEbnfSuffix(ctx: EbnfSuffixContext): void { this.addNewSymbol(EbnfSuffixSymbol, ctx, ctx.text); } public enterLexerCommand(ctx: LexerCommandContext): void { this.pushNewSymbol(LexerCommandSymbol, ctx, ctx.lexerCommandName().text); } public exitLexerCommand(ctx: LexerCommandContext): void { this.popSymbol(); } public exitLabeledElement(ctx: LabeledElementContext): void { this.addNewSymbol(VariableSymbol, ctx, ctx.identifier().text); } public visitTerminal = (node: TerminalNode): void => { // Ignore individual terminals under certain circumstances. if (this.currentSymbol() instanceof LexerCommandSymbol) { return; } switch (node.symbol.type) { case ANTLRv4Lexer.COLON: case ANTLRv4Lexer.COLONCOLON: case ANTLRv4Lexer.COMMA: case ANTLRv4Lexer.SEMI: case ANTLRv4Lexer.LPAREN: case ANTLRv4Lexer.RPAREN: case ANTLRv4Lexer.LBRACE: case ANTLRv4Lexer.RBRACE: case ANTLRv4Lexer.RARROW: case ANTLRv4Lexer.LT: case ANTLRv4Lexer.GT: case ANTLRv4Lexer.ASSIGN: case ANTLRv4Lexer.QUESTION: case ANTLRv4Lexer.STAR: case ANTLRv4Lexer.PLUS_ASSIGN: case ANTLRv4Lexer.PLUS: case ANTLRv4Lexer.OR: case ANTLRv4Lexer.DOLLAR: case ANTLRv4Lexer.RANGE: case ANTLRv4Lexer.DOT: case ANTLRv4Lexer.AT: case ANTLRv4Lexer.POUND: case ANTLRv4Lexer.NOT: { this.addNewSymbol(OperatorSymbol, node, node.text); break; } default: { if (node.symbol.type !== ANTLRv4Lexer.ACTION_CONTENT) { this.addNewSymbol(TerminalSymbol, node, node.text); } break; } } }; private currentSymbol<T extends Symbol>(): T | undefined { if (this.symbolStack.length === 0) { return undefined; } return this.symbolStack[this.symbolStack.length - 1] as T; } /** * Adds a new symbol to the current symbol TOS. * * @param type The type of the symbol to add. * @param context The symbol's parse tree, to allow locating it. * @param args The actual arguments for the new symbol. * * @returns The new symbol. */ private addNewSymbol<T extends Symbol>(type: new (...args: any[]) => T, context: ParseTree, ...args: any[]): T { const symbol = this.symbolTable.addNewSymbolOfType(type, this.currentSymbol(), ...args); symbol.context = context; return symbol; } /** * Creates a new symbol and starts a new scope with it on the symbol stack. * * @param type The type of the symbol to add. * @param context The symbol's parse tree, to allow locating it. * @param args The actual arguments for the new symbol. * * @returns The new scoped symbol. */ private pushNewSymbol<T extends Symbol>(type: new (...args: any[]) => T, context: ParseTree, ...args: any[]): Symbol { const symbol = this.symbolTable.addNewSymbolOfType<T>(type, this.currentSymbol(), ...args); symbol.context = context; this.symbolStack.push(symbol); return symbol; } private popSymbol(): Symbol | undefined { return this.symbolStack.pop(); } /** * The symbol stack usually contains entries beginning with a rule context, followed by a number of blocks and alts * as well as additional parts like actions or predicates. * This function returns the name of the first symbol, which represents the rule (parser/lexer) which we are * currently walking over. * * @returns The rule name from the start symbol. */ private get ruleName(): string { return this.symbolStack.length === 0 ? "" : this.symbolStack[0].name; } } /** * Removes outer quotes from the input. * * @param input The input to clean up. * @param quoteChar The quote char to remove. * * @returns The cleaned string. */ const unquote = (input: string, quoteChar?: string): string => { quoteChar = quoteChar || '"'; if (input[0] === quoteChar && input[input.length - 1] === quoteChar) { return input.slice(1, input.length - 1); } return input; };
the_stack