text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { gte, lt, lte } from "semver" import { RawHero as RawHeroFromSchema } from "../../../../../../app/Schema/Hero/Hero" import { notP } from "../../../../../Data/Bool" import { fmap } from "../../../../../Data/Functor" import { all } from "../../../../../Data/List" import { bindF, ensure, fromMaybe, Maybe, maybe_ } from "../../../../../Data/Maybe" import { lookupF } from "../../../../../Data/OrderedMap" import { Culture } from "../../../../Models/Wiki/Culture" import { L10n } from "../../../../Models/Wiki/L10n" import { IncreaseSkill } from "../../../../Models/Wiki/sub/IncreaseSkill" import { StaticData, StaticDataRecord } from "../../../../Models/Wiki/WikiModel" import { current_version } from "../../../../Selectors/envSelectors" import { getBlessedTradStrIdFromNumId, getMagicalTraditionInstanceIdByNumericId } from "../../../IDUtils" import { hasOwnProperty } from "../../../Object" import { pipe, pipe_ } from "../../../pipe" import { isNumber } from "../../../typeCheckUtils" import { RawCustomItem120alpha11, RawCustomItem130alpha2, RawHero, RawHero120alpha11, RawHero130alpha2, RawHeroBase } from "../../RawData" const SDA = StaticData.A export const MIN_SUPPORTED_VERSION = "0.49.5" export const MAX_SUPPORTED_VERSION = current_version const shallowClone = <A extends object> (x: A): A => ({ ...x }) const fromEntries = <A> (xs: [string, A][]): { [key: string]: A } => { const obj: { [key: string]: A } = {} xs.forEach (x => { obj [x[0]] = x[1] }) return obj } const convertLT = (lower_than_version: string) => <H1 extends RawHeroBase, H2 extends RawHeroBase> (f: (old: H1) => H2) => (hero: H1): H2 => lt (hero.clientVersion, lower_than_version) ? { ...(f (hero)), clientVersion: lower_than_version } : hero as unknown as H2 export const convertHero = (staticData: StaticDataRecord): (orig_hero: RawHeroFromSchema) => Maybe<RawHero> => pipe ( shallowClone, ensure ((hero: RawHeroFromSchema) => gte (hero .clientVersion, MIN_SUPPORTED_VERSION) && lte (hero .clientVersion, MAX_SUPPORTED_VERSION)), fmap (pipe ( pipe ( convertLT ("0.51.1-alpha.2") (hero => { const entry = { ...hero } const oldRaceId = entry.r switch (oldRaceId) { case "R_1": entry.r = "R_1" entry.rv = "RV_1" break case "R_2": entry.r = "R_1" entry.rv = "RV_2" break case "R_3": entry.r = "R_1" entry.rv = "RV_3" break case "R_4": entry.r = "R_1" entry.rv = "RV_4" break case "R_5": entry.r = "R_1" entry.rv = "RV_5" break case "R_6": entry.r = "R_1" entry.rv = "RV_6" break case "R_7": entry.r = "R_1" entry.rv = "RV_7" break case "R_8": entry.r = "R_2" entry.rv = "RV_1" break case "R_9": entry.r = "R_2" entry.rv = "RV_2" break case "R_10": entry.r = "R_2" entry.rv = "RV_3" break case "R_11": entry.r = "R_3" break case "R_12": entry.r = "R_4" break default: break } entry.rules = { ...entry.rules, enableAllRuleBooks: true, enabledRuleBooks: [], } entry.clientVersion = "0.51.1" return entry as RawHero120alpha11 }), convertLT ("0.51.3-alpha.4") (hero => { const entry = { ...hero } if (hasOwnProperty ("SA_243") (entry.activatable) && hasOwnProperty ("SA_255") (entry.activatable)) { const { SA_255: _, ...other } = entry.activatable entry.activatable = other // @ts-ignore entry.ap.spent -= 10 } else if (hasOwnProperty ("SA_255") (entry.activatable)) { const { SA_255: arr, ...other } = entry.activatable entry.activatable = { ...other, SA_243: arr, } } entry.clientVersion = "0.51.3" return entry }), convertLT ("0.51.4-alpha.7") (hero => { const entry = { ...hero } if (hasOwnProperty ("SA_344") (entry.activatable)) { entry.activatable = { ...entry.activatable, SA_344: [ { sid: "CT_3" } ], } } if (hasOwnProperty ("SA_345") (entry.activatable)) { const { SA_344: arr, ...other } = entry.activatable if (Array.isArray (arr)) { entry.activatable = { ...other, SA_344: [ ...arr, { sid: "CT_12" } ], } } else { entry.activatable = { ...other, SA_344: [ { sid: "CT_12" } ], } } } if (hasOwnProperty ("SA_346") (entry.activatable)) { const { SA_344: arr, ...other } = entry.activatable if (Array.isArray (arr)) { entry.activatable = { ...other, SA_344: [ ...arr, { sid: "CT_16" } ], } } else { entry.activatable = { ...other, SA_344: [ { sid: "CT_16" } ], } } } if (hasOwnProperty ("SA_70") (entry.activatable)) { const { SA_70: arr, ...other } = entry.activatable entry.activatable = other for (const active of arr) { const { sid, sid2 } = active const id = getMagicalTraditionInstanceIdByNumericId (sid as number) // @ts-ignore entry.activatable[fromMaybe ("SA_70") (id)] = [ { sid: sid2 } ] } } if (hasOwnProperty ("SA_86") (entry.activatable)) { const { SA_86: arr, ...other } = entry.activatable entry.activatable = other for (const active of arr) { const { sid, sid2 } = active const id = getBlessedTradStrIdFromNumId (sid as number) // @ts-ignore entry.activatable[fromMaybe ("SA_86") (id)] = [ { sid: sid2 } ] } } if (hasOwnProperty ("DISADV_34") (entry.activatable)) { entry.activatable = { ...entry.activatable, DISADV_34: entry.activatable.DISADV_34.map (e => { switch (e.sid) { case 5: return { sid: 1, tier: 2 } case 6: return { sid: 5, tier: 2 } case 7: return { sid: 6, tier: 2 } case 8: return { sid: 7, tier: 2 } case 9: return { sid: 8, tier: 2 } case 10: return { sid: 9, tier: 2 } case 11: return { sid: 10, tier: 2 } case 12: return { sid: 11, tier: 2 } case 13: return { sid: 1, tier: 3 } case 14: return { sid: 12, tier: 3 } default: return e } }), } } entry.clientVersion = "0.51.4" return entry }), convertLT ("1.0.0") (hero => { const entry = { ...hero } if ( hasOwnProperty ("DISADV_45") (entry.activatable) && entry.activatable.DISADV_45.some (e => e.sid === 1) ) { entry.pers.haircolor = 24 entry.pers.eyecolor = 19 } return entry }), convertLT ("1.0.2") (hero => { const adjValue = hero.r === "R_1" || hero.r === "R_3" ? 1 : hero.r === "R_2" || hero.r === "R_4" ? -2 : 0 // @ts-ignore let index = hero.attr.values.findIndex (e => e[2] === adjValue) if (index === -1) { // @ts-ignore index = hero.attr.values.findIndex (e => e[2] !== 0) } return { ...hero, attr: { ...hero.attr, values: hero.attr.values.map ((e, i) => { // @ts-ignore const inter = [ ...e ] as [string, number, number] inter[2] = i === index ? adjValue : 0 return inter }), }, } as unknown as RawHero }), convertLT ("1.1.0-alpha.1") (hero => ({ ...hero, attr: { ...hero.attr, // @ts-ignore values: hero .attr .values .map (e => ({ id: e[0], value: e[1] })), attributeAdjustmentSelected: [ "R_1", "R_3" ] .includes (hero .r!) ? hero .attr .values .reduce ( // @ts-ignore (acc, e) => e[2] === 1 ? e[0] : acc, "ATTR_1" ) : hero .r === "R_2" ? hero .attr .values .reduce ( // @ts-ignore (acc, e) => e[0] === "ATTR_2" && e[2] === 1 ? e[0] : acc, "ATTR_8" ) : hero .attr .values .reduce ( // @ts-ignore (acc, e) => e[0] === "ATTR_4" && e[2] === 1 ? e[0] : acc, "ATTR_6" ), }, // ct: Object.entries (hero.ct) // .reduce<StringKeyObject<number>> ((acc, e) => ({ ...acc, [e[0]]: e[1] - 6 }), {}), })), convertLT ("1.1.0-alpha.9") ((hero): RawHero120alpha11 => ({ ...hero, locale: L10n.A.id (SDA.ui (staticData)), belongings: { ...hero.belongings, items: pipe_ ( hero.belongings.items, Object.entries, (xs: [string, RawCustomItem120alpha11][]) => xs .map<[string, RawCustomItem120alpha11]> ( x => [ x[0], { ...x[1], reloadTime: isNumber (x[1].reloadTime) ? (x[1].reloadTime as number).toString () : x[1].reloadTime, stp: isNumber (x[1].stp) ? (x[1].stp as number).toString () : x[1].stp, }, ] ), fromEntries ), }, })), convertLT ("1.1.0-alpha.18") (hero => hero.activatable.DISADV_48 === undefined ? hero : ({ ...hero, activatable: { ...hero.activatable, DISADV_48: hero.activatable.DISADV_48 .filter (activeObj => typeof activeObj .sid === "string" && /^TAL_/u .test (activeObj .sid)), }, })), convertLT ("1.1.0-alpha.20") (hero => { let activatable = { ...hero.activatable } const editBase = (base: string) => { if (activatable [base] !== undefined && activatable [base] .length === 1) { activatable = { ...activatable, [base]: [ { sid: 1 } ], } } } const editOther = (base: string) => (id: string) => (sid: number) => { if (activatable [id] !== undefined && activatable [id] .length === 1) { activatable = { ...activatable, [base]: activatable [base] === undefined ? [ { sid } ] : [ ...activatable [base], { sid } ], } } } editBase ("ADV_18") editOther ("ADV_18") ("ADV_19") (2) editOther ("ADV_18") ("ADV_20") (3) editOther ("ADV_18") ("ADV_21") (4) editBase ("DISADV_7") editOther ("DISADV_7") ("DISADV_8") (2) editOther ("DISADV_7") ("DISADV_9") (3) editOther ("DISADV_7") ("DISADV_10") (4) return ({ ...hero, activatable, }) }), convertLT ("1.2.0-alpha.6") (hero => pipe_ ( // Try to infer if player used cultural package // To check that, we compare all skills of the cultural package // if the actual SRs from the character are at least as high // as the bonus from the package is Maybe (hero .c), bindF (lookupF (SDA.cultures (staticData))), maybe_ (() => ({ ...hero, isCulturalPackageActive: false, })) (pipe ( Culture.A.culturalPackageSkills, all (skill => hero .talents [IncreaseSkill.A.id (skill)] >= IncreaseSkill.A.value (skill)), isCulturalPackageActive => ({ ...hero, isCulturalPackageActive, }) )) )), convertLT ("1.2.0-alpha.7") // Fix Stigma (Green Hair) actually allow green hair in // personal data ((hero: RawHero120alpha11) => hasOwnProperty ("DISADV_45") (hero .activatable) && hero .activatable .DISADV_45 .some (e => e .sid === 3) ? { ...hero, pers: { ...hero.pers, haircolor: 25, }, } : hero) ), pipe ( convertLT ("1.2.0-alpha.11") // Fix Stigma (Green Hair) actually allow green hair in // personal data (hero => hasOwnProperty ("SA_250") (hero .activatable) && hero .activatable .SA_250 .some (e => Object.keys (hero .spells) .every (id => id !== e.sid)) ? { ...hero, activatable: { SA_250: [], }, } : hero), convertLT ("1.3.0-alpha.2") // Fix different types for structure points and reload time // for items ((hero: RawHero120alpha11): RawHero130alpha2 => ({ ...hero, belongings: { ...hero.belongings, items: pipe_ ( hero.belongings.items, Object.entries, items => items.map ( ([ k, h ]: [string, RawCustomItem120alpha11]): [string, RawCustomItem130alpha2] => [ k, { ...h, reloadTime: h.reloadTime === undefined ? undefined : pipe_ ( h.reloadTime .split ("/") .map (x => Number.parseInt (x, 10)) .filter (notP (Number.isNaN)), xs => xs.length === 0 ? undefined : xs.length === 1 ? xs[0] : xs ), stp: h.reloadTime === undefined ? undefined : pipe_ ( h.reloadTime .split ("/") .map (x => Number.parseInt (x, 10)) .filter (notP (Number.isNaN)), xs => xs.length === 0 ? undefined : xs.length === 1 ? xs[0] : xs ), primaryThreshold: h.primaryThreshold === undefined ? undefined : h.primaryThreshold.primary === undefined ? h.primaryThreshold : { ...h.primaryThreshold, primary: h.primaryThreshold.primary === "ATTR_6_8" ? [ "ATTR_6", "ATTR_8" ] : h.primaryThreshold.primary, }, }, ] ), Object.fromEntries ), }, })) ) )) )
the_stack
import React, {useState, useEffect, useContext, useRef} from "react"; import axios from "axios"; import moment from "moment"; import {RouteComponentProps, withRouter} from "react-router-dom"; import {UserContext} from "../util/user-context"; import styles from "./Detail.module.scss"; import TableView from "../components/table-view/table-view"; import DetailHeader from "../components/detail-header/detail-header"; import AsyncLoader from "../components/async-loader/async-loader"; import {Layout, Menu, PageHeader} from "antd"; import {xmlParser, xmlDecoder, xmlFormatter, jsonFormatter} from "../util/record-parser"; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {faThList, faCode, faInfoCircle} from "@fortawesome/free-solid-svg-icons"; import {MLTooltip, MLTable} from "@marklogic/design-system"; import {getUserPreferences, updateUserPreferences} from "../services/user-preferences"; import DetailPageNonEntity from "../components/detail-page-non-entity/detail-page-non-entity"; import {SearchContext} from "../util/search-context"; import {fetchQueries} from "../api/queries"; import {AuthoritiesContext} from "../util/authorities"; interface Props extends RouteComponentProps<any> { } const {Content} = Layout; const Detail: React.FC<Props> = ({history, location}) => { const {setSavedQueries} = useContext(SearchContext); const {user, handleError} = useContext(UserContext); const [parentPagePreferences, setParentPagePreferences] = useState({}); const getPreferences = () => { let currentPref = getUserPreferences(user.name); if (currentPref !== null) { return JSON.parse(currentPref); } return currentPref; }; const detailPagePreferences = getPreferences(); //Fetching preferences first to be used later everywhere in the component const uri = location.state && location.state["uri"] ? location.state["uri"] : detailPagePreferences["uri"]; const database = location.state && location.state["database"] ? location.state["database"] : detailPagePreferences["database"]; const pkValue = location.state && location.state["primaryKey"] ? location.state["primaryKey"] : detailPagePreferences["primaryKey"]; const [entityInstance, setEntityInstance] = useState({}); const [selected, setSelected] = useState(""); const [data, setData] = useState(); const [isLoading, setIsLoading] = useState(false); const [contentType, setContentType] = useState(""); const [xml, setXml] = useState(); const [isEntityInstance, setIsEntityInstance] = useState(false); const [sources, setSources] = useState(location && location.state && location.state["sources"] ? location.state["sources"] : []); const [documentSize, setDocumentSize] = useState(); const [entityInstanceDocument, setIsEntityInstanceDocument] = useState<boolean | undefined>(undefined); const [sourcesTableData, setSourcesTableData] = useState<any[]>([]); const [historyData, setHistoryData] = useState<any[]>([]); const [collections, setCollections] = useState<any>(); const [recordMetadata, setRecordMetadata] = useState<any>(); const [recordPermissions, setRecordPermissions] = useState<any>(); const [documentProperties, setDocumentProperties] = useState<any>(); const [docQuality, setDocQuality] = useState<any>(); const componentIsMounted = useRef(true); const authorityService = useContext(AuthoritiesContext); const getSaveQueries = async () => { try { if (authorityService.isSavedQueryUser()) { const response = await fetchQueries(); if (response.data) { setSavedQueries(response.data); } } } catch (error) { handleError(error); } }; useEffect(() => { setIsLoading(true); const fetchData = async () => { // When Detail URI is undefined, redirect to Explore if (!uri) { history.push("/tiles/explore"); return; } try { let encodedUri = encodeURIComponent(uri); const result = await axios(`/api/entitySearch?docUri=${encodedUri}&database=${database}`); if (!result.data) { history.push("/error"); } if (componentIsMounted.current) { if (result.data.entityInstanceProperties !== null) { setIsEntityInstanceDocument(true); setIsEntityInstance(true); setEntityInstance(result.data.entityInstanceProperties); } else { setIsEntityInstanceDocument(false); setIsEntityInstance(false); } const recordType = result.data.recordType; if (recordType === "json") { setContentType("json"); setData(result.data.data); } else if (recordType === "xml") { setContentType("xml"); const decodedXml = xmlDecoder(result.data.data); const document = xmlParser(decodedXml); setData(document); setXml(result.data.data); } else if (recordType === "text") { setContentType("text"); setData(result.data.data); } //Setting the data for sources metadata table setSources(result.data.sources); setSourcesTableData(generateSourcesData(result.data.sources)); setHistoryData(generateHistoryData(result.data.history)); setDocumentSize(result.data?.documentSize); setIsLoading(false); setCollections(generateCollections(result.data.collections)); setRecordMetadata(generateMetadata(result.data.recordMetadata)); setRecordPermissions(generatePermissions(result.data.permissions)); setDocumentProperties(result.data.documentProperties); setDocQuality(result.data.quality); } getSaveQueries(); } catch (error) { handleError(error); } }; if (!user.error.type) { fetchData(); } updateDetailPagePreferences(); return () => { componentIsMounted.current = false; }; }, []); useEffect(() => { if (location.state && JSON.stringify(location.state) !== JSON.stringify({})) { entityInstanceDocument && location.state.hasOwnProperty("selectedValue") && location.state["selectedValue"] === "source" ? setSelected("full") : setSelected("instance"); } else { if (location.state === undefined) { location.state = {}; } entityInstanceDocument && setSelected(detailPagePreferences["selected"] ? detailPagePreferences["selected"] : "instance"); handleUserPreferences(); } }, [entityInstanceDocument === true || entityInstanceDocument === false]); const generateSourcesData = (sourceData) => { let parsedData: any[] = []; if (sourceData.length) { sourceData.forEach((obj, index) => { if (obj.constructor.name === "Object") { let sourceName = "none"; let sourceType = "none"; if (obj.hasOwnProperty("datahubSourceName") && obj.datahubSourceName) { sourceName = obj.datahubSourceName; } if (obj.hasOwnProperty("datahubSourceType") && obj.datahubSourceType) { sourceType = obj.datahubSourceType; } let tableObj = { key: index, sourceName: sourceName, sourceType: sourceType, }; parsedData.push(tableObj); } }); } else { let tableObj = { key: 1, sourceName: "none", sourceType: "none", }; parsedData.push(tableObj); } return parsedData; }; const generateHistoryData = (historyData) => { let parsedData: any[] = []; if (historyData.length === 0) { parsedData.push({ key: 1, updatedTime: "none", flow: "none", step: "none", user: "none" }); return parsedData; } historyData.forEach((dataObject, index) => { const tableObj = {}; tableObj["key"] = index; tableObj["updatedTime"] = dataObject.updatedTime ? moment(dataObject.updatedTime).format("yyyy-MM-DD hh:mm") : "none"; tableObj["flow"] = dataObject.flow ? dataObject.flow : "none"; tableObj["step"] = dataObject.step ? dataObject.step : "none"; tableObj["user"] = dataObject.user ? dataObject.user : "none"; parsedData.push(tableObj); }); return parsedData; }; const collectionColumns = [ { title: "Collection", dataIndex: "collection", key: "collection", } ]; const generateCollections = (collections) => { if (collections && collections.length) { let dataSource: any = []; collections.forEach((collection, index) => { let data = {}; data["key"] = index; data["collection"] = collection; dataSource.push(data); }); return dataSource; } }; const recordMetadataColumns = [ { title: "Property", dataIndex: "property", key: "property", }, { title: "Value", dataIndex: "value", key: "value", } ]; const generateMetadata = (metadata) => { if (metadata) { let dataSource: any = []; Object.keys(metadata).forEach((key, index) => { const data = {}; data["key"] = index; data["property"] = key; data["value"] = metadata[key]; dataSource.push(data); }); return dataSource; } }; const recordPermissionsColumns = [ { title: "Role", dataIndex: "role", key: "role", }, { title: "Capability", dataIndex: "capability", key: "capability", } ]; const generatePermissions = (permissions) => { if (permissions && permissions.length) { let dataSource: any = []; permissions.forEach((p, index) => { const data = {}; data["key"] = index; data["role"] = p.roleName; data["capability"] = p.capability; dataSource.push(data); }); return dataSource; } }; //Apply user preferences on each page render const handleUserPreferences = () => { let userPref: any = { zeroState: false, entity: detailPagePreferences.query["entityTypeIds"] ? detailPagePreferences.query["entityTypeIds"] : "", pageNumber: detailPagePreferences["pageNumber"] ? detailPagePreferences["pageNumber"] : 1, start: detailPagePreferences["start"] ? detailPagePreferences["start"] : 1, searchFacets: detailPagePreferences.query["selectedFacets"] ? detailPagePreferences.query["selectedFacets"] : {}, query: detailPagePreferences.query["searchText"] ? detailPagePreferences.query["searchText"] : "", tableView: detailPagePreferences.hasOwnProperty("tableView") ? detailPagePreferences["tableView"] : true, sortOrder: detailPagePreferences["sortOrder"] ? detailPagePreferences["sortOrder"] : [], sources: detailPagePreferences["sources"] ? detailPagePreferences["sources"] : [], primaryKey: detailPagePreferences["primaryKey"] ? detailPagePreferences["primaryKey"] : "", uri: detailPagePreferences["uri"] ? detailPagePreferences["uri"] : "", targetDatabase: detailPagePreferences["database"] ? detailPagePreferences["database"] : "" }; setParentPagePreferences({...userPref}); }; const updateDetailPagePreferences = () => { if (location.state && (location.state.hasOwnProperty("sources") || location.state.hasOwnProperty("uri") || location.state.hasOwnProperty("primaryKey") || location.state.hasOwnProperty("entityInstance"))) { let sources: any = []; let primaryKey: any = ""; let uri: any = ""; let entityInstance: any = {}; let isEntityInstance = true; if (location.state["sources"] && location.state["sources"].length) { sources = location.state["sources"]; } if (location.state["primaryKey"]) { primaryKey = location.state["primaryKey"]; } if (location.state["uri"] && location.state["uri"].length) { uri = location.state["uri"]; } if (location.state["entityInstance"] && Object.keys(location.state["entityInstance"]).length) { entityInstance = location.state["entityInstance"]; } if (location.state.hasOwnProperty("isEntityInstance") && location.state["isEntityInstance"]) { isEntityInstance = location.state["isEntityInstance"]; } let preferencesObject = { ...detailPagePreferences, sources: sources, primaryKey: primaryKey, uri: uri, selected: location.state["selectedValue"] && location.state["selectedValue"] === "source" ? "full" : "instance", entityInstance: entityInstance, isEntityInstance: isEntityInstance }; updateUserPreferences(user.name, preferencesObject); } }; const handleClick = (event) => { setSelected(event.key); //Set the selected view property in user preferences. let preferencesObject = { ...detailPagePreferences, selected: event.key }; updateUserPreferences(user.name, preferencesObject); }; const selectedSearchOptions = { pathname: "/tiles/explore", state: { zeroState: false, entity: location.state && location.state.hasOwnProperty("entity") ? location.state["entity"] : parentPagePreferences["entity"], pageNumber: location.state && location.state.hasOwnProperty("pageNumber") ? location.state["pageNumber"] : parentPagePreferences["pageNumber"], start: location.state && location.state.hasOwnProperty("start") ? location.state["start"] : parentPagePreferences["start"], searchFacets: location.state && location.state.hasOwnProperty("searchFacets") ? location.state["searchFacets"] : parentPagePreferences["searchFacets"], query: location.state && location.state.hasOwnProperty("query") ? location.state["query"] : parentPagePreferences["query"], tableView: location.state && location.state.hasOwnProperty("tableView") ? location.state["tableView"] : parentPagePreferences["tableView"], sortOrder: location.state && location.state.hasOwnProperty("sortOrder") ? location.state["sortOrder"] : parentPagePreferences["sortOrder"], sources: location.state && location.state.hasOwnProperty("sources") ? location.state["sources"] : parentPagePreferences["sources"], isEntityInstance: location.state && location.state.hasOwnProperty("isEntityInstance") ? location.state["isEntityInstance"] : parentPagePreferences["isEntityInstance"], targetDatabase: location.state && location.state.hasOwnProperty("targetDatabase") ? location.state["targetDatabase"] : parentPagePreferences["targetDatabase"], isBackToResultsClicked: true, } }; return ( entityInstanceDocument === undefined ? <div style={{marginTop: "40px"}}> <AsyncLoader /> </div> : entityInstanceDocument ? <Layout> <Content className={styles.detailContent}> <div id="back-button" style={{marginLeft: "-23px"}} onClick={() => history.push(selectedSearchOptions)}> <PageHeader title={<span className={styles.title}>Back to results</span>} data-cy="back-button" onBack={() => history.push(selectedSearchOptions)} /> </div> <div className={styles.header}> <div className={styles.heading}> {data && <DetailHeader document={data} contentType={contentType} uri={uri} primaryKey={pkValue} sources={sources.length ? sources : parentPagePreferences["sources"]} />} </div> <div id="menu" className={styles.menu}> <Menu id="subMenu" onClick={(event) => handleClick(event)} mode="horizontal" selectedKeys={[selected]}> <Menu.Item key="instance" id="instance" data-cy="instance-view"> <MLTooltip title={"Show the processed data"}> <FontAwesomeIcon icon={faThList} size="lg" /> <span className={styles.subMenu}>Instance</span> </MLTooltip> </Menu.Item> <Menu.Item key="full" id="full" data-cy="source-view"> <MLTooltip title={"Show the complete " + contentType.toUpperCase()} > {contentType.toUpperCase() === "XML" ? <FontAwesomeIcon icon={faCode} size="lg" /> : <span className={styles.jsonIcon}></span> } <span className={styles.subMenu}>{contentType.toUpperCase()}</span> </MLTooltip> </Menu.Item> <Menu.Item key="metadata" id="metadata" data-cy="metadata-view"> <MLTooltip title={"Show the metadata"}> <FontAwesomeIcon icon={faInfoCircle} size="lg" /> <span className={styles.subMenu}>Metadata</span> </MLTooltip> </Menu.Item> </Menu> </div> </div> <div className={styles.documentContainer}>{(() => { let block; if (isLoading || user.error.type === "ALERT") { block = <div style={{marginTop: "40px"}}> <AsyncLoader /> </div>; } else if (selected === "instance") { contentType === "json" ? block = (entityInstance) && <TableView document={isEntityInstance ? entityInstance : {}} contentType={contentType} location={location.state ? location.state["id"] : {}} isEntityInstance={entityInstanceDocument} /> : block = (entityInstance) && <TableView document={isEntityInstance ? entityInstance : {}} contentType={contentType} location={location.state ? location.state["id"] : {}} isEntityInstance={entityInstanceDocument} />; } else if (selected === "metadata") { block = <div id="metadata-view"> <div className={styles.docInfoContainer}> <div className={styles.metaItem} data-testid="document-uri"> <span className={styles.metaLabel}>Document URI:</span> <span className={styles.metaValue}>{uri}</span> </div> <div className={styles.metaItem} data-testid="document-quality"> <span className={styles.metaLabel}>Document Quality:</span> <span className={styles.metaValue}>{docQuality}</span> </div> </div> { (collections) && <div className={styles.collectionsTableContainer}> <div className={styles.collectionsTableLabel} data-testid="entity-collections-label">Collections</div> <MLTable bordered dataSource={collections} columns={collectionColumns} className={styles.collectionsTable} data-testid="collections-table" /> </div> } { (recordPermissions) && <div className={styles.recordPermissionsTableContainer}> <div className={styles.recordPermissionsTableLabel} data-testid="entity-record-permissions-label">Permissions</div> <MLTable bordered dataSource={recordPermissions} columns={recordPermissionsColumns} className={styles.recordPermissionsTable} data-testid="record-permissions-table" /> </div> } { (recordMetadata) && <div className={styles.recordMetadataTableContainer}> <div className={styles.recordMetadataTableLabel} data-testid="entity-record-metadata-label">Metadata Values</div> <MLTable bordered dataSource={recordMetadata} columns={recordMetadataColumns} className={styles.recordMetadataTable} data-testid="record-metadata-table" /> </div> } <div className={styles.documentPropertiesContainer}> <div className={styles.documentPropertiesLabel} data-testid="entity-record-properties-label">Document Properties</div> { (documentProperties) ? <pre data-testid="doc-properties-container">{xmlFormatter(documentProperties)}</pre> : <p data-testid="doc-no-properties-message">This document has no properties.</p> } </div> </div>; } else { contentType === "json" ? block = (data) && <pre data-testid="json-container">{jsonFormatter(data)}</pre> : block = (xml) && <pre data-testid="xml-container">{xmlFormatter(xml)}</pre>; } return block; })()}</div> <div></div> </Content> </Layout> : <DetailPageNonEntity uri={uri} sourcesTableData={sourcesTableData} historyData={historyData} selectedSearchOptions={selectedSearchOptions} entityInstance={entityInstance} isEntityInstance={entityInstanceDocument} contentType={contentType} data={data} xml={xml} detailPagePreferences={detailPagePreferences} documentSize={documentSize} database={database} collections={collections} recordMetadata={recordMetadata} recordPermissions={recordPermissions} documentProperties={documentProperties} docQuality={docQuality} /> ); }; export default withRouter(Detail);
the_stack
import { should } from 'chai'; import { DoubleLinkedListInstance } from '../../types/truffle-contracts'; const DoubleLinkedList = artifacts .require('./lists/DoubleLinkedList.sol') as Truffle.Contract<DoubleLinkedListInstance>; should(); const emptyData = '0x0000000000000000000000000000000000000000'; const headData = '0x0000000000000000000000000000000000000001'; const middleData = '0x0000000000000000000000000000000000000002'; const tailData = '0x0000000000000000000000000000000000000003'; /** @test {DoubleLinkedList} contract */ contract('DoubleLinkedList - add', (accounts) => { let doubleLinkedList: DoubleLinkedListInstance; beforeEach(async () => { doubleLinkedList = await DoubleLinkedList.new(); }); /** * Test the two contract methods * @test {DoubleLinkedList#set} and {DoubleLinkedList#get} */ it('Constructor variables.', async () => { (await doubleLinkedList.idCounter()).toNumber().should.be.equal(1); }); it('get on a non existing object returns (0,0,0,0).', async () => { const result = (await doubleLinkedList.get(0)); result[0].toNumber().should.be.equal(0); result[1].toNumber().should.be.equal(0); result[2].toNumber().should.be.equal(0); result[3].should.be.equal(emptyData); }); it('adds an object at the head - event emission.', async () => { const objectEvent = ( await doubleLinkedList.addHead(headData) ).logs[0]; objectEvent.args.id.toNumber().should.be.equal(1); objectEvent.args.data.should.be.equal(headData); }); it('adds an object at the head - data storage.', async () => { const objectId = ( await doubleLinkedList.addHead(headData) ).logs[0].args.id.toNumber(); const result = (await doubleLinkedList.get(objectId)); result[0].toNumber().should.be.equal(objectId); result[1].toNumber().should.be.equal(0); result[2].toNumber().should.be.equal(0); result[3].should.be.equal(headData); }); it('adds two objects from the head.', async () => { const objectOneId = ( await doubleLinkedList.addHead(middleData) ).logs[0].args.id.toNumber(); const objectTwoId = ( await doubleLinkedList.addHead(headData) ).logs[0].args.id.toNumber(); const objectOne = (await doubleLinkedList.get(objectOneId)); objectOne[0].toNumber().should.be.equal(objectOneId); objectOne[1].toNumber().should.be.equal(0); objectOne[2].toNumber().should.be.equal(objectTwoId); objectOne[3].should.be.equal(middleData); const objectTwo = (await doubleLinkedList.get(objectTwoId)); objectTwo[0].toNumber().should.be.equal(objectTwoId); objectTwo[1].toNumber().should.be.equal(objectOneId); objectTwo[2].toNumber().should.be.equal(0); objectTwo[3].should.be.equal(headData); ((await doubleLinkedList.head()).toNumber()).should.be.equal(objectTwoId); }); it('adds an object at the tail - event emission.', async () => { const objectEvent = ( await doubleLinkedList.addTail(headData) ).logs[0]; objectEvent.args.id.toNumber().should.be.equal(1); objectEvent.args.data.should.be.equal(headData); }); it('adds an object at the tail - data storage.', async () => { const objectId = ( await doubleLinkedList.addTail(headData) ).logs[0].args.id.toNumber(); const result = (await doubleLinkedList.get(objectId)); result[0].toNumber().should.be.equal(objectId); result[1].toNumber().should.be.equal(0); result[2].toNumber().should.be.equal(0); result[3].should.be.equal(headData); }); it('adds two objects from the tail.', async () => { const objectOneId = ( await doubleLinkedList.addTail(middleData) ).logs[0].args.id.toNumber(); const objectTwoId = ( await doubleLinkedList.addTail(headData) ).logs[0].args.id.toNumber(); const objectOne = (await doubleLinkedList.get(objectOneId)); objectOne[0].toNumber().should.be.equal(objectOneId); objectOne[1].toNumber().should.be.equal(objectTwoId); objectOne[2].toNumber().should.be.equal(0); objectOne[3].should.be.equal(middleData); const objectTwo = (await doubleLinkedList.get(objectTwoId)); objectTwo[0].toNumber().should.be.equal(objectTwoId); objectTwo[1].toNumber().should.be.equal(0); objectTwo[2].toNumber().should.be.equal(objectOneId); objectTwo[3].should.be.equal(headData); ((await doubleLinkedList.head()).toNumber()).should.be.equal(objectOneId); }); }); contract('DoubleLinkedList - find', (accounts) => { let doubleLinkedList: DoubleLinkedListInstance; let headId: number; let middleId: number; let tailId: number; beforeEach(async () => { doubleLinkedList = await DoubleLinkedList.new(); tailId = ( await doubleLinkedList.addHead(tailData) ).logs[0].args.id.toNumber(); middleId = ( await doubleLinkedList.addHead(middleData) ).logs[0].args.id.toNumber(); headId = ( await doubleLinkedList.addHead(headData) ).logs[0].args.id.toNumber(); }); it('finds an id for given data.', async () => { let resultId = (await doubleLinkedList.findIdForData(headData)); resultId.toNumber().should.be.equal(headId); resultId = (await doubleLinkedList.findIdForData(middleData)); resultId.toNumber().should.be.equal(middleId); resultId = (await doubleLinkedList.findIdForData(tailData)); resultId.toNumber().should.be.equal(tailId); }); }); /** @test {doubleLinkedList} contract */ contract('DoubleLinkedList - remove', (accounts) => { let doubleLinkedList: DoubleLinkedListInstance; let headId: number; let middleId: number; let tailId: number; beforeEach(async () => { doubleLinkedList = await DoubleLinkedList.new(); tailId = ( await doubleLinkedList.addHead(tailData) ).logs[0].args.id.toNumber(); middleId = ( await doubleLinkedList.addHead(middleData) ).logs[0].args.id.toNumber(); headId = ( await doubleLinkedList.addHead(headData) ).logs[0].args.id.toNumber(); }); it('removes the head.', async () => { const removedId = ( await doubleLinkedList.remove(headId) ).logs[1].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(middleId); const middleObject = (await doubleLinkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(tailId); middleObject[2].toNumber().should.be.equal(0); middleObject[3].should.be.equal(middleData); const tailObject = (await doubleLinkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].toNumber().should.be.equal(middleId); tailObject[3].should.be.equal(tailData); }); it('removes the tail.', async () => { const removedId = ( await doubleLinkedList.remove(tailId) ).logs[1].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await doubleLinkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(middleId); headObject[2].toNumber().should.be.equal(0); headObject[3].should.be.equal(headData); const middleObject = (await doubleLinkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(0); middleObject[2].toNumber().should.be.equal(headId); middleObject[3].should.be.equal(middleData); }); it('removes the middle.', async () => { const removedId = ( await doubleLinkedList.remove(middleId) ).logs[1].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await doubleLinkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(tailId); headObject[2].toNumber().should.be.equal(0); headObject[3].should.be.equal(headData); const tailObject = (await doubleLinkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].toNumber().should.be.equal(headId); tailObject[3].should.be.equal(tailData); }); it('removes all.', async () => { (await doubleLinkedList.remove(headId)).logs[1].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(middleId); (await doubleLinkedList.remove(tailId)).logs[1].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(middleId); ((await doubleLinkedList.tail()).toNumber()).should.be.equal(middleId); (await doubleLinkedList.remove(middleId)).logs[1].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(0); ((await doubleLinkedList.tail()).toNumber()).should.be.equal(0); }); }); /** @test {doubleLinkedList} contract */ contract('DoubleLinkedList - insert', (accounts) => { const insertedData = '0x0000000000000000000000000000000000000004'; let doubleLinkedList: DoubleLinkedListInstance; let headId: number; let middleId: number; let tailId: number; beforeEach(async () => { doubleLinkedList = await DoubleLinkedList.new(); tailId = ( await doubleLinkedList.addHead(tailData) ).logs[0].args.id.toNumber(); middleId = ( await doubleLinkedList.addHead(middleData) ).logs[0].args.id.toNumber(); headId = ( await doubleLinkedList.addHead(headData) ).logs[0].args.id.toNumber(); }); it('inserts after the head.', async () => { const insertedId = ( await doubleLinkedList.insertAfter(headId, insertedData) ).logs[0].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await doubleLinkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(insertedId); headObject[2].toNumber().should.be.equal(0); headObject[3].should.be.equal(headData); const insertedObject = (await doubleLinkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(middleId); insertedObject[2].toNumber().should.be.equal(headId); insertedObject[3].should.be.equal(insertedData); const middleObject = (await doubleLinkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(tailId); middleObject[2].toNumber().should.be.equal(insertedId); middleObject[3].should.be.equal(middleData); const tailObject = (await doubleLinkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].toNumber().should.be.equal(middleId); tailObject[3].should.be.equal(tailData); }); it('inserts after the tail.', async () => { const insertedId = ( await doubleLinkedList.insertAfter(tailId, insertedData) ).logs[0].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await doubleLinkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(middleId); headObject[2].toNumber().should.be.equal(0); headObject[3].should.be.equal(headData); const middleObject = (await doubleLinkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(tailId); middleObject[2].toNumber().should.be.equal(headId); middleObject[3].should.be.equal(middleData); const tailObject = (await doubleLinkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(insertedId); tailObject[2].toNumber().should.be.equal(middleId); tailObject[3].should.be.equal(tailData); const insertedObject = (await doubleLinkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(0); insertedObject[2].toNumber().should.be.equal(tailId); insertedObject[3].should.be.equal(insertedData); }); it('inserts after the middle.', async () => { const insertedId = ( await doubleLinkedList.insertAfter(middleId, insertedData) ).logs[0].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await doubleLinkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(middleId); headObject[2].toNumber().should.be.equal(0); headObject[3].should.be.equal(headData); const middleObject = (await doubleLinkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(insertedId); middleObject[2].toNumber().should.be.equal(headId); middleObject[3].should.be.equal(middleData); const insertedObject = (await doubleLinkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(tailId); insertedObject[2].toNumber().should.be.equal(middleId); insertedObject[3].should.be.equal(insertedData); const tailObject = (await doubleLinkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].toNumber().should.be.equal(insertedId); tailObject[3].should.be.equal(tailData); }); it('inserts before the head.', async () => { const insertedId = ( await doubleLinkedList.insertBefore(headId, insertedData) ).logs[0].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(insertedId); const insertedObject = (await doubleLinkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(headId); insertedObject[2].toNumber().should.be.equal(0); insertedObject[3].should.be.equal(insertedData); const headObject = (await doubleLinkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(middleId); headObject[2].toNumber().should.be.equal(insertedId); headObject[3].should.be.equal(headData); const middleObject = (await doubleLinkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(tailId); middleObject[2].toNumber().should.be.equal(headId); middleObject[3].should.be.equal(middleData); const tailObject = (await doubleLinkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].toNumber().should.be.equal(middleId); tailObject[3].should.be.equal(tailData); }); it('inserts before the tail.', async () => { const insertedId = ( await doubleLinkedList.insertBefore(tailId, insertedData) ).logs[0].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await doubleLinkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(middleId); headObject[2].toNumber().should.be.equal(0); headObject[3].should.be.equal(headData); const middleObject = (await doubleLinkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(insertedId); middleObject[2].toNumber().should.be.equal(headId); middleObject[3].should.be.equal(middleData); const insertedObject = (await doubleLinkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(tailId); insertedObject[2].toNumber().should.be.equal(middleId); insertedObject[3].should.be.equal(insertedData); const tailObject = (await doubleLinkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].toNumber().should.be.equal(insertedId); tailObject[3].should.be.equal(tailData); }); it('inserts before the middle.', async () => { const insertedId = ( await doubleLinkedList.insertBefore(middleId, insertedData) ).logs[0].args.id.toNumber(); ((await doubleLinkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await doubleLinkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(insertedId); headObject[2].toNumber().should.be.equal(0); headObject[3].should.be.equal(headData); const insertedObject = (await doubleLinkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(middleId); insertedObject[2].toNumber().should.be.equal(headId); insertedObject[3].should.be.equal(insertedData); const middleObject = (await doubleLinkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(tailId); middleObject[2].toNumber().should.be.equal(insertedId); middleObject[3].should.be.equal(middleData); const tailObject = (await doubleLinkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].toNumber().should.be.equal(middleId); tailObject[3].should.be.equal(tailData); }); }); /* contract('DoubleLinkedList - gas tests', (accounts) => { let doubleLinkedList: DoubleLinkedListInstance; const dummyData = '0x0000000000000000000000000000000000000001'; beforeEach(async () => { doubleLinkedList = await DoubleLinkedList.new(); for (let i = 0; i < 100; i++) { await doubleLinkedList.addHead(dummyData); } }); it('Add Head.', async () => { await doubleLinkedList.addHead(dummyData); }); it('Add Tail.', async () => { await doubleLinkedList.addTail(dummyData); }); it('Insert After.', async () => { const tailId = await doubleLinkedList.tail(); await doubleLinkedList.insertAfter(tailId, dummyData); }); it('Insert Before.', async () => { const tailId = await doubleLinkedList.tail(); await doubleLinkedList.insertBefore(tailId, dummyData); }); it('Remove.', async () => { const tailId = await doubleLinkedList.tail(); await doubleLinkedList.remove(tailId); }); }); */
the_stack
import { JSZip } from 'https://deno.land/x/jszip@0.10.0/mod.ts' import { ProjectSource, getProject } from './get-project.ts' import getDataUrl from './get-data-url.ts' import getFileExtension from './get-file-extension.ts' import { escapeCss, escapeHtml, escapeScript } from './escape.ts' import { EXTENSION_WORKER_URL, extensionWorker as extensionWorkerSource, template, VM_URL, vm } from './dependencies.ts' import { toBlob, toText } from './ensure-ok.ts' export type { ProjectSource } from './get-project.ts' /** A CSS colour */ export type Colour = string export type Logger = (message: string, type: 'status' | 'progress') => void /** * Options customising the screen that shows while the project is * loading. */ export interface LoadingOptions { /** The colour of the loading progress bar or `null` for no progress bar */ progressBar: Colour | null /** * An image to show while the project is loading. Either a `File`, a URL to * an image (not included inside the HTML file), or `null` for no image. */ image: File | string | null /** Whether the loading image should be stretched to fill the screen. */ stretch: boolean } /** * Options for toggling which buttons are shown in the top-right corner of the * resulting HTML file. */ export interface ButtonOptions { /** Whether to show start/stop buttons. */ startStop: boolean /** Whether to show the fullscreen button. */ fullscreen: boolean /** * Whether to show a button that downloads the project's current state as an * .sb3. Apparently this is useful for some kinds of projects where they want * you to remix the project to save the game state or add your own thing to * the project. */ download: boolean /** * Whether to show a button that lets you add a sprite by selecting a * .sprite3/.sprite2 file. * * Apparently, this can be used for an OS project to add a custom app, where * each app is contained within a sprite. */ addSprite: boolean } /** * Options customising the design of variable and list monitors. * * Note that by default, unlike Scratch, monitors are translucent black with * white text because dark theme is cool. I assume a common use of the HTMLifier * is to publish projects on other websites like itch.io, and because of the * negative stigma around Scratch being for beginners to programming, I think it * could be helpful to make it less obvious that a project was made in Scratch. */ export interface MonitorOptions { /** * Whether to show the container box surrounding the monitor. In Scratch, * this is normally shown in light grey, but in HTMLified projects it is * translucent black. Default: true. */ showContainer: boolean /** * Background colour of the monitor value. This includes the orange boxes * around the variable value and red boxes around list item values. If * `null`, then a translucent black will be used. * * If `valueBackground` is `null` and `showContainer` is `false`, then only * the monitor text will be shown. */ valueBackground: Colour | null /** * The text colour of the monitors' labels and values. Default: `white`. */ text: Colour } /** * Options defining how cloud variables are stored. */ export interface CloudOptions { /** * The URL of the cloud server, starting with `ws://` or `wss://`. `null` to * not use a web server and instead store cloud variables in localStorage. * Default: null. */ serverUrl: string | null /** * Whether to use special cloud variable behaviours for cloud variables of * certain names. Some of these special cloud variables interact with web * APIs when set by the project, or are automatically set with a value such * as the URL of the page. * * @see https://github.com/SheepTester/htmlifier/wiki/Special-cloud-behaviours */ specialBehaviours: boolean /** * The project ID used to identify the project to the cloud server. Default: * `0`. Not needed if `serverUrl` is `null`. */ projectId: string } /** Options to customise the resulting converted HTML file. */ export interface HtmlifyOptions { /** Logging function to track the progress of HTMLification. */ log: Logger /** * Whether to store the project.json, assets, and VM separately and bundle * them all up in a .zip file. */ zip: boolean /** Whether to include the VM inside the HTML file. Default: true */ includeVm: boolean /** The page title of the resulting HTML file. */ title: string /** * The value of the username block; this can also be changed by setting `☁ * username` with special cloud behaviours enabled. */ username: string /** Width of stage. Default: 480. */ width: number /** Height of stage. Default: 360. */ height: number /** Whether the stage should be stretched to fill the screen. */ stretch: boolean /** Whether to start the project automatically. Default: true. */ autoStart: boolean /** Whether turbo mode is enabled. */ turbo: boolean /** FPS of the project. Default: 30. */ fps: number /** * Whether to enforce reasonable limits such as the maximum list length (on by * default in vanilla Scratch). Default: true. */ limits: boolean /** * Whether sprite fencing is enabled to prevent sprites from going off * screen (on by default in vanilla Scratch). Default: true. */ fencing: boolean /** * Whether to lock the cursor when the user clicks on the stage. The mouse x/y * blocks are set to the accumulative mouse position, so the `limits` option * should be `false` to allow it to extend beyond the stage. */ pointerLock: boolean /** * A `File` containing an image to set the cursor to, or `'hidden'` to hide * the cursor, or `null` to use the default cursor. */ cursor: File | 'hidden' | null /** A `File` containing the favicon image. */ favicon: File | null /** A `File` containing the background image. */ backgroundImage: File | null /** * List of URLs or JavaScript files containing the unofficial extensions that * the project uses. * * @see * https://github.com/LLK/scratch-vm/blob/develop/docs/extensions.md#types-of-extensions */ extensions: (string | File)[] /** * List of URLs or JavaScript files to include in the resulting HTML file. In * addition to having access to DOM APIs (as opposed to unofficial extensions, * which are sandboxed in a Web Worker), the resulting HTML file also makes * the following variables global: * * - `vm` has the instance of Scratch's `VirtualMachine` * - `setCloud(name, value)` sets a cloud variable with the name `name` * (including the ☁) to `value` * * These injected scripts are equivalent to E羊icques "plugins," which are a * euphemism for userscripts. */ injectedScripts: (string | File)[] /** Customisation options for the loading screen. */ loading: Partial<LoadingOptions> /** Customisation options for the buttons on the top right of the page. */ buttons: Partial<ButtonOptions> /** Customisation of list and variable monitor colours. */ monitors: Partial<MonitorOptions> /** * Control the behaviour of cloud variables when HTMLified. Cloud variables * are stored in localStorage by default. */ cloud: Partial<CloudOptions> } /** * A "converter" that "converts" a project to HTML. * * I put "convert" in scare quotes because there's really no conversion going * on. It just stuffs the Scratch VM and the project data into a single HTML * file that makes the Scratch VM run the project. It's no different than a * self-contained embed of the Scratch project player. * * However, to the common Scratcher, this isn't a big concern. They just want to * see the `.sb3` file extension get turned into a `.html` that can be previewed * immediately in the browser. That is "conversion" enough for them. * * I often see Scratchers asking how to convert from an .sb3 file to some other * language, like JavaScript, Python, or Java. But this is inherently flawed; * programming languages alone aren't required to be able to render graphics or * play sound. @apple502j said it well: * * > The whole idea of "converting something into another language" is flawed. * > Just like how cultural difference affects translation of real-life * > languages, there are big differences that make this idea very hard to * > implement. For example, JavaScript itself does not offer stage rendering, * > so you'll have to add a few hundreds of kilobytes of code just to make that * > cat appear. * * The TurboWarp Packager has a more accurate and descriptive name, at the cost * of not being what the common Scratcher would be thinking of when they want to * turn their Scratch project into a web page. In contrast, the HTMLifier is * somewhat deceptive, considering that similar existing programs (e.g. * Phosphorus) actually do convert Scratch blocks into JavaScript. The HTMLifier * can be seen as a joke, [originally made as a lazy solution to vague * demands](https://scratch.mit.edu/discuss/post/3432236/). * * Anyways, here's an example. * * ```ts * // Converts "Scratch 3.0 is here!" https://scratch.mit.edu/projects/276660763/ * const result = await new Htmlifier() * .htmlify({ type: 'id', id: '276660763' }) * .then(blob => blob.text()) * ``` */ export default class Htmlifier { private async _createHtml ( projectSource: ProjectSource, { log = () => {}, zip: outputZip = false, includeVm = true, title = '', username = '', width = 480, height = 360, stretch: stretchStage = false, autoStart = true, turbo = false, fps = 30, limits = true, fencing = true, pointerLock = false, cursor = null, favicon = null, backgroundImage = null, extensions = [], injectedScripts = [], loading: { progressBar = null, image: loadingImage = null, stretch: stretchLoadingImage = false } = {}, buttons: { startStop: startStopBtns = false, fullscreen: fullscreenBtn = false, download: downloadBtn = false, addSprite: addSpriteBtn = false } = {}, monitors: { showContainer = true, valueBackground = null, text: monitorText = 'white' } = {}, cloud: { serverUrl = null, specialBehaviours = false, projectId = '0' } = {} }: Partial<HtmlifyOptions> ): Promise<Blob> { const project = await getProject(projectSource, log) /** Files to externally include in the .zip file */ const files: Map<string, Blob | string> = new Map() /** * Stores file in .zip if `outputZip` is enabled. Returns a URL (either a * replative path or a data URL) that can be fetched. */ async function registerFile ( fileName: string, file: Blob | string ): Promise<string> { if (outputZip) { fileName = fileName.replace(/[^a-z0-9. _\-,()]|^[ .]+|[ ]+$/gi, '_') while (files.has(fileName)) { fileName = 'another ' + fileName } files.set(fileName, file) return `./${fileName}` } else { return await getDataUrl( typeof file === 'string' ? new Blob([file], { type: 'text/plain' }) : file ) } } /** * Object mapping from asset md5-extension to a fetchable URL. Can also be * `project` and `file`. */ const assets: Record<string, string | unknown> = {} if (project.type === 'assets') { if (!outputZip) { log( 'Since you wanted a single HTML file, I need to represent the costume and sound files as text. This will make them take up 33% more space.', 'status' ) } assets.project = await registerFile( 'project.json', JSON.stringify(project.project) ) for (const [md5Ext, file] of project.assets) { assets[md5Ext] = await registerFile(md5Ext, file) } } else { if (!outputZip) { log( 'Since you wanted a single HTML file, I need to represent the project file as text. This will make it take up 33% more space.', 'status' ) } assets.file = await registerFile('project', project.file) } let extensionWorker: { url: string } | { script: string } = { url: EXTENSION_WORKER_URL } if (extensions.length > 0) { log( 'I shall start downloading each extension script file from their URL.', 'status' ) const extensionScripts: string[] = [] for (const extensionSource of extensions) { if (typeof extensionSource !== 'string') { extensionScripts.push( outputZip ? await registerFile( extensionSource.name, await extensionSource.text() ) : await extensionSource.text() ) } else if (includeVm) { extensionScripts.push( outputZip ? await registerFile( extensionSource + '.js', await fetch(extensionSource).then(toBlob) ) : await fetch(extensionSource).then(toText) ) } } if (includeVm) { // Prepend an override on importScripts to map extension URLs to locally // stored ones const workerScript = [ `const scripts = ${JSON.stringify(extensionScripts, null, '\t')}`, 'const oldImportScripts = self.importScripts', // Fallback to URL import in case the extension importScripts some other // URL outputZip ? 'self.importScripts = (...urls) => oldImportScripts(...urls.map(url => scripts[url] || url))' : 'self.importScripts = (...urls) => urls.forEach(url => scripts[url] ? eval(scripts[url]) : oldImportScripts(url))', extensionWorkerSource ].join('\n') extensionWorker = outputZip ? { url: await registerFile('extension-worker.js', workerScript) } : { script: workerScript } } } type Script = | { type: 'url'; url: string } | { type: 'inline'; source: string } const injectedJs: Script[] = [] if (injectedScripts.length > 0) { log( 'I shall start downloading each script file from their URL.', 'status' ) for (const source of injectedScripts) { if (outputZip) { injectedJs.push({ type: 'url', url: typeof source === 'string' ? await registerFile( source + '.js', await fetch(source).then(toBlob) ) : await registerFile(source.name, await source.text()) }) } else { injectedJs.push({ type: 'inline', source: typeof source === 'string' ? await fetch(source).then(toText) : await source.text() }) } } } log('Now, I shall join everything together into an HTML file.', 'status') let html = template const classes: string[] = [] const styles: string[] = [] html = html.replace('{TITLE}', () => escapeHtml(title)) if (stretchStage) { classes.push('stretch-stage') html = html.replace('{WRAPPER_CSS}', '') } else { styles.push( `#wrapper { width: 100vw; height: ${(height / width) * 100}vw; }`, `@media (min-aspect-ratio: ${width}/${height}) {`, `#wrapper { height: 100vh; width: ${(width / height) * 100}vh; }`, '}' ) } if (cursor === 'hidden') { classes.push('no-cursor') } else if (cursor) { const cursorUrl = await registerFile( 'cursor' + getFileExtension(cursor), cursor ) styles.push( 'body {', `cursor: url("${escapeCss(cursorUrl)}"), auto;`, '}' ) } if (favicon) { const faviconUrl = await registerFile( 'favicon' + getFileExtension(favicon), favicon ) html = html.replace( '{FAVICON}', () => `<link rel="shortcut icon" type="image/png" href="${escapeHtml( faviconUrl )}">` ) } else { html = html.replace('{FAVICON}', '') } if (backgroundImage) { const imageUrl = await registerFile( 'favicon' + getFileExtension(backgroundImage), backgroundImage ) // The background image is added separately to be loaded after the loading // image html = html.replace( '{BACKGROUND_CSS}', `<style>\nbody {\nbackground-image: url("${escapeCss( imageUrl )}");\n}\n</style>` ) } else { html = html.replace('{BACKGROUND_CSS}', '') } if (progressBar) { classes.push('show-loading-progress') styles.push( '#loading-progress {', `border: 1px solid ${progressBar};`, '}', '#loading-progress::before {', `color: ${progressBar};`, '}', '#loading-progress::after {', `background-color: ${progressBar};`, '}' ) } if (loadingImage) { const imageUrl = typeof loadingImage === 'string' ? loadingImage : await registerFile( 'loading' + getFileExtension(loadingImage), loadingImage ) html = html.replace( '{LOADING_IMAGE}', () => `<img src="${escapeHtml(imageUrl)}" id="loading-image">` ) } else { html = html.replace('{LOADING_IMAGE}', '') } if (stretchLoadingImage) classes.push('stretch-loading-image') if (startStopBtns) classes.push('show-start-stop-btns') if (fullscreenBtn) classes.push('show-fullscreen-btn') if (downloadBtn) classes.push('show-download-btn') if (addSpriteBtn) classes.push('show-add-sprite-btn') if (showContainer) classes.push('show-monitor-box') if (valueBackground) { // This class is mainly to overcome selector precedence because // .show-monitor-box .large has greater precedence over .large classes.push('custom-monitor-colour') styles.push( '.custom-monitor-colour .default .monitor-value,', '.custom-monitor-colour .slider .monitor-value,', '.custom-monitor-colour .large,', '.custom-monitor-colour .row-value {', `background-color: ${valueBackground};`, '}' ) } styles.push('.monitor {', `color: ${monitorText};`, '}') html = html .replace('{CLASSES}', () => classes.join(' ')) .replace('{STYLES}', () => styles.length > 0 ? `<style>\n${styles.join('\n')}\n</style>` : '' ) .replace( '{DATA}', () => `<script>\nconst GENERATED = ${Date.now()}\nconst initOptions = ${escapeScript( JSON.stringify( { width, height, stretchStage, fps, turbo, limits, fencing, pointerLock, autoStart, username, loadingProgress: !!progressBar, cloud: { serverUrl, specialBehaviours, projectId }, extensionWorker, extensionCount: extensions.length, assets }, null, '\t' ) )}\ninit(initOptions)\n</script>${injectedJs .map(script => script.type === 'inline' ? `<script>\n${script.source}\n</script>` : `<script src="${script.url}"></script>` ) .join('\n')}` ) if (!includeVm) { html = html.replace('{VM}', () => `<script src="${VM_URL}"></script>`) } else if (outputZip) { files.set('vm.js', vm) html = html.replace('{VM}', () => '<script src="./vm.js"></script>') } else { html = html.replace( '{VM}', () => `<script>\n${escapeScript(vm)}\n</script>` ) } if (outputZip) { log( 'I shall zip all the files into a ZIP file, as you requested.', 'status' ) const zip = new JSZip() for (const [fileName, file] of files) { zip.addFile( fileName, typeof file === 'string' ? file : new Uint8Array(await file.arrayBuffer()) ) } zip.addFile('index.html', html) zip.addFile( 'README.txt', "You can't just open the index.html directly in the browser, unfortunately. Read https://github.com/SheepTester/htmlifier/wiki/Downloading-as-a-.zip\n" ) return await zip.generateAsync({ type: 'blob' }) } else { return new Blob([html], { type: 'text/html' }) } } /** * Convert `project` to HTML. Returns a `Blob` containing the HTML file, or a * ZIP file if the `zip` option was enabled. */ async htmlify ( project: ProjectSource, options: Partial<HtmlifyOptions> = {} ): Promise<Blob> { return await this._createHtml(project, options) } }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * Details of the Azure plan. */ export interface AzurePlan { /** * The sku id. */ skuId?: string; /** * The sku description. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly skuDescription?: string; } /** * Details of the reseller. */ export interface Reseller { /** * The MPN ID of the reseller. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly resellerId?: string; /** * The name of the reseller. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; } /** * The Resource model definition. */ export interface Resource extends BaseResource { /** * Resource Id. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * A partner's customer. */ export interface Customer extends Resource { /** * The ID of the billing profile for the invoice section. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileId?: string; /** * The name of the billing profile for the invoice section. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileDisplayName?: string; /** * The name of the customer. */ displayName?: string; /** * Azure plans enabled for the customer. */ enabledAzurePlans?: AzurePlan[]; /** * The list of resellers for which an Azure plan is enabled for the customer. */ resellers?: Reseller[]; } /** * Address details. */ export interface AddressDetails { /** * First name. */ firstName?: string; /** * Last name. */ lastName?: string; /** * Company name. */ companyName?: string; /** * Address line 1. */ addressLine1: string; /** * Address line 2. */ addressLine2?: string; /** * Address line 3. */ addressLine3?: string; /** * Address city. */ city?: string; /** * Address district. */ district?: string; /** * Address region. */ region?: string; /** * Country code uses ISO2, 2-digit format. */ country: string; /** * Postal code. */ postalCode?: string; /** * Email address. */ email?: string; /** * Phone number. */ phoneNumber?: string; } /** * Result of the address validation */ export interface ValidateAddressResponse { /** * status of the address validation. Possible values include: 'Valid', 'Invalid' */ status?: AddressValidationStatus; /** * The list of suggested addresses. */ suggestedAddresses?: AddressDetails[]; /** * Validation error message. */ validationMessage?: string; } /** * The properties of the product to initiate a transfer. */ export interface TransferProductRequestProperties { /** * The destination invoice section id. */ destinationInvoiceSectionId?: string; } /** * Request parameters to transfer billing subscription. */ export interface TransferBillingSubscriptionRequestProperties { /** * The destination invoice section id. */ destinationInvoiceSectionId: string; } /** * Error details of the transfer eligibility validation */ export interface ValidateSubscriptionTransferEligibilityError { /** * Error code for the product transfer validation. Possible values include: 'InvalidSource', * 'SubscriptionNotActive', 'InsufficientPermissionOnSource', * 'InsufficientPermissionOnDestination', 'DestinationBillingProfilePastDue', * 'SubscriptionTypeNotSupported', 'CrossBillingAccountNotAllowed', * 'NotAvailableForDestinationMarket' */ code?: SubscriptionTransferValidationErrorCode; /** * The error message. */ message?: string; /** * Detailed error message explaining the error. */ details?: string; } /** * Result of the transfer eligibility validation. */ export interface ValidateSubscriptionTransferEligibilityResult { /** * Specifies whether the subscription is eligible to be transferred. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isMoveEligible?: boolean; /** * Validation error details. */ errorDetails?: ValidateSubscriptionTransferEligibilityError; } /** * The billing profile details of the partner of the customer for an indirect motion. */ export interface IndirectRelationshipInfo { /** * The billing account name of the partner or the customer for an indirect motion. */ billingAccountName?: string; /** * The billing profile name of the partner or the customer for an indirect motion. */ billingProfileName?: string; /** * The display name of the partner or customer for an indirect motion. */ displayName?: string; } /** * An invoice section. */ export interface InvoiceSection extends Resource { /** * The name of the invoice section. */ displayName?: string; /** * Dictionary of metadata associated with the invoice section. */ labels?: { [propertyName: string]: string }; /** * Identifies the state of an invoice section. Possible values include: 'Active', 'Restricted' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly state?: InvoiceSectionState; /** * The system generated unique identifier for an invoice section. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly systemId?: string; /** * Identifies the cloud environments that are associated with an invoice section. This is a * system managed optional field and gets updated as the invoice section gets associated with * accounts in various clouds. Possible values include: 'USGov', 'USNat', 'USSec' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly targetCloud?: TargetCloud; } /** * The invoice sections associated to the billing profile. By default this is not populated, unless * it's specified in $expand. */ export interface InvoiceSectionsOnExpand { /** * Indicates whether there are more invoice sections than the ones listed in this collection. The * collection lists a maximum of 50 invoice sections. To get all invoice sections, use the list * invoice sections API. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly hasMoreResults?: boolean; /** * The invoice sections associated to the billing profile. */ value?: InvoiceSection[]; } /** * A billing profile. */ export interface BillingProfile extends Resource { /** * The name of the billing profile. */ displayName?: string; /** * The purchase order name that will appear on the invoices generated for the billing profile. */ poNumber?: string; /** * Identifies which services and purchases are paid by a billing profile. Possible values * include: 'Direct', 'IndirectCustomer', 'IndirectPartner', 'CSPPartner' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingRelationshipType?: BillingRelationshipType; /** * Billing address. */ billTo?: AddressDetails; /** * Identifies the billing profile that is linked to another billing profile in indirect purchase * motion. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly indirectRelationshipInfo?: IndirectRelationshipInfo; /** * Flag controlling whether the invoices for the billing profile are sent through email. */ invoiceEmailOptIn?: boolean; /** * The day of the month when the invoice for the billing profile is generated. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceDay?: number; /** * The currency in which the charges for the billing profile are billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly currency?: string; /** * Information about the enabled azure plans. */ enabledAzurePlans?: AzurePlan[]; /** * The invoice sections associated to the billing profile. By default this is not populated, * unless it's specified in $expand. */ invoiceSections?: InvoiceSectionsOnExpand; /** * Indicates whether user has read access to the billing profile. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly hasReadAccess?: boolean; /** * The system generated unique identifier for a billing profile. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly systemId?: string; /** * The status of the billing profile. Possible values include: 'Active', 'Disabled', 'Warned' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: BillingProfileStatus; /** * Reason for the specified billing profile status. Possible values include: 'PastDue', * 'SpendingLimitReached', 'SpendingLimitExpired' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly statusReasonCode?: StatusReasonCode; /** * The billing profile spending limit. Possible values include: 'Off', 'On' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly spendingLimit?: SpendingLimit; /** * Identifies the cloud environments that are associated with a billing profile. This is a system * managed optional field and gets updated as the billing profile gets associated with accounts * in various clouds. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly targetClouds?: TargetCloud[]; } /** * The billing profiles associated with the billing account. By default this is not populated, * unless it's specified in $expand. */ export interface BillingProfilesOnExpand { /** * Indicates whether there are more billing profiles than the ones listed in this collection. The * collection lists a maximum of 50 billing profiles. To get all billing profiles, use the list * billing profiles API. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly hasMoreResults?: boolean; /** * The billing profiles associated with the billing account. */ value?: BillingProfile[]; } /** * The policies for Enterprise Agreement enrollments. */ export interface EnrollmentPolicies { /** * The policy that controls whether Account Owners can view charges. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly accountOwnerViewCharges?: boolean; /** * The policy that controls whether Department Administrators can view charges. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly departmentAdminViewCharges?: boolean; /** * The policy that controls whether Azure marketplace purchases are allowed in the enrollment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly marketplacesEnabled?: boolean; /** * The policy that controls whether Azure reservation purchases are allowed in the enrollment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly reservedInstancesEnabled?: boolean; } /** * The properties of an enrollment. */ export interface Enrollment { /** * The start date of the enrollment. */ startDate?: Date; /** * The end date of the enrollment. */ endDate?: Date; /** * The billing currency for the enrollment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly currency?: string; /** * The channel type of the enrollment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly channel?: string; /** * The policies for Enterprise Agreement enrollments. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly policies?: EnrollmentPolicies; /** * The language for the enrollment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly language?: string; /** * The country code of the enrollment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly countryCode?: string; /** * The current status of the enrollment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: string; /** * The billing cycle for the enrollment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingCycle?: string; } /** * An enrollment account. */ export interface EnrollmentAccount extends Resource { /** * The name of the enrollment account. */ accountName?: string; /** * The cost center associated with the enrollment account. */ costCenter?: string; /** * The owner of the enrollment account. */ accountOwner?: string; /** * The status of the enrollment account. */ status?: string; /** * The start date of the enrollment account. */ startDate?: Date; /** * The end date of the enrollment account. */ endDate?: Date; /** * Associated department. By default this is not populated, unless it's specified in $expand. */ department?: Department; } /** * A department. */ export interface Department extends Resource { /** * The name of the department. */ departmentName?: string; /** * The cost center associated with the department. */ costCenter?: string; /** * The status of the department. */ status?: string; /** * Associated enrollment accounts. By default this is not populated, unless it's specified in * $expand. */ enrollmentAccounts?: EnrollmentAccount[]; } /** * A billing account. */ export interface BillingAccount extends Resource { /** * The billing account name. */ displayName?: string; /** * The address of the individual or organization that is responsible for the billing account. */ soldTo?: AddressDetails; /** * The type of agreement. Possible values include: 'MicrosoftCustomerAgreement', * 'EnterpriseAgreement', 'MicrosoftOnlineServicesProgram', 'MicrosoftPartnerAgreement' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly agreementType?: AgreementType; /** * The type of customer. Possible values include: 'Enterprise', 'Individual', 'Partner' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly accountType?: AccountType; /** * The current status of the billing account. Possible values include: 'Active', 'Deleted', * 'Disabled', 'Expired', 'Transferred', 'Extended', 'Terminated' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly accountStatus?: AccountStatus; /** * The billing profiles associated with the billing account. By default this is not populated, * unless it's specified in $expand. */ billingProfiles?: BillingProfilesOnExpand; /** * The details about the associated legacy enrollment. By default this is not populated, unless * it's specified in $expand. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly enrollmentDetails?: Enrollment; /** * The departments associated to the enrollment. */ departments?: Department[]; /** * The accounts associated to the enrollment. */ enrollmentAccounts?: EnrollmentAccount[]; /** * Indicates whether user has read access to the billing account. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly hasReadAccess?: boolean; } /** * The request properties of the billing account that can be updated. */ export interface BillingAccountUpdateRequest { /** * The billing account name. */ displayName?: string; /** * The address of the individual or organization that is responsible for the billing account. */ soldTo?: AddressDetails; /** * The type of agreement. Possible values include: 'MicrosoftCustomerAgreement', * 'EnterpriseAgreement', 'MicrosoftOnlineServicesProgram', 'MicrosoftPartnerAgreement' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly agreementType?: AgreementType; /** * The type of customer. Possible values include: 'Enterprise', 'Individual', 'Partner' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly accountType?: AccountType; /** * The current status of the billing account. Possible values include: 'Active', 'Deleted', * 'Disabled', 'Expired', 'Transferred', 'Extended', 'Terminated' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly accountStatus?: AccountStatus; /** * The billing profiles associated with the billing account. By default this is not populated, * unless it's specified in $expand. */ billingProfiles?: BillingProfilesOnExpand; /** * The details about the associated legacy enrollment. By default this is not populated, unless * it's specified in $expand. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly enrollmentDetails?: Enrollment; /** * The departments associated to the enrollment. */ departments?: Department[]; /** * The accounts associated to the enrollment. */ enrollmentAccounts?: EnrollmentAccount[]; /** * Indicates whether user has read access to the billing account. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly hasReadAccess?: boolean; } /** * A billing property. */ export interface BillingProperty extends Resource { /** * The email address on which the account admin gets all Azure notifications. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly accountAdminNotificationEmailAddress?: string; /** * The Azure AD tenant ID of the billing account for the subscription. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingTenantId?: string; /** * The ID of the billing account to which the subscription is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingAccountId?: string; /** * The name of the billing account to which the subscription is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingAccountDisplayName?: string; /** * The ID of the billing profile to which the subscription is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileId?: string; /** * The name of the billing profile to which the subscription is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileDisplayName?: string; /** * The status of the billing profile. Possible values include: 'Active', 'Disabled', 'Warned' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileStatus?: BillingProfileStatus; /** * Reason for the specified billing profile status. Possible values include: 'PastDue', * 'SpendingLimitReached', 'SpendingLimitExpired' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileStatusReasonCode?: BillingProfileStatusReasonCode; /** * The billing profile spending limit. Possible values include: 'Off', 'On' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileSpendingLimit?: BillingProfileSpendingLimit; /** * The cost center applied to the subscription. */ costCenter?: string; /** * The ID of the invoice section to which the subscription is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceSectionId?: string; /** * The name of the invoice section to which the subscription is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceSectionDisplayName?: string; /** * Indicates whether user is the account admin. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isAccountAdmin?: boolean; /** * The product ID of the Azure plan. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly productId?: string; /** * The product name of the Azure plan. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly productName?: string; /** * The sku ID of the Azure plan for the subscription. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly skuId?: string; /** * The sku description of the Azure plan for the subscription. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly skuDescription?: string; } /** * An instruction. */ export interface Instruction extends Resource { /** * The amount budgeted for this billing instruction. */ amount: number; /** * The date this billing instruction goes into effect. */ startDate: Date; /** * The date this billing instruction is no longer in effect. */ endDate: Date; /** * The date this billing instruction was created. */ creationDate?: Date; } /** * The request parameters for creating a new billing profile. */ export interface BillingProfileCreationRequest { /** * The name of the billing profile. */ displayName?: string; /** * The purchase order name that will appear on the invoices generated for the billing profile. */ poNumber?: string; /** * The address of the individual or organization that is responsible for the billing profile. */ billTo?: AddressDetails; /** * Flag controlling whether the invoices for the billing profile are sent through email. */ invoiceEmailOptIn?: boolean; /** * Enabled azure plans for the billing profile. */ enabledAzurePlans?: AzurePlan[]; } /** * The properties of the invoice section. */ export interface InvoiceSectionCreationRequest { /** * The name of the invoice section. */ displayName?: string; } /** * Invoice section properties with create subscription permission. */ export interface InvoiceSectionWithCreateSubPermission { /** * The ID of the invoice section. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceSectionId?: string; /** * The name of the invoice section. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceSectionDisplayName?: string; /** * The system generated unique identifier for an invoice section. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceSectionSystemId?: string; /** * The ID of the billing profile for the invoice section. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileId?: string; /** * The name of the billing profile for the invoice section. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileDisplayName?: string; /** * The status of the billing profile. Possible values include: 'Active', 'Disabled', 'Warned' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileStatus?: BillingProfileStatus; /** * Reason for the specified billing profile status. Possible values include: 'PastDue', * 'SpendingLimitReached', 'SpendingLimitExpired' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileStatusReasonCode?: StatusReasonCodeForBillingProfile; /** * The billing profile spending limit. Possible values include: 'Off', 'On' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileSpendingLimit?: SpendingLimitForBillingProfile; /** * The system generated unique identifier for a billing profile. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileSystemId?: string; /** * Enabled azure plans for the associated billing profile. */ enabledAzurePlans?: AzurePlan[]; } /** * A secure URL that can be used to download a an entity until the URL expires. */ export interface DownloadUrl { /** * The time in UTC when the download URL will expire. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly expiryTime?: Date; /** * The URL to the PDF file. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; } /** * An interface representing ErrorSubDetailsItem. */ export interface ErrorSubDetailsItem { /** * Error code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * Error message indicating why the operation failed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; /** * The target of the particular error. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly target?: string; } /** * The details of the error. */ export interface ErrorDetails { /** * Error code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * Error message indicating why the operation failed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; /** * The target of the particular error. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly target?: string; /** * The sub details of the error. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly details?: ErrorSubDetailsItem[]; } /** * Error response indicates that the service is not able to process the incoming request. The * reason is provided in the error message. */ export interface ErrorResponse { /** * The details of the error. */ error?: ErrorDetails; } /** * The amount. */ export interface Amount { /** * The currency for the amount value. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly currency?: string; /** * Amount value. */ value?: number; } /** * The properties of a document. */ export interface Document { /** * The type of the document. Possible values include: 'Invoice', 'VoidNote', 'TaxReceipt', * 'CreditNote' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly kind?: DocumentType; /** * Document URL. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly url?: string; /** * The source of the document. ENF for Brazil and DRS for rest of the world. Possible values * include: 'DRS', 'ENF' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly source?: DocumentSource; } /** * The properties of a payment. */ export interface PaymentProperties { /** * The type of payment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly paymentType?: string; /** * The paid amount. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly amount?: Amount; /** * The date when the payment was made. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly date?: Date; /** * The family of payment method. Possible values include: 'Credits', 'CheckWire', 'CreditCard', * 'None' */ paymentMethodFamily?: PaymentMethodFamily; /** * The type of payment method. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly paymentMethodType?: string; } /** * The rebill details of an invoice. */ export interface RebillDetails { /** * The ID of credit note. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly creditNoteDocumentId?: string; /** * The ID of invoice. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceDocumentId?: string; /** * Rebill details for an invoice. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly rebillDetails?: { [propertyName: string]: RebillDetails }; } /** * An invoice. */ export interface Invoice extends Resource { /** * The due date for the invoice. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly dueDate?: Date; /** * The date when the invoice was generated. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceDate?: Date; /** * The current status of the invoice. Possible values include: 'Due', 'OverDue', 'Paid', 'Void' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: InvoiceStatus; /** * The amount due as of now. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly amountDue?: Amount; /** * The amount of Azure prepayment applied to the charges. This field is applicable to billing * accounts with agreement type Microsoft Customer Agreement. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly azurePrepaymentApplied?: Amount; /** * The total charges for the invoice billing period. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billedAmount?: Amount; /** * The total refund for returns and cancellations during the invoice billing period. This field * is applicable to billing accounts with agreement type Microsoft Customer Agreement. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly creditAmount?: Amount; /** * The amount of free Azure credits applied to the charges. This field is applicable to billing * accounts with agreement type Microsoft Customer Agreement. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly freeAzureCreditApplied?: Amount; /** * The pre-tax amount due. This field is applicable to billing accounts with agreement type * Microsoft Customer Agreement. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subTotal?: Amount; /** * The amount of tax charged for the billing period. This field is applicable to billing accounts * with agreement type Microsoft Customer Agreement. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly taxAmount?: Amount; /** * The amount due when the invoice was generated. This field is applicable to billing accounts * with agreement type Microsoft Customer Agreement. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly totalAmount?: Amount; /** * The start date of the billing period for which the invoice is generated. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoicePeriodStartDate?: Date; /** * The end date of the billing period for which the invoice is generated. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoicePeriodEndDate?: Date; /** * Invoice type. Possible values include: 'AzureService', 'AzureMarketplace', 'AzureSupport' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceType?: InvoiceType; /** * Specifies if the invoice is generated as part of monthly invoicing cycle or not. This field is * applicable to billing accounts with agreement type Microsoft Customer Agreement. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isMonthlyInvoice?: boolean; /** * The ID of the billing profile for which the invoice is generated. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileId?: string; /** * The name of the billing profile for which the invoice is generated. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileDisplayName?: string; /** * An optional purchase order number for the invoice. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly purchaseOrderNumber?: string; /** * List of documents available to download such as invoice and tax receipt. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly documents?: Document[]; /** * List of payments. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly payments?: PaymentProperties[]; /** * Rebill details for an invoice. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly rebillDetails?: { [propertyName: string]: RebillDetails }; /** * The type of the document. Possible values include: 'Invoice', 'CreditNote' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly documentType?: InvoiceDocumentType; /** * The Id of the active invoice which is originally billed after this invoice was voided. This * field is applicable to the void invoices only. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billedDocumentId?: string; /** * The Id of the invoice which got voided and this credit note was issued as a result. This field * is applicable to the credit notes only. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly creditForDocumentId?: string; /** * The ID of the subscription for which the invoice is generated. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subscriptionId?: string; } /** * A product. */ export interface Product extends Resource { /** * Indicates whether auto renewal is turned on or off for a product. Possible values include: * 'Off', 'On' */ autoRenew?: AutoRenew; /** * The display name of the product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly displayName?: string; /** * The date when the product was purchased. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly purchaseDate?: Date; /** * The ID of the type of product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly productTypeId?: string; /** * The description of the type of product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly productType?: string; /** * The current status of the product. Possible values include: 'Active', 'Inactive', 'PastDue', * 'Expiring', 'Expired', 'Disabled', 'Cancelled', 'AutoRenew' */ status?: ProductStatusType; /** * The date when the product will be renewed or canceled. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly endDate?: Date; /** * The frequency at which the product will be billed. Possible values include: 'OneTime', * 'Monthly', 'UsageBased' */ billingFrequency?: BillingFrequency; /** * The last month charges. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly lastCharge?: Amount; /** * The date of the last charge. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly lastChargeDate?: Date; /** * The quantity purchased for the product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly quantity?: number; /** * The sku ID of the product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly skuId?: string; /** * The sku description of the product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly skuDescription?: string; /** * The id of the tenant in which the product is used. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tenantId?: string; /** * The availability of the product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly availabilityId?: string; /** * The ID of the invoice section to which the product is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceSectionId?: string; /** * The name of the invoice section to which the product is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceSectionDisplayName?: string; /** * The ID of the billing profile to which the product is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileId?: string; /** * The name of the billing profile to which the product is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileDisplayName?: string; /** * The ID of the customer for whom the product was purchased. The field is applicable only for * Microsoft Partner Agreement billing account. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly customerId?: string; /** * The name of the customer for whom the product was purchased. The field is applicable only for * Microsoft Partner Agreement billing account. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly customerDisplayName?: string; /** * Reseller for this product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly reseller?: Reseller; } /** * Error details of the product transfer eligibility validation. */ export interface ValidateProductTransferEligibilityError { /** * Error code for the product transfer validation. Possible values include: 'InvalidSource', * 'ProductNotActive', 'InsufficientPermissionOnSource', 'InsufficientPermissionOnDestination', * 'DestinationBillingProfilePastDue', 'ProductTypeNotSupported', * 'CrossBillingAccountNotAllowed', 'NotAvailableForDestinationMarket', * 'OneTimePurchaseProductTransferNotAllowed' */ code?: ProductTransferValidationErrorCode; /** * The error message. */ message?: string; /** * Detailed error message explaining the error. */ details?: string; } /** * Result of the product transfer eligibility validation. */ export interface ValidateProductTransferEligibilityResult { /** * Specifies whether the transfer is eligible or not. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isMoveEligible?: boolean; /** * Validation error details. */ errorDetails?: ValidateProductTransferEligibilityError; } /** * A billing subscription. */ export interface BillingSubscription extends Resource { /** * The name of the subscription. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly displayName?: string; /** * The ID of the subscription. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subscriptionId?: string; /** * The current billing status of the subscription. Possible values include: 'Active', 'Inactive', * 'Abandoned', 'Deleted', 'Warning' */ subscriptionBillingStatus?: BillingSubscriptionStatusType; /** * The last month charges. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly lastMonthCharges?: Amount; /** * The current month to date charges. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly monthToDateCharges?: Amount; /** * The ID of the billing profile to which the subscription is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileId?: string; /** * The name of the billing profile to which the subscription is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileDisplayName?: string; /** * The cost center applied to the subscription. */ costCenter?: string; /** * The ID of the customer for whom the subscription was created. The field is applicable only for * Microsoft Partner Agreement billing account. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly customerId?: string; /** * The name of the customer for whom the subscription was created. The field is applicable only * for Microsoft Partner Agreement billing account. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly customerDisplayName?: string; /** * The ID of the invoice section to which the subscription is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceSectionId?: string; /** * The name of the invoice section to which the subscription is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceSectionDisplayName?: string; /** * Reseller for this subscription. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly reseller?: Reseller; /** * The sku ID of the Azure plan for the subscription. */ skuId?: string; /** * The sku description of the Azure plan for the subscription. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly skuDescription?: string; } /** * The enrollment account context */ export interface EnrollmentAccountContext { /** * The cost center associated with the enrollment account. */ costCenter?: string; /** * The start date of the enrollment account. */ startDate?: Date; /** * The end date of the enrollment account. */ endDate?: Date; /** * The ID of the enrollment account. */ enrollmentAccountName?: string; } /** * A transaction. */ export interface Transaction extends Resource { /** * The kind of transaction. Options are all or reservation. Possible values include: 'all', * 'reservation' */ kind?: TransactionTypeKind; /** * The date of transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly date?: Date; /** * Invoice on which the transaction was billed or 'pending' if the transaction is not billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoice?: string; /** * The ID of the invoice on which the transaction was billed. This field is only applicable for * transactions which are billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceId?: string; /** * The order ID of the reservation. The field is only applicable for transaction of kind * reservation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly orderId?: string; /** * The name of the reservation order. The field is only applicable for transactions of kind * reservation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly orderName?: string; /** * The family of the product for which the transaction took place. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly productFamily?: string; /** * The ID of the product type for which the transaction took place. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly productTypeId?: string; /** * The type of the product for which the transaction took place. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly productType?: string; /** * The description of the product for which the transaction took place. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly productDescription?: string; /** * The type of transaction. Possible values include: 'Purchase', 'Usage Charge' */ transactionType?: ReservationType; /** * The charge associated with the transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly transactionAmount?: Amount; /** * The quantity purchased in the transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly quantity?: number; /** * The ID of the invoice section which will be billed for the transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceSectionId?: string; /** * The name of the invoice section which will be billed for the transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceSectionDisplayName?: string; /** * The ID of the billing profile which will be billed for the transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileId?: string; /** * The name of the billing profile which will be billed for the transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingProfileDisplayName?: string; /** * The ID of the customer for which the transaction took place. The field is applicable only for * Microsoft Partner Agreement billing account. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly customerId?: string; /** * The name of the customer for which the transaction took place. The field is applicable only * for Microsoft Partner Agreement billing account. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly customerDisplayName?: string; /** * The ID of the subscription that was used for the transaction. The field is only applicable for * transaction of kind reservation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subscriptionId?: string; /** * The name of the subscription that was used for the transaction. The field is only applicable * for transaction of kind reservation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subscriptionName?: string; /** * The type of azure plan of the subscription that was used for the transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly azurePlan?: string; /** * The amount of any Azure credits automatically applied to this transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly azureCreditApplied?: Amount; /** * The ISO 4217 code for the currency in which this transaction is billed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingCurrency?: string; /** * The percentage discount, if any, applied to this transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly discount?: number; /** * The price of the product after applying any discounts. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly effectivePrice?: Amount; /** * The exchange rate used to convert charged amount to billing currency, if applicable. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly exchangeRate?: number; /** * The retail price of the product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly marketPrice?: Amount; /** * The ISO 4217 code for the currency in which the product is priced. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly pricingCurrency?: string; /** * The date of the purchase of the product, or the start date of the month in which usage * started. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly servicePeriodStartDate?: Date; /** * The end date of the product term, or the end date of the month in which usage ended. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly servicePeriodEndDate?: Date; /** * The pre-tax charged amount for the transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subTotal?: Amount; /** * The tax amount applied to the transaction. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tax?: Amount; /** * The unit of measure used to bill for the product. For example, compute services are billed per * hour. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly unitOfMeasure?: string; /** * The number of units used for a given product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly units?: number; /** * The description for the unit of measure for a given product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly unitType?: string; } /** * A policy. */ export interface Policy extends Resource { /** * The policy that controls whether Azure marketplace purchases are allowed for a billing * profile. Possible values include: 'AllAllowed', 'OnlyFreeAllowed', 'NotAllowed' */ marketplacePurchases?: MarketplacePurchasesPolicy; /** * The policy that controls whether Azure reservation purchases are allowed for a billing * profile. Possible values include: 'Allowed', 'NotAllowed' */ reservationPurchases?: ReservationPurchasesPolicy; /** * The policy that controls whether users with Azure RBAC access to a subscription can view its * charges. Possible values include: 'Allowed', 'NotAllowed' */ viewCharges?: ViewChargesPolicy; } /** * The customer's Policy. */ export interface CustomerPolicy extends Resource { /** * The policy that controls whether the users in customer's organization can view charges at * pay-as-you-go prices. Possible values include: 'Allowed', 'NotAllowed' */ viewCharges?: ViewCharges; } /** * The latest Azure credit balance. This is the balance available for pay now. */ export interface AvailableBalance extends Resource { /** * Balance amount. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly amount?: Amount; } /** * The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft.Billing. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provider?: string; /** * Resource on which the operation is performed such as invoice and billing subscription. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly resource?: string; /** * Operation type such as read, write and delete. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operation?: string; } /** * A Billing REST API operation. */ export interface Operation { /** * Operation name: {provider}/{resource}/{operation}. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The object that represents the operation. */ display?: OperationDisplay; } /** * The role assignment */ export interface BillingRoleAssignment extends Resource { /** * The date the role assignment was created. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly createdOn?: string; /** * The tenant Id of the user who created the role assignment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly createdByPrincipalTenantId?: string; /** * The principal Id of the user who created the role assignment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly createdByPrincipalId?: string; /** * The email address of the user who created the role assignment. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly createdByUserEmailAddress?: string; /** * The principal id of the user to whom the role was assigned. */ principalId?: string; /** * The principal tenant id of the user to whom the role was assigned. */ principalTenantId?: string; /** * The ID of the role definition. */ roleDefinitionId?: string; /** * The scope at which the role was assigned. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly scope?: string; /** * The authentication type. */ userAuthenticationType?: string; /** * The email address of the user. */ userEmailAddress?: string; } /** * The set of allowed action and not allowed actions a caller has on a billing account */ export interface BillingPermissionsProperties { /** * The set of actions that the caller is allowed to perform. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly actions?: string[]; /** * The set of actions that the caller is not allowed to perform. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly notActions?: string[]; } /** * The properties of a role definition. */ export interface BillingRoleDefinition extends Resource { /** * The role description * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * The billingPermissions the role has */ permissions?: BillingPermissionsProperties[]; /** * The name of the role * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly roleName?: string; } /** * The details about a participant. */ export interface Participants { /** * The acceptance status of the participant. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: string; /** * The date when the status got changed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly statusDate?: Date; /** * The email address of the participant. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly email?: string; } /** * An agreement. */ export interface Agreement extends Resource { /** * The URL to download the agreement. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly agreementLink?: string; /** * The category of the agreement signed by a customer. Possible values include: * 'MicrosoftCustomerAgreement', 'AffiliatePurchaseTerms', 'Other' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly category?: Category; /** * The mode of acceptance for an agreement. Possible values include: 'ClickToAccept', * 'ESignEmbedded', 'ESignOffline' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly acceptanceMode?: AcceptanceMode; /** * The date from which the agreement is effective. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly effectiveDate?: Date; /** * The date when the agreement expires. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly expirationDate?: Date; /** * The list of participants that participates in acceptance of an agreement. */ participants?: Participants[]; /** * The current status of the agreement. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: string; } /** * An enrollment account resource. */ export interface EnrollmentAccountSummary extends Resource { /** * The account owner's principal name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly principalName?: string; } /** * A billing period resource. */ export interface BillingPeriod extends Resource { /** * The start of the date range covered by the billing period. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingPeriodStartDate?: Date; /** * The end of the date range covered by the billing period. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingPeriodEndDate?: Date; /** * Array of invoice ids that associated with. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly invoiceIds?: string[]; } /** * Optional Parameters. */ export interface BillingAccountsListOptionalParams extends msRest.RequestOptionsBase { /** * May be used to expand the soldTo, invoice sections and billing profiles. */ expand?: string; } /** * Optional Parameters. */ export interface BillingAccountsGetOptionalParams extends msRest.RequestOptionsBase { /** * May be used to expand the soldTo, invoice sections and billing profiles. */ expand?: string; } /** * Optional Parameters. */ export interface BillingProfilesListByBillingAccountOptionalParams extends msRest.RequestOptionsBase { /** * May be used to expand the invoice sections. */ expand?: string; } /** * Optional Parameters. */ export interface BillingProfilesGetOptionalParams extends msRest.RequestOptionsBase { /** * May be used to expand the invoice sections. */ expand?: string; } /** * Optional Parameters. */ export interface CustomersListByBillingProfileOptionalParams extends msRest.RequestOptionsBase { /** * Used for searching customers by their name. Any customer with name containing the search text * will be included in the response */ search?: string; /** * May be used to filter the list of customers. */ filter?: string; } /** * Optional Parameters. */ export interface CustomersListByBillingAccountOptionalParams extends msRest.RequestOptionsBase { /** * Used for searching customers by their name. Any customer with name containing the search text * will be included in the response */ search?: string; /** * May be used to filter the list of customers. */ filter?: string; } /** * Optional Parameters. */ export interface CustomersGetOptionalParams extends msRest.RequestOptionsBase { /** * May be used to expand enabledAzurePlans and resellers */ expand?: string; } /** * Optional Parameters. */ export interface ProductsListByBillingAccountOptionalParams extends msRest.RequestOptionsBase { /** * May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and * 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value are separated by a colon (:). */ filter?: string; } /** * Optional Parameters. */ export interface ProductsListByBillingProfileOptionalParams extends msRest.RequestOptionsBase { /** * May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and * 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value are separated by a colon (:). */ filter?: string; } /** * Optional Parameters. */ export interface ProductsListByInvoiceSectionOptionalParams extends msRest.RequestOptionsBase { /** * May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and * 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value are separated by a colon (:). */ filter?: string; } /** * Optional Parameters. */ export interface ProductsMoveOptionalParams extends msRest.RequestOptionsBase { /** * The destination invoice section id. */ destinationInvoiceSectionId?: string; } /** * Optional Parameters. */ export interface ProductsValidateMoveOptionalParams extends msRest.RequestOptionsBase { /** * The destination invoice section id. */ destinationInvoiceSectionId?: string; } /** * Optional Parameters. */ export interface PoliciesUpdateCustomerOptionalParams extends msRest.RequestOptionsBase { /** * The policy that controls whether the users in customer's organization can view charges at * pay-as-you-go prices. Possible values include: 'Allowed', 'NotAllowed' */ viewCharges?: ViewCharges; } /** * Optional Parameters. */ export interface BillingPropertyUpdateOptionalParams extends msRest.RequestOptionsBase { /** * The cost center applied to the subscription. */ costCenter?: string; } /** * Optional Parameters. */ export interface AgreementsListByBillingAccountOptionalParams extends msRest.RequestOptionsBase { /** * May be used to expand the participants. */ expand?: string; } /** * Optional Parameters. */ export interface AgreementsGetOptionalParams extends msRest.RequestOptionsBase { /** * May be used to expand the participants. */ expand?: string; } /** * Optional Parameters. */ export interface BillingPeriodsListOptionalParams extends msRest.RequestOptionsBase { /** * May be used to filter billing periods by billingPeriodEndDate. The filter supports 'eq', 'lt', * 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. */ filter?: string; /** * Skiptoken is only used if a previous operation returned a partial result. If a previous * response contains a nextLink element, the value of the nextLink element will include a * skiptoken parameter that specifies a starting point to use for subsequent calls. */ skiptoken?: string; /** * May be used to limit the number of results to the most recent N billing periods. */ top?: number; } /** * An interface representing BillingManagementClientOptions. */ export interface BillingManagementClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * Defines headers for CreateOrUpdate operation. */ export interface BillingProfilesCreateOrUpdateHeaders { /** * Location URI to poll for result */ location: string; /** * Recommended time to wait before making another request to check the status of the operation. * The time is specified in seconds. */ retryAfter: number; } /** * Defines headers for CreateOrUpdate operation. */ export interface InvoiceSectionsCreateOrUpdateHeaders { /** * Location URI to poll for result */ location: string; /** * Recommended time to wait before making another request to check the status of the operation. * The time is specified in seconds. */ retryAfter: number; } /** * Defines headers for DownloadInvoice operation. */ export interface InvoicesDownloadInvoiceHeaders { /** * GET this URL to retrieve the status of the asynchronous operation. */ location: string; /** * The amount of delay to use while the status of the operation is checked. The value is * expressed in seconds. */ retryAfter: string; } /** * Defines headers for DownloadMultipleModernInvoice operation. */ export interface InvoicesDownloadMultipleModernInvoiceHeaders { /** * GET this URL to retrieve the status of the asynchronous operation. */ location: string; /** * The amount of delay to use while the status of the operation is checked. The value is * expressed in seconds. */ retryAfter: string; } /** * Defines headers for DownloadBillingSubscriptionInvoice operation. */ export interface InvoicesDownloadBillingSubscriptionInvoiceHeaders { /** * GET this URL to retrieve the status of the asynchronous operation. */ location: string; /** * The amount of delay to use while the status of the operation is checked. The value is * expressed in seconds. */ retryAfter: string; } /** * Defines headers for DownloadMultipleBillingSubscriptionInvoice operation. */ export interface InvoicesDownloadMultipleBillingSubscriptionInvoiceHeaders { /** * GET this URL to retrieve the status of the asynchronous operation. */ location: string; /** * The amount of delay to use while the status of the operation is checked. The value is * expressed in seconds. */ retryAfter: string; } /** * Defines headers for Move operation. */ export interface BillingSubscriptionsMoveHeaders { /** * Location URI to poll for result. */ location: string; /** * Recommended time to wait before making another request to check the status of the operation. * The time is specified in seconds. */ retryAfter: number; } /** * Defines headers for Move operation. */ export interface ProductsMoveHeaders { /** * Location URI to poll for result */ location: string; /** * Recommended time to wait before making another request to check the status of the operation. * The time is specified in seconds. */ retryAfter: number; } /** * @interface * The list of billing accounts. * @extends Array<BillingAccount> */ export interface BillingAccountListResult extends Array<BillingAccount> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of invoice section properties with create subscription permission. * @extends Array<InvoiceSectionWithCreateSubPermission> */ export interface InvoiceSectionListWithCreateSubPermissionResult extends Array<InvoiceSectionWithCreateSubPermission> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of billing instructions used during invoice generation. * @extends Array<Instruction> */ export interface InstructionListResult extends Array<Instruction> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of billing profiles. * @extends Array<BillingProfile> */ export interface BillingProfileListResult extends Array<BillingProfile> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of customers. * @extends Array<Customer> */ export interface CustomerListResult extends Array<Customer> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of invoice sections. * @extends Array<InvoiceSection> */ export interface InvoiceSectionListResult extends Array<InvoiceSection> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * Result of list billingPermissions a caller has on a billing account. * @extends Array<BillingPermissionsProperties> */ export interface BillingPermissionsListResult extends Array<BillingPermissionsProperties> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of billing subscriptions. * @extends Array<BillingSubscription> */ export interface BillingSubscriptionsListResult extends Array<BillingSubscription> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of products. It contains a list of available product summaries in reverse chronological * order by purchase date. * @extends Array<Product> */ export interface ProductsListResult extends Array<Product> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of invoices. * @extends Array<Invoice> */ export interface InvoiceListResult extends Array<Invoice> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of transactions. * @extends Array<Transaction> */ export interface TransactionListResult extends Array<Transaction> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of billing operations and a URL link to get the next set of results. * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> { /** * URL to get the next set of operation list results if there are any. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of role definitions. * @extends Array<BillingRoleDefinition> */ export interface BillingRoleDefinitionListResult extends Array<BillingRoleDefinition> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of role assignments. * @extends Array<BillingRoleAssignment> */ export interface BillingRoleAssignmentListResult extends Array<BillingRoleAssignment> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * Result of listing agreements. * @extends Array<Agreement> */ export interface AgreementListResult extends Array<Agreement> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * Result of listing enrollment accounts. * @extends Array<EnrollmentAccountSummary> */ export interface EnrollmentAccountListResult extends Array<EnrollmentAccountSummary> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * Result of listing billing periods. It contains a list of available billing periods in reverse * chronological order. * @extends Array<BillingPeriod> */ export interface BillingPeriodsListResult extends Array<BillingPeriod> { /** * The link (url) to the next page of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * Defines values for AddressValidationStatus. * Possible values include: 'Valid', 'Invalid' * @readonly * @enum {string} */ export type AddressValidationStatus = 'Valid' | 'Invalid'; /** * Defines values for SubscriptionTransferValidationErrorCode. * Possible values include: 'InvalidSource', 'SubscriptionNotActive', * 'InsufficientPermissionOnSource', 'InsufficientPermissionOnDestination', * 'DestinationBillingProfilePastDue', 'SubscriptionTypeNotSupported', * 'CrossBillingAccountNotAllowed', 'NotAvailableForDestinationMarket' * @readonly * @enum {string} */ export type SubscriptionTransferValidationErrorCode = 'InvalidSource' | 'SubscriptionNotActive' | 'InsufficientPermissionOnSource' | 'InsufficientPermissionOnDestination' | 'DestinationBillingProfilePastDue' | 'SubscriptionTypeNotSupported' | 'CrossBillingAccountNotAllowed' | 'NotAvailableForDestinationMarket'; /** * Defines values for AgreementType. * Possible values include: 'MicrosoftCustomerAgreement', 'EnterpriseAgreement', * 'MicrosoftOnlineServicesProgram', 'MicrosoftPartnerAgreement' * @readonly * @enum {string} */ export type AgreementType = 'MicrosoftCustomerAgreement' | 'EnterpriseAgreement' | 'MicrosoftOnlineServicesProgram' | 'MicrosoftPartnerAgreement'; /** * Defines values for AccountType. * Possible values include: 'Enterprise', 'Individual', 'Partner' * @readonly * @enum {string} */ export type AccountType = 'Enterprise' | 'Individual' | 'Partner'; /** * Defines values for AccountStatus. * Possible values include: 'Active', 'Deleted', 'Disabled', 'Expired', 'Transferred', 'Extended', * 'Terminated' * @readonly * @enum {string} */ export type AccountStatus = 'Active' | 'Deleted' | 'Disabled' | 'Expired' | 'Transferred' | 'Extended' | 'Terminated'; /** * Defines values for BillingRelationshipType. * Possible values include: 'Direct', 'IndirectCustomer', 'IndirectPartner', 'CSPPartner' * @readonly * @enum {string} */ export type BillingRelationshipType = 'Direct' | 'IndirectCustomer' | 'IndirectPartner' | 'CSPPartner'; /** * Defines values for InvoiceSectionState. * Possible values include: 'Active', 'Restricted' * @readonly * @enum {string} */ export type InvoiceSectionState = 'Active' | 'Restricted'; /** * Defines values for TargetCloud. * Possible values include: 'USGov', 'USNat', 'USSec' * @readonly * @enum {string} */ export type TargetCloud = 'USGov' | 'USNat' | 'USSec'; /** * Defines values for BillingProfileStatus. * Possible values include: 'Active', 'Disabled', 'Warned' * @readonly * @enum {string} */ export type BillingProfileStatus = 'Active' | 'Disabled' | 'Warned'; /** * Defines values for StatusReasonCode. * Possible values include: 'PastDue', 'SpendingLimitReached', 'SpendingLimitExpired' * @readonly * @enum {string} */ export type StatusReasonCode = 'PastDue' | 'SpendingLimitReached' | 'SpendingLimitExpired'; /** * Defines values for SpendingLimit. * Possible values include: 'Off', 'On' * @readonly * @enum {string} */ export type SpendingLimit = 'Off' | 'On'; /** * Defines values for BillingProfileStatusReasonCode. * Possible values include: 'PastDue', 'SpendingLimitReached', 'SpendingLimitExpired' * @readonly * @enum {string} */ export type BillingProfileStatusReasonCode = 'PastDue' | 'SpendingLimitReached' | 'SpendingLimitExpired'; /** * Defines values for BillingProfileSpendingLimit. * Possible values include: 'Off', 'On' * @readonly * @enum {string} */ export type BillingProfileSpendingLimit = 'Off' | 'On'; /** * Defines values for StatusReasonCodeForBillingProfile. * Possible values include: 'PastDue', 'SpendingLimitReached', 'SpendingLimitExpired' * @readonly * @enum {string} */ export type StatusReasonCodeForBillingProfile = 'PastDue' | 'SpendingLimitReached' | 'SpendingLimitExpired'; /** * Defines values for SpendingLimitForBillingProfile. * Possible values include: 'Off', 'On' * @readonly * @enum {string} */ export type SpendingLimitForBillingProfile = 'Off' | 'On'; /** * Defines values for InvoiceStatus. * Possible values include: 'Due', 'OverDue', 'Paid', 'Void' * @readonly * @enum {string} */ export type InvoiceStatus = 'Due' | 'OverDue' | 'Paid' | 'Void'; /** * Defines values for InvoiceType. * Possible values include: 'AzureService', 'AzureMarketplace', 'AzureSupport' * @readonly * @enum {string} */ export type InvoiceType = 'AzureService' | 'AzureMarketplace' | 'AzureSupport'; /** * Defines values for DocumentType. * Possible values include: 'Invoice', 'VoidNote', 'TaxReceipt', 'CreditNote' * @readonly * @enum {string} */ export type DocumentType = 'Invoice' | 'VoidNote' | 'TaxReceipt' | 'CreditNote'; /** * Defines values for DocumentSource. * Possible values include: 'DRS', 'ENF' * @readonly * @enum {string} */ export type DocumentSource = 'DRS' | 'ENF'; /** * Defines values for PaymentMethodFamily. * Possible values include: 'Credits', 'CheckWire', 'CreditCard', 'None' * @readonly * @enum {string} */ export type PaymentMethodFamily = 'Credits' | 'CheckWire' | 'CreditCard' | 'None'; /** * Defines values for InvoiceDocumentType. * Possible values include: 'Invoice', 'CreditNote' * @readonly * @enum {string} */ export type InvoiceDocumentType = 'Invoice' | 'CreditNote'; /** * Defines values for AutoRenew. * Possible values include: 'Off', 'On' * @readonly * @enum {string} */ export type AutoRenew = 'Off' | 'On'; /** * Defines values for ProductStatusType. * Possible values include: 'Active', 'Inactive', 'PastDue', 'Expiring', 'Expired', 'Disabled', * 'Cancelled', 'AutoRenew' * @readonly * @enum {string} */ export type ProductStatusType = 'Active' | 'Inactive' | 'PastDue' | 'Expiring' | 'Expired' | 'Disabled' | 'Cancelled' | 'AutoRenew'; /** * Defines values for BillingFrequency. * Possible values include: 'OneTime', 'Monthly', 'UsageBased' * @readonly * @enum {string} */ export type BillingFrequency = 'OneTime' | 'Monthly' | 'UsageBased'; /** * Defines values for ProductTransferValidationErrorCode. * Possible values include: 'InvalidSource', 'ProductNotActive', 'InsufficientPermissionOnSource', * 'InsufficientPermissionOnDestination', 'DestinationBillingProfilePastDue', * 'ProductTypeNotSupported', 'CrossBillingAccountNotAllowed', 'NotAvailableForDestinationMarket', * 'OneTimePurchaseProductTransferNotAllowed' * @readonly * @enum {string} */ export type ProductTransferValidationErrorCode = 'InvalidSource' | 'ProductNotActive' | 'InsufficientPermissionOnSource' | 'InsufficientPermissionOnDestination' | 'DestinationBillingProfilePastDue' | 'ProductTypeNotSupported' | 'CrossBillingAccountNotAllowed' | 'NotAvailableForDestinationMarket' | 'OneTimePurchaseProductTransferNotAllowed'; /** * Defines values for BillingSubscriptionStatusType. * Possible values include: 'Active', 'Inactive', 'Abandoned', 'Deleted', 'Warning' * @readonly * @enum {string} */ export type BillingSubscriptionStatusType = 'Active' | 'Inactive' | 'Abandoned' | 'Deleted' | 'Warning'; /** * Defines values for TransactionTypeKind. * Possible values include: 'all', 'reservation' * @readonly * @enum {string} */ export type TransactionTypeKind = 'all' | 'reservation'; /** * Defines values for ReservationType. * Possible values include: 'Purchase', 'Usage Charge' * @readonly * @enum {string} */ export type ReservationType = 'Purchase' | 'Usage Charge'; /** * Defines values for MarketplacePurchasesPolicy. * Possible values include: 'AllAllowed', 'OnlyFreeAllowed', 'NotAllowed' * @readonly * @enum {string} */ export type MarketplacePurchasesPolicy = 'AllAllowed' | 'OnlyFreeAllowed' | 'NotAllowed'; /** * Defines values for ReservationPurchasesPolicy. * Possible values include: 'Allowed', 'NotAllowed' * @readonly * @enum {string} */ export type ReservationPurchasesPolicy = 'Allowed' | 'NotAllowed'; /** * Defines values for ViewChargesPolicy. * Possible values include: 'Allowed', 'NotAllowed' * @readonly * @enum {string} */ export type ViewChargesPolicy = 'Allowed' | 'NotAllowed'; /** * Defines values for ViewCharges. * Possible values include: 'Allowed', 'NotAllowed' * @readonly * @enum {string} */ export type ViewCharges = 'Allowed' | 'NotAllowed'; /** * Defines values for Category. * Possible values include: 'MicrosoftCustomerAgreement', 'AffiliatePurchaseTerms', 'Other' * @readonly * @enum {string} */ export type Category = 'MicrosoftCustomerAgreement' | 'AffiliatePurchaseTerms' | 'Other'; /** * Defines values for AcceptanceMode. * Possible values include: 'ClickToAccept', 'ESignEmbedded', 'ESignOffline' * @readonly * @enum {string} */ export type AcceptanceMode = 'ClickToAccept' | 'ESignEmbedded' | 'ESignOffline'; /** * Contains response data for the list operation. */ export type BillingAccountsListResponse = BillingAccountListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingAccountListResult; }; }; /** * Contains response data for the get operation. */ export type BillingAccountsGetResponse = BillingAccount & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingAccount; }; }; /** * Contains response data for the update operation. */ export type BillingAccountsUpdateResponse = BillingAccount & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingAccount; }; }; /** * Contains response data for the listInvoiceSectionsByCreateSubscriptionPermission operation. */ export type BillingAccountsListInvoiceSectionsByCreateSubscriptionPermissionResponse = InvoiceSectionListWithCreateSubPermissionResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceSectionListWithCreateSubPermissionResult; }; }; /** * Contains response data for the beginUpdate operation. */ export type BillingAccountsBeginUpdateResponse = BillingAccount & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingAccount; }; }; /** * Contains response data for the listNext operation. */ export type BillingAccountsListNextResponse = BillingAccountListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingAccountListResult; }; }; /** * Contains response data for the listInvoiceSectionsByCreateSubscriptionPermissionNext operation. */ export type BillingAccountsListInvoiceSectionsByCreateSubscriptionPermissionNextResponse = InvoiceSectionListWithCreateSubPermissionResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceSectionListWithCreateSubPermissionResult; }; }; /** * Contains response data for the validate operation. */ export type AddressValidateResponse = ValidateAddressResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ValidateAddressResponse; }; }; /** * Contains response data for the get operation. */ export type AvailableBalancesGetResponse = AvailableBalance & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: AvailableBalance; }; }; /** * Contains response data for the listByBillingProfile operation. */ export type InstructionsListByBillingProfileResponse = InstructionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InstructionListResult; }; }; /** * Contains response data for the get operation. */ export type InstructionsGetResponse = Instruction & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Instruction; }; }; /** * Contains response data for the put operation. */ export type InstructionsPutResponse = Instruction & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Instruction; }; }; /** * Contains response data for the listByBillingProfileNext operation. */ export type InstructionsListByBillingProfileNextResponse = InstructionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InstructionListResult; }; }; /** * Contains response data for the listByBillingAccount operation. */ export type BillingProfilesListByBillingAccountResponse = BillingProfileListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingProfileListResult; }; }; /** * Contains response data for the get operation. */ export type BillingProfilesGetResponse = BillingProfile & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingProfile; }; }; /** * Contains response data for the createOrUpdate operation. */ export type BillingProfilesCreateOrUpdateResponse = BillingProfile & BillingProfilesCreateOrUpdateHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: BillingProfilesCreateOrUpdateHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingProfile; }; }; /** * Contains response data for the listByBillingAccountNext operation. */ export type BillingProfilesListByBillingAccountNextResponse = BillingProfileListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingProfileListResult; }; }; /** * Contains response data for the listByBillingProfile operation. */ export type CustomersListByBillingProfileResponse = CustomerListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CustomerListResult; }; }; /** * Contains response data for the listByBillingAccount operation. */ export type CustomersListByBillingAccountResponse = CustomerListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CustomerListResult; }; }; /** * Contains response data for the get operation. */ export type CustomersGetResponse = Customer & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Customer; }; }; /** * Contains response data for the listByBillingProfileNext operation. */ export type CustomersListByBillingProfileNextResponse = CustomerListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CustomerListResult; }; }; /** * Contains response data for the listByBillingAccountNext operation. */ export type CustomersListByBillingAccountNextResponse = CustomerListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CustomerListResult; }; }; /** * Contains response data for the listByBillingProfile operation. */ export type InvoiceSectionsListByBillingProfileResponse = InvoiceSectionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceSectionListResult; }; }; /** * Contains response data for the get operation. */ export type InvoiceSectionsGetResponse = InvoiceSection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceSection; }; }; /** * Contains response data for the createOrUpdate operation. */ export type InvoiceSectionsCreateOrUpdateResponse = InvoiceSection & InvoiceSectionsCreateOrUpdateHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: InvoiceSectionsCreateOrUpdateHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceSection; }; }; /** * Contains response data for the listByBillingProfileNext operation. */ export type InvoiceSectionsListByBillingProfileNextResponse = InvoiceSectionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceSectionListResult; }; }; /** * Contains response data for the listByCustomer operation. */ export type BillingPermissionsListByCustomerResponse = BillingPermissionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingPermissionsListResult; }; }; /** * Contains response data for the listByBillingAccount operation. */ export type BillingPermissionsListByBillingAccountResponse = BillingPermissionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingPermissionsListResult; }; }; /** * Contains response data for the listByInvoiceSections operation. */ export type BillingPermissionsListByInvoiceSectionsResponse = BillingPermissionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingPermissionsListResult; }; }; /** * Contains response data for the listByBillingProfile operation. */ export type BillingPermissionsListByBillingProfileResponse = BillingPermissionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingPermissionsListResult; }; }; /** * Contains response data for the listByCustomerNext operation. */ export type BillingPermissionsListByCustomerNextResponse = BillingPermissionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingPermissionsListResult; }; }; /** * Contains response data for the listByBillingAccountNext operation. */ export type BillingPermissionsListByBillingAccountNextResponse = BillingPermissionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingPermissionsListResult; }; }; /** * Contains response data for the listByInvoiceSectionsNext operation. */ export type BillingPermissionsListByInvoiceSectionsNextResponse = BillingPermissionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingPermissionsListResult; }; }; /** * Contains response data for the listByBillingProfileNext operation. */ export type BillingPermissionsListByBillingProfileNextResponse = BillingPermissionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingPermissionsListResult; }; }; /** * Contains response data for the listByCustomer operation. */ export type BillingSubscriptionsListByCustomerResponse = BillingSubscriptionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingSubscriptionsListResult; }; }; /** * Contains response data for the listByBillingAccount operation. */ export type BillingSubscriptionsListByBillingAccountResponse = BillingSubscriptionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingSubscriptionsListResult; }; }; /** * Contains response data for the listByBillingProfile operation. */ export type BillingSubscriptionsListByBillingProfileResponse = BillingSubscriptionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingSubscriptionsListResult; }; }; /** * Contains response data for the listByInvoiceSection operation. */ export type BillingSubscriptionsListByInvoiceSectionResponse = BillingSubscriptionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingSubscriptionsListResult; }; }; /** * Contains response data for the get operation. */ export type BillingSubscriptionsGetResponse = BillingSubscription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingSubscription; }; }; /** * Contains response data for the update operation. */ export type BillingSubscriptionsUpdateResponse = BillingSubscription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingSubscription; }; }; /** * Contains response data for the move operation. */ export type BillingSubscriptionsMoveResponse = BillingSubscription & BillingSubscriptionsMoveHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: BillingSubscriptionsMoveHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingSubscription; }; }; /** * Contains response data for the validateMove operation. */ export type BillingSubscriptionsValidateMoveResponse = ValidateSubscriptionTransferEligibilityResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ValidateSubscriptionTransferEligibilityResult; }; }; /** * Contains response data for the listByCustomerNext operation. */ export type BillingSubscriptionsListByCustomerNextResponse = BillingSubscriptionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingSubscriptionsListResult; }; }; /** * Contains response data for the listByBillingAccountNext operation. */ export type BillingSubscriptionsListByBillingAccountNextResponse = BillingSubscriptionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingSubscriptionsListResult; }; }; /** * Contains response data for the listByBillingProfileNext operation. */ export type BillingSubscriptionsListByBillingProfileNextResponse = BillingSubscriptionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingSubscriptionsListResult; }; }; /** * Contains response data for the listByInvoiceSectionNext operation. */ export type BillingSubscriptionsListByInvoiceSectionNextResponse = BillingSubscriptionsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingSubscriptionsListResult; }; }; /** * Contains response data for the listByCustomer operation. */ export type ProductsListByCustomerResponse = ProductsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductsListResult; }; }; /** * Contains response data for the listByBillingAccount operation. */ export type ProductsListByBillingAccountResponse = ProductsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductsListResult; }; }; /** * Contains response data for the listByBillingProfile operation. */ export type ProductsListByBillingProfileResponse = ProductsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductsListResult; }; }; /** * Contains response data for the listByInvoiceSection operation. */ export type ProductsListByInvoiceSectionResponse = ProductsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductsListResult; }; }; /** * Contains response data for the get operation. */ export type ProductsGetResponse = Product & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Product; }; }; /** * Contains response data for the update operation. */ export type ProductsUpdateResponse = Product & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Product; }; }; /** * Contains response data for the move operation. */ export type ProductsMoveResponse = Product & ProductsMoveHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: ProductsMoveHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Product; }; }; /** * Contains response data for the validateMove operation. */ export type ProductsValidateMoveResponse = ValidateProductTransferEligibilityResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ValidateProductTransferEligibilityResult; }; }; /** * Contains response data for the listByCustomerNext operation. */ export type ProductsListByCustomerNextResponse = ProductsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductsListResult; }; }; /** * Contains response data for the listByBillingAccountNext operation. */ export type ProductsListByBillingAccountNextResponse = ProductsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductsListResult; }; }; /** * Contains response data for the listByBillingProfileNext operation. */ export type ProductsListByBillingProfileNextResponse = ProductsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductsListResult; }; }; /** * Contains response data for the listByInvoiceSectionNext operation. */ export type ProductsListByInvoiceSectionNextResponse = ProductsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductsListResult; }; }; /** * Contains response data for the listByBillingAccount operation. */ export type InvoicesListByBillingAccountResponse = InvoiceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceListResult; }; }; /** * Contains response data for the listByBillingProfile operation. */ export type InvoicesListByBillingProfileResponse = InvoiceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceListResult; }; }; /** * Contains response data for the get operation. */ export type InvoicesGetResponse = Invoice & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Invoice; }; }; /** * Contains response data for the getById operation. */ export type InvoicesGetByIdResponse = Invoice & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Invoice; }; }; /** * Contains response data for the downloadInvoice operation. */ export type InvoicesDownloadInvoiceResponse = DownloadUrl & InvoicesDownloadInvoiceHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: InvoicesDownloadInvoiceHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DownloadUrl; }; }; /** * Contains response data for the downloadMultipleModernInvoice operation. */ export type InvoicesDownloadMultipleModernInvoiceResponse = DownloadUrl & InvoicesDownloadMultipleModernInvoiceHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: InvoicesDownloadMultipleModernInvoiceHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DownloadUrl; }; }; /** * Contains response data for the listByBillingSubscription operation. */ export type InvoicesListByBillingSubscriptionResponse = InvoiceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceListResult; }; }; /** * Contains response data for the getBySubscriptionAndInvoiceId operation. */ export type InvoicesGetBySubscriptionAndInvoiceIdResponse = Invoice & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Invoice; }; }; /** * Contains response data for the downloadBillingSubscriptionInvoice operation. */ export type InvoicesDownloadBillingSubscriptionInvoiceResponse = DownloadUrl & InvoicesDownloadBillingSubscriptionInvoiceHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: InvoicesDownloadBillingSubscriptionInvoiceHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DownloadUrl; }; }; /** * Contains response data for the downloadMultipleBillingSubscriptionInvoice operation. */ export type InvoicesDownloadMultipleBillingSubscriptionInvoiceResponse = DownloadUrl & InvoicesDownloadMultipleBillingSubscriptionInvoiceHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: InvoicesDownloadMultipleBillingSubscriptionInvoiceHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DownloadUrl; }; }; /** * Contains response data for the listByBillingAccountNext operation. */ export type InvoicesListByBillingAccountNextResponse = InvoiceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceListResult; }; }; /** * Contains response data for the listByBillingProfileNext operation. */ export type InvoicesListByBillingProfileNextResponse = InvoiceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceListResult; }; }; /** * Contains response data for the listByBillingSubscriptionNext operation. */ export type InvoicesListByBillingSubscriptionNextResponse = InvoiceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: InvoiceListResult; }; }; /** * Contains response data for the listByInvoice operation. */ export type TransactionsListByInvoiceResponse = TransactionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: TransactionListResult; }; }; /** * Contains response data for the listByInvoiceNext operation. */ export type TransactionsListByInvoiceNextResponse = TransactionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: TransactionListResult; }; }; /** * Contains response data for the getByBillingProfile operation. */ export type PoliciesGetByBillingProfileResponse = Policy & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Policy; }; }; /** * Contains response data for the update operation. */ export type PoliciesUpdateResponse = Policy & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Policy; }; }; /** * Contains response data for the getByCustomer operation. */ export type PoliciesGetByCustomerResponse = CustomerPolicy & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CustomerPolicy; }; }; /** * Contains response data for the updateCustomer operation. */ export type PoliciesUpdateCustomerResponse = CustomerPolicy & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CustomerPolicy; }; }; /** * Contains response data for the get operation. */ export type BillingPropertyGetResponse = BillingProperty & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingProperty; }; }; /** * Contains response data for the update operation. */ export type BillingPropertyUpdateResponse = BillingProperty & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingProperty; }; }; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the getByBillingAccount operation. */ export type BillingRoleDefinitionsGetByBillingAccountResponse = BillingRoleDefinition & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleDefinition; }; }; /** * Contains response data for the getByInvoiceSection operation. */ export type BillingRoleDefinitionsGetByInvoiceSectionResponse = BillingRoleDefinition & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleDefinition; }; }; /** * Contains response data for the getByBillingProfile operation. */ export type BillingRoleDefinitionsGetByBillingProfileResponse = BillingRoleDefinition & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleDefinition; }; }; /** * Contains response data for the listByBillingAccount operation. */ export type BillingRoleDefinitionsListByBillingAccountResponse = BillingRoleDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleDefinitionListResult; }; }; /** * Contains response data for the listByInvoiceSection operation. */ export type BillingRoleDefinitionsListByInvoiceSectionResponse = BillingRoleDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleDefinitionListResult; }; }; /** * Contains response data for the listByBillingProfile operation. */ export type BillingRoleDefinitionsListByBillingProfileResponse = BillingRoleDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleDefinitionListResult; }; }; /** * Contains response data for the listByBillingAccountNext operation. */ export type BillingRoleDefinitionsListByBillingAccountNextResponse = BillingRoleDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleDefinitionListResult; }; }; /** * Contains response data for the listByInvoiceSectionNext operation. */ export type BillingRoleDefinitionsListByInvoiceSectionNextResponse = BillingRoleDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleDefinitionListResult; }; }; /** * Contains response data for the listByBillingProfileNext operation. */ export type BillingRoleDefinitionsListByBillingProfileNextResponse = BillingRoleDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleDefinitionListResult; }; }; /** * Contains response data for the getByBillingAccount operation. */ export type BillingRoleAssignmentsGetByBillingAccountResponse = BillingRoleAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignment; }; }; /** * Contains response data for the deleteByBillingAccount operation. */ export type BillingRoleAssignmentsDeleteByBillingAccountResponse = BillingRoleAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignment; }; }; /** * Contains response data for the getByInvoiceSection operation. */ export type BillingRoleAssignmentsGetByInvoiceSectionResponse = BillingRoleAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignment; }; }; /** * Contains response data for the deleteByInvoiceSection operation. */ export type BillingRoleAssignmentsDeleteByInvoiceSectionResponse = BillingRoleAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignment; }; }; /** * Contains response data for the getByBillingProfile operation. */ export type BillingRoleAssignmentsGetByBillingProfileResponse = BillingRoleAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignment; }; }; /** * Contains response data for the deleteByBillingProfile operation. */ export type BillingRoleAssignmentsDeleteByBillingProfileResponse = BillingRoleAssignment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignment; }; }; /** * Contains response data for the listByBillingAccount operation. */ export type BillingRoleAssignmentsListByBillingAccountResponse = BillingRoleAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignmentListResult; }; }; /** * Contains response data for the listByInvoiceSection operation. */ export type BillingRoleAssignmentsListByInvoiceSectionResponse = BillingRoleAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignmentListResult; }; }; /** * Contains response data for the listByBillingProfile operation. */ export type BillingRoleAssignmentsListByBillingProfileResponse = BillingRoleAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignmentListResult; }; }; /** * Contains response data for the listByBillingAccountNext operation. */ export type BillingRoleAssignmentsListByBillingAccountNextResponse = BillingRoleAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignmentListResult; }; }; /** * Contains response data for the listByInvoiceSectionNext operation. */ export type BillingRoleAssignmentsListByInvoiceSectionNextResponse = BillingRoleAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignmentListResult; }; }; /** * Contains response data for the listByBillingProfileNext operation. */ export type BillingRoleAssignmentsListByBillingProfileNextResponse = BillingRoleAssignmentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingRoleAssignmentListResult; }; }; /** * Contains response data for the listByBillingAccount operation. */ export type AgreementsListByBillingAccountResponse = AgreementListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: AgreementListResult; }; }; /** * Contains response data for the get operation. */ export type AgreementsGetResponse = Agreement & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Agreement; }; }; /** * Contains response data for the listByBillingAccountNext operation. */ export type AgreementsListByBillingAccountNextResponse = AgreementListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: AgreementListResult; }; }; /** * Contains response data for the list operation. */ export type EnrollmentAccountsListResponse = EnrollmentAccountListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EnrollmentAccountListResult; }; }; /** * Contains response data for the get operation. */ export type EnrollmentAccountsGetResponse = EnrollmentAccountSummary & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EnrollmentAccountSummary; }; }; /** * Contains response data for the listNext operation. */ export type EnrollmentAccountsListNextResponse = EnrollmentAccountListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EnrollmentAccountListResult; }; }; /** * Contains response data for the list operation. */ export type BillingPeriodsListResponse = BillingPeriodsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingPeriodsListResult; }; }; /** * Contains response data for the get operation. */ export type BillingPeriodsGetResponse = BillingPeriod & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingPeriod; }; }; /** * Contains response data for the listNext operation. */ export type BillingPeriodsListNextResponse = BillingPeriodsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: BillingPeriodsListResult; }; };
the_stack
import * as typemoq from 'typemoq'; import { assert, expect } from 'chai'; import { ConfigurationTarget, Uri, Event } from 'vscode'; import { EnvironmentDetails, IProposedExtensionAPI } from '../client/apiTypes'; import { IInterpreterPathService } from '../client/common/types'; import { IInterpreterService } from '../client/interpreter/contracts'; import { IServiceContainer } from '../client/ioc/types'; import { buildProposedApi } from '../client/proposedApi'; import { IDiscoveryAPI, ProgressNotificationEvent, ProgressReportStage, } from '../client/pythonEnvironments/base/locator'; import { PythonEnvironment } from '../client/pythonEnvironments/info'; import { PythonEnvKind, PythonEnvSource } from '../client/pythonEnvironments/base/info'; import { Architecture } from '../client/common/utils/platform'; import { buildEnvInfo } from '../client/pythonEnvironments/base/info/env'; suite('Proposed Extension API', () => { let serviceContainer: typemoq.IMock<IServiceContainer>; let discoverAPI: typemoq.IMock<IDiscoveryAPI>; let interpreterPathService: typemoq.IMock<IInterpreterPathService>; let interpreterService: typemoq.IMock<IInterpreterService>; let onDidExecutionEvent: Event<Uri | undefined>; let onRefreshProgress: Event<ProgressNotificationEvent>; let proposed: IProposedExtensionAPI; setup(() => { serviceContainer = typemoq.Mock.ofType<IServiceContainer>(undefined, typemoq.MockBehavior.Strict); discoverAPI = typemoq.Mock.ofType<IDiscoveryAPI>(undefined, typemoq.MockBehavior.Strict); interpreterPathService = typemoq.Mock.ofType<IInterpreterPathService>(undefined, typemoq.MockBehavior.Strict); interpreterService = typemoq.Mock.ofType<IInterpreterService>(undefined, typemoq.MockBehavior.Strict); onDidExecutionEvent = typemoq.Mock.ofType<Event<Uri | undefined>>().object; onRefreshProgress = typemoq.Mock.ofType<Event<ProgressNotificationEvent>>().object; interpreterService.setup((i) => i.onDidChangeInterpreterConfiguration).returns(() => onDidExecutionEvent); serviceContainer.setup((s) => s.get(IInterpreterPathService)).returns(() => interpreterPathService.object); serviceContainer.setup((s) => s.get(IInterpreterService)).returns(() => interpreterService.object); discoverAPI.setup((d) => d.onProgress).returns(() => onRefreshProgress); proposed = buildProposedApi(discoverAPI.object, serviceContainer.object); }); test('Provide a callback for tracking refresh progress', async () => { assert.deepEqual(proposed.environment.onRefreshProgress, onRefreshProgress); }); test('Provide a callback which is called when execution details changes', async () => { assert.deepEqual(onDidExecutionEvent, proposed.environment.onDidChangeExecutionDetails); }); test('getExecutionDetails: No resource', async () => { const pythonPath = 'this/is/a/test/path'; interpreterService .setup((c) => c.getActiveInterpreter(undefined)) .returns(() => Promise.resolve(({ path: pythonPath } as unknown) as PythonEnvironment)); const actual = await proposed.environment.getExecutionDetails(); assert.deepEqual(actual, { execCommand: [pythonPath] }); }); test('getExecutionDetails: With resource', async () => { const resource = Uri.file(__filename); const pythonPath = 'this/is/a/test/path'; interpreterService .setup((c) => c.getActiveInterpreter(resource)) .returns(() => Promise.resolve(({ path: pythonPath } as unknown) as PythonEnvironment)); const actual = await proposed.environment.getExecutionDetails(resource); assert.deepEqual(actual, { execCommand: [pythonPath] }); }); test('getActiveInterpreterPath: No resource', async () => { const pythonPath = 'this/is/a/test/path'; interpreterService .setup((c) => c.getActiveInterpreter(undefined)) .returns(() => Promise.resolve(({ path: pythonPath } as unknown) as PythonEnvironment)); const actual = await proposed.environment.getActiveEnvironmentPath(); assert.deepEqual(actual, { path: pythonPath, pathType: 'interpreterPath' }); }); test('getActiveInterpreterPath: With resource', async () => { const resource = Uri.file(__filename); const pythonPath = 'this/is/a/test/path'; interpreterService .setup((c) => c.getActiveInterpreter(resource)) .returns(() => Promise.resolve(({ path: pythonPath } as unknown) as PythonEnvironment)); const actual = await proposed.environment.getActiveEnvironmentPath(resource); assert.deepEqual(actual, { path: pythonPath, pathType: 'interpreterPath' }); }); test('getInterpreterDetails: no discovered python', async () => { discoverAPI.setup((d) => d.getEnvs()).returns(() => []); discoverAPI.setup((p) => p.resolveEnv(typemoq.It.isAny())).returns(() => Promise.resolve(undefined)); const pythonPath = 'this/is/a/test/path (without cache)'; const actual = await proposed.environment.getEnvironmentDetails(pythonPath); expect(actual).to.be.equal(undefined); }); test('getInterpreterDetails: no discovered python (with cache)', async () => { discoverAPI.setup((d) => d.getEnvs()).returns(() => []); discoverAPI.setup((p) => p.resolveEnv(typemoq.It.isAny())).returns(() => Promise.resolve(undefined)); const pythonPath = 'this/is/a/test/path'; const actual = await proposed.environment.getEnvironmentDetails(pythonPath, { useCache: true }); expect(actual).to.be.equal(undefined); }); test('getInterpreterDetails: without cache', async () => { const pythonPath = 'this/is/a/test/path'; const expected: EnvironmentDetails = { interpreterPath: pythonPath, version: ['3', '9', '0'], environmentType: [PythonEnvKind.System], metadata: { sysPrefix: 'prefix/path', bitness: Architecture.x64, project: Uri.file('path/to/project'), }, envFolderPath: undefined, }; discoverAPI.setup((d) => d.getEnvs()).returns(() => []); discoverAPI .setup((p) => p.resolveEnv(pythonPath)) .returns(() => Promise.resolve( buildEnvInfo({ executable: pythonPath, version: { major: 3, minor: 9, micro: 0, }, kind: PythonEnvKind.System, arch: Architecture.x64, sysPrefix: 'prefix/path', searchLocation: Uri.file('path/to/project'), }), ), ); const actual = await proposed.environment.getEnvironmentDetails(pythonPath, { useCache: false }); expect(actual).to.be.deep.equal(expected); }); test('getInterpreterDetails: from cache', async () => { const pythonPath = 'this/is/a/test/path'; const expected: EnvironmentDetails = { interpreterPath: pythonPath, version: ['3', '9', '0'], environmentType: [PythonEnvKind.System], metadata: { sysPrefix: 'prefix/path', bitness: Architecture.x64, project: undefined, }, envFolderPath: undefined, }; discoverAPI .setup((d) => d.getEnvs()) .returns(() => [ { executable: { filename: pythonPath, ctime: 1, mtime: 2, sysPrefix: 'prefix/path', }, version: { major: 3, minor: 9, micro: 0, }, kind: PythonEnvKind.System, arch: Architecture.x64, name: '', location: '', source: [PythonEnvSource.PathEnvVar], distro: { org: '', }, }, ]); discoverAPI .setup((p) => p.resolveEnv(pythonPath)) .returns(() => Promise.resolve( buildEnvInfo({ executable: pythonPath, version: { major: 3, minor: 9, micro: 0, }, kind: PythonEnvKind.System, arch: Architecture.x64, sysPrefix: 'prefix/path', }), ), ); const actual = await proposed.environment.getEnvironmentDetails(pythonPath, { useCache: true }); expect(actual).to.be.deep.equal(expected); }); test('getInterpreterDetails: cache miss', async () => { const pythonPath = 'this/is/a/test/path'; const expected: EnvironmentDetails = { interpreterPath: pythonPath, version: ['3', '9', '0'], environmentType: [PythonEnvKind.System], metadata: { sysPrefix: 'prefix/path', bitness: Architecture.x64, project: undefined, }, envFolderPath: undefined, }; // Force this API to return empty to cause a cache miss. discoverAPI.setup((d) => d.getEnvs()).returns(() => []); discoverAPI .setup((p) => p.resolveEnv(pythonPath)) .returns(() => Promise.resolve( buildEnvInfo({ executable: pythonPath, version: { major: 3, minor: 9, micro: 0, }, kind: PythonEnvKind.System, arch: Architecture.x64, sysPrefix: 'prefix/path', }), ), ); const actual = await proposed.environment.getEnvironmentDetails(pythonPath, { useCache: true }); expect(actual).to.be.deep.equal(expected); }); test('getInterpreterPaths: no pythons found', async () => { discoverAPI.setup((d) => d.getEnvs()).returns(() => []); const actual = await proposed.environment.getEnvironmentPaths(); expect(actual).to.be.deep.equal([]); }); test('getInterpreterPaths: python found', async () => { discoverAPI .setup((d) => d.getEnvs()) .returns(() => [ { executable: { filename: 'this/is/a/test/python/path1', ctime: 1, mtime: 2, sysPrefix: 'prefix/path', }, version: { major: 3, minor: 9, micro: 0, }, kind: PythonEnvKind.System, arch: Architecture.x64, name: '', location: '', source: [PythonEnvSource.PathEnvVar], distro: { org: '', }, }, { executable: { filename: 'this/is/a/test/python/path2', ctime: 1, mtime: 2, sysPrefix: 'prefix/path', }, version: { major: 3, minor: 10, micro: 0, }, kind: PythonEnvKind.Venv, arch: Architecture.x64, name: '', location: '', source: [PythonEnvSource.PathEnvVar], distro: { org: '', }, }, ]); const actual = await proposed.environment.getEnvironmentPaths(); expect(actual?.map((a) => a.path)).to.be.deep.equal([ 'this/is/a/test/python/path1', 'this/is/a/test/python/path2', ]); }); test('setActiveInterpreter: no resource', async () => { interpreterPathService .setup((i) => i.update(undefined, ConfigurationTarget.WorkspaceFolder, 'this/is/a/test/python/path')) .returns(() => Promise.resolve()) .verifiable(typemoq.Times.once()); await proposed.environment.setActiveEnvironment('this/is/a/test/python/path'); interpreterPathService.verifyAll(); }); test('setActiveInterpreter: with resource', async () => { const resource = Uri.parse('a'); interpreterPathService .setup((i) => i.update(resource, ConfigurationTarget.WorkspaceFolder, 'this/is/a/test/python/path')) .returns(() => Promise.resolve()) .verifiable(typemoq.Times.once()); await proposed.environment.setActiveEnvironment('this/is/a/test/python/path', resource); interpreterPathService.verifyAll(); }); test('refreshInterpreters: common scenario', async () => { discoverAPI .setup((d) => d.triggerRefresh(undefined, undefined)) .returns(() => Promise.resolve()) .verifiable(typemoq.Times.once()); discoverAPI .setup((d) => d.getEnvs()) .returns(() => [ { executable: { filename: 'this/is/a/test/python/path1', ctime: 1, mtime: 2, sysPrefix: 'prefix/path', }, version: { major: 3, minor: 9, micro: 0, }, kind: PythonEnvKind.System, arch: Architecture.x64, name: '', location: 'this/is/a/test/python/path1/folder', source: [PythonEnvSource.PathEnvVar], distro: { org: '', }, }, { executable: { filename: 'this/is/a/test/python/path2', ctime: 1, mtime: 2, sysPrefix: 'prefix/path', }, version: { major: 3, minor: 10, micro: 0, }, kind: PythonEnvKind.Venv, arch: Architecture.x64, name: '', location: '', source: [PythonEnvSource.PathEnvVar], distro: { org: '', }, }, ]); const actual = await proposed.environment.refreshEnvironment(); expect(actual).to.be.deep.equal([ { path: 'this/is/a/test/python/path1/folder', pathType: 'envFolderPath' }, { path: 'this/is/a/test/python/path2', pathType: 'interpreterPath' }, ]); discoverAPI.verifyAll(); }); test('getRefreshPromise: common scenario', () => { const expected = Promise.resolve(); discoverAPI .setup((d) => d.getRefreshPromise(typemoq.It.isValue({ stage: ProgressReportStage.allPathsDiscovered }))) .returns(() => expected); const actual = proposed.environment.getRefreshPromise({ stage: ProgressReportStage.allPathsDiscovered }); // We are comparing instances here, they should be the same instance. // So '==' is ok here. // eslint-disable-next-line eqeqeq expect(actual == expected).is.equal(true); }); });
the_stack
import { Agent } from 'http'; import { SecureContextOptions } from 'tls'; import { EventEmitter } from 'eventemitter3'; import Method, * as methods from './methods'; import { LogLevel, Logger } from './logger'; import { RetryOptions } from './retry-policies'; /** * A client for Slack's Web API * * This client provides an alias for each {@link https://api.slack.com/methods|Web API method}. Each method is * a convenience wrapper for calling the {@link WebClient#apiCall} method using the method name as the first parameter. */ export declare class WebClient extends EventEmitter<WebClientEvent> { /** * The base URL for reaching Slack's Web API. Consider changing this value for testing purposes. */ readonly slackApiUrl: string; /** * Authentication and authorization token for accessing Slack Web API (usually begins with `xoxp` or `xoxb`) */ readonly token?: string; /** * Configuration for retry operations. See {@link https://github.com/tim-kos/node-retry|node-retry} for more details. */ private retryConfig; /** * Queue of requests in which a maximum of {@link WebClientOptions.maxRequestConcurrency} can concurrently be * in-flight. */ private requestQueue; /** * Axios HTTP client instance used by this client */ private axios; /** * Configuration for custom TLS handling */ private tlsConfig; /** * Preference for immediately rejecting API calls which result in a rate-limited response */ private rejectRateLimitedCalls; /** * The name used to prefix all logging generated from this object */ private static loggerName; /** * This object's logger instance */ private logger; /** * @param token - An API token to authenticate/authorize with Slack (usually start with `xoxp`, `xoxb`) */ constructor(token?: string, { slackApiUrl, logger, logLevel, maxRequestConcurrency, retryConfig, agent, tls, rejectRateLimitedCalls, headers, }?: WebClientOptions); /** * Generic method for calling a Web API method * * @param method the Web API method to call {@see https://api.slack.com/methods} * @param options options */ apiCall(method: string, options?: WebAPICallOptions): Promise<WebAPICallResult>; /** * Iterate over the result pages of a cursor-paginated Web API method. This method can return two types of values, * depending on which arguments are used. When up to two parameters are used, the return value is an async iterator * which can be used as the iterable in a for-await-of loop. When three or four parameters are used, the return * value is a promise that resolves at the end of iteration. The third parameter, `shouldStop`, is a function that is * called with each `page` and can end iteration by returning `true`. The fourth parameter, `reduce`, is a function * that is called with three arguments: `accumulator`, `page`, and `index`. The `accumulator` is a value of any type * you choose, but it will contain `undefined` when `reduce` is called for the first time. The `page` argument and * `index` arguments are exactly what they say they are. The `reduce` function's return value will be passed in as * `accumulator` the next time its called, and the returned promise will resolve to the last value of `accumulator`. * * The for-await-of syntax is part of ES2018. It is available natively in Node starting with v10.0.0. You may be able * to use it in earlier JavaScript runtimes by transpiling your source with a tool like Babel. However, the * transpiled code will likely sacrifice performance. * * @param method the cursor-paginated Web API method to call {@see https://api.slack.com/docs/pagination} * @param options options * @param shouldStop a predicate that is called with each page, and should return true when pagination can end. * @param reduce a callback that can be used to accumulate a value that the return promise is resolved to */ paginate(method: string, options?: WebAPICallOptions): AsyncIterator<WebAPICallResult>; paginate(method: string, options: WebAPICallOptions, shouldStop: PaginatePredicate): Promise<void>; paginate<R extends PageReducer, A extends PageAccumulator<R>>(method: string, options: WebAPICallOptions, shouldStop: PaginatePredicate, reduce?: PageReducer<A>): Promise<A>; /** * admin method family */ readonly admin: { apps: { approve: Method<methods.AdminAppsApproveArguments>; approved: { list: Method<methods.AdminAppsApprovedListArguments>; }; requests: { list: Method<methods.AdminAppsRequestsListArguments>; }; restrict: Method<methods.AdminAppsRestrictArguments>; restricted: { list: Method<methods.AdminAppsRestrictedListArguments>; }; }; conversations: { setTeams: Method<methods.AdminConversationsSetTeamsArguments>; }; inviteRequests: { approve: Method<methods.AdminInviteRequestsApproveArguments>; deny: Method<methods.AdminInviteRequestsDenyArguments>; list: Method<methods.AdminInviteRequestsListArguments>; approved: { list: Method<methods.AdminInviteRequestsApprovedListArguments>; }; denied: { list: Method<methods.AdminInviteRequestsDeniedListArguments>; }; }; teams: { admins: { list: Method<methods.AdminTeamsAdminsListArguments>; }; create: Method<methods.AdminTeamsCreateArguments>; list: Method<methods.AdminTeamsListArguments>; owners: { list: Method<methods.AdminTeamsOwnersListArguments>; }; settings: { info: Method<methods.AdminTeamsSettingsInfoArguments>; setDefaultChannels: Method<methods.AdminTeamsSettingsSetDefaultChannelsArguments>; setDescription: Method<methods.AdminTeamsSettingsSetDescriptionArguments>; setDiscoverability: Method<methods.AdminTeamsSettingsSetDiscoverabilityArguments>; setIcon: Method<methods.AdminTeamsSettingseSetIconArguments>; setName: Method<methods.AdminTeamsSettingsSetNameArguments>; }; }; users: { session: { reset: Method<methods.AdminUsersSessionResetArguments>; }; assign: Method<methods.AdminUsersAssignArguments>; invite: Method<methods.AdminUsersInviteArguments>; list: Method<methods.AdminUsersListArguments>; remove: Method<methods.AdminUsersRemoveArguments>; setAdmin: Method<methods.AdminUsersSetAdminArguments>; setExpiration: Method<methods.AdminUsersSetExpirationArguments>; setOwner: Method<methods.AdminUsersSetOwnerArguments>; setRegular: Method<methods.AdminUsersSetRegularArguments>; }; }; /** * api method family */ readonly api: { test: Method<methods.APITestArguments>; }; /** * auth method family */ readonly auth: { revoke: Method<methods.AuthRevokeArguments>; test: Method<methods.AuthTestArguments>; }; /** * bots method family */ readonly bots: { info: Method<methods.BotsInfoArguments>; }; /** * channels method family */ readonly channels: { archive: Method<methods.ChannelsArchiveArguments>; create: Method<methods.ChannelsCreateArguments>; history: Method<methods.ChannelsHistoryArguments>; info: Method<methods.ChannelsInfoArguments>; invite: Method<methods.ChannelsInviteArguments>; join: Method<methods.ChannelsJoinArguments>; kick: Method<methods.ChannelsKickArguments>; leave: Method<methods.ChannelsLeaveArguments>; list: Method<methods.ChannelsListArguments>; mark: Method<methods.ChannelsMarkArguments>; rename: Method<methods.ChannelsRenameArguments>; replies: Method<methods.ChannelsRepliesArguments>; setPurpose: Method<methods.ChannelsSetPurposeArguments>; setTopic: Method<methods.ChannelsSetTopicArguments>; unarchive: Method<methods.ChannelsUnarchiveArguments>; }; /** * chat method family */ readonly chat: { delete: Method<methods.ChatDeleteArguments>; deleteScheduledMessage: Method<methods.ChatDeleteScheduledMessageArguments>; getPermalink: Method<methods.ChatGetPermalinkArguments>; meMessage: Method<methods.ChatMeMessageArguments>; postEphemeral: Method<methods.ChatPostEphemeralArguments>; postMessage: Method<methods.ChatPostMessageArguments>; scheduleMessage: Method<methods.ChatScheduleMessageArguments>; scheduledMessages: { list: Method<methods.ChatScheduledMessagesListArguments>; }; unfurl: Method<methods.ChatUnfurlArguments>; update: Method<methods.ChatUpdateArguments>; }; /** * conversations method family */ readonly conversations: { archive: Method<methods.ConversationsArchiveArguments>; close: Method<methods.ConversationsCloseArguments>; create: Method<methods.ConversationsCreateArguments>; history: Method<methods.ConversationsHistoryArguments>; info: Method<methods.ConversationsInfoArguments>; invite: Method<methods.ConversationsInviteArguments>; join: Method<methods.ConversationsJoinArguments>; kick: Method<methods.ConversationsKickArguments>; leave: Method<methods.ConversationsLeaveArguments>; list: Method<methods.ConversationsListArguments>; members: Method<methods.ConversationsMembersArguments>; open: Method<methods.ConversationsOpenArguments>; rename: Method<methods.ConversationsRenameArguments>; replies: Method<methods.ConversationsRepliesArguments>; setPurpose: Method<methods.ConversationsSetPurposeArguments>; setTopic: Method<methods.ConversationsSetTopicArguments>; unarchive: Method<methods.ConversationsUnarchiveArguments>; }; /** * view method family */ readonly views: { open: Method<methods.ViewsOpenArguments>; publish: Method<methods.ViewsPublishArguments>; push: Method<methods.ViewsPushArguments>; update: Method<methods.ViewsUpdateArguments>; }; /** * dialog method family */ readonly dialog: { open: Method<methods.DialogOpenArguments>; }; /** * dnd method family */ readonly dnd: { endDnd: Method<methods.DndEndDndArguments>; endSnooze: Method<methods.DndEndSnoozeArguments>; info: Method<methods.DndInfoArguments>; setSnooze: Method<methods.DndSetSnoozeArguments>; teamInfo: Method<methods.DndTeamInfoArguments>; }; /** * emoji method family */ readonly emoji: { list: Method<methods.EmojiListArguments>; }; /** * files method family */ readonly files: { delete: Method<methods.FilesDeleteArguments>; info: Method<methods.FilesInfoArguments>; list: Method<methods.FilesListArguments>; revokePublicURL: Method<methods.FilesRevokePublicURLArguments>; sharedPublicURL: Method<methods.FilesSharedPublicURLArguments>; upload: Method<methods.FilesUploadArguments>; comments: { delete: Method<methods.FilesCommentsDeleteArguments>; }; remote: { info: Method<methods.FilesRemoteInfoArguments>; list: Method<methods.FilesRemoteListArguments>; add: Method<methods.FilesRemoteAddArguments>; update: Method<methods.FilesRemoteUpdateArguments>; remove: Method<methods.FilesRemoteRemoveArguments>; share: Method<methods.FilesRemoteShareArguments>; }; }; /** * groups method family */ readonly groups: { archive: Method<methods.GroupsArchiveArguments>; create: Method<methods.GroupsCreateArguments>; createChild: Method<methods.GroupsCreateChildArguments>; history: Method<methods.GroupsHistoryArguments>; info: Method<methods.GroupsInfoArguments>; invite: Method<methods.GroupsInviteArguments>; kick: Method<methods.GroupsKickArguments>; leave: Method<methods.GroupsLeaveArguments>; list: Method<methods.GroupsListArguments>; mark: Method<methods.GroupsMarkArguments>; open: Method<methods.GroupsOpenArguments>; rename: Method<methods.GroupsRenameArguments>; replies: Method<methods.GroupsRepliesArguments>; setPurpose: Method<methods.GroupsSetPurposeArguments>; setTopic: Method<methods.GroupsSetTopicArguments>; unarchive: Method<methods.GroupsUnarchiveArguments>; }; /** * im method family */ readonly im: { close: Method<methods.IMCloseArguments>; history: Method<methods.IMHistoryArguments>; list: Method<methods.IMListArguments>; mark: Method<methods.IMMarkArguments>; open: Method<methods.IMOpenArguments>; replies: Method<methods.IMRepliesArguments>; }; /** * migration method family */ readonly migration: { exchange: Method<methods.MigrationExchangeArguments>; }; /** * mpim method family */ readonly mpim: { close: Method<methods.MPIMCloseArguments>; history: Method<methods.MPIMHistoryArguments>; list: Method<methods.MPIMListArguments>; mark: Method<methods.MPIMMarkArguments>; open: Method<methods.MPIMOpenArguments>; replies: Method<methods.MPIMRepliesArguments>; }; /** * oauth method family */ readonly oauth: { access: Method<methods.OAuthAccessArguments>; v2: { access: Method<methods.OAuthV2AccessArguments>; }; }; /** * pins method family */ readonly pins: { add: Method<methods.PinsAddArguments>; list: Method<methods.PinsListArguments>; remove: Method<methods.PinsRemoveArguments>; }; /** * reactions method family */ readonly reactions: { add: Method<methods.ReactionsAddArguments>; get: Method<methods.ReactionsGetArguments>; list: Method<methods.ReactionsListArguments>; remove: Method<methods.ReactionsRemoveArguments>; }; /** * reminders method family */ readonly reminders: { add: Method<methods.RemindersAddArguments>; complete: Method<methods.RemindersCompleteArguments>; delete: Method<methods.RemindersDeleteArguments>; info: Method<methods.RemindersInfoArguments>; list: Method<methods.RemindersListArguments>; }; /** * rtm method family */ readonly rtm: { connect: Method<methods.RTMConnectArguments>; start: Method<methods.RTMStartArguments>; }; /** * search method family */ readonly search: { all: Method<methods.SearchAllArguments>; files: Method<methods.SearchFilesArguments>; messages: Method<methods.SearchMessagesArguments>; }; /** * stars method family */ readonly stars: { add: Method<methods.StarsAddArguments>; list: Method<methods.StarsListArguments>; remove: Method<methods.StarsRemoveArguments>; }; /** * team method family */ readonly team: { accessLogs: Method<methods.TeamAccessLogsArguments>; billableInfo: Method<methods.TeamBillableInfoArguments>; info: Method<methods.TeamInfoArguments>; integrationLogs: Method<methods.TeamIntegrationLogsArguments>; profile: { get: Method<methods.TeamProfileGetArguments>; }; }; /** * usergroups method family */ readonly usergroups: { create: Method<methods.UsergroupsCreateArguments>; disable: Method<methods.UsergroupsDisableArguments>; enable: Method<methods.UsergroupsEnableArguments>; list: Method<methods.UsergroupsListArguments>; update: Method<methods.UsergroupsUpdateArguments>; users: { list: Method<methods.UsergroupsUsersListArguments>; update: Method<methods.UsergroupsUsersUpdateArguments>; }; }; /** * users method family */ readonly users: { conversations: Method<methods.UsersConversationsArguments>; deletePhoto: Method<methods.UsersDeletePhotoArguments>; getPresence: Method<methods.UsersGetPresenceArguments>; identity: Method<methods.UsersIdentityArguments>; info: Method<methods.UsersInfoArguments>; list: Method<methods.UsersListArguments>; lookupByEmail: Method<methods.UsersLookupByEmailArguments>; setPhoto: Method<methods.UsersSetPhotoArguments>; setPresence: Method<methods.UsersSetPresenceArguments>; profile: { get: Method<methods.UsersProfileGetArguments>; set: Method<methods.UsersProfileSetArguments>; }; }; /** * Low-level function to make a single API request. handles queuing, retries, and http-level errors */ private makeRequest; /** * Transforms options (a simple key-value object) into an acceptable value for a body. This can be either * a string, used when posting with a content-type of url-encoded. Or, it can be a readable stream, used * when the options contain a binary (a stream or a buffer) and the upload should be done with content-type * multipart/form-data. * * @param options arguments for the Web API method * @param headers a mutable object representing the HTTP headers for the outgoing request */ private serializeApiCallOptions; /** * Processes an HTTP response into a WebAPICallResult by performing JSON parsing on the body and merging relevent * HTTP headers into the object. * @param response - an http response */ private buildResult; } export default WebClient; export interface WebClientOptions { slackApiUrl?: string; logger?: Logger; logLevel?: LogLevel; maxRequestConcurrency?: number; retryConfig?: RetryOptions; agent?: Agent; tls?: TLSOptions; rejectRateLimitedCalls?: boolean; headers?: object; } export declare type TLSOptions = Pick<SecureContextOptions, 'pfx' | 'key' | 'passphrase' | 'cert' | 'ca'>; export declare enum WebClientEvent { RATE_LIMITED = "rate_limited" } export interface WebAPICallOptions { [argument: string]: unknown; } export interface WebAPICallResult { ok: boolean; error?: string; response_metadata?: { warnings?: string[]; next_cursor?: string; scopes?: string[]; acceptedScopes?: string[]; retryAfter?: number; messages?: string[]; }; [key: string]: unknown; } export interface PaginatePredicate { (page: WebAPICallResult): boolean | undefined | void; } interface PageReducer<A = any> { (accumulator: A | undefined, page: WebAPICallResult, index: number): A; } declare type PageAccumulator<R extends PageReducer> = R extends (accumulator: (infer A) | undefined, page: WebAPICallResult, index: number) => infer A ? A : never; //# sourceMappingURL=WebClient.d.ts.map
the_stack
import React, { useCallback, useEffect, useState, useRef } from 'react'; import { useFoundation, closest, emptyClientRect, FoundationElement, raf } from '@rmwc/base'; import { MDCMenuSurfaceFoundation, util, MDCMenuDimensions, Corner, MDCMenuDistance } from '@material/menu-surface'; import { MenuSurfaceProps, MenuSurfaceApi } from '.'; const ANCHOR_CORNER_MAP: { [key: string]: keyof typeof MDCMenuSurfaceFoundation.Corner; } = { bottomEnd: 'BOTTOM_END', bottomLeft: 'BOTTOM_LEFT', bottomRight: 'BOTTOM_RIGHT', bottomStart: 'BOTTOM_START', topEnd: 'TOP_END', topLeft: 'TOP_LEFT', topRight: 'TOP_RIGHT', topStart: 'TOP_START' }; const getAnchorCornerFromProp = ( anchorCorner: keyof typeof ANCHOR_CORNER_MAP ) => MDCMenuSurfaceFoundation.Corner[ANCHOR_CORNER_MAP[anchorCorner]]; export const useMenuSurfaceFoundation = ( props: MenuSurfaceProps & React.HTMLProps<any> ) => { const [open, setOpen] = useState(props.open); const firstFocusableElementRef = useRef<HTMLElement | null>(null); const previousFocusRef = useRef<HTMLElement | null>(null); const anchorElementRef = useRef<HTMLElement | null>(null); const timerIdRef = useRef<number | null>(null); const { foundation, ...elements } = useFoundation({ props, elements: { rootEl: true }, api: ({ foundation, rootEl }: { foundation: MDCMenuSurfaceFoundation; rootEl: FoundationElement<any, any>; }): MenuSurfaceApi => { return { hoistMenuToBody: () => { // this is controlled by the renderToPortal prop }, setAnchorCorner: (corner: Corner) => foundation.setAnchorCorner(corner), setAnchorElement: (element: HTMLElement) => (anchorElementRef.current = element), setOpen: (open: boolean) => setOpen(open), getSurfaceElement: () => rootEl.ref }; }, foundation: ({ rootEl, getProps, emit }) => { const handleBodyClick = (evt: MouseEvent | TouchEvent) => { foundation.handleBodyClick(evt as MouseEvent); }; const registerBodyClickListener = () => { /** * Corrects issue on mobile devices that don't support fast click * Causing the menu to close as soon as its open **/ setTimeout(() => { document.body.addEventListener('click', handleBodyClick); document.body.addEventListener('touchstart', handleBodyClick); }, 150); }; const deregisterBodyClickListener = () => { document.body.removeEventListener('click', handleBodyClick); document.body.removeEventListener('touchstart', handleBodyClick); }; const getFocusAdapterMethods = () => { return { isFocused: () => document.activeElement === rootEl.ref, saveFocus: () => { previousFocusRef.current = document.activeElement as HTMLElement; }, restoreFocus: () => { if (rootEl.ref && rootEl.ref.contains(document.activeElement)) { if (previousFocusRef.current && previousFocusRef.current.focus) { previousFocusRef.current.focus(); } } }, isFirstElementFocused: () => !!firstFocusableElementRef.current && firstFocusableElementRef.current === document.activeElement, isLastElementFocused: () => !!firstFocusableElementRef.current && firstFocusableElementRef.current === document.activeElement, focusFirstElement: () => !!firstFocusableElementRef.current && firstFocusableElementRef.current.focus && firstFocusableElementRef.current.focus(), focusLastElement: () => !!firstFocusableElementRef.current && firstFocusableElementRef.current.focus && firstFocusableElementRef.current.focus() }; }; const getDimensionAdapterMethods = () => { return { getInnerDimensions: (): MDCMenuDimensions => { return { width: rootEl.ref ? rootEl.ref.offsetWidth : 0, height: rootEl.ref ? rootEl.ref.offsetHeight : 0 }; }, getAnchorDimensions: () => { return ( anchorElementRef.current?.getBoundingClientRect() || emptyClientRect ); }, getWindowDimensions: () => { return { width: window.innerWidth, height: window.innerHeight }; }, getBodyDimensions: () => { return { width: document.body.clientWidth, height: document.body.clientHeight }; }, getWindowScroll: () => { return { x: window.pageXOffset, y: window.pageYOffset }; }, setPosition: (position: Partial<MDCMenuDistance>) => { rootEl.setStyle( 'left', position.left !== undefined ? position.left : null ); rootEl.setStyle( 'right', position.right !== undefined ? position.right : null ); rootEl.setStyle( 'top', position.top !== undefined ? position.top : null ); rootEl.setStyle( 'bottom', position.bottom !== undefined ? position.bottom : null ); }, setMaxHeight: (height: string) => { rootEl.setStyle('maxHeight', height); } }; }; const f = new MDCMenuSurfaceFoundation({ addClass: (className: string) => { rootEl.addClass(className); }, removeClass: (className: string) => { rootEl.removeClass(className); }, hasClass: (className: string) => className === 'mdc-menu-surface' ? true : rootEl.hasClass(className), hasAnchor: () => !!anchorElementRef.current, notifyClose: () => { deregisterBodyClickListener(); setOpen(false); }, notifyOpen: () => { emit('onOpen', {}); registerBodyClickListener(); }, isElementInContainer: (el: HTMLElement) => rootEl.ref === el || (!!rootEl.ref && rootEl.ref.contains(el)), isRtl: () => !!rootEl.ref && getComputedStyle(rootEl.ref).getPropertyValue('direction') === 'rtl', setTransformOrigin: (origin: string) => { rootEl.setStyle( `${util.getTransformPropertyName(window)}-origin`, origin ); }, ...getFocusAdapterMethods(), ...getDimensionAdapterMethods() }); // Fixes a very annoying issue where the menu isn't stateful // this allows us to keep the menu open based on its controlled prop. const existingClose = f.close.bind(f); const newClose = (skipRestoreFocus = false) => { emit('onClose', {}); timerIdRef.current = window.setTimeout(() => { if (!getProps().open) { existingClose(skipRestoreFocus); } }); }; f.close = newClose; // Didn't have another way to hook into the destroy function... const existingDestroy = f.destroy.bind(f); f.destroy = () => { deregisterBodyClickListener(); existingDestroy(); }; return f; } }); const { rootEl } = elements; const handleKeydown = useCallback( (evt: React.KeyboardEvent & KeyboardEvent) => { props.onKeyDown?.(evt); foundation.handleKeydown(evt); }, [props.onKeyDown, foundation] ); rootEl.setProp('onKeyDown', handleKeydown, true); // fixed useEffect(() => { foundation.setFixedPosition(!!props.fixed); }, [props.fixed, foundation]); // on mount useEffect(() => { const el = rootEl.ref; if (el) { const anchor = closest( el, `.${MDCMenuSurfaceFoundation.cssClasses.ANCHOR}` ); anchor && (anchorElementRef.current = anchor); } }, [rootEl.ref]); // renderToPortal useEffect(() => { props.renderToPortal ? foundation.setIsHoisted(true) : foundation.setIsHoisted(false); const autoPosition = () => { try { // silence this, it blows up loudly occasionally // @ts-ignore unsafe private variable access foundation.autoPosition_(); } catch (err) {} }; // wait an extra frame so that the element is actually // done being hoisted and painting. Fixes Issue #453 const handler = props.renderToPortal ? autoPosition : () => {}; raf(() => { foundation.isOpen() && autoPosition(); }); // fix positioning on window resize when renderToPortal is true window.addEventListener('resize', handler); return () => { window.removeEventListener('resize', handler); }; }, [props.renderToPortal, foundation]); // anchorCorner useEffect(() => { const anchorCorner = props.anchorCorner && getAnchorCornerFromProp(props.anchorCorner); if (anchorCorner !== undefined) { foundation.setAnchorCorner(anchorCorner); // @ts-ignore unsafe private variable reference foundation.dimensions_ = foundation.adapter_.getInnerDimensions(); // @ts-ignore unsafe private variable reference foundation.autoPosition_(); } }, [props.anchorCorner, foundation]); // open useEffect(() => { if (open) { const focusableElements = rootEl.ref ? rootEl.ref.querySelectorAll<HTMLElement>( MDCMenuSurfaceFoundation.strings.FOCUSABLE_ELEMENTS ) : []; firstFocusableElementRef.current = focusableElements.length > 0 ? focusableElements[0] : null; foundation.open(); } else if (foundation.isOpen()) { foundation.close(); } }, [open, foundation, rootEl.ref]); useEffect(() => { setOpen(!!props.open); }, [props.open]); // cleanup useEffect(() => { return () => { timerIdRef.current && window.clearTimeout(timerIdRef.current); }; }, []); return { ...elements }; };
the_stack
import { configContext } from "../../../../ConfigContext"; import { armRequest } from "../../request"; import * as Types from "./types"; const apiVersion = "2021-04-15"; /* Lists the SQL databases under an existing Azure Cosmos DB database account. */ export async function listSqlDatabases( subscriptionId: string, resourceGroupName: string, accountName: string ): Promise<Types.SqlDatabaseListResult> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Gets the SQL database under an existing Azure Cosmos DB database account with the provided name. */ export async function getSqlDatabase( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string ): Promise<Types.SqlDatabaseGetResults> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Create or update an Azure Cosmos DB SQL database */ export async function createUpdateSqlDatabase( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, body: Types.SqlDatabaseCreateUpdateParameters ): Promise<Types.SqlDatabaseGetResults | void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "PUT", apiVersion, body }); } /* Deletes an existing Azure Cosmos DB SQL database. */ export async function deleteSqlDatabase( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string ): Promise<void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "DELETE", apiVersion }); } /* Gets the RUs per second of the SQL database under an existing Azure Cosmos DB database account with the provided name. */ export async function getSqlDatabaseThroughput( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string ): Promise<Types.ThroughputSettingsGetResults> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/throughputSettings/default`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Update RUs per second of an Azure Cosmos DB SQL database */ export async function updateSqlDatabaseThroughput( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, body: Types.ThroughputSettingsUpdateParameters ): Promise<Types.ThroughputSettingsGetResults | void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/throughputSettings/default`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "PUT", apiVersion, body }); } /* Migrate an Azure Cosmos DB SQL database from manual throughput to autoscale */ export async function migrateSqlDatabaseToAutoscale( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string ): Promise<Types.ThroughputSettingsGetResults | void | Types.CloudError> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/throughputSettings/default/migrateToAutoscale`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "POST", apiVersion }); } /* Migrate an Azure Cosmos DB SQL database from autoscale to manual throughput */ export async function migrateSqlDatabaseToManualThroughput( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string ): Promise<Types.ThroughputSettingsGetResults | void | Types.CloudError> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/throughputSettings/default/migrateToManualThroughput`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "POST", apiVersion }); } /* Lists the SQL container under an existing Azure Cosmos DB database account. */ export async function listSqlContainers( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string ): Promise<Types.SqlContainerListResult> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Gets the SQL container under an existing Azure Cosmos DB database account. */ export async function getSqlContainer( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string ): Promise<Types.SqlContainerGetResults> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Create or update an Azure Cosmos DB SQL container */ export async function createUpdateSqlContainer( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string, body: Types.SqlContainerCreateUpdateParameters ): Promise<Types.SqlContainerGetResults | void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "PUT", apiVersion, body }); } /* Deletes an existing Azure Cosmos DB SQL container. */ export async function deleteSqlContainer( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string ): Promise<void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "DELETE", apiVersion }); } /* Gets the RUs per second of the SQL container under an existing Azure Cosmos DB database account. */ export async function getSqlContainerThroughput( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string ): Promise<Types.ThroughputSettingsGetResults> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/throughputSettings/default`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Update RUs per second of an Azure Cosmos DB SQL container */ export async function updateSqlContainerThroughput( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string, body: Types.ThroughputSettingsUpdateParameters ): Promise<Types.ThroughputSettingsGetResults | void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/throughputSettings/default`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "PUT", apiVersion, body }); } /* Migrate an Azure Cosmos DB SQL container from manual throughput to autoscale */ export async function migrateSqlContainerToAutoscale( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string ): Promise<Types.ThroughputSettingsGetResults | void | Types.CloudError> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/throughputSettings/default/migrateToAutoscale`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "POST", apiVersion }); } /* Migrate an Azure Cosmos DB SQL container from autoscale to manual throughput */ export async function migrateSqlContainerToManualThroughput( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string ): Promise<Types.ThroughputSettingsGetResults | void | Types.CloudError> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/throughputSettings/default/migrateToManualThroughput`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "POST", apiVersion }); } /* Lists the SQL storedProcedure under an existing Azure Cosmos DB database account. */ export async function listSqlStoredProcedures( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string ): Promise<Types.SqlStoredProcedureListResult> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/storedProcedures`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Gets the SQL storedProcedure under an existing Azure Cosmos DB database account. */ export async function getSqlStoredProcedure( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string, storedProcedureName: string ): Promise<Types.SqlStoredProcedureGetResults> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/storedProcedures/${storedProcedureName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Create or update an Azure Cosmos DB SQL storedProcedure */ export async function createUpdateSqlStoredProcedure( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string, storedProcedureName: string, body: Types.SqlStoredProcedureCreateUpdateParameters ): Promise<Types.SqlStoredProcedureGetResults | void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/storedProcedures/${storedProcedureName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "PUT", apiVersion, body }); } /* Deletes an existing Azure Cosmos DB SQL storedProcedure. */ export async function deleteSqlStoredProcedure( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string, storedProcedureName: string ): Promise<void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/storedProcedures/${storedProcedureName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "DELETE", apiVersion }); } /* Lists the SQL userDefinedFunction under an existing Azure Cosmos DB database account. */ export async function listSqlUserDefinedFunctions( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string ): Promise<Types.SqlUserDefinedFunctionListResult> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/userDefinedFunctions`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Gets the SQL userDefinedFunction under an existing Azure Cosmos DB database account. */ export async function getSqlUserDefinedFunction( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string, userDefinedFunctionName: string ): Promise<Types.SqlUserDefinedFunctionGetResults> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/userDefinedFunctions/${userDefinedFunctionName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Create or update an Azure Cosmos DB SQL userDefinedFunction */ export async function createUpdateSqlUserDefinedFunction( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string, userDefinedFunctionName: string, body: Types.SqlUserDefinedFunctionCreateUpdateParameters ): Promise<Types.SqlUserDefinedFunctionGetResults | void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/userDefinedFunctions/${userDefinedFunctionName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "PUT", apiVersion, body }); } /* Deletes an existing Azure Cosmos DB SQL userDefinedFunction. */ export async function deleteSqlUserDefinedFunction( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string, userDefinedFunctionName: string ): Promise<void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/userDefinedFunctions/${userDefinedFunctionName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "DELETE", apiVersion }); } /* Lists the SQL trigger under an existing Azure Cosmos DB database account. */ export async function listSqlTriggers( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string ): Promise<Types.SqlTriggerListResult> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/triggers`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Gets the SQL trigger under an existing Azure Cosmos DB database account. */ export async function getSqlTrigger( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string, triggerName: string ): Promise<Types.SqlTriggerGetResults> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/triggers/${triggerName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "GET", apiVersion }); } /* Create or update an Azure Cosmos DB SQL trigger */ export async function createUpdateSqlTrigger( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string, triggerName: string, body: Types.SqlTriggerCreateUpdateParameters ): Promise<Types.SqlTriggerGetResults | void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/triggers/${triggerName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "PUT", apiVersion, body }); } /* Deletes an existing Azure Cosmos DB SQL trigger. */ export async function deleteSqlTrigger( subscriptionId: string, resourceGroupName: string, accountName: string, databaseName: string, containerName: string, triggerName: string ): Promise<void> { const path = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${accountName}/sqlDatabases/${databaseName}/containers/${containerName}/triggers/${triggerName}`; return armRequest({ host: configContext.ARM_ENDPOINT, path, method: "DELETE", apiVersion }); }
the_stack
// The MIT License (MIT) // // vs-deploy (https://github.com/mkloubert/vs-deploy) // Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as deploy_contracts from './contracts'; import * as deploy_helpers from './helpers'; import * as deploy_plugins_switch from './plugins/switch'; import * as deploy_values from './values'; import * as Enumerable from 'node-enumerable'; import * as i18 from './i18'; import * as vs_deploy from './deploy'; import * as vscode from 'vscode'; type SavedStates = { [switchName: string]: string }; interface Button { button: vscode.StatusBarItem; command: vscode.Disposable; index: number; settings: deploy_plugins_switch.DeploySwitchButton; switch: deploy_plugins_switch.DeployTargetSwitch; } /** * Stores the new option data for a target. */ export interface NewSwitchOptionState { /** * The new option. */ option: deploy_plugins_switch.DeployTargetSwitchOption; /** * The underlying target. */ target: deploy_plugins_switch.DeployTargetSwitch; } /** * Repository of selected switch options. */ export type SelectedSwitchOptions = { [name: string]: deploy_plugins_switch.DeployTargetSwitchOption }; const BUTTONS: Button[] = []; const KEY_SWITCH_STATES = 'vsdSwitchStates'; let nextButtonId = -1; let switchStates: SelectedSwitchOptions = {}; /** * Changes a switch target. */ export async function changeSwitch() { const ME: vs_deploy.Deployer = this; const TARGETS = <deploy_plugins_switch.DeployTargetSwitch[]>ME.getTargets().filter(t => { return isSwitch(t); }); let selectedOption: deploy_plugins_switch.DeployTargetSwitchOption; let selectedTarget: deploy_plugins_switch.DeployTargetSwitch; const SELECT_TARGET_OPTION = async (index: number) => { await selectTargetOption.apply(ME, [ selectedTarget, index ]); }; const QUICK_PICKS: deploy_contracts.DeployActionQuickPick[] = TARGETS.map((t, i) => { const LABEL = getSwitchName(t, i); const DESCRIPTION = deploy_helpers.toStringSafe(t.description).trim(); return { action: async () => { selectedTarget = t; await SELECT_TARGET_OPTION(i); }, description: DESCRIPTION, label: LABEL, }; }); if (QUICK_PICKS.length < 1) { vscode.window.showWarningMessage( '[vs-deploy] ' + i18.t('plugins.switch.noDefined'), ); return; } let targetAction: Function; if (1 === QUICK_PICKS.length) { targetAction = QUICK_PICKS[0].action; } else { const SELECTED_ITEM = await vscode.window.showQuickPick(QUICK_PICKS, { placeHolder: i18.t('plugins.switch.selectSwitch'), }); if (SELECTED_ITEM) { targetAction = SELECTED_ITEM.action; } } if (targetAction) { await Promise.resolve( targetAction() ); } } /** * Returns the current option of a target. * * @param {deploy_plugins_switch.DeployTargetSwitch} target The target. * @param {TDefault} [defaultValue] The custom default value. * * @return {deploy_plugins_switch.DeployTargetSwitchOption|TDefault} The option (if found). */ export function getCurrentOptionOf<TDefault = false>(target: deploy_plugins_switch.DeployTargetSwitch, defaultValue = <TDefault><any>false): deploy_plugins_switch.DeployTargetSwitchOption | TDefault { if (!target) { return <any>target; } const TARGET_NAME = deploy_helpers.normalizeString( target.name ); const STATES = getSelectedSwitchOptions(); if (STATES) { const OPTION = STATES[TARGET_NAME]; if ('object' === typeof OPTION) { return OPTION; // found } else { // get first (default) one // instead return Enumerable.from( getTargetOptionsOf(target) ).orderBy(o => { return deploy_helpers.toBooleanSafe(o.isDefault) ? 0 : 1; }).firstOrDefault(x => true, defaultValue); } } return defaultValue; } /** * Returns the object that stores the states of all switches. * * @return {SelectedSwitchOptions} The object with the states. */ export function getSelectedSwitchOptions(): SelectedSwitchOptions { return switchStates || <any>{}; } function getSwitches(): deploy_plugins_switch.DeployTargetSwitch[] { const ME: vs_deploy.Deployer = this; return <deploy_plugins_switch.DeployTargetSwitch[]>ME.getTargets().filter(t => { return isSwitch(t); }); } function getSwitchName(target: deploy_plugins_switch.DeployTargetSwitch, index: number): string { if (!target) { return <any>target; } let name = deploy_helpers.toStringSafe(target.name).trim(); if ('' === name) { name = i18.t('plugins.switch.defaultName', index + 1); } return name; } function getSwitchOptionName(target: deploy_plugins_switch.DeployTargetSwitchOption, index: number): string { if (!target) { return <any>target; } let name = deploy_helpers.toStringSafe(target.name).trim(); if ('' === name) { name = i18.t('plugins.switch.defaultOptionName', index + 1); } return name; } /** * Returns the options of a switch target. * * @param {deploy_plugins_switch.DeployTargetSwitch} target The target. * * @return {deploy_plugins_switch.DeployTargetSwitchOption[]} The options. */ export function getTargetOptionsOf(target: deploy_plugins_switch.DeployTargetSwitch): deploy_plugins_switch.DeployTargetSwitchOption[] { if (deploy_helpers.isNullOrUndefined(target)) { return <any>target; } const TARGET_NAME = deploy_helpers.normalizeString(target.name); const OPTIONS: deploy_plugins_switch.DeployTargetSwitchOption[] = []; let objIndex = -1; Enumerable.from( deploy_helpers.asArray(target.options) ).where(v => { return !deploy_helpers.isNullOrUndefined(v); }).select(v => { ++objIndex; v = deploy_helpers.cloneObject(v); if ('object' !== typeof v) { v = { targets: [ deploy_helpers.normalizeString(v) ] }; } v.__id = `${target.__id}\n` + `${deploy_helpers.normalizeString(deploy_helpers.getSortValue(v))}\n` + `${objIndex}\n` + `${deploy_helpers.normalizeString(v.name)}`; v.__index = objIndex; v.targets = Enumerable.from( deploy_helpers.asArray(v.targets) ).select(t => { return deploy_helpers.normalizeString(t); }).where(t => '' !== t && TARGET_NAME !== t) .distinct() .toArray(); return v; }) .pushTo(OPTIONS); return OPTIONS.sort((x, y) => { return deploy_helpers.compareValuesBy(x, y, o => deploy_helpers.getSortValue(o)); }); } function isSwitch(target: deploy_contracts.DeployTarget): target is deploy_plugins_switch.DeployTargetSwitch { if (target) { return [ 'switch' ].indexOf( deploy_helpers.normalizeString(target.type) ) > -1; } return false; } export function printSwitchStates() { const ME: vs_deploy.Deployer = this; try { const SWITCHES: deploy_plugins_switch.DeployTargetSwitch[] = getSwitches.apply(ME, []); if (SWITCHES.length > 0) { ME.outputChannel.appendLine(''); ME.outputChannel.appendLine( i18.t('plugins.switch.states') ); SWITCHES.forEach((s, i) => { const TARGET_NAME = getSwitchName(s, i); ME.outputChannel.append( i18.t('plugins.switch.item', TARGET_NAME), ); const OPTION = getCurrentOptionOf(s); if (false === OPTION) { ME.outputChannel.appendLine( `<${i18.t('plugins.switch.noOptionSelected')}>`, ); } else { ME.outputChannel.appendLine( "'" + getSwitchOptionName(OPTION, OPTION.__index) + "'", ); } }); ME.outputChannel.appendLine(''); } } catch (e) { ME.log(`[ERROR :: vs-deploy] switch.printSwitchStates(): ${deploy_helpers.toStringSafe(e)}`); } } /** * Reloads the switch buttons. */ export function reloadButtons() { const ME = this; while (BUTTONS.length > 0) { const BTN = BUTTONS.shift(); deploy_helpers.tryDispose(BTN.button); deploy_helpers.tryDispose(BTN.command); } const SWITCHES: deploy_plugins_switch.DeployTargetSwitch[] = getSwitches.apply(ME, []); SWITCHES.forEach((s, i) => { let newBtn: vscode.StatusBarItem; let newCmd: vscode.Disposable; try { if (deploy_helpers.isNullOrUndefined(s.button)) { return; } if ('object' !== typeof s.button) { if (!deploy_helpers.toBooleanSafe(s.button)) { return; } } let btn = s.button; if ('object' !== typeof btn) { btn = { }; } if (!deploy_helpers.toBooleanSafe(btn.enabled, true)) { return; } const ID = nextButtonId++; let color = deploy_helpers.normalizeString(btn.color); const IS_RIGHT = deploy_helpers.toBooleanSafe(btn.isRight); let prio = parseInt( deploy_helpers.toStringSafe(btn.priority).trim() ); if (deploy_helpers.isEmptyString(color)) { color = '#ffffff'; } if (isNaN(prio)) { prio = undefined; } const ALIGNMENT = IS_RIGHT ? vscode.StatusBarAlignment.Right : vscode.StatusBarAlignment.Left; const COMMAND = 'extension.deploy.switches.button' + ID; newCmd = vscode.commands.registerCommand(COMMAND, async () => { await selectTargetOption.apply(ME, [ s, i ]); }); newBtn = vscode.window.createStatusBarItem(ALIGNMENT, prio); newBtn.color = color; newBtn.command = COMMAND; newBtn.show(); BUTTONS.push({ button: newBtn, command: newCmd, index: i, settings: deploy_helpers.cloneObject(btn), switch: s, }); } catch (e) { deploy_helpers.tryDispose(newBtn); deploy_helpers.tryDispose(newCmd); ME.log(`[ERROR :: vs-deploy] switch.reloadButtons(): ${deploy_helpers.toStringSafe(e)}`); } }); updateButtons.apply(ME, []); } /** * Reloads the target states for switches. */ export function reloadTargetStates() { const ME: vs_deploy.Deployer = this; resetTargetStates(); try { const STATES = ME.context.workspaceState.get<SavedStates>(KEY_SWITCH_STATES); if (STATES) { const SWITCHES: deploy_plugins_switch.DeployTargetSwitch[] = getSwitches.apply(ME, []); for (let p in STATES) { const OPTION_ID = STATES[p]; if (deploy_helpers.isEmptyString(OPTION_ID)) { continue; } const TARGET_NAME = deploy_helpers.normalizeString(p); SWITCHES.filter(s => { return TARGET_NAME === deploy_helpers.normalizeString(s.name); }).forEach(s => { Enumerable.from( getTargetOptionsOf(s) ).where(o => { return o.__id === OPTION_ID; }).forEach(o => { setCurrentOptionFor(s, o); }); }); } } // clean update saveStates.apply(ME, []).then(() => { }).catch((err) => { ME.log(`[ERROR :: vs-deploy] switch.reloadTargetStates(2): ${deploy_helpers.toStringSafe(err)}`); }); } catch (e) { ME.log(`[ERROR :: vs-deploy] switch.reloadTargetStates(1): ${deploy_helpers.toStringSafe(e)}`); } } /** * Resets all target states for switches. */ export function resetTargetStates() { switchStates = {}; } /** * Saves the states to the current workspace. */ export async function saveStates() { const ME: vs_deploy.Deployer = this; try { let newValue: SavedStates; const STATES = getSelectedSwitchOptions(); if (STATES) { newValue = {}; for (let p in STATES) { newValue[p] = STATES[p].__id; } } await ME.context.workspaceState.update(KEY_SWITCH_STATES, newValue); } catch (e) { ME.log(`[ERROR :: vs-deploy] switch.saveStates(): ${deploy_helpers.toStringSafe(e)}`); } } async function selectTargetOption(target: deploy_plugins_switch.DeployTargetSwitch, index: number) { const ME: vs_deploy.Deployer = this; if (!target) { return; } let selectedOption: deploy_plugins_switch.DeployTargetSwitchOption; const SWITCH_NAME = getSwitchName(target, index); const OPTIONS = Enumerable.from( getTargetOptionsOf(target) ) .toArray() .sort((x, y) => { return deploy_helpers.compareValuesBy(x, y, i => deploy_helpers.getSortValue(i, () => ME.name)); }); const SELECT_OPTION = async () => { if (!selectedOption) { return; } setCurrentOptionFor(target, selectedOption); await saveStates.apply(ME, []); printSwitchStates.apply(ME, []); updateButtons.apply(ME, []); }; const OPTION_QUICK_PICKS: deploy_contracts.DeployActionQuickPick[] = OPTIONS.map((o, i) => { const LABEL = getSwitchOptionName(o, i); const DESCRIPTION = deploy_helpers.toStringSafe(o.description).trim(); let details = ''; let isSelected = false; const SELECTED_OPTION_OF_TARGET = getCurrentOptionOf(target); if (SELECTED_OPTION_OF_TARGET) { if (o.__id === SELECTED_OPTION_OF_TARGET.__id) { isSelected = true; } } return { action: async () => { selectedOption = o; await SELECT_OPTION(); }, description: DESCRIPTION, detail: isSelected ? `(${i18.t('selected')})` : '', label: LABEL, }; }); if (OPTION_QUICK_PICKS.length < 1) { vscode.window.showWarningMessage( '[vs-deploy] ' + i18.t('plugins.switch.noOptionsDefined', SWITCH_NAME), ); return; } let action: Function; if (1 === OPTION_QUICK_PICKS.length) { action = OPTION_QUICK_PICKS[0].action; } else { const SELECTED_ITEM = await vscode.window.showQuickPick(OPTION_QUICK_PICKS, { placeHolder: i18.t('plugins.switch.selectOption', SWITCH_NAME), }); if (SELECTED_ITEM) { action = SELECTED_ITEM.action; } } if (action) { await Promise.resolve(action()); } } /** * Sets the current option for a switch target. * * @param {deploy_plugins_switch.DeployTargetSwitch} target The target. * @param {deploy_plugins_switch.DeployTargetSwitchOption} option The option to set. * * @return {Object} The new data. */ export function setCurrentOptionFor(target: deploy_plugins_switch.DeployTargetSwitch, option: deploy_plugins_switch.DeployTargetSwitchOption): NewSwitchOptionState { if (!target) { return <any>target; } const NAME = deploy_helpers.normalizeString( target.name ); const STATES = getSelectedSwitchOptions(); if (STATES) { STATES[NAME] = option; return { option: STATES[NAME], target: target, }; } } function updateButtons() { const ME: vs_deploy.Deployer = this; BUTTONS.forEach(btn => { const SWITCH_NAME = getSwitchName(btn.switch, btn.index); const OPTION = getCurrentOptionOf(btn.switch); const VALUES: deploy_values.ValueBase[] = [ new deploy_values.StaticValue({ name: 'selectedSwitch', value: SWITCH_NAME, }), new deploy_values.StaticValue({ name: 'selectedSwitchOption', value: false === OPTION ? undefined : getSwitchOptionName(OPTION, OPTION.__index), }), ]; ME.getValues().forEach(v => { VALUES.push(v); }); let text = deploy_helpers.toStringSafe( deploy_values.replaceWithValues(VALUES, btn.settings.text) ).trim(); if ('' === text) { // default text text = i18.t('plugins.switch.button.text', SWITCH_NAME); } let tooltip = deploy_helpers.toStringSafe( deploy_values.replaceWithValues(VALUES, btn.settings.tooltip) ).trim(); if ('' === tooltip) { // default tooltip if (false === OPTION) { tooltip = i18.t('plugins.switch.button.tooltip', i18.t('plugins.switch.noOptionSelected')); } else { tooltip = i18.t('plugins.switch.button.tooltip', `'${getSwitchOptionName(OPTION, OPTION.__index)}'`); } } btn.button.text = text; btn.button.tooltip = tooltip; }); }
the_stack
import itemID from '../../util/itemID'; import { Createable } from '../createables'; export const armorAndItemPacks: Createable[] = [ // Melee armour sets // bronze { name: 'Unpack bronze set (lg)', inputItems: { [itemID('Bronze set (lg)')]: 1 }, outputItems: { [itemID('Bronze full helm')]: 1, [itemID('Bronze platebody')]: 1, [itemID('Bronze platelegs')]: 1, [itemID('Bronze kiteshield')]: 1 }, noCl: true }, { name: 'Bronze set (lg)', inputItems: { [itemID('Bronze full helm')]: 1, [itemID('Bronze platebody')]: 1, [itemID('Bronze platelegs')]: 1, [itemID('Bronze kiteshield')]: 1 }, outputItems: { [itemID('Bronze set (lg)')]: 1 } }, { name: 'Unpack bronze set (sk)', inputItems: { [itemID('Bronze set (sk)')]: 1 }, outputItems: { [itemID('Bronze full helm')]: 1, [itemID('Bronze platebody')]: 1, [itemID('Bronze plateskirt')]: 1, [itemID('Bronze kiteshield')]: 1 }, noCl: true }, { name: 'Bronze set (sk)', inputItems: { [itemID('Bronze full helm')]: 1, [itemID('Bronze platebody')]: 1, [itemID('Bronze plateskirt')]: 1, [itemID('Bronze kiteshield')]: 1 }, outputItems: { [itemID('Bronze set (sk)')]: 1 } }, { name: 'Unpack bronze trimmed set (lg)', inputItems: { [itemID('Bronze trimmed set (lg)')]: 1 }, outputItems: { [itemID('Bronze full helm (t)')]: 1, [itemID('Bronze platebody (t)')]: 1, [itemID('Bronze platelegs (t)')]: 1, [itemID('Bronze kiteshield (t)')]: 1 }, noCl: true }, { name: 'Bronze trimmed set (lg)', inputItems: { [itemID('Bronze full helm (t)')]: 1, [itemID('Bronze platebody (t)')]: 1, [itemID('Bronze platelegs (t)')]: 1, [itemID('Bronze kiteshield (t)')]: 1 }, outputItems: { [itemID('Bronze trimmed set (lg)')]: 1 } }, { name: 'Unpack bronze trimmed set (sk)', inputItems: { [itemID('Bronze trimmed set (sk)')]: 1 }, outputItems: { [itemID('Bronze full helm (t)')]: 1, [itemID('Bronze platebody (t)')]: 1, [itemID('Bronze plateskirt (t)')]: 1, [itemID('Bronze kiteshield (t)')]: 1 }, noCl: true }, { name: 'Bronze trimmed set (sk)', inputItems: { [itemID('Bronze full helm (t)')]: 1, [itemID('Bronze platebody (t)')]: 1, [itemID('Bronze plateskirt (t)')]: 1, [itemID('Bronze kiteshield (t)')]: 1 }, outputItems: { [itemID('Bronze trimmed set (sk)')]: 1 } }, { name: 'Unpack bronze gold-trimmed set (lg)', inputItems: { [itemID('Bronze gold-trimmed set (lg)')]: 1 }, outputItems: { [itemID('Bronze full helm (g)')]: 1, [itemID('Bronze platebody (g)')]: 1, [itemID('Bronze platelegs (g)')]: 1, [itemID('Bronze kiteshield (g)')]: 1 }, noCl: true }, { name: 'Bronze gold-trimmed set (lg)', inputItems: { [itemID('Bronze full helm (g)')]: 1, [itemID('Bronze platebody (g)')]: 1, [itemID('Bronze platelegs (g)')]: 1, [itemID('Bronze kiteshield (g)')]: 1 }, outputItems: { [itemID('Bronze gold-trimmed set (lg)')]: 1 } }, { name: 'Unpack bronze gold-trimmed set (sk)', inputItems: { [itemID('Bronze gold-trimmed set (sk)')]: 1 }, outputItems: { [itemID('Bronze full helm (g)')]: 1, [itemID('Bronze platebody (g)')]: 1, [itemID('Bronze plateskirt (g)')]: 1, [itemID('Bronze kiteshield (g)')]: 1 }, noCl: true }, { name: 'Bronze gold-trimmed set (sk)', inputItems: { [itemID('Bronze full helm (g)')]: 1, [itemID('Bronze platebody (g)')]: 1, [itemID('Bronze plateskirt (g)')]: 1, [itemID('Bronze kiteshield (g)')]: 1 }, outputItems: { [itemID('Bronze gold-trimmed set (sk)')]: 1 } }, // iron { name: 'Unpack iron set (lg)', inputItems: { [itemID('Iron set (lg)')]: 1 }, outputItems: { [itemID('Iron full helm')]: 1, [itemID('Iron platebody')]: 1, [itemID('Iron platelegs')]: 1, [itemID('Iron kiteshield')]: 1 }, noCl: true }, { name: 'Iron set (lg)', inputItems: { [itemID('Iron full helm')]: 1, [itemID('Iron platebody')]: 1, [itemID('Iron platelegs')]: 1, [itemID('Iron kiteshield')]: 1 }, outputItems: { [itemID('Iron set (lg)')]: 1 } }, { name: 'Unpack iron set (sk)', inputItems: { [itemID('Iron set (sk)')]: 1 }, outputItems: { [itemID('Iron full helm')]: 1, [itemID('Iron platebody')]: 1, [itemID('Iron plateskirt')]: 1, [itemID('Iron kiteshield')]: 1 }, noCl: true }, { name: 'Iron set (sk)', inputItems: { [itemID('Iron full helm')]: 1, [itemID('Iron platebody')]: 1, [itemID('Iron plateskirt')]: 1, [itemID('Iron kiteshield')]: 1 }, outputItems: { [itemID('Iron set (sk)')]: 1 } }, { name: 'Unpack iron trimmed set (lg)', inputItems: { [itemID('Iron trimmed set (lg)')]: 1 }, outputItems: { [itemID('Iron full helm (t)')]: 1, [itemID('Iron platebody (t)')]: 1, [itemID('Iron platelegs (t)')]: 1, [itemID('Iron kiteshield (t)')]: 1 }, noCl: true }, { name: 'Iron trimmed set (lg)', inputItems: { [itemID('Iron full helm (t)')]: 1, [itemID('Iron platebody (t)')]: 1, [itemID('Iron platelegs (t)')]: 1, [itemID('Iron kiteshield (t)')]: 1 }, outputItems: { [itemID('Iron trimmed set (lg)')]: 1 } }, { name: 'Unpack iron trimmed set (sk)', inputItems: { [itemID('Iron trimmed set (sk)')]: 1 }, outputItems: { [itemID('Iron full helm (t)')]: 1, [itemID('Iron platebody (t)')]: 1, [itemID('Iron plateskirt (t)')]: 1, [itemID('Iron kiteshield (t)')]: 1 }, noCl: true }, { name: 'Iron trimmed set (sk)', inputItems: { [itemID('Iron full helm (t)')]: 1, [itemID('Iron platebody (t)')]: 1, [itemID('Iron plateskirt (t)')]: 1, [itemID('Iron kiteshield (t)')]: 1 }, outputItems: { [itemID('Iron trimmed set (sk)')]: 1 } }, { name: 'Unpack iron gold-trimmed set (lg)', inputItems: { [itemID('Iron gold-trimmed set (lg)')]: 1 }, outputItems: { [itemID('Iron full helm (g)')]: 1, [itemID('Iron platebody (g)')]: 1, [itemID('Iron platelegs (g)')]: 1, [itemID('Iron kiteshield (g)')]: 1 }, noCl: true }, { name: 'Iron gold-trimmed set (lg)', inputItems: { [itemID('Iron full helm (g)')]: 1, [itemID('Iron platebody (g)')]: 1, [itemID('Iron platelegs (g)')]: 1, [itemID('Iron kiteshield (g)')]: 1 }, outputItems: { [itemID('Iron gold-trimmed set (lg)')]: 1 } }, { name: 'Unpack iron gold-trimmed set (sk)', inputItems: { [itemID('Iron gold-trimmed set (sk)')]: 1 }, outputItems: { [itemID('Iron full helm (g)')]: 1, [itemID('Iron platebody (g)')]: 1, [itemID('Iron plateskirt (g)')]: 1, [itemID('Iron kiteshield (g)')]: 1 }, noCl: true }, { name: 'Iron gold-trimmed set (sk)', inputItems: { [itemID('Iron full helm (g)')]: 1, [itemID('Iron platebody (g)')]: 1, [itemID('Iron plateskirt (g)')]: 1, [itemID('Iron kiteshield (g)')]: 1 }, outputItems: { [itemID('Iron gold-trimmed set (sk)')]: 1 } }, // steel { name: 'Unpack steel set (lg)', inputItems: { [itemID('Steel set (lg)')]: 1 }, outputItems: { [itemID('Steel full helm')]: 1, [itemID('Steel platebody')]: 1, [itemID('Steel platelegs')]: 1, [itemID('Steel kiteshield')]: 1 }, noCl: true }, { name: 'Steel set (lg)', inputItems: { [itemID('Steel full helm')]: 1, [itemID('Steel platebody')]: 1, [itemID('Steel platelegs')]: 1, [itemID('Steel kiteshield')]: 1 }, outputItems: { [itemID('Steel set (lg)')]: 1 } }, { name: 'Unpack steel set (sk)', inputItems: { [itemID('Steel set (sk)')]: 1 }, outputItems: { [itemID('Steel full helm')]: 1, [itemID('Steel platebody')]: 1, [itemID('Steel plateskirt')]: 1, [itemID('Steel kiteshield')]: 1 }, noCl: true }, { name: 'Steel set (sk)', inputItems: { [itemID('Steel full helm')]: 1, [itemID('Steel platebody')]: 1, [itemID('Steel plateskirt')]: 1, [itemID('Steel kiteshield')]: 1 }, outputItems: { [itemID('Steel set (sk)')]: 1 } }, { name: 'Unpack steel trimmed set (lg)', inputItems: { [itemID('Steel trimmed set (lg)')]: 1 }, outputItems: { [itemID('Steel full helm (t)')]: 1, [itemID('Steel platebody (t)')]: 1, [itemID('Steel platelegs (t)')]: 1, [itemID('Steel kiteshield (t)')]: 1 }, noCl: true }, { name: 'Steel trimmed set (lg)', inputItems: { [itemID('Steel full helm (t)')]: 1, [itemID('Steel platebody (t)')]: 1, [itemID('Steel platelegs (t)')]: 1, [itemID('Steel kiteshield (t)')]: 1 }, outputItems: { [itemID('Steel trimmed set (lg)')]: 1 } }, { name: 'Unpack steel trimmed set (sk)', inputItems: { [itemID('Steel trimmed set (sk)')]: 1 }, outputItems: { [itemID('Steel full helm (t)')]: 1, [itemID('Steel platebody (t)')]: 1, [itemID('Steel plateskirt (t)')]: 1, [itemID('Steel kiteshield (t)')]: 1 }, noCl: true }, { name: 'Steel trimmed set (sk)', inputItems: { [itemID('Steel full helm (t)')]: 1, [itemID('Steel platebody (t)')]: 1, [itemID('Steel plateskirt (t)')]: 1, [itemID('Steel kiteshield (t)')]: 1 }, outputItems: { [itemID('Steel trimmed set (sk)')]: 1 } }, { name: 'Unpack steel gold-trimmed set (lg)', inputItems: { [itemID('Steel gold-trimmed set (lg)')]: 1 }, outputItems: { [itemID('Steel full helm (g)')]: 1, [itemID('Steel platebody (g)')]: 1, [itemID('Steel platelegs (g)')]: 1, [itemID('Steel kiteshield (g)')]: 1 }, noCl: true }, { name: 'Steel gold-trimmed set (lg)', inputItems: { [itemID('Steel full helm (g)')]: 1, [itemID('Steel platebody (g)')]: 1, [itemID('Steel platelegs (g)')]: 1, [itemID('Steel kiteshield (g)')]: 1 }, outputItems: { [itemID('Steel gold-trimmed set (lg)')]: 1 } }, { name: 'Unpack steel gold-trimmed set (sk)', inputItems: { [itemID('Steel gold-trimmed set (sk)')]: 1 }, outputItems: { [itemID('Steel full helm (g)')]: 1, [itemID('Steel platebody (g)')]: 1, [itemID('Steel plateskirt (g)')]: 1, [itemID('Steel kiteshield (g)')]: 1 }, noCl: true }, { name: 'Steel gold-trimmed set (sk)', inputItems: { [itemID('Steel full helm (g)')]: 1, [itemID('Steel platebody (g)')]: 1, [itemID('Steel plateskirt (g)')]: 1, [itemID('Steel kiteshield (g)')]: 1 }, outputItems: { [itemID('Steel gold-trimmed set (sk)')]: 1 } }, // black { name: 'Unpack black set (lg)', inputItems: { [itemID('Black set (lg)')]: 1 }, outputItems: { [itemID('Black full helm')]: 1, [itemID('Black platebody')]: 1, [itemID('Black platelegs')]: 1, [itemID('Black kiteshield')]: 1 }, noCl: true }, { name: 'Black set (lg)', inputItems: { [itemID('Black full helm')]: 1, [itemID('Black platebody')]: 1, [itemID('Black platelegs')]: 1, [itemID('Black kiteshield')]: 1 }, outputItems: { [itemID('Black set (lg)')]: 1 } }, { name: 'Unpack black set (sk)', inputItems: { [itemID('Black set (sk)')]: 1 }, outputItems: { [itemID('Black full helm')]: 1, [itemID('Black platebody')]: 1, [itemID('Black plateskirt')]: 1, [itemID('Black kiteshield')]: 1 }, noCl: true }, { name: 'Black set (sk)', inputItems: { [itemID('Black full helm')]: 1, [itemID('Black platebody')]: 1, [itemID('Black plateskirt')]: 1, [itemID('Black kiteshield')]: 1 }, outputItems: { [itemID('Black set (sk)')]: 1 } }, { name: 'Unpack black trimmed set (lg)', inputItems: { [itemID('Black trimmed set (lg)')]: 1 }, outputItems: { [itemID('Black full helm (t)')]: 1, [itemID('Black platebody (t)')]: 1, [itemID('Black platelegs (t)')]: 1, [itemID('Black kiteshield (t)')]: 1 }, noCl: true }, { name: 'Black trimmed set (lg)', inputItems: { [itemID('Black full helm (t)')]: 1, [itemID('Black platebody (t)')]: 1, [itemID('Black platelegs (t)')]: 1, [itemID('Black kiteshield (t)')]: 1 }, outputItems: { [itemID('Black trimmed set (lg)')]: 1 } }, { name: 'Unpack black trimmed set (sk)', inputItems: { [itemID('Black trimmed set (sk)')]: 1 }, outputItems: { [itemID('Black full helm (t)')]: 1, [itemID('Black platebody (t)')]: 1, [itemID('Black plateskirt (t)')]: 1, [itemID('Black kiteshield (t)')]: 1 }, noCl: true }, { name: 'Black trimmed set (sk)', inputItems: { [itemID('Black full helm (t)')]: 1, [itemID('Black platebody (t)')]: 1, [itemID('Black plateskirt (t)')]: 1, [itemID('Black kiteshield (t)')]: 1 }, outputItems: { [itemID('Black trimmed set (sk)')]: 1 } }, { name: 'Unpack black gold-trimmed set (lg)', inputItems: { [itemID('Black gold-trimmed set (lg)')]: 1 }, outputItems: { [itemID('Black full helm (g)')]: 1, [itemID('Black platebody (g)')]: 1, [itemID('Black platelegs (g)')]: 1, [itemID('Black kiteshield (g)')]: 1 }, noCl: true }, { name: 'Black gold-trimmed set (lg)', inputItems: { [itemID('Black full helm (g)')]: 1, [itemID('Black platebody (g)')]: 1, [itemID('Black platelegs (g)')]: 1, [itemID('Black kiteshield (g)')]: 1 }, outputItems: { [itemID('Black gold-trimmed set (lg)')]: 1 } }, { name: 'Unpack black gold-trimmed set (sk)', inputItems: { [itemID('Black gold-trimmed set (sk)')]: 1 }, outputItems: { [itemID('Black full helm (g)')]: 1, [itemID('Black platebody (g)')]: 1, [itemID('Black plateskirt (g)')]: 1, [itemID('Black kiteshield (g)')]: 1 }, noCl: true }, { name: 'Black gold-trimmed set (sk)', inputItems: { [itemID('Black full helm (g)')]: 1, [itemID('Black platebody (g)')]: 1, [itemID('Black plateskirt (g)')]: 1, [itemID('Black kiteshield (g)')]: 1 }, outputItems: { [itemID('Black gold-trimmed set (sk)')]: 1 } }, // mithril { name: 'Unpack mithril set (lg)', inputItems: { [itemID('Mithril set (lg)')]: 1 }, outputItems: { [itemID('Mithril full helm')]: 1, [itemID('Mithril platebody')]: 1, [itemID('Mithril platelegs')]: 1, [itemID('Mithril kiteshield')]: 1 }, noCl: true }, { name: 'Mithril set (lg)', inputItems: { [itemID('Mithril full helm')]: 1, [itemID('Mithril platebody')]: 1, [itemID('Mithril platelegs')]: 1, [itemID('Mithril kiteshield')]: 1 }, outputItems: { [itemID('Mithril set (lg)')]: 1 } }, { name: 'Unpack mithril set (sk)', inputItems: { [itemID('Mithril set (sk)')]: 1 }, outputItems: { [itemID('Mithril full helm')]: 1, [itemID('Mithril platebody')]: 1, [itemID('Mithril plateskirt')]: 1, [itemID('Mithril kiteshield')]: 1 }, noCl: true }, { name: 'Mithril set (sk)', inputItems: { [itemID('Mithril full helm')]: 1, [itemID('Mithril platebody')]: 1, [itemID('Mithril plateskirt')]: 1, [itemID('Mithril kiteshield')]: 1 }, outputItems: { [itemID('Mithril set (sk)')]: 1 } }, { name: 'Unpack mithril trimmed set (lg)', inputItems: { [itemID('Mithril trimmed set (lg)')]: 1 }, outputItems: { [itemID('Mithril full helm (t)')]: 1, [itemID('Mithril platebody (t)')]: 1, [itemID('Mithril platelegs (t)')]: 1, [itemID('Mithril kiteshield (t)')]: 1 }, noCl: true }, { name: 'Mithril trimmed set (lg)', inputItems: { [itemID('Mithril full helm (t)')]: 1, [itemID('Mithril platebody (t)')]: 1, [itemID('Mithril platelegs (t)')]: 1, [itemID('Mithril kiteshield (t)')]: 1 }, outputItems: { [itemID('Mithril trimmed set (lg)')]: 1 } }, { name: 'Unpack mithril trimmed set (sk)', inputItems: { [itemID('Mithril trimmed set (sk)')]: 1 }, outputItems: { [itemID('Mithril full helm (t)')]: 1, [itemID('Mithril platebody (t)')]: 1, [itemID('Mithril plateskirt (t)')]: 1, [itemID('Mithril kiteshield (t)')]: 1 }, noCl: true }, { name: 'Mithril trimmed set (sk)', inputItems: { [itemID('Mithril full helm (t)')]: 1, [itemID('Mithril platebody (t)')]: 1, [itemID('Mithril plateskirt (t)')]: 1, [itemID('Mithril kiteshield (t)')]: 1 }, outputItems: { [itemID('Mithril trimmed set (sk)')]: 1 } }, { name: 'Unpack mithril gold-trimmed set (lg)', inputItems: { [itemID('Mithril gold-trimmed set (lg)')]: 1 }, outputItems: { [itemID('Mithril full helm (g)')]: 1, [itemID('Mithril platebody (g)')]: 1, [itemID('Mithril platelegs (g)')]: 1, [itemID('Mithril kiteshield (g)')]: 1 }, noCl: true }, { name: 'Mithril gold-trimmed set (lg)', inputItems: { [itemID('Mithril full helm (g)')]: 1, [itemID('Mithril platebody (g)')]: 1, [itemID('Mithril platelegs (g)')]: 1, [itemID('Mithril kiteshield (g)')]: 1 }, outputItems: { [itemID('Mithril gold-trimmed set (lg)')]: 1 } }, { name: 'Unpack mithril gold-trimmed set (sk)', inputItems: { [itemID('Mithril gold-trimmed set (sk)')]: 1 }, outputItems: { [itemID('Mithril full helm (g)')]: 1, [itemID('Mithril platebody (g)')]: 1, [itemID('Mithril plateskirt (g)')]: 1, [itemID('Mithril kiteshield (g)')]: 1 }, noCl: true }, { name: 'Mithril gold-trimmed set (sk)', inputItems: { [itemID('Mithril full helm (g)')]: 1, [itemID('Mithril platebody (g)')]: 1, [itemID('Mithril plateskirt (g)')]: 1, [itemID('Mithril kiteshield (g)')]: 1 }, outputItems: { [itemID('Mithril gold-trimmed set (sk)')]: 1 } }, // adamant { name: 'Unpack adamant set (lg)', inputItems: { [itemID('Adamant set (lg)')]: 1 }, outputItems: { [itemID('Adamant full helm')]: 1, [itemID('Adamant platebody')]: 1, [itemID('Adamant platelegs')]: 1, [itemID('Adamant kiteshield')]: 1 }, noCl: true }, { name: 'Adamant set (lg)', inputItems: { [itemID('Adamant full helm')]: 1, [itemID('Adamant platebody')]: 1, [itemID('Adamant platelegs')]: 1, [itemID('Adamant kiteshield')]: 1 }, outputItems: { [itemID('Adamant set (lg)')]: 1 } }, { name: 'Unpack adamant set (sk)', inputItems: { [itemID('Adamant set (sk)')]: 1 }, outputItems: { [itemID('Adamant full helm')]: 1, [itemID('Adamant platebody')]: 1, [itemID('Adamant plateskirt')]: 1, [itemID('Adamant kiteshield')]: 1 }, noCl: true }, { name: 'Adamant set (sk)', inputItems: { [itemID('Adamant full helm')]: 1, [itemID('Adamant platebody')]: 1, [itemID('Adamant plateskirt')]: 1, [itemID('Adamant kiteshield')]: 1 }, outputItems: { [itemID('Adamant set (sk)')]: 1 } }, { name: 'Unpack adamant trimmed set (lg)', inputItems: { [itemID('Adamant trimmed set (lg)')]: 1 }, outputItems: { [itemID('Adamant full helm (t)')]: 1, [itemID('Adamant platebody (t)')]: 1, [itemID('Adamant platelegs (t)')]: 1, [itemID('Adamant kiteshield (t)')]: 1 }, noCl: true }, { name: 'Adamant trimmed set (lg)', inputItems: { [itemID('Adamant full helm (t)')]: 1, [itemID('Adamant platebody (t)')]: 1, [itemID('Adamant platelegs (t)')]: 1, [itemID('Adamant kiteshield (t)')]: 1 }, outputItems: { [itemID('Adamant trimmed set (lg)')]: 1 } }, { name: 'Unpack adamant trimmed set (sk)', inputItems: { [itemID('Adamant trimmed set (sk)')]: 1 }, outputItems: { [itemID('Adamant full helm (t)')]: 1, [itemID('Adamant platebody (t)')]: 1, [itemID('Adamant plateskirt (t)')]: 1, [itemID('Adamant kiteshield (t)')]: 1 }, noCl: true }, { name: 'Adamant trimmed set (sk)', inputItems: { [itemID('Adamant full helm (t)')]: 1, [itemID('Adamant platebody (t)')]: 1, [itemID('Adamant plateskirt (t)')]: 1, [itemID('Adamant kiteshield (t)')]: 1 }, outputItems: { [itemID('Adamant trimmed set (sk)')]: 1 } }, { name: 'Unpack adamant gold-trimmed set (lg)', inputItems: { [itemID('Adamant gold-trimmed set (lg)')]: 1 }, outputItems: { [itemID('Adamant full helm (g)')]: 1, [itemID('Adamant platebody (g)')]: 1, [itemID('Adamant platelegs (g)')]: 1, [itemID('Adamant kiteshield (g)')]: 1 }, noCl: true }, { name: 'Adamant gold-trimmed set (lg)', inputItems: { [itemID('Adamant full helm (g)')]: 1, [itemID('Adamant platebody (g)')]: 1, [itemID('Adamant platelegs (g)')]: 1, [itemID('Adamant kiteshield (g)')]: 1 }, outputItems: { [itemID('Adamant gold-trimmed set (lg)')]: 1 } }, { name: 'Unpack adamant gold-trimmed set (sk)', inputItems: { [itemID('Adamant gold-trimmed set (sk)')]: 1 }, outputItems: { [itemID('Adamant full helm (g)')]: 1, [itemID('Adamant platebody (g)')]: 1, [itemID('Adamant plateskirt (g)')]: 1, [itemID('Adamant kiteshield (g)')]: 1 }, noCl: true }, { name: 'Adamant gold-trimmed set (sk)', inputItems: { [itemID('Adamant full helm (g)')]: 1, [itemID('Adamant platebody (g)')]: 1, [itemID('Adamant plateskirt (g)')]: 1, [itemID('Adamant kiteshield (g)')]: 1 }, outputItems: { [itemID('Adamant gold-trimmed set (sk)')]: 1 } }, // rune { name: 'Unpack rune armour set (lg)', inputItems: { [itemID('Rune armour set (lg)')]: 1 }, outputItems: { [itemID('Rune full helm')]: 1, [itemID('Rune platebody')]: 1, [itemID('Rune platelegs')]: 1, [itemID('Rune kiteshield')]: 1 }, noCl: true }, { name: 'Rune armour set (lg)', inputItems: { [itemID('Rune full helm')]: 1, [itemID('Rune platebody')]: 1, [itemID('Rune platelegs')]: 1, [itemID('Rune kiteshield')]: 1 }, outputItems: { [itemID('Rune armour set (lg)')]: 1 } }, { name: 'Unpack rune armour set (sk)', inputItems: { [itemID('Rune armour set (sk)')]: 1 }, outputItems: { [itemID('Rune full helm')]: 1, [itemID('Rune platebody')]: 1, [itemID('Rune plateskirt')]: 1, [itemID('Rune kiteshield')]: 1 }, noCl: true }, { name: 'Rune armour set (sk)', inputItems: { [itemID('Rune full helm')]: 1, [itemID('Rune platebody')]: 1, [itemID('Rune plateskirt')]: 1, [itemID('Rune kiteshield')]: 1 }, outputItems: { [itemID('Rune armour set (sk)')]: 1 } }, { name: 'Unpack rune trimmed set (lg)', inputItems: { [itemID('Rune trimmed set (lg)')]: 1 }, outputItems: { [itemID('Rune full helm (t)')]: 1, [itemID('Rune platebody (t)')]: 1, [itemID('Rune platelegs (t)')]: 1, [itemID('Rune kiteshield (t)')]: 1 }, noCl: true }, { name: 'Rune trimmed set (lg)', inputItems: { [itemID('Rune full helm (t)')]: 1, [itemID('Rune platebody (t)')]: 1, [itemID('Rune platelegs (t)')]: 1, [itemID('Rune kiteshield (t)')]: 1 }, outputItems: { [itemID('Rune trimmed set (lg)')]: 1 } }, { name: 'Unpack rune trimmed set (sk)', inputItems: { [itemID('Rune trimmed set (sk)')]: 1 }, outputItems: { [itemID('Rune full helm (t)')]: 1, [itemID('Rune platebody (t)')]: 1, [itemID('Rune plateskirt (t)')]: 1, [itemID('Rune kiteshield (t)')]: 1 }, noCl: true }, { name: 'Rune trimmed set (sk)', inputItems: { [itemID('Rune full helm (t)')]: 1, [itemID('Rune platebody (t)')]: 1, [itemID('Rune plateskirt (t)')]: 1, [itemID('Rune kiteshield (t)')]: 1 }, outputItems: { [itemID('Rune trimmed set (sk)')]: 1 } }, { name: 'Unpack rune gold-trimmed set (lg)', inputItems: { [itemID('Rune gold-trimmed set (lg)')]: 1 }, outputItems: { [itemID('Rune full helm (g)')]: 1, [itemID('Rune platebody (g)')]: 1, [itemID('Rune platelegs (g)')]: 1, [itemID('Rune kiteshield (g)')]: 1 }, noCl: true }, { name: 'Rune gold-trimmed set (lg)', inputItems: { [itemID('Rune full helm (g)')]: 1, [itemID('Rune platebody (g)')]: 1, [itemID('Rune platelegs (g)')]: 1, [itemID('Rune kiteshield (g)')]: 1 }, outputItems: { [itemID('Rune gold-trimmed set (lg)')]: 1 } }, { name: 'Unpack rune gold-trimmed set (sk)', inputItems: { [itemID('Rune gold-trimmed set (sk)')]: 1 }, outputItems: { [itemID('Rune full helm (g)')]: 1, [itemID('Rune platebody (g)')]: 1, [itemID('Rune plateskirt (g)')]: 1, [itemID('Rune kiteshield (g)')]: 1 }, noCl: true }, { name: 'Rune gold-trimmed set (sk)', inputItems: { [itemID('Rune full helm (g)')]: 1, [itemID('Rune platebody (g)')]: 1, [itemID('Rune plateskirt (g)')]: 1, [itemID('Rune kiteshield (g)')]: 1 }, outputItems: { [itemID('Rune gold-trimmed set (sk)')]: 1 } }, { name: 'Unpack gilded armour set (lg)', inputItems: { [itemID('Gilded armour set (lg)')]: 1 }, outputItems: { [itemID('Gilded full helm')]: 1, [itemID('Gilded platebody')]: 1, [itemID('Gilded platelegs')]: 1, [itemID('Gilded kiteshield')]: 1 }, noCl: true }, { name: 'Gilded armour set (lg)', inputItems: { [itemID('Gilded full helm')]: 1, [itemID('Gilded platebody')]: 1, [itemID('Gilded platelegs')]: 1, [itemID('Gilded kiteshield')]: 1 }, outputItems: { [itemID('Gilded armour set (lg)')]: 1 } }, { name: 'Unpack gilded armour set (sk)', inputItems: { [itemID('Gilded armour set (sk)')]: 1 }, outputItems: { [itemID('Gilded full helm')]: 1, [itemID('Gilded platebody')]: 1, [itemID('Gilded plateskirt')]: 1, [itemID('Gilded kiteshield')]: 1 }, noCl: true }, { name: 'Gilded armour set (sk)', inputItems: { [itemID('Gilded full helm')]: 1, [itemID('Gilded platebody')]: 1, [itemID('Gilded plateskirt')]: 1, [itemID('Gilded kiteshield')]: 1 }, outputItems: { [itemID('Gilded armour set (sk)')]: 1 } }, // rune god armours { name: 'Unpack guthix armour set (lg)', inputItems: { [itemID('Guthix armour set (lg)')]: 1 }, outputItems: { [itemID('Guthix full helm')]: 1, [itemID('Guthix platebody')]: 1, [itemID('Guthix platelegs')]: 1, [itemID('Guthix kiteshield')]: 1 }, noCl: true }, { name: 'Guthix armour set (lg)', inputItems: { [itemID('Guthix full helm')]: 1, [itemID('Guthix platebody')]: 1, [itemID('Guthix platelegs')]: 1, [itemID('Guthix kiteshield')]: 1 }, outputItems: { [itemID('Guthix armour set (lg)')]: 1 } }, { name: 'Unpack guthix armour set (sk)', inputItems: { [itemID('Guthix armour set (sk)')]: 1 }, outputItems: { [itemID('Guthix full helm')]: 1, [itemID('Guthix platebody')]: 1, [itemID('Guthix plateskirt')]: 1, [itemID('Guthix kiteshield')]: 1 }, noCl: true }, { name: 'Guthix armour set (sk)', inputItems: { [itemID('Guthix full helm')]: 1, [itemID('Guthix platebody')]: 1, [itemID('Guthix plateskirt')]: 1, [itemID('Guthix kiteshield')]: 1 }, outputItems: { [itemID('Guthix armour set (sk)')]: 1 } }, { name: 'Unpack saradomin armour set (lg)', inputItems: { [itemID('Saradomin armour set (lg)')]: 1 }, outputItems: { [itemID('Saradomin full helm')]: 1, [itemID('Saradomin platebody')]: 1, [itemID('Saradomin platelegs')]: 1, [itemID('Saradomin kiteshield')]: 1 }, noCl: true }, { name: 'Saradomin armour set (lg)', inputItems: { [itemID('Saradomin full helm')]: 1, [itemID('Saradomin platebody')]: 1, [itemID('Saradomin platelegs')]: 1, [itemID('Saradomin kiteshield')]: 1 }, outputItems: { [itemID('Saradomin armour set (lg)')]: 1 } }, { name: 'Unpack saradomin armour set (sk)', inputItems: { [itemID('Saradomin armour set (sk)')]: 1 }, outputItems: { [itemID('Saradomin full helm')]: 1, [itemID('Saradomin platebody')]: 1, [itemID('Saradomin plateskirt')]: 1, [itemID('Saradomin kiteshield')]: 1 }, noCl: true }, { name: 'Saradomin armour set (sk)', inputItems: { [itemID('Saradomin full helm')]: 1, [itemID('Saradomin platebody')]: 1, [itemID('Saradomin plateskirt')]: 1, [itemID('Saradomin kiteshield')]: 1 }, outputItems: { [itemID('Saradomin armour set (sk)')]: 1 } }, { name: 'Unpack zamorak armour set (lg)', inputItems: { [itemID('Zamorak armour set (lg)')]: 1 }, outputItems: { [itemID('Zamorak full helm')]: 1, [itemID('Zamorak platebody')]: 1, [itemID('Zamorak platelegs')]: 1, [itemID('Zamorak kiteshield')]: 1 }, noCl: true }, { name: 'Zamorak armour set (lg)', inputItems: { [itemID('Zamorak full helm')]: 1, [itemID('Zamorak platebody')]: 1, [itemID('Zamorak platelegs')]: 1, [itemID('Zamorak kiteshield')]: 1 }, outputItems: { [itemID('Zamorak armour set (lg)')]: 1 } }, { name: 'Unpack zamorak armour set (sk)', inputItems: { [itemID('Zamorak armour set (sk)')]: 1 }, outputItems: { [itemID('Zamorak full helm')]: 1, [itemID('Zamorak platebody')]: 1, [itemID('Zamorak plateskirt')]: 1, [itemID('Zamorak kiteshield')]: 1 }, noCl: true }, { name: 'Zamorak armour set (sk)', inputItems: { [itemID('Zamorak full helm')]: 1, [itemID('Zamorak platebody')]: 1, [itemID('Zamorak plateskirt')]: 1, [itemID('Zamorak kiteshield')]: 1 }, outputItems: { [itemID('Zamorak armour set (sk)')]: 1 } }, { name: 'Unpack ancient rune armour set (lg)', inputItems: { [itemID('Ancient rune armour set (lg)')]: 1 }, outputItems: { [itemID('Ancient full helm')]: 1, [itemID('Ancient platebody')]: 1, [itemID('Ancient platelegs')]: 1, [itemID('Ancient kiteshield')]: 1 }, noCl: true }, { name: 'Ancient rune armour set (lg)', inputItems: { [itemID('Ancient full helm')]: 1, [itemID('Ancient platebody')]: 1, [itemID('Ancient platelegs')]: 1, [itemID('Ancient kiteshield')]: 1 }, outputItems: { [itemID('Ancient rune armour set (lg)')]: 1 } }, { name: 'Unpack ancient rune armour set (sk)', inputItems: { [itemID('Ancient rune armour set (sk)')]: 1 }, outputItems: { [itemID('Ancient full helm')]: 1, [itemID('Ancient platebody')]: 1, [itemID('Ancient plateskirt')]: 1, [itemID('Ancient kiteshield')]: 1 }, noCl: true }, { name: 'Ancient rune armour set (sk)', inputItems: { [itemID('Ancient full helm')]: 1, [itemID('Ancient platebody')]: 1, [itemID('Ancient plateskirt')]: 1, [itemID('Ancient kiteshield')]: 1 }, outputItems: { [itemID('Ancient rune armour set (sk)')]: 1 } }, { name: 'Unpack armadyl rune armour set (lg)', inputItems: { [itemID('Armadyl rune armour set (lg)')]: 1 }, outputItems: { [itemID('Armadyl full helm')]: 1, [itemID('Armadyl platebody')]: 1, [itemID('Armadyl platelegs')]: 1, [itemID('Armadyl kiteshield')]: 1 }, noCl: true }, { name: 'Armadyl rune armour set (lg)', inputItems: { [itemID('Armadyl full helm')]: 1, [itemID('Armadyl platebody')]: 1, [itemID('Armadyl platelegs')]: 1, [itemID('Armadyl kiteshield')]: 1 }, outputItems: { [itemID('Armadyl rune armour set (lg)')]: 1 } }, { name: 'Unpack armadyl rune armour set (sk)', inputItems: { [itemID('Armadyl rune armour set (sk)')]: 1 }, outputItems: { [itemID('Armadyl full helm')]: 1, [itemID('Armadyl platebody')]: 1, [itemID('Armadyl plateskirt')]: 1, [itemID('Armadyl kiteshield')]: 1 }, noCl: true }, { name: 'Armadyl rune armour set (sk)', inputItems: { [itemID('Armadyl full helm')]: 1, [itemID('Armadyl platebody')]: 1, [itemID('Armadyl plateskirt')]: 1, [itemID('Armadyl kiteshield')]: 1 }, outputItems: { [itemID('Armadyl rune armour set (sk)')]: 1 } }, { name: 'Unpack bandos rune armour set (lg)', inputItems: { [itemID('Bandos rune armour set (lg)')]: 1 }, outputItems: { [itemID('Bandos full helm')]: 1, [itemID('Bandos platebody')]: 1, [itemID('Bandos platelegs')]: 1, [itemID('Bandos kiteshield')]: 1 }, noCl: true }, { name: 'Bandos rune armour set (lg)', inputItems: { [itemID('Bandos full helm')]: 1, [itemID('Bandos platebody')]: 1, [itemID('Bandos platelegs')]: 1, [itemID('Bandos kiteshield')]: 1 }, outputItems: { [itemID('Bandos rune armour set (lg)')]: 1 } }, { name: 'Unpack bandos rune armour set (sk)', inputItems: { [itemID('Bandos rune armour set (sk)')]: 1 }, outputItems: { [itemID('Bandos full helm')]: 1, [itemID('Bandos platebody')]: 1, [itemID('Bandos plateskirt')]: 1, [itemID('Bandos kiteshield')]: 1 }, noCl: true }, { name: 'Bandos rune armour set (sk)', inputItems: { [itemID('Bandos full helm')]: 1, [itemID('Bandos platebody')]: 1, [itemID('Bandos plateskirt')]: 1, [itemID('Bandos kiteshield')]: 1 }, outputItems: { [itemID('Bandos rune armour set (sk)')]: 1 } }, // dragon { name: 'Unpack dragon armour set (lg)', inputItems: { [itemID('Dragon armour set (lg)')]: 1 }, outputItems: { [itemID('Dragon full helm')]: 1, [itemID('Dragon platebody')]: 1, [itemID('Dragon platelegs')]: 1, [itemID('Dragon kiteshield')]: 1 }, noCl: true }, { name: 'Dragon armour set (lg)', inputItems: { [itemID('Dragon full helm')]: 1, [itemID('Dragon platebody')]: 1, [itemID('Dragon platelegs')]: 1, [itemID('Dragon kiteshield')]: 1 }, outputItems: { [itemID('Dragon armour set (lg)')]: 1 } }, { name: 'Unpack dragon armour set (sk)', inputItems: { [itemID('Dragon armour set (sk)')]: 1 }, outputItems: { [itemID('Dragon full helm')]: 1, [itemID('Dragon platebody')]: 1, [itemID('Dragon plateskirt')]: 1, [itemID('Dragon kiteshield')]: 1 }, noCl: true }, { name: 'Dragon armour set (sk)', inputItems: { [itemID('Dragon full helm')]: 1, [itemID('Dragon platebody')]: 1, [itemID('Dragon plateskirt')]: 1, [itemID('Dragon kiteshield')]: 1 }, outputItems: { [itemID('Dragon armour set (sk)')]: 1 } }, // barrows { name: "Unpack verac's armour set", inputItems: { [itemID("Verac's armour set")]: 1 }, outputItems: { [itemID("Verac's helm")]: 1, [itemID("Verac's brassard")]: 1, [itemID("Verac's plateskirt")]: 1, [itemID("Verac's flail")]: 1 }, noCl: true }, { name: "Verac's armour set", inputItems: { [itemID("Verac's helm")]: 1, [itemID("Verac's brassard")]: 1, [itemID("Verac's plateskirt")]: 1, [itemID("Verac's flail")]: 1 }, outputItems: { [itemID("Verac's armour set")]: 1 } }, { name: "Unpack dharok's armour set", inputItems: { [itemID("Dharok's armour set")]: 1 }, outputItems: { [itemID("Dharok's helm")]: 1, [itemID("Dharok's platebody")]: 1, [itemID("Dharok's platelegs")]: 1, [itemID("Dharok's greataxe")]: 1 }, noCl: true }, { name: "Dharok's armour set", inputItems: { [itemID("Dharok's helm")]: 1, [itemID("Dharok's platebody")]: 1, [itemID("Dharok's platelegs")]: 1, [itemID("Dharok's greataxe")]: 1 }, outputItems: { [itemID("Dharok's armour set")]: 1 } }, { name: "Unpack guthan's armour set", inputItems: { [itemID("Guthan's armour set")]: 1 }, outputItems: { [itemID("Guthan's helm")]: 1, [itemID("Guthan's platebody")]: 1, [itemID("Guthan's chainskirt")]: 1, [itemID("Guthan's warspear")]: 1 }, noCl: true }, { name: "Guthan's armour set", inputItems: { [itemID("Guthan's helm")]: 1, [itemID("Guthan's platebody")]: 1, [itemID("Guthan's chainskirt")]: 1, [itemID("Guthan's warspear")]: 1 }, outputItems: { [itemID("Guthan's armour set")]: 1 } }, { name: "Unpack ahrim's armour set", inputItems: { [itemID("Ahrim's armour set")]: 1 }, outputItems: { [itemID("Ahrim's hood")]: 1, [itemID("Ahrim's robetop")]: 1, [itemID("Ahrim's robeskirt")]: 1, [itemID("Ahrim's staff")]: 1 }, noCl: true }, { name: "Ahrim's armour set", inputItems: { [itemID("Ahrim's hood")]: 1, [itemID("Ahrim's robetop")]: 1, [itemID("Ahrim's robeskirt")]: 1, [itemID("Ahrim's staff")]: 1 }, outputItems: { [itemID("Ahrim's armour set")]: 1 } }, { name: "Unpack torag's armour set", inputItems: { [itemID("Torag's armour set")]: 1 }, outputItems: { [itemID("Torag's helm")]: 1, [itemID("Torag's platebody")]: 1, [itemID("Torag's platelegs")]: 1, [itemID("Torag's hammers")]: 1 }, noCl: true }, { name: "Torag's armour set", inputItems: { [itemID("Torag's helm")]: 1, [itemID("Torag's platebody")]: 1, [itemID("Torag's platelegs")]: 1, [itemID("Torag's hammers")]: 1 }, outputItems: { [itemID("Torag's armour set")]: 1 } }, { name: "Unpack karil's armour set", inputItems: { [itemID("Karil's armour set")]: 1 }, outputItems: { [itemID("Karil's coif")]: 1, [itemID("Karil's leathertop")]: 1, [itemID("Karil's leatherskirt")]: 1, [itemID("Karil's crossbow")]: 1 }, noCl: true }, { name: "Karil's armour set", inputItems: { [itemID("Karil's coif")]: 1, [itemID("Karil's leathertop")]: 1, [itemID("Karil's leatherskirt")]: 1, [itemID("Karil's crossbow")]: 1 }, outputItems: { [itemID("Karil's armour set")]: 1 } }, // inquisitor { name: "Unpack inquisitor's armour set", inputItems: { [itemID("Inquisitor's armour set")]: 1 }, outputItems: { [itemID("Inquisitor's great helm")]: 1, [itemID("Inquisitor's hauberk")]: 1, [itemID("Inquisitor's plateskirt")]: 1 }, noCl: true }, { name: "Inquisitor's armour set", inputItems: { [itemID("Inquisitor's great helm")]: 1, [itemID("Inquisitor's hauberk")]: 1, [itemID("Inquisitor's plateskirt")]: 1 }, outputItems: { [itemID("Inquisitor's armour set")]: 1 } }, // justiciar { name: 'Unpack justiciar armour set', inputItems: { [itemID('Justiciar armour set')]: 1 }, outputItems: { [itemID('Justiciar faceguard')]: 1, [itemID('Justiciar chestguard')]: 1, [itemID('Justiciar legguards')]: 1 }, noCl: true }, { name: 'Justiciar armour set', inputItems: { [itemID('Justiciar faceguard')]: 1, [itemID('Justiciar chestguard')]: 1, [itemID('Justiciar legguards')]: 1 }, outputItems: { [itemID('Justiciar armour set')]: 1 } }, // obsidian { name: 'Unpack obsidian armour set', inputItems: { [itemID('Obsidian armour set')]: 1 }, outputItems: { [itemID('Obsidian helmet')]: 1, [itemID('Obsidian platebody')]: 1, [itemID('Obsidian platelegs')]: 1 }, noCl: true }, { name: 'Obsidian armour set', inputItems: { [itemID('Obsidian helmet')]: 1, [itemID('Obsidian platebody')]: 1, [itemID('Obsidian platelegs')]: 1 }, outputItems: { [itemID('Obsidian armour set')]: 1 } }, // dragonstone { name: 'Unpack dragonstone armour set', inputItems: { [itemID('Dragonstone armour set')]: 1 }, outputItems: { [itemID('Dragonstone full helm')]: 1, [itemID('Dragonstone platebody')]: 1, [itemID('Dragonstone platelegs')]: 1, [itemID('Dragonstone gauntlets')]: 1, [itemID('Dragonstone boots')]: 1 }, noCl: true }, { name: 'Dragonstone armour set', inputItems: { [itemID('Dragonstone full helm')]: 1, [itemID('Dragonstone platebody')]: 1, [itemID('Dragonstone platelegs')]: 1, [itemID('Dragonstone gauntlets')]: 1, [itemID('Dragonstone boots')]: 1 }, outputItems: { [itemID('Dragonstone armour set')]: 1 } }, // temple knight { name: 'Unpack initiate harness m', inputItems: { [itemID('Initiate harness m')]: 1 }, outputItems: { [itemID('Initiate sallet')]: 1, [itemID('Initiate hauberk')]: 1, [itemID('Initiate cuisse')]: 1 }, noCl: true }, { name: 'Initiate harness m', inputItems: { [itemID('Initiate sallet')]: 1, [itemID('Initiate hauberk')]: 1, [itemID('Initiate cuisse')]: 1 }, outputItems: { [itemID('Initiate harness m')]: 1 } }, { name: 'Unpack proselyte harness m', inputItems: { [itemID('Proselyte harness m')]: 1 }, outputItems: { [itemID('Proselyte sallet')]: 1, [itemID('Proselyte hauberk')]: 1, [itemID('Proselyte cuisse')]: 1 }, noCl: true }, { name: 'Proselyte harness m', inputItems: { [itemID('Proselyte sallet')]: 1, [itemID('Proselyte hauberk')]: 1, [itemID('Proselyte cuisse')]: 1 }, outputItems: { [itemID('Proselyte harness m')]: 1 } }, { name: 'Unpack proselyte harness f', inputItems: { [itemID('Proselyte harness f')]: 1 }, outputItems: { [itemID('Proselyte sallet')]: 1, [itemID('Proselyte hauberk')]: 1, [itemID('Proselyte tasset')]: 1 }, noCl: true }, { name: 'Proselyte harness f', inputItems: { [itemID('Proselyte sallet')]: 1, [itemID('Proselyte hauberk')]: 1, [itemID('Proselyte tasset')]: 1 }, outputItems: { [itemID('Proselyte harness f')]: 1 } }, // range sets // dragonhide { name: 'Unpack green dragonhide set', inputItems: { [itemID('Green dragonhide set')]: 1 }, outputItems: { [itemID("Green d'hide body")]: 1, [itemID("Green d'hide chaps")]: 1, [itemID("Green d'hide vambraces")]: 1 }, noCl: true }, { name: 'Green dragonhide set', inputItems: { [itemID("Green d'hide body")]: 1, [itemID("Green d'hide chaps")]: 1, [itemID("Green d'hide vambraces")]: 1 }, outputItems: { [itemID('Green dragonhide set')]: 1 } }, { name: 'Unpack blue dragonhide set', inputItems: { [itemID('Blue dragonhide set')]: 1 }, outputItems: { [itemID("Blue d'hide body")]: 1, [itemID("Blue d'hide chaps")]: 1, [itemID("Blue d'hide vambraces")]: 1 }, noCl: true }, { name: 'Blue dragonhide set', inputItems: { [itemID("Blue d'hide body")]: 1, [itemID("Blue d'hide chaps")]: 1, [itemID("Blue d'hide vambraces")]: 1 }, outputItems: { [itemID('Blue dragonhide set')]: 1 } }, { name: 'Unpack red dragonhide set', inputItems: { [itemID('Red dragonhide set')]: 1 }, outputItems: { [itemID("Red d'hide body")]: 1, [itemID("Red d'hide chaps")]: 1, [itemID("Red d'hide vambraces")]: 1 }, noCl: true }, { name: 'Red dragonhide set', inputItems: { [itemID("Red d'hide body")]: 1, [itemID("Red d'hide chaps")]: 1, [itemID("Red d'hide vambraces")]: 1 }, outputItems: { [itemID('Red dragonhide set')]: 1 } }, { name: 'Unpack black dragonhide set', inputItems: { [itemID('Black dragonhide set')]: 1 }, outputItems: { [itemID("Black d'hide body")]: 1, [itemID("Black d'hide chaps")]: 1, [itemID("Black d'hide vambraces")]: 1 }, noCl: true }, { name: 'Black dragonhide set', inputItems: { [itemID("Black d'hide body")]: 1, [itemID("Black d'hide chaps")]: 1, [itemID("Black d'hide vambraces")]: 1 }, outputItems: { [itemID('Black dragonhide set')]: 1 } }, { name: 'Unpack gilded dragonhide set', inputItems: { [itemID('Gilded dragonhide set')]: 1 }, outputItems: { [itemID("Gilded d'hide body")]: 1, [itemID("Gilded d'hide chaps")]: 1, [itemID("Gilded d'hide vambraces")]: 1 }, noCl: true }, { name: 'Gilded dragonhide set', inputItems: { [itemID("Gilded d'hide body")]: 1, [itemID("Gilded d'hide chaps")]: 1, [itemID("Gilded d'hide vambraces")]: 1 }, outputItems: { [itemID('Gilded dragonhide set')]: 1 } }, // blessed dragonhide { name: 'Unpack guthix dragonhide set', inputItems: { [itemID('Guthix dragonhide set')]: 1 }, outputItems: { [itemID('Guthix coif')]: 1, [itemID("Guthix d'hide body")]: 1, [itemID('Guthix chaps')]: 1, [itemID('Guthix bracers')]: 1 }, noCl: true }, { name: 'Guthix dragonhide set', inputItems: { [itemID('Guthix coif')]: 1, [itemID("Guthix d'hide body")]: 1, [itemID('Guthix chaps')]: 1, [itemID('Guthix bracers')]: 1 }, outputItems: { [itemID('Guthix dragonhide set')]: 1 } }, { name: 'Unpack saradomin dragonhide set', inputItems: { [itemID('Saradomin dragonhide set')]: 1 }, outputItems: { [itemID('Saradomin coif')]: 1, [itemID("Saradomin d'hide body")]: 1, [itemID('Saradomin chaps')]: 1, [itemID('Saradomin bracers')]: 1 }, noCl: true }, { name: 'Saradomin dragonhide set', inputItems: { [itemID('Saradomin coif')]: 1, [itemID("Saradomin d'hide body")]: 1, [itemID('Saradomin chaps')]: 1, [itemID('Saradomin bracers')]: 1 }, outputItems: { [itemID('Saradomin dragonhide set')]: 1 } }, { name: 'Unpack zamorak dragonhide set', inputItems: { [itemID('Zamorak dragonhide set')]: 1 }, outputItems: { [itemID('Zamorak coif')]: 1, [itemID("Zamorak d'hide body")]: 1, [itemID('Zamorak chaps')]: 1, [itemID('Zamorak bracers')]: 1 }, noCl: true }, { name: 'Zamorak dragonhide set', inputItems: { [itemID('Zamorak coif')]: 1, [itemID("Zamorak d'hide body")]: 1, [itemID('Zamorak chaps')]: 1, [itemID('Zamorak bracers')]: 1 }, outputItems: { [itemID('Zamorak dragonhide set')]: 1 } }, { name: 'Unpack ancient dragonhide set', inputItems: { [itemID('Ancient dragonhide set')]: 1 }, outputItems: { [itemID('Ancient coif')]: 1, [itemID("Ancient d'hide body")]: 1, [itemID('Ancient chaps')]: 1, [itemID('Ancient bracers')]: 1 }, noCl: true }, { name: 'Ancient dragonhide set', inputItems: { [itemID('Ancient coif')]: 1, [itemID("Ancient d'hide body")]: 1, [itemID('Ancient chaps')]: 1, [itemID('Ancient bracers')]: 1 }, outputItems: { [itemID('Ancient dragonhide set')]: 1 } }, { name: 'Unpack armadyl dragonhide set', inputItems: { [itemID('Armadyl dragonhide set')]: 1 }, outputItems: { [itemID('Armadyl coif')]: 1, [itemID("Armadyl d'hide body")]: 1, [itemID('Armadyl chaps')]: 1, [itemID('Armadyl bracers')]: 1 }, noCl: true }, { name: 'Armadyl dragonhide set', inputItems: { [itemID('Armadyl coif')]: 1, [itemID("Armadyl d'hide body")]: 1, [itemID('Armadyl chaps')]: 1, [itemID('Armadyl bracers')]: 1 }, outputItems: { [itemID('Armadyl dragonhide set')]: 1 } }, { name: 'Unpack bandos dragonhide set', inputItems: { [itemID('Bandos dragonhide set')]: 1 }, outputItems: { [itemID('Bandos coif')]: 1, [itemID("Bandos d'hide body")]: 1, [itemID('Bandos chaps')]: 1, [itemID('Bandos bracers')]: 1 }, noCl: true }, { name: 'Bandos dragonhide set', inputItems: { [itemID('Bandos coif')]: 1, [itemID("Bandos d'hide body")]: 1, [itemID('Bandos chaps')]: 1, [itemID('Bandos bracers')]: 1 }, outputItems: { [itemID('Bandos dragonhide set')]: 1 } }, // mage sets { name: 'Unpack mystic set (blue)', inputItems: { [itemID('Mystic set (blue)')]: 1 }, outputItems: { [itemID('Mystic hat')]: 1, [itemID('Mystic robe top')]: 1, [itemID('Mystic robe bottom')]: 1, [itemID('Mystic gloves')]: 1, [itemID('Mystic boots')]: 1 }, noCl: true }, { name: 'Mystic set (blue)', inputItems: { [itemID('Mystic hat')]: 1, [itemID('Mystic robe top')]: 1, [itemID('Mystic robe bottom')]: 1, [itemID('Mystic gloves')]: 1, [itemID('Mystic boots')]: 1 }, outputItems: { [itemID('Mystic set (blue)')]: 1 } }, { name: 'Unpack mystic set (dark)', inputItems: { [itemID('Mystic set (dark)')]: 1 }, outputItems: { [itemID('Mystic hat (dark)')]: 1, [itemID('Mystic robe top (dark)')]: 1, [itemID('Mystic robe bottom (dark)')]: 1, [itemID('Mystic gloves (dark)')]: 1, [itemID('Mystic boots (dark)')]: 1 }, noCl: true }, { name: 'Mystic set (dark)', inputItems: { [itemID('Mystic hat (dark)')]: 1, [itemID('Mystic robe top (dark)')]: 1, [itemID('Mystic robe bottom (dark)')]: 1, [itemID('Mystic gloves (dark)')]: 1, [itemID('Mystic boots (dark)')]: 1 }, outputItems: { [itemID('Mystic set (dark)')]: 1 } }, { name: 'Unpack mystic set (light)', inputItems: { [itemID('Mystic set (light)')]: 1 }, outputItems: { [itemID('Mystic hat (light)')]: 1, [itemID('Mystic robe top (light)')]: 1, [itemID('Mystic robe bottom (light)')]: 1, [itemID('Mystic gloves (light)')]: 1, [itemID('Mystic boots (light)')]: 1 }, noCl: true }, { name: 'Mystic set (light)', inputItems: { [itemID('Mystic hat (light)')]: 1, [itemID('Mystic robe top (light)')]: 1, [itemID('Mystic robe bottom (light)')]: 1, [itemID('Mystic gloves (light)')]: 1, [itemID('Mystic boots (light)')]: 1 }, outputItems: { [itemID('Mystic set (light)')]: 1 } }, { name: 'Unpack mystic set (dusk)', inputItems: { [itemID('Mystic set (dusk)')]: 1 }, outputItems: { [itemID('Mystic hat (dusk)')]: 1, [itemID('Mystic robe top (dusk)')]: 1, [itemID('Mystic robe bottom (dusk)')]: 1, [itemID('Mystic gloves (dusk)')]: 1, [itemID('Mystic boots (dusk)')]: 1 }, noCl: true }, { name: 'Mystic set (dusk)', inputItems: { [itemID('Mystic hat (dusk)')]: 1, [itemID('Mystic robe top (dusk)')]: 1, [itemID('Mystic robe bottom (dusk)')]: 1, [itemID('Mystic gloves (dusk)')]: 1, [itemID('Mystic boots (dusk)')]: 1 }, outputItems: { [itemID('Mystic set (dusk)')]: 1 } }, // { // name: "Unpack dagon'hai robes set", // inputItems: { // [itemID("Dagon'hai robes set")]: 1 // }, // outputItems: { // [itemID("Dagon'hai hat")]: 1, // [itemID("Dagon'hai robe top")]: 1, // [itemID("Dagon'hai robe bottom")]: 1 // }, // noCl: true // }, // { // name: "Dagon'hai robes set", // inputItems: { // [itemID("Dagon'hai hat")]: 1, // [itemID("Dagon'hai robe top")]: 1, // [itemID("Dagon'hai robe bottom")]: 1 // }, // outputItems: { // [itemID("Dagon'hai robes set")]: 1 // } // }, { name: 'Unpack ancestral robes set', inputItems: { [itemID('Ancestral robes set')]: 1 }, outputItems: { [itemID('Ancestral hat')]: 1, [itemID('Ancestral robe top')]: 1, [itemID('Ancestral robe bottom')]: 1 }, noCl: true }, { name: 'Ancestral robes set', inputItems: { [itemID('Ancestral hat')]: 1, [itemID('Ancestral robe top')]: 1, [itemID('Ancestral robe bottom')]: 1 }, outputItems: { [itemID('Ancestral robes set')]: 1 } }, // god books { name: 'Unpack book of balance page set', inputItems: { [itemID('Book of balance page set')]: 1 }, outputItems: { [itemID('Guthix page 1')]: 1, [itemID('Guthix page 2')]: 1, [itemID('Guthix page 3')]: 1, [itemID('Guthix page 4')]: 1 }, noCl: true }, { name: 'Book of balance page set', inputItems: { [itemID('Guthix page 1')]: 1, [itemID('Guthix page 2')]: 1, [itemID('Guthix page 3')]: 1, [itemID('Guthix page 4')]: 1 }, outputItems: { [itemID('Book of balance page set')]: 1 } }, { name: 'Unpack holy book page set', inputItems: { [itemID('Holy book page set')]: 1 }, outputItems: { [itemID('Saradomin page 1')]: 1, [itemID('Saradomin page 2')]: 1, [itemID('Saradomin page 3')]: 1, [itemID('Saradomin page 4')]: 1 }, noCl: true }, { name: 'Holy book page set', inputItems: { [itemID('Saradomin page 1')]: 1, [itemID('Saradomin page 2')]: 1, [itemID('Saradomin page 3')]: 1, [itemID('Saradomin page 4')]: 1 }, outputItems: { [itemID('Holy book page set')]: 1 } }, { name: 'Unpack unholy book page set', inputItems: { [itemID('Unholy book page set')]: 1 }, outputItems: { [itemID('Zamorak page 1')]: 1, [itemID('Zamorak page 2')]: 1, [itemID('Zamorak page 3')]: 1, [itemID('Zamorak page 4')]: 1 }, noCl: true }, { name: 'Unholy book page set', inputItems: { [itemID('Zamorak page 1')]: 1, [itemID('Zamorak page 2')]: 1, [itemID('Zamorak page 3')]: 1, [itemID('Zamorak page 4')]: 1 }, outputItems: { [itemID('Unholy book page set')]: 1 } }, { name: 'Unpack book of darkness page set', inputItems: { [itemID('Book of darkness page set')]: 1 }, outputItems: { [itemID('Ancient page 1')]: 1, [itemID('Ancient page 2')]: 1, [itemID('Ancient page 3')]: 1, [itemID('Ancient page 4')]: 1 }, noCl: true }, { name: 'Book of darkness page set', inputItems: { [itemID('Ancient page 1')]: 1, [itemID('Ancient page 2')]: 1, [itemID('Ancient page 3')]: 1, [itemID('Ancient page 4')]: 1 }, outputItems: { [itemID('Book of darkness page set')]: 1 } }, { name: 'Unpack book of law page set', inputItems: { [itemID('Book of law page set')]: 1 }, outputItems: { [itemID('Armadyl page 1')]: 1, [itemID('Armadyl page 2')]: 1, [itemID('Armadyl page 3')]: 1, [itemID('Armadyl page 4')]: 1 }, noCl: true }, { name: 'Book of law page set', inputItems: { [itemID('Armadyl page 1')]: 1, [itemID('Armadyl page 2')]: 1, [itemID('Armadyl page 3')]: 1, [itemID('Armadyl page 4')]: 1 }, outputItems: { [itemID('Book of law page set')]: 1 } }, { name: 'Unpack book of war page set', inputItems: { [itemID('Book of war page set')]: 1 }, outputItems: { [itemID('Bandos page 1')]: 1, [itemID('Bandos page 2')]: 1, [itemID('Bandos page 3')]: 1, [itemID('Bandos page 4')]: 1 }, noCl: true }, { name: 'Book of war page set', inputItems: { [itemID('Bandos page 1')]: 1, [itemID('Bandos page 2')]: 1, [itemID('Bandos page 3')]: 1, [itemID('Bandos page 4')]: 1 }, outputItems: { [itemID('Book of war page set')]: 1 } }, // twisted relichunter // { // name: 'Unpack twisted relichunter (t1) armour set', // inputItems: { // [itemID('Twisted relichunter (t1) armour set')]: 1 // }, // outputItems: { // [itemID('Twisted hat (t1)')]: 1, // [itemID('Twisted coat (t1)')]: 1, // [itemID('Twisted trousers (t1)')]: 1, // [itemID('Twisted boots (t1)')]: 1 // }, // noCl: true // }, // { // name: 'Twisted relichunter (t1) armour set', // inputItems: { // [itemID('Twisted hat (t1)')]: 1, // [itemID('Twisted coat (t1)')]: 1, // [itemID('Twisted trousers (t1)')]: 1, // [itemID('Twisted boots (t1)')]: 1 // }, // outputItems: { // [itemID('Twisted relichunter (t1) armour set')]: 1 // } // }, // { // name: 'Unpack twisted relichunter (t2) armour set', // inputItems: { // [itemID('Twisted relichunter (t2) armour set')]: 1 // }, // outputItems: { // [itemID('Twisted hat (t2)')]: 1, // [itemID('Twisted coat (t2)')]: 1, // [itemID('Twisted trousers (t2)')]: 1, // [itemID('Twisted boots (t2)')]: 1 // }, // noCl: true // }, // { // name: 'Twisted relichunter (t2) armour set', // inputItems: { // [itemID('Twisted hat (t2)')]: 1, // [itemID('Twisted coat (t2)')]: 1, // [itemID('Twisted trousers (t2)')]: 1, // [itemID('Twisted boots (t2)')]: 1 // }, // outputItems: { // [itemID('Twisted relichunter (t2) armour set')]: 1 // } // }, // { // name: 'Unpack twisted relichunter (t3) armour set', // inputItems: { // [itemID('Twisted relichunter (t3) armour set')]: 1 // }, // outputItems: { // [itemID('Twisted hat (t3)')]: 1, // [itemID('Twisted coat (t3)')]: 1, // [itemID('Twisted trousers (t3)')]: 1, // [itemID('Twisted boots (t3)')]: 1 // }, // noCl: true // }, // { // name: 'Twisted relichunter (t3) armour set', // inputItems: { // [itemID('Twisted hat (t3)')]: 1, // [itemID('Twisted coat (t3)')]: 1, // [itemID('Twisted trousers (t3)')]: 1, // [itemID('Twisted boots (t3)')]: 1 // }, // outputItems: { // [itemID('Twisted relichunter (t3) armour set')]: 1 // } // }, // holiday { name: 'Unpack partyhat set', inputItems: { [itemID('Partyhat set')]: 1 }, outputItems: { [itemID('Red partyhat')]: 1, [itemID('Yellow partyhat')]: 1, [itemID('Green partyhat')]: 1, [itemID('Blue partyhat')]: 1, [itemID('Purple partyhat')]: 1, [itemID('White partyhat')]: 1 }, noCl: true }, { name: 'Partyhat set', inputItems: { [itemID('Red partyhat')]: 1, [itemID('Yellow partyhat')]: 1, [itemID('Green partyhat')]: 1, [itemID('Blue partyhat')]: 1, [itemID('Purple partyhat')]: 1, [itemID('White partyhat')]: 1 }, outputItems: { [itemID('Partyhat set')]: 1 } }, { name: 'Unpack halloween mask set', inputItems: { [itemID('Halloween mask set')]: 1 }, outputItems: { [itemID('Red halloween mask')]: 1, [itemID('Green halloween mask')]: 1, [itemID('Blue halloween mask')]: 1 }, noCl: true }, { name: 'Halloween mask set', inputItems: { [itemID('Red halloween mask')]: 1, [itemID('Green halloween mask')]: 1, [itemID('Blue halloween mask')]: 1 }, outputItems: { [itemID('Halloween mask set')]: 1 } }, // misc { name: 'Unpack combat potion set', inputItems: { [itemID('Combat potion set')]: 1 }, outputItems: { [itemID('Attack potion(4)')]: 1, [itemID('Strength potion(4)')]: 1, [itemID('Defence potion(4)')]: 1 }, noCl: true }, { name: 'Combat potion set', inputItems: { [itemID('Attack potion(4)')]: 1, [itemID('Strength potion(4)')]: 1, [itemID('Defence potion(4)')]: 1 }, outputItems: { [itemID('Combat potion set')]: 1 } }, { name: 'Unpack super potion set', inputItems: { [itemID('Super potion set')]: 1 }, outputItems: { [itemID('Super attack(4)')]: 1, [itemID('Super strength(4)')]: 1, [itemID('Super defence(4)')]: 1 }, noCl: true }, { name: 'Super potion set', inputItems: { [itemID('Super attack(4)')]: 1, [itemID('Super strength(4)')]: 1, [itemID('Super defence(4)')]: 1 }, outputItems: { [itemID('Super potion set')]: 1 } }, { name: 'Unpack dwarf cannon set', inputItems: { [itemID('Dwarf cannon set')]: 1 }, outputItems: { [itemID('Cannon barrels')]: 1, [itemID('Cannon base')]: 1, [itemID('Cannon furnace')]: 1, [itemID('Cannon stand')]: 1 }, noCl: true }, { name: 'Dwarf cannon set', inputItems: { [itemID('Cannon barrels')]: 1, [itemID('Cannon base')]: 1, [itemID('Cannon furnace')]: 1, [itemID('Cannon stand')]: 1 }, outputItems: { [itemID('Dwarf cannon set')]: 1 } } ];
the_stack
import React, { PureComponent, FC } from 'react'; import _ from 'lodash' import { UserState } from 'src/store/reducers/user' import { cx, css } from 'emotion'; import { ConfirmButton, ConfirmModal, LegacyInputStatus, Button, stylesFactory, Input, getTheme,RadioButtonGroup } from 'src/packages/datav-core/src/ui'; import {currentTheme,GrafanaTheme} from 'src/packages/datav-core/src' import { Role } from 'src/types'; import { getBackendSrv } from 'src/core/services/backend/backend'; import { notification } from 'antd'; import isEmail from 'validator/lib/isEmail'; import RolePicker from 'src/views/components/Pickers/RolePicker' import { injectIntl,FormattedMessage, IntlShape } from 'react-intl'; interface Props { user: UserState; onUserDelete: any reloadUsers: any } interface IntlProps { intl: IntlShape } interface State { tempUser: UserState; isLoading: boolean; showDeleteModal: boolean; showDisableModal: boolean; } class UserProfile extends PureComponent<Props & IntlProps, State> { state = { isLoading: false, showDeleteModal: false, showDisableModal: false, tempUser: _.cloneDeep(this.props.user) }; showDeleteUserModal = (show: boolean) => () => { this.setState({ showDeleteModal: show }); }; showDisableUserModal = (show: boolean) => () => { this.setState({ showDisableModal: show }); }; onUserDelete = () => { const { user } = this.props; this.props.onUserDelete(user) this.setState({ showDeleteModal: false }) }; onUserDisable = () => { // const { user, onUserDisable } = this.props; // onUserDisable(user.id); }; onUserEnable = () => { // const { user, onUserEnable } = this.props; // onUserEnable(user.id); }; onChangeSetUser = (key,tempUser) => { getBackendSrv().put(`/api/admin/user/${tempUser.id}`,tempUser).then(() => { this.props.reloadUsers() notification['success']({ message: "Success", description: this.props.intl.formatMessage({id: "info.targetUpdated"}), duration: 5 }); }).catch(() => { this.setState({ ...this.state, tempUser: _.cloneDeep(this.props.user) }) }) } onUserNameChange = (name: string) => { const tempUser = { ...this.state.tempUser, name: name } this.setState({ ...this.state, tempUser:tempUser }) this.onChangeSetUser('name',tempUser) }; onUserUsernameChange = (username:string) => { const tempUser = { ...this.state.tempUser, username: username } this.setState({ ...this.state, tempUser:tempUser }) this.onChangeSetUser('username',tempUser) } onUserEmailChange = (email: string) => { if (!isEmail(email)) { notification['error']({ message: "Error", description: this.props.intl.formatMessage({id: "info.emailFormat"}), duration: 5 }); return } const tempUser = { ...this.state.tempUser, email: email } this.setState({ ...this.state, tempUser:tempUser }) this.onChangeSetUser('email',tempUser) }; onRoleChange = (role: string) => { const tempUser = { ...this.state.tempUser, role: role as Role } this.setState({ ...this.state, tempUser:tempUser }) this.onChangeSetUser('role',tempUser) } onPasswordChange = (password: string) => { const {user} = this.props getBackendSrv().put(`/api/admin/password`,{id: user.id.toString(),password: password}).then(() => { this.props.reloadUsers() notification['success']({ message: "Success", description: this.props.intl.formatMessage({id: "info.targetUpdated"}), duration: 5 }); }) }; render() { const { showDeleteModal, showDisableModal,tempUser } = this.state; const styles = getStyles(getTheme(currentTheme)); return ( <> <h3 className="page-heading"><FormattedMessage id="user.information"/></h3> <div className="gf-form-group"> <div className="gf-form"> <table className="filter-table form-inline"> <tbody> <UserProfileRow label="Username" value={tempUser.username} onChange={this.onUserUsernameChange} /> <UserProfileRow label="Name" value={tempUser.name} onChange={this.onUserNameChange} /> <UserProfileRow label="Email" value={tempUser.email} onChange={this.onUserEmailChange} /> <UserProfileRow label="Password" value="********" inputType="password" onChange={this.onPasswordChange} /> </tbody> </table> </div> <div className={styles.buttonRow}> <Button variant="destructive" onClick={this.showDeleteUserModal(true)}> Delete User </Button> <ConfirmModal isOpen={showDeleteModal} title="Delete user" body="Are you sure you want to delete this user?" confirmText="Delete user" onConfirm={this.onUserDelete} onDismiss={this.showDeleteUserModal(false)} /> {tempUser.isDisabled ? ( <Button variant="secondary" onClick={this.onUserEnable}> Enable User </Button> ) : ( <Button variant="secondary" onClick={this.showDisableUserModal(true)}> Disable User </Button> )} <ConfirmModal isOpen={showDisableModal} title="Disable user" body="Are you sure you want to disable this user?" confirmText="Disable user" onConfirm={this.onUserDisable} onDismiss={this.showDisableUserModal(false)} /> </div> </div> <h3 className="page-heading">User Permissions</h3> <div className="gf-form-group"> <div className="gf-form"> <table className="filter-table form-inline"> <tbody> <tr> <td className="width-16" style={{fontWeight: 500}}>Global Role</td> <td className="width-25" colSpan={2}> <RolePicker onChange={this.onRoleChange} value={tempUser.role}/> </td> </tr> </tbody> </table> </div> </div> </> ); } } export default injectIntl(UserProfile) const getStyles = stylesFactory((theme: GrafanaTheme) => { return { buttonRow: css` margin-top: 0.8rem; > * { margin-right: 16px; } `, }; }); interface UserProfileRowProps { label: string; value?: string; locked?: boolean; lockMessage?: string; inputType?: string; onChange?: (value: string) => void; } interface UserProfileRowState { value: string; editing: boolean; } export class UserProfileRow extends PureComponent<UserProfileRowProps, UserProfileRowState> { inputElem: HTMLInputElement; constructor(props) { super(props) this.state = { editing: false, value: this.props.value || '', }; } static defaultProps: Partial<UserProfileRowProps> = { value: '', locked: false, lockMessage: '', inputType: 'text', }; setInputElem = (elem: any) => { this.inputElem = elem; }; onEditClick = () => { if (this.props.inputType === 'password') { // Reset value for password field this.setState({ editing: true, value: '' }, this.focusInput); } else { this.setState({ editing: true }, this.focusInput); } }; onCancelClick = () => { this.setState({ editing: false, value: this.props.value || '' }); }; onInputChange = (event: React.ChangeEvent<HTMLInputElement>, status?: LegacyInputStatus) => { if (status === LegacyInputStatus.Invalid) { return; } this.setState({ value: event.target.value }); }; onInputBlur = (event: React.FocusEvent<HTMLInputElement>, status?: LegacyInputStatus) => { if (status === LegacyInputStatus.Invalid) { return; } this.setState({ value: event.target.value }); }; focusInput = () => { if (this.inputElem && this.inputElem.focus) { this.inputElem.focus(); } }; onSave = () => { if (this.props.onChange) { this.props.onChange(this.state.value); } this.setState({ ...this.state, editing: false, }) }; render() { const { label, locked, lockMessage, inputType } = this.props; const { value } = this.state; const labelClass = cx( 'width-16', css` font-weight: 500; ` ); const editButtonContainerClass = cx('pull-right'); if (locked) { return <LockedRow label={label} value={value} lockMessage={lockMessage} />; } return ( <tr> <td className={labelClass}>{label}</td> <td className="width-25" colSpan={2}> {this.state.editing ? ( <Input type={inputType} defaultValue={value} onBlur={this.onInputBlur} onChange={this.onInputChange} ref={this.setInputElem} width={30} /> ) : ( <span>{this.props.value}</span> )} </td> <td> <div className={editButtonContainerClass}> <ConfirmButton confirmText="Save" onClick={this.onEditClick} onConfirm={this.onSave} onCancel={this.onCancelClick} closeOnConfirm > Edit </ConfirmButton> </div> </td> </tr> ); } } interface LockedRowProps { label: string; value?: any; lockMessage?: string; } export const LockedRow: FC<LockedRowProps> = ({ label, value, lockMessage }) => { const lockMessageClass = cx( 'pull-right', css` font-style: italic; margin-right: 0.6rem; ` ); const labelClass = cx( 'width-16', css` font-weight: 500; ` ); return ( <tr> <td className={labelClass}>{label}</td> <td className="width-25" colSpan={2}> {value} </td> <td> <span className={lockMessageClass}>{lockMessage}</span> </td> </tr> ); };
the_stack
import { UNMOUNT_TOKEN, dirtyCheckWatchList, saveObservableDependencies, assign, enableWatch, disableWatch, } from "../core"; import { doc, objectHasOwnProperty, nodeInsertBefore, nodeRemoveChild, elementSetAttribute, nodeCloneNode, elementRemoveAttribute, elementSetClassName, htmlElementGetStyle, svgElementGetStyle, } from "../dom/shortcuts"; import { SVG_NAMESPACE } from "../dom/namespaces"; import { CSSStyleProps } from "../dom/style"; import { NodeFlags } from "./node_flags"; import { AttributeDirective } from "./attribute_directive"; import { OpNode, DOMElementOp, EventsOp, ContextOp, TrackByKeyOp, ComponentOp, OpArray, Key, Op } from "./operations"; import { OpState } from "./state"; import { ElementProtoDescriptor } from "./element_proto"; import { ComponentDescriptor, ComponentState } from "./component"; import { setContext, pushContext, ContextDescriptor, ContextState } from "./context"; const enum MagicValues { /** * One of the children nodes were moved. */ MovedChildren = 99999999, /** * New node marker. */ NewNodeMark = -1, /** * LIS marker. */ LISMark = -2, } /** * Simple workaround that efficiently solves a lot of issues with fragments, nested `TrackByKey` ops and holes * (`null` ops). * * Reconciler always goes through the tree from right to left and updates `_nextNode` value when it goes through nodes * associated with DOM nodes, so when we need to insert a new DOM node, we can take it from this variable instead of * recursively looking for a next DOM node. */ let _nextNode!: Node | null; /** * _resetState resets global reconciler state. */ export function _resetState(): void { _nextNode = null; } /** * VisitNodesDirective controls the traversal algorithm {@link visitNodes}`. */ export const enum VisitNodesDirective { /** * Continue traversing the tree. */ Continue = 0, /** * Stops immediately. */ StopImmediate = 1, /** * Stops traversing through children nodes and continues trversing through adjacent nodes. */ Stop = 1 << 1, } /** * visitNodes traverses the operation state tree and invokes `visitor` function for each state node. * * @param opState State node. * @param visitor Visitor function. * @returns {@link VisitNodesDirective} */ export function visitNodes(opState: OpState, visitor: (opState: OpState) => VisitNodesDirective): VisitNodesDirective; export function visitNodes( opState: OpState | null, visitor: (opState: OpState) => VisitNodesDirective, ): VisitNodesDirective { let i = visitor(opState!); if (i !== VisitNodesDirective.Continue) { return (i & VisitNodesDirective.StopImmediate); } const { f, c } = opState!; if ((f & (NodeFlags.Fragment | NodeFlags.TrackByKey)) !== 0) { for (i = 0; i < (c as Array<OpState | null>).length; i++) { if ( (opState = (c as Array<OpState | null>)[i]) !== null && (visitNodes(opState, visitor) & VisitNodesDirective.StopImmediate) !== 0 ) { return VisitNodesDirective.StopImmediate; } } } else if (c !== null) { return visitNodes(c as OpState, visitor); } return VisitNodesDirective.Continue; } /** * getDOMNode retrieves closest DOM node from the {@link OpState} instance. * * @typeparam T DOM node type. * @param opState State node. * @returns DOM node. */ export function getDOMNode<T extends Node>(opState: OpState | null): T | null; export function getDOMNode<T extends Node>(opState: OpState | Array<OpState | null> | null): T | null { if (opState === null) { return null; } let i = (opState as OpState).f; let c: OpState | Node | null; if ((i & (NodeFlags.Element | NodeFlags.Text)) === 0) { opState = (opState as OpState).c; if ((i & (NodeFlags.Fragment | NodeFlags.TrackByKey)) !== 0) { for (i = 0; i < (opState as Array<OpState | null>).length; i++) { if ((c = getDOMNode((opState as Array<OpState | null>)[i])) !== null) { return c as T; } } return null; } return getDOMNode(opState as OpState); } return (opState as OpState).s as T; } export function _dirtyCheck( parentElement: Element, opState: OpState, moveNode: boolean, ): void { const flags = opState.f; const c = opState.c; let state; let i; let r; if ((flags & (NodeFlags.Element | NodeFlags.Text)) !== 0) { state = opState.s as Node; if (moveNode === true) { nodeInsertBefore!.call(parentElement, state, _nextNode); } if (c !== null) { _nextNode = null; _dirtyCheck(state as Element, c as OpState, false); } _nextNode = state; } else if ((flags & NodeFlags.Component) !== 0) { state = opState.s as ComponentState; if ( ((flags & NodeFlags.Dirty) !== 0) || (state.d !== null && dirtyCheckWatchList(state.d) === true) ) { r = opState.o as ComponentOp; /* istanbul ignore else */ if (process.env.NODE_ENV !== "production") { enableWatch(); } r = state.r!(r.v, r.c); /* istanbul ignore else */ if (process.env.NODE_ENV !== "production") { disableWatch(); } state.d = saveObservableDependencies(); opState.c = _update( parentElement, c as OpState | null, r, moveNode, ); } else if (c !== null) { _dirtyCheck(parentElement, c as OpState, moveNode); } } else if ((flags & (NodeFlags.Fragment | NodeFlags.TrackByKey)) !== 0) { i = (c as Array<OpState | null>).length; while (i > 0) { if ((state = (c as Array<OpState | null>)[--i]) !== null) { _dirtyCheck(parentElement, state, moveNode); } } } else if ((flags & NodeFlags.Events) !== 0) { _dirtyCheck(parentElement, c as OpState, moveNode); } else { // ((f & NodeFlags.Context) !== 0) state = setContext(opState.s); _dirtyCheck(parentElement, c as OpState, moveNode); setContext(state); } } function _unmountWalk(opState: OpState): void { const flags = opState.f; let children; let i; let v; if ((children = opState.c) !== null) { if ((flags & (NodeFlags.Fragment | NodeFlags.TrackByKey)) !== 0) { for (i = 0; i < (children as Array<OpState | null>).length; i++) { if ((v = (children as Array<OpState | null>)[i]) !== null) { _unmountWalk(v); } } } else { _unmountWalk(children as OpState); } } if ((flags & NodeFlags.Component) !== 0) { if ((v = (opState.s as ComponentState).u) !== null) { if (typeof v === "function") { v(UNMOUNT_TOKEN); } else { for (i = 0; i < v.length; i++) { v[i](UNMOUNT_TOKEN); } } } } } function _unmountRemove(parentElement: Element, opState: OpState): void; function _unmountRemove( parentElement: Element, opState: OpState | Array<OpState | null> | null, ): void { let i = (opState as OpState).f; let c; if ((i & (NodeFlags.Element | NodeFlags.Text)) !== 0) { nodeRemoveChild!.call(parentElement, (opState as OpState).s as Node); } else { opState = (opState as OpState).c; if ((i & (NodeFlags.TrackByKey | NodeFlags.Fragment)) !== 0) { for (i = 0; i < (opState as Array<OpState | null>).length; ++i) { if ((c = (opState as Array<OpState | null>)[i]) !== null) { _unmountRemove(parentElement, c); } } } else if (opState !== null) { _unmountRemove(parentElement, opState as OpState); } } } export function _unmount(parentElement: Element, opState: OpState): void { _unmountRemove(parentElement, opState); _unmountWalk(opState); } function _mountText(parentElement: Element, o: string | number): OpState { const s = doc.createTextNode(o as string); nodeInsertBefore!.call(parentElement, s, _nextNode); _nextNode = s; return { f: NodeFlags.Text, o, c: null, s }; } function _createElement(node: Element | undefined, op: DOMElementOp): Element { const { t, v, n } = op; const svg = (t.f & NodeFlags.Svg) !== 0; if (node === void 0) { const tagName = t.d as string; node = svg ? doc.createElementNS(SVG_NAMESPACE, tagName) : doc.createElement(tagName); } if (n) { _updateClassName(node, n, svg); } if (v !== void 0) { _updateAttrs(node, void 0, v, svg); } return node; } function _mountObject( parentElement: Element, o: OpNode, ): OpState { const opType = o.t; // polymorphic callsite const f = opType.f; const opState = { f, o, c: null, s: null } as OpState; let prevState; let value; let node; let i; if ((f & NodeFlags.Component) !== 0) { opState.s = prevState = { r: null, d: null, u: null } as ComponentState; // Reusing value variable. prevState.r = value = (opType.d as ComponentDescriptor).c(opState); /* istanbul ignore else */ if (process.env.NODE_ENV !== "production") { enableWatch(); } node = value((o as ComponentOp).v, (o as ComponentOp).c); /* istanbul ignore else */ if (process.env.NODE_ENV !== "production") { disableWatch(); } prevState.d = saveObservableDependencies(); opState.c = _mount(parentElement, node); } else { if ((f & NodeFlags.Element) !== 0) { value = opType.d; if ((f & NodeFlags.ElementProto) !== 0) { node = (value as ElementProtoDescriptor).n as Element; if (node === null) { (value as ElementProtoDescriptor).n = node = _createElement( void 0, (value as ElementProtoDescriptor).p, ); } node = nodeCloneNode!.call(node, false) as Element; } opState.s = node = _createElement(node, o as DOMElementOp); prevState = _nextNode; if ((value = (o as DOMElementOp).c) !== null) { _nextNode = null; opState.c = _mount(node, value); } _nextNode = node; nodeInsertBefore!.call(parentElement, node, prevState); } else if ((f & (NodeFlags.Events | NodeFlags.Context)) !== 0) { if ((f & NodeFlags.Context) !== 0) { opState.s = prevState = ((f & NodeFlags.SetContextState) !== 0) ? setContext((o as ContextOp).v) : pushContext(opType.d as ContextDescriptor, (o as ContextOp).v); opState.c = _mount(parentElement, (o as ContextOp).c); setContext(prevState); } else { opState.c = _mount(parentElement, (o as EventsOp).c); } } else { // ((opFlags & NodeFlags.TrackByKey) !== 0) node = (o as TrackByKeyOp).v; i = node.length; opState.c = value = Array(i); while (i > 0) { value[--i] = _mount(parentElement, node[i].v); } } } return opState; } function _mountFragment(parentElement: Element, o: OpArray): OpState { let i = o.length; const c = Array(i); while (i > 0) { c[--i] = _mount(parentElement, o[i]); } return { f: NodeFlags.Fragment, o, c, s: null }; } export function _mount( parentElement: Element, op: Op, ): OpState | null { return (op !== null) ? ( (typeof op === "object") ? ( (op instanceof Array) ? _mountFragment(parentElement, op) : _mountObject(parentElement, op) ) : _mountText(parentElement, op) ) : null; } /** * _update updates a stateNode with a next operation. * * @param parentElement Parent DOM Element. * @param opState Operation state. * @param nextOp Next operation. * @param moveNode DOM Element should be moved. * @returns OpNode state. */ export function _update( parentElement: Element, opState: OpState | null, nextOp: Op, moveNode: boolean, ): OpState | null { if (nextOp === null) { if (opState !== null) { _unmount(parentElement, opState); } return null; } if (opState === null) { return _mount(parentElement, nextOp); } const { f, o, s } = opState; if ((f & NodeFlags.Text) !== 0) { if (typeof nextOp !== "object") { // Reassign to reduce memory consumption even if nextOp is strictly equal to the prev op. opState.o = nextOp; if (o !== nextOp) { (s as Node).nodeValue = nextOp as string; } if (moveNode === true) { nodeInsertBefore!.call(parentElement, s as Node, _nextNode); } _nextNode = s as Node; } else { nodeRemoveChild!.call(parentElement, s as Node); return _mount(parentElement, nextOp); } } else { // Here we don't need to reassign nextOp because op should always be an object, and strict equality will guarantee // that this object is occupying the same memory region. if (o === nextOp) { _dirtyCheck(parentElement, opState, moveNode); return opState; } if ( ((f & NodeFlags.Fragment) !== 0 ? !(nextOp instanceof Array) : ( nextOp instanceof Array || (o as OpNode).t !== (nextOp as OpNode).t // polymorphic callsites ) ) ) { _unmount(parentElement, opState); return _mount(parentElement, nextOp); } opState.o = nextOp; const opStateChildren = opState.c; let prevData1; let nextData1; let prevData2; let nextData2; let nextValue; let i; if ((f & NodeFlags.Component) !== 0) { prevData1 = (o as ComponentOp).v; prevData2 = (o as ComponentOp).c; nextData1 = (nextOp as ComponentOp).v; nextData2 = (nextOp as ComponentOp).c; nextValue = (nextOp as ComponentOp).t.d as ComponentDescriptor; // Prioritize checking 2nd property as it is most likely will be used to pass children nodes or custom render // function, so it won't have any complex `areEqual` checking. if ( ( (prevData2 !== nextData2) && (nextValue.e2 === void 0 || nextValue.e2(prevData2, nextData2) !== true) ) || ( (prevData1 !== nextData1) && (nextValue.e1 === void 0 || nextValue.e1(prevData1, nextData1) !== true) ) ) { /* istanbul ignore else */ if (process.env.NODE_ENV !== "production") { enableWatch(); } nextData1 = (s as ComponentState).r!(nextData1, nextData2); /* istanbul ignore else */ if (process.env.NODE_ENV !== "production") { disableWatch(); } (s as ComponentState).d = saveObservableDependencies(); opState.c = _update( parentElement, opStateChildren as OpState, nextData1, moveNode, ); } else { _dirtyCheck(parentElement, opState, moveNode); } } else { if ((f & NodeFlags.Element) !== 0) { i = (f & NodeFlags.Svg) !== 0; if ((o as DOMElementOp).n !== (nextValue = (nextOp as DOMElementOp).n)) { if (nextValue === void 0) { nextValue = ""; } _updateClassName(s as Element, nextValue, i); } if ((o as DOMElementOp).v !== (nextValue = (nextOp as DOMElementOp).v)) { _updateAttrs(s as Element, (o as DOMElementOp).v, nextValue, i); } if (moveNode === true) { nodeInsertBefore!.call(parentElement, s as Element, _nextNode); } _nextNode = null; opState.c = _update(s as Element, opStateChildren as OpState, (nextOp as DOMElementOp).c, false); _nextNode = s as Node; } else if ((f & (NodeFlags.Fragment | NodeFlags.TrackByKey)) !== 0) { if ((f & NodeFlags.Fragment) !== 0) { i = (nextOp as OpArray).length; if (i === 0) { _unmount(parentElement, opState); } else { prevData1 = (opStateChildren as Array<OpState | null>).length; if (i !== prevData1) { opState.c = nextValue = Array(i); while (prevData1 > i) { nextData1 = (opStateChildren as Array<OpState | null>)[--prevData1]; if (nextData1 !== null) { _unmount(parentElement, nextData1); } } while (i > prevData1) { nextValue[--i] = _mount(parentElement, (nextOp as OpArray)[i]); } } else { nextValue = (opStateChildren as Array<OpState | null>); } while (i > 0) { nextValue[--i] = _update( parentElement, (opStateChildren as Array<OpState | null>)[i], (nextOp as OpArray)[i], moveNode, ); } } } else { _updateChildrenTrackByKeys( parentElement, opState, (o as TrackByKeyOp).v, (nextOp as TrackByKeyOp).v, moveNode, ); } } else if ((f & NodeFlags.Events) !== 0) { opState.c = _update( parentElement, opStateChildren as OpState, (nextOp as EventsOp).c, moveNode, ); } else { // if ((flags & NodeFlags.Context) !== 0) { nextData1 = (nextOp as ContextOp).v; if ((f & NodeFlags.SetContextState) !== 0) { opState.s = nextData1; } else { nextValue = (s as ContextState).v; if (nextValue.v !== nextData1) { assign(nextValue, nextData1); } } nextValue = setContext(opState.s); opState.c = _update( parentElement, opStateChildren as OpState, (nextOp as ContextOp).c, moveNode, ); setContext(nextValue); } } } return opState; } /** * Update children list with track by key algorithm. * * High-level overview of the algorithm that is implemented in this function. * * This algorithm finds a minimum[1] number of DOM operations. It works in several steps: * * 1. Common prefix and suffix optimization. * * This optimization technique is looking for nodes with identical keys by simultaneously iterating through nodes in the * old children list `A` and new children list `B` from both sides. * * A: -> [a b c d] <- * B: -> [a b d] <- * * Skip nodes "a" and "b" at the start, and node "d" at the end. * * A: -> [c] <- * B: -> [] <- * * 2. Zero length optimizations. * * Check if the size of one of the list is equal to zero. When length of the old children list is zero, insert remaining * nodes from the new list. When length of the new children list is zero, remove remaining nodes from the old list. * * A: -> [a b c g] <- * B: -> [a g] <- * * Skip nodes "a" and "g" (prefix and suffix optimization). * * A: [b c] * B: [] * * Remove nodes "b" and "c". * * 3. Index and unmount removed nodes. * * A: [b c d e f] * B: [c b h f e] * P: [. . . . .] // . == -1 * * Create array `P` (`sources` variable) with the length of the new children list and fill it with `-1` values * (`MagicValue.NewNodeMark` constant). `-1` value indicates that node at this position should be mounted. Later we will * assign node positions in the old children list to this array. * * A: [b c d e f] * B: [c b h f e] * P: [. . . . .] // . == -1 * I: { * c: 0, // B[0] == c * b: 1, // B[1] == b * h: 2, * f: 3, * e: 4, * } * last = 0 * * Create reverse index `I` that maps keys to node positions in the new children list. * * A: [b c d e f] * ^ * B: [c b h f e] * P: [. 0 . . .] // . == -1 * I: { * c: 0, * b: 1, <- * h: 2, * f: 3, * e: 4, * } * last = 1 * * Assign original positions of the nodes from the old children list to the array `P`. * * Iterate through nodes in the old children list and get their new positions from the index `I`. Assign old node * position to the array `P`. When index `I` doesn't have a key for the old node, it means that it should be unmounted. * * When we assigning positions to the array `P`, we also store a position of the last seen node in the new children * list (`pos` variable), if the last seen position is greater than current position of the node at the new list, then * we are switching `moved` flag to `true` (`pos === MagicValue.MovedChildren`). * * A: [b c d e f] * ^ * B: [c b h f e] * P: [1 0 . . .] // . == -1 * I: { * c: 0, <- * b: 1, * h: 2, * f: 3, * e: 4, * } * last = 1 // last > 0; moved = true * * The last position `1` is greater than current position of the node at the new list `0`, switch `moved` flag to * `true`. * * A: [b c d e f] * ^ * B: [c b h f e] * P: [1 0 . . .] // . == -1 * I: { * c: 0, * b: 1, * h: 2, * f: 3, * e: 4, * } * moved = true * * Node with key "d" doesn't exist in the index `I`, unmount node `d`. * * A: [b c d e f] * ^ * B: [c b h f e] * P: [1 0 . . 3] // . == -1 * I: { * c: 0, * b: 1, * h: 2, * f: 3, * e: 4, <- * } * moved = true * * Assign position `3` for `e` node. * * A: [b c d e f] * ^ * B: [c b h f e] * P: [1 0 . 4 3] // . == -1 * I: { * c: 0, * b: 1, * h: 2, * f: 3, <- * e: 4, * } * moved = true * * Assign position `4` for 'f' node. * * 4. Find minimum number of moves when `moved` flag is on and mount new nodes. * * A: [b c d e f] * B: [c b h f e] * P: [1 * . 4 *] // . == -1 * == -2 * * When `moved` is on, mark all nodes in the array `P` that belong to the * [longest increasing subsequence](http://en.wikipedia.org/wiki/Longest_increasing_subsequence) and move all nodes that * doesn't belong to this subsequence. * * Iterate over the new children list and the `P` array simultaneously. When value from `P` array is equal to `-1`, * mount a new node. When it isn't equal to `-2`, move it. * * A: [b c d e f] * B: [c b h f e] * ^ // new_pos == 4 * P: [1 * . 4 *] // . == -1 * == -2 * ^ * * Node "e" has `-2` value in the array `P`, nothing changes. * * A: [b c d e f] * B: [c b h f e] * ^ // new_pos == 3 * P: [1 * . 4 *] // . == -1 * == -2 * ^ * * Node "f" has `4` value in the array `P`, move it before the next node "e". * * A: [b c d e f] * B: [c b h f e] * ^ // new_pos == 2 * P: [1 * . 4 *] // . == -1 * == -2 * ^ * * Node "h" has `-1` value in the array `P`, mount new node "h". * * A: [b c d e f] * B: [c b h f e] * ^ // new_pos == 1 * P: [1 * . 4 *] // . == -1 * == -2 * ^ * * Node "b" has `-2` value in the array `P`, nothing changes. * * A: [b c d e f] * B: [c b h f e] * ^ // new_pos == 0 * P: [1 * . 4 *] // . == -1 * == -2 * * Node "c" has `1` value in the array `P`, move it before the next node "b". * * When `moved` flag is off, skip LIS algorithm and mount nodes that have `-1` value in the array `P`. * * [1] Actually it is almost minimum number of dom ops, when node is removed and another one is inserted at the same * place, instead of insert and remove dom ops, we can use one replace op. It will make everything even more * complicated, and other use cases will be slower, so I don't think that it is worth to use replace here. * * NOTE: There are many variations of this algorithm that are used by many UI libraries and many implementations are * still using an old optimization technique that were removed several years ago from this implementation. This * optimization were used to improve performance of simple moves/swaps. For example: * * A: -> [a b c] <- * B: -> [c b a] <- * * Move "a" and "c" nodes to the other edge. * * A: -> [b] <- * B: -> [b] <- * * Skip node "b". * * This optimization were removed because it breaks the promise that insert and remove operations shouldn't trigger a * move operation. For example: * * A: -> [a b] * B: [c a] <- * * Move node "a" to the end. * * A: [b] * B: [c] * * Remove node "b" and insert node "c". * * In this use case, this optimization performs one unnecessary operation. Instead of removing node "b" and inserting * node "c", it also moves node `a`. * * @param parentElement Parent DOM element. * @param opState OpNode state for a TrackByKey operation. * @param a Previous operations. * @param b Next operations. * @param moveNode Children DOM nodes should be moved. * @noinline * @__NOINLINE__ */ function _updateChildrenTrackByKeys( parentElement: Element, opState: OpState, a: Key<any, OpNode>[], b: Key<any, OpNode>[], moveNode: boolean, ): void { let i = b.length; let j: number | undefined = a.length; let result = Array(i); if (i === 0) { // New children list is empty. if (j > 0) { // Unmount nodes from the old children list. _unmount(parentElement, opState); } } else if (j === 0) { // Old children list is empty. while (i > 0) { // Mount nodes from the new children list. result[--i] = _mount(parentElement, b[i].v); } } else { let opStateChildren = opState.c as Array<OpState | null>; let aEnd = j - 1; // a.length - 1 let bEnd = i - 1; // b.length - 1 let start = 0; let node: OpNode | Key<any, OpNode> | OpState | null = b[bEnd]; // Step 1 outer: while (true) { // Update nodes with the same key at the end. while (a[aEnd].k === node.k) { result[bEnd] = _update(parentElement, opStateChildren[aEnd--], node.v, moveNode); if (start > --bEnd || start > aEnd) { break outer; } node = b[bEnd]; } // Update nodes with the same key at the beginning. while (a[start].k === b[start].k && ++start <= aEnd && start <= bEnd) { // delayed update (all updates should be performed from right-to-left). } break; } // Step 2 if (start > aEnd) { // All nodes from `a` are updated, insert the rest from `b`. while (bEnd >= start) { result[bEnd] = _mount(parentElement, b[bEnd--].v); } } else if (start > bEnd) { // All nodes from `b` are updated, remove the rest from `a`. i = start; do { if ((node = opStateChildren[i++]) !== null) { _unmount(parentElement, node); } } while (i <= aEnd); } else { // Step 3 // When `pos === 99999999`, it means that one of the nodes is in the wrong position and we should rearrange nodes // with LIS-based algorithm `markLIS()`. let pos = 0; let bLength = bEnd - start + 1; let sources = new Int32Array(bLength); // Maps positions in the new children list to positions in the old list. let keyIndex = new Map<any, number>(); // Maps keys to their positions in the new children list. for (i = 0; i < bLength; ++i) { j = i + start; // `NewNodeMark` value indicates that node doesn't exist in the old children list. sources[i] = MagicValues.NewNodeMark; keyIndex.set(b[j].k, j); } for (i = start; i <= aEnd; ++i) { j = keyIndex.get(a[i].k); node = opStateChildren[i]; if (j !== void 0) { pos = (pos < j) ? j : MagicValues.MovedChildren; sources[j - start] = i; result[j] = node; } else if (node !== null) { _unmount(parentElement, node); } } // Step 4 // Mark LIS nodes only when this node weren't moved `moveNode === false` and we've detected that one of the // children nodes were moved `pos === MagicValues.MovedChildren`. if (moveNode === false && pos === MagicValues.MovedChildren) { markLIS(sources); } while (bLength-- > 0) { bEnd = bLength + start; node = b[bEnd].v; j = sources[bLength]; result[bEnd] = (j === -1) ? _mount(parentElement, node) : _update( parentElement, result[bEnd], node, moveNode || (pos === MagicValues.MovedChildren && j !== MagicValues.LISMark), ); } } // Delayed update for nodes from Step 1 (prefix only). Reconciliation algorithm always updates nodes from right to // left. while (start > 0) { result[--start] = _update(parentElement, opStateChildren[start], b[start].v, moveNode); } } opState.c = result; } /** * Modified Longest Increased Subsequence algorithm. * * Mutates input array `a` and replaces all values that are part of LIS with -2 value. * * Constraints: * - Doesn't work with negative numbers. -1 values are ignored. * - Input array `a` should contain at least one value that is greater than -1. * * {@link http://en.wikipedia.org/wiki/Longest_increasing_subsequence} * * @example * * const A = Int32Array.from([-1, 0, 2, 1]); * markLIS(A); * // A => [-1, -2, 2, -2] * * @param a Array of numbers. * @noinline * @__NOINLINE__ */ function markLIS(a: Int32Array): void { let length = a.length; let parent = new Int32Array(length); let index = new Int32Array(length); let indexLength = 0; let i = 0; let j: number; let k: number; let lo: number; let hi: number; // Skip -1 values at the start of the input array `a`. for (; a[i] === MagicValues.NewNodeMark; ++i) { /**/ } index[0] = i++; for (; i < length; ++i) { k = a[i]; if (k !== MagicValues.NewNodeMark) { // Ignore -1 values. j = index[indexLength]; if (a[j] < k) { parent[i] = j; index[++indexLength] = i; } else { lo = 0; hi = indexLength; while (lo < hi) { j = (lo + hi) >> 1; if (a[index[j]] < k) { lo = j + 1; } else { hi = j; } } if (k < a[index[lo]]) { if (lo > 0) { parent[i] = index[lo - 1]; } index[lo] = i; } } } } // Mutate input array `a` and assign -2 value to all nodes that are part of LIS. j = index[indexLength]; while (indexLength-- >= 0) { a[j] = MagicValues.LISMark; j = parent[j]; } } /** * Update DOM classname. * * @param element DOM Element. * @param className Class name. * @param svg SVG Element. */ function _updateClassName(element: Element, className: string, svg: boolean): void { /** * SVGElement.className returns `SVGAnimatedString`. * * #quirks */ if (svg === true) { elementSetAttribute!.call(element, "class", className); } else { elementSetClassName!.call((element as HTMLElement), className); } } /** * Update DOM styles. * * @param element HTML or SVG Element. * @param a Prev styles. * @param b Next styles. * @param svg SVG element. */ function _updateStyle( element: HTMLElement | SVGElement, a: Record<string, string> | undefined, b: Record<string, string> | undefined, svg: boolean, ): void { const style = svg === true ? svgElementGetStyle!.call(element) : htmlElementGetStyle!.call(element); let key: string; let bValue; if (a === void 0) { // a is empty, insert all styles from b. for (key in b!) { bValue = b![key]; if (bValue !== void 0) { style.setProperty(key, bValue); } } } else if (b === void 0) { // b is empty, remove all styles from a for (key in a) { if (a[key] !== void 0) { style.removeProperty(key); } } } else { let matchCount = 0; let i = 0; for (key in a) { const aValue = a[key]; bValue = (objectHasOwnProperty.call(b, key) === true) ? (matchCount++, b[key]) : void 0; if (aValue !== bValue) { if (bValue !== void 0) { style.setProperty(key, bValue); } else { style.removeProperty(key); } } } const keys = Object.keys(b); for (; matchCount < keys.length && i < keys.length; ++i) { key = keys[i]; if (objectHasOwnProperty.call(a, key) === false) { bValue = b[key]; ++matchCount; if (bValue !== void 0) { style.setProperty(key, b[key]); } } } } } /** * Update DOM attributes. * * @param element DOM element. * @param a Prev DOM attributes. * @param b Next DOM attributes. * @param svg SVG element. */ function _updateAttrs( element: Element, a: Record<string, string | number | AttributeDirective<any> | CSSStyleProps | undefined> | undefined, b: Record<string, string | number | AttributeDirective<any> | CSSStyleProps | undefined> | undefined, svg: boolean, ): void { let key: string; if (a === void 0) { // a is empty, insert all attributes from b. for (key in b!) { _updateAttr(element, key, void 0, b![key], svg); } } else if (b === void 0) { // b is empty, remove all attributes from a. for (key in a) { _updateAttr(element, key, a[key], void 0, svg); } } else { let matchCount = 0; let i = 0; for (key in a) { _updateAttr( element, key, a[key], (objectHasOwnProperty.call(b, key) === true) ? (matchCount++, b[key]) : void 0, svg, ); } const keys = Object.keys(b); for (; matchCount < keys.length && i < keys.length; ++i) { key = keys[i]; if (objectHasOwnProperty.call(a, key) === false) { _updateAttr(element, key, void 0, b[key], svg); ++matchCount; } } } } /** * Update DOM attribute. * * @param element DOM Element. * @param key Attribute name. * @param prev Previous value. * @param next Next value. * @param svg SVG element. */ function _updateAttr( element: Element, key: string, prev: string | number | AttributeDirective<any> | CSSStyleProps | undefined, next: string | number | AttributeDirective<any> | CSSStyleProps | undefined, svg: boolean, ): void { if (key !== "style") { if (typeof next === "object") { /* istanbul ignore else */ if (process.env.NODE_ENV !== "production") { if (typeof prev !== "object" && prev !== void 0) { throw new Error( `Invalid DOM attribute, transitioning from basic values to attribute directives isn't allowed`, ); } } (next as AttributeDirective<any>).u!( element, key, prev === void 0 ? void 0 : (prev as AttributeDirective<any>).v, next.v, ); } else if (typeof prev === "object") { /* istanbul ignore else */ if (process.env.NODE_ENV !== "production") { if (typeof next !== "object" && next !== void 0) { throw new Error( `Invalid DOM attribute, transitioning from attribute directives to basic values isn't allowed`, ); } } (prev as AttributeDirective<any>).u!( element, key, (prev as AttributeDirective<any>).v, void 0, ); } else if (prev !== next) { if (next === void 0) { elementRemoveAttribute!.call(element, key); } else { elementSetAttribute!.call(element, key, next as string); } } } else if (prev !== next) { _updateStyle(element as HTMLElement, prev as CSSStyleProps, next as CSSStyleProps, svg); } }
the_stack
const ArrayPrototypePush = Array.prototype.push; const IntlDateTimeFormat = globalThis.Intl.DateTimeFormat; const MathMin = Math.min; const MathMax = Math.max; const MathAbs = Math.abs; const MathFloor = Math.floor; const MathSign = Math.sign; const MathTrunc = Math.trunc; const NumberIsNaN = Number.isNaN; const NumberIsFinite = Number.isFinite; const NumberCtor = Number; const StringCtor = String; const NumberMaxSafeInteger = Number.MAX_SAFE_INTEGER; const ObjectCreate = Object.create; const ObjectDefineProperty = Object.defineProperty; const ObjectIs = Object.is; const ReflectApply = Reflect.apply; import { DEBUG } from './debug'; import JSBI from 'jsbi'; import type { Temporal } from '..'; import type { AnyTemporalLikeType, PrimitivePropertyNames, UnitSmallerThanOrEqualTo, CalendarProtocolParams, TimeZoneProtocolParams, InstantParams, PlainMonthDayParams, ZonedDateTimeParams, CalendarParams, TimeZoneParams, PlainDateParams, PlainTimeParams, DurationParams, PlainDateTimeParams, PlainYearMonthParams, FieldRecord } from './internaltypes'; import { GetIntrinsic } from './intrinsicclass'; import { CreateSlots, GetSlot, HasSlot, SetSlot, EPOCHNANOSECONDS, TIMEZONE_ID, CALENDAR_ID, INSTANT, ISO_YEAR, ISO_MONTH, ISO_DAY, ISO_HOUR, ISO_MINUTE, ISO_SECOND, ISO_MILLISECOND, ISO_MICROSECOND, ISO_NANOSECOND, DATE_BRAND, YEAR_MONTH_BRAND, MONTH_DAY_BRAND, TIME_ZONE, CALENDAR, YEARS, MONTHS, WEEKS, DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS } from './slots'; import { IsBuiltinCalendar } from './calendar'; export const ZERO = JSBI.BigInt(0); const ONE = JSBI.BigInt(1); const SIXTY = JSBI.BigInt(60); export const THOUSAND = JSBI.BigInt(1e3); export const MILLION = JSBI.BigInt(1e6); export const BILLION = JSBI.BigInt(1e9); const NEGATIVE_ONE = JSBI.BigInt(-1); const DAY_SECONDS = 86400; const DAY_NANOS = JSBI.multiply(JSBI.BigInt(DAY_SECONDS), BILLION); const NS_MIN = JSBI.multiply(JSBI.BigInt(-86400), JSBI.BigInt(1e17)); const NS_MAX = JSBI.multiply(JSBI.BigInt(86400), JSBI.BigInt(1e17)); const YEAR_MIN = -271821; const YEAR_MAX = 275760; const BEFORE_FIRST_DST = JSBI.multiply(JSBI.BigInt(-388152), JSBI.BigInt(1e13)); // 1847-01-01T00:00:00Z function IsInteger(value: unknown): value is number { if (typeof value !== 'number' || !NumberIsFinite(value)) return false; const abs = MathAbs(value); return MathFloor(abs) === abs; } // For unknown values, this narrows the result to a Record. But for union types // like `Temporal.DurationLike | string`, it'll strip the primitive types while // leaving the object type(s) unchanged. export function IsObject<T>( value: T ): value is Exclude<T, string | null | undefined | number | bigint | symbol | boolean>; export function IsObject(value: unknown): value is Record<string | number | symbol, unknown> { return (typeof value === 'object' && value !== null) || typeof value === 'function'; } export function ToNumber(value: unknown): number { if (typeof value === 'bigint') throw new TypeError('Cannot convert BigInt to number'); return NumberCtor(value); } function ToInteger(value: unknown): number { const num = ToNumber(value); if (NumberIsNaN(num)) return 0; const integer = MathTrunc(num); if (num === 0) return 0; return integer; } export function ToString(value: unknown): string { if (typeof value === 'symbol') { throw new TypeError('Cannot convert a Symbol value to a String'); } return StringCtor(value); } export function ToIntegerThrowOnInfinity(value: unknown): number { const integer = ToInteger(value); if (!NumberIsFinite(integer)) { throw new RangeError('infinity is out of range'); } return integer; } export function ToPositiveInteger(valueParam: unknown, property?: string): number { const value = ToInteger(valueParam); if (!NumberIsFinite(value)) { throw new RangeError('infinity is out of range'); } if (value < 1) { if (property !== undefined) { throw new RangeError(`property '${property}' cannot be a a number less than one`); } throw new RangeError('Cannot convert a number less than one to a positive integer'); } return value; } export function ToIntegerWithoutRounding(valueParam: unknown): number { const value = ToNumber(valueParam); if (NumberIsNaN(value)) return 0; if (!NumberIsFinite(value)) { throw new RangeError('infinity is out of range'); } if (!IsInteger(value)) { throw new RangeError(`unsupported fractional value ${value}`); } return ToInteger(value); // ℝ(value) in spec text; converts -0 to 0 } function divmod(x: JSBI, y: JSBI): { quotient: JSBI; remainder: JSBI } { const quotient = JSBI.divide(x, y); const remainder = JSBI.remainder(x, y); return { quotient, remainder }; } function abs(x: JSBI): JSBI { if (JSBI.lessThan(x, ZERO)) return JSBI.multiply(x, NEGATIVE_ONE); return x; } type BuiltinCastFunction = (v: unknown) => string | number; const BUILTIN_CASTS = new Map<PrimitivePropertyNames, BuiltinCastFunction>([ ['year', ToIntegerThrowOnInfinity], ['month', ToPositiveInteger], ['monthCode', ToString], ['day', ToPositiveInteger], ['hour', ToIntegerThrowOnInfinity], ['minute', ToIntegerThrowOnInfinity], ['second', ToIntegerThrowOnInfinity], ['millisecond', ToIntegerThrowOnInfinity], ['microsecond', ToIntegerThrowOnInfinity], ['nanosecond', ToIntegerThrowOnInfinity], ['years', ToIntegerWithoutRounding], ['months', ToIntegerWithoutRounding], ['weeks', ToIntegerWithoutRounding], ['days', ToIntegerWithoutRounding], ['hours', ToIntegerWithoutRounding], ['minutes', ToIntegerWithoutRounding], ['seconds', ToIntegerWithoutRounding], ['milliseconds', ToIntegerWithoutRounding], ['microseconds', ToIntegerWithoutRounding], ['nanoseconds', ToIntegerWithoutRounding], ['era', ToString], ['eraYear', ToInteger], ['offset', ToString] ]); const ALLOWED_UNITS: readonly Temporal.DateTimeUnit[] = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond', 'microsecond', 'nanosecond' ] as const; type PluralAndSingularUnitTuple<U extends Temporal.DateTimeUnit> = readonly [Temporal.PluralUnit<U>, U]; const SINGULAR_PLURAL_UNITS: readonly PluralAndSingularUnitTuple<Temporal.DateTimeUnit>[] = [ ['years', 'year'], ['months', 'month'], ['weeks', 'week'], ['days', 'day'], ['hours', 'hour'], ['minutes', 'minute'], ['seconds', 'second'], ['milliseconds', 'millisecond'], ['microseconds', 'microsecond'], ['nanoseconds', 'nanosecond'] ] as const; import * as PARSE from './regex'; const IntlDateTimeFormatEnUsCache = new Map<string, Intl.DateTimeFormat>(); function getIntlDateTimeFormatEnUsForTimeZone(timeZoneIdentifier: string) { let instance = IntlDateTimeFormatEnUsCache.get(timeZoneIdentifier); if (instance === undefined) { instance = new IntlDateTimeFormat('en-us', { timeZone: StringCtor(timeZoneIdentifier), hour12: false, era: 'short', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }); IntlDateTimeFormatEnUsCache.set(timeZoneIdentifier, instance); } return instance; } export function IsTemporalInstant(item: unknown): item is Temporal.Instant { return HasSlot(item, EPOCHNANOSECONDS) && !HasSlot(item, TIME_ZONE, CALENDAR); } export function IsTemporalTimeZone(item: unknown): item is Temporal.TimeZone { return HasSlot(item, TIMEZONE_ID); } export function IsTemporalCalendar(item: unknown): item is Temporal.Calendar { return HasSlot(item, CALENDAR_ID); } export function IsTemporalDuration(item: unknown): item is Temporal.Duration { return HasSlot(item, YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS); } export function IsTemporalDate(item: unknown): item is Temporal.PlainDate { return HasSlot(item, DATE_BRAND); } export function IsTemporalTime(item: unknown): item is Temporal.PlainTime { return ( HasSlot(item, ISO_HOUR, ISO_MINUTE, ISO_SECOND, ISO_MILLISECOND, ISO_MICROSECOND, ISO_NANOSECOND) && !HasSlot(item, ISO_YEAR, ISO_MONTH, ISO_DAY) ); } export function IsTemporalDateTime(item: unknown): item is Temporal.PlainDateTime { return HasSlot( item, ISO_YEAR, ISO_MONTH, ISO_DAY, ISO_HOUR, ISO_MINUTE, ISO_SECOND, ISO_MILLISECOND, ISO_MICROSECOND, ISO_NANOSECOND ); } export function IsTemporalYearMonth(item: unknown): item is Temporal.PlainYearMonth { return HasSlot(item, YEAR_MONTH_BRAND); } export function IsTemporalMonthDay(item: unknown): item is Temporal.PlainMonthDay { return HasSlot(item, MONTH_DAY_BRAND); } export function IsTemporalZonedDateTime(item: unknown): item is Temporal.ZonedDateTime { return HasSlot(item, EPOCHNANOSECONDS, TIME_ZONE, CALENDAR); } export function RejectObjectWithCalendarOrTimeZone(item: AnyTemporalLikeType) { if (HasSlot(item, CALENDAR) || HasSlot(item, TIME_ZONE)) { throw new TypeError('with() does not support a calendar or timeZone property'); } if ((item as { calendar: unknown }).calendar !== undefined) { throw new TypeError('with() does not support a calendar property'); } if ((item as { timeZone: unknown }).timeZone !== undefined) { throw new TypeError('with() does not support a timeZone property'); } } function ParseTemporalTimeZone(stringIdent: string) { let { ianaName, offset, z } = ParseTemporalTimeZoneString(stringIdent); if (ianaName) return ianaName; if (z) return 'UTC'; return offset as string; // if !ianaName && !z then offset must be present } function FormatCalendarAnnotation(id: string, showCalendar: Temporal.ShowCalendarOption['calendarName']) { if (showCalendar === 'never') return ''; if (showCalendar === 'auto' && id === 'iso8601') return ''; return `[u-ca=${id}]`; } function ParseISODateTime(isoString: string) { // ZDT is the superset of fields for every other Temporal type const match = PARSE.zoneddatetime.exec(isoString); if (!match) throw new RangeError(`invalid ISO 8601 string: ${isoString}`); let yearString = match[1]; if (yearString[0] === '\u2212') yearString = `-${yearString.slice(1)}`; const year = ToInteger(yearString); const month = ToInteger(match[2] || match[4]); const day = ToInteger(match[3] || match[5]); const hour = ToInteger(match[6]); const hasTime = match[6] !== undefined; const minute = ToInteger(match[7] || match[10]); let second = ToInteger(match[8] || match[11]); if (second === 60) second = 59; const fraction = (match[9] || match[12]) + '000000000'; const millisecond = ToInteger(fraction.slice(0, 3)); const microsecond = ToInteger(fraction.slice(3, 6)); const nanosecond = ToInteger(fraction.slice(6, 9)); let offset; let z = false; if (match[13]) { offset = undefined; z = true; } else if (match[14] && match[15]) { const offsetSign = match[14] === '-' || match[14] === '\u2212' ? '-' : '+'; const offsetHours = match[15] || '00'; const offsetMinutes = match[16] || '00'; const offsetSeconds = match[17] || '00'; let offsetFraction = match[18] || '0'; offset = `${offsetSign}${offsetHours}:${offsetMinutes}`; if (+offsetFraction) { while (offsetFraction.endsWith('0')) offsetFraction = offsetFraction.slice(0, -1); offset += `:${offsetSeconds}.${offsetFraction}`; } else if (+offsetSeconds) { offset += `:${offsetSeconds}`; } if (offset === '-00:00') offset = '+00:00'; } let ianaName = match[19]; if (ianaName) { try { // Canonicalize name if it is an IANA link name or is capitalized wrong ianaName = GetCanonicalTimeZoneIdentifier(ianaName).toString(); } catch { // Not an IANA name, may be a custom ID, pass through unchanged } } const calendar = match[20]; return { year, month, day, hasTime, hour, minute, second, millisecond, microsecond, nanosecond, ianaName, offset, z, calendar }; } function ParseTemporalInstantString(isoString: string) { const result = ParseISODateTime(isoString); if (!result.z && !result.offset) throw new RangeError('Temporal.Instant requires a time zone offset'); return result; } function ParseTemporalZonedDateTimeString(isoString: string) { const result = ParseISODateTime(isoString); if (!result.ianaName) throw new RangeError('Temporal.ZonedDateTime requires a time zone ID in brackets'); return result; } function ParseTemporalDateTimeString(isoString: string) { return ParseISODateTime(isoString); } function ParseTemporalDateString(isoString: string) { return ParseISODateTime(isoString); } function ParseTemporalTimeString(isoString: string) { const match = PARSE.time.exec(isoString); let hour, minute, second, millisecond, microsecond, nanosecond, calendar; if (match) { hour = ToInteger(match[1]); minute = ToInteger(match[2] || match[5]); second = ToInteger(match[3] || match[6]); if (second === 60) second = 59; const fraction = (match[4] || match[7]) + '000000000'; millisecond = ToInteger(fraction.slice(0, 3)); microsecond = ToInteger(fraction.slice(3, 6)); nanosecond = ToInteger(fraction.slice(6, 9)); calendar = match[15]; } else { let z, hasTime; ({ hasTime, hour, minute, second, millisecond, microsecond, nanosecond, calendar, z } = ParseISODateTime(isoString)); if (!hasTime) throw new RangeError(`time is missing in string: ${isoString}`); if (z) throw new RangeError('Z designator not supported for PlainTime'); } // if it's a date-time string, OK if (/[tT ][0-9][0-9]/.test(isoString)) { return { hour, minute, second, millisecond, microsecond, nanosecond, calendar }; } // slow but non-grammar-dependent way to ensure that time-only strings that // are also valid PlainMonthDay and PlainYearMonth throw. corresponds to // assertion in spec text try { const { month, day } = ParseTemporalMonthDayString(isoString); RejectISODate(1972, month, day); } catch { try { const { year, month } = ParseTemporalYearMonthString(isoString); RejectISODate(year, month, 1); } catch { return { hour, minute, second, millisecond, microsecond, nanosecond, calendar }; } } throw new RangeError(`invalid ISO 8601 time-only string ${isoString}; may need a T prefix`); } function ParseTemporalYearMonthString(isoString: string) { const match = PARSE.yearmonth.exec(isoString); let year, month, calendar, referenceISODay; if (match) { let yearString = match[1]; if (yearString[0] === '\u2212') yearString = `-${yearString.slice(1)}`; year = ToInteger(yearString); month = ToInteger(match[2]); calendar = match[3]; } else { let z; ({ year, month, calendar, day: referenceISODay, z } = ParseISODateTime(isoString)); if (z) throw new RangeError('Z designator not supported for PlainYearMonth'); } return { year, month, calendar, referenceISODay }; } function ParseTemporalMonthDayString(isoString: string) { const match = PARSE.monthday.exec(isoString); let month, day, calendar, referenceISOYear; if (match) { month = ToInteger(match[1]); day = ToInteger(match[2]); } else { let z; ({ month, day, calendar, year: referenceISOYear, z } = ParseISODateTime(isoString)); if (z) throw new RangeError('Z designator not supported for PlainMonthDay'); } return { month, day, calendar, referenceISOYear }; } function ParseTemporalTimeZoneString(stringIdent: string): Partial<{ ianaName: string | undefined; offset: string | undefined; z: boolean | undefined; }> { try { let canonicalIdent = GetCanonicalTimeZoneIdentifier(stringIdent); if (canonicalIdent) { canonicalIdent = canonicalIdent.toString(); if (TestTimeZoneOffsetString(canonicalIdent)) return { offset: canonicalIdent }; return { ianaName: canonicalIdent }; } } catch { // fall through } try { // Try parsing ISO string instead const result = ParseISODateTime(stringIdent); if (result.z || result.offset || result.ianaName) { return result; } } catch { // fall through } throw new RangeError(`Invalid time zone: ${stringIdent}`); } function ParseTemporalDurationString(isoString: string) { const match = PARSE.duration.exec(isoString); if (!match) throw new RangeError(`invalid duration: ${isoString}`); if (match.slice(2).every((element) => element === undefined)) { throw new RangeError(`invalid duration: ${isoString}`); } const sign = match[1] === '-' || match[1] === '\u2212' ? -1 : 1; const years = ToInteger(match[2]) * sign; const months = ToInteger(match[3]) * sign; const weeks = ToInteger(match[4]) * sign; const days = ToInteger(match[5]) * sign; const hours = ToInteger(match[6]) * sign; let fHours: number | string = match[7]; let minutes = ToInteger(match[8]) * sign; let fMinutes: number | string = match[9]; let seconds = ToInteger(match[10]) * sign; const fSeconds = match[11] + '000000000'; let milliseconds = ToInteger(fSeconds.slice(0, 3)) * sign; let microseconds = ToInteger(fSeconds.slice(3, 6)) * sign; let nanoseconds = ToInteger(fSeconds.slice(6, 9)) * sign; fHours = fHours ? (sign * ToInteger(fHours)) / 10 ** fHours.length : 0; fMinutes = fMinutes ? (sign * ToInteger(fMinutes)) / 10 ** fMinutes.length : 0; ({ minutes, seconds, milliseconds, microseconds, nanoseconds } = DurationHandleFractions( fHours, minutes, fMinutes, seconds, milliseconds, microseconds, nanoseconds )); return { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds }; } function ParseTemporalInstant(isoString: string) { const { year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, offset, z } = ParseTemporalInstantString(isoString); const epochNs = GetEpochFromISOParts(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond); if (epochNs === null) throw new RangeError('DateTime outside of supported range'); const offsetNs = z ? 0 : ParseTimeZoneOffsetString(offset as string); return JSBI.subtract(epochNs, JSBI.BigInt(offsetNs)); } export function RegulateISODate( yearParam: number, monthParam: number, dayParam: number, overflow: Temporal.ArithmeticOptions['overflow'] ) { let year = yearParam; let month = monthParam; let day = dayParam; switch (overflow) { case 'reject': RejectISODate(year, month, day); break; case 'constrain': ({ year, month, day } = ConstrainISODate(year, month, day)); break; } return { year, month, day }; } export function RegulateTime( hourParam: number, minuteParam: number, secondParam: number, millisecondParam: number, microsecondParam: number, nanosecondParam: number, overflow: Temporal.ArithmeticOptions['overflow'] ) { let hour = hourParam; let minute = minuteParam; let second = secondParam; let millisecond = millisecondParam; let microsecond = microsecondParam; let nanosecond = nanosecondParam; switch (overflow) { case 'reject': RejectTime(hour, minute, second, millisecond, microsecond, nanosecond); break; case 'constrain': ({ hour, minute, second, millisecond, microsecond, nanosecond } = ConstrainTime( hour, minute, second, millisecond, microsecond, nanosecond )); break; } return { hour, minute, second, millisecond, microsecond, nanosecond }; } export function RegulateISOYearMonth( yearParam: number, monthParam: number, overflow: Temporal.ArithmeticOptions['overflow'] ) { let year = yearParam; let month = monthParam; const referenceISODay = 1; switch (overflow) { case 'reject': RejectISODate(year, month, referenceISODay); break; case 'constrain': ({ year, month } = ConstrainISODate(year, month)); break; } return { year, month }; } function DurationHandleFractions( fHoursParam: number, minutesParam: number, fMinutesParam: number, secondsParam: number, millisecondsParam: number, microsecondsParam: number, nanosecondsParam: number ) { let fHours = fHoursParam; let minutes = minutesParam; let fMinutes = fMinutesParam; let seconds = secondsParam; let milliseconds = millisecondsParam; let microseconds = microsecondsParam; let nanoseconds = nanosecondsParam; if (fHours !== 0) { [minutes, fMinutes, seconds, milliseconds, microseconds, nanoseconds].forEach((val) => { if (val !== 0) throw new RangeError('only the smallest unit can be fractional'); }); const mins = fHours * 60; minutes = MathTrunc(mins); fMinutes = mins % 1; } if (fMinutes !== 0) { [seconds, milliseconds, microseconds, nanoseconds].forEach((val) => { if (val !== 0) throw new RangeError('only the smallest unit can be fractional'); }); const secs = fMinutes * 60; seconds = MathTrunc(secs); const fSeconds = secs % 1; if (fSeconds !== 0) { const mils = fSeconds * 1000; milliseconds = MathTrunc(mils); const fMilliseconds = mils % 1; if (fMilliseconds !== 0) { const mics = fMilliseconds * 1000; microseconds = MathTrunc(mics); const fMicroseconds = mics % 1; if (fMicroseconds !== 0) { const nans = fMicroseconds * 1000; nanoseconds = MathTrunc(nans); } } } } return { minutes, seconds, milliseconds, microseconds, nanoseconds }; } function ToTemporalDurationRecord(item: Temporal.Duration | Temporal.DurationLike) { if (IsTemporalDuration(item)) { return { years: GetSlot(item, YEARS), months: GetSlot(item, MONTHS), weeks: GetSlot(item, WEEKS), days: GetSlot(item, DAYS), hours: GetSlot(item, HOURS), minutes: GetSlot(item, MINUTES), seconds: GetSlot(item, SECONDS), milliseconds: GetSlot(item, MILLISECONDS), microseconds: GetSlot(item, MICROSECONDS), nanoseconds: GetSlot(item, NANOSECONDS) }; } const props = ToPartialRecord(item, [ 'days', 'hours', 'microseconds', 'milliseconds', 'minutes', 'months', 'nanoseconds', 'seconds', 'weeks', 'years' ]); if (!props) throw new TypeError('invalid duration-like'); const { years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0, microseconds = 0, nanoseconds = 0 } = props; return { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds }; } export function ToLimitedTemporalDuration( item: Temporal.DurationLike | string, disallowedProperties: (keyof Temporal.DurationLike)[] = [] ) { let record: Required<Temporal.DurationLike>; if (IsObject(item)) { record = ToTemporalDurationRecord(item); } else { const str = ToString(item); record = ParseTemporalDurationString(str); } const { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = record; RejectDuration(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds); for (const property of disallowedProperties) { if (record[property] !== 0) { throw new RangeError( `Duration field ${property} not supported by Temporal.Instant. Try Temporal.ZonedDateTime instead.` ); } } return record; } export function ToTemporalOverflow(options: Temporal.AssignmentOptions) { return GetOption(options, 'overflow', ['constrain', 'reject'], 'constrain'); } export function ToTemporalDisambiguation(options: Temporal.ToInstantOptions) { return GetOption(options, 'disambiguation', ['compatible', 'earlier', 'later', 'reject'], 'compatible'); } export function ToTemporalRoundingMode( options: { roundingMode?: Temporal.RoundingMode }, fallback: Temporal.RoundingMode ) { return GetOption(options, 'roundingMode', ['ceil', 'floor', 'trunc', 'halfExpand'], fallback); } export function NegateTemporalRoundingMode(roundingMode: Temporal.RoundingMode) { switch (roundingMode) { case 'ceil': return 'floor'; case 'floor': return 'ceil'; default: return roundingMode; } } export function ToTemporalOffset( options: Temporal.OffsetDisambiguationOptions, fallback: Required<Temporal.OffsetDisambiguationOptions>['offset'] ) { return GetOption(options, 'offset', ['prefer', 'use', 'ignore', 'reject'], fallback); } export function ToShowCalendarOption(options: Temporal.ShowCalendarOption) { return GetOption(options, 'calendarName', ['auto', 'always', 'never'], 'auto'); } export function ToShowTimeZoneNameOption(options: Temporal.ZonedDateTimeToStringOptions) { return GetOption(options, 'timeZoneName', ['auto', 'never'], 'auto'); } export function ToShowOffsetOption(options: Temporal.ZonedDateTimeToStringOptions) { return GetOption(options, 'offset', ['auto', 'never'], 'auto'); } export function ToTemporalRoundingIncrement( options: { roundingIncrement?: number }, dividend: number | undefined, inclusive?: boolean ) { let maximum = Infinity; if (dividend !== undefined) maximum = dividend; if (!inclusive && dividend !== undefined) maximum = dividend > 1 ? dividend - 1 : 1; const increment = GetNumberOption(options, 'roundingIncrement', 1, maximum, 1); if (dividend !== undefined && dividend % increment !== 0) { throw new RangeError(`Rounding increment must divide evenly into ${dividend}`); } return increment; } type TemporalDateTimeRoundingMaximumIncrements = { year?: number; month?: number; week?: number; day?: number; hour?: number; minute: number; second: number; millisecond: number; microsecond: number; nanosecond: number; }; export function ToTemporalDateTimeRoundingIncrement( options: { roundingIncrement?: number }, smallestUnit: keyof TemporalDateTimeRoundingMaximumIncrements ) { const maximumIncrements: TemporalDateTimeRoundingMaximumIncrements = { year: undefined, month: undefined, week: undefined, day: undefined, hour: 24, minute: 60, second: 60, millisecond: 1000, microsecond: 1000, nanosecond: 1000 }; return ToTemporalRoundingIncrement(options, maximumIncrements[smallestUnit], false); } export function ToSecondsStringPrecision(options: Temporal.ToStringPrecisionOptions): { precision: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 'auto' | 'minute'; unit: UnitSmallerThanOrEqualTo<'minute'>; increment: number; } { const smallestUnit = ToSmallestTemporalUnit(options, undefined, ['year', 'month', 'week', 'day', 'hour']); switch (smallestUnit) { case 'minute': return { precision: 'minute', unit: 'minute', increment: 1 }; case 'second': return { precision: 0, unit: 'second', increment: 1 }; case 'millisecond': return { precision: 3, unit: 'millisecond', increment: 1 }; case 'microsecond': return { precision: 6, unit: 'microsecond', increment: 1 }; case 'nanosecond': return { precision: 9, unit: 'nanosecond', increment: 1 }; default: // fall through if option not given } let digits = options.fractionalSecondDigits; if (digits === undefined) digits = 'auto'; if (typeof digits !== 'number') { const stringDigits = ToString(digits); if (stringDigits === 'auto') return { precision: 'auto', unit: 'nanosecond', increment: 1 }; throw new RangeError(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${stringDigits}`); } if (NumberIsNaN(digits) || digits < 0 || digits > 9) { throw new RangeError(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${digits}`); } const precision = MathFloor(digits); switch (precision) { case 0: return { precision, unit: 'second', increment: 1 }; case 1: case 2: case 3: return { precision, unit: 'millisecond', increment: 10 ** (3 - precision) }; case 4: case 5: case 6: return { precision, unit: 'microsecond', increment: 10 ** (6 - precision) }; case 7: case 8: case 9: return { precision, unit: 'nanosecond', increment: 10 ** (9 - precision) }; default: throw new RangeError(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${digits}`); } } type ToSingularUnit<T extends Temporal.DateTimeUnit | Temporal.PluralUnit<Temporal.DateTimeUnit> | 'auto'> = Exclude< T, Temporal.PluralUnit<Temporal.DateTimeUnit> | 'auto' >; export function ToLargestTemporalUnit<Allowed extends Temporal.DateTimeUnit>( options: { largestUnit?: Temporal.LargestUnit<Allowed> }, fallback: undefined ): ToSingularUnit<Allowed> | 'auto' | undefined; export function ToLargestTemporalUnit< Allowed extends Temporal.LargestUnit<Temporal.DateTimeUnit>, Disallowed extends Temporal.DateTimeUnit >( options: { largestUnit?: Allowed | undefined }, fallback: 'auto', disallowedStrings: ReadonlyArray<Disallowed>, autoValue: ToSingularUnit<Allowed> ): ToSingularUnit<Allowed>; export function ToLargestTemporalUnit< Allowed extends Temporal.DateTimeUnit, Disallowed extends ToSingularUnit<Exclude<Temporal.DateTimeUnit, Allowed>>, Fallback extends ToSingularUnit<Allowed> | 'auto' | undefined >( options: { largestUnit?: Temporal.LargestUnit<Allowed> }, fallback: Fallback, disallowedStrings: ReadonlyArray<Disallowed> = [], autoValue?: Exclude<ToSingularUnit<Allowed>, 'auto'> | undefined ): ToSingularUnit<Allowed> | (Fallback extends undefined ? undefined : 'auto') { type Ret = ToSingularUnit<Allowed> | (Fallback extends undefined ? undefined : 'auto'); const singular = new Map( SINGULAR_PLURAL_UNITS.filter(([, sing]) => !disallowedStrings.includes(sing as Disallowed)) ) as Map<Temporal.PluralUnit<Allowed>, Allowed>; const allowed = new Set(ALLOWED_UNITS) as Set<Allowed>; for (const s of disallowedStrings) { allowed.delete(s as unknown as Allowed); } const retval = GetOption(options, 'largestUnit', ['auto', ...allowed, ...singular.keys()], fallback); if (retval === 'auto' && autoValue !== undefined) return autoValue; if (singular.has(retval as Temporal.PluralUnit<Allowed>)) { return singular.get(retval as Temporal.PluralUnit<Allowed>) as Ret; } return retval as Ret; } export function ToSmallestTemporalUnit< Allowed extends Temporal.SmallestUnit<Temporal.DateTimeUnit>, Fallback extends ToSingularUnit<Allowed> | undefined, Disallowed extends ToSingularUnit<Exclude<Temporal.DateTimeUnit, Allowed>> >( options: { smallestUnit?: Allowed | undefined }, fallback: Fallback, disallowedStrings: ReadonlyArray<Disallowed> = [] ): ToSingularUnit<Allowed> | (Fallback extends undefined ? undefined : never) { type Ret = ToSingularUnit<Allowed> | (Fallback extends undefined ? undefined : never); const singular = new Map( SINGULAR_PLURAL_UNITS.filter(([, sing]) => !disallowedStrings.includes(sing as Disallowed)) ) as Map<Allowed, ToSingularUnit<Allowed>>; const allowed = new Set(ALLOWED_UNITS) as Set<Allowed>; for (const s of disallowedStrings) { allowed.delete(s as unknown as Allowed); } const value = GetOption(options, 'smallestUnit', [...allowed, ...singular.keys()], fallback); if (singular.has(value as Allowed)) { return singular.get(value as Allowed) as Ret; } return value as Ret; } export function ToTemporalDurationTotalUnit(options: { unit: Temporal.DateTimeUnit | Temporal.PluralUnit<Temporal.DateTimeUnit>; }) { // This AO is identical to ToSmallestTemporalUnit, except: // - default is always `undefined` (caller will throw if omitted) // - option is named `unit` (not `smallestUnit`) // - all units are valid (no `disallowedStrings`) const singular = new Map(SINGULAR_PLURAL_UNITS); const value = GetOption(options, 'unit', [...singular.values(), ...singular.keys()], undefined); if (singular.has(value as Temporal.PluralUnit<Temporal.DateTimeUnit>)) { return singular.get(value as Temporal.PluralUnit<Temporal.DateTimeUnit>); } return value as Temporal.DateTimeUnit; } export function ToRelativeTemporalObject(options: { relativeTo?: | Temporal.ZonedDateTime | Temporal.PlainDateTime | Temporal.ZonedDateTimeLike | Temporal.PlainDateTimeLike | string | undefined; }): Temporal.ZonedDateTime | Temporal.PlainDate | undefined { const relativeTo = options.relativeTo; if (relativeTo === undefined) return relativeTo; let offsetBehaviour: OffsetBehaviour = 'option'; let matchMinutes = false; let year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, calendar, timeZone, offset; if (IsObject(relativeTo)) { if (IsTemporalZonedDateTime(relativeTo) || IsTemporalDate(relativeTo)) return relativeTo; if (IsTemporalDateTime(relativeTo)) return TemporalDateTimeToDate(relativeTo); calendar = GetTemporalCalendarWithISODefault(relativeTo); const fieldNames = CalendarFields(calendar, [ 'day', 'hour', 'microsecond', 'millisecond', 'minute', 'month', 'monthCode', 'nanosecond', 'second', 'year' ] as const); const fields = ToTemporalDateTimeFields(relativeTo, fieldNames); const dateOptions = ObjectCreate(null); dateOptions.overflow = 'constrain'; ({ year, month, day, hour, minute, second, millisecond, microsecond, nanosecond } = InterpretTemporalDateTimeFields( calendar, fields, dateOptions )); // The `offset` and `timeZone` properties only exist on ZonedDateTime (or // ZonedDateTimeLike-property bags). The assertions below are used to avoid // TS errors while not diverging runtime code from proposal-temporal. offset = (relativeTo as Temporal.ZonedDateTimeLike).offset; if (offset === undefined) offsetBehaviour = 'wall'; timeZone = (relativeTo as Temporal.ZonedDateTimeLike).timeZone; } else { let ianaName, z; ({ year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, calendar, ianaName, offset, z } = ParseISODateTime(ToString(relativeTo))); if (ianaName) timeZone = ianaName; if (z) { offsetBehaviour = 'exact'; } else if (!offset) { offsetBehaviour = 'wall'; } if (!calendar) calendar = GetISO8601Calendar(); calendar = ToTemporalCalendar(calendar); matchMinutes = true; } if (timeZone) { timeZone = ToTemporalTimeZone(timeZone); let offsetNs = 0; if (offsetBehaviour === 'option') offsetNs = ParseTimeZoneOffsetString(ToString(offset)); const epochNanoseconds = InterpretISODateTimeOffset( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, offsetBehaviour, offsetNs, timeZone, 'compatible', 'reject', matchMinutes ); return CreateTemporalZonedDateTime(epochNanoseconds, timeZone, calendar); } return CreateTemporalDate(year, month, day, calendar); } export function ValidateTemporalUnitRange(largestUnit: Temporal.DateTimeUnit, smallestUnit: Temporal.DateTimeUnit) { if (ALLOWED_UNITS.indexOf(largestUnit) > ALLOWED_UNITS.indexOf(smallestUnit)) { throw new RangeError(`largestUnit ${largestUnit} cannot be smaller than smallestUnit ${smallestUnit}`); } } export function DefaultTemporalLargestUnit( years: number, months: number, weeks: number, days: number, hours: number, minutes: number, seconds: number, milliseconds: number, microseconds: number, nanoseconds: number ): Temporal.DateTimeUnit { const singular = new Map<string, Temporal.DateTimeUnit>(SINGULAR_PLURAL_UNITS); for (const [prop, v] of [ ['years', years], ['months', months], ['weeks', weeks], ['days', days], ['hours', hours], ['minutes', minutes], ['seconds', seconds], ['milliseconds', milliseconds], ['microseconds', microseconds], ['nanoseconds', nanoseconds] ] as const) { if (v !== 0) return singular.get(prop) as Temporal.DateTimeUnit; } return 'nanosecond'; } export function LargerOfTwoTemporalUnits<T1 extends Temporal.DateTimeUnit, T2 extends Temporal.DateTimeUnit>( unit1: T1, unit2: T2 ) { if (ALLOWED_UNITS.indexOf(unit1) > ALLOWED_UNITS.indexOf(unit2)) return unit2; return unit1; } export function ToPartialRecord<B extends AnyTemporalLikeType>(bagParam: B, fieldsParam: ReadonlyArray<keyof B>) { // External callers are limited to specific types, but this function's // implementation uses generic property types. The casts below (and at the // end) convert to/from generic records. const bag = bagParam as Record<PrimitivePropertyNames & keyof B, string | number | undefined>; const fields = fieldsParam as ReadonlyArray<keyof B & PrimitivePropertyNames>; let any = false; let result = {} as typeof bag; for (const property of fields) { const value = bag[property]; if (value !== undefined) { any = true; if (BUILTIN_CASTS.has(property)) { result[property] = (BUILTIN_CASTS.get(property) as BuiltinCastFunction)(value); } else { result[property] = value; } } } return any ? (result as B) : false; } export function PrepareTemporalFields<B extends AnyTemporalLikeType>( bagParam: B, fieldsParam: ReadonlyArray<FieldRecord<B>> ): Required<B> { // External callers are limited to specific types, but this function's // implementation uses generic property types. The casts below (and at the // end) convert to/from generic records. const bag = bagParam as Record<PrimitivePropertyNames & keyof B, string | number | undefined>; const fields = fieldsParam as ReadonlyArray<FieldRecord<typeof bag>>; const result = {} as typeof bag; let any = false; for (const fieldRecord of fields) { const [property, defaultValue] = fieldRecord; let value = bag[property]; if (value === undefined) { if (fieldRecord.length === 1) { throw new TypeError(`required property '${property}' missing or undefined`); } value = defaultValue; } else { any = true; if (BUILTIN_CASTS.has(property as PrimitivePropertyNames)) { value = (BUILTIN_CASTS.get(property) as BuiltinCastFunction)(value); } } result[property] = value; } if (!any) { throw new TypeError('no supported properties found'); } if ( ((result as { era: unknown })['era'] === undefined) !== ((result as { eraYear: unknown })['eraYear'] === undefined) ) { throw new RangeError("properties 'era' and 'eraYear' must be provided together"); } return result as unknown as Required<B>; } // field access in the following operations is intentionally alphabetical export function ToTemporalDateFields( bag: Temporal.PlainDateLike, fieldNames: readonly (keyof Temporal.PlainDateLike)[] ) { const entries: [keyof Temporal.PlainDateLike, 0 | undefined][] = [ ['day', undefined], ['month', undefined], ['monthCode', undefined], ['year', undefined] ]; // Add extra fields from the calendar at the end fieldNames.forEach((fieldName) => { if (!entries.some(([name]) => name === fieldName)) { entries.push([fieldName, undefined]); } }); return PrepareTemporalFields(bag, entries); } export function ToTemporalDateTimeFields( bag: Temporal.PlainDateTimeLike, fieldNames: readonly (keyof Temporal.PlainDateTimeLike)[] ) { const entries: [keyof Temporal.PlainDateTimeLike, 0 | undefined][] = [ ['day', undefined], ['hour', 0], ['microsecond', 0], ['millisecond', 0], ['minute', 0], ['month', undefined], ['monthCode', undefined], ['nanosecond', 0], ['second', 0], ['year', undefined] ]; // Add extra fields from the calendar at the end fieldNames.forEach((fieldName) => { if (!entries.some(([name]) => name === fieldName)) { entries.push([fieldName, undefined]); } }); return PrepareTemporalFields(bag, entries); } export function ToTemporalMonthDayFields( bag: Temporal.PlainMonthDayLike, fieldNames: readonly (keyof Temporal.PlainMonthDayLike)[] ) { const entries: [keyof Temporal.PlainMonthDayLike, 0 | undefined][] = [ ['day', undefined], ['month', undefined], ['monthCode', undefined], ['year', undefined] ]; // Add extra fields from the calendar at the end fieldNames.forEach((fieldName) => { if (!entries.some(([name]) => name === fieldName)) { entries.push([fieldName, undefined]); } }); return PrepareTemporalFields(bag, entries); } export function ToTemporalTimeRecord(bag: Temporal.PlainTimeLike) { return PrepareTemporalFields(bag, [ ['hour', 0], ['microsecond', 0], ['millisecond', 0], ['minute', 0], ['nanosecond', 0], ['second', 0] ]); } export function ToTemporalYearMonthFields( bag: Temporal.PlainYearMonthLike, fieldNames: readonly (keyof Temporal.PlainYearMonthLike)[] ) { const entries: [keyof Temporal.PlainYearMonthLike, 0 | undefined][] = [ ['month', undefined], ['monthCode', undefined], ['year', undefined] ]; // Add extra fields from the calendar at the end fieldNames.forEach((fieldName) => { if (!entries.some(([name]) => name === fieldName)) { entries.push([fieldName, undefined]); } }); return PrepareTemporalFields(bag, entries); } function ToTemporalZonedDateTimeFields( bag: Temporal.ZonedDateTimeLike, fieldNames: readonly (keyof Temporal.ZonedDateTimeLike)[] ) { const entries: ([keyof Temporal.ZonedDateTimeLike, 0 | undefined] | ['timeZone'])[] = [ ['day', undefined], ['hour', 0], ['microsecond', 0], ['millisecond', 0], ['minute', 0], ['month', undefined], ['monthCode', undefined], ['nanosecond', 0], ['second', 0], ['year', undefined], ['offset', undefined], ['timeZone'] ]; // Add extra fields from the calendar at the end fieldNames.forEach((fieldName) => { if (!entries.some(([name]) => name === fieldName)) { entries.push([fieldName, undefined]); } }); return PrepareTemporalFields(bag, entries); } export function ToTemporalDate( itemParam: PlainDateParams['from'][0], options: PlainDateParams['from'][1] = ObjectCreate(null) ): Temporal.PlainDate { let item = itemParam; if (IsObject(item)) { if (IsTemporalDate(item)) return item; if (IsTemporalZonedDateTime(item)) { item = BuiltinTimeZoneGetPlainDateTimeFor( GetSlot(item, TIME_ZONE), GetSlot(item, INSTANT), GetSlot(item, CALENDAR) ); } if (IsTemporalDateTime(item)) { return CreateTemporalDate( GetSlot(item, ISO_YEAR), GetSlot(item, ISO_MONTH), GetSlot(item, ISO_DAY), GetSlot(item, CALENDAR) ); } const calendar = GetTemporalCalendarWithISODefault(item); const fieldNames = CalendarFields(calendar, ['day', 'month', 'monthCode', 'year'] as const); const fields = ToTemporalDateFields(item, fieldNames); return DateFromFields(calendar, fields, options); } ToTemporalOverflow(options); // validate and ignore const { year, month, day, calendar, z } = ParseTemporalDateString(ToString(item)); if (z) throw new RangeError('Z designator not supported for PlainDate'); const TemporalPlainDate = GetIntrinsic('%Temporal.PlainDate%'); return new TemporalPlainDate(year, month, day, calendar); // include validation } export function InterpretTemporalDateTimeFields( calendar: Temporal.CalendarProtocol, fields: Pick<Temporal.PlainDateTime, Exclude<keyof Temporal.PlainDateTimeLike, 'calendar'>>, options: Temporal.AssignmentOptions ) { let { hour, minute, second, millisecond, microsecond, nanosecond } = ToTemporalTimeRecord(fields); const overflow = ToTemporalOverflow(options); const date = DateFromFields(calendar, fields, options); const year = GetSlot(date, ISO_YEAR); const month = GetSlot(date, ISO_MONTH); const day = GetSlot(date, ISO_DAY); ({ hour, minute, second, millisecond, microsecond, nanosecond } = RegulateTime( hour, minute, second, millisecond, microsecond, nanosecond, overflow )); return { year, month, day, hour, minute, second, millisecond, microsecond, nanosecond }; } export function ToTemporalDateTime( item: PlainDateTimeParams['from'][0], options: PlainDateTimeParams['from'][1] = ObjectCreate(null) ) { let year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, microsecond: number, nanosecond: number, calendar; if (IsObject(item)) { if (IsTemporalDateTime(item)) return item; if (IsTemporalZonedDateTime(item)) { return BuiltinTimeZoneGetPlainDateTimeFor( GetSlot(item, TIME_ZONE), GetSlot(item, INSTANT), GetSlot(item, CALENDAR) ); } if (IsTemporalDate(item)) { return CreateTemporalDateTime( GetSlot(item, ISO_YEAR), GetSlot(item, ISO_MONTH), GetSlot(item, ISO_DAY), 0, 0, 0, 0, 0, 0, GetSlot(item, CALENDAR) ); } calendar = GetTemporalCalendarWithISODefault(item); const fieldNames = CalendarFields(calendar, [ 'day', 'hour', 'microsecond', 'millisecond', 'minute', 'month', 'monthCode', 'nanosecond', 'second', 'year' ] as const); const fields = ToTemporalDateTimeFields(item, fieldNames); ({ year, month, day, hour, minute, second, millisecond, microsecond, nanosecond } = InterpretTemporalDateTimeFields( calendar, fields, options )); } else { ToTemporalOverflow(options); // validate and ignore let z; ({ year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, calendar, z } = ParseTemporalDateTimeString(ToString(item))); if (z) throw new RangeError('Z designator not supported for PlainDateTime'); RejectDateTime(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond); if (calendar === undefined) calendar = GetISO8601Calendar(); calendar = ToTemporalCalendar(calendar); } return CreateTemporalDateTime(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, calendar); } export function ToTemporalDuration(item: DurationParams['from'][0]) { let years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds; if (IsObject(item)) { if (IsTemporalDuration(item)) return item; ({ years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = ToTemporalDurationRecord(item)); } else { ({ years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = ParseTemporalDurationString(ToString(item))); } const TemporalDuration = GetIntrinsic('%Temporal.Duration%'); return new TemporalDuration( years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds ); } export function ToTemporalInstant(item: InstantParams['from'][0]) { if (IsTemporalInstant(item)) return item; if (IsTemporalZonedDateTime(item)) { const TemporalInstant = GetIntrinsic('%Temporal.Instant%'); return new TemporalInstant(GetSlot(item, EPOCHNANOSECONDS)); } const ns = ParseTemporalInstant(ToString(item)); const TemporalInstant = GetIntrinsic('%Temporal.Instant%'); return new TemporalInstant(ns); } export function ToTemporalMonthDay( item: PlainMonthDayParams['from'][0], options: PlainMonthDayParams['from'][1] = ObjectCreate(null) ) { if (IsObject(item)) { if (IsTemporalMonthDay(item)) return item; let calendar: Temporal.CalendarProtocol, calendarAbsent: boolean; if (HasSlot(item, CALENDAR)) { calendar = GetSlot(item, CALENDAR); calendarAbsent = false; } else { let maybeStringCalendar = item.calendar; calendarAbsent = maybeStringCalendar === undefined; if (maybeStringCalendar === undefined) maybeStringCalendar = GetISO8601Calendar(); calendar = ToTemporalCalendar(maybeStringCalendar); } const fieldNames = CalendarFields(calendar, ['day', 'month', 'monthCode', 'year'] as const); const fields = ToTemporalMonthDayFields(item, fieldNames); // Callers who omit the calendar are not writing calendar-independent // code. In that case, `monthCode`/`year` can be omitted; `month` and // `day` are sufficient. Add a `year` to satisfy calendar validation. if (calendarAbsent && fields.month !== undefined && fields.monthCode === undefined && fields.year === undefined) { fields.year = 1972; } return MonthDayFromFields(calendar, fields, options); } ToTemporalOverflow(options); // validate and ignore let { month, day, referenceISOYear, calendar: maybeStringCalendar } = ParseTemporalMonthDayString(ToString(item)); let calendar: Temporal.CalendarProtocol | string | undefined = maybeStringCalendar; if (calendar === undefined) calendar = GetISO8601Calendar(); calendar = ToTemporalCalendar(calendar); if (referenceISOYear === undefined) { RejectISODate(1972, month, day); return CreateTemporalMonthDay(month, day, calendar); } const result = CreateTemporalMonthDay(month, day, calendar, referenceISOYear); const canonicalOptions = ObjectCreate(null); return MonthDayFromFields(calendar, result, canonicalOptions); } export function ToTemporalTime( itemParam: PlainTimeParams['from'][0], overflow: NonNullable<PlainTimeParams['from'][1]>['overflow'] = 'constrain' ) { let item = itemParam; let hour, minute, second, millisecond, microsecond, nanosecond, calendar; if (IsObject(item)) { if (IsTemporalTime(item)) return item; if (IsTemporalZonedDateTime(item)) { item = BuiltinTimeZoneGetPlainDateTimeFor( GetSlot(item, TIME_ZONE), GetSlot(item, INSTANT), GetSlot(item, CALENDAR) ); } if (IsTemporalDateTime(item)) { const TemporalPlainTime = GetIntrinsic('%Temporal.PlainTime%'); return new TemporalPlainTime( GetSlot(item, ISO_HOUR), GetSlot(item, ISO_MINUTE), GetSlot(item, ISO_SECOND), GetSlot(item, ISO_MILLISECOND), GetSlot(item, ISO_MICROSECOND), GetSlot(item, ISO_NANOSECOND) ); } calendar = GetTemporalCalendarWithISODefault(item); if (ToString(calendar) !== 'iso8601') { throw new RangeError('PlainTime can only have iso8601 calendar'); } ({ hour, minute, second, millisecond, microsecond, nanosecond } = ToTemporalTimeRecord(item)); ({ hour, minute, second, millisecond, microsecond, nanosecond } = RegulateTime( hour, minute, second, millisecond, microsecond, nanosecond, overflow )); } else { ({ hour, minute, second, millisecond, microsecond, nanosecond, calendar } = ParseTemporalTimeString( ToString(item) )); RejectTime(hour, minute, second, millisecond, microsecond, nanosecond); if (calendar !== undefined && calendar !== 'iso8601') { throw new RangeError('PlainTime can only have iso8601 calendar'); } } const TemporalPlainTime = GetIntrinsic('%Temporal.PlainTime%'); return new TemporalPlainTime(hour, minute, second, millisecond, microsecond, nanosecond); } export function ToTemporalYearMonth( item: PlainYearMonthParams['from'][0], options: PlainYearMonthParams['from'][1] = ObjectCreate(null) ) { if (IsObject(item)) { if (IsTemporalYearMonth(item)) return item; const calendar = GetTemporalCalendarWithISODefault(item); const fieldNames = CalendarFields(calendar, ['month', 'monthCode', 'year'] as const); const fields = ToTemporalYearMonthFields(item, fieldNames); return YearMonthFromFields(calendar, fields, options); } ToTemporalOverflow(options); // validate and ignore let { year, month, referenceISODay, calendar: maybeStringCalendar } = ParseTemporalYearMonthString(ToString(item)); // TODO: replace with ternary? let calendar: Temporal.CalendarProtocol | string = maybeStringCalendar; if (calendar === undefined) calendar = GetISO8601Calendar(); calendar = ToTemporalCalendar(calendar); if (referenceISODay === undefined) { RejectISODate(year, month, 1); return CreateTemporalYearMonth(year, month, calendar); } const result = CreateTemporalYearMonth(year, month, calendar, referenceISODay); const canonicalOptions = ObjectCreate(null); return YearMonthFromFields(calendar, result, canonicalOptions); } type OffsetBehaviour = 'wall' | 'exact' | 'option'; export function InterpretISODateTimeOffset( year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, microsecond: number, nanosecond: number, offsetBehaviour: OffsetBehaviour, offsetNs: number, timeZone: Temporal.TimeZoneProtocol, disambiguation: NonNullable<Temporal.ToInstantOptions['disambiguation']>, offsetOpt: Temporal.OffsetDisambiguationOptions['offset'], matchMinute: boolean ) { const DateTime = GetIntrinsic('%Temporal.PlainDateTime%'); const dt = new DateTime(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond); if (offsetBehaviour === 'wall' || offsetOpt === 'ignore') { // Simple case: ISO string without a TZ offset (or caller wants to ignore // the offset), so just convert DateTime to Instant in the given time zone const instant = BuiltinTimeZoneGetInstantFor(timeZone, dt, disambiguation); return GetSlot(instant, EPOCHNANOSECONDS); } // The caller wants the offset to always win ('use') OR the caller is OK // with the offset winning ('prefer' or 'reject') as long as it's valid // for this timezone and date/time. if (offsetBehaviour === 'exact' || offsetOpt === 'use') { // Calculate the instant for the input's date/time and offset const epochNs = GetEpochFromISOParts(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond); if (epochNs === null) throw new RangeError('ZonedDateTime outside of supported range'); return JSBI.subtract(epochNs, JSBI.BigInt(offsetNs)); } // "prefer" or "reject" const possibleInstants = GetPossibleInstantsFor(timeZone, dt); for (const candidate of possibleInstants) { const candidateOffset = GetOffsetNanosecondsFor(timeZone, candidate); const roundedCandidateOffset = JSBI.toNumber( RoundNumberToIncrement(JSBI.BigInt(candidateOffset), 60e9, 'halfExpand') ); if (candidateOffset === offsetNs || (matchMinute && roundedCandidateOffset === offsetNs)) { return GetSlot(candidate, EPOCHNANOSECONDS); } } // the user-provided offset doesn't match any instants for this time // zone and date/time. if (offsetOpt === 'reject') { const offsetStr = FormatTimeZoneOffsetString(offsetNs); const timeZoneString = IsTemporalTimeZone(timeZone) ? GetSlot(timeZone, TIMEZONE_ID) : 'time zone'; // The tsc emit for this line rewrites to invoke the PlainDateTime's valueOf method, NOT // toString (which is invoked by Node when using template literals directly). // See https://github.com/microsoft/TypeScript/issues/39744 for the proposed fix in tsc emit throw new RangeError(`Offset ${offsetStr} is invalid for ${dt.toString()} in ${timeZoneString}`); } // fall through: offsetOpt === 'prefer', but the offset doesn't match // so fall back to use the time zone instead. const instant = DisambiguatePossibleInstants(possibleInstants, timeZone, dt, disambiguation); return GetSlot(instant, EPOCHNANOSECONDS); } export function ToTemporalZonedDateTime( item: ZonedDateTimeParams['from'][0], options: ZonedDateTimeParams['from'][1] = ObjectCreate(null) ) { let year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, microsecond: number, nanosecond: number, timeZone, offset: string | undefined, calendar: string | Temporal.CalendarProtocol; let matchMinute = false; let offsetBehaviour: OffsetBehaviour = 'option'; if (IsObject(item)) { if (IsTemporalZonedDateTime(item)) return item; calendar = GetTemporalCalendarWithISODefault(item); const fieldNames = CalendarFields(calendar, [ 'day', 'hour', 'microsecond', 'millisecond', 'minute', 'month', 'monthCode', 'nanosecond', 'second', 'year' ] as const); const fields = ToTemporalZonedDateTimeFields(item, fieldNames); ({ year, month, day, hour, minute, second, millisecond, microsecond, nanosecond } = InterpretTemporalDateTimeFields( calendar, fields, options )); timeZone = ToTemporalTimeZone(fields.timeZone); offset = fields.offset; if (offset === undefined) { offsetBehaviour = 'wall'; } else { offset = ToString(offset); } } else { ToTemporalOverflow(options); // validate and ignore let ianaName, z; ({ year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, ianaName, offset, z, calendar } = ParseTemporalZonedDateTimeString(ToString(item))); if (!ianaName) throw new RangeError('time zone ID required in brackets'); if (z) { offsetBehaviour = 'exact'; } else if (!offset) { offsetBehaviour = 'wall'; } const TemporalTimeZone = GetIntrinsic('%Temporal.TimeZone%'); timeZone = new TemporalTimeZone(ianaName); if (!calendar) calendar = GetISO8601Calendar(); calendar = ToTemporalCalendar(calendar); matchMinute = true; // ISO strings may specify offset with less precision } let offsetNs = 0; // The code above guarantees that if offsetBehaviour === 'option', then // `offset` is not undefined. if (offsetBehaviour === 'option') offsetNs = ParseTimeZoneOffsetString(offset as string); const disambiguation = ToTemporalDisambiguation(options); const offsetOpt = ToTemporalOffset(options, 'reject'); const epochNanoseconds = InterpretISODateTimeOffset( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, offsetBehaviour, offsetNs, timeZone, disambiguation, offsetOpt, matchMinute ); return CreateTemporalZonedDateTime(epochNanoseconds, timeZone, calendar); } export function CreateTemporalDateSlots( result: Temporal.PlainDate, isoYear: number, isoMonth: number, isoDay: number, calendar: Temporal.CalendarProtocol ) { RejectISODate(isoYear, isoMonth, isoDay); RejectDateRange(isoYear, isoMonth, isoDay); CreateSlots(result); SetSlot(result, ISO_YEAR, isoYear); SetSlot(result, ISO_MONTH, isoMonth); SetSlot(result, ISO_DAY, isoDay); SetSlot(result, CALENDAR, calendar); SetSlot(result, DATE_BRAND, true); if (DEBUG) { ObjectDefineProperty(result, '_repr_', { value: `${result[Symbol.toStringTag]} <${TemporalDateToString(result)}>`, writable: false, enumerable: false, configurable: false }); } } export function CreateTemporalDate( isoYear: number, isoMonth: number, isoDay: number, calendar: Temporal.CalendarProtocol = GetISO8601Calendar() ) { const TemporalPlainDate = GetIntrinsic('%Temporal.PlainDate%'); const result = ObjectCreate(TemporalPlainDate.prototype); CreateTemporalDateSlots(result, isoYear, isoMonth, isoDay, calendar); return result; } export function CreateTemporalDateTimeSlots( result: Temporal.PlainDateTime, isoYear: number, isoMonth: number, isoDay: number, h: number, min: number, s: number, ms: number, µs: number, ns: number, calendar: Temporal.CalendarProtocol ) { RejectDateTime(isoYear, isoMonth, isoDay, h, min, s, ms, µs, ns); RejectDateTimeRange(isoYear, isoMonth, isoDay, h, min, s, ms, µs, ns); CreateSlots(result); SetSlot(result, ISO_YEAR, isoYear); SetSlot(result, ISO_MONTH, isoMonth); SetSlot(result, ISO_DAY, isoDay); SetSlot(result, ISO_HOUR, h); SetSlot(result, ISO_MINUTE, min); SetSlot(result, ISO_SECOND, s); SetSlot(result, ISO_MILLISECOND, ms); SetSlot(result, ISO_MICROSECOND, µs); SetSlot(result, ISO_NANOSECOND, ns); SetSlot(result, CALENDAR, calendar); if (DEBUG) { Object.defineProperty(result, '_repr_', { value: `${result[Symbol.toStringTag]} <${TemporalDateTimeToString(result, 'auto')}>`, writable: false, enumerable: false, configurable: false }); } } export function CreateTemporalDateTime( isoYear: number, isoMonth: number, isoDay: number, h: number, min: number, s: number, ms: number, µs: number, ns: number, calendar: Temporal.CalendarProtocol = GetISO8601Calendar() ) { const TemporalPlainDateTime = GetIntrinsic('%Temporal.PlainDateTime%'); const result = ObjectCreate(TemporalPlainDateTime.prototype); CreateTemporalDateTimeSlots(result, isoYear, isoMonth, isoDay, h, min, s, ms, µs, ns, calendar); return result as Temporal.PlainDateTime; } export function CreateTemporalMonthDaySlots( result: Temporal.PlainMonthDay, isoMonth: number, isoDay: number, calendar: Temporal.CalendarProtocol, referenceISOYear: number ) { RejectISODate(referenceISOYear, isoMonth, isoDay); RejectDateRange(referenceISOYear, isoMonth, isoDay); CreateSlots(result); SetSlot(result, ISO_MONTH, isoMonth); SetSlot(result, ISO_DAY, isoDay); SetSlot(result, ISO_YEAR, referenceISOYear); SetSlot(result, CALENDAR, calendar); SetSlot(result, MONTH_DAY_BRAND, true); if (DEBUG) { Object.defineProperty(result, '_repr_', { value: `${result[Symbol.toStringTag]} <${TemporalMonthDayToString(result)}>`, writable: false, enumerable: false, configurable: false }); } } export function CreateTemporalMonthDay( isoMonth: number, isoDay: number, calendar: Temporal.CalendarProtocol = GetISO8601Calendar(), referenceISOYear = 1972 ) { const TemporalPlainMonthDay = GetIntrinsic('%Temporal.PlainMonthDay%'); const result = ObjectCreate(TemporalPlainMonthDay.prototype); CreateTemporalMonthDaySlots(result, isoMonth, isoDay, calendar, referenceISOYear); return result; } export function CreateTemporalYearMonthSlots( result: Temporal.PlainYearMonth, isoYear: number, isoMonth: number, calendar: Temporal.CalendarProtocol, referenceISODay: number ) { RejectISODate(isoYear, isoMonth, referenceISODay); RejectYearMonthRange(isoYear, isoMonth); CreateSlots(result); SetSlot(result, ISO_YEAR, isoYear); SetSlot(result, ISO_MONTH, isoMonth); SetSlot(result, ISO_DAY, referenceISODay); SetSlot(result, CALENDAR, calendar); SetSlot(result, YEAR_MONTH_BRAND, true); if (DEBUG) { Object.defineProperty(result, '_repr_', { value: `${result[Symbol.toStringTag]} <${TemporalYearMonthToString(result)}>`, writable: false, enumerable: false, configurable: false }); } } export function CreateTemporalYearMonth( isoYear: number, isoMonth: number, calendar: Temporal.CalendarProtocol = GetISO8601Calendar(), referenceISODay = 1 ) { const TemporalPlainYearMonth = GetIntrinsic('%Temporal.PlainYearMonth%'); const result = ObjectCreate(TemporalPlainYearMonth.prototype); CreateTemporalYearMonthSlots(result, isoYear, isoMonth, calendar, referenceISODay); return result; } export function CreateTemporalZonedDateTimeSlots( result: Temporal.ZonedDateTime, epochNanoseconds: JSBI, timeZone: Temporal.TimeZoneProtocol, calendar: Temporal.CalendarProtocol ) { ValidateEpochNanoseconds(epochNanoseconds); CreateSlots(result); SetSlot(result, EPOCHNANOSECONDS, epochNanoseconds); SetSlot(result, TIME_ZONE, timeZone); SetSlot(result, CALENDAR, calendar); const TemporalInstant = GetIntrinsic('%Temporal.Instant%'); const instant = new TemporalInstant(GetSlot(result, EPOCHNANOSECONDS)); SetSlot(result, INSTANT, instant); if (DEBUG) { Object.defineProperty(result, '_repr_', { value: `${result[Symbol.toStringTag]} <${TemporalZonedDateTimeToString(result, 'auto')}>`, writable: false, enumerable: false, configurable: false }); } } export function CreateTemporalZonedDateTime( epochNanoseconds: JSBI, timeZone: Temporal.TimeZoneProtocol, calendar: Temporal.CalendarProtocol = GetISO8601Calendar() ) { const TemporalZonedDateTime = GetIntrinsic('%Temporal.ZonedDateTime%'); const result = ObjectCreate(TemporalZonedDateTime.prototype); CreateTemporalZonedDateTimeSlots(result, epochNanoseconds, timeZone, calendar); return result; } export function GetISO8601Calendar() { const TemporalCalendar = GetIntrinsic('%Temporal.Calendar%'); return new TemporalCalendar('iso8601'); } // TODO: should (can?) we make this generic so the field names are checked // against the type that the calendar is a property of? export function CalendarFields<F extends Iterable<string>>(calendar: Temporal.CalendarProtocol, fieldNamesParam: F) { let fieldNames = fieldNamesParam; if (calendar.fields) { fieldNames = calendar.fields(fieldNames) as F; } const result: string[] = []; for (const name of fieldNames) { if (typeof name !== 'string') throw new TypeError('bad return from calendar.fields()'); ArrayPrototypePush.call(result, name); } return result as unknown as F; } export function CalendarMergeFields( calendar: Temporal.CalendarProtocol, fields: Record<string, unknown>, additionalFields: Record<string, unknown> ) { const calMergeFields = calendar.mergeFields; if (!calMergeFields) { return { ...fields, ...additionalFields }; } const result = Reflect.apply(calMergeFields, calendar, [fields, additionalFields]); if (!IsObject(result)) throw new TypeError('bad return from calendar.mergeFields()'); return result; } export function CalendarDateAdd( calendar: Temporal.CalendarProtocol, date: CalendarProtocolParams['dateAdd'][0], duration: CalendarProtocolParams['dateAdd'][1], options: CalendarProtocolParams['dateAdd'][2], dateAddParam?: Temporal.CalendarProtocol['dateAdd'] ) { let dateAdd = dateAddParam; if (dateAdd === undefined) { dateAdd = calendar.dateAdd; } const result = ReflectApply(dateAdd, calendar, [date, duration, options]); if (!IsTemporalDate(result)) throw new TypeError('invalid result'); return result; } export function CalendarDateUntil( calendar: Temporal.CalendarProtocol, date: CalendarProtocolParams['dateUntil'][0], otherDate: CalendarProtocolParams['dateUntil'][1], options: CalendarProtocolParams['dateUntil'][2], dateUntilParam?: Temporal.CalendarProtocol['dateUntil'] ) { let dateUntil = dateUntilParam; if (dateUntil === undefined) { dateUntil = calendar.dateUntil; } const result = ReflectApply(dateUntil, calendar, [date, otherDate, options]); if (!IsTemporalDuration(result)) throw new TypeError('invalid result'); return result; } export function CalendarYear(calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['year'][0]) { const result = calendar.year(dateLike); if (result === undefined) { throw new RangeError('calendar year result must be an integer'); } return ToIntegerThrowOnInfinity(result); } export function CalendarMonth(calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['month'][0]) { const result = calendar.month(dateLike); if (result === undefined) { throw new RangeError('calendar month result must be a positive integer'); } return ToPositiveInteger(result); } export function CalendarMonthCode( calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['monthCode'][0] ) { const result = calendar.monthCode(dateLike); if (result === undefined) { throw new RangeError('calendar monthCode result must be a string'); } return ToString(result); } export function CalendarDay(calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['day'][0]) { const result = calendar.day(dateLike); if (result === undefined) { throw new RangeError('calendar day result must be a positive integer'); } return ToPositiveInteger(result); } export function CalendarEra(calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['era'][0]) { let result = calendar.era(dateLike); if (result !== undefined) { result = ToString(result); } return result; } export function CalendarEraYear(calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['eraYear'][0]) { let result = calendar.eraYear(dateLike); if (result !== undefined) { result = ToIntegerThrowOnInfinity(result); } return result; } export function CalendarDayOfWeek( calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['dayOfWeek'][0] ) { return calendar.dayOfWeek(dateLike); } export function CalendarDayOfYear( calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['dayOfYear'][0] ) { return calendar.dayOfYear(dateLike); } export function CalendarWeekOfYear( calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['weekOfYear'][0] ) { return calendar.weekOfYear(dateLike); } export function CalendarDaysInWeek( calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['daysInWeek'][0] ) { return calendar.daysInWeek(dateLike); } export function CalendarDaysInMonth( calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['daysInMonth'][0] ) { return calendar.daysInMonth(dateLike); } export function CalendarDaysInYear( calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['daysInYear'][0] ) { return calendar.daysInYear(dateLike); } export function CalendarMonthsInYear( calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['monthsInYear'][0] ) { return calendar.monthsInYear(dateLike); } export function CalendarInLeapYear( calendar: Temporal.CalendarProtocol, dateLike: CalendarProtocolParams['inLeapYear'][0] ) { return calendar.inLeapYear(dateLike); } export function ToTemporalCalendar(calendarLikeParam: CalendarParams['from'][0]) { let calendarLike = calendarLikeParam; if (IsObject(calendarLike)) { if (HasSlot(calendarLike, CALENDAR)) return GetSlot(calendarLike, CALENDAR); if (!('calendar' in calendarLike)) return calendarLike; calendarLike = (calendarLike as unknown as { calendar: string | Temporal.CalendarProtocol }).calendar; if (IsObject(calendarLike) && !('calendar' in calendarLike)) return calendarLike; } const identifier = ToString(calendarLike); const TemporalCalendar = GetIntrinsic('%Temporal.Calendar%'); if (IsBuiltinCalendar(identifier)) return new TemporalCalendar(identifier); let calendar; try { ({ calendar } = ParseISODateTime(identifier)); } catch { throw new RangeError(`Invalid calendar: ${identifier}`); } if (!calendar) calendar = 'iso8601'; return new TemporalCalendar(calendar); } function GetTemporalCalendarWithISODefault( item: Temporal.CalendarProtocol | { calendar?: Temporal.PlainDateLike['calendar'] } ): Temporal.Calendar | Temporal.CalendarProtocol { if (HasSlot(item, CALENDAR)) return GetSlot(item, CALENDAR); const { calendar } = item as Exclude<typeof item, Temporal.CalendarProtocol>; if (calendar === undefined) return GetISO8601Calendar(); return ToTemporalCalendar(calendar); } export function CalendarEquals(one: Temporal.CalendarProtocol, two: Temporal.CalendarProtocol) { if (one === two) return true; const cal1 = ToString(one); const cal2 = ToString(two); return cal1 === cal2; } export function ConsolidateCalendars(one: Temporal.CalendarProtocol, two: Temporal.CalendarProtocol) { if (one === two) return two; const sOne = ToString(one); const sTwo = ToString(two); if (sOne === sTwo || sOne === 'iso8601') { return two; } else if (sTwo === 'iso8601') { return one; } else { throw new RangeError('irreconcilable calendars'); } } export function DateFromFields( calendar: Temporal.CalendarProtocol, fields: CalendarProtocolParams['dateFromFields'][0], options?: Partial<CalendarProtocolParams['dateFromFields'][1]> ) { const result = calendar.dateFromFields(fields, options); if (!IsTemporalDate(result)) throw new TypeError('invalid result'); return result; } export function YearMonthFromFields( calendar: Temporal.CalendarProtocol, fields: CalendarProtocolParams['yearMonthFromFields'][0], options?: CalendarProtocolParams['yearMonthFromFields'][1] ) { const result = calendar.yearMonthFromFields(fields, options); if (!IsTemporalYearMonth(result)) throw new TypeError('invalid result'); return result; } export function MonthDayFromFields( calendar: Temporal.CalendarProtocol, fields: CalendarProtocolParams['monthDayFromFields'][0], options?: CalendarProtocolParams['monthDayFromFields'][1] ) { const result = calendar.monthDayFromFields(fields, options); if (!IsTemporalMonthDay(result)) throw new TypeError('invalid result'); return result; } export function ToTemporalTimeZone(temporalTimeZoneLikeParam: TimeZoneParams['from'][0]) { let temporalTimeZoneLike = temporalTimeZoneLikeParam; if (IsObject(temporalTimeZoneLike)) { if (IsTemporalZonedDateTime(temporalTimeZoneLike)) return GetSlot(temporalTimeZoneLike, TIME_ZONE); if (!('timeZone' in temporalTimeZoneLike)) return temporalTimeZoneLike; temporalTimeZoneLike = (temporalTimeZoneLike as unknown as { timeZone: typeof temporalTimeZoneLike }).timeZone; if (IsObject(temporalTimeZoneLike) && !('timeZone' in temporalTimeZoneLike)) { return temporalTimeZoneLike; } } const identifier = ToString(temporalTimeZoneLike); const timeZone = ParseTemporalTimeZone(identifier); const TemporalTimeZone = GetIntrinsic('%Temporal.TimeZone%'); return new TemporalTimeZone(timeZone); } export function TimeZoneEquals(one: Temporal.TimeZoneProtocol, two: Temporal.TimeZoneProtocol) { if (one === two) return true; const tz1 = ToString(one); const tz2 = ToString(two); return tz1 === tz2; } export function TemporalDateTimeToDate(dateTime: Temporal.PlainDateTime) { return CreateTemporalDate( GetSlot(dateTime, ISO_YEAR), GetSlot(dateTime, ISO_MONTH), GetSlot(dateTime, ISO_DAY), GetSlot(dateTime, CALENDAR) ); } export function TemporalDateTimeToTime(dateTime: Temporal.PlainDateTime) { const Time = GetIntrinsic('%Temporal.PlainTime%'); return new Time( GetSlot(dateTime, ISO_HOUR), GetSlot(dateTime, ISO_MINUTE), GetSlot(dateTime, ISO_SECOND), GetSlot(dateTime, ISO_MILLISECOND), GetSlot(dateTime, ISO_MICROSECOND), GetSlot(dateTime, ISO_NANOSECOND) ); } export function GetOffsetNanosecondsFor( timeZone: Temporal.TimeZoneProtocol, instant: TimeZoneProtocolParams['getOffsetNanosecondsFor'][0] ) { let getOffsetNanosecondsFor = timeZone.getOffsetNanosecondsFor; if (typeof getOffsetNanosecondsFor !== 'function') { throw new TypeError('getOffsetNanosecondsFor not callable'); } const offsetNs = Reflect.apply(getOffsetNanosecondsFor, timeZone, [instant]); if (typeof offsetNs !== 'number') { throw new TypeError('bad return from getOffsetNanosecondsFor'); } if (!IsInteger(offsetNs) || MathAbs(offsetNs) > 86400e9) { throw new RangeError('out-of-range return from getOffsetNanosecondsFor'); } return offsetNs; } export function BuiltinTimeZoneGetOffsetStringFor(timeZone: Temporal.TimeZoneProtocol, instant: Temporal.Instant) { const offsetNs = GetOffsetNanosecondsFor(timeZone, instant); return FormatTimeZoneOffsetString(offsetNs); } export function BuiltinTimeZoneGetPlainDateTimeFor( timeZone: Temporal.TimeZoneProtocol, instant: Temporal.Instant, calendar: Temporal.CalendarProtocol ) { const ns = GetSlot(instant, EPOCHNANOSECONDS); const offsetNs = GetOffsetNanosecondsFor(timeZone, instant); let { year, month, day, hour, minute, second, millisecond, microsecond, nanosecond } = GetISOPartsFromEpoch(ns); ({ year, month, day, hour, minute, second, millisecond, microsecond, nanosecond } = BalanceISODateTime( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond + offsetNs )); return CreateTemporalDateTime(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, calendar); } export function BuiltinTimeZoneGetInstantFor( timeZone: Temporal.TimeZoneProtocol, dateTime: Temporal.PlainDateTime, disambiguation: NonNullable<Temporal.ToInstantOptions['disambiguation']> ) { const possibleInstants = GetPossibleInstantsFor(timeZone, dateTime); return DisambiguatePossibleInstants(possibleInstants, timeZone, dateTime, disambiguation); } function DisambiguatePossibleInstants( possibleInstants: Temporal.Instant[], timeZone: Temporal.TimeZoneProtocol, dateTime: Temporal.PlainDateTime, disambiguation: NonNullable<Temporal.ToInstantOptions['disambiguation']> ) { const Instant = GetIntrinsic('%Temporal.Instant%'); const numInstants = possibleInstants.length; if (numInstants === 1) return possibleInstants[0]; if (numInstants) { switch (disambiguation) { case 'compatible': // fall through because 'compatible' means 'earlier' for "fall back" transitions case 'earlier': return possibleInstants[0]; case 'later': return possibleInstants[numInstants - 1]; case 'reject': { throw new RangeError('multiple instants found'); } } } const year = GetSlot(dateTime, ISO_YEAR); const month = GetSlot(dateTime, ISO_MONTH); const day = GetSlot(dateTime, ISO_DAY); const hour = GetSlot(dateTime, ISO_HOUR); const minute = GetSlot(dateTime, ISO_MINUTE); const second = GetSlot(dateTime, ISO_SECOND); const millisecond = GetSlot(dateTime, ISO_MILLISECOND); const microsecond = GetSlot(dateTime, ISO_MICROSECOND); const nanosecond = GetSlot(dateTime, ISO_NANOSECOND); const utcns = GetEpochFromISOParts(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond); if (utcns === null) throw new RangeError('DateTime outside of supported range'); const dayBefore = new Instant(JSBI.subtract(utcns, DAY_NANOS)); const dayAfter = new Instant(JSBI.add(utcns, DAY_NANOS)); const offsetBefore = GetOffsetNanosecondsFor(timeZone, dayBefore); const offsetAfter = GetOffsetNanosecondsFor(timeZone, dayAfter); const nanoseconds = offsetAfter - offsetBefore; switch (disambiguation) { case 'earlier': { const calendar = GetSlot(dateTime, CALENDAR); const PlainDateTime = GetIntrinsic('%Temporal.PlainDateTime%'); const earlier = AddDateTime( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, calendar, 0, 0, 0, 0, 0, 0, 0, 0, 0, -nanoseconds, undefined ); const earlierPlainDateTime = new PlainDateTime( earlier.year, earlier.month, earlier.day, earlier.hour, earlier.minute, earlier.second, earlier.millisecond, earlier.microsecond, earlier.nanosecond, calendar ); return GetPossibleInstantsFor(timeZone, earlierPlainDateTime)[0]; } case 'compatible': // fall through because 'compatible' means 'later' for "spring forward" transitions case 'later': { const calendar = GetSlot(dateTime, CALENDAR); const PlainDateTime = GetIntrinsic('%Temporal.PlainDateTime%'); const later = AddDateTime( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, calendar, 0, 0, 0, 0, 0, 0, 0, 0, 0, nanoseconds, undefined ); const laterPlainDateTime = new PlainDateTime( later.year, later.month, later.day, later.hour, later.minute, later.second, later.millisecond, later.microsecond, later.nanosecond, calendar ); const possible = GetPossibleInstantsFor(timeZone, laterPlainDateTime); return possible[possible.length - 1]; } case 'reject': { throw new RangeError('no such instant found'); } } } function GetPossibleInstantsFor( timeZone: Temporal.TimeZoneProtocol, dateTime: TimeZoneProtocolParams['getPossibleInstantsFor'][0] ) { const possibleInstants = timeZone.getPossibleInstantsFor(dateTime); const result: Temporal.Instant[] = []; for (const instant of possibleInstants) { if (!IsTemporalInstant(instant)) { throw new TypeError('bad return from getPossibleInstantsFor'); } ArrayPrototypePush.call(result, instant); } return result; } export function ISOYearString(year: number) { let yearString; if (year < 1000 || year > 9999) { const sign = year < 0 ? '-' : '+'; const yearNumber = MathAbs(year); yearString = sign + `000000${yearNumber}`.slice(-6); } else { yearString = `${year}`; } return yearString; } export function ISODateTimePartString(part: number) { return `00${part}`.slice(-2); } export function FormatSecondsStringPart( second: number, millisecond: number, microsecond: number, nanosecond: number, precision: ReturnType<typeof ToSecondsStringPrecision>['precision'] ) { if (precision === 'minute') return ''; const secs = `:${ISODateTimePartString(second)}`; let fractionNumber = millisecond * 1e6 + microsecond * 1e3 + nanosecond; let fraction: string; if (precision === 'auto') { if (fractionNumber === 0) return secs; fraction = `${fractionNumber}`.padStart(9, '0'); while (fraction[fraction.length - 1] === '0') fraction = fraction.slice(0, -1); } else { if (precision === 0) return secs; fraction = `${fractionNumber}`.padStart(9, '0').slice(0, precision); } return `${secs}.${fraction}`; } export function TemporalInstantToString( instant: Temporal.Instant, timeZone: Temporal.TimeZoneProtocol | undefined, precision: ReturnType<typeof ToSecondsStringPrecision>['precision'] ) { let outputTimeZone = timeZone; if (outputTimeZone === undefined) { const TemporalTimeZone = GetIntrinsic('%Temporal.TimeZone%'); outputTimeZone = new TemporalTimeZone('UTC'); } const iso = GetISO8601Calendar(); const dateTime = BuiltinTimeZoneGetPlainDateTimeFor(outputTimeZone, instant, iso); const year = ISOYearString(GetSlot(dateTime, ISO_YEAR)); const month = ISODateTimePartString(GetSlot(dateTime, ISO_MONTH)); const day = ISODateTimePartString(GetSlot(dateTime, ISO_DAY)); const hour = ISODateTimePartString(GetSlot(dateTime, ISO_HOUR)); const minute = ISODateTimePartString(GetSlot(dateTime, ISO_MINUTE)); const seconds = FormatSecondsStringPart( GetSlot(dateTime, ISO_SECOND), GetSlot(dateTime, ISO_MILLISECOND), GetSlot(dateTime, ISO_MICROSECOND), GetSlot(dateTime, ISO_NANOSECOND), precision ); let timeZoneString = 'Z'; if (timeZone !== undefined) { const offsetNs = GetOffsetNanosecondsFor(outputTimeZone, instant); timeZoneString = FormatISOTimeZoneOffsetString(offsetNs); } return `${year}-${month}-${day}T${hour}:${minute}${seconds}${timeZoneString}`; } interface ToStringOptions { unit: ReturnType<typeof ToSecondsStringPrecision>['unit']; increment: number; roundingMode: ReturnType<typeof ToTemporalRoundingMode>; } export function TemporalDurationToString( duration: Temporal.Duration, precision: Temporal.ToStringPrecisionOptions['fractionalSecondDigits'] = 'auto', options: ToStringOptions | undefined = undefined ) { function formatNumber(num: number) { if (num <= NumberMaxSafeInteger) return num.toString(10); return JSBI.BigInt(num).toString(10); } const years = GetSlot(duration, YEARS); const months = GetSlot(duration, MONTHS); const weeks = GetSlot(duration, WEEKS); const days = GetSlot(duration, DAYS); const hours = GetSlot(duration, HOURS); const minutes = GetSlot(duration, MINUTES); let seconds = GetSlot(duration, SECONDS); let ms = GetSlot(duration, MILLISECONDS); let µs = GetSlot(duration, MICROSECONDS); let ns = GetSlot(duration, NANOSECONDS); const sign = DurationSign(years, months, weeks, days, hours, minutes, seconds, ms, µs, ns); if (options) { const { unit, increment, roundingMode } = options; ({ seconds, milliseconds: ms, microseconds: µs, nanoseconds: ns } = RoundDuration(0, 0, 0, 0, 0, 0, seconds, ms, µs, ns, increment, unit, roundingMode)); } const dateParts = []; if (years) dateParts.push(`${formatNumber(MathAbs(years))}Y`); if (months) dateParts.push(`${formatNumber(MathAbs(months))}M`); if (weeks) dateParts.push(`${formatNumber(MathAbs(weeks))}W`); if (days) dateParts.push(`${formatNumber(MathAbs(days))}D`); const timeParts = []; if (hours) timeParts.push(`${formatNumber(MathAbs(hours))}H`); if (minutes) timeParts.push(`${formatNumber(MathAbs(minutes))}M`); const secondParts = []; let total = TotalDurationNanoseconds(0, 0, 0, seconds, ms, µs, ns, 0); let nsBigInt: JSBI, µsBigInt: JSBI, msBigInt: JSBI, secondsBigInt: JSBI; ({ quotient: total, remainder: nsBigInt } = divmod(total, THOUSAND)); ({ quotient: total, remainder: µsBigInt } = divmod(total, THOUSAND)); ({ quotient: secondsBigInt, remainder: msBigInt } = divmod(total, THOUSAND)); const fraction = MathAbs(JSBI.toNumber(msBigInt)) * 1e6 + MathAbs(JSBI.toNumber(µsBigInt)) * 1e3 + MathAbs(JSBI.toNumber(nsBigInt)); let decimalPart; if (precision === 'auto') { if (fraction !== 0) { decimalPart = `${fraction}`.padStart(9, '0'); while (decimalPart[decimalPart.length - 1] === '0') { decimalPart = decimalPart.slice(0, -1); } } } else if (precision !== 0) { decimalPart = `${fraction}`.padStart(9, '0').slice(0, precision); } if (decimalPart) secondParts.unshift('.', decimalPart); if (!JSBI.equal(secondsBigInt, ZERO) || secondParts.length || precision !== 'auto') { secondParts.unshift(abs(secondsBigInt).toString()); } if (secondParts.length) timeParts.push(`${secondParts.join('')}S`); if (timeParts.length) timeParts.unshift('T'); if (!dateParts.length && !timeParts.length) return 'PT0S'; return `${sign < 0 ? '-' : ''}P${dateParts.join('')}${timeParts.join('')}`; } export function TemporalDateToString( date: Temporal.PlainDate, showCalendar: Temporal.ShowCalendarOption['calendarName'] = 'auto' ) { const year = ISOYearString(GetSlot(date, ISO_YEAR)); const month = ISODateTimePartString(GetSlot(date, ISO_MONTH)); const day = ISODateTimePartString(GetSlot(date, ISO_DAY)); const calendarID = ToString(GetSlot(date, CALENDAR)); const calendar = FormatCalendarAnnotation(calendarID, showCalendar); return `${year}-${month}-${day}${calendar}`; } export function TemporalDateTimeToString( dateTime: Temporal.PlainDateTime, precision: ReturnType<typeof ToSecondsStringPrecision>['precision'], showCalendar: ReturnType<typeof ToShowCalendarOption> = 'auto', options: ToStringOptions | undefined = undefined ) { let year = GetSlot(dateTime, ISO_YEAR); let month = GetSlot(dateTime, ISO_MONTH); let day = GetSlot(dateTime, ISO_DAY); let hour = GetSlot(dateTime, ISO_HOUR); let minute = GetSlot(dateTime, ISO_MINUTE); let second = GetSlot(dateTime, ISO_SECOND); let millisecond = GetSlot(dateTime, ISO_MILLISECOND); let microsecond = GetSlot(dateTime, ISO_MICROSECOND); let nanosecond = GetSlot(dateTime, ISO_NANOSECOND); if (options) { const { unit, increment, roundingMode } = options; ({ year, month, day, hour, minute, second, millisecond, microsecond, nanosecond } = RoundISODateTime( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, increment, unit, roundingMode )); } const yearString = ISOYearString(year); const monthString = ISODateTimePartString(month); const dayString = ISODateTimePartString(day); const hourString = ISODateTimePartString(hour); const minuteString = ISODateTimePartString(minute); const secondsString = FormatSecondsStringPart(second, millisecond, microsecond, nanosecond, precision); const calendarID = ToString(GetSlot(dateTime, CALENDAR)); const calendar = FormatCalendarAnnotation(calendarID, showCalendar); return `${yearString}-${monthString}-${dayString}T${hourString}:${minuteString}${secondsString}${calendar}`; } export function TemporalMonthDayToString( monthDay: Temporal.PlainMonthDay, showCalendar: Temporal.ShowCalendarOption['calendarName'] = 'auto' ) { const month = ISODateTimePartString(GetSlot(monthDay, ISO_MONTH)); const day = ISODateTimePartString(GetSlot(monthDay, ISO_DAY)); let resultString = `${month}-${day}`; const calendar = GetSlot(monthDay, CALENDAR); const calendarID = ToString(calendar); if (calendarID !== 'iso8601') { const year = ISOYearString(GetSlot(monthDay, ISO_YEAR)); resultString = `${year}-${resultString}`; } const calendarString = FormatCalendarAnnotation(calendarID, showCalendar); if (calendarString) resultString += calendarString; return resultString; } export function TemporalYearMonthToString( yearMonth: Temporal.PlainYearMonth, showCalendar: Temporal.ShowCalendarOption['calendarName'] = 'auto' ) { const year = ISOYearString(GetSlot(yearMonth, ISO_YEAR)); const month = ISODateTimePartString(GetSlot(yearMonth, ISO_MONTH)); let resultString = `${year}-${month}`; const calendar = GetSlot(yearMonth, CALENDAR); const calendarID = ToString(calendar); if (calendarID !== 'iso8601') { const day = ISODateTimePartString(GetSlot(yearMonth, ISO_DAY)); resultString += `-${day}`; } const calendarString = FormatCalendarAnnotation(calendarID, showCalendar); if (calendarString) resultString += calendarString; return resultString; } export function TemporalZonedDateTimeToString( zdt: Temporal.ZonedDateTime, precision: ReturnType<typeof ToSecondsStringPrecision>['precision'], showCalendar: ReturnType<typeof ToShowCalendarOption> = 'auto', showTimeZone: ReturnType<typeof ToShowTimeZoneNameOption> = 'auto', showOffset: ReturnType<typeof ToShowOffsetOption> = 'auto', options: ToStringOptions | undefined = undefined ) { let instant = GetSlot(zdt, INSTANT); if (options) { const { unit, increment, roundingMode } = options; const ns = RoundInstant(GetSlot(zdt, EPOCHNANOSECONDS), increment, unit, roundingMode); const TemporalInstant = GetIntrinsic('%Temporal.Instant%'); instant = new TemporalInstant(ns); } const tz = GetSlot(zdt, TIME_ZONE); const iso = GetISO8601Calendar(); const dateTime = BuiltinTimeZoneGetPlainDateTimeFor(tz, instant, iso); const year = ISOYearString(GetSlot(dateTime, ISO_YEAR)); const month = ISODateTimePartString(GetSlot(dateTime, ISO_MONTH)); const day = ISODateTimePartString(GetSlot(dateTime, ISO_DAY)); const hour = ISODateTimePartString(GetSlot(dateTime, ISO_HOUR)); const minute = ISODateTimePartString(GetSlot(dateTime, ISO_MINUTE)); const seconds = FormatSecondsStringPart( GetSlot(dateTime, ISO_SECOND), GetSlot(dateTime, ISO_MILLISECOND), GetSlot(dateTime, ISO_MICROSECOND), GetSlot(dateTime, ISO_NANOSECOND), precision ); let result = `${year}-${month}-${day}T${hour}:${minute}${seconds}`; if (showOffset !== 'never') { const offsetNs = GetOffsetNanosecondsFor(tz, instant); result += FormatISOTimeZoneOffsetString(offsetNs); } if (showTimeZone !== 'never') result += `[${tz}]`; const calendarID = ToString(GetSlot(zdt, CALENDAR)); result += FormatCalendarAnnotation(calendarID, showCalendar); return result; } export function TestTimeZoneOffsetString(string: string) { return OFFSET.test(StringCtor(string)); } export function ParseTimeZoneOffsetString(string: string): number { const match = OFFSET.exec(StringCtor(string)); if (!match) { throw new RangeError(`invalid time zone offset: ${string}`); } const sign = match[1] === '-' || match[1] === '\u2212' ? -1 : +1; const hours = +match[2]; const minutes = +(match[3] || 0); const seconds = +(match[4] || 0); const nanoseconds = +((match[5] || 0) + '000000000').slice(0, 9); return sign * (((hours * 60 + minutes) * 60 + seconds) * 1e9 + nanoseconds); } export function GetCanonicalTimeZoneIdentifier(timeZoneIdentifier: string): string { if (TestTimeZoneOffsetString(timeZoneIdentifier)) { const offsetNs = ParseTimeZoneOffsetString(timeZoneIdentifier); return FormatTimeZoneOffsetString(offsetNs); } const formatter = getIntlDateTimeFormatEnUsForTimeZone(StringCtor(timeZoneIdentifier)); return formatter.resolvedOptions().timeZone; } export function GetIANATimeZoneOffsetNanoseconds(epochNanoseconds: JSBI, id: string) { const { year, month, day, hour, minute, second, millisecond, microsecond, nanosecond } = GetIANATimeZoneDateTimeParts( epochNanoseconds, id ); const utc = GetEpochFromISOParts(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond); if (utc === null) throw new RangeError('Date outside of supported range'); return JSBI.toNumber(JSBI.subtract(utc, epochNanoseconds)); } function FormatTimeZoneOffsetString(offsetNanosecondsParam: number): string { const sign = offsetNanosecondsParam < 0 ? '-' : '+'; const offsetNanoseconds = MathAbs(offsetNanosecondsParam); const nanoseconds = offsetNanoseconds % 1e9; const seconds = MathFloor(offsetNanoseconds / 1e9) % 60; const minutes = MathFloor(offsetNanoseconds / 60e9) % 60; const hours = MathFloor(offsetNanoseconds / 3600e9); const hourString = ISODateTimePartString(hours); const minuteString = ISODateTimePartString(minutes); const secondString = ISODateTimePartString(seconds); let post = ''; if (nanoseconds) { let fraction = `${nanoseconds}`.padStart(9, '0'); while (fraction[fraction.length - 1] === '0') fraction = fraction.slice(0, -1); post = `:${secondString}.${fraction}`; } else if (seconds) { post = `:${secondString}`; } return `${sign}${hourString}:${minuteString}${post}`; } function FormatISOTimeZoneOffsetString(offsetNanosecondsParam: number): string { let offsetNanoseconds = JSBI.toNumber( RoundNumberToIncrement(JSBI.BigInt(offsetNanosecondsParam), 60e9, 'halfExpand') ); const sign = offsetNanoseconds < 0 ? '-' : '+'; offsetNanoseconds = MathAbs(offsetNanoseconds); const minutes = (offsetNanoseconds / 60e9) % 60; const hours = MathFloor(offsetNanoseconds / 3600e9); const hourString = ISODateTimePartString(hours); const minuteString = ISODateTimePartString(minutes); return `${sign}${hourString}:${minuteString}`; } export function GetEpochFromISOParts( year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, microsecond: number, nanosecond: number ) { // Note: Date.UTC() interprets one and two-digit years as being in the // 20th century, so don't use it const legacyDate = new Date(); legacyDate.setUTCHours(hour, minute, second, millisecond); legacyDate.setUTCFullYear(year, month - 1, day); const ms = legacyDate.getTime(); if (NumberIsNaN(ms)) return null; let ns = JSBI.multiply(JSBI.BigInt(ms), MILLION); ns = JSBI.add(ns, JSBI.multiply(JSBI.BigInt(microsecond), THOUSAND)); ns = JSBI.add(ns, JSBI.BigInt(nanosecond)); if (JSBI.lessThan(ns, NS_MIN) || JSBI.greaterThan(ns, NS_MAX)) return null; return ns; } function GetISOPartsFromEpoch(epochNanoseconds: JSBI) { const { quotient, remainder } = divmod(epochNanoseconds, MILLION); let epochMilliseconds = JSBI.toNumber(quotient); let nanos = JSBI.toNumber(remainder); if (nanos < 0) { nanos += 1e6; epochMilliseconds -= 1; } const microsecond = MathFloor(nanos / 1e3) % 1e3; const nanosecond = nanos % 1e3; const item = new Date(epochMilliseconds); const year = item.getUTCFullYear(); const month = item.getUTCMonth() + 1; const day = item.getUTCDate(); const hour = item.getUTCHours(); const minute = item.getUTCMinutes(); const second = item.getUTCSeconds(); const millisecond = item.getUTCMilliseconds(); return { epochMilliseconds, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond }; } // ts-prune-ignore-next TODO: remove this after tests are converted to TS export function GetIANATimeZoneDateTimeParts(epochNanoseconds: JSBI, id: string) { const { epochMilliseconds, millisecond, microsecond, nanosecond } = GetISOPartsFromEpoch(epochNanoseconds); const { year, month, day, hour, minute, second } = GetFormatterParts(id, epochMilliseconds); return BalanceISODateTime(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond); } export function GetIANATimeZoneNextTransition(epochNanoseconds: JSBI, id: string) { const uppercap = JSBI.add(SystemUTCEpochNanoSeconds(), JSBI.multiply(DAY_NANOS, JSBI.BigInt(366))); let leftNanos = epochNanoseconds; const leftOffsetNs = GetIANATimeZoneOffsetNanoseconds(leftNanos, id); let rightNanos = leftNanos; let rightOffsetNs = leftOffsetNs; while (leftOffsetNs === rightOffsetNs && JSBI.lessThan(JSBI.BigInt(leftNanos), uppercap)) { rightNanos = JSBI.add(leftNanos, JSBI.multiply(DAY_NANOS, JSBI.BigInt(2 * 7))); rightOffsetNs = GetIANATimeZoneOffsetNanoseconds(rightNanos, id); if (leftOffsetNs === rightOffsetNs) { leftNanos = rightNanos; } } if (leftOffsetNs === rightOffsetNs) return null; const result = bisect( (epochNs: JSBI) => GetIANATimeZoneOffsetNanoseconds(epochNs, id), leftNanos, rightNanos, leftOffsetNs, rightOffsetNs ); return result; } export function GetIANATimeZonePreviousTransition(epochNanoseconds: JSBI, id: string) { const lowercap = BEFORE_FIRST_DST; // 1847-01-01T00:00:00Z let rightNanos = JSBI.subtract(epochNanoseconds, ONE); const rightOffsetNs = GetIANATimeZoneOffsetNanoseconds(rightNanos, id); let leftNanos = rightNanos; let leftOffsetNs = rightOffsetNs; while (rightOffsetNs === leftOffsetNs && JSBI.greaterThan(rightNanos, lowercap)) { leftNanos = JSBI.subtract(rightNanos, JSBI.multiply(DAY_NANOS, JSBI.BigInt(2 * 7))); leftOffsetNs = GetIANATimeZoneOffsetNanoseconds(leftNanos, id); if (rightOffsetNs === leftOffsetNs) { rightNanos = leftNanos; } } if (rightOffsetNs === leftOffsetNs) return null; const result = bisect( (epochNs: JSBI) => GetIANATimeZoneOffsetNanoseconds(epochNs, id), leftNanos, rightNanos, leftOffsetNs, rightOffsetNs ); return result; } // ts-prune-ignore-next TODO: remove this after tests are converted to TS export function GetFormatterParts(timeZone: string, epochMilliseconds: number) { const formatter = getIntlDateTimeFormatEnUsForTimeZone(timeZone); // Using `format` instead of `formatToParts` for compatibility with older clients const datetime = formatter.format(new Date(epochMilliseconds)); const [month, day, year, era, hour, minute, second] = datetime.split(/[^\w]+/); return { year: era.toUpperCase().startsWith('B') ? -year + 1 : +year, month: +month, day: +day, hour: hour === '24' ? 0 : +hour, // bugs.chromium.org/p/chromium/issues/detail?id=1045791 minute: +minute, second: +second }; } export function GetIANATimeZoneEpochValue( id: string, year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, microsecond: number, nanosecond: number ) { const ns = GetEpochFromISOParts(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond); if (ns === null) throw new RangeError('DateTime outside of supported range'); let nsEarlier = JSBI.subtract(ns, DAY_NANOS); if (JSBI.lessThan(nsEarlier, NS_MIN)) nsEarlier = ns; let nsLater = JSBI.add(ns, DAY_NANOS); if (JSBI.greaterThan(nsLater, NS_MAX)) nsLater = ns; const earliest = GetIANATimeZoneOffsetNanoseconds(nsEarlier, id); const latest = GetIANATimeZoneOffsetNanoseconds(nsLater, id); const found = earliest === latest ? [earliest] : [earliest, latest]; return found .map((offsetNanoseconds) => { const epochNanoseconds = JSBI.subtract(ns, JSBI.BigInt(offsetNanoseconds)); const parts = GetIANATimeZoneDateTimeParts(epochNanoseconds, id); if ( year !== parts.year || month !== parts.month || day !== parts.day || hour !== parts.hour || minute !== parts.minute || second !== parts.second || millisecond !== parts.millisecond || microsecond !== parts.microsecond || nanosecond !== parts.nanosecond ) { return undefined; } return epochNanoseconds; }) .filter((x) => x !== undefined) as JSBI[]; } export function LeapYear(year: number) { if (undefined === year) return false; const isDiv4 = year % 4 === 0; const isDiv100 = year % 100 === 0; const isDiv400 = year % 400 === 0; return isDiv4 && (!isDiv100 || isDiv400); } export function ISODaysInMonth(year: number, month: number) { const DoM = { standard: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], leapyear: [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] }; return DoM[LeapYear(year) ? 'leapyear' : 'standard'][month - 1]; } export function DayOfWeek(year: number, month: number, day: number) { const m = month + (month < 3 ? 10 : -2); const Y = year - (month < 3 ? 1 : 0); const c = MathFloor(Y / 100); const y = Y - c * 100; const d = day; const pD = d; const pM = MathFloor(2.6 * m - 0.2); const pY = y + MathFloor(y / 4); const pC = MathFloor(c / 4) - 2 * c; const dow = (pD + pM + pY + pC) % 7; return dow + (dow <= 0 ? 7 : 0); } export function DayOfYear(year: number, month: number, day: number) { let days = day; for (let m = month - 1; m > 0; m--) { days += ISODaysInMonth(year, m); } return days; } export function WeekOfYear(year: number, month: number, day: number) { const doy = DayOfYear(year, month, day); const dow = DayOfWeek(year, month, day) || 7; const doj = DayOfWeek(year, 1, 1); const week = MathFloor((doy - dow + 10) / 7); if (week < 1) { if (doj === 5 || (doj === 6 && LeapYear(year - 1))) { return 53; } else { return 52; } } if (week === 53) { if ((LeapYear(year) ? 366 : 365) - doy < 4 - dow) { return 1; } } return week; } export function DurationSign( y: number, mon: number, w: number, d: number, h: number, min: number, s: number, ms: number, µs: number, ns: number ) { for (const prop of [y, mon, w, d, h, min, s, ms, µs, ns]) { if (prop !== 0) return prop < 0 ? -1 : 1; } return 0; } function BalanceISOYearMonth(yearParam: number, monthParam: number) { let year = yearParam; let month = monthParam; if (!NumberIsFinite(year) || !NumberIsFinite(month)) throw new RangeError('infinity is out of range'); month -= 1; year += MathFloor(month / 12); month %= 12; if (month < 0) month += 12; month += 1; return { year, month }; } function BalanceISODate(yearParam: number, monthParam: number, dayParam: number) { let year = yearParam; let month = monthParam; let day = dayParam; if (!NumberIsFinite(day)) throw new RangeError('infinity is out of range'); ({ year, month } = BalanceISOYearMonth(year, month)); let daysInYear = 0; let testYear = month > 2 ? year : year - 1; while (((daysInYear = LeapYear(testYear) ? 366 : 365), day < -daysInYear)) { year -= 1; testYear -= 1; day += daysInYear; } testYear += 1; while (((daysInYear = LeapYear(testYear) ? 366 : 365), day > daysInYear)) { year += 1; testYear += 1; day -= daysInYear; } while (day < 1) { ({ year, month } = BalanceISOYearMonth(year, month - 1)); day += ISODaysInMonth(year, month); } while (day > ISODaysInMonth(year, month)) { day -= ISODaysInMonth(year, month); ({ year, month } = BalanceISOYearMonth(year, month + 1)); } return { year, month, day }; } function BalanceISODateTime( yearParam: number, monthParam: number, dayParam: number, hourParam: number, minuteParam: number, secondParam: number, millisecondParam: number, microsecondParam: number, nanosecondParam: number ) { const { deltaDays, hour, minute, second, millisecond, microsecond, nanosecond } = BalanceTime( hourParam, minuteParam, secondParam, millisecondParam, microsecondParam, nanosecondParam ); const { year, month, day } = BalanceISODate(yearParam, monthParam, dayParam + deltaDays); return { year, month, day, hour, minute, second, millisecond, microsecond, nanosecond }; } function BalanceTime( hourParam: number, minuteParam: number, secondParam: number, millisecondParam: number, microsecondParam: number, nanosecondParam: number ) { let hour = hourParam; let minute = minuteParam; let second = secondParam; let millisecond = millisecondParam; let microsecond = microsecondParam; let nanosecond = nanosecondParam; if ( !NumberIsFinite(hour) || !NumberIsFinite(minute) || !NumberIsFinite(second) || !NumberIsFinite(millisecond) || !NumberIsFinite(microsecond) || !NumberIsFinite(nanosecond) ) { throw new RangeError('infinity is out of range'); } microsecond += MathFloor(nanosecond / 1000); nanosecond = NonNegativeModulo(nanosecond, 1000); millisecond += MathFloor(microsecond / 1000); microsecond = NonNegativeModulo(microsecond, 1000); second += MathFloor(millisecond / 1000); millisecond = NonNegativeModulo(millisecond, 1000); minute += MathFloor(second / 60); second = NonNegativeModulo(second, 60); hour += MathFloor(minute / 60); minute = NonNegativeModulo(minute, 60); const deltaDays = MathFloor(hour / 24); hour = NonNegativeModulo(hour, 24); return { deltaDays, hour, minute, second, millisecond, microsecond, nanosecond }; } export function TotalDurationNanoseconds( daysParam: number, hoursParam: number, minutesParam: number, secondsParam: number, millisecondsParam: number, microsecondsParam: number, nanosecondsParam: number, offsetShift: number ) { const days: JSBI = JSBI.BigInt(daysParam); let nanoseconds: JSBI = JSBI.BigInt(nanosecondsParam); if (daysParam !== 0) nanoseconds = JSBI.subtract(JSBI.BigInt(nanosecondsParam), JSBI.BigInt(offsetShift)); const hours = JSBI.add(JSBI.BigInt(hoursParam), JSBI.multiply(days, JSBI.BigInt(24))); const minutes = JSBI.add(JSBI.BigInt(minutesParam), JSBI.multiply(hours, SIXTY)); const seconds = JSBI.add(JSBI.BigInt(secondsParam), JSBI.multiply(minutes, SIXTY)); const milliseconds = JSBI.add(JSBI.BigInt(millisecondsParam), JSBI.multiply(seconds, THOUSAND)); const microseconds = JSBI.add(JSBI.BigInt(microsecondsParam), JSBI.multiply(milliseconds, THOUSAND)); return JSBI.add(JSBI.BigInt(nanoseconds), JSBI.multiply(microseconds, THOUSAND)); } function NanosecondsToDays(nanosecondsParam: JSBI, relativeTo: ReturnType<typeof ToRelativeTemporalObject>) { const TemporalInstant = GetIntrinsic('%Temporal.Instant%'); const sign = MathSign(JSBI.toNumber(nanosecondsParam)); let nanoseconds = JSBI.BigInt(nanosecondsParam); let dayLengthNs = 86400e9; if (sign === 0) return { days: 0, nanoseconds: ZERO, dayLengthNs }; if (!IsTemporalZonedDateTime(relativeTo)) { let days: JSBI; ({ quotient: days, remainder: nanoseconds } = divmod(nanoseconds, JSBI.BigInt(dayLengthNs))); return { days: JSBI.toNumber(days), nanoseconds, dayLengthNs }; } const startNs = GetSlot(relativeTo, EPOCHNANOSECONDS); const start = GetSlot(relativeTo, INSTANT); const endNs = JSBI.add(startNs, nanoseconds); const end = new TemporalInstant(endNs); const timeZone = GetSlot(relativeTo, TIME_ZONE); const calendar = GetSlot(relativeTo, CALENDAR); // Find the difference in days only. const dtStart = BuiltinTimeZoneGetPlainDateTimeFor(timeZone, start, calendar); const dtEnd = BuiltinTimeZoneGetPlainDateTimeFor(timeZone, end, calendar); let { days } = DifferenceISODateTime( GetSlot(dtStart, ISO_YEAR), GetSlot(dtStart, ISO_MONTH), GetSlot(dtStart, ISO_DAY), GetSlot(dtStart, ISO_HOUR), GetSlot(dtStart, ISO_MINUTE), GetSlot(dtStart, ISO_SECOND), GetSlot(dtStart, ISO_MILLISECOND), GetSlot(dtStart, ISO_MICROSECOND), GetSlot(dtStart, ISO_NANOSECOND), GetSlot(dtEnd, ISO_YEAR), GetSlot(dtEnd, ISO_MONTH), GetSlot(dtEnd, ISO_DAY), GetSlot(dtEnd, ISO_HOUR), GetSlot(dtEnd, ISO_MINUTE), GetSlot(dtEnd, ISO_SECOND), GetSlot(dtEnd, ISO_MILLISECOND), GetSlot(dtEnd, ISO_MICROSECOND), GetSlot(dtEnd, ISO_NANOSECOND), calendar, 'day' ); let intermediateNs = AddZonedDateTime(start, timeZone, calendar, 0, 0, 0, days, 0, 0, 0, 0, 0, 0); // may disambiguate // If clock time after addition was in the middle of a skipped period, the // endpoint was disambiguated to a later clock time. So it's possible that // the resulting disambiguated result is later than endNs. If so, then back // up one day and try again. Repeat if necessary (some transitions are // > 24 hours) until either there's zero days left or the date duration is // back inside the period where it belongs. Note that this case only can // happen for positive durations because the only direction that // `disambiguation: 'compatible'` can change clock time is forwards. if (sign === 1) { while (days > 0 && JSBI.greaterThan(intermediateNs, endNs)) { --days; intermediateNs = AddZonedDateTime(start, timeZone, calendar, 0, 0, 0, days, 0, 0, 0, 0, 0, 0); // may do disambiguation } } nanoseconds = JSBI.subtract(endNs, intermediateNs); let isOverflow = false; let relativeInstant = new TemporalInstant(intermediateNs); do { // calculate length of the next day (day that contains the time remainder) const oneDayFartherNs = AddZonedDateTime(relativeInstant, timeZone, calendar, 0, 0, 0, sign, 0, 0, 0, 0, 0, 0); const relativeNs = GetSlot(relativeInstant, EPOCHNANOSECONDS); dayLengthNs = JSBI.toNumber(JSBI.subtract(oneDayFartherNs, relativeNs)); isOverflow = JSBI.greaterThan( JSBI.multiply(JSBI.subtract(nanoseconds, JSBI.BigInt(dayLengthNs)), JSBI.BigInt(sign)), ZERO ); if (isOverflow) { nanoseconds = JSBI.subtract(nanoseconds, JSBI.BigInt(dayLengthNs)); relativeInstant = new TemporalInstant(oneDayFartherNs); days += sign; } } while (isOverflow); return { days, nanoseconds, dayLengthNs: MathAbs(dayLengthNs) }; } export function BalanceDuration( daysParam: number, hoursParam: number, minutesParam: number, secondsParam: number, millisecondsParam: number, microsecondsParam: number, nanosecondsParam: number, largestUnit: ReturnType<typeof ToLargestTemporalUnit>, relativeTo: ReturnType<typeof ToRelativeTemporalObject> = undefined ) { let days = daysParam; let nanosecondsBigInt: JSBI, microsecondsBigInt: JSBI, millisecondsBigInt: JSBI, secondsBigInt: JSBI, minutesBigInt: JSBI, hoursBigInt: JSBI; if (IsTemporalZonedDateTime(relativeTo)) { const endNs = AddZonedDateTime( GetSlot(relativeTo, INSTANT), GetSlot(relativeTo, TIME_ZONE), GetSlot(relativeTo, CALENDAR), 0, 0, 0, days, hoursParam, minutesParam, secondsParam, millisecondsParam, microsecondsParam, nanosecondsParam ); const startNs = GetSlot(relativeTo, EPOCHNANOSECONDS); nanosecondsBigInt = JSBI.subtract(endNs, startNs); } else { nanosecondsBigInt = TotalDurationNanoseconds( days, hoursParam, minutesParam, secondsParam, millisecondsParam, microsecondsParam, nanosecondsParam, 0 ); } if (largestUnit === 'year' || largestUnit === 'month' || largestUnit === 'week' || largestUnit === 'day') { ({ days, nanoseconds: nanosecondsBigInt } = NanosecondsToDays(nanosecondsBigInt, relativeTo)); } else { days = 0; } const sign = JSBI.lessThan(nanosecondsBigInt, ZERO) ? -1 : 1; nanosecondsBigInt = abs(nanosecondsBigInt); microsecondsBigInt = millisecondsBigInt = secondsBigInt = minutesBigInt = hoursBigInt = ZERO; switch (largestUnit) { case 'year': case 'month': case 'week': case 'day': case 'hour': ({ quotient: microsecondsBigInt, remainder: nanosecondsBigInt } = divmod(nanosecondsBigInt, THOUSAND)); ({ quotient: millisecondsBigInt, remainder: microsecondsBigInt } = divmod(microsecondsBigInt, THOUSAND)); ({ quotient: secondsBigInt, remainder: millisecondsBigInt } = divmod(millisecondsBigInt, THOUSAND)); ({ quotient: minutesBigInt, remainder: secondsBigInt } = divmod(secondsBigInt, SIXTY)); ({ quotient: hoursBigInt, remainder: minutesBigInt } = divmod(minutesBigInt, SIXTY)); break; case 'minute': ({ quotient: microsecondsBigInt, remainder: nanosecondsBigInt } = divmod(nanosecondsBigInt, THOUSAND)); ({ quotient: millisecondsBigInt, remainder: microsecondsBigInt } = divmod(microsecondsBigInt, THOUSAND)); ({ quotient: secondsBigInt, remainder: millisecondsBigInt } = divmod(millisecondsBigInt, THOUSAND)); ({ quotient: minutesBigInt, remainder: secondsBigInt } = divmod(secondsBigInt, SIXTY)); break; case 'second': ({ quotient: microsecondsBigInt, remainder: nanosecondsBigInt } = divmod(nanosecondsBigInt, THOUSAND)); ({ quotient: millisecondsBigInt, remainder: microsecondsBigInt } = divmod(microsecondsBigInt, THOUSAND)); ({ quotient: secondsBigInt, remainder: millisecondsBigInt } = divmod(millisecondsBigInt, THOUSAND)); break; case 'millisecond': ({ quotient: microsecondsBigInt, remainder: nanosecondsBigInt } = divmod(nanosecondsBigInt, THOUSAND)); ({ quotient: millisecondsBigInt, remainder: microsecondsBigInt } = divmod(microsecondsBigInt, THOUSAND)); break; case 'microsecond': ({ quotient: microsecondsBigInt, remainder: nanosecondsBigInt } = divmod(nanosecondsBigInt, THOUSAND)); break; case 'nanosecond': break; default: throw new Error('assert not reached'); } const hours = JSBI.toNumber(hoursBigInt) * sign; const minutes = JSBI.toNumber(minutesBigInt) * sign; const seconds = JSBI.toNumber(secondsBigInt) * sign; const milliseconds = JSBI.toNumber(millisecondsBigInt) * sign; const microseconds = JSBI.toNumber(microsecondsBigInt) * sign; const nanoseconds = JSBI.toNumber(nanosecondsBigInt) * sign; return { days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds }; } export function UnbalanceDurationRelative( yearsParam: number, monthsParam: number, weeksParam: number, daysParam: number, largestUnit: ReturnType<typeof ToLargestTemporalUnit>, relativeToParam: ReturnType<typeof ToRelativeTemporalObject> ) { let years = yearsParam; let months = monthsParam; let weeks = weeksParam; let days = daysParam; const TemporalDuration = GetIntrinsic('%Temporal.Duration%'); const sign = DurationSign(years, months, weeks, days, 0, 0, 0, 0, 0, 0); let calendar; let relativeTo: Temporal.PlainDate | undefined; if (relativeToParam) { relativeTo = ToTemporalDate(relativeToParam); calendar = GetSlot(relativeTo, CALENDAR); } const oneYear = new TemporalDuration(sign); const oneMonth = new TemporalDuration(0, sign); const oneWeek = new TemporalDuration(0, 0, sign); switch (largestUnit) { case 'year': // no-op break; case 'month': { if (!calendar) throw new RangeError('a starting point is required for months balancing'); // balance years down to months const dateAdd = calendar.dateAdd; const dateUntil = calendar.dateUntil; let relativeToDateOnly: Temporal.PlainDateLike = relativeTo as Temporal.PlainDateLike; while (MathAbs(years) > 0) { const addOptions = ObjectCreate(null); const newRelativeTo = CalendarDateAdd(calendar, relativeToDateOnly, oneYear, addOptions, dateAdd); const untilOptions = ObjectCreate(null); untilOptions.largestUnit = 'month'; const untilResult = CalendarDateUntil(calendar, relativeToDateOnly, newRelativeTo, untilOptions, dateUntil); const oneYearMonths = GetSlot(untilResult, MONTHS); relativeToDateOnly = newRelativeTo; months += oneYearMonths; years -= sign; } } break; case 'week': if (!calendar) throw new RangeError('a starting point is required for weeks balancing'); // balance years down to days while (MathAbs(years) > 0) { let oneYearDays; ({ relativeTo, days: oneYearDays } = MoveRelativeDate(calendar, relativeTo as Temporal.PlainDate, oneYear)); days += oneYearDays; years -= sign; } // balance months down to days while (MathAbs(months) > 0) { let oneMonthDays; ({ relativeTo, days: oneMonthDays } = MoveRelativeDate(calendar, relativeTo as Temporal.PlainDate, oneMonth)); days += oneMonthDays; months -= sign; } break; default: // balance years down to days while (MathAbs(years) > 0) { if (!calendar) throw new RangeError('a starting point is required for balancing calendar units'); let oneYearDays; ({ relativeTo, days: oneYearDays } = MoveRelativeDate(calendar, relativeTo as Temporal.PlainDate, oneYear)); days += oneYearDays; years -= sign; } // balance months down to days while (MathAbs(months) > 0) { if (!calendar) throw new RangeError('a starting point is required for balancing calendar units'); let oneMonthDays; ({ relativeTo, days: oneMonthDays } = MoveRelativeDate(calendar, relativeTo as Temporal.PlainDate, oneMonth)); days += oneMonthDays; months -= sign; } // balance weeks down to days while (MathAbs(weeks) > 0) { if (!calendar) throw new RangeError('a starting point is required for balancing calendar units'); let oneWeekDays; ({ relativeTo, days: oneWeekDays } = MoveRelativeDate(calendar, relativeTo as Temporal.PlainDate, oneWeek)); days += oneWeekDays; weeks -= sign; } break; } return { years, months, weeks, days }; } export function BalanceDurationRelative( yearsParam: number, monthsParam: number, weeksParam: number, daysParam: number, largestUnit: ReturnType<typeof ToLargestTemporalUnit>, relativeToParam: ReturnType<typeof ToRelativeTemporalObject> ) { let years = yearsParam; let months = monthsParam; let weeks = weeksParam; let days = daysParam; const TemporalDuration = GetIntrinsic('%Temporal.Duration%'); const sign = DurationSign(years, months, weeks, days, 0, 0, 0, 0, 0, 0); if (sign === 0) return { years, months, weeks, days }; let calendar; let relativeTo: Temporal.PlainDate | undefined; if (relativeToParam) { relativeTo = ToTemporalDate(relativeToParam); calendar = GetSlot(relativeTo, CALENDAR); } const oneYear = new TemporalDuration(sign); const oneMonth = new TemporalDuration(0, sign); const oneWeek = new TemporalDuration(0, 0, sign); switch (largestUnit) { case 'year': { if (!calendar) throw new RangeError('a starting point is required for years balancing'); // balance days up to years let newRelativeTo, oneYearDays; ({ relativeTo: newRelativeTo, days: oneYearDays } = MoveRelativeDate( calendar, relativeTo as Temporal.PlainDate, oneYear )); while (MathAbs(days) >= MathAbs(oneYearDays)) { days -= oneYearDays; years += sign; relativeTo = newRelativeTo; ({ relativeTo: newRelativeTo, days: oneYearDays } = MoveRelativeDate(calendar, relativeTo, oneYear)); } // balance days up to months let oneMonthDays; ({ relativeTo: newRelativeTo, days: oneMonthDays } = MoveRelativeDate( calendar, relativeTo as Temporal.PlainDate, oneMonth )); while (MathAbs(days) >= MathAbs(oneMonthDays)) { days -= oneMonthDays; months += sign; relativeTo = newRelativeTo; ({ relativeTo: newRelativeTo, days: oneMonthDays } = MoveRelativeDate(calendar, relativeTo, oneMonth)); } // balance months up to years const dateAdd = calendar.dateAdd; const addOptions = ObjectCreate(null); newRelativeTo = CalendarDateAdd(calendar, relativeTo as Temporal.PlainDate, oneYear, addOptions, dateAdd); const dateUntil = calendar.dateUntil; const untilOptions = ObjectCreate(null); untilOptions.largestUnit = 'month'; let untilResult = CalendarDateUntil( calendar, relativeTo as Temporal.PlainDate, newRelativeTo, untilOptions, dateUntil ); let oneYearMonths = GetSlot(untilResult, MONTHS); while (MathAbs(months) >= MathAbs(oneYearMonths)) { months -= oneYearMonths; years += sign; relativeTo = newRelativeTo; const addOptions = ObjectCreate(null); newRelativeTo = CalendarDateAdd(calendar, relativeTo, oneYear, addOptions, dateAdd); const untilOptions = ObjectCreate(null); untilOptions.largestUnit = 'month'; untilResult = CalendarDateUntil(calendar, relativeTo, newRelativeTo, untilOptions, dateUntil); oneYearMonths = GetSlot(untilResult, MONTHS); } break; } case 'month': { if (!calendar) throw new RangeError('a starting point is required for months balancing'); // balance days up to months let newRelativeTo, oneMonthDays; ({ relativeTo: newRelativeTo, days: oneMonthDays } = MoveRelativeDate( calendar, relativeTo as Temporal.PlainDate, oneMonth )); while (MathAbs(days) >= MathAbs(oneMonthDays)) { days -= oneMonthDays; months += sign; relativeTo = newRelativeTo; ({ relativeTo: newRelativeTo, days: oneMonthDays } = MoveRelativeDate(calendar, relativeTo, oneMonth)); } break; } case 'week': { if (!calendar) throw new RangeError('a starting point is required for weeks balancing'); // balance days up to weeks let newRelativeTo, oneWeekDays; ({ relativeTo: newRelativeTo, days: oneWeekDays } = MoveRelativeDate( calendar, relativeTo as Temporal.PlainDate, oneWeek )); while (MathAbs(days) >= MathAbs(oneWeekDays)) { days -= oneWeekDays; weeks += sign; relativeTo = newRelativeTo; ({ relativeTo: newRelativeTo, days: oneWeekDays } = MoveRelativeDate(calendar, relativeTo, oneWeek)); } break; } default: // no-op break; } return { years, months, weeks, days }; } export function CalculateOffsetShift( relativeTo: ReturnType<typeof ToRelativeTemporalObject>, y: number, mon: number, w: number, d: number, h: number, min: number, s: number, ms: number, µs: number, ns: number ) { if (IsTemporalZonedDateTime(relativeTo)) { const instant = GetSlot(relativeTo, INSTANT); const timeZone = GetSlot(relativeTo, TIME_ZONE); const calendar = GetSlot(relativeTo, CALENDAR); const offsetBefore = GetOffsetNanosecondsFor(timeZone, instant); const after = AddZonedDateTime(instant, timeZone, calendar, y, mon, w, d, h, min, s, ms, µs, ns); const TemporalInstant = GetIntrinsic('%Temporal.Instant%'); const instantAfter = new TemporalInstant(after); const offsetAfter = GetOffsetNanosecondsFor(timeZone, instantAfter); return offsetAfter - offsetBefore; } return 0; } export function CreateNegatedTemporalDuration(duration: Temporal.Duration) { const TemporalDuration = GetIntrinsic('%Temporal.Duration%'); return new TemporalDuration( -GetSlot(duration, YEARS), -GetSlot(duration, MONTHS), -GetSlot(duration, WEEKS), -GetSlot(duration, DAYS), -GetSlot(duration, HOURS), -GetSlot(duration, MINUTES), -GetSlot(duration, SECONDS), -GetSlot(duration, MILLISECONDS), -GetSlot(duration, MICROSECONDS), -GetSlot(duration, NANOSECONDS) ); } export function ConstrainToRange(value: number | undefined, min: number, max: number) { // Math.Max accepts undefined values and returns NaN. Undefined values are // used for optional params in the method below. return MathMin(max, MathMax(min, value as number)); } function ConstrainISODate(year: number, monthParam: number, dayParam?: number) { const month = ConstrainToRange(monthParam, 1, 12); const day = ConstrainToRange(dayParam, 1, ISODaysInMonth(year, month)); return { year, month, day }; } function ConstrainTime( hourParam: number, minuteParam: number, secondParam: number, millisecondParam: number, microsecondParam: number, nanosecondParam: number ) { const hour = ConstrainToRange(hourParam, 0, 23); const minute = ConstrainToRange(minuteParam, 0, 59); const second = ConstrainToRange(secondParam, 0, 59); const millisecond = ConstrainToRange(millisecondParam, 0, 999); const microsecond = ConstrainToRange(microsecondParam, 0, 999); const nanosecond = ConstrainToRange(nanosecondParam, 0, 999); return { hour, minute, second, millisecond, microsecond, nanosecond }; } export function RejectToRange(value: number, min: number, max: number) { if (value < min || value > max) throw new RangeError(`value out of range: ${min} <= ${value} <= ${max}`); } function RejectISODate(year: number, month: number, day: number) { RejectToRange(month, 1, 12); RejectToRange(day, 1, ISODaysInMonth(year, month)); } function RejectDateRange(year: number, month: number, day: number) { // Noon avoids trouble at edges of DateTime range (excludes midnight) RejectDateTimeRange(year, month, day, 12, 0, 0, 0, 0, 0); } export function RejectTime( hour: number, minute: number, second: number, millisecond: number, microsecond: number, nanosecond: number ) { RejectToRange(hour, 0, 23); RejectToRange(minute, 0, 59); RejectToRange(second, 0, 59); RejectToRange(millisecond, 0, 999); RejectToRange(microsecond, 0, 999); RejectToRange(nanosecond, 0, 999); } function RejectDateTime( year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, microsecond: number, nanosecond: number ) { RejectISODate(year, month, day); RejectTime(hour, minute, second, millisecond, microsecond, nanosecond); } function RejectDateTimeRange( year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, microsecond: number, nanosecond: number ) { RejectToRange(year, YEAR_MIN, YEAR_MAX); // Reject any DateTime 24 hours or more outside the Instant range if ( (year === YEAR_MIN && null == GetEpochFromISOParts(year, month, day + 1, hour, minute, second, millisecond, microsecond, nanosecond - 1)) || (year === YEAR_MAX && null == GetEpochFromISOParts(year, month, day - 1, hour, minute, second, millisecond, microsecond, nanosecond + 1)) ) { throw new RangeError('DateTime outside of supported range'); } } export function ValidateEpochNanoseconds(epochNanoseconds: JSBI) { if (JSBI.lessThan(epochNanoseconds, NS_MIN) || JSBI.greaterThan(epochNanoseconds, NS_MAX)) { throw new RangeError('Instant outside of supported range'); } } function RejectYearMonthRange(year: number, month: number) { RejectToRange(year, YEAR_MIN, YEAR_MAX); if (year === YEAR_MIN) { RejectToRange(month, 4, 12); } else if (year === YEAR_MAX) { RejectToRange(month, 1, 9); } } function RejectDuration( y: number, mon: number, w: number, d: number, h: number, min: number, s: number, ms: number, µs: number, ns: number ) { const sign = DurationSign(y, mon, w, d, h, min, s, ms, µs, ns); for (const prop of [y, mon, w, d, h, min, s, ms, µs, ns]) { if (!NumberIsFinite(prop)) throw new RangeError('infinite values not allowed as duration fields'); const propSign = MathSign(prop); if (propSign !== 0 && propSign !== sign) throw new RangeError('mixed-sign values not allowed as duration fields'); } } export function DifferenceISODate<Allowed extends Temporal.DateTimeUnit>( y1: number, m1: number, d1: number, y2: number, m2: number, d2: number, largestUnit: Allowed ) { switch (largestUnit) { case 'year': case 'month': { const sign = -CompareISODate(y1, m1, d1, y2, m2, d2); if (sign === 0) return { years: 0, months: 0, weeks: 0, days: 0 }; const start = { year: y1, month: m1, day: d1 }; const end = { year: y2, month: m2, day: d2 }; let years = end.year - start.year; let mid = AddISODate(y1, m1, d1, years, 0, 0, 0, 'constrain'); let midSign = -CompareISODate(mid.year, mid.month, mid.day, y2, m2, d2); if (midSign === 0) { return largestUnit === 'year' ? { years, months: 0, weeks: 0, days: 0 } : { years: 0, months: years * 12, weeks: 0, days: 0 }; } let months = end.month - start.month; if (midSign !== sign) { years -= sign; months += sign * 12; } mid = AddISODate(y1, m1, d1, years, months, 0, 0, 'constrain'); midSign = -CompareISODate(mid.year, mid.month, mid.day, y2, m2, d2); if (midSign === 0) { return largestUnit === 'year' ? { years, months, weeks: 0, days: 0 } : { years: 0, months: months + years * 12, weeks: 0, days: 0 }; } if (midSign !== sign) { // The end date is later in the month than mid date (or earlier for // negative durations). Back up one month. months -= sign; if (months === -sign) { years -= sign; months = 11 * sign; } mid = AddISODate(y1, m1, d1, years, months, 0, 0, 'constrain'); midSign = -CompareISODate(y1, m1, d1, mid.year, mid.month, mid.day); } let days = 0; // If we get here, months and years are correct (no overflow), and `mid` // is within the range from `start` to `end`. To count the days between // `mid` and `end`, there are 3 cases: // 1) same month: use simple subtraction // 2) end is previous month from intermediate (negative duration) // 3) end is next month from intermediate (positive duration) if (mid.month === end.month) { // 1) same month: use simple subtraction days = end.day - mid.day; } else if (sign < 0) { // 2) end is previous month from intermediate (negative duration) // Example: intermediate: Feb 1, end: Jan 30, DaysInMonth = 31, days = -2 days = -mid.day - (ISODaysInMonth(end.year, end.month) - end.day); } else { // 3) end is next month from intermediate (positive duration) // Example: intermediate: Jan 29, end: Feb 1, DaysInMonth = 31, days = 3 days = end.day + (ISODaysInMonth(mid.year, mid.month) - mid.day); } if (largestUnit === 'month') { months += years * 12; years = 0; } return { years, months, weeks: 0, days }; } case 'week': case 'day': { let larger, smaller, sign; if (CompareISODate(y1, m1, d1, y2, m2, d2) < 0) { smaller = { year: y1, month: m1, day: d1 }; larger = { year: y2, month: m2, day: d2 }; sign = 1; } else { smaller = { year: y2, month: m2, day: d2 }; larger = { year: y1, month: m1, day: d1 }; sign = -1; } let days = DayOfYear(larger.year, larger.month, larger.day) - DayOfYear(smaller.year, smaller.month, smaller.day); for (let year = smaller.year; year < larger.year; ++year) { days += LeapYear(year) ? 366 : 365; } let weeks = 0; if (largestUnit === 'week') { weeks = MathFloor(days / 7); days %= 7; } weeks *= sign; days *= sign; return { years: 0, months: 0, weeks, days }; } default: throw new Error('assert not reached'); } } export function DifferenceTime( h1: number, min1: number, s1: number, ms1: number, µs1: number, ns1: number, h2: number, min2: number, s2: number, ms2: number, µs2: number, ns2: number ) { let hours = h2 - h1; let minutes = min2 - min1; let seconds = s2 - s1; let milliseconds = ms2 - ms1; let microseconds = µs2 - µs1; let nanoseconds = ns2 - ns1; const sign = DurationSign(0, 0, 0, 0, hours, minutes, seconds, milliseconds, microseconds, nanoseconds); hours *= sign; minutes *= sign; seconds *= sign; milliseconds *= sign; microseconds *= sign; nanoseconds *= sign; let deltaDays = 0; ({ deltaDays, hour: hours, minute: minutes, second: seconds, millisecond: milliseconds, microsecond: microseconds, nanosecond: nanoseconds } = BalanceTime(hours, minutes, seconds, milliseconds, microseconds, nanoseconds)); deltaDays *= sign; hours *= sign; minutes *= sign; seconds *= sign; milliseconds *= sign; microseconds *= sign; nanoseconds *= sign; return { deltaDays, hours, minutes, seconds, milliseconds, microseconds, nanoseconds }; } export function DifferenceInstant( ns1: JSBI, ns2: JSBI, increment: number, unit: keyof typeof nsPerTimeUnit, roundingMode: Temporal.RoundingMode ) { const diff = JSBI.subtract(ns2, ns1); const remainder = JSBI.remainder(diff, JSBI.BigInt(86400e9)); const wholeDays = JSBI.subtract(diff, remainder); const roundedRemainder = RoundNumberToIncrement(remainder, nsPerTimeUnit[unit] * increment, roundingMode); const roundedDiff = JSBI.add(wholeDays, roundedRemainder); const nanoseconds = JSBI.toNumber(JSBI.remainder(roundedDiff, THOUSAND)); const microseconds = JSBI.toNumber(JSBI.remainder(JSBI.divide(roundedDiff, THOUSAND), THOUSAND)); const milliseconds = JSBI.toNumber(JSBI.remainder(JSBI.divide(roundedDiff, MILLION), THOUSAND)); const seconds = JSBI.toNumber(JSBI.divide(roundedDiff, BILLION)); return { seconds, milliseconds, microseconds, nanoseconds }; } export function DifferenceISODateTime( y1Param: number, mon1Param: number, d1Param: number, h1: number, min1: number, s1: number, ms1: number, µs1: number, ns1: number, y2: number, mon2: number, d2: number, h2: number, min2: number, s2: number, ms2: number, µs2: number, ns2: number, calendar: Temporal.CalendarProtocol, largestUnit: Temporal.DateTimeUnit, options = ObjectCreate(null) ) { let y1 = y1Param; let mon1 = mon1Param; let d1 = d1Param; let { deltaDays, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = DifferenceTime( h1, min1, s1, ms1, µs1, ns1, h2, min2, s2, ms2, µs2, ns2 ); const timeSign = DurationSign(0, 0, 0, deltaDays, hours, minutes, seconds, milliseconds, microseconds, nanoseconds); ({ year: y1, month: mon1, day: d1 } = BalanceISODate(y1, mon1, d1 + deltaDays)); const dateSign = CompareISODate(y2, mon2, d2, y1, mon1, d1); if (dateSign === -timeSign) { ({ year: y1, month: mon1, day: d1 } = BalanceISODate(y1, mon1, d1 - timeSign)); ({ hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = BalanceDuration( -timeSign, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, largestUnit )); } const date1 = CreateTemporalDate(y1, mon1, d1, calendar); const date2 = CreateTemporalDate(y2, mon2, d2, calendar); const dateLargestUnit = LargerOfTwoTemporalUnits('day', largestUnit); const untilOptions = { ...options, largestUnit: dateLargestUnit }; let { years, months, weeks, days } = CalendarDateUntil(calendar, date1, date2, untilOptions); // Signs of date part and time part may not agree; balance them together ({ days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = BalanceDuration( days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, largestUnit )); return { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds }; } export function DifferenceZonedDateTime( ns1: JSBI, ns2: JSBI, timeZone: Temporal.TimeZoneProtocol, calendar: Temporal.CalendarProtocol, largestUnit: Temporal.DateTimeUnit, options?: Temporal.DifferenceOptions<Temporal.DateTimeUnit> ) { const nsDiff = JSBI.subtract(ns2, ns1); if (JSBI.equal(nsDiff, ZERO)) { return { years: 0, months: 0, weeks: 0, days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds: 0, microseconds: 0, nanoseconds: 0 }; } // Find the difference in dates only. const TemporalInstant = GetIntrinsic('%Temporal.Instant%'); const start = new TemporalInstant(ns1); const end = new TemporalInstant(ns2); const dtStart = BuiltinTimeZoneGetPlainDateTimeFor(timeZone, start, calendar); const dtEnd = BuiltinTimeZoneGetPlainDateTimeFor(timeZone, end, calendar); let { years, months, weeks, days } = DifferenceISODateTime( GetSlot(dtStart, ISO_YEAR), GetSlot(dtStart, ISO_MONTH), GetSlot(dtStart, ISO_DAY), GetSlot(dtStart, ISO_HOUR), GetSlot(dtStart, ISO_MINUTE), GetSlot(dtStart, ISO_SECOND), GetSlot(dtStart, ISO_MILLISECOND), GetSlot(dtStart, ISO_MICROSECOND), GetSlot(dtStart, ISO_NANOSECOND), GetSlot(dtEnd, ISO_YEAR), GetSlot(dtEnd, ISO_MONTH), GetSlot(dtEnd, ISO_DAY), GetSlot(dtEnd, ISO_HOUR), GetSlot(dtEnd, ISO_MINUTE), GetSlot(dtEnd, ISO_SECOND), GetSlot(dtEnd, ISO_MILLISECOND), GetSlot(dtEnd, ISO_MICROSECOND), GetSlot(dtEnd, ISO_NANOSECOND), calendar, largestUnit, options ); const intermediateNs = AddZonedDateTime(start, timeZone, calendar, years, months, weeks, 0, 0, 0, 0, 0, 0, 0); // may disambiguate let timeRemainderNs = JSBI.subtract(ns2, intermediateNs); const intermediate = CreateTemporalZonedDateTime(intermediateNs, timeZone, calendar); ({ nanoseconds: timeRemainderNs, days } = NanosecondsToDays(timeRemainderNs, intermediate)); // Finally, merge the date and time durations and return the merged result. const { hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = BalanceDuration( 0, 0, 0, 0, 0, 0, JSBI.toNumber(timeRemainderNs), 'hour' ); return { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds }; } export function AddISODate( yearParam: number, monthParam: number, dayParam: number, yearsParam: number, monthsParam: number, weeksParam: number, daysParam: number, overflow: Temporal.ArithmeticOptions['overflow'] ) { let year = yearParam; let month = monthParam; let day = dayParam; let years = yearsParam; let months = monthsParam; let weeks = weeksParam; let days = daysParam; year += years; month += months; ({ year, month } = BalanceISOYearMonth(year, month)); ({ year, month, day } = RegulateISODate(year, month, day, overflow)); days += 7 * weeks; day += days; ({ year, month, day } = BalanceISODate(year, month, day)); return { year, month, day }; } export function AddTime( hourParam: number, minuteParam: number, secondParam: number, millisecondParam: number, microsecondParam: number, nanosecondParam: number, hours: number, minutes: number, seconds: number, milliseconds: number, microseconds: number, nanoseconds: number ) { let hour = hourParam; let minute = minuteParam; let second = secondParam; let millisecond = millisecondParam; let microsecond = microsecondParam; let nanosecond = nanosecondParam; hour += hours; minute += minutes; second += seconds; millisecond += milliseconds; microsecond += microseconds; nanosecond += nanoseconds; let deltaDays = 0; ({ deltaDays, hour, minute, second, millisecond, microsecond, nanosecond } = BalanceTime( hour, minute, second, millisecond, microsecond, nanosecond )); return { deltaDays, hour, minute, second, millisecond, microsecond, nanosecond }; } export function AddDuration( y1: number, mon1: number, w1: number, d1: number, h1: number, min1: number, s1: number, ms1: number, µs1: number, ns1: number, y2: number, mon2: number, w2: number, d2: number, h2: number, min2: number, s2: number, ms2: number, µs2: number, ns2: number, relativeTo: ReturnType<typeof ToRelativeTemporalObject> ) { const largestUnit1 = DefaultTemporalLargestUnit(y1, mon1, w1, d1, h1, min1, s1, ms1, µs1, ns1); const largestUnit2 = DefaultTemporalLargestUnit(y2, mon2, w2, d2, h2, min2, s2, ms2, µs2, ns2); const largestUnit = LargerOfTwoTemporalUnits(largestUnit1, largestUnit2); let years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds; if (!relativeTo) { if (largestUnit === 'year' || largestUnit === 'month' || largestUnit === 'week') { throw new RangeError('relativeTo is required for years, months, or weeks arithmetic'); } years = months = weeks = 0; ({ days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = BalanceDuration( d1 + d2, h1 + h2, min1 + min2, s1 + s2, ms1 + ms2, µs1 + µs2, ns1 + ns2, largestUnit )); } else if (IsTemporalDate(relativeTo)) { const TemporalDuration = GetIntrinsic('%Temporal.Duration%'); const calendar = GetSlot(relativeTo, CALENDAR); const dateDuration1 = new TemporalDuration(y1, mon1, w1, d1, 0, 0, 0, 0, 0, 0); const dateDuration2 = new TemporalDuration(y2, mon2, w2, d2, 0, 0, 0, 0, 0, 0); const dateAdd = calendar.dateAdd; const firstAddOptions = ObjectCreate(null); const intermediate = CalendarDateAdd(calendar, relativeTo, dateDuration1, firstAddOptions, dateAdd); const secondAddOptions = ObjectCreate(null); const end = CalendarDateAdd(calendar, intermediate, dateDuration2, secondAddOptions, dateAdd); const dateLargestUnit = LargerOfTwoTemporalUnits('day', largestUnit); const differenceOptions = ObjectCreate(null); differenceOptions.largestUnit = dateLargestUnit; ({ years, months, weeks, days } = CalendarDateUntil(calendar, relativeTo, end, differenceOptions)); // Signs of date part and time part may not agree; balance them together ({ days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = BalanceDuration( days, h1 + h2, min1 + min2, s1 + s2, ms1 + ms2, µs1 + µs2, ns1 + ns2, largestUnit )); } else { // relativeTo is a ZonedDateTime const TemporalInstant = GetIntrinsic('%Temporal.Instant%'); const timeZone = GetSlot(relativeTo, TIME_ZONE); const calendar = GetSlot(relativeTo, CALENDAR); const intermediateNs = AddZonedDateTime( GetSlot(relativeTo, INSTANT), timeZone, calendar, y1, mon1, w1, d1, h1, min1, s1, ms1, µs1, ns1 ); const endNs = AddZonedDateTime( new TemporalInstant(intermediateNs), timeZone, calendar, y2, mon2, w2, d2, h2, min2, s2, ms2, µs2, ns2 ); if (largestUnit !== 'year' && largestUnit !== 'month' && largestUnit !== 'week' && largestUnit !== 'day') { // The user is only asking for a time difference, so return difference of instants. years = 0; months = 0; weeks = 0; days = 0; ({ seconds, milliseconds, microseconds, nanoseconds } = DifferenceInstant( GetSlot(relativeTo, EPOCHNANOSECONDS), endNs, 1, 'nanosecond', 'halfExpand' )); ({ hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = BalanceDuration( 0, 0, 0, seconds, milliseconds, microseconds, nanoseconds, largestUnit )); } else { ({ years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = DifferenceZonedDateTime(GetSlot(relativeTo, EPOCHNANOSECONDS), endNs, timeZone, calendar, largestUnit)); } } RejectDuration(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds); return { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds }; } export function AddInstant( epochNanoseconds: JSBI, h: number, min: number, s: number, ms: number, µs: number, ns: number ) { let sum = ZERO; sum = JSBI.add(sum, JSBI.BigInt(ns)); sum = JSBI.add(sum, JSBI.multiply(JSBI.BigInt(µs), THOUSAND)); sum = JSBI.add(sum, JSBI.multiply(JSBI.BigInt(ms), MILLION)); sum = JSBI.add(sum, JSBI.multiply(JSBI.BigInt(s), BILLION)); sum = JSBI.add(sum, JSBI.multiply(JSBI.BigInt(min), JSBI.BigInt(60 * 1e9))); sum = JSBI.add(sum, JSBI.multiply(JSBI.BigInt(h), JSBI.BigInt(60 * 60 * 1e9))); const result = JSBI.add(epochNanoseconds, sum); ValidateEpochNanoseconds(result); return result; } export function AddDateTime( year: number, month: number, day: number, hourParam: number, minuteParam: number, secondParam: number, millisecondParam: number, microsecondParam: number, nanosecondParam: number, calendar: Temporal.CalendarProtocol, years: number, months: number, weeks: number, daysParam: number, hours: number, minutes: number, seconds: number, milliseconds: number, microseconds: number, nanoseconds: number, options?: Temporal.ArithmeticOptions ) { let days = daysParam; // Add the time part let { deltaDays, hour, minute, second, millisecond, microsecond, nanosecond } = AddTime( hourParam, minuteParam, secondParam, millisecondParam, microsecondParam, nanosecondParam, hours, minutes, seconds, milliseconds, microseconds, nanoseconds ); days += deltaDays; // Delegate the date part addition to the calendar const TemporalDuration = GetIntrinsic('%Temporal.Duration%'); const datePart = CreateTemporalDate(year, month, day, calendar); const dateDuration = new TemporalDuration(years, months, weeks, days, 0, 0, 0, 0, 0, 0); const addedDate = CalendarDateAdd(calendar, datePart, dateDuration, options); return { year: GetSlot(addedDate, ISO_YEAR), month: GetSlot(addedDate, ISO_MONTH), day: GetSlot(addedDate, ISO_DAY), hour, minute, second, millisecond, microsecond, nanosecond }; } export function AddZonedDateTime( instant: Temporal.Instant, timeZone: Temporal.TimeZoneProtocol, calendar: Temporal.CalendarProtocol, years: number, months: number, weeks: number, days: number, h: number, min: number, s: number, ms: number, µs: number, ns: number, options?: Temporal.ArithmeticOptions ) { // If only time is to be added, then use Instant math. It's not OK to fall // through to the date/time code below because compatible disambiguation in // the PlainDateTime=>Instant conversion will change the offset of any // ZonedDateTime in the repeated clock time after a backwards transition. // When adding/subtracting time units and not dates, this disambiguation is // not expected and so is avoided below via a fast path for time-only // arithmetic. // BTW, this behavior is similar in spirit to offset: 'prefer' in `with`. const TemporalDuration = GetIntrinsic('%Temporal.Duration%'); if (DurationSign(years, months, weeks, days, 0, 0, 0, 0, 0, 0) === 0) { return AddInstant(GetSlot(instant, EPOCHNANOSECONDS), h, min, s, ms, µs, ns); } // RFC 5545 requires the date portion to be added in calendar days and the // time portion to be added in exact time. const dt = BuiltinTimeZoneGetPlainDateTimeFor(timeZone, instant, calendar); const datePart = CreateTemporalDate(GetSlot(dt, ISO_YEAR), GetSlot(dt, ISO_MONTH), GetSlot(dt, ISO_DAY), calendar); const dateDuration = new TemporalDuration(years, months, weeks, days, 0, 0, 0, 0, 0, 0); const addedDate = CalendarDateAdd(calendar, datePart, dateDuration, options); const dtIntermediate = CreateTemporalDateTime( GetSlot(addedDate, ISO_YEAR), GetSlot(addedDate, ISO_MONTH), GetSlot(addedDate, ISO_DAY), GetSlot(dt, ISO_HOUR), GetSlot(dt, ISO_MINUTE), GetSlot(dt, ISO_SECOND), GetSlot(dt, ISO_MILLISECOND), GetSlot(dt, ISO_MICROSECOND), GetSlot(dt, ISO_NANOSECOND), calendar ); // Note that 'compatible' is used below because this disambiguation behavior // is required by RFC 5545. const instantIntermediate = BuiltinTimeZoneGetInstantFor(timeZone, dtIntermediate, 'compatible'); return AddInstant(GetSlot(instantIntermediate, EPOCHNANOSECONDS), h, min, s, ms, µs, ns); } function RoundNumberToIncrement(quantity: JSBI, increment: number, mode: Temporal.RoundingMode) { if (increment === 1) return quantity; let { quotient, remainder } = divmod(quantity, JSBI.BigInt(increment)); if (JSBI.equal(remainder, ZERO)) return quantity; const sign = JSBI.lessThan(remainder, ZERO) ? -1 : 1; switch (mode) { case 'ceil': if (sign > 0) quotient = JSBI.add(quotient, JSBI.BigInt(sign)); break; case 'floor': if (sign < 0) quotient = JSBI.add(quotient, JSBI.BigInt(sign)); break; case 'trunc': // no change needed, because divmod is a truncation break; case 'halfExpand': // "half up away from zero" if (JSBI.toNumber(abs(JSBI.multiply(remainder, JSBI.BigInt(2)))) >= increment) { quotient = JSBI.add(quotient, JSBI.BigInt(sign)); } break; } return JSBI.multiply(quotient, JSBI.BigInt(increment)); } export function RoundInstant( epochNs: JSBI, increment: number, unit: keyof typeof nsPerTimeUnit, roundingMode: Temporal.RoundingMode ) { // Note: NonNegativeModulo, but with BigInt let remainder = JSBI.remainder(epochNs, JSBI.BigInt(86400e9)); if (JSBI.lessThan(remainder, ZERO)) remainder = JSBI.add(remainder, JSBI.BigInt(86400e9)); const wholeDays = JSBI.subtract(epochNs, remainder); const roundedRemainder = RoundNumberToIncrement(remainder, nsPerTimeUnit[unit] * increment, roundingMode); return JSBI.add(wholeDays, roundedRemainder); } export function RoundISODateTime( yearParam: number, monthParam: number, dayParam: number, hourParam: number, minuteParam: number, secondParam: number, millisecondParam: number, microsecondParam: number, nanosecondParam: number, increment: number, unit: UnitSmallerThanOrEqualTo<'day'>, roundingMode: Temporal.RoundingMode, dayLengthNs = 86400e9 ) { const { deltaDays, hour, minute, second, millisecond, microsecond, nanosecond } = RoundTime( hourParam, minuteParam, secondParam, millisecondParam, microsecondParam, nanosecondParam, increment, unit, roundingMode, dayLengthNs ); const { year, month, day } = BalanceISODate(yearParam, monthParam, dayParam + deltaDays); return { year, month, day, hour, minute, second, millisecond, microsecond, nanosecond }; } export function RoundTime( hour: number, minute: number, second: number, millisecond: number, microsecond: number, nanosecond: number, increment: number, unit: keyof typeof nsPerTimeUnit | 'day', roundingMode: Temporal.RoundingMode, dayLengthNs = 86400e9 ) { let quantity = ZERO; switch (unit) { case 'day': case 'hour': quantity = JSBI.BigInt(hour); // fall through case 'minute': quantity = JSBI.add(JSBI.multiply(quantity, SIXTY), JSBI.BigInt(minute)); // fall through case 'second': quantity = JSBI.add(JSBI.multiply(quantity, SIXTY), JSBI.BigInt(second)); // fall through case 'millisecond': quantity = JSBI.add(JSBI.multiply(quantity, THOUSAND), JSBI.BigInt(millisecond)); // fall through case 'microsecond': quantity = JSBI.add(JSBI.multiply(quantity, THOUSAND), JSBI.BigInt(microsecond)); // fall through case 'nanosecond': quantity = JSBI.add(JSBI.multiply(quantity, THOUSAND), JSBI.BigInt(nanosecond)); } const nsPerUnit = unit === 'day' ? dayLengthNs : nsPerTimeUnit[unit]; const rounded = RoundNumberToIncrement(quantity, nsPerUnit * increment, roundingMode); const result = JSBI.toNumber(JSBI.divide(rounded, JSBI.BigInt(nsPerUnit))); switch (unit) { case 'day': return { deltaDays: result, hour: 0, minute: 0, second: 0, millisecond: 0, microsecond: 0, nanosecond: 0 }; case 'hour': return BalanceTime(result, 0, 0, 0, 0, 0); case 'minute': return BalanceTime(hour, result, 0, 0, 0, 0); case 'second': return BalanceTime(hour, minute, result, 0, 0, 0); case 'millisecond': return BalanceTime(hour, minute, second, result, 0, 0); case 'microsecond': return BalanceTime(hour, minute, second, millisecond, result, 0); case 'nanosecond': return BalanceTime(hour, minute, second, millisecond, microsecond, result); default: throw new Error(`Invalid unit ${unit}`); } } function DaysUntil( earlier: Temporal.PlainDate | Temporal.PlainDateTime | Temporal.ZonedDateTime, later: Temporal.PlainDate | Temporal.PlainDateTime | Temporal.ZonedDateTime ) { return DifferenceISODate( GetSlot(earlier, ISO_YEAR), GetSlot(earlier, ISO_MONTH), GetSlot(earlier, ISO_DAY), GetSlot(later, ISO_YEAR), GetSlot(later, ISO_MONTH), GetSlot(later, ISO_DAY), 'day' ).days; } function MoveRelativeDate( calendar: Temporal.CalendarProtocol, relativeToParam: NonNullable<ReturnType<typeof ToRelativeTemporalObject>>, duration: Temporal.Duration ) { const options = ObjectCreate(null); const later = CalendarDateAdd(calendar, relativeToParam, duration, options); const days = DaysUntil(relativeToParam, later); return { relativeTo: later, days }; } export function MoveRelativeZonedDateTime( relativeTo: Temporal.ZonedDateTime, years: number, months: number, weeks: number, days: number ) { const timeZone = GetSlot(relativeTo, TIME_ZONE); const calendar = GetSlot(relativeTo, CALENDAR); const intermediateNs = AddZonedDateTime( GetSlot(relativeTo, INSTANT), timeZone, calendar, years, months, weeks, days, 0, 0, 0, 0, 0, 0 ); return CreateTemporalZonedDateTime(intermediateNs, timeZone, calendar); } export function AdjustRoundedDurationDays( yearsParam: number, monthsParam: number, weeksParam: number, daysParam: number, hoursParam: number, minutesParam: number, secondsParam: number, millisecondsParam: number, microsecondsParam: number, nanosecondsParam: number, increment: number, unit: Temporal.DateTimeUnit, roundingMode: Temporal.RoundingMode, relativeTo: ReturnType<typeof ToRelativeTemporalObject> ) { let years = yearsParam; let months = monthsParam; let weeks = weeksParam; let days = daysParam; let hours = hoursParam; let minutes = minutesParam; let seconds = secondsParam; let milliseconds = millisecondsParam; let microseconds = microsecondsParam; let nanoseconds = nanosecondsParam; if ( !IsTemporalZonedDateTime(relativeTo) || unit === 'year' || unit === 'month' || unit === 'week' || unit === 'day' || (unit === 'nanosecond' && increment === 1) ) { return { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds }; } // There's one more round of rounding possible: if relativeTo is a // ZonedDateTime, the time units could have rounded up into enough hours // to exceed the day length. If this happens, grow the date part by a // single day and re-run exact time rounding on the smaller remainder. DO // NOT RECURSE, because once the extra hours are sucked up into the date // duration, there's no way for another full day to come from the next // round of rounding. And if it were possible (e.g. contrived calendar // with 30-minute-long "days") then it'd risk an infinite loop. let timeRemainderNs = TotalDurationNanoseconds( 0, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, 0 ); const direction = MathSign(JSBI.toNumber(timeRemainderNs)); const timeZone = GetSlot(relativeTo, TIME_ZONE); const calendar = GetSlot(relativeTo, CALENDAR); const dayStart = AddZonedDateTime( GetSlot(relativeTo, INSTANT), timeZone, calendar, years, months, weeks, days, 0, 0, 0, 0, 0, 0 ); const TemporalInstant = GetIntrinsic('%Temporal.Instant%'); const dayEnd = AddZonedDateTime( new TemporalInstant(dayStart), timeZone, calendar, 0, 0, 0, direction, 0, 0, 0, 0, 0, 0 ); const dayLengthNs = JSBI.subtract(dayEnd, dayStart); if ( JSBI.greaterThanOrEqual(JSBI.multiply(JSBI.subtract(timeRemainderNs, dayLengthNs), JSBI.BigInt(direction)), ZERO) ) { ({ years, months, weeks, days } = AddDuration( years, months, weeks, days, 0, 0, 0, 0, 0, 0, 0, 0, 0, direction, 0, 0, 0, 0, 0, 0, relativeTo )); timeRemainderNs = RoundInstant(JSBI.subtract(timeRemainderNs, dayLengthNs), increment, unit, roundingMode); ({ hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = BalanceDuration( 0, 0, 0, 0, 0, 0, JSBI.toNumber(timeRemainderNs), 'hour' )); } return { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds }; } export function RoundDuration( yearsParam: number, monthsParam: number, weeksParam: number, daysParam: number, hoursParam: number, minutesParam: number, secondsParam: number, millisecondsParam: number, microsecondsParam: number, nanosecondsParam: number, increment: number, unit: Temporal.DateTimeUnit, roundingMode: Temporal.RoundingMode, relativeToParam: ReturnType<typeof ToRelativeTemporalObject> = undefined ) { let years = yearsParam; let months = monthsParam; let weeks = weeksParam; let days = daysParam; let hours = hoursParam; let minutes = minutesParam; let seconds = secondsParam; let milliseconds = millisecondsParam; let microseconds = microsecondsParam; let nanoseconds = JSBI.BigInt(nanosecondsParam); const TemporalDuration = GetIntrinsic('%Temporal.Duration%'); let calendar, zdtRelative; // A cast is used below because relativeTo will be either PlainDate or // undefined for the rest of this long method (after any ZDT=>PlainDate // conversion below), and TS isn't smart enough to know that the type has // changed. See https://github.com/microsoft/TypeScript/issues/27706. let relativeTo = relativeToParam as Temporal.PlainDate | undefined; if (relativeTo) { if (IsTemporalZonedDateTime(relativeTo)) { zdtRelative = relativeTo; relativeTo = ToTemporalDate(relativeTo); } else if (!IsTemporalDate(relativeTo)) { throw new TypeError('starting point must be PlainDate or ZonedDateTime'); } calendar = GetSlot(relativeTo, CALENDAR); } // First convert time units up to days, if rounding to days or higher units. // If rounding relative to a ZonedDateTime, then some days may not be 24h. // TS doesn't know that `dayLengthNs` is only used if the unit is day or // larger. We'll cast away `undefined` when it's used lower down below. let dayLengthNs: JSBI | undefined; if (unit === 'year' || unit === 'month' || unit === 'week' || unit === 'day') { nanoseconds = TotalDurationNanoseconds(0, hours, minutes, seconds, milliseconds, microseconds, nanosecondsParam, 0); let intermediate; if (zdtRelative) { intermediate = MoveRelativeZonedDateTime(zdtRelative, years, months, weeks, days); } let deltaDays; let dayLength: number; ({ days: deltaDays, nanoseconds, dayLengthNs: dayLength } = NanosecondsToDays(nanoseconds, intermediate)); dayLengthNs = JSBI.BigInt(dayLength); days += deltaDays; hours = minutes = seconds = milliseconds = microseconds = 0; } let total: number; switch (unit) { case 'year': { if (!calendar) throw new RangeError('A starting point is required for years rounding'); // convert months and weeks to days by calculating difference( // relativeTo + years, relativeTo + { years, months, weeks }) const yearsDuration = new TemporalDuration(years); const dateAdd = calendar.dateAdd; const firstAddOptions = ObjectCreate(null); const yearsLater = CalendarDateAdd( calendar, relativeTo as Temporal.PlainDate, yearsDuration, firstAddOptions, dateAdd ); const yearsMonthsWeeks = new TemporalDuration(years, months, weeks); const secondAddOptions = ObjectCreate(null); const yearsMonthsWeeksLater = CalendarDateAdd( calendar, relativeTo as Temporal.PlainDate, yearsMonthsWeeks, secondAddOptions, dateAdd ); const monthsWeeksInDays = DaysUntil(yearsLater, yearsMonthsWeeksLater); relativeTo = yearsLater; days += monthsWeeksInDays; const thirdAddOptions = ObjectCreate(null); const daysLater = CalendarDateAdd(calendar, relativeTo, { days }, thirdAddOptions, dateAdd); const untilOptions = ObjectCreate(null); untilOptions.largestUnit = 'year'; const yearsPassed = CalendarDateUntil(calendar, relativeTo, daysLater, untilOptions).years; years += yearsPassed; const oldRelativeTo = relativeTo; const fourthAddOptions = ObjectCreate(null); relativeTo = CalendarDateAdd(calendar, relativeTo, { years: yearsPassed }, fourthAddOptions, dateAdd); const daysPassed = DaysUntil(oldRelativeTo, relativeTo); days -= daysPassed; const oneYear = new TemporalDuration(days < 0 ? -1 : 1); let { days: oneYearDays } = MoveRelativeDate(calendar, relativeTo, oneYear); // Note that `nanoseconds` below (here and in similar code for months, // weeks, and days further below) isn't actually nanoseconds for the // full date range. Instead, it's a BigInt representation of total // days multiplied by the number of nanoseconds in the last day of // the duration. This lets us do days-or-larger rounding using BigInt // math which reduces precision loss. oneYearDays = MathAbs(oneYearDays); // dayLengthNs is never undefined if unit is `day` or larger. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const divisor = JSBI.multiply(JSBI.BigInt(oneYearDays), dayLengthNs!); nanoseconds = JSBI.add( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion JSBI.add(JSBI.multiply(divisor, JSBI.BigInt(years)), JSBI.multiply(JSBI.BigInt(days), dayLengthNs!)), nanoseconds ); const rounded = RoundNumberToIncrement( nanoseconds, JSBI.toNumber(JSBI.multiply(divisor, JSBI.BigInt(increment))), roundingMode ); total = JSBI.toNumber(nanoseconds) / JSBI.toNumber(divisor); years = JSBI.toNumber(JSBI.divide(rounded, divisor)); nanoseconds = ZERO; months = weeks = days = 0; break; } case 'month': { if (!calendar) throw new RangeError('A starting point is required for months rounding'); // convert weeks to days by calculating difference(relativeTo + // { years, months }, relativeTo + { years, months, weeks }) const yearsMonths = new TemporalDuration(years, months); const dateAdd = calendar.dateAdd; const firstAddOptions = ObjectCreate(null); const yearsMonthsLater = CalendarDateAdd( calendar, relativeTo as Temporal.PlainDate, yearsMonths, firstAddOptions, dateAdd ); const yearsMonthsWeeks = new TemporalDuration(years, months, weeks); const secondAddOptions = ObjectCreate(null); const yearsMonthsWeeksLater = CalendarDateAdd( calendar, relativeTo as Temporal.PlainDate, yearsMonthsWeeks, secondAddOptions, dateAdd ); const weeksInDays = DaysUntil(yearsMonthsLater, yearsMonthsWeeksLater); relativeTo = yearsMonthsLater; days += weeksInDays; // Months may be different lengths of days depending on the calendar, // convert days to months in a loop as described above under 'years'. const sign = MathSign(days); const oneMonth = new TemporalDuration(0, days < 0 ? -1 : 1); let oneMonthDays: number; ({ relativeTo, days: oneMonthDays } = MoveRelativeDate(calendar, relativeTo, oneMonth)); while (MathAbs(days) >= MathAbs(oneMonthDays)) { months += sign; days -= oneMonthDays; ({ relativeTo, days: oneMonthDays } = MoveRelativeDate(calendar, relativeTo, oneMonth)); } oneMonthDays = MathAbs(oneMonthDays); // dayLengthNs is never undefined if unit is `day` or larger. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const divisor = JSBI.multiply(JSBI.BigInt(oneMonthDays), dayLengthNs!); nanoseconds = JSBI.add( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion JSBI.add(JSBI.multiply(divisor, JSBI.BigInt(months)), JSBI.multiply(JSBI.BigInt(days), dayLengthNs!)), nanoseconds ); const rounded = RoundNumberToIncrement( nanoseconds, JSBI.toNumber(JSBI.multiply(divisor, JSBI.BigInt(increment))), roundingMode ); total = JSBI.toNumber(nanoseconds) / JSBI.toNumber(divisor); months = JSBI.toNumber(JSBI.divide(rounded, divisor)); nanoseconds = ZERO; weeks = days = 0; break; } case 'week': { if (!calendar) throw new RangeError('A starting point is required for weeks rounding'); // Weeks may be different lengths of days depending on the calendar, // convert days to weeks in a loop as described above under 'years'. const sign = MathSign(days); const oneWeek = new TemporalDuration(0, 0, days < 0 ? -1 : 1); let oneWeekDays; ({ relativeTo, days: oneWeekDays } = MoveRelativeDate(calendar, relativeTo as Temporal.PlainDate, oneWeek)); while (MathAbs(days) >= MathAbs(oneWeekDays)) { weeks += sign; days -= oneWeekDays; ({ relativeTo, days: oneWeekDays } = MoveRelativeDate(calendar, relativeTo, oneWeek)); } oneWeekDays = MathAbs(oneWeekDays); // dayLengthNs is never undefined if unit is `day` or larger. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const divisor = JSBI.multiply(JSBI.BigInt(oneWeekDays), dayLengthNs!); nanoseconds = JSBI.add( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion JSBI.add(JSBI.multiply(divisor, JSBI.BigInt(weeks)), JSBI.multiply(JSBI.BigInt(days), dayLengthNs!)), nanoseconds ); const rounded = RoundNumberToIncrement( nanoseconds, JSBI.toNumber(JSBI.multiply(divisor, JSBI.BigInt(increment))), roundingMode ); total = JSBI.toNumber(nanoseconds) / JSBI.toNumber(divisor); weeks = JSBI.toNumber(JSBI.divide(rounded, divisor)); nanoseconds = ZERO; days = 0; break; } case 'day': { // dayLengthNs is never undefined if unit is `day` or larger. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const divisor = dayLengthNs!; nanoseconds = JSBI.add(JSBI.multiply(divisor, JSBI.BigInt(days)), nanoseconds); const rounded = RoundNumberToIncrement( nanoseconds, JSBI.toNumber(JSBI.multiply(divisor, JSBI.BigInt(increment))), roundingMode ); total = JSBI.toNumber(nanoseconds) / JSBI.toNumber(divisor); days = JSBI.toNumber(JSBI.divide(rounded, divisor)); nanoseconds = ZERO; break; } case 'hour': { const divisor = 3600e9; let allNanoseconds = JSBI.multiply(JSBI.BigInt(hours), JSBI.BigInt(3600e9)); allNanoseconds = JSBI.add(allNanoseconds, JSBI.multiply(JSBI.BigInt(minutes), JSBI.BigInt(60e9))); allNanoseconds = JSBI.add(allNanoseconds, JSBI.multiply(JSBI.BigInt(seconds), BILLION)); allNanoseconds = JSBI.add(allNanoseconds, JSBI.multiply(JSBI.BigInt(milliseconds), MILLION)); allNanoseconds = JSBI.add(allNanoseconds, JSBI.multiply(JSBI.BigInt(microseconds), THOUSAND)); allNanoseconds = JSBI.add(allNanoseconds, nanoseconds); total = JSBI.toNumber(allNanoseconds) / divisor; const rounded = RoundNumberToIncrement(allNanoseconds, divisor * increment, roundingMode); hours = JSBI.toNumber(JSBI.divide(rounded, JSBI.BigInt(divisor))); nanoseconds = ZERO; minutes = seconds = milliseconds = microseconds = 0; break; } case 'minute': { const divisor = 60e9; let allNanoseconds = JSBI.multiply(JSBI.BigInt(minutes), JSBI.BigInt(60e9)); allNanoseconds = JSBI.add(allNanoseconds, JSBI.multiply(JSBI.BigInt(seconds), BILLION)); allNanoseconds = JSBI.add(allNanoseconds, JSBI.multiply(JSBI.BigInt(milliseconds), MILLION)); allNanoseconds = JSBI.add(allNanoseconds, JSBI.multiply(JSBI.BigInt(microseconds), THOUSAND)); allNanoseconds = JSBI.add(allNanoseconds, nanoseconds); total = JSBI.toNumber(allNanoseconds) / divisor; const rounded = RoundNumberToIncrement(allNanoseconds, divisor * increment, roundingMode); minutes = JSBI.toNumber(JSBI.divide(rounded, JSBI.BigInt(divisor))); nanoseconds = ZERO; seconds = milliseconds = microseconds = 0; break; } case 'second': { const divisor = 1e9; let allNanoseconds = JSBI.multiply(JSBI.BigInt(seconds), BILLION); allNanoseconds = JSBI.add(allNanoseconds, JSBI.multiply(JSBI.BigInt(milliseconds), MILLION)); allNanoseconds = JSBI.add(allNanoseconds, JSBI.multiply(JSBI.BigInt(microseconds), THOUSAND)); allNanoseconds = JSBI.add(allNanoseconds, nanoseconds); total = JSBI.toNumber(allNanoseconds) / divisor; const rounded = RoundNumberToIncrement(allNanoseconds, divisor * increment, roundingMode); seconds = JSBI.toNumber(JSBI.divide(rounded, JSBI.BigInt(divisor))); nanoseconds = ZERO; milliseconds = microseconds = 0; break; } case 'millisecond': { const divisor = 1e6; let allNanoseconds = JSBI.multiply(JSBI.BigInt(milliseconds), MILLION); allNanoseconds = JSBI.add(allNanoseconds, JSBI.multiply(JSBI.BigInt(microseconds), THOUSAND)); allNanoseconds = JSBI.add(allNanoseconds, nanoseconds); total = JSBI.toNumber(allNanoseconds) / divisor; const rounded = RoundNumberToIncrement(allNanoseconds, divisor * increment, roundingMode); milliseconds = JSBI.toNumber(JSBI.divide(rounded, JSBI.BigInt(divisor))); nanoseconds = ZERO; microseconds = 0; break; } case 'microsecond': { const divisor = 1e3; let allNanoseconds = JSBI.multiply(JSBI.BigInt(microseconds), THOUSAND); allNanoseconds = JSBI.add(allNanoseconds, nanoseconds); total = JSBI.toNumber(allNanoseconds) / divisor; const rounded = RoundNumberToIncrement(allNanoseconds, divisor * increment, roundingMode); microseconds = JSBI.toNumber(JSBI.divide(rounded, JSBI.BigInt(divisor))); nanoseconds = ZERO; break; } case 'nanosecond': { total = JSBI.toNumber(nanoseconds); nanoseconds = RoundNumberToIncrement(nanoseconds, increment, roundingMode); break; } } return { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds: JSBI.toNumber(nanoseconds), total }; } export function CompareISODate(y1: number, m1: number, d1: number, y2: number, m2: number, d2: number) { for (const [x, y] of [ [y1, y2], [m1, m2], [d1, d2] ]) { if (x !== y) return ComparisonResult(x - y); } return 0; } function NonNegativeModulo(x: number, y: number) { let result = x % y; if (ObjectIs(result, -0)) return 0; if (result < 0) result += y; return result; } // Defaults to native bigint, or something "native bigint-like". // For users of Temporal that are running in environments without native BigInt, // the only guarantee we should give is that the returned object's toString will // return a string containing an accurate base 10 value of this bigint. This // form factor should correctly interop with other bigint compat libraries // easily. type ExternalBigInt = bigint; export function ToBigIntExternal(arg: unknown): ExternalBigInt { const jsbiBI = ToBigInt(arg); if (typeof (globalThis as any).BigInt !== 'undefined') return (globalThis as any).BigInt(jsbiBI.toString(10)); return jsbiBI as unknown as ExternalBigInt; } export function ToBigInt(arg: unknown): JSBI { if (arg instanceof JSBI) { return arg; } let prim = arg; if (typeof arg === 'object') { const toPrimFn = (arg as { [Symbol.toPrimitive]: unknown })[Symbol.toPrimitive]; if (toPrimFn && typeof toPrimFn === 'function') { prim = ReflectApply(toPrimFn, arg, ['number']); } } switch (typeof prim) { case 'undefined': case 'object': case 'number': case 'symbol': default: throw new TypeError(`cannot convert ${typeof arg} to bigint`); case 'string': if (!prim.match(/^\s*(?:[+-]?\d+\s*)?$/)) { throw new SyntaxError('invalid BigInt syntax'); } // eslint: no-fallthrough: false case 'bigint': try { return JSBI.BigInt((prim as bigint).toString()); } catch (e) { if (e instanceof Error && e.message.startsWith('Invalid integer')) throw new SyntaxError(e.message); throw e; } case 'boolean': if (prim) { return ONE; } else { return ZERO; } } } // Note: This method returns values with bogus nanoseconds based on the previous iteration's // milliseconds. That way there is a guarantee that the full nanoseconds are always going to be // increasing at least and that the microsecond and nanosecond fields are likely to be non-zero. export const SystemUTCEpochNanoSeconds: () => JSBI = (() => { let ns = JSBI.BigInt(Date.now() % 1e6); return () => { const ms = JSBI.BigInt(Date.now()); const result = JSBI.add(JSBI.multiply(ms, MILLION), ns); ns = JSBI.divide(ms, MILLION); if (JSBI.greaterThan(result, NS_MAX)) return NS_MAX; if (JSBI.lessThan(result, NS_MIN)) return NS_MIN; return result; }; })(); export function SystemTimeZone() { const fmt = new IntlDateTimeFormat('en-us'); const TemporalTimeZone = GetIntrinsic('%Temporal.TimeZone%'); return new TemporalTimeZone(ParseTemporalTimeZone(fmt.resolvedOptions().timeZone)); } export function ComparisonResult(value: number) { return value < 0 ? -1 : value > 0 ? 1 : (value as 0); } export function GetOptionsObject<T>(options: T) { if (options === undefined) return ObjectCreate(null) as NonNullable<T>; if (IsObject(options) && options !== null) return options; throw new TypeError(`Options parameter must be an object, not ${options === null ? 'null' : `${typeof options}`}`); } export function CreateOnePropObject<K extends string, V>(propName: K, propValue: V): { [k in K]: V } { const o = ObjectCreate(null); o[propName] = propValue; return o; } function GetOption<P extends string, O extends Partial<Record<P, unknown>>>( options: O, property: P, allowedValues: ReadonlyArray<O[P]>, fallback: undefined ): O[P]; function GetOption< P extends string, O extends Partial<Record<P, unknown>>, Fallback extends Required<O>[P] | undefined >( options: O, property: P, allowedValues: ReadonlyArray<O[P]>, fallback: Fallback ): Fallback extends undefined ? O[P] | undefined : Required<O>[P]; function GetOption< P extends string, O extends Partial<Record<P, unknown>>, Fallback extends Required<O>[P] | undefined >( options: O, property: P, allowedValues: ReadonlyArray<O[P]>, fallback: O[P] ): Fallback extends undefined ? O[P] | undefined : Required<O>[P] { let value = options[property]; if (value !== undefined) { value = ToString(value) as O[P]; if (!allowedValues.includes(value)) { throw new RangeError(`${property} must be one of ${allowedValues.join(', ')}, not ${value}`); } return value; } return fallback; } function GetNumberOption<P extends string, T extends Partial<Record<P, unknown>>>( options: T, property: P, minimum: number, maximum: number, fallback: number ): number { let valueRaw = options[property]; if (valueRaw === undefined) return fallback; const value = ToNumber(valueRaw); if (NumberIsNaN(value) || value < minimum || value > maximum) { throw new RangeError(`${property} must be between ${minimum} and ${maximum}, not ${value}`); } return MathFloor(value); } const OFFSET = new RegExp(`^${PARSE.offset.source}$`); function bisect( getState: (epochNs: JSBI) => number, leftParam: JSBI, rightParam: JSBI, lstateParam: number = getState(leftParam), rstateParam: number = getState(rightParam) ) { // This doesn't make much sense - why do these get converted unnecessarily? let left = JSBI.BigInt(leftParam); let right = JSBI.BigInt(rightParam); let lstate = lstateParam; let rstate = rstateParam; while (JSBI.greaterThan(JSBI.subtract(right, left), ONE)) { const middle = JSBI.divide(JSBI.add(left, right), JSBI.BigInt(2)); const mstate = getState(middle); if (mstate === lstate) { left = middle; lstate = mstate; } else if (mstate === rstate) { right = middle; rstate = mstate; } else { throw new Error(`invalid state in bisection ${lstate} - ${mstate} - ${rstate}`); } } return right; } const nsPerTimeUnit = { hour: 3600e9, minute: 60e9, second: 1e9, millisecond: 1e6, microsecond: 1e3, nanosecond: 1 };
the_stack
import assert from "assert" import crypto from "crypto" import { isEqual } from "lodash" import fs from "fs" import path from "path" import { v4 as uuid } from "uuid" import { getMissingChanges, applyChanges } from "./merge" import Micromerge, { ActorId, Change, Patch } from "../src/micromerge" import { generateDocs } from "./generateDocs" import { accumulatePatches } from "./accumulatePatches" function assertUnreachable(x: never): never { throw new Error("Didn't expect to get here" + x) } const saveFailedTrace = (data: unknown) => { const filename = `../traces/fail-${uuid()}.json` fs.writeFileSync(path.resolve(__dirname, filename), JSON.stringify(data)) console.log(`wrote failed trace to ${filename}`) } type OpTypes = "insert" | "remove" | "addMark" | "removeMark" const opTypes: OpTypes[] = ["insert", "remove", "addMark", "removeMark"] type MarkTypes = "strong" | "em" | "link" | "comment" const markTypes: MarkTypes[] = ["strong", "em", "link", "comment"] const exampleURLs = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("").map(letter => `${letter}.com`) const commentHistory: string[] = [] function addMarkChange(doc: Micromerge) { const length = (doc.root.text as string[]).length const startIndex = Math.floor(Math.random() * length) const endIndex = startIndex + Math.floor(Math.random() * (length - startIndex)) + 1 const markType = markTypes[Math.floor(Math.random() * markTypes.length)] // eslint-disable-next-line @typescript-eslint/no-explicit-any const sharedStuff: any = { path: ["text"], action: "addMark", startIndex, endIndex, markType, } if (markType === "link") { // pick one of the four urls we use to encourage adjacent matching spans const url = exampleURLs[Math.floor(Math.random() * exampleURLs.length)] return doc.change([ { ...sharedStuff, attrs: { url }, }, ]) } else if (markType === "comment") { // make a new comment ID and remember it so we can try removing it later const id = "comment-" + crypto.randomBytes(2).toString("hex") commentHistory.push(id) return doc.change([ { ...sharedStuff, attrs: { id }, }, ]) } else { return doc.change([sharedStuff]) } } function removeMarkChange(doc: Micromerge) { const length = (doc.root.text as unknown[]).length const startIndex = Math.floor(Math.random() * length) const endIndex = startIndex + Math.floor(Math.random() * (length - startIndex)) + 1 const markType = markTypes[Math.floor(Math.random() * markTypes.length)] // eslint-disable-next-line @typescript-eslint/no-explicit-any const sharedStuff: any = { path: ["text"], action: "addMark", startIndex, endIndex, markType, } if (markType === "link") { const url = exampleURLs[Math.floor(Math.random() * exampleURLs.length)] return doc.change([ { ...sharedStuff, attrs: { url }, // do we need a URL? }, ]) } else if (markType === "comment") { // note to gklitt: we should probably enumerate the existing comments, right now it just grows const id = commentHistory[Math.floor(Math.random() * commentHistory.length)] return doc.change([ { ...sharedStuff, attrs: { id }, }, ]) } else { return doc.change([sharedStuff]) } } const MAX_CHARS = 2 function insertChange(doc: Micromerge) { const length = (doc.root.text as unknown[]).length const index = Math.floor(Math.random() * length) const numChars = Math.floor(Math.random() * MAX_CHARS) const values = crypto.randomBytes(numChars).toString("hex").split("") return doc.change([ { path: ["text"], action: "insert", index, values, }, ]) } function removeChange(doc: Micromerge) { const length = (doc.root.text as unknown[]).length // gklitt: this appears to be a real bug! if you delete everything things go wonky const index = Math.floor(Math.random() * length) + 1 const count = Math.ceil(Math.random() * (length - index)) const { change, patches } = doc.change([ { path: ["text"], action: "delete", index, count, }, ]) return { change, patches } } function handleOp(op: OpTypes, doc: Micromerge): { change: Change; patches: Patch[] } { switch (op) { case "insert": return insertChange(doc) case "remove": return removeChange(doc) case "addMark": return addMarkChange(doc) case "removeMark": return removeMarkChange(doc) default: assertUnreachable(op) } } const { docs, patches: allPatches, initialChange } = generateDocs("ABCDE", 3) const docIds = docs.map(d => d.actorId) type SharedHistory = Record<ActorId, Change[]> export const queues: SharedHistory = {} docIds.forEach(id => (queues[id] = [])) queues["doc1"].push(initialChange) const syncs = [] // eslint-disable-next-line no-constant-condition while (true) { const randomTarget = Math.floor(Math.random() * docs.length) const doc = docs[randomTarget] const queue = queues[docIds[randomTarget]] const patchList = allPatches[randomTarget] const op = opTypes[Math.floor(Math.random() * opTypes.length)] const { change, patches } = handleOp(op, doc) queue.push(change) patchList.push(...patches) const shouldSync = true // (Math.random() < 0.2) if (shouldSync) { const left = Math.floor(Math.random() * docs.length) let right: number do { right = Math.floor(Math.random() * docs.length) } while (left == right) // console.log("merging", docs[left].actorId, docs[right].actorId) syncs.push({ left: docs[left].actorId, right: docs[right].actorId, missingLeft: getMissingChanges(docs[left], docs[right]), missingRight: getMissingChanges(docs[right], docs[left]), }) // console.log(util.inspect(getMissingChanges(docs[left], docs[right]), true, 10)) // console.log(util.inspect(getMissingChanges(docs[right], docs[left]), true, 10)) const rightPatches = applyChanges(docs[right], getMissingChanges(docs[left], docs[right])) const leftPatches = applyChanges(docs[left], getMissingChanges(docs[right], docs[left])) allPatches[right].push(...rightPatches) allPatches[left].push(...leftPatches) const leftText = docs[left].getTextWithFormatting(["text"]) const rightText = docs[right].getTextWithFormatting(["text"]) if (!isEqual(accumulatePatches(allPatches[left]), leftText)) { console.log(`de-sync with ${allPatches[left].length} patches`) saveFailedTrace({ docId: docs[left].actorId, patchDoc: accumulatePatches(allPatches[left]), batchDoc: leftText, // @ts-ignore -- reach into private metadata, it's fine for this purpose meta: docs[left].metadata["1@doc1"].map(item => ({ ...item, // show mark op sets as arrays in JSON markOpsBefore: item.markOpsBefore && [...item.markOpsBefore], markOpsAfter: item.markOpsAfter && [...item.markOpsAfter], })), patches: allPatches[left], queues, syncs, }) } if (!isEqual(accumulatePatches(allPatches[right]), rightText)) { console.log(`de-sync with ${allPatches[right].length} patches`) saveFailedTrace({ docId: docs[right].actorId, patchDoc: accumulatePatches(allPatches[right]), batchDoc: rightText, // @ts-ignore -- reach into private metadata, it's fine for this purpose meta: docs[right].metadata["1@doc1"].map(item => ({ ...item, // show mark op sets as arrays in JSON markOpsBefore: item.markOpsBefore && [...item.markOpsBefore], markOpsAfter: item.markOpsAfter && [...item.markOpsAfter], })), patches: allPatches[right], queues, syncs, }) } assert.deepStrictEqual(accumulatePatches(allPatches[right]), rightText) assert.deepStrictEqual(accumulatePatches(allPatches[left]), leftText) if (!isEqual(leftText, rightText)) { saveFailedTrace({ queues, left: { doc: docs[left].actorId, text: leftText, // @ts-ignore -- reach into private metadata, it's fine for this purpose meta: docs[left].metadata["1@doc1"].map(item => ({ ...item, // show mark op sets as arrays in JSON markOpsBefore: item.markOpsBefore && [...item.markOpsBefore], markOpsAfter: item.markOpsAfter && [...item.markOpsAfter], })), }, right: { doc: docs[right].actorId, text: rightText, // @ts-ignore -- reach into private metadata, it's fine meta: docs[right].metadata["1@doc1"].map(item => ({ ...item, // show mark op sets as arrays in JSON markOpsBefore: item.markOpsBefore && [...item.markOpsBefore], markOpsAfter: item.markOpsAfter && [...item.markOpsAfter], })), }, syncs, }) } assert.deepStrictEqual(docs[left].clock, docs[right].clock) assert.deepStrictEqual(leftText, rightText) } }
the_stack
import { ChildProcess, execFile } from 'child_process'; import { IService } from './main'; import { IRegistry } from './registry'; import { app, dialog } from 'electron'; import { AsyncRemote, asyncRemoteMain } from '../asyncremote'; import { IApplication, IClosingService } from './app'; import { ArrayExt } from '@lumino/algorithm'; import log from 'electron-log'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import * as http from 'http'; import { IEnvironmentType, IPythonEnvironment } from './tokens'; import { appConfig, getEnvironmentPath, getSchemasDir, getUserDataDir } from './utils'; const SERVER_LAUNCH_TIMEOUT = 30000; // milliseconds const SERVER_RESTART_LIMIT = 3; // max server restarts function createTempFile( fileName = 'temp', data = '', encoding: BufferEncoding = 'utf8' ) { const tempDirPath = path.join(os.tmpdir(), 'jlab_desktop'); const tmpDir = fs.mkdtempSync(tempDirPath); const tmpFilePath = path.join(tmpDir, fileName); fs.writeFileSync(tmpFilePath, data, { encoding }); return tmpFilePath; } function createLaunchScript( environment: IPythonEnvironment, baseCondaPath: string, schemasDir: string ): string { const isWin = process.platform === 'win32'; const envPath = getEnvironmentPath(environment); // note: traitlets<5.0 require fully specified arguments to // be followed by equals sign without a space; this can be // removed once jupyter_server requires traitlets>5.0 const launchCmd = [ 'python', '-m', 'jupyterlab', '--no-browser', `--LabServerApp.schemas_dir="${schemasDir}"`, // do not use any config file '--JupyterApp.config_file_name=""', `--ServerApp.port=${appConfig.jlabPort}`, // use our token rather than any pre-configured password '--ServerApp.password=""', '--ServerApp.allow_origin="*"', // enable hidden files (let user decide whether to display them) '--ContentsManager.allow_hidden=True' ].join(' '); let script: string; const isConda = environment.type === IEnvironmentType.CondaRoot || environment.type === IEnvironmentType.CondaEnv; if (isWin) { if (isConda) { script = ` CALL ${baseCondaPath}\\condabin\\activate.bat CALL conda activate ${envPath} CALL ${launchCmd}`; } else { script = ` CALL ${envPath}\\activate.bat CALL ${launchCmd}`; } } else { if (isConda) { script = ` source ${baseCondaPath}/bin/activate conda activate ${envPath} ${launchCmd}`; } else { script = ` source ${envPath}/bin/activate ${launchCmd}`; } } const ext = isWin ? 'bat' : 'sh'; const scriptPath = createTempFile(`launch.${ext}`, script); if (!isWin) { fs.chmodSync(scriptPath, 0o755); } return scriptPath; } async function waitForDuration(duration: number): Promise<boolean> { return new Promise(resolve => { setTimeout(() => { resolve(false); }, duration); }); } async function checkIfUrlExists(url: URL): Promise<boolean> { return new Promise<boolean>(resolve => { const req = http.request(url, function (r) { resolve(r.statusCode >= 200 && r.statusCode < 400); }); req.on('error', function (err) { resolve(false); }); req.end(); }); } async function waitUntilServerIsUp(port: number): Promise<boolean> { const url = new URL(`http://localhost:${port}`); return new Promise<boolean>(resolve => { async function checkUrl() { const exists = await checkIfUrlExists(url); if (exists) { return resolve(true); } else { setTimeout(async () => { await checkUrl(); }, 500); } } checkUrl(); }); } export class JupyterServer { constructor( options: JupyterServer.IOptions, app: IApplication, registry: IRegistry ) { this._info.environment = options.environment; this._app = app; this._registry = registry; } get info(): JupyterServer.IInfo { return this._info; } /** * Start a local Jupyter server. This method can be * called multiple times without initiating multiple starts. * * @return a promise that is resolved when the server has started. */ public start(): Promise<JupyterServer.IInfo> { if (this._startServer) { return this._startServer; } let started = false; this._startServer = new Promise<JupyterServer.IInfo>( // eslint-disable-next-line no-async-promise-executor async (resolve, reject) => { const home = process.env.JLAB_DESKTOP_HOME || app.getPath('home'); const isWin = process.platform === 'win32'; const pythonPath = this._info.environment.path; if (!fs.existsSync(pythonPath)) { dialog.showMessageBox({ message: `Environment not found at: ${pythonPath}`, type: 'error' }); reject(); } this._info.url = `http://localhost:${appConfig.jlabPort}`; this._info.token = appConfig.token; let baseCondaPath: string = ''; if (this._info.environment.type === IEnvironmentType.CondaRoot) { baseCondaPath = getEnvironmentPath(this._info.environment); } else if (this._info.environment.type === IEnvironmentType.CondaEnv) { const baseCondaPathSet = await this._app.getCondaRootPath(); if (baseCondaPathSet && fs.existsSync(baseCondaPathSet)) { baseCondaPath = baseCondaPathSet; } else { const environments = await this._registry.getCondaEnvironments(); for (const environment of environments) { if (environment.type === IEnvironmentType.CondaRoot) { baseCondaPath = getEnvironmentPath(environment); this._app.setCondaRootPath(baseCondaPath); break; } } } if (baseCondaPath === '') { const choice = dialog.showMessageBoxSync({ message: 'Select conda base environment', detail: 'Base conda environment not found. Please select a root conda environment to activate the custom environment.', type: 'error', buttons: ['OK', 'Cancel'], defaultId: 0, cancelId: 0 }); if (choice == 1) { reject(new Error('Failed to activate conda environment')); return; } const filePaths = dialog.showOpenDialogSync({ properties: [ 'openDirectory', 'showHiddenFiles', 'noResolveAliases' ], buttonLabel: 'Use Conda Root' }); if (filePaths && filePaths.length > 0) { baseCondaPath = filePaths[0]; if ( !this._registry.validateCondaBaseEnvironmentAtPath( baseCondaPath ) ) { reject(new Error('Invalid base conda environment')); return; } this._app.setCondaRootPath(baseCondaPath); } else { reject(new Error('Failed to activate conda environment')); return; } } } const launchScriptPath = createLaunchScript( this._info.environment, baseCondaPath, getSchemasDir() ); this._nbServer = execFile(launchScriptPath, { cwd: home, shell: isWin ? 'cmd.exe' : '/bin/bash', env: { ...process.env, JUPYTER_TOKEN: appConfig.token, JUPYTER_CONFIG_DIR: process.env.JLAB_DESKTOP_CONFIG_DIR || getUserDataDir() } }); Promise.race([ waitUntilServerIsUp(appConfig.jlabPort), waitForDuration(SERVER_LAUNCH_TIMEOUT) ]).then((up: boolean) => { if (up) { started = true; fs.unlinkSync(launchScriptPath); resolve(this._info); } else { reject(new Error('Failed to launch Jupyter Server')); } }); this._nbServer.on('exit', () => { if (started) { /* On Windows, JupyterLab server sometimes crashes randomly during websocket connection. As a result of this, users experience kernel connections failures. This crash only happens when server is launched from electron app. Since we haven't been able to detect the exact cause of these crashes we are restarting the server at the same port. After the restart, users are able to launch new kernels for the notebook. */ this._cleanupListeners(); if (!this._stopping && this._restartCount < SERVER_RESTART_LIMIT) { started = false; this._startServer = null; this.start(); this._restartCount++; } } else { this._serverStartFailed(); reject( new Error( 'Jupyter Server process terminated before the initialization completed' ) ); } }); this._nbServer.on('error', (err: Error) => { if (started) { dialog.showMessageBox({ message: `Jupyter Server process errored: ${err.message}`, type: 'error' }); } else { this._serverStartFailed(); reject(err); } }); } ); return this._startServer; } /** * Stop the currently executing Jupyter server. * * @return a promise that is resolved when the server has stopped. */ public stop(): Promise<void> { // If stop has already been initiated, just return the promise if (this._stopServer) { return this._stopServer; } this._stopping = true; this._stopServer = new Promise<void>((res, rej) => { if (this._nbServer !== undefined) { if (process.platform === 'win32') { execFile( 'taskkill', ['/PID', String(this._nbServer.pid), '/T', '/F'], () => { res(); } ); } else { this._nbServer.kill(); this._stopping = false; res(); } } else { this._stopping = false; res(); } }); return this._stopServer; } private _serverStartFailed(): void { this._cleanupListeners(); // Server didn't start, resolve stop promise this._stopServer = Promise.resolve(); } private _cleanupListeners(): void { this._nbServer.removeAllListeners(); this._nbServer.stderr.removeAllListeners(); } /** * The child process object for the Jupyter server */ private _nbServer: ChildProcess; private _stopServer: Promise<void> = null; private _startServer: Promise<JupyterServer.IInfo> = null; private _info: JupyterServer.IInfo = { url: null, token: null, environment: null, version: null }; private _app: IApplication; private _registry: IRegistry; private _stopping: boolean = false; private _restartCount: number = 0; } export namespace JupyterServer { export interface IOptions { environment: IPythonEnvironment; } export interface IInfo { url: string; token: string; environment: IPythonEnvironment; version?: string; } } export interface IServerFactory { /** * Create and start a 'free' server. The server created will be returned * in the next call to 'createServer'. * * This method is a way to pre-launch Jupyter servers to improve load * times. * * @param opts the Jupyter server options. * * @return the factory item. */ createFreeServer: ( opts: JupyterServer.IOptions ) => JupyterServerFactory.IFactoryItem; /** * Create a Jupyter server. * * If a free server is available, it is preferred over * server creation. * * @param opts the Jupyter server options. * @param forceNewServer force the creation of a new server over a free server. * * @return the factory item. */ createServer: ( opts: JupyterServer.IOptions ) => Promise<JupyterServerFactory.IFactoryItem>; /** * Kill all currently running servers. * * @return a promise that is fulfilled when all servers are killed. */ killAllServers: () => Promise<void[]>; } export namespace IServerFactory { export interface IServerStarted { readonly factoryId: number; url: string; token: string; error?: Error; } export interface IServerStop { factoryId: number; } export let requestServerStart: AsyncRemote.IMethod<void, IServerStarted> = { id: 'JupyterServerFactory-requestserverstart' }; export let requestServerStop: AsyncRemote.IMethod<IServerStop, void> = { id: 'JupyterServerFactory-requestserverstop' }; export let requestServerStartPath: AsyncRemote.IMethod< void, IServerStarted > = { id: 'JupyterServerFactory-requestserverstartpath' }; export let pathSelectedEvent: AsyncRemote.IEvent<void> = { id: 'JupyterServerFactory-pathselectedevent' }; } export class JupyterServerFactory implements IServerFactory, IClosingService { constructor(app: IApplication, registry: IRegistry) { this._app = app; this._registry = registry; app.registerClosingService(this); asyncRemoteMain.registerRemoteMethod( IServerFactory.requestServerStart, () => { return this.createServer({} as JupyterServer.IOptions) .then((data: JupyterServerFactory.IFactoryItem) => { return this._factoryToIPC(data); }) .catch((e: Error) => { return this._errorToIPC(e); }); } ); asyncRemoteMain.registerRemoteMethod( IServerFactory.requestServerStartPath, (data: any, caller) => { return this._registry .getUserJupyterPath() .then((environment: IPythonEnvironment) => { asyncRemoteMain.emitRemoteEvent( IServerFactory.pathSelectedEvent, undefined, caller ); return this.createServer({ environment }); }) .then((data: JupyterServerFactory.IFactoryItem) => { return this._factoryToIPC(data); }) .catch((e: Error) => { if (e.message !== 'cancel') { return this._errorToIPC(e); } }); } ); asyncRemoteMain.registerRemoteMethod( IServerFactory.requestServerStop, (arg: IServerFactory.IServerStop) => { return this.stopServer(arg.factoryId); } ); } /** * Create and start a 'free' server. The server created will be returned * in the next call to 'createServer'. * * This method is a way to pre-launch Jupyter servers to improve load * times. * * @param opts the Jupyter server options. * * @return the factory item. */ createFreeServer( opts: JupyterServer.IOptions ): JupyterServerFactory.IFactoryItem { let item: JupyterServerFactory.IFactoryItem; let env: Promise<IPythonEnvironment>; if (!opts.environment) { env = this._registry.getDefaultEnvironment(); } else { env = Promise.resolve(opts.environment); } env .then(env => { opts.environment = env; item = this._createServer(opts); return item.server.start(); }) .catch((e: Error) => { // The server failed to start, remove it from the factory. log.warn(e); }); return item; } /** * Create a Jupyter server. * * If a free server is available, it is preferred over * server creation. * * @param opts the Jupyter server options. * @param forceNewServer force the creation of a new server over a free server. */ createServer( opts: JupyterServer.IOptions, forceNewServer?: boolean ): Promise<JupyterServerFactory.IFactoryItem> { let server: JupyterServerFactory.IFactoryItem; let env: Promise<IPythonEnvironment>; if (!opts.environment) { env = this._registry.getDefaultEnvironment(); } else { env = Promise.resolve(opts.environment); } return env .then(env => { if (forceNewServer) { server = this._createServer({ environment: env }); } else { server = this._findUnusedServer({ environment: env }, !opts.environment) || this._createServer({ environment: env }); } server.used = true; return server.server.start(); }) .then((data: JupyterServer.IInfo) => { return Promise.resolve(server); }) .catch(e => { this._removeFailedServer(server.factoryId); return Promise.reject(e); }); } /** * Stop a Jupyter server. * * @param factoryId the factory item id. */ stopServer(factoryId: number): Promise<void> { let idx = this._getServerIdx(factoryId); if (idx < 0) { return Promise.reject(new Error('Invalid server id: ' + factoryId)); } let server = this._servers[idx]; if (server.closing) { return server.closing; } let promise = new Promise<void>((res, rej) => { server.server .stop() .then(() => { ArrayExt.removeAt(this._servers, idx); res(); }) .catch(e => { log.error(e); ArrayExt.removeAt(this._servers, idx); rej(); }); }); server.closing = promise; return promise; } /** * Kill all currently running servers. * * @return a promise that is fulfilled when all servers are killed. */ killAllServers(): Promise<void[]> { // Get stop promises from all servers let stopPromises = this._servers.map(server => { return server.server.stop(); }); // Empty the server array. this._servers = []; return Promise.all(stopPromises); } /** * Closes all servers and cleans up any remaining listeners * @return promise that is fulfilled when the server factory is ready to quit */ finished(): Promise<void> { let promise = new Promise<void>((resolve, reject) => { this.killAllServers() .then(() => { resolve(); }) .catch(() => { reject(); }); }); return promise; } private _createServer( opts: JupyterServer.IOptions ): JupyterServerFactory.IFactoryItem { let item: JupyterServerFactory.IFactoryItem = { factoryId: this._nextId++, server: new JupyterServer(opts, this._app, this._registry), closing: null, used: false }; this._servers.push(item); return item; } private _findUnusedServer( opts: JupyterServer.IOptions, usedDefault: boolean ): JupyterServerFactory.IFactoryItem | null { let result = ArrayExt.findFirstValue( this._servers, (server: JupyterServerFactory.IFactoryItem, idx: number) => { return ( !server.used && opts.environment.path === server.server.info.environment.path ); } ); if (!result && usedDefault) { result = ArrayExt.findFirstValue(this._servers, server => { return !server.used; }); } return result; } private _removeFailedServer(factoryId: number): void { let idx = this._getServerIdx(factoryId); if (idx < 0) { return; } ArrayExt.removeAt(this._servers, idx); } private _getServerIdx(factoryId: number): number { return ArrayExt.findFirstIndex( this._servers, (s: JupyterServerFactory.IFactoryItem, idx: number) => { if (s.factoryId === factoryId) { return true; } return false; } ); } private _factoryToIPC( data: JupyterServerFactory.IFactoryItem ): IServerFactory.IServerStarted { let info = data.server.info; return { factoryId: data.factoryId, url: info.url, token: info.token }; } private _errorToIPC(e: Error): IServerFactory.IServerStarted { return { factoryId: -1, url: null, token: null, error: e }; } private _servers: JupyterServerFactory.IFactoryItem[] = []; private _nextId: number = 1; private _app: IApplication; private _registry: IRegistry; } export namespace JupyterServerFactory { /** * The object created by the JupyterServerFactory. */ export interface IFactoryItem { /** * The factory ID. Used to keep track of the server. */ readonly factoryId: number; /** * Whether the server is currently used. */ used: boolean; /** * A promise that is created when the server is closing * and resolved on close. */ closing: Promise<void>; /** * The actual Jupyter server object. */ server: JupyterServer; } } let service: IService = { requirements: ['IRegistry', 'IApplication'], provides: 'IServerFactory', activate: (registry: IRegistry, app: IApplication): IServerFactory => { return new JupyterServerFactory(app, registry); }, autostart: true }; export default service;
the_stack
declare module "kinect-azure" { export default KinectAzure; export interface ImageFrame { imageData: Buffer; imageLength: number; width: number; height: number; strideBytes: number; } export interface TimeStamp { deviceTimeStamp: number; systemTimeStamp: number; } export interface Body { id: number; skeleton: Skeleton; } export interface Skeleton { joints: Joint[]; } export interface Joint { index: number; cameraX: number; cameraY: number; cameraZ: number; orientationX: number; orientationY: number; orientationZ: number; orientationW: number; colorX: number; colorY: number; depthX: number; depthY: number; confidence: number; } export interface KinectData { imu: { temperature: number; accX: number; accY: number; accZ: number; accTimestamp: number; gyroX: number; gyroY: number; gyroZ: number; gyroTimestamp: number; }; colorImageFrame: ImageFrame & TimeStamp; depthImageFrame: ImageFrame & TimeStamp; irImageFrame: ImageFrame & TimeStamp; depthToColorImageFrame: ImageFrame; colorToDepthImageFrame: ImageFrame; bodyFrame: { bodyIndexMapImageFrame: ImageFrame; bodyIndexMapToColorImageFrame: ImageFrame; numBodies: number; bodies: Body[]; }; } class KinectAzure { get time(): number; get duration(): number; constructor(); close(): boolean; /** * Creates a body tracker * @param options The configuration for the body tracker */ createTracker( options: Partial<{ sensor_orientation: K4ABT_SENSOR_ORIENTATION; processing_mode: K4ABT_TRACKER_PROCESSING_MODE; /** The id of the GPU to use */ gpu_device_id: number; /** Specify the model file name and location used by the tracker. */ model_path: string; }> = {} ): boolean; destroyTracker(): number; getDepthModeRange(depthMode: K4A_DEPTH_MODE): { min: number; max: number }; open(): boolean; /** open a playback mkv stream */ openPlayback(path: String, playback_handle: Function): boolean; pause(): boolean; resume(): boolean; seek(time: number): boolean; setAutoExposure(): void; /** * Backlight compensation setting * @param {number} value 0 means backlight compensation is disabled, 1 means it is enabled */ setBacklightCompensation(value: number): void; /** * Brightness setting * @param {number} value valid range is 0 to 255, default value = 128 */ setBrightness(value: number = 128): void; /** * Set the Azure Kinect color sensor control value. * @param {Object} options The configuration for the color control * @param {number} options.command Color sensor control command. (eg KinectAzure. K4A_COLOR_CONTROL_EXPOSURE_TIME_ABSOLUTE, ...) * @param {number} options.mode Color sensor control mode to set. This mode represents whether the command is in automatic or manual mode. (eg KinectAzure. K4A_COLOR_CONTROL_MODE_AUTO, KinectAzure.K4A_COLOR_CONTROL_MODE_MANUAL) * @param {number} options.value Value to set the color sensor's control to. The value is only valid if mode is set to K4A_COLOR_CONTROL_MODE_MANUAL, and is otherwise ignored. */ setColorControl(options: { command: K4A_COLOR_CONTROL; mode: K4A_COLOR_CONTROL_MODE; value: number; }): void; /** * Contrast setting * @param {number} value value range is 0 to 10 */ setContrast(value: number): void; setExposure(value: number): void; /** * Gain setting * @param {number} value value */ setGain(value: number): void; /** * Powerline compensation setting * @param {number} value 1 sets it to 50Hz, 2 sets it to 60 Hz */ setPowerlineFrequency(value: number): void; /** * Saturation setting * @param {number} value value range is 0 to 50 */ setSaturation(value: number): void; /** * Sharpness setting * @param {number} value value */ setSharpness(value: number): void; /** * Whitebalance setting * @param {number} value unit is degrees Kelvin. Must be divisible by 10. */ setWhiteBalance(value: number): void; /** * Starts the kinect cameras * * min and max depth are used to normalize depth data. * @param {Object} options The configuration for the cameras */ startCameras(options?: CameraOptions): boolean; startListening(cb: Function): void; /** * Starts the kinect cameras. * * min and max depth are used to normalize depth data */ startPlayback( options?: Partial<{ /** The number of frames per second, if not set will default to recording fps */ camera_fps: K4A_FRAMES_PER_SECOND; /** The color format */ color_format: K4A_IMAGE_FORMAT; /** generate depth to color image */ include_depth_to_color: bool; /** generate color to depth image */ include_color_to_depth: bool; /** flip blue and red channels */ flip_BGRA_to_RGBA: bool; /** apply the depth data to the alpha channel of the color image */ apply_depth_to_alpha: bool; /** min depth distance in mm */ min_depth: number; /** max depth distance in mm */ max_depth: number; }> ): boolean; stopCameras(): void; stopListening(cb?: (err, result) => void): Promise<void>; stopPlayback(): void; static K4ABT_BODY_INDEX_MAP_BACKGROUND: number; static K4ABT_JOINT_ANKLE_LEFT: number; static K4ABT_JOINT_ANKLE_RIGHT: number; static K4ABT_JOINT_CLAVICLE_LEFT: number; static K4ABT_JOINT_CLAVICLE_RIGHT: number; static K4ABT_JOINT_COUNT: number; static K4ABT_JOINT_EAR_LEFT: number; static K4ABT_JOINT_EAR_RIGHT: number; static K4ABT_JOINT_ELBOW_LEFT: number; static K4ABT_JOINT_ELBOW_RIGHT: number; static K4ABT_JOINT_EYE_LEFT: number; static K4ABT_JOINT_EYE_RIGHT: number; static K4ABT_JOINT_FOOT_LEFT: number; static K4ABT_JOINT_FOOT_RIGHT: number; static K4ABT_JOINT_HANDTIP_LEFT: number; static K4ABT_JOINT_HANDTIP_RIGHT: number; static K4ABT_JOINT_HAND_LEFT: number; static K4ABT_JOINT_HAND_RIGHT: number; static K4ABT_JOINT_HEAD: number; static K4ABT_JOINT_HIP_LEFT: number; static K4ABT_JOINT_HIP_RIGHT: number; static K4ABT_JOINT_KNEE_LEFT: number; static K4ABT_JOINT_KNEE_RIGHT: number; static K4ABT_JOINT_NECK: number; static K4ABT_JOINT_NOSE: number; static K4ABT_JOINT_PELVIS: number; static K4ABT_JOINT_SHOULDER_LEFT: number; static K4ABT_JOINT_SHOULDER_RIGHT: number; static K4ABT_JOINT_SPINE_CHEST: number; static K4ABT_JOINT_SPINE_NAVEL: number; static K4ABT_JOINT_THUMB_LEFT: number; static K4ABT_JOINT_THUMB_RIGHT: number; static K4ABT_JOINT_WRIST_LEFT: number; static K4ABT_JOINT_WRIST_RIGHT: number; static K4ABT_SENSOR_ORIENTATION_CLOCKWISE90: number; static K4ABT_SENSOR_ORIENTATION_COUNTERCLOCKWISE90: number; static K4ABT_SENSOR_ORIENTATION_DEFAULT: number; static K4ABT_SENSOR_ORIENTATION_FLIP180: number; static K4ABT_TRACKER_PROCESSING_MODE_CPU: number; static K4ABT_TRACKER_PROCESSING_MODE_GPU: number; static K4ABT_TRACKER_PROCESSING_MODE_GPU_CUDA: number; static K4ABT_TRACKER_PROCESSING_MODE_GPU_DIRECTML: number; static K4ABT_TRACKER_PROCESSING_MODE_GPU_TENSORRT: number; static K4A_COLOR_CONTROL_AUTO_EXPOSURE_PRIORITY: number; static K4A_COLOR_CONTROL_BACKLIGHT_COMPENSATION: number; static K4A_COLOR_CONTROL_BRIGHTNESS: number; static K4A_COLOR_CONTROL_CONTRAST: number; static K4A_COLOR_CONTROL_EXPOSURE_TIME_ABSOLUTE: number; static K4A_COLOR_CONTROL_GAIN: number; static K4A_COLOR_CONTROL_MODE_AUTO: number; static K4A_COLOR_CONTROL_MODE_MANUAL: number; static K4A_COLOR_CONTROL_POWERLINE_FREQUENCY: number; static K4A_COLOR_CONTROL_SATURATION: number; static K4A_COLOR_CONTROL_SHARPNESS: number; static K4A_COLOR_CONTROL_WHITEBALANCE: number; static K4A_COLOR_RESOLUTION_1080P: number; static K4A_COLOR_RESOLUTION_1440P: number; static K4A_COLOR_RESOLUTION_1536P: number; static K4A_COLOR_RESOLUTION_2160P: number; static K4A_COLOR_RESOLUTION_3072P: number; static K4A_COLOR_RESOLUTION_720P: number; static K4A_COLOR_RESOLUTION_OFF: number; static K4A_DEPTH_MODE_NFOV_2X2BINNED: number; static K4A_DEPTH_MODE_NFOV_UNBINNED: number; static K4A_DEPTH_MODE_OFF: number; static K4A_DEPTH_MODE_PASSIVE_IR: number; static K4A_DEPTH_MODE_WFOV_2X2BINNED: number; static K4A_DEPTH_MODE_WFOV_UNBINNED: number; static K4A_FRAMES_PER_SECOND_15: number; static K4A_FRAMES_PER_SECOND_30: number; static K4A_FRAMES_PER_SECOND_5: number; static K4A_IMAGE_FORMAT_COLOR_BGRA32: number; static K4A_IMAGE_FORMAT_COLOR_MJPG: number; static K4A_IMAGE_FORMAT_COLOR_NV12: number; static K4A_IMAGE_FORMAT_COLOR_YUY2: number; static K4A_IMAGE_FORMAT_CUSTOM: number; static K4A_IMAGE_FORMAT_CUSTOM16: number; static K4A_IMAGE_FORMAT_CUSTOM8: number; static K4A_IMAGE_FORMAT_DEPTH16: number; static K4A_IMAGE_FORMAT_IR16: number; } export interface CameraOptions extends Partial<{ /** The number of frames per second */ camera_fps: K4A_FRAMES_PER_SECOND; /** The color format */ color_format: K4A_IMAGE_FORMAT; /** The color resolution */ color_resolution: K4A_COLOR_RESOLUTION; /** The depth mode */ depth_mode: K4A_DEPTH_MODE; /** The point cloud mode */ point_cloud_mode: number; /** Only produce capture objects if they contain synchronized color and depth images */ synchronized_image_only: boolean; /** generate depth to color image */ include_depth_to_color: boolean; /** generate color to depth image */ include_color_to_depth: boolean; /** include body index map */ include_body_index_map: boolean; /** include imu data (temperature, accelerometer, gyroscope) */ include_imu_sample: boolean; /** flip blue and red channels */ flip_BGRA_to_RGBA: boolean; /** apply the depth data to the alpha channel of the color image */ apply_depth_to_alpha: boolean; /** converts depth_to_color 16bit image to RGBA 32bit greyscale image */ depth_to_greyscale: boolean; /** converts depth_to_color 16bit image to RGBA 32bit color image */ depth_to_redblue: boolean; /** min depth distance in mm */ min_depth: number; /** max depth distance in mm */ max_depth: number; }> {} export const enum K4A_DEPTH_MODE { /**Depth sensor will be turned off with this setting. */ OFF, /**Depth captured at 320x288. Passive IR is also captured at 320x288. */ NFOV_2X2BINNED, /**Depth captured at 640x576. Passive IR is also captured at 640x576. */ NFOV_UNBINNED, /**Depth captured at 512x512. Passive IR is also captured at 512x512. */ WFOV_2X2BINNED, /**Depth captured at 1024x1024. Passive IR is also captured at 1024x1024. */ WFOV_UNBINNED, /**Passive IR only, captured at 1024x1024. */ PASSIVE_IR, } export const enum K4A_COLOR_RESOLUTION { /**Color camera will be turned off with this setting */ RESOLUTION_OFF, /**1280 * 720 16:9 */ _720P, /**1920 * 1080 16:9 */ _1080P, /**2560 * 1440 16:9 */ _1440P, /**2048 * 1536 4:3 */ _1536P, /**3840 * 2160 16:9 */ _2160P, /**4096 * 3072 4:3 */ _3072P, } export const enum K4A_IMAGE_FORMAT { COLOR_MJPG = 0, COLOR_NV12 = 1, COLOR_YUY2 = 2, COLOR_BGRA32 = 3, DEPTH16 = 4, IR16 = 5, CUSTOM8 = 6, CUSTOM16 = 6, CUSTOM = 7, } export const enum K4A_FRAMES_PER_SECOND { _5 = 0, _15 = 1, _30 = 2, } export const enum K4ABT_SENSOR_ORIENTATION { /**< Mount the sensor at its default orientation */ DEFAULT = 0, /**< Clockwisely rotate the sensor 90 degree */ CLOCKWISE90, /**< Counter-clockwisely rotate the sensor 90 degrees */ COUNTERCLOCKWISE90, /**< Mount the sensor upside-down */ FLIP180, } export const enum K4ABT_JOINT { PELVIS, SPINE_NAVEL, SPINE_CHEST, NECK, CLAVICLE_LEFT, SHOULDER_LEFT, ELBOW_LEFT, WRIST_LEFT, HAND_LEFT, HANDTIP_LEFT, THUMB_LEFT, CLAVICLE_RIGHT, SHOULDER_RIGHT, ELBOW_RIGHT, WRIST_RIGHT, HAND_RIGHT, HANDTIP_RIGHT, THUMB_RIGHT, HIP_LEFT, KNEE_LEFT, ANKLE_LEFT, FOOT_LEFT, HIP_RIGHT, KNEE_RIGHT, ANKLE_RIGHT, FOOT_RIGHT, HEAD, NOSE, EYE_LEFT, EAR_LEFT, EYE_RIGHT, EAR_RIGHT, COUNT, } export const enum K4ABT_TRACKER_PROCESSING_MODE { /**< SDK will use the most appropriate GPU mode for the operating system to run the tracker */ GPU = 0, /**< SDK will use CPU only mode to run the tracker */ CPU = 1, // Currently this is ONNX DirectML EP for Windows and ONNX Cuda EP for Linux. ONNX TensorRT EP is experimental /**< SDK will use ONNX Cuda EP to run the tracker */ GPU_CUDA = 2, /**< SDK will use ONNX TensorRT EP to run the tracker */ GPU_TENSORRT = 3, /**< SDK will use ONNX DirectML EP to run the tracker (Windows only) */ GPU_DIRECTML = 4, } export const enum K4A_COLOR_CONTROL { /** Exposure time setting. * * \details * May be set to ::K4A_COLOR_CONTROL_MODE_AUTO or ::K4A_COLOR_CONTROL_MODE_MANUAL. * * \details * The Azure Kinect supports a limited number of fixed expsore settings. When setting this, expect the exposure to * be rounded up to the nearest setting. Exceptions are 1) The last value in the table is the upper limit, so a * value larger than this will be overridden to the largest entry in the table. 2) The exposure time cannot be * larger than the equivelent FPS. So expect 100ms exposure time to be reduced to 30ms or 33.33ms when the camera is * started. The most recent copy of the table 'device_exposure_mapping' is in * https://github.com/microsoft/Azure-Kinect-Sensor-SDK/blob/develop/src/color/color_priv.h * * \details * Exposure time is measured in microseconds. */ EXPOSURE_TIME_ABSOLUTE, /** Exposure or Framerate priority setting. * * \details * May only be set to ::K4A_COLOR_CONTROL_MODE_MANUAL. * * \details * Value of 0 means framerate priority. Value of 1 means exposure priority. * * \details * Using exposure priority may impact the framerate of both the color and depth cameras. * * \details * Deprecated starting in 1.2.0. Please discontinue usage, firmware does not support this. */ AUTO_EXPOSURE_PRIORITY, /** Brightness setting. * * \details * May only be set to ::K4A_COLOR_CONTROL_MODE_MANUAL. * * \details * The valid range is 0 to 255. The default value is 128. */ BRIGHTNESS, /** Contrast setting. * * \details * May only be set to ::K4A_COLOR_CONTROL_MODE_MANUAL. */ CONTRAST, /** Saturation setting. * * \details * May only be set to ::K4A_COLOR_CONTROL_MODE_MANUAL. */ SATURATION, /** Sharpness setting. * * \details * May only be set to ::K4A_COLOR_CONTROL_MODE_MANUAL. */ SHARPNESS, /** White balance setting. * * \details * May be set to ::K4A_COLOR_CONTROL_MODE_AUTO or ::K4A_COLOR_CONTROL_MODE_MANUAL. * * \details * The unit is degrees Kelvin. The setting must be set to a value evenly divisible by 10 degrees. */ WHITEBALANCE, /** Backlight compensation setting. * * \details * May only be set to ::K4A_COLOR_CONTROL_MODE_MANUAL. * * \details * Value of 0 means backlight compensation is disabled. Value of 1 means backlight compensation is enabled. */ BACKLIGHT_COMPENSATION, /** Gain setting. * * \details * May only be set to ::K4A_COLOR_CONTROL_MODE_MANUAL. */ GAIN, /** Powerline frequency setting. * * \details * May only be set to ::K4A_COLOR_CONTROL_MODE_MANUAL. * * \details * Value of 1 sets the powerline compensation to 50 Hz. Value of 2 sets the powerline compensation to 60 Hz. */ POWERLINE_FREQUENCY, } export const enum K4A_COLOR_CONTROL_MODE { /**< set the associated k4a_color_control_command_t to auto*/ AUTO = 0, /**< set the associated k4a_color_control_command_t to manual*/ MANUAL = 1, } }
the_stack
import * as assert from 'assert'; import { Event } from 'vs/base/common/event'; import { flakySuite } from 'vs/base/test/common/testUtils'; import { TestContextService, TestWorkingCopy } from 'vs/workbench/test/common/workbenchTestServices'; import { getRandomTestPath } from 'vs/base/test/node/testUtils'; import { tmpdir } from 'os'; import { join } from 'vs/base/common/path'; import { Promises } from 'vs/base/node/pfs'; import { URI } from 'vs/base/common/uri'; import { TestWorkingCopyHistoryService } from 'vs/workbench/services/workingCopy/test/electron-browser/workingCopyHistoryService.test'; import { WorkingCopyHistoryTracker } from 'vs/workbench/services/workingCopy/common/workingCopyHistoryTracker'; import { WorkingCopyService } from 'vs/workbench/services/workingCopy/common/workingCopyService'; import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService'; import { TestFileService, TestPathService } from 'vs/workbench/test/browser/workbenchTestServices'; import { DeferredPromise } from 'vs/base/common/async'; import { IFileService } from 'vs/platform/files/common/files'; import { Schemas } from 'vs/base/common/network'; import { basename, dirname, isEqual, joinPath } from 'vs/base/common/resources'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { UndoRedoService } from 'vs/platform/undoRedo/common/undoRedoService'; import { TestDialogService } from 'vs/platform/dialogs/test/common/testDialogService'; import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IWorkingCopyHistoryEntry, IWorkingCopyHistoryEntryDescriptor } from 'vs/workbench/services/workingCopy/common/workingCopyHistory'; import { assertIsDefined } from 'vs/base/common/types'; flakySuite('WorkingCopyHistoryTracker', () => { let testDir: string; let historyHome: string; let workHome: string; let workingCopyHistoryService: TestWorkingCopyHistoryService; let workingCopyService: WorkingCopyService; let fileService: IFileService; let configurationService: TestConfigurationService; let tracker: WorkingCopyHistoryTracker; let testFile1Path: string; let testFile2Path: string; const testFile1PathContents = 'Hello Foo'; const testFile2PathContents = [ 'Lorem ipsum ', 'dolor öäü sit amet ', 'adipiscing ßß elit', 'consectetur ' ].join('').repeat(1000); let increasingTimestampCounter = 1; async function addEntry(descriptor: IWorkingCopyHistoryEntryDescriptor, token: CancellationToken): Promise<IWorkingCopyHistoryEntry> { const entry = await workingCopyHistoryService.addEntry({ ...descriptor, timestamp: increasingTimestampCounter++ // very important to get tests to not be flaky with stable sort order }, token); return assertIsDefined(entry); } setup(async () => { testDir = getRandomTestPath(tmpdir(), 'vsctests', 'workingcopyhistorytracker'); historyHome = join(testDir, 'User', 'History'); workHome = join(testDir, 'work'); workingCopyHistoryService = new TestWorkingCopyHistoryService(testDir); workingCopyService = new WorkingCopyService(); fileService = workingCopyHistoryService._fileService; configurationService = workingCopyHistoryService._configurationService; tracker = createTracker(); await Promises.mkdir(historyHome, { recursive: true }); await Promises.mkdir(workHome, { recursive: true }); testFile1Path = join(workHome, 'foo.txt'); testFile2Path = join(workHome, 'bar.txt'); await Promises.writeFile(testFile1Path, testFile1PathContents); await Promises.writeFile(testFile2Path, testFile2PathContents); }); function createTracker() { return new WorkingCopyHistoryTracker( workingCopyService, workingCopyHistoryService, new UriIdentityService(new TestFileService()), new TestPathService(undefined, Schemas.file), configurationService, new UndoRedoService(new TestDialogService(), new TestNotificationService()), new TestContextService(), workingCopyHistoryService._fileService ); } teardown(() => { workingCopyHistoryService.dispose(); workingCopyService.dispose(); tracker.dispose(); return Promises.rm(testDir); }); test('history entry added on save', async () => { const workingCopy1 = new TestWorkingCopy(URI.file(testFile1Path)); const workingCopy2 = new TestWorkingCopy(URI.file(testFile2Path)); const stat1 = await fileService.resolve(workingCopy1.resource, { resolveMetadata: true }); const stat2 = await fileService.resolve(workingCopy2.resource, { resolveMetadata: true }); workingCopyService.registerWorkingCopy(workingCopy1); workingCopyService.registerWorkingCopy(workingCopy2); const saveResult = new DeferredPromise<void>(); let addedCounter = 0; workingCopyHistoryService.onDidAddEntry(e => { if (isEqual(e.entry.workingCopy.resource, workingCopy1.resource) || isEqual(e.entry.workingCopy.resource, workingCopy2.resource)) { addedCounter++; if (addedCounter === 2) { saveResult.complete(); } } }); await workingCopy1.save(undefined, stat1); await workingCopy2.save(undefined, stat2); await saveResult.p; }); test('history entry skipped when setting disabled (globally)', async () => { configurationService.setUserConfiguration('workbench.localHistory.enabled', false, URI.file(testFile1Path)); return assertNoLocalHistoryEntryAddedWithSettingsConfigured(); }); test('history entry skipped when setting disabled (exclude)', () => { configurationService.setUserConfiguration('workbench.localHistory.exclude', { '**/foo.txt': true }); // Recreate to apply settings tracker.dispose(); tracker = createTracker(); return assertNoLocalHistoryEntryAddedWithSettingsConfigured(); }); test('history entry skipped when too large', async () => { configurationService.setUserConfiguration('workbench.localHistory.maxFileSize', 0, URI.file(testFile1Path)); return assertNoLocalHistoryEntryAddedWithSettingsConfigured(); }); async function assertNoLocalHistoryEntryAddedWithSettingsConfigured(): Promise<void> { const workingCopy1 = new TestWorkingCopy(URI.file(testFile1Path)); const workingCopy2 = new TestWorkingCopy(URI.file(testFile2Path)); const stat1 = await fileService.resolve(workingCopy1.resource, { resolveMetadata: true }); const stat2 = await fileService.resolve(workingCopy2.resource, { resolveMetadata: true }); workingCopyService.registerWorkingCopy(workingCopy1); workingCopyService.registerWorkingCopy(workingCopy2); const saveResult = new DeferredPromise<void>(); workingCopyHistoryService.onDidAddEntry(e => { if (isEqual(e.entry.workingCopy.resource, workingCopy1.resource)) { assert.fail('Unexpected working copy history entry: ' + e.entry.workingCopy.resource.toString()); } if (isEqual(e.entry.workingCopy.resource, workingCopy2.resource)) { saveResult.complete(); } }); await workingCopy1.save(undefined, stat1); await workingCopy2.save(undefined, stat2); await saveResult.p; } test('entries moved (file rename)', async () => { const entriesMoved = Event.toPromise(workingCopyHistoryService.onDidMoveEntries); const workingCopy = new TestWorkingCopy(URI.file(testFile1Path)); const entry1 = await addEntry({ resource: workingCopy.resource, source: 'test-source' }, CancellationToken.None); const entry2 = await addEntry({ resource: workingCopy.resource, source: 'test-source' }, CancellationToken.None); const entry3 = await addEntry({ resource: workingCopy.resource, source: 'test-source' }, CancellationToken.None); let entries = await workingCopyHistoryService.getEntries(workingCopy.resource, CancellationToken.None); assert.strictEqual(entries.length, 3); const renamedWorkingCopyResource = joinPath(dirname(workingCopy.resource), 'renamed.txt'); await workingCopyHistoryService._fileService.move(workingCopy.resource, renamedWorkingCopyResource); await entriesMoved; entries = await workingCopyHistoryService.getEntries(workingCopy.resource, CancellationToken.None); assert.strictEqual(entries.length, 0); entries = await workingCopyHistoryService.getEntries(renamedWorkingCopyResource, CancellationToken.None); assert.strictEqual(entries.length, 4); assert.strictEqual(entries[0].id, entry1.id); assert.strictEqual(entries[0].timestamp, entry1.timestamp); assert.strictEqual(entries[0].source, entry1.source); assert.notStrictEqual(entries[0].location, entry1.location); assert.strictEqual(entries[0].workingCopy.resource.toString(), renamedWorkingCopyResource.toString()); assert.strictEqual(entries[1].id, entry2.id); assert.strictEqual(entries[1].timestamp, entry2.timestamp); assert.strictEqual(entries[1].source, entry2.source); assert.notStrictEqual(entries[1].location, entry2.location); assert.strictEqual(entries[1].workingCopy.resource.toString(), renamedWorkingCopyResource.toString()); assert.strictEqual(entries[2].id, entry3.id); assert.strictEqual(entries[2].timestamp, entry3.timestamp); assert.strictEqual(entries[2].source, entry3.source); assert.notStrictEqual(entries[2].location, entry3.location); assert.strictEqual(entries[2].workingCopy.resource.toString(), renamedWorkingCopyResource.toString()); const all = await workingCopyHistoryService.getAll(CancellationToken.None); assert.strictEqual(all.length, 1); assert.strictEqual(all[0].toString(), renamedWorkingCopyResource.toString()); }); test('entries moved (folder rename)', async () => { const entriesMoved = Event.toPromise(workingCopyHistoryService.onDidMoveEntries); const workingCopy1 = new TestWorkingCopy(URI.file(testFile1Path)); const workingCopy2 = new TestWorkingCopy(URI.file(testFile2Path)); const entry1A = await addEntry({ resource: workingCopy1.resource, source: 'test-source' }, CancellationToken.None); const entry2A = await addEntry({ resource: workingCopy1.resource, source: 'test-source' }, CancellationToken.None); const entry3A = await addEntry({ resource: workingCopy1.resource, source: 'test-source' }, CancellationToken.None); const entry1B = await addEntry({ resource: workingCopy2.resource, source: 'test-source' }, CancellationToken.None); const entry2B = await addEntry({ resource: workingCopy2.resource, source: 'test-source' }, CancellationToken.None); const entry3B = await addEntry({ resource: workingCopy2.resource, source: 'test-source' }, CancellationToken.None); let entries = await workingCopyHistoryService.getEntries(workingCopy1.resource, CancellationToken.None); assert.strictEqual(entries.length, 3); entries = await workingCopyHistoryService.getEntries(workingCopy2.resource, CancellationToken.None); assert.strictEqual(entries.length, 3); const renamedWorkHome = joinPath(dirname(URI.file(workHome)), 'renamed'); await workingCopyHistoryService._fileService.move(URI.file(workHome), renamedWorkHome); const renamedWorkingCopy1Resource = joinPath(renamedWorkHome, basename(workingCopy1.resource)); const renamedWorkingCopy2Resource = joinPath(renamedWorkHome, basename(workingCopy2.resource)); await entriesMoved; entries = await workingCopyHistoryService.getEntries(workingCopy1.resource, CancellationToken.None); assert.strictEqual(entries.length, 0); entries = await workingCopyHistoryService.getEntries(workingCopy2.resource, CancellationToken.None); assert.strictEqual(entries.length, 0); entries = await workingCopyHistoryService.getEntries(renamedWorkingCopy1Resource, CancellationToken.None); assert.strictEqual(entries.length, 4); assert.strictEqual(entries[0].id, entry1A.id); assert.strictEqual(entries[0].timestamp, entry1A.timestamp); assert.strictEqual(entries[0].source, entry1A.source); assert.notStrictEqual(entries[0].location, entry1A.location); assert.strictEqual(entries[0].workingCopy.resource.toString(), renamedWorkingCopy1Resource.toString()); assert.strictEqual(entries[1].id, entry2A.id); assert.strictEqual(entries[1].timestamp, entry2A.timestamp); assert.strictEqual(entries[1].source, entry2A.source); assert.notStrictEqual(entries[1].location, entry2A.location); assert.strictEqual(entries[1].workingCopy.resource.toString(), renamedWorkingCopy1Resource.toString()); assert.strictEqual(entries[2].id, entry3A.id); assert.strictEqual(entries[2].timestamp, entry3A.timestamp); assert.strictEqual(entries[2].source, entry3A.source); assert.notStrictEqual(entries[2].location, entry3A.location); assert.strictEqual(entries[2].workingCopy.resource.toString(), renamedWorkingCopy1Resource.toString()); entries = await workingCopyHistoryService.getEntries(renamedWorkingCopy2Resource, CancellationToken.None); assert.strictEqual(entries.length, 4); assert.strictEqual(entries[0].id, entry1B.id); assert.strictEqual(entries[0].timestamp, entry1B.timestamp); assert.strictEqual(entries[0].source, entry1B.source); assert.notStrictEqual(entries[0].location, entry1B.location); assert.strictEqual(entries[0].workingCopy.resource.toString(), renamedWorkingCopy2Resource.toString()); assert.strictEqual(entries[1].id, entry2B.id); assert.strictEqual(entries[1].timestamp, entry2B.timestamp); assert.strictEqual(entries[1].source, entry2B.source); assert.notStrictEqual(entries[1].location, entry2B.location); assert.strictEqual(entries[1].workingCopy.resource.toString(), renamedWorkingCopy2Resource.toString()); assert.strictEqual(entries[2].id, entry3B.id); assert.strictEqual(entries[2].timestamp, entry3B.timestamp); assert.strictEqual(entries[2].source, entry3B.source); assert.notStrictEqual(entries[2].location, entry3B.location); assert.strictEqual(entries[2].workingCopy.resource.toString(), renamedWorkingCopy2Resource.toString()); const all = await workingCopyHistoryService.getAll(CancellationToken.None); assert.strictEqual(all.length, 2); for (const resource of all) { if (resource.toString() !== renamedWorkingCopy1Resource.toString() && resource.toString() !== renamedWorkingCopy2Resource.toString()) { assert.fail(`Unexpected history resource: ${resource.toString()}`); } } }); });
the_stack
import { DebugProtocol } from 'vscode-debugprotocol'; import { BufferStream } from "./BufferStream"; /* eslint-disable no-bitwise */ export enum LuaOpcode { OP_MOVE,/* A B R(A) := R(B) */ OP_LOADK,/* A Bx R(A) := Kst(Bx) */ OP_LOADKX,/* A R(A) := Kst(extra arg) */ OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */ OP_LOADNIL,/* A B R(A), R(A+1), ..., R(A+B) := nil */ OP_GETUPVAL,/* A B R(A) := UpValue[B] */ OP_GETTABUP,/* A B C R(A) := UpValue[B][RK(C)] */ OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */ OP_SETTABUP,/* A B C UpValue[A][RK(B)] := RK(C) */ OP_SETUPVAL,/* A B UpValue[B] := R(A) */ OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C) */ OP_NEWTABLE,/* A B C R(A) := {} (size = B,C) */ OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */ OP_ADD,/* A B C R(A) := RK(B) + RK(C) */ OP_SUB,/* A B C R(A) := RK(B) - RK(C) */ OP_MUL,/* A B C R(A) := RK(B) * RK(C) */ OP_DIV,/* A B C R(A) := RK(B) / RK(C) */ OP_MOD,/* A B C R(A) := RK(B) % RK(C) */ OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */ OP_UNM,/* A B R(A) := -R(B) */ OP_NOT,/* A B R(A) := not R(B) */ OP_LEN,/* A B R(A) := length of R(B) */ OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */ OP_JMP,/* A sBx pc+=sBx; if (A) close all upvalues >= R(A) + 1 */ OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */ OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ OP_TEST,/* A C if not (R(A) <=> C) then pc++ */ OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */ OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */ OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */ OP_FORLOOP,/* A sBx R(A)+=R(A+2); if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/ OP_FORPREP,/* A sBx R(A)-=R(A+2); pc+=sBx */ OP_TFORCALL,/* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2)); */ OP_TFORLOOP,/* A sBx if R(A+1) ~= nil then { R(A)=R(A+1); pc += sBx }*/ OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */ OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx]) */ OP_VARARG,/* A B R(A), R(A+1), ..., R(A+B-2) = vararg */ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */ } export enum LuaConstType { Nil = 0, Boolean = 1, Number = 3, String = 4, } const header = [ 0x1b, 0x4c, 0x75, 0x61, // LUA_SIGNATURE 0x52, 0x00, // lua version 0x01, 0x04, 0x08, 0x04, 0x08, 0x00, // lua config parameters: LE, 4 byte int, 8 byte size_t, 4 byte instruction, 8 byte LuaNumber, number is double 0x19, 0x93, 0x0d, 0x0a, 0x1a, 0x0a, // magic ]; function readHeader(b:BufferStream) { for (let i = 0; i < header.length; i++) { const n = b.readUInt8(); if (n !== header[i]) { throw new Error(`Invalid Lua Header at offset ${i}, expected ${header[i]} got ${n}`); } } } function readLuaString(b:BufferStream) { const size = b.readBigUInt64LE(); if (size > 0) { const s = b.readString(Number(size)-1); b.readUInt8(); return s; } else { return ""; } } /* | B | C | A | Op | | Bx | A | Op | | Ax | Op | */ export class LuaInstruction { constructor(readonly raw:number){} public get Op() : LuaOpcode { return this.raw & 0x3f; } public get A() { return (this.raw >> 6)& 0xff; } public get B() { return (this.raw >> 23)& 0x1ff; } public get C() { return (this.raw >> 14)& 0x1ff; } public get Ax() { return (this.raw >> 6)& 0x3ffffff; } public get Bx() { return (this.raw >> 14)& 0x3ffff; } public get sBx() { return this.Bx - 0x1ffff; } line:number; } class LuaUpval { name?:string; readonly instack:boolean; readonly idx:number; constructor(b:BufferStream) { this.instack = b.readUInt8() !== 0; this.idx = b.readUInt8(); } } export class LuaLocal { readonly name:string; readonly start:number; readonly end:number; constructor(b:BufferStream) { this.name = readLuaString(b); this.start = b.readUInt32LE(); this.end = b.readUInt32LE(); } } export class LuaConstant { public constructor(type:LuaConstType.Nil); public constructor(type:LuaConstType.Boolean,value:boolean); public constructor(type:LuaConstType.Number,value:number); public constructor(type:LuaConstType.String,value:string); public constructor( public readonly type:LuaConstType, public readonly value?:boolean|number|string ) { switch (type) { case LuaConstType.Nil: if (value !== undefined) {throw new Error(`Invalid Lua Constant: ${type} ${value}`);} break; case LuaConstType.Boolean: if (typeof value !== "boolean") {throw new Error(`Invalid Lua Constant: ${type} ${value}`);} break; case LuaConstType.Number: if (typeof value !== "number") {throw new Error(`Invalid Lua Constant: ${type} ${value}`);} break; case LuaConstType.String: if (typeof value !== "string") {throw new Error(`Invalid Lua Constant: ${type} ${value}`);} break; default: throw new Error(`Invalid Lua Constant Type: ${type}`); } } public get label() : string { switch (this.type) { case LuaConstType.Nil: return "nil"; case LuaConstType.Boolean: case LuaConstType.Number: return this.value!.toString(); case LuaConstType.String: return `"${(<string>this.value)}"`; //TODO: escape strings default: throw new Error(`Invalid Lua Constant Type: ${this.type} ${this.value}`); } } } export class LuaFunction { readonly source:string; readonly nparam:number; readonly is_vararg:boolean; readonly maxstack:number; readonly locals:LuaLocal[]=[]; readonly upvals:LuaUpval[]=[]; readonly instructions:LuaInstruction[]=[]; readonly constants:LuaConstant[]=[]; readonly inner_functions:LuaFunction[]=[]; readonly firstline:number; readonly lastline:number; constructor(b:BufferStream, withheader?:boolean) { if (withheader) { readHeader(b); } this.firstline = b.readUInt32LE(); this.lastline = b.readUInt32LE(); this.nparam = b.readUInt8(); this.is_vararg = b.readUInt8() !== 0; this.maxstack = b.readUInt8(); const num_insts = b.readUInt32LE(); for (let i = 0; i < num_insts; i++) { const inst = b.readUInt32LE(); this.instructions.push(new LuaInstruction(inst)); } const num_const = b.readUInt32LE(); for (let i = 0; i < num_const; i++) { const type:LuaConstType = b.readUInt8(); switch (type) { case LuaConstType.Nil: this.constants.push(new LuaConstant(LuaConstType.Nil)); break; case LuaConstType.Boolean: this.constants.push(new LuaConstant(LuaConstType.Boolean, b.readUInt8()!==0)); break; case LuaConstType.Number: this.constants.push(new LuaConstant(LuaConstType.Number, b.readDoubleLE())); break; case LuaConstType.String: this.constants.push(new LuaConstant(LuaConstType.String, readLuaString(b))); break; default: throw new Error(`Invalid Lua Constant Type: ${type}`); } } const num_protos = b.readUInt32LE(); for (let i = 0; i < num_protos; i++) { this.inner_functions.push(new LuaFunction(b)); } const num_upvals = b.readUInt32LE(); for (let i = 0; i < num_upvals; i++) { this.upvals.push(new LuaUpval(b)); } this.source = readLuaString(b); const num_lineinfo = b.readUInt32LE(); for (let i = 0; i < num_lineinfo; i++) { this.instructions[i].line = b.readUInt32LE(); } const num_locals = b.readUInt32LE(); for (let i = 0; i < num_locals; i++) { this.locals.push(new LuaLocal(b)); } const num_upval_names = b.readUInt32LE(); for (let i = 0; i < num_upval_names; i++) { this.upvals[i].name = readLuaString(b); } } private _baseAddr?:number; public get baseAddr() : number|undefined { return this._baseAddr; } public rebase(base:number) : number { let nextbase = base; this._baseAddr = nextbase; nextbase += this.instructions.length; this.inner_functions.forEach(f => { nextbase = f.rebase(nextbase); }); return nextbase; } public getFunctionAtStartLine(startline:number) : LuaFunction|undefined { if (this.firstline === startline) { return this; } if ( this.firstline < startline && (this.lastline===0 || this.lastline > startline) && this.inner_functions) { for (let i = 0; i < this.inner_functions.length; i++) { const f = this.inner_functions[i].getFunctionAtStartLine(startline); if (f) { return f; } } } return; } public getInstructionsAtBase(base:number,count:number) : DebugProtocol.DisassembledInstruction[]|undefined { if (count===0 || !this._baseAddr) {return;} if (this._baseAddr <= base && this._baseAddr+this.instructions.length > base) { const offset = base - this._baseAddr; const instrs:DebugProtocol.DisassembledInstruction[] = []; if (offset + count > this.instructions.length) { count = this.instructions.length - offset; } for (let i = 0; i < count; i++) { instrs.push({ address: "0x"+(this._baseAddr+offset+i).toString(16), instruction: this.getInstructionLabel(i+offset), line: this.instructions[i+offset].line, instructionBytes: this.instructions[i+offset].raw.toString(16), symbol: i+offset===0 ? this.source+":"+this.firstline : undefined }); } return instrs; } if ( this.inner_functions) { for (let i = 0; i < this.inner_functions.length; i++) { const instrs = this.inner_functions[i].getInstructionsAtBase(base,count); if (instrs) { return instrs; } } } return; } getDisassembledSingleFunction():string { const instructions = this.instructions.map((i,pc)=>this.getInstructionLabel(pc)); return [ `function at ${this.source}:${this.firstline}-${this.lastline}`, `${this.is_vararg?"vararg":`${this.nparam} params`} ${this.upvals.length} upvals ${this.maxstack} maxstack`, `${this.instructions.length} instructions ${this.constants.length} constants ${this.inner_functions.length} functions`, ...instructions, ].join("\n"); } getInstructionLabel(pc:number) { const current = this.instructions[pc]; const next = this.instructions[pc+1]; switch (current.Op) { case LuaOpcode.OP_LOADK: return `LOADK ${this.getRegisterLabel(pc,current.A)} := ${this.constants[current.Bx].label}`; case LuaOpcode.OP_LOADKX: return `LOADKX ${this.getRegisterLabel(pc,current.A)} := ${this.constants[next.Ax].label}`; case LuaOpcode.OP_LOADBOOL: return `LOADBOOL ${this.getRegisterLabel(pc,current.A)} := ${current.B!==0}${current.C!==0?" pc++":""}`; case LuaOpcode.OP_LOADNIL: return `LOADNIL ${this.getRegisterLabel(pc,current.A)}...${this.getRegisterLabel(pc,current.A+current.B)})`; case LuaOpcode.OP_GETUPVAL: return `GETUPVAL ${this.getRegisterLabel(pc,current.A)} := ${this.getUpvalLabel(current.B)}`; case LuaOpcode.OP_GETTABUP: return `GETTABUP ${this.getRegisterLabel(pc,current.A)} := ${this.getUpvalLabel(current.B)}[${this.getRegisterOrConstantLabel(pc,current.C)}]`; case LuaOpcode.OP_GETTABLE: return `GETTABLE ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterLabel(pc,current.B)}[${this.getRegisterOrConstantLabel(pc,current.C)}]`; case LuaOpcode.OP_SETTABUP: return `SETTABUP ${this.getUpvalLabel(current.A)}[${this.getRegisterOrConstantLabel(pc,current.B)}] := ${this.getRegisterOrConstantLabel(pc,current.C)}`; case LuaOpcode.OP_SETUPVAL: return `SETUPVAL ${this.getUpvalLabel(current.B)} := ${this.getRegisterLabel(pc,current.A)}`; case LuaOpcode.OP_SETTABLE: return `SETTABLE ${this.getRegisterLabel(pc,current.A)}[${this.getRegisterOrConstantLabel(pc,current.B)}] := ${this.getRegisterOrConstantLabel(pc,current.C)}`; case LuaOpcode.OP_NEWTABLE: { const rawb = current.B; const b = this.fb2int(rawb); const rawc = current.C; const c = this.fb2int(rawc); const asize = rawb===b?`${b}`:`${rawb}->${b}`; const hsize = rawc===c?`${c}`:`${rawc}->${c}`; return `NEWTABLE ${this.getRegisterLabel(pc,current.A)} := {} size(${asize},${hsize})`; } case LuaOpcode.OP_SELF: return `SELF ${this.getRegisterLabel(pc,current.A+1)} := ${this.getRegisterLabel(pc,current.B)}; ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterLabel(pc,current.B)}[${this.getRegisterOrConstantLabel(pc,current.C)}]`; case LuaOpcode.OP_ADD: return `ADD ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterOrConstantLabel(pc,current.B)} + ${this.getRegisterOrConstantLabel(pc,current.C)}`; case LuaOpcode.OP_SUB: return `SUB ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterOrConstantLabel(pc,current.B)} - ${this.getRegisterOrConstantLabel(pc,current.C)}`; case LuaOpcode.OP_MUL: return `MUL ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterOrConstantLabel(pc,current.B)} * ${this.getRegisterOrConstantLabel(pc,current.C)}`; case LuaOpcode.OP_DIV: return `DIV ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterOrConstantLabel(pc,current.B)} / ${this.getRegisterOrConstantLabel(pc,current.C)}`; case LuaOpcode.OP_MOD: return `MOD ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterOrConstantLabel(pc,current.B)} % ${this.getRegisterOrConstantLabel(pc,current.C)}`; case LuaOpcode.OP_POW: return `POW ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterOrConstantLabel(pc,current.B)} ^ ${this.getRegisterOrConstantLabel(pc,current.C)}`; case LuaOpcode.OP_MOVE: return `MOVE ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterLabel(pc,current.B)}`; case LuaOpcode.OP_UNM: return `UNM ${this.getRegisterLabel(pc,current.A)} := -${this.getRegisterLabel(pc,current.B)}`; case LuaOpcode.OP_NOT: return `NOT ${this.getRegisterLabel(pc,current.A)} := not ${this.getRegisterLabel(pc,current.B)}`; case LuaOpcode.OP_LEN: return `LEN ${this.getRegisterLabel(pc,current.A)} := length of ${this.getRegisterLabel(pc,current.B)}`; case LuaOpcode.OP_CONCAT: return `CONCAT ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterLabel(pc,current.B)}.. ... ..${this.getRegisterLabel(pc,current.C)}`; case LuaOpcode.OP_JMP: return `JMP pc+=${current.sBx}${current.A?`; close >= ${current.A-1}`:""}`; case LuaOpcode.OP_EQ: return `EQ if(${this.getRegisterOrConstantLabel(pc,current.B)} ${current.A?"~=":"=="} ${this.getRegisterOrConstantLabel(pc,current.B)}) then pc++`; case LuaOpcode.OP_LT: return `LT if(${this.getRegisterOrConstantLabel(pc,current.B)} ${current.A?">=":"<"} ${this.getRegisterOrConstantLabel(pc,current.B)}) then pc++`; case LuaOpcode.OP_LE: return `LE if(${this.getRegisterOrConstantLabel(pc,current.B)} ${current.A?">":"<="} ${this.getRegisterOrConstantLabel(pc,current.B)}) then pc++`; case LuaOpcode.OP_TEST: return `TEST if ${current.C?"not ":""}${this.getRegisterLabel(pc,current.A)} then pc++`; case LuaOpcode.OP_TESTSET: return `TESTSET if ${current.C?"":"not "}${this.getRegisterLabel(pc,current.A)} then ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterLabel(pc,current.B)} else pc++`; case LuaOpcode.OP_CALL: return `CALL ${this.getRegisterLabel(pc,current.A)}(${current.B?current.B-1:"var"} args ${current.C?current.C-1:"var"} returns)`; case LuaOpcode.OP_TAILCALL: return `TAILCALL return ${this.getRegisterLabel(pc,current.A)}(${current.B?current.B-1:"var"} args)`; case LuaOpcode.OP_RETURN: return `RETURN return ${current.B?current.B-1:"var"} results ${current.B>1?`starting at ${this.getRegisterLabel(pc,current.A)}`:""}`; case LuaOpcode.OP_FORLOOP: return `FORLOOP ${this.getRegisterLabel(pc,current.A)} += ${this.getRegisterLabel(pc,current.A+2)}; if ${this.getRegisterLabel(pc,current.A)} <= ${this.getRegisterLabel(pc,current.A+1)} then { pc+=${current.sBx}; ${this.getRegisterLabel(pc,current.A+3)} := ${this.getRegisterLabel(pc,current.A)} }`; case LuaOpcode.OP_FORPREP: return `FORPREP ${this.getRegisterLabel(pc,current.A)} -= ${this.getRegisterLabel(pc,current.A+2)}; pc += ${current.sBx}`; case LuaOpcode.OP_TFORCALL: return `TFORCALL ${this.getRegisterLabel(pc,current.A+3)}...${this.getRegisterLabel(pc,current.A+2+current.C)} := ${this.getRegisterLabel(pc,current.A)}(${this.getRegisterLabel(pc,current.A+1)},${this.getRegisterLabel(pc,current.A+2)})`; case LuaOpcode.OP_TFORLOOP: return `TFORLOOP if ${this.getRegisterLabel(pc,current.A+1)} ~= nil then { ${this.getRegisterLabel(pc,current.A)} := ${this.getRegisterLabel(pc,current.A+1)}; pc += ${current.sBx} }`; case LuaOpcode.OP_SETLIST: const C = (current.C ? current.C : next.Ax) - 1; const FPF = 50; return `SETLIST ${this.getRegisterLabel(pc,current.A)}[${(C*FPF)+1}...${(current.B?(C*FPF)+current.B:"")}] := ${this.getRegisterLabel(pc,current.A+1)}...${current.B?this.getRegisterLabel(pc,current.A+current.B):"top"}`; case LuaOpcode.OP_CLOSURE: const func = this.inner_functions[current.Bx]; return `CLOSURE ${this.getRegisterLabel(pc,current.A)} := closure(${func.source}:${func.firstline}-${func.lastline})`; case LuaOpcode.OP_VARARG: return `VARARG ${this.getRegisterLabel(pc,current.A)}...${current.B?this.getRegisterLabel(pc,current.A+current.B-2):"top"}`; case LuaOpcode.OP_EXTRAARG: return `EXTRAARG`; default: return `UNKNOWN OP(${current.Op}) A(${current.A}) B(${current.B}) C(${current.C})`; } } // sizes in newtable are packed into a "float byte" type for expanded range: // (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if // eeeee != 0 and (xxx) otherwise. private fb2int(x:number):number { const e = (x>>3)&0x1f; return e===0?x:(((x&7)+8)<<(e-1)); } private getRegisterOrConstantLabel(pc:number, idx:number) { if (idx & 0x100) { return this.constants[idx & 0xff].label; } else { return this.getRegisterLabel(pc,idx); } } private getUpvalLabel(idx:number) : string { return `Up(${this.upvals[idx]?.name ?? idx})`; } private getRegisterLabel(pc:number,idx:number) : string { let stack = 0; for (let i = 0; i < this.locals.length; i++) { const loc = this.locals[i]; if (loc.start <= pc+1) { if (loc.end >= pc+1) { if (stack === idx ) { return `R(${loc.name})`; } stack++; } } else { break; } } return `R(${idx})`; } }
the_stack
////////////////////////////////////////////////////////////////////////////////////////////////////// /** * de Casteljau's algorithm for drawing and splitting bezier curves. * Inspired by https://pomax.github.io/bezierinfo/ * * @param {Number[][]} points Array of [x,y] points: [start, control1, control2, ..., end] * The original segment to split. * @param {Number} t Where to split the curve (value between [0, 1]) * @return {Object} An object { left, right } where left is the segment from 0..t and * right is the segment from t..1. */ function decasteljau(points, t) { 'worklet'; const left = []; const right = []; function decasteljauRecurse(points, t) { 'worklet'; if (points.length === 1) { left.push(points[0]); right.push(points[0]); } else { const newPoints = Array(points.length - 1); for (let i = 0; i < newPoints.length; i++) { if (i === 0) { left.push(points[0]); } if (i === newPoints.length - 1) { right.push(points[i + 1]); } newPoints[i] = [ (1 - t) * points[i][0] + t * points[i + 1][0], (1 - t) * points[i][1] + t * points[i + 1][1], ]; } decasteljauRecurse(newPoints, t); } } if (points.length) { decasteljauRecurse(points, t); } return { left, right: right.reverse() }; } /** * Convert segments represented as points back into a command object * * @param {Number[][]} points Array of [x,y] points: [start, control1, control2, ..., end] * Represents a segment * @return {Object} A command object representing the segment. */ function pointsToCommand(points) { 'worklet'; const command = {}; if (points.length === 4) { command.x2 = points[2][0]; command.y2 = points[2][1]; } if (points.length >= 3) { command.x1 = points[1][0]; command.y1 = points[1][1]; } command.x = points[points.length - 1][0]; command.y = points[points.length - 1][1]; if (points.length === 4) { // start, control1, control2, end command.type = 'C'; } else if (points.length === 3) { // start, control, end command.type = 'Q'; } else { // start, end command.type = 'L'; } return command; } /** * Runs de Casteljau's algorithm enough times to produce the desired number of segments. * * @param {Number[][]} points Array of [x,y] points for de Casteljau (the initial segment to split) * @param {Number} segmentCount Number of segments to split the original into * @return {Number[][][]} Array of segments */ function splitCurveAsPoints(points, segmentCount) { 'worklet'; segmentCount = segmentCount || 2; const segments = []; let remainingCurve = points; const tIncrement = 1 / segmentCount; // x-----x-----x-----x // t= 0.33 0.66 1 // x-----o-----------x // r= 0.33 // x-----o-----x // r= 0.5 (0.33 / (1 - 0.33)) === tIncrement / (1 - (tIncrement * (i - 1)) // x-----x-----x-----x----x // t= 0.25 0.5 0.75 1 // x-----o----------------x // r= 0.25 // x-----o----------x // r= 0.33 (0.25 / (1 - 0.25)) // x-----o----x // r= 0.5 (0.25 / (1 - 0.5)) for (let i = 0; i < segmentCount - 1; i++) { const tRelative = tIncrement / (1 - tIncrement * i); const split = decasteljau(remainingCurve, tRelative); segments.push(split.left); remainingCurve = split.right; } // last segment is just to the end from the last point segments.push(remainingCurve); return segments; } /** * Convert command objects to arrays of points, run de Casteljau's algorithm on it * to split into to the desired number of segments. * * @param {Object} commandStart The start command object * @param {Object} commandEnd The end command object * @param {Number} segmentCount The number of segments to create * @return {Object[]} An array of commands representing the segments in sequence */ export function splitCurve(commandStart, commandEnd, segmentCount) { 'worklet'; const points = [[commandStart.x, commandStart.y]]; if (commandEnd.x1 != null) { points.push([commandEnd.x1, commandEnd.y1]); } if (commandEnd.x2 != null) { points.push([commandEnd.x2, commandEnd.y2]); } points.push([commandEnd.x, commandEnd.y]); return splitCurveAsPoints(points, segmentCount).map(pointsToCommand); } /** * List of params for each command type in a path `d` attribute */ const typeMap = { M: ['x', 'y'], L: ['x', 'y'], H: ['x'], V: ['y'], C: ['x1', 'y1', 'x2', 'y2', 'x', 'y'], S: ['x2', 'y2', 'x', 'y'], Q: ['x1', 'y1', 'x', 'y'], T: ['x', 'y'], A: ['rx', 'ry', 'xAxisRotation', 'largeArcFlag', 'sweepFlag', 'x', 'y'], Z: [], }; // Add lower case entries too matching uppercase (e.g. 'm' == 'M') Object.keys(typeMap).forEach((key) => { typeMap[key.toLowerCase()] = typeMap[key]; }); function arrayOfLength(length, value) { 'worklet'; const array = Array(length); for (let i = 0; i < length; i++) { array[i] = value; } return array; } /** * Converts a command object to a string to be used in a `d` attribute * @param {Object} command A command object * @return {String} The string for the `d` attribute */ function commandToString(command) { 'worklet'; return `${command.type}${typeMap[command.type] .map((p) => command[p]) .join(',')}`; } /** * Converts command A to have the same type as command B. * * e.g., L0,5 -> C0,5,0,5,0,5 * * Uses these rules: * x1 <- x * x2 <- x * y1 <- y * y2 <- y * rx <- 0 * ry <- 0 * xAxisRotation <- read from B * largeArcFlag <- read from B * sweepflag <- read from B * * @param {Object} aCommand Command object from path `d` attribute * @param {Object} bCommand Command object from path `d` attribute to match against * @return {Object} aCommand converted to type of bCommand */ function convertToSameType(aCommand, bCommand) { 'worklet'; const conversionMap = { x1: 'x', y1: 'y', x2: 'x', y2: 'y', }; const readFromBKeys = ['xAxisRotation', 'largeArcFlag', 'sweepFlag']; // convert (but ignore M types) if (aCommand.type !== bCommand.type && bCommand.type.toUpperCase() !== 'M') { const aConverted = {}; Object.keys(bCommand).forEach((bKey) => { const bValue = bCommand[bKey]; // first read from the A command let aValue = aCommand[bKey]; // if it is one of these values, read from B no matter what if (aValue === undefined) { if (readFromBKeys.includes(bKey)) { aValue = bValue; } else { // if it wasn't in the A command, see if an equivalent was if (aValue === undefined && conversionMap[bKey]) { aValue = aCommand[conversionMap[bKey]]; } // if it doesn't have a converted value, use 0 if (aValue === undefined) { aValue = 0; } } } aConverted[bKey] = aValue; }); // update the type to match B aConverted.type = bCommand.type; aCommand = aConverted; } return aCommand; } /** * Interpolate between command objects commandStart and commandEnd segmentCount times. * If the types are L, Q, or C then the curves are split as per de Casteljau's algorithm. * Otherwise we just copy commandStart segmentCount - 1 times, finally ending with commandEnd. * * @param {Object} commandStart Command object at the beginning of the segment * @param {Object} commandEnd Command object at the end of the segment * @param {Number} segmentCount The number of segments to split this into. If only 1 * Then [commandEnd] is returned. * @return {Object[]} Array of ~segmentCount command objects between commandStart and * commandEnd. (Can be segmentCount+1 objects if commandStart is type M). */ function splitSegment(commandStart, commandEnd, segmentCount) { 'worklet'; let segments = []; // line, quadratic bezier, or cubic bezier if ( commandEnd.type === 'L' || commandEnd.type === 'Q' || commandEnd.type === 'C' ) { segments = segments.concat( splitCurve(commandStart, commandEnd, segmentCount) ); // general case - just copy the same point } else { const copyCommand = Object.assign({}, commandStart); // convert M to L if (copyCommand.type === 'M') { copyCommand.type = 'L'; } segments = segments.concat( arrayOfLength(segmentCount - 1).map(() => copyCommand) ); segments.push(commandEnd); } return segments; } /** * Extends an array of commandsToExtend to the length of the referenceCommands by * splitting segments until the number of commands match. Ensures all the actual * points of commandsToExtend are in the extended array. * * @param {Object[]} commandsToExtend The command object array to extend * @param {Object[]} referenceCommands The command object array to match in length * @param {Function} excludeSegment a function that takes a start command object and * end command object and returns true if the segment should be excluded from splitting. * @return {Object[]} The extended commandsToExtend array */ function extend(commandsToExtend, referenceCommands, excludeSegment) { 'worklet'; // compute insertion points: // number of segments in the path to extend const numSegmentsToExtend = commandsToExtend.length - 1; // number of segments in the reference path. const numReferenceSegments = referenceCommands.length - 1; // this value is always between [0, 1]. const segmentRatio = numSegmentsToExtend / numReferenceSegments; // create a map, mapping segments in referenceCommands to how many points // should be added in that segment (should always be >= 1 since we need each // point itself). // 0 = segment 0-1, 1 = segment 1-2, n-1 = last vertex const countPointsPerSegment = arrayOfLength(numReferenceSegments).reduce( (accum, d, i) => { let insertIndex = Math.floor(segmentRatio * i); // handle excluding segments if ( excludeSegment && insertIndex < commandsToExtend.length - 1 && excludeSegment( commandsToExtend[insertIndex], commandsToExtend[insertIndex + 1] ) ) { // set the insertIndex to the segment that this point should be added to: // round the insertIndex essentially so we split half and half on // neighbouring segments. hence the segmentRatio * i < 0.5 const addToPriorSegment = (segmentRatio * i) % 1 < 0.5; // only skip segment if we already have 1 point in it (can't entirely remove a segment) if (accum[insertIndex]) { // TODO - Note this is a naive algorithm that should work for most d3-area use cases // but if two adjacent segments are supposed to be skipped, this will not perform as // expected. Could be updated to search for nearest segment to place the point in, but // will only do that if necessary. // add to the prior segment if (addToPriorSegment) { if (insertIndex > 0) { insertIndex -= 1; // not possible to add to previous so adding to next } else if (insertIndex < commandsToExtend.length - 1) { insertIndex += 1; } // add to next segment } else if (insertIndex < commandsToExtend.length - 1) { insertIndex += 1; // not possible to add to next so adding to previous } else if (insertIndex > 0) { insertIndex -= 1; } } } accum[insertIndex] = (accum[insertIndex] || 0) + 1; return accum; }, [] ); // extend each segment to have the correct number of points for a smooth interpolation const extended = countPointsPerSegment.reduce((extended, segmentCount, i) => { // if last command, just add `segmentCount` number of times if (i === commandsToExtend.length - 1) { const lastCommandCopies = arrayOfLength( segmentCount, Object.assign({}, commandsToExtend[commandsToExtend.length - 1]) ); // convert M to L if (lastCommandCopies[0].type === 'M') { lastCommandCopies.forEach((d) => { d.type = 'L'; }); } return extended.concat(lastCommandCopies); } // otherwise, split the segment segmentCount times. return extended.concat( splitSegment(commandsToExtend[i], commandsToExtend[i + 1], segmentCount) ); }, []); // add in the very first point since splitSegment only adds in the ones after it extended.unshift(commandsToExtend[0]); return extended; } /** * Takes a path `d` string and converts it into an array of command * objects. Drops the `Z` character. * * @param {String|null} d A path `d` string */ export function pathCommandsFromString(d) { 'worklet'; // split into valid tokens const tokens = (d || '').match(/[MLCSTQAHVZmlcstqahv]|-?[\d.e+-]+/g) || []; const commands = []; let commandArgs; let command; // iterate over each token, checking if we are at a new command // by presence in the typeMap for (let i = 0; i < tokens.length; ++i) { commandArgs = typeMap[tokens[i]]; // new command found: if (commandArgs) { command = { type: tokens[i], }; // add each of the expected args for this command: for (let a = 0; a < commandArgs.length; ++a) { command[commandArgs[a]] = +tokens[i + a + 1]; } // need to increment our token index appropriately since // we consumed token args i += commandArgs.length; commands.push(command); } } return commands; } /** * Interpolate from A to B by extending A and B during interpolation to have * the same number of points. This allows for a smooth transition when they * have a different number of points. * * Ignores the `Z` command in paths unless both A and B end with it. * * This function works directly with arrays of command objects instead of with * path `d` strings (see interpolatePath for working with `d` strings). * * @param {Object[]} aCommandsInput Array of path commands * @param {Object[]} bCommandsInput Array of path commands * @param {Function} excludeSegment a function that takes a start command object and * end command object and returns true if the segment should be excluded from splitting. * @returns {Function} Interpolation function that maps t ([0, 1]) to an array of path commands. */ export function interpolatePathCommands( aCommandsInput, bCommandsInput, excludeSegment ) { 'worklet'; // make a copy so we don't mess with the input arrays let aCommands = aCommandsInput == null ? [] : aCommandsInput.slice(); let bCommands = bCommandsInput == null ? [] : bCommandsInput.slice(); // both input sets are empty, so we don't interpolate if (!aCommands.length && !bCommands.length) { return function nullInterpolator() { 'worklet'; return []; }; } // do we add Z during interpolation? yes if both have it. (we'd expect both to have it or not) const addZ = (aCommands.length === 0 || aCommands[aCommands.length - 1].type === 'Z') && (bCommands.length === 0 || bCommands[bCommands.length - 1].type === 'Z'); // we temporarily remove Z if (aCommands.length > 0 && aCommands[aCommands.length - 1].type === 'Z') { aCommands.pop(); } if (bCommands.length > 0 && bCommands[bCommands.length - 1].type === 'Z') { bCommands.pop(); } // if A is empty, treat it as if it used to contain just the first point // of B. This makes it so the line extends out of from that first point. if (!aCommands.length) { aCommands.push(bCommands[0]); // otherwise if B is empty, treat it as if it contains the first point // of A. This makes it so the line retracts into the first point. } else if (!bCommands.length) { bCommands.push(aCommands[0]); } // extend to match equal size const numPointsToExtend = Math.abs(bCommands.length - aCommands.length); if (numPointsToExtend !== 0) { // B has more points than A, so add points to A before interpolating if (bCommands.length > aCommands.length) { aCommands = extend(aCommands, bCommands, excludeSegment); // else if A has more points than B, add more points to B } else if (bCommands.length < aCommands.length) { bCommands = extend(bCommands, aCommands, excludeSegment); } } // commands have same length now. // convert commands in A to the same type as those in B aCommands = aCommands.map((aCommand, i) => convertToSameType(aCommand, bCommands[i]) ); // create mutable interpolated command objects const interpolatedCommands = aCommands.map((aCommand) => aCommand); if (addZ) { interpolatedCommands.push({ type: 'Z' }); aCommands.push({ type: 'Z' }); // required for when returning at t == 0 } return function pathCommandInterpolator(t) { 'worklet'; // at 1 return the final value without the extensions used during interpolation if (t === 1) { return bCommandsInput == null ? [] : bCommandsInput; } // work with aCommands directly since interpolatedCommands are mutated if (t === 0) { return aCommands; } // interpolate the commands using the mutable interpolated command objs for (let i = 0; i < interpolatedCommands.length; ++i) { // if (interpolatedCommands[i].type === 'Z') continue; const aCommand = aCommands[i]; const bCommand = bCommands[i]; const interpolatedCommand = interpolatedCommands[i]; for (let j = 0; j < typeMap[interpolatedCommand.type].length; j++) { const arg = typeMap[interpolatedCommand.type][j]; interpolatedCommand[arg] = (1 - t) * aCommand[arg] + t * bCommand[arg]; // do not use floats for flags (#27), round to integer if (arg === 'largeArcFlag' || arg === 'sweepFlag') { interpolatedCommand[arg] = Math.round(interpolatedCommand[arg]); } } } return interpolatedCommands; }; } /** * Interpolate from A to B by extending A and B during interpolation to have * the same number of points. This allows for a smooth transition when they * have a different number of points. * * Ignores the `Z` character in paths unless both A and B end with it. * * @param {String} a The `d` attribute for a path * @param {String} b The `d` attribute for a path * @param {Function} excludeSegment a function that takes a start command object and * end command object and returns true if the segment should be excluded from splitting. * @returns {Function} Interpolation function that maps t ([0, 1]) to a path `d` string. */ export function interpolatePath(a, b, excludeSegment) { 'worklet'; let aCommands = pathCommandsFromString(a); let bCommands = pathCommandsFromString(b); if (!aCommands.length && !bCommands.length) { return function nullInterpolator() { 'worklet'; return ''; }; } const commandInterpolator = interpolatePathCommands( aCommands, bCommands, excludeSegment ); return function pathStringInterpolator(t) { 'worklet'; // at 1 return the final value without the extensions used during interpolation if (t === 1) { return b == null ? '' : b; } const interpolatedCommands = commandInterpolator(t); // convert to a string (fastest concat: https://jsperf.com/join-concat/150) let interpolatedString = ''; for (let i = 0; i < interpolatedCommands.length; i++) { const interpolatedCommand = interpolatedCommands[i]; interpolatedString += commandToString(interpolatedCommand); } return interpolatedString; }; }
the_stack
import React from 'react'; import _ from 'lodash'; import { shallow, mount } from 'enzyme'; import sinon from 'sinon'; import assert from 'assert'; import { common } from '../../util/generic-tests'; import DataTable from './DataTable'; import ScrollTable from '../ScrollTable/ScrollTable'; import Checkbox from '../Checkbox/Checkbox'; import EmptyStateWrapper from '../EmptyStateWrapper/EmptyStateWrapper'; import DragCaptureZone from '../DragCaptureZone/DragCaptureZone'; const { Column, ColumnGroup } = DataTable; const { EmptyStateWrapper: { Title, Body }, } = DataTable; const testData: any = [ { id: '01', first_name: 'Isaac', last_name: 'Newton', email: 'inewton@example.com', occupation: 'Physicist', isDisabled: true, isSelected: true, isActive: true, }, { id: '02', first_name: 'Albert', last_name: 'Einstein', email: 'aeinstein@example.com', occupation: 'Physicist', isDisabled: false, isSelected: false, isActive: false, }, { id: '03', first_name: 'Leonardo', last_name: 'da Vinci', email: 'ldvinci@example.com', occupation: 'Engineer', isDisabled: true, isSelected: true, isActive: true, }, { id: '04', first_name: 'Aristotle', last_name: '--', email: 'aristotle@example.com', occupation: 'Tutor', isDisabled: false, isSelected: false, isActive: false, }, { id: '05', first_name: 'Galileo', last_name: 'Galilei', email: 'ggalilei@example.com', occupation: 'Physicist', isDisabled: false, isSelected: true, isActive: true, }, { id: '06', first_name: 'Charles', last_name: 'Darwin', email: 'cdarwin@example.com', occupation: 'Biologist', isDisabled: true, isSelected: false, isActive: false, }, { id: '07', first_name: 'Alexander', last_name: 'Macedon', email: 'amacedon@example.com', occupation: 'Head of State', isDisabled: true, isSelected: false, isActive: true, }, { id: '08', first_name: 'Plato', last_name: 'Plato', email: 'plato@example.com', occupation: 'Philosopher', isDisabled: false, isSelected: true, isActive: false, }, { id: '09', first_name: 'Mahatma', last_name: 'Gandhi', email: 'mgandhi@example.com', occupation: 'Politician', isDisabled: true, isSelected: true, isActive: false, }, { id: '10', first_name: 'William', last_name: 'Shakespeare', email: 'wshakespear@example.com', occupation: 'Playwright', isDisabled: false, isSelected: false, isActive: true, }, ]; describe('DataTable', () => { common(DataTable, { selectRoot: (wrapper: any) => wrapper.find(ScrollTable), } as any); describe('render', () => { it('should render a minimal ScrollTable', () => { const wrapper = shallow(<DataTable data={[]} />); const scrollTableWrapper = wrapper.find(ScrollTable).shallow(); assert( scrollTableWrapper.is('.lucid-DataTable'), 'must have the component className' ); assert.equal( scrollTableWrapper.find(ScrollTable.Thead).length, 1, 'must contain a Thead' ); assert.equal( scrollTableWrapper.find(ScrollTable.Tbody).length, 1, 'must contain a Tbody' ); }); }); describe('props', () => { describe('data', () => { it('should render 10 empty rows by default if data is an empty array', () => { const wrapper = shallow(<DataTable data={[]} />); const TrWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); assert.equal(TrWrapper.length, 10, 'should render 10 empty rows'); }); it('should render a row for each element in the array if data size is greater than or equal to 10', () => { const wrapper = shallow(<DataTable data={testData} />); const TrWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); assert.equal( TrWrapper.length, testData.length, 'number of rendered rows must match size of the data array' ); }); it('should render a cell in each row for each object property in the array elements', () => { const testDataWithEmptyCells: any = [ { id: 1, first_name: 'Isaac', email: 'inewton@example.com', occupation: 'Physicist', isDisabled: true, isSelected: true, isActive: true, }, { id: 2, first_name: 'Albert', last_name: null, email: 'aeinstein@example.com', occupation: 'Physicist', isDisabled: false, isSelected: false, isActive: false, }, ]; const wrapper = shallow( <DataTable data={testDataWithEmptyCells}> <Column field='id' title='ID' /> <Column field='first_name' title='First' /> <Column field='last_name' title='Last' /> <Column field='email' title='Email' /> <Column field='occupation' title='Occupation' /> </DataTable> ); // select the rows of the rendered table const trsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); // for each row check that the correct cells are rendered in order trsWrapper.forEach((trWrapper, index) => { if (index < 2) { const tdsWrapper = trWrapper.shallow().find(ScrollTable.Td); assert.equal( trWrapper.props().isDisabled, _.get(testDataWithEmptyCells[index], 'isDisabled'), 'row must be passed `isDisabled`' ); assert.equal( trWrapper.props().isSelected, _.get(testDataWithEmptyCells[index], 'isSelected'), 'row must be passed `isSelected`' ); assert.equal( trWrapper.props().isActive, _.get(testDataWithEmptyCells[index], 'isActive'), 'row must be passed `isActive`' ); assert.equal( tdsWrapper.at(0).children().text(), _.get(testDataWithEmptyCells[index], 'id'), 'first cell must match id of current row' ); assert( !tdsWrapper.at(0).prop('isEmpty'), 'should not be marked as empty, despite not being a string' ); assert.equal( tdsWrapper.at(1).children().text(), _.get(testDataWithEmptyCells[index], 'first_name'), 'second cell must match first_name of current row' ); assert.equal( tdsWrapper.at(2).children().text(), '--', 'third (empty) cell should be `--`' ); assert.equal( tdsWrapper.at(3).children().text(), _.get(testDataWithEmptyCells[index], 'email'), 'fourth cell must match email of current row' ); assert.equal( tdsWrapper.at(4).children().text(), _.get(testDataWithEmptyCells[index], 'occupation'), 'fifth cell must match occupation of current row' ); } }); }); it('should render without prop warning for isSelected when data is empty array', () => { const emptyData: any = []; const wrapper = shallow(<DataTable isSelectable data={emptyData} />); expect(wrapper.find(Checkbox).props().isSelected).toEqual(false); }); }); describe('minRows', () => { it('should render 10 empty rows if data is an empty array', () => { const wrapper = shallow(<DataTable data={[]} />); const TrWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); assert.equal(TrWrapper.length, 10, 'should render 10 empty rows'); }); it('should render a row for each element in the array if there is more data than `minRows`', () => { const wrapper = shallow(<DataTable data={testData} minRows={7} />); const TrWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); assert.equal( TrWrapper.length, testData.length, 'number of rendered rows must match size of the data array' ); }); it('should render at least the number of `minRows` if there is less data than `minRows`', () => { const wrapper = shallow(<DataTable data={testData} minRows={14} />); const TrWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); assert.equal( TrWrapper.length, 14, 'number of rendered rows must match `minRows` value' ); }); }); describe('isSelectable', () => { it('should render a checkbox in the first column of each row', () => { const wrapper = shallow( <DataTable isSelectable data={testData}> <Column field='id' title='ID' /> <Column field='first_name' title='First' /> <Column field='last_name' title='Last' /> <Column field='email' title='Email' /> <Column field='occupation' title='Occupation' /> </DataTable> ); // select the rows of the rendered table body const bodyTrsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); // for each row check that isSelectable matches bodyTrsWrapper.forEach((trWrapper) => { const tdsWrapper = trWrapper.shallow().find(ScrollTable.Td); const tdArray = tdsWrapper.map((tdWrapper) => tdWrapper.shallow()); assert.equal( tdArray[0].find(Checkbox).length, 1, 'first cell must be a checkbox' ); }); }); it('should default to false', () => { const wrapper = shallow( <DataTable data={testData}> <Column field='id' title='ID' /> <Column field='first_name' title='First' /> <Column field='last_name' title='Last' /> <Column field='email' title='Email' /> <Column field='occupation' title='Occupation' /> </DataTable> ); // select the rows of the rendered table body const bodyTrsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); // for each row check that isSelectable matches bodyTrsWrapper.forEach((trWrapper) => { const tdsWrapper = trWrapper.shallow().find(ScrollTable.Td); const tdArray = tdsWrapper.map((tdWrapper) => tdWrapper.shallow()); assert.equal( tdArray[0].find(Checkbox).length, 0, 'first cell must not be a checkbox' ); }); }); }); describe('isActionable', () => { it('should pass thru to the underlying ScrollTable rows', () => { const wrapper = shallow(<DataTable isActionable data={testData} />); // select the rows of the rendered table const trsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); // for each row check that isActionable matches trsWrapper.forEach((trWrapper) => { assert.equal(trWrapper.prop('isActionable'), true); }); }); it('should default to false', () => { const wrapper = shallow(<DataTable data={testData} />); // select the rows of the rendered table const trsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); // for each row check that isActionable is false trsWrapper.forEach((trWrapper) => { assert.equal(trWrapper.prop('isActionable'), false); }); }); }); describe('onSelect', () => { it('should be triggered when a checkbox is selected passing params row data and index', () => { const onSelect: any = sinon.spy(); const wrapper = shallow( <DataTable isSelectable onSelect={onSelect} data={testData}> <Column field='id' title='ID' /> <Column field='first_name' title='First' /> <Column field='last_name' title='Last' /> <Column field='email' title='Email' /> <Column field='occupation' title='Occupation' /> </DataTable> ); // select the rows of the rendered table body const bodyTrsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); // for each row check that isSelectable matches bodyTrsWrapper.forEach((trWrapper, index) => { const tdsWrapper = trWrapper.shallow().find(ScrollTable.Td); const tdArray = tdsWrapper.map((tdWrapper) => tdWrapper.shallow()); const checkBoxOnSelectFunction = tdArray[0] .find(Checkbox) .prop('onSelect'); // @ts-ignore checkBoxOnSelectFunction({}); assert.equal(onSelect.callCount, index + 1, 'must be called'); assert.equal( onSelect.getCall(index).args[0], testData[index], 'first arg must match the selected row data' ); assert.equal( onSelect.getCall(index).args[1], index, 'second arg must match the clicked row index' ); assert( _.has(onSelect.getCall(index).args[2], 'props'), 'third arg must include props' ); assert( _.has(onSelect.getCall(index).args[2], 'event'), 'third arg must include event' ); }); }); it('should have inDeterminate on the header checkbox when data is partially selected', () => { const wrapper = shallow( <DataTable isSelectable data={testData}> <Column field='id' title='ID' /> <Column field='first_name' title='First' /> <Column field='last_name' title='Last' /> <Column field='email' title='Email' /> <Column field='occupation' title='Occupation' /> </DataTable> ); // select the rows of the rendered table head const headTrsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Thead) .shallow() .find(ScrollTable.Tr); const firstHeadCellWrapper = headTrsWrapper .shallow() .find(ScrollTable.Th) .first(); const selectAllCheckboxWrapper = firstHeadCellWrapper.find(Checkbox); assert.equal( true, selectAllCheckboxWrapper.prop('isIndeterminate'), 'The CheckBox should be in an indeterminate state' ); }); }); describe('onSelectAll', () => { it('should be triggered when a checkbox is selected passing params row data and index', () => { const onSelectAll = sinon.spy(); const wrapper = shallow( <DataTable isSelectable onSelectAll={onSelectAll} data={testData}> <Column field='id' title='ID' /> <Column field='first_name' title='First' /> <Column field='last_name' title='Last' /> <Column field='email' title='Email' /> <Column field='occupation' title='Occupation' /> </DataTable> ); // select the rows of the rendered table head const headTrsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Thead) .shallow() .find(ScrollTable.Tr); const firstHeadCellWrapper = headTrsWrapper .shallow() .find(ScrollTable.Th) .first(); const selectAllCheckboxWrapper = firstHeadCellWrapper.find(Checkbox); const checkboxSelectAllFunction = selectAllCheckboxWrapper.prop('onSelect'); //@ts-ignore checkboxSelectAllFunction({}); assert(onSelectAll.called, 'onSelectAll handler must be called'); }); }); describe('onRowClick', () => { it('should be triggered when row is clicked', () => { const onRowClick = sinon.spy(); const wrapper = shallow( <DataTable isActionable onRowClick={onRowClick} data={testData}> <Column field='id' title='ID' /> <Column field='first_name' title='First' /> <Column field='last_name' title='Last' /> <Column field='email' title='Email' /> <Column field='occupation' title='Occupation' /> </DataTable> ); // select the rows of the rendered table body const bodyTrsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Tbody) .shallow() .find(ScrollTable.Tr); // for each row check that isSelectable matches bodyTrsWrapper.forEach((trWrapper, index) => { const rowClickFunction = trWrapper.prop('onClick'); // @ts-ignore rowClickFunction({ target: { tagName: 'tr' } }); assert.equal(onRowClick.callCount, index + 1, 'must be called'); assert.equal( onRowClick.getCall(index).args[0], testData[index], 'first arg must match the selected row data' ); assert.equal( onRowClick.getCall(index).args[1], index, 'second arg must match the clicked row index' ); assert( _.has(onRowClick.getCall(index).args[2], 'props'), 'third arg must include props' ); assert( _.has(onRowClick.getCall(index).args[2], 'event'), 'third arg must include event' ); }); }); }); describe('onSort', () => { it('should be triggered when a column header with `isSortable` is clicked', () => { const onSort = sinon.spy(); const wrapper = shallow( <DataTable isActionable onSort={onSort} data={testData}> <Column field='id' isSortable title='ID' /> <Column field='first_name' isSortable title='First' /> <Column field='last_name' isSortable title='Last' /> <Column field='email' isSortable title='Email' /> <Column field='occupation' isSortable title='Occupation' /> </DataTable> ); // select the rows of the rendered table head const headTrsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Thead) .shallow() .find(ScrollTable.Tr); const thsWrapper = headTrsWrapper.shallow().find(ScrollTable.Th); const tdArray = thsWrapper.map((tdWrapper) => tdWrapper.shallow()); const mockEvent = { stopPropagation: _.noop, preventDefault: _.noop }; tdArray[0].simulate('click', mockEvent); assert.equal(onSort.callCount, 1, 'must be called once'); assert.equal( onSort.getCall(0).args[0], 'id', 'first arg must be passed `id` as the field name' ); assert( _.has(onSort.getCall(0).args[1], 'props'), 'last arg must be passed props' ); assert( _.has(onSort.getCall(0).args[1], 'event'), 'last arg must be passed event' ); tdArray[1].simulate('click', mockEvent); assert.equal(onSort.callCount, 2, 'must be called twice'); assert.equal( onSort.getCall(1).args[0], 'first_name', 'first arg must be passed `first_name` as the field name' ); assert( _.has(onSort.getCall(1).args[1], 'props'), 'last arg must be passed props' ); assert( _.has(onSort.getCall(1).args[1], 'event'), 'last arg must be passed event' ); tdArray[2].simulate('click', mockEvent); assert.equal(onSort.callCount, 3, 'must be called three times'); assert.equal( onSort.getCall(2).args[0], 'last_name', 'first arg must be passed `last_name` as the field name' ); assert( _.has(onSort.getCall(2).args[1], 'props'), 'last arg must be passed props' ); assert( _.has(onSort.getCall(2).args[1], 'event'), 'last arg must be passed event' ); tdArray[3].simulate('click', mockEvent); assert.equal(onSort.callCount, 4, 'must be called four times'); assert.equal( onSort.getCall(3).args[0], 'email', 'first arg must be passed `email` as the field name' ); assert( _.has(onSort.getCall(3).args[1], 'props'), 'last arg must be passed props' ); assert( _.has(onSort.getCall(3).args[1], 'event'), 'last arg must be passed event' ); tdArray[4].simulate('click', mockEvent); assert.equal(onSort.callCount, 5, 'must be called five times'); assert.equal( onSort.getCall(4).args[0], 'occupation', 'first arg must be passed `occupation` as the field name' ); assert( _.has(onSort.getCall(4).args[1], 'props'), 'last arg must be passed props' ); assert( _.has(onSort.getCall(4).args[1], 'event'), 'last arg must be passed event' ); }); }); describe('isLoading', () => { it('should show a `LoadingIndicator` if `isLoading`', () => { const wrapper = shallow(<DataTable data={[]} isLoading />); const loadingIndicatorWrapper = wrapper .find(EmptyStateWrapper) .shallow() .find('LoadingIndicator'); assert(loadingIndicatorWrapper.prop('isLoading')); }); }); describe('anchorMessage', () => { it('should position the `LoadingMessage`/`EmpyStateMessage` near the top of the table', () => { const loadingWrapper = shallow( <DataTable data={[]} isLoading anchorMessage /> ); const loadingOverlayWrapper = loadingWrapper .find(EmptyStateWrapper) .shallow() .find('LoadingIndicator') .shallow() .find('OverlayWrapper'); assert(loadingOverlayWrapper.prop('anchorMessage')); const emptyWrapper = shallow(<DataTable data={[]} anchorMessage />); const emptyOverlayWrapper = emptyWrapper .find(EmptyStateWrapper) .shallow() .find('OverlayWrapper'); assert(emptyOverlayWrapper.prop('anchorMessage')); }); }); describe('isFullWidth', () => { it('should apply the `&-full-width` class if `isFullWidth` is true', () => { const wrapper = shallow(<DataTable data={[]} isFullWidth />); assert( wrapper.find(ScrollTable).hasClass('lucid-DataTable-full-width') ); }); }); describe('isResize', () => { it('should show a `resizer` if `isResizable equals to true`', () => { const onResize = jest.fn(); const wrapper = mount( <DataTable hasFixedHeader onResize={onResize} data={testData}> <Column minWidth={50} field='id' isResizable title='ID' /> <Column field='first_name' isResizable title='First' /> <Column field='last_name' isResizable title='Last' /> <Column field='email' isResizable title='Email' /> <Column field='occupation' isResizable title='Occupation' /> </DataTable> ); const dragCaptureZoneWrapper = wrapper.find(DragCaptureZone).at(1); const mockEvent = new Event('mouseup'); dragCaptureZoneWrapper.prop('onDragEnd')( { dx: 100, dy: 0, pageX: 100, pageY: 0, } as any, { event: mockEvent, props: {}, } as any ); }); }); }); describe('child components', () => { describe('Column', () => { it('should render a column in the header for each Column defined', () => { const wrapper = shallow( <DataTable data={testData}> <Column field='id' title='ID' /> <Column field='first_name' title='First' /> <Column field='last_name' title='Last' /> <Column field='email' title='Email' /> <Column field='occupation' title='Occupation' /> </DataTable> ); // select the rows of the rendered table head const headTrsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Thead) .shallow() .find(ScrollTable.Tr); const thsWrapper = headTrsWrapper.shallow().find(ScrollTable.Th); const tdArray = thsWrapper.map((tdWrapper) => tdWrapper.shallow()); assert.equal( tdArray[0].text(), 'ID', 'first column must render correct title' ); assert.equal( tdArray[1].text(), 'First', 'second column must render correct title' ); assert.equal( tdArray[2].text(), 'Last', 'third column must render correct title' ); assert.equal( tdArray[3].text(), 'Email', 'fourth column must render correct title' ); assert.equal( tdArray[4].text(), 'Occupation', 'last column must render correct title' ); }); }); describe('ColumnGroup', () => { it('should render a cell with colspan in the header for each Column defined within', () => { const wrapper = shallow( <DataTable data={testData}> <Column field='id' title='ID' /> <ColumnGroup title='Name'> <Column field='first_name' title='First' /> <Column field='last_name' title='Last' /> </ColumnGroup> <Column field='email' title='Email' /> <Column field='occupation' title='Occupation' /> </DataTable> ); // select the rows of the rendered table head const headTrsWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Thead) .shallow() .find(ScrollTable.Tr); const thsFirstRowWrapper = headTrsWrapper .at(0) .shallow() .find(ScrollTable.Th); const thsSecondRowWrapper = headTrsWrapper .at(1) .shallow() .find(ScrollTable.Th); const thFirstRowArray = thsFirstRowWrapper.map((thWrapper) => thWrapper.shallow() ); const thSecondRowArray = thsSecondRowWrapper.map((thWrapper) => thWrapper.shallow() ); assert.equal( thFirstRowArray[0].text(), 'ID', 'must render correct title' ); assert.equal( thFirstRowArray[0].prop('rowSpan'), 2, 'rowSpan must be 2' ); assert.equal( thFirstRowArray[1].text(), 'Name', 'must render correct title for grouped column' ); assert.equal( thFirstRowArray[1].prop('colSpan'), 2, 'colSpan must be 2 for grouped column' ); assert.equal( thSecondRowArray[0].text(), 'First', 'must render correct title' ); assert( !_.isEqual(thSecondRowArray[0].prop('rowSpan'), 2), 'rowSpan must not be 2' ); assert.equal( thSecondRowArray[1].text(), 'Last', 'must render correct title' ); assert( !_.isEqual(thSecondRowArray[1].prop('rowSpan'), 2), 'rowSpan must not be 2' ); assert.equal( thFirstRowArray[2].text(), 'Email', 'must render correct title' ); assert.equal( thFirstRowArray[2].prop('rowSpan'), 2, 'rowSpan must be 2' ); assert.equal( thFirstRowArray[3].text(), 'Occupation', 'must render correct title' ); assert.equal( thFirstRowArray[3].prop('rowSpan'), 2, 'rowSpan must be 2' ); }); it('should default to align=center', () => { const wrapper = shallow( <DataTable data={testData}> <Column field='id' title='ID' /> <ColumnGroup title='Name'> <Column field='first_name' title='First' /> <Column field='last_name' title='Last' /> </ColumnGroup> <Column field='email' title='Email' /> <Column field='occupation' title='Occupation' /> </DataTable> ); const thWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Thead) .shallow() .find(ScrollTable.Tr) .first() .shallow() .find(ScrollTable.Th) .at(1) .shallow(); assert(thWrapper.hasClass('lucid-Table-align-center'), 'must be true'); }); it('should respect align prop', () => { const wrapper = shallow( <DataTable data={testData}> <Column field='id' title='ID' /> <ColumnGroup title='Name' align='right'> <Column field='first_name' title='First' /> <Column field='last_name' title='Last' /> </ColumnGroup> <Column field='email' title='Email' /> <Column field='occupation' title='Occupation' /> </DataTable> ); const thWrapper = wrapper .find(ScrollTable) .shallow() .find(ScrollTable.Thead) .shallow() .find(ScrollTable.Tr) .first() .shallow() .find(ScrollTable.Th) .at(1) .shallow(); assert(thWrapper.hasClass('lucid-Table-align-right'), 'must be true'); }); }); describe('EmptyStateWrapper Title', () => { it('should render the message title element', () => { const titleText = 'Here is the Title Text'; const wrapper = shallow( <DataTable data={[]}> <EmptyStateWrapper> <Title>{titleText}</Title> </EmptyStateWrapper> </DataTable> ); const messageTitleWrapper = wrapper .find(EmptyStateWrapper) .shallow() .find('.lucid-EmptyStateWrapper-message-title') .shallow(); assert.equal( messageTitleWrapper.text(), titleText, 'must contain the title text' ); }); }); describe('EmptyStateWrapper Body', () => { it('should render the message body element', () => { const bodyElement = ( <div className='parent-div'> <div className='nested-div' /> </div> ); const wrapper = shallow( <DataTable data={[]}> <EmptyStateWrapper> <Body>{bodyElement}</Body> </EmptyStateWrapper> </DataTable> ); const messageBodyWrapper = wrapper.find(EmptyStateWrapper).shallow(); assert( messageBodyWrapper.contains(bodyElement), 'must contain the body element' ); }); }); describe('cellValue is a function', () => { it('should pass column width as a prop to cellValue', () => { const testDataWithFunctionInCellValue: any = [ { id: 1, first_name: 'Isaac', email: 'inewton@example.com', occupation: 'Physicist', isDisabled: true, isSelected: true, isActive: true, status: (width) => <Checkbox width={width} />, }, ]; const wrapper = mount( <DataTable hasFixedHeader data={testDataWithFunctionInCellValue}> <Column field='id' isResizable title='ID' /> <Column field='first_name' isResizable title='First' /> <Column field='last_name' isResizable title='Last' /> <Column field='email' isResizable title='Email' /> <Column field='occupation' isResizable title='Occupation' /> <Column field='status' isResizable title='Status' /> </DataTable> ); expect(wrapper.find(Checkbox).props()).toHaveProperty('width'); }); }); }); });
the_stack
import { Loki } from "../../src/loki"; import { Collection } from "../../src/collection"; describe("loki", () => { let db: Loki; interface User { name: string; age: number; lang: string; } let users: Collection<User>; beforeEach(() => { db = new Loki("test.json"); users = db.addCollection<User>("user"); users.insert({ name: "dave", age: 25, lang: "English" }); users.insert({ name: "joe", age: 39, lang: "Italian" }); users.insert({ name: "jonas", age: 30, lang: "Swedish" }); }); describe("core methods", () => { it("works", () => { const tdb = new Loki("regextests"); const tcu = tdb.addCollection<User>("user"); tcu.insert({ name: "abcd", age: 25, lang: "English" }); tcu.insert({ name: "AbCd", age: 39, lang: "Italian" }); tcu.insert({ name: "acdb", age: 30, lang: "Swedish" }); tcu.insert({ name: "aBcD", age: 30, lang: "Swedish" }); // findOne() const j = users.findOne({ "name": "jonas" }); expect(j.name).toEqual("jonas"); // find() const result = users.find({ "age": { "$gt": 29 } }); expect(result.length).toEqual(2); // $regex test with raw regex expect(users.find({ "name": { "$regex": /o/ } }).length).toEqual(2); // case insensitive regex with array of ["pattern", "options"] expect(tcu.find({ "name": { "$regex": ["abcd", "i"] } }).length).toEqual(3); // regex with single encoded string pattern (no options) expect(tcu.find({ "name": { "$regex": "cd" } }).length).toEqual(2); // $contains expect(users.find({ "name": { "$contains": "jo" } }).length).toEqual(2); // $contains using array element expect(users.find({ "name": { "$contains": ["jo"] } }).length).toEqual(2); // $contains any with one value expect(users.find({ "name": { "$containsAny": "nas" } }).length).toEqual(1); // $contains any with multiple values expect(users.find({ "name": { "$containsAny": ["nas", "dave"] } }).length).toEqual(2); // insert() : try inserting existing document (should fail), try adding doc with legacy id column const collectionLength = users.count(); const objDave = users.findOne({ "name": "dave" }); let wasAdded = true; try { users.insert(objDave); } catch (err) { wasAdded = false; } expect(wasAdded).toEqual(false); expect(collectionLength).toEqual(users.count()); // our collections are not strongly typed so lets invent some object that has its 'own' id column let legacyObject = { id: 999, first: "aaa", last: "bbb", city: "pasadena", state: "ca" }; wasAdded = true; try { users.insert(legacyObject as any); } catch (err) { wasAdded = false; } expect(wasAdded).toEqual(true); // remove object so later queries access valid properties on all objects if (wasAdded) { users.remove(legacyObject as any); // the object itself should have been modified } // update() legacyObject = { id: 998, first: "aaa", last: "bbb", city: "pasadena", state: "ca" }; let wasUpdated = true; try { users.update(legacyObject as any); } catch (err) { wasUpdated = false; } expect(wasUpdated).toEqual(false); // remove() - add some bogus object to remove const userCount1 = users.count(); const testObject = { first: "aaa", last: "bbb", city: "pasadena", state: "ca" }; users.insert(testObject as any); expect(userCount1 + 1).toEqual(users.count()); users.remove(testObject as any); expect(userCount1).toEqual(users.count()); }); it("meta not set on returned objects", function () { const tdb = new Loki("test.db"); const coll = tdb.addCollection<{ a: number, b: number }>("tc", { disableMeta: true }); // verify single insert return objs do not have meta set const obj = coll.insert({ a: 1, b: 2 }); expect(obj.hasOwnProperty("meta")).toEqual(false); expect(obj.hasOwnProperty("$loki")).toEqual(true); // verify batch insert return objs do not have meta set const objs = coll.insert([{ a: 2, b: 3 }, { a: 3, b: 4 }]); expect(Array.isArray(objs)); objs.forEach((o) => { expect(o.hasOwnProperty("meta")).toEqual(false); expect(o.hasOwnProperty("$loki")).toEqual(true); }); }); }); describe("dot notation", () => { it("works", () => { interface DNC { first: string; last: string; addr?: { street?: string; state?: string; zip?: number; }; } const dnc = db.addCollection<DNC, { "addr.state": string, "addr.zip": number }>("dncoll", { nestedProperties: ["addr.state", "addr.zip"] }); dnc.insert({ first: "aaa", last: "bbb", addr: { street: "111 anystreet", state: "AS", zip: 12345 } }); dnc.insert({ first: "ddd", last: "eee", addr: { street: "222 anystreet", state: "FF", zip: 32345 } }); // make sure it can handle case where top level property doesn't exist dnc.insert({ first: "mmm", last: "nnn" }); // make sure it can handle case where subscan property doesn't exist dnc.insert({ first: "ooo", last: "ppp", addr: { state: "YY" } }); dnc.insert({ first: "jjj", last: "kkk", addr: { street: "777 anystreet", state: "WW", zip: 12345 } }); // test dot notation using regular find (with multiple results) const firstResult = dnc.find({ "addr.zip": 12345 }); expect(firstResult.length).toEqual(2); expect(firstResult[0].addr.zip).toEqual(12345); expect(firstResult[1].addr.zip).toEqual(12345); // test not notation using findOne const secObj = dnc.findOne({ "addr.state": "FF" }); expect(secObj !== null).toBeTruthy(); expect(secObj.addr.zip).toEqual(32345); }); it("with transaction", () => { const dnc = db.addCollection<{ first: string, addr: { zip: number } }, { "addr.zip": number }>("dncoll", { nestedProperties: ["addr.zip"], transactional: true, unique: ["first"] }); const doc = dnc.insert({first: "abc", addr: {zip: 12345}}); expect(doc["addr.zip"]).toBeDefined(); expect(() => dnc.insert({first: "abc", addr: {zip: 54321}})).toThrowError(); expect(dnc.find({"first": "abc"})[0]["addr.zip"]).toBeDefined(); }); }); // We only support dot notation involving array when // the leaf property is the array. This verifies that functionality describe("dot notation across leaf object array", () => { it("works", () => { interface ABC { id: number; children: { someProperty?: number }[]; } const dna = db.addCollection<ABC, { "children.someProperty": number[] }>("dnacoll", { nestedProperties: ["children.someProperty"] }); dna.insert({ id: 1, children: [{ someProperty: 11 }] }); dna.insert({ id: 2, children: [{ someProperty: 22 }] }); dna.insert({ id: 3, children: [{ someProperty: 33 }, { someProperty: 22 }] }); dna.insert({ id: 4, children: [{ someProperty: 11 }] }); dna.insert({ id: 5, children: [{ // Missing }] }); dna.insert({ id: 6, children: [{ someProperty: null }] }); let results = dna.find({ "children.someProperty": { "$contains": 33 } }); expect(results.length).toEqual(1); results = dna.find({ "children.someProperty": { "$contains": 22 } }); expect(results.length).toEqual(2); results = dna.find({ "children.someProperty": { "$contains": 11 } }); expect(results.length).toEqual(2); }); }); describe("dot notation terminating at leaf array", () => { it("works", () => { interface ABC { relations: { ids: number[]; }; } const dna = db.addCollection<ABC, { "relations.ids": number[] }>("dnacoll", { nestedProperties: ["relations.ids"] }); dna.insert({ "relations": { "ids": [379] } }); dna.insert({ "relations": { "ids": [12, 379] } }); dna.insert({ "relations": { "ids": [111] } }); const results = dna.find({ "relations.ids": { $contains: 379 } }); expect(results.length).toEqual(2); }); }); describe("dot notation across child array", () => { it("works", () => { interface ABC { id: number; children: { id: number; someArray: { someProperty?: number }[] }[]; } const dna = db.addCollection<ABC, { "children.someArray.someProperty": number[] }>("dnacoll", { nestedProperties: ["children.someArray.someProperty"] }); dna.insert({ id: 1, children: [{ id: 11, someArray: [{ someProperty: 111 }] }] }); dna.insert({ id: 2, children: [{ id: 22, someArray: [{ someProperty: 222 }] }] }); dna.insert({ id: 3, children: [{ id: 33, someArray: [{ someProperty: 333 }, { someProperty: 222 }] }] }); dna.insert({ id: 4, children: [{ id: 44, someArray: [{ someProperty: 111 }] }] }); dna.insert({ id: 5, children: [{ id: 55, someArray: [{ // Missing }] }] }); dna.insert({ id: 6, children: [{ id: 66, someArray: [{ someProperty: null }] }] }); let results = dna.find({ "children.someArray.someProperty": { "$contains": 333 } }); expect(results.length).toEqual(1); results = dna.find({ "children.someArray.someProperty": { "$contains": 111 } }); expect(results.length).toEqual(2); results = dna.find({ "children.someArray.someProperty": { "$contains": 222 } }); expect(results.length).toEqual(2); results = dna.find({ "$and": [{ "id": 3 }, { "children.someArray.someProperty": { "$contains": 222 } }] }); expect(results.length).toEqual(1); results = dna.find({ "$and": [{ "id": 1 }, { "children.someArray.someProperty": { "$contains": 222 } }] }); expect(results.length).toEqual(0); results = dna.find({ "$or": [{ "id": 1 }, { "children.someArray.someProperty": { "$contains": 222 } }] }); expect(results.length).toEqual(3); }); }); describe("avl indexes", () => { it("works", () => { interface ITC { "testid": number; } const itc = db.addCollection<ITC>("test", { rangedIndexes: { testid: { indexTypeName: "avl", comparatorName: "js" } } }); itc.insert({ "testid": 1 }); itc.insert({ "testid": 2 }); itc.insert({ "testid": 5 }); itc.insert({ "testid": 5 }); itc.insert({ "testid": 9 }); itc.insert({ "testid": 11 }); itc.insert({ "testid": 22 }); itc.insert({ "testid": 22 }); // lte let results = itc.find({ "testid": { "$lte": 1 } }); expect(results.length).toEqual(1); results = itc.find({ "testid": { "$lte": 22 } }); expect(results.length).toEqual(8); // lt results = itc.find({ "testid": { "$lt": 1 } }); expect(results.length).toEqual(0); results = itc.find({ "testid": { "$lt": 22 } }); expect(results.length).toEqual(6); // eq results = itc.find({ "testid": { "$eq": 22 } }); expect(results.length).toEqual(2); // gt results = itc.find({ "testid": { "$gt": 22 } }); expect(results.length).toEqual(0); results = itc.find({ "testid": { "$gt": 5 } }); expect(results.length).toEqual(4); // gte results = itc.find({ "testid": { "$gte": 5 } }); expect(results.length).toEqual(6); results = itc.find({ "testid": { "$gte": 10 } }); expect(results.length).toEqual(3); }); }); describe("ResultSet", () => { it("works", () => { // ResultSet find expect(users.chain().find({ "age": { "$gte": 30 } }).where((obj: User) => obj.lang === "Swedish").data().length).toEqual(1); // ResultSet offset expect(users.chain().offset(1).data().length).toEqual(users.count() - 1); // ResultSet limit expect(users.chain().limit(2).data().length).toEqual(2); }); }); describe("andOrOps", () => { it("works", () => { interface EIC { "testid": number; "testString": string; "testFloat": number; } const eic = db.addCollection<EIC>("eic"); eic.insert({ "testid": 1, "testString": "hhh", "testFloat": 5.2 }); //0 eic.insert({ "testid": 1, "testString": "bbb", "testFloat": 6.2 }); //1 eic.insert({ "testid": 5, "testString": "zzz", "testFloat": 7.2 }); //2 eic.insert({ "testid": 6, "testString": "ggg", "testFloat": 1.2 }); //3 eic.insert({ "testid": 9, "testString": "www", "testFloat": 8.2 }); //4 eic.insert({ "testid": 11, "testString": "yyy", "testFloat": 4.2 }); //5 eic.insert({ "testid": 22, "testString": "bbb", "testFloat": 9.2 }); //6 eic.insert({ "testid": 23, "testString": "m", "testFloat": 2.2 }); //7 // coll.find explicit $and expect(eic.find({ "$and": [{ "testid": 1 }, { "testString": "bbb" }] }).length).toEqual(1); // coll.find implicit '$and' expect(eic.find({ "testid": 1, "testString": "bbb" }).length).toEqual(1); // ResultSet.find explicit $and expect(eic.chain().find({ "$and": [{ "testid": 1 }, { "testString": "bbb" }] }).data().length).toEqual(1); // ResultSet.find implicit $and expect(eic.chain().find({ "testid": 1, "testString": "bbb" }).data().length).toEqual(1); // ResultSet.find explicit operators expect(eic.chain().find({ "$and": [{ "testid": { "$eq": 1 } }, { "testFloat": { "$gt": 6.0 } }] }).data().length).toEqual(1); // coll.find $or expect(eic.find({ "$or": [{ "testid": 1 }, { "testString": "bbb" }] }).length).toEqual(3); // ResultSet.find $or expect(eic.chain().find({ "$or": [{ "testid": 1 }, { "testString": "bbb" }] }).data().length).toEqual(3); // ResultSet.find explicit operators expect(eic.chain().find({ "$or": [{ "testid": 1 }, { "testFloat": { "$gt": 7.0 } }] }).data().length).toEqual(5); // add index and repeat final test eic.ensureRangedIndex("testid"); expect(eic.chain().find({ "$and": [{ "testid": { "$eq": 1 } }, { "testFloat": { "$gt": 6.0 } }] }).data().length).toEqual(1); expect(eic.chain().find({ "$or": [{ "testid": 1 }, { "testFloat": { "$gt": 7.0 } }] }).data().length).toEqual(5); db.removeCollection("eic"); }); }); describe("findOne", () => { it("works", () => { interface EIC { "testid": number; "testString": string; "testFloat": number; } const eic = db.addCollection<EIC>("eic"); eic.insert({ "testid": 1, "testString": "hhh", "testFloat": 5.2 }); //0 eic.insert({ "testid": 1, "testString": "bbb", "testFloat": 6.2 }); //1 eic.insert({ "testid": 5, "testString": "zzz", "testFloat": 7.2 }); //2 // coll.findOne return type expect(typeof eic.findOne({ "testid": 1 })).toEqual("object"); // coll.findOne return match expect(eic.findOne({ "testid": 5 }).testFloat).toEqual(7.2); // findOne with $and op expect(eic.findOne({ "$and": [{ "testid": 1 }, { "testString": "bbb" }] }).testFloat).toEqual(6.2); expect(eic.findOne({ "$or": [{ "testid": 2 }, { "testString": "zzz" }] }).testFloat).toEqual(7.2); db.removeCollection("eic"); }); }); describe("ResultSet unfiltered simplesort works", () => { it("works", () => { const ssdb = new Loki("sandbox.db"); interface User { name: string; owner: string; maker: string; } // Add a collection to the database const items = ssdb.addCollection<User>("items", { rangedIndexes: { "name": {}} }); // Add some documents to the collection items.insert({ name: "mjolnir", owner: "thor", maker: "dwarves" }); items.insert({ name: "gungnir", owner: "odin", maker: "elves" }); items.insert({ name: "tyrfing", owner: "svafrlami", maker: "dwarves" }); items.insert({ name: "draupnir", owner: "odin", maker: "elves" }); // simplesort without filters on prop with index should work let results = items.chain().simplesort("name").data(); expect(results.length).toEqual(4); expect(results[0].name).toEqual("draupnir"); expect(results[1].name).toEqual("gungnir"); expect(results[2].name).toEqual("mjolnir"); expect(results[3].name).toEqual("tyrfing"); // simplesort without filters on prop without index should work results = items.chain().simplesort("owner").data(); expect(results.length).toEqual(4); expect(results[0].owner).toEqual("odin"); expect(results[1].owner).toEqual("odin"); expect(results[2].owner).toEqual("svafrlami"); expect(results[3].owner).toEqual("thor"); }); }); describe("ResultSet data clone", () => { it("nested works ", () => { const idb = new Loki("sandbox.db"); interface AUser { user: { name: string; owner: string; maker: string; }; } // Add a collection to the database const items = idb.addCollection<AUser, { "user.name": string }>("items", { nestedProperties: ["user.name"] }); // Add some documents to the collection items.insert({ user: { name: "mjolnir", owner: "thor", maker: "dwarves" } }); items.insert({ user: { name: "gungnir", owner: "odin", maker: "elves" } }); items.insert({ user: { name: "tyrfing", owner: "svafrlami", maker: "dwarves" } }); items.insert({ user: { name: "draupnir", owner: "odin", maker: "elves" } }); const result = items.chain().data({ forceClones: true }); expect(result[0]["user.name"]).toBeDefined(); expect(result[0]["user.owner"]).toBeUndefined(); }); }); describe("ResultSet data removeMeta works", () => { it("works", () => { const idb = new Loki("sandbox.db"); interface User { name: string; owner: string; maker: string; } // Add a collection to the database const items = idb.addCollection<User>("items", { rangedIndexes: { "owner" : {}} }); // Add some documents to the collection items.insert({ name: "mjolnir", owner: "thor", maker: "dwarves" }); items.insert({ name: "gungnir", owner: "odin", maker: "elves" }); items.insert({ name: "tyrfing", owner: "svafrlami", maker: "dwarves" }); items.insert({ name: "draupnir", owner: "odin", maker: "elves" }); // unfiltered with strip meta let result = items.chain().data({ removeMeta: true }); expect(result.length).toEqual(4); expect(result[0].hasOwnProperty("$loki")).toEqual(false); expect(result[0].hasOwnProperty("meta")).toEqual(false); expect(result[1].hasOwnProperty("$loki")).toEqual(false); expect(result[1].hasOwnProperty("meta")).toEqual(false); expect(result[2].hasOwnProperty("$loki")).toEqual(false); expect(result[2].hasOwnProperty("meta")).toEqual(false); expect(result[3].hasOwnProperty("$loki")).toEqual(false); expect(result[3].hasOwnProperty("meta")).toEqual(false); // indexed sort with strip meta result = items.chain().simplesort("owner").limit(2).data({ removeMeta: true }); expect(result.length).toEqual(2); expect(result[0].owner).toEqual("odin"); expect(result[0].hasOwnProperty("$loki")).toEqual(false); expect(result[0].hasOwnProperty("meta")).toEqual(false); expect(result[1].owner).toEqual("odin"); expect(result[1].hasOwnProperty("$loki")).toEqual(false); expect(result[1].hasOwnProperty("meta")).toEqual(false); // unindexed find strip meta result = items.chain().find({ maker: "elves" }).data({ removeMeta: true }); expect(result.length).toEqual(2); expect(result[0].maker).toEqual("elves"); expect(result[0].hasOwnProperty("$loki")).toEqual(false); expect(result[0].hasOwnProperty("meta")).toEqual(false); expect(result[1].maker).toEqual("elves"); expect(result[1].hasOwnProperty("$loki")).toEqual(false); expect(result[1].hasOwnProperty("meta")).toEqual(false); // now try unfiltered without strip meta and ensure loki and meta are present result = items.chain().data(); expect(result.length).toEqual(4); expect(result[0].hasOwnProperty("$loki")).toEqual(true); expect(result[0].hasOwnProperty("meta")).toEqual(true); expect(result[1].hasOwnProperty("$loki")).toEqual(true); expect(result[1].hasOwnProperty("meta")).toEqual(true); expect(result[2].hasOwnProperty("$loki")).toEqual(true); expect(result[2].hasOwnProperty("meta")).toEqual(true); expect(result[3].hasOwnProperty("$loki")).toEqual(true); expect(result[3].hasOwnProperty("meta")).toEqual(true); // now try without strip meta and ensure loki and meta are present result = items.chain().simplesort("owner").limit(2).data(); expect(result.length).toEqual(2); expect(result[0].owner).toEqual("odin"); expect(result[0].hasOwnProperty("$loki")).toEqual(true); expect(result[0].hasOwnProperty("meta")).toEqual(true); expect(result[1].owner).toEqual("odin"); expect(result[1].hasOwnProperty("$loki")).toEqual(true); expect(result[1].hasOwnProperty("meta")).toEqual(true); // unindexed find strip meta result = items.chain().find({ maker: "elves" }).data(); expect(result.length).toEqual(2); expect(result[0].maker).toEqual("elves"); expect(result[0].hasOwnProperty("$loki")).toEqual(true); expect(result[0].hasOwnProperty("meta")).toEqual(true); expect(result[1].maker).toEqual("elves"); expect(result[1].hasOwnProperty("$loki")).toEqual(true); expect(result[1].hasOwnProperty("meta")).toEqual(true); }); }); describe("chained removes", () => { it("works", () => { interface RSC { "testid": number; "testString": string; "testFloat": number; } const rsc = db.addCollection<RSC>("rsc"); rsc.insert({ "testid": 1, "testString": "hhh", "testFloat": 5.2 }); rsc.insert({ "testid": 1, "testString": "bbb", "testFloat": 6.2 }); rsc.insert({ "testid": 2, "testString": "ccc", "testFloat": 6.2 }); rsc.insert({ "testid": 5, "testString": "zzz", "testFloat": 7.2 }); const docCount = rsc.find().length; // verify initial doc count expect(docCount).toEqual(4); // remove middle documents rsc.chain().find({ testFloat: 6.2 }).remove(); // verify new doc count expect(rsc.find().length).toEqual(2); expect(rsc.chain().data().length).toEqual(2); // now fetch and retain all remaining documents const results = rsc.chain().simplesort("testString").data(); // make sure its the documents we expect expect(results[0].testString).toEqual("hhh"); expect(results[1].testString).toEqual("zzz"); }); }); /* Dynamic View Tests */ });
the_stack
import express from 'express'; import * as fs from 'fs'; import csvparse from 'csv-parse'; import * as util from 'util'; import * as Stream from 'stream'; import * as Genie from 'genie-toolkit'; import * as db from './db'; import * as user from './user'; import * as I18n from './i18n'; import { BadRequestError, ForbiddenError } from './errors'; import * as schemaModel from '../model/schema'; import * as entityModel from '../model/entity'; import * as stringModel from '../model/strings'; const NAME_REGEX = /^([A-Za-z_][A-Za-z0-9_.-]*):([A-Za-z_][A-Za-z0-9_]*)$/; interface TokenizedRow { type_id : number; value : string; preprocessed : string; weight : number; } class StreamTokenizer extends Stream.Transform { private _preprocessed : boolean; private _typeId : number; private _tokenizer : Genie.I18n.BaseTokenizer; constructor(options : { language : string; preprocessed : boolean; typeId : number; }) { super({ objectMode: true }); this._preprocessed = options.preprocessed; this._typeId = options.typeId; this._tokenizer = I18n.get(options.language).genie.getTokenizer(); } _transform(row : string[], encoding : BufferEncoding, callback : (err ?: Error|null, out ?: TokenizedRow) => void) { if (row.length < 1 || !row[0]) { callback(); return; } let value, preprocessed, weight; if (row.length === 1) { value = row[0]; weight = 1.0; } else if (row.length === 2) { if (isFinite(+row[1])) { value = row[0]; weight = parseFloat(row[1]); } else { value = row[0]; preprocessed = row[1]; weight = 1.0; } } else { value = row[0]; preprocessed = row[1]; weight = parseFloat(row[2]) || 1.0; } if (!(weight > 0.0)) weight = 1.0; if (preprocessed === undefined && this._preprocessed) preprocessed = value; if (preprocessed !== undefined) { callback(null, { type_id: this._typeId, value, preprocessed, weight }); } else { const result = this._tokenizer.tokenize(value); // ignore lines with uppercase (entity) tokens if (result.tokens.some((t) => /[A-Z]/.test(t))) { callback(null); } else { callback(null, { type_id: this._typeId, value, preprocessed: result.tokens.join(' '), weight }); } } } _flush(callback : () => void) { process.nextTick(callback); } } export async function uploadEntities(req : express.Request) { const language = I18n.localeToLanguage(req.locale); const tokenizer = I18n.get(req.locale).genie.getTokenizer(); try { await db.withTransaction(async (dbClient) => { const match = NAME_REGEX.exec(req.body.entity_id); if (match === null) throw new BadRequestError(req._("Invalid entity type ID.")); const [, prefix, /*suffix*/] = match; if ((req.user!.roles & user.Role.THINGPEDIA_ADMIN) === 0) { let row; try { row = await schemaModel.getByKind(dbClient, prefix); } catch(e) { if (e.code !== 'ENOENT') throw e; } if (!row || row.owner !== req.user!.developer_org) throw new ForbiddenError(req._("The prefix of the entity ID must correspond to the ID of a Thingpedia device owned by your organization.")); } const entity = { name: req.body.entity_name, id: req.body.entity_id, is_well_known: false, has_ner_support: !req.body.no_ner_support }; try { const existing = await entityModel.get(dbClient, req.body.entity_id); if (entity.name === entity.id) entity.name = existing.name; await entityModel.update(dbClient, existing.id, entity); await entityModel.deleteValues(dbClient, existing.id); } catch(e) { if (e.code !== 'ENOENT') throw e; await entityModel.create(dbClient, entity); } if (req.body.no_ner_support) return; if (!req.file) throw new BadRequestError(req._("You must upload a CSV file with the entity values.")); const parser = csvparse({delimiter: ','}); fs.createReadStream(req.file.path).pipe(parser); const transformer = new Stream.Transform({ objectMode: true, transform(row, encoding, callback) { if (row.length !== 2) { callback(); return; } const value = row[0].trim(); const name = row[1]; const { tokens } = tokenizer.tokenize(name); const canonical = tokens.join(' '); callback(null, { language, entity_id: req.body.entity_id, entity_value: value, entity_canonical: canonical, entity_name: name }); }, flush(callback) { process.nextTick(callback); } }); const writer = entityModel.insertValueStream(dbClient); parser.pipe(transformer).pipe(writer); // we need to do a somewhat complex error handling dance to ensure // that we don't have any inflight requests by the time we terminate // the transaction, otherwise we might run SQL queries on the wrong // connection/transaction and that would be bad await new Promise<void>((resolve, reject) => { let error : Error|undefined; parser.on('error', (e) => { error = new BadRequestError(e.message); transformer.end(); }); transformer.on('error', (e) => { error = e; writer.end(); }); writer.on('error', reject); writer.on('finish', () => { if (error) reject(error); else resolve(); }); }); }); } finally { if (req.file) await util.promisify(fs.unlink)(req.file.path); } } export async function uploadStringDataset(req : express.Request) { const language = I18n.localeToLanguage(req.locale); try { await db.withTransaction(async (dbClient) => { const match = NAME_REGEX.exec(req.body.type_name); if (match === null) throw new BadRequestError(req._("Invalid string type ID.")); if (['public-domain', 'free-permissive', 'free-copyleft', 'non-commercial', 'proprietary'].indexOf(req.body.license) < 0) throw new BadRequestError(req._("Invalid license.")); const [, prefix, /*suffix*/] = match; if ((req.user!.roles & user.Role.THINGPEDIA_ADMIN) === 0) { let row; try { row = await schemaModel.getByKind(dbClient, prefix); } catch(e) { if (e.code !== 'ENOENT') throw e; } if (!row || row.owner !== req.user!.developer_org) throw new ForbiddenError(req._("The prefix of the dataset ID must correspond to the ID of a Thingpedia device owned by your organization.")); } if (!req.file) throw new BadRequestError(req._("You must upload a TSV file with the string values.")); let stringType; const string = { language: language, type_name: req.body.type_name, name: req.body.name, license: req.body.license, attribution: req.body.attribution || '', }; try { stringType = await stringModel.getByTypeName(dbClient, req.body.type_name, language); if (string.license === 'public-domain') string.license = stringType.license; string.attribution = string.attribution || stringType.attribution; if (string.name === string.type_name) string.name = stringType.name; await stringModel.update(dbClient, stringType.id, string); await stringModel.deleteValues(dbClient, stringType.id); } catch(e) { stringType = await stringModel.create(dbClient, string); } const file = fs.createReadStream(req.file.path); file.setEncoding('utf8'); const parser = file.pipe(csvparse({ delimiter: '\t', relax: true, relax_column_count: true })); const transformer = new StreamTokenizer({ preprocessed: !!req.body.preprocessed, language, typeId: stringType.id, }); const writer = stringModel.insertValueStream(dbClient); parser.pipe(transformer).pipe(writer); // we need to do a somewhat complex error handling dance to ensure // that we don't have any inflight requests by the time we terminate // the transaction, otherwise we might run SQL queries on the wrong // connection/transaction and that would be bad await new Promise<void>((resolve, reject) => { let error : Error|undefined; parser.on('error', (e) => { error = new BadRequestError(e.message); transformer.end(); }); transformer.on('error', (e) => { error = e; writer.end(); }); writer.on('error', reject); writer.on('finish', () => { if (error) reject(error); else resolve(); }); }); }); } finally { if (req.file) await util.promisify(fs.unlink)(req.file.path); } }
the_stack
import { useTheme } from "@kaizen/design-tokens" import * as React from "react" import { Base, BaseProps } from "./Base" import { AnimatedBase, AnimatedBaseProps } from "./Players/LottiePlayer" export type SpotProps = Pick<BaseProps, "alt" | "classNameAndIHaveSpokenToDST"> export type AnimatedSpotProps = SpotProps & AnimatedBaseProps & { isAnimated?: boolean } const noZenIllustrationWarning = (illustrationName: string) => { // eslint-disable-next-line no-console console.warn( `Kaizen Illustration: No corresponding Zen illustration for ${illustrationName}. Displaying Heart illustration instead."` ) } const noAnimationSupportWarning = (illustrationName: string) => { // eslint-disable-next-line no-console console.warn( `Kaizen Illustration: Animations are not supported for ${illustrationName} in Zen."` ) } /** * Moods */ export const Cautionary = ({ isAnimated, ...otherProps }: AnimatedSpotProps) => { const { themeKey } = useTheme() const illustrationPath = themeKey === "zen" ? "illustrations/spot/moods-cautionary.svg" : "illustrations/heart/spot/moods-cautionary.svg" const StaticIllustration = <Base {...otherProps} name={illustrationPath} /> const AnimatedIllustration = ( <AnimatedBase {...otherProps} name="illustrations/spot/moods-cautionary.lottie" fallback={illustrationPath} /> ) if (isAnimated) { if (themeKey === "zen") { noAnimationSupportWarning("Cautionary") return StaticIllustration } return AnimatedIllustration } return StaticIllustration } export const Informative = ({ isAnimated, ...otherProps }: AnimatedSpotProps) => { const { themeKey } = useTheme() const illustrationPath = themeKey === "zen" ? "illustrations/spot/moods-informative.svg" : "illustrations/heart/spot/moods-informative.svg" const StaticIllustration = <Base {...otherProps} name={illustrationPath} /> const AnimatedIllustration = ( <AnimatedBase {...otherProps} name="illustrations/spot/moods-informative.lottie" fallback={illustrationPath} /> ) if (isAnimated) { if (themeKey === "zen") { noAnimationSupportWarning("Cautionary") return StaticIllustration } return AnimatedIllustration } return StaticIllustration } export const Negative = ({ isAnimated, ...otherProps }: AnimatedSpotProps) => { const { themeKey } = useTheme() const illustrationPath = themeKey === "zen" ? "illustrations/spot/moods-negative.svg" : "illustrations/heart/spot/moods-negative.svg" const StaticIllustration = <Base {...otherProps} name={illustrationPath} /> const AnimatedIllustration = ( <AnimatedBase {...otherProps} name="illustrations/spot/moods-negative.lottie" fallback={illustrationPath} /> ) if (isAnimated) { if (themeKey === "zen") { noAnimationSupportWarning("Cautionary") return StaticIllustration } return AnimatedIllustration } return StaticIllustration } /** * @deprecated Use the non-gendered Positive illustration instead */ export const PositiveMale = ({ isAnimated, ...otherProps }: AnimatedSpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/moods-positive-male.svg" : "illustrations/heart/spot/moods-positive.svg" return <Base {...otherProps} name={illustrationPath} /> } /** * @deprecated Use the non-gendered Positive illustration instead */ export const PositiveFemale = ({ isAnimated, ...otherProps }: AnimatedSpotProps) => { const { themeKey } = useTheme() const illustrationPath = themeKey === "zen" ? "illustrations/spot/moods-positive-female.svg" : "illustrations/heart/spot/moods-positive.svg" const StaticIllustration = <Base {...otherProps} name={illustrationPath} /> const AnimatedIllustration = ( <AnimatedBase {...otherProps} name="illustrations/spot/moods-positive.lottie" fallback={illustrationPath} /> ) if (isAnimated) { if (themeKey === "zen") { noAnimationSupportWarning("Cautionary") return StaticIllustration } return AnimatedIllustration } return StaticIllustration } export const Positive = ({ isAnimated, ...otherProps }: AnimatedSpotProps) => { const { themeKey } = useTheme() const illustrationPath = themeKey === "zen" ? "illustrations/spot/moods-positive-female.svg" : "illustrations/heart/spot/moods-positive.svg" const StaticIllustration = <Base {...otherProps} name={illustrationPath} /> const AnimatedIllustration = ( <AnimatedBase {...otherProps} name="illustrations/spot/moods-positive.lottie" fallback={illustrationPath} /> ) if (isAnimated) { if (themeKey === "zen") { noAnimationSupportWarning("Cautionary") return StaticIllustration } return AnimatedIllustration } return StaticIllustration } export const Assertive = ({ isAnimated, ...otherProps }: AnimatedSpotProps) => { const { themeKey } = useTheme() if (themeKey === "zen") { noZenIllustrationWarning("Assertive") } const illustrationPath = "illustrations/heart/spot/moods-assertive.svg" const StaticIllustration = <Base {...otherProps} name={illustrationPath} /> const AnimatedIllustration = ( <AnimatedBase {...otherProps} name="illustrations/heart/spot/moods-assertive.lottie" fallback={illustrationPath} /> ) if (isAnimated) { if (themeKey === "zen") { noAnimationSupportWarning("Cautionary") return StaticIllustration } return AnimatedIllustration } return StaticIllustration } /** * Template Library / Engagement */ export const BenefitsSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-benefits-survey.svg" : "illustrations/heart/spot/template-library-benefits-survey.svg" return <Base {...props} name={illustrationPath} /> } export const CustomSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-custom-survey.svg" : "illustrations/heart/spot/template-library-custom-survey.svg" return <Base {...props} name={illustrationPath} /> } export const CustomUnattributedSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-custom-unattributed-survey.svg" : "illustrations/heart/spot/template-library-custom-unattributed-survey.svg" return <Base {...props} name={illustrationPath} /> } export const EngagementSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-engagement-survey.svg" : "illustrations/heart/spot/template-library-engagement-survey.svg" return <Base {...props} name={illustrationPath} /> } export const InclusionSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-inclusion-survey.svg" : "illustrations/heart/spot/template-library-inclusion-survey.svg" return <Base {...props} name={illustrationPath} /> } export const QuickEngagementSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-quick-engagement-survey.svg" : "illustrations/heart/spot/template-library-quick-engagement-survey.svg" return <Base {...props} name={illustrationPath} /> } export const ValuesSurvey1 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-values-survey-1.svg" : "illustrations/heart/spot/template-library-values-survey-1.svg" return <Base {...props} name={illustrationPath} /> } export const ValuesSurvey2 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-values-survey-2.svg" : "illustrations/heart/spot/template-library-values-survey-2.svg" return <Base {...props} name={illustrationPath} /> } export const WellbeingSurvey1 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-wellbeing-survey-1.svg" : "illustrations/heart/spot/template-library-wellbeing-survey-1.svg" return <Base {...props} name={illustrationPath} /> } export const WellbeingSurvey2 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-wellbeing-survey-2.svg" : "illustrations/heart/spot/template-library-wellbeing-survey-2.svg" return <Base {...props} name={illustrationPath} /> } export const WellbeingSurvey3 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-wellbeing-survey-3.svg" : "illustrations/heart/spot/template-library-wellbeing-survey-3.svg" return <Base {...props} name={illustrationPath} /> } export const ChangeReadiness = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-change-readiness.svg" : "illustrations/heart/spot/template-library-change-readiness.svg" return <Base {...props} name={illustrationPath} /> } export const ChangeSuccess = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-change-success.svg" : "illustrations/heart/spot/template-library-change-success.svg" return <Base {...props} name={illustrationPath} /> } export const PerformanceDiagnostics = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-diagnostics.svg" : "illustrations/heart/spot/template-library-performance-diagnostics.svg" return <Base {...props} name={illustrationPath} /> } export const LeadingThroughCrisis = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-leading-through-crisis.svg" return <Base {...props} name={illustrationPath} /> } export const EmergencyResponse = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-emergency-response.svg" return <Base {...props} name={illustrationPath} /> } /** * Template Library / Experience */ export const CandidateSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-candidate-survey.svg" : "illustrations/heart/spot/template-library-candidate-survey.svg" return <Base {...props} name={illustrationPath} /> } export const CustomOnboardSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-custom-onboard-survey.svg" : "illustrations/heart/spot/template-library-custom-onboard-survey.svg" return <Base {...props} name={illustrationPath} /> } export const ExitSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-exit-survey.svg" : "illustrations/heart/spot/template-library-exit-survey.svg" return <Base {...props} name={illustrationPath} /> } export const InternSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-intern-survey.svg" : "illustrations/heart/spot/template-library-intern-survey.svg" return <Base {...props} name={illustrationPath} /> } export const PhasedWeek1OnboardSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-phased-week-1-onboard-survey.svg" : "illustrations/heart/spot/template-library-phased-week-1-onboard-survey.svg" return <Base {...props} name={illustrationPath} /> } export const PhasedWeek5OnboardSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-phased-week-5-onboard-survey.svg" : "illustrations/heart/spot/template-library-phased-week-5-onboard-survey.svg" return <Base {...props} name={illustrationPath} /> } export const SinglePointOnboardSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-single-point-onboard-survey.svg" : "illustrations/heart/spot/template-library-single-point-onboard-survey.svg" return <Base {...props} name={illustrationPath} /> } export const GeneralOnboardSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-general-onboard-survey.svg" return <Base {...props} name={illustrationPath} /> } export const RemoteOnboardSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-remote-onboard-survey.svg" return <Base {...props} name={illustrationPath} /> } /** * Template Library / Performance */ export const Individual360 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-individual-360.svg" : "illustrations/heart/spot/template-library-individual-360.svg" return <Base {...props} name={illustrationPath} /> } export const Leadership360 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-leadership-360.svg" : "illustrations/heart/spot/template-library-leadership-360.svg" return <Base {...props} name={illustrationPath} /> } export const Manager360 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-manager-360.svg" : "illustrations/heart/spot/template-library-manager-360.svg" return <Base {...props} name={illustrationPath} /> } export const Individual180 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-individual-180.svg" return <Base {...props} name={illustrationPath} /> } export const Leadership180 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-leadership-180.svg" return <Base {...props} name={illustrationPath} /> } export const Manager180 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-manager-180.svg" return <Base {...props} name={illustrationPath} /> } export const TeamEffectiveness1 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-team-effectiveness-1.svg" : "illustrations/heart/spot/template-library-team-effectiveness-1.svg" return <Base {...props} name={illustrationPath} /> } export const TeamEffectiveness2 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/template-library-team-effectiveness-2.svg" : "illustrations/heart/spot/template-library-team-effectiveness-2.svg" return <Base {...props} name={illustrationPath} /> } /** * Template Library / COVID-19 */ export const WellbeingSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-wellbeing-survey.svg" return <Base {...props} name={illustrationPath} /> } export const Response = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-response.svg" return <Base {...props} name={illustrationPath} /> } export const RemoteWorkQSet = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-remote-work-q-set.svg" return <Base {...props} name={illustrationPath} /> } export const ReturnToWorkplace = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-return-to-workplace.svg" return <Base {...props} name={illustrationPath} /> } export const PulseSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/template-library-pulse-survey.svg" return <Base {...props} name={illustrationPath} /> } /** * New Account */ export const AccountBasics = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/new-account-account-basics.svg" : "illustrations/heart/spot/new-account-account-basics.svg" return <Base {...props} name={illustrationPath} /> } export const CompanyDetails = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/new-account-company-details.svg" : "illustrations/heart/spot/new-account-company-details.svg" return <Base {...props} name={illustrationPath} /> } export const EmployeeData = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/new-account-employee-data.svg" : "illustrations/heart/spot/new-account-employee-data.svg" return <Base {...props} name={illustrationPath} /> } export const Gdpr = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/new-account-gdpr.svg" : "illustrations/heart/spot/new-account-gdpr.svg" return <Base {...props} name={illustrationPath} /> } export const Timezone = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/new-account-timezone.svg" : "illustrations/heart/spot/new-account-timezone.svg" return <Base {...props} name={illustrationPath} /> } export const AddUser = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/new-account-add-user.svg" : "illustrations/heart/spot/new-account-add-user.svg" return <Base {...props} name={illustrationPath} /> } /** * Skills Coach (previously referred to as Manager Learning) */ export const Strategy = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/manager-learning-strategy.svg" : "illustrations/heart/spot/skills-coach-strategy.svg" return <Base {...props} name={illustrationPath} /> } export const Resilience = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/manager-learning-resilience.svg" : "illustrations/heart/spot/skills-coach-resilience.svg" return <Base {...props} name={illustrationPath} /> } export const RemoteManager = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/manager-learning-remote-manager.svg" : "illustrations/heart/spot/skills-coach-remote-manager.svg" return <Base {...props} name={illustrationPath} /> } export const Productivity = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/manager-learning-productivity.svg" : "illustrations/heart/spot/skills-coach-productivity.svg" return <Base {...props} name={illustrationPath} /> } export const ManagerLearning = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/manager-learning-manager-learning.svg" : "illustrations/heart/spot/skills-coach-manager-learning.svg" return <Base {...props} name={illustrationPath} /> } export const Feedback = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/manager-learning-feedback.svg" : "illustrations/heart/spot/skills-coach-feedback.svg" return <Base {...props} name={illustrationPath} /> } export const Coaching = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/manager-learning-coaching.svg" : "illustrations/heart/spot/skills-coach-coaching.svg" return <Base {...props} name={illustrationPath} /> } export const OneOnOne = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/manager-learning-1-on-1.svg" : "illustrations/heart/spot/skills-coach-1-on-1.svg" return <Base {...props} name={illustrationPath} /> } /** * Miscellaneous */ export const ViewReports = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-view-reports.svg" : "illustrations/heart/spot/miscellaneous-view-reports.svg" return <Base {...props} name={illustrationPath} /> } export const ReadArticle = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-read-article.svg" : "illustrations/heart/spot/miscellaneous-read-article.svg" return <Base {...props} name={illustrationPath} /> } export const FastAction = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-fast-action.svg" : "illustrations/heart/spot/miscellaneous-fast-action.svg" return <Base {...props} name={illustrationPath} /> } export const BaselineSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-baseline-survey.svg" : "illustrations/heart/spot/miscellaneous-baseline-survey.svg" return <Base {...props} name={illustrationPath} /> } export const SpreadsheetTemplate = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-spreadsheet-template.svg" : "illustrations/heart/spot/miscellaneous-spreadsheet-template.svg" return <Base {...props} name={illustrationPath} /> } export const AddImage = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-add-image.svg" : "illustrations/heart/spot/miscellaneous-add-image.svg" return <Base {...props} name={illustrationPath} /> } export const MeetingVoices = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-meeting-voices.svg" : "illustrations/heart/spot/miscellaneous-meeting-voices.svg" return <Base {...props} name={illustrationPath} /> } export const Workshop = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-workshop.svg" : "illustrations/heart/spot/miscellaneous-workshop.svg" return <Base {...props} name={illustrationPath} /> } export const Video = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-video.svg" : "illustrations/heart/spot/miscellaneous-video.svg" return <Base {...props} name={illustrationPath} /> } export const ReportSharing = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-report-sharing.svg" : "illustrations/heart/spot/miscellaneous-report-sharing.svg" return <Base {...props} name={illustrationPath} /> } export const BlankSurvey = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-blank-survey.svg" : "illustrations/heart/spot/miscellaneous-blank-survey.svg" return <Base {...props} name={illustrationPath} /> } export const TakeAim = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-take-aim.svg" : "illustrations/heart/spot/miscellaneous-take-aim.svg" return <Base {...props} name={illustrationPath} /> } export const Action = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-action.svg" : "illustrations/heart/spot/miscellaneous-action.svg" return <Base {...props} name={illustrationPath} /> } export const Training1 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-training-1.svg" : "illustrations/heart/spot/miscellaneous-training-1.svg" return <Base {...props} name={illustrationPath} /> } export const Training2 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-training-2.svg" : "illustrations/heart/spot/miscellaneous-training-2.svg" return <Base {...props} name={illustrationPath} /> } export const Training3 = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-training-3.svg" : "illustrations/heart/spot/miscellaneous-training-3.svg" return <Base {...props} name={illustrationPath} /> } export const ShareReport = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-share-report.svg" : "illustrations/heart/spot/miscellaneous-share-report.svg" return <Base {...props} name={illustrationPath} /> } export const Team = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-team.svg" : "illustrations/heart/spot/miscellaneous-team.svg" return <Base {...props} name={illustrationPath} /> } export const ExecutiveReportSharing = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-executive-report-sharing.svg" : "illustrations/heart/spot/miscellaneous-executive-report-sharing.svg" return <Base {...props} name={illustrationPath} /> } export const ManagerReportSharing = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-manager-report-sharing.svg" : "illustrations/heart/spot/miscellaneous-manager-report-sharing.svg" return <Base {...props} name={illustrationPath} /> } export const LeaderReportSharing = (props: SpotProps) => { const theme = useTheme() const illustrationPath = theme.themeKey === "zen" ? "illustrations/spot/miscellaneous-leader-report-sharing.svg" : "illustrations/heart/spot/miscellaneous-leader-report-sharing.svg" return <Base {...props} name={illustrationPath} /> } export const Alarm = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("Alarm") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-alarm.svg" /> ) } export const Fire = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("Fire") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-fire.svg" /> ) } export const Fireworks = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("Fireworks") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-fireworks.svg" /> ) } export const FullImport = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("FullImport") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-full-import.svg" /> ) } export const HrisImport = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("HrisImport") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-hris-import.svg" /> ) } export const PartialImport = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("PartialImport") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-partial-import.svg" /> ) } export const Starburst = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("Starburst") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-starburst.svg" /> ) } export const Stop = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("Stop") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-stop.svg" /> ) } export const TrafficCone = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("TrafficCone") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-traffic-cone.svg" /> ) } export const Trophy = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("Trophy") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-trophy.svg" /> ) } export const UnderConstruction = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("UnderConstruction") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-under-construction.svg" /> ) } export const ValueAdd = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("ValueAdd") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-value-add.svg" /> ) } export const Recommendation = (props: SpotProps) => { const theme = useTheme() if (theme.themeKey === "zen") { noZenIllustrationWarning("Recommendation") } return ( <Base {...props} name="illustrations/heart/spot/miscellaneous-shield.svg" /> ) }
the_stack
import yaml from "js-yaml"; import { urlJoin } from "url-join-ts"; import { strict as assert } from "assert"; import { getBucketName, log, min, roundDown, roundDownToOdd, select } from "@opstrace/utils"; import { State } from "../../reducer"; import { getNodeCount, getControllerConfig, deepMerge } from "../../helpers"; import { KubeConfig } from "@kubernetes/client-node"; import { Deployment, Namespace, ResourceCollection, Service, V1Alpha1CortexResource, V1ServicemonitorResource, withPodAntiAffinityRequired } from "@opstrace/kubernetes"; import { DockerImages } from "@opstrace/controller-config"; import { ConfigMap } from "@opstrace/kubernetes"; export function CortexResources( state: State, kubeConfig: KubeConfig, namespace: string ): ResourceCollection { const collection = new ResourceCollection(); const { target, gcp, region, infrastructureName, metricRetentionDays } = getControllerConfig(state); const configsDBName = "cortex"; const dbconfig = new URL(state.config.config?.postgreSQLEndpoint || ""); const dbURL = urlJoin(state.config.config?.postgreSQLEndpoint, configsDBName); const config = { memcached: { replicas: select(getNodeCount(state), [ { "<=": 5, choose: 2 }, { "<=": 9, choose: 3 }, { "<=": Infinity, choose: min(4, roundDown(getNodeCount(state) / 3)) } ]), max_item_size: "2m", memory_limit: 4096, resources: {} }, storegateway: { resources: {}, replicas: select(getNodeCount(state), [ { "<=": 6, choose: 3 }, { "<=": Infinity, choose: roundDownToOdd(getNodeCount(state) / 2) } ]) }, compactor: { resources: {}, replicas: select(getNodeCount(state), [ { "<=": 6, choose: 3 }, { "<=": 9, choose: 5 }, { "<=": Infinity, choose: roundDownToOdd(getNodeCount(state) / 2) } ]) }, querier: { resources: {}, replicas: select(getNodeCount(state), [ { "<=": 6, choose: 3 }, { "<=": 9, choose: 5 }, { "<=": Infinity, choose: roundDownToOdd(getNodeCount(state) / 2) } ]) }, queryFrontend: { replicas: 2 // more than 2 is not beneficial (less advantage of queuing requests in front of queriers) }, configs: { replicas: 1 // start with 1, see how it goes }, ruler: { replicas: 3 }, alertmanager: { replicas: 3 }, distributor: { resources: {}, replicas: select(getNodeCount(state), [ { "<=": 4, choose: 3 }, { "<=": 6, choose: 5 }, { "<=": 8, choose: 7 }, { "<=": 10, choose: 9 }, { "<=": Infinity, choose: roundDownToOdd(getNodeCount(state) / 2) } ]) }, gateway: { replicas: select(getNodeCount(state), [ { "<=": 4, choose: 2 }, { "<=": 8, choose: 3 }, { "<=": Infinity, choose: 5 } ]) }, ingester: { resources: {}, replicas: select(getNodeCount(state), [ { "<=": 20, // From 3 to 20 nodes, run ~Nnodes ingesters // Keeping replicas odd to reduce risk of ring contention // Example: 5 nodes => 5 ingesters, 6 nodes => 5 ingesters, 7 nodes => 7 ingesters choose: roundDownToOdd(getNodeCount(state)) }, { "<=": 42, // From 21 to 42 nodes, stay with 21 ingesters. // This ensures a smooth transition from replicas=Nnodes to replicas=Nnodes/2, // without the number of ingesters dropping as the nodes increase. choose: 21 }, { "<=": Infinity, // Above 42 nodes, run ~Nnodes/2 ingesters // NOTE: At this scale, its unknown if Nnodes/2 is reasonable. choose: roundDownToOdd(getNodeCount(state) / 2) } ]) }, env: [] }; collection.add( new Namespace( { apiVersion: "v1", kind: "Namespace", metadata: { name: namespace } }, kubeConfig ) ); let annotations = {}; if (target === "gcp") { assert(gcp?.cortexServiceAccount); annotations = { "iam.gke.io/gcp-service-account": gcp.cortexServiceAccount }; } const dataBucketName = getBucketName({ clusterName: infrastructureName, suffix: "cortex" }); const configBucketName = getBucketName({ clusterName: infrastructureName, suffix: "cortex-config" }); let dataStorageBackend = {}; let configStorageBackend = {}; switch (target) { case "aws": { const bucketRegion = `s3.${region}.amazonaws.com`; dataStorageBackend = { backend: "s3", s3: { bucket_name: dataBucketName, endpoint: bucketRegion } }; configStorageBackend = { backend: "s3", s3: { bucket_name: configBucketName, endpoint: bucketRegion } }; break; } case "gcp": { dataStorageBackend = { backend: "gcs", gcs: { bucket_name: dataBucketName } }; configStorageBackend = { backend: "gcs", gcs: { bucket_name: configBucketName } }; break; } } // TODO: Investigate if we can (and should) set the user runtime config via // the api directly instead of using this intermediary config map. // Read the config map with the user overrides. const cortexUserRuntimeConfig = state.kubernetes.cluster.ConfigMaps.resources.find( cm => cm.namespace === namespace && cm.name === "cortex-runtime-config" ); // These are the Opstrace cortex runtime config defaults. const cortexDefaultRuntimeConfig = { ingester_limits: { // The maximum number of global inflight requests per ingester // pod. By default this is unlimited, which risks ingesters OOMing // under heavy load. If the limit is reached, the ingester will // reject requests, but it keeps the ingester safe. This has been // observed when hundreds of thousands or millions of new metric // series are being added into cortex, where ingester pods can be // bogged down with initializing storage for those new series. In // theory this limit could be scaled according to the available // RAM on the nodes, but in practice the actual value here isn't // super important: if the ingester starts to fall behind then // queued requests will generally go from near-zero to // stratospheric levels within a few seconds, so there isn't much // difference between a 1k or 10k limit. See also the identically // named limit for distributor pods. max_inflight_push_requests: 1000 } }; let cortexRuntimeConfig = {}; const key = "runtime-config.yaml"; if ( cortexUserRuntimeConfig !== undefined && cortexUserRuntimeConfig.spec.data !== undefined && key in cortexUserRuntimeConfig.spec.data ) { const data = yaml.load( cortexUserRuntimeConfig.spec.data["runtime-config.yaml"] ); cortexRuntimeConfig = deepMerge(cortexDefaultRuntimeConfig, data); } else { cortexRuntimeConfig = cortexDefaultRuntimeConfig; } log.debug( `cortex runtime config: ${JSON.stringify(cortexRuntimeConfig, null, 2)}` ); // TODO: Remove when opstrace application is able to apply changes to the // cortex CRD runtime_config field. const rtccm = new ConfigMap( { apiVersion: "v1", data: { "runtime-config.yaml": yaml.safeDump(cortexDefaultRuntimeConfig) }, kind: "ConfigMap", metadata: { name: "cortex-runtime-config", namespace } }, kubeConfig ); // Set immutable: annotation-based custom convention, so that the Opstrace // controller will not delete/overwrite this config map when it detects // change. Note that the UI API implementation is expected to mutate this // config map. rtccm.setImmutable(); collection.add(rtccm); collection.add( new V1Alpha1CortexResource( { apiVersion: "cortex.opstrace.io/v1alpha1", kind: "Cortex", metadata: { name: "opstrace-cortex", namespace: namespace }, spec: { image: DockerImages.cortex, ingester_spec: { replicas: config.ingester.replicas, storage_class_name: "pd-ssd", datadir_size: "30Gi" }, compactor_spec: { replicas: config.compactor.replicas, storage_class_name: "pd-ssd", datadir_size: "30Gi" }, store_gateway_spec: { replicas: config.storegateway.replicas, storage_class_name: "pd-ssd", datadir_size: "30Gi" }, distributor_spec: { replicas: config.distributor.replicas }, query_frontend_spec: { replicas: config.queryFrontend.replicas }, querier_spec: { replicas: config.querier.replicas }, alertmanager_spec: { replicas: config.alertmanager.replicas }, ruler_spec: { replicas: config.ruler.replicas }, memcached: { image: DockerImages.memcached, chunks_cache_spec: { replicas: config.memcached.replicas, max_item_size: config.memcached.max_item_size, memory_limit: config.memcached.memory_limit }, metadata_cache_spec: { replicas: config.memcached.replicas, max_item_size: config.memcached.max_item_size, memory_limit: config.memcached.memory_limit }, index_queries_cache_spec: { replicas: config.memcached.replicas, max_item_size: config.memcached.max_item_size, memory_limit: config.memcached.memory_limit }, index_writes_cache_spec: { replicas: config.memcached.replicas, max_item_size: config.memcached.max_item_size, memory_limit: config.memcached.memory_limit }, results_cache_spec: { replicas: config.memcached.replicas, max_item_size: config.memcached.max_item_size, memory_limit: config.memcached.memory_limit } }, service_account_spec: { annotations: annotations }, config: { server: { grpc_server_max_recv_msg_size: 41943040, // default (4 MB) * 10 grpc_server_max_send_msg_size: 41943040, // default (4 MB) * 10 // https://github.com/grafana/cortex-jsonnet/pull/233 grpc_server_ping_without_stream_allowed: true, grpc_server_min_time_between_pings: "10s" }, memberlist: { max_join_backoff: "1m", max_join_retries: 20, min_join_backoff: "1s" }, query_range: { split_queries_by_interval: "24h" }, limits: { compactor_blocks_retention_period: `${ (metricRetentionDays + 1) * 24 }h`, // Define the sample ingestion rate, enforced in the individual // distributor. The idea is that this limit is applied locally, // see "ingestion_rate_strategy" below. ingestion_rate: 100000, // The default strategy is 'local', i.e. the effective limit can be // determined by multiplying with the number of distributors at hand. ingestion_rate_strategy: "local", // Per-user allowed ingestion burst size (in number of samples). ingestion_burst_size: 200000, // The maximum number of active series per user, across the cluster. // Supported only if -distributor.shard-by-all-labels is true (which // we set, above). max_global_series_per_user: 10000000, // The maximum number of active series per user, per ingester. As this // conflicts with `max_global_series_per_user`, set this so that it hits // in _later_ when ingesters are evenly loaded. Assume at least 3 // ingesters. That is, set this to max_global_series_per_user / 2 max_series_per_user: 5000000, accept_ha_samples: true, ha_cluster_label: "prometheus", ha_replica_label: "prometheus_replica", ruler_tenant_shard_size: 3 }, ingester: { lifecycler: { join_after: "30s", observe_period: "30s", num_tokens: 512 }, // Enable tracking of active series and export them as metrics. // Enables the metric `cortex_ingester_active_series`, resolving per // tenant ("user"). active_series_metrics_enabled: true, active_series_metrics_update_period: "1m", // After what time a series is considered to be inactive. active_series_metrics_idle_timeout: "10m" }, distributor: { instance_limits: { // Global push requests per distributor pod. // By default this is unlimited, and setting it reduces the risk of distributor OOMs under heavy load. // If this limit is reached then the distributor will reject requests. // This was observed when sending metric data with thousands or tens of thousands of labels. // In practice the inflight requests should be <5 territory, even when ingesters are falling behind. // See also the identically named limit for ingester pods. max_inflight_push_requests: 50 } }, blocks_storage: { tsdb: { // Note list_of_durations type, and e.g. "2h0m0s" does not validate as a single value // "2h0m0s," also does not. How to provide a list with a single value? // block_ranges_period: "2h0m0s,", //default retention_period: "6h" }, ...dataStorageBackend }, configs: { database: { uri: dbURL, migrations_dir: "/migrations" } }, alertmanager_storage: { ...configStorageBackend }, ruler_storage: { ...configStorageBackend } }, runtime_config: cortexRuntimeConfig } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "memcached-results", tenant: "system" }, name: "memcached-results", namespace }, spec: { endpoints: [ { interval: "30s", port: "exporter-http-metrics", path: "/metrics" } ], jobLabel: "name", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "memcached-results" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "memcached-metadata", tenant: "system" }, name: "memcached-metadata", namespace }, spec: { endpoints: [ { interval: "30s", port: "exporter-http-metrics", path: "/metrics" } ], jobLabel: "name", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "memcached-metadata" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "memcached-metadata", tenant: "system" }, name: "memcached-metadata", namespace }, spec: { endpoints: [ { interval: "30s", port: "exporter-http-metrics", path: "/metrics" } ], jobLabel: "name", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "memcached-metadata" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "memcached-index-writes", tenant: "system" }, name: "memcached-index-writes", namespace }, spec: { endpoints: [ { interval: "30s", port: "exporter-http-metrics", path: "/metrics" } ], jobLabel: "name", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "memcached-index-writes" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "distributor", tenant: "system" }, name: "distributor", namespace }, spec: { endpoints: [ { interval: "30s", port: "http", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "distributor" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "ingester", tenant: "system" }, name: "ingester", namespace }, spec: { endpoints: [ { interval: "30s", port: "http", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "ingester" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "store-gateway", tenant: "system" }, name: "store-gateway", namespace }, spec: { endpoints: [ { interval: "30s", port: "http", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "store-gateway" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "compactor", tenant: "system" }, name: "compactor", namespace }, spec: { endpoints: [ { interval: "30s", port: "http", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "compactor" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "querier", tenant: "system" }, name: "querier", namespace }, spec: { endpoints: [ { interval: "30s", port: "http", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "querier" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "query-frontend", tenant: "system" }, name: "query-frontend", namespace }, spec: { endpoints: [ { interval: "30s", port: "http", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "query-frontend" } } } }, kubeConfig ) ); collection.add( new Deployment( { apiVersion: "apps/v1", kind: "Deployment", metadata: { name: "configs", namespace }, spec: { replicas: config.configs.replicas, selector: { matchLabels: { name: "configs" } }, template: { metadata: { labels: { name: "configs" } }, spec: { // TODO: handle image pull secrets // imagePullSecrets: getImagePullSecrets(), initContainers: [ { image: DockerImages.postgresClient, name: "createcortexconfigsdb", env: [ { name: "PGHOST", value: dbconfig.hostname }, { name: "PGUSER", value: dbconfig.username }, { name: "PGPASSWORD", value: dbconfig.password } ], command: [ "sh", "-c", `echo "SELECT 'CREATE DATABASE ${configsDBName}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '${configsDBName}')\\gexec" | psql` ] } ], affinity: withPodAntiAffinityRequired({ name: "configs" }), containers: [ { name: "configs", image: DockerImages.cortex, imagePullPolicy: "IfNotPresent", args: [ "-target=configs", "-config.file=/etc/cortex/config.yaml" ], env: config.env, ports: [ { containerPort: 80, name: "http" } ], volumeMounts: [ { mountPath: "/etc/cortex", name: "cortex-config" }, { mountPath: "/etc/cortex-runtime-cfg", name: "cortex-runtime-config" } ] } ], volumes: [ { configMap: { name: "opstrace-cortex-config" }, name: "cortex-config" }, { configMap: { name: "opstrace-cortex-runtime-config" }, name: "cortex-runtime-config" } ] } } } }, kubeConfig ) ); collection.add( new Service( { apiVersion: "v1", kind: "Service", metadata: { labels: { job: `${namespace}.configs`, name: "configs" }, name: "configs", namespace }, spec: { clusterIP: "None", ports: [ { port: 80, name: "http" } ], selector: { name: "configs" } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "configs", tenant: "system" }, name: "configs", namespace }, spec: { endpoints: [ { interval: "30s", port: "http", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "configs" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "ruler", tenant: "system" }, name: "ruler", namespace }, spec: { endpoints: [ { interval: "30s", port: "http", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "ruler" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "alertmanager", tenant: "system" }, name: "alertmanager", namespace }, spec: { endpoints: [ { interval: "30s", port: "http", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "alertmanager" } } } }, kubeConfig ) ); return collection; }
the_stack
namespace Textor { export class LanguageService { public set language(value: ILanguage) { this._language = value; } public get language(): ILanguage { return this._language; } private _textEditor: TextEditor; private _textReader: TextReader; private _line: number; private _column: number; private _index: number; private _timeout: number; private _timeoutEnabled: boolean = false; private _language: ILanguage = null; private _syntaxTable: LanguageStyle[][] = []; private _style: string; private _state: string; constructor(textEditor: TextEditor) { this._textEditor = textEditor; } public getStyles(line: number): LanguageStyle[] { if (this._syntaxTable[line]) { return this._syntaxTable[line]; } return []; } public invalidate(oldRange: TextRange, newRange: TextRange, text: string) { if (this._language !== null) { // stop existing worker if (this._timeoutEnabled) { window.clearTimeout(this._timeout); this._timeoutEnabled = false; } // search backwards to find position with last known state let state = null; this._line = 0; this._column = 0; if (this._syntaxTable.length > 0) { let line = oldRange.start.line; let index = 0; while ((this._syntaxTable[line]) && (index < this._syntaxTable[line].length) && (oldRange.start.column > this._syntaxTable[line][index].start)) { index++; } while ((line >= 0) && (index >= 0)) { index--; if (index < 0) { line--; index = this._syntaxTable[line] ? this._syntaxTable[line].length - 1 : 0; } if (this._syntaxTable[line] && this._syntaxTable[line][index] && this._syntaxTable[line][index].state !== null) { state = this._syntaxTable[line][index].state; this._line = line; this._column = this._syntaxTable[line][index].start; break; } } } // move syntax data that has not changed and clear new range if text is inserted this.moveRange(oldRange.end.clone(), newRange.end.clone()); if (text.length > 0) { this.clearRange(newRange.start, newRange.end); } // find syntax line index for start position this._index = 0; while ((this._syntaxTable[this._line]) && (this._index < this._syntaxTable[this._line].length) && (this._column > this._syntaxTable[this._line][this._index].start)) { this._index++; } // create text reader and initialize language module this._textReader = this._textEditor.createTextReader(); this._textReader.textPosition.line = this._line; this._textReader.textPosition.column = this._column; this._language.begin(this._textReader, state); this._style = "text"; this.window_setTimeout(); } } public log() { for (let line: number = 0; line < this._syntaxTable.length; line++) { let text: string = "line " + line + ": "; if (this._syntaxTable[line]) { text += "[ "; for (const item of this._syntaxTable[line]) { text += item.start + item.style[0] + ((item.state !== null) ? "X" : "-") + " "; } text += " ]"; } console.log(text); } return "-"; } private window_setTimeout() { const timeout: number = new Date().getTime() + 20; const startPosition: TextPosition = new TextPosition(this._line, this._column); let line: number = this._textReader.textPosition.line; let column: number = this._textReader.textPosition.column; while (this._textReader.peek().length > 0) { const data: ILanguageStyle = this._language.read(); const c: string = this._textReader.peek(); if ((c.length === 0) || (data.style !== null) || (data.state !== null)) { if ((c.length === 0) || (data.style !== this._style) || (data.state !== this._state) || (data.state !== null)) { if ((c.length === 0) || (line !== this._line) || (column !== this._column) || (data.state !== null)) { this.addRecord(this._column, line, this._style, this._state); this._column = column; } this._style = data.style; this._state = data.state; } line = this._textReader.textPosition.line; column = this._textReader.textPosition.column; } if (new Date().getTime() > timeout) { break; } } if (this._textReader.peek().length > 0) { this._timeout = window.setTimeout(this.window_setTimeout.bind(this), 100); this._timeoutEnabled = true; } else { this.addRecord(this._column, this._line, this._style, null); } this._textEditor.invalidateRange(new TextRange(startPosition, new TextPosition(this._line, this._column))); this._textEditor.update(); } private moveRange(oldPosition: TextPosition, newPosition: TextPosition) { if (oldPosition.compareTo(newPosition) < 0) { // update data after old position to new position let index: number = 0; while ((this._syntaxTable[oldPosition.line]) && (index < this._syntaxTable[oldPosition.line].length) && (oldPosition.column > this._syntaxTable[oldPosition.line][index].start)) { index++; } if (this._syntaxTable[oldPosition.line]) { const syntax = this._syntaxTable[oldPosition.line].splice(index, this._syntaxTable[oldPosition.line].length - index); for (const item of syntax) { item.start += newPosition.column - oldPosition.column; } const size = newPosition.line - oldPosition.line; if (size > 0) { const newArray = new Array(size); for (let i = 0; i < size; i++) { newArray[i] = (index > 0) ? [ { style: this._syntaxTable[oldPosition.line][index - 1].style, state: null, start: 0 } ] : []; } const tail = this._syntaxTable.splice(oldPosition.line + 1, this._syntaxTable.length - oldPosition.line + 1); this._syntaxTable = this._syntaxTable.concat(newArray, tail); } this._syntaxTable[newPosition.line] = this._syntaxTable[newPosition.line].concat(syntax); } } else if (oldPosition.compareTo(newPosition) > 0) { // remove data between old position and new position let index = 0; if (oldPosition.line >= this._syntaxTable.length) { oldPosition.line = this._syntaxTable.length - 1; index = this._syntaxTable[oldPosition.line].length - 1; } else { while ((this._syntaxTable[oldPosition.line]) && (index < this._syntaxTable[oldPosition.line].length) && (oldPosition.column > this._syntaxTable[oldPosition.line][index].start)) { index++; } } if (this._syntaxTable[oldPosition.line]) { const syntax = this._syntaxTable[oldPosition.line].splice(index, this._syntaxTable[oldPosition.line].length - index); for (const item of syntax) { item.start -= oldPosition.column - newPosition.column; } index = 0; while ((this._syntaxTable[newPosition.line]) && (index < this._syntaxTable[newPosition.line].length) && (newPosition.column > this._syntaxTable[newPosition.line][index].start)) { index++; } this._syntaxTable.splice(newPosition.line + 1, oldPosition.line - newPosition.line); this._syntaxTable[newPosition.line].splice(index, this._syntaxTable[newPosition.line].length - index); this._syntaxTable[newPosition.line] = this._syntaxTable[newPosition.line].concat(syntax); } } } private clearRange(startPosition: TextPosition, endPosition: TextPosition) { if (startPosition.line === endPosition.line) { const line = this._syntaxTable[startPosition.line]; if (line) { let startIndex = -1; for (let i = 0; i < line.length; i++) { if (startIndex === -1 && startPosition.column >= line[i].start) { startIndex = i; } if (startIndex !== -1 && endPosition.column >= line[i].start) { this._syntaxTable[startPosition.line].splice(startIndex, i - startIndex); break; } } } } else { if (this._syntaxTable[startPosition.line]) { for (let i = this._syntaxTable[startPosition.line].length - 1; i >= 0; i--) { if (this._syntaxTable[startPosition.line][i].start > startPosition.column) { this._syntaxTable[startPosition.line].splice(i, 1); } } } for (let i = startPosition.line + 1; i < endPosition.line; i++) { this._syntaxTable[i] = []; } if (this._syntaxTable[endPosition.line]) { for (let i = this._syntaxTable[endPosition.line].length - 1; i >= 0; i--) { if (this._syntaxTable[endPosition.line][i].start < endPosition.column) { this._syntaxTable[endPosition.line].splice(i, 1); } } } } } private addRecord(column: number, nextLine: number, style: string, state: string) { this._syntaxTable[this._line] = this._syntaxTable[this._line] || []; if ((this._index > 0) && ((this._index - 1) < this._syntaxTable[this._line].length) && (this._syntaxTable[this._line][this._index - 1].start === this._column)) { const current = this._syntaxTable[this._line][this._index - 1]; current.style = style; if (state !== null) { current.state = state; } } else if (this._index < this._syntaxTable[this._line].length) { const current = this._syntaxTable[this._line][this._index]; if (column >= current.start) { current.start = column; current.style = style; current.state = state; this._index++; } else { this._syntaxTable[this._line].splice(this._index, 0, new LanguageStyle(style, state, column)); this._index++; } } else { this._syntaxTable[this._line].push(new LanguageStyle(style, state, column)); this._index++; } while (this._line < nextLine) { this._syntaxTable[this._line].splice(this._index, this._syntaxTable[this._line].length - this._index); this._line++; this._index = 0; this.addRecord(0, this._line, style, null); } } } }
the_stack
import { StageComponent, ComponentTester } from 'aurelia-testing'; import { bootstrap } from 'aurelia-bootstrapper'; import { RegistrationForm } from './resources/registration-form'; import { validateTrigger, ValidateEvent } from '../src/aurelia-validation'; import { configure, blur, change, focusout } from './shared'; describe('end to end', () => { it('basic scenarios', (done: () => void) => { const component: ComponentTester = StageComponent .withResources() .inView('<registration-form></registration-form>') .boundTo({}); component.bootstrap(configure); let firstName: HTMLInputElement; let lastName: HTMLInputElement; let number1: HTMLInputElement; let number2: HTMLInputElement; // let password: HTMLInputElement; let confirmPassword: HTMLInputElement; let ceInput: HTMLInputElement; let viewModel: RegistrationForm; const renderer = { render: jasmine.createSpy() }; component.create(bootstrap as any) // grab some references. .then(() => { viewModel = component.viewModel; viewModel.controller.addRenderer(renderer); firstName = component.element.querySelector('#firstName') as HTMLInputElement; lastName = component.element.querySelector('#lastName') as HTMLInputElement; number1 = component.element.querySelector('#number1') as HTMLInputElement; number2 = component.element.querySelector('#number2') as HTMLInputElement; // password = component.element.querySelector('#password') as HTMLInputElement; confirmPassword = component.element.querySelector('#confirmPassword') as HTMLInputElement; ceInput = component.element.querySelector('custom-input#ce input') as HTMLInputElement; }) // initially there should not be any errors .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error1')) // blur the ceInput field- this should not trigger validation. .then(() => blur(ceInput)) // confirm there are no errors. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error1.1')) // focusout the ceInput field - this should not trigger validation as well because the default trigger is blur. .then(() => focusout(ceInput)) // confirm there are no errors. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error1.2')) // blur the firstName field- this should trigger validation. .then(() => blur(firstName)) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error2')) // make a model change to the firstName field. // this should reset the errors for the firstName field. .then(() => viewModel.firstName = 'test') // confirm the errors were reset. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error3')) // blur the firstName field- this should trigger validation. .then(() => blur(firstName)) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error2.1')) // make a model change to the firstName field. // this should reset the errors for the firstName field. .then(() => viewModel.firstName = 'foo') // confirm the errors were reset. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error3.1')) // blur the lastName field- this should trigger validation. .then(() => blur(lastName)) // confirm there's an error. .then(() => { expect(viewModel.controller.errors.length).toBe(1, 'error4'); const calls = renderer.render.calls; const renderInstruction = calls.argsFor(calls.count() - 1)[0]; expect(renderInstruction.render[0].elements[0]).toBe(lastName, 'error5'); }) // blur the number1 field- this should trigger validation. .then(() => blur(number1)) // confirm there's an error. .then(() => { expect(viewModel.controller.errors.length).toBe(2, 'error6'); const calls = renderer.render.calls; const renderInstruction = calls.argsFor(calls.count() - 1)[0]; expect(renderInstruction.render[0].elements[0]).toBe(number1, 'error7'); }) // blur the number2 field- this should trigger validation. .then(() => blur(number2)) // confirm there's an error. .then(() => { expect(viewModel.controller.errors.length).toBe(3, 'error8'); const calls = renderer.render.calls; const renderInstruction = calls.argsFor(calls.count() - 1)[0]; expect(renderInstruction.render[0].elements[0]).toBe(number2, 'error9'); }) // make a model change to the number1 field. // this should reset the errors for the number1 field. .then(() => viewModel.number1 = 1) // confirm the error was reset. .then(() => expect(viewModel.controller.errors.length).toBe(2, 'error10')) // make a model change to the number2 field. // this should reset the errors for the number2 field. .then(() => viewModel.number2 = 2) // confirm the error was reset. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error11')) // change the numbers back to invalid values. .then(() => { viewModel.number1 = 0; viewModel.number2 = 0; viewModel.firstName = ''; }) // hide the form and change the validateTrigger to 'focusout'. .then(() => { viewModel.showForm = false; viewModel.controller.validateTrigger = validateTrigger.focusout; }) // show the form .then(() => viewModel.showForm = true) // initially there should not be any errors .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error100.1')) // focusout the ceInput field - this trigger validation. .then(() => focusout(ceInput)) // confirm there are no errors. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error100.2')) // make a model change to the firstName field. // this should reset the errors for the firstName field. .then(() => viewModel.ceValue = 'test') // confirm the errors were reset. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error100.2.1')) // focusout the firstName field- this should trigger validation. .then(() => focusout(firstName)) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error100.3')) // make a model change to the firstName field. // this should reset the errors for the firstName field. .then(() => viewModel.firstName = 'test') // confirm the errors were reset. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error100.4')) // focusout the firstName field- this should trigger validation. .then(() => focusout(firstName)) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error100.3.1')) // make a model change to the firstName field. // this should reset the errors for the firstName field. .then(() => viewModel.firstName = 'foo') // confirm the errors were reset. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error100.4.1')) // focusout the lastName field- this should trigger validation. .then(() => focusout(lastName)) // confirm there's an error. .then(() => { expect(viewModel.controller.errors.length).toBe(1, 'error100.5'); const calls = renderer.render.calls; const renderInstruction = calls.argsFor(calls.count() - 1)[0]; expect(renderInstruction.render[0].elements[0]).toBe(lastName, 'error100.6'); }) // focusout the number1 field- this should trigger validation. .then(() => focusout(number1)) // confirm there's an error. .then(() => { expect(viewModel.controller.errors.length).toBe(2, 'error100.7'); const calls = renderer.render.calls; const renderInstruction = calls.argsFor(calls.count() - 1)[0]; expect(renderInstruction.render[0].elements[0]).toBe(number1, 'error100.8'); }) // focusout the number2 field- this should trigger validation. .then(() => focusout(number2)) // confirm there's an error. .then(() => { expect(viewModel.controller.errors.length).toBe(3, 'error100.9'); const calls = renderer.render.calls; const renderInstruction = calls.argsFor(calls.count() - 1)[0]; expect(renderInstruction.render[0].elements[0]).toBe(number2, 'error100.10'); }) // make a model change to the number1 field. // this should reset the errors for the number1 field. .then(() => viewModel.number1 = 1) // confirm the error was reset. .then(() => expect(viewModel.controller.errors.length).toBe(2, 'error100.11')) // make a model change to the number2 field. // this should reset the errors for the number2 field. .then(() => viewModel.number2 = 2) // confirm the error was reset. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error100.12')) // change the numbers back to invalid values. .then(() => { viewModel.number1 = 0; viewModel.number2 = 0; viewModel.firstName = ''; }) // hide the form and change the validateTrigger to 'change'. .then(() => { viewModel.showForm = false; viewModel.controller.validateTrigger = validateTrigger.change; }) // show the form .then(() => viewModel.showForm = true) // confirm hiding and showing the form reset the errors. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error12')) // change the firstName field- this should trigger validation. .then(() => change(ceInput, 'test')) // confirm there's no error. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error13')) // change the firstName field- this should trigger validation. .then(() => change(ceInput, '')) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error14')) // change the firstName field- this should trigger validation. .then(() => change(firstName, 'foo')) // confirm there's no error. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error13')) // change the firstName field- this should trigger validation. .then(() => change(firstName, '')) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(2, 'error14')) // change the number1 field- this should trigger validation. .then(() => change(number1, '-1')) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(3, 'error15')) // change the number2 field- this should trigger validation. .then(() => change(number2.firstElementChild as HTMLInputElement, '-1')) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(4, 'error16')) // change the number1 field- this should trigger validation. .then(() => change(number1, '32')) // confirm the error was reset. .then(() => expect(viewModel.controller.errors.length).toBe(3, 'error17')) // change the number2 field- this should trigger validation. .then(() => change(number2.firstElementChild as HTMLInputElement, '23')) // confirm the error was reset. .then(() => expect(viewModel.controller.errors.length).toBe(2, 'error18')) // change the numbers back to invalid values. .then(() => { viewModel.number1 = 0; viewModel.number2 = 0; viewModel.password = 'a'; viewModel.confirmPassword = 'a'; viewModel.controller.reset(); }) // make the passwords mismatch. .then(() => change(confirmPassword, 'b')) // confirm the custom validator worked .then(() => expect(viewModel.controller.errors[0].message) .toBe('Confirm Password must match Password', 'error19')) // hide the form and change the validateTrigger to 'manual'. .then(() => { viewModel.showForm = false; viewModel.controller.validateTrigger = validateTrigger.manual; }) // show the form .then(() => viewModel.showForm = true) // confirm hiding and showing the form reset the errors. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error20')) // validate all bindings .then(() => viewModel.controller.validate()) // confirm validating resulted in errors. .then(() => expect(viewModel.controller.errors.length).toBe(7, 'error21')) // reset all bindings .then(() => viewModel.controller.reset()) // confirm resetting cleared all errors. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error22')) // hide the form and change the validateTrigger to 'changeOrBlur'. .then(() => { viewModel.showForm = false; viewModel.controller.validateTrigger = validateTrigger.changeOrBlur; }) // show the form .then(() => viewModel.showForm = true) // confirm hiding and showing the form reset the errors. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error23')) // blur the ceInput field- this should trigger validation. .then(() => blur(ceInput)) // confirm there's no error as the event won't bubble .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error24')) // make a model change to the firstName field. // and blur the field .then(() => change(ceInput, 'test')) .then(() => blur(ceInput)) // confirm there are no errors as blur still does not bubble .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error25')) // focusout the field .then(() => focusout(ceInput)) // confirm there are no errors as no handler for focusout .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error25')) // blur the firstName field- this should trigger validation. .then(() => blur(firstName)) // confirm there's no error as it is still pristine. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error24')) // make a model change to the firstName field. // and trigger the first validation by blurring the field .then(() => change(firstName, 'test')) .then(() => blur(firstName)) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error25')) // As the field is already touched by validation, changing the value to a valid one should reset the error .then(() => change(firstName, 'foo')) // confirm the errors were reset. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error25.1')) // change the lastName field- this should trigger validation. .then(() => change(lastName, 'abcdef')) .then(() => change(lastName, '')) .then(() => blur(lastName)) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error26')) // make lastName valid again .then(() => change(lastName, 'ghi')) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error27')) // change the numbers back to invalid values. .then(() => { viewModel.number1 = 0; viewModel.number2 = 0; viewModel.ceValue = ''; viewModel.firstName = ''; viewModel.lastName = ''; viewModel.password = 'a'; viewModel.controller.reset(); }) // perform manual validation and // assert that when the values are changed to valid values, all the errors are removed .then(() => viewModel.controller.validate()) .then(() => expect(viewModel.controller.errors.length).toBe(7, 'error27.1')) .then(() => change(ceInput, 'foo')) .then(() => change(firstName, 'foo')) .then(() => change(lastName, 'test')) .then(() => { viewModel.number1 = 42; viewModel.number2 = 42; viewModel.email = 'a@b.com'; viewModel.password = 'a'; return change(confirmPassword, 'a'); }) .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error27.2')) // change the numbers back to invalid values. .then(() => { viewModel.number1 = 0; viewModel.number2 = 0; viewModel.ceValue = ''; viewModel.firstName = ''; viewModel.lastName = ''; }) // hide the form and change the validateTrigger to 'changeOrFocusout'. .then(() => { viewModel.showForm = false; viewModel.controller.validateTrigger = validateTrigger.changeOrFocusout; }) // show the form .then(() => viewModel.showForm = true) // confirm hiding and showing the form reset the errors. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error200.1')) // focusout the ceInput field- this should trigger validation. .then(() => focusout(ceInput)) // confirm there's an error .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error200.2')) // make a model change to the firstName field. .then(() => change(ceInput, 'test')) .then(() => focusout(ceInput)) // confirm there are no errors .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error200.3')) // set the ceInput to valid value .then(() => change(ceInput, 'foo')) // confirm that there are no errors .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error200.3.1')) // focusout the firstName field- this should trigger validation. .then(() => focusout(firstName)) // confirm there's no error as it is still pristine. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error200.5')) // make a model change to the firstName field. // and trigger the first validation by focusing out the field .then(() => change(firstName, 'test')) .then(() => focusout(firstName)) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error200.6')) // As the field is already touched by validation, changing the value to a valid one should reset the error .then(() => change(firstName, 'foo')) // confirm the errors were reset. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error200.7')) // change the lastName field- this should trigger validation. .then(() => change(lastName, 'abcdef')) .then(() => change(lastName, '')) .then(() => focusout(lastName)) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error200.8')) // make lastName valid again .then(() => change(lastName, 'ghi')) // confirm there's an error. .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error200.9')) // change the numbers back to invalid values. .then(() => { viewModel.number1 = 0; viewModel.number2 = 0; viewModel.ceValue = ''; viewModel.firstName = ''; viewModel.lastName = ''; viewModel.email = ''; viewModel.password = ''; viewModel.controller.reset(); }) // perform manual validation and // assert that when the values are changed to valid values, all the errors are removed .then(() => viewModel.controller.validate()) .then(() => expect(viewModel.controller.errors.length).toBe(7, 'error200.10')) .then(() => change(ceInput, 'foo')) .then(() => change(firstName, 'foo')) .then(() => change(lastName, 'test')) .then(() => { viewModel.number1 = 42; viewModel.number2 = 42; viewModel.email = 'a@b.com'; viewModel.password = 'a'; return change(confirmPassword, 'a'); }) .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error200.11')) // add some errors .then(() => { const error1 = viewModel.controller.addError('object error', viewModel); expect(error1.message).toBe('object error', 'error28'); expect(error1.object).toBe(viewModel, 'error29'); expect(error1.propertyName).toBe(null, 'error30'); const error2 = viewModel.controller.addError('string property error', viewModel, 'lastName'); expect(error2.message).toBe('string property error', 'error31'); expect(error2.object).toBe(viewModel, 'error32'); expect(error2.propertyName).toBe('lastName', 'error33'); const error3 = viewModel.controller.addError('expression property error', viewModel, vm => vm.firstName); expect(error3.message).toBe('expression property error', 'error34'); expect(error3.object).toBe(viewModel, 'error35'); expect(error3.propertyName).toBe('firstName', 'error36'); expect(viewModel.controller.errors.length).toBe(3, 'error37'); viewModel.controller.removeError(error1); expect(viewModel.controller.errors.length).toBe(2, 'error38'); viewModel.controller.removeError(error2); expect(viewModel.controller.errors.length).toBe(1, 'error39'); viewModel.controller.removeError(error3); expect(viewModel.controller.errors.length).toBe(0, 'error40'); }) // subscribe to error events .then(() => { let event1: ValidateEvent; let event2: ValidateEvent; const spy1 = jasmine.createSpy().and.callFake((event: ValidateEvent) => event1 = event); const spy2 = jasmine.createSpy().and.callFake((event: ValidateEvent) => event2 = event); viewModel.controller.subscribe(spy1); viewModel.controller.subscribe(spy2); return Promise.resolve() .then(() => change(lastName, '')) .then(() => { expect(spy1).toHaveBeenCalled(); expect(spy2).toHaveBeenCalled(); expect(event1).toBeDefined(); expect(event2).toBeDefined(); expect(event1).toBe(event2, 'error43'); expect(event1.errors.length).toBe(1, 'error44'); spy1.calls.reset(); spy2.calls.reset(); event1 = null as any; event2 = null as any; }) .then(() => change(firstName, '')) .then(() => { expect(spy1).toHaveBeenCalled(); expect(spy2).toHaveBeenCalled(); expect(event1).toBeDefined(); expect(event2).toBeDefined(); expect(event1).toBe(event2, 'error47'); expect(event1.errors.length).toBe(2, 'error48'); }); }) // cleanup and finish. .then(() => component.dispose()) .then(done); }); });
the_stack
import * as GObject from "@gi-types/gobject"; import * as Gio from "@gi-types/gio"; export const MIXER_UI_DEVICE_INVALID: number; export namespace MixerControlState { export const $gtype: GObject.GType<MixerControlState>; } export enum MixerControlState { CLOSED = 0, READY = 1, CONNECTING = 2, FAILED = 3, } export namespace MixerStreamState { export const $gtype: GObject.GType<MixerStreamState>; } export enum MixerStreamState { INVALID = 0, RUNNING = 1, IDLE = 2, SUSPENDED = 3, } export namespace MixerUIDeviceDirection { export const $gtype: GObject.GType<MixerUIDeviceDirection>; } export enum MixerUIDeviceDirection { INPUT = 0, OUTPUT = 1, } export namespace HeadsetPortChoice { export const $gtype: GObject.GType<HeadsetPortChoice>; } export enum HeadsetPortChoice { NONE = 0, HEADPHONES = 1, HEADSET = 2, MIC = 4, } export module ChannelMap { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class ChannelMap extends GObject.Object { static $gtype: GObject.GType<ChannelMap>; constructor(properties?: Partial<ChannelMap.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ChannelMap.ConstructorProperties>, ...args: any[]): void; // Fields priv: ChannelMapPrivate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "volume-changed", callback: (_source: this, object: boolean) => void): number; connect_after(signal: "volume-changed", callback: (_source: this, object: boolean) => void): number; emit(signal: "volume-changed", object: boolean): void; // Constructors static ["new"](): ChannelMap; // Members can_balance(): boolean; can_fade(): boolean; get_mapping(): string; get_num_channels(): number; get_volume(): number; vfunc_volume_changed(set: boolean): void; } export module MixerCard { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; human_profile: string; humanProfile: string; icon_name: string; iconName: string; id: number; index: number; name: string; pa_context: any; paContext: any; profile: string; } } export class MixerCard extends GObject.Object { static $gtype: GObject.GType<MixerCard>; constructor(properties?: Partial<MixerCard.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MixerCard.ConstructorProperties>, ...args: any[]): void; // Properties human_profile: string; humanProfile: string; icon_name: string; iconName: string; id: number; index: number; name: string; pa_context: any; paContext: any; profile: string; // Fields priv: MixerCardPrivate; // Members change_profile(profile?: string | null): boolean; get_gicon(): Gio.Icon; get_icon_name(): string; get_id(): number; get_index(): number; get_name(): string; get_ports(): MixerCardPort[]; get_profiles(): MixerCardProfile[]; set_icon_name(name: string): boolean; set_name(name: string): boolean; set_ports(ports: MixerCardPort[]): boolean; set_profile(profile: string): boolean; set_profiles(profiles: MixerCardProfile[]): boolean; } export module MixerControl { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; name: string; } } export class MixerControl extends GObject.Object { static $gtype: GObject.GType<MixerControl>; constructor(properties?: Partial<MixerControl.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MixerControl.ConstructorProperties>, ...args: any[]): void; // Properties name: string; // Fields priv: MixerControlPrivate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "active-input-update", callback: (_source: this, object: number) => void): number; connect_after(signal: "active-input-update", callback: (_source: this, object: number) => void): number; emit(signal: "active-input-update", object: number): void; connect(signal: "active-output-update", callback: (_source: this, object: number) => void): number; connect_after(signal: "active-output-update", callback: (_source: this, object: number) => void): number; emit(signal: "active-output-update", object: number): void; connect( signal: "audio-device-selection-needed", callback: (_source: this, object: number, p0: boolean, p1: number) => void ): number; connect_after( signal: "audio-device-selection-needed", callback: (_source: this, object: number, p0: boolean, p1: number) => void ): number; emit(signal: "audio-device-selection-needed", object: number, p0: boolean, p1: number): void; connect(signal: "card-added", callback: (_source: this, object: number) => void): number; connect_after(signal: "card-added", callback: (_source: this, object: number) => void): number; emit(signal: "card-added", object: number): void; connect(signal: "card-removed", callback: (_source: this, object: number) => void): number; connect_after(signal: "card-removed", callback: (_source: this, object: number) => void): number; emit(signal: "card-removed", object: number): void; connect(signal: "default-sink-changed", callback: (_source: this, object: number) => void): number; connect_after(signal: "default-sink-changed", callback: (_source: this, object: number) => void): number; emit(signal: "default-sink-changed", object: number): void; connect(signal: "default-source-changed", callback: (_source: this, object: number) => void): number; connect_after(signal: "default-source-changed", callback: (_source: this, object: number) => void): number; emit(signal: "default-source-changed", object: number): void; connect(signal: "input-added", callback: (_source: this, object: number) => void): number; connect_after(signal: "input-added", callback: (_source: this, object: number) => void): number; emit(signal: "input-added", object: number): void; connect(signal: "input-removed", callback: (_source: this, object: number) => void): number; connect_after(signal: "input-removed", callback: (_source: this, object: number) => void): number; emit(signal: "input-removed", object: number): void; connect(signal: "output-added", callback: (_source: this, object: number) => void): number; connect_after(signal: "output-added", callback: (_source: this, object: number) => void): number; emit(signal: "output-added", object: number): void; connect(signal: "output-removed", callback: (_source: this, object: number) => void): number; connect_after(signal: "output-removed", callback: (_source: this, object: number) => void): number; emit(signal: "output-removed", object: number): void; connect(signal: "state-changed", callback: (_source: this, object: number) => void): number; connect_after(signal: "state-changed", callback: (_source: this, object: number) => void): number; emit(signal: "state-changed", object: number): void; connect(signal: "stream-added", callback: (_source: this, object: number) => void): number; connect_after(signal: "stream-added", callback: (_source: this, object: number) => void): number; emit(signal: "stream-added", object: number): void; connect(signal: "stream-changed", callback: (_source: this, object: number) => void): number; connect_after(signal: "stream-changed", callback: (_source: this, object: number) => void): number; emit(signal: "stream-changed", object: number): void; connect(signal: "stream-removed", callback: (_source: this, object: number) => void): number; connect_after(signal: "stream-removed", callback: (_source: this, object: number) => void): number; emit(signal: "stream-removed", object: number): void; // Constructors static ["new"](name: string): MixerControl; // Members change_input(input: MixerUIDevice): void; change_output(output: MixerUIDevice): void; change_profile_on_selected_device(device: MixerUIDevice, profile?: string | null): boolean; close(): boolean; get_cards(): MixerCard[]; get_default_sink(): MixerStream; get_default_source(): MixerStream; get_event_sink_input(): MixerStream; get_sink_inputs(): MixerSinkInput[]; get_sinks(): MixerSink[]; get_source_outputs(): MixerSourceOutput[]; get_sources(): MixerSource[]; get_state(): MixerControlState; get_stream_from_device(device: MixerUIDevice): MixerStream; get_streams(): MixerStream[]; get_vol_max_amplified(): number; get_vol_max_norm(): number; lookup_card_id(id: number): MixerCard; lookup_device_from_stream(stream: MixerStream): MixerUIDevice; lookup_input_id(id: number): MixerUIDevice; lookup_output_id(id: number): MixerUIDevice; lookup_stream_id(id: number): MixerStream; open(): boolean; set_default_sink(stream: MixerStream): boolean; set_default_source(stream: MixerStream): boolean; set_headset_port(id: number, choices: HeadsetPortChoice): void; vfunc_active_input_update(id: number): void; vfunc_active_output_update(id: number): void; vfunc_audio_device_selection_needed(id: number, show_dialog: boolean, choices: HeadsetPortChoice): void; vfunc_card_added(id: number): void; vfunc_card_removed(id: number): void; vfunc_default_sink_changed(id: number): void; vfunc_default_source_changed(id: number): void; vfunc_input_added(id: number): void; vfunc_input_removed(id: number): void; vfunc_output_added(id: number): void; vfunc_output_removed(id: number): void; vfunc_state_changed(new_state: MixerControlState): void; vfunc_stream_added(id: number): void; vfunc_stream_changed(id: number): void; vfunc_stream_removed(id: number): void; } export module MixerEventRole { export interface ConstructorProperties extends MixerStream.ConstructorProperties { [key: string]: any; device: string; } } export class MixerEventRole extends MixerStream { static $gtype: GObject.GType<MixerEventRole>; constructor(properties?: Partial<MixerEventRole.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MixerEventRole.ConstructorProperties>, ...args: any[]): void; // Properties device: string; // Fields priv: MixerEventRolePrivate | any; } export module MixerSink { export interface ConstructorProperties extends MixerStream.ConstructorProperties { [key: string]: any; } } export class MixerSink extends MixerStream { static $gtype: GObject.GType<MixerSink>; constructor(properties?: Partial<MixerSink.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MixerSink.ConstructorProperties>, ...args: any[]): void; // Fields priv: MixerSinkPrivate | any; } export module MixerSinkInput { export interface ConstructorProperties extends MixerStream.ConstructorProperties { [key: string]: any; } } export class MixerSinkInput extends MixerStream { static $gtype: GObject.GType<MixerSinkInput>; constructor(properties?: Partial<MixerSinkInput.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MixerSinkInput.ConstructorProperties>, ...args: any[]): void; // Fields priv: MixerSinkInputPrivate | any; } export module MixerSource { export interface ConstructorProperties extends MixerStream.ConstructorProperties { [key: string]: any; } } export class MixerSource extends MixerStream { static $gtype: GObject.GType<MixerSource>; constructor(properties?: Partial<MixerSource.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MixerSource.ConstructorProperties>, ...args: any[]): void; // Fields priv: MixerSourcePrivate | any; } export module MixerSourceOutput { export interface ConstructorProperties extends MixerStream.ConstructorProperties { [key: string]: any; } } export class MixerSourceOutput extends MixerStream { static $gtype: GObject.GType<MixerSourceOutput>; constructor(properties?: Partial<MixerSourceOutput.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MixerSourceOutput.ConstructorProperties>, ...args: any[]): void; // Fields priv: MixerSourceOutputPrivate | any; } export module MixerStream { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; application_id: string; applicationId: string; can_decibel: boolean; canDecibel: boolean; card_index: number; cardIndex: number; channel_map: ChannelMap; channelMap: ChannelMap; decibel: number; description: string; form_factor: string; formFactor: string; icon_name: string; iconName: string; id: number; index: number; is_event_stream: boolean; isEventStream: boolean; is_muted: boolean; isMuted: boolean; is_virtual: boolean; isVirtual: boolean; name: string; pa_context: any; paContext: any; port: string; state: MixerStreamState; sysfs_path: string; sysfsPath: string; volume: number; } } export abstract class MixerStream extends GObject.Object { static $gtype: GObject.GType<MixerStream>; constructor(properties?: Partial<MixerStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MixerStream.ConstructorProperties>, ...args: any[]): void; // Properties application_id: string; applicationId: string; can_decibel: boolean; canDecibel: boolean; card_index: number; cardIndex: number; channel_map: ChannelMap; channelMap: ChannelMap; decibel: number; description: string; form_factor: string; formFactor: string; icon_name: string; iconName: string; id: number; index: number; is_event_stream: boolean; isEventStream: boolean; is_muted: boolean; isMuted: boolean; is_virtual: boolean; isVirtual: boolean; name: string; pa_context: any; paContext: any; port: string; state: MixerStreamState; sysfs_path: string; sysfsPath: string; volume: number; // Fields priv: MixerStreamPrivate; // Members change_is_muted(is_muted: boolean): boolean; change_port(port: string): boolean; get_application_id(): string; get_base_volume(): number; get_can_decibel(): boolean; get_card_index(): number; get_channel_map(): ChannelMap; get_decibel(): number; get_description(): string; get_form_factor(): string; get_gicon(): Gio.Icon; get_icon_name(): string; get_id(): number; get_index(): number; get_is_muted(): boolean; get_name(): string; get_port(): MixerStreamPort; get_ports(): MixerStreamPort[]; get_state(): MixerStreamState; get_sysfs_path(): string; get_volume(): number; is_running(): boolean; push_volume(): boolean; set_application_id(application_id: string): boolean; set_base_volume(base_volume: number): boolean; set_can_decibel(can_decibel: boolean): boolean; set_card_index(card_index: number): boolean; set_decibel(db: number): boolean; set_description(description: string): boolean; set_form_factor(form_factor: string): boolean; set_icon_name(name: string): boolean; set_is_event_stream(is_event_stream: boolean): boolean; set_is_muted(is_muted: boolean): boolean; set_is_virtual(is_event_stream: boolean): boolean; set_name(name: string): boolean; set_port(port: string): boolean; set_ports(ports: MixerStreamPort[]): boolean; set_state(state: MixerStreamState): boolean; set_sysfs_path(sysfs_path: string): boolean; set_volume(volume: number): boolean; vfunc_change_is_muted(is_muted: boolean): boolean; vfunc_change_port(port: string): boolean; vfunc_push_volume(operation?: any | null): boolean; } export module MixerUIDevice { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; card: any; description: string; icon_name: string; iconName: string; origin: string; port_available: boolean; portAvailable: boolean; port_name: string; portName: string; stream_id: number; streamId: number; type: number; } } export class MixerUIDevice extends GObject.Object { static $gtype: GObject.GType<MixerUIDevice>; constructor(properties?: Partial<MixerUIDevice.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MixerUIDevice.ConstructorProperties>, ...args: any[]): void; // Properties card: any; description: string; icon_name: string; iconName: string; origin: string; port_available: boolean; portAvailable: boolean; port_name: string; portName: string; stream_id: number; streamId: number; type: number; // Fields priv: MixerUIDevicePrivate; // Members get_active_profile(): string; get_best_profile(selected: string | null, current: string): string; get_description(): string; get_gicon(): Gio.Icon; get_icon_name(): string; get_id(): number; get_matching_profile(profile: string): string; get_origin(): string; get_port(): string; get_profiles(): MixerCardProfile[]; get_stream_id(): number; get_supported_profiles(): MixerCardProfile[]; get_top_priority_profile(): string; get_user_preferred_profile(): string; has_ports(): boolean; invalidate_stream(): void; is_output(): boolean; set_profiles(in_profiles: MixerCardProfile[]): void; set_user_preferred_profile(profile: string): void; should_profiles_be_hidden(): boolean; } export class ChannelMapPrivate { static $gtype: GObject.GType<ChannelMapPrivate>; constructor(copy: ChannelMapPrivate); } export class MixerCardPort { static $gtype: GObject.GType<MixerCardPort>; constructor(copy: MixerCardPort); // Fields port: string; human_port: string; icon_name: string; priority: number; available: number; direction: number; profiles: any[]; } export class MixerCardPrivate { static $gtype: GObject.GType<MixerCardPrivate>; constructor(copy: MixerCardPrivate); } export class MixerCardProfile { static $gtype: GObject.GType<MixerCardProfile>; constructor( properties?: Partial<{ profile?: string; human_profile?: string; status?: string; priority?: number; n_sinks?: number; n_sources?: number; }> ); constructor(copy: MixerCardProfile); // Fields profile: string; human_profile: string; status: string; priority: number; n_sinks: number; n_sources: number; // Members compare(b: MixerCardProfile): number; } export class MixerControlPrivate { static $gtype: GObject.GType<MixerControlPrivate>; constructor(copy: MixerControlPrivate); } export class MixerEventRolePrivate { static $gtype: GObject.GType<MixerEventRolePrivate>; constructor(copy: MixerEventRolePrivate); } export class MixerSinkInputPrivate { static $gtype: GObject.GType<MixerSinkInputPrivate>; constructor(copy: MixerSinkInputPrivate); } export class MixerSinkPrivate { static $gtype: GObject.GType<MixerSinkPrivate>; constructor(copy: MixerSinkPrivate); } export class MixerSourceOutputPrivate { static $gtype: GObject.GType<MixerSourceOutputPrivate>; constructor(copy: MixerSourceOutputPrivate); } export class MixerSourcePrivate { static $gtype: GObject.GType<MixerSourcePrivate>; constructor(copy: MixerSourcePrivate); } export class MixerStreamPort { static $gtype: GObject.GType<MixerStreamPort>; constructor( properties?: Partial<{ port?: string; human_port?: string; priority?: number; available?: boolean; }> ); constructor(copy: MixerStreamPort); // Fields port: string; human_port: string; priority: number; available: boolean; } export class MixerStreamPrivate { static $gtype: GObject.GType<MixerStreamPrivate>; constructor(copy: MixerStreamPrivate); } export class MixerUIDevicePrivate { static $gtype: GObject.GType<MixerUIDevicePrivate>; constructor(copy: MixerUIDevicePrivate); }
the_stack
import { Platform } from 'react-native'; import { Color } from './types'; export const colors: { [colorname: string]: number[] } = { aliceblue: [240, 248, 255], antiquewhite: [250, 235, 215], aqua: [0, 255, 255], aquamarine: [127, 255, 212], azure: [240, 255, 255], beige: [245, 245, 220], bisque: [255, 228, 196], black: [0, 0, 0], blanchedalmond: [255, 235, 205], blue: [0, 0, 255], blueviolet: [138, 43, 226], brown: [165, 42, 42], burlywood: [222, 184, 135], cadetblue: [95, 158, 160], chartreuse: [127, 255, 0], chocolate: [210, 105, 30], coral: [255, 127, 80], cornflowerblue: [100, 149, 237], cornsilk: [255, 248, 220], crimson: [220, 20, 60], cyan: [0, 255, 255], darkblue: [0, 0, 139], darkcyan: [0, 139, 139], darkgoldenrod: [184, 134, 11], darkgray: [169, 169, 169], darkgreen: [0, 100, 0], darkgrey: [169, 169, 169], darkkhaki: [189, 183, 107], darkmagenta: [139, 0, 139], darkolivegreen: [85, 107, 47], darkorange: [255, 140, 0], darkorchid: [153, 50, 204], darkred: [139, 0, 0], darksalmon: [233, 150, 122], darkseagreen: [143, 188, 143], darkslateblue: [72, 61, 139], darkslategray: [47, 79, 79], darkslategrey: [47, 79, 79], darkturquoise: [0, 206, 209], darkviolet: [148, 0, 211], deeppink: [255, 20, 147], deepskyblue: [0, 191, 255], dimgray: [105, 105, 105], dimgrey: [105, 105, 105], dodgerblue: [30, 144, 255], firebrick: [178, 34, 34], floralwhite: [255, 250, 240], forestgreen: [34, 139, 34], fuchsia: [255, 0, 255], gainsboro: [220, 220, 220], ghostwhite: [248, 248, 255], gold: [255, 215, 0], goldenrod: [218, 165, 32], gray: [128, 128, 128], green: [0, 128, 0], greenyellow: [173, 255, 47], grey: [128, 128, 128], honeydew: [240, 255, 240], hotpink: [255, 105, 180], indianred: [205, 92, 92], indigo: [75, 0, 130], ivory: [255, 255, 240], khaki: [240, 230, 140], lavender: [230, 230, 250], lavenderblush: [255, 240, 245], lawngreen: [124, 252, 0], lemonchiffon: [255, 250, 205], lightblue: [173, 216, 230], lightcoral: [240, 128, 128], lightcyan: [224, 255, 255], lightgoldenrodyellow: [250, 250, 210], lightgray: [211, 211, 211], lightgreen: [144, 238, 144], lightgrey: [211, 211, 211], lightpink: [255, 182, 193], lightsalmon: [255, 160, 122], lightseagreen: [32, 178, 170], lightskyblue: [135, 206, 250], lightslategray: [119, 136, 153], lightslategrey: [119, 136, 153], lightsteelblue: [176, 196, 222], lightyellow: [255, 255, 224], lime: [0, 255, 0], limegreen: [50, 205, 50], linen: [250, 240, 230], magenta: [255, 0, 255], maroon: [128, 0, 0], mediumaquamarine: [102, 205, 170], mediumblue: [0, 0, 205], mediumorchid: [186, 85, 211], mediumpurple: [147, 112, 219], mediumseagreen: [60, 179, 113], mediumslateblue: [123, 104, 238], mediumspringgreen: [0, 250, 154], mediumturquoise: [72, 209, 204], mediumvioletred: [199, 21, 133], midnightblue: [25, 25, 112], mintcream: [245, 255, 250], mistyrose: [255, 228, 225], moccasin: [255, 228, 181], navajowhite: [255, 222, 173], navy: [0, 0, 128], oldlace: [253, 245, 230], olive: [128, 128, 0], olivedrab: [107, 142, 35], orange: [255, 165, 0], orangered: [255, 69, 0], orchid: [218, 112, 214], palegoldenrod: [238, 232, 170], palegreen: [152, 251, 152], paleturquoise: [175, 238, 238], palevioletred: [219, 112, 147], papayawhip: [255, 239, 213], peachpuff: [255, 218, 185], peru: [205, 133, 63], pink: [255, 192, 203], plum: [221, 160, 221], powderblue: [176, 224, 230], purple: [128, 0, 128], rebeccapurple: [102, 51, 153], red: [255, 0, 0], rosybrown: [188, 143, 143], royalblue: [65, 105, 225], saddlebrown: [139, 69, 19], salmon: [250, 128, 114], sandybrown: [244, 164, 96], seagreen: [46, 139, 87], seashell: [255, 245, 238], sienna: [160, 82, 45], silver: [192, 192, 192], skyblue: [135, 206, 235], slateblue: [106, 90, 205], slategray: [112, 128, 144], slategrey: [112, 128, 144], snow: [255, 250, 250], springgreen: [0, 255, 127], steelblue: [70, 130, 180], tan: [210, 180, 140], teal: [0, 128, 128], thistle: [216, 191, 216], tomato: [255, 99, 71], turquoise: [64, 224, 208], violet: [238, 130, 238], wheat: [245, 222, 179], white: [255, 255, 255], whitesmoke: [245, 245, 245], yellow: [255, 255, 0], yellowgreen: [154, 205, 50], }; export const colorNames: { [colorname: string]: number | void } = {}; for (const name in colors) { if (colors.hasOwnProperty(name)) { const color: number[] = colors[name]; const r = color[0]; const g = color[1]; const b = color[2]; colorNames[name] = (0xff000000 | (r << 16) | (g << 8) | b) >>> 0; } } Object.freeze(colorNames); function hslToRgb(_h: number, _s: number, _l: number, a: number) { const h = _h / 360; const s = _s / 100; const l = _l / 100; let t1; let t2; let t3; let rgb; let val; if (s === 0) { val = l; return [val, val, val, a]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } t1 = 2 * l - t2; rgb = [0, 0, 0, a]; for (let i = 0; i < 3; i++) { t3 = h + (1 / 3) * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val; } return rgb; } function hwbToRgb(_h: number, _w: number, _b: number, a: number) { const h = _h / 360; let wh = _w / 100; let bl = _b / 100; const ratio = wh + bl; let i; let v; let f; let n; // wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } i = Math.floor(6 * h); v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } n = wh + f * (v - wh); // linear interpolation let r; let g; let b; switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } return [r, g, b, a]; } function clamp(num: number, min: number, max: number) { return Math.min(Math.max(min, num), max); } const abbr = /^#([a-f0-9]{3,4})$/i; const hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i; const rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d.]+)\s*)?\)$/; const per = /^rgba?\(\s*([+-]?[\d.]+)%\s*,\s*([+-]?[\d.]+)%\s*,\s*([+-]?[\d.]+)%\s*(?:,\s*([+-]?[\d.]+)\s*)?\)$/; const keyword = /(\D+)/; function rgbFromString(string: string) { let rgb = [0, 0, 0, 1]; let match; let i; let hexAlpha; if ((match = string.match(hex))) { hexAlpha = match[2]; match = match[1]; for (i = 0; i < 3; i++) { // https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19 const i2 = i * 2; rgb[i] = parseInt(match.slice(i2, i2 + 2), 16) / 255; } if (hexAlpha) { rgb[3] = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100; } } else if ((match = string.match(abbr))) { match = match[1]; hexAlpha = match[3]; for (i = 0; i < 3; i++) { rgb[i] = parseInt(match[i] + match[i], 16) / 255; } if (hexAlpha) { rgb[3] = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100; } } else if ((match = string.match(rgba))) { for (i = 0; i < 3; i++) { rgb[i] = parseInt(match[i + 1], 0) / 255; } if (match[4]) { rgb[3] = parseFloat(match[4]); } } else if ((match = string.match(per))) { for (i = 0; i < 3; i++) { rgb[i] = parseFloat(match[i + 1]) / 100; } if (match[4]) { rgb[3] = parseFloat(match[4]); } } else if ((match = string.match(keyword))) { if (match[1] === 'transparent') { return [0, 0, 0, 0]; } let color = colorNames[match[1]]; if (!(typeof color === 'number')) { return null; } return integerColor(color); } else { return null; } for (i = 0; i < 4; i++) { rgb[i] = clamp(rgb[i], 0, 1); } return rgb; } const hslRegEx = /^hsla?\(\s*([+-]?(?:\d*\.)?\d+)(?:deg)?\s*,\s*([+-]?[\d.]+)%\s*,\s*([+-]?[\d.]+)%\s*(?:,\s*([+-]?[\d.]+)\s*)?\)$/; function rgbFromHslString(string: string) { const match = string.match(hslRegEx); if (!match) { return null; } const alpha = parseFloat(match[4]); const h = (parseFloat(match[1]) + 360) % 360; const s = clamp(parseFloat(match[2]), 0, 100); const l = clamp(parseFloat(match[3]), 0, 100); const a = isNaN(alpha) ? 1 : clamp(alpha, 0, 1); return hslToRgb(h, s, l, a); } const hwbRegEx = /^hwb\(\s*([+-]?\d*[.]?\d+)(?:deg)?\s*,\s*([+-]?[\d.]+)%\s*,\s*([+-]?[\d.]+)%\s*(?:,\s*([+-]?[\d.]+)\s*)?\)$/; function rgbFromHwbString(string: string) { const match = string.match(hwbRegEx); if (!match) { return null; } const alpha = parseFloat(match[4]); const h = ((parseFloat(match[1]) % 360) + 360) % 360; const w = clamp(parseFloat(match[2]), 0, 100); const b = clamp(parseFloat(match[3]), 0, 100); const a = isNaN(alpha) ? 1 : clamp(alpha, 0, 1); return hwbToRgb(h, w, b, a); } function colorFromString(string: string) { const prefix = string.substring(0, 3).toLowerCase(); switch (prefix) { case 'hsl': return rgbFromHslString(string); case 'hwb': return rgbFromHwbString(string); default: return rgbFromString(string); } } const identity = (x: number) => x; const toSignedInt32 = (x: number) => x | 0x0; // Android use 32 bit *signed* integer to represent the color // We utilize the fact that bitwise operations in JS also operates on // signed 32 bit integers, so that we can use those to convert from // *unsigned* to *signed* 32bit in that way. export const integerColor = Platform.OS === 'android' ? toSignedInt32 : identity; // Returns 0xaarrggbb or null export default function extractColor(color: Color | void) { if (typeof color === 'number') { if (color >>> 0 === color && color >= 0 && color <= 0xffffffff) { return integerColor(color); } return null; } const parsedColor = typeof color === 'string' ? colorFromString(color) : color; if (!Array.isArray(parsedColor)) { return parsedColor; } const r = parsedColor[0]; const g = parsedColor[1]; const b = parsedColor[2]; const a = parsedColor[3]; const int32Color = ((a === undefined ? 0xff000000 : Math.round(a * 255) << 24) | (Math.round(r * 255) << 16) | (Math.round(g * 255) << 8) | Math.round(b * 255)) >>> 0; return integerColor(int32Color); }
the_stack
import { equals, PathNode, pluck, Rejection, RejectType, Resolvable, services, StateService, Transition, TransitionService, UIRouter, } from '../src'; import { PromiseResult, tree2Array } from './_testUtils'; import { TestingPlugin } from './_testingPlugin'; describe('transition', function() { let router: UIRouter; let $transitions: TransitionService; let $state: StateService; function makeTransition(from, to, options?): Transition { const fromState = $state.target(from).$state(); const fromPath = fromState.path.map(state => new PathNode(state)); return $transitions.create(fromPath, $state.target(to, null, options)); } const _delay = millis => new Promise(resolve => setTimeout(resolve, millis)); const delay = millis => () => _delay(millis); const tick = (val?) => new Promise(resolve => setTimeout(() => resolve(val))); // Use this in a .then(go('from', 'to')) when you want to run a transition you expect to succeed const go = (from, to, options?) => () => makeTransition(from, to, options) .run() .then(tick); // Use this in a .then(goFail('from', 'to')) when you want to run a transition you expect to fail const goFail = (from, to, options?) => () => makeTransition(from, to, options) .run() .catch(tick); beforeEach(() => { router = new UIRouter(); router.plugin(TestingPlugin); $state = router.stateService; $transitions = router.transitionService; const stateTree = { first: {}, second: {}, third: {}, A: { B: { C: { D: {}, }, E: { F: {}, }, }, G: { H: { I: {}, }, }, }, }; const states = tree2Array(stateTree, false); states.forEach(state => router.stateRegistry.register(state)); }); describe('service', () => { describe('async event hooks:', () => { it('$transition$.promise should resolve on success', done => { const result = new PromiseResult(); $transitions.onStart({ from: '*', to: 'second' }, function($transition$) { result.setPromise($transition$.promise); }); Promise.resolve() .then(go('', 'second')) .then(() => expect(result.called()).toEqual({ resolve: true, reject: false, complete: true })) .then(done); }); it('$transition$.promise should reject on error', done => { const result = new PromiseResult(); $transitions.onStart({ from: '*', to: 'third' }, function($transition$) { result.setPromise($transition$.promise); throw new Error('transition failed'); }); Promise.resolve() .then(goFail('', 'third')) .then(() => { expect(result.called()).toEqual({ resolve: false, reject: true, complete: true }); expect(result.get().reject instanceof Rejection).toBeTruthy(); expect(result.get().reject.message).toEqual('The transition errored'); expect(result.get().reject.detail.message).toEqual('transition failed'); }) .then(done); }); it('$transition$.promise should reject on error in synchronous hooks', done => { const result = new PromiseResult(); $transitions.onBefore({ from: '*', to: 'third' }, function($transition$) { result.setPromise($transition$.promise); throw new Error('transition failed'); }); Promise.resolve() .then(goFail('', 'third')) .then(() => { expect(result.called()).toEqual({ resolve: false, reject: true, complete: true }); expect(result.get().reject instanceof Rejection).toBeTruthy(); expect(result.get().reject.message).toEqual('The transition errored'); expect(result.get().reject.detail.message).toEqual('transition failed'); }) .then(done); }); it('should receive the transition as the first parameter', done => { let t = null; $transitions.onStart({ from: '*', to: 'second' }, function(trans) { t = trans; }); const tsecond = makeTransition('', 'second'); tsecond .run() .then(tick) .then(() => expect(t).toBe(tsecond)) .then(done); }); // Test for #2972 and https://github.com/ui-router/react/issues/3 it('should reject transitions that are superseded by a new transition', done => { $state.defaultErrorHandler(function() {}); router.stateRegistry.register({ name: 'slowResolve', resolve: { foo: delay(50), }, }); const results = { success: 0, error: 0 }; const success = () => results.success++; const error = () => results.error++; $transitions.onBefore({}, trans => { trans.promise.then(success, error); }); $state.go('slowResolve'); _delay(20) .then(() => $state.go('A').transition.promise) .then(delay(50)) .then(() => expect(results).toEqual({ success: 1, error: 1 })) .then(done); }); describe('.onCreate()', function() { beforeEach(() => $state.defaultErrorHandler(() => {})); it('should pass the transition', () => { let log = ''; $transitions.onCreate({}, t => (log += `${t.from().name};${t.to().name};`)); log += 'create;'; makeTransition('first', 'second'); log += 'created;'; expect(log).toBe('create;first;second;created;'); }); it('should run in priority order', () => { let log = ''; $transitions.onCreate({}, t => ((log += '2;'), null), { priority: 2 }); $transitions.onCreate({}, t => ((log += '3;'), null), { priority: 3 }); $transitions.onCreate({}, t => ((log += '1;'), null), { priority: 1 }); log += 'create;'; makeTransition('first', 'second'); log += 'created;'; expect(log).toBe('create;3;2;1;created;'); }); it('should ignore return values', done => { $transitions.onCreate({}, t => false); $transitions.onCreate({}, t => new Promise(resolve => resolve(false))); const trans = makeTransition('first', 'second'); trans.run().then(() => { expect($state.current.name).toBe('second'); done(); }); }); it('should fail on error', () => { $transitions.onCreate({}, () => { throw 'doh'; }); expect(() => makeTransition('first', 'second')).toThrow(); }); }); describe('.onBefore()', function() { beforeEach(() => $state.defaultErrorHandler(() => {})); it('should stop running remaining hooks if hook modifies transition synchronously', done => { let counter = 0; const increment = amount => { return () => { counter += amount; return false; }; }; $transitions.onBefore({}, increment(1), { priority: 2 }); $transitions.onBefore({}, increment(100), { priority: 1 }); Promise.resolve() .then(goFail('first', 'second')) .then(() => expect(counter).toBe(1)) .then(goFail('second', 'third')) .then(() => expect(counter).toBe(2)) .then(done); }); it('should stop running remaining hooks when synchronous result throws or returns false|TargetState', done => { let current = null; $transitions.onBefore({}, t => { current = t.to().name; }); $transitions.onBefore( { to: 'first' }, () => { throw Error('first-error'); }, { priority: 1 } ); $transitions.onBefore({ to: 'second' }, () => false, { priority: 3 }); $transitions.onBefore({ to: 'third' }, () => $state.target('A'), { priority: 2 }); Promise.resolve() .then(goFail('A', 'first')) .then((res: any) => { expect(res.type).toBe(RejectType.ERROR); expect(current).toBe(null); }) .then(goFail('A', 'second')) .then((res: any) => { expect(res.type).toBe(RejectType.ABORTED); expect(current).toBe(null); }) .then(goFail('A', 'third')) .then((res: any) => { expect(res.type).toBe(RejectType.SUPERSEDED); expect(current).toBe(null); }) .then(go('A', 'B')) .then(() => expect(current).toBe('B')) .then(done); }); }); describe('.onStart()', function() { it('should fire matching events when transition starts', done => { let t = null; $transitions.onStart({ from: 'first', to: 'second' }, function($transition$) { t = $transition$; }); Promise.resolve() .then(go('first', 'third')) .then(() => expect(t).toBeNull()) .then(go('first', 'second')) .then(() => expect(t).not.toBeNull()) .then(done); }); it('should get Transition as an argument, and a null state', done => { const args = { trans: undefined, state: undefined }; $transitions.onStart({ from: '*', to: 'third' }, <any>function(trans, state) { args.trans = trans; args.state = state; }); const transition = makeTransition('', 'third'); const result = new PromiseResult(transition.promise); transition .run() .then(tick) .then(() => { expect(result.called()).toEqual({ resolve: true, reject: false, complete: true }); expect(typeof args.trans.from).toBe('function'); expect(args.state).toBeNull(); }) .then(done); }); }); describe('.onEnter()', function() { it('should get Transition and the state being entered as arguments', done => { const states = []; const args = { trans: undefined, state: undefined, third: undefined }; $transitions.onEnter({ entering: '*' }, <any>function(trans, state, third) { states.push(state); args.trans = trans; args.third = third; }); Promise.resolve() .then(go('', 'D')) .then(() => { expect(pluck(states, 'name')).toEqual(['A', 'B', 'C', 'D']); expect(typeof args.trans.from).toBe('function'); expect(args.third).toBeUndefined(); }) .then(done); }); it('should be called on only states being entered', done => { let states = []; $transitions.onEnter({ entering: '**' }, function(trans, state) { states.push(state); }); Promise.resolve() .then(go('B', 'D')) .then(() => expect(pluck(states, 'name')).toEqual(['C', 'D'])) .then(() => (states = [])) .then(go('H', 'D')) .then(() => expect(pluck(states, 'name')).toEqual(['B', 'C', 'D'])) .then(done); }); it('should be called only when from state matches and the state being enter matches to', done => { let states = [], states2 = []; $transitions.onEnter({ from: '*', entering: 'C' }, function(trans, state) { states.push(state); }); $transitions.onEnter({ from: 'B', entering: 'C' }, function(trans, state) { states2.push(state); }); Promise.resolve() .then(go('A', 'D')) .then(() => { expect(pluck(states, 'name')).toEqual(['C']); expect(pluck(states2, 'name')).toEqual([]); }) .then(() => { states = []; states2 = []; }) .then(go('B', 'D')) .then(() => { expect(pluck(states, 'name')).toEqual(['C']); expect(pluck(states2, 'name')).toEqual(['C']); }) .then(done); }); }); describe('.onExit()', function() { it('should get Transition and the state being exited as arguments', done => { const args = { trans: undefined, state: undefined, third: undefined }; const states = []; $transitions.onExit({ exiting: '**' }, <any>function(trans, state, third) { states.push(state); args.trans = trans; args.third = third; }); Promise.resolve() .then(go('D', 'H')) .then(() => { expect(pluck(states, 'name')).toEqual(['D', 'C', 'B']); expect(typeof args.trans.from).toBe('function'); expect(args.third).toBeUndefined(); }) .then(done); }); it('should be called on only states being exited', done => { let states = []; $transitions.onExit({ exiting: '*' }, function(trans, state) { states.push(state); }); Promise.resolve() .then(go('D', 'B')) .then(() => expect(pluck(states, 'name')).toEqual(['D', 'C'])) .then(() => (states = [])) .then(go('H', 'D')) .then(() => expect(pluck(states, 'name')).toEqual(['H', 'G'])) .then(done); }); it('should be called only when the to state matches and the state being exited matches the from state', done => { let states = [], states2 = []; $transitions.onExit({ exiting: 'D', to: '*' }, function(trans, state) { states.push(state); }); $transitions.onExit({ exiting: 'D', to: 'C' }, function(trans, state) { states2.push(state); }); Promise.resolve() .then(go('D', 'B')) .then(() => { expect(pluck(states, 'name')).toEqual(['D']); expect(pluck(states2, 'name')).toEqual([]); }) .then(() => { states = []; states2 = []; }) .then(go('D', 'C')) .then(() => { expect(pluck(states, 'name')).toEqual(['D']); expect(pluck(states2, 'name')).toEqual(['D']); }) .then(done); }); // test for #3081 it('should inject resolve values from the exited state', done => { router.stateRegistry.register({ name: 'design', url: '/design', resolve: { cc: () => 'cc resolve' }, onExit: (trans, state) => { expect(state).toBe(router.stateRegistry.get('design')); expect(trans.injector(null, 'from').get('cc')).toBe('cc resolve'); done(); }, }); Promise.resolve() .then(() => $state.go('design')) .then(() => $state.go('A')); }); }); describe('.onSuccess()', function() { beforeEach(() => $state.defaultErrorHandler(function() {})); it('should only be called if the transition succeeds', done => { let states = []; $transitions.onSuccess({ from: '*', to: '*' }, function(trans) { states.push(trans.to().name); }); $transitions.onEnter({ from: 'A', entering: 'C' }, function() { return false; }); Promise.resolve() .then(goFail('A', 'C')) .then(() => expect(states).toEqual([])) .then(() => (states = [])) .then(go('B', 'C')) .then(() => expect(states).toEqual(['C'])) .then(done); }); it('should call all .onSuccess() even when callbacks fail (throw errors, etc)', done => { const states = []; $transitions.onSuccess({ from: '*', to: '*' }, () => false); $transitions.onSuccess({ from: '*', to: '*' }, () => $state.target('A')); $transitions.onSuccess({ from: '*', to: '*' }, function() { throw new Error('oops!'); }); $transitions.onSuccess({ from: '*', to: '*' }, function(trans) { states.push(trans.to().name); }); Promise.resolve() .then(go('B', 'C')) .then(() => expect(states).toEqual(['C'])) .then(done); }); }); describe('.onError()', function() { it('should be called if the transition aborts.', done => { const states = []; $transitions.onEnter({ from: 'A', entering: 'C' }, function() { return false; }); $transitions.onError({}, function(trans) { states.push(trans.to().name); }); Promise.resolve() .then(goFail('A', 'D')) .then(() => expect(states).toEqual(['D'])) .then(done); }); it('should be called if any part of the transition fails.', done => { const states = []; $transitions.onEnter({ from: 'A', entering: 'C' }, function() { throw new Error('oops!'); }); $transitions.onError({}, function(trans) { states.push(trans.to().name); }); Promise.resolve() .then(goFail('A', 'D')) .then(() => expect(states).toEqual(['D'])) .then(done); }); it('should be called if an onBefore hook fails.', done => { const states = []; $transitions.onBefore({ from: 'A', entering: 'C' }, function() { throw new Error('oops!'); }); $transitions.onError({}, function(trans) { states.push(trans.to().name); }); Promise.resolve() .then(goFail('A', 'D')) .then(() => expect(states).toEqual(['D'])) .then(done); }); it('should be called for only handlers matching the transition.', done => { const hooks = []; $transitions.onEnter({ from: 'A', entering: 'C' }, function() { throw new Error('oops!'); }); $transitions.onError({ from: '*', to: '*' }, function() { hooks.push('splatsplat'); }); $transitions.onError({ from: 'A', to: 'C' }, function() { hooks.push('AC'); }); $transitions.onError({ from: 'A', to: 'D' }, function() { hooks.push('AD'); }); Promise.resolve() .then(goFail('A', 'D')) .then(() => expect(hooks).toEqual(['splatsplat', 'AD'])) .then(done); }); it('should call all error handlers when transition fails.', done => { let count = 0; $state.defaultErrorHandler(() => {}); $transitions.onStart({}, () => false); $transitions.onError({}, () => { count += 1; return false; }); $transitions.onError({}, () => { count += 10; $state.target('A'); }); $transitions.onError({}, function() { count += 100; throw new Error('oops!'); }); $transitions.onError({}, () => { count += 1000; }); Promise.resolve() .then(goFail('B', 'C')) .then(() => expect(count).toBe(1111)) .then(done); }); }); // Test for #2866 it('should have access to the failure reason in transition.error().', done => { const error = new Error('oops!'); let transError; $transitions.onEnter({ from: 'A', entering: 'C' }, function() { throw error; }); $transitions.onError({}, function(trans) { transError = trans.error(); }); Promise.resolve() .then(goFail('A', 'D')) .then(() => expect(transError.detail).toBe(error)) .then(done); }); it("return value of 'false' should reject the transition with ABORT status", done => { let states = [], rejection, transition = makeTransition('', 'D'); $transitions.onEnter({ entering: '*' }, function(trans, state) { states.push(state); }); $transitions.onEnter({ from: '*', entering: 'C' }, function() { return false; }); transition.promise.catch(function(err) { rejection = err; }); transition .run() .catch(tick) .then(() => { expect(pluck(states, 'name')).toEqual(['A', 'B', 'C']); expect(rejection.type).toEqual(RejectType.ABORTED); }) .then(done); }); it('return value of type Transition should abort the transition with SUPERSEDED status', done => { let states = [], rejection, transition = makeTransition('A', 'D'); $transitions.onEnter({ entering: '*' }, function(trans, state) { states.push(state); }); $transitions.onEnter({ from: '*', entering: 'C' }, () => $state.target('B')); transition.promise.catch(function(err) { rejection = err; }); transition .run() .catch(tick) .then(() => { expect(pluck(states, 'name')).toEqual(['B', 'C']); expect(rejection.type).toEqual(RejectType.SUPERSEDED); expect(rejection.detail.name()).toEqual('B'); expect(rejection.redirected).toEqual(true); }) .then(done); }); it('hooks which start a new transition should cause the old transition to be rejected.', done => { let current = null; function currenTransition() { return current; } let states = [], rejection, transition2, transition2success, transition = (current = makeTransition('A', 'D', { current: currenTransition })); $transitions.onEnter({ entering: '*', to: '*' }, function(trans, state) { states.push(state); }); $transitions.onEnter({ from: 'A', entering: 'C' }, function() { transition2 = current = makeTransition('A', 'G', { current: currenTransition }); // similar to using $state.go() in a controller, etc. transition2.run(); }); transition.promise.catch(function(err) { rejection = err; }); transition .run() .then(tick, tick) .then(() => { // .onEnter() from A->C should have set transition2. transition2.promise.then(function() { transition2success = true; }); }) .then(tick, tick) .then(() => { expect(pluck(states, 'name')).toEqual(['B', 'C', 'G']); expect(rejection instanceof Rejection).toBeTruthy(); expect(rejection.type).toEqual(RejectType.SUPERSEDED); expect(rejection.detail.to().name).toEqual('G'); expect(rejection.detail.from().name).toEqual('A'); expect(rejection.redirected).toBeUndefined(); expect(transition2success).toBe(true); }) .then(done); }); it('hooks which return a promise should resolve the promise before continuing', done => { const log = [], transition = makeTransition('A', 'D'); $transitions.onEnter({ from: '*', entering: '*' }, function(trans, state) { log.push('#' + state.name); return new Promise<void>(resolve => setTimeout(() => { log.push('^' + state.name); resolve(); }) ); }); transition .run() .then(tick, tick) .then(() => expect(log.join('')).toBe('#B^B#C^C#D^D')) .then(done); }); it('hooks which return a promise should resolve the promise before continuing', done => { const log = [], transition = makeTransition('A', 'D'); const $q = services.$q; const defers = { B: $q.defer(), C: $q.defer(), D: $q.defer() }; function resolveDeferredFor(name) { log.push('^' + name); defers[name].resolve('ok, go ahead!'); return tick(); } $transitions.onEnter({ entering: '**' }, function waitWhileEnteringState(trans, state) { log.push('#' + state.name); return defers[state.name].promise; }); transition.promise.then(function() { log.push('DONE'); }); transition.run(); tick() .then(() => expect(log.join(';')).toBe('#B')) .then(() => resolveDeferredFor('B')) .then(() => expect(log.join(';')).toBe('#B;^B;#C')) .then(() => resolveDeferredFor('C')) .then(() => expect(log.join(';')).toBe('#B;^B;#C;^C;#D')) .then(() => resolveDeferredFor('D')) .then(() => expect(log.join(';')).toBe('#B;^B;#C;^C;#D;^D;DONE')) .then(done, done); }); it('hooks can add resolves to a $transition$ and they will be available to be injected in nested states', done => { const log = [], transition = makeTransition('A', 'D'); const $q = services.$q; const defer = $q.defer(); $transitions.onEnter( { entering: '**' }, function logEnter(trans, state) { log.push('Entered#' + state.name); }, { priority: -1 } ); $transitions.onEnter({ entering: 'B' }, function addResolves($transition$: Transition) { log.push('adding resolve'); const resolveFn = function() { log.push('resolving'); return defer.promise; }; $transition$.addResolvable(new Resolvable('newResolve', resolveFn)); }); $transitions.onEnter({ entering: 'C' }, function useTheNewResolve(trans) { log.push(trans.injector().get('newResolve')); }); transition.promise.then(function() { log.push('DONE!'); }); transition.run(); tick() .then(() => expect(log.join(';')).toBe('adding resolve;Entered#B;resolving')) .then(() => defer.resolve('resolvedval')) .then(tick, tick) .then(() => expect(log.join(';')).toBe('adding resolve;Entered#B;resolving;resolvedval;Entered#C;Entered#D;DONE!') ) .then(done, done); }); // test for https://github.com/angular-ui/ui-router/issues/3544 it('hooks can add resolves to a $transition$ and they will be available in onSuccess', done => { const log = [], transition = makeTransition('A', 'B'); const $q = services.$q; const defer = $q.defer(); $transitions.onEnter( { entering: '**' }, function logEnter(trans, state) { log.push('Entered#' + state.name); }, { priority: -1 } ); $transitions.onEnter({ entering: 'B' }, function addResolves($transition$: Transition) { log.push('adding resolve'); const resolveFn = function() { log.push('resolving'); return defer.promise; }; $transition$.addResolvable(new Resolvable('newResolve', resolveFn)); }); $transitions.onSuccess({}, function useTheNewResolve(trans) { log.push('SUCCESS!'); log.push(trans.injector().get('newResolve')); }); transition.promise.then(function() { log.push('DONE!'); }); transition.run(); tick() .then(() => expect(log.join(';')).toBe('adding resolve;Entered#B;resolving')) .then(() => defer.resolve('resolvedval')) .then(tick, tick) .then(() => expect(log.join(';')).toBe('adding resolve;Entered#B;resolving;SUCCESS!;resolvedval;DONE!')) .then(done, done); }); // Test for https://github.com/ui-router/core/issues/32 it('should match "" (empty string) to root state only', async done => { const beforeLog = [], successLog = []; router.transitionService.onBefore({ from: '', to: '**' }, trans => { beforeLog.push(trans.from().name); }); router.transitionService.onSuccess({ from: '', to: '**' }, trans => { successLog.push(trans.from().name); }); await $state.go('A'); expect(beforeLog).toEqual(successLog); expect(beforeLog.length).toBe(1); expect(beforeLog[0]).toBe(''); await $state.go('B'); expect(beforeLog).toEqual(successLog); expect(beforeLog.length).toBe(1); expect(beforeLog[0]).toBe(''); done(); }); it('should be invoked only once if invokeLimit is 1', done => { let count = 0; $transitions.onStart( {}, function() { count++; }, { invokeLimit: 1 } ); Promise.resolve() .then(() => expect(count).toBe(0)) .then(go('A', 'D')) .then(() => expect(count).toBe(1)) .then(go('D', 'A')) .then(() => expect(count).toBe(1)) .then(go('A', 'D')) .then(() => expect(count).toBe(1)) .then(done); }); it('should be invoked only twice if invokeLimit is 2', done => { let count = 0; $transitions.onStart( {}, () => { count++; }, { invokeLimit: 2 } ); Promise.resolve() .then(() => expect(count).toBe(0)) .then(go('A', 'D')) .then(() => expect(count).toBe(1)) .then(go('D', 'A')) .then(() => expect(count).toBe(2)) .then(go('A', 'D')) .then(() => expect(count).toBe(2)) .then(done); }); }); describe('redirected transition', () => { let urlRedirect, requiresAuth; beforeEach(() => { urlRedirect = router.stateRegistry.register({ name: 'urlRedirect', url: '/urlRedirect', redirectTo: 'redirectTarget', }); requiresAuth = router.stateRegistry.register({ name: 'requiresAuth', url: '/requiresAuth' }); router.stateRegistry.register({ name: 'redirectTarget', url: '/redirectTarget' }); }); it('should not replace the current url when redirecting a state.go transition', async done => { const spy = spyOn(router.urlService, 'url').and.callThrough(); await $state.go('urlRedirect'); expect(router.urlService.path()).toBe('/redirectTarget'); expect(spy).toHaveBeenCalledWith('/redirectTarget', false); done(); }); it('should replace the current url when redirecting a url sync', done => { const url = spyOn(router.urlService, 'url').and.callThrough(); const transitionTo = spyOn(router.stateService, 'transitionTo').and.callThrough(); router.transitionService.onSuccess({}, () => { expect(transitionTo).toHaveBeenCalledWith(urlRedirect, {}, { inherit: true, source: 'url' }); expect(router.stateService.current.name).toBe('redirectTarget'); expect(router.urlService.path()).toBe('/redirectTarget'); expect(url.calls.count()).toEqual(2); expect(url.calls.argsFor(0)).toEqual(['/urlRedirect']); expect(url.calls.argsFor(1)).toEqual(['/redirectTarget', true]); done(); }); router.urlService.url('/urlRedirect'); }); it('should replace the current url when redirecting a url sync transition, even if the redirect is ignored', async done => { router.stateRegistry.register({ name: 'queryparam', url: '/?param', }); await router.stateService.go('queryparam', { param: undefined }); expect(router.globals.params.param).toEqual(undefined); router.transitionService.onStart({}, trans => { // redirect transition removing ?param=foo if (trans.params().param === 'foo') { return trans.targetState().withParams({ param: undefined }); } }); router.urlService.url('/?param=foo'); const url = spyOn(router.locationService, 'url').and.callThrough(); const update = spyOn(router.urlRouter, 'update').and.callThrough(); router.transitionService.onError({}, trans => { if (trans.error().type === RejectType.IGNORED) { setTimeout(() => { expect(update.calls.count()).toBe(1); expect(url.calls.count()).toBe(2); expect(url.calls.argsFor(0)).toEqual([]); expect(url.calls.argsFor(1)).toEqual(['/', true]); expect(router.urlService.url()).toBe('/'); expect(router.globals.params.param).toEqual(undefined); done(); }); } }); }); it('should not replace the current url when redirecting a url sync with { location: false }', done => { router.transitionService.onBefore({ to: 'requiresAuth' }, trans => { return router.stateService.target('redirectTarget', null, { location: false }); }); const url = spyOn(router.urlService, 'url').and.callThrough(); const transitionTo = spyOn(router.stateService, 'transitionTo').and.callThrough(); router.transitionService.onSuccess({}, () => { expect(transitionTo).toHaveBeenCalledWith(requiresAuth, {}, { inherit: true, source: 'url' }); expect(router.globals.current.name).toBe('redirectTarget'); expect(router.urlService.path()).toBe('/requiresAuth'); expect(url.calls.count()).toEqual(1); expect(url.calls.argsFor(0)).toEqual(['/requiresAuth']); done(); }); router.urlService.url('/requiresAuth'); }); }); }); describe('Transition() instance', function() { describe('.entering', function() { it('should return the path elements being entered', () => { let t = makeTransition('', 'A'); expect(pluck(t.entering(), 'name')).toEqual(['A']); t = makeTransition('', 'D'); expect(pluck(t.entering(), 'name')).toEqual(['A', 'B', 'C', 'D']); }); it('should not include already entered elements', () => { const t = makeTransition('B', 'D'); expect(pluck(t.entering(), 'name')).toEqual(['C', 'D']); }); }); describe('.exiting', function() { it('should return the path elements being exited', () => { let t = makeTransition('D', 'C'); expect(pluck(t.exiting(), 'name')).toEqual(['D']); t = makeTransition('D', 'A'); expect(pluck(t.exiting(), 'name')).toEqual(['D', 'C', 'B']); }); }); describe('.is', function() { it('should match globs', () => { const t = makeTransition('', 'first'); expect(t.is({ to: 'first' })).toBe(true); expect(t.is({ from: '' })).toBe(true); expect(t.is({ to: 'first', from: '' })).toBe(true); expect(t.is({ to: ['first', 'second'] })).toBe(true); expect(t.is({ to: ['first', 'second'], from: ['', 'third'] })).toBe(true); expect(t.is({ to: 'first', from: '**' })).toBe(true); expect(t.is({ to: 'second' })).toBe(false); expect(t.is({ from: 'first' })).toBe(false); expect(t.is({ to: 'first', from: 'second' })).toBe(false); expect(t.is({ to: ['', 'third'] })).toBe(false); expect(t.is({ to: '**', from: 'first' })).toBe(false); }); it('should match using functions', () => { const t = makeTransition('', 'first'); expect( t.is({ to: function(state) { return state.name === 'first'; }, }) ).toBe(true); expect( t.is({ from: function(state) { return state.name === ''; }, }) ).toBe(true); expect( t.is({ to: function(state) { return state.name === 'first'; }, from: function(state) { return state.name === ''; }, }) ).toBe(true); expect( t.is({ to: function(state) { return state.name === 'first'; }, from: '**', }) ).toBe(true); expect( t.is({ to: function(state) { return state.name === 'second'; }, }) ).toBe(false); expect( t.is({ from: function(state) { return state.name === 'first'; }, }) ).toBe(false); expect( t.is({ to: function(state) { return state.name === 'first'; }, from: function(state) { return state.name === 'second'; }, }) ).toBe(false); // expect(t.is({ to: ["", "third"] })).toBe(false); // expect(t.is({ to: "**", from: "first" })).toBe(false); }); }); }); describe('inherited params', () => { it('should inherit params when trans options `inherit: true`', async done => { router.stateRegistry.register({ name: 'foo', url: '/:path?query1&query2' }); await $state.go('foo', { path: 'abc', query1: 'def', query2: 'ghi' }); expect(router.globals.params).toEqualValues({ path: 'abc', query1: 'def', query2: 'ghi' }); await $state.go('foo', { query2: 'jkl' }); expect(router.globals.params).toEqualValues({ path: 'abc', query1: 'def', query2: 'jkl' }); done(); }); it('should not inherit params when param declaration has inherit: false', async done => { router.stateRegistry.register({ name: 'foo', url: '/:path?query1&query2', params: { query1: { inherit: false, value: null }, }, }); await $state.go('foo', { path: 'abc', query1: 'def', query2: 'ghi' }); expect(router.globals.params).toEqualValues({ path: 'abc', query1: 'def', query2: 'ghi' }); await $state.go('foo', { query2: 'jkl' }); expect(router.globals.params).toEqualValues({ path: 'abc', query1: null, query2: 'jkl' }); done(); }); it('should not inherit previous params when new params are passed', async done => { router.stateRegistry.register({ name: 'foo', url: '?fooParam', }); await $state.go('foo', { fooParam: 'abc' }); expect(router.globals.params).toEqualValues({ fooParam: 'abc' }); await $state.go('foo', { fooParam: undefined }); expect(router.globals.params).toEqualValues({ fooParam: undefined }); done(); }); it('should not inherit params whose type has inherit: false', async done => { router.urlService.config.type('inherit', { inherit: true, encode: x => x, decode: x => x, is: () => true, equals: equals, pattern: /.*/, raw: false, }); router.urlService.config.type('noinherit', { inherit: false, encode: x => x, decode: x => x, is: () => true, equals: equals, pattern: /.*/, raw: false, }); router.stateRegistry.register({ name: 'foo', url: '/?{query1:inherit}&{query2:noinherit}', }); await $state.go('foo', { query1: 'abc', query2: 'def' }); expect(router.globals.params).toEqualValues({ query1: 'abc', query2: 'def' }); await $state.go('foo'); expect(router.globals.params).toEqualValues({ query1: 'abc', query2: undefined }); done(); }); it('should not inherit the "hash" param value', async done => { router.stateRegistry.register({ name: 'hash', url: '/hash' }); router.stateRegistry.register({ name: 'other', url: '/other' }); await $state.go('hash', { '#': 'abc' }); expect(router.globals.params).toEqualValues({ '#': 'abc' }); expect(router.urlService.hash()).toBe('abc'); await $state.go('hash'); expect(router.globals.params).toEqualValues({ '#': null }); expect(router.urlService.hash()).toBe(''); await $state.go('other', { '#': 'def' }); expect(router.globals.params).toEqualValues({ '#': 'def' }); expect(router.urlService.hash()).toBe('def'); await $state.go('hash'); expect(router.globals.params).toEqualValues({ '#': null }); expect(router.urlService.hash()).toBe(''); done(); }); }); describe('paramsChanged()', () => { beforeEach(() => { router.stateRegistry.register({ name: 'stateA', url: '/stateA/:param1/:param2' }); router.stateRegistry.register({ name: 'stateB', url: '/stateB/:param3' }); router.stateRegistry.register({ name: 'stateB.nest', url: '/nest/:param4' }); }); it('should contain only changed param values', async done => { await $state.go('stateA', { param1: 'abc', param2: 'def' }); const goPromise = $state.go('stateA', { param1: 'abc', param2: 'xyz' }); await goPromise; const changed = goPromise.transition.paramsChanged(); expect(Object.keys(changed)).toEqual(['param2']); expect(changed).toEqual({ param2: 'xyz' }); done(); }); it('should contain new params values when switching states', async done => { await $state.go('stateB', { param3: '123' }); const goPromise = $state.go('stateB.nest', { param3: '123', param4: '456' }); await goPromise; const changed = goPromise.transition.paramsChanged(); expect(Object.keys(changed)).toEqual(['param4']); expect(changed).toEqual({ param4: '456' }); done(); }); it('should contain removed params with `undefined` when switching states', async done => { await $state.go('stateB.nest', { param3: '123', param4: '456' }); const goPromise = $state.go('stateB'); await goPromise; const changed = goPromise.transition.paramsChanged(); expect(Object.keys(changed)).toEqual(['param4']); expect(changed).toEqual({ param4: undefined }); done(); }); it('should contain removed params with `undefined` when switching states', async done => { await $state.go('stateB.nest', { param3: '123', param4: '456' }); const goPromise = $state.go('stateB'); await goPromise; const changed = goPromise.transition.paramsChanged(); expect(Object.keys(changed)).toEqual(['param4']); expect(changed).toEqual({ param4: undefined }); done(); }); it('should contain added and removed params', async done => { await $state.go('stateB.nest', { param3: '123', param4: '456' }); const goPromise = $state.go('stateA', { param1: 'abc', param2: 'def' }); await goPromise; const changed = goPromise.transition.paramsChanged(); expect(Object.keys(changed).sort()).toEqual(['param1', 'param2', 'param3', 'param4']); expect(changed).toEqual({ param1: 'abc', param2: 'def', param3: undefined, param4: undefined }); done(); }); }); describe('from previous transitions', () => { it('should get their Transition resolves cleaned up', async done => { router.stateRegistry.register({ name: 'resolve', resolve: { foo: () => 'Some data' } }); const trans = router.stateService.go('resolve').transition; await trans.promise; expect(trans.injector().get(Transition)).toBe(trans); expect(trans.injector().get('foo')).toBe('Some data'); await router.stateService.go('A'); expect(trans.injector().get(Transition)).toBe(null); expect(trans.injector().get('foo')).toBe('Some data'); done(); }); }); });
the_stack
import { BufferScanResult, BufferStoppedChangingEvent, ContextualBufferScanResult, Cursor, CursorPositionChangedEvent, Decoration, DecorationLayerOptions, DecorationOptions, DisplayMarker, DisplayMarkerLayer, Disposable, EditorChangedEvent, FindDisplayMarkerOptions, Grammar, Gutter, GutterOptions, LayerDecoration, MarkerLayer, Point, PointCompatible, Range, RangeCompatible, RangeLike, ReadonlyEditOptions, ScanContextOptions, ScopeDescriptor, Selection, SelectionChangedEvent, TextBuffer, TextEditOptions, TextInsertionOptions, } from '../index'; /** * This class represents all essential editing state for a single TextBuffer, * including cursor and selection positions, folds, and soft wraps. */ export class TextEditor { readonly id: number; // NOTE: undocumented within the public API. Don't go down the rabbit hole. constructor(options?: object); // Event Subscription /** Calls your callback when the buffer's title has changed. */ onDidChangeTitle(callback: (title: string) => void): Disposable; /** Calls your callback when the buffer's path, and therefore title, has changed. */ onDidChangePath(callback: (path: string) => void): Disposable; /** * Invoke the given callback synchronously when the content of the buffer * changes. */ onDidChange(callback: (event: EditorChangedEvent[]) => void): Disposable; /** * Invoke callback when the buffer's contents change. It is emit * asynchronously 300ms after the last buffer change. This is a good place * to handle changes to the buffer without compromising typing performance. */ onDidStopChanging(callback: (event: BufferStoppedChangingEvent) => void): Disposable; /** * Calls your callback when a Cursor is moved. If there are multiple cursors, * your callback will be called for each cursor. */ onDidChangeCursorPosition(callback: (event: CursorPositionChangedEvent) => void): Disposable; /** Calls your callback when a selection's screen range changes. */ onDidChangeSelectionRange(callback: (event: SelectionChangedEvent) => void): Disposable; /** Invoke the given callback after the buffer is saved to disk. */ onDidSave(callback: (event: { path: string }) => void): Disposable; /** Invoke the given callback when the editor is destroyed. */ onDidDestroy(callback: () => void): Disposable; /** Retrieves the current TextBuffer. */ getBuffer(): TextBuffer; /** Sets the read-only state for the editor. */ setReadOnly(readonly: boolean): void; /** Whether or not this editor is in read-only mode. */ isReadOnly(): boolean; /** * Calls your callback when a Gutter is added to the editor. Immediately calls * your callback for each existing gutter. */ observeGutters(callback: (gutter: Gutter) => void): Disposable; /** Calls your callback when a Gutter is added to the editor. */ onDidAddGutter(callback: (gutter: Gutter) => void): Disposable; /** Calls your callback when a Gutter is removed from the editor. */ onDidRemoveGutter(callback: (name: string) => void): Disposable; /** Calls your callback when soft wrap was enabled or disabled. */ onDidChangeSoftWrapped(callback: (softWrapped: boolean) => void): Disposable; /** Calls your callback when the buffer's encoding has changed. */ onDidChangeEncoding(callback: (encoding: string) => void): Disposable; /** * Calls your callback when the grammar that interprets and colorizes the text * has been changed. Immediately calls your callback with the current grammar. */ observeGrammar(callback: (grammar: Grammar) => void): Disposable; /** * Calls your callback when the grammar that interprets and colorizes the text * has been changed. */ onDidChangeGrammar(callback: (grammar: Grammar) => void): Disposable; /** Calls your callback when the result of ::isModified changes. */ onDidChangeModified(callback: (modified: boolean) => void): Disposable; /** * Calls your callback when the buffer's underlying file changes on disk at a * moment when the result of ::isModified is true. */ onDidConflict(callback: () => void): Disposable; /** Calls your callback before text has been inserted. */ onWillInsertText(callback: (event: { text: string; cancel(): void }) => void): Disposable; /** Calls your callback after text has been inserted. */ onDidInsertText(callback: (event: { text: string }) => void): Disposable; /** * Calls your callback when a Cursor is added to the editor. Immediately calls * your callback for each existing cursor. */ observeCursors(callback: (cursor: Cursor) => void): Disposable; /** Calls your callback when a Cursor is added to the editor. */ onDidAddCursor(callback: (cursor: Cursor) => void): Disposable; /** Calls your callback when a Cursor is removed from the editor. */ onDidRemoveCursor(callback: (cursor: Cursor) => void): Disposable; /** * Calls your callback when a Selection is added to the editor. Immediately * calls your callback for each existing selection. */ observeSelections(callback: (selection: Selection) => void): Disposable; /** Calls your callback when a Selection is added to the editor. */ onDidAddSelection(callback: (selection: Selection) => void): Disposable; /** Calls your callback when a Selection is removed from the editor. */ onDidRemoveSelection(callback: (selection: Selection) => void): Disposable; /** * Calls your callback with each Decoration added to the editor. Calls your * callback immediately for any existing decorations. */ observeDecorations(callback: (decoration: Decoration) => void): Disposable; /** Calls your callback when a Decoration is added to the editor. */ onDidAddDecoration(callback: (decoration: Decoration) => void): Disposable; /** Calls your callback when a Decoration is removed from the editor. */ onDidRemoveDecoration(callback: (decoration: Decoration) => void): Disposable; /** Calls your callback when the placeholder text is changed. */ onDidChangePlaceholderText(callback: (placeholderText: string) => void): Disposable; // File Details /** * Get the editor's title for display in other parts of the UI such as the tabs. * If the editor's buffer is saved, its title is the file name. If it is unsaved, * its title is "untitled". */ getTitle(): string; /** * Get unique title for display in other parts of the UI, such as the window title. * If the editor's buffer is unsaved, its title is "untitled" If the editor's * buffer is saved, its unique title is formatted as one of the following, * * "" when it is the only editing buffer with this file name. * " — " when other buffers have this file name. */ getLongTitle(): string; /** Returns the string path of this editor's text buffer. */ getPath(): string | undefined; /** Returns boolean true if this editor has been modified. */ isModified(): boolean; /** Returns boolean true if this editor has no content. */ isEmpty(): boolean; /** Returns the string character set encoding of this editor's text buffer. */ getEncoding(): string; /** Set the character set encoding to use in this editor's text buffer. */ setEncoding(encoding: string): void; // File Operations /** * Saves the editor's text buffer. * See TextBuffer::save for more details. */ save(): Promise<void>; /** * Saves the editor's text buffer as the given path. * See TextBuffer::saveAs for more details. */ saveAs(filePath: string): Promise<void>; // Reading Text /** Returns a string representing the entire contents of the editor. */ getText(): string; /** Get the text in the given range in buffer coordinates. */ getTextInBufferRange(range: RangeCompatible): string; /** Returns a number representing the number of lines in the buffer. */ getLineCount(): number; /** * Returns a number representing the number of screen lines in the editor. * This accounts for folds. */ getScreenLineCount(): number; /** * Returns a number representing the last zero-indexed buffer row number of * the editor. */ getLastBufferRow(): number; /** * Returns a number representing the last zero-indexed screen row number of * the editor. */ getLastScreenRow(): number; /** * Returns a string representing the contents of the line at the given * buffer row. */ lineTextForBufferRow(bufferRow: number): string; /** * Returns a string representing the contents of the line at the given * screen row. */ lineTextForScreenRow(screenRow: number): string; /** Get the range of the paragraph surrounding the most recently added cursor. */ getCurrentParagraphBufferRange(): Range; // Mutating Text /** Replaces the entire contents of the buffer with the given string. */ setText(text: string, options?: ReadonlyEditOptions): void; /** Set the text in the given Range in buffer coordinates. */ setTextInBufferRange(range: RangeCompatible, text: string, options?: TextEditOptions & ReadonlyEditOptions): Range; /* For each selection, replace the selected text with the given text. */ insertText(text: string, options?: TextInsertionOptions & ReadonlyEditOptions): Range | false; /** For each selection, replace the selected text with a newline. */ insertNewline(options?: ReadonlyEditOptions): void; /** * For each selection, if the selection is empty, delete the character following * the cursor. Otherwise delete the selected text. */ delete(options?: ReadonlyEditOptions): void; /** * For each selection, if the selection is empty, delete the character preceding * the cursor. Otherwise delete the selected text. */ backspace(options?: ReadonlyEditOptions): void; /** * Mutate the text of all the selections in a single transaction. * All the changes made inside the given function can be reverted with a single * call to ::undo. */ mutateSelectedText(fn: (selection: Selection, index: number) => void): void; /** * For each selection, transpose the selected text. * If the selection is empty, the characters preceding and following the cursor * are swapped. Otherwise, the selected characters are reversed. */ transpose(options?: ReadonlyEditOptions): void; /** * Convert the selected text to upper case. * For each selection, if the selection is empty, converts the containing word * to upper case. Otherwise convert the selected text to upper case. */ upperCase(options?: ReadonlyEditOptions): void; /** * Convert the selected text to lower case. * For each selection, if the selection is empty, converts the containing word * to upper case. Otherwise convert the selected text to upper case. */ lowerCase(options?: ReadonlyEditOptions): void; /** * Toggle line comments for rows intersecting selections. * If the current grammar doesn't support comments, does nothing. */ toggleLineCommentsInSelection(options?: ReadonlyEditOptions): void; /** For each cursor, insert a newline at beginning the following line. */ insertNewlineBelow(options?: ReadonlyEditOptions): void; /** For each cursor, insert a newline at the end of the preceding line. */ insertNewlineAbove(options?: ReadonlyEditOptions): void; /** * For each selection, if the selection is empty, delete all characters of the * containing word that precede the cursor. Otherwise delete the selected text. */ deleteToBeginningOfWord(options?: ReadonlyEditOptions): void; /** * Similar to ::deleteToBeginningOfWord, but deletes only back to the previous * word boundary. */ deleteToPreviousWordBoundary(options?: ReadonlyEditOptions): void; /** Similar to ::deleteToEndOfWord, but deletes only up to the next word boundary. */ deleteToNextWordBoundary(options?: ReadonlyEditOptions): void; /** * For each selection, if the selection is empty, delete all characters of the * containing subword following the cursor. Otherwise delete the selected text. */ deleteToBeginningOfSubword(options?: ReadonlyEditOptions): void; /** * For each selection, if the selection is empty, delete all characters of the * containing subword following the cursor. Otherwise delete the selected text. */ deleteToEndOfSubword(options?: ReadonlyEditOptions): void; /** * For each selection, if the selection is empty, delete all characters of the * containing line that precede the cursor. Otherwise delete the selected text. */ deleteToBeginningOfLine(options?: ReadonlyEditOptions): void; /** * For each selection, if the selection is not empty, deletes the selection * otherwise, deletes all characters of the containing line following the cursor. * If the cursor is already at the end of the line, deletes the following newline. */ deleteToEndOfLine(options?: ReadonlyEditOptions): void; /** * For each selection, if the selection is empty, delete all characters of the * containing word following the cursor. Otherwise delete the selected text. */ deleteToEndOfWord(options?: ReadonlyEditOptions): void; /** Delete all lines intersecting selections. */ deleteLine(options?: ReadonlyEditOptions): void; // History /** Undo the last change. */ undo(options?: ReadonlyEditOptions): void; /** Redo the last change. */ redo(options?: ReadonlyEditOptions): void; /** * Batch multiple operations as a single undo/redo step. * Any group of operations that are logically grouped from the perspective of undoing * and redoing should be performed in a transaction. If you want to abort the transaction, * call ::abortTransaction to terminate the function's execution and revert any changes * performed up to the abortion. */ transact(fn: () => void): void; /** * Batch multiple operations as a single undo/redo step. * Any group of operations that are logically grouped from the perspective of undoing * and redoing should be performed in a transaction. If you want to abort the transaction, * call ::abortTransaction to terminate the function's execution and revert any changes * performed up to the abortion. */ transact(groupingInterval: number, fn: () => void): void; /** * Abort an open transaction, undoing any operations performed so far within the * transaction. */ abortTransaction(): void; /** * Create a pointer to the current state of the buffer for use with ::revertToCheckpoint * and ::groupChangesSinceCheckpoint. */ createCheckpoint(): number; /** * Revert the buffer to the state it was in when the given checkpoint was created. * The redo stack will be empty following this operation, so changes since the checkpoint * will be lost. If the given checkpoint is no longer present in the undo history, no * changes will be made to the buffer and this method will return false. */ revertToCheckpoint(checkpoint: number): boolean; /** * Group all changes since the given checkpoint into a single transaction for purposes * of undo/redo. * If the given checkpoint is no longer present in the undo history, no grouping will be * performed and this method will return false. */ groupChangesSinceCheckpoint(checkpoint: number): boolean; // TextEditor Coordinates /** Convert a position in buffer-coordinates to screen-coordinates. */ screenPositionForBufferPosition( bufferPosition: PointCompatible, options?: { clipDirection?: 'backward' | 'forward' | 'closest' | undefined }, ): Point; /** Convert a position in screen-coordinates to buffer-coordinates. */ bufferPositionForScreenPosition( bufferPosition: PointCompatible, options?: { clipDirection?: 'backward' | 'forward' | 'closest' | undefined }, ): Point; /** Convert a range in buffer-coordinates to screen-coordinates. */ screenRangeForBufferRange(bufferRange: RangeCompatible): Range; /** Convert a range in screen-coordinates to buffer-coordinates. */ bufferRangeForScreenRange(screenRange: RangeCompatible): Range; /** Clip the given Point to a valid position in the buffer. */ clipBufferPosition(bufferPosition: PointCompatible): Point; /** * Clip the start and end of the given range to valid positions in the buffer. * See ::clipBufferPosition for more information. */ clipBufferRange(range: RangeCompatible): Range; /** Clip the given Point to a valid position on screen. */ clipScreenPosition( screenPosition: PointCompatible, options?: { clipDirection?: 'backward' | 'forward' | 'closest' | undefined }, ): Point; /** * Clip the start and end of the given range to valid positions on screen. * See ::clipScreenPosition for more information. */ clipScreenRange(range: RangeCompatible, options?: { clipDirection?: 'backward' | 'forward' | 'closest' | undefined }): Range; // Decorations /** * Add a decoration that tracks a DisplayMarker. When the marker moves, is * invalidated, or is destroyed, the decoration will be updated to reflect * the marker's state. */ decorateMarker(marker: DisplayMarker, decorationParams: DecorationOptions): Decoration; /** * Add a decoration to every marker in the given marker layer. Can be used to * decorate a large number of markers without having to create and manage many * individual decorations. */ decorateMarkerLayer( markerLayer: MarkerLayer | DisplayMarkerLayer, decorationParams: DecorationLayerOptions, ): LayerDecoration; /** Get all decorations. */ getDecorations(propertyFilter?: DecorationOptions): Decoration[]; /** Get all decorations of type 'line'. */ getLineDecorations(propertyFilter?: DecorationOptions): Decoration[]; /** Get all decorations of type 'line-number'. */ getLineNumberDecorations(propertyFilter?: DecorationOptions): Decoration[]; /** Get all decorations of type 'highlight'. */ getHighlightDecorations(propertyFilter?: DecorationOptions): Decoration[]; /** Get all decorations of type 'overlay'. */ getOverlayDecorations(propertyFilter?: DecorationOptions): Decoration[]; // Markers /** * Create a marker on the default marker layer with the given range in buffer coordinates. * This marker will maintain its logical location as the buffer is changed, so if you mark * a particular word, the marker will remain over that word even if the word's location * in the buffer changes. */ markBufferRange( range: RangeCompatible, properties?: { maintainHistory?: boolean | undefined; reversed?: boolean | undefined; invalidate?: 'never' | 'surround' | 'overlap' | 'inside' | 'touch' | undefined; }, ): DisplayMarker; /** * Create a marker on the default marker layer with the given range in screen coordinates. * This marker will maintain its logical location as the buffer is changed, so if you mark * a particular word, the marker will remain over that word even if the word's location in * the buffer changes. */ markScreenRange( range: RangeCompatible, properties?: { maintainHistory?: boolean | undefined; reversed?: boolean | undefined; invalidate?: 'never' | 'surround' | 'overlap' | 'inside' | 'touch' | undefined; }, ): DisplayMarker; /** * Create a marker on the default marker layer with the given buffer position and no tail. * To group multiple markers together in their own private layer, see ::addMarkerLayer. */ markBufferPosition( bufferPosition: PointCompatible, options?: { invalidate?: 'never' | 'surround' | 'overlap' | 'inside' | 'touch' | undefined; }, ): DisplayMarker; /** * Create a marker on the default marker layer with the given screen position and no tail. * To group multiple markers together in their own private layer, see ::addMarkerLayer. */ markScreenPosition( screenPosition: PointCompatible, options?: { invalidate?: 'never' | 'surround' | 'overlap' | 'inside' | 'touch' | undefined; clipDirection?: 'backward' | 'forward' | 'closest' | undefined; }, ): DisplayMarker; /** * Find all DisplayMarkers on the default marker layer that match the given properties. * * This method finds markers based on the given properties. Markers can be associated * with custom properties that will be compared with basic equality. In addition, there * are several special properties that will be compared with the range of the markers * rather than their properties. */ findMarkers(properties: FindDisplayMarkerOptions): DisplayMarker[]; /** Create a marker layer to group related markers. */ addMarkerLayer(options?: { maintainHistory?: boolean | undefined; persistent?: boolean | undefined }): DisplayMarkerLayer; /** Get a DisplayMarkerLayer by id. */ getMarkerLayer(id: number): DisplayMarkerLayer | undefined; /** * Get the default DisplayMarkerLayer. * All marker APIs not tied to an explicit layer interact with this default layer. */ getDefaultMarkerLayer(): DisplayMarkerLayer; /** Get the DisplayMarker on the default layer for the given marker id. */ getMarker(id: number): DisplayMarker; /** Get all DisplayMarkers on the default marker layer. Consider using ::findMarkers. */ getMarkers(): DisplayMarker[]; /** Get the number of markers in the default marker layer. */ getMarkerCount(): number; // Cursors /** Get the position of the most recently added cursor in buffer coordinates. */ getCursorBufferPosition(): Point; /** Get the position of all the cursor positions in buffer coordinates. */ getCursorBufferPositions(): Point[]; /** * Move the cursor to the given position in buffer coordinates. * If there are multiple cursors, they will be consolidated to a single cursor. */ setCursorBufferPosition(position: PointCompatible, options?: { autoscroll?: boolean | undefined }): void; /** Get a Cursor at given screen coordinates Point. */ getCursorAtScreenPosition(position: PointCompatible): Cursor | undefined; /** Get the position of the most recently added cursor in screen coordinates. */ getCursorScreenPosition(): Point; /** Get the position of all the cursor positions in screen coordinates. */ getCursorScreenPositions(): Point[]; /** * Move the cursor to the given position in screen coordinates. * If there are multiple cursors, they will be consolidated to a single cursor. */ setCursorScreenPosition(position: PointCompatible, options?: { autoscroll?: boolean | undefined }): void; /** Add a cursor at the given position in buffer coordinates. */ addCursorAtBufferPosition(bufferPosition: PointCompatible, options?: { autoscroll?: boolean | undefined }): Cursor; /** Add a cursor at the position in screen coordinates. */ addCursorAtScreenPosition(screenPosition: PointCompatible): Cursor; /** Returns a boolean indicating whether or not there are multiple cursors. */ hasMultipleCursors(): boolean; /** Move every cursor up one row in screen coordinates. */ moveUp(lineCount?: number): void; /** Move every cursor down one row in screen coordinates. */ moveDown(lineCount?: number): void; /** Move every cursor left one column. */ moveLeft(columnCount?: number): void; /** Move every cursor right one column. */ moveRight(columnCount?: number): void; /** Move every cursor to the beginning of its line in buffer coordinates. */ moveToBeginningOfLine(): void; /** Move every cursor to the beginning of its line in screen coordinates. */ moveToBeginningOfScreenLine(): void; /** Move every cursor to the first non-whitespace character of its line. */ moveToFirstCharacterOfLine(): void; /** Move every cursor to the end of its line in buffer coordinates. */ moveToEndOfLine(): void; /** Move every cursor to the end of its line in screen coordinates. */ moveToEndOfScreenLine(): void; /** Move every cursor to the beginning of its surrounding word. */ moveToBeginningOfWord(): void; /** Move every cursor to the end of its surrounding word. */ moveToEndOfWord(): void; /** * Move every cursor to the top of the buffer. * If there are multiple cursors, they will be merged into a single cursor. */ moveToTop(): void; /** * Move every cursor to the bottom of the buffer. * If there are multiple cursors, they will be merged into a single cursor. */ moveToBottom(): void; /** Move every cursor to the beginning of the next word. */ moveToBeginningOfNextWord(): void; /** Move every cursor to the previous word boundary. */ moveToPreviousWordBoundary(): void; /** Move every cursor to the next word boundary. */ moveToNextWordBoundary(): void; /** Move every cursor to the previous subword boundary. */ moveToPreviousSubwordBoundary(): void; /** Move every cursor to the next subword boundary. */ moveToNextSubwordBoundary(): void; /** Move every cursor to the beginning of the next paragraph. */ moveToBeginningOfNextParagraph(): void; /** Move every cursor to the beginning of the previous paragraph. */ moveToBeginningOfPreviousParagraph(): void; /** Returns the most recently added Cursor. */ getLastCursor(): Cursor; /** Returns the word surrounding the most recently added cursor. */ getWordUnderCursor(options?: { wordRegex?: RegExp | undefined; includeNonWordCharacters?: boolean | undefined; allowPrevious?: boolean | undefined; }): string; /** Get an Array of all Cursors. */ getCursors(): Cursor[]; /** * Get all Cursors, ordered by their position in the buffer instead of the * order in which they were added. */ getCursorsOrderedByBufferPosition(): Cursor[]; // Selections /** Get the selected text of the most recently added selection. */ getSelectedText(): string; /** Get the Range of the most recently added selection in buffer coordinates. */ getSelectedBufferRange(): Range; /** * Get the Ranges of all selections in buffer coordinates. * The ranges are sorted by when the selections were added. Most recent at the end. */ getSelectedBufferRanges(): Range[]; /** * Set the selected range in buffer coordinates. If there are multiple selections, * they are reduced to a single selection with the given range. */ setSelectedBufferRange( bufferRange: RangeCompatible, options?: { reversed?: boolean | undefined; preserveFolds?: boolean | undefined }, ): void; /** * Set the selected ranges in buffer coordinates. If there are multiple selections, * they are replaced by new selections with the given ranges. */ setSelectedBufferRanges( bufferRanges: ReadonlyArray<RangeCompatible>, options?: { reversed?: boolean | undefined; preserveFolds?: boolean | undefined }, ): void; /** Get the Range of the most recently added selection in screen coordinates. */ getSelectedScreenRange(): Range; /** * Get the Ranges of all selections in screen coordinates. * The ranges are sorted by when the selections were added. Most recent at the end. */ getSelectedScreenRanges(): Range[]; /** * Set the selected range in screen coordinates. If there are multiple selections, * they are reduced to a single selection with the given range. */ setSelectedScreenRange(screenRange: RangeCompatible, options?: { reversed?: boolean | undefined }): void; /** * Set the selected ranges in screen coordinates. If there are multiple selections, * they are replaced by new selections with the given ranges. */ setSelectedScreenRanges(screenRanges: ReadonlyArray<RangeCompatible>, options?: { reversed?: boolean | undefined }): void; /** Add a selection for the given range in buffer coordinates. */ addSelectionForBufferRange( bufferRange: RangeCompatible, options?: { reversed?: boolean | undefined; preserveFolds?: boolean | undefined }, ): Selection; /** Add a selection for the given range in screen coordinates. */ addSelectionForScreenRange( screenRange: RangeCompatible, options?: { reversed?: boolean | undefined; preserveFolds?: boolean | undefined }, ): Selection; /** * Select from the current cursor position to the given position in buffer coordinates. * This method may merge selections that end up intersecting. */ selectToBufferPosition(position: PointCompatible): void; /** * Select from the current cursor position to the given position in screen coordinates. * This method may merge selections that end up intersecting. */ selectToScreenPosition(position: PointCompatible): void; /** * Move the cursor of each selection one character upward while preserving the * selection's tail position. * This method may merge selections that end up intersecting. */ selectUp(rowCount?: number): void; /** * Move the cursor of each selection one character downward while preserving * the selection's tail position. * This method may merge selections that end up intersecting. */ selectDown(rowCount?: number): void; /** * Move the cursor of each selection one character leftward while preserving * the selection's tail position. * This method may merge selections that end up intersecting. */ selectLeft(columnCount?: number): void; /** * Move the cursor of each selection one character rightward while preserving * the selection's tail position. * This method may merge selections that end up intersecting. */ selectRight(columnCount?: number): void; /** * Select from the top of the buffer to the end of the last selection in the buffer. * This method merges multiple selections into a single selection. */ selectToTop(): void; /** * Selects from the top of the first selection in the buffer to the end of the buffer. * This method merges multiple selections into a single selection. */ selectToBottom(): void; /** * Select all text in the buffer. * This method merges multiple selections into a single selection. */ selectAll(): void; /** * Move the cursor of each selection to the beginning of its line while preserving * the selection's tail position. * This method may merge selections that end up intersecting. */ selectToBeginningOfLine(): void; /** * Move the cursor of each selection to the first non-whitespace character of its * line while preserving the selection's tail position. If the cursor is already * on the first character of the line, move it to the beginning of the line. * This method may merge selections that end up intersecting. */ selectToFirstCharacterOfLine(): void; /** * Move the cursor of each selection to the end of its line while preserving the * selection's tail position. * This method may merge selections that end up intersecting. */ selectToEndOfLine(): void; /** * Expand selections to the beginning of their containing word. * Operates on all selections. Moves the cursor to the beginning of the containing * word while preserving the selection's tail position. */ selectToBeginningOfWord(): void; /** * Expand selections to the end of their containing word. * Operates on all selections. Moves the cursor to the end of the containing word * while preserving the selection's tail position. */ selectToEndOfWord(): void; /** * For each cursor, select the containing line. * This method merges selections on successive lines. */ selectLinesContainingCursors(): void; /** Select the word surrounding each cursor. */ selectWordsContainingCursors(): void; /** * For each selection, move its cursor to the preceding subword boundary while * maintaining the selection's tail position. * This method may merge selections that end up intersecting. */ selectToPreviousSubwordBoundary(): void; /** * For each selection, move its cursor to the next subword boundary while maintaining * the selection's tail position. * This method may merge selections that end up intersecting. */ selectToNextSubwordBoundary(): void; /** * For each selection, move its cursor to the preceding word boundary while * maintaining the selection's tail position. * This method may merge selections that end up intersecting. */ selectToPreviousWordBoundary(): void; /** * For each selection, move its cursor to the next word boundary while maintaining * the selection's tail position. * This method may merge selections that end up intersecting. */ selectToNextWordBoundary(): void; /** * Expand selections to the beginning of the next word. * Operates on all selections. Moves the cursor to the beginning of the next word * while preserving the selection's tail position. */ selectToBeginningOfNextWord(): void; /** * Expand selections to the beginning of the next paragraph. * Operates on all selections. Moves the cursor to the beginning of the next * paragraph while preserving the selection's tail position. */ selectToBeginningOfNextParagraph(): void; /** * Expand selections to the beginning of the next paragraph. * Operates on all selections. Moves the cursor to the beginning of the next * paragraph while preserving the selection's tail position. */ selectToBeginningOfPreviousParagraph(): void; /** For each selection, select the syntax node that contains that selection. */ selectLargerSyntaxNode(): void; /** Undo the effect a preceding call to `::selectLargerSyntaxNode`. */ selectSmallerSyntaxNode(): void; /** Select the range of the given marker if it is valid. */ selectMarker(marker: DisplayMarker): Range | undefined; /** Get the most recently added Selection. */ getLastSelection(): Selection; /** Get current Selections. */ getSelections(): Selection[]; /** * Get all Selections, ordered by their position in the buffer instead of the * order in which they were added. */ getSelectionsOrderedByBufferPosition(): Selection[]; // NOTE: this calls into Selection::intersectsBufferRange, which itself calls // into Range::intersectsWith. Range::intersectsWith is one of the few functions // which does NOT take a range-compatible array. /** Determine if a given range in buffer coordinates intersects a selection. */ selectionIntersectsBufferRange(bufferRange: RangeLike): boolean; // Searching and Replacing /** * Scan regular expression matches in the entire buffer, calling the given * iterator function on each match. * * ::scan functions as the replace method as well via the replace. */ scan(regex: RegExp, options: ScanContextOptions, iterator: (params: ContextualBufferScanResult) => void): void; /** * Scan regular expression matches in the entire buffer, calling the given * iterator function on each match. * * ::scan functions as the replace method as well via the replace. */ scan(regex: RegExp, iterator: (params: BufferScanResult) => void): void; /** * Scan regular expression matches in a given range, calling the given iterator. * function on each match. */ scanInBufferRange(regex: RegExp, range: RangeCompatible, iterator: (params: BufferScanResult) => void): void; /** * Scan regular expression matches in a given range in reverse order, calling the * given iterator function on each match. */ backwardsScanInBufferRange( regex: RegExp, range: RangeCompatible, iterator: (params: BufferScanResult) => void, ): void; // Tab Behavior /** Returns a boolean indicating whether softTabs are enabled for this editor. */ getSoftTabs(): boolean; /** Enable or disable soft tabs for this editor. */ setSoftTabs(softTabs: boolean): void; /** Toggle soft tabs for this editor. */ toggleSoftTabs(): boolean; /** Get the on-screen length of tab characters. */ getTabLength(): number; /** * Set the on-screen length of tab characters. Setting this to a number will * override the editor.tabLength setting. */ setTabLength(tabLength: number): void; /** Determine if the buffer uses hard or soft tabs. */ usesSoftTabs(): boolean | undefined; /** * Get the text representing a single level of indent. * If soft tabs are enabled, the text is composed of N spaces, where N is the * tab length. Otherwise the text is a tab character (\t). */ getTabText(): string; // Soft Wrap Behavior /** Determine whether lines in this editor are soft-wrapped. */ isSoftWrapped(): boolean; /** Enable or disable soft wrapping for this editor. */ setSoftWrapped(softWrapped: boolean): boolean; /** Toggle soft wrapping for this editor. */ toggleSoftWrapped(): boolean; /** Gets the column at which column will soft wrap. */ getSoftWrapColumn(): number; // Indentation /** * Get the indentation level of the given buffer row. * Determines how deeply the given row is indented based on the soft tabs and tab * length settings of this editor. Note that if soft tabs are enabled and the tab * length is 2, a row with 4 leading spaces would have an indentation level of 2. */ indentationForBufferRow(bufferRow: number): number; /** * Set the indentation level for the given buffer row. * Inserts or removes hard tabs or spaces based on the soft tabs and tab length settings * of this editor in order to bring it to the given indentation level. Note that if soft * tabs are enabled and the tab length is 2, a row with 4 leading spaces would have an * indentation level of 2. */ setIndentationForBufferRow( bufferRow: number, newLevel: number, options?: { preserveLeadingWhitespace?: boolean | undefined }, ): void; /** Indent rows intersecting selections by one level. */ indentSelectedRows(options?: ReadonlyEditOptions): void; /** Outdent rows intersecting selections by one level. */ outdentSelectedRows(options?: ReadonlyEditOptions): void; /** * Get the indentation level of the given line of text. * Determines how deeply the given line is indented based on the soft tabs and tab length * settings of this editor. Note that if soft tabs are enabled and the tab length is 2, * a row with 4 leading spaces would have an indentation level of 2. */ indentLevelForLine(line: string): number; /** Indent rows intersecting selections based on the grammar's suggested indent level. */ autoIndentSelectedRows(options?: ReadonlyEditOptions): void; // Grammars /** Get the current Grammar of this editor. */ getGrammar(): Grammar; // Managing Syntax Scopes /** * Returns a ScopeDescriptor that includes this editor's language. * e.g. [".source.ruby"], or [".source.coffee"]. */ getRootScopeDescriptor(): ScopeDescriptor; /** Get the syntactic scopeDescriptor for the given position in buffer coordinates. */ scopeDescriptorForBufferPosition(bufferPosition: PointCompatible): ScopeDescriptor; /** * Get the syntactic tree {ScopeDescriptor} for the given position in buffer * coordinates or the syntactic {ScopeDescriptor} for TextMate language mode */ syntaxTreeScopeDescriptorForBufferPosition(bufferPosition: PointCompatible): ScopeDescriptor; /** * Get the range in buffer coordinates of all tokens surrounding the cursor * that match the given scope selector. */ bufferRangeForScopeAtCursor(scopeSelector: string): Range; /** Determine if the given row is entirely a comment. */ isBufferRowCommented(bufferRow: number): boolean; // Clipboard Operations /** For each selection, copy the selected text. */ copySelectedText(): void; /** For each selection, cut the selected text. */ cutSelectedText(options?: ReadonlyEditOptions): void; /** * For each selection, replace the selected text with the contents of the clipboard. * If the clipboard contains the same number of selections as the current editor, * each selection will be replaced with the content of the corresponding clipboard * selection text. */ pasteText(options?: TextInsertionOptions & ReadonlyEditOptions): void; /** * For each selection, if the selection is empty, cut all characters of the * containing screen line following the cursor. Otherwise cut the selected text. */ cutToEndOfLine(options?: ReadonlyEditOptions): void; /** * For each selection, if the selection is empty, cut all characters of the * containing buffer line following the cursor. Otherwise cut the selected text. */ cutToEndOfBufferLine(options?: ReadonlyEditOptions): void; // Folds /** * Fold the most recent cursor's row based on its indentation level. * The fold will extend from the nearest preceding line with a lower indentation * level up to the nearest following row with a lower indentation level. */ foldCurrentRow(): void; /** Unfold the most recent cursor's row by one level. */ unfoldCurrentRow(): void; /** * Fold the given row in buffer coordinates based on its indentation level. * If the given row is foldable, the fold will begin there. Otherwise, it will * begin at the first foldable row preceding the given row. */ foldBufferRow(bufferRow: number): void; /** Unfold all folds containing the given row in buffer coordinates. */ unfoldBufferRow(bufferRow: number): void; /** For each selection, fold the rows it intersects. */ foldSelectedLines(): void; /** Fold all foldable lines. */ foldAll(): void; /** Unfold all existing folds. */ unfoldAll(): void; /** * Fold all foldable lines at the given indent level. * @param level A zero-indexed number. */ foldAllAtIndentLevel(level: number): void; /** * Determine whether the given row in buffer coordinates is foldable. * A foldable row is a row that starts a row range that can be folded. */ isFoldableAtBufferRow(bufferRow: number): boolean; /** * Determine whether the given row in screen coordinates is foldable. * A foldable row is a row that starts a row range that can be folded. */ isFoldableAtScreenRow(bufferRow: number): boolean; /** Fold the given buffer row if it isn't currently folded, and unfold it otherwise. */ toggleFoldAtBufferRow(bufferRow: number): void; /** Determine whether the most recently added cursor's row is folded. */ isFoldedAtCursorRow(): boolean; /** Determine whether the given row in buffer coordinates is folded. */ isFoldedAtBufferRow(bufferRow: number): boolean; /** Determine whether the given row in screen coordinates is folded. */ isFoldedAtScreenRow(screenRow: number): boolean; // Gutters /** Add a custom Gutter. */ addGutter(options: GutterOptions): Gutter; /** Get this editor's gutters. */ getGutters(): Gutter[]; /** Get the gutter with the given name. */ gutterWithName(name: string): Gutter | null; // Scrolling the TextEditor /** Scroll the editor to reveal the most recently added cursor if it is off-screen. */ scrollToCursorPosition(options?: { center?: boolean | undefined }): void; /** Scrolls the editor to the given buffer position. */ scrollToBufferPosition(bufferPosition: PointCompatible, options?: { center?: boolean | undefined }): void; /** Scrolls the editor to the given screen position. */ scrollToScreenPosition(screenPosition: PointCompatible, options?: { center?: boolean | undefined }): void; // TextEditor Rendering /** Retrieves the rendered line height in pixels. */ getLineHeightInPixels(): number; /** Retrieves the greyed out placeholder of a mini editor. */ getPlaceholderText(): string; /** * Set the greyed out placeholder of a mini editor. Placeholder text will be * displayed when the editor has no content. */ setPlaceholderText(placeholderText: string): void; /** Undocumented: Buffer range for syntax scope at position */ bufferRangeForScopeAtPosition(scope: string, point: PointCompatible): Range; /** Undocumented: Get syntax token at buffer position */ tokenForBufferPosition(pos: PointCompatible): { value: string; scopes: string[] }; }
the_stack
import { mat4, quat, vec3, vec4 } from 'gl-matrix'; import { assert, isPowerOfTwo, log, LogLevel, upperPowerOfTwo } from '../auxiliaries'; import { GLTF_ELEMENTS_PER_TYPE, GltfAsset, GltfLoader } from 'gltf-loader-ts'; import { MeshPrimitive } from 'gltf-loader-ts/lib/gltf'; import { GLTFHelper } from './gltfhelper'; import { GLTFMesh } from './gltfmesh'; import { GLTFAlphaMode, GLTFPbrMaterial, GLTFShaderFlags } from './gltfpbrmaterial'; import { GLTFPrimitive, IndexBinding, VertexBinding } from './gltfprimitive'; import { Buffer } from '../buffer'; import { Context } from '../context'; import { ResourceManager } from '../core'; import { Program } from '../program'; import { GeometryComponent, Material, TransformComponent } from '../scene'; import { SceneNode } from '../scene/scenenode'; import { Shader } from '../shader'; import { Texture2D } from '../texture2d'; /** * This class can be used to load the glTF file format, which describes scenes and models. * It handles all buffer, texture and geometry creation as well as scene generation. * Per glTF scene, one SceneNode is generated which represents the hierarchy of the scene. * ``` * const loader = new GLTFLoader(this._context); * await loader.loadAsset(GltfRenderer.assetURI); * const rootNode = loader.defaultScene; * ``` */ export class GLTFLoader { protected _context: Context; protected _sceneName: string; protected _defaultScene: SceneNode | undefined; protected _scenes: Array<SceneNode>; protected _resourceManager: ResourceManager; protected _meshes: Array<GLTFMesh>; protected _nameMeshMap: Map<string, GLTFMesh>; protected _uriTextureMap: Map<string, Texture2D>; protected _pbrProgram: Program; protected _pbrDefaultMaterial: Material; constructor(context: Context) { this._context = context; const gl = this._context.gl; this._resourceManager = new ResourceManager(this._context); this._scenes = new Array<SceneNode>(); const vert = new Shader(this._context, gl.VERTEX_SHADER, 'gltf_default.vert'); // eslint-disable-next-line @typescript-eslint/no-var-requires vert.initialize(require('./shaders/gltf_default.vert')); const frag = new Shader(this._context, gl.FRAGMENT_SHADER, 'gltf_default.frag'); // eslint-disable-next-line @typescript-eslint/no-var-requires frag.initialize(require('./shaders/gltf_default.frag')); this._pbrProgram = new Program(this._context, 'GLTFPbrProgram'); this._pbrProgram.initialize([vert, frag]); } protected async loadTextures(asset: GltfAsset): Promise<void> { const gl = this._context.gl; this._uriTextureMap = new Map<string, Texture2D>(); const textures = asset.gltf.textures; const images = asset.gltf.images; const samplers = asset.gltf.samplers; if (!textures || !images) { return; } let textureId = 0; for (const textureInfo of textures) { if (textureInfo.source === undefined) { log(LogLevel.Warning, `The GLTF model does not specify a texture source. Possibly it uses an unsupported extension.`); textureId++; continue; } const imageId = textureInfo.source!; const image = images[imageId]; const identifier = this._sceneName + '_texture_' + textureId; const name = image.name === undefined ? image.uri : image.name; // TODO: make sure image is only loaded once if it is referenced by multiple textures let data: HTMLImageElement | HTMLCanvasElement = await asset.imageData.get(imageId); /** * If the texture is not power of two, resize it to avoid problems with REPEAT samplers. * See: https://www.khronos.org/webgl/wiki/WebGL_and_OpenGL_Differences#Non-Power_of_Two_Texture_Support */ if (!isPowerOfTwo(data.width) || !isPowerOfTwo(data.height)) { // Scale up the texture to the next highest power of two dimensions. const canvas = document.createElement('canvas'); canvas.width = upperPowerOfTwo(data.width); canvas.height = upperPowerOfTwo(data.height); const ctx = canvas.getContext('2d'); if (ctx === undefined) { log(LogLevel.Error, 'Failed to create context while trying to resize non power of two texture'); } ctx!.drawImage(data, 0, 0, canvas.width, canvas.height); data = canvas; } const texture = new Texture2D(this._context, name); texture.initialize(data.width, data.height, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE); texture.data(data); if (samplers === undefined || textureInfo.sampler === undefined) { texture.wrap(gl.REPEAT, gl.REPEAT); texture.filter(gl.LINEAR, gl.LINEAR); } else { const sampler = samplers[textureInfo.sampler]; texture.wrap(sampler.wrapS || gl.REPEAT, sampler.wrapT || gl.REPEAT); texture.filter(sampler.magFilter || gl.LINEAR, sampler.minFilter || gl.LINEAR); if (sampler.minFilter === gl.NEAREST_MIPMAP_NEAREST || sampler.minFilter === gl.LINEAR_MIPMAP_NEAREST || sampler.minFilter === gl.NEAREST_MIPMAP_LINEAR || sampler.minFilter === gl.LINEAR_MIPMAP_LINEAR) { texture.generateMipMap(); } } this._resourceManager.add(texture, [name, identifier]); const uri = image.uri ? image.uri : identifier; this._uriTextureMap.set(uri, texture); textureId++; } } protected getTexture(index: number): Texture2D | undefined { const identifier = this._sceneName + '_texture_' + index; const texture = this._resourceManager.get(identifier) as Texture2D; if (texture === undefined) { log(LogLevel.Warning, `Texture with index ${index} could not be located.`); return; } return texture; } protected async loadMaterials(asset: GltfAsset): Promise<void> { // Init default material this._pbrDefaultMaterial = new GLTFPbrMaterial(this._context, 'DefaultMaterial'); this._resourceManager.add(this._pbrDefaultMaterial, [this._pbrDefaultMaterial.name]); const materials = asset.gltf.materials; if (!materials) { return; } // Init materials specified by GLTF let materialId = 0; for (const materialInfo of materials) { const identifier = this._sceneName + '_material_' + materialId; const material = new GLTFPbrMaterial(this._context, materialInfo.name); const normalTexture = materialInfo.normalTexture; if (normalTexture !== undefined) { material.normalTexture = this.getTexture(normalTexture.index); material.normalTexCoord = normalTexture.texCoord || 0; material.normalScale = normalTexture.scale || 1; } const occlusionTexture = materialInfo.occlusionTexture; if (occlusionTexture !== undefined) { material.occlusionTexture = this.getTexture(occlusionTexture.index); material.occlusionTexCoord = occlusionTexture.texCoord || 0; } const emissiveTexture = materialInfo.emissiveTexture; if (emissiveTexture !== undefined) { material.emissiveTexture = this.getTexture(emissiveTexture.index); material.emissiveTexCoord = emissiveTexture.texCoord || 0; } material.emissiveFactor = vec3.fromValues(0, 0, 0); if (materialInfo.emissiveFactor !== undefined) { material.emissiveFactor = vec3.fromValues.apply(undefined, materialInfo.emissiveFactor); } material.alphaMode = GLTFAlphaMode.OPAQUE; if (materialInfo.alphaMode === 'MASK') { material.alphaMode = GLTFAlphaMode.MASK; if (materialInfo.alphaCutoff === undefined) { // Standard assumes default of 0.5 material.alphaCutoff = 0.5; } else { material.alphaCutoff = materialInfo.alphaCutoff!; } } else if (materialInfo.alphaMode === 'BLEND') { material.alphaMode = GLTFAlphaMode.BLEND; material.isTransparent = true; } material.isDoubleSided = materialInfo.doubleSided || false; const pbrInfo = materialInfo.pbrMetallicRoughness; // TODO: full support of material properties if (pbrInfo === undefined) { log(LogLevel.Warning, 'Model contains a material without PBR information'); } const baseColorTexture = pbrInfo!.baseColorTexture; if (baseColorTexture !== undefined) { material.baseColorTexture = this.getTexture(baseColorTexture.index); material.baseColorTexCoord = baseColorTexture.texCoord || 0; } const metallicRoughnessTexture = pbrInfo!.metallicRoughnessTexture; if (metallicRoughnessTexture !== undefined) { material.metallicRoughnessTexture = this.getTexture(metallicRoughnessTexture.index); material.metallicRoughnessTexCoord = metallicRoughnessTexture.texCoord || 0; } material.baseColorFactor = vec4.fromValues(1, 1, 1, 1); if (pbrInfo!.baseColorFactor !== undefined) { material.baseColorFactor = vec4.fromValues.apply(undefined, pbrInfo!.baseColorFactor); } material.metallicFactor = 1.0; if (pbrInfo!.metallicFactor !== undefined) { material.metallicFactor = pbrInfo!.metallicFactor!; } material.roughnessFactor = 1.0; if (pbrInfo!.roughnessFactor !== undefined) { material.roughnessFactor = pbrInfo!.roughnessFactor!; } this._resourceManager.add(material, [materialInfo.name, identifier]); materialId++; } } protected inferBufferUsage(asset: GltfAsset, bufferViewId: number): GLenum { const gl = this._context.gl; const meshes = asset.gltf.meshes; const accessors = asset.gltf.accessors; if (meshes === undefined || accessors === undefined) { log(LogLevel.Error, `Asset does not include any meshes or accessors`); return gl.ARRAY_BUFFER; } /** * Find out if any primitive uses this buffer view as an index buffer. * If so, the buffer view can only be used as an index buffer as per specification */ for (const meshInfo of meshes!) { for (const primitive of meshInfo.primitives) { const indexAccessorId = primitive.indices; if (indexAccessorId === undefined) { continue; } const accessor = accessors![indexAccessorId]; const indexBufferViewId = accessor.bufferView; if (indexBufferViewId === undefined) { continue; } else if (indexBufferViewId === bufferViewId) { return gl.ELEMENT_ARRAY_BUFFER; } } } return gl.ARRAY_BUFFER; } protected async loadBuffers(asset: GltfAsset): Promise<void> { const gl = this._context.gl; const bufferViews = asset.gltf.bufferViews; const accessors = asset.gltf.accessors; if (!bufferViews) { log(LogLevel.Warning, 'The asset does not include any buffer view information.'); return; } if (!accessors) { log(LogLevel.Warning, 'The asset does not include any accessor information.'); return; } /** * Create a buffer for each buffer view in the model. * If a target (index or array buffer) is specified use it, otherwise infer it from the usage within primitives. */ let bufferViewId = 0; for (const bufferViewInfo of bufferViews) { const identifier = this._sceneName + '_bufferView_' + bufferViewId; const data = await asset.bufferViewData(bufferViewId); let target = bufferViewInfo.target; if (target === undefined) { target = this.inferBufferUsage(asset, bufferViewId); } const buffer = new Buffer(this._context, identifier); buffer.initialize(target); buffer.data(data, gl.STATIC_DRAW); this._resourceManager.add(buffer, [identifier]); bufferViewId++; } /** * Create buffers for sparse accessors * See: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#sparse-accessors */ let accessorId = 0; for (const accessorInfo of accessors) { const bufferViewIndex = accessorInfo.bufferView; const sparseInfo = accessorInfo.sparse; if (bufferViewIndex === undefined || sparseInfo !== undefined) { const identifier = this._sceneName + '_accessor_' + accessorId; const buffer = new Buffer(this._context, identifier); const data = await asset.accessorData(accessorId); // TODO: find out if sparse accessor can be used for index buffers buffer.initialize(gl.ARRAY_BUFFER); buffer.data(data, gl.STATIC_DRAW); this._resourceManager.add(buffer, [identifier]); } accessorId++; } } protected async loadMeshes(asset: GltfAsset): Promise<Array<GLTFMesh>> { this._meshes = new Array<GLTFMesh>(); this._nameMeshMap = new Map<string, GLTFMesh>(); const meshes = asset.gltf.meshes; if (meshes === undefined) { log(LogLevel.Warning, 'The asset does not contain any mesh information'); return this._meshes; } let primitiveId = 0; for (const meshInfo of meshes) { const mesh = new GLTFMesh(meshInfo.name); for (const primitiveInfo of meshInfo.primitives) { const primitive = await this.loadPrimitive(asset, primitiveInfo, primitiveId); if (primitive !== undefined) { mesh.addPrimitive(primitive); } primitiveId++; } if (meshInfo.name) { this._nameMeshMap.set(meshInfo.name, mesh); } this._meshes.push(mesh); } return this._meshes; } protected async loadPrimitive(asset: GltfAsset, primitiveInfo: MeshPrimitive, id: number): Promise<GLTFPrimitive | undefined> { const gl = this._context.gl; const accessors = asset.gltf.accessors; const bufferViews = asset.gltf.bufferViews; if (accessors === undefined) { log(LogLevel.Error, 'GLTF asset does not have any accessors.'); return; } if (bufferViews === undefined) { log(LogLevel.Error, 'GLTF asset does not have any buffer views.'); return; } let modeNumber = primitiveInfo.mode; const identifier = this._sceneName + '_primitive_' + id; // if no mode is specified the default is 4 (gl.TRIANGLES) if (!modeNumber) { modeNumber = 4; } const drawMode = GLTFHelper.modeToEnum(gl, modeNumber); const bindings = new Array<VertexBinding>(); let material = this._pbrDefaultMaterial; if (primitiveInfo.material !== undefined) { const materialIdentifier = this._sceneName + '_material_' + primitiveInfo.material!; const fetchedMaterial = this._resourceManager.get(materialIdentifier); if (fetchedMaterial !== undefined) { material = fetchedMaterial as Material; } else { log(LogLevel.Warning, `Material ${materialIdentifier} could not be found.`); } } let geometryFlags = 0; for (const semantic in primitiveInfo.attributes) { // init buffer/attribute binding for attribute const attributeIndex = GLTFHelper.nameToAttributeIndex(semantic); if (semantic === 'NORMAL') { geometryFlags |= GLTFShaderFlags.HAS_NORMALS; } if (semantic === 'TANGENT') { geometryFlags |= GLTFShaderFlags.HAS_TANGENTS; } if (semantic === 'COLOR_0') { geometryFlags |= GLTFShaderFlags.HAS_COLORS; } if (semantic === 'TEXCOORD_0' || semantic === 'TEXCOORD_1' || semantic === 'TEXCOORD_2') { geometryFlags |= GLTFShaderFlags.HAS_UV; } const accessorIndex = primitiveInfo.attributes[semantic]; const accessorInfo = accessors[accessorIndex]; const bufferViewIndex = accessorInfo.bufferView; const sparseInfo = accessorInfo.sparse; let buffer: Buffer; let stride = 0; if (bufferViewIndex === undefined || sparseInfo !== undefined) { const accessorIdentifier = this._sceneName + '_accessor_' + accessorIndex; buffer = this._resourceManager.get(accessorIdentifier) as Buffer; } else { const bufferViewInfo = bufferViews[bufferViewIndex!]; const bufferViewIdentifier = this._sceneName + '_bufferView_' + bufferViewIndex; buffer = this._resourceManager.get(bufferViewIdentifier) as Buffer; stride = bufferViewInfo.byteStride || 0; } const binding = new VertexBinding(); binding.buffer = buffer!; binding.attributeIndex = attributeIndex; binding.numVertices = accessorInfo.count; binding.normalized = accessorInfo.normalized || false; binding.size = GLTF_ELEMENTS_PER_TYPE[accessorInfo.type]; binding.offset = accessorInfo.byteOffset || 0; binding.stride = stride; binding.type = accessorInfo.componentType; bindings.push(binding); } let indexBinding: IndexBinding | undefined; if (primitiveInfo.indices !== undefined) { const accessorInfo = accessors[primitiveInfo.indices]; const bufferViewIndex = accessorInfo.bufferView; if (!bufferViewIndex === undefined) { log(LogLevel.Error, 'Accessor does not reference a BufferView.'); } const bufferViewIdentifier = this._sceneName + '_bufferView_' + bufferViewIndex; const buffer = this._resourceManager.get(bufferViewIdentifier) as Buffer; indexBinding = new IndexBinding(); indexBinding.buffer = buffer; indexBinding.numIndices = accessorInfo.count; indexBinding.offset = accessorInfo.byteOffset || 0; indexBinding.type = accessorInfo.componentType; } const primitive = new GLTFPrimitive(this._context, bindings, indexBinding, drawMode, material, geometryFlags); primitive.initialize(); this._resourceManager.add(primitive, [identifier]); return primitive; } protected async generateScenes(asset: GltfAsset): Promise<void> { const nodes = asset.gltf.nodes; const scenes = asset.gltf.scenes; if (!nodes || !scenes) { log(LogLevel.Warning, 'The asset does not contain any nodes or scene information.'); return; } const idToNode = new Map<number, SceneNode>(); /** * First pass over all nodes to initialize them and save the index to node mapping. */ let nodeId = 0; for (const node of nodes) { const name = node.name || 'node_' + nodeId; const sceneNode = new SceneNode(name); idToNode.set(nodeId, sceneNode); if (node.matrix) { const matrix = mat4.fromValues.apply(undefined, node.matrix); const transformComponent = new TransformComponent(matrix); sceneNode.addComponent(transformComponent); } else if (node.translation || node.rotation || node.scale) { let rotation = quat.create(); if (node.rotation) { rotation = quat.fromValues.apply(undefined, node.rotation); } let translation = vec3.create(); if (node.translation) { translation = vec3.fromValues.apply(undefined, node.translation); } let scale = vec3.fromValues(1, 1, 1); if (node.scale) { scale = vec3.fromValues.apply(undefined, node.scale); } const matrix = mat4.fromRotationTranslationScale( mat4.create(), rotation, translation, scale, ); const transformComponent = new TransformComponent(matrix); sceneNode.addComponent(transformComponent); } if (node.mesh !== undefined) { const mesh = this._meshes[node.mesh]; for (const primitive of mesh.primitives) { const geometryComponent = new GeometryComponent(); geometryComponent.material = primitive.material; geometryComponent.geometry = primitive; sceneNode.addComponent(geometryComponent); } } /** * TODO: skinning support */ if (node.skin || node.weights) { log(LogLevel.Info, 'Imported GLTF assets uses skins, which are not supported yet.'); } nodeId++; } /** * Second pass over all nodes to create the hierarchy. */ nodeId = 0; for (const node of nodes) { const sceneNode = idToNode.get(nodeId); assert(sceneNode !== undefined, 'Scene node could not be found.'); if (node.children) { for (const childId of node.children) { const childNode = idToNode.get(childId); if (!childNode) { log(LogLevel.Error, 'Model references a node that does not exist.'); } sceneNode!.addNode(childNode!); } } nodeId++; } /** * Create a scene node per scene specified by gltf. * Gltf scenes can specify multiple root nodes. * Therefore, the top level scene nodes are wrappers to contain all root nodes of a scene. */ let sceneId = 0; for (const scene of scenes) { const name = scene.name || 'scene_' + sceneId; const sceneNode = new SceneNode(name); if (scene.nodes) { for (const nodeId of scene.nodes) { const node = idToNode.get(nodeId); if (!node) { log(LogLevel.Error, 'Scene references a node that does not exist.'); } sceneNode.addNode(node!); } } else { log(LogLevel.Warning, `Scene ${name} does not contain any nodes.`); } this._scenes.push(sceneNode); sceneId++; } const defaultSceneId = asset.gltf.scene; if (defaultSceneId !== undefined) { this._defaultScene = this._scenes[defaultSceneId]; } } async loadAsset(uri: string): Promise<void> { const loader = new GltfLoader(); const asset = await loader.load(uri); const gltf = asset.gltf; this._sceneName = 'scene'; if (gltf.scenes && gltf.scene && gltf.scenes[gltf.scene!].name) { this._sceneName = gltf.scenes[gltf.scene!].name; } await this.loadTextures(asset) .then(() => this.loadMaterials(asset)) .then(() => this.loadBuffers(asset)) .then(() => this.loadMeshes(asset)) .then(() => this.generateScenes(asset)); } uninitialize(): void { this._scenes = []; this._defaultScene = undefined; this._resourceManager.uninitialize(); } /** * Get a single mesh from the glTF scene. * * @param name - Name of the mesh as specified in the glTF file */ getMeshByName(name: string): GLTFMesh | undefined { return this._nameMeshMap.get(name); } /** * Get a list of all meshes contained in the glTF asset. * The meshes are given in the order in which they appear in the glTF file. */ get meshes(): Array<GLTFMesh> { return this._meshes; } /** * Returns a map, where the key is an URI referncing image data and the values are * the corresponding generated texture by this loader. * For textures, where no URI is available (e.g. loaded from an internal data blob), * an id generated by the loader is used. */ get uriTextureMap(): Map<string, Texture2D> { return this._uriTextureMap; } /** * A default program, which can be used to render resources loaded with glTF. * It supports physically-based rendering as described in the glTF standard. */ get pbrProgram(): Program { return this._pbrProgram; } get scenes(): Array<SceneNode> { return this._scenes; } /** * Returns the default scene is specified by glTF, otherwise returns the first scene. */ get defaultScene(): SceneNode { if (this._defaultScene !== undefined) { return this._defaultScene; } else if (this._scenes !== undefined && this._scenes.length > 0) { return this._scenes[0]; } else { log(LogLevel.Warning, 'Default scene was requested, but none is available.'); return new SceneNode('EmptyScene'); } } }
the_stack
import { CircleSpec, CurveSpec, EllipseSpec, LineSpec, PathSpec, PolygonSpec, PolylineSpec, RectSpec, ShapeSpec, } from './types'; const convertQuadraticToCubicBezier = (spec: CurveSpec, prevSpec: CurveSpec): CurveSpec => prevSpec ? { curve: { type: 'cubic', x1: prevSpec.x + 2 / 3 * (spec.curve.x1 - prevSpec.x), y1: prevSpec.y + 2 / 3 * (spec.curve.y1 - prevSpec.y), x2: spec.x + 2 / 3 * (spec.curve.x1 - spec.x), y2: spec.y + 2 / 3 * (spec.curve.y1 - spec.y), }, x: spec.x, y: spec.y, } : // This should never happen, but just return the original spec if we didn't have a starting point. spec; const toPoints = (spec: ShapeSpec): CurveSpec[] => { switch (spec.type) { case 'circle': return getPointsFromCircle(spec); case 'ellipse': return getPointsFromEllipse(spec); case 'line': return getPointsFromLine(spec); case 'path': return getPointsFromPath(spec); case 'polygon': return getPointsFromPolygon(spec); case 'polyline': return getPointsFromPolyline(spec); case 'rect': return getPointsFromRect(spec); default: return []; } }; const getPointsFromCircle = ({cx, cy, r}: CircleSpec): CurveSpec[] => { return [ { x: cx, y: cy - r, moveTo: true, }, { x: cx, y: cy + r, curve: { type: 'arc', rx: r, ry: r, sweepFlag: 1, }, }, { x: cx, y: cy - r, curve: { type: 'arc', rx: r, ry: r, sweepFlag: 1, }, }, ]; }; const getPointsFromEllipse = ({cx, cy, rx, ry}: EllipseSpec): CurveSpec[] => { return [ { x: cx, y: cy - ry, moveTo: true, }, { x: cx, y: cy + ry, curve: { rx, ry, type: 'arc', sweepFlag: 1, }, }, { x: cx, y: cy - ry, curve: { rx, ry, type: 'arc', sweepFlag: 1, }, }, ]; }; const getPointsFromLine = ({x1, x2, y1, y2}: LineSpec): CurveSpec[] => { return [ { x: x1, y: y1, moveTo: true, }, { x: x2, y: y2, }, ]; }; const validCommands = /[MmLlHhVvCcSsQqTtAaZz]/g; const commandLengths = { A: 7, C: 6, H: 1, L: 2, M: 2, Q: 4, S: 4, T: 2, V: 1, Z: 0, }; const relativeCommands = [ 'a', 'c', 'h', 'l', 'm', 'q', 's', 't', 'v', ]; const PARSING_REGEXPS = { command: /^[MmLlHhVvCcSsQqTtAaZz]/g, whitespace: /^[\s]+/, comma: /^,/, number: /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^-?\d*\.?\d+(?:e[+-]?\d+)?/i, }; const isRelative = (command: string): boolean => relativeCommands.indexOf(command) !== -1; const optionalArcKeys = ['xAxisRotation', 'largeArcFlag', 'sweepFlag']; const getCommands = (d: string): string[] => d && d.match(validCommands); interface Token { type: string; raw: string; } function tokenize (d: string): Token[] { const tokens = []; let chunk = d; while (chunk.length > 0) { for (const regexpName in PARSING_REGEXPS) { const match = PARSING_REGEXPS[regexpName].exec(chunk); if (match) { tokens.push({ type: regexpName, raw: match[0], }); // Need to slice the chunk at the original match length chunk = chunk.slice(match[0].length, chunk.length); break; } } } return tokens; } const getParams = (d: string): number[][] => { const tokens = tokenize(d); const fixed = tokens.filter((t) => { return t.type === 'number' || t.type === 'command' || t.type === 'comma'; }).map((t) => { return t.raw; }).join(' '); const segs = fixed.split(validCommands) .map((p) => { return p.trim(); }) .filter((p) => { return p.length > 0; }); return segs.map((s) => { return s.split(/[ ,]+/) .map((n) => { return parseFloat(n); }) .filter((n) => { return !isNaN(n); }); }); }; const getPointsFromPath = ({d}: PathSpec): CurveSpec[] => { const commands = getCommands(d); if (!commands) { return []; } const params = getParams(d); const points: CurveSpec[] = []; let moveTo; for (let i = 0, l = commands.length; i < l; i++) { const command = commands[i]; const upperCaseCommand = command.toUpperCase(); const commandLength = commandLengths[upperCaseCommand]; const relative = isRelative(command); let prevPoint = (points.length < 1) ? null : points[points.length - 1]; if (commandLength > 0) { const commandParams = params.shift(); const iterations = commandParams.length / commandLength; for (let j = 0; j < iterations; j++) { prevPoint = (points.length < 1) ? null : points[points.length - 1]; switch (upperCaseCommand) { case 'M': const x = (relative && prevPoint ? prevPoint.x : 0) + commandParams.shift(); const y = (relative && prevPoint ? prevPoint.y : 0) + commandParams.shift(); moveTo = { x, y, }; points.push({ x, y, moveTo: true, }); break; case 'L': points.push({ x: (relative ? prevPoint.x : 0) + commandParams.shift(), y: (relative ? prevPoint.y : 0) + commandParams.shift(), }); break; case 'H': points.push({ x: (relative ? prevPoint.x : 0) + commandParams.shift(), y: prevPoint.y, }); break; case 'V': points.push({ x: prevPoint.x, y: (relative ? prevPoint.y : 0) + commandParams.shift(), }); break; case 'A': points.push({ curve: { type: 'arc', rx: commandParams.shift(), ry: commandParams.shift(), xAxisRotation: commandParams.shift(), largeArcFlag: commandParams.shift(), sweepFlag: commandParams.shift(), }, x: (relative ? prevPoint.x : 0) + commandParams.shift(), y: (relative ? prevPoint.y : 0) + commandParams.shift(), }); for (const k of optionalArcKeys) { if (points[points.length - 1].curve[k] === 0) { delete points[points.length - 1].curve[k]; } } break; case 'C': points.push({ curve: { type: 'cubic', x1: (relative ? prevPoint.x : 0) + commandParams.shift(), y1: (relative ? prevPoint.y : 0) + commandParams.shift(), x2: (relative ? prevPoint.x : 0) + commandParams.shift(), y2: (relative ? prevPoint.y : 0) + commandParams.shift(), }, x: (relative ? prevPoint.x : 0) + commandParams.shift(), y: (relative ? prevPoint.y : 0) + commandParams.shift(), }); break; case 'S': const sx2 = (relative ? prevPoint.x : 0) + commandParams.shift(); const sy2 = (relative ? prevPoint.y : 0) + commandParams.shift(); const sx = (relative ? prevPoint.x : 0) + commandParams.shift(); const sy = (relative ? prevPoint.y : 0) + commandParams.shift(); const diff: {x: number, y: number} = { x: null, y: null, }; let sx1; let sy1; if (prevPoint.curve && prevPoint.curve.type === 'cubic') { diff.x = Math.abs(prevPoint.x - prevPoint.curve.x2); diff.y = Math.abs(prevPoint.y - prevPoint.curve.y2); sx1 = prevPoint.x < prevPoint.curve.x2 ? prevPoint.x - diff.x : prevPoint.x + diff.x; sy1 = prevPoint.y < prevPoint.curve.y2 ? prevPoint.y - diff.y : prevPoint.y + diff.y; } else { diff.x = Math.abs(sx - sx2); diff.y = Math.abs(sy - sy2); sx1 = prevPoint.x; sy1 = prevPoint.y; } points.push({ curve: { type: 'cubic', x1: sx1, y1: sy1, x2: sx2, y2: sy2, }, x: sx, y: sy, }); break; case 'Q': points.push(convertQuadraticToCubicBezier({ curve: { type: 'quadratic', x1: (relative ? prevPoint.x : 0) + commandParams.shift(), y1: (relative ? prevPoint.y : 0) + commandParams.shift(), }, x: (relative ? prevPoint.x : 0) + commandParams.shift(), y: (relative ? prevPoint.y : 0) + commandParams.shift(), }, prevPoint)); break; case 'T': const tx = (relative ? prevPoint.x : 0) + commandParams.shift(); const ty = (relative ? prevPoint.y : 0) + commandParams.shift(); let tx1; let ty1; if (prevPoint.curve && prevPoint.curve.type === 'quadratic') { const diff = { x: Math.abs(prevPoint.x - prevPoint.curve.x1), y: Math.abs(prevPoint.y - prevPoint.curve.y1), }; tx1 = prevPoint.x < prevPoint.curve.x1 ? prevPoint.x - diff.x : prevPoint.x + diff.x; ty1 = prevPoint.y < prevPoint.curve.y1 ? prevPoint.y - diff.y : prevPoint.y + diff.y; } else { tx1 = prevPoint.x; ty1 = prevPoint.y; } points.push(convertQuadraticToCubicBezier({ curve: { type: 'quadratic', x1: tx1, y1: ty1, }, x: tx, y: ty, }, prevPoint)); break; } } } else if (prevPoint !== null) { if (upperCaseCommand === 'Z') { prevPoint.closed = true; } if (moveTo !== undefined && (prevPoint.x !== moveTo.x || prevPoint.y !== moveTo.y)) { points.push({ x: moveTo.x, y: moveTo.y, }); } } } return points; }; const getPointsFromPolygon = ({points}: PolygonSpec): CurveSpec[] => { return getPointsFromPoints({ points, closed: true, }); }; const getPointsFromPolyline = ({points}: PolylineSpec): CurveSpec[] => { return getPointsFromPoints({ points, closed: false, }); }; const getPointsFromPoints = ({closed, points}: {closed: boolean, points: string}): CurveSpec[] => { const numbers = points.split(/[\s,]+/).map((n: string) => parseFloat(n)); const p = numbers.reduce( (arr, point, i) => { if (i % 2 === 0) { arr.push({x: point}); } else { arr[(i - 1) / 2].y = point; } return arr; }, [], ); if (closed) { p.push({...p[0]}); } p[0].moveTo = true; return p; }; const getPointsFromRect = ({height, rx, ry, width, x, y}: RectSpec): CurveSpec[] => { if (rx || ry) { return getPointsFromRectWithCornerRadius({ height, width, x, y, rx: rx || ry, ry: ry || rx, type: 'rect', }); } return getPointsFromBasicRect({ height, width, x, y, }); }; const getPointsFromBasicRect = ({height, width, x, y}: RectSpec): CurveSpec[] => { return [ { x, y, moveTo: true, }, { y, x: x + width, }, { x: x + width, y: y + height, }, { x, y: y + height, }, { x, y, }, ]; }; const getPointsFromRectWithCornerRadius = ({height, rx, ry, width, x, y}: RectSpec): CurveSpec[] => { const curve = { rx, ry, type: 'arc', sweepFlag: 1, }; return [ { y, x: x + rx, moveTo: true, }, { y, x: x + width - rx, }, { curve, x: x + width, y: y + ry, }, { x: x + width, y: y + height - ry, }, { curve, x: x + width - rx, y: y + height, }, { x: x + rx, y: y + height, }, { curve, x, y: y + height - ry, }, { x, y: y + ry, }, { curve, y, x: x + rx, }, ]; }; export default toPoints;
the_stack
import { Archive, ProjectDiagram } from '@styled-icons/fa-solid' import { withRouter } from 'react-router-dom' import { SlidersH } from '@styled-icons/fa-solid/SlidersH' import { LocationService } from '@xrengine/client-core/src/admin/state/LocationService' import { DockLayout, DockMode } from 'rc-dock' import 'rc-dock/dist/rc-dock.css' import React, { Component } from 'react' import { DndProvider } from 'react-dnd' import { HTML5Backend } from 'react-dnd-html5-backend' import { withTranslation } from 'react-i18next' import Modal from 'react-modal' import styled from 'styled-components' import { createScene, getScene, saveScene } from '../functions/sceneFunctions' import AssetsPanel from './assets/AssetsPanel' import { DialogContextProvider } from './contexts/DialogContext' import { defaultSettings, SettingsContextProvider } from './contexts/SettingsContext' import ConfirmDialog from './dialogs/ConfirmDialog' import ErrorDialog from './dialogs/ErrorDialog' import ExportProjectDialog from './dialogs/ExportProjectDialog' import { ProgressDialog } from './dialogs/ProgressDialog' import SaveNewProjectDialog from './dialogs/SaveNewProjectDialog' import DragLayer from './dnd/DragLayer' import HierarchyPanelContainer from './hierarchy/HierarchyPanelContainer' import { PanelDragContainer, PanelIcon, PanelTitle } from './layout/Panel' import PropertiesPanelContainer from './properties/PropertiesPanelContainer' import defaultTemplateUrl from './templates/crater.json' import tutorialTemplateUrl from './templates/tutorial.json' import ToolBar from './toolbar/ToolBar' import ViewportPanelContainer from './viewport/ViewportPanelContainer' import PerformanceCheckDialog from './dialogs/PerformanceCheckDialog' import PublishDialog from './dialogs/PublishDialog' import PublishedSceneDialog from './dialogs/PublishedSceneDialog' import i18n from 'i18next' import FileBrowserPanel from './assets/FileBrowserPanel' import { cmdOrCtrlString } from '../functions/utils' import configs from './configs' import { accessLocationState } from '@xrengine/client-core/src/admin/state/LocationState' import { accessSceneState } from '@xrengine/client-core/src/admin/state/SceneState' import { SceneService } from '@xrengine/client-core/src/admin/state/SceneService' import { CommandManager } from '../managers/CommandManager' import EditorCommands from '../constants/EditorCommands' import EditorEvents from '../constants/EditorEvents' import { SceneManager } from '../managers/SceneManager' import { ControlManager } from '../managers/ControlManager' import { NodeManager, registerPredefinedNodes } from '../managers/NodeManager' import { registerPredefinedSources, SourceManager } from '../managers/SourceManager' import { CacheManager } from '../managers/CacheManager' import { ProjectManager } from '../managers/ProjectManager' import { SceneDetailInterface } from '@xrengine/common/src/interfaces/SceneInterface' import { client } from '@xrengine/client-core/src/feathers' import { upload } from '@xrengine/client-core/src/util/upload' const maxUploadSize = 25 /** * getSceneUrl used to create url for the scene. * * @author Robert Long * @param {any} sceneId * @return {string} [url] */ export const getSceneUrl = (sceneId): string => `${configs.APP_URL}/scenes/${sceneId}` /** * publishProject is used to publish project, firstly we save the project the publish. * * @author Robert Long * @param {any} project * @param {any} showDialog * @param {any} hideDialog * @return {Promise} [returns published project data] */ export const publishProject = async (project, showDialog, hideDialog?): Promise<any> => { let screenshotUrl try { const scene = SceneManager.instance.scene const abortController = new AbortController() const signal = abortController.signal // Save the scene if it has been modified. if (SceneManager.instance.sceneModified) { showDialog(ProgressDialog, { title: i18n.t('editor:saving'), message: i18n.t('editor:savingMsg'), cancelable: true, onCancel: () => { abortController.abort() } }) // saving project. project = await saveScene(project.scene_id, signal) if (signal.aborted) { const error = new Error(i18n.t('editor:errors.publishProjectAborted')) error['aborted'] = true throw error } } showDialog(ProgressDialog, { title: i18n.t('editor:generateScreenshot'), message: i18n.t('editor:generateScreenshotMsg') }) // Wait for 5ms so that the ProgressDialog shows up. await new Promise((resolve) => setTimeout(resolve, 5)) // Take a screenshot of the scene from the current camera position to use as the thumbnail const screenshot = await SceneManager.instance.takeScreenshot() console.log('Screenshot is') console.log(screenshot) const { blob: screenshotBlob, cameraTransform: screenshotCameraTransform } = screenshot console.log('screenshotBlob is') console.log(screenshotBlob) screenshotUrl = URL.createObjectURL(screenshotBlob) console.log('Screenshot url is', screenshotUrl) if (signal.aborted) { const error = new Error(i18n.t('editor:errors.publishProjectAborted')) error['aborted'] = true throw error } let { name } = scene.metadata name = (project.scene && project.scene.name) || name || SceneManager.instance.scene.name // Display the publish dialog and wait for the user to submit / cancel const publishParams: any = await new Promise((resolve) => { showDialog(PublishDialog, { screenshotUrl, initialSceneParams: { name }, onCancel: () => resolve(null), onPublish: resolve }) }) // User clicked cancel if (!publishParams) { URL.revokeObjectURL(screenshotUrl) hideDialog() const error = new Error(i18n.t('editor:errors.publishProjectAborted')) error['aborted'] = true throw error } // Update the scene with the metadata from the publishDialog scene.setMetadata({ name: publishParams.name, previewCameraTransform: screenshotCameraTransform }) showDialog(ProgressDialog, { title: i18n.t('editor:publishingScene'), message: i18n.t('editor:publishingSceneMsg'), cancelable: true, onCancel: () => { abortController.abort() } }) // Clone the existing scene, process it for exporting, and then export as a glb blob const { glbBlob, chunks } = await SceneManager.instance.exportScene({ scores: true }) if (signal.aborted) { const error = new Error(i18n.t('editor:errors.publishProjectAborted')) error['aborted'] = true throw error } const performanceCheckResult = await new Promise((resolve) => { showDialog(PerformanceCheckDialog, { chunks, onCancel: () => resolve(false), onConfirm: () => resolve(true) }) }) if (!performanceCheckResult) { const error = new Error(i18n.t('editor:errors.publishProjectAborted')) error['aborted'] = true throw error } // Serialize Editor scene const serializedScene = await SceneManager.instance.scene.serialize(project.scene_id) const sceneBlob = new Blob([JSON.stringify(serializedScene)], { type: 'application/json' }) showDialog(ProgressDialog, { title: i18n.t('editor:publishingScene'), message: i18n.t('editor:publishingSceneMsg'), cancelable: true, onCancel: () => { abortController.abort() } }) const size = glbBlob.size / 1024 / 1024 const maxSize = maxUploadSize if (size > maxSize) { throw new Error(i18n.t('editor:errors.sceneTooLarge', { size: size.toFixed(2), maxSize })) } showDialog(ProgressDialog, { title: i18n.t('editor:publishingScene'), message: i18n.t('editor:uploadingThumbnailMsg'), cancelable: true, onCancel: () => { abortController.abort() } }) // Upload the screenshot file const { file_id: screenshotId, meta: { access_token: screenshotToken } } = (await upload(screenshotBlob, undefined, abortController.signal)) as any if (signal.aborted) { const error = new Error(i18n.t('editor:errors.publishProjectAborted')) error['aborted'] = true throw error } const { file_id: glbId, meta: { access_token: glbToken } }: any = await upload(glbBlob, (uploadProgress) => { showDialog( ProgressDialog, { title: i18n.t('editor:publishingScene'), message: i18n.t('editor:uploadingSceneMsg', { percentage: Math.floor(uploadProgress * 100) }), onCancel: () => { abortController.abort() } }, abortController.signal ) }) if (signal.aborted) { const error = new Error(i18n.t('editor:errors.publishProjectAborted')) error['aborted'] = true throw error } const { file_id: sceneFileId, meta: { access_token: sceneFileToken } } = (await upload(sceneBlob, undefined, abortController.signal)) as any if (signal.aborted) { const error = new Error(i18n.t('editor:errors.publishProjectAborted')) error['aborted'] = true throw error } const sceneParams = { screenshot_file_id: screenshotId, screenshot_file_token: screenshotToken, model_file_id: glbId, model_file_token: glbToken, scene_file_id: sceneFileId, scene_file_token: sceneFileToken, name: publishParams.name } try { project = await client.service(`/publish-scene/${project.scene_id}`).create({ scene: sceneParams }) } catch (error) { throw new Error(error) } showDialog(PublishedSceneDialog, { sceneName: sceneParams.name, screenshotUrl, sceneUrl: getSceneUrl(project.scene.scene_id), onConfirm: () => { hideDialog() } }) } finally { if (screenshotUrl) { URL.revokeObjectURL(screenshotUrl) } } return project } /** * StyledEditorContainer component is used as root element of new project page. * On this page we have an editor to create a new or modifing an existing project. * * @author Robert Long * @type {Styled component} */ const StyledEditorContainer = (styled as any).div` display: flex; flex: 1; flex-direction: column; height: 100%; width: 100%; position: fixed; ` /** *Styled component used as workspace container. * * @author Robert Long * @type {type} */ const WorkspaceContainer = (styled as any).div` display: flex; flex: 1; overflow: hidden; margin: 0px; ` /** *Styled component used as dock container. * * @author Hanzla Mateen * @type {type} */ const DockContainer = (styled as any).div` .dock-panel { background: transparent; pointer-events: auto; opacity: 0.8; border: none; } .dock-panel:first-child { position: relative; z-index: 99; } .dock-panel[data-dockid="+3"] { visibility: hidden; pointer-events: none; } .dock-divider { pointer-events: auto; } .dock { border-radius: 4px; background: #282C31; } .dock-top .dock-bar { font-size: 12px; border-bottom: 1px solid rgba(0,0,0,0.2); background: #282C31; } .dock-tab { background: #282C31; border-bottom: none; } .dock-tab:hover, .dock-tab-active, .dock-tab-active:hover { color: #ffffff; } .dock-ink-bar { background-color: #ffffff; } ` type EditorContainerProps = { t: any match: any location: any history: any } type EditorContainerState = { project: SceneDetailInterface parentSceneId: null // templateUrl: any; settingsContext: any // error: null; creatingProject: any DialogComponent: any pathParams: Map<string, unknown> queryParams: Map<string, string> dialogProps: {} modified: boolean } /** * EditorContainer class used for creating container for Editor * * @author Robert Long */ class EditorContainer extends Component<EditorContainerProps, EditorContainerState> { constructor(props) { super(props) let settings = defaultSettings const storedSettings = localStorage.getItem('editor-settings') if (storedSettings) { settings = JSON.parse(storedSettings) } ProjectManager.buildProjectManager(settings) CommandManager.buildCommandManager() SceneManager.buildSceneManager() ControlManager.buildControlManager() NodeManager.buildNodeManager(SceneManager.instance.scene) SourceManager.buildSourceManager() CacheManager.init() registerPredefinedNodes() registerPredefinedSources() // ProjectManager.instance.initializeFeathersClient(getToken()) CommandManager.instance.addListener(EditorEvents.RENDERER_INITIALIZED.toString(), this.setDebuginfo) CommandManager.instance.addListener(EditorEvents.PROJECT_LOADED.toString(), this.onProjectLoaded) CommandManager.instance.addListener(EditorEvents.ERROR.toString(), this.onEditorError) CommandManager.instance.addListener(EditorEvents.SAVE_PROJECT.toString(), this.onSaveProject) this.state = { // error: null, project: null, parentSceneId: null, pathParams: new Map(Object.entries(props.match.params)), queryParams: new Map(new URLSearchParams(window.location.search).entries()), settingsContext: { settings, updateSetting: this.updateSetting }, creatingProject: null, // templateUrl: defaultTemplateUrl, DialogComponent: null, dialogProps: {}, modified: false } this.t = this.props.t } componentDidMount() { if (accessLocationState().locations.updateNeeded.value === true) { LocationService.fetchAdminLocations() } if (accessSceneState().scenes.updateNeeded.value === true) { SceneService.fetchAdminScenes() } if (accessLocationState().locationTypes.updateNeeded.value === true) { LocationService.fetchLocationTypes() } const pathParams = this.state.pathParams const queryParams = this.state.queryParams const projectId = pathParams.get('projectId') if (projectId === 'new') { if (queryParams.has('template')) { this.loadProjectTemplate(queryParams.get('template')) } else if (queryParams.has('sceneId')) { this.loadScene(queryParams.get('sceneId')) } else { this.loadProjectTemplate(defaultTemplateUrl) } } else if (projectId === 'tutorial') { this.loadProjectTemplate(tutorialTemplateUrl) } else { this.loadProject(projectId) } } componentDidUpdate(prevProps: EditorContainerProps) { if (this.props.location.pathname !== prevProps.location.pathname && !this.state.creatingProject) { // const { projectId } = this.props.match.params; const prevProjectId = prevProps.match.params.projectId const queryParams = new Map(new URLSearchParams(window.location.search).entries()) this.setState({ queryParams }) const pathParams = this.state.pathParams const projectId = pathParams.get('projectId') let templateUrl = null if (projectId === 'new' && !queryParams.has('sceneId')) { templateUrl = queryParams.get('template') || defaultTemplateUrl } else if (projectId === 'tutorial') { templateUrl = tutorialTemplateUrl } if (projectId === 'new' || projectId === 'tutorial') { this.loadProjectTemplate(templateUrl) } else if (prevProjectId !== 'tutorial' && prevProjectId !== 'new') { this.loadProject(projectId) } } } componentWillUnmount() { CommandManager.instance.removeListener(EditorEvents.SAVE_PROJECT.toString(), this.onSaveProject) CommandManager.instance.removeListener(EditorEvents.ERROR.toString(), this.onEditorError) CommandManager.instance.removeListener(EditorEvents.PROJECT_LOADED.toString(), this.onProjectLoaded) ProjectManager.instance.dispose() } t: Function async loadProjectTemplate(templateFile) { this.setState({ project: null, parentSceneId: null // templateUrl }) this.showDialog(ProgressDialog, { title: this.t('editor:loading'), // "Loading Project", message: this.t('editor:loadingMsg') }) try { if (templateFile.metadata) { delete templateFile.metadata.sceneUrl delete templateFile.metadata.sceneId } await ProjectManager.instance.loadProject(templateFile) this.hideDialog() } catch (error) { console.error(error) this.showDialog(ErrorDialog, { title: this.t('editor:loadingError'), message: error.message || this.t('editor:loadingErrorMsg'), error }) } } async loadScene(sceneId) { this.setState({ project: null, parentSceneId: sceneId // templateUrl: null, }) this.showDialog(ProgressDialog, { title: this.t('editor:loading'), message: this.t('editor:loadingMsg') }) try { const scene: any = await getScene(sceneId) console.warn('loadScene:scene', scene) const projectFile = scene.data await ProjectManager.instance.loadProject(projectFile) this.hideDialog() } catch (error) { console.error(error) this.showDialog(ErrorDialog, { title: this.t('editor:loadingError'), message: error.message || this.t('editor:loadingErrorMsg'), error }) } } async importProject(projectFile) { const project = this.state.project this.setState({ project: null, parentSceneId: null // templateUrl: null, }) this.showDialog(ProgressDialog, { title: this.t('editor:loading'), message: this.t('editor:loadingMsg') }) try { await ProjectManager.instance.loadProject(projectFile) SceneManager.instance.sceneModified = true this.updateModifiedState() this.hideDialog() } catch (error) { console.error(error) this.showDialog(ErrorDialog, { title: this.t('editor:loadingError'), message: error.message || this.t('editor:loadingErrorMsg'), error }) } finally { if (project) { this.setState({ project }) } } } async loadProject(projectId) { this.setState({ project: null, parentSceneId: null }) this.showDialog(ProgressDialog, { title: this.t('editor:loading'), message: this.t('editor:loadingMsg') }) let project: SceneDetailInterface try { project = await getScene(projectId) ProjectManager.instance.ownedFileIds = JSON.parse(project.ownedFileIds) globalThis.currentProjectID = project.scene_id const projectIndex = project.scene_url.split('collection/')[1] const projectFile = await client.service(`collection`).get(projectIndex, { headers: { 'content-type': 'application/json' } }) await ProjectManager.instance.loadProject(projectFile) this.hideDialog() } catch (error) { console.error(error) this.showDialog(ErrorDialog, { title: this.t('editor:loadingError'), message: error.message || this.t('editor:loadingErrorMsg'), error }) } finally { if (project) { this.setState({ project }) } } } updateModifiedState(then?) { const nextModified = SceneManager.instance.sceneModified && !this.state.creatingProject if (nextModified !== this.state.modified) { this.setState({ modified: nextModified }, then) } else if (then) { then() } } generateToolbarMenu = () => { return [ { name: this.t('editor:menubar.newProject'), action: this.onNewProject }, { name: this.t('editor:menubar.saveProject'), hotkey: `${cmdOrCtrlString} + S`, action: this.onSaveProject }, { name: this.t('editor:menubar.saveAs'), action: this.onDuplicateProject }, { name: this.t('editor:menubar.exportGLB'), // TODO: Disabled temporarily till workers are working action: this.onExportProject }, { name: this.t('editor:menubar.importProject'), action: this.onImportLegacyProject }, { name: this.t('editor:menubar.exportProject'), action: this.onExportLegacyProject }, { name: this.t('editor:menubar.quit'), action: this.onOpenProject } ] } setDebuginfo = () => { const gl = SceneManager.instance.renderer.webglRenderer.getContext() const debugInfo = gl.getExtension('WEBGL_debug_renderer_info') let webglVendor = 'Unknown' let webglRenderer = 'Unknown' if (debugInfo) { webglVendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) webglRenderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) } CommandManager.instance.removeListener(EditorEvents.RENDERER_INITIALIZED.toString(), this.setDebuginfo) } /** * Dialog Context */ showDialog = (DialogComponent, dialogProps = {}) => { this.setState({ DialogComponent, dialogProps }) } hideDialog = () => { this.setState({ DialogComponent: null, dialogProps: {} }) } dialogContext = { showDialog: this.showDialog, hideDialog: this.hideDialog } /** * Scene Event Handlers */ onEditorError = (error) => { if (error['aborted']) { this.hideDialog() return } console.error(error) this.showDialog(ErrorDialog, { title: error.title || this.t('editor:error'), message: error.message || this.t('editor:errorMsg'), error }) } onProjectLoaded = () => { this.updateModifiedState() } updateSetting(key, value) { const settings = Object.assign(this.state.settingsContext.settings, { [key]: value }) localStorage.setItem('editor-settings', JSON.stringify(settings)) ProjectManager.instance.settings = settings CommandManager.instance.emitEvent(EditorEvents.SETTINGS_CHANGED) this.setState({ settingsContext: { ...this.state.settingsContext, settings } }) } /** * Project Actions */ createProject = async () => { const { parentSceneId } = this.state as any this.showDialog(ProgressDialog, { title: this.t('editor:generateScreenshot'), message: this.t('editor:generateScreenshotMsg') }) // Wait for 5ms so that the ProgressDialog shows up. await new Promise((resolve) => setTimeout(resolve, 5)) const blob = await SceneManager.instance.takeScreenshot(512, 320) const result: any = (await new Promise((resolve) => { this.showDialog(SaveNewProjectDialog, { thumbnailUrl: URL.createObjectURL(blob), initialName: SceneManager.instance.scene.name, onConfirm: resolve, onCancel: resolve }) })) as any if (!result) { this.hideDialog() return null } const abortController = new AbortController() this.showDialog(ProgressDialog, { title: this.t('editor:saving'), message: this.t('editor:savingMsg'), cancelable: true, onCancel: () => { abortController.abort() this.hideDialog() } }) CommandManager.instance.executeCommand(EditorCommands.MODIFY_PROPERTY, SceneManager.instance.scene, { properties: { name: result.name } }) SceneManager.instance.scene.setMetadata({ name: result.name }) const project = await createScene( SceneManager.instance.scene, parentSceneId, blob, abortController.signal, this.showDialog, this.hideDialog ) SceneManager.instance.sceneModified = false globalThis.currentProjectID = project.scene_id const pathParams = this.state.pathParams pathParams.set('projectId', project.scene_id) this.updateModifiedState(() => { this.setState({ creatingProject: true, project, pathParams }, () => { this.props.history.replace(`/editor/${project.scene_id}`) this.setState({ creatingProject: false }) }) }) return project } onNewProject = async () => { this.props.history.push('/editor/new') } onOpenProject = () => { this.props.history.push('/editor') } onDuplicateProject = async () => { const abortController = new AbortController() this.showDialog(ProgressDialog, { title: this.t('editor:duplicating'), message: this.t('editor:duplicatingMsg'), cancelable: true, onCancel: () => { abortController.abort() this.hideDialog() } }) await new Promise((resolve) => setTimeout(resolve, 5)) try { const newProject = await this.createProject() SceneManager.instance.sceneModified = false this.updateModifiedState() this.hideDialog() const pathParams = this.state.pathParams pathParams.set('projectId', newProject.scene_id) this.setState({ pathParams: pathParams }) } catch (error) { console.error(error) this.showDialog(ErrorDialog, { title: this.t('editor:savingError'), message: error.message || this.t('editor:savingErrorMsg') }) } } onExportProject = async () => { const options = await new Promise((resolve) => { this.showDialog(ExportProjectDialog, { defaultOptions: Object.assign({}, SceneManager.DefaultExportOptions), onConfirm: resolve, onCancel: resolve }) }) if (!options) { this.hideDialog() return } const abortController = new AbortController() this.showDialog(ProgressDialog, { title: this.t('editor:exporting'), message: this.t('editor:exportingMsg'), cancelable: true, onCancel: () => abortController.abort() }) try { const { glbBlob } = await SceneManager.instance.exportScene(options) this.hideDialog() const el = document.createElement('a') el.download = SceneManager.instance.scene.name + '.glb' el.href = URL.createObjectURL(glbBlob) document.body.appendChild(el) el.click() document.body.removeChild(el) } catch (error) { if (error['aborted']) { this.hideDialog() return } console.error(error) this.showDialog(ErrorDialog, { title: this.t('editor:exportingError'), message: error.message || this.t('editor:exportingErrorMsg'), error }) } } onImportLegacyProject = async () => { const confirm = await new Promise((resolve) => { this.showDialog(ConfirmDialog, { title: this.t('editor:importLegacy'), message: this.t('editor:importLegacyMsg'), onConfirm: () => resolve(true), onCancel: () => resolve(false) }) }) this.hideDialog() if (!confirm) return const el = document.createElement('input') el.type = 'file' el.accept = '.world' el.style.display = 'none' el.onchange = () => { if (el.files.length > 0) { const fileReader: any = new FileReader() fileReader.onload = () => { const json = JSON.parse((fileReader as any).result) if (json.metadata) { delete json.metadata.sceneUrl delete json.metadata.sceneId } this.importProject(json) } fileReader.readAsText(el.files[0]) } } el.click() } onExportLegacyProject = async () => { const { project } = this.state const projectFile = await SceneManager.instance.scene.serialize(project.scene_id) if (projectFile.metadata) { delete projectFile.metadata.sceneUrl delete projectFile.metadata.sceneId } const projectJson = JSON.stringify(projectFile) const projectBlob = new Blob([projectJson]) const el = document.createElement('a') const fileName = SceneManager.instance.scene.name.toLowerCase().replace(/\s+/g, '-') el.download = fileName + '.world' el.href = URL.createObjectURL(projectBlob) document.body.appendChild(el) el.click() document.body.removeChild(el) } onSaveProject = async () => { const abortController = new AbortController() this.showDialog(ProgressDialog, { title: this.t('editor:saving'), message: this.t('editor:savingMsg'), cancelable: true, onCancel: () => { abortController.abort() this.hideDialog() } }) // Wait for 5ms so that the ProgressDialog shows up. await new Promise((resolve) => setTimeout(resolve, 5)) try { const { project } = this.state if (project) { const newProject = await saveScene(project.scene_id, abortController.signal) this.setState({ project: newProject }) const pathParams = this.state.pathParams pathParams.set('projectId', newProject.scene_id) this.setState({ pathParams: pathParams }) } else { await this.createProject() } SceneManager.instance.sceneModified = false this.updateModifiedState() this.hideDialog() } catch (error) { console.error(error) this.showDialog(ErrorDialog, { title: this.t('editor:savingError'), message: error.message || this.t('editor:savingErrorMsg') }) } } // Currently doesn't work onPublishProject = async (): Promise<void> => { try { let project = this.state.project if (!project) { project = await this.createProject() } if (!project) { return } project = await publishProject(project, this.showDialog, this.hideDialog) if (!project) { return } SceneManager.instance.sceneModified = false this.updateModifiedState() this.setState({ project }) } catch (error) { if (error['abortedsettingsContext']) { this.hideDialog() return } console.error(error) this.showDialog(ErrorDialog, { title: this.t('editor:publishingError'), message: error.message || this.t('editor:publishingErrorMsg'), error }) } } getSceneId() { const { project } = this.state as any return ( (project && project.scene && project.scene.scene_id) || (SceneManager.instance.scene && SceneManager.instance.scene.metadata && SceneManager.instance.scene.metadata.sceneId) ) } onOpenScene = () => { const sceneId = this.getSceneId() if (sceneId) { const url = getSceneUrl(sceneId) window.open(url) } } render() { const { DialogComponent, dialogProps, settingsContext } = this.state const toolbarMenu = this.generateToolbarMenu() // const isPublishedScene = !!this.getSceneId() // const locations = useLocationState().locations.locations.value // let assigneeScene // if (locations) { // locations.forEach((element) => { // if (element.sceneId === this.state.queryParams.get('projectId')) { // assigneeScene = element // } // }) // } let defaultLayout = { dockbox: { mode: 'horizontal' as DockMode, children: [ { mode: 'vertical' as DockMode, size: 8, children: [ { tabs: [{ id: 'viewPanel', title: 'Viewport', content: <div /> }], size: 1 } ] }, { mode: 'vertical' as DockMode, size: 2, children: [ { tabs: [ { id: 'hierarchyPanel', title: ( <PanelDragContainer> <PanelIcon as={ProjectDiagram} size={12} /> <PanelTitle>Hierarchy</PanelTitle> </PanelDragContainer> ), content: <HierarchyPanelContainer /> } ] }, { tabs: [ { id: 'propertiesPanel', title: ( <PanelDragContainer> <PanelIcon as={SlidersH} size={12} /> <PanelTitle>Properties</PanelTitle> </PanelDragContainer> ), content: <PropertiesPanelContainer /> }, { id: 'assetsPanel', title: 'Elements', content: <AssetsPanel /> }, { id: 'fileBrowserPanel', title: ( <PanelDragContainer> <PanelIcon as={Archive} size={12} /> <PanelTitle>File Browser</PanelTitle> </PanelDragContainer> ), content: <FileBrowserPanel /> } ] } ] } ] } } return ( <StyledEditorContainer id="editor-container"> <SettingsContextProvider value={settingsContext}> <DialogContextProvider value={this.dialogContext}> <DndProvider backend={HTML5Backend}> <DragLayer /> {toolbarMenu && <ToolBar menu={toolbarMenu} />} <WorkspaceContainer> <ViewportPanelContainer /> <DockContainer> <DockLayout defaultLayout={defaultLayout} style={{ pointerEvents: 'none', position: 'absolute', left: 5, top: 55, right: 5, bottom: 5 }} /> </DockContainer> </WorkspaceContainer> <Modal ariaHideApp={false} isOpen={!!DialogComponent} onRequestClose={this.hideDialog} shouldCloseOnOverlayClick={false} className="Modal" overlayClassName="Overlay" > {DialogComponent && ( <DialogComponent onConfirm={this.hideDialog} onCancel={this.hideDialog} {...dialogProps} /> )} </Modal> </DndProvider> </DialogContextProvider> </SettingsContextProvider> </StyledEditorContainer> ) } } export default withTranslation()(withRouter(EditorContainer))
the_stack
import { TiledeskAuthService } from './../../../../chat21-core/providers/tiledesk/tiledesk-auth.service'; import { TiledeskService } from '../../../services/tiledesk/tiledesk.service'; import { Component, OnInit, Input, ChangeDetectorRef } from '@angular/core'; // models import { UserModel } from 'src/chat21-core/models/user'; import { ConversationModel } from 'src/chat21-core/models/conversation'; import { ArchivedConversationsHandlerService } from 'src/chat21-core/providers/abstract/archivedconversations-handler.service'; import { ConversationsHandlerService } from 'src/chat21-core/providers/abstract/conversations-handler.service'; import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; import { ContactsService } from 'src/app/services/contacts/contacts.service'; import { AppConfigProvider } from '../../../services/app-config'; import { setChannelType } from '../../../../chat21-core/utils/utils'; import { TYPE_SUPPORT_GROUP, TYPE_DIRECT, TYPE_GROUP } from '../../../../chat21-core/utils/constants'; import { DomSanitizer } from '@angular/platform-browser'; import { LoggerService } from 'src/chat21-core/providers/abstract/logger.service'; import { LoggerInstance } from 'src/chat21-core/providers/logger/loggerInstance'; @Component({ selector: 'app-info-content', templateUrl: './info-content.component.html', styleUrls: ['./info-content.component.scss'], }) export class InfoContentComponent implements OnInit { @Input() openInfoConversation: boolean; @Input() translationMap: Map<string, string>; // @Input() member: UserModel; @Input() loggedUser: UserModel @Input() tenant: string @Input() groupDetail: any public member: UserModel; public urlConversation: any; // public loggedUser: UserModel; // private tenant: string; public conversationWith: string; public conversationWithFullname: string; public conv_type: string; private channelType: string; public urlConversationSupportGroup: any; public conversations: Array<ConversationModel> = []; public conversationSelected: any; public panelType: string; public project_id: string private logger: LoggerService = LoggerInstance.getInstance(); public IS_GROUP_PANEL: boolean = false constructor( public archivedConversationsHandlerService: ArchivedConversationsHandlerService, public conversationsHandlerService: ConversationsHandlerService, public tiledeskAuthService: TiledeskAuthService, private route: ActivatedRoute, public contactsService: ContactsService, public appConfigProvider: AppConfigProvider, private sanitizer: DomSanitizer, public tiledeskService: TiledeskService ) { this.logger.log('[INFO-CONTENT-COMP] HELLO (CONSTUCTOR) !!!!!'); // this.loggedUser = this.authService.getCurrentUser(); // this.logger.log('INFO-CONTENT-COMP loggedUser: ', this.loggedUser); const appconfig = appConfigProvider.getConfig() // this.tenant = appconfig.tenant; this.tenant = appconfig.firebaseConfig.tenant; this.logger.log('[INFO-CONTENT-COMP] appconfig firebaseConfig tenant ', this.tenant); this.route.paramMap.subscribe(params => { this.logger.log('[INFO-CONTENT-COMP] initialize params: ', params); this.conversationWith = params.get('IDConv'); this.logger.log('[INFO-CONTENT-COMP] - paramMap.subscribe conversationWith: ', this.conversationWith); this.conversationWithFullname = params.get('FullNameConv'); this.conv_type = params.get('Convtype'); const conversationWith_segments = this.conversationWith.split('-'); // Removes the last element of the array if is = to the separator if (conversationWith_segments[conversationWith_segments.length - 1] === '') { conversationWith_segments.pop(); } if (conversationWith_segments.length === 4) { const lastArrayElement = conversationWith_segments[conversationWith_segments.length - 1] this.logger.log('[INFO-CONTENT-COMP] - paramMap.subscribe lastArrayElement ', lastArrayElement); this.logger.log('[INFO-CONTENT-COMP] - paramMap.subscribe lastArrayElement length', lastArrayElement.length); if (lastArrayElement.length !== 32) { conversationWith_segments.pop(); } } this.logger.log('[INFO-CONTENT-COMP] - paramMap.subscribe conversationWith_segments: ', conversationWith_segments); if (this.conversationWith.startsWith("support-group")) { if (conversationWith_segments.length === 4) { this.project_id = conversationWith_segments[2]; this.selectInfoContentTypeInfoSupportGroup(); } else { this.getProjectIdByConversationWith(this.conversationWith) } } else { this.selectInfoContentTypeDirectAndGroup(this.conversationWith); } // this.project_id = this.groupDetail['attributes']['projectId'] }); } getProjectIdByConversationWith(conversationWith: string) { const tiledeskToken = this.tiledeskAuthService.getTiledeskToken(); this.tiledeskService.getProjectIdByConvRecipient(tiledeskToken, conversationWith).subscribe(res => { this.logger.log('[INFO-CONTENT-COMP] - GET PROJECTID BY CONV RECIPIENT RES', res); if (res) { this.project_id = res.id_project this.logger.log('[INFO-CONTENT-COMP] - GET PROJECTID BY CONV RECIPIENT this.project_id', this.project_id); } }, (error) => { this.logger.error('[INFO-CONTENT-COMP] - GET PROJECTID BY CONV RECIPIENT - ERROR ', error); }, () => { this.logger.log('[INFO-CONTENT-COMP] - GET PROJECTID BY CONV RECIPIENT * COMPLETE *'); this.selectInfoContentTypeInfoSupportGroup(); }); } ngOnInit() { this.logger.log('>>> N INFO-CONTENT-COMP CALLING ngOnInit'); this.logger.log('[INFO-CONTENT-COMP] - ngOnInit - Logged user', this.loggedUser); this.logger.log('[INFO-CONTENT-COMP] - ngOnInit - Tenant', this.tenant); this.logger.log('[INFO-CONTENT-COMP] - ngOnInit - conversationWith', this.conversationWith); this.logger.log('[INFO-CONTENT-COMP] - ngOnInit - conversationWithFullname', this.conversationWithFullname); this.logger.log('[INFO-CONTENT-COMP] - ngOnInit - conv_type', this.conv_type); this.logger.log('[INFO-CONTENT-COMP] - ngOnInit - project_id', this.project_id); // this.initConversationsHandler(); // nk // this.selectInfoContentTypeComponent(); // nk } ngAfterViewInit() { this.logger.log('[INFO-CONTENT-COMP] - ngAfterViewInit'); } ngOnDestroy() { this.logger.log('[INFO-CONTENT-COMP] - ngOnDestroy'); } selectInfoContentTypeInfoSupportGroup() { this.panelType = '' this.logger.log('[INFO-CONTENT-COMP] - selectInfoContentTypeComponent - SUPPORT_GROUP - conversationWith start with "support-group" ', this.conversationWith.startsWith("support-group")); this.urlConversationSupportGroup = ''; this.setInfoSupportGroup(); this.panelType = 'support-group-panel'; this.IS_GROUP_PANEL = false; this.logger.log('[INFO-CONTENT-COMP] - panelType IS_GROUP_PANEL: ', this.IS_GROUP_PANEL); this.logger.log('[INFO-CONTENT-COMP] - panelType: ', this.panelType); } // --------------------------------------------------- // START SET INFO COMPONENT // --------------------------------------------------- selectInfoContentTypeDirectAndGroup(conversationWith) { this.logger.log('[INFO-CONTENT-COMP] - selectInfoContentTypeComponent conversationWith: ', this.conversationWith); if (conversationWith) { this.panelType = 'direct-panel' // if (conversationWith.startsWith("support-group")) { // this.panelType = '' // this.logger.log('[INFO-CONTENT-COMP] - selectInfoContentTypeComponent - SUPPORT_GROUP - conversationWith start with "support-group" ', this.conversationWith.startsWith("support-group")); // this.urlConversationSupportGroup = ''; // this.setInfoSupportGroup(); // this.panelType = 'support-group-panel'; // this.IS_GROUP_PANEL = false; // this.logger.log('[INFO-CONTENT-COMP] - panelType IS_GROUP_PANEL: ', this.IS_GROUP_PANEL); // this.logger.log('[INFO-CONTENT-COMP] - panelType: ', this.panelType); // } else if (conversationWith.startsWith("group-")) { this.panelType = '' this.logger.log('[INFO-CONTENT-COMP] - selectInfoContentTypeComponent - GROUP - conversationWith start with "group-" ', this.conversationWith.startsWith("group-")); this.setInfoGroup(); this.panelType = 'group-panel'; this.IS_GROUP_PANEL = true; this.logger.log('[INFO-CONTENT-COMP] - panelType IS_GROUP_PANEL: ', this.IS_GROUP_PANEL); this.logger.log('[INFO-CONTENT-COMP] - panelType: ', this.panelType); } else { this.panelType = '' this.logger.log('[INFO-CONTENT-COMP] - selectInfoContentTypeComponent - DIRECT - conversationWith NOT START with "group-" NOR with "support-group" ',); this.setInfoDirect(); this.panelType = 'direct-panel'; this.IS_GROUP_PANEL = false; this.logger.log('[INFO-CONTENT-COMP] - panelType IS_GROUP_PANEL: ', this.IS_GROUP_PANEL); this.logger.log('[INFO-CONTENT-COMP] - panelType: ', this.panelType); } } } // private deleteHandler(): void { // if ( this.panelType !== 'group-panel') { // this.childExists = false; // this.logger.log('INFO-CONTENT-COMP - childExists panelType ', this.panelType); // this.logger.log('INFO-CONTENT-COMP - childExists ', this.childExists); // } else if (this.panelType === 'group-panel'){ // this.childExists = true; // this.logger.log('INFO-CONTENT-COMP - childExists panelType ', this.panelType); // this.logger.log('INFO-CONTENT-COMP - childExists ', this.childExists); // } // } // --------------------------------------------------- // @ setInfoDirect // --------------------------------------------------- setInfoDirect() { this.logger.log('[INFO-CONTENT-COMP] - setInfoDirect ', this.conversationWith); this.member = null; const tiledeskToken = this.tiledeskAuthService.getTiledeskToken(); this.contactsService.loadContactDetail(tiledeskToken, this.conversationWith) .subscribe(res => { this.logger.log('[INFO-CONTENT-COMP] - setInfoDirect loadContactDetail RES', res); this.member = res this.logger.log('[INFO-CONTENT-COMP] - setInfoDirect member', this.member); }, (error) => { this.logger.error('[INFO-CONTENT-COMP] - setInfoDirect loadContactDetail - ERROR ', error); }, () => { this.logger.log('I[INFO-CONTENT-COMP] - setInfoDirect loadContactDetail * COMPLETE *'); }); } // --------------------------------------------------- // @ setInfoGroup // --------------------------------------------------- setInfoGroup() { this.logger.log('[INFO-CONTENT-COMP] - setInfoGroup groupDetail ', this.groupDetail); } // --------------------------------------------------- // @ setInfoSupportGroup // --------------------------------------------------- setInfoSupportGroup() { this.logger.log('[INFO-CONTENT-COMP] setInfoSupportGroup HERE YES '); const tiledeskToken = this.tiledeskAuthService.getTiledeskToken(); const DASHBOARD_URL = this.appConfigProvider.getConfig().dashboardUrl; this.logger.log('[INFO-CONTENT-COMP] setInfoSupportGroup projectID ', this.project_id); if (this.conversationWith) { let urlPanel = DASHBOARD_URL + '#/project/' + this.project_id + '/request-for-panel/' + this.conversationWith; urlPanel += '?token=' + tiledeskToken; const urlConversationTEMP = this.sanitizer.bypassSecurityTrustResourceUrl(urlPanel); this.urlConversationSupportGroup = urlConversationTEMP; this.logger.log('[INFO-CONTENT-COMP] setInfoSupportGroup urlConversationSupportGroup ', this.urlConversationSupportGroup) } else { this.urlConversationSupportGroup = this.sanitizer.bypassSecurityTrustResourceUrl(DASHBOARD_URL); } this.logger.log('[INFO-CONTENT-COMP] urlConversationSupportGroup:: ', this.urlConversationSupportGroup, this.conversationSelected); } } // import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; // import { DomSanitizer} from '@angular/platform-browser'; // // services // import { AppConfigProvider } from '../../services/app-config'; // import { UserService } from '../../services/user.service'; // import { PresenceService } from '../../services/presence.service'; // import { EventsService } from '../../services/events-service'; // import { CustomTranslateService } from 'src/chat21-core/custom-translate.service'; // // models // import { UserModel } from '../../models/user'; // // utils // import { avatarPlaceholder, getColorBck, isInArray, setLastDateWithLabels } from '../../utils/utils'; // @Component({ // selector: 'app-conversation-info', // templateUrl: './conversation-info.page.html', // styleUrls: ['./conversation-info.page.scss'], // }) // export class ConversationInfoPage implements OnInit { // // ========= begin:: Input/Output values ============// // // @Output() eventClose = new EventEmitter(); // @Input() attributes: any = {}; // @Input() channelType: string; // @Input() conversationWith: string; // @Input() openInfoConversation: boolean; // // ========= end:: Input/Output values ============// // private DASHBOARD_URL: string; // private FIREBASESTORAGE_BASE_URL_IMAGE: string; // private urlStorageBucket: string; // private projectID: string; // private subscriptions = []; // public urlConversation: any; // public member: UserModel; // public translationMap: Map<string, string>; // constructor( // private appConfig: AppConfigProvider, // private sanitizer: DomSanitizer, // private userService: UserService, // private presenceService: PresenceService, // private events: EventsService, // private translateService: CustomTranslateService, // ) { // this.DASHBOARD_URL = this.appConfig.getConfig().dashboardUrl; // this.FIREBASESTORAGE_BASE_URL_IMAGE = this.appConfig.getConfig().FIREBASESTORAGE_BASE_URL_IMAGE; // this.urlStorageBucket = this.appConfig.getConfig().firebaseConfig.storageBucket + '/o/profiles%2F'; // } // public translations() { // const keys = [ // 'LABEL_TODAY', // 'LABEL_TOMORROW', // 'LABEL_TO', // 'LABEL_LAST_ACCESS', // 'ARRAY_DAYS', // 'LABEL_ACTIVE_NOW' // ]; // this.translationMap = this.translateService.translateLanguage(keys); // } // /** // * // */ // setSubscriptions() { // this.logger.log('setSubscriptions'); // this.presenceService.userIsOnline(this.conversationWith); // this.presenceService.lastOnlineForUser(this.conversationWith); // let keySubscription = ''; // keySubscription = 'is-online-' + this.conversationWith; // if (!isInArray(keySubscription, this.subscriptions)) { // this.subscriptions.push(keySubscription); // this.events.subscribe(keySubscription, this.userIsOnLine); // } // keySubscription = 'last-connection-date-' + this.conversationWith; // if (!isInArray(keySubscription, this.subscriptions)) { // this.subscriptions.push(keySubscription); // this.events.subscribe(keySubscription, this.userLastConnection); // } // } // /** // * // */ // userIsOnLine = (userId: string, isOnline: boolean) => { // this.logger.log('************** userIsOnLine', userId, isOnline); // this.member.online = isOnline; // } // /** // * // */ // userLastConnection = (userId: string, timestamp: string) => { // this.logger.log('************** userLastConnection', userId, timestamp); // if (timestamp && timestamp !== '') { // const lastConnectionDate = setLastDateWithLabels(this.translationMap, timestamp); // this.member.lastConnection = lastConnectionDate; // } // }
the_stack
import type { Event } from 'electron' import { Vue, Component } from 'vue-property-decorator' import TabSmall from '../../vue/component/TabSmall.vue' import TaskLoading from '../../vue/component/TaskLoading.vue' import InputText from '../../vue/component/InputText.vue' import { unpackTexture2D } from './unpack-texture-2d' // import { generateObjectId } from '../common/object-id' // import { MasterData } from '../main/on-master-read' import getPath from '../common/get-path' import { getLyrics, getScoreDifficulties, showOpenDialog, showSaveDialog } from './ipc' import type { DownloadPromise } from 'mishiro-core' import configurer from './config' import type { MishiroConfig } from '../main/config' import type { Live, BGM } from './back/resolve-audio-manifest' import { setAudioList } from './store' import { readAcb } from './audio' import { error } from './log' const fs = window.node.fs const path = window.node.path const os = window.node.os const iconvLite = window.node.iconvLite const { shell, ipcRenderer, clipboard } = window.node.electron const { scoreDir, bgmDir, bgmAsarDir, liveDir, jacketDir } = getPath function filterTime (second: number, float = false): string { let min: string | number = Math.floor(second / 60) let sec: string | number = Math.floor(second % 60) if (min < 10) { min = `0${min}` } if (sec < 10) { sec = `0${sec}` } if (float) { const floatPart = String(second).split('.')[1] return floatPart ? `${min}:${sec}.${('0' + floatPart).slice(-2)}` : `${min}:${sec}.00` } return `${min}:${sec}` } @Component({ components: { TaskLoading, InputText, TabSmall }, filters: { time (second: number) { return filterTime(second, false) } } }) export default class extends Vue { dler = new this.core.Downloader() audioDownloadPromise: DownloadPromise<string> | null = null scoreDownloader = new this.core.Downloader() jacketDownloader = new this.core.Downloader() queryString: string = '' total: number = 0 current: number = 0 text: string = '' activeAudio: BGM | Live = {} as any duration: number = 100 currentTime: number = 0 isGameRunning: boolean = false allLyrics: Array<{ time: number, lyrics: string, size: any}> = [] lyrics: Array<{ time: number, lyrics: string, size: any}> = [] jacketSrc: string = '' audioTypeTabs = { bgm: 'BGM', live: 'LIVE' } currentAudioType = 'BGM' audioDownloading = false audioExporting = false selectedAudios: Array<BGM | Live> = [] downloadingTasks: Array<BGM | Live> = [] lastClickedAudio: BGM | Live | null = null controlDown = false shiftDown = false // @Prop({ default: () => ({}) }) master: MasterData get liveManifest (): Live[] { return this.$store.state.master.liveManifest || [] // return this.master.liveManifest ? this.master.liveManifest : [] } get bgmManifest (): BGM[] { return this.$store.state.master.bgmManifest || [] // return this.master.bgmManifest ? this.master.bgmManifest : [] } get wavProgress (): boolean { return this.core.config.getProgressCallback() } get audioListData (): BGM[] | Live[] { return this.$store.state.audioListData || [] } created (): void { const proxy = configurer.get('proxy') ?? '' this.dler.setProxy(proxy) this.scoreDownloader.setProxy(proxy) this.jacketDownloader.setProxy(proxy) this.event.$on('optionSaved', (options: MishiroConfig) => { const configProxy = options.proxy ?? '' this.dler.setProxy(configProxy) this.scoreDownloader.setProxy(configProxy) this.jacketDownloader.setProxy(configProxy) }) } oninput (target: HTMLInputElement): void { this.bgm.currentTime = Number(target.value) } stopDownload (): void { this.playSe(this.cancelSe) this.current = 0 this.total = this.current this.downloadingTasks = [] if (this.audioDownloadPromise) { this.audioDownloadPromise.download.abort() } this.audioDownloading = false } async exportSelectedItem (): Promise<void> { this.playSe(this.enterSe) const exportTasks = this.selectedAudios.slice(0) if (exportTasks.length <= 0) { this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('home.noEmptyDownload')) return } for (let i = 0; i < exportTasks.length; i++) { if (!exportTasks[i]._canplay) { this.event.$emit('alert', this.$t('home.errorTitle'), `Not exists: ${exportTasks[i].fileName}`) return } } const result = await showOpenDialog({ title: this.$t('live.exportDir') as string, defaultPath: bgmDir('..'), properties: [ 'openDirectory', 'createDirectory', 'promptToCreate', 'treatPackageAsDirectory', 'showHiddenFiles', 'dontAddToRecent' ] }) if (result.canceled) return this.audioExporting = true let completeCount = 0 const targetDir = result.filePaths[0] fs.mkdirsSync(targetDir) const loopCount = configurer.get('loopCount') || 0 for (let i = 0; i < exportTasks.length; i++) { const audio = exportTasks[i] const audioType = audio.name.split('/')[0] const type = configurer.get('audioExport') ?? 'wav' const audioFileName = audio.fileName + '.' + type const hcaFileName = audio.fileName + '.hca' const wavFileName = audio.fileName + '.wav' const dir = audioType === 'b' ? bgmDir : (audioType === 'l' ? liveDir : null) if (!dir) { error('LIVE AUDIO EXPORT: Unknown audio type') completeCount++ continue } let hcaFilePath = dir(hcaFileName) const wavFilePath = path.join(targetDir, wavFileName) const audioFilePath = path.join(targetDir, audioFileName) let hcaInAsar = false let hcaFilePathExist = fs.existsSync(hcaFilePath) if (audioType === 'b' && !hcaFilePathExist) { const asarHcaFilePath = bgmAsarDir(hcaFileName) if (fs.existsSync(asarHcaFilePath)) { hcaFilePathExist = true hcaFilePath = asarHcaFilePath hcaInAsar = true } } this.text = `[${completeCount}/${exportTasks.length}] ${audioFileName}` this.current = (100 * completeCount / exportTasks.length) this.total = this.current try { if (type === 'wav') { await window.node.mishiroCore.audio.hca2wav(hcaInAsar ? fs.readFileSync(hcaFilePath) : hcaFilePath, wavFilePath, loopCount) } else if (type === 'mp3') { const tmpwavPath = path.join(os.tmpdir(), wavFileName) await window.node.mishiroCore.audio.hca2wav(hcaInAsar ? fs.readFileSync(hcaFilePath) : hcaFilePath, tmpwavPath, loopCount) await window.node.mishiroCore.audio.wav2mp3(tmpwavPath, audioFilePath, (prog) => { const currentPercent = prog.loading this.$set(audio, '_percent', currentPercent) this.current = (100 * completeCount / exportTasks.length) + currentPercent / exportTasks.length this.total = this.current }) await fs.remove(tmpwavPath) } else if (type === 'aac') { const tmpwavPath = path.join(os.tmpdir(), wavFileName) await window.node.mishiroCore.audio.hca2wav(hcaInAsar ? fs.readFileSync(hcaFilePath) : hcaFilePath, tmpwavPath, loopCount) await window.node.mishiroCore.audio.wav2aac(tmpwavPath, audioFilePath, (prog) => { const currentPercent = prog.loading this.$set(audio, '_percent', currentPercent) this.current = (100 * completeCount / exportTasks.length) + currentPercent / exportTasks.length this.total = this.current }) await fs.remove(tmpwavPath) } } catch (err) { error(`LIVE AUDIO EXPORT: ${err.stack}`) } this.text = '' completeCount++ } this.text = '' this.current = 0 this.total = this.current this.audioExporting = false } async downloadSelectedItem (): Promise<void> { this.playSe(this.enterSe) if (!navigator.onLine) { this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('home.noNetwork')) return } this.downloadingTasks = this.selectedAudios.slice(0) if (this.downloadingTasks.length <= 0) { this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('home.noEmptyDownload')) return } this.audioDownloading = true let completeCount = 0 for (let i = 0; i < this.downloadingTasks.length; i++) { const audio = this.downloadingTasks[i] const audioType = audio.name.split('/')[0] const acbPathObj = path.posix.parse(audio.name) const acbBase = acbPathObj.base const awbBase = acbPathObj.name + '.awb' const hcaFileName = audio.fileName + '.hca' const needAwb = !!audio.awbHash const dir = audioType === 'b' ? bgmDir : (audioType === 'l' ? liveDir : null) if (!dir) { error('LIVE AUDIO DOWNLOAD: Unknown audio type') completeCount++ continue } let hcaFilePath = dir(hcaFileName) // let hcaInAsar = false let hcaFilePathExist = fs.existsSync(hcaFilePath) if (audioType === 'b' && !hcaFilePathExist) { const asarHcaFilePath = bgmAsarDir(hcaFileName) if (fs.existsSync(asarHcaFilePath)) { hcaFilePathExist = true hcaFilePath = asarHcaFilePath // hcaInAsar = true } } if (hcaFilePathExist) { completeCount++ continue } this.text = `[${completeCount}/${this.downloadingTasks.length}] ${path.basename(audio.name)}` const acbPath = dir(acbBase) if (!hcaFilePathExist) { let result: string const awbPath = dir(awbBase) try { this.audioDownloadPromise = this.dler.downloadSound( audioType, audio.hash, acbPath, (prog) => { this.text = `[${completeCount}/${this.downloadingTasks.length}] ${prog.name as string}` if (!needAwb) { const currentPercent = prog.loading this.$set(audio, '_percent', currentPercent) this.current = (100 * completeCount / this.downloadingTasks.length) + currentPercent / this.downloadingTasks.length this.total = this.current } } ) result = await this.audioDownloadPromise this.audioDownloadPromise = null if (needAwb) { this.audioDownloadPromise = this.dler.downloadSound( audioType, audio.awbHash!, awbPath, (prog) => { this.text = `[${completeCount}/${this.downloadingTasks.length}] ${prog.name as string}` const currentPercent = prog.loading this.$set(audio, '_percent', currentPercent) this.current = (100 * completeCount / this.downloadingTasks.length) + currentPercent / this.downloadingTasks.length this.total = this.current } ) result = await this.audioDownloadPromise this.audioDownloadPromise = null } } catch (errorPath) { this.audioDownloadPromise = null this.event.$emit('alert', this.$t('home.errorTitle'), (this.$t('home.downloadFailed') as string) + '<br/>' + (errorPath as string)) completeCount++ continue } if (!result) { completeCount++ continue } const acbEntries = readAcb(acbPath) if (acbEntries.length === 0) { completeCount++ continue } await fs.promises.writeFile(hcaFilePath, acbEntries[0].buffer) await fs.remove(acbPath) if (needAwb) await fs.remove(awbPath) } this.$set(audio, '_canplay', true) await this.ensureScoreAndJacket(audio) this.text = '' completeCount++ } this.audioDownloading = false this.text = '' this.current = 0 this.total = this.current this.downloadingTasks = [] } async ensureScoreAndJacket (audio: BGM | Live): Promise<boolean> { if ('score' in audio) { if (!fs.existsSync(scoreDir(audio.score!))) { try { const scoreBdb = await this.scoreDownloader.downloadDatabase( audio.scoreHash!, scoreDir(audio.score!.split('.')[0]) ) if (scoreBdb) { // this.core.util.lz4dec(scoreBdb as string, 'bdb') fs.removeSync(scoreDir(audio.score!.split('.')[0])) } else { this.event.$emit('alert', this.$t('home.errorTitle'), 'Score database download failed') return false } } catch (errorPath) { this.event.$emit('alert', this.$t('home.errorTitle'), (this.$t('home.downloadFailed') as string) + '<br/>' + (errorPath as string)) return false } } } if ('jacket' in audio) { const name = path.parse(audio.jacket!).name const jacketlz4 = jacketDir(name) const pngName = name + '_m.png' const pngPath = jacketDir(pngName) if (!fs.existsSync(pngPath)) { try { const jacketu3d = await this.jacketDownloader.downloadAsset( audio.jacketHash!, jacketlz4 ) if (jacketu3d) { // this.core.util.lz4dec(scoreBdb as string, 'bdb') await fs.remove(jacketlz4) await unpackTexture2D(jacketu3d) await fs.remove(jacketDir(name + '_s.png')) } else { this.event.$emit('alert', this.$t('home.errorTitle'), 'Jacket download failed') return false } } catch (errorPath) { this.event.$emit('alert', this.$t('home.errorTitle'), (this.$t('home.downloadFailed') as string) + '<br/>' + (errorPath as string)) return false } } } return true } formatJson (obj: any): string { try { return JSON.stringify(obj, null, 2) } catch (err) { return err.message } } selectAudioNew (audio: BGM | Live): void { this.playSe(this.enterSe) const index = this.selectedAudios.indexOf(audio) if (this.controlDown) { if (index !== -1) { this.selectedAudios.splice(index, 1) this.$set(audio, '_active', false) } else { this.selectedAudios.push(audio) this.$set(audio, '_active', true) } this.lastClickedAudio = audio } else if (this.shiftDown) { if (!this.lastClickedAudio) { this.lastClickedAudio = audio this.$set(audio, '_active', true) return } const lastClickedIndex = this.audioListData.indexOf(this.lastClickedAudio) if (lastClickedIndex !== -1) { const thisIndex = this.audioListData.indexOf(audio) let start: number let end: number if (lastClickedIndex < thisIndex) { start = lastClickedIndex end = thisIndex + 1 } else { start = thisIndex end = lastClickedIndex + 1 } this.selectedAudios.forEach(a => { this.$set(a, '_active', false) }) this.selectedAudios.length = 0 this.selectedAudios = this.audioListData.slice(start, end) this.selectedAudios.forEach(a => { this.$set(a, '_active', true) }) } else { this.selectedAudios.push(audio) this.lastClickedAudio = audio this.$set(audio, '_active', true) } } else { this.selectedAudios.forEach(a => { this.$set(a, '_active', false) }) this.selectedAudios.length = 0 this.selectedAudios.push(audio) this.$set(audio, '_active', true) this.lastClickedAudio = audio } } async selectAudio (audio: BGM | Live): Promise<void> { if (this.activeAudio.hash === audio.hash) return this.playSe(this.enterSe) const r = await this.ensureScoreAndJacket(audio) if (!r) return this.activeAudio = audio const audioType = audio.name.split('/')[0] const hcaFileName = audio.fileName + '.hca' const dir = audioType === 'b' ? bgmDir : (audioType === 'l' ? liveDir : null) if (!dir) { this.event.$emit('alert', this.$t('home.errorTitle'), 'Unknown audio type') return } let hcaFilePath = dir(hcaFileName) // let hcaInAsar = false let hcaFilePathExist = fs.existsSync(hcaFilePath) if (audioType === 'b' && !hcaFilePathExist) { const asarHcaFilePath = bgmAsarDir(hcaFileName) if (fs.existsSync(asarHcaFilePath)) { hcaFilePathExist = true hcaFilePath = asarHcaFilePath // hcaInAsar = true } } this.event.$emit('liveSelect', { src: hcaFilePath }) const activeAudio = this.activeAudio if ('score' in activeAudio) { this.allLyrics = await getLyrics(scoreDir(activeAudio.score!)) } else { this.allLyrics = [] this.lyrics = [] } if ('jacket' in activeAudio) { const name = path.parse(activeAudio.jacket!).name // const jacketlz4 = jacketDir(name) const pngName = name + '_m.png' const pngPath = jacketDir(pngName) this.jacketSrc = path.posix.relative(getPath('renderer').replace(/\\/g, '/'), pngPath.replace(/\\/g, '/')).replace(/\\/g, '/') } else { this.jacketSrc = '' } } onAudioTypeChange (): void { this.selectedAudios.forEach(a => { this.$set(a, '_active', false) }) this.selectedAudios.length = 0 this.query(true) } query (quiet: boolean): void { if (!quiet) { this.playSe(this.enterSe) } if (this.queryString) { if (this.currentAudioType === 'BGM') { const arr = [] if (this.queryString === '/ok') { for (let i = 0; i < this.bgmManifest.length; i++) { if (this.bgmManifest[i]._canplay) { arr.push(this.bgmManifest[i]) } } } else { const re = new RegExp(this.queryString) for (let i = 0; i < this.bgmManifest.length; i++) { if (re.test(this.bgmManifest[i].fileName)) { arr.push(this.bgmManifest[i]) } } } setAudioList(arr) } else if (this.currentAudioType === 'LIVE') { const arr = [] if (this.queryString === '/ok') { for (let i = 0; i < this.liveManifest.length; i++) { if (this.liveManifest[i]._canplay) { arr.push(this.liveManifest[i]) } } } else { const re = new RegExp(this.queryString) for (let i = 0; i < this.liveManifest.length; i++) { if (re.test(this.liveManifest[i].fileName)) { arr.push(this.liveManifest[i]) } } } setAudioList(arr) } } else { setAudioList(this.allAudioListData) } this.$nextTick(() => { if (this.$refs.audioList) { (this.$refs.audioList as HTMLDivElement).scrollTop = 0 } }) } opendir (): void { this.playSe(this.enterSe) const dirb = bgmDir() const dirl = liveDir() if (!fs.existsSync(dirb)) fs.mkdirsSync(dirb) if (!fs.existsSync(dirl)) fs.mkdirsSync(dirl) if (window.node.process.platform === 'win32') { shell.openExternal(dirb).catch(err => { console.error(err) error(`LIVE opendir: ${err.stack}`) }) shell.openExternal(dirl).catch(err => { console.error(err) error(`LIVE opendir: ${err.stack}`) }) } else { shell.showItemInFolder(dirb + '/.') shell.showItemInFolder(dirl + '/.') } } openLyrics (): void { const self = this let bodyhtml = this.allLyrics.map(line => line.lyrics).join('<br/>') if (this.jacketSrc) { bodyhtml = `<div style="text-align:center" ><img src="${this.jacketSrc}" /></div>${bodyhtml}` } const title = path.parse(this.activeAudio.fileName).name this.event.$emit('alert', title, bodyhtml, undefined, { text: this.$t('live.copy'), cb () { self.playSe(self.enterSe) clipboard.writeText(self.allLyrics.map(line => line.lyrics).join(os.EOL)) } }, { text: this.$t('live.export'), cb: () => { self.playSe(self.enterSe) showSaveDialog({ title: 'Save LRC - ' + title, defaultPath: getPath.scoreDir(title + '.lrc') }).then((res) => { if (res.filePath) { const lyricsArr = this.allLyrics.map(line => `[${filterTime(line.time, true)}]${line.lyrics}`) lyricsArr.unshift('[by:mishiro]') lyricsArr.push('') const lrcstr = lyricsArr.join(os.EOL) const data = iconvLite.encode(lrcstr, configurer.get('lrcEncoding') || 'utf8') fs.writeFileSync(res.filePath, data) } }).catch((err) => { console.error(err) error(`LIVE openLyrics: ${err.stack}`) }) } }) } private async gameOrScore (): Promise<boolean> { if (this.isGameRunning) { this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('live.gameRunning')) return false } const activeAudio = this.activeAudio as Live if (!activeAudio.score) { this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('live.noScore')) return false } if (!fs.existsSync(liveDir(activeAudio.fileName + '.hca'))) { this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('live.noAudio')) return false } if (!fs.existsSync(scoreDir(activeAudio.score))) { try { // let scoreBdb = await this.scoreDownloader.downloadOne( // this.getDbUrl(activeAudio.scoreHash), // scoreDir(activeAudio.score.split('.')[0]) // ) const scoreBdb = await this.scoreDownloader.downloadDatabase( activeAudio.scoreHash!, scoreDir(activeAudio.score.split('.')[0]) ) if (scoreBdb) { // this.core.util.lz4dec(scoreBdb as string, 'bdb') fs.removeSync(scoreDir(activeAudio.score.split('.')[0])) } else { this.event.$emit('alert', this.$t('home.errorTitle'), 'Score database download failed') return false } } catch (errorPath) { this.event.$emit('alert', this.$t('home.errorTitle'), (this.$t('home.downloadFailed') as string) + '<br/>' + (errorPath as string)) return false } } return true } // async startGame () { // this.playSe(this.enterSe) // const result = await this.gameOrScore() // if (result) this.event.$emit('game', this.activeAudio) // } async startScore (): Promise<void> { this.playSe(this.enterSe) const result = await this.gameOrScore() if (!result) return const difficulties = await getScoreDifficulties(scoreDir((this.activeAudio as Live).score!)) this.event.$emit('score', this.activeAudio, difficulties) } // private checkScore (scoreFile: string) { // const id = generateObjectId() // return new Promise<boolean>((resolve) => { // ipcRenderer.once(id, (_e: Event, hasMasterPlus: boolean) => { // resolve(hasMasterPlus) // }) // ipcRenderer.send('checkScore', id, scoreFile) // }) // } get allAudioListData (): BGM[] | Live[] { if (this.currentAudioType === 'BGM') { return this.bgmManifest } else if (this.currentAudioType === 'LIVE') { return this.liveManifest } return [] } mounted (): void { this.$nextTick(() => { this.bgm.on('timeupdate', () => { this.currentTime = this.bgm.currentTime for (let i = this.allLyrics.length - 1; i >= 0; i--) { const line = this.allLyrics[i] if (this.bgm.currentTime >= line.time) { this.lyrics = i === this.allLyrics.length - 1 ? [this.allLyrics[i]] : [this.allLyrics[i], this.allLyrics[i + 1]] break } } }) this.bgm.on('durationchange', () => { this.duration = this.bgm.duration }) this.event.$on('playerSelect', (fileName: string) => { if (this.bgmManifest.filter(bgm => bgm.fileName === fileName).length > 0) { this.allLyrics = [] this.lyrics = [] this.jacketSrc = '' this.activeAudio = this.bgmManifest.filter(bgm => bgm.fileName === fileName)[0] } else { this.activeAudio = this.liveManifest.filter(bgm => bgm.fileName === fileName)[0] } }) this.event.$on('gameStart', () => { this.isGameRunning = true }) this.event.$on('enterKey', (block: string) => { if (block === 'live') { this.query(false) } }) ipcRenderer.on('liveEnd', (_event: Event, liveResult: any, isCompleted: boolean) => { this.isGameRunning = false if (isCompleted) this.playSe(new Audio('../../asset/se.asar/se_live_wow.mp3')) if (liveResult) this.event.$emit('showLiveResult', liveResult) else this.event.$emit('playBgm') }) // ipcRenderer.on('lyrics', (_event: Event, lyrics: { time: number; lyrics: string; size: any }[]) => { // this.allLyrics = lyrics // }) document.addEventListener('keydown', (e: KeyboardEvent) => { if (e.key === 'Control') { this.controlDown = true } else if (e.key === 'Shift') { this.shiftDown = true } }) document.addEventListener('keyup', (e: KeyboardEvent) => { if (e.key === 'Control') { this.controlDown = false } else if (e.key === 'Shift') { this.shiftDown = false } }) }) } }
the_stack
export default function makeDashboard(integrationId: string) { return { annotations: { list: [ { builtIn: 1, datasource: "-- Grafana --", enable: true, hide: true, iconColor: "rgba(0, 211, 255, 1)", name: "Annotations & Alerts", type: "dashboard" } ] }, editable: true, gnetId: null, graphTooltip: 0, iteration: 1623957533555, links: [], panels: [ { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 0 }, hiddenSeries: false, id: 2, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sys_cpu_combined_percent_normalized{job='cockroachdb',instance=~"$node"}`, interval: "", intervalFactor: 1, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "CPU Percent", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:233", format: "percentunit", label: "CPU (percentage)", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:234", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Memory in use across all nodes", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 8 }, hiddenSeries: false, id: 4, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sys_rss{integration_id="${integrationId}",instance=~"$node"}`, hide: false, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Memory Usage", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:78", format: "bytes", label: "memory usage", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:79", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 16 }, hiddenSeries: false, id: 6, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `rate(sys_host_disk_read_bytes{integration_id="${integrationId}",instance=~"$node"}[5m])`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Disk Read B/s", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:183", format: "bytes", label: "bytes", logBase: 1, max: null, min: null, show: true }, { $$hashKey: "object:184", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 24 }, hiddenSeries: false, id: 8, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `rate(sys_host_disk_write_bytes{integration_id="${integrationId}",instance=~"$node"}[5m])`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Disk Write B/s", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:655", format: "bytes", label: "bytes", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:656", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 32 }, hiddenSeries: false, id: 10, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `rate(sys_host_disk_read_count{integration_id="${integrationId}",instance=~"$node"}[5m])`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Disk Read IOPS", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:761", format: "short", label: "IOPS", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:762", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 40 }, hiddenSeries: false, id: 12, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `rate(sys_host_disk_write_count{integration_id="${integrationId}",instance=~"$node"}[5m])`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Disk Write IOPS", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:850", format: "short", label: "IOPS", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:851", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 48 }, hiddenSeries: false, id: 14, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `rate(sys_host_disk_iopsinprogress{integration_id="${integrationId}",instance=~"$node"}[5m])`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Disk Ops In Progress", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:926", format: "short", label: "Ops", logBase: 1, max: null, min: null, show: true }, { $$hashKey: "object:927", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Free disk space available to CockroachDB data.\n\n[How is this metric calculated?](https://www.cockroachlabs.com/docs/v21.1/ui-storage-dashboard.html#capacity-metrics)", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 56 }, hiddenSeries: false, id: 20, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `capacity_available{integration_id="${integrationId}",instance=~"$node"}`, interval: "", intervalFactor: 1, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Available Disk Capacity", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:103", format: "bytes", label: "capacity", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:104", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 64 }, hiddenSeries: false, id: 16, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `rate(sys_host_net_recv_bytes{integration_id="${integrationId}",instance=~"$node"}[5m])`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Network Bytes Received", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1076", format: "bytes", label: "bytes", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1077", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 72 }, hiddenSeries: false, id: 18, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `rate(sys_host_net_send_bytes{integration_id="${integrationId}",instance=~"$node"}[5m])`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Network Bytes Sent", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:708", format: "bytes", label: "bytes", logBase: 1, max: null, min: null, show: true }, { $$hashKey: "object:709", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } } ], refresh: false, schemaVersion: 27, style: "dark", tags: [], templating: { list: [ { allValue: "", current: { selected: true, text: "All", value: "$__all" }, datasource: "metrics", definition: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, description: null, error: null, hide: 0, includeAll: true, label: "Node", multi: false, name: "node", options: [], query: { query: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, refId: "Prometheusa-node-Variable-Query" }, refresh: 1, regex: "", skipUrlSync: false, sort: 3, tagValuesQuery: "", tags: [], tagsQuery: "", type: "query", useTags: false } ] }, time: { from: "now-1h", to: "now" }, timepicker: {}, timezone: "utc", title: "CRDB Console: Hardware", uid: `har-${integrationId}`, version: 4 }; } export type Dashboard = ReturnType<typeof makeDashboard>;
the_stack
import * as assert from 'assert'; import * as sinon from 'sinon'; import { Handles } from 'vscode-debugadapter'; import { OBJECT_VARIABLE_DISPLAY_NAME, SCOPES } from '../../src/debugAdapter/constants/variablesView'; import RuntimeInterface from '../../src/debugAdapter/runtimeInterface'; import VariablesHandler from '../../src/debugAdapter/variablesHandler'; describe('VariablesHandler unit tests', () => { const runtimeInterface = new RuntimeInterface(); afterEach(() => { sinon.restore(); }); describe('getVariableAttributesByVariableRef - when SCOPES.all.ref is requested', () => { it('getVariableAttributesByVariableRef should pass when variables contain array property', async () => { // Arrange sinon.stub(RuntimeInterface.prototype, 'variables').resolves({ [arrayProp.key]: arrayProp.value }); // Act const variablesHandler = new VariablesHandler(runtimeInterface); const result = await variablesHandler.getVariableAttributesByVariableRef(SCOPES.all.ref); // Assert const containsArrayProp = result.some((e) => e.name === arrayProp.key && e.value === JSON.stringify(arrayProp.value) && e.variablesReference === 0); assert.strictEqual(containsArrayProp, true, 'result should contains array prop'); }); it('getVariableAttributesByVariableRef should pass when variables contain boolean property', async () => { // Arrange sinon.stub(RuntimeInterface.prototype, 'variables').resolves({ [boolProp.key]: boolProp.value }); // Act const variablesHandler = new VariablesHandler(runtimeInterface); const result = await variablesHandler.getVariableAttributesByVariableRef(SCOPES.all.ref); // Assert const containsBoolProp = result.some((e) => e.name === boolProp.key && e.value === JSON.stringify(boolProp.value) && e.variablesReference === 0); assert.strictEqual(containsBoolProp, true, 'result should contains boolProp prop'); }); it('getVariableAttributesByVariableRef should pass when variables contain null property', async () => { // Arrange sinon.stub(RuntimeInterface.prototype, 'variables').resolves({ [nullProp.key]: nullProp.value }); // Act const variablesHandler = new VariablesHandler(runtimeInterface); const result = await variablesHandler.getVariableAttributesByVariableRef(SCOPES.all.ref); // Assert const containsNullProp = result.some((e) => e.name === nullProp.key && e.value === JSON.stringify(nullProp.value) && e.variablesReference === 0); assert.strictEqual(containsNullProp, true, 'result should contains null prop'); }); it('getVariableAttributesByVariableRef should pass when variables contain number property', async () => { // Arrange sinon.stub(RuntimeInterface.prototype, 'variables').resolves({ [numProp.key]: numProp.value }); // Act const variablesHandler = new VariablesHandler(runtimeInterface); const result = await variablesHandler.getVariableAttributesByVariableRef(SCOPES.all.ref); // Assert const containsNumberProp = result.some((e) => e.name === numProp.key && e.value === JSON.stringify(numProp.value) && e.variablesReference === 0); assert.strictEqual(containsNumberProp, true, 'result should contains Number prop'); }); it('getVariableAttributesByVariableRef should pass when variables contain object property', async () => { // Arrange sinon.stub(RuntimeInterface.prototype, 'variables').resolves({ [objProp.key]: objProp.value }); const generateVariablesAttrKeyStub = sinon.stub(VariablesHandler.prototype, 'generateVariablesAttrKey' as any); // Act const variablesHandler = new VariablesHandler(runtimeInterface); const result = await variablesHandler.getVariableAttributesByVariableRef(SCOPES.all.ref); // Assert const objectVar = result.find((e) => e.name === objProp.key); assert.notEqual(objectVar, undefined, 'objectVar shouldn\'t be undefined'); assert.notStrictEqual(objectVar!.variablesReference, 0, 'objectVar\'s value shouldn\'t be 0'); assert.strictEqual(objectVar!.value, OBJECT_VARIABLE_DISPLAY_NAME, `objectVar\'s value should be ${OBJECT_VARIABLE_DISPLAY_NAME}`); assert.strictEqual(generateVariablesAttrKeyStub.calledWith('', objProp.key), true, 'generateVariablesAttrKey should be called with concrete arguments'); }); it('getVariableAttributesByVariableRef should call handles.create when variables contain object property', async () => { // Arrange sinon.stub(RuntimeInterface.prototype, 'variables').resolves({ [objProp.key]: objProp.value }); const variablePath = `/${objProp.key}`; const handlesCreateStub = sinon.stub(Handles.prototype, 'create').returns(123); // Act const variablesHandler = new VariablesHandler(runtimeInterface); const result = await variablesHandler.getVariableAttributesByVariableRef(SCOPES.all.ref); // Assert const objectVar = result.find((e) => e.name === objProp.key); assert.notEqual(objectVar, undefined, 'objectVar shouldn\'t be undefined'); assert.notStrictEqual(objectVar!.variablesReference, 0, 'objectVar\'s value shouldn\'t be 0'); assert.strictEqual(objectVar!.value, OBJECT_VARIABLE_DISPLAY_NAME, `objectVar\'s value should be ${OBJECT_VARIABLE_DISPLAY_NAME}`); assert.strictEqual(handlesCreateStub.calledWithMatch(variablePath), true, `handles.create should be called with ${variablePath} argument`); }); it('getVariableAttributesByVariableRef should pass when variables contain string property', async () => { // Arrange sinon.stub(RuntimeInterface.prototype, 'variables').resolves({ [stringProp.key]: stringProp.value }); // Act const variablesHandler = new VariablesHandler(runtimeInterface); const result = await variablesHandler.getVariableAttributesByVariableRef(SCOPES.all.ref); // Assert const containsStringProp = result.some((e) => e.name === stringProp.key && e.value === JSON.stringify(stringProp.value) && e.variablesReference === 0); assert.strictEqual(containsStringProp, true, 'result should contains String prop'); }); it('getVariableAttributesByVariableRef should pass when variables contain undefined property', async () => { // Arrange sinon.stub(RuntimeInterface.prototype, 'variables').resolves({ [undefinedProp.key]: undefinedProp.value }); // Act const variablesHandler = new VariablesHandler(runtimeInterface); const result = await variablesHandler.getVariableAttributesByVariableRef(SCOPES.all.ref); // Assert const containsUndefinedProp = result.some((e) => e.name === undefinedProp.key && e.value === JSON.stringify(undefinedProp.value) && e.variablesReference === 0); assert.strictEqual(containsUndefinedProp, true, 'result should contains undefined prop'); }); }); it('getVariableAttributesByVariableRef should pass when variableReference is not SCOPE.all.ref', async () => { // Arrange const nestedVariableReference = 987; const nestedObjectTestProperty = { key: 'Test', value: 'Test' }; const nestedObjectValue = { [nestedObjectTestProperty.key]: nestedObjectTestProperty.value }; const nestedObject = { key: 'NestedVariable', value: nestedObjectValue }; const objectVariable = { key: 'TestVariable', value: { [nestedObject.key]: nestedObject.value } }; // variables structure: // variables = { // TestVariable: { // NestedVariable: { // Test: 'Test', // }, // }, // } sinon.stub(RuntimeInterface.prototype, 'variables').resolves({ [objectVariable.key]: objectVariable.value }); sinon.stub(Handles.prototype, 'get') .withArgs(nestedVariableReference) .returns(`/${objectVariable.key}/${nestedObject.key}`); // Act const variablesHandler = new VariablesHandler(runtimeInterface); const result = await variablesHandler.getVariableAttributesByVariableRef(nestedVariableReference); const containsNestedObjectProperty = result.some((v) => v.name === nestedObjectTestProperty.key && v.value === JSON.stringify(nestedObjectTestProperty.value) && v.variablesReference === 0); // Assert assert.strictEqual(containsNestedObjectProperty, true, 'should contain nestedObjectProperty'); }); describe('evaluateExpression', () => { it('should pass when expression is simple', async () => { // Arrange const variableKey = 'key'; const variables = { [variableKey]: 'test' }; sinon.stub(RuntimeInterface.prototype, 'variables').resolves(variables); const testExpression = variableKey; // Act const variablesHandler = new VariablesHandler(runtimeInterface); const evaluatedVar = await variablesHandler.evaluateExpression(testExpression); // Assert assert.strictEqual(evaluatedVar.result, JSON.stringify(variables[variableKey]), `evaluatedVar.result should be ${variables[variableKey]}`); assert.strictEqual(evaluatedVar.variablesReference, 0, 'evaluatedVar.variablesReference shouldn\'t be 0'); }); it('should pass when expression is complex', async () => { // Arrange const objectKey = 'key'; const objectProp = 'prop'; const variables = { [objectKey]: { [objectProp]: 'test', }, }; sinon.stub(RuntimeInterface.prototype, 'variables').resolves(variables); const testExpression = `${objectKey}.${objectProp}`; // Act const variablesHandler = new VariablesHandler(runtimeInterface); const evaluatedVar = await variablesHandler.evaluateExpression(testExpression); // Assert const objectPropValue = variables[objectKey][objectProp]; assert.strictEqual( evaluatedVar.result, JSON.stringify(objectPropValue), `evaluatedVar.result should be ${objectPropValue}`, ); assert.strictEqual(evaluatedVar.variablesReference, 0, 'evaluatedVar.variablesReference shouldn\'t be 0'); }); }); }); const arrayProp = { key: 'arrayProp', value: [1, 2] }; const boolProp = { key: 'boolProp', value: true }; const nullProp = { key: 'nullProp', value: null }; const numProp = { key: 'numProp', value: 123 }; const objProp = { key: 'objProp', value: { a: 1 } }; const stringProp = { key: 'stringProp', value: 'test' }; const undefinedProp = { key: 'undefinedProp', value: undefined };
the_stack
import assert from 'assert'; import * as Stream from 'stream'; import * as Url from 'url'; import * as fs from 'fs'; import * as path from 'path'; import * as tmpSync from 'tmp'; import * as tmp from 'tmp-promise'; import * as cmd from './command'; import { safeMkdir } from './fsutils'; import * as AWS from 'aws-sdk'; // An abstraction over file system operations, that supports local files and s3:// URIs const _backends = { 's3:': { mkdirRecursive() { // nothing to do, directories don't need to be created in S3 and don't carry // metadata anyway }, async download(url : Url.UrlObject, ...extraArgs : string[]) { if (url.pathname!.endsWith('/')) { // directory // use /var/tmp as the parent directory, to ensure it's on disk and not in a tmpfs const { path: dir } = await tmp.dir({ mode: 0o700, tmpdir: '/var/tmp', unsafeCleanup: true, prefix: path.basename(url.pathname!) + '.' }); const args = ['s3', 'sync', 's3://' + url.hostname + url.pathname, dir]; if (extraArgs.length > 0) args.push(...extraArgs); await cmd.exec('aws', args); return dir; } else { // file const { path: file } = await tmp.file({ mode: 0o600, discardDescriptor: true, tmpdir: '/var/tmp', prefix: path.basename(url.pathname!) + '.' }); await cmd.exec('aws', ['s3', 'cp', 's3://' + url.hostname + url.pathname, file]); return file; } }, async upload(localpath : string, url : Url.UrlObject, ...extraArgs : string[]) { const dest = 's3://' + url.hostname + url.pathname; if (fs.lstatSync(localpath).isFile()) { await cmd.exec('aws', ['s3', 'cp', localpath, dest]); return; } const args = ['s3', 'sync', localpath, dest]; if (extraArgs.length > 0) args.push(...extraArgs); await cmd.exec('aws', args); }, async removeRecursive(url : Url.UrlObject) { return cmd.exec('aws', ['s3', 'rm', '--recursive', 's3://' + url.hostname + url.pathname]); }, async sync(url1 : Url.UrlObject, url2 : Url.UrlObject, ...extraArgs : string[]) { const args = ['s3', 'sync', 's3://' + url1.hostname + url1.pathname, 's3://' + url2.hostname + url2.pathname, ]; if (extraArgs.length > 0) args.push(...extraArgs); return cmd.exec('aws', args); }, createLocalWriteStream(url : Url.UrlObject) { const { name: tmpFile, fd: tmpFD } = tmpSync.fileSync({ mode: 0o600, tmpdir: '/var/tmp' }); const stream = fs.createWriteStream(tmpFile, { fd: tmpFD }); stream.on('finish', async () => { await this.upload(tmpFile, url); await fs.unlink(tmpFile, (err) => { if (err) throw (err); }); }); return stream; }, createWriteStream(url : Url.UrlObject, localSpooling : boolean) { if (localSpooling) return this.createLocalWriteStream(url); const s3 = new AWS.S3(); const stream = new Stream.PassThrough(); const key = url.pathname!.startsWith('/') ? url.pathname!.substring(1) : url.pathname!; s3.upload({ Bucket: url.hostname!, Key: key, Body: stream, }, (err, data) => { if (err) { console.log('upload error:', err); stream.emit('error', err); return; } console.log('upload success:', data); }); return stream; }, createReadStream(url : Url.UrlObject) { const s3 = new AWS.S3(); const key = url.pathname!.startsWith('/') ? url.pathname!.substring(1) : url.pathname!; const download = s3.getObject({ Bucket: url.hostname!, Key: key }); return download.createReadStream(); }, async getDownloadLinkOrStream(url : Url.UrlObject) { const s3 = new AWS.S3(); const key = url.pathname!.startsWith('/') ? url.pathname!.substring(1) : url.pathname; return s3.getSignedUrlPromise('getObject', { Bucket: url.hostname, Key: key, Expires: 60 // seconds }); }, async writeFile(url : Url.UrlObject, blob : string|Buffer|NodeJS.ReadableStream, options : { contentType ?: string } = {}) { const s3 = new AWS.S3(); const key = url.pathname!.startsWith('/') ? url.pathname!.substring(1) : url.pathname!; const upload = s3.upload({ Bucket: url.hostname!, Key: key, Body: blob, ContentType: options.contentType }); return upload.promise(); } }, 'file:': { async mkdirRecursive(url : string | Url.UrlObject) { const pathname = typeof url === "string" ? url : url.pathname!; const components = path.resolve(pathname).split('/').slice(1); let subpath = ''; for (const component of components) { subpath += '/' + component; await safeMkdir(subpath); } }, async download(url : Url.UrlObject, ...extraArgs : string[]) { // the file is already local, so we have nothing to do // (note that the hostname part of the URL is ignored) return path.resolve(url.pathname!); }, async upload(localdir : string, url : Url.UrlObject, ...extraArgs : string[]) { let hostname = ''; if (!url.hostname) { if (path.resolve(localdir) === path.resolve(url.pathname!)) return; } else { hostname = url.hostname + ':'; } const args = ['-av', localdir, `${hostname}${url.pathname}`]; if (extraArgs.length > 0) args.push(...extraArgs); await cmd.exec('rsync', args); }, async removeRecursive(url : Url.UrlObject) { return cmd.exec('rm', ['-r', url.pathname!]); }, async sync(url1 : Url.UrlObject, url2 : Url.UrlObject, ...extraArgs : string[]) { const args = ['-av', url1.hostname ? `${url1.hostname}:${url1.pathname}` : url1.pathname!, url2.hostname ? `${url2.hostname}:${url2.pathname}` : url2.pathname!, ]; if (extraArgs.length > 0) args.push(...extraArgs); return cmd.exec('rsync', args); }, createWriteStream(url : Url.UrlObject) { return fs.createWriteStream(url.pathname!); }, createReadStream(url : Url.UrlObject) { return fs.createReadStream(url.pathname!); }, getDownloadLinkOrStream(url : Url.UrlObject) { return fs.createReadStream(url.pathname!); }, async writeFile(url : Url.UrlObject, blob : string|Buffer|NodeJS.ReadableStream, options ?: { contentType ?: string }) { await this.mkdirRecursive(path.dirname(url.pathname!)); const output = fs.createWriteStream(url.pathname!); if (typeof blob === 'string' || blob instanceof Uint8Array) output.end(blob); else blob.pipe(output); return new Promise((callback, errback) => { output.on('finish', callback); output.on('error', errback); }); } } }; const cwd = 'file://' + (path.resolve(process.env.THINGENGINE_ROOTDIR || '.')) + '/'; function getBackend(url : string) { url = Url.resolve(cwd, url); const parsed = Url.parse(url); if (parsed.protocol !== 's3:' && parsed.protocol !== 'file:') throw new Error(`Unknown URL scheme ${parsed.protocol}`); return [parsed, _backends[parsed.protocol!]] as const; } /** A path.resolve()-like interface that supports s3:// and file:// URIs correctly. Can be called with one argument to make it absolute, or 2 or more arguments to perform path resolution. Note that path resolution is not the same as URL resolution: Url.resolve('file://foo', 'bar') = 'file://bar' path.resolve('/foo', 'bar') = 'foo/bar' AbstractFS.resolve('file://foo', 'bar') = 'file://foo/bar' AbstractFS.resolve('/foo', 'bar') = '/foo/bar' */ export function resolve(url : string, ...others : string[]) { url = Url.resolve(cwd, url); for (const other of others) url = Url.resolve(url + '/', other); return url; } export async function mkdirRecursive(url : string) { const [parsed, backend] = getBackend(url); return backend.mkdirRecursive(parsed); } export async function download(url : string, ...extraArgs : string[]) { const [parsed, backend] = getBackend(url); return backend.download(parsed, ...extraArgs); } export async function upload(localdir : string, url : string, ...extraArgs : string[]) { const [parsed, backend] = getBackend(url); return backend.upload(localdir, parsed, ...extraArgs); } export async function removeRecursive(url : string) { const [parsed, backend] = getBackend(url); return backend.removeRecursive(parsed); } export async function sync(url1 : string, url2 : string, ...extraArgs : string[]) { const [parsed1, backend1] = getBackend(url1); const [parsed2, backend2] = getBackend(url2); if (backend1 === backend2) { await backend1.sync(parsed1, parsed2, ...extraArgs); return; } // download to a temporary directory, then upload const tmpdir = await backend1.download(parsed1, ...extraArgs); await backend2.upload(tmpdir, parsed2, ...extraArgs); // tmpdir is not created for local file if (parsed1.protocol !== 'file:') await removeTemporary(tmpdir); } export function createWriteStream(url : string, localSpooling : boolean) { const [parsed, backend] = getBackend(url); return backend.createWriteStream(parsed, localSpooling); } export function createReadStream(url : string) { const [parsed, backend] = getBackend(url); return backend.createReadStream(parsed); } export function getDownloadLinkOrStream(url : string) { const [parsed, backend] = getBackend(url); return backend.getDownloadLinkOrStream(parsed); } export async function writeFile(url : string, blob : string|Buffer|NodeJS.ReadableStream, options ?: { contentType ?: string }) { const [parsed, backend] = getBackend(url); return backend.writeFile(parsed, blob, options); } export async function removeTemporary(pathname : string) { if (!pathname.startsWith('/var/tmp')) return; await _backends['file:'].removeRecursive({ pathname }); } export function isLocal(url : string) { const [parsed,] = getBackend(url); return parsed.protocol === 'file:' && !parsed.hostname; } export function getLocalPath(url : string) { const [parsed,] = getBackend(url); assert(parsed.protocol === 'file:'); return parsed.pathname; }
the_stack
import * as tf from '@tensorflow/tfjs'; import { chunk } from 'lodash'; import * as types from '../../../types'; import { EmbeddingsModel } from '../embeddings/EmbeddingsModel'; export default class ClassificationModel extends types.PipelineModel implements types.IPipelineModel { private static setup( config: types.IClassificationModelParams & types.IDefaultModelParams, { maxWordsPerSentence: maxWords, intents }: types.IDatasetParams ) { const numClasses = intents.length; const LEARNING_RATE = 0.0012; // use 1e-4 as default as alternative starting point const ADAM_BETA_1 = 0.0008; const ADAM_BETA_2 = 0.03; const optimizer = tf.train.adam(LEARNING_RATE, ADAM_BETA_1, ADAM_BETA_2); // Layer 1: Convolution + max pool const input = tf.input({ dtype: 'float32', name: 'embedded_words', shape: [maxWords, config.embeddingDimensions] }); const convLayer1 = tf.layers .conv1d({ activation: 'relu', filters: config.numFilters, inputShape: [maxWords, config.embeddingDimensions], kernelInitializer: 'randomNormal', kernelSize: [config.filterSizes[0]], name: 'classConv1', padding: 'valid' }) .apply(input); const maxpool1 = tf.layers .maxPooling1d({ padding: 'valid', poolSize: maxWords - config.filterSizes[0] + 1 }) .apply(convLayer1) as tf.SymbolicTensor; // Layer 2: Convolution + max pool const convLayer2 = tf.layers .conv1d({ activation: 'relu', filters: config.numFilters, inputShape: [maxWords, config.embeddingDimensions], kernelInitializer: 'randomNormal', kernelSize: [config.filterSizes[1]], name: 'classConv2', padding: 'valid' }) .apply(input); const maxpool2 = tf.layers .maxPooling1d({ padding: 'valid', poolSize: maxWords - config.filterSizes[1] + 1 }) .apply(convLayer2) as tf.SymbolicTensor; // Layer 3: Convolution + max pool const convLayer3 = tf.layers .conv1d({ activation: 'relu', filters: config.numFilters, inputShape: [maxWords, config.embeddingDimensions], kernelInitializer: 'randomNormal', kernelSize: [config.filterSizes[2]], name: 'classConv3', padding: 'valid' }) .apply(input); const maxpool3 = tf.layers .maxPooling1d({ padding: 'valid', poolSize: maxWords - config.filterSizes[2] + 1 }) .apply(convLayer3) as tf.SymbolicTensor; // Concatenation of all CNN layers on different levels and apply a fully connected dense layer const concatLayer = tf.layers.concatenate({ axis: 1 }).apply([maxpool1, maxpool2, maxpool3]); const flat = tf.layers.flatten().apply(concatLayer); const dropOut = tf.layers.dropout({ rate: config.drop }).apply(flat) as tf.SymbolicTensor; const flatPool1 = tf.layers.flatten().apply(maxpool1) as tf.SymbolicTensor; const concatForClassification = tf.layers.concatenate({ axis: 1 }).apply([dropOut, flatPool1]); const outClassification = tf.layers .dense({ activation: 'softmax', units: numClasses }) .apply(concatForClassification) as tf.SymbolicTensor; const model = tf.model({ inputs: input, outputs: outClassification }); model.compile({ loss: 'categoricalCrossentropy', metrics: ['accuracy'], optimizer }); return model; } private config: types.IClassificationModelParams & types.IDefaultModelParams; private datasetParams: types.IDatasetParams; private model: tf.LayersModel; private embeddingsModel: EmbeddingsModel; private logger: types.IPipelineModelLogger; private classificationTrainStatsHandler: types.ITrainStatsHandler['classification'] | undefined; constructor( config: types.IClassificationModelParams & types.IDefaultModelParams, datasetParams: types.IDatasetParams, embeddingsModel: EmbeddingsModel, logger: types.IPipelineModelLogger, pretrainedModel?: tf.LayersModel, classificationTrainStatsHandler?: types.ITrainStatsHandler['classification'] ) { super(); this.config = config; this.datasetParams = datasetParams; this.embeddingsModel = embeddingsModel; this.model = pretrainedModel ? pretrainedModel : ClassificationModel.setup(this.config, this.datasetParams); this.logger = logger; this.classificationTrainStatsHandler = classificationTrainStatsHandler; } public tfModel = () => this.model; public predict = (sentences: string[]): types.IClassificationPred[] => { const prediction = [] as types.IClassificationPred[]; tf.tidy(() => { const embeddedSentences = this.embeddingsModel.embed(sentences); const output = this.model.predict(embeddedSentences) as tf.Tensor<tf.Rank>; const d = output.dataSync() as Float32Array; output.dispose(); embeddedSentences.dispose(); const intents = this.datasetParams.intents; sentences.forEach((s, i) => { const preds = d.slice(i * intents.length, i * intents.length + intents.length); const sentencePreds: types.IClassificationPred[] = []; preds.forEach((p, idx) => sentencePreds.push({ confidence: p, intent: intents[idx], sentence: s }) ); sentencePreds.sort((a, b) => (a.confidence > b.confidence ? -1 : 1)); prediction.push(sentencePreds[0]); }); }); return prediction; }; public train = async (trainDataset: types.ITrainingParams): Promise<void> => { const trainYChunks = chunk(trainDataset.trainY, this.config.batchSize); const trainXChunks = chunk(trainDataset.trainX, this.config.batchSize); this.logger.log('Start training classification model!'); const m = this.model; let enoughAccuracyReached = false; for (const [index, xChunk] of trainXChunks.entries()) { if (enoughAccuracyReached) { return; } const embeddedSentences = this.embeddingsModel.embed(xChunk); const dataLabels = tf.tensor1d(trainYChunks[index], 'int32'); const hotEncodedLabels = tf.oneHot(dataLabels, this.datasetParams.intents.length); await m.fit(embeddedSentences, hotEncodedLabels, { // batchSize: this.config.batchSize, callbacks: { onBatchEnd: tf.nextFrame }, epochs: this.config.epochs, shuffle: true, validationSplit: this.config.trainingValidationSplit }); dataLabels.dispose(); embeddedSentences.dispose(); hotEncodedLabels.dispose(); const h = m.history.history; const c = h.val_loss.length - 1; if (this.classificationTrainStatsHandler) { this.classificationTrainStatsHandler({ batch: index + 1, batchEpochs: m.history.epoch.length, currentBatchSize: trainXChunks[index].length, tensorsInMemory: tf.memory().numTensors, totalBatches: trainXChunks.length, trainingAccuracy: h.acc[c], trainingLoss: h.loss[c], validationAccuracy: h.val_acc[c], validationLoss: h.val_loss[c] }); } this.logger.log(`Trained ${m.history.epoch.length} epochs on batch ${index + 1} of ${trainXChunks.length}`); this.logger.log(`Training Loss: ${h.loss[c]} | Training Accuracy: ${h.acc[c]}`); this.logger.log(`Validation Loss: ${h.val_loss[c]} | Validation Accuracy: ${h.val_acc[c]}`); this.logger.warn(`(Memory) Number of tensors in memory at the end of batch: ${tf.memory().numTensors}`); this.logger.log('=================================================================================================='); if ( this.config.lossThresholdToStopTraining && h.loss[c] < this.config.lossThresholdToStopTraining && h.val_loss[c] < this.config.lossThresholdToStopTraining ) { enoughAccuracyReached = true; this.logger.warn(`Enough accuracy reached! Ending training after batch ${index + 1} of ${trainXChunks.length}`); this.logger.log('=================================================================================================='); } } }; public test = async ( testExamples: types.ITestingParams, resultsHandler?: types.ITestPredictionsHandler ): Promise<types.IPredictionStats> => { const handler = resultsHandler ? resultsHandler : this.defaultResultsLogger; const stats: types.IPredictionStats = { correct: 0, wrong: 0, lowConfidence: 0 }; const x = chunk(testExamples.testX, this.config.batchSize); const y = chunk(testExamples.testY, this.config.batchSize); for (const [i, sentences] of x.entries()) { const predictions = this.predict(sentences); handler(sentences, y[i], predictions, stats); } return stats; }; private defaultResultsLogger = ( x: types.ITestingParams['testX'], y: types.ITestingParams['testY'], o: types.IClassificationPred[], stats: types.IPredictionStats ): types.IPredictionStats => { x.forEach((s, i) => { const intent = this.datasetParams.intents[y[i]]; const correct = o[i].intent === intent; if (o[i].confidence < this.config.lowConfidenceThreshold) { if (stats.lowConfidence === undefined) { return; } stats.lowConfidence++; this.logger.warn(`LOW CONFIDENCE (intent: ${o[i].intent}, confidence: ${o[i].confidence}) - ${s}`); } else if (correct) { stats.correct++; this.logger.debug(`CORRECT (intent: ${o[i].intent}, confidence: ${o[i].confidence}) - ${s}`); } else { stats.wrong++; this.logger.error(`WRONG (intent: ${o[i].intent}, confidence: ${o[i].confidence}) - ${s}`); } }); return stats; }; }
the_stack
// Copyright (c) 2019 Erin Catto // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import * as b2 from "@box2d"; import * as testbed from "@testbed"; /// export class Rope extends testbed.Test { public readonly m_rope1: b2.Rope = new b2.Rope(); public readonly m_rope2: b2.Rope = new b2.Rope(); public readonly m_tuning1: b2.RopeTuning = new b2.RopeTuning(); public readonly m_tuning2: b2.RopeTuning = new b2.RopeTuning(); public m_iterations1: number = 0; public m_iterations2: number = 0; public readonly m_position1: b2.Vec2 = new b2.Vec2(); public readonly m_position2: b2.Vec2 = new b2.Vec2(); public m_speed: number = 0.0; constructor() { super(); const N: number = 20; const L: number = 0.5; // b2Vec2 vertices[N]; const vertices: b2.Vec2[] = b2.Vec2.MakeArray(N); // float masses[N]; const masses: number[] = b2.MakeNumberArray(N); for (let i = 0; i < N; ++i) { vertices[i].Set(0.0, L * (N - i)); masses[i] = 1.0; } masses[0] = 0.0; masses[1] = 0.0; this.m_tuning1.bendHertz = 30.0; this.m_tuning1.bendDamping = 4.0; this.m_tuning1.bendStiffness = 1.0; this.m_tuning1.bendingModel = b2.pbdTriangleBendingModel; this.m_tuning1.isometric = true; this.m_tuning1.stretchHertz = 30.0; this.m_tuning1.stretchDamping = 4.0; this.m_tuning1.stretchStiffness = 1.0; this.m_tuning1.stretchingModel = b2.pbdStretchingModel; this.m_tuning2.bendHertz = 30.0; this.m_tuning2.bendDamping = 0.7; this.m_tuning2.bendStiffness = 1.0; this.m_tuning2.bendingModel = b2.pbdHeightBendingModel; this.m_tuning2.isometric = true; this.m_tuning2.stretchHertz = 30.0; this.m_tuning2.stretchDamping = 1.0; this.m_tuning2.stretchStiffness = 1.0; this.m_tuning2.stretchingModel = b2.pbdStretchingModel; this.m_position1.Set(-5.0, 15.0); this.m_position2.Set(5.0, 15.0); const def: b2.RopeDef = new b2.RopeDef(); // def.vertices = vertices; vertices.forEach((value: b2.Vec2) => def.vertices.push(value)); def.count = N; def.gravity.Set(0.0, -10.0); // def.masses = masses; masses.forEach((value: number) => def.masses.push(value)); def.position.Copy(this.m_position1); def.tuning.Copy(this.m_tuning1); this.m_rope1.Create(def); def.position.Copy(this.m_position2); def.tuning.Copy(this.m_tuning2); this.m_rope2.Create(def); this.m_iterations1 = 8; this.m_iterations2 = 8; this.m_speed = 10.0; } // void UpdateUI() override // { // ImGui::SetNextWindowPos(ImVec2(10.0, 100.0)); // ImGui::SetNextWindowSize(ImVec2(200.0, 700.0)); // ImGui::Begin("Tuning", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); // ImGui::Separator(); // ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); // const ImGuiComboFlags comboFlags = 0; // const char* bendModels[] = { "Spring", "PBD Ang", "XPBD Ang", "PBD Dist", "PBD Height", "PBD Triangle" }; // const char* stretchModels[] = { "PBD", "XPBD" }; // ImGui::Text("Rope 1"); // static int bendModel1 = this.m_tuning1.bendingModel; // if (ImGui::BeginCombo("Bend Model##1", bendModels[bendModel1], comboFlags)) // { // for (int i = 0; i < Ithis.M_ARRAYSIZE(bendModels); ++i) // { // bool isSelected = (bendModel1 == i); // if (ImGui::Selectable(bendModels[i], isSelected)) // { // bendModel1 = i; // this.m_tuning1.bendingModel = b2BendingModel(i); // } // if (isSelected) // { // ImGui::SetItemDefaultFocus(); // } // } // ImGui::EndCombo(); // } // ImGui::SliderFloat("Damping##B1", &this.m_tuning1.bendDamping, 0.0, 4.0, "%.1f"); // ImGui::SliderFloat("Hertz##B1", &this.m_tuning1.bendHertz, 0.0, 60.0, "%.0"); // ImGui::SliderFloat("Stiffness##B1", &this.m_tuning1.bendStiffness, 0.0, 1.0, "%.1f"); // ImGui::Checkbox("Isometric##1", &this.m_tuning1.isometric); // ImGui::Checkbox("Fixed Mass##1", &this.m_tuning1.fixedEffectiveMass); // ImGui::Checkbox("Warm Start##1", &this.m_tuning1.warmStart); // static int stretchModel1 = this.m_tuning1.stretchingModel; // if (ImGui::BeginCombo("Stretch Model##1", stretchModels[stretchModel1], comboFlags)) // { // for (int i = 0; i < Ithis.M_ARRAYSIZE(stretchModels); ++i) // { // bool isSelected = (stretchModel1 == i); // if (ImGui::Selectable(stretchModels[i], isSelected)) // { // stretchModel1 = i; // this.m_tuning1.stretchingModel = b2StretchingModel(i); // } // if (isSelected) // { // ImGui::SetItemDefaultFocus(); // } // } // ImGui::EndCombo(); // } // ImGui::SliderFloat("Damping##S1", &this.m_tuning1.stretchDamping, 0.0, 4.0, "%.1f"); // ImGui::SliderFloat("Hertz##S1", &this.m_tuning1.stretchHertz, 0.0, 60.0, "%.0"); // ImGui::SliderFloat("Stiffness##S1", &this.m_tuning1.stretchStiffness, 0.0, 1.0, "%.1f"); // ImGui::SliderInt("Iterations##1", &this.m_iterations1, 1, 100, "%d"); // ImGui::Separator(); // ImGui::Text("Rope 2"); // static int bendModel2 = this.m_tuning2.bendingModel; // if (ImGui::BeginCombo("Bend Model##2", bendModels[bendModel2], comboFlags)) // { // for (int i = 0; i < Ithis.M_ARRAYSIZE(bendModels); ++i) // { // bool isSelected = (bendModel2 == i); // if (ImGui::Selectable(bendModels[i], isSelected)) // { // bendModel2 = i; // this.m_tuning2.bendingModel = b2BendingModel(i); // } // if (isSelected) // { // ImGui::SetItemDefaultFocus(); // } // } // ImGui::EndCombo(); // } // ImGui::SliderFloat("Damping##B2", &this.m_tuning2.bendDamping, 0.0, 4.0, "%.1f"); // ImGui::SliderFloat("Hertz##B2", &this.m_tuning2.bendHertz, 0.0, 60.0, "%.0"); // ImGui::SliderFloat("Stiffness##B2", &this.m_tuning2.bendStiffness, 0.0, 1.0, "%.1f"); // ImGui::Checkbox("Isometric##2", &this.m_tuning2.isometric); // ImGui::Checkbox("Fixed Mass##2", &this.m_tuning2.fixedEffectiveMass); // ImGui::Checkbox("Warm Start##2", &this.m_tuning2.warmStart); // static int stretchModel2 = this.m_tuning2.stretchingModel; // if (ImGui::BeginCombo("Stretch Model##2", stretchModels[stretchModel2], comboFlags)) // { // for (int i = 0; i < Ithis.M_ARRAYSIZE(stretchModels); ++i) // { // bool isSelected = (stretchModel2 == i); // if (ImGui::Selectable(stretchModels[i], isSelected)) // { // stretchModel2 = i; // this.m_tuning2.stretchingModel = b2StretchingModel(i); // } // if (isSelected) // { // ImGui::SetItemDefaultFocus(); // } // } // ImGui::EndCombo(); // } // ImGui::SliderFloat("Damping##S2", &this.m_tuning2.stretchDamping, 0.0, 4.0, "%.1f"); // ImGui::SliderFloat("Hertz##S2", &this.m_tuning2.stretchHertz, 0.0, 60.0, "%.0"); // ImGui::SliderFloat("Stiffness##S2", &this.m_tuning2.stretchStiffness, 0.0, 1.0, "%.1f"); // ImGui::SliderInt("Iterations##2", &this.m_iterations2, 1, 100, "%d"); // ImGui::Separator(); // ImGui::SliderFloat("Speed", &this.m_speed, 10.0, 100.0, "%.0"); // if (ImGui::Button("Reset")) // { // this.m_position1.Set(-5.0, 15.0); // this.m_position2.Set(5.0, 15.0); // this.m_rope1.Reset(this.m_position1); // this.m_rope2.Reset(this.m_position2); // } // ImGui::PopItemWidth(); // ImGui::End(); // } public m_move_x: number = 0.0; public Keyboard(key: string) { switch (key) { case ",": this.m_move_x = -1.0; break; case ".": this.m_move_x = 1.0; break; } } public KeyboardUp(key: string): void { switch (key) { case ",": case ".": this.m_move_x = 0.0; break; } } public Step(settings: testbed.Settings): void { let dt: number = settings.m_hertz > 0.0 ? 1.0 / settings.m_hertz : 0.0; if (settings.m_pause === true && settings.m_singleStep === false) { dt = 0.0; } // if (glfwGetKey(g_mainWindow, GLFW_KEY_COMMA) == GLFW_PRESS) // { // this.m_position1.x -= this.m_speed * dt; // this.m_position2.x -= this.m_speed * dt; // } // if (glfwGetKey(g_mainWindow, GLFW_KEY_PERIOD) == GLFW_PRESS) // { // this.m_position1.x += this.m_speed * dt; // this.m_position2.x += this.m_speed * dt; // } if (this.m_move_x) { this.m_position1.x += this.m_move_x * this.m_speed * dt; this.m_position2.x += this.m_move_x * this.m_speed * dt; } this.m_rope1.SetTuning(this.m_tuning1); this.m_rope2.SetTuning(this.m_tuning2); this.m_rope1.Step(dt, this.m_iterations1, this.m_position1); this.m_rope2.Step(dt, this.m_iterations2, this.m_position2); super.Step(settings); this.m_rope1.Draw(testbed.g_debugDraw); this.m_rope2.Draw(testbed.g_debugDraw); testbed.g_debugDraw.DrawString(5, this.m_textLine, "Press comma and period to move left and right"); // this.m_textLine += this.m_textIncrement; } public static Create(): testbed.Test { return new Rope(); } } export const testIndex: number = testbed.RegisterTest("Rope", "Bending", Rope.Create); // class Rope : public Test // { // public: // Rope() // { // const int32 N = 20; // const float L = 0.5f; // b2Vec2 vertices[N]; // float masses[N]; // for (let i = 0; i < N; ++i) // { // vertices[i].Set(0.0, L * (N - i)); // masses[i] = 1.0; // } // masses[0] = 0.0; // masses[1] = 0.0; // this.m_tuning1.bendHertz = 30.0; // this.m_tuning1.bendDamping = 4.0; // this.m_tuning1.bendStiffness = 1.0; // this.m_tuning1.bendingModel = b2_xpbdAngleBendingModel; // this.m_tuning1.isometric = true; // this.m_tuning1.stretchHertz = 30.0; // this.m_tuning1.stretchDamping = 4.0; // this.m_tuning1.stretchStiffness = 1.0; // this.m_tuning1.stretchingModel = b2_xpbdStretchingModel; // this.m_tuning2.bendHertz = 30.0; // this.m_tuning2.bendDamping = 0.7f; // this.m_tuning2.bendStiffness = 1.0; // this.m_tuning2.bendingModel = b2_pbdHeightBendingModel; // this.m_tuning2.isometric = true; // this.m_tuning2.stretchHertz = 30.0; // this.m_tuning2.stretchDamping = 1.0; // this.m_tuning2.stretchStiffness = 1.0; // this.m_tuning2.stretchingModel = b2_pbdStretchingModel; // this.m_position1.Set(-5.0, 15.0); // this.m_position2.Set(5.0, 15.0); // b2RopeDef def; // def.vertices = vertices; // def.count = N; // def.gravity.Set(0.0, -10.0); // def.masses = masses; // def.position = this.m_position1; // def.tuning = this.m_tuning1; // this.m_rope1.Create(def); // def.position = this.m_position2; // def.tuning = this.m_tuning2; // this.m_rope2.Create(def); // this.m_iterations1 = 8; // this.m_iterations2 = 8; // this.m_speed = 10.0; // } // void UpdateUI() override // { // ImGui::SetNextWindowPos(ImVec2(10.0, 100.0)); // ImGui::SetNextWindowSize(ImVec2(200.0, 700.0)); // ImGui::Begin("Tuning", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize); // ImGui::Separator(); // ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); // const ImGuiComboFlags comboFlags = 0; // const char* bendModels[] = { "Spring", "PBD Ang", "XPBD Ang", "PBD Dist", "PBD Height" }; // const char* stretchModels[] = { "PBD", "XPBD" }; // ImGui::Text("Rope 1"); // static int bendModel1 = this.m_tuning1.bendingModel; // if (ImGui::BeginCombo("Bend Model##1", bendModels[bendModel1], comboFlags)) // { // for (int i = 0; i < Ithis.M_ARRAYSIZE(bendModels); ++i) // { // bool isSelected = (bendModel1 == i); // if (ImGui::Selectable(bendModels[i], isSelected)) // { // bendModel1 = i; // this.m_tuning1.bendingModel = b2BendingModel(i); // } // if (isSelected) // { // ImGui::SetItemDefaultFocus(); // } // } // ImGui::EndCombo(); // } // ImGui::SliderFloat("Damping##B1", &this.m_tuning1.bendDamping, 0.0, 4.0, "%.1f"); // ImGui::SliderFloat("Hertz##B1", &this.m_tuning1.bendHertz, 0.0, 60.0, "%.0"); // ImGui::SliderFloat("Stiffness##B1", &this.m_tuning1.bendStiffness, 0.0, 1.0, "%.1f"); // ImGui::Checkbox("Isometric##1", &this.m_tuning1.isometric); // ImGui::Checkbox("Fixed Mass##1", &this.m_tuning1.fixedEffectiveMass); // ImGui::Checkbox("Warm Start##1", &this.m_tuning1.warmStart); // static int stretchModel1 = this.m_tuning1.stretchingModel; // if (ImGui::BeginCombo("Stretch Model##1", stretchModels[stretchModel1], comboFlags)) // { // for (int i = 0; i < Ithis.M_ARRAYSIZE(stretchModels); ++i) // { // bool isSelected = (stretchModel1 == i); // if (ImGui::Selectable(stretchModels[i], isSelected)) // { // stretchModel1 = i; // this.m_tuning1.stretchingModel = b2StretchingModel(i); // } // if (isSelected) // { // ImGui::SetItemDefaultFocus(); // } // } // ImGui::EndCombo(); // } // ImGui::SliderFloat("Damping##S1", &this.m_tuning1.stretchDamping, 0.0, 4.0, "%.1f"); // ImGui::SliderFloat("Hertz##S1", &this.m_tuning1.stretchHertz, 0.0, 60.0, "%.0"); // ImGui::SliderFloat("Stiffness##S1", &this.m_tuning1.stretchStiffness, 0.0, 1.0, "%.1f"); // ImGui::SliderInt("Iterations##1", &this.m_iterations1, 1, 100, "%d"); // ImGui::Separator(); // ImGui::Text("Rope 2"); // static int bendModel2 = this.m_tuning2.bendingModel; // if (ImGui::BeginCombo("Bend Model##2", bendModels[bendModel2], comboFlags)) // { // for (int i = 0; i < Ithis.M_ARRAYSIZE(bendModels); ++i) // { // bool isSelected = (bendModel2 == i); // if (ImGui::Selectable(bendModels[i], isSelected)) // { // bendModel2 = i; // this.m_tuning2.bendingModel = b2BendingModel(i); // } // if (isSelected) // { // ImGui::SetItemDefaultFocus(); // } // } // ImGui::EndCombo(); // } // ImGui::SliderFloat("Damping##B2", &this.m_tuning2.bendDamping, 0.0, 4.0, "%.1f"); // ImGui::SliderFloat("Hertz##B2", &this.m_tuning2.bendHertz, 0.0, 60.0, "%.0"); // ImGui::SliderFloat("Stiffness##B2", &this.m_tuning2.bendStiffness, 0.0, 1.0, "%.1f"); // ImGui::Checkbox("Isometric##2", &this.m_tuning2.isometric); // ImGui::Checkbox("Fixed Mass##2", &this.m_tuning2.fixedEffectiveMass); // ImGui::Checkbox("Warm Start##2", &this.m_tuning2.warmStart); // static int stretchModel2 = this.m_tuning2.stretchingModel; // if (ImGui::BeginCombo("Stretch Model##2", stretchModels[stretchModel2], comboFlags)) // { // for (int i = 0; i < Ithis.M_ARRAYSIZE(stretchModels); ++i) // { // bool isSelected = (stretchModel2 == i); // if (ImGui::Selectable(stretchModels[i], isSelected)) // { // stretchModel2 = i; // this.m_tuning2.stretchingModel = b2StretchingModel(i); // } // if (isSelected) // { // ImGui::SetItemDefaultFocus(); // } // } // ImGui::EndCombo(); // } // ImGui::SliderFloat("Damping##S2", &this.m_tuning2.stretchDamping, 0.0, 4.0, "%.1f"); // ImGui::SliderFloat("Hertz##S2", &this.m_tuning2.stretchHertz, 0.0, 60.0, "%.0"); // ImGui::SliderFloat("Stiffness##S2", &this.m_tuning2.stretchStiffness, 0.0, 1.0, "%.1f"); // ImGui::SliderInt("Iterations##2", &this.m_iterations2, 1, 100, "%d"); // ImGui::Separator(); // ImGui::SliderFloat("Speed", &this.m_speed, 10.0, 100.0, "%.0"); // if (ImGui::Button("Reset")) // { // this.m_position1.Set(-5.0, 15.0); // this.m_position2.Set(5.0, 15.0); // this.m_rope1.Reset(this.m_position1); // this.m_rope2.Reset(this.m_position2); // } // ImGui::PopItemWidth(); // ImGui::End(); // } // void Step(Settings& settings) override // { // float dt = settings.m_hertz > 0.0 ? 1.0 / settings.m_hertz : 0.0; // if (settings.m_pause == 1 && settings.m_singleStep == 0) // { // dt = 0.0; // } // if (glfwGetKey(g_mainWindow, GLFW_KEY_COMMA) == GLFW_PRESS) // { // this.m_position1.x -= this.m_speed * dt; // this.m_position2.x -= this.m_speed * dt; // } // if (glfwGetKey(g_mainWindow, GLFW_KEY_PERIOD) == GLFW_PRESS) // { // this.m_position1.x += this.m_speed * dt; // this.m_position2.x += this.m_speed * dt; // } // this.m_rope1.SetTuning(this.m_tuning1); // this.m_rope2.SetTuning(this.m_tuning2); // this.m_rope1.Step(dt, this.m_iterations1, this.m_position1); // this.m_rope2.Step(dt, this.m_iterations2, this.m_position2); // Test::Step(settings); // this.m_rope1.Draw(&g_debugDraw); // this.m_rope2.Draw(&g_debugDraw); // g_debugDraw.DrawString(5, this.m_textLine, "Press comma and period to move left and right"); // this.m_textLine += this.m_textIncrement; // } // static Test* Create() // { // return new Rope; // } // b2Rope this.m_rope1; // b2Rope this.m_rope2; // b2RopeTuning this.m_tuning1; // b2RopeTuning this.m_tuning2; // int32 this.m_iterations1; // int32 this.m_iterations2; // b2Vec2 this.m_position1; // b2Vec2 this.m_position2; // float this.m_speed; // }; // static int testIndex = RegisterTest("Rope", "Bending", Rope::Create); // export class OldRope extends testbed.Test { // // public this.m_rope = new b2.Rope(); // public m_angle = 0.0; // constructor() { // super(); // /*const int32*/ // const N = 40; // /*b2.Vec2[]*/ // const vertices = b2.Vec2.MakeArray(N); // /*float32[]*/ // const masses = b2.MakeNumberArray(N); // for (let i = 0; i < N; ++i) { // vertices[i].Set(0.0, 20.0 - 0.25 * i); // masses[i] = 1.0; // } // masses[0] = 0.0; // masses[1] = 0.0; // /*b2.RopeDef*/ // // const def = new b2.RopeDef(); // // def.vertices = vertices; // // def.count = N; // // def.gravity.Set(0.0, -10.0); // // def.masses = masses; // // def.damping = 0.1; // // def.k2 = 1.0; // // def.k3 = 0.5; // // this.m_rope.Initialize(def); // this.m_angle = 0.0; // // this.m_rope.SetAngle(this.m_angle); // } // public Keyboard(key: string) { // switch (key) { // case "q": // this.m_angle = b2.Max(-b2.pi, this.m_angle - 0.05 * b2.pi); // // this.m_rope.SetAngle(this.m_angle); // break; // case "e": // this.m_angle = b2.Min(b2.pi, this.m_angle + 0.05 * b2.pi); // // this.m_rope.SetAngle(this.m_angle); // break; // } // } // public Step(settings: testbed.Settings): void { // // let dt = settings.m_hertz > 0.0 ? 1.0 / settings.m_hertz : 0.0; // // if (settings.m_pause && !settings.m_singleStep) { // // dt = 0.0; // // } // // this.m_rope.Step(dt, 1); // super.Step(settings); // // this.m_rope.Draw(testbed.g_debugDraw); // testbed.g_debugDraw.DrawString(5, this.m_textLine, "Press (q,e) to adjust target angle"); // this.m_textLine += testbed.DRAW_STRING_NEW_LINE; // testbed.g_debugDraw.DrawString(5, this.m_textLine, `Target angle = ${(this.m_angle * 180.0 / b2.pi).toFixed(2)} degrees`); // this.m_textLine += testbed.DRAW_STRING_NEW_LINE; // } // public static Create(): testbed.Test { // return new OldRope(); // } // }
the_stack
import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as protos from 'fabric-protos'; import { CollectionConfig, Collection } from '../src/CollectionConfig'; import { EndorsementPolicy } from '../src/Policy'; chai.should(); chai.use(sinonChai); chai.use(chaiAsPromised); // tslint:disable:no-unused-expression describe('CollectionConfig', () => { it('should create the collection', () => { const collection: Collection = { name: 'myCollection', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 0, maxPeerCount: 3 }; const staticCollectionConfig: protos.common.StaticCollectionConfig = new protos.common.StaticCollectionConfig(); staticCollectionConfig.name = collection.name; staticCollectionConfig.required_peer_count = collection.requiredPeerCount; staticCollectionConfig.maximum_peer_count = collection.maxPeerCount; staticCollectionConfig.block_to_live = 0; staticCollectionConfig.member_only_read = false; staticCollectionConfig.member_only_write = false; const collectionPolicyConfig: protos.common.CollectionPolicyConfig = new protos.common.CollectionPolicyConfig(); const endorsementPolicy: EndorsementPolicy = new EndorsementPolicy(); collectionPolicyConfig.signature_policy = endorsementPolicy.buildPolicy(collection.policy); staticCollectionConfig.member_orgs_policy = collectionPolicyConfig; const collectionConfig: protos.common.CollectionConfig = new protos.common.CollectionConfig(); collectionConfig.static_collection_config = staticCollectionConfig; const collectionConfigPackage: protos.common.ICollectionConfigPackage = { config: [collectionConfig] }; const expectedResult: protos.common.CollectionConfigPackage = new protos.common.CollectionConfigPackage(collectionConfigPackage); const result: protos.common.CollectionConfigPackage = CollectionConfig.buildCollectionConfigPackage([collection]); result.should.deep.equal(expectedResult); }); it('should create the collection with optional properties', () => { const collection: Collection = { name: 'myCollection', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 1, maxPeerCount: 3, memberOnlyRead: true, memberOnlyWrite: true, blockToLive: 10 }; const staticCollectionConfig: protos.common.StaticCollectionConfig = new protos.common.StaticCollectionConfig(); staticCollectionConfig.name = collection.name; staticCollectionConfig.required_peer_count = collection.requiredPeerCount; staticCollectionConfig.maximum_peer_count = collection.maxPeerCount; staticCollectionConfig.block_to_live = collection.blockToLive; staticCollectionConfig.member_only_read = collection.memberOnlyRead; staticCollectionConfig.member_only_write = collection.memberOnlyWrite; const collectionPolicyConfig: protos.common.CollectionPolicyConfig = new protos.common.CollectionPolicyConfig(); const endorsementPolicy: EndorsementPolicy = new EndorsementPolicy(); collectionPolicyConfig.signature_policy = endorsementPolicy.buildPolicy(collection.policy); staticCollectionConfig.member_orgs_policy = collectionPolicyConfig; const collectionConfig: protos.common.CollectionConfig = new protos.common.CollectionConfig(); collectionConfig.static_collection_config = staticCollectionConfig; const collectionConfigPackage: protos.common.ICollectionConfigPackage = { config: [collectionConfig] }; const expectedResult: protos.common.CollectionConfigPackage = new protos.common.CollectionConfigPackage(collectionConfigPackage); const result: protos.common.CollectionConfigPackage = CollectionConfig.buildCollectionConfigPackage([collection]); result.should.deep.equal(expectedResult); }); it('should create the collection with endorsement policy property', () => { const collection: Collection = { name: 'myCollection', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 1, maxPeerCount: 3, endorsementPolicy: { signaturePolicy: `AND('Org1MSP.member', 'Org2MSP.member')` } }; const staticCollectionConfig: protos.common.StaticCollectionConfig = new protos.common.StaticCollectionConfig(); staticCollectionConfig.name = collection.name; staticCollectionConfig.required_peer_count = collection.requiredPeerCount; staticCollectionConfig.maximum_peer_count = collection.maxPeerCount; staticCollectionConfig.block_to_live = 0; staticCollectionConfig.member_only_read = false; staticCollectionConfig.member_only_write = false; const collectionPolicyConfig: protos.common.CollectionPolicyConfig = new protos.common.CollectionPolicyConfig(); const endorsementPolicy: EndorsementPolicy = new EndorsementPolicy(); collectionPolicyConfig.signature_policy = endorsementPolicy.buildPolicy(collection.policy); staticCollectionConfig.member_orgs_policy = collectionPolicyConfig; const collectionConfig: protos.common.CollectionConfig = new protos.common.CollectionConfig(); collectionConfig.static_collection_config = staticCollectionConfig; const applicationPolicy: protos.common.ApplicationPolicy = new protos.common.ApplicationPolicy(); const policy: EndorsementPolicy = new EndorsementPolicy(); const signaturePolicy: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(collection.endorsementPolicy.signaturePolicy); applicationPolicy.signature_policy = signaturePolicy; staticCollectionConfig.endorsement_policy = applicationPolicy; const collectionConfigPackage: protos.common.ICollectionConfigPackage = { config: [collectionConfig] }; const expectedResult: protos.common.CollectionConfigPackage = new protos.common.CollectionConfigPackage(collectionConfigPackage); const result: protos.common.CollectionConfigPackage = CollectionConfig.buildCollectionConfigPackage([collection]); result.should.deep.equal(expectedResult); }); it('should create the collection with endorsement policy property (channel policy reference)', () => { const collection: Collection = { name: 'myCollection', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 1, maxPeerCount: 3, endorsementPolicy: { channelConfigPolicy: 'myPolicy' } }; const staticCollectionConfig: protos.common.StaticCollectionConfig = new protos.common.StaticCollectionConfig(); staticCollectionConfig.name = collection.name; staticCollectionConfig.required_peer_count = collection.requiredPeerCount; staticCollectionConfig.maximum_peer_count = collection.maxPeerCount; staticCollectionConfig.block_to_live = 0; staticCollectionConfig.member_only_read = false; staticCollectionConfig.member_only_write = false; const collectionPolicyConfig: protos.common.CollectionPolicyConfig = new protos.common.CollectionPolicyConfig(); const endorsementPolicy: EndorsementPolicy = new EndorsementPolicy(); collectionPolicyConfig.signature_policy = endorsementPolicy.buildPolicy(collection.policy); staticCollectionConfig.member_orgs_policy = collectionPolicyConfig; const collectionConfig: protos.common.CollectionConfig = new protos.common.CollectionConfig(); collectionConfig.static_collection_config = staticCollectionConfig; const applicationPolicy: protos.common.ApplicationPolicy = new protos.common.ApplicationPolicy(); applicationPolicy.channel_config_policy_reference = collection.endorsementPolicy.channelConfigPolicy; staticCollectionConfig.endorsement_policy = applicationPolicy; const collectionConfigPackage: protos.common.ICollectionConfigPackage = { config: [collectionConfig] }; const expectedResult: protos.common.CollectionConfigPackage = new protos.common.CollectionConfigPackage(collectionConfigPackage); const result: protos.common.CollectionConfigPackage = CollectionConfig.buildCollectionConfigPackage([collection]); result.should.deep.equal(expectedResult); }); it('should error if no collections passed in', () => { (() => CollectionConfig.buildCollectionConfigPackage([])).should.throw('CollectionConfig invalid: collection config is empty'); }); it('should error if no name given', () => { // @ts-ignore (() => CollectionConfig.buildCollectionConfigPackage([{ policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 1, maxPeerCount: 3 }]) ).should.throw('CollectionConfig invalid: missing property name, name should be a string'); }); it('should error if no policy given', () => { // @ts-ignore (() => CollectionConfig.buildCollectionConfigPackage([{ name: 'collectionMarbles', requiredPeerCount: 1, maxPeerCount: 3 }])).should.throw('CollectionConfig invalid: missing property policy'); }); it('should error if no requiredPeerCount given', () => { // @ts-ignore (() => CollectionConfig.buildCollectionConfigPackage([{ name: 'collectionMarbles', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, maxPeerCount: 3 }])).should.throw('CollectionConfig invalid: missing property requiredPeerCount, requiredPeerCount should be a integer'); }); it('should error if no maxPeerCount given', () => { // @ts-ignore (() => CollectionConfig.buildCollectionConfigPackage([{ name: 'collectionMarbles', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 1 }])).should.throw('CollectionConfig invalid: missing property maxPeerCount, maxPeerCount should be a integer'); }); it('should error if maxPeerCount is less than requiredPeerCount', () => { // @ts-ignore (() => CollectionConfig.buildCollectionConfigPackage([{ name: 'collectionMarbles', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 4, maxPeerCount: 3 }])).should.throw('CollectionConfig invalid: maxPeerCount should be greater than requiredPeerCount'); }); it('should error if blockToLive is negative', () => { // @ts-ignore (() => CollectionConfig.buildCollectionConfigPackage([{ name: 'collectionMarbles', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 1, maxPeerCount: 3, blockToLive: -1, }])).should.throw('CollectionConfig invalid: blockToLive should should be a positive number'); }); it('should error if memberOnlyRead is not a boolean', () => { (() => { const collection: Collection = { name: 'collectionMarbles', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 1, maxPeerCount: 3 }; // @ts-ignore collection.memberOnlyRead = 'bob'; CollectionConfig.buildCollectionConfigPackage([collection]); }).should.throw('CollectionConfig invalid: memberOnlyRead property should be a boolean'); }); it('should error if memberOnlyWrite is not a boolean', () => { (() => { const collection: Collection = { name: 'collectionMarbles', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 1, maxPeerCount: 3 }; // @ts-ignore collection.memberOnlyWrite = 'bob'; CollectionConfig.buildCollectionConfigPackage([collection]); }).should.throw('CollectionConfig invalid: memberOnlyWrite property should be a boolean'); }); });
the_stack
import * as path from 'path'; import { EslintStrategy } from "./BaseEslintEngine"; import {FileHandler} from '../util/FileHandler'; import {ENGINE, LANGUAGE, HARDCODED_RULES} from '../../Constants'; import {ESRule, ESRuleConfig, LooseObject, RuleViolation} from '../../types'; import { Logger, Messages, SfdxError } from '@salesforce/core'; import { OutputProcessor } from '../pmd/OutputProcessor'; import {deepCopy} from '../../lib/util/Utils'; import {EslintStrategyHelper, ProcessRuleViolationType, RuleDefaultStatus} from './EslintCommons'; Messages.importMessagesDirectory(__dirname); const messages = Messages.loadMessages('@salesforce/sfdx-scanner', 'TypescriptEslintStrategy'); export enum TYPESCRIPT_ENGINE_OPTIONS { // Specify the location of the tsconfig.json file TSCONFIG = 'tsconfig' } const ES_PLUS_TS_CONFIG = { "parser": "@typescript-eslint/parser", "baseConfig": {}, "parserOptions": { "sourceType": "module", "ecmaVersion": 2018, }, "plugins": [ "@typescript-eslint" ], "ignorePatterns": [ "lib/**", "node_modules/**" ], "useEslintrc": false, // Will not use external config "resolvePluginsRelativeTo": __dirname, // Use the plugins found in the sfdx scanner installation directory "cwd": __dirname // Use the parser found in the sfdx scanner installation }; const TS_CONFIG = 'tsconfig.json'; export class TypescriptEslintStrategy implements EslintStrategy { private static LANGUAGES = [LANGUAGE.TYPESCRIPT]; private initialized: boolean; private logger: Logger; private fileHandler: FileHandler; private outputProcessor: OutputProcessor; private baseEslintConfig: LooseObject; private extendedEslintConfig: LooseObject; private untypedConfig: LooseObject; private typedConfig: LooseObject; async init(): Promise<void> { if (this.initialized) { return; } this.logger = await Logger.child(this.getEngine().valueOf()); this.fileHandler = new FileHandler(); this.outputProcessor = await OutputProcessor.create({}); const pathToBaseConfig = require.resolve('eslint') .replace(path.join('lib', 'api.js'), path.join('conf', 'eslint-recommended.js')); this.baseEslintConfig = require(pathToBaseConfig); const pathToExtendedBaseConfig = require.resolve('@typescript-eslint/eslint-plugin') .replace('index.js', path.join('configs', 'eslint-recommended.js')); this.extendedEslintConfig = require(pathToExtendedBaseConfig).default.overrides[0]; const pathToUntypedRecommendedConfig = require.resolve('@typescript-eslint/eslint-plugin') .replace('index.js', path.join('configs', 'recommended.json')); this.untypedConfig = JSON.parse(await this.fileHandler.readFile(pathToUntypedRecommendedConfig)); const pathToTypedRecommendedConfig = require.resolve('@typescript-eslint/eslint-plugin') .replace('index.js', path.join('configs', 'recommended-requiring-type-checking.json')); this.typedConfig = JSON.parse(await this.fileHandler.readFile(pathToTypedRecommendedConfig)); this.initialized = true; } getEngine(): ENGINE { return ENGINE.ESLINT_TYPESCRIPT; } /* eslint-disable @typescript-eslint/no-explicit-any */ getCatalogConfig(): Record<string, any> { return ES_PLUS_TS_CONFIG; } getLanguages(): string[] { return TypescriptEslintStrategy.LANGUAGES; } filterUnsupportedPaths(paths: string[]): string[] { const filteredPaths = paths.filter(p => p.endsWith(".ts")); this.logger.trace(`Input paths: ${paths}, Filtered paths: ${filteredPaths}`); return filteredPaths; } filterDisallowedRules(rulesByName: Map<string, ESRule>): Map<string, ESRule> { // We want to identify rules that are deprecated, and rules that are extended by other rules, so we can manually // filter them out. const extendedRules: Set<string> = new Set(); const deprecatedRules: Set<string> = new Set(); for (const [name, rule] of rulesByName.entries()) { if (rule.meta.deprecated) { deprecatedRules.add(name); } if (rule.meta.docs.extendsBaseRule) { // The `extendsBaseRule` property can be a string, representing the name of the rule being extended. if (typeof rule.meta.docs.extendsBaseRule === 'string') { extendedRules.add(rule.meta.docs.extendsBaseRule); } else { // Alternatively, it can be just the boolean true, which indicates that this rule extends a base rule // with the exact same name. So to determine the base rule's name, we need to remove all namespacing // information from this rule's name, i.e. strip everything up through the last '/' character. extendedRules.add(name.slice(name.lastIndexOf('/') + 1)); } } } // Now, we'll want to create a new Map containing every rule that isn't deprecated or extended. const filteredMap: Map<string,ESRule> = new Map(); for (const [name, rule] of rulesByName.entries()) { if (!extendedRules.has(name) && !deprecatedRules.has(name)) { filteredMap.set(name, rule); } } return filteredMap; } ruleDefaultEnabled(name: string): boolean { // Check the configs in descending order of priority, i.e. start with the one that would override the others. const status: RuleDefaultStatus = EslintStrategyHelper.getDefaultStatus(this.typedConfig, name) || EslintStrategyHelper.getDefaultStatus(this.untypedConfig, name) || EslintStrategyHelper.getDefaultStatus(this.extendedEslintConfig, name) || EslintStrategyHelper.getDefaultStatus(this.baseEslintConfig, name); // Return true only if the highest-priority status is explicitly enabled. return status === RuleDefaultStatus.ENABLED; } getDefaultConfig(ruleName: string): ESRuleConfig { // Get the highest-priority configuration we can find. return EslintStrategyHelper.getDefaultConfig(this.typedConfig, ruleName) || EslintStrategyHelper.getDefaultConfig(this.untypedConfig, ruleName) || EslintStrategyHelper.getDefaultConfig(this.extendedEslintConfig, ruleName) || EslintStrategyHelper.getDefaultConfig(this.baseEslintConfig, ruleName); } /* eslint-disable @typescript-eslint/no-explicit-any */ async getRunConfig(engineOptions: Map<string, string>): Promise<Record<string, any>> { const tsconfigPath = await this.findTsconfig(engineOptions); // Alert the user we found a config file, if --verbose this.alertUser(tsconfigPath); const config = {}; Object.assign(config, deepCopy(ES_PLUS_TS_CONFIG)); // Enable typescript by registering its project config file config["parserOptions"].project = tsconfigPath; this.logger.trace(`Using config for run: ${JSON.stringify(config)}`); return config; } private alertUser(tsconfigPath: string): void { const event = { messageKey: 'info.usingEngineConfigFile', args: [tsconfigPath], type: 'INFO', handler: 'UX', verbose: true, time: Date.now() }; this.outputProcessor.emitEvents([event]); } /** * Converts the eslint message that requires the scanned files to be a subset of the files specified by tsconfig.json */ processRuleViolation(): ProcessRuleViolationType { return (fileName: string, ruleViolation: RuleViolation): void => { const message: string = ruleViolation.message; if (message.startsWith('Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.\nThe file does not match your project config') && message.endsWith('The file must be included in at least one of the projects provided.')) { ruleViolation.message = messages.getMessage('FileNotIncludedByTsConfig', [fileName, TS_CONFIG]); ruleViolation.exception = true; } else if (message.startsWith('Parsing error:')) { ruleViolation.ruleName = HARDCODED_RULES.FILES_MUST_COMPILE.name; ruleViolation.category = HARDCODED_RULES.FILES_MUST_COMPILE.category; ruleViolation.exception = true; } } } /** * Try to find a tsconfig.json in the engineOptions map or current working directory, engineOptions takes precedence. * Throw an error if a tsconfig.json file can't be found. */ async findTsconfig(engineOptions: Map<string, string>): Promise<string> { const foundTsConfig = (await this.checkEngineOptionsForTsconfig(engineOptions)) || (await this.checkWorkingDirectoryForTsconfig()); if (!foundTsConfig) { const cwd = path.resolve(); // Not specified in engineOptions and not found in the current directory throw SfdxError.create('@salesforce/sfdx-scanner', 'TypescriptEslintStrategy', 'MissingTsConfigFromCwd', [TS_CONFIG, cwd, TS_CONFIG]); } this.logger.trace(`Using ${TS_CONFIG} from ${foundTsConfig}`); return foundTsConfig; } /** * Returns the tsconfig.json file specified in the engineOptions if it is specified and valid, or null if * engineOptions doesn't specify a tsconfig.json value. * Throw an error if the file specified in engineOptions is invalid for any reason. */ protected async checkEngineOptionsForTsconfig(engineOptions: Map<string, string>): Promise<string> { const tsConfigFromOptions = engineOptions.get(TYPESCRIPT_ENGINE_OPTIONS.TSCONFIG); if (tsConfigFromOptions != null) { if (!(await this.fileHandler.exists(tsConfigFromOptions))) { // Specified in the engineOptions but it isn't a file throw SfdxError.create('@salesforce/sfdx-scanner', 'TypescriptEslintStrategy', 'NotAFileTsConfigFromOptions', [TS_CONFIG, tsConfigFromOptions]); } else if (path.basename(tsConfigFromOptions).toLowerCase() !== TS_CONFIG) { // Found the file, but it's not named tsconfig.json throw SfdxError.create('@salesforce/sfdx-scanner', 'TypescriptEslintStrategy', 'InvalidNameTsConfigFromOptions', [tsConfigFromOptions, TS_CONFIG]); } else { return tsConfigFromOptions; } } return null; } /** * Return the path of a tsconfig.json file if it exists in the current working directory, or null if it doesn't. */ protected async checkWorkingDirectoryForTsconfig(): Promise<string> { const tsconfigPath = path.resolve(TS_CONFIG); if (await this.fileHandler.exists(tsconfigPath)) { this.logger.trace(`Found ${TS_CONFIG} in current working directory ${tsconfigPath}`); return tsconfigPath; } return null; } }
the_stack
import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { UpdateData, UpdateKeyOfExpect, deleteExpect, } from "../reduxComponents/actions/actions"; interface Props { id: string; remove: (x: number) => boolean; } export const ExpectStatement: React.FC<Props> = ({ id, remove }) => { const dispatch = useDispatch(); let counter = 0; let first: number; const data = useSelector((state: any) => state.expects); const index = useSelector((state: any) => state.keyOfExpect); const updateData = (data: any) => dispatch(UpdateData(data)); const updateExpectKey = () => dispatch(UpdateKeyOfExpect()); const deleteExpectFromStore = (data: any) => dispatch(deleteExpect(data)); useEffect(() => { data[index] = {}; data[index].testTypes = ".toEqual"; data[index][`lastInput${index}`] = ""; data[index].selectors = {}; data[index].selectors[`expect${index}selector0`] = ".type"; updateData(data); updateExpectKey(); }, []); // removes the expect block selected function removeExpect() { // uses remove prop from ItStatement componene to see if the user is able to delete if (remove(parseInt(id, 10))) { deleteExpectFromStore(id); document.getElementById(`expect-block ${id}`)?.remove(); } // if there is only one expect block then do not delete else { // eslint-disable-next-line no-console console.log("cannot remove expect block"); } } // when a selector is changed then create new fields function handleChange( event: | React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLSelectElement> ) { const block = document.getElementById(id); // if the selector is set to find then append a new text box and selector if ( event.target?.value === ".find" || event.target?.value === ".contains" || event.target?.value === ".every" || event.target?.value === ".everyWhere" || event.target?.value === ".hasClass" || event.target?.value === ".exists" || event.target?.value === ".forEach" || event.target?.value === ".is" || event.target?.value === ".at" || event.target?.value === ".simulate" || event.target?.value === ".prop" || event.target?.value === ".tap" || event.target?.value === ".some" || event.target?.value === ".name" || event.target?.value === ".isEmptyRender" || event.target?.value === ".first" || event.target?.value === ".get" || event.target?.value === ".getElements" || event.target?.value === ".hostNodes" ) { if (event.target?.id === `expect${id}selector0`) { first = counter; } // will keep value of prop key if user wants to change key again if (typeof data[`${id}`].selectors[`${event.target?.id}`] === "object") { const value = Object.values( data[`${id}`].selectors[`${event.target?.id}`] )[0]; data[`${id}`].selectors[`${event.target?.id}`] = {}; data[`${id}`].selectors[`${event.target?.id}`][ `${event.target?.value}` ] = value; } else { data[`${id}`].selectors[`${event.target?.id}`] = {}; data[`${id}`].selectors[`${event.target?.id}`][ `${event.target?.value}` ] = ""; // creates a text box for the input const child = document.createElement("input"); child.id = `expect${id}input${counter}`; child.className = "inputbox"; child.type = "text"; child.placeholder = "Selector optional"; child.onchange = () => { // eslint-disable-next-line @typescript-eslint/no-use-before-define inputText(event.target?.id, event.target?.value); }; // eslint-disable-next-line no-plusplus counter++; // creates a selector for the next portion const secondSelector = document.createElement("select"); secondSelector.id = `expect${id}selector${counter}`; secondSelector.className = "expectdrop1"; secondSelector.innerHTML = ` <option value = 'nothing'></option> <option value = '.type'>type</option> <option value = '.text'>text</option> <option value = '.find'>to find</option> <option value = '.exists'>to exist</option> <option value = '.contains'>contains</option> <option value = '.every'>every</option> <option value = '.everyWhere'>everyWhere(fn)</option> <option value = '.hasClass'>has class</option> <option value = '.forEach'>forEach(fn)</option> <option value = '.is'>is</option> <option value = '.at'>at</option> <option value = '.simulate'>simulate</option> <option value = '.prop'>prop</option> <option value = '.tap'>tap(interceptor)</option> <option value = '.some'>some</option> <option value = '.name'>name</option> <option value = '.isEmptyRender'>is empty render</option> <option value = '.first'>first</option> <option value = '.get'>get</option> <option value = '.getElements'>get elements</option> <option value = '.hostNodes'>host nodes</option>`; data[`${id}`].selectors[`expect${id}selector${counter}`] = ".nothing"; secondSelector.onchange = handleChange; // create line break const linebreak = document.createElement("br"); if (block) { block.appendChild(child); block.appendChild(linebreak); block.appendChild(secondSelector); } } } // select a new option for the selector else { const breaks = document.getElementsByTagName("br"); let breaksLength = breaks.length; data[`${id}`].selectors[`${event.target?.id}`] = event.target?.value; let checker = false; // if the value changed was for the first selector if (event.target?.id === `expect${id}selector0`) { document.getElementById(`expect${id}input${first}`)?.remove(); // eslint-disable-next-line no-plusplus breaks[breaksLength--]?.remove(); } // delete all elements that were appended after the selector chosen for (const keys of Object.keys(data[`${id}`].selectors)) { // checker will be true when the correct identifier is found // all values after that identifier will be removed from the store if (checker) { delete data[`${id}`].selectors[`${keys}`]; document.getElementById(`${keys}`)?.remove(); document .getElementById(`${keys}`.replace("selector", "input")) ?.remove(); // eslint-disable-next-line no-plusplus breaks[breaksLength--]?.remove(); // eslint-disable-next-line no-plusplus counter--; } else if (keys === event.target.id) { checker = true; document .getElementById(`${keys}`.replace("selector", "input")) ?.remove(); // eslint-disable-next-line no-plusplus breaks[breaksLength--]?.remove(); } } } // updates the elements in the store updateData(data); } // updates the last input box in the store function updateInput( event: | React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLSelectElement> ) { data[`${id}`][`${event.target?.id}`] = event.target?.value; updateData(data); } // updates the last selector value (expectdrop2) in the store function updateLastSelector(event: any) { data[`${id}`][`${event.target?.id}`] = event.target?.value; updateData(data); } // sets the input box text as the value of the object associated with the selector function inputText(elementId: string, elementKey: string) { const text = (document.getElementById( elementId.replace("selector", "input") ) as HTMLInputElement).value; data[`${id}`].selectors[`${elementId}`][`${elementKey}`] = text; updateData(data); } return ( <div className="expectBlock" id={`expect-block ${id}`}> <div className="expect1" id={`${id}`}> <label>expect wrapper</label> <button className="removeexpect" onClick={removeExpect}> X </button> <br /> <select className="expectdrop1" id={`expect${id}selector0`} onChange={handleChange} > <option value=".type">type</option> <option value=".text">text</option> <option value=".find">to find</option> <option value=".exists">to exist</option> <option value=".contains">contains</option> <option value=".every">every</option> <option value=".everyWhere">everyWhere(fn)</option> <option value=".hasClass">has class</option> <option value=".forEach">forEach(fn)</option> <option value=".is">is</option> <option value=".at">at</option> <option value=".simulate">simulate</option> <option value=".prop">prop</option> <option value=".tap">tap(interceptor)</option> <option value=".some">some</option> <option value=".name">name</option> <option value=".isEmptyRender">is empty render</option> <option value=".isEmpty">is empty</option> <option value=".first">first</option> <option value=".get">get</option> <option value=".getElements">get elements</option> <option value=".hostNodes">host nodes</option> </select> </div> <div className="expect2"> <select className="expectdrop2" id="testTypes" onChange={updateLastSelector} > <option value=".toEqual">to Equal</option> <option value=".toMatch">to Match</option> <option value=".toBe">to Be</option> <option value=".toHaveLength">to Have Length</option> </select> <input id={`lastInput${id}`} type="text" onChange={updateInput} /> </div> </div> ); };
the_stack
import React, { Component } from "react"; import { Dialog, DialogContent, DialogActions, withStyles, Button, CardHeader, Avatar, TextField, Toolbar, IconButton, Fade, Typography, Tooltip, Menu, MenuItem, GridList, ListSubheader, GridListTile } from "@material-ui/core"; import { parse as parseParams, ParsedQuery } from "query-string"; import { styles } from "./Compose.styles"; import { UAccount } from "../types/Account"; import { Visibility } from "../types/Visibility"; import AttachFileIcon from "@material-ui/icons/AttachFile"; import TagFacesIcon from "@material-ui/icons/TagFaces"; import HowToVoteIcon from "@material-ui/icons/HowToVote"; import VisibilityIcon from "@material-ui/icons/Visibility"; import WarningIcon from "@material-ui/icons/Warning"; import DeleteIcon from "@material-ui/icons/Delete"; import RadioButtonCheckedIcon from "@material-ui/icons/RadioButtonChecked"; import Mastodon from "megalodon"; import { withSnackbar } from "notistack"; import { Attachment } from "../types/Attachment"; import { PollWizard, PollWizardOption } from "../types/Poll"; import filedialog from "file-dialog"; import ComposeMediaAttachment from "../components/ComposeMediaAttachment"; import EmojiPicker from "../components/EmojiPicker"; import { DateTimePicker, MuiPickersUtilsProvider } from "material-ui-pickers"; import MomentUtils from "@date-io/moment"; import { getUserDefaultVisibility, getConfig, getUserDefaultBool } from "../utilities/settings"; import { draftExists, writeDraft, loadDraft } from "../utilities/compose"; /** * The state for the Composer page. */ interface IComposerState { /** * The current user as an Account. */ account: UAccount; /** * The visibility of the post. */ visibility: Visibility; /** * Whether there should be a content warning. */ sensitive: boolean; /** * The content warning message. */ sensitiveText?: string; /** * Whether the visibility drop-down should be visible. */ visibilityMenu: boolean; /** * The text contents of the post. */ text: string; /** * The remaining amount of characters. */ remainingChars: number; /** * An optional reply ID. */ reply?: string; /** * The account to reply to, if it exists. */ acct?: string; /** * An optional list of media attachments. */ attachments?: [Attachment]; /** * An optional poll for the post. */ poll?: PollWizard; /** * The expiration date of a poll, if it exists. */ pollExpiresDate?: any; /** * Whether the emoji picker should be visible. */ showEmojis: boolean; /** * Whether or not the account's instance is federated. */ federated: boolean; } /** * The Compose page contains all of the information to create a UI for post creation. */ class Composer extends Component<any, IComposerState> { /** * The Mastodon client to work with. */ client: Mastodon; /** * Construct the Compose page by generating the Mastodon client and setting default values. * @param props The properties passed into the Compose component, usually the page queries. */ constructor(props: any) { super(props); // Generate the Mastodon client this.client = new Mastodon( localStorage.getItem("access_token") as string, localStorage.getItem("baseurl") + "/api/v1" ); // Set the initial state this.state = { account: JSON.parse(localStorage.getItem("account") as string), visibility: getUserDefaultVisibility(), sensitive: false, visibilityMenu: false, text: "", remainingChars: getUserDefaultBool("imposeCharacterLimit") ? 500 : 9999999999999, showEmojis: false, federated: true }; } /** * Run any additional state checks and setup once the page has mounted. This includes * parsing the query parameters and loading the configuration, as well as defining the * clipboard listener. */ componentDidMount() { // Parse the parameters and get the account information if available. let state = this.getComposerParams(this.props); let text = state.acct ? `@${state.acct}: ` : ""; this.client.get("/accounts/verify_credentials").then((resp: any) => { let account: UAccount = resp.data; this.setState({ account }); }); // Get the configuration and load the config values. getConfig().then((config: any) => { this.setState({ federated: config.federation.allowPublicPosts, reply: state.reply, acct: state.acct, visibility: state.visibility, text, remainingChars: getUserDefaultBool("imposeCharacterLimit") ? 500 - text.length : 99999999 }); }); // Attach the paste listener to listen for the clipboard and upload media // if possible. window.addEventListener("paste", (evt: Event) => { let thePasteEvent = evt as ClipboardEvent; let fileList: File[] = []; if (thePasteEvent.clipboardData != null) { let clipitems = thePasteEvent.clipboardData.items; if (clipitems !== undefined) { for (let i = 0; i < clipitems.length; i++) { if (clipitems[i].type.indexOf("image") !== -1) { let clipfile = clipitems[i].getAsFile(); if (clipfile != null) { fileList.push(clipfile); } } } if (fileList.length > 0) { this.uploadMedia(fileList); } } } }); } /** * Reload the properties and set the state to those new properties. This usually * occurs when the page is either reloaded or changes but React doesn't see the * properties change. * @param props The properties passed into the Compose component, usually the page queries. */ componentWillReceiveProps(props: any) { let state = this.getComposerParams(props); let text = state.acct ? `@${state.acct}: ` : ""; this.setState({ reply: state.reply, acct: state.acct, visibility: state.visibility, text, remainingChars: getUserDefaultBool("imposeCharacterLimit") ? 500 - text.length : 99999999 }); } /** * Check if there is unsaved text and store it as a draft. */ componentWillUnmount() { if (this.state.text !== "") { writeDraft( this.state.text, this.state.reply ? Number(this.state.reply) : -999 ); this.props.enqueueSnackbar("Draft saved."); } } /** * Restore the draft from session storage and pre-load it into the state. */ restoreDraft() { const draft = loadDraft(); const text = draft.contents; const reply = draft.replyId !== -999 ? draft.replyId.toString() : undefined; this.setState({ text, reply }); this.props.enqueueSnackbar("Restored draft."); } /** * Check the location string and attempt to parse it into a parsed query. * @param location The location string from React Router. * @returns The ParsedQuery object containing all of the parameters. */ checkComposerParams(location?: string): ParsedQuery { let params = ""; if (location !== undefined && typeof location === "string") { params = location.replace("#/compose", ""); } else { params = window.location.hash.replace("#/compose", ""); } return parseParams(params); } /** * Check the property's location string, parse it, and return it. * @param props The properties passed into the Compose component, usually the page queries. * @returns An object containing the reply ID, reply account, and visibility. */ getComposerParams(props: any) { let params = this.checkComposerParams(props.location); let reply: string = ""; let acct: string = ""; let visibility = this.state.visibility; if (params.reply) { reply = params.reply.toString(); } if (params.acct) { acct = params.acct.toString(); } if (params.visibility) { visibility = params.visibility.toString() as Visibility; } return { reply, acct, visibility }; } /** * Update the text in the state and calculate the remaining character length. * @param text The text to update the state to */ updateTextFromField(text: string) { this.setState({ text, remainingChars: getUserDefaultBool("imposeCharacterLimit") ? 500 - text.length : 99999999 }); } /** * Update the content warning text in the state * @param sensitiveText The text to update the state to */ updateWarningFromField(sensitiveText: string) { this.setState({ sensitiveText }); } /** * Update the visibility in the state * @param visibility The visibility to update the state to */ changeVisibility(visibility: Visibility) { this.setState({ visibility }); } /** * Open a file dialog to let the user choose files to upload to the server and then upload them. */ promptMediaDialog() { filedialog({ multiple: false, accept: ".jpeg,.jpg,.png,.gif,.webm,.mp4,.mov,.ogg,.wav,.mp3,.flac" }) .then((media: FileList) => this.uploadMedia(media)) .catch((err: Error) => { this.props.enqueueSnackbar("Couldn't get media: " + err.name, { variant: "error" }); console.error(err.message); }); } /** * Upload a list of files to Mastodon as attachments. Reads the first item in the list. * This also updates the attachments state after a successful upload. * @param media The list of files (`FileList` or `File[]`) to send to Mastodon. */ uploadMedia(media: FileList | File[]) { // Create a new FormData for Mastodon let mediaForm = new FormData(); mediaForm.append("file", media[0]); // Let the user know we're uploading the file this.props.enqueueSnackbar("Uploading media...", { persist: true, key: "media-upload" }); // Try to upload the media to the server. this.client .post("/media", mediaForm) // If we succeed, get the attachments and update the state. .then((resp: any) => { let attachment: Attachment = resp.data; let attachments = this.state.attachments; if (attachments) { attachments.push(attachment); } else { attachments = [attachment]; } this.setState({ attachments }); this.props.closeSnackbar("media-upload"); this.props.enqueueSnackbar("Media uploaded."); }) // If we fail, display an error. .catch((err: Error) => { this.props.closeSnackbar("media-upload"); this.props.enqueueSnackbar( "Couldn't upload media: " + err.name, { variant: "error" } ); }); } /** * Iterate through the attachments and grab the attachments' IDs. * @returns A list of IDs as `string[]` */ getOnlyMediaIds() { let ids: string[] = []; if (this.state.attachments) { return this.state.attachments.map( (attachment: Attachment) => attachment.id ); } return ids; } /** * Update the list of attachments by inserting an attachment. * @param attachment The attachment to insert into the attachments list. */ fetchAttachmentAfterUpdate(attachment: Attachment) { let attachments = this.state.attachments; if (attachments) { attachments.forEach((attach: Attachment) => { if (attach.id === attachment.id && attachments) { attachments[attachments.indexOf(attach)] = attachment; } }); this.setState({ attachments }); } } /** * Remove an attachment from the list of attachments and update the state. * @param attachment The attachment to remove from the list */ deleteMediaAttachment(attachment: Attachment) { let attachments = this.state.attachments; if (attachments) { attachments.forEach((attach: Attachment) => { if (attach.id === attachment.id && attachments) { attachments.splice(attachments.indexOf(attach), 1); } this.setState({ attachments }); }); this.props.enqueueSnackbar("Attachment removed."); } } /** * Insert an emoji at the end of text string and update the state * @param e The emoji to insert into the text */ insertEmoji(e: any) { if (e.custom) { let text = this.state.text + e.colons; this.setState({ text, remainingChars: 500 - text.length }); } else { let text = this.state.text + e.native; this.setState({ text, remainingChars: 500 - text.length }); } } /** * Create an empty poll. */ createPoll() { if (this.state.poll === undefined) { let expiration = new Date(); let current = new Date(); expiration.setMinutes(expiration.getMinutes() + 30); let expiryDifference = expiration.getTime() - current.getTime() / 1000; let temporaryPoll: PollWizard = { expires_at: expiryDifference.toString(), multiple: false, options: [{ title: "Option 1" }, { title: "Option 2" }] }; this.setState({ poll: temporaryPoll, pollExpiresDate: expiration }); } } /** * Insert a new poll item into the poll. */ addPollItem() { if ( this.state.poll !== undefined && this.state.poll.options.length < 4 ) { let newOption = { title: "New option" }; let options = this.state.poll.options; let poll = this.state.poll; options.push(newOption); poll.options = options; poll.multiple = true; this.setState({ poll: poll }); } else if (this.state.poll && this.state.poll.options.length === 4) { this.props.enqueueSnackbar( "You've reached the options limit in your poll.", { variant: "error" } ); } } /** * Edit an existing poll item with new text * @param position The position of the poll item in the list * @param newTitle The new text to update */ editPollItem(position: number, newTitle: any) { if (this.state.poll !== undefined) { let poll = this.state.poll; let options = this.state.poll.options; options.forEach((option: PollWizardOption) => { if (position === options.indexOf(option)) { option.title = newTitle.target.value; } }); poll.options = options; this.setState({ poll: poll }); this.props.enqueueSnackbar("Option edited."); } } /** * Removes a poll item from the poll * @param item The item to remove */ removePollItem(item: string) { if ( this.state.poll !== undefined && this.state.poll.options.length > 2 ) { let options = this.state.poll.options; let poll = this.state.poll; options.forEach((option: PollWizardOption) => { if (item === option.title) { options.splice(options.indexOf(option), 1); } }); poll.options = options; if (options.length === 2) { poll.multiple = false; } this.setState({ poll: poll }); } else if (this.state.poll && this.state.poll.options.length <= 2) { this.props.enqueueSnackbar("Polls must have at least two items.", { variant: "error" }); } } /** * Set the expiration date of the poll. * @param date The new expiration date */ setPollExpires(date: string) { let currentDate = new Date(); let newDate = new Date(date); let poll = this.state.poll; if (poll) { let expiry = (newDate.getTime() - currentDate.getTime()) / 1000; if (expiry >= 1800) { poll.expires_at = expiry.toString(); this.setState({ poll, pollExpiresDate: date }); this.props.enqueueSnackbar("Expiration updated."); } else { this.props.enqueueSnackbar( "Expiration is too small (min. 30 minutes).", { variant: "error" } ); } } } /** * Remove the poll from the post. */ removePoll() { this.setState({ poll: undefined }); } /** * Check if the user presses the Ctrl/Cmd+Enter key and post to the server if possible. * @param event The keyboard event */ postViaKeyboard(event: any) { if ((event.metaKey || event.ctrlKey) && event.keyCode === 13) { this.post(); } } /** * Send the post to Mastodon and return to the previous page, if possible. */ post() { // First, finalize the poll. let pollOptions: string[] = []; if (this.state.poll) { this.state.poll.options.forEach((option: PollWizardOption) => { pollOptions.push(option.title); }); } // Send a post request to Mastodon. this.client .post("/statuses", { status: this.state.text, media_ids: this.getOnlyMediaIds(), visibility: this.state.visibility, sensitive: this.state.sensitive, spoiler_text: this.state.sensitiveText, in_reply_to_id: this.state.reply, poll: this.state.poll ? { options: pollOptions, expires_in: this.state.poll.expires_at, multiple: this.state.poll.multiple } : null }) // If we succeed, send a success message, clear the status // text field, and go back. .then(() => { this.props.enqueueSnackbar("Posted!"); // This is necessary to prevent session drafts from saving // posts that were already posted. this.setState({ text: "" }); window.history.back(); }) // Otherwise, show an error message and don't do anything. .catch((err: Error) => { this.props.enqueueSnackbar("Couldn't post: " + err.name); console.error(err.message); }); } /** * Toggle the content warning section. */ toggleSensitive() { this.setState({ sensitive: !this.state.sensitive }); } /** * Toggle the visibility drop down menu. */ toggleVisibilityMenu() { this.setState({ visibilityMenu: !this.state.visibilityMenu }); } /** * Toggle the emoji picker. */ toggleEmojis() { this.setState({ showEmojis: !this.state.showEmojis }); } /** * Render all of the components on the page given a set of classes. */ render() { const { classes } = this.props; return ( <Dialog open={true} maxWidth="sm" fullWidth={true} className={classes.dialog} onClose={() => window.history.back()} > <CardHeader avatar={<Avatar src={this.state.account.avatar_static} />} title={`${this.state.account.display_name} (@${this.state.account.acct})`} subheader={ this.state.visibility.charAt(0).toUpperCase() + this.state.visibility.substr(1) } /> <DialogContent className={classes.dialogContent}> {this.state.sensitive ? ( <Fade in={this.state.sensitive}> <TextField variant="outlined" fullWidth label="Content warning" margin="dense" onChange={event => this.updateWarningFromField( event.target.value ) } /> </Fade> ) : null} {this.state.visibility === "direct" ? ( <Typography variant="caption"> <WarningIcon className={classes.warningCaption} />{" "} Don't forget to add the usernames of the accounts you want to message in your post. </Typography> ) : null} <TextField variant="outlined" multiline fullWidth placeholder="What's on your mind?" margin="normal" onChange={event => this.updateTextFromField(event.target.value) } onKeyDown={event => this.postViaKeyboard(event)} inputProps={{ maxLength: 500 }} value={this.state.text} /> {getUserDefaultBool("imposeCharacterLimit") ? ( <Typography variant="caption" className={ this.state.remainingChars <= 100 ? classes.charsReachingLimit : null } > {`${this.state.remainingChars} character${ this.state.remainingChars === 1 ? "" : "s" } remaining`} </Typography> ) : ( <Typography variant="caption"> <WarningIcon className={classes.warningCaption} />{" "} You have the character limit turned off. Make sure that your post matches your instance's character limit before posting. </Typography> )} {this.state.attachments && this.state.attachments.length > 0 ? ( <div className={classes.composeAttachmentArea}> <GridList cellHeight={48} className={ classes.composeAttachmentAreaGridList } > <GridListTile key="Subheader-composer" cols={2} style={{ height: "auto" }} > <ListSubheader>Attachments</ListSubheader> </GridListTile> {this.state.attachments.map( (attachment: Attachment) => { let c = ( <ComposeMediaAttachment client={this.client} attachment={attachment} onAttachmentUpdate={( attachment: Attachment ) => this.fetchAttachmentAfterUpdate( attachment ) } onDeleteCallback={( attachment: Attachment ) => this.deleteMediaAttachment( attachment ) } /> ); return c; } )} </GridList> </div> ) : null} {this.state.poll ? ( <div style={{ marginTop: 4 }}> {this.state.poll ? this.state.poll.options.map( ( option: PollWizardOption, index: number ) => { let c = ( <div style={{ display: "flex" }} key={ "compose_option_" + index.toString() } > <RadioButtonCheckedIcon className={ classes.pollWizardOptionIcon } /> <TextField onBlur={(event: any) => this.editPollItem( index, event ) } defaultValue={ option.title } /> <div className={ classes.pollWizardFlexGrow } /> <Tooltip title="Remove poll option"> <IconButton onClick={() => this.removePollItem( option.title ) } > <DeleteIcon /> </IconButton> </Tooltip> </div> ); return c; } ) : null} <div style={{ display: "flex" }}> <MuiPickersUtilsProvider utils={MomentUtils}> <DateTimePicker value={ this.state.pollExpiresDate ? this.state.pollExpiresDate : new Date() } onChange={(date: any) => { this.setPollExpires( date.toISOString() ); }} label="Poll exipres on" disablePast /> </MuiPickersUtilsProvider> <div className={classes.pollWizardFlexGrow} /> <Button onClick={() => this.addPollItem()}> Add Option </Button> </div> </div> ) : null} </DialogContent> <Toolbar className={classes.dialogActions}> <Tooltip title="Add photos, videos, or audio"> <IconButton disabled={this.state.poll !== undefined} onClick={() => this.promptMediaDialog()} id="compose-media" > <AttachFileIcon /> </IconButton> </Tooltip> <Tooltip title="Insert emoji"> <IconButton id="compose-emoji" onClick={() => this.toggleEmojis()} className={classes.desktopOnly} > <TagFacesIcon /> </IconButton> </Tooltip> <Menu open={this.state.showEmojis} anchorEl={document.getElementById("compose-emoji")} onClose={() => this.toggleEmojis()} className={classes.composeEmoji} > <EmojiPicker onGetEmoji={(emoji: any) => this.insertEmoji(emoji)} /> </Menu> <Tooltip title="Add/remove a poll"> <IconButton disabled={ this.state.attachments && this.state.attachments.length > 0 } id="compose-poll" onClick={() => { this.state.poll ? this.removePoll() : this.createPoll(); }} > <HowToVoteIcon /> </IconButton> </Tooltip> <Tooltip title="Change who sees your post"> <IconButton id="compose-visibility" onClick={() => this.toggleVisibilityMenu()} > <VisibilityIcon /> </IconButton> </Tooltip> <Tooltip title="Set a content warning"> <IconButton onClick={() => this.toggleSensitive()} id="compose-warning" > <WarningIcon /> </IconButton> </Tooltip> <Menu open={this.state.visibilityMenu} anchorEl={document.getElementById("compose-visibility")} onClose={() => this.toggleVisibilityMenu()} > <MenuItem onClick={() => this.changeVisibility("direct")} > Direct (direct message) </MenuItem> <MenuItem onClick={() => this.changeVisibility("private")} > Private (followers only) </MenuItem> <MenuItem onClick={() => this.changeVisibility("unlisted")} > Unlisted </MenuItem> {this.state.federated ? ( <MenuItem onClick={() => this.changeVisibility("public")} > Public </MenuItem> ) : null} </Menu> </Toolbar> {draftExists() ? ( <DialogContent className={classes.draftDisplayArea}> <Typography className={classes.draftText}> You have an unsaved post. </Typography> <div className={classes.draftFlexGrow} /> <Button color="primary" size="small" onClick={() => this.restoreDraft()} > Restore </Button> </DialogContent> ) : null} <DialogActions> <Button color="secondary" onClick={() => this.post()}> Post </Button> </DialogActions> </Dialog> ); } } export default withStyles(styles)(withSnackbar(Composer));
the_stack
* taken from https://github.com/jetstack/cert-manager/releases/download/v1.2.0/cert-manager.yaml * * 1. copy the correct yaml * 2. covert to json (https://www.convertjson.com/yaml-to-json.htm) * 3. paste here * 4. `yarn generate-apis` (this will take this CRD and turn it into a KubernetesResource Class that we use in our Typescript). * Output from this command is in https://github.com/opstrace/opstrace/tree/6be8da8aa2db3479d72acb47b0156ff2b04939a2/lib/kubernetes/src/custom-resources directory. * 5. it's likely you'll have compiler errors now in packages like the controller, where we now need to update the resource spec * 5. adjust any specs that now use the updated resources so they conform to the new spec. */ export const orders = { apiVersion: "apiextensions.k8s.io/v1", kind: "CustomResourceDefinition", metadata: { annotations: { "cert-manager.io/inject-ca-from-secret": "cert-manager/cert-manager-webhook-ca" }, labels: { app: "cert-manager", "app.kubernetes.io/instance": "cert-manager", "app.kubernetes.io/name": "cert-manager" }, name: "orders.acme.cert-manager.io" }, spec: { conversion: { strategy: "Webhook", webhook: { clientConfig: { service: { name: "cert-manager-webhook", namespace: "cert-manager", path: "/convert" } }, conversionReviewVersions: ["v1", "v1beta1"] } }, group: "acme.cert-manager.io", names: { categories: ["cert-manager", "cert-manager-acme"], kind: "Order", listKind: "OrderList", plural: "orders", singular: "order" }, scope: "Namespaced", versions: [ { additionalPrinterColumns: [ { jsonPath: ".status.state", name: "State", type: "string" }, { jsonPath: ".spec.issuerRef.name", name: "Issuer", priority: 1, type: "string" }, { jsonPath: ".status.reason", name: "Reason", priority: 1, type: "string" }, { description: "CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.", jsonPath: ".metadata.creationTimestamp", name: "Age", type: "date" } ], name: "v1alpha2", schema: { openAPIV3Schema: { description: "Order is a type to represent an Order with an ACME server", properties: { apiVersion: { description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", type: "string" }, kind: { description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", type: "string" }, metadata: { type: "object" }, spec: { properties: { commonName: { description: "CommonName is the common name as specified on the DER encoded CSR. If specified, this value must also be present in `dnsNames` or `ipAddresses`. This field must match the corresponding field on the DER encoded CSR.", type: "string" }, csr: { description: "Certificate signing request bytes in DER encoding. This will be used when finalizing the order. This field must be set on the order.", format: "byte", type: "string" }, dnsNames: { description: "DNSNames is a list of DNS names that should be included as part of the Order validation process. This field must match the corresponding field on the DER encoded CSR.", items: { type: "string" }, type: "array" }, duration: { description: "Duration is the duration for the not after date for the requested certificate. this is set on order creation as pe the ACME spec.", type: "string" }, ipAddresses: { description: "IPAddresses is a list of IP addresses that should be included as part of the Order validation process. This field must match the corresponding field on the DER encoded CSR.", items: { type: "string" }, type: "array" }, issuerRef: { description: "IssuerRef references a properly configured ACME-type Issuer which should be used to create this Order. If the Issuer does not exist, processing will be retried. If the Issuer is not an 'ACME' Issuer, an error will be returned and the Order will be marked as failed.", properties: { group: { description: "Group of the resource being referred to.", type: "string" }, kind: { description: "Kind of the resource being referred to.", type: "string" }, name: { description: "Name of the resource being referred to.", type: "string" } }, required: ["name"], type: "object" } }, required: ["csr", "issuerRef"], type: "object" }, status: { properties: { authorizations: { description: "Authorizations contains data returned from the ACME server on what authorizations must be completed in order to validate the DNS names specified on the Order.", items: { description: "ACMEAuthorization contains data returned from the ACME server on an authorization that must be completed in order validate a DNS name on an ACME Order resource.", properties: { challenges: { description: "Challenges specifies the challenge types offered by the ACME server. One of these challenge types will be selected when validating the DNS name and an appropriate Challenge resource will be created to perform the ACME challenge process.", items: { description: "Challenge specifies a challenge offered by the ACME server for an Order. An appropriate Challenge resource can be created to perform the ACME challenge process.", properties: { token: { description: "Token is the token that must be presented for this challenge. This is used to compute the 'key' that must also be presented.", type: "string" }, type: { description: "Type is the type of challenge being offered, e.g. 'http-01', 'dns-01', 'tls-sni-01', etc. This is the raw value retrieved from the ACME server. Only 'http-01' and 'dns-01' are supported by cert-manager, other values will be ignored.", type: "string" }, url: { description: "URL is the URL of this challenge. It can be used to retrieve additional metadata about the Challenge from the ACME server.", type: "string" } }, required: ["token", "type", "url"], type: "object" }, type: "array" }, identifier: { description: "Identifier is the DNS name to be validated as part of this authorization", type: "string" }, initialState: { description: "InitialState is the initial state of the ACME authorization when first fetched from the ACME server. If an Authorization is already 'valid', the Order controller will not create a Challenge resource for the authorization. This will occur when working with an ACME server that enables 'authz reuse' (such as Let's Encrypt's production endpoint). If not set and 'identifier' is set, the state is assumed to be pending and a Challenge will be created.", enum: [ "valid", "ready", "pending", "processing", "invalid", "expired", "errored" ], type: "string" }, url: { description: "URL is the URL of the Authorization that must be completed", type: "string" }, wildcard: { description: "Wildcard will be true if this authorization is for a wildcard DNS name. If this is true, the identifier will be the *non-wildcard* version of the DNS name. For example, if '*.example.com' is the DNS name being validated, this field will be 'true' and the 'identifier' field will be 'example.com'.", type: "boolean" } }, required: ["url"], type: "object" }, type: "array" }, certificate: { description: "Certificate is a copy of the PEM encoded certificate for this Order. This field will be populated after the order has been successfully finalized with the ACME server, and the order has transitioned to the 'valid' state.", format: "byte", type: "string" }, failureTime: { description: "FailureTime stores the time that this order failed. This is used to influence garbage collection and back-off.", format: "date-time", type: "string" }, finalizeURL: { description: "FinalizeURL of the Order. This is used to obtain certificates for this order once it has been completed.", type: "string" }, reason: { description: "Reason optionally provides more information about a why the order is in the current state.", type: "string" }, state: { description: "State contains the current state of this Order resource. States 'success' and 'expired' are 'final'", enum: [ "valid", "ready", "pending", "processing", "invalid", "expired", "errored" ], type: "string" }, url: { description: "URL of the Order. This will initially be empty when the resource is first created. The Order controller will populate this field when the Order is first processed. This field will be immutable after it is initially set.", type: "string" } }, type: "object" } }, required: ["metadata"], type: "object" } }, served: true, storage: false, subresources: { status: {} } }, { additionalPrinterColumns: [ { jsonPath: ".status.state", name: "State", type: "string" }, { jsonPath: ".spec.issuerRef.name", name: "Issuer", priority: 1, type: "string" }, { jsonPath: ".status.reason", name: "Reason", priority: 1, type: "string" }, { description: "CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.", jsonPath: ".metadata.creationTimestamp", name: "Age", type: "date" } ], name: "v1alpha3", schema: { openAPIV3Schema: { description: "Order is a type to represent an Order with an ACME server", properties: { apiVersion: { description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", type: "string" }, kind: { description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", type: "string" }, metadata: { type: "object" }, spec: { properties: { commonName: { description: "CommonName is the common name as specified on the DER encoded CSR. If specified, this value must also be present in `dnsNames` or `ipAddresses`. This field must match the corresponding field on the DER encoded CSR.", type: "string" }, csr: { description: "Certificate signing request bytes in DER encoding. This will be used when finalizing the order. This field must be set on the order.", format: "byte", type: "string" }, dnsNames: { description: "DNSNames is a list of DNS names that should be included as part of the Order validation process. This field must match the corresponding field on the DER encoded CSR.", items: { type: "string" }, type: "array" }, duration: { description: "Duration is the duration for the not after date for the requested certificate. this is set on order creation as pe the ACME spec.", type: "string" }, ipAddresses: { description: "IPAddresses is a list of IP addresses that should be included as part of the Order validation process. This field must match the corresponding field on the DER encoded CSR.", items: { type: "string" }, type: "array" }, issuerRef: { description: "IssuerRef references a properly configured ACME-type Issuer which should be used to create this Order. If the Issuer does not exist, processing will be retried. If the Issuer is not an 'ACME' Issuer, an error will be returned and the Order will be marked as failed.", properties: { group: { description: "Group of the resource being referred to.", type: "string" }, kind: { description: "Kind of the resource being referred to.", type: "string" }, name: { description: "Name of the resource being referred to.", type: "string" } }, required: ["name"], type: "object" } }, required: ["csr", "issuerRef"], type: "object" }, status: { properties: { authorizations: { description: "Authorizations contains data returned from the ACME server on what authorizations must be completed in order to validate the DNS names specified on the Order.", items: { description: "ACMEAuthorization contains data returned from the ACME server on an authorization that must be completed in order validate a DNS name on an ACME Order resource.", properties: { challenges: { description: "Challenges specifies the challenge types offered by the ACME server. One of these challenge types will be selected when validating the DNS name and an appropriate Challenge resource will be created to perform the ACME challenge process.", items: { description: "Challenge specifies a challenge offered by the ACME server for an Order. An appropriate Challenge resource can be created to perform the ACME challenge process.", properties: { token: { description: "Token is the token that must be presented for this challenge. This is used to compute the 'key' that must also be presented.", type: "string" }, type: { description: "Type is the type of challenge being offered, e.g. 'http-01', 'dns-01', 'tls-sni-01', etc. This is the raw value retrieved from the ACME server. Only 'http-01' and 'dns-01' are supported by cert-manager, other values will be ignored.", type: "string" }, url: { description: "URL is the URL of this challenge. It can be used to retrieve additional metadata about the Challenge from the ACME server.", type: "string" } }, required: ["token", "type", "url"], type: "object" }, type: "array" }, identifier: { description: "Identifier is the DNS name to be validated as part of this authorization", type: "string" }, initialState: { description: "InitialState is the initial state of the ACME authorization when first fetched from the ACME server. If an Authorization is already 'valid', the Order controller will not create a Challenge resource for the authorization. This will occur when working with an ACME server that enables 'authz reuse' (such as Let's Encrypt's production endpoint). If not set and 'identifier' is set, the state is assumed to be pending and a Challenge will be created.", enum: [ "valid", "ready", "pending", "processing", "invalid", "expired", "errored" ], type: "string" }, url: { description: "URL is the URL of the Authorization that must be completed", type: "string" }, wildcard: { description: "Wildcard will be true if this authorization is for a wildcard DNS name. If this is true, the identifier will be the *non-wildcard* version of the DNS name. For example, if '*.example.com' is the DNS name being validated, this field will be 'true' and the 'identifier' field will be 'example.com'.", type: "boolean" } }, required: ["url"], type: "object" }, type: "array" }, certificate: { description: "Certificate is a copy of the PEM encoded certificate for this Order. This field will be populated after the order has been successfully finalized with the ACME server, and the order has transitioned to the 'valid' state.", format: "byte", type: "string" }, failureTime: { description: "FailureTime stores the time that this order failed. This is used to influence garbage collection and back-off.", format: "date-time", type: "string" }, finalizeURL: { description: "FinalizeURL of the Order. This is used to obtain certificates for this order once it has been completed.", type: "string" }, reason: { description: "Reason optionally provides more information about a why the order is in the current state.", type: "string" }, state: { description: "State contains the current state of this Order resource. States 'success' and 'expired' are 'final'", enum: [ "valid", "ready", "pending", "processing", "invalid", "expired", "errored" ], type: "string" }, url: { description: "URL of the Order. This will initially be empty when the resource is first created. The Order controller will populate this field when the Order is first processed. This field will be immutable after it is initially set.", type: "string" } }, type: "object" } }, required: ["metadata"], type: "object" } }, served: true, storage: false, subresources: { status: {} } }, { additionalPrinterColumns: [ { jsonPath: ".status.state", name: "State", type: "string" }, { jsonPath: ".spec.issuerRef.name", name: "Issuer", priority: 1, type: "string" }, { jsonPath: ".status.reason", name: "Reason", priority: 1, type: "string" }, { description: "CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.", jsonPath: ".metadata.creationTimestamp", name: "Age", type: "date" } ], name: "v1beta1", schema: { openAPIV3Schema: { description: "Order is a type to represent an Order with an ACME server", properties: { apiVersion: { description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", type: "string" }, kind: { description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", type: "string" }, metadata: { type: "object" }, spec: { properties: { commonName: { description: "CommonName is the common name as specified on the DER encoded CSR. If specified, this value must also be present in `dnsNames` or `ipAddresses`. This field must match the corresponding field on the DER encoded CSR.", type: "string" }, dnsNames: { description: "DNSNames is a list of DNS names that should be included as part of the Order validation process. This field must match the corresponding field on the DER encoded CSR.", items: { type: "string" }, type: "array" }, duration: { description: "Duration is the duration for the not after date for the requested certificate. this is set on order creation as pe the ACME spec.", type: "string" }, ipAddresses: { description: "IPAddresses is a list of IP addresses that should be included as part of the Order validation process. This field must match the corresponding field on the DER encoded CSR.", items: { type: "string" }, type: "array" }, issuerRef: { description: "IssuerRef references a properly configured ACME-type Issuer which should be used to create this Order. If the Issuer does not exist, processing will be retried. If the Issuer is not an 'ACME' Issuer, an error will be returned and the Order will be marked as failed.", properties: { group: { description: "Group of the resource being referred to.", type: "string" }, kind: { description: "Kind of the resource being referred to.", type: "string" }, name: { description: "Name of the resource being referred to.", type: "string" } }, required: ["name"], type: "object" }, request: { description: "Certificate signing request bytes in DER encoding. This will be used when finalizing the order. This field must be set on the order.", format: "byte", type: "string" } }, required: ["issuerRef", "request"], type: "object" }, status: { properties: { authorizations: { description: "Authorizations contains data returned from the ACME server on what authorizations must be completed in order to validate the DNS names specified on the Order.", items: { description: "ACMEAuthorization contains data returned from the ACME server on an authorization that must be completed in order validate a DNS name on an ACME Order resource.", properties: { challenges: { description: "Challenges specifies the challenge types offered by the ACME server. One of these challenge types will be selected when validating the DNS name and an appropriate Challenge resource will be created to perform the ACME challenge process.", items: { description: "Challenge specifies a challenge offered by the ACME server for an Order. An appropriate Challenge resource can be created to perform the ACME challenge process.", properties: { token: { description: "Token is the token that must be presented for this challenge. This is used to compute the 'key' that must also be presented.", type: "string" }, type: { description: "Type is the type of challenge being offered, e.g. 'http-01', 'dns-01', 'tls-sni-01', etc. This is the raw value retrieved from the ACME server. Only 'http-01' and 'dns-01' are supported by cert-manager, other values will be ignored.", type: "string" }, url: { description: "URL is the URL of this challenge. It can be used to retrieve additional metadata about the Challenge from the ACME server.", type: "string" } }, required: ["token", "type", "url"], type: "object" }, type: "array" }, identifier: { description: "Identifier is the DNS name to be validated as part of this authorization", type: "string" }, initialState: { description: "InitialState is the initial state of the ACME authorization when first fetched from the ACME server. If an Authorization is already 'valid', the Order controller will not create a Challenge resource for the authorization. This will occur when working with an ACME server that enables 'authz reuse' (such as Let's Encrypt's production endpoint). If not set and 'identifier' is set, the state is assumed to be pending and a Challenge will be created.", enum: [ "valid", "ready", "pending", "processing", "invalid", "expired", "errored" ], type: "string" }, url: { description: "URL is the URL of the Authorization that must be completed", type: "string" }, wildcard: { description: "Wildcard will be true if this authorization is for a wildcard DNS name. If this is true, the identifier will be the *non-wildcard* version of the DNS name. For example, if '*.example.com' is the DNS name being validated, this field will be 'true' and the 'identifier' field will be 'example.com'.", type: "boolean" } }, required: ["url"], type: "object" }, type: "array" }, certificate: { description: "Certificate is a copy of the PEM encoded certificate for this Order. This field will be populated after the order has been successfully finalized with the ACME server, and the order has transitioned to the 'valid' state.", format: "byte", type: "string" }, failureTime: { description: "FailureTime stores the time that this order failed. This is used to influence garbage collection and back-off.", format: "date-time", type: "string" }, finalizeURL: { description: "FinalizeURL of the Order. This is used to obtain certificates for this order once it has been completed.", type: "string" }, reason: { description: "Reason optionally provides more information about a why the order is in the current state.", type: "string" }, state: { description: "State contains the current state of this Order resource. States 'success' and 'expired' are 'final'", enum: [ "valid", "ready", "pending", "processing", "invalid", "expired", "errored" ], type: "string" }, url: { description: "URL of the Order. This will initially be empty when the resource is first created. The Order controller will populate this field when the Order is first processed. This field will be immutable after it is initially set.", type: "string" } }, type: "object" } }, required: ["metadata", "spec"], type: "object" } }, served: true, storage: false, subresources: { status: {} } }, { additionalPrinterColumns: [ { jsonPath: ".status.state", name: "State", type: "string" }, { jsonPath: ".spec.issuerRef.name", name: "Issuer", priority: 1, type: "string" }, { jsonPath: ".status.reason", name: "Reason", priority: 1, type: "string" }, { description: "CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.", jsonPath: ".metadata.creationTimestamp", name: "Age", type: "date" } ], name: "v1", schema: { openAPIV3Schema: { description: "Order is a type to represent an Order with an ACME server", properties: { apiVersion: { description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", type: "string" }, kind: { description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", type: "string" }, metadata: { type: "object" }, spec: { properties: { commonName: { description: "CommonName is the common name as specified on the DER encoded CSR. If specified, this value must also be present in `dnsNames` or `ipAddresses`. This field must match the corresponding field on the DER encoded CSR.", type: "string" }, dnsNames: { description: "DNSNames is a list of DNS names that should be included as part of the Order validation process. This field must match the corresponding field on the DER encoded CSR.", items: { type: "string" }, type: "array" }, duration: { description: "Duration is the duration for the not after date for the requested certificate. this is set on order creation as pe the ACME spec.", type: "string" }, ipAddresses: { description: "IPAddresses is a list of IP addresses that should be included as part of the Order validation process. This field must match the corresponding field on the DER encoded CSR.", items: { type: "string" }, type: "array" }, issuerRef: { description: "IssuerRef references a properly configured ACME-type Issuer which should be used to create this Order. If the Issuer does not exist, processing will be retried. If the Issuer is not an 'ACME' Issuer, an error will be returned and the Order will be marked as failed.", properties: { group: { description: "Group of the resource being referred to.", type: "string" }, kind: { description: "Kind of the resource being referred to.", type: "string" }, name: { description: "Name of the resource being referred to.", type: "string" } }, required: ["name"], type: "object" }, request: { description: "Certificate signing request bytes in DER encoding. This will be used when finalizing the order. This field must be set on the order.", format: "byte", type: "string" } }, required: ["issuerRef", "request"], type: "object" }, status: { properties: { authorizations: { description: "Authorizations contains data returned from the ACME server on what authorizations must be completed in order to validate the DNS names specified on the Order.", items: { description: "ACMEAuthorization contains data returned from the ACME server on an authorization that must be completed in order validate a DNS name on an ACME Order resource.", properties: { challenges: { description: "Challenges specifies the challenge types offered by the ACME server. One of these challenge types will be selected when validating the DNS name and an appropriate Challenge resource will be created to perform the ACME challenge process.", items: { description: "Challenge specifies a challenge offered by the ACME server for an Order. An appropriate Challenge resource can be created to perform the ACME challenge process.", properties: { token: { description: "Token is the token that must be presented for this challenge. This is used to compute the 'key' that must also be presented.", type: "string" }, type: { description: "Type is the type of challenge being offered, e.g. 'http-01', 'dns-01', 'tls-sni-01', etc. This is the raw value retrieved from the ACME server. Only 'http-01' and 'dns-01' are supported by cert-manager, other values will be ignored.", type: "string" }, url: { description: "URL is the URL of this challenge. It can be used to retrieve additional metadata about the Challenge from the ACME server.", type: "string" } }, required: ["token", "type", "url"], type: "object" }, type: "array" }, identifier: { description: "Identifier is the DNS name to be validated as part of this authorization", type: "string" }, initialState: { description: "InitialState is the initial state of the ACME authorization when first fetched from the ACME server. If an Authorization is already 'valid', the Order controller will not create a Challenge resource for the authorization. This will occur when working with an ACME server that enables 'authz reuse' (such as Let's Encrypt's production endpoint). If not set and 'identifier' is set, the state is assumed to be pending and a Challenge will be created.", enum: [ "valid", "ready", "pending", "processing", "invalid", "expired", "errored" ], type: "string" }, url: { description: "URL is the URL of the Authorization that must be completed", type: "string" }, wildcard: { description: "Wildcard will be true if this authorization is for a wildcard DNS name. If this is true, the identifier will be the *non-wildcard* version of the DNS name. For example, if '*.example.com' is the DNS name being validated, this field will be 'true' and the 'identifier' field will be 'example.com'.", type: "boolean" } }, required: ["url"], type: "object" }, type: "array" }, certificate: { description: "Certificate is a copy of the PEM encoded certificate for this Order. This field will be populated after the order has been successfully finalized with the ACME server, and the order has transitioned to the 'valid' state.", format: "byte", type: "string" }, failureTime: { description: "FailureTime stores the time that this order failed. This is used to influence garbage collection and back-off.", format: "date-time", type: "string" }, finalizeURL: { description: "FinalizeURL of the Order. This is used to obtain certificates for this order once it has been completed.", type: "string" }, reason: { description: "Reason optionally provides more information about a why the order is in the current state.", type: "string" }, state: { description: "State contains the current state of this Order resource. States 'success' and 'expired' are 'final'", enum: [ "valid", "ready", "pending", "processing", "invalid", "expired", "errored" ], type: "string" }, url: { description: "URL of the Order. This will initially be empty when the resource is first created. The Order controller will populate this field when the Order is first processed. This field will be immutable after it is initially set.", type: "string" } }, type: "object" } }, required: ["metadata", "spec"], type: "object" } }, served: true, storage: true, subresources: { status: {} } } ] }, status: { acceptedNames: { kind: "", plural: "" }, conditions: [], storedVersions: [] } };
the_stack
import { ObjectWriterOptions, XMLSerializedAsObject, XMLSerializedAsObjectArray, XMLBuilderOptions } from "../interfaces" import { applyDefaults, isArray, isString } from "@oozcitak/util" import { Node, NodeType } from "@oozcitak/dom/lib/dom/interfaces" import { BaseWriter } from "./BaseWriter" /** * Serializes XML nodes into objects and arrays. */ export class ObjectWriter extends BaseWriter<ObjectWriterOptions, XMLSerializedAsObject | XMLSerializedAsObjectArray> { private _currentList!: NodeList private _currentIndex!: number private _listRegister!: NodeList[] /** * Initializes a new instance of `ObjectWriter`. * * @param builderOptions - XML builder options * @param writerOptions - serialization options */ constructor(builderOptions: XMLBuilderOptions, writerOptions: ObjectWriterOptions) { super(builderOptions) this._writerOptions = applyDefaults(writerOptions, { format: "object", wellFormed: false, group: false, verbose: false }) as Required<ObjectWriterOptions> } /** * Produces an XML serialization of the given node. * * @param node - node to serialize */ serialize(node: Node): XMLSerializedAsObject | XMLSerializedAsObjectArray { this._currentList = [] this._currentIndex = 0 this._listRegister = [this._currentList] /** * First pass, serialize nodes * This creates a list of nodes grouped under node types while preserving * insertion order. For example: * [ * root: [ * node: [ * { "@" : { "att1": "val1", "att2": "val2" } * { "#": "node text" } * { childNode: [] } * { "#": "more text" } * ], * node: [ * { "@" : { "att": "val" } * { "#": [ "text line1", "text line2" ] } * ] * ] * ] */ this.serializeNode(node, this._writerOptions.wellFormed) /** * Second pass, process node lists. Above example becomes: * { * root: { * node: [ * { * "@att1": "val1", * "@att2": "val2", * "#1": "node text", * childNode: {}, * "#2": "more text" * }, * { * "@att": "val", * "#": [ "text line1", "text line2" ] * } * ] * } * } */ return this._process(this._currentList, this._writerOptions) as any } private _process(items: NodeList, options: Required<ObjectWriterOptions>): string | XMLSerializedAsObject | XMLSerializedAsObjectArray { if (items.length === 0) return {} // determine if there are non-unique element names const namesSeen: { [key: string]: boolean } = {} let hasNonUniqueNames = false let textCount = 0 let commentCount = 0 let instructionCount = 0 let cdataCount = 0 for (let i = 0; i < items.length; i++) { const item = items[i] const key = Object.keys(item)[0] switch (key) { case "@": continue case "#": textCount++ break case "!": commentCount++ break case "?": instructionCount++ break case "$": cdataCount++ break default: if (namesSeen[key]) { hasNonUniqueNames = true } else { namesSeen[key] = true } break } } const defAttrKey = this._getAttrKey() const defTextKey = this._getNodeKey(NodeType.Text) const defCommentKey = this._getNodeKey(NodeType.Comment) const defInstructionKey = this._getNodeKey(NodeType.ProcessingInstruction) const defCdataKey = this._getNodeKey(NodeType.CData) if (textCount === 1 && items.length === 1 && isString((items[0] as TextNode)["#"])) { // special case of an element node with a single text node return (items[0] as TextNode)["#"] } else if (hasNonUniqueNames) { const obj: XMLSerializedAsObject | XMLSerializedAsObjectArray = { } // process attributes first for (let i = 0; i < items.length; i++) { const item = items[i] const key = Object.keys(item)[0] if (key === "@") { const attrs = (item as AttrNode)["@"] const attrKeys = Object.keys(attrs) if (attrKeys.length === 1) { obj[defAttrKey + attrKeys[0]] = attrs[attrKeys[0]] } else { obj[defAttrKey] = (item as AttrNode)["@"] } } } // list contains element nodes with non-unique names // return an array with mixed content notation const result: XMLSerializedAsObject | XMLSerializedAsObjectArray = [] for (let i = 0; i < items.length; i++) { const item = items[i] const key = Object.keys(item)[0] switch (key) { case "@": // attributes were processed above break case "#": result.push({ [defTextKey]: (item as TextNode)["#"] }) break case "!": result.push({ [defCommentKey]: (item as CommentNode)["!"] }) break case "?": result.push({ [defInstructionKey]: (item as InstructionNode)["?"] }) break case "$": result.push({ [defCdataKey]: (item as CDATANode)["$"] }) break default: // element node const ele = item as ElementNode if (ele[key].length !== 0 && isArray(ele[key][0])) { // group of element nodes const eleGroup: XMLSerializedAsObjectArray = [] const listOfLists = ele[key] as NodeList[] for (let i = 0; i < listOfLists.length; i++) { eleGroup.push(this._process(listOfLists[i], options) as any) } result.push({ [key]: eleGroup }) } else { // single element node if (options.verbose) { result.push({ [key]: [this._process(ele[key] as NodeList, options) as any] }) } else { result.push({ [key]: this._process(ele[key] as NodeList, options) }) } } break } } obj[defTextKey] = result return obj } else { // all element nodes have unique names // return an object while prefixing data node keys let textId: number = 1 let commentId: number = 1 let instructionId: number = 1 let cdataId: number = 1 const obj: XMLSerializedAsObject = {} for (let i = 0; i < items.length; i++) { const item = items[i] const key = Object.keys(item)[0] switch (key) { case "@": const attrs = (item as AttrNode)["@"] const attrKeys = Object.keys(attrs) if (!options.group || attrKeys.length === 1) { for (const attrName in attrs) { obj[defAttrKey + attrName] = attrs[attrName] } } else { obj[defAttrKey] = attrs } break case "#": textId = this._processSpecItem((item as TextNode)["#"], obj as any, options.group, defTextKey, textCount, textId) break case "!": commentId = this._processSpecItem((item as CommentNode)["!"], obj as any, options.group, defCommentKey, commentCount, commentId) break case "?": instructionId = this._processSpecItem((item as InstructionNode)["?"], obj as any, options.group, defInstructionKey, instructionCount, instructionId) break case "$": cdataId = this._processSpecItem((item as CDATANode)["$"], obj as any, options.group, defCdataKey, cdataCount, cdataId) break default: // element node const ele = item as ElementNode if (ele[key].length !== 0 && isArray(ele[key][0])) { // group of element nodes const eleGroup: XMLSerializedAsObjectArray = [] const listOfLists = ele[key] as NodeList[] for (let i = 0; i < listOfLists.length; i++) { eleGroup.push(this._process(listOfLists[i], options) as any) } obj[key] = eleGroup } else { // single element node if (options.verbose) { obj[key] = [this._process(ele[key] as NodeList, options) as any] } else { obj[key] = this._process(ele[key] as NodeList, options) } } break } } return obj } } private _processSpecItem(item: string | string[], obj: { [key: string]: string | string[] }, group: boolean, defKey: string, count: number, id: number): number { if (!group && isArray(item) && count + item.length > 2) { for (const subItem of item) { const key = defKey + (id++).toString() obj[key] = subItem } } else { const key = count > 1 ? defKey + (id++).toString() : defKey obj[key] = item } return id } /** @inheritdoc */ beginElement(name: string) { const childItems: NodeList = [] if (this._currentList.length === 0) { this._currentList.push({ [name]: childItems }) } else { const lastItem = this._currentList[this._currentList.length - 1] if (this._isElementNode(lastItem, name)) { if (lastItem[name].length !== 0 && isArray(lastItem[name][0])) { const listOfLists = lastItem[name] as NodeList[] listOfLists.push(childItems) } else { lastItem[name] = [lastItem[name] as NodeList, childItems] } } else { this._currentList.push({ [name]: childItems }) } } this._currentIndex++ if (this._listRegister.length > this._currentIndex) { this._listRegister[this._currentIndex] = childItems } else { this._listRegister.push(childItems) } this._currentList = childItems } /** @inheritdoc */ endElement() { this._currentList = this._listRegister[--this._currentIndex] } /** @inheritdoc */ attribute(name: string, value: string) { if (this._currentList.length === 0) { this._currentList.push({ "@": { [name]: value } }) } else { const lastItem = this._currentList[this._currentList.length - 1] /* istanbul ignore else */ if (this._isAttrNode(lastItem)) { lastItem["@"][name] = value } else { this._currentList.push({ "@": { [name]: value } }) } } } /** @inheritdoc */ comment(data: string) { if (this._currentList.length === 0) { this._currentList.push({ "!": data }) } else { const lastItem = this._currentList[this._currentList.length - 1] if (this._isCommentNode(lastItem)) { if (isArray(lastItem["!"])) { lastItem["!"].push(data) } else { lastItem["!"] = [lastItem["!"], data] } } else { this._currentList.push({ "!": data }) } } } /** @inheritdoc */ text(data: string) { if (this._currentList.length === 0) { this._currentList.push({ "#": data }) } else { const lastItem = this._currentList[this._currentList.length - 1] if (this._isTextNode(lastItem)) { if (isArray(lastItem["#"])) { lastItem["#"].push(data) } else { lastItem["#"] = [lastItem["#"], data] } } else { this._currentList.push({ "#": data }) } } } /** @inheritdoc */ instruction(target: string, data: string) { const value = (data === "" ? target : target + " " + data) if (this._currentList.length === 0) { this._currentList.push({ "?": value }) } else { const lastItem = this._currentList[this._currentList.length - 1] if (this._isInstructionNode(lastItem)) { if (isArray(lastItem["?"])) { lastItem["?"].push(value) } else { lastItem["?"] = [lastItem["?"], value] } } else { this._currentList.push({ "?": value }) } } } /** @inheritdoc */ cdata(data: string) { if (this._currentList.length === 0) { this._currentList.push({ "$": data }) } else { const lastItem = this._currentList[this._currentList.length - 1] if (this._isCDATANode(lastItem)) { if (isArray(lastItem["$"])) { lastItem["$"].push(data) } else { lastItem["$"] = [lastItem["$"], data] } } else { this._currentList.push({ "$": data }) } } } private _isAttrNode(x: any): x is AttrNode { return "@" in x } private _isTextNode(x: any): x is TextNode { return "#" in x } private _isCommentNode(x: any): x is CommentNode { return "!" in x } private _isInstructionNode(x: any): x is InstructionNode { return "?" in x } private _isCDATANode(x: any): x is CDATANode { return "$" in x } private _isElementNode(x: any, name: string): x is ElementNode { return name in x } /** * Returns an object key for an attribute or namespace declaration. */ private _getAttrKey(): string { return this._builderOptions.convert.att } /** * Returns an object key for the given node type. * * @param nodeType - node type to get a key for */ private _getNodeKey(nodeType: NodeType): string { switch (nodeType) { case NodeType.Comment: return this._builderOptions.convert.comment case NodeType.Text: return this._builderOptions.convert.text case NodeType.ProcessingInstruction: return this._builderOptions.convert.ins case NodeType.CData: return this._builderOptions.convert.cdata /* istanbul ignore next */ default: throw new Error("Invalid node type.") } } } type AttrNode = { "@": { [key: string]: string } } type TextNode = { "#": string | string[] } type CommentNode = { "!": string | string[] } type InstructionNode = { "?": string | string[] } type CDATANode = { "$": string | string[] } type NodeList = (ElementNode | AttrNode | TextNode | CommentNode | InstructionNode | CDATANode)[] type ElementNode = { [key: string]: NodeList | NodeList[] }
the_stack
// Types and comments extracted from: // https://kamailio.org/docs/tutorials/5.3.x/kamailio-kemi-framework/ export {}; declare global { const KSR: typeof KamailioKemi; } declare namespace KamailioKemi { // Allowed flags type Flag = 0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31; // Write a log message to DEBUG level export function dbg(logStr: string): void; // Write a log message to ERROR level. export function err(logStr: string): void; // Write a log message to INFO level. export function info(logStr: string): void; // Set the internal flag to add rport parameter to local generated Via header. export function add_local_rport(): boolean; // Adds a tcp port alias for the current connection (if tcp). Useful if you want to send all the trafic to // port_alias through the same connection this request came from (it could help for firewall or nat traversal). // When the aliased connection is closed (e.g. it is idle for too much time), all the port aliases are removed. export function add_tcp_alias(port: number): void; // Adds the port from the message via as an alias to TCP connection. See add_tcp_alias(int port) for more details. export function add_tcp_alias_via(): number; // Set the flag for "rport" handling (send the reply based on source address instead of Via header). export function force_rport(): boolean; // Return true if the value of the parameter matches the method type of the SIP message. export function is_method(method: string): boolean; /* * Return true if SIP method of the currently processed message is matching * one of the corresponding characters given as parameter. * Matching the method is done based on corresponding characters: * * I - INVITE * A - ACK * B - BYE * C - CANCEL * R - REGISTER * M - MESSAGE * O - OPTIONS * S - SUBSCRIBE * P - PUBLISH * N - NOTIFY * U - UPDATE * K - KDMQ * G - GET * T - POST * V - PUT * D - DELETE */ export function is_method_in(method: string): boolean; // Helpers for common methods export function is_INVITE(): boolean; export function is_ACK(): boolean; export function is_BYE(): boolean; export function is_CANCEL(): boolean; export function is_REGISTER(): boolean; export function is_MESSAGE(): boolean; export function is_SUBSCRIBE(): boolean; export function is_PUBLISH(): boolean; export function is_NOTIFY(): boolean; export function is_OPTIONS(): boolean; export function is_INFO(): boolean; export function is_UPDATE(): boolean; export function is_PRACK(): boolean; // Return true of the URI address provided as parameter matches a local socket (IP) or local domain. export function is_myself(uri: string): boolean; // Return true if the URI in From header matches a local socket (IP) or local domain. export function is_myself_furi(): boolean; // Return true if the R-URI matches a local socket (IP) or local domain. export function is_myself_ruri(): boolean; // Return true if the URI in To header matches a local socket (IP) or local domain. export function is_myself_turi(): boolean; // Write a log message specifying the level value. export function log(level: "dbg"|"info"|"warn"|"crit"|"err", msg: string): void; // Set the SIP message/transaction flag at the index provided by the parameter. The flag parameter has to be a number from 0 to 31. export function setflag(flag: Flag): boolean; // Reset the SIP message/transaction flag at the index provided by the parameter. The flag parameter has to be a number from 0 to 31. export function resetflag(flag: Flag): boolean; // Return true if the message/transaction flag at the index provided by the parameter is set (the bit has value 1). export function isflagset(flag: Flag): boolean; // Set the branch flag at the index provided by the parameter. The flag parameter has to be a number from 0 to 31. export function setbflag(flag: Flag): boolean; // Reset the branch flag at the index provided by the parameter. The flag parameter has to be a number from 0 to 31. export function resetbflag(flag: Flag): boolean; // Return true if the branch flag at the index provided by the parameter is set (the bit has value 1). export function isbflagset(flag: Flag): boolean; // Set the flag at the index provided by the first parameter to the branch number specified by the second parameter. // The flag parameter has to be a number from 0 to 31. // The branch parameter should be between 0 and 12 (a matter of max_branches global parameter). export function setbiflag(flag: Flag, branch: number): boolean; // Reset a branch flag by position and branch index. export function resetbiflag(flag: Flag, branch: number): boolean; // Test if a branch flag is set by position and branch index. export function isbiflagset(flag: Flag, branch: number): boolean; // Set a script flag export function setsflag(flag: Flag): boolean; // Reset a script flag export function resetsflag(flag: Flag): boolean; // Test if a script flag is set export function issflagset(flag: Flag): boolean; // Set request URI export function seturi(uri: string): boolean; // Set request user export function setuser(usr: string): boolean; // Set request host export function sethost(host: string): boolean; // Set destination URI export function setdsturi(uri: string): boolean; // Reset the destination URI (aka: outbound proxy address, dst_uri, $du). export function resetdsturi(): boolean; // Test if destination URI is set. export function isdsturiset(): boolean; // Set the DROP flag, so at the end of KEMI script execution, the SIP request branch or the SIP response is not forwarded. export function set_drop(): void; export function set_advertised_address(addr: string): number; export function set_advertised_port(port: string): number; export function set_forward_close(): boolean; export function set_forward_no_connect(): boolean; export function set_reply_close(): boolean; export function set_reply_no_connect(): boolean; // Forward the SIP request in stateless mode to the address set in destination URI ($du), or, // if this is not set, to the address in request URI ($ru). export function forward(): number; // Forward the SIP request in stateless mode to the address provided in the SIP URI parameter. export function forward_uri(uri: string): number; // Special declaration of debugger and enum to avoid using reserved words namespace _debugger { function dbg_pv_dump(): number; function dbg_pv_dump_ex(mask: number, level: number): number; } namespace _enum { function enum_i_query_suffix(vsuffix: string): number; function enum_pv_query(ve164: string): number; function enum_pv_query_suffix(ve164: string, vsuffix: string): number; function enum_pv_query_suffix_service(ve164: string, vsuffix: string, vservice: string): number; function enum_query(): number; function enum_query_suffix(vsuffix: string): number; function enum_query_suffix_service(vsuffix: string, vservice: string): number; function i_enum_query(): number; function i_enum_query_suffix_service(vsuffix: string, vservice: string): number; function is_from_user_enum(): number; function is_from_user_enum_suffix(vsuffix: string): number; function is_from_user_enum_suffix_service(vsuffix: string, vservice: string): number; } // noinspection ReservedWordAsName // TypeScript Version: 2.2 export { _debugger as debugger, _enum as enum }; export namespace pv { // Return the value of pseudo-variable `pvname`. // The returned value can be string or integer function get(pvname: string): string|number|null; // Same as get(), but returns empty string on null function gete(pvname: string): string|number; // Same as get(), but returns `vn` on null function getvn(pvname: string, vn: number): string|number; // Return the value of pseudo-variable pvname if it is different than $null or // the parameter vs if the variable is having the $null value. function getvs(pvname: string, vn: number): string|number; // Return the value of pseudo-variable pvname if it is different than $null or the string <<null>> if the // variable is having the $null value. This should be used instead of KSR.pv.get(...) in the scripting // languages that throw and error when attempting to print a NULL (or NIL) value. function getw(pvname: string): string|number; // Set the value of pseudo-variable pvname to integer value provided by parameter val. function seti(pvname: string, val: number): void; // Set the value of pseudo-variable pvname to string value provided by parameter val. function sets(pvname: string, val: string): void; // Set the value of pseudo-variable pvname to $null. function unset(pvname: string): void; // Return true if pseudo-variable pvname is $null. function is_null(pvname: string): boolean; } export namespace hdr { // Append header to current SIP message (request or reply). It will be added after the last header. function append(hdr: string): number; // Append header to current SIP message (request or reply). // It will be added after the first header matching the name hdrName. function append_after(hdr: string, hdrName: string): number; // Insert header to current SIP message (request or reply). // It will be added before the first header. function insert(hdr: string): number; // Insert header to current SIP message (request or reply). // It will be added before the header matching the name hdrName. function insert_before(hdr: string, hdrName: string): number; // Remove all the headers with the name hdrName. function remove(hdrName: string): number; // Return greater than 0 if a header with the name hdrName exists and less than 0 if there is no such header. function is_present(hdrName: string): number; // Add a header to the SIP response to be generated by Kamailio for the current SIP request. function append_to_reply(hdr: string): number; } export namespace x { // Execute a function (specified by fname) exported by a Kamailio module. Additional parameters must be string // and they are passed to the Kamailio module function. function modf(name: string, ...params: string[]): number; // Equivalent of exit from native kamailio.cfg scripting language, stop the execution of the SIP routing script. function exit(): void; // Equivalent of drop from native kamailio.cfg scripting language, stop the execution of the SIP routing script // and drop routing further the SIP request branch or response. function drop(): void; } export namespace acc { // Equivalent of native kamailio.cfg function: acc_db_request("comment", "dbtable"). function acc_db_request(comment: string, dbtable: string): number; // Equivalent of native kamailio.cfg function: acc_log_request("comment"). function acc_log_request(comment: string): number; // Equivalent of native kamailio.cfg function: acc_request("comment", "dbtable"). function acc_request(comment: string, dbtable: string): number; } export namespace acc_radius { function request(comment: string): number; } export namespace alias_db { function lookup(stable: string): number; function lookup_ex(stable: string, sflags: string): number; } export namespace app_jsdt { function dofile(script: string): number; function dostring(script: string): number; function run(func: string): number; function run_p1(func: string, p1: string): number; function run_p2(func: string, p1: string, p2: string): number; function run_p3(func: string, p1: string, p2: string, p3: string): number; function runstring(script: string): number; } export namespace app_lua { function dofile(script: string): number; function dostring(script: string): number; function run(func: string): number; function run_p1(func: string, p1: string): number; function run_p2(func: string, p1: string, p2: string): number; function run_p3(func: string, p1: string, p2: string, p3: string): number; function runstring(script: string): number; } export namespace app_python { function exec(method: string): number; function exec_p1(method: string, p1: string): number; } export namespace app_python3 { function exec(method: string): number; function exec_p1(method: string, p1: string): number; } export namespace app_ruby { function run(func: string): number; function run_p1(func: string, p1: string): number; function run_p2(func: string, p1: string, p2: string): number; function run_p3(func: string, p1: string, p2: string, p3: string): number; } export namespace app_sqlang { function dofile(script: string): number; function dostring(script: string): number; function run(func: string): number; function run_p1(func: string, p1: string): number; function run_p2(func: string, p1: string, p2: string): number; function run_p3(func: string, p1: string, p2: string, p3: string): number; function runstring(script: string): number; } export namespace async { function route(rn: string, s: number): number; function task_route(rn: string): number; } export namespace auth { function auth_challenge(realm: string, flags: number): number; function consume_credentials(): number; function has_credentials(srealm: string): number; function pv_auth_check(srealm: string, spasswd: string, vflags: number, vchecks: number): number; } export namespace auth_db { function auth_check(srealm: string, stable: string, iflags: number): number; function is_subscriber(suri: string, stable: string, iflags: number): number; } export namespace auth_ephemeral { function autheph_authenticate(susername: string, spassword: string): number; function autheph_check(srealm: string): number; function autheph_proxy(srealm: string): number; function autheph_www(srealm: string): number; function autheph_www_method(srealm: string, smethod: string): number; } export namespace auth_radius { function proxy_authorize(srealm: string): number; function proxy_authorize_user(srealm: string, suser: string): number; function www_authorize(srealm: string): number; function www_authorize_user(srealm: string, suser: string): number; } export namespace auth_xkeys { function auth_xkeys_add(shdr: string, skey: string, salg: string, sdata: string): number; function auth_xkeys_check(shdr: string, skey: string, salg: string, sdata: string): number; } export namespace benchmark { function bm_log_timer(tname: string): number; function bm_start_timer(tname: string): number; } export namespace blst { function blst_add(t: number): number; function blst_add_default(): number; function blst_add_retry_after(t_min: number, t_max: number): number; function blst_clear_ignore(mask: number): number; function blst_clear_ignore_all(): number; function blst_del(): number; function blst_is_blacklisted(): number; function blst_rpl_clear_ignore(mask: number): number; function blst_rpl_clear_ignore_all(): number; function blst_rpl_set_ignore(mask: number): number; function blst_rpl_set_ignore_all(): number; function blst_set_ignore(mask: number): number; function blst_set_ignore_all(): number; } export namespace call_control { function call_control(): number; } export namespace cfgutils { function abort(): number; function core_hash(s1: string, s2: string, sz: number): number; function lock(lkey: string): number; function pkg_status(): number; function pkg_summary(): number; function rand_event(): number; function rand_get_prob(): number; function rand_reset_prob(): number; function rand_set_prob(percent_par: number): number; function shm_status(): number; function shm_summary(): number; function trylock(lkey: string): number; function unlock(lkey: string): number; } export namespace cnxcc { function get_channel_count(sclient: string, pvname: string): number; function set_max_channels(sclient: string, max_chan: number): number; function set_max_credit(sclient: string, scredit: string, scps: string, initp: number, finishp: number): number; function set_max_time(sclient: string, max_secs: number): number; function terminate_all(sclient: string): number; function update_max_time(sclient: string, secs: number): number; } export namespace corex { function append_branch(): number; function append_branch_uri(uri: string): number; function append_branch_uri_q(uri: string, q: string): number; function has_ruri_user(): number; function has_user_agent(): number; function isxflagset(fval: number): number; function resetxflag(fval: number): number; function send_data(uri: string, data: string): number; function sendx(uri: string, sock: string, data: string): number; function set_recv_socket(ssock: string): number; function set_send_socket(ssock: string): number; function set_source_address(saddr: string): number; function setxflag(fval: number): number; function via_add_srvid(fval: number): number; function via_add_xavp_params(fval: number): number; function via_use_xavp_fields(fval: number): number; } export namespace counters { function add(sname: string, v: number): number; function inc(sname: string): number; function reset(sname: string): number; } export namespace crypto { function aes_decrypt(ins: string, keys: string, dpv: string): number; function aes_encrypt(ins: string, keys: string, dpv: string): number; } export namespace dialog { function dlg_bye(side: string): number; function dlg_db_load_callid(callid: string): number; function dlg_db_load_extra(): number; function dlg_get(sc: string, sf: string, st: string): number; function dlg_isflagset(val: number): number; function dlg_manage(): number; function dlg_resetflag(val: number): number; function dlg_set_property(pval: string): number; function dlg_set_timeout(to: number): number; function dlg_set_timeout_id(to: number, he: number, hi: number): number; function dlg_setflag(val: number): number; function get_profile_size(sprofile: string, svalue: string, spv: string): number; function get_profile_size_static(sprofile: string, spv: string): number; function is_in_profile(sprofile: string, svalue: string): number; function is_in_profile_static(sprofile: string): number; function is_known_dlg(): number; function set_dlg_profile(sprofile: string, svalue: string): number; function set_dlg_profile_static(sprofile: string): number; function unset_dlg_profile(sprofile: string, svalue: string): number; function unset_dlg_profile_static(sprofile: string): number; } export namespace dialplan { function dp_match(dpid: number, src: string): number; function dp_replace(dpid: number, src: string, dst: string): number; } export namespace dispatcher { function ds_is_from_list(group: number): number; function ds_is_from_list_mode(vset: number, vmode: number): number; function ds_is_from_list_uri(vset: number, vmode: number, vuri: string): number; function ds_is_from_lists(): number; function ds_list_exists(set: number): number; function ds_load_unset(): number; function ds_load_update(): number; function ds_mark_dst(): number; function ds_mark_dst_state(sval: string): number; function ds_next_domain(): number; function ds_next_dst(): number; function ds_reload(): number; function ds_select(set: number, alg: number): number; function ds_select_domain(set: number, alg: number): number; function ds_select_domain_limit(set: number, alg: number, limit: number): number; function ds_select_dst(set: number, alg: number): number; function ds_select_dst_limit(set: number, alg: number, limit: number): number; function ds_select_limit(set: number, alg: number, limit: number): number; function ds_select_routes(srules: string, smode: string): number; function ds_select_routes_limit(srules: string, smode: string, rlimit: number): number; function ds_set_domain(): number; function ds_set_dst(): number; } export namespace diversion { function add_diversion(reason: string): number; function add_diversion_uri(reason: string, uri: string): number; } export namespace dmq { function bcast_message(peer_str: string, body_str: string, ct_str: string): number; function handle_message(): number; function handle_message_rc(returnval: number): number; function is_from_node(): number; function send_message(peer_str: string, to_str: string, body_str: string, ct_str: string): number; function t_replicate(): number; function t_replicate_mode(mode: number): number; } export namespace domain { function is_domain_local(sdomain: string): number; function is_from_local(): number; function is_uri_host_local(): number; function lookup_domain(_sdomain: string): number; function lookup_domain_prefix(_sdomain: string, _sprefix: string): number; } export namespace drouting { function do_routing(grp_id: number): number; function do_routing_furi(): number; function goes_to_gw(): number; function goes_to_gw_type(type: number): number; function is_from_gw(): number; function is_from_gw_type(type: number): number; function is_from_gw_type_flags(type: number, flags: number): number; function next_routing(): number; function use_next_gw(): number; } export namespace evapi { function async_relay(sdata: string): number; function close(): number; function relay(sdata: string): number; function relay_multicast(sdata: string, stag: string): number; function relay_unicast(sdata: string, stag: string): number; function set_tag(stag: string): number; } export namespace exec { function exec_avp(cmd: string): number; function exec_dset(cmd: string): number; function exec_msg(cmd: string): number; } export namespace geoip { function match(tomatch: string, pvclass: string): number; } export namespace geoip2 { function match(tomatch: string, pvclass: string): number; } export namespace group { function is_user_in(uri: string, grp: string): number; } export namespace htable { function sht_has_name(sname: string, sop: string, sval: string): number; function sht_has_str_value(sname: string, sop: string, sval: string): number; function sht_iterator_end(iname: string): number; function sht_iterator_next(iname: string): number; function sht_iterator_start(iname: string, hname: string): number; function sht_lock(htname: string, skey: string): number; function sht_reset(hname: string): number; function sht_rm(hname: string, iname: string): number; function sht_rm_name(sname: string, sop: string, sval: string): number; function sht_rm_name_re(htname: string, rexp: string): number; function sht_rm_value(sname: string, sop: string, sval: string): number; function sht_rm_value_re(htname: string, rexp: string): number; function sht_setex(htname: string, itname: string, itval: number): number; function sht_seti(htname: string, itname: string, itval: number): number; function sht_sets(htname: string, itname: string, itval: string): number; function sht_setxi(htname: string, itname: string, itval: number, exval: number): number; function sht_setxs(htname: string, itname: string, itval: string, exval: number): number; function sht_unlock(htname: string, skey: string): number; } export namespace http_async_client { function query(sdata: string, rn: string): number; } export namespace http_client { function curl_connect(con: string, url: string, dpv: string): number; function curl_connect_post(con: string, url: string, ctype: string, data: string, dpv: string): number; function query(url: string, dpv: string): number; function query_post(url: string, post: string, dpv: string): number; function query_post_hdrs(url: string, post: string, hdrs: string, dpv: string): number; } export namespace imc { function imc_manager(): number; } export namespace ipops { function compare_ips(_sval1: string, _sval2: string): number; function compare_pure_ips(_sval1: string, _sval2: string): number; function detailed_ip_type(_sval: string, _dpv: string): number; function detailed_ipv4_type(_sval: string, _dpv: string): number; function detailed_ipv6_type(_sval: string, _dpv: string): number; function dns_int_match_ip(vhn: string, vip: string): number; function dns_query(naptrname: string, pvid: string): number; function dns_sys_match_ip(vhn: string, vip: string): number; function ip_is_in_subnet(_sval1: string, _sval2: string): number; function ip_type(sval: string): number; function is_in_subnet(_sval1: string, _sval2: string): number; function is_ip(sval: string): number; function is_ip4(sval: string): number; function is_ip6(sval: string): number; function is_ip6_reference(sval: string): number; function is_ip_rfc1918(sval: string): number; function is_pure_ip(sval: string): number; function naptr_query(naptrname: string, pvid: string): number; function srv_query(naptrname: string, pvid: string): number; } export namespace jansson { function get(spath: string, sdoc: string, spv: string): number; } export namespace jsonrpcs { function exec(scmd: string): number; } export namespace keepalive { function is_alive(dest: string): number; } export namespace kex { function resetdebug(): number; function setdebug(lval: number): number; } export namespace lcr { function defunct_gw(defunct_period: number): number; function from_any_gw(): number; function from_any_gw_addr(addr_str: string, transport: number): number; function from_gw(lcr_id: number): number; function from_gw_addr(lcr_id: number, addr_str: string, transport: number): number; function inactivate_gw(): number; function load_gws(lcr_id: number): number; function load_gws_furi(lcr_id: number, ruri_user: string, from_uri: string): number; function load_gws_ruser(lcr_id: number, ruri_user: string): number; function next_gw(): number; function to_any_gw(): number; function to_any_gw_addr(addr_str: string, transport: number): number; function to_gw(lcr_id: number): number; function to_gw_addr(lcr_id: number, addr_str: string, transport: number): number; } export namespace log_custom { function log_udp(txt: string): number; } export namespace log_systemd { function sd_journal_print(slev: string, stxt: string): number; function sd_journal_send_xvap(xname: string): number; } export namespace maxfwd { function is_maxfwd_lt(limit: number): number; function process_maxfwd(limit: number): number; } export namespace mediaproxy { function end_media_session(): number; function engage_media_proxy(): number; function use_media_proxy(): number; } export namespace misc_radius { function does_uri_exist(): number; function does_uri_exist_uval(suri: string): number; function does_uri_user_exist(): number; function does_uri_user_exist_uval(user: string): number; function is_user_in(user: string, group: string): number; function load_callee_avps(user: string): number; function load_caller_avps(user: string): number; } export namespace mqueue { function mq_add(mq: string, key: string, val: string): number; function mq_fetch(mq: string): number; function mq_pv_free(mq: string): number; function mq_size(mq: string): number; } export namespace msilo { function mdump(): number; function mdump_uri(owner_s: string): number; function mstore(): number; function mstore_uri(owner_s: string): number; } export namespace msrp { function cmap_lookup(): number; function cmap_save(): number; function is_reply(): number; function is_request(): number; function relay(): number; function relay_flags(rtflags: number): number; function reply(rcode: string, rtext: string, rhdrs: string): number; function reply_flags(rtflags: number): number; function set_dst(rtaddr: string, rfsock: string): number; } export namespace mtree { function mt_match(tname: string, tomatch: string, mval: number): number; } export namespace nat_traversal { function client_nat_test(tests: number): number; function fix_contact(): number; function nat_keepalive(): number; } export namespace nathelper { function add_contact_alias(): number; function add_contact_alias_addr(ip_str: string, port_str: string, proto_str: string): number; function add_rcv_param(upos: number): number; function fix_nated_contact(): number; function fix_nated_register(): number; function fix_nated_sdp(level: number): number; function fix_nated_sdp_ip(level: number, ip: string): number; function handle_ruri_alias(): number; function is_rfc1918(address: string): number; function nat_uac_test(tests: number): number; function set_contact_alias(): number; } export namespace ndb_mongodb { function exec(ssrv: string, sdname: string, scname: string, scmd: string, sres: string): number; function exec_simple(ssrv: string, sdname: string, scname: string, scmd: string, sres: string): number; function find(ssrv: string, sdname: string, scname: string, scmd: string, sres: string): number; function find_one(ssrv: string, sdname: string, scname: string, scmd: string, sres: string): number; function free_reply(name: string): number; function next_reply(name: string): number; } export namespace ndb_redis { function redis_cmd(srv: string, rcmd: string, sres: string): number; function redis_cmd_p1(srv: string, rcmd: string, p1: string, sres: string): number; function redis_cmd_p2(srv: string, rcmd: string, p1: string, p2: string, sres: string): number; function redis_cmd_p3(srv: string, rcmd: string, p1: string, p2: string, p3: string, sres: string): number; function redis_free(name: string): number; } export namespace path { function add_path(): number; function add_path_received(): number; function add_path_received_user(_user: string): number; function add_path_received_user_params(_user: string, _params: string): number; function add_path_user(_user: string): number; function add_path_user_params(_user: string, _params: string): number; } export namespace pdt { function pd_translate(sd: string, md: number): number; function pprefix2domain(m: number, s: number): number; } export namespace permissions { function allow_address(addr_group: number, ips: string, port: number): number; function allow_address_group(_addr: string, _port: number): number; function allow_source_address(addr_group: number): number; function allow_source_address_group(): number; } export namespace phonenum { function match(tomatch: string, pvclass: string): number; } export namespace pike { function pike_check_req(): number; } export namespace pipelimit { function pl_check(pipeid: string): number; function pl_check_limit(pipeid: string, alg: string, limit: number): number; function pl_drop(): number; function pl_drop_range(rmin: number, rmax: number): number; function pl_drop_retry(rafter: number): number; } export namespace prefix_route { function prefix_route(ruser: string): number; function prefix_route_uri(): number; } export namespace presence { function handle_publish(): number; function handle_publish_uri(sender_uri: string): number; function handle_subscribe(): number; function handle_subscribe_uri(wuri: string): number; function pres_auth_status(watcher_uri: string, presentity_uri: string): number; function pres_has_subscribers(pres_uri: string, wevent: string): number; function pres_refresh_watchers(pres: string, event: string, type: number): number; function pres_refresh_watchers_file(pres: string, event: string, type: number, file_uri: string, filename: string): number; function pres_update_watchers(pres_uri: string, event: string): number; } export namespace presence_xml { function pres_check_activities(pres_uri: string, activity: string): number; function pres_check_basic(pres_uri: string, status: string): number; } export namespace pua { function pua_set_publish(): number; function pua_update_contact(): number; } export namespace pvx { function evalx(dst: string, fmt: string): number; function pv_var_to_xavp(varname: string, xname: string): number; function pv_xavp_print(): number; function pv_xavp_to_var(xname: string): number; function sbranch_append(): number; function sbranch_reset(): number; function sbranch_set_ruri(): number; function xavp_params_explode(sparams: string, sxname: string): number; function xavp_params_implode(sxname: string, svname: string): number; } export namespace rabbitmq { function publish(exchange: string, routingkey: string, contenttype: string, messagebody: string): number; function publish_consume(exchange: string, routingkey: string, contenttype: string, messagebody: string, dpv: string): number; } export namespace regex { function pcre_match(string: string, regex: string): number; function pcre_match_group(string: string, num_pcre: number): number; } export namespace registrar { function add_sock_hdr(hdr_name: string): number; function lookup(table: string): number; function lookup_branches(_dtable: string): number; function lookup_to_dset(table: string, uri: string): number; function lookup_uri(table: string, uri: string): number; function reg_fetch_contacts(dtable: string, uri: string, profile: string): number; function reg_free_contacts(profile: string): number; function registered(table: string): number; function registered_action(_dtable: string, _uri: string, _f: number, _aflags: number): number; function registered_flags(_dtable: string, _uri: string, _f: number): number; function registered_uri(_dtable: string, _uri: string): number; function save(table: string, flags: number): number; function save_uri(table: string, flags: number, uri: string): number; function set_q_override(new_q: string): number; function unregister(_dtable: string, _uri: string): number; function unregister_ruid(_dtable: string, _uri: string, _ruid: string): number; } export namespace rls { function handle_notify(): number; function handle_subscribe(): number; function handle_subscribe_uri(wuri: string): number; function update_subs(uri: string, event: string): number; } export namespace rr { function add_rr_param(sparam: string): number; function check_route_param(sre: string): number; function is_direction(dir: string): number; function loose_route(): number; function record_route(): number; function record_route_params(params: string): number; function remove_record_route(): number; } export namespace rtjson { function init_routes(rdoc: string): number; function next_route(): number; function push_routes(): number; function update_branch(): number; } export namespace rtpengine { function rtpengine_answer(flags: string): number; function rtpengine_answer0(): number; function rtpengine_delete(flags: string): number; function rtpengine_delete0(): number; function rtpengine_manage(flags: string): number; function rtpengine_manage0(): number; function rtpengine_offer(flags: string): number; function rtpengine_offer0(): number; function set_rtpengine_set(r1: number): number; // This function is the sibling function to set_rtpengine_set(). // The original module function is declared as set_rtpengine_set(setid[, setid2]). // In KEMI set_rtpengine_set() takes only the first parameter and set_rtpengine_set2() allows for the second optional parameter to be passed. // Please review the documentation for set_rtpengine_set() for more information. function set_rtpengine_set2(r1: number, r2: number): number; function start_recording(): number; function stop_recording(): number; } export namespace rtpproxy { function rtpproxy_answer(flags: string): number; function rtpproxy_answer0(): number; function rtpproxy_answer_ip(flags: string, mip: string): number; function rtpproxy_destroy(flags: string): number; function rtpproxy_destroy0(): number; function rtpproxy_manage(flags: string): number; function rtpproxy_manage0(): number; function rtpproxy_manage_ip(flags: string, mip: string): number; function rtpproxy_offer(flags: string): number; function rtpproxy_offer0(): number; function rtpproxy_offer_ip(flags: string, mip: string): number; function rtpproxy_stop_stream2uac(): number; function rtpproxy_stop_stream2uas(): number; function rtpproxy_stream2uac(pname: string, count: number): number; function rtpproxy_stream2uas(pname: string, count: number): number; function set_rtpproxy_set(rset: number): number; function start_recording(): number; } export namespace sanity { function sanity_check(mflags: number, uflags: number): number; function sanity_check_defaults(): number; function sanity_reply(): number; } export namespace sca { function call_info_update(update_mask: number, uri_to: string, uri_from: string): number; function call_info_update_default(): number; function call_info_update_mask(umask: number): number; function call_info_update_turi(umask: number, sto: string): number; function handle_subscribe(): number; } export namespace sdpops { function keep_codecs_by_id(codecs: string, media: string): number; function keep_codecs_by_name(codecs: string, media: string): number; function remove_codecs_by_id(codecs: string, media: string): number; function remove_codecs_by_name(codecs: string, media: string): number; function remove_line_by_prefix(prefix: string, media: string): number; function remove_media(media: string): number; function sdp_content(): number; function sdp_content_flags(flags: number): number; function sdp_get(avp: string): number; function sdp_get_line_startswith(aname: string, sline: string): number; function sdp_print(llevel: number): number; function sdp_transport(avp: string): number; function sdp_with_active_media(media: string): number; function sdp_with_ice(): number; function sdp_with_media(media: string): number; } export namespace sipcapture { function float2int(_val: string, _coof: string): number; function report_capture(_table: string): number; function report_capture_cid(_table: string, _cid: string): number; function report_capture_data(_table: string, _cid: string, _data: string): number; function sip_capture(): number; function sip_capture_forward(puri: string): number; function sip_capture_mode(_table: string, _cmdata: string): number; function sip_capture_table(_table: string): number; } export namespace sipdump { function send(stag: string): number; } export namespace sipjson { function sj_serialize(smode: string, pvn: string): number; } export namespace siptrace { function hlog(message: string): number; function hlog_cid(correlationid: string, message: string): number; function sip_trace(): number; function sip_trace_dst(duri: string): number; function sip_trace_dst_cid(duri: string, cid: string): number; } export namespace siputils { function has_totag(): number; function is_alphanum(tval: string): number; function is_alphanumex(tval: string, eset: string): number; function is_first_hop(): number; function is_numeric(tval: string): number; function is_reply(): number; function is_request(): number; function is_tel_number(tval: string): number; function is_uri(suri: string): number; function is_user(suser: string): number; function uri_param(sparam: string): number; function uri_param_value(sparam: string, svalue: string): number; } export namespace sl { function send_reply(code: number, reason: string): number; function sl_forward_reply(code: string, reason: string): number; function sl_reply_error(): number; function sl_send_reply(code: number, reason: string): number; } export namespace speeddial { function lookup(stable: string): number; function lookup_owner(stable: string, sowner: string): number; } export namespace sqlops { function sql_is_null(sres: string, i: number, j: number): number; function sql_num_columns(sres: string): number; function sql_num_rows(sres: string): number; function sql_query(scon: string, squery: string, sres: string): number; function sql_query_async(scon: string, squery: string): number; function sql_result_free(sres: string): number; function sql_xquery(scon: string, squery: string, xavp: string): number; } export namespace ss7ops { function isup_to_json(proto: number): number; } export namespace sst { function sst_check_min(flag: number): number; } export namespace statistics { function reset_stat(sname: string): number; function update_stat(sname: string, sval: number): number; } export namespace statsc { function statsc_reset(): number; } export namespace statsd { function statsd_decr(key: string): number; function statsd_gauge(key: string, val: string): number; function statsd_incr(key: string): number; function statsd_set(key: string, val: string): number; function statsd_start(key: string): number; function statsd_stop(key: string): number; } export namespace tcpops { function tcp_conid_alive(i_conid: number): number; function tcp_conid_state(i_conid: number): number; function tcp_enable_closed_event(): number; function tcp_enable_closed_event_cid(i_conid: number): number; function tcp_keepalive_disable(): number; function tcp_keepalive_disable_cid(i_con: number): number; function tcp_keepalive_enable(i_idle: number, i_cnt: number, i_intvl: number): number; function tcp_keepalive_enable_cid(i_con: number, i_idle: number, i_cnt: number, i_intvl: number): number; function tcp_set_connection_lifetime(i_time: number): number; function tcp_set_connection_lifetime_cid(i_conid: number, i_time: number): number; } export namespace textops { function append_body_part(txt: string, ct: string): number; function append_body_part_cd(txt: string, ct: string, cd: string): number; function append_body_part_hex(txt: string, ct: string): number; function append_body_part_hex_cd(htxt: string, ct: string, cd: string): number; function cmp_istr(s1: string, s2: string): number; function cmp_str(s1: string, s2: string): number; function filter_body(content_type: string): number; function get_body_part(ctype: string, pvname: string): number; function get_body_part_raw(ctype: string, pvname: string): number; function has_body(): number; function has_body_type(ctype: string): number; function in_list(subject: string, list: string, vsep: string): number; function in_list_prefix(subject: string, list: string, vsep: string): number; function is_audio_on_hold(): number; function is_present_hf(hname: string): number; function is_present_hf_re(ematch: string): number; function is_privacy(privacy: string): number; function remove_body_part(content_type: string): number; function remove_hf_exp(ematch: string, eskip: string): number; function remove_hf_re(ematch: string): number; function replace(sre: string, sval: string): number; function replace_all(sre: string, sval: string): number; function replace_body(sre: string, sval: string): number; function replace_body_all(sre: string, sval: string): number; function replace_body_atonce(sre: string, sval: string): number; function replace_body_str(mkey: string, rval: string, rmode: string): number; function replace_hdrs(sre: string, sval: string): number; function replace_hdrs_str(mkey: string, rval: string, rmode: string): number; function replace_str(mkey: string, rval: string, rmode: string): number; function search(sre: string): number; function search_append(ematch: string, val: string): number; function search_append_body(ematch: string, val: string): number; function search_body(sre: string): number; function search_hf(hname: string, sre: string, flags: string): number; function set_body(nb: string, nc: string): number; function set_body_multipart(nbody: string, ctype: string, boundary: string): number; function set_body_multipart_boundary(boundary: string): number; function set_body_multipart_content(nbody: string, ctype: string): number; function set_body_multipart_mode(): number; function set_reply_body(nb: string, nc: string): number; function starts_with(s1: string, s2: string): number; function subst(subst: string): number; function subst_body(subst: string): number; function subst_hf(hname: string, subst: string, flags: string): number; function subst_uri(subst: string): number; function subst_user(subst: string): number; } export namespace textopsx { function append_hf_value(hexp: string, val: string): number; function assign_hf_value(hexp: string, val: string): number; function assign_hf_value2(hexp: string, val: string): number; function change_reply_status(code: number, reason: string): number; function exclude_hf_value(hexp: string, val: string): number; function fnmatch(val: string, match: string): number; function fnmatch_ex(val: string, match: string, flags: string): number; function hf_value_exists(hexp: string, val: string): number; function include_hf_value(hexp: string, val: string): number; function insert_hf_value(hexp: string, val: string): number; function keep_hf(): number; function keep_hf_re(sre: string): number; function msg_apply_changes(): number; function msg_set_buffer(obuf: string): number; function remove_body(): number; function remove_hf_value(hexp: string): number; function remove_hf_value2(hexp: string, val: string): number; } export namespace tls { function is_peer_verified(): number; } export namespace tm { function t_any_replied(): number; function t_any_timeout(): number; function t_branch_replied(): number; function t_branch_timeout(): number; function t_check_status(sexp: string): number; function t_check_trans(): number; function t_drop_replies(mode: string): number; function t_drop_replies_all(): number; function t_grep_status(code: number): number; function t_is_canceled(): number; function t_is_expired(): number; function t_is_retr_async_reply(): number; function t_is_set(target: string): number; function t_load_contacts(): number; function t_lookup_cancel(): number; function t_lookup_cancel_flags(flags: number): number; function t_lookup_request(): number; function t_newtran(): number; function t_next_contact_flow(): number; function t_next_contacts(): number; function t_on_branch(rname: string): number; function t_on_branch_failure(rname: string): number; function t_on_failure(rname: string): number; function t_on_reply(rname: string): number; function t_relay(): number; function t_release(): number; function t_replicate(suri: string): number; function t_reply(code: number, reason: string): number; function t_reset_fr(): number; function t_reset_max_lifetime(): number; function t_reset_retr(): number; function t_retransmit_reply(): number; function t_save_lumps(): number; function t_send_reply(code: number, reason: string): number; function t_set_auto_inv_100(state: number): number; function t_set_disable_6xx(state: number): number; function t_set_disable_failover(state: number): number; function t_set_disable_internal_reply(state: number): number; function t_set_fr(fr_inv: number, fr: number): number; function t_set_fr_inv(fr_inv: number): number; function t_set_max_lifetime(t1: number, t2: number): number; function t_set_no_e2e_cancel_reason(state: number): number; function t_set_retr(t1: number, t2: number): number; function t_uac_send(method: string, ruri: string, nexthop: string, ssock: string, hdrs: string, body: string): number; function t_use_uac_headers(): number; } export namespace tmrec { function is_leap_year(y: number): number; function is_leap_year_now(): number; function match(rv: string): number; function match_timestamp(rv: string, ti: number): number; function time_period_match(period: string): number; function time_period_match_timestamp(period: string, ti: number): number; } export namespace tmx { function t_cancel_branches(mode: string): number; function t_cancel_callid(callid_s: string, cseq_s: string, fl: number): number; function t_cancel_callid_reason(callid_s: string, cseq_s: string, fl: number, rcode: number): number; function t_continue(tindex: number, tlabel: number, cbname: string): number; function t_flush_flags(): number; function t_flush_xflags(): number; function t_is_branch_route(): number; function t_is_failure_route(): number; function t_is_reply_route(): number; function t_is_request_route(): number; function t_precheck_trans(): number; function t_reply_callid(callid_s: string, cseq_s: string, code: number, status_s: string): number; function t_reuse_branch(): number; function t_suspend(): number; } export namespace tsilo { function ts_append(_table: string, _ruri: string): number; function ts_append_to(tindex: number, tlabel: number, _table: string): number; function ts_append_to_uri(tindex: number, tlabel: number, _table: string, _uri: string): number; function ts_store(): number; function ts_store_uri(puri: string): number; } export namespace uac { function uac_auth(): number; function uac_reg_disable(attr: string, val: string): number; function uac_reg_enable(attr: string, val: string): number; function uac_reg_lookup(userid: string, sdst: string): number; function uac_reg_refresh(l_uuid: string): number; function uac_reg_request_to(userid: string, imode: number): number; function uac_reg_status(sruuid: string): number; function uac_replace_from(pdsp: string, puri: string): number; function uac_replace_from_uri(puri: string): number; function uac_replace_to(pdsp: string, puri: string): number; function uac_replace_to_uri(puri: string): number; function uac_req_send(): number; function uac_restore_from(): number; function uac_restore_to(): number; } export namespace uac_redirect { function get_redirects(max_c: number, max_b: number): number; function get_redirects_acc(max_c: number, max_b: number, reason: string): number; function get_redirects_all(): number; } export namespace uri_db { function check_from(): number; function check_to(): number; function check_uri(suri: string): number; function check_uri_realm(suri: string, susername: string, srealm: string): number; function does_uri_exist(): number; } export namespace userblacklist { function check_user_blacklist(suser: string, sdomain: string): number; function check_user_blacklist_number(suser: string, sdomain: string, snumber: string): number; function check_user_blacklist_table(suser: string, sdomain: string, snumber: string, stable: string): number; function check_user_whitelist(suser: string, sdomain: string): number; function check_user_whitelist_number(suser: string, sdomain: string, snumber: string): number; function check_user_whitelist_table(suser: string, sdomain: string, snumber: string, stable: string): number; } export namespace utils { function xcap_auth_status(watcher_uri: string, presentity_uri: string): number; } export namespace websocket { function close(): number; function close_conid(status: number, reason: string, con: number): number; function close_reason(status: number, reason: string): number; function handle_handshake(): number; } export namespace xcap_server { function xcaps_del(uri: string, path: string): number; function xcaps_get(uri: string, path: string): number; function xcaps_put(uri: string, path: string, pbody: string): number; } export namespace xhttp { function xhttp_reply(code: number, reason: string, ctype: string, body: string): number; } export namespace xhttp_pi { function dispatch(): number; } export namespace xhttp_rpc { function dispatch(): number; } export namespace xlog { function xalert(lmsg: string): number; function xcrit(lmsg: string): number; function xdbg(lmsg: string): number; function xerr(lmsg: string): number; function xinfo(lmsg: string): number; function xlog(slevel: string, lmsg: string): number; function xnotice(lmsg: string): number; function xwarn(lmsg: string): number; } export namespace xmlrpc { function dispatch_rpc(): number; function xmlrpc_reply(rcode: number, reason: string): number; } }
the_stack
import { Base } from "./Base"; import { Element, RelativeFunction, Stage } from "tree2d"; import { eventTranslators, SupportedEvents, VugelEvent, VugelEventListener, VugelFocusEvent, VugelKeyboardEvent, VugelMouseEvent, } from "../../events"; import { VugelStage } from "../../wrapper"; import { ensureBoolean, ensureColor, ensureFloat, isString } from "../utils/TypeUtils"; export { VugelNodeEventListener, VugelTextureErrorEventListener, VugelTextureEventListener, VugelResizeEventListener, VugelNodeEventObject, VugelTextureErrorEventObject, VugelTextureEventObject, VugelResizeEventObject, } from "./tree2dEvents"; import { VugelNodeEventListener, VugelTextureErrorEventListener, VugelTextureEventListener, VugelResizeEventListener, augmentTree2dElementEvent, } from "./tree2dEvents"; type NodeEvents = { onAuxclick?: VugelEventListener<VugelMouseEvent>; onClick?: VugelEventListener<VugelMouseEvent>; onContextmenu?: VugelEventListener<VugelMouseEvent>; onDblclick?: VugelEventListener<VugelMouseEvent>; onMousedown?: VugelEventListener<VugelMouseEvent>; onMouseenter?: VugelEventListener<VugelMouseEvent>; onMouseleave?: VugelEventListener<VugelMouseEvent>; onMousemove?: VugelEventListener<VugelMouseEvent>; onMouseout?: VugelEventListener<VugelMouseEvent>; onMouseover?: VugelEventListener<VugelMouseEvent>; onMouseup?: VugelEventListener<VugelMouseEvent>; onTouchcancel?: VugelEventListener<VugelMouseEvent>; onTouchend?: VugelEventListener<VugelMouseEvent>; onTouchmove?: VugelEventListener<VugelMouseEvent>; onTouchstart?: VugelEventListener<VugelMouseEvent>; onFocusin?: VugelEventListener<VugelFocusEvent>; onFocusout?: VugelEventListener<VugelFocusEvent>; onFocus?: VugelEventListener<VugelFocusEvent>; onBlur?: VugelEventListener<VugelFocusEvent>; onKeypress?: VugelEventListener<VugelKeyboardEvent>; onKeydown?: VugelEventListener<VugelKeyboardEvent>; onKeyup?: VugelEventListener<VugelKeyboardEvent>; }; export class Node extends Base { public readonly stage: VugelStage; public _nodeEvents?: NodeEvents = undefined; private pointerEvents: boolean | undefined = undefined; /** * CSS cursor type to be displayed when this node is being hovered. */ public "cursor-type": string | undefined = undefined; constructor(stage: VugelStage, base?: Element) { super(base || new Element(stage)); this.stage = stage; if (this.element) { this.element.data = this; } } getParentNode(): Node | undefined { let current = this.parent; while (current && !(current as any).el) { current = current.parent; } return current as Node; } get el(): Element { return this.element!; } get id() { return this.el.id; } set id(v: string | undefined) { this.el.id = v; } get "direct-ref"() { return this.el.ref; } set "direct-ref"(v: string | undefined) { // The direct ref can be used to reference children in direct containers. this.el.ref = v; } get "pointer-events"() { return this.pointerEvents; } set "pointer-events"(v: boolean | undefined) { this.pointerEvents = v; } capturePointerEvents(): boolean { return this.pointerEvents || (this.pointerEvents === undefined && this.getParentCapturePointerEvents()); } private getParentCapturePointerEvents() { const parentNode = this.getParentNode(); return parentNode ? parentNode.capturePointerEvents() : true; } // Returns the element containing the texture. Texture clipping and tinting will be applied to this element. get textureElement(): Element { return this.element!; } focus() { this.stage.eventHelpers.focusManager.setFocus(this); } dispatchEvent<T extends Event | undefined>(event: VugelEvent<T>) { const vueEventType = eventTranslators[event.type as SupportedEvents]; const eventHandler = this._nodeEvents?.[vueEventType] as VugelEventListener<any>; eventHandler?.({ ...event, currentTarget: this, }); } /** * Dispatches a bubbled event. * * @param event the event to be dispatched * @param ancestorBubble if you want to fake bubble (for example for a mouseleave event) until a certain ancestor, this field should be used. * Note that this will also update the target of the event. When setting it to "true", it will effectively bubble all the way down, though updating the target the entire tree. */ dispatchBubbledEvent<T extends Event | undefined>( event: VugelEvent<T>, ancestorBubble: Base | true | undefined = undefined, ) { const vueEventType = eventTranslators[event.type as SupportedEvents]; let currentNode: Base | undefined = this; while (currentNode !== undefined && currentNode !== ancestorBubble) { const eventHandler = (currentNode as Node)._nodeEvents?.[vueEventType] as VugelEventListener<any>; const newEvent = { ...event, currentTarget: currentNode, target: ancestorBubble !== undefined ? currentNode : event.target, }; eventHandler?.(newEvent); if (ancestorBubble !== undefined && newEvent.cancelBubble) { return; } currentNode = currentNode.parent; } } // Converts the world (canvas) coordinates to an offset w.r.t. to this Node getLocalOffset(worldX: number, worldY: number) { return this.el.core.convertWorldCoordsToLocal(worldX, worldY); } get x() { return this.el.x; } set x(v: number) { this.el.x = ensureFloat(v); } get "func-x"() { return this.el.funcX; } set "func-x"(v: RelativeFunction | string | undefined) { this.el.funcX = ensureRelativeFunction(v); } get y() { return this.el.y; } set y(v: number) { this.el.y = v; } get "func-y"() { return this.el.funcY; } set "func-y"(v: RelativeFunction | string | undefined) { this.el.funcY = ensureRelativeFunction(v); } get w() { return this.el.w; } set w(v: number) { this.el.w = v; } get "func-w"() { return this.el.funcW; } set "func-w"(v: RelativeFunction | string | undefined) { this.el.funcW = ensureRelativeFunction(v); } // This can be used to apply properties directly to this node. Can be handy when the setting relies on the stage. set "apply-direct"(v: (e: { node: Node }) => void) { v({ node: this }); } get h() { return this.el.h; } set h(v: number) { this.el.h = v; } get "func-h"() { return this.el.funcH; } set "func-h"(v: RelativeFunction | string | undefined) { this.el.funcH = ensureRelativeFunction(v); } get "scale-x"() { return this.el.scaleX; } set "scale-x"(v: number) { this.el.scaleX = ensureFloat(v); } get "scale-y"() { return this.el.scaleY; } set "scale-y"(v: number) { this.el.scaleY = ensureFloat(v); } get scale() { return this.el.scale; } set scale(v: any) { this.el.scale = ensureFloat(v); } get "pivot-x"() { return this.el.pivotX; } set "pivot-x"(v: number) { this.el.pivotX = ensureFloat(v); } get "pivot-y"() { return this.el.pivotY; } set "pivot-y"(v: number) { this.el.pivotY = ensureFloat(v); } get pivot() { return this.el.pivot; } set pivot(v: any) { this.el.pivot = ensureFloat(v); } get "mount-x"() { return this.el.mountX; } set "mount-x"(v: number) { this.el.mountX = ensureFloat(v); } get "mount-y"() { return this.el.mountY; } set "mount-y"(v: number) { this.el.mountY = ensureFloat(v); } get mount() { return this.el.mount; } set mount(v: any) { this.el.mount = ensureFloat(v); } get rotation() { return this.el.rotation; } set rotation(v: number) { this.el.rotation = ensureFloat(v); } get alpha() { return this.el.alpha; } set alpha(v: number) { this.el.alpha = ensureFloat(v); } get visible() { return this.el.visible; } set visible(v: boolean) { this.el.visible = ensureBoolean(v); } get "color-top-left"() { return this.textureElement.colorUl; } set "color-top-left"(v: number | string) { this.textureElement.colorUl = ensureColor(v); } get "color-top-right"() { return this.textureElement.colorUr; } set "color-top-right"(v: number | string) { this.textureElement.colorUr = ensureColor(v); } get "color-bottom-left"() { return this.textureElement.colorBl; } set "color-bottom-left"(v: number | string) { this.textureElement.colorBl = ensureColor(v); } get "color-bottom-right"() { return this.textureElement.colorBr; } set "color-bottom-right"(v: number | string) { this.textureElement.colorBr = ensureColor(v); } get "color-top"() { return this.textureElement.colorTop; } set "color-top"(v: number | string) { this.textureElement.colorTop = ensureColor(v); } get "color-bottom"() { return this.textureElement.colorBottom; } set "color-bottom"(v: number | string) { this.textureElement.colorBottom = ensureColor(v); } get "color-left"() { return this.textureElement.colorLeft; } set "color-left"(v: number | string) { this.textureElement.colorLeft = ensureColor(v); } get "color-right"() { return this.textureElement.colorRight; } set "color-right"(v: number | string) { this.textureElement.colorRight = ensureColor(v); } get color() { return this.textureElement.color; } set color(v: number | string) { this.textureElement.color = ensureColor(v); } get "clip-x"() { return this.textureElement.texture?.x || 0; } set "clip-x"(v: number) { if (this.textureElement.texture) { this.textureElement.texture.x = v; } } get "clip-y"() { return this.textureElement.texture?.y || 0; } set "clip-y"(v: number) { if (this.textureElement.texture) { this.textureElement.texture.y = v; } } get "clip-w"() { return this.textureElement.texture?.w || 0; } set "clip-w"(v: number) { if (this.textureElement.texture) { this.textureElement.texture.w = v; } } get "clip-h"() { return this.textureElement.texture?.h || 0; } set "clip-h"(v: number) { if (this.textureElement.texture) { this.textureElement.texture.h = v; } } get "pixel-ratio"() { return this.textureElement.texture?.pixelRatio || 1; } set "pixel-ratio"(v: number) { if (this.textureElement.texture) { this.textureElement.texture.pixelRatio = ensureFloat(v); } } get "z-index"() { return this.el.zIndex; } set "z-index"(v: number) { this.el.zIndex = ensureFloat(v); } get "bounds-margin"() { return this.el.boundsMargin; } set "bounds-margin"(v: number | undefined) { this.el.boundsMargin = ensureFloat(v); } get "bounds-margin-left"() { return this.el.boundsMarginLeft; } set "bounds-margin-left"(v: number) { this.el.boundsMarginLeft = ensureFloat(v); } get "bounds-margin-top"() { return this.el.boundsMarginTop; } set "bounds-margin-top"(v: number) { this.el.boundsMarginTop = ensureFloat(v); } get "bounds-margin-right"() { return this.el.boundsMarginRight; } set "bounds-margin-right"(v: number) { this.el.boundsMarginRight = ensureFloat(v); } get "bounds-margin-bottom"() { return this.el.boundsMarginBottom; } set "bounds-margin-bottom"(v: number) { this.el.boundsMarginBottom = ensureFloat(v); } get "flex-item"() { return this.el.flexItem; } set "flex-item"(v: boolean) { this.el.flexItem = ensureBoolean(v); } get "flex-grow"() { return this.el.flexGrow; } set "flex-grow"(v: number) { this.el.flexGrow = ensureFloat(v); } get "flex-shrink"() { return this.el.flexShrink; } set "flex-shrink"(v: number) { this.el.flexShrink = ensureFloat(v); } get "flex-align-self"() { return this.el.flexAlignSelf; } set "flex-align-self"(v: "flex-start" | "flex-end" | "center" | "stretch" | undefined) { this.el.flexAlignSelf = v; } get margin() { return this.el.margin; } set margin(v: number) { this.el.margin = ensureFloat(v); } get "margin-left"() { return this.el.marginLeft; } set "margin-left"(v: number) { this.el.marginLeft = ensureFloat(v); } get "margin-right"() { return this.el.marginRight; } set "margin-right"(v: number) { this.el.marginRight = ensureFloat(v); } get "margin-top"() { return this.el.marginTop; } set "margin-top"(v: number) { this.el.marginTop = ensureFloat(v); } get "margin-bottom"() { return this.el.marginBottom; } set "margin-bottom"(v: number) { this.el.marginBottom = ensureFloat(v); } get "min-width"() { return this.el.minWidth; } set "min-width"(v: number) { this.el.minWidth = ensureFloat(v); } get "min-height"() { return this.el.minHeight; } set "min-height"(v: number) { this.el.minHeight = ensureFloat(v); } get "max-width"() { return this.el.maxWidth; } set "max-width"(v: number) { this.el.maxWidth = ensureFloat(v); } get "max-height"() { return this.el.maxHeight; } set "max-height"(v: number) { this.el.maxHeight = ensureFloat(v); } get "skip-in-layout"() { return this.el.skipInLayout; } set "skip-in-layout"(v: boolean) { this.el.skipInLayout = ensureBoolean(v); } public get nodeEvents(): NodeEvents { if (!this._nodeEvents) { this._nodeEvents = {}; } return this._nodeEvents; } // Setters for NodeEvents set onSetup(v: VugelNodeEventListener | undefined) { this.el.onSetup = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onAttach(v: VugelNodeEventListener | undefined) { this.el.onAttach = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onDetach(v: VugelNodeEventListener | undefined) { this.el.onDetach = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onEnabled(v: VugelNodeEventListener | undefined) { this.el.onEnabled = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onDisabled(v: VugelNodeEventListener | undefined) { this.el.onDisabled = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onActive(v: VugelNodeEventListener | undefined) { this.el.onActive = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onInactive(v: VugelNodeEventListener | undefined) { this.el.onInactive = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onTextureError(v: VugelTextureErrorEventListener | undefined) { this.el.onTextureError = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onTextureLoaded(v: VugelTextureEventListener | undefined) { this.el.onTextureLoaded = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onTextureUnloaded(v: VugelTextureEventListener | undefined) { this.el.onTextureUnloaded = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onResize(v: VugelResizeEventListener | undefined) { this.el.onResize = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onUpdate(v: VugelNodeEventListener | undefined) { this.el.onUpdate = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onAfterCalcs(v: VugelNodeEventListener | undefined) { this.el.onAfterCalcs = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } set onAfterUpdate(v: VugelNodeEventListener | undefined) { this.el.onAfterUpdate = v ? (e) => v(augmentTree2dElementEvent(e)) : undefined; } // MouseEvent set onAuxclick(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onAuxclick = e; } set onClick(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onClick = e; } set onContextmenu(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onContextmenu = e; } set onDblclick(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onDblclick = e; } set onMousedown(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onMousedown = e; } set onMouseenter(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onMouseenter = e; } set onMouseleave(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onMouseleave = e; } set onMousemove(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onMousemove = e; } set onMouseout(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onMouseout = e; } set onMouseover(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onMouseover = e; } set onMouseup(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onMouseup = e; } // TouchEvent set onTouchcancel(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onTouchcancel = e; } set onTouchend(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onTouchend = e; } set onTouchmove(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onTouchmove = e; } set onTouchstart(e: VugelEventListener<VugelMouseEvent> | undefined) { this.nodeEvents.onTouchstart = e; } // FocusEvent set onFocusin(e: VugelEventListener<VugelFocusEvent> | undefined) { this.nodeEvents.onFocusin = e; } set onFocusout(e: VugelEventListener<VugelFocusEvent> | undefined) { this.nodeEvents.onFocusout = e; } set onFocus(e: VugelEventListener<VugelFocusEvent> | undefined) { this.nodeEvents.onFocus = e; } set onBlur(e: VugelEventListener<VugelFocusEvent> | undefined) { this.nodeEvents.onBlur = e; } // KeyboardEvent set onKeypress(e: VugelEventListener<VugelKeyboardEvent> | undefined) { this.nodeEvents.onKeypress = e; } set onKeydown(e: VugelEventListener<VugelKeyboardEvent> | undefined) { this.nodeEvents.onKeydown = e; } set onKeyup(e: VugelEventListener<VugelKeyboardEvent> | undefined) { this.nodeEvents.onKeyup = e; } getLayoutX() { return this.el.layoutX; } getLayoutY() { return this.el.layoutY; } getLayoutW() { return this.el.layoutW; } getLayoutH() { return this.el.layoutH; } } /** * Do not proxify Nodes when using template refs. * See https://github.com/vuejs/vue-next/pull/1060 */ (Node.prototype as any)["__v_skip"] = true; function ensureRelativeFunction(v: RelativeFunction | string | undefined) { if (isString(v)) { // Convert to function. return convertRelativeFunction(v); } else { return v; } } // We hold a cache because string-based vue properties will otherwise result in a new relative function on every vnode // update, with performance implications. const cachedRelFunctions = new Map<string, RelativeFunction>(); function convertRelativeFunction(body: string): RelativeFunction { let fn = cachedRelFunctions.get(body); if (!fn) { fn = new Function("w", "h", `return ${body}`) as RelativeFunction; cachedRelFunctions.set(body, fn); } return fn; }
the_stack
export namespace Keynote { // Default Application export interface Application {} // Class /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A master slide in a theme or slideshow document */ export interface MasterSlide { /** * The name of the master slide */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A slide in a slideshow document */ export interface Slide { /** * The master slide this slide is based upon */ baseSlide(): any; /** * Is the default body text displayed? */ bodyShowing(): boolean; /** * Is the slide skipped? */ skipped(): boolean; /** * index of the slide in the document */ slideNumber(): number; /** * Is the default slide title displayed? */ titleShowing(): boolean; /** * The default body container of the slide */ defaultBodyItem(): any; /** * The default title container of the slide */ defaultTitleItem(): any; /** * The presenter notes for the slide */ presenterNotes(): any; /** * The transition settings to apply to the slide. */ transitionProperties(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A collection of master slides, with shared design intents and elements. */ export interface Theme { /** * The identifier used by the application. */ id(): string; name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * This provides the base rich text class for all iWork applications. */ export interface RichText { /** * The color of the font. Expressed as an RGB value consisting of a list of three color values from 0 to 65535. ex: Blue = {0, 0, 65535}. */ color(): any; /** * The name of the font. Can be the PostScript name, such as: “TimesNewRomanPS-ItalicMT”, or display name: “Times New Roman Italic”. TIP: Use the Font Book application get the information about a typeface. */ font(): string; /** * The size of the font. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * One of some text's characters. */ export interface Character {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * One of some text's paragraphs. */ export interface Paragraph {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * One of some text's words. */ export interface Word {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A container for iWork items */ export interface IWorkContainer {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An item which supports formatting */ export interface IWorkItem { /** * The height of the iWork item. */ height(): number; /** * Whether the object is locked. */ locked(): boolean; /** * The iWork container containing this iWork item. */ parent(): any; /** * The horizontal and vertical coordinates of the top left point of the iWork item. */ position(): any; /** * The width of the iWork item. */ width(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An audio clip */ export interface AudioClip { /** * The name of the audio file. */ fileName(): any; /** * The volume setting for the audio clip, from 0 (none) to 100 (full volume). */ clipVolume(): number; /** * If or how the audio clip repeats. */ repetitionMethod(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A shape container */ export interface Shape { /** * The background, if any, for the shape. */ backgroundFillType(): any; /** * The text contained within the shape. */ objectText(): any; /** * Is the iWork item displaying a reflection? */ reflectionShowing(): boolean; /** * The percentage of reflection of the iWork item, from 0 (none) to 100 (full). */ reflectionValue(): number; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; /** * The opacity of the object, in percent. */ opacity(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A chart */ export interface Chart {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An image container */ export interface Image { /** * Text associated with the image, read aloud by VoiceOver. */ description(): string; /** * The image file. */ file(): any; /** * The name of the image file. */ fileName(): any; /** * The opacity of the object, in percent. */ opacity(): number; /** * Is the iWork item displaying a reflection? */ reflectionShowing(): boolean; /** * The percentage of reflection of the iWork item, from 0 (none) to 100 (full). */ reflectionValue(): number; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A group container */ export interface Group { /** * The height of the iWork item. */ height(): number; /** * The iWork container containing this iWork item. */ parent(): any; /** * The horizontal and vertical coordinates of the top left point of the iWork item. */ position(): any; /** * The width of the iWork item. */ width(): number; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A line */ export interface Line { /** * A list of two numbers indicating the horizontal and vertical position of the line ending point. */ endPoint(): any; /** * Is the iWork item displaying a reflection? */ reflectionShowing(): boolean; /** * The percentage of reflection of the iWork item, from 0 (none) to 100 (full). */ reflectionValue(): number; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; /** * A list of two numbers indicating the horizontal and vertical position of the line starting point. */ startPoint(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A movie container */ export interface Movie { /** * The name of the movie file. */ fileName(): any; /** * The volume setting for the movie, from 0 (none) to 100 (full volume). */ movieVolume(): number; /** * The opacity of the object, in percent. */ opacity(): number; /** * Is the iWork item displaying a reflection? */ reflectionShowing(): boolean; /** * The percentage of reflection of the iWork item, from 0 (none) to 100 (full). */ reflectionValue(): number; /** * If or how the movie repeats. */ repetitionMethod(): any; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A table */ export interface Table { /** * The item's name. */ name(): string; /** * The range describing every cell in the table. */ cellRange(): any; /** * The cells currently selected in the table. */ selectionRange(): any; /** * The number of rows in the table. */ rowCount(): number; /** * The number of columns in the table. */ columnCount(): number; /** * The number of header rows in the table. */ headerRowCount(): number; /** * The number of header columns in the table. */ headerColumnCount(): number; /** * The number of footer rows in the table. */ footerRowCount(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A text container */ export interface TextItem { /** * The background, if any, for the text item. */ backgroundFillType(): any; /** * The text contained within the text item. */ objectText(): any; /** * The opacity of the object, in percent. */ opacity(): number; /** * Is the iWork item displaying a reflection? */ reflectionShowing(): boolean; /** * The percentage of reflection of the iWork item, from 0 (none) to 100 (full). */ reflectionValue(): number; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A range of cells in a table */ export interface Range { /** * The font of the range's cells. */ fontName(): string; /** * The font size of the range's cells. */ fontSize(): any; /** * The format of the range's cells. */ format(): any; /** * The horizontal alignment of content in the range's cells. */ alignment(): any; /** * The range's coordinates. */ name(): string; /** * The text color of the range's cells. */ textColor(): any; /** * Whether text should wrap in the range's cells. */ textWrap(): boolean; /** * The background color of the range's cells. */ backgroundColor(): any; /** * The vertical alignment of content in the range's cells. */ verticalAlignment(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A cell in a table */ export interface Cell { /** * The cell's column. */ column(): any; /** * The cell's row. */ row(): any; /** * The actual value in the cell, or missing value if the cell is empty. */ value(): any; /** * The formatted value in the cell, or missing value if the cell is empty. */ formattedValue(): string; /** * The formula in the cell, as text, e.g. =SUM(40+2). If the cell does not contain a formula, returns missing value. To set the value of a cell to a formula as text, use the value property. */ formula(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A row of cells in a table */ export interface Row { /** * The row's index in the table (e.g., the second row has address 2). */ address(): number; /** * The height of the row. */ height(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A column of cells in a table */ export interface Column { /** * The column's index in the table (e.g., the second column has address 2). */ address(): number; /** * The width of the column. */ width(): any; } // CLass Extension /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The Keynote application. */ export interface Application {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The Keynote document. */ export interface Document { /** * Document ID. */ id(): string; /** * Are the slide numbers displayed? */ slideNumbersShowing(): boolean; /** * The theme assigned to the document. */ documentTheme(): any; /** * Make the slideshow play repeatedly. */ autoLoop(): boolean; /** * Automatically play the presentation when opening the file. */ autoPlay(): boolean; /** * Restart the slideshow if it's inactive for the specified time */ autoRestart(): boolean; /** * Restart the slideshow if it's inactive for the specified time */ maximumIdleDuration(): number; /** * The currently selected slide, or the slide that would display if the presentation was started. */ currentSlide(): any; /** * The height of the document (in points). Standard slide height = 768. Wide slide height = 1080. */ height(): number; /** * The width of the document (in points). Standard slide width = 1024. Wide slide width = 1920. */ width(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Deprecated Keynote application properties and verbs. */ export interface Application { /** * Are any slideshows playing */ playing(): boolean; /** * Is the slide selector visible? */ slideSwitcherVisible(): boolean; frozen(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface Document {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface Slide {} // Records /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ExportOptions { /** * compressed image quality, ranging from 0.0 (maximum compression, lowest quality) to 1.0 (lossless compression, highest quality). This option only pertains to JPEG format images. */ compressionFactor(): any; /** * format for resulting images. */ imageFormat(): any; /** * format for exported movie. */ movieFormat(): any; /** * choose whether to include notes, etc. */ exportStyle(): any; /** * print each stage of builds */ allStages(): boolean; /** * include skipped slides */ skippedSlides(): boolean; /** * add borders around slides */ borders(): boolean; /** * include slide numbers */ slideNumbers(): boolean; /** * include date */ date(): boolean; /** * export in raw KPF */ rawKPF(): boolean; /** * password */ password(): string; /** * password hint */ passwordHint(): string; /** * quality of images in PDF document */ PDFImageQuality(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Properties common to all transitions */ export interface TransitionSettings { /** * Should the transition begin automatically? A value of false indicates to transition on click. */ automaticTransition(): boolean; /** * The number of seconds to wait until beginning the transition. */ transitionDelay(): any; /** * The number of seconds allocated for the transition to occur. */ transitionDuration(): any; /** * The transition effect to apply between the current and following slides. */ transitionEffect(): any; } // Function options /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ExportOptionalParameter { /** * the destination file */ to: any; /** * The format to use. */ as: any; /** * Optional export settings. */ withProperties?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface DuplicateOptionalParameter { /** * The location for the new copy or copies. */ to?: any; /** * Properties to set in the new copy or copies right away. */ withProperties?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SetOptionalParameter { /** * The new value. */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MakeOptionalParameter { /** * The class of the new object. */ new: any; /** * The location at which to insert the object. */ at?: any; /** * The initial contents of the object. */ withData?: any; /** * The initial values for properties of the object. */ withProperties?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SortOptionalParameter { /** * The column to sort by. */ by: any; direction?: any; /** * Limit the sort to the specified rows. */ inRows?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface AddChartOptionalParameter { rowNames?: any; columnNames?: any; data?: any; type?: any; groupBy?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface StartOptionalParameter { /** * slide at which to start playing */ from?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MakeImageSlidesOptionalParameter { /** * a list of image files to add */ files: any; setTitles?: boolean; master?: any; } } export interface Keynote extends Keynote.Application { // Functions /** * Export a slideshow to another file * @param directParameter The slideshow to export * @param option * */ export(directParameter: Keynote.Document, option?: Keynote.ExportOptionalParameter): void; /** * Copy an object. * @param directParameter The object(s) to copy. * @param option * */ duplicate(directParameter: any, option?: Keynote.DuplicateOptionalParameter): void; /** * Sets the value of the specified object(s). * @param directParameter undefined * @param option * */ set(directParameter: any, option?: Keynote.SetOptionalParameter): void; /** * Delete an object. * @param directParameter undefined * */ delete(directParameter: any, ): void; /** * Create a new object. * @param option * @return The new object. */ make(option?: Keynote.MakeOptionalParameter): any; /** * Clear the contents of a specified range of cells, including formatting and style. * @param directParameter undefined * */ clear(directParameter: Keynote.Range, ): void; /** * Merge a specified range of cells. * @param directParameter undefined * */ merge(directParameter: Keynote.Range, ): void; /** * Sort the rows of the table. * @param directParameter undefined * @param option * */ sort(directParameter: Keynote.Table, option?: Keynote.SortOptionalParameter): void; /** * Unmerge all merged cells in a specified range. * @param directParameter undefined * */ unmerge(directParameter: Keynote.Range, ): void; /** * Add a chart to a slide * @param directParameter the slide to add the chart to * @param option * */ addChart(directParameter: Keynote.Slide, option?: Keynote.AddChartOptionalParameter): void; /** * Start playing the presentation. * @param directParameter The presentation to play * @param option * */ start(directParameter: Keynote.Document, option?: Keynote.StartOptionalParameter): void; /** * Make a series of slides from a list of files. * @param directParameter the document to add the slides to * @param option * */ makeImageSlides(directParameter: Keynote.Document, option?: Keynote.MakeImageSlidesOptionalParameter): void; /** * Stop the presentation. * @param directParameter undefined * */ stop(directParameter: Keynote.Document, ): void; /** * Advance one build or slide. * */ showNext(): void; /** * Go to the previous slide. * */ showPrevious(): void; /** * Show the slide switcher in play mode * @param directParameter undefined * */ showSlideSwitcher(directParameter: Keynote.Document, ): void; /** * Hide the slide switcher in play mode * @param directParameter undefined * */ hideSlideSwitcher(directParameter: Keynote.Document, ): void; /** * Move the slide switcher forward one slide * @param directParameter undefined * */ moveSlideSwitcherForward(directParameter: Keynote.Document, ): void; /** * Move the slide switcher backward one slide * @param directParameter undefined * */ moveSlideSwitcherBackward(directParameter: Keynote.Document, ): void; /** * Hide the slide switcher without changing slides * @param directParameter undefined * */ cancelSlideSwitcher(directParameter: Keynote.Document, ): void; /** * Hide the slide switcher, going to the slide it has selected * @param directParameter undefined * */ acceptSlideSwitcher(directParameter: Keynote.Document, ): void; /** * * */ startSlideshow(): void; /** * * @param directParameter the object for the command * */ startFrom(directParameter: Keynote.Slide, ): void; /** * * */ stopSlideshow(): void; /** * * @param directParameter the object for the command * */ show(directParameter: Keynote.Slide, ): void; }
the_stack
require('source-map-support').install(); var falafel = require("falafel"); /** * You can visualize ASTs using http://esprima.org/demo/parse.html which is handy */ /** * We keep applying optimizations until the length of the code stops decreasing */ export function optimize(javascript_str: string): string { //return simplify(javascript_str); var current_length = javascript_str.length + 1; while (javascript_str.length < current_length) { current_length = javascript_str.length; var current = javascript_str; //optimize stages javascript_str = simplify(parentIsObjectCheckRemoval(clauseRepetitionElimination(childParentAnnihilation(pruneBooleanLiterals(javascript_str))))); } return current; } /** * optimizes and removes outer paranthesis, only safe for use in end user expressions, like .read or .write, where the parenthesis * cannot be doing anything useful. * @param javascript_str */ export function optimizeAndTrim(javascript_str: string): string { var optimized = optimize(javascript_str); optimized = optimized.replace(/^\(+true\)+$/, "true"); optimized = optimized.replace(/^\(+false\)+$/,"false"); return optimized; } var simplifyMemory: {[js: string]: string} = {}; /** * rewrites the javascript to remove redundant parenthesis and white space */ export function simplify(javascript_str: string):string { if (simplifyMemory[javascript_str]) return simplifyMemory[javascript_str]; var simplify_fn = function(node){ node.precedence = 1000; //default precedence for all nodes other than operator nodes, e.g. terminals if(node.type == "BinaryExpression" || node.type == "BooleanExpression" || node.type == "LogicalExpression"){ node.precedence = js_precedence(node.operator); //overwrite with actual precedence var LHS:any, RHS:any; if(node.left.precedence >= node.precedence){ LHS = node.left.source(); //LHS is already strongly bound }else if(node.left.precedence < node.precedence){ LHS = "("+node.left.source()+")"; //LHS is not strongly bound, boost with brackets } if(node.right.precedence == node.precedence && isCommunicativeUniquePrecedence(node.operator)){ //special case for communicative operators RHS = node.right.source(); }else if(node.right.precedence > node.precedence){ //NOTE: > NOT >= RHS = node.right.source(); //RHS is already strongly bound }else if(node.right.precedence <= node.precedence){ RHS = "("+node.right.source()+")"; //RHS is not strongly bound, boost with brackets } node.update(LHS + node.operator + RHS); } }; var result = falafel(javascript_str.toString(), {}, simplify_fn).toString(); simplifyMemory[javascript_str] = result; return result; } var pruneBooleanLiteralsMemory: {[js: string]: string} = {}; /** * rewrites the javascript to remove pointless boolean literals like true && X */ export function pruneBooleanLiterals(javascript_str: string): string { if (pruneBooleanLiteralsMemory[javascript_str]) return pruneBooleanLiteralsMemory[javascript_str]; var simplify_fn = function(node){ if (node.type == "UnaryExpression") { //!true => false if (node.operator == '!' && node.argument.type == 'Literal') { node.update(!node.argument.value) } } else if(node.type == "LogicalExpression") { //helper functions for querying literal arguments node.left.is = function(val) {return node.left.type == 'Literal' && node.left.value == val;}; node.right.is = function(val) {return node.right.type == 'Literal' && node.right.value == val;}; if (node.operator == '&&' && node.left.is(true) && node.right.is(true)) { node.update("true") } else if (node.operator == '&&' && node.left.is(false)) { node.update("false") } else if (node.operator == '&&' && node.right.is(false)) { node.update("false") } else if (node.operator == '&&' && node.left.is(true)) { node.update("("+node.right.source() + ")") } else if (node.operator == '&&' && node.right.is(true)) { node.update("("+node.left.source() + ")") } else if (node.operator == '||' && node.left.is(false) && node.right.is(false)) { node.update("false") } else if (node.operator == '||' && node.left.is(true)) { node.update("true") } else if (node.operator == '||' && node.right.is(true)) { node.update("true") } else if (node.operator == '||' && node.left.is(false)) { node.update("("+node.right.source() + ")") } else if (node.operator == '||' && node.right.is(false)) { node.update("("+node.left.source() + ")") } } }; var result = falafel(javascript_str.toString(), {}, simplify_fn).toString(); pruneBooleanLiteralsMemory[javascript_str] = result; return result; } var clauseRepetitionEliminationMemory: {[js: string]: string} = {}; /** * remove repeated clauses in && and || groups * note the order of lazy evaluation means the first occurrences ordering must be preserved! * a && b && c && c && b => a && b && c */ export function clauseRepetitionElimination(javascript_str: string): string { if (clauseRepetitionEliminationMemory[javascript_str]) return clauseRepetitionEliminationMemory[javascript_str]; var simplify_fn = function(node){ if(node.type == "LogicalExpression") { if (node.parent.type == "LogicalExpression" && node.parent.operator == node.operator) { //so the parent is part of the same group so we don't want to do the expensive optimization yet } else { //we are the top level logical expression, lets hunt for repetitions //the left pointer should be another logical expression //the right should be a single expression var operator = node.operator; var clauses = []; var logical = node; while (logical.type == "LogicalExpression" && logical.operator == operator) { clauses.push(logical.right.source()); logical = logical.left; } clauses.push(logical.source()); //logical was the left of the previous seen logical expression var clauses = clauses.reverse(); //make the LHS first for (var primaryClause = 0; primaryClause < clauses.length; primaryClause++) { for (var repeatClause = primaryClause + 1; repeatClause < clauses.length; repeatClause++) { if (clauses[primaryClause] == clauses[repeatClause]) { //secondaryClause repeats the primary clause, so delete it and adjust the indexing clauses.splice(repeatClause,1); repeatClause--; //adjustment for an element being removed during a loop } } } //now clauses should have no repeatitions and should be in the correct order LEFT to RIGHT node.update(simplify("((" + clauses.join(")" + operator + "(") + "))")) } } }; var result = falafel(javascript_str.toString(), {}, simplify_fn).toString(); clauseRepetitionEliminationMemory[javascript_str] = result; return result; } var childParentAnnihilationMemory: {[js: string]: string} = {}; /** * blah.child(XXX).parent().blah() => blah.blah() (if we don't include any other implementations of child) */ export function childParentAnnihilation(javascript_str: string): string { if (childParentAnnihilationMemory[javascript_str]) return childParentAnnihilationMemory[javascript_str]; /* data.child('x').parent().val() AST expansion looks like:- { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "CallExpression", "callee": { "type": "MemberExpression", <--- start hunting here "computed": false, "object": { "type": "CallExpression", <---- () of parent, this will be removed "callee": { "type": "MemberExpression", "computed": false, "object": { "type": "CallExpression", "callee": { "type": "MemberExpression", "computed": false, "object": { <--- kept "type": "Identifier", "name": "data" }, "property": { "type": "Identifier", "name": "child" } }, "arguments": [ <---- irrelavant { "type": "Literal", "value": "x", "raw": "'x'" } ] }, "property": { "type": "Identifier", "name": "parent" } }, "arguments": [] }, "property": { "type": "Identifier", "name": "val" } }, "arguments": [] } } ] } */ var simplify_fn = function(node){ //detect the above situation and rewrite if (node.type == 'MemberExpression' && node.object.type == 'CallExpression' && node.object.arguments.length == 0 && node.object.callee.type == 'MemberExpression' && node.object.callee.property.type == 'Identifier' && node.object.callee.property.name == 'parent' && node.object.callee.object.type == 'CallExpression' && node.object.callee.object.callee.type == 'MemberExpression' && node.object.callee.object.callee.property.type == 'Identifier' && node.object.callee.object.callee.property.name == 'child') { //rewrite node node.object.update(node.object.callee.object.callee.object.source()) } }; var result = falafel(javascript_str.toString(), {}, simplify_fn).toString(); childParentAnnihilationMemory[javascript_str] = result; return result; } var parentIsObjectCheckRemovalMemory: {[js: string]: string} = {}; var parent_pattern = /^!newData(\.parent\(\))+\.exists\(\)\|\|newData(\.parent\(\))+\.hasChildren\(\)$/; export function parentIsObjectCheckRemoval(javascript_str: string) { if (parentIsObjectCheckRemovalMemory[javascript_str]) return parentIsObjectCheckRemovalMemory[javascript_str]; //if on the top level && we are checking to see if our parent is an object or null, we are doing a redundant check because //we can only write either null, a primitive or an object at newData location //therefore our parent will flip only to null, or an object, thus we don't need to check for this pattern //((!newData.parent().parent().parent().parent().parent().exists()||newData.parent().parent().parent().parent().parent().hasChildren()) var simplify_fn = function(node){ //detect the above situation and rewrite if (node.type == 'LogicalExpression' && node.operator == '||') { var match = parent_pattern.exec(node.source()); if (match != null && match[1] == match[2]) { //check the number of ".parent()" match between exists and hasChildren node.update("true") } } }; var result = falafel(javascript_str.toString(), {}, simplify_fn).toString(); parentIsObjectCheckRemovalMemory[javascript_str] = result; return result; } var singleQuoteRegex = new RegExp("'", "g"); /** * backslash is inserted before every single quote, intended to be run within a string context */ export function escapeSingleQuotes(string_literal: string): string { string_literal = string_literal.replace(singleQuoteRegex, "\\'"); return string_literal } var escapeRegex = new RegExp("\\\\", "g"); //detects a single backslash /** * backslash is inserted before every backslash, intended to be run within a string context, when placing an existing * escaped string within another */ export function escapeEscapes(string_literal: string): string { string_literal = string_literal.replace(escapeRegex, "\\\\"); return string_literal } /** * changes double quotes to single quotes * might have been easier just to escape the existing double quotes */ export function sanitizeQuotes(javascript_str: string) { var simplify_fn = function(node){ if (node.type == "Literal") { //double quoted string needs to be changed to single quotes if (node.raw.indexOf('"') == 0) node.update("'" + escapeSingleQuotes(node.value) + "'") } }; return falafel(javascript_str.toString(), {}, simplify_fn).toString(); } var isCommunicativeUniquePrecedence = function(token:string):boolean{ switch (token) { case '||': case '&&': case '&': case '|': return true; default: return false; } }; /** * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence * Precedence in retrieved from esprima source function "binaryPrecedence" */ var js_precedence = function(token:string):number { switch (token) { case '||': return 1; case '&&': return 2; case '|': return 3; case '^': return 4; case '&': return 5; case '==': case '!=': case '===': case '!==': return 6; case '<': case '>': case '<=': case '>=': case 'instanceof': return 7; case '<<': case '>>': case '>>>': return 8; case '+': case '-': return 9; case '*': case '/': case '%': return 11; default: return 0; } };
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * An API Configuration is an association of an API Controller Config and a Gateway Config * * To get more information about ApiConfig, see: * * * [API documentation](https://cloud.google.com/api-gateway/docs/reference/rest/v1beta/projects.locations.apis.configs) * * How-to Guides * * [Official Documentation](https://cloud.google.com/api-gateway/docs/creating-api-config) * * ## Example Usage * ### Apigateway Api Config Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * import * from "fs"; * * const apiCfgApi = new gcp.apigateway.Api("apiCfgApi", {apiId: "api-cfg"}, { * provider: google_beta, * }); * const apiCfgApiConfig = new gcp.apigateway.ApiConfig("apiCfgApiConfig", { * api: apiCfgApi.apiId, * apiConfigId: "cfg", * openapiDocuments: [{ * document: { * path: "spec.yaml", * contents: Buffer.from(fs.readFileSync("test-fixtures/apigateway/openapi.yaml"), 'binary').toString('base64'), * }, * }], * }, { * provider: google_beta, * }); * ``` * * ## Import * * ApiConfig can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:apigateway/apiConfig:ApiConfig default projects/{{project}}/locations/global/apis/{{api}}/configs/{{api_config_id}} * ``` * * ```sh * $ pulumi import gcp:apigateway/apiConfig:ApiConfig default {{project}}/{{api}}/{{api_config_id}} * ``` * * ```sh * $ pulumi import gcp:apigateway/apiConfig:ApiConfig default {{api}}/{{api_config_id}} * ``` */ export class ApiConfig extends pulumi.CustomResource { /** * Get an existing ApiConfig 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?: ApiConfigState, opts?: pulumi.CustomResourceOptions): ApiConfig { return new ApiConfig(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:apigateway/apiConfig:ApiConfig'; /** * Returns true if the given object is an instance of ApiConfig. 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 ApiConfig { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ApiConfig.__pulumiType; } /** * The API to attach the config to. */ public readonly api!: pulumi.Output<string>; /** * Identifier to assign to the API Config. Must be unique within scope of the parent resource(api). */ public readonly apiConfigId!: pulumi.Output<string>; /** * Creates a unique name beginning with the * specified prefix. If this and apiConfigId are unspecified, a random value is chosen for the name. */ public readonly apiConfigIdPrefix!: pulumi.Output<string>; /** * A user-visible name for the API. */ public readonly displayName!: pulumi.Output<string>; /** * Immutable. Gateway specific configuration. * If not specified, backend authentication will be set to use OIDC authentication using the default compute service account * Structure is documented below. */ public readonly gatewayConfig!: pulumi.Output<outputs.apigateway.ApiConfigGatewayConfig | undefined>; /** * Resource labels to represent user-provided metadata. */ public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>; /** * The resource name of the API Config. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * An OpenAPI Specification Document describing an API. * Structure is documented below. */ public readonly openapiDocuments!: pulumi.Output<outputs.apigateway.ApiConfigOpenapiDocument[]>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * The ID of the associated Service Config (https://cloud.google.com/service-infrastructure/docs/glossary#config). */ public /*out*/ readonly serviceConfigId!: pulumi.Output<string>; /** * Create a ApiConfig 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: ApiConfigArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ApiConfigArgs | ApiConfigState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ApiConfigState | undefined; inputs["api"] = state ? state.api : undefined; inputs["apiConfigId"] = state ? state.apiConfigId : undefined; inputs["apiConfigIdPrefix"] = state ? state.apiConfigIdPrefix : undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["gatewayConfig"] = state ? state.gatewayConfig : undefined; inputs["labels"] = state ? state.labels : undefined; inputs["name"] = state ? state.name : undefined; inputs["openapiDocuments"] = state ? state.openapiDocuments : undefined; inputs["project"] = state ? state.project : undefined; inputs["serviceConfigId"] = state ? state.serviceConfigId : undefined; } else { const args = argsOrState as ApiConfigArgs | undefined; if ((!args || args.api === undefined) && !opts.urn) { throw new Error("Missing required property 'api'"); } if ((!args || args.openapiDocuments === undefined) && !opts.urn) { throw new Error("Missing required property 'openapiDocuments'"); } inputs["api"] = args ? args.api : undefined; inputs["apiConfigId"] = args ? args.apiConfigId : undefined; inputs["apiConfigIdPrefix"] = args ? args.apiConfigIdPrefix : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["gatewayConfig"] = args ? args.gatewayConfig : undefined; inputs["labels"] = args ? args.labels : undefined; inputs["openapiDocuments"] = args ? args.openapiDocuments : undefined; inputs["project"] = args ? args.project : undefined; inputs["name"] = undefined /*out*/; inputs["serviceConfigId"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(ApiConfig.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ApiConfig resources. */ export interface ApiConfigState { /** * The API to attach the config to. */ api?: pulumi.Input<string>; /** * Identifier to assign to the API Config. Must be unique within scope of the parent resource(api). */ apiConfigId?: pulumi.Input<string>; /** * Creates a unique name beginning with the * specified prefix. If this and apiConfigId are unspecified, a random value is chosen for the name. */ apiConfigIdPrefix?: pulumi.Input<string>; /** * A user-visible name for the API. */ displayName?: pulumi.Input<string>; /** * Immutable. Gateway specific configuration. * If not specified, backend authentication will be set to use OIDC authentication using the default compute service account * Structure is documented below. */ gatewayConfig?: pulumi.Input<inputs.apigateway.ApiConfigGatewayConfig>; /** * Resource labels to represent user-provided metadata. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The resource name of the API Config. */ name?: pulumi.Input<string>; /** * An OpenAPI Specification Document describing an API. * Structure is documented below. */ openapiDocuments?: pulumi.Input<pulumi.Input<inputs.apigateway.ApiConfigOpenapiDocument>[]>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The ID of the associated Service Config (https://cloud.google.com/service-infrastructure/docs/glossary#config). */ serviceConfigId?: pulumi.Input<string>; } /** * The set of arguments for constructing a ApiConfig resource. */ export interface ApiConfigArgs { /** * The API to attach the config to. */ api: pulumi.Input<string>; /** * Identifier to assign to the API Config. Must be unique within scope of the parent resource(api). */ apiConfigId?: pulumi.Input<string>; /** * Creates a unique name beginning with the * specified prefix. If this and apiConfigId are unspecified, a random value is chosen for the name. */ apiConfigIdPrefix?: pulumi.Input<string>; /** * A user-visible name for the API. */ displayName?: pulumi.Input<string>; /** * Immutable. Gateway specific configuration. * If not specified, backend authentication will be set to use OIDC authentication using the default compute service account * Structure is documented below. */ gatewayConfig?: pulumi.Input<inputs.apigateway.ApiConfigGatewayConfig>; /** * Resource labels to represent user-provided metadata. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * An OpenAPI Specification Document describing an API. * Structure is documented below. */ openapiDocuments: pulumi.Input<pulumi.Input<inputs.apigateway.ApiConfigOpenapiDocument>[]>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; }
the_stack
import { createLocalVue, ThisTypedMountOptions, Wrapper } from '@vue/test-utils'; // tslint:disable-next-line: no-implicit-dependencies import flushPromises from 'flush-promises'; import Vue, { CreateElement } from 'vue'; import { mountVueDatatablePager as _mountVueDatatablePager } from '../../../__tests__/helpers/mount-mixin-components'; jest.mock( '../../classes/table-type' ); jest.mock( '../../classes/settings' ); // @ts-ignore import { setting, TableType } from '../../classes/table-type'; import { EPagerType, namespaceEvent } from '../../utils'; import { ITableTypeConsumer } from '../mixins/table-type-consumer-factory'; import { VueDatatablePager } from './vue-datatable-pager'; const localVue = createLocalVue(); const DatatableButton = { render( createElement: CreateElement ) { return createElement( 'li', this.$slots.default || this.value ); }, props: { value: { type: Number }}, }; const makeDefaultTableMock = ( tableProps: Partial<{ totalPages: number; totalRows: number }> = {} ) => Object.assign( { $emit: jest.fn(), pagers: [], $on: jest.fn(), totalPages: 0, totalRows: Infinity }, tableProps ); const mountVueDatatablePager = ( mountOptions: ThisTypedMountOptions<VueDatatablePager<VueDatatablePager<any>> & ITableTypeConsumer & Vue>, tableProps: Partial<{ totalPages: number; totalRows: number }> = {}, ) => { const defaultTable = makeDefaultTableMock( tableProps ); localVue.prototype.$datatables = { default: defaultTable }; mountOptions = Object.assign( mountOptions, { stubs: { PagerButton: DatatableButton }} ); const wrapper = _mountVueDatatablePager( true, new TableType( 'foo' ), mountOptions ); // Re-set data that were re-initialized in the ctor return { wrapper, defaultTable }; }; const getTextContent = ( wrapper: Wrapper<any> ) => wrapper.element.outerHTML .replace( /></g, '> <' ) .replace( /<[^>]+?>/g, '' ) .replace( /[\s\n]+/g, ' ' ) .trim(); beforeEach( () => { jest.clearAllMocks(); jest.restoreAllMocks(); localVue.prototype.$datatables = {}; } ); describe( 'Pager types', () => { describe( 'Abbreviated', () => { it( 'With default number of sides items, on first page', async () => { const { wrapper } = mountVueDatatablePager( { localVue, propsData: { type: EPagerType.Abbreviated }, data: () => ( { totalPages: 10, page: 1 } ) } ); await flushPromises(); expect( wrapper.element.nodeName ).toBe( 'NAV' ); expect( getTextContent( wrapper ) ).toBe( '1 2 3 ... 10' ); expect( wrapper.element.children.length ).toBe( 1 ); expect( wrapper.element.children[0].nodeName ).toBe( 'UL' ); expect( wrapper.element.children[0].children.length ).toBe( 5 ); } ); it( 'With default number of sides items, on central page', async () => { const { wrapper } = mountVueDatatablePager( { localVue, propsData: { type: EPagerType.Abbreviated }, data: () => ( { totalPages: 10, page: 5 } ) } ); await flushPromises(); expect( wrapper.element.nodeName ).toBe( 'NAV' ); expect( getTextContent( wrapper ) ).toBe( '1 ... 3 4 5 6 7 ... 10' ); expect( wrapper.element.children.length ).toBe( 1 ); expect( wrapper.element.children[0].nodeName ).toBe( 'UL' ); expect( wrapper.element.children[0].children.length ).toBe( 9 ); } ); it( 'With default number of sides items, on last page', async () => { const { wrapper } = mountVueDatatablePager( { localVue, propsData: { type: EPagerType.Abbreviated }, data: () => ( { totalPages: 10, page: 10 } ) } ); await flushPromises(); expect( wrapper.element.nodeName ).toBe( 'NAV' ); expect( getTextContent( wrapper ) ).toBe( '1 ... 8 9 10' ); expect( wrapper.element.children.length ).toBe( 1 ); expect( wrapper.element.children[0].nodeName ).toBe( 'UL' ); expect( wrapper.element.children[0].children.length ).toBe( 5 ); } ); it( 'With 1 side items, on central page', async () => { const { wrapper } = mountVueDatatablePager( { localVue, propsData: { type: EPagerType.Abbreviated, sidesCount: 1 }, data: () => ( { totalPages: 10, page: 5 } ) } ); await flushPromises(); expect( wrapper.element.nodeName ).toBe( 'NAV' ); expect( getTextContent( wrapper ) ).toBe( '1 ... 4 5 6 ... 10' ); expect( wrapper.element.children.length ).toBe( 1 ); expect( wrapper.element.children[0].nodeName ).toBe( 'UL' ); expect( wrapper.element.children[0].children.length ).toBe( 7 ); } ); } ); describe( 'Short', () => { it( 'Central page', async () => { setting.mockImplementation( p => ( { 'pager.icons.previous': 'PREV', 'pager.icons.next': 'NEXT' } )[p] ); const { wrapper } = mountVueDatatablePager( { localVue, propsData: { type: EPagerType.Short }, data: () => ( { totalPages: 5, page: 3 } ) } ); await flushPromises(); expect( wrapper.element.nodeName ).toBe( 'NAV' ); expect( getTextContent( wrapper ) ).toBe( 'PREV 3 NEXT' ); expect( setting ).toHaveBeenCalledWith( 'pager.icons.previous' ); expect( setting ).toHaveBeenCalledWith( 'pager.icons.next' ); expect( wrapper.element.children.length ).toBe( 1 ); expect( wrapper.element.children[0].nodeName ).toBe( 'UL' ); expect( wrapper.element.children[0].children.length ).toBe( 3 ); } ); it( 'First page', async () => { setting.mockImplementation( p => ( { 'pager.icons.previous': 'PREV', 'pager.icons.next': 'NEXT' } )[p] ); const { wrapper } = mountVueDatatablePager( { localVue, propsData: { type: EPagerType.Short }, data: () => ( { totalPages: 5, page: 1 } ) } ); await flushPromises(); expect( wrapper.element.nodeName ).toBe( 'NAV' ); expect( getTextContent( wrapper ) ).toBe( '1 NEXT' ); expect( setting ).not.toHaveBeenCalledWith( 'pager.icons.previous' ); expect( setting ).toHaveBeenCalledWith( 'pager.icons.next' ); expect( wrapper.element.children.length ).toBe( 1 ); expect( wrapper.element.children[0].nodeName ).toBe( 'UL' ); expect( wrapper.element.children[0].children.length ).toBe( 2 ); } ); it( 'Last page', async () => { setting.mockImplementation( p => ( { 'pager.icons.previous': 'PREV', 'pager.icons.next': 'NEXT' } )[p] ); const { wrapper } = mountVueDatatablePager( { localVue, propsData: { type: EPagerType.Short }, data: () => ( { totalPages: 5, page: 5 } ) } ); await flushPromises(); expect( wrapper.element.nodeName ).toBe( 'NAV' ); expect( getTextContent( wrapper ) ).toBe( 'PREV 5' ); expect( setting ).toHaveBeenCalledWith( 'pager.icons.previous' ); expect( setting ).not.toHaveBeenCalledWith( 'pager.icons.next' ); expect( wrapper.element.children.length ).toBe( 1 ); expect( wrapper.element.children[0].nodeName ).toBe( 'UL' ); expect( wrapper.element.children[0].children.length ).toBe( 2 ); } ); } ); describe( 'Long', () => { it( 'Default', async () => { const { wrapper } = mountVueDatatablePager( { localVue, propsData: { type: EPagerType.Long }, data: () => ( { totalPages: 2 } ) } ); await flushPromises(); expect( wrapper.element.nodeName ).toBe( 'NAV' ); expect( getTextContent( wrapper ) ).toBe( '1 2' ); expect( wrapper.element.children.length ).toBe( 1 ); expect( wrapper.element.children[0].nodeName ).toBe( 'UL' ); expect( wrapper.element.children[0].children.length ).toBe( 2 ); } ); } ); } ); describe( 'Table-Pager linking', () => { describe( '`created`', () => { it( 'Pager should try to link the table on creation', () => { const mockLinkWithTable = jest.spyOn( ( VueDatatablePager as any ).extendOptions.methods, 'linkWithTable' ); const { wrapper } = mountVueDatatablePager( { localVue, propsData: { table: 'foo' }} ); expect( mockLinkWithTable ).toHaveBeenCalledTimes( 1 ); expect( mockLinkWithTable ).toHaveBeenCalledWith( 'foo' ); } ); it( 'Pager should not bind event initialization on successfull immediate linking', () => { jest.spyOn( ( VueDatatablePager as any ).extendOptions.methods, 'linkWithTable' ).mockReturnValue( true ); const $onMock = jest.spyOn( localVue.prototype, '$on' ); const { wrapper } = mountVueDatatablePager( { localVue, propsData: { table: 'foo' }} ); expect( $onMock ).not.toHaveBeenCalled(); } ); it( 'Pager should bind event initialization on failed immediate linking', () => { const $onMock = jest.spyOn( localVue.prototype, '$on' ); const $offMock = jest.spyOn( localVue.prototype, '$off' ); const mockLinkWithTable = jest.spyOn( ( VueDatatablePager as any ).extendOptions.methods, 'linkWithTable' ).mockReturnValue( false ); const { wrapper } = mountVueDatatablePager( { localVue, propsData: { table: 'foo' }} ); expect( $onMock ).toHaveBeenCalledTimes( 1 ); expect( $onMock.mock.calls[0][0] ).toBe( namespaceEvent( 'ready' ) ); const callback = $onMock.mock.calls[0][1] as ( tableName: string ) => void; expect( callback ).toBeInstanceOf( Function ); // Deregister itself on resolution expect( $offMock ).not.toHaveBeenCalled(); mockLinkWithTable.mockClear(); callback( 'bar' ); expect( $offMock ).not.toHaveBeenCalled(); expect( mockLinkWithTable ).not.toHaveBeenCalled(); mockLinkWithTable.mockReturnValue( true ); callback( 'foo' ); expect( $offMock ).toHaveBeenCalledTimes( 1 ); expect( $offMock.mock.calls[0][0] ).toBe( namespaceEvent( 'ready' ) ); expect( $offMock.mock.calls[0][1] ).toBe( callback ); expect( mockLinkWithTable ).toHaveBeenCalledTimes( 1 ); expect( mockLinkWithTable ).toHaveBeenCalledWith( 'foo' ); } ); } ); describe( '`linkWithTable`', () => { it( 'Should fail if the table does not exists', () => { const that = { $datatables: {}}; const linkWithTable = ( VueDatatablePager as any ).extendOptions.methods.linkWithTable as ( tableName: string ) => boolean; expect( linkWithTable.call( that, 'foo' ) ).toBe( false ); } ); it( 'Should succeed if the table exists', () => { const tableMock = makeDefaultTableMock(); const that = { $datatables: { foo: tableMock }, onPageCountChanged: jest.fn(), onPageChanged: jest.fn(), $on: jest.fn(), onSetPage: jest.fn() }; const linkWithTable = ( VueDatatablePager as any ).extendOptions.methods.linkWithTable as ( tableName: string ) => boolean; expect( linkWithTable.call( that, 'foo' ) ).toBe( true ); // Assert that the table was correctly notified of changes expect( tableMock.$emit ).toHaveBeenCalledTimes( 1 ); expect( tableMock.$emit ).toHaveBeenCalledWith( namespaceEvent( 'pager-bound' ), that ); // Assert that table events were correctly bound expect( tableMock.$on ).toHaveBeenCalledTimes( 2 ); expect( tableMock.$on ).toHaveBeenCalledWith( namespaceEvent( 'page-count-changed' ), that.onPageCountChanged ); expect( tableMock.$on ).toHaveBeenCalledWith( namespaceEvent( 'page-changed' ), that.onPageChanged ); expect( that.$on ).toHaveBeenCalledWith( namespaceEvent( 'set-page' ), that.onSetPage ); } ); } ); } ); it( 'returns the correct pagination class', () => { setting.mockReturnValue( 'PAGINATION' ); const { wrapper } = mountVueDatatablePager( { localVue } ); expect( wrapper.vm.paginationClass ).toBe( 'PAGINATION' ); expect( setting ).toHaveBeenCalledTimes( 1 ); expect( setting ).toHaveBeenCalledWith( 'pager.classes.pager' ); } );
the_stack
import * as React from 'react'; import hoistNonReactStatics from 'hoist-non-react-statics'; import IdentificationContext from '../contexts/IdentificationContext'; import Consumer from '../components/Consumer'; import {LIFECYCLE} from '../components/Provider'; import md5 from './md5'; import {warn} from './debug'; import getKeyByFiberNode from './getKeyByFiberNode'; import withIdentificationContextConsumer, {IIdentificationContextConsumerComponentProps} from './withIdentificationContextConsumer'; import withKeepAliveContextConsumer, {IKeepAliveContextConsumerComponentProps} from './withKeepAliveContextConsumer'; import shallowEqual from './shallowEqual'; import getKeepAlive from './getKeepAlive'; export enum COMMAND { UNACTIVATE = 'unactivate', UNMOUNT = 'unmount', ACTIVATE = 'activate', CURRENT_UNMOUNT = 'current_unmount', CURRENT_UNACTIVATE = 'current_unactivate', } interface IListenUpperKeepAliveContainerProps extends IIdentificationContextConsumerComponentProps, IKeepAliveContextConsumerComponentProps { disabled?: boolean; name?: string; } interface IListenUpperKeepAliveContainerState { activated: boolean; } interface ITriggerLifecycleContainerProps extends IKeepAliveContextConsumerComponentProps { propKey: string; extra?: any; keepAlive: boolean; getCombinedKeepAlive: () => boolean; } /** * Decorating the <KeepAlive> component, the main function is to listen to events emitted by the upper <KeepAlive> component, triggering events of the current <KeepAlive> component. * * @export * @template P * @param {React.ComponentType<any>} Component * @returns {React.ComponentType<P>} */ export default function keepAliveDecorator<P = any>(Component: React.ComponentType<any>): React.ComponentType<P> { class TriggerLifecycleContainer extends React.PureComponent<ITriggerLifecycleContainerProps> { private identification: string; private activated = false; private ifStillActivate = false; // Let the lifecycle of the cached component be called normally. private needActivate = true; private lifecycle = LIFECYCLE.MOUNTED; constructor(props: ITriggerLifecycleContainerProps, ...args: any) { super(props, ...args); const { _keepAliveContextProps: { cache, }, } = props; if (!cache) { warn('[React Keep Alive] You should not use <KeepAlive> outside a <Provider>.'); } } public componentDidMount() { if (!this.ifStillActivate) { this.activate(); } const { keepAlive, _keepAliveContextProps: { eventEmitter, }, } = this.props; if (keepAlive) { this.needActivate = true; eventEmitter.emit([this.identification, COMMAND.ACTIVATE]); } } public componentDidCatch() { if (!this.activated) { this.activate(); } } public componentWillUnmount() { const { getCombinedKeepAlive, _keepAliveContextProps: { eventEmitter, isExisted, }, } = this.props; const keepAlive = getCombinedKeepAlive(); if (!keepAlive || !isExisted()) { eventEmitter.emit([this.identification, COMMAND.CURRENT_UNMOUNT]); eventEmitter.emit([this.identification, COMMAND.UNMOUNT]); } // When the Provider components are unmounted, the cache is not needed, // so you don't have to execute the componentWillUnactivate lifecycle. if (keepAlive && isExisted()) { eventEmitter.emit([this.identification, COMMAND.CURRENT_UNACTIVATE]); eventEmitter.emit([this.identification, COMMAND.UNACTIVATE]); } } private activate = () => { this.activated = true; } private reactivate = () => { this.ifStillActivate = false; this.forceUpdate(); } private isNeedActivate = () => { return this.needActivate; } private notNeedActivate = () => { this.needActivate = false; } private getLifecycle = () => { return this.lifecycle; } private setLifecycle = (lifecycle: LIFECYCLE) => { this.lifecycle = lifecycle; } public render() { const { propKey, keepAlive, extra, getCombinedKeepAlive, _keepAliveContextProps: { isExisted, storeElement, cache, eventEmitter, setCache, unactivate, providerIdentification, }, ...wrapperProps } = this.props; if (!this.identification) { // We need to generate a corresponding unique identifier based on the information of the component. this.identification = md5( `${providerIdentification}${propKey}`, ); // The last activated component must be unactivated before it can be activated again. const currentCache = cache[this.identification]; if (currentCache) { this.ifStillActivate = currentCache.activated as boolean; currentCache.ifStillActivate = this.ifStillActivate; currentCache.reactivate = this.reactivate; } } const { isNeedActivate, notNeedActivate, activated, getLifecycle, setLifecycle, identification, ifStillActivate, } = this; return !ifStillActivate ? ( <Consumer identification={identification} keepAlive={keepAlive} cache={cache} setCache={setCache} unactivate={unactivate} > <IdentificationContext.Provider value={{ identification, eventEmitter, keepAlive, activated, getLifecycle, isExisted, extra, }} > <Component {...wrapperProps} _container={{ isNeedActivate, notNeedActivate, setLifecycle, eventEmitter, identification, storeElement, keepAlive, cache, }} /> </IdentificationContext.Provider> </Consumer> ) : null; } } class ListenUpperKeepAliveContainer extends React.Component<IListenUpperKeepAliveContainerProps, IListenUpperKeepAliveContainerState> { private combinedKeepAlive: boolean; public state = { activated: true, }; private activate: () => void; private unactivate: () => void; private unmount: () => void; public shouldComponentUpdate(nextProps: IListenUpperKeepAliveContainerProps, nextState: IListenUpperKeepAliveContainerState) { if (this.state.activated !== nextState.activated) { return true; } const { _keepAliveContextProps, _identificationContextProps, ...rest } = this.props; const { _keepAliveContextProps: nextKeepAliveContextProps, _identificationContextProps: nextIdentificationContextProps, ...nextRest } = nextProps; if (!shallowEqual(rest, nextRest)) { return true; } if ( !shallowEqual(_keepAliveContextProps, nextKeepAliveContextProps) || !shallowEqual(_identificationContextProps, nextIdentificationContextProps) ) { return true; } return false; } public componentDidMount() { this.listenUpperKeepAlive(); } public componentWillUnmount() { this.unlistenUpperKeepAlive(); } private listenUpperKeepAlive() { const {identification, eventEmitter} = this.props._identificationContextProps; if (!identification) { return; } eventEmitter.on( [identification, COMMAND.ACTIVATE], this.activate = () => this.setState({activated: true}), true, ); eventEmitter.on( [identification, COMMAND.UNACTIVATE], this.unactivate = () => this.setState({activated: false}), true, ); eventEmitter.on( [identification, COMMAND.UNMOUNT], this.unmount = () => this.setState({activated: false}), true, ); } private unlistenUpperKeepAlive() { const {identification, eventEmitter} = this.props._identificationContextProps; if (!identification) { return; } eventEmitter.off([identification, COMMAND.ACTIVATE], this.activate); eventEmitter.off([identification, COMMAND.UNACTIVATE], this.unactivate); eventEmitter.off([identification, COMMAND.UNMOUNT], this.unmount); } private getCombinedKeepAlive = () => { return this.combinedKeepAlive; } public render() { const { _identificationContextProps: { identification, keepAlive: upperKeepAlive, getLifecycle, }, disabled, name, ...wrapperProps } = this.props; const {activated} = this.state; const { _keepAliveContextProps: { include, exclude, }, } = wrapperProps; // When the parent KeepAlive component is mounted or unmounted, // use the keepAlive prop of the parent KeepAlive component. const propKey = name || getKeyByFiberNode((this as any)._reactInternalFiber); if (!propKey) { warn('[React Keep Alive] <KeepAlive> components must have key or name.'); return null; } const newKeepAlive = getKeepAlive(propKey, include, exclude, disabled); this.combinedKeepAlive = getLifecycle === undefined || getLifecycle() === LIFECYCLE.UPDATING ? newKeepAlive : identification ? upperKeepAlive && newKeepAlive : newKeepAlive; return activated ? ( <TriggerLifecycleContainer {...wrapperProps} key={propKey} propKey={propKey} keepAlive={this.combinedKeepAlive} getCombinedKeepAlive={this.getCombinedKeepAlive} /> ) : null; } } const KeepAlive = withKeepAliveContextConsumer( withIdentificationContextConsumer(ListenUpperKeepAliveContainer) ) as any; return hoistNonReactStatics(KeepAlive, Component); }
the_stack
const models = require('../../../../../db/mysqldb/index') import moment from 'moment' const { resClientJson } = require('../../../utils/resData') const Op = require('sequelize').Op const cheerio = require('cheerio') const clientWhere = require('../../../utils/clientWhere') const xss = require('xss') const config = require('../../../../../config') const lowdb = require('../../../../../db/lowdb/index') const { TimeNow, TimeDistance } = require('../../../utils/time') import { statusList, userMessageAction, modelAction, payType, payTypeText, isFree, isFreeText, trialRead, productTypeInfo, modelName, userLevel } from '../../../utils/constant' import userVirtual from '../../../common/userVirtual' import attention from '../../../common/attention' function computedReadTime(s: any) { // 计算分钟 // 算法:将秒数除以60,然后下舍入,既得到分钟数 var slookTextNum = 5 // 一秒能看多少文字 var h: any h = Math.floor(s / (60 * slookTextNum)) // 计算秒 // 算法:取得秒%60的余数,既得到秒数 s = s % 60 // 将变量转换为字符串 h += '' s += '' // 如果只有一位数,前面增加一个0 h = h.length == 1 ? '0' + h : h s = s.length == 1 ? '0' + s : s return h + '分' + s + '秒' } function getNoMarkupStr(markupStr: string) { /* markupStr 源码</> */ // console.log(markupStr); let noMarkupStr = markupStr /* 得到可视文本(不含图片),将&nbsp;&lt;&gt;转为空字符串和<和>显示,同时去掉了换行,文本单行显示 */ // console.log("1--S" + noMarkupStr + "E--"); noMarkupStr = noMarkupStr.replace(/(\r\n|\n|\r)/gm, '') /* 去掉可视文本中的换行,(没有用,上一步已经自动处理) */ // console.log("2--S" + noMarkupStr + "E--"); noMarkupStr = noMarkupStr.replace(/^\s+/g, '') /* 替换开始位置一个或多个空格为一个空字符串 */ // console.log("3--S" + noMarkupStr + "E--"); noMarkupStr = noMarkupStr.replace(/\s+$/g, '') /* 替换结束位置一个或多个空格为一个空字符串 */ // console.log("4--S" + noMarkupStr + "E--"); noMarkupStr = noMarkupStr.replace(/\s+/g, ' ') /* 替换中间位置一个或多个空格为一个空格 */ // console.log("5--S" + noMarkupStr + "E--"); return noMarkupStr } function isDigit(value: any) { var patrn = /^[0-9]*$/ if (patrn.exec(value) == null || value == '') { return false } else { return true } } function getSubStr(string: string) { let str = '' let len = 0 for (var i = 0; i < string.length; i++) { if (string[i].match(/[^\x00-\xff]/gi) != null) { len += 2 } else { len += 1 } if (len > 240) { /* 240为要截取的长度 */ str += '...' break } str += string[i] } return str } class Books { /** * 新建小书post提交 * @param {object} ctx 上下文对象 */ static async createBooks(req: any, res: any, next: any) { let reqData = req.body let { user = '' } = req try { if (!reqData.title) { throw new Error('请输入小书名字') } if (reqData.title.length > 150) { throw new Error('小书标题过长,请小于150个字符') } if (!reqData.description) { throw new Error('请输入小书简介') } if (!reqData.content) { throw new Error('请输入小书详情') } if (!reqData.tag_ids) { throw new Error('请选择小书标签') } if (!reqData.is_free) { throw new Error('请选择是否免费还是付费') } if (Number(reqData.is_free) !== isFree.free) { if (!reqData.pay_type) { throw new Error('请选择支付类型') } if (reqData.price < 0) { throw new Error('请请输入大于等于0的定价!') } if (reqData.price > 100) { throw new Error('小书当前定价不能超过100,后续等待管理员开放!') } if (!isDigit(reqData.price)) { throw new Error('请输入整数数字类型!') } } // 判断是否违规,禁言 let date = new Date() let currDate = moment(date.setHours(date.getHours())).format( 'YYYY-MM-DD HH:mm:ss' ) if (new Date(currDate).getTime() < new Date(user.ban_dt).getTime()) { throw new Error( `当前用户因违规已被管理员禁用发布系统,时间到:${moment( user.ban_dt ).format('YYYY年MM月DD日 HH时mm分ss秒')},如有疑问请联系网站管理员` ) } let userInfo = await models.user_info.findOne({ where: { uid: user.uid } }) if (userInfo.experience < userLevel.three) { throw new Error('用户等级大于等于Lv3才可创建小书') } // 虚拟币判断是否可以进行继续的操作 const isVirtual = await userVirtual.isVirtual({ uid: user.uid, type: modelName.books, action: modelAction.create }) if (!isVirtual) { throw new Error('贝壳余额不足!') } let oneArticleTag = await models.article_tag.findOne({ where: { tag_id: config.ARTICLE_TAG.dfOfficialExclusive } }) const website = lowdb .read() .get('website') .value() if (~reqData.tag_ids.indexOf(config.ARTICLE_TAG.dfOfficialExclusive)) { if (!~user.user_role_ids.indexOf(config.USER_ROLE.dfManagementTeam)) { throw new Error( `${oneArticleTag.name}只有${website.website_name}管理团队才能发布小书` ) } } let userRoleALL = await models.user_role.findAll({ where: { user_role_id: { [Op.or]: user.user_role_ids.split(',') }, user_role_type: 1 // 用户角色类型1是默认角色 } }) let userAuthorityIds = '' userRoleALL.map((roleItem: any) => { userAuthorityIds += roleItem.user_authority_ids + ',' }) let status = ~userAuthorityIds.indexOf(config.BOOKS.dfNoReviewBooksId) ? statusList.freeReview // 免审核 : statusList.pendingReview // 待审核 const createBooks = await models.books.create({ uid: user.uid, title: xss(reqData.title), description: xss(reqData.description), content: xss(reqData.content) /* 主内容 */, cover_img: reqData.cover_img || config.DF_ICON /* 封面 */, origin_content: reqData.origin_content /* 源内容 */, status, // '1:审核中;2:审核通过;3:审核失败;4:无需审核' is_public: Number(reqData.is_public), // 是否公开 tag_ids: reqData.tag_ids, is_free: reqData.is_free, // 免费还是付费 pay_type: reqData.pay_type, // 支付类型 price: parseInt(reqData.price) // 价格 }) await userVirtual.setVirtual({ uid: user.uid, associate: createBooks.books_id, type: modelName.books, action: modelAction.create }) await attention.attentionMessage({ uid: user.uid, type: modelName.books, action: modelAction.create, associate_id: createBooks.books_id }) resClientJson(res, { state: 'success', message: '创建成功' }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * ajax 查询一篇用户自己的小书 * @param {object} ctx 上下文对象 */ static async getUserBooksInfo(req: any, res: any, next: any) { let { books_id } = req.query let { user = '' } = req try { let books = await models.books.findOne({ where: { uid: user.uid, books_id } }) if (books) { if (books) { resClientJson(res, { state: 'success', message: '获取小书成功', data: { books } }) } else { resClientJson(res, { state: 'error', message: '获取小书失败' }) } } else { throw new Error('获取小书失败') } } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 更新小书 * @param {object} ctx 上下文对象 */ static async updateBooks(req: any, res: any, next: any) { let reqData = req.body let { user = '' } = req try { if (!reqData.title) { throw new Error('请输入小书名字') } if (reqData.title.length > 150) { throw new Error('小书标题过长,请小于150个字符') } if (!reqData.description) { throw new Error('请输入小书简介') } if (!reqData.content) { throw new Error('请输入小书详情') } if (!reqData.tag_ids) { throw new Error('请选择小书标签') } if (!reqData.is_free) { throw new Error('请选择是否免费还是付费') } if (Number(reqData.is_free) !== isFree.free) { if (!reqData.pay_type) { throw new Error('请选择支付类型') } if (reqData.price < 0) { throw new Error('请输入大于等于0的定价!') } if (reqData.price > 100) { throw new Error('小书当前定价不能超过100,后续等待管理员开放!') } if (!isDigit(reqData.price)) { throw new Error('请输入整数数字类型!') } } let date = new Date() let currDate = moment(date.setHours(date.getHours())).format( 'YYYY-MM-DD HH:mm:ss' ) if (new Date(currDate).getTime() < new Date(user.ban_dt).getTime()) { throw new Error( `当前用户因违规已被管理员禁用发布系统,时间到:${moment( user.ban_dt ).format('YYYY年MM月DD日 HH时mm分ss秒')},如有疑问请联系网站管理员` ) } let oneArticleTag = await models.article_tag.findOne({ where: { tag_id: config.ARTICLE_TAG.dfOfficialExclusive } }) const website = lowdb .read() .get('website') .value() if (~reqData.tag_ids.indexOf(config.ARTICLE_TAG.dfOfficialExclusive)) { if (!~user.user_role_ids.indexOf(config.USER_ROLE.dfManagementTeam)) { throw new Error( `${oneArticleTag.name}只有${website.website_name}管理团队才能发布小书` ) } } let userRoleALL = await models.user_role.findAll({ where: { user_role_id: { [Op.or]: user.user_role_ids.split(',') }, user_role_type: 1 // 用户角色类型1是默认角色 } }) let userAuthorityIds = '' userRoleALL.map((roleItem: any) => { userAuthorityIds += roleItem.user_authority_ids + ',' }) let status = ~userAuthorityIds.indexOf(config.BOOKS.dfNoReviewBooksId) ? statusList.freeReview // 免审核 : statusList.pendingReview // 待审核 await models.books.update( { title: xss(reqData.title), description: xss(reqData.description), content: xss(reqData.content) /* 主内容 */, cover_img: reqData.cover_img || config.DF_ICON /* 封面 */, origin_content: reqData.origin_content /* 源内容 */, status, // '1:审核中;2:审核通过;3:审核失败;4:无需审核' is_public: Number(reqData.is_public), // 是否公开 tag_ids: reqData.tag_ids, is_free: reqData.is_free, // 免费还是付费 pay_type: reqData.pay_type, // 支付类型 price: parseInt(reqData.price) // 价格 }, { where: { books_id: reqData.books_id, // 查询条件 uid: user.uid } } ) resClientJson(res, { state: 'success', message: '修改小书成功' }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 删除一本小书 * @param {object} ctx 上下文对象 */ static async deleteBooks(req: any, res: any, next: any) { const resData = req.body let { user = '' } = req try { await models.books.update( { status: statusList.deleted }, // '状态(1:审核中;2:审核通过;3:审核失败,4回收站,5已删除)'}, { { where: { books_id: resData.books_id, // 查询条件 uid: user.uid } } ) resClientJson(res, { state: 'success', message: '删除小书成功' }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } // 首页的公开的小书列表 static async getBooksList(req: any, res: any, next: any) { let page = req.query.page || 1 let pageSize = req.query.pageSize || 24 let sort = req.query.sort let tagId = req.query.tagId let columnEnName = req.query.columnEnName let tagIdArr = [] let whereParams: any = { is_public: true, status: { [Op.or]: [statusList.reviewSuccess, statusList.freeReview] } } let orderParams: any[] = [] let allArticleTagId = [] // 全部禁止某些文章标签推送的id let allArticleTag = await models.article_tag.findAll({ where: { is_push: false } // 为空,获取全部,也可以自己添加条件 }) if (allArticleTag && allArticleTag.length > 0) { for (let item in allArticleTag) { allArticleTagId.push(allArticleTag[item].tag_id) } whereParams['tag_ids'] = { [Op.notRegexp]: `${allArticleTagId.join('|')}` } } if (columnEnName && columnEnName !== 'all') { if (!tagId) { let oneArticleColumn = await models.article_column.findOne({ where: { en_name: columnEnName } // 为空,获取全部,也可以自己添加条件 }) tagIdArr = oneArticleColumn.tag_ids.split(',') } else { tagIdArr = [tagId] } } !sort && (orderParams = [['create_date', 'DESC']]) sort === 'hot' && (orderParams = [['read_count', 'DESC']]) tagIdArr.length > 0 && (whereParams['tag_ids'] = { [Op.regexp]: `${tagIdArr.join('|')}` }) sort === '7day' && (whereParams['create_date'] = { [Op.between]: [ new Date(TimeNow.showWeekFirstDay()), new Date(TimeNow.showWeekLastDay()) ] }) sort === '30day' && (whereParams['create_date'] = { [Op.between]: [ new Date(TimeNow.showMonthFirstDay()), new Date(TimeNow.showMonthLastDay()) ] }) try { let { count, rows } = await models.books.findAndCountAll({ where: whereParams, // 为空,获取全部,也可以自己添加条件 offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目 limit: pageSize, // 每页限制返回的数据条数 order: orderParams }) for (let i in rows) { rows[i].setDataValue( 'create_dt', await TimeDistance(rows[i].create_date) ) rows[i].setDataValue('update_dt', await TimeDistance(rows[i].update_dt)) rows[i].setDataValue( 'bookCount', await models.book.count({ where: { books_id: rows[i].books_id } }) ) rows[i].setDataValue( 'collectUserIds', await models.collect.findAll({ where: { associate_id: rows[i].books_id, is_associate: true, type: modelName.books } }) ) if (rows[i].tag_ids) { rows[i].setDataValue( 'tag', await models.article_tag.findAll({ where: { tag_id: { [Op.or]: rows[i].tag_ids.split(',') } } }) ) } rows[i].setDataValue( 'user', await models.user.findOne({ where: { uid: rows[i].uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) ) } await resClientJson(res, { state: 'success', message: 'success', data: { page, count, pageSize, list: rows } }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * ajax 查询一篇小书信息 * @param {object} ctx 上下文对象 */ static async getBooksInfo(req: any, res: any, next: any) { let { books_id, type } = req.query let { user = '', islogin } = req try { let books = await models.books.findOne({ where: { books_id } }) if (books) { if (type === 'look') { await models.books.update( { read_count: Number(books.read_count) + 1 }, { where: { books_id } } // 为空,获取全部,也可以自己添加条件 ) } books.setDataValue('create_dt', await TimeDistance(books.create_date)) books.setDataValue( 'collectUserIds', await models.collect.findAll({ where: { associate_id: books.books_id, is_associate: true, type: modelName.books } }) ) books.setDataValue( 'bookCount', await models.book.count({ where: { books_id } }) ) books.setDataValue( 'trialReadCount', await models.book.count({ where: { books_id, trial_read: trialRead.yes } }) ) books.setDataValue( 'user', await models.user.findOne({ where: { uid: books.uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) ) if (islogin) { // 获取商品信息 const productInfo = await models.order.findOne({ where: { product_id: books_id, product_type: modelName.books, uid: user.uid } }) if (productInfo) { // 存在商品信息,说明当前商品已被用户购买 books.setDataValue('isBuy', true) } else { books.setDataValue('isBuy', false) } } else { books.setDataValue('isBuy', false) } if (books.status === statusList.deleted) { books.setDataValue('content', '小书已被删除') } if (books) { resClientJson(res, { state: 'success', message: '获取小书成功', data: { books } }) } else { resClientJson(res, { state: 'error', message: '获取小书失败', data: { books: {} } }) } } else { throw new Error('获取小书失败') } } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * ajax 查询一篇小书所有的章节 * @param {object} ctx 上下文对象 */ static async getBooksBookAll(req: any, res: any, next: any) { let { books_id } = req.query let { user = '', islogin } = req try { let books = await models.books.findOne({ where: { books_id } }) if (books) { let allBook = await models.book.findAll({ where: { books_id }, attributes: [ 'book_id', 'books_id', 'uid', 'title', 'excerpt', 'status', 'rejection_reason', 'sort', 'read_count', 'update_date', 'read_time', 'create_date', 'trial_read' ] }) for (let i in allBook) { if (islogin) { // 获取商品信息 const productInfo = await models.order.findOne({ where: { product_id: books_id, product_type: modelName.books, uid: user.uid } }) if (productInfo) { // 存在商品信息,说明当前商品已被用户购买 allBook[i].setDataValue('isBuy', true) } else { allBook[i].setDataValue('isBuy', false) } } else { allBook[i].setDataValue('isBuy', false) } allBook[i].setDataValue( 'commentCount', await models.book_comment.count({ where: { book_id: allBook[i].book_id } }) ) allBook[i].setDataValue( 'rTime', await computedReadTime(allBook[i].read_time) ) } resClientJson(res, { state: 'success', message: '获取小书所有章节成功', data: { list: allBook } }) } else { resClientJson(res, { state: 'error', message: '获取小书章节失败,小书不存在' }) } } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } } export default Books
the_stack
import * as React from "react"; import { Trans } from "@lingui/macro"; import { Tooltip } from "reactjs-components"; import AddButton from "#SRC/js/components/form/AddButton"; import DeleteRowButton from "#SRC/js/components/form/DeleteRowButton"; import FieldAutofocus from "#SRC/js/components/form/FieldAutofocus"; import FieldHelp from "#SRC/js/components/form/FieldHelp"; import FieldInput from "#SRC/js/components/form/FieldInput"; import FieldLabel from "#SRC/js/components/form/FieldLabel"; import FormGroup from "#SRC/js/components/form/FormGroup"; import FormGroupContainer from "#SRC/js/components/form/FormGroupContainer"; import FormGroupHeading from "#SRC/js/components/form/FormGroupHeading"; import FormGroupHeadingContent from "#SRC/js/components/form/FormGroupHeadingContent"; import FormRow from "#SRC/js/components/form/FormRow"; import FieldError from "#SRC/js/components/form/FieldError"; import InfoTooltipIcon from "#SRC/js/components/form/InfoTooltipIcon"; import { FormOutput, FormError, RestartPolicy } from "./helpers/JobFormData"; import { getFieldError } from "./helpers/ErrorUtil"; import { JobDataPlaceholders } from "./helpers/DefaultFormData"; interface RunConfigSectionProps { formData: FormOutput; errors: FormError[]; showErrors: boolean; onRemoveItem: (path: string, index: number) => void; onAddItem: (path: string) => void; } class RunConfigFormSection extends React.Component<RunConfigSectionProps> { public render() { const { formData, errors, showErrors, onAddItem, onRemoveItem, } = this.props; const labels = formData.labels || []; const artifacts = formData.artifacts || []; try { return ( <div className="form-section"> {/* RUN CONFIGURATION */} <Trans render="h1" className="flush-top short-bottom"> Run Configuration </Trans> <Trans render="p">More advanced settings for this job.</Trans> {/* MAX LAUNCH DELAY */} <FormRow> <FormGroup className="column-3"> <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent title="Max Launch Delay"> <Trans render="span">Max Launch Delay</Trans> </FormGroupHeadingContent> <FormGroupHeadingContent title="Max Launch Delay Info"> <Tooltip content={ <Trans> The number of seconds until the job needs to be running. If the deadline is reached without successfully running the job, the job is aborted. </Trans> } interactive={true} maxWidth={300} wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> <FieldInput type="number" name="job.run.maxLaunchDelay" value={formData.maxLaunchDelay} placeholder={JobDataPlaceholders.maxLaunchDelay} /> <FieldHelp> <Trans render="span">Enter in seconds</Trans> </FieldHelp> </FormGroup> </FormRow> {/* KILL GRACE PERIOD */} <FormRow> <FormGroup className="column-3"> <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent title="Kill Grace Period"> <Trans render="span">Kill Grace Period</Trans> </FormGroupHeadingContent> <FormGroupHeadingContent title="Kill Grace Period Info"> <Tooltip content={ <Trans> Configures the number of seconds between escalating from SIGTERM to SIGKILL when signalling tasks to terminate. Using this grace period, tasks should perform orderly shut down immediately upon receiving SIGTERM. </Trans> } interactive={true} maxWidth={300} wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> <FieldInput type="number" name="job.run.taskKillGracePeriodSeconds" value={formData.killGracePeriod} /> <FieldHelp> <Trans render="span">Enter in seconds</Trans> </FieldHelp> </FormGroup> </FormRow> {/* USERNAME */} <FormRow> <FormGroup className="column-6"> <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent title="Username"> <Trans render="span">Username</Trans> </FormGroupHeadingContent> <FormGroupHeadingContent title="Username Info"> <Tooltip content={ <Trans> The user to use to run the tasks on the agent </Trans> } interactive={true} maxWidth={300} wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> <FieldInput name="job.run.user" value={formData.user} /> <FieldHelp> <Trans render="span"> Enter user to run tasks on the agent </Trans> </FieldHelp> </FormGroup> </FormRow> {/* ARTIFACT URI */} <h3 className="short-bottom"> <FormGroupHeading> <FormGroupHeadingContent> <Trans render="span">Artifact URI</Trans> </FormGroupHeadingContent> <FormGroupHeadingContent> <Tooltip content={ <Trans> Provided URIs are passed to Mesos fetcher module and resolved in runtime </Trans> } interactive={true} maxWidth={300} wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> </h3> {artifacts.map((artifact, i) => ( <FormGroupContainer key={i} onRemove={onRemoveItem("artifacts", i)}> <FormRow> <FormGroup className="column-11"> <FieldAutofocus> <FieldInput name={`uri.${i}.artifacts`} type="text" value={artifact.uri} placeholder="http://www.artifact.com" /> </FieldAutofocus> </FormGroup> </FormRow> <FormRow> <FormGroup className="column-auto"> <FieldLabel matchInputHeight={true}> <FieldInput checked={artifact.executable} name={`executable.${i}.artifacts`} type="checkbox" /> Executable </FieldLabel> </FormGroup> <FormGroup className="column-auto"> <FieldLabel matchInputHeight={true}> <FieldInput checked={artifact.extract} name={`extract.${i}.artifacts`} type="checkbox" /> Extract </FieldLabel> </FormGroup> <FormGroup className="column-auto"> <FieldLabel matchInputHeight={true}> <FieldInput checked={artifact.cache} name={`cache.${i}.artifacts`} type="checkbox" /> Cache </FieldLabel> </FormGroup> </FormRow> </FormGroupContainer> ))} <FormRow> <FormGroup className="column-12"> <AddButton onClick={onAddItem("artifacts")}> <Trans>Add Artifact</Trans> </AddButton> </FormGroup> </FormRow> {/* RESTART CONFIGURATION */} <Trans render="h2" className="short-bottom"> Restart Policy </Trans> <Trans render="p"> The steps to take if a job fails. Either never relaunch a job or try to start a job when it fails. </Trans> {/* RESTART JOB */} <FormGroup> <FieldLabel> <FieldInput checked={formData.restartPolicy !== RestartPolicy.OnFailure} name="restartPolicy" type="radio" value={RestartPolicy.Never} /> <Trans render="span">Never</Trans> </FieldLabel> <FieldLabel> <FieldInput checked={formData.restartPolicy === RestartPolicy.OnFailure} name="restartPolicy" type="radio" value={RestartPolicy.OnFailure} /> <Trans render="span">On Failure</Trans> </FieldLabel> </FormGroup> {/* RETRY TIME */} <FormRow> <FormGroup className="column-3"> <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent title="Retry Time"> <Trans render="span">Keep Trying Time</Trans> </FormGroupHeadingContent> <FormGroupHeadingContent title="Retry Time Info"> <Tooltip content={ <Trans> If the job fails, how long should we try to restart the job. If no value is set, this means forever. </Trans> } interactive={true} maxWidth={300} wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> <FieldInput type="number" name="activeDeadlineSeconds" value={formData.retryTime} disabled={formData.restartPolicy !== RestartPolicy.OnFailure} /> <FieldHelp> <Trans render="span"> If no value is set, this means forever </Trans> </FieldHelp> </FormGroup> </FormRow> {/* LABELS */} <Trans render="h2" className="short-bottom"> Labels </Trans> <Trans render="p"> Attach metadata to expose additional information in other services. </Trans> {labels.length > 0 ? ( <FormRow> <FormGroup className="column-6 short-bottom"> <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent> <Trans render="span">Key</Trans> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> </FormGroup> <FormGroup className="column-6 short-bottom"> <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent> <Trans render="span">Value</Trans> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> </FormGroup> <span style={{ visibility: "hidden", height: 0 }}> {/* fake horizontal spacing, countering the buttons below */} <DeleteRowButton /> </span> </FormRow> ) : null} {labels.map(([key, value], i) => ( <FormRow key={i}> <FormGroup className="column-6" showError={Boolean( showErrors && getFieldError(`labels.${i}`, errors) )} > <FieldAutofocus> <FieldInput name={`key.${i}.labels`} value={key} /> <FieldError> {getFieldError(`labels.${i}`, errors)} </FieldError> </FieldAutofocus> <span className="emphasis form-colon">:</span> </FormGroup> <FormGroup className="column-6"> <FieldInput name={`value.${i}.labels`} value={value} /> </FormGroup> <FormGroup hasNarrowMargins={true}> <DeleteRowButton onClick={onRemoveItem("labels", i)} /> </FormGroup> </FormRow> ))} <FormRow> <FormGroup className="column-12"> <AddButton onClick={onAddItem("labels")}> <Trans>Add Label</Trans> </AddButton> </FormGroup> </FormRow> </div> ); } catch { return ( <Trans> Sorry! An error occured while trying to parse and render the JSON you specified. </Trans> ); } } } export default RunConfigFormSection;
the_stack
import { False, True } from './conditionals'; // ------- // Helpers // ------- /** * An object with string keys and values of type `any`. */ export type PlainObject = Record<string, any>; /** * Takes any type and makes it an object type. * Useful when combined with `&` intersection types. * @param T A type who will be converted into an object * @returns An object formed by the key, value pairs of T */ export type ObjectType<T> = { [k in keyof T]: T[k]; }; /** * Takes two objects and returns their intersection. * This combines all keys and uses `ObjectType` to "clean up" the resultant object. * Useful for making extremely complex types look nice in VSCode. * @param T First object to be intersected * @param U Second object to be intersected * @returns `T` & `U` cleaned up to look like flat object to VSCode */ export type CombineObjects<T extends object, U extends object> = ObjectType<T & U>; /** * Gets the value of specified property on any object without compile time error (`Property 'b' does not exist on type '{ a: string; }'.`) and the like. * Returns `never` if the key is not on the object. * It helps to use `If<HasKey...` to handle validity of the object first. * @param T Object to get values from * @param K Key to query object for value * @returns `T[K]` if the key exists, `never` otherwise */ export type GetKey<T, K extends keyof any> = K extends keyof T ? T[K] : never; /** * Like `GetKey`, but returns `unknown` if the key is not present on the object. * @param T Object to get values from * @param K Key to query object for value * @returns `T[K]` if the key exists, `unknown` otherwise */ export type TryKey<T, K extends keyof any> = K extends keyof T ? T[K]: unknown; /** * Takes two objects and returns their element-wise intersection. * *Note*: this removes any key-level information, such as optional or readonly keys. * @param T First object to be intersected * @param U Second object to be intersected * @returns element-wise `T` & `U` cleaned up to look like flat object to VSCode */ export type ElementwiseIntersect<T extends object, U extends object> = { [k in (keyof T | keyof U)]: TryKey<T, k> & TryKey<U, k>; }; // ---- // Keys // ---- /** * Objects can be indexed by multiple types: `string`, `number`, `symbol`. * For safe compatibility with typescript version, this type will always * have the correct set of object key types for the current version of TS. * * This is useful for functions that must take a key, instead of `K extends string`, * use `K extends ObjectKeys`. */ export type ObjectKeys = keyof any; /** * Typescript 2.9 introduced `number | symbol` as possible results from `keyof any`. * For backwards compatibility with objects containing only `string` keys, this will * exclude any `number | symbol` keys from `keyof`. * @param T type from which to get keys * @returns keys of `T` that extend `string` */ export type StringKeys<T> = Exclude<keyof T, number | symbol>; /** * When an object has optional or readonly keys, that information is contained within the key. * When using optional/readonly keys in another object, they will retain optional/readonly status. * `PureKeys` will remove the optional/readonly status modifiers from keys. * @param T type from which to get keys * @returns keys of `T` without status modifiers (readonly/optional) */ export type PureKeys<T> = Record<keyof T, keyof T>[keyof T]; /** * Gets all of the keys that are shared between two objects. * @param T first type from which keys will be pulled * @param U second type from which keys will be pulled * @returns the keys that both `T` and `U` have in common. */ export type SharedKeys<T, U> = keyof T & keyof U; /** * Gets all keys between two objects. * @param T first type from which keys will be pulled * @param U second type from which keys will be pulled * @returns the keys of `T` in addition to the keys of `U` */ export type AllKeys<T, U> = keyof T | keyof U; /** * Gets all of the keys that are different between two objects. * This is a set difference between `keyof T` and `keyof U`. * Note that calling this with arguments reversed will have different results. * @param T first type from which keys will be pulled * @param U second type from which keys will be pulled * @returns keys of `T` minus the keys of `U` */ export type DiffKeys<T, U> = Exclude<keyof T, keyof U>; /** * Returns `True` if a key, `K`, is present in a type, `T`, else `False`. * @param T type to check for existence of key `K`. * @param K key to query `T` for * @returns `True` if `K` is a key of `T`. Else `False`. */ export type HasKey<T, K extends keyof any> = K extends keyof T ? True : False; /** * @param T the union to get the keys of * @returns a union containing all the keys of members of `T` */ export type UnionKeys<T> // Using a conditional here, so that it distributes over members of the union // See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types = T extends unknown ? keyof T : never; // ------------- // Manipulations // ------------- /** * Get a union of the properties of an object. * @param T the object whose property values will be unionized * @returns a union of the right-side values of `T` */ export type UnionizeProperties<T extends object> = T[keyof T]; /** * Gives back an object with listed keys removed. * This is the opposite of `Pick`. * @param T the object whose properties will be removed * @param K the union of keys to remove from `T` * @returns `T` with the keys `K` removed */ export type Omit<T extends object, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; /** * Returns only the shared properties between two objects. * All shared properties must be the same type. * @param T the first object * @param U a second object whose shared properties (keys contained in both `T` and `U`) must have the same type as those in `T` * @returns the properties that are shared between `T` and `U` */ export type Intersect<T extends object, U extends Partial<T>> = Omit<U, DiffKeys<U, T>>; /** * Can change the types of properties on an object. * This is similar to `Merge`, except that it will not add previously non-existent properties to the object. * @param T the object whose properties will be overwritten * @param U the object who will overwrite `T` * @returns `T` with properties overwritten with values in `U` */ export type Overwrite<T extends object, U extends object> = { [k in keyof T]: k extends keyof U ? U[k] : T[k]; }; /** * Much like `_.merge` in javascript, this returns an object with all keys present between both objects, but conflicts resolved by rightmost object. * @param T the object whose properties will be overwritten * @param U the object whose properties will be present _as is_ in the resultant object * @returns an object containing all of `U` and properties of `T` not present in `U` */ export type Merge<T extends object, U extends object> = Overwrite<T, U> & U; /** * For discriminated unions of objects, it is important to have a single "tag" property. * Creates an object with each entry being tagged by the key defining that entry. * @param T a Record of objects * @param Key the key to add to each inner object as the tag property * @returns a record where each key of the record is now the `Key` property of the inner object */ export type TaggedObject<T extends Record<keyof any, object>, Key extends keyof any> = { [K in keyof T]: T[K] & Record<Key, K>; }; // --------- // Accessors // --------- /** * Uses `Partial` to make every parameter of an object optional (`| undefined`). * Iterates through arrays of objects and nested objects. * @param T the type to take a partial of. Can be deeply nested. * @returns `Partial<T>` recursively through all properties of `T` */ export type DeepPartial<T> = Partial<{ [k in keyof T]: T[k] extends unknown[] ? Array<DeepPartial<T[k][number]>> : T[k] extends Function ? T[k] : T[k] extends object ? DeepPartial<T[k]> : T[k]; }>; /** * Marks all keys as required. * @param T object whose keys will be marked required * @returns `T` with all fields marked required */ export type AllRequired<T extends object> = { [K in keyof T]-?: NonNullable<T[K]> }; /** * Mark specific keys, `K`, of `T` as required. * @param T object whose keys will be marked required * @param K keys of `T` that will be marked required * @returns `T` with keys, `K`, marked as required */ export type Required<T extends object, K extends keyof T> = CombineObjects< {[k in K]-?: NonNullable<T[k]> }, Omit<T, K> >; /** * Mark specific keys, `K`, of `T` as optional (think `Partial`). * @param T object whose keys will be marked optional * @param K keys of `T` that will be marked optional * @returns `T` with keys, `K`, marked as optional */ export type Optional<T extends object, K extends keyof T> = CombineObjects< {[k in K]?: T[k] | undefined }, Omit<T, K> >; /** * Uses `Readonly` to make every parameter of an object - and its sub-objects recursively - readonly. * @param T type to be recursively traversed with keys marked as readonly * @returns `T` with all keys recursively marked as readonly */ export type DeepReadonly<T> = Readonly<{ [k in keyof T]: T[k] extends unknown[] ? ReadonlyArray<DeepReadonly<T[k][number]>> : T[k] extends Function ? T[k] : T[k] extends object ? DeepReadonly<T[k]> : T[k]; }>; /** * Gets all keys that point to a given type. * @param O the object whose keys will be returned * @param T the type to filter by * @returns keys of `O` whose right-side value is `T` */ export type KeysByType<O extends object, T> = { [k in keyof O]-?: O[k] extends T ? k : never; }[keyof O]; // ------- // Classes // ------- /** * Builds the type of any constructor function for a particular object. * @param T the object to build a constructor for * @returns a constructor for `T` with the prototype set to `T` */ export interface ConstructorFor<T extends object> { new (...args: any[]): T; prototype: T; } // ------ // Unions // ------ /** * Makes a union 'strict', such that members are disallowed from including the keys of other members * For example, `{x: 1, y: 1}` is a valid member of `{x: number} | {y: number}`, * but it's not a valid member of StrictUnion<{x: number} | {y: number}>. * @param T a union type * @returns a the strict version of `T` */ export type StrictUnion<T> = _StrictUnionHelper<T, T>; // UnionMember is actually passed as the whole union, but it's used in a distributive conditional // to refer to each individual member of the union /** no-doc */ export type _StrictUnionHelper<UnionMember, Union> = UnionMember extends unknown ? UnionMember & Partial<Record<Exclude<UnionKeys<Union>, keyof UnionMember>, never>> : never;
the_stack
import { TestBed, fakeAsync, tick } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { AlertsService } from 'services/alerts.service'; import { CsrfTokenService } from 'services/csrf-token.service'; import { ExplorationDataService } from 'pages/exploration-editor-page/services/exploration-data.service'; import { ExplorationRightsService } from './exploration-rights.service'; import { ExplorationRightsBackendApiService } from './exploration-rights-backend-api.service'; import cloneDeep from 'lodash/cloneDeep'; describe('Exploration rights service', () => { let ers: ExplorationRightsService = null; let als: AlertsService = null; let httpTestingController: HttpTestingController = null; let explorationRightsBackendApiService: ExplorationRightsBackendApiService; let csrfService = null; let clearWarningsSpy = null; let successHandler = null; let failHandler = null; let serviceData = { rights: { owner_names: ['abc'], editor_names: [], voice_artist_names: [], viewer_names: [], status: 'private', cloned_from: 'e1234', community_owned: true, viewable_if_private: true } }; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ { provide: ExplorationDataService, useValue: { explorationId: '12345', data: { version: 1 } } }, ExplorationRightsBackendApiService ] }); als = TestBed.inject(AlertsService); csrfService = TestBed.inject(CsrfTokenService); ers = TestBed.inject(ExplorationRightsService); httpTestingController = TestBed.inject(HttpTestingController); explorationRightsBackendApiService = TestBed.inject(ExplorationRightsBackendApiService); }); beforeEach(() => { spyOn(csrfService, 'getTokenAsync').and.callFake(() => { return Promise.resolve('simple-csrf-token'); }); clearWarningsSpy = spyOn(als, 'clearWarnings').and.callThrough(); successHandler = jasmine.createSpy('success'); failHandler = jasmine.createSpy('fail'); }); afterEach(() => { httpTestingController.verify(); }); it('should correctly initializes the service', () => { expect(ers.ownerNames).toBeUndefined(); expect(ers.editorNames).toBeUndefined(); expect(ers.voiceArtistNames).toBeUndefined(); expect(ers.viewerNames).toBeUndefined(); expect(ers.isPrivate()).toBe(false); expect(ers.isPublic()).toBe(false); expect(ers.clonedFrom()).toBeUndefined(); expect(ers.isCommunityOwned()).toBeUndefined(); expect(ers.viewableIfPrivate()).toBeUndefined(); ers.init( serviceData.rights.owner_names, serviceData.rights.editor_names, serviceData.rights.voice_artist_names, serviceData.rights.viewer_names, serviceData.rights.status, serviceData.rights.cloned_from, serviceData.rights.community_owned, serviceData.rights.viewable_if_private ); expect(ers.ownerNames).toEqual(serviceData.rights.owner_names); expect(ers.editorNames).toEqual(serviceData.rights.editor_names); expect(ers.voiceArtistNames).toEqual( serviceData.rights.voice_artist_names); expect(ers.viewerNames).toEqual(serviceData.rights.viewer_names); expect(ers.isPrivate()).toEqual(true); expect(ers.clonedFrom()).toEqual(serviceData.rights.cloned_from); expect(ers.isCommunityOwned()).toBe( serviceData.rights.community_owned); expect(ers.viewableIfPrivate()).toBe( serviceData.rights.viewable_if_private); }); it('should reports the correct cloning status', () => { ers.init(['abc'], [], [], [], 'public', '1234', true, false); expect(ers.isCloned()).toBe(true); expect(ers.clonedFrom()).toEqual('1234'); ers.init(['abc'], [], [], [], 'public', null, true, false); expect(ers.isCloned()).toBe(false); expect(ers.clonedFrom()).toBeNull(); }); it('should reports the correct community-owned status', () => { ers.init(['abc'], [], [], [], 'public', '1234', false, false); expect(ers.isCommunityOwned()).toBe(false); ers.init(['abc'], [], [], [], 'public', '1234', true, false); expect(ers.isCommunityOwned()).toBe(true); }); it('should reports the correct derived statuses', () => { ers.init(['abc'], [], [], [], 'private', 'e1234', true, false); expect(ers.isPrivate()).toBe(true); expect(ers.isPublic()).toBe(false); ers.init(['abc'], [], [], [], 'public', 'e1234', true, false); expect(ers.isPrivate()).toBe(false); expect(ers.isPublic()).toBe(true); }); it('should reports correcty if exploration rights is viewable when private', () => { ers.init(['abc'], [], [], [], 'private', 'e1234', true, true); expect(ers.viewableIfPrivate()).toBe(true); ers.init(['abc'], [], [], [], 'private', 'e1234', false, false); expect(ers.viewableIfPrivate()).toBe(false); }); it('should change community owned to true', fakeAsync(() => { serviceData.rights.community_owned = true; spyOn( explorationRightsBackendApiService, 'makeCommunityOwnedPutData').and.returnValue( Promise.resolve(serviceData)); ers.init(['abc'], [], [], [], 'private', 'e1234', false, true); ers.makeCommunityOwned(); tick(); expect(explorationRightsBackendApiService.makeCommunityOwnedPutData) .toHaveBeenCalled(); expect(ers.isCommunityOwned()).toBe(true); })); it('should use reject handler when changing community owned to true fails', fakeAsync(() => { spyOn( explorationRightsBackendApiService, 'makeCommunityOwnedPutData').and.returnValue( Promise.reject()); ers.init( ['abc'], [], [], [], 'private', 'e1234', false, true); ers.makeCommunityOwned().then( successHandler, failHandler); tick(); expect(ers.isCommunityOwned()).toBe(false); expect(clearWarningsSpy).not.toHaveBeenCalled(); expect(successHandler).not.toHaveBeenCalled(); expect(failHandler).toHaveBeenCalled(); })); it('should change exploration right viewability', fakeAsync(() => { serviceData.rights.viewable_if_private = true; spyOn( explorationRightsBackendApiService, 'setViewabilityPutData').and.returnValue( Promise.resolve(serviceData)); ers.setViewability(true); tick(); expect(ers.viewableIfPrivate()).toBe(true); })); it('should use reject when changing exploration right viewability fails', fakeAsync(() => { spyOn( explorationRightsBackendApiService, 'setViewabilityPutData').and.returnValue( Promise.reject()); ers.init( ['abc'], [], [], [], 'private', 'e1234', false, false); ers.setViewability(true).then( successHandler, failHandler); tick(); expect(ers.viewableIfPrivate()).toBe(false); expect(clearWarningsSpy).not.toHaveBeenCalled(); expect(successHandler).not.toHaveBeenCalled(); expect(failHandler).toHaveBeenCalled(); })); it('should save a new member', fakeAsync(() => { serviceData.rights.viewer_names = ['viewerName']; spyOn( explorationRightsBackendApiService, 'saveRoleChangesPutData').and.returnValue( Promise.resolve(serviceData)); ers.saveRoleChanges('newUser', 'viewer'); tick(); expect(ers.viewerNames).toEqual( ['viewerName']); })); it('should remove existing user', fakeAsync(() => { serviceData.rights.viewer_names = ['newUser']; spyOn( explorationRightsBackendApiService, 'removeRoleAsyncDeleteData').and.returnValue( Promise.resolve(serviceData)); ers.removeRoleAsync('newUser').then(successHandler, failHandler); tick(); expect(successHandler).toHaveBeenCalled(); expect(failHandler).not.toHaveBeenCalled(); expect(ers.viewerNames).toEqual( serviceData.rights.viewer_names); })); it('should save a new voice artist', fakeAsync(() => { serviceData.rights.voice_artist_names = ['voiceArtist']; spyOn( explorationRightsBackendApiService, 'assignVoiceArtistRoleAsyncPostData').and.returnValue( Promise.resolve(serviceData)); ers.init(['abc'], [], [], [], 'public', '1234', true, false); expect(ers.voiceArtistNames).toEqual([]); ers.assignVoiceArtistRoleAsync('voiceArtist').then( successHandler, failHandler); tick(); expect(ers.voiceArtistNames).toEqual(['voiceArtist']); })); it('should remove existing voice artist', fakeAsync(() => { serviceData.rights.voice_artist_names = []; spyOn( explorationRightsBackendApiService, 'removeVoiceArtistRoleAsyncDeleteData').and.returnValue( Promise.resolve(serviceData)); ers.init(['abc'], [], ['voiceArtist'], [], 'public', '1234', true, false); tick(); expect(ers.voiceArtistNames).toEqual(['voiceArtist']); ers.removeVoiceArtistRoleAsync('voiceArtist').then( successHandler, failHandler); tick(); expect(successHandler).toHaveBeenCalled(); expect(failHandler).not.toHaveBeenCalled(); expect(ers.voiceArtistNames).toEqual([]); })); it('should check user already has roles', () => { serviceData.rights.owner_names = ['newOwner']; serviceData.rights.viewer_names = ['newViewer']; serviceData.rights.editor_names = ['newEditor']; serviceData.rights.voice_artist_names = ['newVoiceArtist']; ers.init( serviceData.rights.owner_names, serviceData.rights.editor_names, serviceData.rights.voice_artist_names, serviceData.rights.viewer_names, serviceData.rights.status, serviceData.rights.cloned_from, serviceData.rights.community_owned, serviceData.rights.viewable_if_private ); expect(ers.checkUserAlreadyHasRoles('newOwner')).toBeTruthy(); expect(ers.checkUserAlreadyHasRoles('newViewer')).toBeTruthy(); expect(ers.checkUserAlreadyHasRoles('newEditor')).toBeTruthy(); expect(ers.checkUserAlreadyHasRoles('newVoiceArtist')).toBeTruthy(); expect(ers.checkUserAlreadyHasRoles('notInAllUsersList')).toBeFalsy(); }); it('should check oldrole of user', () => { let sampleDataResultsCopy = cloneDeep(serviceData); sampleDataResultsCopy.rights.owner_names.push('newOwner'); sampleDataResultsCopy.rights.viewer_names.push('newViewer'); sampleDataResultsCopy.rights.editor_names.push('newEditor'); sampleDataResultsCopy.rights.voice_artist_names.push('newVoiceArtist'); ers.init( sampleDataResultsCopy.rights.owner_names, sampleDataResultsCopy.rights.editor_names, sampleDataResultsCopy.rights.voice_artist_names, sampleDataResultsCopy.rights.viewer_names, sampleDataResultsCopy.rights.status, sampleDataResultsCopy.rights.cloned_from, sampleDataResultsCopy.rights.community_owned, sampleDataResultsCopy.rights.viewable_if_private ); expect(ers.getOldRole('newOwner')).toEqual('owner'); expect(ers.getOldRole('newViewer')).toEqual('viewer'); expect(ers.getOldRole('newEditor')).toEqual('editor'); expect(ers.getOldRole('newVoiceArtist')).toEqual('voice artist'); }); it('should reject handler when saving a new member fails', fakeAsync(() => { spyOn( explorationRightsBackendApiService, 'saveRoleChangesPutData').and.returnValue( Promise.reject()); ers.saveRoleChanges( 'newUser', 'viewer').then( successHandler, failHandler); tick(); expect(clearWarningsSpy).not.toHaveBeenCalled(); expect(successHandler).not.toHaveBeenCalled(); expect(failHandler).toHaveBeenCalled(); })); it('should make exploration rights public', fakeAsync(() => { let sampleDataResultsCopy = angular.copy(serviceData); sampleDataResultsCopy.rights.status = 'public'; spyOn( explorationRightsBackendApiService, 'publishPutData').and.returnValue( Promise.resolve(sampleDataResultsCopy)); ers.publish(); tick(); expect(ers.isPublic()).toBe(true); })); it('should call reject handler when making exploration rights public fails', fakeAsync(() => { spyOn( explorationRightsBackendApiService, 'publishPutData').and.returnValue( Promise.reject()); ers.publish().then(successHandler, failHandler); tick(); expect(clearWarningsSpy).not.toHaveBeenCalled(); expect(successHandler).not.toHaveBeenCalled(); expect(failHandler).toHaveBeenCalled(); })); it('should save moderator change to backend', fakeAsync(() => { spyOn( explorationRightsBackendApiService, 'saveModeratorChangeToBackendAsyncPutData').and.returnValue( Promise.resolve(serviceData)); ers.saveModeratorChangeToBackendAsync(''); tick(); expect(clearWarningsSpy).toHaveBeenCalled(); expect(ers.ownerNames).toEqual( serviceData.rights.owner_names); expect(ers.editorNames).toEqual( serviceData.rights.editor_names); expect(ers.voiceArtistNames).toEqual( serviceData.rights.voice_artist_names); expect(ers.viewerNames).toEqual( serviceData.rights.viewer_names); expect(ers.isPrivate()).toEqual(true); expect(ers.clonedFrom()).toEqual( serviceData.rights.cloned_from); expect(ers.isCommunityOwned()).toBe( serviceData.rights.community_owned); expect(ers.viewableIfPrivate()).toBe( serviceData.rights.viewable_if_private); })); it('should reject handler when saving moderator change to backend fails', fakeAsync(() => { spyOn( explorationRightsBackendApiService, 'saveModeratorChangeToBackendAsyncPutData').and.returnValue( Promise.reject()); ers.saveModeratorChangeToBackendAsync(''); tick(); expect(clearWarningsSpy).not.toHaveBeenCalled(); expect(ers.ownerNames).toBeNull(); expect(ers.editorNames).toBeNull(); expect(ers.voiceArtistNames).toBeNull(); expect(ers.viewerNames).toBeNull(); expect(ers.isPrivate()).toBe(false); expect(ers.isPublic()).toBe(false); expect(ers.clonedFrom()).toBeNull(); expect(ers.isCommunityOwned()).toBeNull(); expect(ers.viewableIfPrivate()).toBeNull(); })); });
the_stack
'use strict'; import * as sinon from 'sinon'; import * as vscode from 'vscode'; import * as sinonChai from 'sinon-chai'; import * as chai from 'chai'; import * as path from 'path'; import { TestUtil } from '../TestUtil'; import { ExtensionCommands } from '../../ExtensionCommands'; import { VSCodeBlockchainOutputAdapter } from '../../extension/logging/VSCodeBlockchainOutputAdapter'; import { UserInputUtil } from '../../extension/commands/UserInputUtil'; import { BlockchainWalletExplorerProvider } from '../../extension/explorer/walletExplorer'; import { FabricWallet } from 'ibm-blockchain-platform-wallet'; import { IdentityTreeItem } from '../../extension/explorer/model/IdentityTreeItem'; import { FabricRuntimeUtil, FabricWalletRegistry, FabricWalletRegistryEntry, LogType, FabricWalletGeneratorFactory } from 'ibm-blockchain-platform-common'; import { ExtensionUtil } from '../../extension/util/ExtensionUtil'; chai.should(); chai.use(sinonChai); // tslint:disable no-unused-expression describe('deleteIdentityCommand', () => { let mySandBox: sinon.SinonSandbox; let logSpy: sinon.SinonSpy; let showConfirmationWarningMessage: sinon.SinonStub; let showWalletsQuickPickStub: sinon.SinonStub; let showIdentitiesQuickPickStub: sinon.SinonStub; let purpleWalletEntry: FabricWalletRegistryEntry; let blueWalletEntry: FabricWalletRegistryEntry; let purpleWallet: FabricWallet; let purpleWalletIdentitiesStub: sinon.SinonStub; let executeCommandSpy: sinon.SinonSpy; let identityName: string[]; let localWalletEntry: FabricWalletRegistryEntry; let localWalletIdentitiesStub: sinon.SinonStub; let blueWalletIdentitiesStub: sinon.SinonStub; let purpleWalletRemoveIdentityStub: sinon.SinonStub; let blueWalletRemoveIdentityStub: sinon.SinonStub; let localWalletRemoveIdentityStub: sinon.SinonStub; before(async () => { mySandBox = sinon.createSandbox(); await TestUtil.setupTests(mySandBox); await TestUtil.startLocalFabric(); }); beforeEach(async () => { // Set up stubs mySandBox.restore(); logSpy = mySandBox.stub(VSCodeBlockchainOutputAdapter.instance(), 'log'); showConfirmationWarningMessage = mySandBox.stub(UserInputUtil, 'showConfirmationWarningMessage').resolves(true); showWalletsQuickPickStub = mySandBox.stub(UserInputUtil, 'showWalletsQuickPickBox'); showIdentitiesQuickPickStub = mySandBox.stub(UserInputUtil, 'showIdentitiesQuickPickBox'); // Reset the wallet registry await FabricWalletRegistry.instance().clear(); // Add wallets to the registry purpleWalletEntry = new FabricWalletRegistryEntry({ name: 'purpleWallet', walletPath: path.join(__dirname, '../../test/tmp/v2/wallets/purpleWallet') }); blueWalletEntry = new FabricWalletRegistryEntry({ name: 'blueWallet', walletPath: path.join(__dirname, '../../test/tmp/v2/wallets/blueWallet') }); await FabricWalletRegistry.instance().add(purpleWalletEntry); await FabricWalletRegistry.instance().add(blueWalletEntry); purpleWallet = await FabricWallet.newFabricWallet(purpleWalletEntry.walletPath); purpleWalletIdentitiesStub = mySandBox.stub(purpleWallet, 'getIdentityNames'); const blueWallet: FabricWallet = await FabricWallet.newFabricWallet(blueWalletEntry.walletPath); blueWalletIdentitiesStub = mySandBox.stub(blueWallet, 'getIdentityNames'); localWalletEntry = await FabricWalletRegistry.instance().get('Org1', '1 Org Local Fabric'); const localWallet: FabricWallet = await FabricWallet.newFabricWallet(localWalletEntry.walletPath); localWalletIdentitiesStub = mySandBox.stub(localWallet, 'getIdentityNames'); const getWalletStub: sinon.SinonStub = mySandBox.stub(FabricWalletGeneratorFactory.getFabricWalletGenerator(), 'getWallet'); getWalletStub.withArgs(purpleWalletEntry).resolves(purpleWallet); getWalletStub.withArgs(localWalletEntry).resolves(localWallet); getWalletStub.withArgs(blueWalletEntry).resolves(blueWallet); purpleWalletRemoveIdentityStub = mySandBox.stub(purpleWallet, 'removeIdentity'); blueWalletRemoveIdentityStub = mySandBox.stub(blueWallet, 'removeIdentity'); localWalletRemoveIdentityStub = mySandBox.stub(localWallet, 'removeIdentity'); executeCommandSpy = mySandBox.spy(vscode.commands, 'executeCommand'); }); afterEach(() => { mySandBox.restore(); }); it('should delete an identity when called from the command palette', async () => { identityName = ['greenConga', 'yellowConga']; showWalletsQuickPickStub.resolves({ label: purpleWalletEntry.name, data: purpleWalletEntry }); purpleWalletIdentitiesStub.resolves(identityName); showIdentitiesQuickPickStub.resolves([identityName[0]]); await vscode.commands.executeCommand(ExtensionCommands.DELETE_IDENTITY); purpleWalletRemoveIdentityStub.should.have.been.calledWith(identityName[0]); showWalletsQuickPickStub.should.have.been.calledOnce; purpleWalletIdentitiesStub.should.have.been.calledOnce; showIdentitiesQuickPickStub.should.have.been.calledOnce; logSpy.should.have.been.calledTwice; showConfirmationWarningMessage.should.have.been.calledOnce; logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `deleteIdentity`); logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully deleted identity: ${identityName[0]}`); executeCommandSpy.should.have.been.calledWith(ExtensionCommands.REFRESH_WALLETS); }); it('should delete multiple identities when called from the command palette', async () => { identityName = ['greenConga', 'yellowConga']; showWalletsQuickPickStub.resolves({ label: purpleWalletEntry.name, data: purpleWalletEntry }); purpleWalletIdentitiesStub.resolves([identityName]); showIdentitiesQuickPickStub.resolves(identityName); await vscode.commands.executeCommand(ExtensionCommands.DELETE_IDENTITY); purpleWalletRemoveIdentityStub.getCall(0).should.have.been.calledWith(identityName[0]); purpleWalletRemoveIdentityStub.getCall(1).should.have.been.calledWith(identityName[1]); showWalletsQuickPickStub.should.have.been.calledOnce; purpleWalletIdentitiesStub.should.have.been.calledOnce; showIdentitiesQuickPickStub.should.have.been.calledOnce; logSpy.should.have.been.calledTwice; showConfirmationWarningMessage.should.have.been.calledOnce; logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `deleteIdentity`); logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully deleted selected identities.`); executeCommandSpy.should.have.been.calledWith(ExtensionCommands.REFRESH_WALLETS); }); it('should handle the user not selecting a identity to delete', async () => { identityName = ['greenConga', 'yellowConga']; showWalletsQuickPickStub.resolves({ label: purpleWalletEntry.name, data: purpleWalletEntry }); purpleWalletIdentitiesStub.resolves([identityName]); showIdentitiesQuickPickStub.resolves([]); await vscode.commands.executeCommand(ExtensionCommands.DELETE_IDENTITY); showWalletsQuickPickStub.should.have.been.calledOnce; purpleWalletIdentitiesStub.should.have.been.calledOnce; showIdentitiesQuickPickStub.should.have.been.calledOnce; purpleWalletRemoveIdentityStub.should.not.have.been.called; logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `deleteIdentity`); }); it('should handle the user cancelling selecting a wallet', async () => { showWalletsQuickPickStub.resolves(); await vscode.commands.executeCommand(ExtensionCommands.DELETE_IDENTITY); showWalletsQuickPickStub.should.have.been.calledOnce; purpleWalletIdentitiesStub.should.not.have.been.called; purpleWalletRemoveIdentityStub.should.not.have.been.called; logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `deleteIdentity`); }); it('should show an error if it finds no identities in the chosen wallet', async () => { showWalletsQuickPickStub.resolves({ label: purpleWalletEntry.name, data: purpleWalletEntry }); purpleWalletIdentitiesStub.resolves([]); await vscode.commands.executeCommand(ExtensionCommands.DELETE_IDENTITY); showWalletsQuickPickStub.should.have.been.calledOnce; purpleWalletIdentitiesStub.should.have.been.calledOnce; purpleWalletRemoveIdentityStub.should.not.have.been.called; logSpy.should.have.been.calledTwice; logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, `deleteIdentity`); logSpy.getCall(1).should.have.been.calledWith(LogType.ERROR, `No identities in wallet: ${purpleWalletEntry.walletPath}`); }); it('should show a different error if there are no non-admin identities in the local_fabric wallet', async () => { identityName = ['bob']; showWalletsQuickPickStub.resolves({ label: localWalletEntry.name, data: localWalletEntry }); localWalletIdentitiesStub.resolves([]); await vscode.commands.executeCommand(ExtensionCommands.DELETE_IDENTITY); localWalletIdentitiesStub.should.have.been.calledOnce; localWalletRemoveIdentityStub.should.not.have.been.called; logSpy.should.have.been.calledTwice; logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, `deleteIdentity`); logSpy.getCall(1).should.have.been.calledWith(LogType.ERROR, `No identities to delete in wallet: ${localWalletEntry.displayName}. The ${FabricRuntimeUtil.ADMIN_USER} identity cannot be deleted.`); }); it('should handle the user cancelling selecting an identity to delete', async () => { identityName = ['greenConga', 'yellowConga']; showWalletsQuickPickStub.resolves({ label: purpleWalletEntry.name, data: purpleWalletEntry }); purpleWalletIdentitiesStub.resolves(identityName); showIdentitiesQuickPickStub.resolves(); await vscode.commands.executeCommand(ExtensionCommands.DELETE_IDENTITY); showWalletsQuickPickStub.should.have.been.calledOnce; purpleWalletIdentitiesStub.should.have.been.calledOnce; showIdentitiesQuickPickStub.should.have.been.calledOnce; purpleWalletRemoveIdentityStub.should.not.have.been.called; logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `deleteIdentity`); }); it('should handle the user cancelling, or saying no to, the warning box', async () => { showWalletsQuickPickStub.resolves({ label: blueWalletEntry.name, data: blueWalletEntry }); blueWalletIdentitiesStub.resolves(['biscuits', 'yellowConga']); showIdentitiesQuickPickStub.resolves('biscuits'); showConfirmationWarningMessage.resolves(false); await vscode.commands.executeCommand(ExtensionCommands.DELETE_IDENTITY); showWalletsQuickPickStub.should.have.been.calledOnce; blueWalletIdentitiesStub.should.have.been.calledOnce; showIdentitiesQuickPickStub.should.have.been.calledOnce; blueWalletRemoveIdentityStub.should.not.have.been.called; showConfirmationWarningMessage.should.have.been.calledOnce; logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `deleteIdentity`); }); it('should delete an identity and filter admin id from local wallet', async () => { identityName = [FabricRuntimeUtil.ADMIN_USER, 'bob']; showWalletsQuickPickStub.resolves({ label: localWalletEntry.displayName, data: localWalletEntry }); localWalletIdentitiesStub.resolves(identityName); showIdentitiesQuickPickStub.resolves([identityName[1]]); await vscode.commands.executeCommand(ExtensionCommands.DELETE_IDENTITY); showIdentitiesQuickPickStub.should.have.been.calledOnceWithExactly('Choose the identities to delete', true, [identityName[1]]); }); describe('called from the tree', () => { it('should delete an identity when called from the wallet tree', async () => { identityName = ['blueConga']; const blockchainWalletExplorerProvider: BlockchainWalletExplorerProvider = ExtensionUtil.getBlockchainWalletExplorerProvider(); const treeItem: IdentityTreeItem = new IdentityTreeItem(blockchainWalletExplorerProvider, identityName[0], blueWalletEntry.name, [], blueWalletEntry); await vscode.commands.executeCommand(ExtensionCommands.DELETE_IDENTITY, treeItem); blueWalletRemoveIdentityStub.should.have.been.calledWith(identityName[0]); showWalletsQuickPickStub.should.not.have.been.called; showConfirmationWarningMessage.should.have.been.calledOnce; logSpy.should.have.been.calledTwice; logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `deleteIdentity`); logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully deleted identity: ${identityName[0]}`); executeCommandSpy.should.have.been.calledWith(ExtensionCommands.REFRESH_WALLETS); }); it('should delete an identity and filter admin id from local wallet', async () => { identityName = ['bob']; const blockchainWalletExplorerProvider: BlockchainWalletExplorerProvider = ExtensionUtil.getBlockchainWalletExplorerProvider(); const treeItem: IdentityTreeItem = new IdentityTreeItem(blockchainWalletExplorerProvider, identityName[0], localWalletEntry.displayName, [], localWalletEntry); await vscode.commands.executeCommand(ExtensionCommands.DELETE_IDENTITY, treeItem); localWalletRemoveIdentityStub.should.have.been.calledWith(identityName[0]); showWalletsQuickPickStub.should.not.have.been.called; showConfirmationWarningMessage.should.have.been.calledOnce; logSpy.should.have.been.calledTwice; logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `deleteIdentity`); logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully deleted identity: ${identityName[0]}`); executeCommandSpy.should.have.been.calledWith(ExtensionCommands.REFRESH_WALLETS); }); }); });
the_stack
import { ContractWrappers, ERC20TokenContract, ERC721TokenContract, OrderInfo, OrderStatus, } from '@0x/contract-wrappers'; import { Order, SignedOrder } from '@0x/order-utils'; import { BigNumber } from '@0x/utils'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { DecodedLogArgs, LogWithDecodedArgs, TransactionReceiptWithDecodedLogs } from 'ethereum-types'; import * as _ from 'lodash'; import ora = require('ora'); import { DECIMALS, UNLIMITED_ALLOWANCE_IN_BASE_UNITS } from './constants'; // tslint:disable-next-line:no-var-requires const Table = require('cli-table'); type TableCol = string[] | BigNumber[]; type TableData = string[][] | BigNumber[][]; interface Table { push(data: TableCol): void; toString(): string; } const EMPTY_DATA: TableData = []; const DEFAULT_EVENTS = ['Fill', 'Transfer', 'CancelUpTo', 'Cancel']; const erc721IconRaw = [ ' ____ ', ' .X +. .', '.Xx + -. .', 'XXx++ -.. ', 'XXxx++--.. ', ` XXXxx+++-- `, " XXXxxx' ", ' "" ', ]; const erc721Icon = erc721IconRaw.join('\n'); const defaultSchema = { style: { head: ['green'], }, }; const borderlessSchema = { ...defaultSchema, chars: { top: '', 'top-mid': '', 'top-left': '', 'top-right': '', bottom: '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': '', left: '', 'left-mid': '', mid: '', 'mid-mid': '', right: '', 'right-mid': '', middle: ' ', }, style: { 'padding-left': 1, 'padding-right': 0, head: ['blue'] }, }; const dataSchema = { ...borderlessSchema, style: { 'padding-left': 1, 'padding-right': 0, head: ['yellow'] }, }; export class PrintUtils { private readonly _contractWrappers: ContractWrappers; private readonly _web3Wrapper: Web3Wrapper; private readonly _accounts: { [name: string]: string }; private readonly _tokens: { [name: string]: string }; public static printScenario(header: string): void { const table = new Table({ ...defaultSchema, head: [header], }); PrintUtils.pushAndPrint(table, EMPTY_DATA); } public static printData(header: string, tableData: TableData): void { const table = new Table({ ...dataSchema, head: [header, ''], }); PrintUtils.pushAndPrint(table, tableData); } public static printHeader(header: string): void { const table = new Table({ ...borderlessSchema, style: { 'padding-left': 0, 'padding-right': 0, head: ['blue'] }, head: [header], }); console.log(''); PrintUtils.pushAndPrint(table, EMPTY_DATA); } public static pushAndPrint(table: Table, tableData: TableData): void { for (const col of tableData) { for (const i in col) { if (col[i] === UNLIMITED_ALLOWANCE_IN_BASE_UNITS.toString()) { col[i] = 'MAX_UINT'; } } table.push(col); } console.log(table.toString()); } constructor( web3Wrapper: Web3Wrapper, contractWrappers: ContractWrappers, accounts: { [name: string]: string }, tokens: { [name: string]: string }, ) { this._contractWrappers = contractWrappers; this._web3Wrapper = web3Wrapper; this._accounts = accounts; this._tokens = tokens; this._web3Wrapper.abiDecoder.addABI(contractWrappers.exchange.abi); this._web3Wrapper.abiDecoder.addABI(contractWrappers.weth9.abi); this._web3Wrapper.abiDecoder.addABI(ERC721TokenContract.ABI()); } public printAccounts(): void { const data: string[][] = []; _.forOwn(this._accounts, (address, name) => { const accountName = `${name.charAt(0).toUpperCase()}${name.slice(1)}`; data.push([accountName, address]); }); PrintUtils.printData('Accounts', data); } public async fetchAndPrintContractBalancesAsync(): Promise<void> { const flattenedBalances = []; const flattenedAccounts = Object.keys(this._accounts).map( account => account.charAt(0).toUpperCase() + account.slice(1), ); for (const tokenSymbol in this._tokens) { const balances = [tokenSymbol]; const tokenAddress = this._tokens[tokenSymbol]; for (const account in this._accounts) { const address = this._accounts[account]; const token = new ERC20TokenContract(tokenAddress, this._contractWrappers.getProvider()); const balanceBaseUnits = await token.balanceOf(address).callAsync(); const balance = Web3Wrapper.toUnitAmount(balanceBaseUnits, DECIMALS); balances.push(balance.toString()); } flattenedBalances.push(balances); } const ethBalances = ['ETH']; // ETH for (const account in this._accounts) { const address = this._accounts[account]; const balanceBaseUnits = await this._web3Wrapper.getBalanceInWeiAsync(address); const balance = Web3Wrapper.toUnitAmount(balanceBaseUnits, DECIMALS); ethBalances.push(balance.toString()); } flattenedBalances.push(ethBalances); const table = new Table({ ...dataSchema, head: ['Token', ...flattenedAccounts], }); PrintUtils.printHeader('Balances'); PrintUtils.pushAndPrint(table, flattenedBalances); } public async fetchAndPrintContractAllowancesAsync(): Promise<void> { const erc20ProxyAddress = this._contractWrappers.contractAddresses.erc20Proxy; const flattenedAllowances = []; const flattenedAccounts = Object.keys(this._accounts).map( account => account.charAt(0).toUpperCase() + account.slice(1), ); for (const tokenSymbol in this._tokens) { const allowances = [tokenSymbol]; const tokenAddress = this._tokens[tokenSymbol]; for (const account in this._accounts) { const address = this._accounts[account]; const token = new ERC20TokenContract(tokenAddress, this._contractWrappers.getProvider()); const allowance = await token.allowance(address, erc20ProxyAddress).callAsync(); allowances.push(allowance.toString()); } flattenedAllowances.push(allowances); } const table = new Table({ ...dataSchema, head: ['Token', ...flattenedAccounts], }); PrintUtils.printHeader('Allowances'); PrintUtils.pushAndPrint(table, flattenedAllowances); } public async awaitTransactionMinedSpinnerAsync( message: string, txHash: string, ): Promise<TransactionReceiptWithDecodedLogs> { const spinner = ora(`${message}: ${txHash}`).start(); if (!spinner.isSpinning) { console.log(message, txHash); } try { const receipt = await this._web3Wrapper.awaitTransactionMinedAsync(txHash); receipt.status === 1 ? spinner.stop() : spinner.fail(message); return receipt; } catch (e) { spinner.fail(message); throw e; } } public printTransaction( header: string, txReceipt: TransactionReceiptWithDecodedLogs, data: string[][] = [], eventNames: string[] = DEFAULT_EVENTS, ): void { PrintUtils.printHeader('Transaction'); const headerColor = txReceipt.status === 1 ? 'green' : 'red'; const table = new Table({ ...defaultSchema, head: [header, txReceipt.transactionHash], style: { ...defaultSchema.style, head: [headerColor] }, }); const status = txReceipt.status === 1 ? 'Success' : 'Failure'; const tableData = [...data, ['gasUsed', txReceipt.gasUsed.toString()], ['status', status]]; PrintUtils.pushAndPrint(table, tableData); if (txReceipt.logs.length > 0) { PrintUtils.printHeader('Logs'); for (const log of txReceipt.logs) { const decodedLog = this._web3Wrapper.abiDecoder.tryToDecodeLogOrNoop(log); // tslint:disable:no-unnecessary-type-assertion const event = (log as LogWithDecodedArgs<DecodedLogArgs>).event; if (event && eventNames.includes(event)) { // tslint:disable:no-unnecessary-type-assertion const args = (decodedLog as LogWithDecodedArgs<DecodedLogArgs>).args; const logData = [['contract', log.address], ...Object.entries(args)]; PrintUtils.printData(`${event}`, logData as any); } } } } // tslint:disable-next-line:prefer-function-over-method public printOrderInfos(orderInfos: { [orderName: string]: OrderInfo }): void { const data: string[][] = []; _.forOwn(orderInfos, (value, key) => data.push([key, OrderStatus[value.orderStatus]])); PrintUtils.printData('Order Info', data); } // tslint:disable-next-line:prefer-function-over-method public printOrder(order: Order | SignedOrder): void { PrintUtils.printData('Order', Object.entries(order)); } public async fetchAndPrintERC721OwnerAsync(erc721TokenAddress: string, tokenId: BigNumber): Promise<void> { const flattenedBalances = []; const flattenedAccounts = Object.keys(this._accounts).map( account => account.charAt(0).toUpperCase() + account.slice(1), ); const tokenSymbol = 'ERC721'; const balances = [tokenSymbol]; const token = new ERC721TokenContract(erc721TokenAddress, this._contractWrappers.getProvider()); const owner = await token.ownerOf(tokenId).callAsync(); for (const account in this._accounts) { const address = this._accounts[account]; const balance = owner === address ? erc721Icon : ''; balances.push(balance); } flattenedBalances.push(balances); const table = new Table({ ...dataSchema, head: ['Token', ...flattenedAccounts], }); PrintUtils.printHeader('ERC721 Owner'); PrintUtils.pushAndPrint(table, flattenedBalances); } }
the_stack
declare namespace egret { /** * @private * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * @private * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ interface ISocket { /** * 连接 * @method egret.ISocket#connect * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 连接 * @method egret.ISocket#connect * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ connect(host: string, port: number): void; /** * 连接 * @method egret.ISocket#connect */ connectByUrl(url: string): void; /** * * @param onConnect * @param onClose * @param onSocketData * @param onError * @param thisObject * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * * @param onConnect * @param onClose * @param onSocketData * @param onError * @param thisObject * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ addCallBacks(onConnect: Function, onClose: Function, onSocketData: Function, onError: Function, thisObject: any): void; /** * * @param message * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * * @param message * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ send(message: any): void; /** * * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ close(): void; /** * * @version Egret 4.1.0 * @platform Web,Native * @language en_US */ /** * * @version Egret 4.1.0 * @platform Web,Native * @language zh_CN */ disconnect(): void; } /** * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ let ISocket: { new (): ISocket; }; } declare namespace egret { /** * The egret.WebSocket class enables code to establish a TCP socket connection, for sending and receiving character string or binary data. * To use the methods of the egret.WebSocket class, first use the constructor function new egret.WebSocket to create an egret.WebSocket object. * The socket transmits and receives data in asynchronous mode. * @event egret.Event.CONNECT Successfully connect to the server。 * @event egret.ProgressEvent.SOCKET_DATA Receiving server data。 * @event egret.Event.CLOSE Dispatched when the server closes the connection. * @event egret.ProgressEvent Dispatched when an IO error causes a send or load operation to fail. * @see http://edn.egret.com/cn/docs/page/602 WebSocket * @version Egret 2.4 * @platform Web,Native * @includeExample extension/socket/WebSocket.ts * @language en_US */ /** * egret.WebSocket 类启用代码以建立传输控制协议 (TCP) 套接字连接,用于发送和接收字符串或二进制数据。 * 要使用 egret.WebSocket 类的方法,请先使用构造函数 new egret.WebSocket 创建一个 egret.WebSocket 对象。 * 套接字以异步方式传输和接收数据。 * @event egret.Event.CONNECT 连接服务器成功。 * @event egret.ProgressEvent.SOCKET_DATA 接收服务器数据。 * @event egret.Event.CLOSE 在服务器关闭连接时调度。 * @event egret.IOErrorEvent.IO_ERROR 在出现输入/输出错误并导致发送或加载操作失败时调度。。 * @see http://edn.egret.com/cn/docs/page/602 WebSocket * @version Egret 2.4 * @platform Web,Native * @includeExample extension/socket/WebSocket.ts * @language zh_CN */ class WebSocket extends egret.EventDispatcher { /** * Send and receive data in character string format * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 以字符串格式发送和接收数据 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ static TYPE_STRING: string; /** * Send and receive data in binary format * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 以二进制格式发送和接收数据 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ static TYPE_BINARY: string; /** * @private */ private socket; /** * @private */ private _writeMessage; /** * @private */ private _readMessage; /** * @private */ private _connected; /** * @private */ private _connecting; /** * Create an egret.WebSocket object * This parameter is reserved for later versions. The connection address and port number are imported in the connect function * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 创建一个 egret.WebSocket 对象 * 参数为预留参数,现版本暂不处理,连接地址和端口号在 connect 函数中传入 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ constructor(host?: string, port?: number); /** * Connect the socket to the specified host and port number * @param host Name or IP address of the host to be connected * @param port Port number to be connected * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 将套接字连接到指定的主机和端口 * @param host 要连接到的主机的名称或 IP 地址 * @param port 要连接到的端口号 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ connect(host: string, port: number): void; /** * 根据提供的url连接 * @param url 全地址。如ws://echo.websocket.org:80 */ connectByUrl(url: string): void; /** * Closesocket * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 关闭套接字 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ close(): void; /** * @private * */ private onConnect(); /** * @private * */ private onClose(); /** * @private * */ private onError(); /** * @private * * @param message */ private onSocketData(message); /** * Refresh all data accumulated in the output buffer area of the socket * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 对套接字输出缓冲区中积累的所有数据进行刷新 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ flush(): void; /** * @private */ private _isReadySend; /** * Write data in character string in the socket * @param message The character string to be written in the socket * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 将字符串数据写入套接字 * @param message 要写入套接字的字符串 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ writeUTF(message: string): void; /** * Read a UTF-8 character string from the socket * @returns {string} * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 从套接字读取一个 UTF-8 字符串 * @returns {string} * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ readUTF(): string; /** * @private */ private _readByte; /** * @private */ private _writeByte; /** * @private */ private _bytesWrite; /** * Write a series of bytes from the specified byte array. The writing operation starts from the location expressed by offset. * If the length parameter is ignored, the default length 0 indicates that data is written from offset in the entire buffer area. * If the offset parameter is ignored, data is written in the entire buffer area. * @param bytes The ByteArray object where data is read from * @param offset Zero-based offset in the ByteArray object. From here start performing data writing * @param length Number of bytes to be written Default value 0 indicates data is written in the entire buffer area from the value specified by the offset parameter * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 从指定的字节数组写入一系列字节。写入操作从 offset 指定的位置开始。 * 如果省略了 length 参数,则默认长度 0 将导致该方法从 offset 开始写入整个缓冲区。 * 如果还省略了 offset 参数,则写入整个缓冲区。 * @param bytes 要从中读取数据的 ByteArray 对象 * @param offset ByteArray 对象中从零开始的偏移量,应由此开始执行数据写入 * @param length 要写入的字节数。默认值 0 导致从 offset 参数指定的值开始写入整个缓冲区 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ writeBytes(bytes: ByteArray, offset?: number, length?: number): void; /** * Read data byte number specified by the length parameter from the socket. Read these bytes into the specified byte array starting from the location expressed by offset. * @param bytes The ByteArray object that data is read into * @param offset The offset for data reading starts from this byte array * @param length Byte number to be read Default value 0 indicates reading all available data * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 从套接字读取 length 参数指定的数据字节数。从 offset 所表示的位置开始,将这些字节读入指定的字节数组 * @param bytes 要将数据读入的 ByteArray 对象 * @param offset 数据读取的偏移量应从该字节数组中开始 * @param length 要读取的字节数。默认值 0 导致读取所有可用的数据 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ readBytes(bytes: ByteArray, offset?: number, length?: number): void; /** * Indicates whether the Socket object is connected currently * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 表示此 Socket 对象目前是否已连接 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ readonly connected: boolean; /** * @private */ private _type; /** * Format for sending and receiving data. The default setting is the character string format * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 发送和接收数据的格式,默认是字符串格式 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ type: string; static URI: "ws://" | "wss://"; } } declare namespace egret.web { /** * @private */ class HTML5WebSocket implements ISocket { private socket; constructor(); private onConnect; private onClose; private onSocketData; private onError; private thisObject; addCallBacks(onConnect: Function, onClose: Function, onSocketData: Function, onError: Function, thisObject: any): void; private host; private port; connect(host: string, port?: number): void; connectByUrl(url: string): void; private _bindEvent(); send(message: any): void; close(): void; disconnect(): void; } }
the_stack
import React, { createRef, forwardRef, useState } from 'react'; import { Menu, MenuItem, Typeahead } from '../..'; import { clearTypeahead, clickOrFocusInput, getInitialState, hideMenu, toggleMenu, } from '../../core/Typeahead'; import { findItems, findMenu, findPaginator, getHint, getInput, getItems, getMenu, getTokens, noop, prepareSnapshot, render, screen, userEvent, waitFor, waitForOverlay, } from '../helpers'; import states from '../data'; const ID = 'rbt-id'; const TestComponent = forwardRef((props, ref) => ( <Typeahead id={ID} labelKey="name" onChange={noop} options={states} ref={ref} {...props} /> )); const ControlledTestComponent = (props) => { const [selected, setSelected] = useState(props.selected); return ( <TestComponent {...props} onChange={setSelected} selected={selected} /> ); }; describe('<Typeahead> snapshots', () => { it('checks the snapshot for a single-select typeahead', () => { expect(prepareSnapshot(<TestComponent />)).toMatchSnapshot(); }); it('checks the snapshot for a multi-select typeahead', () => { const snapshot = prepareSnapshot( <TestComponent multiple selected={states.slice(0, 4)} /> ); expect(snapshot).toMatchSnapshot(); }); }); describe('<Typeahead>', () => { it('auto-focuses the typeahead input', async () => { render(<TestComponent autoFocus />); await waitFor(() => { expect(getInput()).toHaveFocus(); }); }); it('sets and unsets the focus state on focus/blur', async () => { render(<TestComponent />); const input = getInput(); expect(input).not.toHaveFocus(); input.focus(); await waitFor(() => { expect(input).toHaveFocus(); }); input.blur(); expect(input).not.toHaveFocus(); }); describe('input focus', () => { afterEach(() => { // The menu should close but the input stays focused. expect(getMenu()).not.toBeInTheDocument(); expect(getInput()).toHaveFocus(); }); it('maintains focus when clicking a menu item', () => { render(<TestComponent />); const input = getInput(); input.focus(); userEvent.click(getItems()[0]); }); it('maintains focus when clicking the clear button', () => { render(<TestComponent clearButton selected={states.slice(0, 1)} />); const input = getInput(); input.focus(); // Click the close button userEvent.click(screen.getByRole('button')); }); }); it('truncates selections when using `defaultSelected`', () => { let selected = states.slice(0, 4); render( <TestComponent defaultSelected={selected}> {(state) => { selected = state.selected; }} </TestComponent> ); expect(selected).toHaveLength(1); }); describe('behaviors when selections are passed in', () => { let selected, selectedText; beforeEach(() => { selected = states.slice(0, 1); selectedText = selected[0].name; }); afterEach(async () => { const input = getInput(); input.focus(); expect(input).toHaveValue(selectedText); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).toHaveTextContent(selectedText); }); it('filters menu options based on `selected` values', () => { render(<TestComponent selected={selected} />); }); it('filters menu options based on `defaultSelected` values', () => { render(<TestComponent defaultSelected={selected} />); }); }); it('uses the `filterBy` prop as a callback to filter results', async () => { const filterBy = jest.fn( (option, props) => option.name.indexOf(props.text) > -1 ); render(<TestComponent filterBy={filterBy} />); const input = getInput(); userEvent.type(input, 'Cali'); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).toHaveTextContent('California'); expect(filterBy).toHaveBeenCalled(); }); it('does not filter options when the menu is closed', () => { const filterBy = jest.fn(); render(<TestComponent filterBy={filterBy} open={false} />); const input = getInput(); userEvent.type(input, 'Cali'); expect(filterBy).not.toHaveBeenCalled(); }); describe('menu visibility behavior', () => { it('shows the menu on initial render', async () => { render(<TestComponent defaultOpen />); expect(await findMenu()).toBeInTheDocument(); }); it('shows the menu when `open` is `true`', async () => { render(<TestComponent open />); expect(await findMenu()).toBeInTheDocument(); }); it('hides the menu when `open` is `false`', () => { render(<TestComponent open={false} />); getInput().focus(); expect(getMenu()).not.toBeInTheDocument(); }); it('shows the menu when the input is focused', async () => { render(<TestComponent />); getInput().focus(); expect(await findMenu()).toBeInTheDocument(); }); it('hides the menu on focus when `minLength=1`', () => { render(<TestComponent minLength={1} />); getInput().focus(); expect(getMenu()).not.toBeInTheDocument(); }); it('shows the menu when there are no results and `allowNew=true`', async () => { render(<TestComponent allowNew options={[]} />); userEvent.type(getInput(), 'xx'); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).toHaveTextContent('New selection: xx'); }); }); it('should disable the input if the component is disabled', () => { render(<TestComponent disabled />); expect(getInput()).toBeDisabled(); }); it('should not highlight disabled options', async () => { const options = [ { name: 'foo' }, { disabled: true, name: 'bar' }, { disabled: true, name: 'boo' }, { name: 'baz' }, { disabled: true, name: 'bro' }, ]; render(<TestComponent options={options} />); getInput().focus(); const items = await findItems(); expect(items[1]).toHaveClass('disabled'); expect(items[2]).toHaveClass('disabled'); expect(items[4]).toHaveClass('disabled'); userEvent.keyboard('{arrowdown}'); expect(items[0]).toHaveClass('active'); userEvent.keyboard('{arrowdown}'); expect(items[3]).toHaveClass('active'); userEvent.keyboard('{arrowup}'); expect(items[0]).toHaveClass('active'); userEvent.keyboard('{arrowup}{arrowup}'); expect(items[3]).toHaveClass('active'); }); describe('pagination behaviors', () => { let maxResults, onPaginate, shownResultsCount; beforeEach(() => { maxResults = 10; shownResultsCount = maxResults; onPaginate = jest.fn((e, shownResults) => { shownResultsCount = shownResults; }); }); it('has a menu item for pagination', async () => { render(<TestComponent maxResults={10} />); getInput().focus(); const paginator = await findPaginator(); expect(paginator).toHaveTextContent('Display additional results...'); expect(paginator).toHaveClass('rbt-menu-pagination-option'); }); it('handles non-string labels', async () => { render( <TestComponent maxResults={10} paginationText={<div>More...</div>} /> ); getInput().focus(); const paginator = await findPaginator(); expect(paginator).toHaveTextContent('More...'); expect(paginator).toHaveAttribute('aria-label', ''); }); it('triggers the pagination item via mouse or keyboard', async () => { render(<TestComponent maxResults={maxResults} onPaginate={onPaginate} />); getInput().focus(); const paginator = await findPaginator(); userEvent.click(paginator); expect(onPaginate).toHaveBeenCalledTimes(1); expect(shownResultsCount).toBe(maxResults * 2); expect(getItems()).toHaveLength(21); userEvent.keyboard('{arrowup}{enter}'); expect(onPaginate).toHaveBeenCalledTimes(2); expect(shownResultsCount).toBe(maxResults * 3); expect(getItems()).toHaveLength(31); }); it('calls `onPaginate` when `labelKey` is a function', async () => { render( <TestComponent labelKey={(o) => o.name} maxResults={maxResults} onPaginate={onPaginate} /> ); getInput().focus(); userEvent.keyboard('{arrowup}{enter}'); await waitFor(() => { expect(onPaginate).toHaveBeenCalledTimes(1); }); expect(shownResultsCount).toBe(maxResults * 2); expect(getItems()).toHaveLength(21); }); it('displays custom pagination text', async () => { const paginationText = 'More Results...'; render(<TestComponent maxResults={10} paginationText={paginationText} />); getInput().focus(); const paginator = await findPaginator(); expect(paginator).toHaveTextContent(paginationText); }); it('does not have a menu item for pagination', async () => { render(<TestComponent paginate={false} />); getInput().focus(); const paginator = await findPaginator(); expect(paginator).not.toHaveTextContent('Display additional results...'); expect(paginator).not.toHaveClass('rbt-menu-pagination-option'); }); it('resets the shown results when the input value changes', async () => { maxResults = 5; render(<TestComponent maxResults={maxResults} onPaginate={onPaginate} />); const input = getInput(); userEvent.type(input, 'ar'); userEvent.keyboard('{arrowup}{enter}'); await waitFor(() => { expect(onPaginate).toHaveBeenCalledTimes(1); }); expect(shownResultsCount).toBe(maxResults * 2); userEvent.clear(input); userEvent.type(input, 'or'); userEvent.keyboard('{arrowup}{enter}'); await waitFor(() => { expect(onPaginate).toHaveBeenCalledTimes(2); }); expect(shownResultsCount).toBe(maxResults * 2); }); it('updates the active item after pagination', async () => { render(<TestComponent maxResults={maxResults} />); getInput().focus(); userEvent.keyboard('{arrowup}{enter}'); const items = await findItems(); expect(items).toHaveLength(21); expect(items[maxResults]).toHaveClass('active'); }); }); describe('when `maxResults` is set', () => { const maxResults = 5; it('should limit results when `paginate=true`', async () => { render(<TestComponent maxResults={maxResults} />); getInput().focus(); // When `paginate` is true, there will be a pagination menu item in // addition to the shown results. const items = await findItems(); expect(items).toHaveLength(maxResults + 1); }); it('should limit results when `paginate=false`', async () => { render(<TestComponent maxResults={maxResults} paginate={false} />); getInput().focus(); const items = await findItems(); expect(items).toHaveLength(maxResults); }); }); it('renders a large input', () => { render(<TestComponent size="large" />); expect(getInput()).toHaveClass('form-control-lg'); }); it('renders a small input', () => { render(<TestComponent size="small" />); expect(getInput()).toHaveClass('form-control-sm'); }); it('renders a loading indicator', () => { render(<TestComponent isLoading />); expect(screen.queryByRole('status')).toBeInTheDocument(); }); describe('updates when re-rendering with new props', () => { it('acts as a controlled input in single-select mode', () => { let selected = []; const children = (state) => { selected = state.selected; }; const selected1 = states.slice(0, 1); const selected2 = states.slice(1, 2); // Pass in new selection const { rerender } = render( <TestComponent selected={selected1}>{children}</TestComponent> ); expect(selected).toEqual(selected1); expect(getInput()).toHaveValue(selected1[0].name); // Pass in another new selection rerender(<TestComponent selected={selected2}>{children}</TestComponent>); expect(selected).toEqual(selected2); expect(getInput()).toHaveValue(selected2[0].name); // Clear the selections. rerender(<TestComponent selected={[]}>{children}</TestComponent>); expect(selected).toEqual([]); expect(getInput()).toHaveValue(''); }); it('acts as a controlled input in multi-select mode', () => { const { container, rerender } = render( <TestComponent multiple selected={states.slice(0, 4)} /> ); const tokens = getTokens(container); const input = getInput(); expect(tokens).toHaveLength(4); expect(input).toHaveValue(''); // Clear the selections. rerender(<TestComponent multiple selected={[]} />); expect(tokens).toHaveLength(0); expect(input).toHaveValue(''); }); it('updates the selections and input value in single-select mode', async () => { let selected = []; render( <ControlledTestComponent selected={states.slice(0, 1)}> {(state) => { selected = state.selected; }} </ControlledTestComponent> ); const input = getInput(); expect(selected).toHaveLength(1); expect(input).toHaveValue('Alabama'); // Delete the last character. input.focus(); userEvent.keyboard('{backspace}'); // Text entry should clear the selection and keep the partial entry. await waitFor(() => { expect(selected).toHaveLength(0); }); expect(input).toHaveValue('Alabam'); }); }); describe('`highlightOnlyResult` behavior', () => { let onChange, selected; beforeEach(() => { onChange = jest.fn((s) => (selected = [s])); selected = []; }); it('does not highlight the only result', async () => { render(<TestComponent onChange={onChange} />); const input = getInput(); userEvent.type(input, 'Alab'); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).not.toHaveClass('active'); userEvent.keyboard('{enter}'); expect(selected).toHaveLength(0); expect(onChange).toHaveBeenCalledTimes(0); }); it('highlights the only result', async () => { render(<TestComponent highlightOnlyResult onChange={onChange} />); const input = getInput(); userEvent.type(input, 'Alab'); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).toHaveClass('active'); userEvent.keyboard('{enter}'); expect(selected).toHaveLength(1); expect(onChange).toHaveBeenCalledTimes(1); }); it('does not highlight the only result when `allowNew=true`', async () => { render( <TestComponent allowNew highlightOnlyResult onChange={onChange} /> ); const input = getInput(); userEvent.type(input, 'qqq'); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).not.toHaveClass('active'); userEvent.keyboard('{enter}'); expect(selected).toHaveLength(0); expect(onChange).toHaveBeenCalledTimes(0); }); it('does not highlight or select a disabled result', async () => { render( <TestComponent highlightOnlyResult onChange={onChange} options={[ { name: 'foo' }, { disabled: true, name: 'bar' }, { disabled: true, name: 'boo' }, { name: 'baz' }, ]} /> ); const input = getInput(); userEvent.type(input, 'bar'); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).not.toHaveClass('active'); userEvent.keyboard('{enter}'); expect(selected).toHaveLength(0); expect(onChange).toHaveBeenCalledTimes(0); }); }); it('displays the active item value in the input', async () => { render(<TestComponent />); const input = getInput(); input.focus(); userEvent.keyboard('{arrowdown}'); await waitFor(() => { expect(input).toHaveValue('Alabama'); }); }); it('applies custom styles to the top-level container', () => { const { container } = render( <TestComponent style={{ display: 'inline-flex' }} /> ); expect(container.firstChild).toHaveStyle('display: inline-flex'); }); describe('input props', () => { let input, inputProps; beforeEach(() => { inputProps = { autoComplete: 'nope', className: 'input-classname', id: 'input-id', name: 'input-name', onClick: jest.fn(), tabIndex: '5', type: 'number', }; }); afterEach(async () => { userEvent.click(input); await waitFor(() => { expect(inputProps.onClick).toHaveBeenCalledTimes(1); }); expect(input).toHaveAttribute('autocomplete', inputProps.autoComplete); expect(input).toHaveClass(inputProps.className); expect(input).toHaveAttribute('id', inputProps.id); expect(input).toHaveAttribute('name', inputProps.name); expect(input).toHaveAttribute('tabIndex', inputProps.tabIndex); expect(input).toHaveAttribute('type', inputProps.type); }); it('applies the input props single-select mode', () => { render(<TestComponent inputProps={inputProps} />); input = getInput(); }); it('applies the input props in multi-select mode', () => { render( <TestComponent inputProps={inputProps} multiple selected={states.slice(0, 1)} /> ); input = screen.getByRole('spinbutton'); const token = screen.getByRole('button').parentElement; expect(token).toHaveAttribute('tabIndex', inputProps.tabIndex); }); }); it('calls `onBlur`', async () => { const onBlur = jest.fn(); render(<TestComponent onBlur={onBlur} />); const input = getInput(); userEvent.click(input); input.blur(); await waitFor(() => { expect(onBlur).toHaveBeenCalledTimes(1); }); }); it('calls `onFocus`', async () => { const onFocus = jest.fn(); render(<TestComponent onFocus={onFocus} />); userEvent.click(getInput()); await waitFor(() => { expect(onFocus).toHaveBeenCalledTimes(1); }); }); it('calls `onKeyDown`', async () => { const onKeyDown = jest.fn(); render(<TestComponent onKeyDown={onKeyDown} />); userEvent.click(getInput()); userEvent.keyboard('{enter}'); await waitFor(() => { expect(onKeyDown).toHaveBeenCalledTimes(1); }); }); it('calls `onMenuToggle`', () => { const onMenuToggle = jest.fn(); render(<TestComponent onMenuToggle={onMenuToggle} />); const input = getInput(); expect(onMenuToggle).toHaveBeenCalledTimes(0); input.focus(); expect(onMenuToggle).toHaveBeenCalledTimes(1); // Shouldn't be called again if not hidden first. input.focus(); expect(onMenuToggle).toHaveBeenCalledTimes(1); userEvent.keyboard('{esc}'); expect(onMenuToggle).toHaveBeenCalledTimes(2); }); describe('hint behavior', () => { it('hides and shows the hint in the single-select case', async () => { const { container } = render(<TestComponent />); const input = getInput(); const hint = getHint(container); userEvent.type(input, 'Ala'); await waitFor(() => { expect(input).toHaveFocus(); }); expect(hint).toHaveValue('Alabama'); input.blur(); expect(input).not.toHaveFocus(); expect(hint).toHaveValue(''); }); it('hides and shows the hint in the multi-select case', async () => { const { container } = render(<TestComponent multiple />); const input = getInput(); const hint = getHint(container); userEvent.type(input, 'Ala'); await waitFor(() => { expect(input).toHaveFocus(); }); expect(hint).toHaveValue('Alabama'); input.blur(); expect(input).not.toHaveFocus(); expect(hint).toHaveValue(''); }); it('does not display a hint if the menu is hidden', async () => { const { container } = render(<TestComponent />); const input = getInput(); const hint = getHint(container); userEvent.type(input, 'Ala'); // When focused, the typeahead should show the menu and hint text. expect(getMenu()).toBeInTheDocument(); expect(hint).toHaveValue('Alabama'); userEvent.keyboard('{esc}'); // Expect the input to remain focused, but the menu and hint to be hidden. expect(input).toHaveFocus(); expect(getMenu()).not.toBeInTheDocument(); expect(hint).toHaveValue(''); }); }); describe('behavior when selecting the hinted result', () => { let key, onChange, onKeyDown; beforeEach(() => { key = 0; onChange = jest.fn(); onKeyDown = jest.fn((e) => (key = e.key)); }); it('should select the hinted result on tab keydown', () => { render(<TestComponent onChange={onChange} onKeyDown={onKeyDown} />); userEvent.type(getInput(), 'Ala'); userEvent.tab(); expect(key).toBe('Tab'); expect(onChange).toHaveBeenCalledTimes(1); }); it('should select the hinted result on right arrow keydown', () => { render(<TestComponent onChange={onChange} onKeyDown={onKeyDown} />); const input = getInput(); userEvent.type(input, 'Ala'); userEvent.keyboard('{arrowright}'); expect(key).toBe('ArrowRight'); expect(onChange).toHaveBeenCalledTimes(1); }); it( 'should not select the hinted result on right arrow keydown unless ' + 'the cursor is at the end of the input value', async () => { render(<TestComponent onChange={onChange} onKeyDown={onKeyDown} />); const input = getInput(); userEvent.type(input, 'Ala'); await waitForOverlay(); input.selectionStart = 1; userEvent.keyboard('{arrowright}'); expect(key).toBe('ArrowRight'); expect(onChange).toHaveBeenCalledTimes(0); } ); it('should not select the hinted result on enter keydown', async () => { render(<TestComponent onChange={onChange} onKeyDown={onKeyDown} />); const input = getInput(); userEvent.type(input, 'Ala'); await waitForOverlay(); userEvent.keyboard('{enter}'); expect(key).toBe('Enter'); expect(onChange).toHaveBeenCalledTimes(0); }); it('should select the hinted result on enter keydown', () => { render( <TestComponent inputProps={{ shouldSelectHint: (shouldSelectHint, e) => { return e.key === 'Enter' || shouldSelectHint; }, }} onChange={onChange} onKeyDown={onKeyDown} /> ); const input = getInput(); userEvent.type(input, 'Ala'); userEvent.keyboard('{enter}'); expect(key).toBe('Enter'); expect(onChange).toHaveBeenCalledTimes(1); }); }); describe('keydown behaviors with active item', () => { let onChange, onKeyDown; beforeEach(() => { onChange = jest.fn(); onKeyDown = jest.fn(); }); it('selects the active item when pressing return', () => { render(<TestComponent onChange={onChange} onKeyDown={onKeyDown} />); getInput().focus(); userEvent.keyboard('{arrowdown}{enter}'); expect(onChange).toHaveBeenCalledTimes(1); expect(onKeyDown).toHaveBeenCalledTimes(2); }); it('does not select the active item when the menu is closed', () => { render( <TestComponent onChange={onChange} onKeyDown={onKeyDown} open={false} /> ); getInput().focus(); userEvent.keyboard('{arrowdown}{enter}'); expect(onChange).toHaveBeenCalledTimes(0); expect(onKeyDown).toHaveBeenCalledTimes(2); }); }); it('prevents form submission when the menu is open', () => { const onSubmit = jest.fn(); render( <form onSubmit={onSubmit}> <TestComponent /> <button type="submit">submit</button> </form> ); const input = getInput(); input.focus(); userEvent.keyboard('{enter}'); expect(onSubmit).toHaveBeenCalledTimes(0); userEvent.keyboard('{esc}{enter}'); expect(onSubmit).toHaveBeenCalledTimes(1); }); it('hides the menu when tabbing out of the input', () => { render(<TestComponent />); getInput().focus(); expect(getMenu()).toBeInTheDocument(); userEvent.tab(); expect(getMenu()).not.toBeInTheDocument(); }); it('calls the keydown handler when a key is pressed', async () => { const onKeyDown = jest.fn(); render(<TestComponent onKeyDown={onKeyDown} />); userEvent.type(getInput(), 'foo'); await waitFor(() => { expect(onKeyDown).toHaveBeenCalledTimes(3); }); }); describe('accessibility attributes', () => { it('adds an id to the menu for accessibility', async () => { const { rerender } = render(<TestComponent />); const input = getInput(); expect(input).not.toHaveAttribute('aria-owns'); input.focus(); const menu = await findMenu(); expect(menu).toHaveAttribute('id', ID); expect(input).toHaveAttribute('aria-owns', ID); const id = 'my-id'; rerender(<TestComponent id={id} />); expect(menu).toHaveAttribute('id', id); expect(input).toHaveAttribute('aria-owns', id); }); it('sets aria attributes for single-selection', async () => { render(<TestComponent id="my-id" />); const input = getInput(); expect(input).toHaveAttribute('aria-autocomplete', 'both'); expect(input).toHaveAttribute('aria-expanded', 'false'); expect(input).not.toHaveAttribute('aria-activedescendant'); input.focus(); userEvent.keyboard('{arrowdown}'); await waitFor(() => { expect(input).toHaveAttribute('aria-expanded', 'true'); }); expect(input).toHaveAttribute('aria-activedescendant', 'my-id-item-0'); }); it('sets aria attributes for multi-selection', () => { render(<TestComponent multiple />); const input = getInput(); expect(input).toHaveAttribute('aria-autocomplete', 'list'); expect(input).not.toHaveAttribute('aria-expanded'); }); it('sets menu item attributes', async () => { render(<TestComponent id="my-id" />); getInput().focus(); const items = await findItems(); const item = items[0]; expect(item).toHaveAttribute('aria-label', 'Alabama'); expect(item).toHaveAttribute('aria-selected', 'false'); expect(item).toHaveClass('dropdown-item'); userEvent.keyboard('{arrowdown}'); expect(item).toHaveAttribute('aria-selected', 'true'); }); }); describe('<Typeahead> multi-select', () => { it('displays and removes selections', () => { render(<TestComponent multiple selected={states.slice(0, 3)} />); // Use close button as a proxy for the token. const closeButtons = screen.getAllByRole('button'); expect(closeButtons).toHaveLength(3); userEvent.click(closeButtons[0]); expect(screen.getAllByRole('button')).toHaveLength(2); }); it('adds selections', () => { render(<TestComponent multiple />); const input = getInput(); input.focus(); userEvent.keyboard('{arrowdown}{enter}'); expect(screen.getAllByRole('button')).toHaveLength(1); expect(input).toHaveValue(''); }); }); it('opens the menu when the up or down arrow keys are pressed', async () => { render(<TestComponent />); const input = getInput(); input.focus(); expect(await findMenu()).toBeInTheDocument(); userEvent.keyboard('{esc}'); expect(getMenu()).not.toBeInTheDocument(); userEvent.keyboard('{arrowdown}'); expect(await findMenu()).toBeInTheDocument(); userEvent.keyboard('{esc}'); expect(getMenu()).not.toBeInTheDocument(); userEvent.keyboard('{arrowup}'); expect(await findMenu()).toBeInTheDocument(); }); it('renders a custom input', () => { const renderInput = jest.fn(); render(<TestComponent renderInput={renderInput} />); expect(renderInput).toHaveBeenCalled(); }); it('renders custom content in the menu items', async () => { render( <TestComponent renderMenuItemChildren={ // Render the capital instead of the state name. (o) => o.capital } /> ); getInput().focus(); const items = await findItems(); expect(items[0]).toHaveTextContent('Montgomery'); }); it('renders custom tokens', () => { render( <TestComponent multiple renderToken={(option, props, idx) => ( <div className="custom-token" key={idx}> {option.capital} </div> )} selected={states.slice(0, 1)} /> ); expect(screen.getByText('Montgomery')).toHaveClass('custom-token'); }); it('renders children', () => { const text = 'This is the child'; render( <TestComponent> <div data-testid="children">{text}</div> </TestComponent> ); const children = screen.queryByTestId('children'); expect(children).toBeInTheDocument(); expect(children).toHaveTextContent(text); }); it('renders children via a render function', async () => { render( <TestComponent> {(props) => ( <div data-testid="children"> The menu {props.isMenuShown ? 'is' : 'is not'} open </div> )} </TestComponent> ); const children = screen.getByTestId('children'); expect(children).toHaveTextContent('The menu is not open'); getInput().focus(); await waitFor(() => { expect(children).toHaveTextContent('The menu is open'); }); }); describe('validation states', () => { it('renders with validation classnames in single-select mode', () => { const { rerender } = render(<TestComponent />); const input = getInput(); expect(input).not.toHaveClass('is-invalid'); expect(input).not.toHaveClass('is-valid'); rerender(<TestComponent isInvalid isValid />); expect(input).toHaveClass('is-invalid'); expect(input).toHaveClass('is-valid'); }); it('renders with validation classnames in multi-select mode', () => { const { container, rerender } = render(<TestComponent multiple />); const formControl = container.getElementsByClassName('form-control')[0]; expect(formControl).not.toHaveClass('is-invalid'); expect(formControl).not.toHaveClass('is-valid'); rerender(<TestComponent isInvalid isValid multiple />); expect(formControl).toHaveClass('is-invalid'); expect(formControl).toHaveClass('is-valid'); }); }); describe('allowNew behavior', () => { let emptyLabel, newSelectionPrefix, value; beforeEach(() => { emptyLabel = 'No results...'; newSelectionPrefix = 'New selection: '; value = 'xxx'; }); it('omits the custom option when `allowNew` is set to `false`', async () => { render(<TestComponent emptyLabel={emptyLabel} />); const input = getInput(); userEvent.type(input, value); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).toHaveTextContent(emptyLabel); }); it('adds the custom option when `allowNew` is set to `true`', async () => { let selected; render( <TestComponent allowNew emptyLabel={emptyLabel} newSelectionPrefix={newSelectionPrefix} onChange={(s) => { selected = s; }} /> ); const input = getInput(); userEvent.type(input, value); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).toHaveTextContent(`${newSelectionPrefix}${value}`); userEvent.click(items[0]); expect(selected[0].id).toContain('new-id-'); }); it('omits the custom option when there is an exact text match', async () => { value = 'North Carolina'; render(<TestComponent allowNew />); const input = getInput(); userEvent.type(input, value); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).toHaveTextContent(value); }); it('adds a custom option when `allowNew` returns true', async () => { value = 'North Carolina'; render( <TestComponent allowNew={() => true} newSelectionPrefix={newSelectionPrefix} /> ); const input = getInput(); userEvent.type(input, value); const items = await findItems(); expect(items).toHaveLength(2); expect(items[0]).toHaveTextContent(value); expect(items[1]).toHaveTextContent(`${newSelectionPrefix}${value}`); }); it('omits new option when `allowNew` returns false', async () => { render(<TestComponent allowNew={() => false} emptyLabel={emptyLabel} />); const input = getInput(); userEvent.type(input, value); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).toHaveTextContent(emptyLabel); }); it('handles custom options when `labelKey` is a function', async () => { render( <TestComponent allowNew labelKey={(o) => o.name} newSelectionPrefix={newSelectionPrefix} /> ); const input = getInput(); userEvent.type(input, value); const items = await findItems(); expect(items).toHaveLength(1); expect(items[0]).toHaveTextContent(`${newSelectionPrefix}${value}`); }); }); }); describe('<Typeahead> Public Methods', () => { it('exposes the typeahead instance and public methods', () => { const ref = createRef(); render(<TestComponent ref={ref} />); ['clear', 'blur', 'focus', 'getInput', 'hideMenu', 'toggleMenu'].forEach( (method) => { expect(typeof ref.current[method]).toBe('function'); } ); }); it('calls the public `focus` and `blur` methods', () => { const ref = createRef(); render(<TestComponent ref={ref} />); const input = getInput(); ref.current.focus(); expect(input).toHaveFocus(); ref.current.blur(); expect(input).not.toHaveFocus(); }); it('calls the public `clear` method', () => { const ref = createRef(); const { container } = render( <TestComponent multiple ref={ref} selected={states.slice(0, 3)} /> ); const input = getInput(); userEvent.type(input, 'foo'); const tokens = container.getElementsByClassName('rbt-token'); expect(tokens).toHaveLength(3); expect(input).toHaveValue('foo'); ref.current.clear(); expect(tokens).toHaveLength(0); expect(input).toHaveValue(''); }); it('calls the public `getInput` method', () => { const ref = createRef(); render(<TestComponent ref={ref} />); expect(ref.current.getInput()).toEqual(getInput()); }); it('calls the public `hideMenu` method', async () => { const ref = createRef(); render(<TestComponent ref={ref} />); getInput().focus(); const menu = await findMenu(); expect(menu).toBeInTheDocument(); ref.current.hideMenu(); expect(menu).not.toBeInTheDocument(); }); it('calls the public `toggleMenu` method', () => { const ref = createRef(); render(<TestComponent ref={ref} />); expect(getMenu()).not.toBeInTheDocument(); ref.current.toggleMenu(); expect(getMenu()).toBeInTheDocument(); ref.current.toggleMenu(); expect(getMenu()).not.toBeInTheDocument(); }); it('clears the typeahead after a selection', async () => { const ref = createRef(); const onChange = jest.fn(() => { ref.current.clear(); }); render(<TestComponent onChange={onChange} ref={ref} />); const input = getInput(); input.focus(); const items = await findItems(); userEvent.click(items[0]); expect(onChange).toHaveBeenCalledTimes(1); expect(input).toHaveValue(''); }); }); describe('<Typeahead> `change` events', () => { let onChange, onInputChange; beforeEach(() => { onChange = jest.fn(); onInputChange = jest.fn(); }); it('calls `onChange` when a menu item is clicked', async () => { render(<TestComponent onInputChange={onInputChange} onChange={onChange} />); getInput().focus(); const items = await findItems(); userEvent.click(items[0]); expect(onChange).toHaveBeenCalledTimes(1); expect(onInputChange).toHaveBeenCalledTimes(0); }); it('calls `onChange` when a menu item is selected via keyboard', () => { render(<TestComponent onInputChange={onInputChange} onChange={onChange} />); getInput().focus(); userEvent.keyboard('{arrowdown}{enter}'); expect(onChange).toHaveBeenCalledTimes(1); expect(onInputChange).toHaveBeenCalledTimes(0); }); it('handles clear button clicks in single-select mode', () => { let event, value; onInputChange = jest.fn((v, e) => { value = v; event = e; }); render( <TestComponent clearButton onChange={onChange} onInputChange={onInputChange} selected={states.slice(0, 1)} /> ); userEvent.click(screen.getByRole('button')); expect(onChange).toHaveBeenCalledTimes(1); expect(onInputChange).toHaveBeenCalledTimes(1); expect(value).toBe(''); expect(event).toBeDefined(); }); it('handles clear button clicks in multi-select mode', () => { let selected; onInputChange = jest.fn(); onChange = jest.fn((s) => { selected = s; }); render( <TestComponent clearButton multiple onChange={onChange} onInputChange={onInputChange} selected={states.slice(0, 2)} /> ); userEvent.click(screen.getByRole('button', { name: 'Clear' })); expect(onChange).toHaveBeenCalledTimes(1); expect(onInputChange).toHaveBeenCalledTimes(0); expect(selected).toHaveLength(0); }); it('handles clear button clicks in multi-select mode with initial input', () => { let event, selected, value; onInputChange = jest.fn((v, e) => { value = v; event = e; }); onChange = jest.fn((s) => { selected = s; }); // Test that any text in the input also gets cleared. render( <TestComponent clearButton defaultInputValue="test" multiple onChange={onChange} onInputChange={onInputChange} selected={states.slice(0, 2)} /> ); userEvent.click(screen.getByRole('button', { name: 'Clear' })); expect(onChange).toHaveBeenCalledTimes(1); expect(onInputChange).toHaveBeenCalledTimes(1); expect(value).toBe(''); expect(event).toBeDefined(); expect(selected).toHaveLength(0); }); it('calls `onInputChange` when text is entered in the input', async () => { render(<TestComponent onInputChange={onInputChange} />); const input = getInput(); userEvent.type(input, 'z'); await waitFor(() => { expect(onInputChange).toHaveBeenCalledTimes(1); }); }); it('`onInputChange` receives an event as the second param', async () => { let event; render(<TestComponent onInputChange={(text, e) => (event = e)} />); const input = getInput(); userEvent.type(input, 'z'); await waitFor(() => { expect(event).toBeDefined(); }); }); it('calls `onChange` when there is a selection and text is entered', async () => { const selected = states.slice(0, 1); render( <TestComponent onChange={onChange} onInputChange={onInputChange} selected={selected} /> ); const input = getInput(); userEvent.type(input, 'z'); await waitFor(() => { expect(onChange).toHaveBeenCalledTimes(1); }); expect(onInputChange).toHaveBeenCalledTimes(1); }); it('does not call either when selections are updated via props', () => { const selected = states.slice(0, 1); const { rerender } = render( <TestComponent onChange={onChange} onInputChange={onInputChange} selected={[]} /> ); expect(onChange).toHaveBeenCalledTimes(0); expect(onInputChange).toHaveBeenCalledTimes(0); rerender( <TestComponent onChange={onChange} onInputChange={onInputChange} selected={selected} /> ); expect(onChange).toHaveBeenCalledTimes(0); expect(onInputChange).toHaveBeenCalledTimes(0); }); it('does not call either when `clear()` is called externally', () => { const ref = createRef(); const selected = states.slice(0, 1); render( <TestComponent defaultSelected={selected} ref={ref} onChange={onChange} onInputChange={onInputChange} /> ); expect(getInput()).toHaveValue(selected[0].name); ref.current.clear(); expect(getInput()).toHaveValue(''); expect(onChange).toHaveBeenCalledTimes(0); expect(onInputChange).toHaveBeenCalledTimes(0); }); }); describe('<Typeahead> input value behaviors', () => { let defaultInputValue, defaultSelected, selected; beforeEach(() => { defaultInputValue = 'This is a default value'; defaultSelected = states.slice(0, 1); selected = states.slice(0, 1); }); it("doesn't set a value when there is no default value or selection", () => { render(<TestComponent selected={[]} />); expect(getInput()).toHaveValue(''); }); it('sets an input value based on the `selected` value', () => { render(<TestComponent selected={selected} />); expect(getInput()).toHaveValue(selected[0].name); }); it('sets a default initial input value', () => { render(<TestComponent defaultInputValue={defaultInputValue} />); expect(getInput()).toHaveValue(defaultInputValue); }); it('sets an input value based on the `defaultSelected` value', () => { render(<TestComponent defaultSelected={defaultSelected} />); expect(getInput()).toHaveValue(defaultSelected[0].name); }); it('overrides the default input value if there is a selection', () => { render( <TestComponent defaultInputValue={defaultInputValue} selected={selected} /> ); expect(getInput()).toHaveValue(selected[0].name); }); }); describe('<Typeahead> with clear button', () => { it('does not display a clear button', () => { render(<TestComponent clearButton selected={[]} />); expect(screen.queryByRole('button')).not.toBeInTheDocument(); }); it('displays a clear button', () => { render(<TestComponent clearButton selected={states.slice(0, 1)} />); expect(screen.queryByRole('button')).toBeInTheDocument(); }); }); /** * Some basic tests for the custom menu-rendering use-case. * Helps ensure that the context-related logic doesn't break. */ describe('<Typeahead> with custom menu', () => { const renderMenu = ( results, { newSelectionPrefix, paginationText, renderMenuItemChildren, ...menuProps } ) => ( <Menu {...menuProps}> {/* Use `slice` to avoid mutating the original array */} {results .slice() .reverse() .map((r, index) => ( <MenuItem key={r.name} option={r} position={index}> {r.name} </MenuItem> ))} </Menu> ); it('renders the custom menu', async () => { render(<TestComponent renderMenu={renderMenu} />); getInput().focus(); const items = await findItems(); expect(items[0]).toHaveTextContent('Wyoming'); }); it('shows the correct hint', async () => { const { container } = render(<TestComponent renderMenu={renderMenu} />); const hint = getHint(container); userEvent.type(getInput(), 'u'); const items = await findItems(); expect(items[0]).toHaveTextContent('Utah'); expect(hint).toHaveValue('utah'); }); it('selects the correct option', async () => { const onChange = jest.fn(); render(<TestComponent onChange={onChange} renderMenu={renderMenu} />); const input = getInput(); input.focus(); userEvent.keyboard('{arrowdown}'); const items = await findItems(); expect(items[0]).toHaveTextContent('Wyoming'); expect(items[0]).toHaveClass('active'); userEvent.keyboard('{enter}'); expect(onChange).toHaveBeenCalledTimes(1); expect(input).toHaveValue('Wyoming'); }); // Integration test to ensure that active index updating works correctly when // reshuffling the result set. it('correctly handles disabled options', async () => { const options = states.map((state) => { return state.name === 'Wyoming' ? { ...state, disabled: true } : state; }); render(<TestComponent options={options} renderMenu={renderMenu} />); getInput().focus(); userEvent.keyboard('{arrowdown}'); // Keying down should skip over the first option const items = await findItems(); expect(items[1]).toHaveClass('active'); expect(items[1]).toHaveTextContent('Wisconsin'); }); }); describe('State modifiers', () => { const defaultState = { activeIndex: -1, activeItem: undefined, initialItem: undefined, isFocused: false, selected: [], showMenu: false, text: '', }; it('calls the clearTypeahead modifier', () => { const props = { defaultOpen: false, defaultSelected: [], maxResults: 10, }; const state = { isFocused: true, }; expect(clearTypeahead(state, props)).toEqual({ ...defaultState, isFocused: true, shownResults: 10, }); }); it('calls the clickOrFocusInput modifier', () => { const state = { isFocused: false, showMenu: false, }; expect(clickOrFocusInput(state)).toEqual({ isFocused: true, showMenu: true, }); }); it('calls the getInitialState modifier', () => { expect( getInitialState({ defaultInputValue: 'foo', defaultOpen: false, defaultSelected: [], maxResults: 10, }) ).toEqual({ ...defaultState, shownResults: 10, text: 'foo', }); expect( getInitialState({ defaultInputValue: 'foo', defaultOpen: true, defaultSelected: ['bar', 'foo'], maxResults: 10, }) ).toEqual({ ...defaultState, selected: ['bar'], showMenu: true, shownResults: 10, text: 'bar', }); }); it('calls the hideMenu modifier', () => { const props = { defaultSelected: [], maxResults: 10, }; expect(hideMenu({}, props)).toEqual({ activeIndex: -1, activeItem: undefined, initialItem: undefined, showMenu: false, shownResults: props.maxResults, }); }); it('calls the toggleMenu modifier', () => { const props = { defaultSelected: [], maxResults: 10, }; expect(toggleMenu({ showMenu: false })).toEqual({ showMenu: true, }); expect(toggleMenu({ showMenu: true }, props)).toEqual({ activeIndex: -1, activeItem: undefined, initialItem: undefined, showMenu: false, shownResults: props.maxResults, }); }); });
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * A config defined for a single managed instance that belongs to an instance group manager. It preserves the instance name * across instance group manager operations and can define stateful disks or metadata that are unique to the instance. * * To get more information about PerInstanceConfig, see: * * * [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/instanceGroupManagers) * * How-to Guides * * [Official Documentation](https://cloud.google.com/compute/docs/instance-groups/stateful-migs#per-instance_configs) * * ## Example Usage * * ## Import * * PerInstanceConfig can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:compute/perInstanceConfig:PerInstanceConfig default projects/{{project}}/zones/{{zone}}/instanceGroupManagers/{{instance_group_manager}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/perInstanceConfig:PerInstanceConfig default {{project}}/{{zone}}/{{instance_group_manager}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/perInstanceConfig:PerInstanceConfig default {{zone}}/{{instance_group_manager}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/perInstanceConfig:PerInstanceConfig default {{instance_group_manager}}/{{name}} * ``` */ export class PerInstanceConfig extends pulumi.CustomResource { /** * Get an existing PerInstanceConfig 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?: PerInstanceConfigState, opts?: pulumi.CustomResourceOptions): PerInstanceConfig { return new PerInstanceConfig(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:compute/perInstanceConfig:PerInstanceConfig'; /** * Returns true if the given object is an instance of PerInstanceConfig. 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 PerInstanceConfig { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === PerInstanceConfig.__pulumiType; } /** * The instance group manager this instance config is part of. */ public readonly instanceGroupManager!: pulumi.Output<string>; /** * The minimal action to perform on the instance during an update. * Default is `NONE`. Possible values are: * * REPLACE * * RESTART * * REFRESH * * NONE */ public readonly minimalAction!: pulumi.Output<string | undefined>; /** * The most disruptive action to perform on the instance during an update. * Default is `REPLACE`. Possible values are: * * REPLACE * * RESTART * * REFRESH * * NONE */ public readonly mostDisruptiveAllowedAction!: pulumi.Output<string | undefined>; /** * The name for this per-instance config and its corresponding instance. */ public readonly name!: pulumi.Output<string>; /** * The preserved state for this instance. * Structure is documented below. */ public readonly preservedState!: pulumi.Output<outputs.compute.PerInstanceConfigPreservedState | undefined>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * When true, deleting this config will immediately remove any specified state from the underlying instance. * When false, deleting this config will *not* immediately remove any state from the underlying instance. * State will be removed on the next instance recreation or update. */ public readonly removeInstanceStateOnDestroy!: pulumi.Output<boolean | undefined>; /** * Zone where the containing instance group manager is located */ public readonly zone!: pulumi.Output<string | undefined>; /** * Create a PerInstanceConfig 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: PerInstanceConfigArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: PerInstanceConfigArgs | PerInstanceConfigState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as PerInstanceConfigState | undefined; inputs["instanceGroupManager"] = state ? state.instanceGroupManager : undefined; inputs["minimalAction"] = state ? state.minimalAction : undefined; inputs["mostDisruptiveAllowedAction"] = state ? state.mostDisruptiveAllowedAction : undefined; inputs["name"] = state ? state.name : undefined; inputs["preservedState"] = state ? state.preservedState : undefined; inputs["project"] = state ? state.project : undefined; inputs["removeInstanceStateOnDestroy"] = state ? state.removeInstanceStateOnDestroy : undefined; inputs["zone"] = state ? state.zone : undefined; } else { const args = argsOrState as PerInstanceConfigArgs | undefined; if ((!args || args.instanceGroupManager === undefined) && !opts.urn) { throw new Error("Missing required property 'instanceGroupManager'"); } inputs["instanceGroupManager"] = args ? args.instanceGroupManager : undefined; inputs["minimalAction"] = args ? args.minimalAction : undefined; inputs["mostDisruptiveAllowedAction"] = args ? args.mostDisruptiveAllowedAction : undefined; inputs["name"] = args ? args.name : undefined; inputs["preservedState"] = args ? args.preservedState : undefined; inputs["project"] = args ? args.project : undefined; inputs["removeInstanceStateOnDestroy"] = args ? args.removeInstanceStateOnDestroy : undefined; inputs["zone"] = args ? args.zone : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(PerInstanceConfig.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering PerInstanceConfig resources. */ export interface PerInstanceConfigState { /** * The instance group manager this instance config is part of. */ instanceGroupManager?: pulumi.Input<string>; /** * The minimal action to perform on the instance during an update. * Default is `NONE`. Possible values are: * * REPLACE * * RESTART * * REFRESH * * NONE */ minimalAction?: pulumi.Input<string>; /** * The most disruptive action to perform on the instance during an update. * Default is `REPLACE`. Possible values are: * * REPLACE * * RESTART * * REFRESH * * NONE */ mostDisruptiveAllowedAction?: pulumi.Input<string>; /** * The name for this per-instance config and its corresponding instance. */ name?: pulumi.Input<string>; /** * The preserved state for this instance. * Structure is documented below. */ preservedState?: pulumi.Input<inputs.compute.PerInstanceConfigPreservedState>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * When true, deleting this config will immediately remove any specified state from the underlying instance. * When false, deleting this config will *not* immediately remove any state from the underlying instance. * State will be removed on the next instance recreation or update. */ removeInstanceStateOnDestroy?: pulumi.Input<boolean>; /** * Zone where the containing instance group manager is located */ zone?: pulumi.Input<string>; } /** * The set of arguments for constructing a PerInstanceConfig resource. */ export interface PerInstanceConfigArgs { /** * The instance group manager this instance config is part of. */ instanceGroupManager: pulumi.Input<string>; /** * The minimal action to perform on the instance during an update. * Default is `NONE`. Possible values are: * * REPLACE * * RESTART * * REFRESH * * NONE */ minimalAction?: pulumi.Input<string>; /** * The most disruptive action to perform on the instance during an update. * Default is `REPLACE`. Possible values are: * * REPLACE * * RESTART * * REFRESH * * NONE */ mostDisruptiveAllowedAction?: pulumi.Input<string>; /** * The name for this per-instance config and its corresponding instance. */ name?: pulumi.Input<string>; /** * The preserved state for this instance. * Structure is documented below. */ preservedState?: pulumi.Input<inputs.compute.PerInstanceConfigPreservedState>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * When true, deleting this config will immediately remove any specified state from the underlying instance. * When false, deleting this config will *not* immediately remove any state from the underlying instance. * State will be removed on the next instance recreation or update. */ removeInstanceStateOnDestroy?: pulumi.Input<boolean>; /** * Zone where the containing instance group manager is located */ zone?: pulumi.Input<string>; }
the_stack
/// <reference types="node" /> import * as stream from 'stream'; export type QRCodeErrorCorrectionLevel = 'low' | 'medium' | 'quartile' | 'high' | 'L' | 'M' | 'Q' | 'H'; export interface QRCodeOptions { /** * QR Code version. If not specified the more suitable value will be calculated. */ version?: number | undefined; /** * Error correction level. * Possible values are low, medium, quartile, high or L, M, Q, H. * Default: M */ errorCorrectionLevel?: QRCodeErrorCorrectionLevel | undefined; /** * Helper function used internally to convert a kanji to its Shift JIS value. * Provide this function if you need support for Kanji mode. */ toSJISFunc?: ((codePoint: string) => number) | undefined; } export interface QRCodeToDataURLOptions extends QRCodeRenderersOptions { /** * Data URI format. * Default: image/png */ type?: 'image/png' | 'image/jpeg' | 'image/webp' | undefined; rendererOpts?: { /** * A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. * Default: 0.92 */ quality?: number | undefined; } | undefined; } export interface QRCodeToStringOptions extends QRCodeRenderersOptions { /** * Output format. * Default: utf8 */ type?: 'utf8' | 'svg' | 'terminal' | undefined; } export interface QRCodeToFileOptions extends QRCodeRenderersOptions { /** * Output format. * Default: png */ type?: 'png' | 'svg' | 'utf8' | undefined; rendererOpts?: { /** * Compression level for deflate. * Default: 9 */ deflateLevel?: number | undefined; /** * Compression strategy for deflate. * Default: 3 */ deflateStrategy?: number | undefined; } | undefined; } export interface QRCodeToFileStreamOptions extends QRCodeRenderersOptions { /** * Output format. Only png supported for file stream */ type?: 'png' | undefined; rendererOpts?: { /** * Compression level for deflate. * Default: 9 */ deflateLevel?: number | undefined; /** * Compression strategy for deflate. * Default: 3 */ deflateStrategy?: number | undefined; } | undefined; } export interface QRCodeToBufferOptions extends QRCodeRenderersOptions { /** * Output format. Only png supported for Buffer. */ type?: 'png' | undefined; rendererOpts?: { /** * Compression level for deflate. * Default: 9 */ deflateLevel?: number | undefined; /** * Compression strategy for deflate. * Default: 3 */ deflateStrategy?: number | undefined; } | undefined; } export interface QRCodeRenderersOptions extends QRCodeOptions { /** * Define how much wide the quiet zone should be. * Default: 4 */ margin?: number | undefined; /** * Scale factor. A value of 1 means 1px per modules (black dots). * Default: 4 */ scale?: number | undefined; /** * Forces a specific width for the output image. * If width is too small to contain the qr symbol, this option will be ignored. * Takes precedence over scale. */ width?: number | undefined; color?: { /** * Color of dark module. Value must be in hex format (RGBA). * Note: dark color should always be darker than color.light. * Default: #000000ff */ dark?: string | undefined; /** * Color of light module. Value must be in hex format (RGBA). * Default: #ffffffff */ light?: string | undefined; } | undefined; } export interface QRCodeSegment { data: string | Buffer | Uint8ClampedArray; mode: 'alphanumeric' | 'numeric' | 'kanji' | 'byte'; } export interface QRCode { /** * Bitmatrix class with modules data */ modules: any; /** * Calculated QR Code version */ version: number; /** * Error Correction Level */ errorCorrectionLevel: number; /** * Calculated Mask pattern */ maskPattern: any; /** * Generated segments */ segments: QRCodeSegment[]; } /** * Creates QR Code symbol and returns a qrcode object. */ export function create(text: string | QRCodeSegment[], options: QRCodeOptions): QRCode; /** * Draws qr code symbol to canvas. */ export function toCanvas( canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], callback: (error: Error) => void, ): void; /** * Draws qr code symbol to canvas. */ export function toCanvas( canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], options?: QRCodeRenderersOptions, ): Promise<any>; /** * Draws qr code symbol to canvas. */ export function toCanvas( canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], options: QRCodeRenderersOptions, callback: (error: Error) => void, ): void; /** * Draws qr code symbol to canvas. */ export function toCanvas( text: string | QRCodeSegment[], callback: (error: Error, canvas: HTMLCanvasElement) => void, ): void; /** * Draws qr code symbol to canvas. */ export function toCanvas(text: string | QRCodeSegment[], options?: QRCodeRenderersOptions): Promise<any>; /** * Draws qr code symbol to canvas. */ export function toCanvas( text: string | QRCodeSegment[], options: QRCodeRenderersOptions, callback: (error: Error, canvas: HTMLCanvasElement) => void, ): void; /** * Draws qr code symbol to node canvas. */ export function toCanvas(canvas: any, text: string | QRCodeSegment[], callback: (error: Error) => void): void; /** * Draws qr code symbol to node canvas. */ export function toCanvas(canvas: any, text: string | QRCodeSegment[], options?: QRCodeRenderersOptions): Promise<any>; /** * Draws qr code symbol to node canvas. */ export function toCanvas( canvas: any, text: string | QRCodeSegment[], options: QRCodeRenderersOptions, callback: (error: Error) => void, ): void; /** * Returns a Data URI containing a representation of the QR Code image. */ export function toDataURL( canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], callback: (error: Error, url: string) => void, ): void; /** * Returns a Data URI containing a representation of the QR Code image. */ export function toDataURL( canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], options?: QRCodeToDataURLOptions, ): Promise<string>; /** * Returns a Data URI containing a representation of the QR Code image. */ export function toDataURL( canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], options: QRCodeToDataURLOptions, callback: (error: Error, url: string) => void, ): void; /** * Returns a Data URI containing a representation of the QR Code image. */ export function toDataURL(text: string | QRCodeSegment[], callback: (error: Error, url: string) => void): void; /** * Returns a Data URI containing a representation of the QR Code image. */ export function toDataURL(text: string | QRCodeSegment[], options?: QRCodeToDataURLOptions): Promise<string>; /** * Returns a Data URI containing a representation of the QR Code image. */ export function toDataURL( text: string | QRCodeSegment[], options: QRCodeToDataURLOptions, callback: (error: Error, url: string) => void, ): void; /** * Returns a string representation of the QR Code. * If choosen output format is svg it will returns a string containing xml code. */ export function toString(text: string | QRCodeSegment[], callback: (error: Error, string: string) => void): void; /** * Returns a string representation of the QR Code. * If choosen output format is svg it will returns a string containing xml code. */ export function toString(text: string | QRCodeSegment[], options?: QRCodeToStringOptions): Promise<string>; /** * Returns a string representation of the QR Code. * If choosen output format is svg it will returns a string containing xml code. */ export function toString( text: string | QRCodeSegment[], options: QRCodeToStringOptions, callback: (error: Error, string: string) => void, ): void; /** * Saves QR Code to image file. * If options.type is not specified, the format will be guessed from file extension. * Recognized extensions are png, svg, txt. */ export function toFile(path: string, text: string | QRCodeSegment[], callback: (error: Error) => void): void; /** * Saves QR Code to image file. * If options.type is not specified, the format will be guessed from file extension. * Recognized extensions are png, svg, txt. */ export function toFile(path: string, text: string | QRCodeSegment[], options?: QRCodeToFileOptions): Promise<any>; /** * Saves QR Code to image file. * If options.type is not specified, the format will be guessed from file extension. * Recognized extensions are png, svg, txt. */ export function toFile( path: string, text: string | QRCodeSegment[], options: QRCodeToFileOptions, callback: (error: Error) => void, ): void; /** * Writes QR Code image to stream. Only works with png format for now. */ export function toFileStream( stream: stream.Writable, text: string | QRCodeSegment[], callback: (error: Error) => void, ): void; /** * Writes QR Code image to stream. Only works with png format for now. */ export function toFileStream( stream: stream.Writable, text: string | QRCodeSegment[], options?: QRCodeToFileStreamOptions, ): Promise<any>; /** * Writes QR Code image to stream. Only works with png format for now. */ export function toFileStream( stream: stream.Writable, text: string | QRCodeSegment[], options: QRCodeToFileStreamOptions, callback: (error: Error) => void, ): void; /** * Returns a Buffer containing a representation of the QR Code image. Only works with png format. */ export function toBuffer(text: string | QRCodeSegment[], callback: (error: Error, buffer: Buffer) => void): void; /** * Returns a Buffer containing a representation of the QR Code image. Only works with png format. */ export function toBuffer(text: string | QRCodeSegment[], options?: QRCodeToBufferOptions): Promise<Buffer>; /** * Returns a Buffer containing a representation of the QR Code image. Only works with png format. */ export function toBuffer( text: string | QRCodeSegment[], options: QRCodeToBufferOptions, callback: (error: Error, buffer: Buffer) => void, ): void;
the_stack
import Rectangle from '../view/geometry/Rectangle'; import EventObject from '../view/event/EventObject'; import EventSource from '../view/event/EventSource'; import { fit, getCurrentStyle } from '../util/styleUtils'; import InternalEvent from '../view/event/InternalEvent'; import Client from '../Client'; import { NODETYPE } from '../util/Constants'; import { br, write } from '../util/domUtils'; import Translations from '../util/Translations'; import { getClientX, getClientY } from '../util/EventUtils'; import { htmlEntities } from '../util/StringUtils'; import { utils } from '../util/Utils'; /** * Basic window inside a document. * * Creating a simple window. * @example * * ```javascript * var tb = document.createElement('div'); * var wnd = new MaxWindow('Title', tb, 100, 100, 200, 200, true, true); * wnd.setVisible(true); * ``` * * Creating a window that contains an iframe. * @example * * ```javascript * var frame = document.createElement('iframe'); * frame.setAttribute('width', '192px'); * frame.setAttribute('height', '172px'); * frame.setAttribute('src', 'http://www.example.com/'); * frame.style.backgroundColor = 'white'; * * var w = document.body.clientWidth; * var h = (document.body.clientHeight || document.documentElement.clientHeight); * var wnd = new MaxWindow('Title', frame, (w-200)/2, (h-200)/3, 200, 200); * wnd.setVisible(true); * ``` * * To limit the movement of a window, eg. to keep it from being moved beyond * the top, left corner the following method can be overridden (recommended): * * ```javascript * wnd.setLocation(x, y) * { * x = Math.max(0, x); * y = Math.max(0, y); * setLocation.apply(this, arguments); * }; * ``` * * Or the following event handler can be used: * * ```javascript * wnd.addListener(mxEvent.MOVE, function(e) * { * wnd.setLocation(Math.max(0, wnd.getX()), Math.max(0, wnd.getY())); * }); * ``` * * To keep a window inside the current window: * * ```javascript * mxEvent.addListener(window, 'resize', mxUtils.bind(this, function() * { * var iw = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; * var ih = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; * * var x = this.window.getX(); * var y = this.window.getY(); * * if (x + this.window.table.clientWidth > iw) * { * x = Math.max(0, iw - this.window.table.clientWidth); * } * * if (y + this.window.table.clientHeight > ih) * { * y = Math.max(0, ih - this.window.table.clientHeight); * } * * if (this.window.getX() != x || this.window.getY() != y) * { * this.window.setLocation(x, y); * } * })); * ``` * * ### Event: mxEvent.MOVE_START * * Fires before the window is moved. The <code>event</code> property contains * the corresponding mouse event. * * ### Event: mxEvent.MOVE * * Fires while the window is being moved. The <code>event</code> property * contains the corresponding mouse event. * * ### Event: mxEvent.MOVE_END * * Fires after the window is moved. The <code>event</code> property contains * the corresponding mouse event. * * ### Event: mxEvent.RESIZE_START * * Fires before the window is resized. The <code>event</code> property contains * the corresponding mouse event. * * ### Event: mxEvent.RESIZE * * Fires while the window is being resized. The <code>event</code> property * contains the corresponding mouse event. * * ### Event: mxEvent.RESIZE_END * * Fires after the window is resized. The <code>event</code> property contains * the corresponding mouse event. * * ### Event: mxEvent.MAXIMIZE * * Fires after the window is maximized. The <code>event</code> property * contains the corresponding mouse event. * * ### Event: mxEvent.MINIMIZE * * Fires after the window is minimized. The <code>event</code> property * contains the corresponding mouse event. * * ### Event: mxEvent.NORMALIZE * * Fires after the window is normalized, that is, it returned from * maximized or minimized state. The <code>event</code> property contains the * corresponding mouse event. * * ### Event: mxEvent.ACTIVATE * * Fires after a window is activated. The <code>previousWindow</code> property * contains the previous window. The event sender is the active window. * * ### Event: mxEvent.SHOW * * Fires after the window is shown. This event has no properties. * * ### Event: mxEvent.HIDE * * Fires after the window is hidden. This event has no properties. * * ### Event: mxEvent.CLOSE * * Fires before the window is closed. The <code>event</code> property contains * the corresponding mouse event. * * ### Event: mxEvent.DESTROY * * Fires before the window is destroyed. This event has no properties. * * @class MaxWindow * @extends EventSource */ class MaxWindow extends EventSource { constructor( title: string, content: HTMLElement | null, x: number, y: number, width: number | null=null, height: number | null=null, minimizable: boolean=true, movable: boolean=true, replaceNode: HTMLElement | null=null, style: string='' ) { super(); if (content != null) { minimizable = minimizable; this.content = content; this.init(x, y, width, height, style); this.installMaximizeHandler(); this.installMinimizeHandler(); this.installCloseHandler(); this.setMinimizable(minimizable); this.setTitle(title); if (movable) { this.installMoveHandler(); } if (replaceNode != null && replaceNode.parentNode != null) { replaceNode.parentNode.replaceChild(this.div, replaceNode); } else { document.body.appendChild(this.div); } } } static activeWindow: MaxWindow | null = null; td!: HTMLElement; div!: HTMLElement; table!: HTMLElement; resize!: HTMLElement; buttons!: HTMLElement; minimize!: HTMLElement; maximize!: HTMLElement; closeImg!: HTMLElement; contentWrapper!: HTMLElement; image!: HTMLImageElement; /** * Initializes the DOM tree that represents the window. */ init(x: number, y: number, width: number | null=null, height: number | null=null, style: string='MaxWindow'): void { this.div = document.createElement('div'); this.div.className = style; this.div.style.left = `${x}px`; this.div.style.top = `${y}px`; this.table = document.createElement('table'); this.table.className = style; // Disables built-in pan and zoom in IE10 and later if (Client.IS_POINTER) { this.div.style.touchAction = 'none'; } // Workaround for table size problems in FF if (width != null) { this.div.style.width = `${width}px`; this.table.style.width = `${width}px`; } if (height != null) { this.div.style.height = `${height}px`; this.table.style.height = `${height}px`; } // Creates title row const tbody = document.createElement('tbody'); let tr = document.createElement('tr'); this.title = document.createElement('td'); this.title.className = `${style}Title`; this.buttons = document.createElement('div'); this.buttons.style.position = 'absolute'; this.buttons.style.display = 'inline-block'; this.buttons.style.right = '4px'; this.buttons.style.top = '5px'; this.title.appendChild(this.buttons); tr.appendChild(this.title); tbody.appendChild(tr); // Creates content row and table cell tr = document.createElement('tr'); this.td = document.createElement('td'); this.td.className = `${style}Pane`; this.contentWrapper = document.createElement('div'); this.contentWrapper.className = `${style}Pane`; this.contentWrapper.style.width = '100%'; this.contentWrapper.appendChild(this.content); // Workaround for div around div restricts height // of inner div if outerdiv has hidden overflow if (this.content.nodeName.toUpperCase() !== 'DIV') { this.contentWrapper.style.height = '100%'; } // Puts all content into the DOM this.td.appendChild(this.contentWrapper); tr.appendChild(this.td); tbody.appendChild(tr); this.table.appendChild(tbody); this.div.appendChild(this.table); // Puts the window on top of other windows when clicked const activator = (evt: MouseEvent) => { this.activate(); }; InternalEvent.addGestureListeners(this.title, activator); InternalEvent.addGestureListeners(this.table, activator); this.hide(); } /** * URL of the image to be used for the close icon in the titlebar. */ closeImage = `${Client.imageBasePath}/close.gif`; /** * URL of the image to be used for the minimize icon in the titlebar. */ minimizeImage = `${Client.imageBasePath}/minimize.gif`; /** * URL of the image to be used for the normalize icon in the titlebar. */ normalizeImage = `${Client.imageBasePath}/normalize.gif`; /** * URL of the image to be used for the maximize icon in the titlebar. */ maximizeImage = `${Client.imageBasePath}/maximize.gif`; /** * URL of the image to be used for the resize icon. */ resizeImage = `${Client.imageBasePath}/resize.gif`; /** * Boolean flag that represents the visible state of the window. */ visible: boolean = false; /** * {@link Rectangle} that specifies the minimum width and height of the window. * Default is (50, 40). */ minimumSize = new Rectangle(0, 0, 50, 40); /** * Specifies if the window should be destroyed when it is closed. If this * is false then the window is hidden using <setVisible>. Default is true. */ destroyOnClose: boolean = true; /** * Reference to the DOM node (TD) that contains the title. */ title!: HTMLElement; /** * Reference to the DOM node that represents the window content. */ content!: HTMLElement; /** * Sets the window title to the given string. HTML markup inside the title * will be escaped. */ setTitle(title: string): void { // Removes all text content nodes (normally just one) let child = this.title.firstChild; while (child != null) { const next = child.nextSibling; if (child.nodeType === NODETYPE.TEXT) { (<Element>child.parentNode).removeChild(child); } child = next; } write(this.title, title || ''); this.title.appendChild(this.buttons); } /** * Sets if the window contents should be scrollable. */ setScrollable(scrollable: boolean): void { // Workaround for hang in Presto 2.5.22 (Opera 10.5) if (navigator.userAgent == null || navigator.userAgent.indexOf('Presto/2.5') < 0) { if (scrollable) { this.contentWrapper.style.overflow = 'auto'; } else { this.contentWrapper.style.overflow = 'hidden'; } } } /** * Puts the window on top of all other windows. */ activate(): void { if (MaxWindow.activeWindow !== this) { const style = getCurrentStyle(this.getElement()); const index = style != null ? parseInt(style.zIndex) : 3; if (MaxWindow.activeWindow) { const elt = MaxWindow.activeWindow.getElement(); if (elt != null && elt.style != null) { elt.style.zIndex = String(index); } } const previousWindow = MaxWindow.activeWindow; this.getElement().style.zIndex = String(index + 1); MaxWindow.activeWindow = this; this.fireEvent(new EventObject(InternalEvent.ACTIVATE, { previousWindow })); } } /** * Returuns the outermost DOM node that makes up the window. */ getElement(): HTMLElement { return this.div; } /** * Makes sure the window is inside the client area of the window. */ fit(): void { fit(this.div); } /** * Returns true if the window is resizable. */ isResizable(): boolean { if (this.resize != null) { return this.resize.style.display !== 'none'; } return false; } /** * Sets if the window should be resizable. To avoid interference with some * built-in features of IE10 and later, the use of the following code is * recommended if there are resizable <MaxWindow>s in the page: * * ```javascript * if (Client.IS_POINTER) * { * document.body.style.msTouchAction = 'none'; * } * ``` */ setResizable(resizable: boolean): void { if (resizable) { if (this.resize == null) { this.resize = document.createElement('img'); this.resize.style.position = 'absolute'; this.resize.style.bottom = '2px'; this.resize.style.right = '2px'; this.resize.setAttribute('src', this.resizeImage); this.resize.style.cursor = 'nw-resize'; let startX: number | null = null; let startY: number | null = null; let width: number | null = null; let height: number | null = null; const start = (evt: MouseEvent) => { // LATER: pointerdown starting on border of resize does start // the drag operation but does not fire consecutive events via // one of the listeners below (does pan instead). // Workaround: document.body.style.msTouchAction = 'none' this.activate(); startX = getClientX(evt); startY = getClientY(evt); width = this.div.offsetWidth; height = this.div.offsetHeight; InternalEvent.addGestureListeners(document, null, dragHandler, dropHandler); this.fireEvent(new EventObject(InternalEvent.RESIZE_START, { event: evt })); InternalEvent.consume(evt); }; // Adds a temporary pair of listeners to intercept // the gesture event in the document let dragHandler = (evt: MouseEvent) => { if (startX != null && startY != null) { const dx = getClientX(evt) - startX; const dy = getClientY(evt) - startY; if (width != null && height != null) { this.setSize(width + dx, height + dy); } this.fireEvent(new EventObject(InternalEvent.RESIZE, { event: evt })); InternalEvent.consume(evt); } }; let dropHandler = (evt: MouseEvent) => { if (startX != null && startY != null) { startX = null; startY = null; InternalEvent.removeGestureListeners( document, null, dragHandler, dropHandler ); this.fireEvent(new EventObject(InternalEvent.RESIZE_END, { event: evt })); InternalEvent.consume(evt); } }; InternalEvent.addGestureListeners(this.resize, start, dragHandler, dropHandler); this.div.appendChild(this.resize); } else { this.resize.style.display = 'inline'; } } else if (this.resize != null) { this.resize.style.display = 'none'; } } /** * Sets the size of the window. */ setSize(width: number, height: number): void { width = Math.max(this.minimumSize.width, width); height = Math.max(this.minimumSize.height, height); // Workaround for table size problems in FF this.div.style.width = `${width}px`; this.div.style.height = `${height}px`; this.table.style.width = `${width}px`; this.table.style.height = `${height}px`; this.contentWrapper.style.height = `${ this.div.offsetHeight - this.title.offsetHeight }px`; } /** * Sets if the window is minimizable. */ setMinimizable(minimizable: boolean): void { this.minimize.style.display = minimizable ? '' : 'none'; } /** * Returns an {@link Rectangle} that specifies the size for the minimized window. * A width or height of 0 means keep the existing width or height. This * implementation returns the height of the window title and keeps the width. */ getMinimumSize(): Rectangle { return new Rectangle(0, 0, 0, this.title.offsetHeight); } /** * Installs the event listeners required for minimizing the window. */ installMinimizeHandler(): void { this.minimize = document.createElement('img'); this.minimize.setAttribute('src', this.minimizeImage); this.minimize.setAttribute('title', 'Minimize'); this.minimize.style.cursor = 'pointer'; this.minimize.style.marginLeft = '2px'; this.minimize.style.display = 'none'; this.buttons.appendChild(this.minimize); let minimized = false; let maxDisplay: string | null = null; let height: string | null = null; const funct = (evt: MouseEvent) => { this.activate(); if (!minimized) { minimized = true; this.minimize.setAttribute('src', this.normalizeImage); this.minimize.setAttribute('title', 'Normalize'); this.contentWrapper.style.display = 'none'; maxDisplay = this.maximize.style.display; this.maximize.style.display = 'none'; height = this.table.style.height; const minSize = this.getMinimumSize(); if (minSize.height > 0) { this.div.style.height = `${minSize.height}px`; this.table.style.height = `${minSize.height}px`; } if (minSize.width > 0) { this.div.style.width = `${minSize.width}px`; this.table.style.width = `${minSize.width}px`; } if (this.resize != null) { this.resize.style.visibility = 'hidden'; } this.fireEvent(new EventObject(InternalEvent.MINIMIZE, { event: evt })); } else { minimized = false; this.minimize.setAttribute('src', this.minimizeImage); this.minimize.setAttribute('title', 'Minimize'); this.contentWrapper.style.display = ''; // default if (maxDisplay != null && height != null) { this.maximize.style.display = maxDisplay; this.div.style.height = height; this.table.style.height = height; } if (this.resize != null) { this.resize.style.visibility = ''; } this.fireEvent(new EventObject(InternalEvent.NORMALIZE, { event: evt })); } InternalEvent.consume(evt); }; InternalEvent.addGestureListeners(this.minimize, funct); } /** * Sets if the window is maximizable. */ setMaximizable(maximizable: boolean): void { this.maximize.style.display = maximizable ? '' : 'none'; } /** * Installs the event listeners required for maximizing the window. */ installMaximizeHandler(): void { this.maximize = document.createElement('img'); this.maximize.setAttribute('src', this.maximizeImage); this.maximize.setAttribute('title', 'Maximize'); this.maximize.style.cursor = 'default'; this.maximize.style.marginLeft = '2px'; this.maximize.style.cursor = 'pointer'; this.maximize.style.display = 'none'; this.buttons.appendChild(this.maximize); let maximized = false; let x: number | null = null; let y: number | null = null; let height: string | null = null; let width: string | null = null; let minDisplay: string | null = null; const funct = (evt: MouseEvent) => { this.activate(); if (this.maximize.style.display !== 'none') { if (!maximized) { maximized = true; this.maximize.setAttribute('src', this.normalizeImage); this.maximize.setAttribute('title', 'Normalize'); this.contentWrapper.style.display = ''; minDisplay = this.minimize.style.display; this.minimize.style.display = 'none'; // Saves window state x = parseInt(this.div.style.left); y = parseInt(this.div.style.top); height = this.table.style.height; width = this.table.style.width; this.div.style.left = '0px'; this.div.style.top = '0px'; const docHeight = Math.max( document.body.clientHeight || 0, document.documentElement.clientHeight || 0 ); this.div.style.width = `${document.body.clientWidth - 2}px`; this.div.style.height = `${docHeight - 2}px`; this.table.style.width = `${document.body.clientWidth - 2}px`; this.table.style.height = `${docHeight - 2}px`; if (this.resize != null) { this.resize.style.visibility = 'hidden'; } const style = <CSSStyleDeclaration>getCurrentStyle(this.contentWrapper); if (style.overflow === 'auto' || this.resize != null) { this.contentWrapper.style.height = `${ this.div.offsetHeight - this.title.offsetHeight }px`; } this.fireEvent(new EventObject(InternalEvent.MAXIMIZE, { event: evt })); } else { maximized = false; this.maximize.setAttribute('src', this.maximizeImage); this.maximize.setAttribute('title', 'Maximize'); this.contentWrapper.style.display = ''; if (minDisplay != null) { this.minimize.style.display = minDisplay; } // Restores window state this.div.style.left = `${x}px`; this.div.style.top = `${y}px`; if (width != null && height != null) { this.div.style.height = height; this.div.style.width = width; } const style = <CSSStyleDeclaration>getCurrentStyle(this.contentWrapper); if (style.overflow === 'auto' || this.resize != null) { this.contentWrapper.style.height = `${ this.div.offsetHeight - this.title.offsetHeight }px`; } if (width != null && height != null) { this.table.style.height = height; this.table.style.width = width; } if (this.resize != null) { this.resize.style.visibility = ''; } this.fireEvent(new EventObject(InternalEvent.NORMALIZE, { event: evt })); } InternalEvent.consume(evt); } }; InternalEvent.addGestureListeners(this.maximize, funct); InternalEvent.addListener(this.title, 'dblclick', funct); } /** * Installs the event listeners required for moving the window. */ installMoveHandler(): void { this.title.style.cursor = 'move'; InternalEvent.addGestureListeners(this.title, (evt: MouseEvent) => { const startX = getClientX(evt); const startY = getClientY(evt); const x = this.getX(); const y = this.getY(); // Adds a temporary pair of listeners to intercept // the gesture event in the document const dragHandler = (evt: MouseEvent) => { const dx = getClientX(evt) - startX; const dy = getClientY(evt) - startY; this.setLocation(x + dx, y + dy); this.fireEvent(new EventObject(InternalEvent.MOVE, { event: evt })); InternalEvent.consume(evt); }; const dropHandler = (evt: MouseEvent) => { InternalEvent.removeGestureListeners(document, null, dragHandler, dropHandler); this.fireEvent(new EventObject(InternalEvent.MOVE_END, { event: evt })); InternalEvent.consume(evt); }; InternalEvent.addGestureListeners(document, null, dragHandler, dropHandler); this.fireEvent(new EventObject(InternalEvent.MOVE_START, { event: evt })); InternalEvent.consume(evt); }); // Disables built-in pan and zoom in IE10 and later if (Client.IS_POINTER) { this.title.style.touchAction = 'none'; } } /** * Sets the upper, left corner of the window. */ setLocation(x: number, y: number): void { this.div.style.left = `${x}px`; this.div.style.top = `${y}px`; } /** * Returns the current position on the x-axis. */ getX(): number { return parseInt(this.div.style.left); } /** * Returns the current position on the y-axis. */ getY(): number { return parseInt(this.div.style.top); } /** * Adds the <closeImage> as a new image node in <closeImg> and installs the * <close> event. */ installCloseHandler(): void { this.closeImg = document.createElement('img'); this.closeImg.setAttribute('src', this.closeImage); this.closeImg.setAttribute('title', 'Close'); this.closeImg.style.marginLeft = '2px'; this.closeImg.style.cursor = 'pointer'; this.closeImg.style.display = 'none'; this.buttons.appendChild(this.closeImg); InternalEvent.addGestureListeners(this.closeImg, (evt: MouseEvent) => { this.fireEvent(new EventObject(InternalEvent.CLOSE, { event: evt })); if (this.destroyOnClose) { this.destroy(); } else { this.setVisible(false); } InternalEvent.consume(evt); }); } /** * Sets the image associated with the window. * * * @param image - URL of the image to be used. */ setImage(image: string): void { this.image = document.createElement('img'); this.image.setAttribute('src', image); this.image.setAttribute('align', 'left'); this.image.style.marginRight = '4px'; this.image.style.marginLeft = '0px'; this.image.style.marginTop = '-2px'; this.title.insertBefore(this.image, this.title.firstChild); } /** * Sets the image associated with the window. * * * @param closable - Boolean specifying if the window should be closable. */ setClosable(closable: boolean): void { this.closeImg.style.display = closable ? '' : 'none'; } /** * Returns true if the window is visible. */ isVisible(): boolean { if (this.div != null) { return this.div.style.display !== 'none'; } return false; } /** * Shows or hides the window depending on the given flag. * * * @param visible - Boolean indicating if the window should be made visible. */ setVisible(visible: boolean): void { if (this.div != null && this.isVisible() !== visible) { if (visible) { this.show(); } else { this.hide(); } } } /** * Shows the window. */ show(): void { this.div.style.display = ''; this.activate(); const style = <CSSStyleDeclaration>getCurrentStyle(this.contentWrapper); if ( (style.overflow == 'auto' || this.resize != null) && this.contentWrapper.style.display != 'none' ) { this.contentWrapper.style.height = `${ this.div.offsetHeight - this.title.offsetHeight }px`; } this.fireEvent(new EventObject(InternalEvent.SHOW)); } /** * Hides the window. */ hide(): void { this.div.style.display = 'none'; this.fireEvent(new EventObject(InternalEvent.HIDE)); } /** * Destroys the window and removes all associated resources. Fires a * <destroy> event prior to destroying the window. */ destroy(): void { this.fireEvent(new EventObject(InternalEvent.DESTROY)); if (this.div != null) { InternalEvent.release(this.div); // @ts-ignore this.div.parentNode.removeChild(this.div); // @ts-ignore this.div = null; } // @ts-ignore this.title = null; // @ts-ignore this.content = null; // @ts-ignore this.contentWrapper = null; } } /** * Shows the specified text content in a new <MaxWindow> or a new browser * window if isInternalWindow is false. * * @param content String that specifies the text to be displayed. * @param isInternalWindow Optional boolean indicating if an MaxWindow should be * used instead of a new browser window. Default is false. */ export const popup = (content: string, isInternalWindow: boolean=false) => { if (isInternalWindow) { const div = document.createElement('div'); div.style.overflow = 'scroll'; div.style.width = '636px'; div.style.height = '460px'; const pre = document.createElement('pre'); pre.innerHTML = htmlEntities(content, false) .replace(/\n/g, '<br>') .replace(/ /g, '&nbsp;'); div.appendChild(pre); const w = document.body.clientWidth; const h = Math.max( document.body.clientHeight || 0, document.documentElement.clientHeight ); const wnd = new MaxWindow( 'Popup Window', div, w / 2 - 320, h / 2 - 240, 640, 480, false, true ); wnd.setClosable(true); wnd.setVisible(true); } else { // Wraps up the XML content in a textarea if (Client.IS_NS) { const wnd = window.open(); if (!wnd) { throw new Error('Permission not granted to open popup window'); } wnd.document.writeln(`<pre>${htmlEntities(content)}</pre`); wnd.document.close(); } else { const wnd = window.open(); if (!wnd) { throw new Error('Permission not granted to open popup window'); } const pre = wnd.document.createElement('pre'); pre.innerHTML = htmlEntities(content, false) .replace(/\n/g, '<br>') .replace(/ /g, '&nbsp;'); wnd.document.body.appendChild(pre); } } }; /** * Displays the given error message in a new <MaxWindow> of the given width. * If close is true then an additional close button is added to the window. * The optional icon specifies the icon to be used for the window. Default * is {@link Utils#errorImage}. * * @param message String specifying the message to be displayed. * @param width Integer specifying the width of the window. * @param close Optional boolean indicating whether to add a close button. * @param icon Optional icon for the window decoration. */ export const error = (message: string, width: number, close: boolean, icon: string | null=null) => { const div = document.createElement('div'); div.style.padding = '20px'; const img = document.createElement('img'); img.setAttribute('src', icon || utils.errorImage); img.setAttribute('valign', 'bottom'); img.style.verticalAlign = 'middle'; div.appendChild(img); div.appendChild(document.createTextNode('\u00a0')); // &nbsp; div.appendChild(document.createTextNode('\u00a0')); // &nbsp; div.appendChild(document.createTextNode('\u00a0')); // &nbsp; write(div, message); const w = document.body.clientWidth; const h = document.body.clientHeight || document.documentElement.clientHeight; const warn = new MaxWindow( Translations.get(utils.errorResource) || utils.errorResource, div, (w - width) / 2, h / 4, width, null, false, true ); if (close) { br(div); const tmp = document.createElement('p'); const button = document.createElement('button'); button.setAttribute('style', 'float:right'); InternalEvent.addListener(button, 'click', (evt: MouseEvent) => { warn.destroy(); }); write(button, Translations.get(utils.closeResource) || utils.closeResource); tmp.appendChild(button); div.appendChild(tmp); br(div); warn.setClosable(true); } warn.setVisible(true); return warn; }; export default MaxWindow;
the_stack
import React from "react"; import moment from "moment"; import { success, error } from "../toast/toast"; import { TaggedFarmEvent, SpecialStatus, TaggedSequence, TaggedRegimen, ParameterApplication, } from "farmbot"; import { ExecutableQuery } from "../farm_designer/interfaces"; import { formatTimeField, formatDateField } from "./map_state_to_props_add_edit"; import { BlurableInput, Col, Row, SaveBtn, FBSelect, DropDownItem, Help, } from "../ui"; import { destroy, save, overwrite } from "../api/crud"; import { history } from "../history"; import { betterMerge, parseIntInput } from "../util"; import { maybeWarnAboutMissedTasks } from "./util"; import { FarmEventRepeatForm } from "./farm_event_repeat_form"; import { scheduleForFarmEvent } from "./calendar/scheduler"; import { executableType } from "../farm_designer/util"; import { Content } from "../constants"; import { EventTimePicker } from "./event_time_picker"; import { TzWarning } from "./tz_warning"; import { nextRegItemTimes } from "./map_state_to_props"; import { first } from "lodash"; import { TimeUnit, ExecutableType, FarmEvent, } from "farmbot/dist/resources/api_resources"; import { LocalsList } from "../sequences/locals_list/locals_list"; import { ResourceIndex } from "../resources/interfaces"; import { addOrEditParamApps, variableList, getRegimenVariableData, } from "../sequences/locals_list/variable_support"; import { AllowedVariableNodes, } from "../sequences/locals_list/locals_list_support"; import { t } from "../i18next_wrapper"; import { TimeSettings } from "../interfaces"; import { ErrorBoundary } from "../error_boundary"; export const NEVER: TimeUnit = "never"; /** Separate each of the form fields into their own interface. Recombined later * on save. */ export interface FarmEventViewModel { id: number | undefined; startDate: string; startTime: string; endDate: string; endTime: string; repeat: string; timeUnit: string; executable_type: string; executable_id: string; timeSettings: TimeSettings; body?: ParameterApplication[]; } export type FarmEventViewModelKey = keyof FarmEventViewModel; /** Breaks up a TaggedFarmEvent into a structure that can easily be used * by the edit form. * USE CASE EXAMPLE: We have a "date" and "time" field that are created from * a single "start_time" FarmEvent field. */ export function destructureFarmEvent( fe: TaggedFarmEvent, timeSettings: TimeSettings): FarmEventViewModel { const startTime = fe.body.start_time; const endTime = fe.body.end_time || new Date(); return { id: fe.body.id, startDate: formatDateField(startTime.toString(), timeSettings), startTime: formatTimeField(startTime.toString(), timeSettings), endDate: formatDateField(endTime.toString(), timeSettings), endTime: formatTimeField(endTime.toString(), timeSettings), repeat: (fe.body.repeat || 1).toString(), timeUnit: fe.body.time_unit, executable_type: fe.body.executable_type, executable_id: (fe.body.executable_id || "").toString(), timeSettings, body: fe.body.body, }; } const startTimeWarning = () => { const message = t("Event start time needs to be in the future, not the past."); const title = t("Unable to save event."); error(message, { title }); }; const nothingToRunWarning = () => { const message = t("All items scheduled before the start time. Nothing to run."); const title = t("Unable to save event."); error(message, { title }); }; type RecombineOptions = { forceRegimensToMidnight: boolean }; /** Take a FormViewModel and recombine the fields into a FarmEvent * that can be used to apply updates (such as a PUT request to the API). */ export function recombine(vm: FarmEventViewModel, options: RecombineOptions): TaggedFarmEvent["body"] { // Make sure that `repeat` is set to `never` when dealing with regimens. const isReg = vm.executable_type === "Regimen"; const startTime = isReg && options.forceRegimensToMidnight ? "00:00" : vm.startTime; return { id: vm.id, start_time: offsetTime(vm.startDate, startTime, vm.timeSettings), end_time: offsetTime(vm.endDate, vm.endTime, vm.timeSettings), repeat: parseInt(vm.repeat, 10) || 1, time_unit: (isReg ? "never" : vm.timeUnit) as TimeUnit, executable_id: parseIntInput(vm.executable_id), executable_type: vm.executable_type as ("Sequence" | "Regimen"), body: vm.body, }; } export function offsetTime( date: string, time: string, timeSettings: TimeSettings): string { const out = moment(date); const [hrs, min] = time.split(":").map(x => parseInt(x)); out.hours(hrs); out.minutes(min); const utcOffsetDifference = moment().utcOffset() / 60 - timeSettings.utcOffset; return out.add(utcOffsetDifference, "hours").toISOString(); } export interface EditFEProps { deviceTimezone: string | undefined; executableOptions: DropDownItem[]; repeatOptions: DropDownItem[]; farmEvent: TaggedFarmEvent; dispatch: Function; findExecutable: ExecutableQuery; title: string; deleteBtn?: boolean; timeSettings: TimeSettings; resources: ResourceIndex; } export interface EditFEFormState { /** * Hold a partial FarmEvent locally containing only updates made by the form. */ fe: Partial<FarmEventViewModel>; /** * This form has local state and does not cause any global state changes when * editing. * * Example: Navigating away from the page while editing will discard changes. */ specialStatusLocal: SpecialStatus; } export class EditFEForm extends React.Component<EditFEProps, EditFEFormState> { state: EditFEFormState = { fe: {}, specialStatusLocal: SpecialStatus.SAVED }; /** API data for the FarmEvent to which form updates can be applied. */ get viewModel() { return destructureFarmEvent(this.props.farmEvent, this.props.timeSettings); } get executable() { const et = this.fieldGet("executable_type"); const id = parseInt(this.fieldGet("executable_id")); if (et === "Sequence" || et === "Regimen") { return this.props.findExecutable(et, id); } else { throw new Error(`${et} is not a valid executable_type`); } } get isReg() { return this.fieldGet("executable_type") === "Regimen"; } /** Executable requires variables or a user has manually added bodyVariables. */ get needsVariables() { const varData = this.props.resources.sequenceMetas[this.executable.uuid]; return Object.keys(varData || {}).length > 0; } get variableData() { if (this.executable.kind === "Regimen") { const regimenVariables = this.executable.body.body; return getRegimenVariableData(regimenVariables, this.props.resources); } return this.props.resources.sequenceMetas[this.executable.uuid]; } get bodyVariables(): ParameterApplication[] { return this.state.fe.body || this.props.farmEvent.body.body || []; } overwriteStateFEBody = (newBody: ParameterApplication[]) => { const state = this.state; state.fe.body = newBody; this.setState(state); }; editBodyVariables = (bodyVariables: ParameterApplication[]) => (variable: ParameterApplication) => { const body = addOrEditParamApps(bodyVariables, variable); this.overwriteStateFEBody(body); this.setState({ specialStatusLocal: SpecialStatus.DIRTY }); }; LocalsList = () => <LocalsList locationDropdownKey={JSON.stringify(this.bodyVariables)} bodyVariables={this.bodyVariables} variableData={this.variableData} sequenceUuid={this.executable.uuid} resources={this.props.resources} onChange={this.editBodyVariables(this.bodyVariables)} allowedVariableNodes={AllowedVariableNodes.variable} />; executableSet = (ddi: DropDownItem) => { if (ddi.value) { const { id, executable_type } = this.props.farmEvent.body; const prev_executable_type = executable_type; const next_executable_type = executableType(ddi.headingId); if (id && prev_executable_type !== next_executable_type) { error(t("Cannot change between Sequences and Regimens.")); history.push("/app/designer/events"); } else { const { uuid } = this.props.findExecutable( next_executable_type, parseInt("" + ddi.value)); const varData = this.props.resources.sequenceMetas[uuid]; const update: EditFEFormState = { fe: { executable_type: next_executable_type, executable_id: ddi.value.toString(), }, specialStatusLocal: SpecialStatus.DIRTY }; this.overwriteStateFEBody(variableList(varData) || []); this.setState(betterMerge(this.state, update)); } } }; executableGet = (): DropDownItem => { const headingId: ExecutableType = (this.executable.kind === "Sequence") ? "Sequence" : "Regimen"; return { value: this.executable.body.id || 0, label: this.executable.body.name, headingId }; }; fieldSet = (key: FarmEventViewModelKey, value: string) => // A merge is required to not overwrite `fe`. this.setState(betterMerge(this.state, { fe: { [key]: value }, specialStatusLocal: SpecialStatus.DIRTY })); fieldGet = (key: FarmEventViewModelKey): string => (this.state.fe[key] || this.viewModel[key] || "").toString(); nextItemTime = (fe: FarmEvent, now: moment.Moment, ): moment.Moment | undefined => { const { timeSettings } = this.props; const kind = fe.executable_type; const start = fe.start_time; const isRegimen = (x: TaggedSequence | TaggedRegimen): x is TaggedRegimen => !!(x.kind === "Regimen"); switch (kind) { case "Sequence": return first(scheduleForFarmEvent(fe, now).items); case "Regimen": const r = this.props.findExecutable(kind, fe.executable_id); const nextItem = isRegimen(r) ? first(nextRegItemTimes(r.body.regimen_items, start, now, timeSettings)) : undefined; const futureStartTimeFallback = moment(start) > now ? moment(start) : undefined; return nextItem || futureStartTimeFallback; default: throw new Error(`${kind} is not a valid executable_type`); } }; /** Rejects save of Farm Event if: */ maybeRejectStartTime = (f: FarmEvent, now = moment()) => { /** adding a new event (editing repeats for ongoing events is allowed) */ const newEvent = this.props.title.toLowerCase().includes("add"); /** start time is in the past */ const inThePast = moment(f.start_time) < now; /** is a sequence event */ const sequenceEvent = !this.isReg; return newEvent && (inThePast && sequenceEvent); }; /** Merge and recombine FarmEvent form updates into and updated FarmEvent. */ get updatedFarmEvent() { /** ViewModel with INVALID `body` (must be replaced). */ const vm = betterMerge(this.viewModel, this.state.fe); const oldBodyData = this.needsVariables ? this.viewModel.body : []; vm.body = this.state.fe.body || oldBodyData; const opts: RecombineOptions = { forceRegimensToMidnight: true }; return recombine(vm, opts); } /** Once saved, if * - Regimen Farm Event: * * If scheduled for today, warn about the possibility of missing tasks. * * Display the start time difference from now. * * Return to calendar view. * - Sequence Farm Event: * * Determine the time for the next item to be run. * * Return to calendar view. */ commitViewModel = (now = moment()) => { if (this.maybeRejectStartTime(this.updatedFarmEvent)) { return startTimeWarning(); } const nextRun = this.nextItemTime(this.updatedFarmEvent, now); if (!nextRun) { return nothingToRunWarning(); } const { dispatch } = this.props; dispatch(overwrite(this.props.farmEvent, this.updatedFarmEvent)); dispatch(save(this.props.farmEvent.uuid)) .then(() => { this.setState({ specialStatusLocal: SpecialStatus.SAVED }); dispatch(maybeWarnAboutMissedTasks(this.props.farmEvent, () => alert(t(Content.REGIMEN_TODAY_SKIPPED_ITEM_RISK)), now)); success(t("The next item in this event will run {{timeFromNow}}.", { timeFromNow: nextRun.from(now) })); history.push("/app/designer/events"); }) .catch(() => { error(t("Unable to save event.")); this.setState({ specialStatusLocal: SpecialStatus.DIRTY }); }); }; render() { const { farmEvent } = this.props; return <div className="edit-farm-event-form"> <ErrorBoundary> <FarmEventForm isRegimen={this.isReg} fieldGet={this.fieldGet} fieldSet={this.fieldSet} timeSettings={this.props.timeSettings} executableOptions={this.props.executableOptions} executableSet={this.executableSet} executableGet={this.executableGet} dispatch={this.props.dispatch} specialStatus={farmEvent.specialStatus || this.state.specialStatusLocal} onSave={() => this.commitViewModel()}> <ErrorBoundary> <this.LocalsList /> </ErrorBoundary> </FarmEventForm> </ErrorBoundary> <FarmEventDeleteButton hidden={!this.props.deleteBtn} farmEvent={this.props.farmEvent} dispatch={this.props.dispatch} /> <TzWarning deviceTimezone={this.props.deviceTimezone} /> </div>; } } export interface StartTimeFormProps { isRegimen: boolean; fieldGet(key: FarmEventViewModelKey): string; fieldSet(key: FarmEventViewModelKey, value: string): void; timeSettings: TimeSettings; now?: moment.Moment; disabled?: boolean; } export const StartTimeForm = (props: StartTimeFormProps) => { const forceMidnight = props.isRegimen; const isNew = !parseInt("" + props.fieldGet("id")); const startDatetimeError = isNew && !forceMidnight && !moment(props.now).isBefore(moment(offsetTime(props.fieldGet("startDate"), props.fieldGet("startTime"), props.timeSettings))) ? t("Start time and date must be in the future.") : undefined; return <div className="start-time-form"> <label> {t("Starts")} </label> <Row> <Col xs={6}> <BlurableInput type="date" disabled={props.disabled} className="add-event-start-date" name="start_date" value={props.fieldGet("startDate")} error={startDatetimeError} onCommit={e => props.fieldSet("startDate", e.currentTarget.value)} /> </Col> <Col xs={6}> <EventTimePicker className="add-event-start-time" name="start_time" timeSettings={props.timeSettings} value={props.fieldGet("startTime")} error={startDatetimeError} onCommit={e => props.fieldSet("startTime", e.currentTarget.value)} disabled={props.disabled || forceMidnight} hidden={forceMidnight} /> </Col> </Row> </div>; }; export interface RepeatFormProps { isRegimen: boolean; fieldGet(key: FarmEventViewModelKey): string; fieldSet(key: FarmEventViewModelKey, value: string): void; timeSettings: TimeSettings; disabled?: boolean; } export const RepeatForm = (props: RepeatFormProps) => { const allowRepeat = !props.isRegimen && props.fieldGet("timeUnit") !== NEVER; return <div className="farm-event-repeat-options"> {!props.isRegimen ? <label> <input type="checkbox" name="timeUnit" onChange={e => props.fieldSet("timeUnit", (!e.currentTarget.checked || props.isRegimen) ? "never" : "daily")} disabled={props.disabled || props.isRegimen} checked={allowRepeat} /> {t("Repeats?")} </label> : <div className={"no-repeat"} />} <FarmEventRepeatForm timeSettings={props.timeSettings} disabled={!allowRepeat} hidden={!allowRepeat} fieldSet={props.fieldSet} timeUnit={props.fieldGet("timeUnit") as TimeUnit} repeat={props.fieldGet("repeat")} endDate={props.fieldGet("endDate")} endTime={props.fieldGet("endTime")} dateError={dateCheck(props.fieldGet)} timeError={timeCheck(props.fieldGet, props.timeSettings)} /> </div>; }; export const dateCheck = ( fieldGet: (key: FarmEventViewModelKey) => string, ): string | undefined => { const startDate = fieldGet("startDate"); const endDate = fieldGet("endDate"); if (!moment(endDate).isSameOrAfter(moment(startDate))) { return t("End date must not be before start date."); } }; export const timeCheck = ( fieldGet: (key: FarmEventViewModelKey) => string, timeSettings: TimeSettings, ): string | undefined => { const startDate = fieldGet("startDate"); const startTime = fieldGet("startTime"); const endDate = fieldGet("endDate"); const endTime = fieldGet("endTime"); const start = offsetTime(startDate, startTime, timeSettings); const end = offsetTime(endDate, endTime, timeSettings); if (moment(start).isSameOrAfter(moment(end))) { return t("End time must be after start time."); } }; export interface FarmEventDeleteButtonProps { hidden: boolean; farmEvent: TaggedFarmEvent; dispatch: Function; } export const FarmEventDeleteButton = (props: FarmEventDeleteButtonProps) => <button className="fb-button red" hidden={props.hidden} title={t("Delete")} onClick={() => props.dispatch(destroy(props.farmEvent.uuid)) .then(() => { history.push("/app/designer/events"); success(t("Deleted event."), { title: t("Deleted") }); })}> {t("Delete")} </button>; export interface FarmEventFormProps { isRegimen: boolean; fieldGet(key: FarmEventViewModelKey): string; fieldSet(key: FarmEventViewModelKey, value: string): void; timeSettings: TimeSettings; executableOptions: DropDownItem[]; executableSet(ddi: DropDownItem): void; executableGet(): DropDownItem | undefined; dispatch: Function; specialStatus: SpecialStatus; onSave(): void; children?: React.ReactChild; } export const FarmEventForm = (props: FarmEventFormProps) => { const { isRegimen, fieldGet, fieldSet, timeSettings } = props; return <div className="farm-event-form"> <label> {t("Sequence or Regimen")} </label> {props.executableOptions.filter(x => !x.heading).length < 1 && <Help text={Content.MISSING_EXECUTABLE} customIcon={"exclamation-triangle"} />} <FBSelect list={props.executableOptions} onChange={props.executableSet} selectedItem={props.executableGet()} /> {props.children} <StartTimeForm disabled={!props.executableGet()} isRegimen={isRegimen} fieldGet={fieldGet} fieldSet={fieldSet} timeSettings={timeSettings} /> <RepeatForm disabled={!props.executableGet()} isRegimen={isRegimen} fieldGet={fieldGet} fieldSet={fieldSet} timeSettings={props.timeSettings} /> <SaveBtn status={props.specialStatus} onClick={props.onSave} /> </div>; };
the_stack
import ModelViewerElementBase, {$renderer, $scene, $userInputElement} from '../model-viewer-base.js'; import {Renderer} from '../three-components/Renderer.js'; import {Constructor, timePasses, waitForEvent} from '../utilities.js'; import {assetPath, spy, until} from './helpers.js'; import {BasicSpecTemplate} from './templates.js'; const expect = chai.expect; const expectBlobDimensions = async (blob: Blob, width: number, height: number) => { const img = await new Promise<HTMLImageElement>((resolve) => { const url = URL.createObjectURL(blob); const img = new Image(); img.onload = () => { resolve(img); }; img.src = url; }); expect(img.width).to.be.equal(Math.round(width)); expect(img.height).to.be.equal(Math.round(height)); }; suite('ModelViewerElementBase', () => { test('is not registered as a custom element by default', () => { expect(customElements.get('model-viewer-base')).to.be.equal(undefined); }); suite('when registered', () => { let nextId = 0; let tagName: string; let ModelViewerElement: Constructor<ModelViewerElementBase>; setup(() => { tagName = `model-viewer-base-${nextId++}`; ModelViewerElement = class extends ModelViewerElementBase { static get is() { return tagName; } }; customElements.define(tagName, ModelViewerElement); }); BasicSpecTemplate(() => ModelViewerElement, () => tagName); suite('with alt text', () => { let element: ModelViewerElementBase; let input: HTMLDivElement; setup(() => { element = new ModelViewerElement(); input = element[$userInputElement]; document.body.insertBefore(element, document.body.firstChild); }); teardown(() => { if (element.parentNode != null) { element.parentNode.removeChild(element); } }); test('gives the input a related aria-label', async () => { const altText = 'foo'; element.alt = altText; await timePasses(); expect(input.getAttribute('aria-label')).to.be.equal(altText); }); suite('that is removed', () => { test('reverts input to default aria-label', async () => { const defaultAriaLabel = input.getAttribute('aria-label'); const altText = 'foo'; element.alt = altText; await timePasses(); element.alt = null; await timePasses(); expect(input.getAttribute('aria-label')) .to.be.equal(defaultAriaLabel); }); }); }); suite('with a valid src', () => { let element: ModelViewerElementBase; setup(() => { element = new ModelViewerElement(); document.body.insertBefore(element, document.body.firstChild); }); teardown(() => { if (element.parentNode != null) { element.parentNode.removeChild(element); } }); test('eventually dispatches a load event', async () => { const sourceLoads = waitForEvent(element, 'load'); element.src = assetPath('models/Astronaut.glb'); await sourceLoads; }); suite('that changes before the model loads', () => { test('it loads the second value on microtask timing', async () => { element.src = assetPath('models/Astronaut.glb'); await timePasses(); element.src = assetPath('models/Horse.glb'); await waitForEvent(element, 'load'); expect(element[$scene].url) .to.be.equal(assetPath('models/Horse.glb')); }); test('it loads the second value on task timing', async () => { element.src = assetPath('models/Astronaut.glb'); await timePasses(1); element.src = assetPath('models/Horse.glb'); await waitForEvent(element, 'load'); expect(element[$scene].url) .to.be.equal(assetPath('models/Horse.glb')); }); }); }); suite('with an invalid src', () => { let element: ModelViewerElementBase; setup(() => { element = new ModelViewerElement(); document.body.insertBefore(element, document.body.firstChild); }); teardown(() => { if (element.parentNode != null) { element.parentNode.removeChild(element); } }); test('eventually dispatches an error event', async () => { const sourceErrors = waitForEvent(element, 'error'); element.src = './does-not-exist.glb'; await sourceErrors; }); }); suite('when losing the GL context', () => { let element: ModelViewerElementBase; setup(() => { element = new ModelViewerElement(); document.body.insertBefore(element, document.body.firstChild); }); teardown(() => { if (element.parentNode != null) { element.parentNode.removeChild(element); } }); test('dispatches a related error event', async () => { const {threeRenderer, canvas3D} = Renderer.singleton; canvas3D.addEventListener('webglcontextlost', function(event) { event.preventDefault(); Renderer.resetSingleton(); }, false); const errorEventDispatches = waitForEvent(element, 'error'); // We make a best effor to simulate the real scenario here, but // for some cases like headless Chrome WebGL might be disabled, // so we simulate the scenario. // @see https://threejs.org/docs/index.html#api/en/renderers/WebGLRenderer.forceContextLoss if (threeRenderer.getContext() != null) { threeRenderer.forceContextLoss(); } else { threeRenderer.domElement.dispatchEvent( new CustomEvent('webglcontextlost')); } const event = await errorEventDispatches; expect((event as any).detail.type).to.be.equal('webglcontextlost'); }); }); suite('capturing screenshots', () => { let element: ModelViewerElementBase; let width: number; let height: number; setup(async () => { element = new ModelViewerElement(); // Avoid testing our memory ceiling in CI by limiting the size // of the screenshots we produce in these tests: width = 32; height = 64; element.style.width = `${width}px`; element.style.height = `${height}px`; document.body.insertBefore(element, document.body.firstChild); const modelLoads = waitForEvent(element, 'load'); element.src = assetPath('models/cube.gltf'); await modelLoads; }); teardown(() => { if (element.parentNode != null) { element.parentNode.removeChild(element); } }); suite('toDataURL', () => { test('produces a URL-compatible string', () => { const dataUrlMatcher = /^data\:image\//; expect(dataUrlMatcher.test(element.toDataURL())).to.be.true; }); }); suite('toBlob', () => { test('produces a blob', async () => { const blob = await element.toBlob(); expect(blob).to.not.be.null; }); test('can convert blob to object URL', async () => { const blob = await element.toBlob(); const objectUrl = URL.createObjectURL(blob); const objectUrlMatcher = /^blob\:/; expect(objectUrlMatcher.test(objectUrl)).to.be.true; }); test('has size', async () => { const blob = await element.toBlob(); expect(blob.size).to.be.greaterThan(0); }); test('uses fallbacks on unsupported browsers', async () => { // Emulate unsupported browser let restoreCanvasToBlob = () => {}; try { restoreCanvasToBlob = spy(HTMLCanvasElement.prototype, 'toBlob', {value: undefined}); } catch (error) { // Ignored... } const blob = await element.toBlob(); expect(blob).to.not.be.null; restoreCanvasToBlob(); }); test( 'blobs on supported and unsupported browsers are equivalent', async () => { let restoreCanvasToBlob = () => {}; try { restoreCanvasToBlob = spy( HTMLCanvasElement.prototype, 'toBlob', {value: undefined}); } catch (error) { // Ignored... } const unsupportedBrowserBlob = await element.toBlob(); restoreCanvasToBlob(); const supportedBrowserBlob = await element.toBlob(); // Blob.prototype.arrayBuffer is not available in Edge / Safari // Using Response to get arrayBuffer instead const supportedBrowserResponse = new Response(supportedBrowserBlob); const unsupportedBrowserResponse = new Response(unsupportedBrowserBlob); const supportedBrowserArrayBuffer = await supportedBrowserResponse.arrayBuffer(); const unsupportedBrowserArrayBuffer = await unsupportedBrowserResponse.arrayBuffer(); expect(unsupportedBrowserArrayBuffer) .to.eql(supportedBrowserArrayBuffer); }); test.skip('idealAspect gives the proper blob dimensions', async () => { const basicBlob = await element.toBlob(); const idealBlob = await element.toBlob({idealAspect: true}); const idealHeight = 32 / element[$scene].idealAspect; const {dpr, scaleFactor} = element[$renderer]; const f = dpr * scaleFactor; await expectBlobDimensions(basicBlob, width * f, height * f); await expectBlobDimensions(idealBlob, width * f, idealHeight * f); }); }); }); suite('orchestrates rendering', () => { let elements: Array<ModelViewerElementBase> = []; setup(async () => { elements.push(new ModelViewerElement()); elements.push(new ModelViewerElement()); elements.push(new ModelViewerElement()); for (let element of elements) { element.style.position = 'relative'; element.style.marginBottom = '100vh'; element.src = assetPath('models/cube.gltf'); document.body.insertBefore(element, document.body.firstChild); } }); teardown(() => { elements.forEach( element => element.parentNode != null && element.parentNode.removeChild(element)); }); test('sets a model within viewport to be visible', async () => { await until(() => { return elements[2].modelIsVisible; }); expect(elements[2].modelIsVisible).to.be.true; }); test.skip('only models visible in the viewport', async () => { // IntersectionObserver needs to set appropriate // visibility on the scene, lots of timing issues when // running -- wait for the visibility flags to be flipped await until(() => { return elements .map((element, index) => { return (index === 0) === element.modelIsVisible; }) .reduce(((l, r) => l && r), true); }); expect(elements[0].modelIsVisible).to.be.ok; expect(elements[1].modelIsVisible).to.not.be.ok; expect(elements[2].modelIsVisible).to.not.be.ok; }); }); }); });
the_stack
* AccumulationChart file */ import { Property, Component, Complex, Collection, NotifyPropertyChanges, INotifyPropertyChanged } from '@syncfusion/ej2-base'; import { ModuleDeclaration, Internationalization, Event, EmitType, Browser, EventHandler, Touch } from '@syncfusion/ej2-base'; import { remove, extend, isNullOrUndefined, updateBlazorTemplate } from '@syncfusion/ej2-base'; import { AccumulationChartModel } from './accumulation-model'; import { Font, Margin, Border, TooltipSettings, Indexes } from '../common/model/base'; import { AccumulationSeries, AccPoints, PieCenter } from './model/acc-base'; import { AccumulationType, AccumulationSelectionMode } from './model/enum'; import { IAccSeriesRenderEventArgs, IAccTextRenderEventArgs } from './model/pie-interface'; import { IAccAnimationCompleteEventArgs, IAccPointRenderEventArgs, IAccLoadedEventArgs } from './model/pie-interface'; import { Theme, getThemeColor } from '../common/model/theme'; import { ILegendRenderEventArgs, IMouseEventArgs, IPointEventArgs, ITooltipRenderEventArgs, IAfterExportEventArgs } from '../chart/model/chart-interface'; import { IAnnotationRenderEventArgs } from '../chart/model/chart-interface'; import { load, pointClick } from '../common/model/constants'; import { pointMove, chartMouseClick, chartMouseDown } from '../common/model/constants'; import { chartMouseLeave, chartMouseMove, chartMouseUp, resized, beforeResize } from '../common/model/constants'; import { FontModel, MarginModel, BorderModel, IndexesModel, TooltipSettingsModel } from '../common/model/base-model'; import { AccumulationSeriesModel, PieCenterModel } from './model/acc-base-model'; import { LegendSettings } from '../common/legend/legend'; import { AccumulationLegend } from './renderer/legend'; import { LegendSettingsModel } from '../common/legend/legend-model'; import { ChartLocation, subtractRect, indexFinder, appendChildElement, redrawElement, blazorTemplatesReset } from '../common/utils/helper'; import { RectOption, showTooltip, ImageOption } from '../common/utils/helper'; import { textElement, createSvg, calculateSize, removeElement, firstToLowerCase, withInBounds } from '../common/utils/helper'; import { getElement, titlePositionX } from '../common/utils/helper'; import { Rect, Size, measureText, TextOption, SvgRenderer, CanvasRenderer } from '@syncfusion/ej2-svg-base'; import { Data } from '../common/model/data'; import { AccumulationTooltip } from './user-interaction/tooltip'; import { AccumulationBase } from './renderer/accumulation-base'; import { PieSeries } from './renderer/pie-series'; import { AccumulationDataLabel } from './renderer/dataLabel'; import { FunnelSeries } from './renderer/funnel-series'; import { PyramidSeries } from './renderer/pyramid-series'; import { AccumulationSelection } from './user-interaction/selection'; import { AccumulationTheme } from './model/enum'; import { AccumulationAnnotationSettingsModel } from './model/acc-base-model'; import { AccumulationAnnotationSettings } from './model/acc-base'; import { AccumulationAnnotation } from './annotation/annotation'; import { IPrintEventArgs } from '../chart/model/chart-interface'; import { Alignment, ExportType, SelectionPattern } from '../common/utils/enum'; import { getTitle } from '../common/utils/helper'; import { Index } from '../common/model/base'; import { IThemeStyle } from '../chart/model/chart-interface'; import { IAccResizeEventArgs, IAccBeforeResizeEventArgs } from './model/pie-interface'; import { DataManager } from '@syncfusion/ej2-data'; import { Export } from '../chart/print-export/export'; import { ExportUtils } from '../common/utils/export'; /** * Represents the AccumulationChart control. * ```html * <div id="accumulation"/> * <script> * var accObj = new AccumulationChart({ }); * accObj.appendTo("#accumulation"); * </script> * ``` * * @public */ @NotifyPropertyChanges export class AccumulationChart extends Component<HTMLElement> implements INotifyPropertyChanged { // Module declarations /** * `accBaseModue` is used to define the common functionalities of accumulation series * * @private */ public accBaseModule: AccumulationBase; /** * `pieSeriesModule` is used to render pie series. * * @private */ public pieSeriesModule: PieSeries; /** * `funnelSeriesModule` is used to render funnel series. * * @private */ public funnelSeriesModule: FunnelSeries; /** * `pyramidSeriesModule` is used to render funnel series. * * @private */ public pyramidSeriesModule: PyramidSeries; /** * `accumulationLegendModule` is used to manipulate and add legend in accumulation chart. */ public accumulationLegendModule: AccumulationLegend; /** * `accumulationDataLabelModule` is used to manipulate and add dataLabel in accumulation chart. */ public accumulationDataLabelModule: AccumulationDataLabel; /** * `accumulationTooltipModule` is used to manipulate and add tooltip in accumulation chart. */ public accumulationTooltipModule: AccumulationTooltip; /** * `accumulationSelectionModule` is used to manipulate and add selection in accumulation chart. */ public accumulationSelectionModule: AccumulationSelection; /** * `annotationModule` is used to manipulate and add annotation in chart. */ public annotationModule: AccumulationAnnotation; /** * Export Module is used to export Accumulation chart. */ public exportModule: Export; // Property declarations goes here /** * The width of the chart as a string in order to provide input as both like '100px' or '100%'. * If specified as '100%, chart will render to the full width of its parent element. * * @default null */ @Property(null) public width: string; /** * The height of the chart as a string in order to provide input as both like '100px' or '100%'. * If specified as '100%, chart will render to the full height of its parent element. * * @default null */ @Property(null) public height: string; /** * Title for accumulation chart * * @default null */ @Property(null) public title: string; /** * The background image of the chart that accepts value in string as url link or location of an image. * * @default null */ @Property(null) public backgroundImage: string; /** * Center of pie */ @Complex<PieCenterModel>({}, PieCenter) public center: PieCenterModel; /** * Specifies the dataSource for the AccumulationChart. It can be an array of JSON objects or an instance of DataManager. * ```html * <div id='Pie'></div> * ``` * ```typescript * let dataManager: DataManager = new DataManager({ * url: 'http://mvc.syncfusion.com/Services/Northwnd.svc/Tasks/' * }); * let query: Query = new Query().take(50).where('Estimate', 'greaterThan', 0, false); * let pie: AccumulationChart = new AccumulationChart({ * ... * dataSource: dataManager, * series: [{ * xName: 'Id', * yName: 'Estimate', * query: query * }], * ... * }); * pie.appendTo('#Pie'); * ``` * * @default '' */ @Property('') public dataSource: Object | DataManager; /** * Options for customizing the `title` of accumulation chart. */ @Complex<FontModel>(Theme.chartTitleFont, Font) public titleStyle: FontModel; /** * SubTitle for accumulation chart * * @default null */ @Property(null) public subTitle: string; /** * Options for customizing the `subtitle` of accumulation chart. */ @Complex<FontModel>(Theme.chartSubTitleFont, Font) public subTitleStyle: FontModel; /** * Options for customizing the legend of accumulation chart. */ @Complex<LegendSettingsModel>({}, LegendSettings) public legendSettings: LegendSettingsModel; /** * Options for customizing the tooltip of accumulation chart. */ @Complex<TooltipSettingsModel>({}, TooltipSettings) public tooltip: TooltipSettingsModel; /** * Specifies whether point has to get selected or not. Takes value either 'None 'or 'Point' * * @default None */ @Property('None') public selectionMode: AccumulationSelectionMode; /** * Specifies whether point has to get highlighted or not. Takes value either 'None 'or 'Point' * * @default None */ @Property('None') public highLightMode: AccumulationSelectionMode; /** * Specifies whether series or data point for accumulation chart has to be selected. They are, * * none: sets none as selecting pattern to accumulation chart . * * chessboard: sets chess board as selecting pattern accumulation chart . * * dots: sets dots as selecting pattern accumulation chart . * * diagonalForward: sets diagonal forward as selecting pattern to accumulation chart . * * crosshatch: sets crosshatch as selecting pattern to accumulation chart. * * pacman: sets pacman selecting pattern to accumulation chart. * * diagonalbackward: sets diagonal backward as selecting pattern to accumulation chart. * * grid: sets grid as selecting pattern to accumulation chart. * * turquoise: sets turquoise as selecting pattern to accumulation chart. * * star: sets star as selecting pattern to accumulation chart. * * triangle: sets triangle as selecting pattern to accumulation chart. * * circle: sets circle as selecting pattern to accumulation chart. * * tile: sets tile as selecting pattern to accumulation chart. * * horizontaldash: sets horizontal dash as selecting pattern to accumulation chart. * * verticaldash: sets vertical dash as selecting pattern to accumulation chart. * * rectangle: sets rectangle as selecting pattern. * * box: sets box as selecting pattern to accumulation chart. * * verticalstripe: sets vertical stripe as selecting pattern to accumulation chart. * * horizontalstripe: sets horizontal stripe as selecting pattern to accumulation chart. * * bubble: sets bubble as selecting pattern to accumulation chart. * * @default None */ @Property('None') public selectionPattern: SelectionPattern; /** * Specifies whether series or data point has to be selected. They are, * * none: sets none as highlighting pattern to accumulation chart. * * chessboard: sets chess board as highlighting pattern to accumulation chart. * * dots: sets dots as highlighting pattern to accumulation chart. * * diagonalForward: sets diagonal forward as highlighting pattern to accumulation chart. * * crosshatch: sets crosshatch as highlighting pattern to accumulation chart. * * pacman: sets pacman highlighting pattern to accumulation chart. * * diagonalbackward: sets diagonal backward as highlighting pattern to accumulation chart. * * grid: sets grid as highlighting pattern to accumulation chart. * * turquoise: sets turquoise as highlighting pattern to accumulation chart. * * star: sets star as highlighting pattern to accumulation chart. * * triangle: sets triangle as highlighting pattern to accumulation chart. * * circle: sets circle as highlighting pattern to accumulation chart. * * tile: sets tile as highlighting pattern to accumulation chart. * * horizontaldash: sets horizontal dash as highlighting pattern to accumulation chart. * * verticaldash: sets vertical dash as highlighting pattern to accumulation chart. * * rectangle: sets rectangle as highlighting pattern to accumulation chart. * * box: sets box as highlighting pattern to accumulation chart. * * verticalstripe: sets vertical stripe as highlighting pattern to accumulation chart. * * horizontalstripe: sets horizontal stripe as highlighting pattern to accumulation chart. * * bubble: sets bubble as highlighting pattern to accumulation chart. * * @default None */ @Property('None') public highlightPattern: SelectionPattern; /** * If set true, enables the border in pie and accumulation chart while mouse moving. * * @default true */ @Property(true) public enableBorderOnMouseMove: boolean; /** * If set true, enables the multi selection in accumulation chart. It requires `selectionMode` to be `Point`. * * @default false */ @Property(false) public isMultiSelect: boolean; /** * If set true, enables the animation for both chart and accumulation. * * @default true */ @Property(true) public enableAnimation: boolean; /** * Specifies the point indexes to be selected while loading a accumulation chart. * It requires `selectionMode` to be `Point`. * ```html * <div id='Pie'></div> * ``` * ```typescript * let pie: AccumulationChart = new AccumulationChart({ * ... * selectionMode: 'Point', * selectedDataIndexes: [ { series: 0, point: 1}, * { series: 2, point: 3} ], * ... * }); * pie.appendTo('#Pie'); * ``` * * @default [] */ @Collection<IndexesModel>([], Indexes) public selectedDataIndexes: IndexesModel[]; /** * Options to customize the left, right, top and bottom margins of accumulation chart. */ @Complex<MarginModel>({}, Margin) public margin: MarginModel; /** * If set true, labels for the point will be placed smartly without overlapping. * * @default true */ @Property(true) public enableSmartLabels: boolean; /** * Options for customizing the color and width of the chart border. */ @Complex<BorderModel>({ color: '#DDDDDD', width: 0 }, Border) public border: BorderModel; /** * The background color of the chart, which accepts value in hex, rgba as a valid CSS color string. * * @default null */ @Property(null) public background: string; /** * The configuration for series in accumulation chart. */ @Collection<AccumulationSeriesModel>([{}], AccumulationSeries) public series: AccumulationSeriesModel[]; /** * The configuration for annotation in chart. */ @Collection<AccumulationAnnotationSettingsModel>([{}], AccumulationAnnotationSettings) public annotations: AccumulationAnnotationSettingsModel[]; /** * Specifies the theme for accumulation chart. * * @default 'Material' */ @Property('Material') public theme: AccumulationTheme; /** * Specifies whether a grouping separator should be used for a number. * * @default false */ @Property(false) public useGroupingSeparator: boolean; /** * To enable export feature in chart. * * @default true */ @Property(true) public enableExport: boolean; /** * To enable export feature in blazor chart. * * @default false */ @Property(false) public allowExport: boolean; /** * Triggers after accumulation chart loaded. * * @event * @blazorProperty 'Loaded' */ @Event() public loaded: EmitType<IAccLoadedEventArgs>; /** * Triggers before accumulation chart load. * * @event */ @Event() public load: EmitType<IAccLoadedEventArgs>; /** * Triggers before the series gets rendered. * * @event * @deprecated */ @Event() public seriesRender: EmitType<IAccSeriesRenderEventArgs>; /** * Triggers before the legend gets rendered. * * @event * @deprecated */ @Event() public legendRender: EmitType<ILegendRenderEventArgs>; /** * Triggers before the data label for series gets rendered. * * @event * @deprecated */ @Event() public textRender: EmitType<IAccTextRenderEventArgs>; /** * Triggers before the tooltip for series gets rendered. * * @event */ @Event() public tooltipRender: EmitType<ITooltipRenderEventArgs>; /** * Triggers before each points for series gets rendered. * * @event * @deprecated */ @Event() public pointRender: EmitType<IAccPointRenderEventArgs>; /** * Triggers before the annotation gets rendered. * * @event * @deprecated */ @Event() public annotationRender: EmitType<IAnnotationRenderEventArgs>; /** * Triggers before the prints gets started. * * @event * @blazorProperty 'OnPrint' */ @Event() public beforePrint: EmitType<IPrintEventArgs>; /** * Triggers on hovering the accumulation chart. * * @event * @blazorProperty 'OnChartMouseMove' */ @Event() public chartMouseMove: EmitType<IMouseEventArgs>; /** * Triggers on clicking the accumulation chart. * * @event * @blazorProperty 'OnChartMouseClick' */ @Event() public chartMouseClick: EmitType<IMouseEventArgs>; /** * Triggers on point click. * * @event * @blazorProperty 'OnPointClick' */ @Event() public pointClick: EmitType<IPointEventArgs>; /** * Triggers on point move. * * @event * @blazorProperty 'PointMoved' */ @Event() public pointMove: EmitType<IPointEventArgs>; /** * Triggers after animation gets completed for series. * * @event * @blazorProperty 'OnAnimationComplete' */ @Event() public animationComplete: EmitType<IAccAnimationCompleteEventArgs>; /** * Triggers on mouse down. * * @event * @blazorProperty 'OnChartMouseDown' */ @Event() public chartMouseDown: EmitType<IMouseEventArgs>; /** * Triggers while cursor leaves the accumulation chart. * * @event * @blazorProperty 'OnChartMouseLeave' */ @Event() public chartMouseLeave: EmitType<IMouseEventArgs>; /** * Triggers on mouse up. * * @event * @blazorProperty 'OnChartMouseUp' */ @Event() public chartMouseUp: EmitType<IMouseEventArgs>; /** * Triggers before window resize. * @event * @blazorProperty 'BeforeResize' */ @Event() public beforeResize: EmitType<IAccBeforeResizeEventArgs>; /** * Triggers after window resize. * * @event * @blazorProperty 'Resized' */ @Event() public resized: EmitType<IAccResizeEventArgs>; /** * Triggers after the export completed. * * @event * @blazorProperty 'AfterExport' */ @Event() public afterExport: EmitType<IAfterExportEventArgs>; /** * Defines the currencyCode format of the accumulation chart * * @private * @aspType string */ @Property('USD') private currencyCode: string; /** * Animate the series bounds on data change. * * @private */ public animate(duration?: number): void { this.duration = duration ? duration : 700; this.animateselected = true; this.animateSeries = false; let temIndex: number = 0; const tempcolor: string[] = []; const tempindex: number[] = []; const tempindex1: number[] = []; const currentSeries: AccumulationSeries = this.visibleSeries[0]; let datasource: object[] = []; datasource = currentSeries.dataSource as Object[]; currentSeries.sumOfPoints = 0; if (currentSeries.points.length < Object.keys(currentSeries.dataSource).length) { this.refresh(); } else if (currentSeries.points.length > Object.keys(currentSeries.dataSource).length) { const currentSeries: AccumulationSeries = this.visibleSeries[0]; currentSeries.points = currentSeries.points.filter((entry1: AccPoints) => { entry1.visible = false; tempindex.push(entry1.index); tempcolor.push(entry1.color); return (datasource).some((entry2: AccPoints) => { const accPoint: AccPoints = entry2 as AccPoints; if (entry1.x === accPoint.x) { entry1.visible = true; tempindex1.push(entry1.index); entry1.index = temIndex; temIndex++; } return entry1.x === accPoint.x; }); }); const missing: number[] = tempindex.filter((item: number) => tempindex1.indexOf(item) < 0); const interval: number = tempindex.length - missing.length; for (let i: number = (tempindex.length - 1); i >= interval; i--) { removeElement('container_Series_0_Point_' + tempindex[i]); } for (let i: number = 0; i < currentSeries.points.length; i++) { currentSeries.points[i].y = currentSeries.dataSource[i].y; currentSeries.points[i].color = tempcolor[i]; currentSeries.sumOfPoints += currentSeries.dataSource[i].y; } this.redraw = this.enableAnimation; this.animateSeries = false; this.calculateBounds(); this.renderElements(); } else { for (let i: number = 0; i < currentSeries.points.length; i++) { currentSeries.points[i].y = currentSeries.dataSource[i][currentSeries.yName]; currentSeries.points[i].color = currentSeries.dataSource[i][currentSeries.pointColorMapping] != null ? currentSeries.dataSource[i][currentSeries.pointColorMapping] : currentSeries.points[i].color; currentSeries.sumOfPoints += currentSeries.dataSource[i][currentSeries.yName]; } this.redraw = this.enableAnimation; this.animateSeries = false; this.removeSvg(); this.refreshPoints(currentSeries.points); this.renderElements(); } } // internal properties for Accumulation charts /** @private */ public svgObject: Element; /** @private */ private animateselected: boolean = false; /** @public */ public duration: number; /** @private */ public initialClipRect: Rect; /** @private */ public availableSize: Size; /** @private */ public renderer: SvgRenderer | CanvasRenderer; /** @private */ public intl: Internationalization; /** @private */ public visibleSeries: AccumulationSeries[]; /** @private */ public seriesCounts: number; /** @private */ public explodeDistance: number = 0; /** @private */ public mouseX: number; /** @private */ public mouseY: number; private resizeTo: number; /** @private */ public origin: ChartLocation; /** @private */ public get type(): AccumulationType { if (this.series && this.series.length) { return this.series[0].type; } return 'Pie'; } /** @private */ public isTouch: boolean; /** @private */ public redraw: boolean; /** @private */ public animateSeries: boolean; private titleCollection: string[]; private subTitleCollection: string[]; /** @private */ public themeStyle: IThemeStyle; private chartid: number = 57724; /** @private */ public isBlazor: boolean; /** @private */ public accumulationResizeBound: EventListenerOrEventListenerObject; /** * Constructor for creating the AccumulationChart widget * * @private */ constructor(options?: AccumulationChartModel, element?: string | HTMLElement) { super(options, element); } // accumulation chart methods /** * To create svg object, renderer and binding events for the container. */ protected preRender(): void { const blazor: string = 'Blazor'; this.isBlazor = window[blazor]; this.allowServerDataBinding = false; this.unWireEvents(); this.setCulture(); this.animateSeries = true; if (this.element.id === '') { const collection: number = document.getElementsByClassName('e-accumulationchart').length; this.element.id = 'acc_chart_' + this.chartid + '_' + collection; } calculateSize(this); this.wireEvents(); } /** * Themeing for chart goes here */ private setTheme(): void { /*! Set theme for accumulation chart */ this.themeStyle = getThemeColor(this.theme); } /** * To render the accumulation chart elements */ protected render(): void { if (this.element.className.indexOf('e-accumulationchart') === -1) { this.element.classList.add('e-accumulationchart'); } const loadEventData: IAccLoadedEventArgs = { chart: this.isBlazor ? {} as AccumulationChart : this, accumulation: this.isBlazor ? {} as AccumulationChart : this, theme: this.theme, name: load, cancel: false }; this.trigger(load, loadEventData, () => { this.theme = this.isBlazor ? loadEventData.theme : this.theme; this.setTheme(); this.accBaseModule = new AccumulationBase(this); this.pieSeriesModule = new PieSeries(this); this.calculateVisibleSeries(); this.processData(); this.renderComplete(); this.allowServerDataBinding = true; }); } /** * Method to unbind events for accumulation chart */ private unWireEvents(): void { /*! Find the Events type */ const isIE11Pointer: Boolean = Browser.isPointer; const start: string = Browser.touchStartEvent; const move: string = Browser.touchMoveEvent; const stop: string = Browser.touchEndEvent; const cancel: string = isIE11Pointer ? 'pointerleave' : 'mouseleave'; /*! UnBind the Event handler */ EventHandler.remove(this.element, move, this.accumulationMouseMove); EventHandler.remove(this.element, stop, this.accumulationMouseEnd); EventHandler.remove(this.element, start, this.accumulationMouseStart); EventHandler.remove(this.element, 'click', this.accumulationOnMouseClick); EventHandler.remove(this.element, 'contextmenu', this.accumulationRightClick); EventHandler.remove(this.element, cancel, this.accumulationMouseLeave); window.removeEventListener( (Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.accumulationResizeBound ); } /** * Method to bind events for the accumulation chart */ private wireEvents(): void { /** * To fix react timeout destroy issue. */ if (!this.element) { return; } /*! Find the Events type */ const isIE11Pointer: Boolean = Browser.isPointer; const start: string = Browser.touchStartEvent; const stop: string = Browser.touchEndEvent; const move: string = Browser.touchMoveEvent; const cancel: string = isIE11Pointer ? 'pointerleave' : 'mouseleave'; /*! Bind the Event handler */ EventHandler.add(this.element, move, this.accumulationMouseMove, this); EventHandler.add(this.element, stop, this.accumulationMouseEnd, this); EventHandler.add(this.element, start, this.accumulationMouseStart, this); EventHandler.add(this.element, 'click', this.accumulationOnMouseClick, this); EventHandler.add(this.element, 'contextmenu', this.accumulationRightClick, this); EventHandler.add(this.element, cancel, this.accumulationMouseLeave, this); this.accumulationResizeBound = this.accumulationResize.bind(this); window.addEventListener( (Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.accumulationResizeBound ); new Touch(this.element); // To avoid geasture blocking for browser /*! Apply the style for chart */ this.setStyle(<HTMLElement>this.element); } /** * Method to set mouse x, y from events */ private setMouseXY(e: PointerEvent): void { let pageX: number; let pageY: number; const svgRectElement: Element = getElement(this.element.id + '_svg'); if (svgRectElement && this.element) { const svgRect: ClientRect = svgRectElement.getBoundingClientRect(); const rect: ClientRect = this.element.getBoundingClientRect(); if (e.type.indexOf('touch') > -1) { this.isTouch = true; const touchArg: TouchEvent = <TouchEvent & PointerEvent>e; pageY = touchArg.changedTouches[0].clientY; pageX = touchArg.changedTouches[0].clientX; } else { this.isTouch = e.pointerType === 'touch' || e.pointerType === '2'; pageX = e.clientX; pageY = e.clientY; } this.mouseY = (pageY - rect.top) - Math.max(svgRect.top - rect.top, 0); this.mouseX = (pageX - rect.left) - Math.max(svgRect.left - rect.left, 0); } } /** * Handles the mouse end. * * @returns {boolean} Mouse end of accumulation chart. * @private */ public accumulationMouseEnd(e: PointerEvent): boolean { this.setMouseXY(e); this.trigger(chartMouseUp, { target: (<Element>e.target).id, x: this.mouseX, y: this.mouseY }); if (this.isTouch) { this.titleTooltip(e, this.mouseX, this.mouseY, this.isTouch); if (this.accumulationDataLabelModule && this.visibleSeries[0].dataLabel.visible) { this.accumulationDataLabelModule.move(e, this.mouseX, this.mouseY, this.isTouch); } if (this.accumulationLegendModule && this.legendSettings.visible) { this.accumulationLegendModule.move(e); } } this.notify(Browser.touchEndEvent, e); return false; } /*public removeSvgOffset(x: number, y: number): ChartLocation { let rect: ClientRect = this.element.getBoundingClientRect(); let svgRect: ClientRect = getElement(this.element.id + '_svg').getBoundingClientRect(); return { x: (x - rect.left) - Math.max(svgRect.left - rect.left, 0), y: (y - rect.top) - Math.max(svgRect.top - rect.top, 0)}; }*/ /** * Handles the mouse start. * * @returns {boolean} Mouse start of accumulation chart. * @private */ public accumulationMouseStart(e: PointerEvent): boolean { this.setMouseXY(e); this.trigger(chartMouseDown, { target: (<Element>e.target).id, x: this.mouseX, y: this.mouseY }); return false; } /** * Handles the accumulation chart resize. * * @returns {boolean} Resize method of accumulation chart. * @private */ public accumulationResize(): boolean { this.animateSeries = false; const args: IAccResizeEventArgs = { accumulation: this.isBlazor ? {} as AccumulationChart : this, previousSize: new Size( this.availableSize.width, this.availableSize.height ), name: resized, currentSize: new Size(0, 0), chart: this.isBlazor ? {} as AccumulationChart : this }; let beforeResizeArgs: IAccBeforeResizeEventArgs = { name: 'beforeResize', cancelResizedEvent: false }; if (this.resizeTo) { clearTimeout(this.resizeTo); } this.trigger(beforeResize, beforeResizeArgs); if (!beforeResizeArgs.cancelResizedEvent) { this.resizeTo = +setTimeout( (): void => { if (this.isDestroyed) { clearTimeout(this.resizeTo); return; } calculateSize(this); args.currentSize = this.availableSize; this.trigger(resized, args); this.refreshSeries(); this.refreshChart(); }, 500); } return false; } /** * Handles the print method for accumulation chart control. */ public print(id?: string[] | string | Element): void { // To handle the print funtion in IE and Edge browsers const clippath: string = document.getElementById(this.element.id + '_Series_0').style.clipPath; document.getElementById(this.element.id + '_Series_0').style.clipPath = ''; const exportChart: ExportUtils = new ExportUtils(this); exportChart.print(id); document.getElementById(this.element.id + '_Series_0').style.clipPath = clippath; } /** * Export method for the chart. */ public export(type: ExportType, fileName: string): void { if (this.exportModule) { this.exportModule.export(type, fileName); if (this.afterExport) { this.exportModule.getDataUrl(this); } } } /** * Applying styles for accumulation chart element */ private setStyle(element: HTMLElement): void { element.style.touchAction = 'element'; element.style.msTouchAction = 'element'; element.style.msContentZooming = 'none'; element.style.msUserSelect = 'none'; element.style.webkitUserSelect = 'none'; element.style.position = 'relative'; element.style.display = 'block'; } /** * Method to set the annotation content dynamically for accumulation. */ public setAnnotationValue(annotationIndex: number, content: string): void { const annotation: AccumulationAnnotationSettings = <AccumulationAnnotationSettings>this.annotations[annotationIndex]; let element: HTMLElement; const parentNode: Element = getElement(this.element.id + '_Annotation_Collections'); if (content) { annotation.content = content; if (parentNode) { element = this.createElement('div'); removeElement(this.element.id + '_Annotation_' + annotationIndex); this.annotationModule.processAnnotation( annotation, annotationIndex, element ); parentNode.appendChild(element.children[0]); } else { this.annotationModule.renderAnnotations( getElement(this.element.id + '_Secondary_Element') ); } } } /** * Handles the mouse move on accumulation chart. * * @returns {boolean} Mouse move of accumulation chart. * @private */ public accumulationMouseMove(e: PointerEvent): boolean { if (!getElement(this.element.id + '_svg')) { return false; } this.setMouseXY(e); this.trigger(chartMouseMove, { target: (<Element>e.target).id, x: this.mouseX, y: this.mouseY }); if (this.pointMove) { this.triggerPointEvent(pointMove, <Element>e.target, e); } if (this.accumulationLegendModule && this.legendSettings.visible) { this.accumulationLegendModule.move(e); } if (this.accumulationDataLabelModule && this.visibleSeries[0] && this.visibleSeries[0].dataLabel.visible) { this.accumulationDataLabelModule.move(e, this.mouseX, this.mouseY); } if (!this.isTouch) { this.titleTooltip(e, this.mouseX, this.mouseY); } if (this.enableBorderOnMouseMove && this.type === 'Pie' && this.pieSeriesModule && withInBounds(this.mouseX, this.mouseY, this.initialClipRect)) { this.pieSeriesModule.findSeries(e); } this.notify(Browser.touchMoveEvent, e); return false; } public titleTooltip(event: Event, x: number, y: number, isTouch?: boolean): void { const targetId: string = (<HTMLElement>event.target).id; const id: boolean = (targetId === (this.element.id + '_title') || targetId === (this.element.id + '_subTitle') || targetId === (this.element.id + '_chart_legend_title')); if (((<HTMLElement>event.target).textContent.indexOf('...') > -1) && id) { const title: string = (targetId === (this.element.id + '_title')) ? this.title : (targetId === (this.element.id + '_subTitle')) ? this.subTitle : this.legendSettings.title; showTooltip( title, x, y, this.element.offsetWidth, this.element.id + '_EJ2_Title_Tooltip', getElement(this.element.id + '_Secondary_Element'), isTouch ); } else { removeElement(this.element.id + '_EJ2_Title_Tooltip'); } } /** * Handles the mouse click on accumulation chart. * * @returns {boolean} Mouse click of accumulation chart. * @private */ public accumulationOnMouseClick(e: PointerEvent): boolean { this.setMouseXY(e); if (this.accumulationLegendModule && this.legendSettings.visible) { this.accumulationLegendModule.click(e); } if (this.selectionMode !== 'None' && this.accumulationSelectionModule) { this.accumulationSelectionModule.calculateSelectedElements(this, e); } if (this.visibleSeries[0].explode) { this.accBaseModule.processExplode(e); } if (this.enableBorderOnMouseMove && this.pieSeriesModule && this.type === 'Pie') { this.pieSeriesModule.findSeries(e); } this.trigger(chartMouseClick, { target: (<Element>e.target).id, x: this.mouseX, y: this.mouseY }); if (this.pointClick) { this.triggerPointEvent(pointClick, <Element>e.target, e); } return false; } private triggerPointEvent(event: string, element: Element, e?: PointerEvent | TouchEvent): void { const evt: PointerEvent = e as PointerEvent; const indexes: Index = indexFinder(element.id, true); if (indexes.series >= 0 && indexes.point >= 0) { this.trigger(event, { series: this.isBlazor ? {} : this.series[indexes.series], point: (<AccumulationSeries>this.series[indexes.series]).points[indexes.point], seriesIndex: indexes.series, pointIndex: indexes.point, x: this.mouseX, y: this.mouseY, pageX: evt.pageX, pageY: evt.pageY }); } } /** * Handles the mouse right click on accumulation chart. * * @returns {boolean} Right click of accumulation chart. * @private */ public accumulationRightClick(event: MouseEvent | PointerEvent): boolean { if (event.buttons === 2 || (<PointerEvent>event).pointerType === 'touch') { event.preventDefault(); event.stopPropagation(); return false; } return true; } /** * Handles the mouse leave on accumulation chart. * * @returns {boolean} Mouse leave of accumulation chart. * @private */ public accumulationMouseLeave(e: PointerEvent): boolean { this.setMouseXY(e); this.trigger(chartMouseLeave, { target: (<Element>e.target).id, x: this.mouseX, y: this.mouseY }); this.notify(Browser.isPointer ? 'pointerleave' : 'mouseleave', e); let borderElement: Element = document.getElementById(this.element.id + 'PointHover_Border'); if (borderElement) { this.pieSeriesModule.removeBorder(borderElement, 1000); borderElement = null; } return false; } /** * Method to set culture for chart */ private setCulture(): void { this.intl = new Internationalization(); } /** * Method to create SVG element for accumulation chart. */ private createPieSvg(): void { this.removeSvg(); createSvg(this); } /** * To Remove the SVG from accumulation chart. * * @returns {boolean} Remove svg. * @private */ public removeSvg(): void { if (this.redraw) { return null; } blazorTemplatesReset(this); removeElement(this.element.id + '_Secondary_Element'); if (this.svgObject) { while (this.svgObject.childNodes.length > 0) { this.svgObject.removeChild(this.svgObject.firstChild); } if (!this.svgObject.hasChildNodes() && this.svgObject.parentNode) { remove(this.svgObject); } } removeElement('EJ2_legend_tooltip'); removeElement('EJ2_datalabel_tooltip'); removeElement(this.element.id + 'PointHover_Border'); } /** * Method to create the secondary element for tooltip, datalabel and annotaitons. */ private createSecondaryElement(): void { const element: Element = redrawElement(this.redraw, this.element.id + '_Secondary_Element') || this.createElement('div', { id: this.element.id + '_Secondary_Element', styles: 'position: relative' }); appendChildElement(false, this.element, element, this.redraw); } /** * Method to find visible series based on series types */ private calculateVisibleSeries(): void { this.visibleSeries = []; for (let i: number = 0, length: number = this.series.length; i < length; i++) { (this.series[i] as AccumulationSeries).index = i; if (this.series[i].type === this.type && this.visibleSeries.length === 0) { this.visibleSeries.push(this.series[i] as AccumulationSeries); break; } } } /** * To find points from dataSource */ private processData(render: boolean = true): void { this.seriesCounts = 0; for (const series of this.visibleSeries) { series.dataModule = new Data(series.dataSource || this.dataSource, series.query); series.refreshDataManager(this, render); } } /** * To refresh the accumulation chart * * @private */ public refreshChart(): void { this.doGrouppingProcess(); this.createPieSvg(); this.calculateBounds(); this.renderElements(); removeElement('chartmeasuretext'); } /** * Method to find groupped points */ private doGrouppingProcess(): void { const series: AccumulationSeries = this.visibleSeries[0]; if (!isNullOrUndefined(series.resultData) && ((!isNullOrUndefined(series.lastGroupTo) && series.lastGroupTo !== series.groupTo))) { series.getPoints(series.resultData, this); } } /** * Method to calculate bounds for accumulation chart */ private calculateBounds(): void { this.initialClipRect = new Rect(this.margin.left, this.margin.top, this.availableSize.width, this.availableSize.height); this.titleCollection = []; this.subTitleCollection = []; let titleHeight: number = 0; let subTitleHeight: number = 0; let maxWidth: number = 0; let titleWidth: number = 0; this.titleCollection = getTitle(this.title, this.titleStyle, this.initialClipRect.width); titleHeight = this.title ? measureText(this.title, this.titleStyle).height * this.titleCollection.length : titleHeight; if (this.subTitle) { for (const titleText of this.titleCollection) { titleWidth = measureText(titleText, this.titleStyle).width; maxWidth = titleWidth > maxWidth ? titleWidth : maxWidth; } this.subTitleCollection = getTitle(this.subTitle, this.subTitleStyle, maxWidth); subTitleHeight = (measureText(this.subTitle, this.subTitleStyle).height * this.subTitleCollection.length); } subtractRect( this.initialClipRect, new Rect( 0, (subTitleHeight + titleHeight), this.margin.right + this.margin.left, this.margin.bottom + this.margin.top ) ); this.calculateLegendBounds(); } /* * Method to calculate legend bounds for accumulation chart */ private calculateLegendBounds(): void { if (!this.accumulationLegendModule || !this.legendSettings.visible) { return null; } this.accumulationLegendModule.getLegendOptions(this, <AccumulationSeries[]>this.visibleSeries); this.accumulationLegendModule.calculateLegendBounds(this.initialClipRect, this.availableSize, null); } /** * To render elements for accumulation chart * * @private */ public renderElements(): void { this.renderBorder(); this.createSecondaryElement(); this.renderSeries(); this.renderTitle(); this.renderLegend(); appendChildElement(false, this.element, this.svgObject, this.redraw); this.processSelection(); this.processExplode(); this.renderAnnotation(); this.setSecondaryElementPosition(); updateBlazorTemplate(this.element.id + '_DataLabel', 'Template', this.series[0].dataLabel); this.trigger('loaded', { accumulation: this.isBlazor ? {} : this, chart: this.isBlazor ? {} : this }); this.animateSeries = false; } /** * To set the left and top position for data label template for center aligned chart * * @private */ public setSecondaryElementPosition(): void { const tooltipParent: HTMLDivElement = getElement(this.element.id + '_Secondary_Element') as HTMLDivElement; if (!tooltipParent) { return; } const rect: ClientRect = this.element.getBoundingClientRect(); const svgRect: ClientRect = getElement(this.element.id + '_svg').getBoundingClientRect(); tooltipParent.style.left = Math.max(svgRect.left - rect.left, 0) + 'px'; tooltipParent.style.top = Math.max(svgRect.top - rect.top, 0) + 'px'; } /** * To render the annotaitions for accumulation series. * * @private */ public renderAnnotation(): void { if (this.annotationModule) { this.annotationModule.renderAnnotations( getElement(this.element.id + '_Secondary_Element') ); } } /** * Method to process the explode in accumulation chart * * @private */ public processExplode(): void { if (this.redraw) { return null; } if (!this.visibleSeries[0].explode) { return null; } this.accBaseModule.invokeExplode(); } /** * Method to render series for accumulation chart */ private renderSeries(): void { if (!this.redraw) { this.svgObject.appendChild(this.renderer.createGroup({ id: this.element.id + '_SeriesCollection' })); } for (const series of this.visibleSeries) { if (series.visible && this[(firstToLowerCase(series.type) + 'SeriesModule')]) { this[(firstToLowerCase(series.type) + 'SeriesModule')].initProperties(this, series); series.renderSeries(this, this.redraw); } } } /** * Method to render border for accumulation chart */ private renderBorder(): void { const padding: number = this.border.width; appendChildElement( false, this.svgObject, this.renderer.drawRectangle(new RectOption( this.element.id + '_border', this.background || this.themeStyle.background, this.border, 1, new Rect(padding / 2, padding / 2, this.availableSize.width - padding, this.availableSize.height - padding)) ), this.redraw ); // to draw back ground image for accumulation chart const backGroundImage: string = this.backgroundImage; if (backGroundImage) { const image: ImageOption = new ImageOption( this.availableSize.height - padding, this.availableSize.width - padding, backGroundImage, 0, 0, this.element.id + '_background', 'visible', 'none' ); appendChildElement(false, this.svgObject, this.renderer.drawImage(image) as HTMLElement, this.redraw); } } /** * Method to render legend for accumulation chart */ private renderLegend(): void { if (!this.accumulationLegendModule || !this.legendSettings.visible) { return null; } if (this.accumulationLegendModule.legendCollections.length) { if (this.visibleSeries[0].type === 'Pie') { this.accumulationLegendModule.getSmartLegendLocation( this.visibleSeries[0].labelBound, this.accumulationLegendModule.legendBounds, this.margin); } this.accumulationLegendModule.renderLegend( this, this.legendSettings, this.accumulationLegendModule.legendBounds, this.redraw); } } /** * To process the selection in accumulation chart * * @private */ public processSelection(): void { if (!this.accumulationSelectionModule || this.selectionMode === 'None') { return null; } const selectedDataIndexes: Indexes[] = <Indexes[]>extend([], this.accumulationSelectionModule.selectedDataIndexes, null, true); this.accumulationSelectionModule.invokeSelection(this); if (selectedDataIndexes.length > 0) { this.accumulationSelectionModule.selectedDataIndexes = selectedDataIndexes; this.accumulationSelectionModule.redrawSelection(this); } } /** * To render title for accumulation chart */ private renderTitle(): void { const margin: MarginModel = this.margin; if (!this.title) { return null; } const alignment: Alignment = this.titleStyle.textAlignment; const getAnchor: string = alignment === 'Near' ? 'start' : alignment === 'Far' ? 'end' : 'middle'; const titleSize: Size = measureText(this.title, this.titleStyle); const rect: Rect = new Rect( margin.left, 0, this.availableSize.width - margin.left - margin.right, 0 ); const options: TextOption = new TextOption( this.element.id + '_title', titlePositionX( rect, this.titleStyle ), this.margin.top + (titleSize.height * 3 / 4), getAnchor, this.titleCollection, '', 'auto' ); const element: Element = textElement( this.renderer, options, this.titleStyle, this.titleStyle.color || this.themeStyle.chartTitle, this.svgObject, false, this.redraw ); if (element) { element.setAttribute('aria-label', this.title); } if (this.subTitle) { this.renderSubTitle(options); } } private renderSubTitle(options: TextOption): void { let maxWidth: number = 0; let titleWidth: number = 0; const padding: number = 10; const alignment: Alignment = this.titleStyle.textAlignment; const getAnchor: Function = (alignment: Alignment): string => { return alignment === 'Near' ? 'start' : alignment === 'Far' ? 'end' : 'middle'; }; const subTitleElementSize: Size = measureText(this.subTitle, this.subTitleStyle); for (const titleText of this.titleCollection) { titleWidth = measureText(titleText, this.titleStyle).width; maxWidth = titleWidth > maxWidth ? titleWidth : maxWidth; } const rect: Rect = new Rect( alignment === 'Center' ? (options.x - maxWidth / 2) : alignment === 'Far' ? options.x - maxWidth : options.x, 0, maxWidth, 0 ); const subTitleOption: TextOption = new TextOption( this.element.id + '_subTitle', titlePositionX( rect, this.subTitleStyle ), options.y * options.text.length + ((subTitleElementSize.height) * 3 / 4) + padding, getAnchor(this.subTitleStyle.textAlignment), this.subTitleCollection, '', 'auto' ); textElement(this.renderer, subTitleOption, this.subTitleStyle, this.subTitleStyle.color || this.themeStyle.chartTitle, this.svgObject, false, this.redraw); } /** * To get the series parent element * * @private */ public getSeriesElement(): Element { return this.svgObject.getElementsByTagName('g')[0]; } /** * To refresh the all visible series points * * @private */ public refreshSeries(): void { for (const series of this.visibleSeries) { this.refreshPoints(series.points); } } /** * To refresh points label region and visible * * @private */ public refreshPoints(points: AccPoints[]): void { for (const point of points) { point.labelPosition = null; point.labelRegion = null; point.labelVisible = true; } } /** * To get Module name * * @private */ public getModuleName(): string { return 'accumulationchart'; } /** * To destroy the accumulationcharts * * @private */ public destroy(): void { /** * To fix react timeout destroy issue. */ if (this.element) { this.unWireEvents(); super.destroy(); this.element.classList.remove('e-accumulationchart'); this.removeSvg(); this.svgObject = null; } } /** * To provide the array of modules needed for control rendering * * @returns {ModuleDeclaration[]} required modules * @private */ public requiredModules(): ModuleDeclaration[] { const modules: ModuleDeclaration[] = []; let enableAnnotation: boolean = false; modules.push({ member: this.type + 'Series', args: [this] }); if (this.legendSettings.visible) { modules.push({ member: 'AccumulationLegend', args: [this] }); } if (this.findDatalabelVisibility()) { modules.push({ member: 'AccumulationDataLabel', args: [this] }); } if (this.tooltip.enable) { modules.push({ member: 'AccumulationTooltip', args: [this] }); } if (this.selectionMode !== 'None') { modules.push({ member: 'AccumulationSelection', args: [this] }); } if (this.enableExport || this.allowExport) { modules.push({ member: 'Export', args: [this] }); } enableAnnotation = this.annotations.some((value: AccumulationAnnotationSettings) => { return (value.content !== null); }); if (enableAnnotation) { modules.push({ member: 'Annotation', args: [this] }); } return modules; } /** * To find datalabel visibility in series */ private findDatalabelVisibility(): boolean { for (const series of this.series) { if (series.dataLabel.visible) { return true; } } return false; } /** * Get visible series for accumulation chart by index */ private changeVisibleSeries(visibleSeries: AccumulationSeries[], index: number): AccumulationSeries { for (const series of visibleSeries) { if (index === series.index) { return series; } } return null; } /** * Get the properties to be maintained in the persisted state. * * @private */ public getPersistData(): string { return ''; } /** * Called internally if any of the property value changed. * * @private */ // tslint:disable-next-line:max-func-body-length public onPropertyChanged(newProp: AccumulationChartModel, oldProp: AccumulationChartModel): void { const update: { refreshElements: boolean, refreshBounds: boolean } = { refreshElements: false, refreshBounds: false }; for (const prop of Object.keys(newProp)) { switch (prop) { case 'theme': this.animateSeries = true; break; case 'title': case 'subTitle': case 'height': case 'width': case 'margin': update.refreshBounds = true; break; case 'titleStyle': if (newProp.titleStyle && (newProp.titleStyle.size || newProp.titleStyle.textOverflow)) { update.refreshBounds = true; } else { update.refreshElements = true; } break; case 'subTitleStyle': if (newProp.subTitleStyle && (newProp.subTitleStyle.size || newProp.subTitleStyle.textOverflow)) { update.refreshBounds = true; } else { update.refreshElements = true; } break; case 'legendSettings': update.refreshBounds = true; update.refreshElements = true; break; case 'dataSource': this.processData(false); update.refreshBounds = true; break; case 'series': if (!this.animateselected) { const len: number = this.series.length; let seriesRefresh: boolean = false; let series: AccumulationSeriesModel; let blazorProp: boolean; for (let i: number = 0; i < len; i++) { series = newProp.series[i]; if (this.isBlazor && (series.startAngle || series.endAngle || series.explodeOffset || series.neckHeight || series.neckWidth || series.radius || series.innerRadius || series.groupMode || series.emptyPointSettings)) { blazorProp = true; } if (newProp.series[i] && (newProp.series[i].dataSource || newProp.series[i].yName || newProp.series[i].xName || newProp.series[i].dataLabel || blazorProp)) { extend(this.changeVisibleSeries(this.visibleSeries, i), series, null, true); seriesRefresh = true; } if (newProp.series[i] && !isNullOrUndefined(newProp.series[i].explodeIndex) && newProp.series[i].explodeIndex >= 0 && newProp.series[i].explodeIndex !== oldProp.series[i].explodeIndex) { this.accBaseModule.explodePoints(newProp.series[i].explodeIndex, this); this.accBaseModule.deExplodeAll(newProp.series[i].explodeIndex, this.enableAnimation ? 300 : 0); } else if (newProp.series[i].explodeIndex < 0) { this.accBaseModule.deExplodeAll(newProp.series[i].explodeIndex, this.enableAnimation ? 300 : 0); } } if (seriesRefresh) { this.processData(false); update.refreshBounds = true; } } this.animateselected = false; this.redraw = false; break; case 'locale': case 'currencyCode': super.refresh(); break; case 'background': case 'border': case 'annotations': case 'enableSmartLabels': update.refreshElements = true; break; case 'isMultiSelect': case 'selectedDataIndexes': case 'selectionMode': if (this.accumulationSelectionModule) { if (isNullOrUndefined(this.accumulationSelectionModule.selectedDataIndexes)) { this.accumulationSelectionModule.invokeSelection(this); } else { this.accumulationSelectionModule.redrawSelection(this); } } break; } } if (!update.refreshBounds && update.refreshElements) { this.createPieSvg(); this.renderElements(); } else if (update.refreshBounds) { this.refreshSeries(); this.createPieSvg(); this.calculateBounds(); this.renderElements(); } } }
the_stack
import polylabel from 'polylabel'; import * as SVG from 'svg.js'; import 'svg.draggable.js'; import 'svg.resize.js'; import 'svg.select.js'; import { CanvasController } from './canvasController'; import { Listener, Master } from './master'; import { DrawHandler, DrawHandlerImpl } from './drawHandler'; import { EditHandler, EditHandlerImpl } from './editHandler'; import { MergeHandler, MergeHandlerImpl } from './mergeHandler'; import { SplitHandler, SplitHandlerImpl } from './splitHandler'; import { GroupHandler, GroupHandlerImpl } from './groupHandler'; import { RegionSelector, RegionSelectorImpl } from './regionSelector'; import { ZoomHandler, ZoomHandlerImpl } from './zoomHandler'; import { InteractionHandler, InteractionHandlerImpl } from './interactionHandler'; import { AutoborderHandler, AutoborderHandlerImpl } from './autoborderHandler'; import consts from './consts'; import { translateToSVG, translateFromSVG, translateToCanvas, translateFromCanvas, pointsToNumberArray, parsePoints, displayShapeSize, scalarProduct, vectorLength, ShapeSizeElement, DrawnState, rotate2DPoints, readPointsFromShape, } from './shared'; import { CanvasModel, Geometry, UpdateReasons, FrameZoom, ActiveElement, DrawData, MergeData, SplitData, GroupData, Mode, Size, Configuration, InteractionResult, InteractionData, } from './canvasModel'; export interface CanvasView { html(): HTMLDivElement; } export class CanvasViewImpl implements CanvasView, Listener { private loadingAnimation: SVGSVGElement; private text: SVGSVGElement; private adoptedText: SVG.Container; private background: HTMLCanvasElement; private bitmap: HTMLCanvasElement; private grid: SVGSVGElement; private content: SVGSVGElement; private attachmentBoard: HTMLDivElement; private adoptedContent: SVG.Container; private canvas: HTMLDivElement; private gridPath: SVGPathElement; private gridPattern: SVGPatternElement; private controller: CanvasController; private svgShapes: Record<number, SVG.Shape>; private svgTexts: Record<number, SVG.Text>; private issueRegionPattern_1: SVG.Pattern; private issueRegionPattern_2: SVG.Pattern; private drawnStates: Record<number, DrawnState>; private drawnIssueRegions: Record<number, SVG.Shape>; private geometry: Geometry; private drawHandler: DrawHandler; private editHandler: EditHandler; private mergeHandler: MergeHandler; private splitHandler: SplitHandler; private groupHandler: GroupHandler; private regionSelector: RegionSelector; private zoomHandler: ZoomHandler; private autoborderHandler: AutoborderHandler; private interactionHandler: InteractionHandler; private activeElement: ActiveElement; private configuration: Configuration; private snapToAngleResize: number; private innerObjectsFlags: { drawHidden: Record<number, boolean>; }; private set mode(value: Mode) { this.controller.mode = value; } private get mode(): Mode { return this.controller.mode; } private stateIsLocked(state: any): boolean { const { configuration } = this.controller; return state.lock || configuration.forceDisableEditing; } private translateToCanvas(points: number[]): number[] { const { offset } = this.controller.geometry; return translateToCanvas(offset, points); } private translateFromCanvas(points: number[]): number[] { const { offset } = this.controller.geometry; return translateFromCanvas(offset, points); } private translatePointsFromRotatedShape(shape: SVG.Shape, points: number[]): number[] { const { rotation } = shape.transform(); // currently shape is rotated and shifted somehow additionally (css transform property) // let's remove rotation to get correct transformation matrix (element -> screen) // correct means that we do not consider points to be rotated // because rotation property is stored separately and already saved shape.rotate(0); const result = []; try { // get each point and apply a couple of matrix transformation to it const point = this.content.createSVGPoint(); // matrix to convert from ELEMENT file system to CLIENT coordinate system const ctm = ((shape.node as any) as SVGRectElement | SVGPolygonElement | SVGPolylineElement).getScreenCTM(); // matrix to convert from CLIENT coordinate system to CANVAS coordinate system const ctm1 = this.content.getScreenCTM().inverse(); // NOTE: I tried to use element.getCTM(), but this way does not work on firefox for (let i = 0; i < points.length; i += 2) { point.x = points[i]; point.y = points[i + 1]; let transformedPoint = point.matrixTransform(ctm); transformedPoint = transformedPoint.matrixTransform(ctm1); result.push(transformedPoint.x, transformedPoint.y); } } finally { shape.rotate(rotation); } return result; } private stringifyToCanvas(points: number[]): string { return points.reduce((acc: string, val: number, idx: number): string => { if (idx % 2) { return `${acc}${val} `; } return `${acc}${val},`; }, ''); } private isInnerHidden(clientID: number): boolean { return this.innerObjectsFlags.drawHidden[clientID] || false; } private setupInnerFlags(clientID: number, path: 'drawHidden', value: boolean): void { this.innerObjectsFlags[path][clientID] = value; const shape = this.svgShapes[clientID]; const text = this.svgTexts[clientID]; const state = this.drawnStates[clientID]; if (value) { if (shape) { (state.shapeType === 'points' ? shape.remember('_selectHandler').nested : shape).addClass( 'cvat_canvas_hidden', ); } if (text) { text.addClass('cvat_canvas_hidden'); } } else { delete this.innerObjectsFlags[path][clientID]; if (state) { if (!state.outside && !state.hidden) { if (shape) { (state.shapeType === 'points' ? shape.remember('_selectHandler').nested : shape).removeClass( 'cvat_canvas_hidden', ); } if (text) { text.removeClass('cvat_canvas_hidden'); this.updateTextPosition(text, shape); } } } } } private onInteraction( shapes: InteractionResult[] | null, shapesUpdated = true, isDone = false, threshold: number | null = null, ): void { const { zLayer } = this.controller; if (Array.isArray(shapes)) { const event: CustomEvent = new CustomEvent('canvas.interacted', { bubbles: false, cancelable: true, detail: { shapesUpdated, isDone, shapes, zOrder: zLayer || 0, threshold, }, }); this.canvas.dispatchEvent(event); } if (shapes === null || isDone) { const event: CustomEvent = new CustomEvent('canvas.canceled', { bubbles: false, cancelable: true, }); this.canvas.dispatchEvent(event); this.mode = Mode.IDLE; this.controller.interact({ enabled: false, }); } } private onDrawDone(data: any | null, duration: number, continueDraw?: boolean): void { const hiddenBecauseOfDraw = Object.keys(this.innerObjectsFlags.drawHidden) .map((_clientID): number => +_clientID); if (hiddenBecauseOfDraw.length) { for (const hidden of hiddenBecauseOfDraw) { this.setupInnerFlags(hidden, 'drawHidden', false); } } if (data) { const { clientID, points } = data as any; if (typeof clientID === 'number') { const event: CustomEvent = new CustomEvent('canvas.canceled', { bubbles: false, cancelable: true, }); this.canvas.dispatchEvent(event); const [state] = this.controller.objects.filter((_state: any): boolean => _state.clientID === clientID); this.onEditDone(state, points); return; } const { zLayer } = this.controller; const event: CustomEvent = new CustomEvent('canvas.drawn', { bubbles: false, cancelable: true, detail: { // eslint-disable-next-line new-cap state: { ...data, zOrder: zLayer || 0, }, continue: continueDraw, duration, }, }); this.canvas.dispatchEvent(event); } else if (!continueDraw) { const event: CustomEvent = new CustomEvent('canvas.canceled', { bubbles: false, cancelable: true, }); this.canvas.dispatchEvent(event); } if (!continueDraw) { this.mode = Mode.IDLE; this.controller.draw({ enabled: false, }); } } private onEditDone(state: any, points: number[], rotation?: number): void { if (state && points) { const event: CustomEvent = new CustomEvent('canvas.edited', { bubbles: false, cancelable: true, detail: { state, points, rotation: typeof rotation === 'number' ? rotation : state.rotation, }, }); this.canvas.dispatchEvent(event); } else { const event: CustomEvent = new CustomEvent('canvas.canceled', { bubbles: false, cancelable: true, }); this.canvas.dispatchEvent(event); } this.mode = Mode.IDLE; } private onMergeDone(objects: any[] | null, duration?: number): void { if (objects) { const event: CustomEvent = new CustomEvent('canvas.merged', { bubbles: false, cancelable: true, detail: { duration, states: objects, }, }); this.canvas.dispatchEvent(event); } else { const event: CustomEvent = new CustomEvent('canvas.canceled', { bubbles: false, cancelable: true, }); this.canvas.dispatchEvent(event); } this.controller.merge({ enabled: false, }); this.mode = Mode.IDLE; } private onSplitDone(object: any): void { if (object) { const event: CustomEvent = new CustomEvent('canvas.splitted', { bubbles: false, cancelable: true, detail: { state: object, frame: object.frame, }, }); this.canvas.dispatchEvent(event); } else { const event: CustomEvent = new CustomEvent('canvas.canceled', { bubbles: false, cancelable: true, }); this.canvas.dispatchEvent(event); } this.controller.split({ enabled: false, }); this.mode = Mode.IDLE; } private onGroupDone(objects?: any[]): void { if (objects) { const event: CustomEvent = new CustomEvent('canvas.groupped', { bubbles: false, cancelable: true, detail: { states: objects, }, }); this.canvas.dispatchEvent(event); } else { const event: CustomEvent = new CustomEvent('canvas.canceled', { bubbles: false, cancelable: true, }); this.canvas.dispatchEvent(event); } this.controller.group({ enabled: false, }); this.mode = Mode.IDLE; } private onRegionSelected(points?: number[]): void { if (points) { const event: CustomEvent = new CustomEvent('canvas.regionselected', { bubbles: false, cancelable: true, detail: { points, }, }); this.canvas.dispatchEvent(event); } else { const event: CustomEvent = new CustomEvent('canvas.canceled', { bubbles: false, cancelable: true, }); this.canvas.dispatchEvent(event); } this.controller.selectRegion(false); this.mode = Mode.IDLE; } private onFindObject(e: MouseEvent): void { if (e.button === 0) { const { offset } = this.controller.geometry; const [x, y] = translateToSVG(this.content, [e.clientX, e.clientY]); const event: CustomEvent = new CustomEvent('canvas.find', { bubbles: false, cancelable: true, detail: { x: x - offset, y: y - offset, states: this.controller.objects, }, }); this.canvas.dispatchEvent(event); e.preventDefault(); } } private onFocusRegion(x: number, y: number, width: number, height: number): void { // First of all, compute and apply scale let scale = null; if ((this.geometry.angle / 90) % 2) { // 90, 270, .. scale = Math.min( Math.max( Math.min(this.geometry.canvas.width / height, this.geometry.canvas.height / width), FrameZoom.MIN, ), FrameZoom.MAX, ); } else { scale = Math.min( Math.max( Math.min(this.geometry.canvas.width / width, this.geometry.canvas.height / height), FrameZoom.MIN, ), FrameZoom.MAX, ); } this.geometry = { ...this.geometry, scale }; this.transformCanvas(); const [canvasX, canvasY] = translateFromSVG(this.content, [x + width / 2, y + height / 2]); const canvasOffset = this.canvas.getBoundingClientRect(); const [cx, cy] = [ this.canvas.clientWidth / 2 + canvasOffset.left, this.canvas.clientHeight / 2 + canvasOffset.top, ]; const dragged = { ...this.geometry, top: this.geometry.top + cy - canvasY, left: this.geometry.left + cx - canvasX, scale, }; this.controller.geometry = dragged; this.geometry = dragged; this.moveCanvas(); } private moveCanvas(): void { for (const obj of [this.background, this.grid, this.bitmap]) { obj.style.top = `${this.geometry.top}px`; obj.style.left = `${this.geometry.left}px`; } for (const obj of [this.content, this.text, this.attachmentBoard]) { obj.style.top = `${this.geometry.top - this.geometry.offset}px`; obj.style.left = `${this.geometry.left - this.geometry.offset}px`; } // Transform handlers this.drawHandler.transform(this.geometry); this.editHandler.transform(this.geometry); this.zoomHandler.transform(this.geometry); this.autoborderHandler.transform(this.geometry); this.interactionHandler.transform(this.geometry); this.regionSelector.transform(this.geometry); } private transformCanvas(): void { // Transform canvas for (const obj of [this.background, this.grid, this.content, this.bitmap, this.attachmentBoard]) { obj.style.transform = `scale(${this.geometry.scale}) rotate(${this.geometry.angle}deg)`; } // Transform grid this.gridPath.setAttribute('stroke-width', `${consts.BASE_GRID_WIDTH / this.geometry.scale}px`); // Transform all shape points for (const element of [ ...window.document.getElementsByClassName('svg_select_points'), ...window.document.getElementsByClassName('svg_select_points_rot'), ]) { element.setAttribute('stroke-width', `${consts.POINTS_STROKE_WIDTH / this.geometry.scale}`); element.setAttribute('r', `${consts.BASE_POINT_SIZE / this.geometry.scale}`); } for (const element of window.document.getElementsByClassName('cvat_canvas_poly_direction')) { const angle = (element as any).instance.data('angle'); (element as any).instance.style({ transform: `scale(${1 / this.geometry.scale}) rotate(${angle}deg)`, }); } for (const element of window.document.getElementsByClassName('cvat_canvas_selected_point')) { const previousWidth = element.getAttribute('stroke-width') as string; element.setAttribute('stroke-width', `${+previousWidth * 2}`); } // Transform all drawn shapes for (const key in this.svgShapes) { if (Object.prototype.hasOwnProperty.call(this.svgShapes, key)) { const object = this.svgShapes[key]; object.attr({ 'stroke-width': consts.BASE_STROKE_WIDTH / this.geometry.scale, }); } } // Transform all text for (const key in this.svgShapes) { if ( Object.prototype.hasOwnProperty.call(this.svgShapes, key) && Object.prototype.hasOwnProperty.call(this.svgTexts, key) ) { this.updateTextPosition(this.svgTexts[key], this.svgShapes[key]); } } // Transform all drawn issues region for (const issueRegion of Object.values(this.drawnIssueRegions)) { ((issueRegion as any) as SVG.Shape).attr('r', `${(consts.BASE_POINT_SIZE * 3) / this.geometry.scale}`); ((issueRegion as any) as SVG.Shape).attr( 'stroke-width', `${consts.BASE_STROKE_WIDTH / this.geometry.scale}`, ); } // Transform patterns for (const pattern of [this.issueRegionPattern_1, this.issueRegionPattern_2]) { pattern.attr({ width: consts.BASE_PATTERN_SIZE / this.geometry.scale, height: consts.BASE_PATTERN_SIZE / this.geometry.scale, }); pattern.children().forEach((element: SVG.Element): void => { element.attr('stroke-width', consts.BASE_STROKE_WIDTH / this.geometry.scale); }); } // Transform handlers this.drawHandler.transform(this.geometry); this.editHandler.transform(this.geometry); this.zoomHandler.transform(this.geometry); this.autoborderHandler.transform(this.geometry); this.interactionHandler.transform(this.geometry); this.regionSelector.transform(this.geometry); } private resizeCanvas(): void { for (const obj of [this.background, this.grid, this.bitmap]) { obj.style.width = `${this.geometry.image.width}px`; obj.style.height = `${this.geometry.image.height}px`; } for (const obj of [this.content, this.text, this.attachmentBoard]) { obj.style.width = `${this.geometry.image.width + this.geometry.offset * 2}px`; obj.style.height = `${this.geometry.image.height + this.geometry.offset * 2}px`; } } private setupIssueRegions(issueRegions: Record<number, { hidden: boolean; points: number[] }>): void { for (const issueRegion of Object.keys(this.drawnIssueRegions)) { if (!(issueRegion in issueRegions) || !+issueRegion) { this.drawnIssueRegions[+issueRegion].remove(); delete this.drawnIssueRegions[+issueRegion]; } } for (const issueRegion of Object.keys(issueRegions)) { if (issueRegion in this.drawnIssueRegions) continue; const points = this.translateToCanvas(issueRegions[+issueRegion].points); if (points.length === 2) { this.drawnIssueRegions[+issueRegion] = this.adoptedContent .circle((consts.BASE_POINT_SIZE * 3 * 2) / this.geometry.scale) .center(points[0], points[1]) .addClass('cvat_canvas_issue_region') .attr({ id: `cvat_canvas_issue_region_${issueRegion}`, fill: 'url(#cvat_issue_region_pattern_1)', }); } else if (points.length === 4) { const stringified = this.stringifyToCanvas([ points[0], points[1], points[2], points[1], points[2], points[3], points[0], points[3], ]); this.drawnIssueRegions[+issueRegion] = this.adoptedContent .polygon(stringified) .addClass('cvat_canvas_issue_region') .attr({ id: `cvat_canvas_issue_region_${issueRegion}`, fill: 'url(#cvat_issue_region_pattern_1)', 'stroke-width': `${consts.BASE_STROKE_WIDTH / this.geometry.scale}`, }); } else { const stringified = this.stringifyToCanvas(points); this.drawnIssueRegions[+issueRegion] = this.adoptedContent .polygon(stringified) .addClass('cvat_canvas_issue_region') .attr({ id: `cvat_canvas_issue_region_${issueRegion}`, fill: 'url(#cvat_issue_region_pattern_1)', 'stroke-width': `${consts.BASE_STROKE_WIDTH / this.geometry.scale}`, }); } if (issueRegions[+issueRegion].hidden) { this.drawnIssueRegions[+issueRegion].style({ display: 'none' }); } } } private setupObjects(states: any[]): void { const created = []; const updated = []; for (const state of states) { if (!(state.clientID in this.drawnStates)) { created.push(state); } else { const drawnState = this.drawnStates[state.clientID]; // object has been changed or changed frame for a track if (drawnState.updated !== state.updated || drawnState.frame !== state.frame) { updated.push(state); } } } const newIDs = states.map((state: any): number => state.clientID); const deleted = Object.keys(this.drawnStates) .map((clientID: string): number => +clientID) .filter((id: number): boolean => !newIDs.includes(id)) .map((id: number): any => this.drawnStates[id]); if (deleted.length || updated.length || created.length) { if (this.activeElement.clientID !== null) { this.deactivate(); } this.deleteObjects(deleted); this.addObjects(created); this.updateObjects(updated); this.sortObjects(); if (this.controller.activeElement.clientID !== null) { const { clientID } = this.controller.activeElement; if (states.map((state: any): number => state.clientID).includes(clientID)) { this.activate(this.controller.activeElement); } } this.autoborderHandler.updateObjects(); } } private hideDirection(shape: SVG.Polygon | SVG.PolyLine): void { /* eslint class-methods-use-this: 0 */ const handler = shape.remember('_selectHandler'); if (!handler || !handler.nested) return; const nested = handler.nested as SVG.Parent; if (nested.children().length) { nested.children()[0].removeClass('cvat_canvas_first_poly_point'); } const node = nested.node as SVG.LinkedHTMLElement; const directions = node.getElementsByClassName('cvat_canvas_poly_direction'); for (const direction of directions) { const { instance } = direction as any; instance.off('click'); instance.remove(); } } private showDirection(state: any, shape: SVG.Polygon | SVG.PolyLine): void { const path = consts.ARROW_PATH; const points = parsePoints(state.points); const handler = shape.remember('_selectHandler'); if (!handler || !handler.nested) return; const firstCircle = handler.nested.children()[0]; const secondCircle = handler.nested.children()[1]; firstCircle.addClass('cvat_canvas_first_poly_point'); const [cx, cy] = [(secondCircle.cx() + firstCircle.cx()) / 2, (secondCircle.cy() + firstCircle.cy()) / 2]; const [firstPoint, secondPoint] = points.slice(0, 2); const xAxis = { i: 1, j: 0 }; const baseVector = { i: secondPoint.x - firstPoint.x, j: secondPoint.y - firstPoint.y }; const baseVectorLength = vectorLength(baseVector); let cosinus = 0; if (baseVectorLength !== 0) { // two points have the same coordinates cosinus = scalarProduct(xAxis, baseVector) / (vectorLength(xAxis) * baseVectorLength); } const angle = (Math.acos(cosinus) * (Math.sign(baseVector.j) || 1) * 180) / Math.PI; const pathElement = handler.nested .path(path) .fill('white') .stroke({ width: 1, color: 'black', }) .addClass('cvat_canvas_poly_direction') .style({ 'transform-origin': `${cx}px ${cy}px`, transform: `scale(${1 / this.geometry.scale}) rotate(${angle}deg)`, }) .move(cx, cy); pathElement.on('click', (e: MouseEvent): void => { if (e.button === 0) { e.stopPropagation(); if (state.shapeType === 'polygon') { const reversedPoints = [points[0], ...points.slice(1).reverse()]; this.onEditDone(state, pointsToNumberArray(reversedPoints)); } else { const reversedPoints = points.reverse(); this.onEditDone(state, pointsToNumberArray(reversedPoints)); } } }); pathElement.data('angle', angle); pathElement.dmove(-pathElement.width() / 2, -pathElement.height() / 2); } private selectize(value: boolean, shape: SVG.Element): void { const mousedownHandler = (e: MouseEvent): void => { if (e.button !== 0) return; e.preventDefault(); if (this.activeElement.clientID !== null) { const pointID = Array.prototype.indexOf.call( ((e.target as HTMLElement).parentElement as HTMLElement).children, e.target, ); const [state] = this.controller.objects.filter( (_state: any): boolean => _state.clientID === this.activeElement.clientID, ); if (['polygon', 'polyline', 'points'].includes(state.shapeType)) { if (state.shapeType === 'points' && (e.altKey || e.ctrlKey)) { const selectedClientID = +((e.target as HTMLElement).parentElement as HTMLElement).getAttribute('clientID'); if (state.clientID !== selectedClientID) { return; } } if (e.altKey) { const { points } = state; this.onEditDone(state, points.slice(0, pointID * 2).concat(points.slice(pointID * 2 + 2))); } else if (e.shiftKey) { this.canvas.dispatchEvent( new CustomEvent('canvas.editstart', { bubbles: false, cancelable: true, }), ); this.mode = Mode.EDIT; this.deactivate(); this.editHandler.edit({ enabled: true, state, pointID, }); } } } }; const dblClickHandler = (e: MouseEvent): void => { e.preventDefault(); if (this.activeElement.clientID !== null) { const [state] = this.controller.objects.filter( (_state: any): boolean => _state.clientID === this.activeElement.clientID, ); if (state.shapeType === 'cuboid') { if (e.shiftKey) { const points = this.translateFromCanvas( pointsToNumberArray((e.target as any).parentElement.parentElement.instance.attr('points')), ); this.onEditDone(state, points); } } } }; const contextMenuHandler = (e: MouseEvent): void => { const pointID = Array.prototype.indexOf.call( ((e.target as HTMLElement).parentElement as HTMLElement).children, e.target, ); if (this.activeElement.clientID !== null) { const [state] = this.controller.objects.filter( (_state: any): boolean => _state.clientID === this.activeElement.clientID, ); this.canvas.dispatchEvent( new CustomEvent('canvas.contextmenu', { bubbles: false, cancelable: true, detail: { mouseEvent: e, objectState: state, pointID, }, }), ); } e.preventDefault(); }; if (value) { const getGeometry = (): Geometry => this.geometry; const getController = (): CanvasController => this.controller; const getActiveElement = (): ActiveElement => this.activeElement; (shape as any).selectize(value, { deepSelect: true, pointSize: (2 * consts.BASE_POINT_SIZE) / this.geometry.scale, rotationPoint: shape.type === 'rect' || shape.type === 'ellipse', pointType(cx: number, cy: number): SVG.Circle { const circle: SVG.Circle = this.nested .circle(this.options.pointSize) .stroke('black') .fill('inherit') .center(cx, cy) .attr({ 'fill-opacity': 1, 'stroke-width': consts.POINTS_STROKE_WIDTH / getGeometry().scale, }); circle.on('mouseenter', (e: MouseEvent): void => { const activeElement = getActiveElement(); if (activeElement !== null && (e.altKey || e.ctrlKey)) { const [state] = getController().objects.filter( (_state: any): boolean => _state.clientID === activeElement.clientID, ); if (state?.shapeType === 'points') { const selectedClientID = +((e.target as HTMLElement).parentElement as HTMLElement).getAttribute('clientID'); if (state.clientID !== selectedClientID) { return; } } } circle.attr({ 'stroke-width': consts.POINTS_SELECTED_STROKE_WIDTH / getGeometry().scale, }); circle.on('dblclick', dblClickHandler); circle.on('mousedown', mousedownHandler); circle.on('contextmenu', contextMenuHandler); circle.addClass('cvat_canvas_selected_point'); }); circle.on('mouseleave', (): void => { circle.attr({ 'stroke-width': consts.POINTS_STROKE_WIDTH / getGeometry().scale, }); circle.off('dblclick', dblClickHandler); circle.off('mousedown', mousedownHandler); circle.off('contextmenu', contextMenuHandler); circle.removeClass('cvat_canvas_selected_point'); }); return circle; }, }); } else { (shape as any).selectize(false, { deepSelect: true, }); } const handler = shape.remember('_selectHandler'); if (handler && handler.nested) { handler.nested.fill(shape.attr('fill')); } const [rotationPoint] = window.document.getElementsByClassName('svg_select_points_rot'); if (rotationPoint && !rotationPoint.children.length) { const title = document.createElementNS('http://www.w3.org/2000/svg', 'title'); title.textContent = 'Hold Shift to snap angle'; rotationPoint.appendChild(title); } } private onShiftKeyDown = (e: KeyboardEvent): void => { if (!e.repeat && e.code.toLowerCase().includes('shift')) { this.snapToAngleResize = consts.SNAP_TO_ANGLE_RESIZE_SHIFT; if (this.activeElement) { const shape = this.svgShapes[this.activeElement.clientID]; if (shape && shape.hasClass('cvat_canvas_shape_activated')) { (shape as any).resize({ snapToAngle: this.snapToAngleResize }); } } } }; private onShiftKeyUp = (e: KeyboardEvent): void => { if (e.code.toLowerCase().includes('shift') && this.activeElement) { this.snapToAngleResize = consts.SNAP_TO_ANGLE_RESIZE_DEFAULT; if (this.activeElement) { const shape = this.svgShapes[this.activeElement.clientID]; if (shape && shape.hasClass('cvat_canvas_shape_activated')) { (shape as any).resize({ snapToAngle: this.snapToAngleResize }); } } } }; private onMouseUp = (event: MouseEvent): void => { if (event.button === 0 || event.button === 1) { this.controller.disableDrag(); } }; public constructor(model: CanvasModel & Master, controller: CanvasController) { this.controller = controller; this.geometry = controller.geometry; this.svgShapes = {}; this.svgTexts = {}; this.drawnStates = {}; this.drawnIssueRegions = {}; this.activeElement = { clientID: null, attributeID: null, }; this.configuration = model.configuration; this.mode = Mode.IDLE; this.snapToAngleResize = consts.SNAP_TO_ANGLE_RESIZE_DEFAULT; this.innerObjectsFlags = { drawHidden: {}, }; // Create HTML elements this.loadingAnimation = window.document.createElementNS('http://www.w3.org/2000/svg', 'svg'); this.text = window.document.createElementNS('http://www.w3.org/2000/svg', 'svg'); this.adoptedText = SVG.adopt((this.text as any) as HTMLElement) as SVG.Container; this.background = window.document.createElement('canvas'); this.bitmap = window.document.createElement('canvas'); // window.document.createElementNS('http://www.w3.org/2000/svg', 'svg'); this.grid = window.document.createElementNS('http://www.w3.org/2000/svg', 'svg'); this.gridPath = window.document.createElementNS('http://www.w3.org/2000/svg', 'path'); this.gridPattern = window.document.createElementNS('http://www.w3.org/2000/svg', 'pattern'); this.content = window.document.createElementNS('http://www.w3.org/2000/svg', 'svg'); this.adoptedContent = SVG.adopt((this.content as any) as HTMLElement) as SVG.Container; this.attachmentBoard = window.document.createElement('div'); this.canvas = window.document.createElement('div'); const loadingCircle: SVGCircleElement = window.document.createElementNS('http://www.w3.org/2000/svg', 'circle'); const gridDefs: SVGDefsElement = window.document.createElementNS('http://www.w3.org/2000/svg', 'defs'); const gridRect: SVGRectElement = window.document.createElementNS('http://www.w3.org/2000/svg', 'rect'); // Setup defs const contentDefs = this.adoptedContent.defs(); this.issueRegionPattern_1 = contentDefs .pattern(consts.BASE_PATTERN_SIZE, consts.BASE_PATTERN_SIZE, (add): void => { add.line(0, 0, 0, 10).stroke('red'); }) .attr({ id: 'cvat_issue_region_pattern_1', patternTransform: 'rotate(45)', patternUnits: 'userSpaceOnUse', }); this.issueRegionPattern_2 = contentDefs .pattern(consts.BASE_PATTERN_SIZE, consts.BASE_PATTERN_SIZE, (add): void => { add.line(0, 0, 0, 10).stroke('yellow'); }) .attr({ id: 'cvat_issue_region_pattern_2', patternTransform: 'rotate(45)', patternUnits: 'userSpaceOnUse', }); // Setup loading animation this.loadingAnimation.setAttribute('id', 'cvat_canvas_loading_animation'); loadingCircle.setAttribute('id', 'cvat_canvas_loading_circle'); loadingCircle.setAttribute('r', '30'); loadingCircle.setAttribute('cx', '50%'); loadingCircle.setAttribute('cy', '50%'); // Setup grid this.grid.setAttribute('id', 'cvat_canvas_grid'); this.grid.setAttribute('version', '2'); this.gridPath.setAttribute('d', 'M 1000 0 L 0 0 0 1000'); this.gridPath.setAttribute('fill', 'none'); this.gridPath.setAttribute('stroke-width', `${consts.BASE_GRID_WIDTH}`); this.gridPath.setAttribute('opacity', 'inherit'); this.gridPattern.setAttribute('id', 'cvat_canvas_grid_pattern'); this.gridPattern.setAttribute('width', '100'); this.gridPattern.setAttribute('height', '100'); this.gridPattern.setAttribute('patternUnits', 'userSpaceOnUse'); gridRect.setAttribute('width', '100%'); gridRect.setAttribute('height', '100%'); gridRect.setAttribute('fill', 'url(#cvat_canvas_grid_pattern)'); // Setup content this.text.setAttribute('id', 'cvat_canvas_text_content'); this.background.setAttribute('id', 'cvat_canvas_background'); this.content.setAttribute('id', 'cvat_canvas_content'); this.bitmap.setAttribute('id', 'cvat_canvas_bitmap'); this.bitmap.style.display = 'none'; // Setup sticked div this.attachmentBoard.setAttribute('id', 'cvat_canvas_attachment_board'); // Setup wrappers this.canvas.setAttribute('id', 'cvat_canvas_wrapper'); // Unite created HTML elements together this.loadingAnimation.appendChild(loadingCircle); this.grid.appendChild(gridDefs); this.grid.appendChild(gridRect); gridDefs.appendChild(this.gridPattern); this.gridPattern.appendChild(this.gridPath); this.canvas.appendChild(this.loadingAnimation); this.canvas.appendChild(this.text); this.canvas.appendChild(this.background); this.canvas.appendChild(this.bitmap); this.canvas.appendChild(this.grid); this.canvas.appendChild(this.content); this.canvas.appendChild(this.attachmentBoard); // Setup API handlers this.autoborderHandler = new AutoborderHandlerImpl(this.content); this.drawHandler = new DrawHandlerImpl( this.onDrawDone.bind(this), this.adoptedContent, this.adoptedText, this.autoborderHandler, this.geometry, this.configuration, ); this.editHandler = new EditHandlerImpl(this.onEditDone.bind(this), this.adoptedContent, this.autoborderHandler); this.mergeHandler = new MergeHandlerImpl( this.onMergeDone.bind(this), this.onFindObject.bind(this), this.adoptedContent, ); this.splitHandler = new SplitHandlerImpl( this.onSplitDone.bind(this), this.onFindObject.bind(this), this.adoptedContent, ); this.groupHandler = new GroupHandlerImpl( this.onGroupDone.bind(this), (): any[] => this.controller.objects, this.onFindObject.bind(this), this.adoptedContent, ); this.regionSelector = new RegionSelectorImpl( this.onRegionSelected.bind(this), this.adoptedContent, this.geometry, ); this.zoomHandler = new ZoomHandlerImpl(this.onFocusRegion.bind(this), this.adoptedContent, this.geometry); this.interactionHandler = new InteractionHandlerImpl( this.onInteraction.bind(this), this.adoptedContent, this.geometry, this.configuration, ); // Setup event handlers this.content.addEventListener('dblclick', (e: MouseEvent): void => { this.controller.fit(); e.preventDefault(); }); this.content.addEventListener('mousedown', (event): void => { if ([0, 1].includes(event.button)) { if ( [Mode.IDLE, Mode.DRAG_CANVAS, Mode.MERGE, Mode.SPLIT] .includes(this.mode) || event.button === 1 || event.altKey ) { this.controller.enableDrag(event.clientX, event.clientY); } } }); window.document.addEventListener('mouseup', this.onMouseUp); window.document.addEventListener('keydown', this.onShiftKeyDown); window.document.addEventListener('keyup', this.onShiftKeyUp); this.content.addEventListener('wheel', (event): void => { if (event.ctrlKey) return; const { offset } = this.controller.geometry; const point = translateToSVG(this.content, [event.clientX, event.clientY]); this.controller.zoom(point[0] - offset, point[1] - offset, event.deltaY > 0 ? -1 : 1); this.canvas.dispatchEvent( new CustomEvent('canvas.zoom', { bubbles: false, cancelable: true, }), ); event.preventDefault(); }); this.content.addEventListener('mousemove', (e): void => { this.controller.drag(e.clientX, e.clientY); if (this.mode !== Mode.IDLE) return; if (e.ctrlKey || e.altKey) return; const { offset } = this.controller.geometry; const [x, y] = translateToSVG(this.content, [e.clientX, e.clientY]); const event: CustomEvent = new CustomEvent('canvas.moved', { bubbles: false, cancelable: true, detail: { x: x - offset, y: y - offset, states: this.controller.objects, }, }); this.canvas.dispatchEvent(event); }); this.content.oncontextmenu = (): boolean => false; model.subscribe(this); } public notify(model: CanvasModel & Master, reason: UpdateReasons): void { this.geometry = this.controller.geometry; if (reason === UpdateReasons.CONFIG_UPDATED) { const { activeElement } = this; this.deactivate(); const { configuration } = model; if (configuration.displayAllText && !this.configuration.displayAllText) { for (const i in this.drawnStates) { if (!(i in this.svgTexts)) { this.svgTexts[i] = this.addText(this.drawnStates[i]); } } } else if (configuration.displayAllText === false && this.configuration.displayAllText) { for (const i in this.drawnStates) { if (i in this.svgTexts && Number.parseInt(i, 10) !== activeElement.clientID) { this.svgTexts[i].remove(); delete this.svgTexts[i]; } } } const recreateText = configuration.textContent !== this.configuration.textContent; const updateTextPosition = configuration.displayAllText !== this.configuration.displayAllText || configuration.textFontSize !== this.configuration.textFontSize || configuration.textPosition !== this.configuration.textPosition || recreateText; if (configuration.smoothImage === true) { this.background.classList.remove('cvat_canvas_pixelized'); } else if (configuration.smoothImage === false) { this.background.classList.add('cvat_canvas_pixelized'); } this.configuration = configuration; if (recreateText) { const states = this.controller.objects; for (const key of Object.keys(this.drawnStates)) { const clientID = +key; const [state] = states.filter((_state: any) => _state.clientID === clientID); if (clientID in this.svgTexts) { this.svgTexts[clientID].remove(); delete this.svgTexts[clientID]; if (state) this.svgTexts[clientID] = this.addText(state); } } } if (updateTextPosition) { for (const i in this.drawnStates) { if (i in this.svgTexts) { this.updateTextPosition(this.svgTexts[i], this.svgShapes[i]); } } } this.activate(activeElement); this.editHandler.configurate(this.configuration); this.drawHandler.configurate(this.configuration); this.interactionHandler.configurate(this.configuration); // remove if exist and not enabled // this.setupObjects([]); // this.setupObjects(model.objects); } else if (reason === UpdateReasons.BITMAP) { const { imageBitmap } = model; if (imageBitmap) { this.bitmap.style.display = ''; this.redrawBitmap(); } else { this.bitmap.style.display = 'none'; } } else if (reason === UpdateReasons.IMAGE_CHANGED) { const { image } = model; if (!image) { this.loadingAnimation.classList.remove('cvat_canvas_hidden'); } else { this.loadingAnimation.classList.add('cvat_canvas_hidden'); const ctx = this.background.getContext('2d'); this.background.setAttribute('width', `${image.renderWidth}px`); this.background.setAttribute('height', `${image.renderHeight}px`); if (ctx) { if (image.imageData instanceof ImageData) { ctx.scale( image.renderWidth / image.imageData.width, image.renderHeight / image.imageData.height, ); ctx.putImageData(image.imageData, 0, 0); // Transformation matrix must not affect the putImageData() method. // By this reason need to redraw the image to apply scale. // https://www.w3.org/TR/2dcontext/#dom-context-2d-putimagedata ctx.drawImage(this.background, 0, 0); } else { ctx.drawImage(image.imageData, 0, 0); } } this.moveCanvas(); this.resizeCanvas(); this.transformCanvas(); } } else if (reason === UpdateReasons.FITTED_CANVAS) { // Canvas geometry is going to be changed. Old object positions aren't valid any more this.setupObjects([]); this.setupIssueRegions({}); this.moveCanvas(); this.resizeCanvas(); this.canvas.dispatchEvent( new CustomEvent('canvas.reshape', { bubbles: false, cancelable: true, }), ); } else if ([UpdateReasons.IMAGE_ZOOMED, UpdateReasons.IMAGE_FITTED].includes(reason)) { this.moveCanvas(); this.transformCanvas(); if (reason === UpdateReasons.IMAGE_FITTED) { this.canvas.dispatchEvent( new CustomEvent('canvas.fit', { bubbles: false, cancelable: true, }), ); } } else if (reason === UpdateReasons.IMAGE_MOVED) { this.moveCanvas(); } else if (reason === UpdateReasons.OBJECTS_UPDATED) { if (this.mode === Mode.GROUP) { this.groupHandler.resetSelectedObjects(); } this.setupObjects(this.controller.objects); if (this.mode === Mode.MERGE) { this.mergeHandler.repeatSelection(); } const event: CustomEvent = new CustomEvent('canvas.setup'); this.canvas.dispatchEvent(event); } else if (reason === UpdateReasons.ISSUE_REGIONS_UPDATED) { this.setupIssueRegions(this.controller.issueRegions); } else if (reason === UpdateReasons.GRID_UPDATED) { const size: Size = this.geometry.grid; this.gridPattern.setAttribute('width', `${size.width}`); this.gridPattern.setAttribute('height', `${size.height}`); } else if (reason === UpdateReasons.SHAPE_FOCUSED) { const { padding, clientID } = this.controller.focusData; const object = this.svgShapes[clientID]; if (object) { const bbox: SVG.BBox = object.bbox(); this.onFocusRegion( bbox.x - padding, bbox.y - padding, bbox.width + padding * 2, bbox.height + padding * 2, ); } } else if (reason === UpdateReasons.SHAPE_ACTIVATED) { this.activate(this.controller.activeElement); } else if (reason === UpdateReasons.SELECT_REGION) { if (this.mode === Mode.SELECT_REGION) { this.regionSelector.select(true); this.canvas.style.cursor = 'pointer'; } else { this.regionSelector.select(false); } } else if (reason === UpdateReasons.DRAG_CANVAS) { if (this.mode === Mode.DRAG_CANVAS) { this.canvas.dispatchEvent( new CustomEvent('canvas.dragstart', { bubbles: false, cancelable: true, }), ); this.canvas.style.cursor = 'move'; } else { this.canvas.dispatchEvent( new CustomEvent('canvas.dragstop', { bubbles: false, cancelable: true, }), ); this.canvas.style.cursor = ''; } } else if (reason === UpdateReasons.ZOOM_CANVAS) { if (this.mode === Mode.ZOOM_CANVAS) { this.canvas.dispatchEvent( new CustomEvent('canvas.zoomstart', { bubbles: false, cancelable: true, }), ); this.canvas.style.cursor = 'zoom-in'; this.zoomHandler.zoom(); } else { this.canvas.dispatchEvent( new CustomEvent('canvas.zoomstop', { bubbles: false, cancelable: true, }), ); this.canvas.style.cursor = ''; this.zoomHandler.cancel(); } } else if (reason === UpdateReasons.DRAW) { const data: DrawData = this.controller.drawData; if (data.enabled && this.mode === Mode.IDLE) { this.canvas.style.cursor = 'crosshair'; this.mode = Mode.DRAW; if (typeof data.redraw === 'number') { this.setupInnerFlags(data.redraw, 'drawHidden', true); } this.drawHandler.draw(data, this.geometry); } else { this.canvas.style.cursor = ''; if (this.mode !== Mode.IDLE) { this.drawHandler.draw(data, this.geometry); } } } else if (reason === UpdateReasons.INTERACT) { const data: InteractionData = this.controller.interactionData; if (data.enabled && (this.mode === Mode.IDLE || data.intermediateShape)) { if (!data.intermediateShape) { this.canvas.style.cursor = 'crosshair'; this.mode = Mode.INTERACT; } this.interactionHandler.interact(data); } else { if (!data.enabled) { this.canvas.style.cursor = ''; } if (this.mode !== Mode.IDLE) { this.interactionHandler.interact(data); } } } else if (reason === UpdateReasons.MERGE) { const data: MergeData = this.controller.mergeData; if (data.enabled) { this.canvas.style.cursor = 'copy'; this.mode = Mode.MERGE; } else { this.canvas.style.cursor = ''; } this.mergeHandler.merge(data); } else if (reason === UpdateReasons.SPLIT) { const data: SplitData = this.controller.splitData; if (data.enabled) { this.canvas.style.cursor = 'copy'; this.mode = Mode.SPLIT; } else { this.canvas.style.cursor = ''; } this.splitHandler.split(data); } else if (reason === UpdateReasons.GROUP) { const data: GroupData = this.controller.groupData; if (data.enabled) { this.canvas.style.cursor = 'copy'; this.mode = Mode.GROUP; } else { this.canvas.style.cursor = ''; } this.groupHandler.group(data); } else if (reason === UpdateReasons.SELECT) { if (this.mode === Mode.MERGE) { this.mergeHandler.select(this.controller.selected); } else if (this.mode === Mode.SPLIT) { this.splitHandler.select(this.controller.selected); } else if (this.mode === Mode.GROUP) { this.groupHandler.select(this.controller.selected); } } else if (reason === UpdateReasons.CANCEL) { if (this.mode === Mode.DRAW) { this.drawHandler.cancel(); } else if (this.mode === Mode.INTERACT) { this.interactionHandler.cancel(); } else if (this.mode === Mode.MERGE) { this.mergeHandler.cancel(); } else if (this.mode === Mode.SPLIT) { this.splitHandler.cancel(); } else if (this.mode === Mode.GROUP) { this.groupHandler.cancel(); } else if (this.mode === Mode.SELECT_REGION) { this.regionSelector.cancel(); } else if (this.mode === Mode.EDIT) { this.editHandler.cancel(); } else if (this.mode === Mode.DRAG_CANVAS) { this.canvas.dispatchEvent( new CustomEvent('canvas.dragstop', { bubbles: false, cancelable: true, }), ); } else if (this.mode === Mode.ZOOM_CANVAS) { this.zoomHandler.cancel(); this.canvas.dispatchEvent( new CustomEvent('canvas.zoomstop', { bubbles: false, cancelable: true, }), ); } this.mode = Mode.IDLE; this.canvas.style.cursor = ''; } else if (reason === UpdateReasons.DATA_FAILED) { const event: CustomEvent = new CustomEvent('canvas.error', { detail: { exception: model.exception, }, }); this.canvas.dispatchEvent(event); } else if (reason === UpdateReasons.DESTROY) { this.canvas.dispatchEvent( new CustomEvent('canvas.destroy', { bubbles: false, cancelable: true, }), ); window.document.removeEventListener('keydown', this.onShiftKeyDown); window.document.removeEventListener('keyup', this.onShiftKeyUp); window.document.removeEventListener('mouseup', this.onMouseUp); this.interactionHandler.destroy(); } if (model.imageBitmap && [UpdateReasons.IMAGE_CHANGED, UpdateReasons.OBJECTS_UPDATED].includes(reason)) { this.redrawBitmap(); } } public html(): HTMLDivElement { return this.canvas; } private redrawBitmap(): void { const width = +this.background.style.width.slice(0, -2); const height = +this.background.style.height.slice(0, -2); this.bitmap.setAttribute('width', `${width}px`); this.bitmap.setAttribute('height', `${height}px`); const states = this.controller.objects; const ctx = this.bitmap.getContext('2d'); ctx.imageSmoothingEnabled = false; if (ctx) { ctx.fillStyle = 'black'; ctx.fillRect(0, 0, width, height); for (const state of states) { if (state.hidden || state.outside) continue; ctx.fillStyle = 'white'; if (['rectangle', 'polygon', 'cuboid'].includes(state.shapeType)) { let points = [...state.points]; if (state.shapeType === 'rectangle') { points = rotate2DPoints( points[0] + (points[2] - points[0]) / 2, points[1] + (points[3] - points[1]) / 2, state.rotation, [ points[0], // xtl points[1], // ytl points[2], // xbr points[1], // ytl points[2], // xbr points[3], // ybr points[0], // xtl points[3], // ybr ], ); } else if (state.shapeType === 'cuboid') { points = [ points[0], points[1], points[4], points[5], points[8], points[9], points[12], points[13], ]; } ctx.beginPath(); ctx.moveTo(points[0], points[1]); for (let i = 0; i < points.length; i += 2) { ctx.lineTo(points[i], points[i + 1]); } ctx.closePath(); ctx.fill(); } if (state.shapeType === 'ellipse') { const [cx, cy, rightX, topY] = state.points; ctx.beginPath(); ctx.ellipse(cx, cy, rightX - cx, cy - topY, (state.rotation * Math.PI) / 180.0, 0, 2 * Math.PI); ctx.closePath(); ctx.fill(); } if (state.shapeType === 'cuboid') { for (let i = 0; i < 5; i++) { const points = [ state.points[(0 + i * 4) % 16], state.points[(1 + i * 4) % 16], state.points[(2 + i * 4) % 16], state.points[(3 + i * 4) % 16], state.points[(6 + i * 4) % 16], state.points[(7 + i * 4) % 16], state.points[(4 + i * 4) % 16], state.points[(5 + i * 4) % 16], ]; ctx.beginPath(); ctx.moveTo(points[0], points[1]); for (let j = 0; j < points.length; j += 2) { ctx.lineTo(points[j], points[j + 1]); } ctx.closePath(); ctx.fill(); } } } } } private saveState(state: any): void { this.drawnStates[state.clientID] = { clientID: state.clientID, outside: state.outside, occluded: state.occluded, source: state.source, hidden: state.hidden, lock: state.lock, shapeType: state.shapeType, points: [...state.points], rotation: state.rotation, attributes: { ...state.attributes }, descriptions: [...state.descriptions], zOrder: state.zOrder, pinned: state.pinned, updated: state.updated, frame: state.frame, label: state.label, }; } private updateObjects(states: any[]): void { for (const state of states) { const { clientID } = state; const drawnState = this.drawnStates[clientID]; const shape = this.svgShapes[state.clientID]; const text = this.svgTexts[state.clientID]; const isInvisible = state.hidden || state.outside || this.isInnerHidden(state.clientID); if (drawnState.hidden !== state.hidden || drawnState.outside !== state.outside) { if (isInvisible) { (state.shapeType === 'points' ? shape.remember('_selectHandler').nested : shape).addClass( 'cvat_canvas_hidden', ); if (text) { text.addClass('cvat_canvas_hidden'); } } else { (state.shapeType === 'points' ? shape.remember('_selectHandler').nested : shape).removeClass( 'cvat_canvas_hidden', ); if (text) { text.removeClass('cvat_canvas_hidden'); this.updateTextPosition(text, shape); } } } if (drawnState.zOrder !== state.zOrder) { if (state.shapeType === 'points') { shape.remember('_selectHandler').nested.attr('data-z-order', state.zOrder); } else { shape.attr('data-z-order', state.zOrder); } } if (drawnState.occluded !== state.occluded) { if (state.occluded) { shape.addClass('cvat_canvas_shape_occluded'); } else { shape.removeClass('cvat_canvas_shape_occluded'); } } if (drawnState.pinned !== state.pinned && this.activeElement.clientID !== null) { const activeElement = { ...this.activeElement }; this.deactivate(); this.activate(activeElement); } if (drawnState.rotation) { // need to rotate it back before changing points shape.untransform(); } if ( state.points.length !== drawnState.points.length || state.points.some((p: number, id: number): boolean => p !== drawnState.points[id]) ) { const translatedPoints: number[] = this.translateToCanvas(state.points); if (state.shapeType === 'rectangle') { const [xtl, ytl, xbr, ybr] = translatedPoints; shape.attr({ x: xtl, y: ytl, width: xbr - xtl, height: ybr - ytl, }); } else if (state.shapeType === 'ellipse') { const [cx, cy] = translatedPoints; const [rx, ry] = [translatedPoints[2] - cx, cy - translatedPoints[3]]; shape.attr({ cx, cy, rx, ry, }); } else { const stringified = this.stringifyToCanvas(translatedPoints); if (state.shapeType !== 'cuboid') { (shape as any).clear(); } shape.attr('points', stringified); if (state.shapeType === 'points' && !isInvisible) { this.selectize(false, shape); this.setupPoints(shape as SVG.PolyLine, state); } } } if (state.rotation) { // now, when points changed, need to rotate it to new angle shape.rotate(state.rotation); } const stateDescriptions = state.descriptions; const drawnStateDescriptions = drawnState.descriptions; if ( drawnState.label.id !== state.label.id || drawnStateDescriptions.length !== stateDescriptions.length || drawnStateDescriptions.some((desc: string, id: number): boolean => desc !== stateDescriptions[id]) ) { // need to remove created text and create it again if (text) { text.remove(); this.svgTexts[state.clientID] = this.addText(state); } } else { // check if there are updates in attributes for (const attrID of Object.keys(state.attributes)) { if (state.attributes[attrID] !== drawnState.attributes[+attrID]) { if (text) { const [span] = text.node.querySelectorAll<SVGTSpanElement>(`[attrID="${attrID}"]`); if (span && span.textContent) { const prefix = span.textContent.split(':').slice(0, -1).join(':'); span.textContent = `${prefix}: ${state.attributes[attrID]}`; } } } } } this.saveState(state); } } private deleteObjects(states: any[]): void { for (const state of states) { if (state.clientID in this.svgTexts) { this.svgTexts[state.clientID].remove(); delete this.svgTexts[state.clientID]; } this.svgShapes[state.clientID].fire('remove'); this.svgShapes[state.clientID].off('click'); this.svgShapes[state.clientID].off('remove'); this.svgShapes[state.clientID].remove(); delete this.drawnStates[state.clientID]; delete this.svgShapes[state.clientID]; } } private addObjects(states: any[]): void { const { displayAllText } = this.configuration; for (const state of states) { const points: number[] = state.points as number[]; const translatedPoints: number[] = this.translateToCanvas(points); // TODO: Use enums after typification cvat-core if (state.shapeType === 'rectangle') { this.svgShapes[state.clientID] = this.addRect(translatedPoints, state); } else { const stringified = this.stringifyToCanvas(translatedPoints); if (state.shapeType === 'polygon') { this.svgShapes[state.clientID] = this.addPolygon(stringified, state); } else if (state.shapeType === 'polyline') { this.svgShapes[state.clientID] = this.addPolyline(stringified, state); } else if (state.shapeType === 'points') { this.svgShapes[state.clientID] = this.addPoints(stringified, state); } else if (state.shapeType === 'ellipse') { this.svgShapes[state.clientID] = this.addEllipse(stringified, state); } else if (state.shapeType === 'cuboid') { this.svgShapes[state.clientID] = this.addCuboid(stringified, state); } else { continue; } } this.svgShapes[state.clientID].on('click.canvas', (): void => { this.canvas.dispatchEvent( new CustomEvent('canvas.clicked', { bubbles: false, cancelable: true, detail: { state, }, }), ); }); if (displayAllText) { this.svgTexts[state.clientID] = this.addText(state); this.updateTextPosition(this.svgTexts[state.clientID], this.svgShapes[state.clientID]); } this.saveState(state); } } private sortObjects(): void { // TODO: Can be significantly optimized const states = Array.from(this.content.getElementsByClassName('cvat_canvas_shape')).map((state: SVGElement): [ SVGElement, number, ] => [state, +state.getAttribute('data-z-order')]); const crosshair = Array.from(this.content.getElementsByClassName('cvat_canvas_crosshair')); crosshair.forEach((line: SVGLineElement): void => this.content.append(line)); const interaction = Array.from(this.content.getElementsByClassName('cvat_interaction_point')); interaction.forEach((circle: SVGCircleElement): void => this.content.append(circle)); const needSort = states.some((pair): boolean => pair[1] !== states[0][1]); if (!states.length || !needSort) { return; } const sorted = states.sort((a, b): number => a[1] - b[1]); sorted.forEach((pair): void => { this.content.appendChild(pair[0]); }); this.content.prepend(...sorted.map((pair): SVGElement => pair[0])); } private deactivateAttribute(): void { const { clientID, attributeID } = this.activeElement; if (clientID !== null && attributeID !== null) { const text = this.svgTexts[clientID]; if (text) { const [span] = (text.node.querySelectorAll(`[attrID="${attributeID}"]`) as any) as SVGTSpanElement[]; if (span) { span.style.fill = ''; } } this.activeElement = { ...this.activeElement, attributeID: null, }; } } private deactivateShape(): void { if (this.activeElement.clientID !== null) { const { displayAllText } = this.configuration; const { clientID } = this.activeElement; const drawnState = this.drawnStates[clientID]; const shape = this.svgShapes[clientID]; shape.removeClass('cvat_canvas_shape_activated'); shape.removeClass('cvat_canvas_shape_draggable'); if (!drawnState.pinned) { (shape as any).off('dragstart'); (shape as any).off('dragend'); (shape as any).draggable(false); } if (drawnState.shapeType !== 'points') { this.selectize(false, shape); } if (drawnState.shapeType === 'cuboid') { (shape as any).attr('projections', false); } (shape as any).off('resizestart'); (shape as any).off('resizing'); (shape as any).off('resizedone'); (shape as any).resize('stop'); // TODO: Hide text only if it is hidden by settings const text = this.svgTexts[clientID]; if (text && !displayAllText) { text.remove(); delete this.svgTexts[clientID]; } this.sortObjects(); this.activeElement = { ...this.activeElement, clientID: null, }; } } private deactivate(): void { this.deactivateAttribute(); this.deactivateShape(); } private activateAttribute(clientID: number, attributeID: number): void { const text = this.svgTexts[clientID]; if (text) { const [span] = (text.node.querySelectorAll(`[attrID="${attributeID}"]`) as any) as SVGTSpanElement[]; if (span) { span.style.fill = 'red'; } this.activeElement = { ...this.activeElement, attributeID, }; } } private activateShape(clientID: number): void { const [state] = this.controller.objects.filter((_state: any): boolean => _state.clientID === clientID); if (state && state.shapeType === 'points') { this.svgShapes[clientID] .remember('_selectHandler') .nested.style('pointer-events', this.stateIsLocked(state) ? 'none' : ''); } if (!state || state.hidden || state.outside) { return; } const shape = this.svgShapes[clientID]; let text = this.svgTexts[clientID]; if (!text) { text = this.addText(state); this.svgTexts[state.clientID] = text; } this.updateTextPosition(text, shape); if (this.stateIsLocked(state)) { return; } shape.addClass('cvat_canvas_shape_activated'); if (state.shapeType === 'points') { this.content.append(this.svgShapes[clientID].remember('_selectHandler').nested.node); } else { this.content.append(shape.node); } const { showProjections } = this.configuration; if (state.shapeType === 'cuboid' && showProjections) { (shape as any).attr('projections', true); } const hideText = (): void => { if (text) { text.addClass('cvat_canvas_hidden'); } }; const showText = (): void => { if (text) { text.removeClass('cvat_canvas_hidden'); this.updateTextPosition(text, shape); } }; if (!state.pinned) { shape.addClass('cvat_canvas_shape_draggable'); (shape as any) .draggable() .on('dragstart', (): void => { this.mode = Mode.DRAG; hideText(); (shape as any).on('remove.drag', (): void => { this.mode = Mode.IDLE; // disable internal drag events of SVG.js window.dispatchEvent(new MouseEvent('mouseup')); }); }) .on('dragend', (e: CustomEvent): void => { (shape as any).off('remove.drag'); this.mode = Mode.IDLE; showText(); const p1 = e.detail.handler.startPoints.point; const p2 = e.detail.p; const delta = 1; const dx2 = (p1.x - p2.x) ** 2; const dy2 = (p1.y - p2.y) ** 2; if (Math.sqrt(dx2 + dy2) >= delta) { // these points does not take into account possible transformations, applied on the element // so, if any (like rotation) we need to map them to canvas coordinate space let points = readPointsFromShape(shape); // let's keep current points, but they could be rewritten in updateObjects this.drawnStates[clientID].points = this.translateFromCanvas(points); const { rotation } = shape.transform(); if (rotation) { points = this.translatePointsFromRotatedShape(shape, points); } points = this.translateFromCanvas(points); this.canvas.dispatchEvent( new CustomEvent('canvas.dragshape', { bubbles: false, cancelable: true, detail: { id: state.clientID, }, }), ); this.onEditDone(state, points); } }); } if (state.shapeType !== 'points') { this.selectize(true, shape); } const showDirection = (): void => { if (['polygon', 'polyline'].includes(state.shapeType)) { this.showDirection(state, shape as SVG.Polygon | SVG.PolyLine); } }; const hideDirection = (): void => { if (['polygon', 'polyline'].includes(state.shapeType)) { this.hideDirection(shape as SVG.Polygon | SVG.PolyLine); } }; showDirection(); let shapeSizeElement: ShapeSizeElement | null = null; let resized = false; const resizeFinally = (): void => { if (shapeSizeElement) { shapeSizeElement.rm(); shapeSizeElement = null; } this.mode = Mode.IDLE; }; (shape as any) .resize({ snapToGrid: 0.1, snapToAngle: this.snapToAngleResize, }) .on('resizestart', (): void => { this.mode = Mode.RESIZE; resized = false; hideDirection(); hideText(); if (state.shapeType === 'rectangle' || state.shapeType === 'ellipse') { shapeSizeElement = displayShapeSize(this.adoptedContent, this.adoptedText); } (shape as any).on('remove.resize', () => { // disable internal resize events of SVG.js window.dispatchEvent(new MouseEvent('mouseup')); resizeFinally(); }); }) .on('resizing', (): void => { resized = true; if (shapeSizeElement) { shapeSizeElement.update(shape); } }) .on('resizedone', (): void => { (shape as any).off('remove.resize'); resizeFinally(); showDirection(); showText(); if (resized) { let rotation = shape.transform().rotation || 0; // be sure, that rotation in range [0; 360] while (rotation < 0) rotation += 360; rotation %= 360; // these points does not take into account possible transformations, applied on the element // so, if any (like rotation) we need to map them to canvas coordinate space let points = readPointsFromShape(shape); // let's keep current points, but they could be rewritten in updateObjects this.drawnStates[clientID].points = this.translateFromCanvas(points); this.drawnStates[clientID].rotation = rotation; if (rotation) { points = this.translatePointsFromRotatedShape(shape, points); } // points = this.translateFromCanvas(points); this.canvas.dispatchEvent( new CustomEvent('canvas.resizeshape', { bubbles: false, cancelable: true, detail: { id: state.clientID, }, }), ); this.onEditDone(state, this.translateFromCanvas(points), rotation); } }); this.canvas.dispatchEvent( new CustomEvent('canvas.activated', { bubbles: false, cancelable: true, detail: { state, }, }), ); } private activate(activeElement: ActiveElement): void { // Check if another element have been already activated if (this.activeElement.clientID !== null) { if (this.activeElement.clientID !== activeElement.clientID) { // Deactivate previous shape and attribute this.deactivate(); } else if (this.activeElement.attributeID !== activeElement.attributeID) { this.deactivateAttribute(); } } const { clientID, attributeID } = activeElement; if (clientID !== null && this.activeElement.clientID !== clientID) { this.activateShape(clientID); this.activeElement = { ...this.activeElement, clientID, }; } if (clientID !== null && attributeID !== null && this.activeElement.attributeID !== attributeID) { this.activateAttribute(clientID, attributeID); } } // Update text position after corresponding box has been moved, resized, etc. private updateTextPosition(text: SVG.Text, shape: SVG.Shape): void { if (text.node.style.display === 'none') return; // wrong transformation matrix const { textFontSize, textPosition } = this.configuration; text.untransform(); text.style({ 'font-size': `${textFontSize}px` }); const { rotation } = shape.transform(); // Find the best place for a text let [clientX, clientY, clientCX, clientCY]: number[] = [0, 0, 0, 0]; if (textPosition === 'center') { let cx = 0; let cy = 0; if (shape.type === 'rect') { // for rectangle finding a center is simple cx = +shape.attr('x') + +shape.attr('width') / 2; cy = +shape.attr('y') + +shape.attr('height') / 2; } else if (shape.type === 'ellipse') { // even simpler for ellipses cx = +shape.attr('cx'); cy = +shape.attr('cy'); } else { // for polyshapes we use special algorithm const points = parsePoints(pointsToNumberArray(shape.attr('points'))); [cx, cy] = polylabel([points.map((point) => [point.x, point.y])]); } [clientX, clientY] = translateFromSVG(this.content, [cx, cy]); // center is exactly clientX, clientY clientCX = clientX; clientCY = clientY; } else { let box = (shape.node as any).getBBox(); // Translate the whole box to the client coordinate system const [x1, y1, x2, y2]: number[] = translateFromSVG(this.content, [ box.x, box.y, box.x + box.width, box.y + box.height, ]); clientCX = x1 + (x2 - x1) / 2; clientCY = y1 + (y2 - y1) / 2; box = { x: Math.min(x1, x2), y: Math.min(y1, y2), width: Math.max(x1, x2) - Math.min(x1, x2), height: Math.max(y1, y2) - Math.min(y1, y2), }; // first try to put to the top right corner [clientX, clientY] = [box.x + box.width, box.y]; if ( clientX + ((text.node as any) as SVGTextElement) .getBBox().width + consts.TEXT_MARGIN > this.canvas.offsetWidth ) { // if out of visible area, try to put text to top left corner [clientX, clientY] = [box.x, box.y]; } } // Translate found coordinates to text SVG const [x, y, rotX, rotY]: number[] = translateToSVG(this.text, [ clientX + (textPosition === 'auto' ? consts.TEXT_MARGIN : 0), clientY + (textPosition === 'auto' ? consts.TEXT_MARGIN : 0), clientCX, clientCY, ]); const textBBox = ((text.node as any) as SVGTextElement).getBBox(); // Finally draw a text if (textPosition === 'center') { text.move(x - textBBox.width / 2, y - textBBox.height / 2); } else { text.move(x, y); } if (rotation) { text.rotate(rotation, rotX, rotY); } for (const tspan of (text.lines() as any).members) { tspan.attr('x', text.attr('x')); } } private addText(state: any): SVG.Text { const { undefinedAttrValue } = this.configuration; const content = this.configuration.textContent; const withID = content.includes('id'); const withAttr = content.includes('attributes'); const withLabel = content.includes('label'); const withSource = content.includes('source'); const withDescriptions = content.includes('descriptions'); const textFontSize = this.configuration.textFontSize || 12; const { label, clientID, attributes, source, descriptions, } = state; const attrNames = label.attributes.reduce((acc: any, val: any): void => { acc[val.id] = val.name; return acc; }, {}); return this.adoptedText .text((block): void => { block.tspan(`${withLabel ? label.name : ''} ${withID ? clientID : ''} ${withSource ? `(${source})` : ''}`).style({ 'text-transform': 'uppercase', }); if (withDescriptions) { for (const desc of descriptions) { block .tspan(`${desc}`) .attr({ dy: '1em', x: 0, }) .addClass('cvat_canvas_text_description'); } } if (withAttr) { for (const attrID of Object.keys(attributes)) { const value = attributes[attrID] === undefinedAttrValue ? '' : attributes[attrID]; block .tspan(`${attrNames[attrID]}: ${value}`) .attr({ attrID, dy: '1em', x: 0, }) .addClass('cvat_canvas_text_attribute'); } } }) .move(0, 0) .style({ 'font-size': textFontSize }) .addClass('cvat_canvas_text'); } private addRect(points: number[], state: any): SVG.Rect { const [xtl, ytl, xbr, ybr] = points; const rect = this.adoptedContent .rect() .size(xbr - xtl, ybr - ytl) .attr({ clientID: state.clientID, 'color-rendering': 'optimizeQuality', id: `cvat_canvas_shape_${state.clientID}`, fill: state.color, 'shape-rendering': 'geometricprecision', stroke: state.color, 'stroke-width': consts.BASE_STROKE_WIDTH / this.geometry.scale, 'data-z-order': state.zOrder, }) .move(xtl, ytl) .addClass('cvat_canvas_shape'); if (state.rotation) { rect.rotate(state.rotation); } if (state.occluded) { rect.addClass('cvat_canvas_shape_occluded'); } if (state.hidden || state.outside || this.isInnerHidden(state.clientID)) { rect.addClass('cvat_canvas_hidden'); } return rect; } private addPolygon(points: string, state: any): SVG.Polygon { const polygon = this.adoptedContent .polygon(points) .attr({ clientID: state.clientID, 'color-rendering': 'optimizeQuality', id: `cvat_canvas_shape_${state.clientID}`, fill: state.color, 'shape-rendering': 'geometricprecision', stroke: state.color, 'stroke-width': consts.BASE_STROKE_WIDTH / this.geometry.scale, 'data-z-order': state.zOrder, }) .addClass('cvat_canvas_shape'); if (state.occluded) { polygon.addClass('cvat_canvas_shape_occluded'); } if (state.hidden || state.outside || this.isInnerHidden(state.clientID)) { polygon.addClass('cvat_canvas_hidden'); } return polygon; } private addPolyline(points: string, state: any): SVG.PolyLine { const polyline = this.adoptedContent .polyline(points) .attr({ clientID: state.clientID, 'color-rendering': 'optimizeQuality', id: `cvat_canvas_shape_${state.clientID}`, fill: state.color, 'shape-rendering': 'geometricprecision', stroke: state.color, 'stroke-width': consts.BASE_STROKE_WIDTH / this.geometry.scale, 'data-z-order': state.zOrder, }) .addClass('cvat_canvas_shape'); if (state.occluded) { polyline.addClass('cvat_canvas_shape_occluded'); } if (state.hidden || state.outside || this.isInnerHidden(state.clientID)) { polyline.addClass('cvat_canvas_hidden'); } return polyline; } private addCuboid(points: string, state: any): any { const cube = (this.adoptedContent as any) .cube(points) .fill(state.color) .attr({ clientID: state.clientID, 'color-rendering': 'optimizeQuality', id: `cvat_canvas_shape_${state.clientID}`, fill: state.color, 'shape-rendering': 'geometricprecision', stroke: state.color, 'stroke-width': consts.BASE_STROKE_WIDTH / this.geometry.scale, 'data-z-order': state.zOrder, }) .addClass('cvat_canvas_shape'); if (state.occluded) { cube.addClass('cvat_canvas_shape_occluded'); } if (state.hidden || state.outside || this.isInnerHidden(state.clientID)) { cube.addClass('cvat_canvas_hidden'); } return cube; } private setupPoints(basicPolyline: SVG.PolyLine, state: any): any { this.selectize(true, basicPolyline); const group: SVG.G = basicPolyline .remember('_selectHandler') .nested.addClass('cvat_canvas_shape') .attr({ clientID: state.clientID, id: `cvat_canvas_shape_${state.clientID}`, 'data-polyline-id': basicPolyline.attr('id'), 'data-z-order': state.zOrder, }); group.on('click.canvas', (event: MouseEvent): void => { // Need to redispatch the event on another element basicPolyline.fire(new MouseEvent('click', event)); // redispatch event to canvas to be able merge points clicking them this.content.dispatchEvent(new MouseEvent('click', event)); }); group.bbox = basicPolyline.bbox.bind(basicPolyline); group.clone = basicPolyline.clone.bind(basicPolyline); return group; } private addEllipse(points: string, state: any): SVG.Rect { const [cx, cy, rightX, topY] = points.split(/[/,\s]/g).map((coord) => +coord); const [rx, ry] = [rightX - cx, cy - topY]; const rect = this.adoptedContent .ellipse(rx * 2, ry * 2) .attr({ clientID: state.clientID, 'color-rendering': 'optimizeQuality', id: `cvat_canvas_shape_${state.clientID}`, fill: state.color, 'shape-rendering': 'geometricprecision', stroke: state.color, 'stroke-width': consts.BASE_STROKE_WIDTH / this.geometry.scale, 'data-z-order': state.zOrder, }) .center(cx, cy) .addClass('cvat_canvas_shape'); if (state.rotation) { rect.rotate(state.rotation); } if (state.occluded) { rect.addClass('cvat_canvas_shape_occluded'); } if (state.hidden || state.outside || this.isInnerHidden(state.clientID)) { rect.addClass('cvat_canvas_hidden'); } return rect; } private addPoints(points: string, state: any): SVG.PolyLine { const shape = this.adoptedContent .polyline(points) .attr({ 'color-rendering': 'optimizeQuality', 'pointer-events': 'none', 'shape-rendering': 'geometricprecision', 'stroke-width': 0, fill: state.color, // to right fill property when call SVG.Shape::clone() }) .style({ opacity: 0, }); const group = this.setupPoints(shape, state); if (state.hidden || state.outside || this.isInnerHidden(state.clientID)) { group.addClass('cvat_canvas_hidden'); } shape.remove = (): SVG.PolyLine => { this.selectize(false, shape); shape.constructor.prototype.remove.call(shape); return shape; }; return shape; } }
the_stack
import * as vscode from 'vscode'; import { configuration } from './../../configuration/configuration'; import { TextEditor } from './../../textEditor'; import { clamp } from '../../util/util'; import { getSentenceBegin, getSentenceEnd } from '../../textobject/sentence'; import { WordType, nextWordEnd, prevWordEnd, prevWordStart, nextWordStart, } from '../../textobject/word'; import { Position } from 'vscode'; /** * Controls how a PositionDiff affects the Position it's applied to. */ enum PositionDiffType { /** Sets both the line and character exactly */ ExactPosition, /** Offsets both the line and character */ Offset, /** Offsets the line and sets the column exactly */ ExactCharacter, /** Brings the Position to the beginning of the line if `vim.startofline` is true */ ObeyStartOfLine, /** Brings the Position to the end of the line */ EndOfLine, } /** * Represents a difference between two Positions. * Add it to a Position to get another Position. */ export class PositionDiff { public readonly line: number; public readonly character: number; public readonly type: PositionDiffType; private constructor(type: PositionDiffType, line: number, character: number) { this.type = type; this.line = line; this.character = character; } /** Has no effect */ public static identity(): PositionDiff { return PositionDiff.offset({ line: 0, character: 0 }); } /** Offsets both the Position's line and character */ public static offset({ line = 0, character = 0 }): PositionDiff { return new PositionDiff(PositionDiffType.Offset, line, character); } /** Sets the Position's line and character exactly */ public static exactPosition(position: Position): PositionDiff { return new PositionDiff(PositionDiffType.ExactPosition, position.line, position.character); } /** Brings the Position to the beginning of the line if `vim.startofline` is true */ public static startOfLine(): PositionDiff { return new PositionDiff(PositionDiffType.ObeyStartOfLine, 0, 0); } /** Brings the Position to the end of the line */ public static endOfLine(): PositionDiff { return new PositionDiff(PositionDiffType.EndOfLine, 0, 0); } /** Offsets the Position's line and sets its character exactly */ public static exactCharacter({ lineOffset, character, }: { lineOffset?: number; character: number; }): PositionDiff { return new PositionDiff(PositionDiffType.ExactCharacter, lineOffset ?? 0, character); } public toString(): string { switch (this.type) { case PositionDiffType.Offset: return `[ Diff: Offset ${this.line} ${this.character} ]`; case PositionDiffType.ExactCharacter: return `[ Diff: ExactCharacter ${this.line} ${this.character} ]`; case PositionDiffType.ExactPosition: return `[ Diff: ExactPosition ${this.line} ${this.character} ]`; case PositionDiffType.ObeyStartOfLine: return `[ Diff: ObeyStartOfLine ${this.line} ]`; case PositionDiffType.EndOfLine: return `[ Diff: EndOfLine ${this.line} ]`; default: const guard: never = this.type; throw new Error(`Unknown PositionDiffType: ${this.type}`); } } } /** * @returns the Position of the 2 provided which comes earlier in the document. */ export function earlierOf(p1: Position, p2: Position): Position { return p1.isBefore(p2) ? p1 : p2; } /** * @returns the Position of the 2 provided which comes later in the document. */ export function laterOf(p1: Position, p2: Position): Position { return p1.isBefore(p2) ? p2 : p1; } /** * @returns the given Positions in the order they appear in the document. */ export function sorted(p1: Position, p2: Position): [Position, Position] { return p1.isBefore(p2) ? [p1, p2] : [p2, p1]; } declare module 'vscode' { interface Position { toString(): string; add(document: vscode.TextDocument, diff: PositionDiff, boundsCheck?: boolean): Position; subtract(other: Position): PositionDiff; /** * @returns a new Position with the same line and the given character. * Does bounds-checking to make sure the result is valid. * @deprecated use `Position.with` instead */ withColumn(column: number): Position; /** * @returns the Position `count` characters to the left of this Position. Does not go over line breaks. */ getLeft(count?: number): Position; /** * @returns the Position `count` characters to the right of this Position. Does not go over line breaks. */ getRight(count?: number): Position; /** * @returns the Position `count` lines down from this Position */ getDown(count?: number): Position; /** * @returns the Position `count` lines up from this Position */ getUp(count?: number): Position; getLeftThroughLineBreaks(includeEol?: boolean): Position; getRightThroughLineBreaks(includeEol?: boolean): Position; getOffsetThroughLineBreaks(offset: number): Position; /** * @returns the start of the first word to the left of the current position, like `b` * * @param wordType how word boundaries are determined * @param inclusive if true, returns the current position if it's at the start of a word */ prevWordStart( document: vscode.TextDocument, args?: { wordType?: WordType; inclusive?: boolean } ): Position; /** * @returns the start of the first word to the right of the current position, like `w` * * @param wordType how word boundaries are determined * @param inclusive if true, returns the current position if it's at the start of a word */ nextWordStart( document: vscode.TextDocument, args?: { wordType?: WordType; inclusive?: boolean } ): Position; /** * @returns the end of the first word to the left of the current position, like `ge` * * @param wordType how word boundaries are determined */ prevWordEnd(document: vscode.TextDocument, args?: { wordType?: WordType }): Position; /** * @returns the end of the first word to the right of the current position, like `e` * * @param wordType how word boundaries are determined * @param inclusive if true, returns the current position if it's at the end of a word */ nextWordEnd( document: vscode.TextDocument, args?: { wordType?: WordType; inclusive?: boolean } ): Position; getSentenceBegin(args: { forward: boolean }): Position; getSentenceEnd(): Position; getLineBegin(): Position; /** * @returns the beginning of the line, excluding preceeding whitespace. * This respects the `autoindent` setting, and returns `getLineBegin()` if auto-indent is disabled. */ getLineBeginRespectingIndent(document: vscode.TextDocument): Position; /** * @returns a new Position at the end of this position's line. */ getLineEnd(): Position; /** * @returns a new Position at the end of this Position's line, including the invisible newline character. */ getLineEndIncludingEOL(): Position; /** * @returns a new Position one to the left if this Position is on the EOL. Otherwise, returns this position. */ getLeftIfEOL(): Position; /** * @returns the position that the cursor would be at if you pasted *text* at the current position. */ advancePositionByText(text: string): Position; /** * Is this position at the beginning of the line? */ isLineBeginning(): boolean; /** * Is this position at the end of the line? */ isLineEnd(): boolean; isFirstWordOfLine(document: vscode.TextDocument): boolean; isAtDocumentBegin(): boolean; isAtDocumentEnd(): boolean; /** * Returns whether the current position is in the leading whitespace of a line */ isInLeadingWhitespace(document: vscode.TextDocument): boolean; /** * If `vim.startofline` is set, get first non-blank character's position. */ obeyStartOfLine(document: vscode.TextDocument): Position; isValid(textEditor: vscode.TextEditor): boolean; } } Position.prototype.toString = function (this: Position) { return `[${this.line}, ${this.character}]`; }; Position.prototype.add = function ( this: Position, document: vscode.TextDocument, diff: PositionDiff, boundsCheck = true ): Position { if (diff.type === PositionDiffType.ExactPosition) { return new Position(diff.line, diff.character); } const resultLine = clamp(this.line + diff.line, 0, document.lineCount - 1); let resultChar: number; if (diff.type === PositionDiffType.Offset) { resultChar = this.character + diff.character; } else if (diff.type === PositionDiffType.ExactCharacter) { resultChar = diff.character; } else if (diff.type === PositionDiffType.ObeyStartOfLine) { resultChar = this.obeyStartOfLine(document).character; } else if (diff.type === PositionDiffType.EndOfLine) { resultChar = this.getLineEnd().character; } else { throw new Error(`Unknown PositionDiffType: ${diff.type}`); } const pos = new Position(resultLine, Math.max(resultChar, 0)); return boundsCheck ? document.validatePosition(pos) : pos; }; Position.prototype.subtract = function (this: Position, other: Position): PositionDiff { return PositionDiff.offset({ line: this.line - other.line, character: this.character - other.character, }); }; /** * @returns a new Position with the same line and the given character. * Does bounds-checking to make sure the result is valid. */ Position.prototype.withColumn = function (this: Position, column: number): Position { column = clamp(column, 0, TextEditor.getLineLength(this.line)); return new Position(this.line, column); }; /** * @returns the Position `count` characters to the left of this Position. Does not go over line breaks. */ Position.prototype.getLeft = function (this: Position, count = 1): Position { return new Position(this.line, Math.max(this.character - count, 0)); }; /** * @returns the Position `count` characters to the right of this Position. Does not go over line breaks. */ Position.prototype.getRight = function (this: Position, count = 1): Position { return new Position( this.line, Math.min(this.character + count, TextEditor.getLineLength(this.line)) ); }; /** * @returns the Position `count` lines down from this Position */ Position.prototype.getDown = function (this: Position, count = 1): Position { if (vscode.window.activeTextEditor) { const line = Math.min(this.line + count, TextEditor.getLineCount() - 1); return new Position(line, Math.min(this.character, TextEditor.getLineLength(line))); } else { return this.translate({ lineDelta: count }); } }; /** * @returns the Position `count` lines up from this Position */ Position.prototype.getUp = function (this: Position, count = 1): Position { const line = Math.max(this.line - count, 0); return new Position(line, Math.min(this.character, TextEditor.getLineLength(line))); }; /** * Same as getLeft, but goes up to the previous line on line breaks. * Equivalent to left arrow (in a non-vim editor!) */ Position.prototype.getLeftThroughLineBreaks = function ( this: Position, includeEol = true ): Position { if (!this.isLineBeginning()) { return this.getLeft(); } // First char on first line, can not go left any more if (this.line === 0) { return this; } if (includeEol) { return this.getUp().getLineEnd(); } else { return this.getUp().getLineEnd().getLeft(); } }; Position.prototype.getRightThroughLineBreaks = function ( this: Position, includeEol = false ): Position { if (this.isAtDocumentEnd()) { return this; } if (this.line < TextEditor.getLineCount() - 1) { const pos = includeEol ? this : this.getRight(); if (pos.isLineEnd()) { return this.with({ character: 0 }).getDown(); } } else if (!includeEol && this.character === TextEditor.getLineLength(this.line) - 1) { // Last character of document, don't go on to non-existent EOL return this; } return this.getRight(); }; Position.prototype.getOffsetThroughLineBreaks = function ( this: Position, offset: number ): Position { let pos = new Position(this.line, this.character); if (offset < 0) { for (let i = 0; i < -offset; i++) { pos = pos.getLeftThroughLineBreaks(); } } else { for (let i = 0; i < offset; i++) { pos = pos.getRightThroughLineBreaks(); } } return pos; }; Position.prototype.prevWordStart = function ( this: Position, document: vscode.TextDocument, args?: { wordType?: WordType; inclusive?: boolean } ): Position { return prevWordStart(document, this, args?.wordType ?? WordType.Normal, args?.inclusive ?? false); }; Position.prototype.nextWordStart = function ( this: Position, document: vscode.TextDocument, args?: { wordType?: WordType; inclusive?: boolean } ): Position { return nextWordStart(document, this, args?.wordType ?? WordType.Normal, args?.inclusive ?? false); }; Position.prototype.prevWordEnd = function ( this: Position, document: vscode.TextDocument, args?: { wordType?: WordType } ): Position { return prevWordEnd(document, this, args?.wordType ?? WordType.Normal); }; Position.prototype.nextWordEnd = function ( this: Position, document: vscode.TextDocument, args?: { wordType?: WordType; inclusive?: boolean } ): Position { return nextWordEnd(document, this, args?.wordType ?? WordType.Normal, args?.inclusive ?? false); }; Position.prototype.getSentenceBegin = function ( this: Position, args: { forward: boolean } ): Position { return getSentenceBegin(this, args); }; Position.prototype.getSentenceEnd = function (this: Position): Position { return getSentenceEnd(this); }; /** * @returns a new Position at the beginning of the current line. */ Position.prototype.getLineBegin = function (this: Position): Position { return new Position(this.line, 0); }; /** * @returns the beginning of the line, excluding preceeding whitespace. * This respects the `autoindent` setting, and returns `getLineBegin()` if auto-indent is disabled. */ Position.prototype.getLineBeginRespectingIndent = function ( this: Position, document: vscode.TextDocument ): Position { if (!configuration.autoindent) { return this.getLineBegin(); } return TextEditor.getFirstNonWhitespaceCharOnLine(document, this.line); }; /** * @returns a new Position at the end of this position's line. */ Position.prototype.getLineEnd = function (this: Position): Position { return new Position(this.line, TextEditor.getLineLength(this.line)); }; /** * @returns a new Position at the end of this Position's line, including the invisible newline character. */ Position.prototype.getLineEndIncludingEOL = function (this: Position): Position { // TODO: isn't this one too far? return new Position(this.line, TextEditor.getLineLength(this.line) + 1); }; /** * @returns a new Position one to the left if this Position is on the EOL. Otherwise, returns this position. */ Position.prototype.getLeftIfEOL = function (this: Position): Position { return this.character === TextEditor.getLineLength(this.line) ? this.getLeft() : this; }; /** * @returns the position that the cursor would be at if you pasted *text* at the current position. */ Position.prototype.advancePositionByText = function (this: Position, text: string): Position { const newlines: number[] = []; let idx = text.indexOf('\n', 0); while (idx >= 0) { newlines.push(idx); idx = text.indexOf('\n', idx + 1); } if (newlines.length === 0) { return new Position(this.line, this.character + text.length); } else { return new Position( this.line + newlines.length, text.length - (newlines[newlines.length - 1] + 1) ); } }; /** * Is this position at the beginning of the line? */ Position.prototype.isLineBeginning = function (this: Position): boolean { return this.character === 0; }; /** * Is this position at the end of the line? */ Position.prototype.isLineEnd = function (this: Position): boolean { return this.character >= TextEditor.getLineLength(this.line); }; Position.prototype.isFirstWordOfLine = function ( this: Position, document: vscode.TextDocument ): boolean { return ( TextEditor.getFirstNonWhitespaceCharOnLine(document, this.line).character === this.character ); }; Position.prototype.isAtDocumentBegin = function (this: Position): boolean { return this.line === 0 && this.isLineBeginning(); }; Position.prototype.isAtDocumentEnd = function (this: Position): boolean { return this.line === TextEditor.getLineCount() - 1 && this.isLineEnd(); }; /** * Returns whether the current position is in the leading whitespace of a line * @param allowEmpty : Use true if "" is valid */ Position.prototype.isInLeadingWhitespace = function ( this: Position, document: vscode.TextDocument ): boolean { return /^\s+$/.test(document.getText(new vscode.Range(this.getLineBegin(), this))); }; /** * If `vim.startofline` is set, get first non-blank character's position. */ Position.prototype.obeyStartOfLine = function ( this: Position, document: vscode.TextDocument ): Position { return configuration.startofline ? TextEditor.getFirstNonWhitespaceCharOnLine(document, this.line) : this; }; Position.prototype.isValid = function (this: Position, textEditor: vscode.TextEditor): boolean { try { // line // TODO: this `|| 1` seems dubious... const lineCount = TextEditor.getLineCount(textEditor) || 1; if (this.line >= lineCount) { return false; } // char const charCount = TextEditor.getLineLength(this.line); if (this.character > charCount + 1) { return false; } } catch (e) { return false; } return true; };
the_stack
import { Observable, Subject } from "rxjs"; import { Device, IFido2Device } from "../../fido2/fido2-device-cli"; import noble from '@abandonware/noble'; import { logger } from "../../log/debug"; import { DeviceService, DeviceState } from "../transport"; import { first } from "rxjs/operators"; import { BleDeviceNotFound } from "../../errors/ble"; const nodeBle = process.platform === 'win32' ? require('noble-winrt') as typeof noble : noble; export interface BLE { peripheral: noble.Peripheral; characteristics: noble.Characteristic[]; device: IFido2Device } export const FidoService = 'fffd'; export enum FidoCharacteristic { fidoControlPoint = 'f1d0fff1deaaeceeb42fc9ba7ed623bb', fidoStatus = 'f1d0fff2deaaeceeb42fc9ba7ed623bb', fidoControlPointLength = 'f1d0fff3deaaeceeb42fc9ba7ed623bb', fidoServiceRevisionBitfield = 'f1d0fff4deaaeceeb42fc9ba7ed623bb', fidoServiceRevision = '2a28', batteryLevel = '2a19', appearance = '2a01', deviceName = '2a00', firmwareVersion = '2a26', manufacturer = '2a29' } enum FidoServiceRevisionBit { U2F_1_1 = 0x80, U2F_1_2 = 0x40, FIDO2 = 0x20, } class BleService implements DeviceService { state: DeviceState; private device: Map<string, BLE>; private deviceSubject: Subject<Device>; private adapterSubject: Subject<void>; constructor() { this.state = DeviceState.off; this.device = new Map<string, BLE>(); this.deviceSubject = new Subject<Device>(); this.adapterSubject = new Subject<void>(); nodeBle.on('stateChange', async (state) => { if (state === 'poweredOn') { this.adapterSubject.next(); } }); nodeBle.on('discover', async (peripheral) => { logger.debug('discover', { uuid: peripheral.uuid, state: peripheral.state, rssi: peripheral.rssi }); /** * Device connecting. */ if (peripheral.state === 'connected' || peripheral.state === 'connecting') return; /** * Device already connected. Not needed but for sure. */ if (this.device.get(peripheral.uuid)) return; /** * Connect and get Services/Characteristics. */ await peripheral.connectAsync(); let sc = await peripheral.discoverSomeServicesAndCharacteristicsAsync([], [ FidoCharacteristic.fidoControlPoint, FidoCharacteristic.fidoStatus, FidoCharacteristic.fidoControlPointLength, FidoCharacteristic.fidoServiceRevisionBitfield, FidoCharacteristic.fidoServiceRevision, FidoCharacteristic.manufacturer, FidoCharacteristic.firmwareVersion, FidoCharacteristic.deviceName, FidoCharacteristic.appearance, FidoCharacteristic.batteryLevel ]); let device: IFido2Device = { transport: 'ble', uuid: peripheral.uuid }; let fidoControlPoint: boolean = false; let fidoStatus: boolean = false; let fidoControlPointLength: boolean = false; let fidoServiceRevisionBitfield: number = 0; let fidoServiceRevision: boolean = false; /** * Get info. */ await Promise.all(sc.characteristics.map<Promise<boolean>>(async c => { switch (c.uuid.toLowerCase()) { case FidoCharacteristic.batteryLevel: { let batteryLevel = await c.readAsync(); if (batteryLevel.length) device.batteryLevel = batteryLevel.readUInt8(0); return true; } case FidoCharacteristic.appearance: { let appearance = await c.readAsync(); if (appearance.length) device.appearance = appearance.readUInt16BE(0); return true; } case FidoCharacteristic.deviceName: { let deviceName = await c.readAsync(); if (deviceName.length) device.name = deviceName.toString(); return true; } case FidoCharacteristic.firmwareVersion: { let firmwareVersion = await c.readAsync(); if (firmwareVersion.length) device.firmwareVersion = firmwareVersion.toString(); return true; } case FidoCharacteristic.manufacturer: { let manufacturer = await c.readAsync(); if (manufacturer.length) device.manufacturer = manufacturer.toString(); return true; } case FidoCharacteristic.fidoServiceRevision: { fidoServiceRevision = true; return true; } case FidoCharacteristic.fidoServiceRevisionBitfield: { let buff = await c.readAsync(); if (buff.length >= 1) fidoServiceRevisionBitfield = buff.readUInt8(0); return true; } case FidoCharacteristic.fidoControlPointLength: { let buff = await c.readAsync(); fidoControlPointLength = true; if (buff.length >= 2) device.maxPacketLength = buff.readUInt16BE(0); return true; } case FidoCharacteristic.fidoStatus: { fidoStatus = true; return true; } case FidoCharacteristic.fidoControlPoint: { fidoControlPoint = true; return true; } default: return true; } })); /** * GAP device name not available. */ device.name || (device.name = peripheral.advertisement.localName); /** * Check for fido2 compatible. */ if (!(fidoControlPoint && fidoControlPointLength && fidoStatus && (fidoServiceRevisionBitfield & FidoServiceRevisionBit.FIDO2))) { peripheral.removeAllListeners(); await peripheral.disconnectAsync(); return; } /** * Handle disconnect peripheral. */ peripheral.on('disconnect', () => { logger.debug('disconnect', peripheral.uuid); /** * Notify device detach. */ logger.debug(device.uuid, peripheral.uuid) this.deviceSubject.next({ device, status: 'detach' }); /** * Disconnect and remove device. */ peripheral.removeAllListeners(); this.device.delete(peripheral.uuid); }); /** * Push fido2 device. */ this.device.set(peripheral.uuid, { peripheral, characteristics: sc.characteristics, device }); this.deviceSubject.next({ device, status: 'attach' }); }); logger.debug('create ble service success'); } /** * Start ble service, allow service to scan device. * @returns */ async start(): Promise<void> { /** * Only start service when service is off. */ if (this.state === DeviceState.on) return; logger.debug('start ble service'); /** * Update service state. */ this.state = DeviceState.on; /** * Ble adapter poweredOn, just start scanning. */ if (nodeBle.state === 'poweredOn') { return await nodeBle.startScanningAsync([FidoService], true); } /** * Waiting for ble adapter poweredOn. */ return await new Promise<void>((resolve, reject) => { /** * Set timeout in case ble adapter turn off. */ const timer = setTimeout(() => { logger.debug('ble adapter timeout') resolve(); }, 8000); /** * Waiting for ble adapter power on. */ this.adapterSubject.pipe(first()).subscribe(async () => { clearTimeout(timer); await nodeBle.startScanningAsync([FidoService], true); resolve(); }); }); } /** * Stop ble service, stop service scanning device. * @returns */ async stop(): Promise<void> { /** * Only start when service is on. */ if (this.state === DeviceState.off) return; logger.debug('stop ble service'); /** * Update service state. */ this.state = DeviceState.off; /** * Stop scan ble device and disconnect all connected peripheral. */ await nodeBle.stopScanningAsync(); // this.device.forEach(x => x.peripheral.disconnectAsync()); return; } /** * Get ble service observable, notify when fido2 ble device is nearby. */ get observable(): Subject<Device> { return this.deviceSubject; } /** * Get connected device. */ getDevice(uuid: string): BLE { let device = this.device.get(uuid); if (device === undefined) throw new BleDeviceNotFound(); return device; } /** * Release ble service, disconnect all peripheral. */ async release(): Promise<void> { this.device.forEach(x => x.peripheral.disconnectAsync()); return; } /** * Remove all listener, free resource, ... */ async shutdown(): Promise<void> { this.device.forEach(x => x.peripheral.disconnectAsync()); await nodeBle.stopScanningAsync(); nodeBle.removeAllListeners(); return; } } export const ble = new BleService();
the_stack
////interface I { //// methodOfInterface(): number; ////} ////interface I2 { //// methodOfInterface2(): number; ////} ////interface I3 { //// getValue(): string; //// method(): string; ////} ////interface I4 { //// staticMethod(): void; //// method(): string; ////} ////class B0 { //// private privateMethod() { } //// protected protectedMethod() { } //// static staticMethod() { } //// getValue(): string | boolean { return "hello"; } //// private privateMethod1() { } //// protected protectedMethod1() { } //// static staticMethod1() { } //// getValue1(): string | boolean { return "hello"; } ////} ////interface I5 extends B0 { //// methodOfInterface5(): number; ////} ////interface I6 extends B0 { //// methodOfInterface6(): number; //// staticMethod(): void; ////} ////interface I7 extends I { //// methodOfInterface7(): number; ////} ////class B { //// private privateMethod() { } //// protected protectedMethod() { } //// static staticMethod() { } //// getValue(): string | boolean { return "hello"; } ////} ////class C0 implements I, I2 { //// /*implementsIAndI2*/ ////} ////class C00 implements I, I2 { //// static /*implementsIAndI2AndWritingStatic*/ ////} ////class C001 implements I, I2 { //// methodOfInterface/*implementsIAndI2AndWritingMethodNameOfI*/ ////} ////class C extends B implements I, I2 { //// /*extendsBAndImplementsIAndI2*/ ////} ////class C1 extends B implements I, I2 { //// static /*extendsBAndImplementsIAndI2AndWritingStatic*/ ////} ////class D extends B implements I, I2 { //// /*extendsBAndImplementsIAndI2WithMethodFromB*/ //// protected protectedMethod() { //// return "protected"; //// } ////} ////class E extends B implements I, I2 { //// /*extendsBAndImplementsIAndI2WithMethodFromI*/ //// methodOfInterface() { //// return 1; //// } ////} ////class F extends B implements I, I2 { //// /*extendsBAndImplementsIAndI2WithMethodFromBAndI*/ //// protected protectedMethod() { //// return "protected" //// } //// methodOfInterface() { //// return 1; //// } ////} ////class F2 extends B implements I, I2 { //// protected protectedMethod() { //// return "protected" //// } //// methodOfInterface() { //// return 1; //// } //// static /*extendsBAndImplementsIAndI2WithMethodFromBAndIAndTypesStatic*/ ////} ////class G extends B implements I3 { //// /*extendsBAndImplementsI3WithSameNameMembers*/ ////} ////class H extends B implements I3 { //// /*extendsBAndImplementsI3WithSameNameMembersAndHasImplementedTheMember*/ //// getValue() { //// return "hello"; //// } ////} ////class J extends B0 implements I4 { //// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethod*/ ////} ////class L extends B0 implements I4 { //// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethod*/ //// staticMethod2() { //// return "hello"; //// } ////} ////class K extends B0 implements I4 { //// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethod*/ //// staticMethod() { //// return "hello"; //// } ////} ////class M extends B0 implements I4 { //// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStatic*/ //// static staticMethod() { //// return "hello"; //// } ////} ////class N extends B0 implements I4 { //// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBoth*/ //// staticMethod() { //// return "hello"; //// } //// static staticMethod() { //// return "hello"; //// } ////} ////class J1 extends B0 implements I4 { //// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodWritingStatic*/ ////} ////class L1 extends B0 implements I4 { //// staticMethod2() { //// return "hello"; //// } //// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethodWritingStatic*/ ////} ////class K1 extends B0 implements I4 { //// staticMethod() { //// return "hello"; //// } //// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodWritingStatic*/ ////} ////class M1 extends B0 implements I4 { //// static staticMethod() { //// return "hello"; //// } //// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStaticWritingStatic*/ ////} ////class N1 extends B0 implements I4 { //// staticMethod() { //// return "hello"; //// } //// static staticMethod() { //// return "hello"; //// } //// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBothWritingStatic*/ ////} ////class O implements I7 { //// /*implementsI7whichExtendsI*/ ////} ////class P implements I7, I { //// /*implementsI7whichExtendsIAndAlsoImplementsI*/ ////} ////class Q implements I, I7 { //// /*implementsIAndAlsoImplementsI7whichExtendsI*/ ////} ////class R implements I5 { //// /*implementsI5ThatExtendsB0*/ ////} ////class S implements I6 { //// /*implementsI6ThatExtendsB0AndHasStaticMethodOfB0*/ ////} ////class T extends B0 implements I5 { //// /*extendsB0AndImplementsI5ThatExtendsB0*/ ////} ////class U extends B0 implements I6 { //// /*extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0*/ ////} ////class R1 implements I5 { //// static /*implementsI5ThatExtendsB0TypesStatic*/ ////} ////class S1 implements I6 { //// static /*implementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic*/ ////} ////class T1 extends B0 implements I5 { //// static /*extendsB0AndImplementsI5ThatExtendsB0TypesStatic*/ ////} ////class U1 extends B0 implements I6 { //// static /*extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic*/ ////} const allowedKeywordCount = verify.allowedClassElementKeywords.length; type CompletionInfo = [string, string]; type CompletionInfoVerifier = { validMembers: CompletionInfo[], invalidMembers: CompletionInfo[] }; function verifyClassElementLocations({ validMembers, invalidMembers }: CompletionInfoVerifier, classElementCompletionLocations: string[]) { for (const marker of classElementCompletionLocations) { goTo.marker(marker); verifyCompletionInfo(validMembers, verify); verifyCompletionInfo(invalidMembers, verify.not); verify.completionListContainsClassElementKeywords(); verify.completionListCount(allowedKeywordCount + validMembers.length); } } function verifyCompletionInfo(memberInfo: CompletionInfo[], verify: FourSlashInterface.verifyNegatable) { for (const [symbol, text] of memberInfo) { verify.completionListContains(symbol, text, /*documentation*/ undefined, "method"); } } const validInstanceMembersOfBaseClassB: CompletionInfo[] = [ ["getValue", "(method) B.getValue(): string | boolean"], ["protectedMethod", "(method) B.protectedMethod(): void"], ]; const validStaticMembersOfBaseClassB: CompletionInfo[] = [ ["staticMethod", "(method) B.staticMethod(): void"] ]; const privateMembersOfBaseClassB: CompletionInfo[] = [ ["privateMethod", "(method) B.privateMethod(): void"], ]; const protectedPropertiesOfBaseClassB0: CompletionInfo[] = [ ["protectedMethod", "(method) B0.protectedMethod(): void"], ["protectedMethod1", "(method) B0.protectedMethod1(): void"], ]; const publicPropertiesOfBaseClassB0: CompletionInfo[] = [ ["getValue", "(method) B0.getValue(): string | boolean"], ["getValue1", "(method) B0.getValue1(): string | boolean"], ]; const validInstanceMembersOfBaseClassB0: CompletionInfo[] = protectedPropertiesOfBaseClassB0.concat(publicPropertiesOfBaseClassB0); const validStaticMembersOfBaseClassB0: CompletionInfo[] = [ ["staticMethod", "(method) B0.staticMethod(): void"], ["staticMethod1", "(method) B0.staticMethod1(): void"] ]; const privateMembersOfBaseClassB0: CompletionInfo[] = [ ["privateMethod", "(method) B0.privateMethod(): void"], ["privateMethod1", "(method) B0.privateMethod1(): void"], ]; const membersOfI: CompletionInfo[] = [ ["methodOfInterface", "(method) I.methodOfInterface(): number"], ]; const membersOfI2: CompletionInfo[] = [ ["methodOfInterface2", "(method) I2.methodOfInterface2(): number"], ]; const membersOfI3: CompletionInfo[] = [ ["getValue", "(method) I3.getValue(): string"], ["method", "(method) I3.method(): string"], ]; const membersOfI4: CompletionInfo[] = [ ["staticMethod", "(method) I4.staticMethod(): void"], ["method", "(method) I4.method(): string"], ]; const membersOfI5: CompletionInfo[] = publicPropertiesOfBaseClassB0.concat([ ["methodOfInterface5", "(method) I5.methodOfInterface5(): number"] ]); const membersOfI6: CompletionInfo[] = publicPropertiesOfBaseClassB0.concat([ ["staticMethod", "(method) I6.staticMethod(): void"], ["methodOfInterface6", "(method) I6.methodOfInterface6(): number"] ]); const membersOfI7: CompletionInfo[] = membersOfI.concat([ ["methodOfInterface7", "(method) I7.methodOfInterface7(): number"] ]); function getCompletionInfoVerifier( validMembers: CompletionInfo[], invalidMembers: CompletionInfo[], arrayToDistribute: CompletionInfo[], isValidDistributionCriteria: (v: CompletionInfo) => boolean): CompletionInfoVerifier { if (arrayToDistribute) { validMembers = validMembers.concat(arrayToDistribute.filter(isValidDistributionCriteria)); invalidMembers = invalidMembers.concat(arrayToDistribute.filter(v => !isValidDistributionCriteria(v))); } return { validMembers, invalidMembers } } const noMembers: CompletionInfo[] = []; const membersOfIAndI2 = membersOfI.concat(membersOfI2); const invalidMembersOfBAtInstanceLocation = privateMembersOfBaseClassB.concat(validStaticMembersOfBaseClassB); // members of I and I2 verifyClassElementLocations({ validMembers: membersOfIAndI2, invalidMembers: noMembers }, [ "implementsIAndI2", "implementsIAndI2AndWritingMethodNameOfI" ]); // Static location so no members of I and I2 verifyClassElementLocations({ validMembers: noMembers, invalidMembers: membersOfIAndI2 }, ["implementsIAndI2AndWritingStatic"]); const allInstanceBAndIAndI2 = membersOfIAndI2.concat(validInstanceMembersOfBaseClassB); // members of instance B, I and I2 verifyClassElementLocations({ validMembers: allInstanceBAndIAndI2, invalidMembers: invalidMembersOfBAtInstanceLocation }, ["extendsBAndImplementsIAndI2"]); // static location so only static members of B and no members of instance B, I and I2 verifyClassElementLocations({ validMembers: validStaticMembersOfBaseClassB, invalidMembers: privateMembersOfBaseClassB.concat(allInstanceBAndIAndI2) }, [ "extendsBAndImplementsIAndI2AndWritingStatic", "extendsBAndImplementsIAndI2WithMethodFromBAndIAndTypesStatic" ]); // instance members of B without protectedMethod, I and I2 verifyClassElementLocations( getCompletionInfoVerifier( /*validMembers*/ membersOfIAndI2, /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, /*arrayToDistribute*/ validInstanceMembersOfBaseClassB, value => value[0] !== "protectedMethod"), ["extendsBAndImplementsIAndI2WithMethodFromB"]); // instance members of B, members of T without methodOfInterface and I2 verifyClassElementLocations( getCompletionInfoVerifier( /*validMembers*/ membersOfI2.concat(validInstanceMembersOfBaseClassB), /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, /*arrayToDistribute*/ membersOfI, value => value[0] !== "methodOfInterface"), ["extendsBAndImplementsIAndI2WithMethodFromI"]); // instance members of B without protectedMethod, members of T without methodOfInterface and I2 verifyClassElementLocations( getCompletionInfoVerifier( /*validMembers*/ membersOfI2, /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, /*arrayToDistribute*/ membersOfI.concat(validInstanceMembersOfBaseClassB), value => value[0] !== "methodOfInterface" && value[0] !== "protectedMethod"), ["extendsBAndImplementsIAndI2WithMethodFromBAndI"]); // members of B and members of I3 that are not same as name of method in B verifyClassElementLocations( getCompletionInfoVerifier( /*validMembers*/ validInstanceMembersOfBaseClassB, /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, /*arrayToDistribute*/ membersOfI3, value => value[0] !== "getValue"), ["extendsBAndImplementsI3WithSameNameMembers"]); // members of B (without getValue since its implemented) and members of I3 that are not same as name of method in B verifyClassElementLocations( getCompletionInfoVerifier( /*validMembers*/ noMembers, /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, /*arrayToDistribute*/ membersOfI3.concat(validInstanceMembersOfBaseClassB), value => value[0] !== "getValue"), ["extendsBAndImplementsI3WithSameNameMembersAndHasImplementedTheMember"]); const invalidMembersOfB0AtInstanceSide = privateMembersOfBaseClassB0.concat(validStaticMembersOfBaseClassB0); const invalidMembersOfB0AtStaticSide = privateMembersOfBaseClassB0.concat(validInstanceMembersOfBaseClassB0); // members of B0 and members of I4 verifyClassElementLocations({ validMembers: validInstanceMembersOfBaseClassB0.concat(membersOfI4), invalidMembers: invalidMembersOfB0AtInstanceSide }, [ "extendsB0ThatExtendsAndImplementsI4WithStaticMethod", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethod", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStatic" ]); // members of B0 and members of I4 that are not staticMethod verifyClassElementLocations( getCompletionInfoVerifier( /*validMembers*/ validInstanceMembersOfBaseClassB0, /*invalidMembers*/ invalidMembersOfB0AtInstanceSide, /*arrayToDistribute*/ membersOfI4, value => value[0] !== "staticMethod" ), [ "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethod", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBoth" ]); // static members of B0 verifyClassElementLocations({ validMembers: validStaticMembersOfBaseClassB0, invalidMembers: invalidMembersOfB0AtStaticSide.concat(membersOfI4) }, [ "extendsB0ThatExtendsAndImplementsI4WithStaticMethodWritingStatic", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethodWritingStatic", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodWritingStatic" ]); // static members of B0 without staticMethod verifyClassElementLocations( getCompletionInfoVerifier( /*validMembers*/ noMembers, /*invalidMembers*/ invalidMembersOfB0AtStaticSide.concat(membersOfI4), /*arrayToDistribute*/ validStaticMembersOfBaseClassB0, value => value[0] !== "staticMethod" ), [ "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStaticWritingStatic", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBothWritingStatic" ]); // members of I7 extends I verifyClassElementLocations({ validMembers: membersOfI7, invalidMembers: noMembers }, [ "implementsI7whichExtendsI", "implementsI7whichExtendsIAndAlsoImplementsI", "implementsIAndAlsoImplementsI7whichExtendsI" ]); const invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 = invalidMembersOfB0AtInstanceSide; // members of I5 extends B0 verifyClassElementLocations({ validMembers: membersOfI5.concat(protectedPropertiesOfBaseClassB0), invalidMembers: invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 }, [ "implementsI5ThatExtendsB0", ]); // members of I6 extends B0 verifyClassElementLocations({ validMembers: membersOfI6.concat(protectedPropertiesOfBaseClassB0), invalidMembers: invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 }, [ "implementsI6ThatExtendsB0AndHasStaticMethodOfB0", ]); // members of B0 and I5 that extends B0 verifyClassElementLocations({ validMembers: membersOfI5.concat(protectedPropertiesOfBaseClassB0), invalidMembers: invalidMembersOfB0AtInstanceSide }, [ "extendsB0AndImplementsI5ThatExtendsB0" ]); // members of B0 and I6 that extends B0 verifyClassElementLocations({ validMembers: membersOfI6.concat(protectedPropertiesOfBaseClassB0), invalidMembers: invalidMembersOfB0AtInstanceSide }, [ "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0" ]); // nothing on static side as these do not extend any other class verifyClassElementLocations({ validMembers: [], invalidMembers: membersOfI5.concat(membersOfI6, invalidMembersOfB0AtStaticSide) }, [ "implementsI5ThatExtendsB0TypesStatic", "implementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic" ]); // statics of base B but nothing from instance side verifyClassElementLocations({ validMembers: validStaticMembersOfBaseClassB0, invalidMembers: membersOfI5.concat(membersOfI6, invalidMembersOfB0AtStaticSide) }, [ "extendsB0AndImplementsI5ThatExtendsB0TypesStatic", "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic" ]);
the_stack
// Test Data Source module Helper.ItemsManager { "use strict"; var UI = WinJS.UI; var Scheduler = WinJS.Utilities.Scheduler; interface IFetchResult { items: any[]; offset: number; totalCount?: number; absoluteIndex?: number; atStart?: boolean; atEnd?: boolean; } function createTestDataAdapter(objects, controller, abilities) { // Private members var listDataNotificationHandler, array = [], keyToIndexMap = {}, nextAvailableKey = 0, requests = [], countBeforeDelta, countAfterDelta, countBeforeOverride, countAfterOverride, dataSourceAccessed = false, editsInProgress = false, requestFulfilledSynchronously = false; function directivesForMethod(method, args) { if (controller && controller.directivesForMethod) { return controller.directivesForMethod(method, args); } else { return null; } } function getDataLength() { return typeof controller.returnCount === 'undefined' ? array.length : Math.min(controller.returnCount, array.length); } function item(key, data) { return { key: key.toString(), data: data }; } function setItem(index, key, data) { array[index] = item(key, data); keyToIndexMap[key] = index; } function updateKeyToIndexMap(first) { // Update the key map entries for all indices that changed for (var i = first; i < array.length; i++) { keyToIndexMap[array[i].key] = i; } } function keyFromIndex(index) { return (index < 0 || index >= array.length ? null : array[index].key); } function indexIfSupported(index) { return (abilities && !abilities.itemsFromIndex ? undefined : index); } function itemsFromIndexImplementation(complete, error, index, countBefore, countAfter, returnAbsoluteIndex, maxLength) { if (controller.communicationFailure) { error(new WinJS.ErrorFromName(UI.FetchError.noResponse.toString())); } else { var directives = directivesForMethod("itemsFromIndex", [index, countBefore, countAfter]); dataSourceAccessed = true; countBefore = (countBeforeOverride >= 0 ? countBeforeOverride : Math.max(countBefore + countBeforeDelta, 0)); countAfter = (countAfterOverride >= 0 ? countAfterOverride : Math.max(countAfter + countAfterDelta, 0)); // returnCount simulate a datasource that is changing size. // If returnCount is defined, then the maximum number of items can be retrived from this dataSource is returnCount. if (index >= maxLength) { error(new WinJS.ErrorFromName(UI.FetchError.doesNotExist.toString())); } else { var first = Math.max(0, index - countBefore), last = Math.min(maxLength - 1, index + countAfter), items = new Array(last + 1 - first); for (var i = first; i <= last; i++) { var item = array[i]; items[i - first] = { key: item.key, data: item.data }; } var fetchResult: IFetchResult = { items: items, offset: index - first, totalCount: (directives.omitCount ? undefined : maxLength), // TODO: omitCount is always undefined. This seems a test bug. I }; if (returnAbsoluteIndex && !directives.omitIndices) { fetchResult.absoluteIndex = index; } if (first === 0) { // If the first item is being returned, volunteer this information fetchResult.atStart = true; } if (last >= maxLength) { // If the last item is being returned, volunteer this information fetchResult.atEnd = true; } complete(fetchResult); } } } function keyValid(key, error) { if (typeof keyToIndexMap[key] !== "number") { error(new WinJS.ErrorFromName(UI.EditError.noLongerMeaningful.toString())); return false; } else { return true; } } function noop() { } function insert(complete, error, index, data) { if (controller.communicationFailure) { error(new WinJS.ErrorFromName(UI.EditError.noResponse.toString())); } else { var itemNew = item(nextAvailableKey++, data); array.splice(index, 0, itemNew); updateKeyToIndexMap(index); complete(itemNew); } } function change(complete, error, key, dataNew) { if (controller.communicationFailure) { error(new WinJS.ErrorFromName(UI.EditError.noResponse.toString())); } else if (controller.readOnly) { error(new WinJS.ErrorFromName(UI.EditError.notPermitted.toString())); } else if (controller.notMeaningfulEdit) { error(new WinJS.ErrorFromName(UI.EditError.noLongerMeaningful.toString())); } else { var index = keyToIndexMap[key]; array[index].data = dataNew; complete(); } } function move(complete, error, indexTo, key) { if (controller.communicationFailure) { error(new WinJS.ErrorFromName(UI.EditError.noResponse.toString())); } else { var indexFrom = keyToIndexMap[key], removed = array.splice(indexFrom, 1); if (indexFrom < indexTo) { indexTo--; } array.splice(indexTo, 0, removed[0]); updateKeyToIndexMap(Math.min(indexFrom, indexTo)); complete(); } } function remove(complete, error, key) { if (controller.communicationFailure) { error(new WinJS.ErrorFromName(UI.EditError.noResponse.toString())); } else { var index = keyToIndexMap[key]; delete keyToIndexMap[key]; array.splice(index, 1); updateKeyToIndexMap(index); complete(); } } function insertionIndex(previousKey, nextKey) { var index; if (previousKey === null) { return keyToIndexMap[nextKey]; } index = keyToIndexMap[previousKey] + 1; if (nextKey !== null && keyToIndexMap[nextKey] !== index) { throw new Error("Invalid arguments: previousKey and nextKey should be the keys of adjacent elements."); } return index; } function changeNotificationsEnabled(method, args) { var directives = directivesForMethod(method, args); return directives && directives.sendChangeNotifications; } function implementRequest(request) { var directives = request.directives; countBeforeDelta = 0; countAfterDelta = 0; countBeforeOverride = -1; countAfterOverride = -1; if (directives) { if (directives.countBeforeDelta !== undefined) { countBeforeDelta = directives.countBeforeDelta; } if (directives.countAfterDelta !== undefined) { countAfterDelta = directives.countAfterDelta; } if (directives.countBeforeOverride > 0) { countBeforeOverride = directives.countBeforeOverride; } if (directives.countAfterOverride > 0) { countAfterOverride = directives.countAfterOverride; } } request.execute(); } function createPromise(method, args, promiseInit) { return new WinJS.Promise(function (complete, error) { var directives = directivesForMethod(method, args); var request = { method: method, args: args, directives: directives, execute: function () { promiseInit(complete, error); } }; if (!directives || !directives.callMethodSynchronously) { requests.push(request); if (directives && typeof directives.delay === "number") { var implementNextRequest = function implementNextRequest() { if (requests.length > 0) { implementRequest(requests.splice(0, 1)[0]); } }; if (directives.delay === 0) { Scheduler.schedule(function () { implementNextRequest(); }, Scheduler.Priority.high, null, "TestComponents._TestDataSource._implementNextRequest"); } else { setTimeout(implementNextRequest, directives.delay); } } } else { requestFulfilledSynchronously = true; implementRequest(request); } }); } // Construction controller = controller || {}; // Build the item array and key map for (var i = 0, length = objects.length; i < length; i++) { setItem(i, nextAvailableKey, objects[i]); nextAvailableKey++; } // Public methods return { // DataSource methods setNotificationHandler: function (notificationHandler) { listDataNotificationHandler = notificationHandler; }, itemSignature: abilities && !abilities.itemSignature ? undefined : function (itemData) { if (WinJS.Utilities._isDOMElement(itemData)) { return "<" + WinJS.Utilities._uniqueID(itemData) + ">"; } return "<" + JSON.stringify(itemData) + ">"; }, itemsFromStart: abilities && !abilities.itemsFromStart ? undefined : function (count) { var maxLength = getDataLength(); return createPromise("itemsFromStart", arguments, function (complete, error) { if (typeof controller.returnCountBeforePromise === 'undefined') { maxLength = getDataLength(); } if (maxLength === 0) { error(new WinJS.ErrorFromName(UI.FetchError.doesNotExist.toString())); } else { itemsFromIndexImplementation(complete, error, 0, 0, count - 1, false, maxLength); } }); }, itemsFromEnd: abilities && !abilities.itemsFromEnd ? undefined : function (count) { var maxLength = getDataLength(); return createPromise("itemsFromEnd", arguments, function (complete, error) { if (typeof controller.returnCountBeforePromise === 'undefined') { maxLength = getDataLength(); } if (maxLength === 0) { error(new WinJS.ErrorFromName(UI.FetchError.doesNotExist.toString())); } else { itemsFromIndexImplementation(complete, error, maxLength - 1, count - 1, 0, true, maxLength); } }); }, itemsFromKey: abilities && !abilities.itemsFromKey ? undefined : function (key, countBefore, countAfter) { var maxLength = getDataLength(); return createPromise("itemsFromKey", arguments, function (complete, error) { var index = keyToIndexMap[key]; if (typeof controller.returnCountBeforePromise === 'undefined') { maxLength = getDataLength(); } if (typeof index !== "number") { error(new WinJS.ErrorFromName(UI.FetchError.doesNotExist.toString())); } else { itemsFromIndexImplementation(complete, error, index, countBefore, countAfter, true, maxLength); } }); }, itemsFromIndex: abilities && !abilities.itemsFromIndex ? undefined : function (index, countBefore, countAfter) { var maxLength = getDataLength(); return createPromise("itemsFromIndex", arguments, function (complete, error) { if (typeof controller.returnCountBeforePromise === 'undefined') { maxLength = getDataLength(); } itemsFromIndexImplementation(complete, error, index, countBefore, countAfter, false, maxLength); }); }, itemsFromDescription: abilities && !abilities.itemsFromDescription ? undefined : function (description, countBefore, countAfter) { var maxLength = getDataLength(); return createPromise("itemsFromDescription", arguments, function (complete, error) { // TODO: For now, just treat the description as a key var index = keyToIndexMap[description]; if (typeof controller.returnCountBeforePromise === 'undefined') { maxLength = getDataLength(); } if (typeof index !== "number") { error(new WinJS.ErrorFromName(UI.FetchError.doesNotExist.toString())); } else { itemsFromIndexImplementation(complete, error, index, countBefore, countAfter, true, maxLength); } }); }, getCount: abilities && !abilities.getCount ? undefined : function () { var maxLength = getDataLength(); return createPromise("getCount", arguments, function (complete, error) { if (typeof controller.returnCountBeforePromise === 'undefined') { maxLength = getDataLength(); } if (controller.count_NoResponse) { error(new WinJS.ErrorFromName(UI.CountError.noResponse.toString())); } else if (controller.countUnknown) { error(new WinJS.ErrorFromName(UI.CountResult.unknown.toString())); } else { complete(maxLength); } }); }, beginEdits: abilities && !abilities.beginEdits ? undefined : function () { if (editsInProgress) { throw new Error(); } editsInProgress = true; }, insertAtStart: abilities && !abilities.insertAtStart ? undefined : function (key, data) { return createPromise("insertAtStart", arguments, function (complete, error) { // key parameter is ignored, as keys are generated insert(complete, error, 0, data); }); }, insertBefore: abilities && !abilities.insertBefore ? undefined : function (key, data, nextKey) { return createPromise("insertBefore", arguments, function (complete, error) { // key parameter is ignored, as keys are generated if (keyValid(nextKey, error)) { insert(complete, error, keyToIndexMap[nextKey], data); } }); }, insertAfter: abilities && !abilities.insertAfter ? undefined : function (key, data, previousKey) { return createPromise("insertAfter", arguments, function (complete, error) { // key parameter is ignored, as keys are generated if (keyValid(previousKey, error)) { insert(complete, error, keyToIndexMap[previousKey] + 1, data); } }); }, insertAtEnd: abilities && !abilities.insertAtEnd ? undefined : function (key, data) { var maxLength = getDataLength(); return createPromise("insertAtEnd", arguments, function (complete, error) { // key parameter is ignored, as keys are generated if (typeof controller.returnCountBeforePromise === 'undefined') { maxLength = getDataLength(); } insert(complete, error, maxLength, data); }); }, change: abilities && !abilities.change ? undefined : function (key, newData) { return createPromise("change", arguments, function (complete, error) { if (keyValid(key, error)) { change(complete, error, key, newData); } }); }, moveToStart: abilities && !abilities.moveToStart ? undefined : function (key) { return createPromise("moveToStart", arguments, function (complete, error) { if (keyValid(key, error)) { move(complete, error, 0, key); } }); }, moveBefore: abilities && !abilities.moveBefore ? undefined : function (key, nextKey) { return createPromise("moveBefore", arguments, function (complete, error) { if (keyValid(key, error) && keyValid(nextKey, error)) { move(complete, error, keyToIndexMap[nextKey], key); } }); }, moveAfter: abilities && !abilities.moveAfter ? undefined : function (key, previousKey) { return createPromise("moveAfter", arguments, function (complete, error) { if (keyValid(key, error) && keyValid(previousKey, error)) { move(complete, error, keyToIndexMap[previousKey] + 1, key); } }); }, moveToEnd: abilities && !abilities.moveToEnd ? undefined : function (key) { var maxLength = getDataLength(); return createPromise("moveToEnd", arguments, function (complete, error) { if (typeof controller.returnCountBeforePromise === 'undefined') { maxLength = getDataLength(); } if (keyValid(key, error)) { move(complete, error, maxLength, key); } }); }, remove: abilities && !abilities.remove ? undefined : function (key) { return createPromise("remove", arguments, function (complete, error) { if (keyValid(key, error)) { remove(complete, error, key); } }); }, endEdits: abilities && !abilities.endEdits ? undefined : function () { if (!editsInProgress) { throw new Error(); } editsInProgress = false; }, // Test methods // Returns true if the data source has been accessed since the last call to clearDataSourceAccessed isDataSourceAccessed: function () { return dataSourceAccessed; }, clearDataSourceAccessed: function () { dataSourceAccessed = false; }, insertItem: function (key, data, previousKey, nextKey) { // key parameter is ignored, as keys are generated var index = insertionIndex(previousKey, nextKey); array.splice(index, 0, item(nextAvailableKey, data)); updateKeyToIndexMap(index); nextAvailableKey++; }, changeItem: function (key, newData) { array[keyToIndexMap[key]].data = newData; }, removeItem: function (key) { var index = keyToIndexMap[key]; delete keyToIndexMap[key]; array.splice(index, 1); updateKeyToIndexMap(index); }, moveItem: function (key, previousKey, nextKey) { var indexFrom = keyToIndexMap[key], indexTo = insertionIndex(previousKey, nextKey), removed = array.splice(indexFrom, 1); if (indexFrom < indexTo) { indexTo--; } array.splice(indexTo, 0, removed[0]); updateKeyToIndexMap(Math.min(indexFrom, indexTo)); }, // Sets the value for the dataSourceAccessed flag setDataSourceAccessedFlag: function (status) { dataSourceAccessed = status; }, // Call to this method will resume data source edits reEstablishDSConnection: function () { controller.communicationFailure = false; }, // This will set properties like readOnly/notMeaningfulEdit. // Based on these values, DSA returns notPermitted/noLongerMeaningful status code from the editing methods. setProperty: function (propertyName, value) { if (propertyName === "notMeaningfulEdit") controller.notMeaningfulEdit = value; else if (propertyName === "readOnly") controller.readOnly = value; else if (propertyName === "communicationFailure") controller.communicationFailure = value; else if (propertyName === "count_NoResponse") controller.count_NoResponse = true; else if (propertyName === "countUnknown") controller.countUnknown = true; else if (propertyName === "returnCount") controller.returnCount = value; else if (propertyName === "returnCountBeforePromise") // when value is defined, returnCount is calcualted before promise created; otherwise calculated when promise executed. // By default, returnCountBeforePromise is undefined; and all the previous test is using the value calculated when promise executed and the value is array.length // Thus, adding this varible does not break existing test. // This value should be set at beginning of a test; and should not be changed in the test. // If you change it during a test, then the promise still in process will use the new value. controller.returnCountBeforePromise = value; }, swapItems: function (indexA, indexB) { var temp = array[indexA]; array[indexA] = array[indexB]; array[indexB] = temp; updateKeyToIndexMap(0); }, changeKey: function (oldKey, newKey) { var index = keyToIndexMap[oldKey]; array[index].key = newKey; delete keyToIndexMap[oldKey]; keyToIndexMap[newKey] = index; }, requestCount: function () { return requests.length; }, readRequest: function (index) { return requests[index]; }, fulfillRequest: function (index) { implementRequest(requests.splice(index, 1)[0]); }, fulfillNextRequest: function () { if (requests.length > 0) { this.fulfillRequest(0); } }, fulfillRandomRequest: function () { if (requests.length > 0) { this.fulfillRequest(Helper.ItemsManager.pseudorandom(requests.length)); } }, fulfillAllRequests: function () { while (requests.length > 0) { this.fulfillNextRequest(); } }, requestFulfilledSynchronously: function () { var result = requestFulfilledSynchronously; // Calling this method clears the flag requestFulfilledSynchronously = false; return result; }, replaceItems: function (items) { array = []; keyToIndexMap = {}; for (var i = 0, length = items.length; i < length; i++) { var item = items[i]; setItem(i, item.key, item.data) var keyValue = parseInt(item.key, 10); if (nextAvailableKey <= keyValue) { nextAvailableKey = keyValue + 1; } } }, getItems: function () { return array; }, invalidateAll: function () { listDataNotificationHandler.invalidateAll(); }, reload: function () { listDataNotificationHandler.reload(); }, indexFromKey: function (key) { return keyToIndexMap[key]; }, currentCount: function () { return array.length; }, currentMaxLength: function () { var maxLength = getDataLength(); return maxLength; }, beginModifications: function () { if (changeNotificationsEnabled("beginNotifications", arguments)) { listDataNotificationHandler.beginNotifications(); } }, insertAtIndex: function (data, index) { LiveUnit.Assert.isTrue(index >= 0 && index <= array.length); insert(noop, noop, index, data); if (changeNotificationsEnabled("insertAtIndex", arguments)) { listDataNotificationHandler.inserted(array[index], keyFromIndex(index - 1), keyFromIndex(index + 1), indexIfSupported(index)); } }, changeAtIndex: function (index, newData) { LiveUnit.Assert.isTrue(index >= 0 && index < array.length); var key = array[index].key; change(noop, noop, key, newData); if (changeNotificationsEnabled("changeAtIndex", arguments)) { listDataNotificationHandler.changed(array[index]); } }, moveToIndex: function (index, newIndex) { LiveUnit.Assert.isTrue(index >= 0 && index < array.length); LiveUnit.Assert.isTrue(newIndex >= 0 && newIndex <= array.length); var key = array[index].key, data = array[index].data, previousKey = keyFromIndex(newIndex - 1), nextKey = keyFromIndex(newIndex); move(noop, noop, newIndex, key); if (changeNotificationsEnabled("moveToIndex", arguments)) { listDataNotificationHandler.moved(array[keyToIndexMap[key]], previousKey, nextKey, indexIfSupported(index), indexIfSupported(newIndex)); } }, removeAtIndex: function (index) { LiveUnit.Assert.isTrue(index >= 0 && index < array.length); var key = array[index].key; remove(noop, noop, key); if (changeNotificationsEnabled("removeAtIndex", arguments)) { listDataNotificationHandler.removed(key, indexIfSupported(index)); } }, endModifications: function () { if (changeNotificationsEnabled("endModifications", arguments)) { listDataNotificationHandler.endNotifications(); } } }; }; var TestDataSource = WinJS.Class.derive(UI.VirtualizedDataSource, function (objects, controller, abilities) { var testDataAdapter = createTestDataAdapter(objects, controller, abilities); this._baseDataSourceConstructor(testDataAdapter); this.testDataAdapter = testDataAdapter; }); export function createTestDataSource(objects, controller, abilities) { return new TestDataSource(objects, controller, abilities); }; }
the_stack
import { RestContext, rest } from 'msw'; import { setupServer } from 'msw/node'; import { ConfigReader } from '@backstage/config'; import { PermissionClient } from './PermissionClient'; import { EvaluatePermissionRequest, AuthorizeResult, IdentifiedPermissionMessage, ConditionalPolicyDecision, } from './types/api'; import { DiscoveryApi } from './types/discovery'; import { createPermission } from './permissions'; const server = setupServer(); const token = 'fake-token'; const mockBaseUrl = 'http://backstage:9191/i-am-a-mock-base'; const discovery: DiscoveryApi = { async getBaseUrl() { return mockBaseUrl; }, }; const client: PermissionClient = new PermissionClient({ discovery, config: new ConfigReader({ permission: { enabled: true } }), }); const mockPermission = createPermission({ name: 'test.permission', attributes: {}, resourceType: 'foo', }); describe('PermissionClient', () => { beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); afterAll(() => server.close()); afterEach(() => server.resetHandlers()); describe('authorize', () => { const mockAuthorizeConditional = { permission: mockPermission, resourceRef: 'foo:bar', }; const mockAuthorizeHandler = jest.fn((req, res, { json }: RestContext) => { const responses = req.body.items.map( (a: IdentifiedPermissionMessage<EvaluatePermissionRequest>) => ({ id: a.id, result: AuthorizeResult.ALLOW, }), ); return res(json({ items: responses })); }); beforeEach(() => { server.use(rest.post(`${mockBaseUrl}/authorize`, mockAuthorizeHandler)); }); afterEach(() => { jest.clearAllMocks(); }); it('should fetch entities from correct endpoint', async () => { await client.authorize([mockAuthorizeConditional]); expect(mockAuthorizeHandler).toHaveBeenCalled(); }); it('should include a request body', async () => { await client.authorize([mockAuthorizeConditional]); const request = mockAuthorizeHandler.mock.calls[0][0]; expect(request.body).toEqual({ items: [ expect.objectContaining({ permission: mockPermission, resourceRef: 'foo:bar', }), ], }); }); it('should return the response from the fetch request', async () => { const response = await client.authorize([mockAuthorizeConditional]); expect(response[0]).toEqual( expect.objectContaining({ result: AuthorizeResult.ALLOW }), ); }); it('should not include authorization headers if no token is supplied', async () => { await client.authorize([mockAuthorizeConditional]); const request = mockAuthorizeHandler.mock.calls[0][0]; expect(request.headers.has('authorization')).toEqual(false); }); it('should include correctly-constructed authorization header if token is supplied', async () => { await client.authorize([mockAuthorizeConditional], { token }); const request = mockAuthorizeHandler.mock.calls[0][0]; expect(request.headers.get('authorization')).toEqual('Bearer fake-token'); }); it('should forward response errors', async () => { mockAuthorizeHandler.mockImplementationOnce( (_req, res, { status }: RestContext) => { return res(status(401)); }, ); await expect( client.authorize([mockAuthorizeConditional], { token }), ).rejects.toThrowError(/request failed with 401/i); }); it('should reject responses with missing ids', async () => { mockAuthorizeHandler.mockImplementationOnce( (_req, res, { json }: RestContext) => { return res( json({ items: [{ id: 'wrong-id', result: AuthorizeResult.ALLOW }], }), ); }, ); await expect( client.authorize([mockAuthorizeConditional], { token }), ).rejects.toThrowError(/items in response do not match request/i); }); it('should reject invalid responses', async () => { mockAuthorizeHandler.mockImplementationOnce( (req, res, { json }: RestContext) => { const responses = req.body.items.map( (a: IdentifiedPermissionMessage<EvaluatePermissionRequest>) => ({ id: a.id, outcome: AuthorizeResult.ALLOW, }), ); return res(json({ items: responses })); }, ); await expect( client.authorize([mockAuthorizeConditional], { token }), ).rejects.toThrowError(/invalid input/i); }); it('should allow all when permission.enabled is false', async () => { mockAuthorizeHandler.mockImplementationOnce( (req, res, { json }: RestContext) => { const responses = req.body.map( (a: IdentifiedPermissionMessage<EvaluatePermissionRequest>) => ({ id: a.id, result: AuthorizeResult.DENY, }), ); return res(json({ items: responses })); }, ); const disabled = new PermissionClient({ discovery, config: new ConfigReader({ permission: { enabled: false } }), }); const response = await disabled.authorize([mockAuthorizeConditional]); expect(response[0]).toEqual( expect.objectContaining({ result: AuthorizeResult.ALLOW }), ); expect(mockAuthorizeHandler).not.toBeCalled(); }); it('should allow all when permission.enabled is not configured', async () => { mockAuthorizeHandler.mockImplementationOnce( (req, res, { json }: RestContext) => { const responses = req.body.map( (a: IdentifiedPermissionMessage<EvaluatePermissionRequest>) => ({ id: a.id, outcome: AuthorizeResult.DENY, }), ); return res(json(responses)); }, ); const disabled = new PermissionClient({ discovery, config: new ConfigReader({}), }); const response = await disabled.authorize([mockAuthorizeConditional]); expect(response[0]).toEqual( expect.objectContaining({ result: AuthorizeResult.ALLOW }), ); expect(mockAuthorizeHandler).not.toBeCalled(); }); }); describe('authorizeConditional', () => { const mockResourceAuthorizeConditional = { permission: mockPermission, }; const mockPolicyDecisionHandler = jest.fn( (req, res, { json }: RestContext) => { const responses = req.body.items.map( (a: IdentifiedPermissionMessage<ConditionalPolicyDecision>) => ({ id: a.id, pluginId: 'test-plugin', resourceType: 'test-resource', result: AuthorizeResult.CONDITIONAL, conditions: { resourceType: 'test-resource', rule: 'FOO', params: ['bar'], }, }), ); return res(json({ items: responses })); }, ); beforeEach(() => { server.use( rest.post(`${mockBaseUrl}/authorize`, mockPolicyDecisionHandler), ); }); afterEach(() => { jest.clearAllMocks(); }); it('should fetch entities from correct endpoint', async () => { await client.authorizeConditional([mockResourceAuthorizeConditional]); expect(mockPolicyDecisionHandler).toHaveBeenCalled(); }); it('should include a request body', async () => { await client.authorizeConditional([mockResourceAuthorizeConditional]); const request = mockPolicyDecisionHandler.mock.calls[0][0]; expect(request.body).toEqual({ items: [ expect.objectContaining({ permission: mockPermission, }), ], }); }); it('should return the response from the fetch request', async () => { const response = await client.authorizeConditional([ mockResourceAuthorizeConditional, ]); expect(response[0]).toEqual( expect.objectContaining({ result: AuthorizeResult.CONDITIONAL, conditions: { rule: 'FOO', resourceType: 'test-resource', params: ['bar'], }, }), ); }); it('should not include authorization headers if no token is supplied', async () => { await client.authorizeConditional([mockResourceAuthorizeConditional]); const request = mockPolicyDecisionHandler.mock.calls[0][0]; expect(request.headers.has('authorization')).toEqual(false); }); it('should include correctly-constructed authorization header if token is supplied', async () => { await client.authorizeConditional([mockResourceAuthorizeConditional], { token, }); const request = mockPolicyDecisionHandler.mock.calls[0][0]; expect(request.headers.get('authorization')).toEqual('Bearer fake-token'); }); it('should forward response errors', async () => { mockPolicyDecisionHandler.mockImplementationOnce( (_req, res, { status }: RestContext) => { return res(status(401)); }, ); await expect( client.authorizeConditional([mockResourceAuthorizeConditional], { token, }), ).rejects.toThrowError(/request failed with 401/i); }); it('should reject responses with missing ids', async () => { mockPolicyDecisionHandler.mockImplementationOnce( (_req, res, { json }: RestContext) => { return res( json({ items: [{ id: 'wrong-id', result: AuthorizeResult.ALLOW }], }), ); }, ); await expect( client.authorizeConditional([mockResourceAuthorizeConditional], { token, }), ).rejects.toThrowError(/items in response do not match request/i); }); it('should reject invalid responses', async () => { mockPolicyDecisionHandler.mockImplementationOnce( (req, res, { json }: RestContext) => { const responses = req.body.items.map( (a: IdentifiedPermissionMessage<ConditionalPolicyDecision>) => ({ id: a.id, outcome: AuthorizeResult.ALLOW, }), ); return res(json({ items: responses })); }, ); await expect( client.authorizeConditional([mockResourceAuthorizeConditional], { token, }), ).rejects.toThrowError(/invalid input/i); }); it('should allow all when permission.enabled is false', async () => { mockPolicyDecisionHandler.mockImplementationOnce( (req, res, { json }: RestContext) => { const responses = req.body.map( (a: IdentifiedPermissionMessage<ConditionalPolicyDecision>) => ({ id: a.id, result: AuthorizeResult.DENY, }), ); return res(json({ items: responses })); }, ); const disabled = new PermissionClient({ discovery, config: new ConfigReader({ permission: { enabled: false } }), }); const response = await disabled.authorizeConditional( [mockResourceAuthorizeConditional], { token, }, ); expect(response[0]).toEqual( expect.objectContaining({ result: AuthorizeResult.ALLOW }), ); expect(mockPolicyDecisionHandler).not.toBeCalled(); }); it('should allow all when permission.enabled is not configured', async () => { mockPolicyDecisionHandler.mockImplementationOnce( (req, res, { json }: RestContext) => { const responses = req.body.map( (a: IdentifiedPermissionMessage<ConditionalPolicyDecision>) => ({ id: a.id, outcome: AuthorizeResult.DENY, }), ); return res(json(responses)); }, ); const disabled = new PermissionClient({ discovery, config: new ConfigReader({}), }); const response = await disabled.authorizeConditional( [mockResourceAuthorizeConditional], { token, }, ); expect(response[0]).toEqual( expect.objectContaining({ result: AuthorizeResult.ALLOW }), ); expect(mockPolicyDecisionHandler).not.toBeCalled(); }); }); });
the_stack
import connect, {sql} from '..'; const mysql: { createConnection: (opts: any) => any; } = require('mysql2/promise'); jest.setTimeout(30000); const db = connect(); const rawConnection = mysql.createConnection({ uri: process.env.MYSQL_URL, dateStrings: true, }); const rawConnection2 = mysql.createConnection({ uri: process.env.MYSQL_URL, dateStrings: true, }); beforeAll(async () => { await (await rawConnection).query(`SET time_zone = "+00:00";`); }); afterAll(async () => { await db.dispose(); (await rawConnection).close(); (await rawConnection2).close(); }); test('dates', async () => { await db.task(async (db) => { await db.query(sql`SET time_zone = "+00:00";`); await db.query(sql` DROP TABLE IF EXISTS dates_test_dates; CREATE TABLE dates_test_dates ( id INT NOT NULL PRIMARY KEY, a DATETIME NOT NULL, b TIMESTAMP NOT NULL, c TIME NOT NULL, d YEAR NOT NULL ); DROP TABLE IF EXISTS dates_test_pure_dates; CREATE TABLE dates_test_pure_dates ( id INT NOT NULL PRIMARY KEY, date_value DATE NOT NULL ); `); const sampleDate = new Date('2000-06-03T05:40:10.123Z'); await db.query(sql` INSERT INTO dates_test_dates (id, a, b, c, d) VALUES (1, ${sampleDate}, ${sampleDate}, ${sampleDate}, ${2000}), (2, ${'2000-06-03 05:40:10'}, ${'2000-06-03 05:40:10'}, ${'05:40:10.123'}, ${2000}); `); await db.query(sql` INSERT INTO dates_test_pure_dates (id, date_value) VALUES (1, ${'2000-06-03'}), (2, ${new Date('2000-06-03T00:00:00.000Z')}), (3, ${new Date('2000-06-03T01:00:00.000Z')}), (4, ${new Date('2000-06-03T23:00:00.000Z')}); `); expect( (await (await rawConnection).query(`SELECT * from dates_test_dates`))[0], ).toEqual([ { a: '2000-06-03 15:10:10', b: '2000-06-03 15:10:10', c: '15:10:10', d: 2000, id: 1, }, { a: '2000-06-03 05:40:10', b: '2000-06-03 05:40:10', c: '05:40:10', d: 2000, id: 2, }, ]); expect( ( await (await rawConnection).query(`SELECT * from dates_test_pure_dates`) )[0], ).toEqual([ { date_value: '2000-06-03', id: 1, }, { date_value: '2000-06-03', id: 2, }, { date_value: '2000-06-03', id: 3, }, { date_value: '2000-06-04', id: 4, }, ]); const result = await db.query(sql` SELECT * from dates_test_dates; `); expect(result).toEqual([ { a: new Date('2000-06-03T05:40:10.000Z'), b: new Date('2000-06-03T05:40:10.000Z'), c: '15:10:10', d: 2000, id: 1, }, { a: new Date('2000-06-02T20:10:10.000Z'), b: new Date('2000-06-02T20:10:10.000Z'), c: '05:40:10', d: 2000, id: 2, }, ]); expect( await db.query(sql` SELECT * from dates_test_pure_dates; `), ).toEqual([ { date_value: new Date('2000-06-02T14:30:00.000Z'), id: 1, }, { date_value: new Date('2000-06-02T14:30:00.000Z'), id: 2, }, { date_value: new Date('2000-06-02T14:30:00.000Z'), id: 3, }, { date_value: new Date('2000-06-03T14:30:00.000Z'), id: 4, }, ]); }); }); test('dates with timezone set to local', async () => { // setting timezone on another connection has no impact await (await rawConnection2).query(`SET time_zone = "+03:00";`); const db = connect({timeZone: 'local'}); await db.task(async (db) => { // Setting timezone to match our local timezone means that fields of type `TIMESTAMP` are stored // as UTC, and then returned as local time. This means we are now storing the correct times for // `TIMESTAMP` fields. // The `rawConnection` is still set to UTC, so you can see the actual UTC values being stored. await db.query(sql` DROP TABLE IF EXISTS dates_test_dates; CREATE TABLE dates_test_dates ( id INT NOT NULL PRIMARY KEY, a DATETIME NOT NULL, b TIMESTAMP NOT NULL, c TIME NOT NULL, d YEAR NOT NULL ); DROP TABLE IF EXISTS dates_test_pure_dates; CREATE TABLE dates_test_pure_dates ( id INT NOT NULL PRIMARY KEY, date_value DATE NOT NULL ); `); const sampleDate = new Date('2000-06-03T05:40:10.123Z'); await db.query(sql` INSERT INTO dates_test_dates (id, a, b, c, d) VALUES (1, ${sampleDate}, ${sampleDate}, ${sampleDate}, ${2000}), (2, ${'2000-06-03 05:40:10'}, ${'2000-06-03 05:40:10'}, ${'05:40:10.123'}, ${2000}); `); await db.query(sql` INSERT INTO dates_test_pure_dates (id, date_value) VALUES (1, ${'2000-06-03'}), (2, ${new Date('2000-06-03T00:00:00.000Z')}), (3, ${new Date('2000-06-03T01:00:00.000Z')}), (4, ${new Date('2000-06-03T23:00:00.000Z')}); `); expect( (await (await rawConnection).query(`SELECT * from dates_test_dates`))[0], ).toEqual([ { a: '2000-06-03 15:10:10', b: '2000-06-03 05:40:10', c: '15:10:10', d: 2000, id: 1, }, { a: '2000-06-03 05:40:10', b: '2000-06-02 20:10:10', c: '05:40:10', d: 2000, id: 2, }, ]); expect( ( await (await rawConnection).query(`SELECT * from dates_test_pure_dates`) )[0], ).toEqual([ { date_value: '2000-06-03', id: 1, }, { date_value: '2000-06-03', id: 2, }, { date_value: '2000-06-03', id: 3, }, { date_value: '2000-06-04', id: 4, }, ]); const result = await db.query(sql` SELECT * from dates_test_dates; `); expect(result).toEqual([ { a: new Date('2000-06-03T05:40:10.000Z'), b: new Date('2000-06-03T05:40:10.000Z'), c: '15:10:10', d: 2000, id: 1, }, { a: new Date('2000-06-02T20:10:10.000Z'), b: new Date('2000-06-02T20:10:10.000Z'), c: '05:40:10', d: 2000, id: 2, }, ]); expect( await db.query(sql` SELECT * from dates_test_pure_dates; `), ).toEqual([ { date_value: new Date('2000-06-02T14:30:00.000Z'), id: 1, }, { date_value: new Date('2000-06-02T14:30:00.000Z'), id: 2, }, { date_value: new Date('2000-06-02T14:30:00.000Z'), id: 3, }, { date_value: new Date('2000-06-03T14:30:00.000Z'), id: 4, }, ]); }); await db.dispose(); }); test('dates with timezone set to utc', async () => { // setting timezone on another connection has no impact await (await rawConnection2).query(`SET time_zone = "+04:00";`); const db = connect({timeZone: 'utc'}); await db.task(async (db) => { await db.query(sql` DROP TABLE IF EXISTS dates_test_dates; CREATE TABLE dates_test_dates ( id INT NOT NULL PRIMARY KEY, a DATETIME NOT NULL, b TIMESTAMP NOT NULL, c TIME NOT NULL, d YEAR NOT NULL ); DROP TABLE IF EXISTS dates_test_pure_dates; CREATE TABLE dates_test_pure_dates ( id INT NOT NULL PRIMARY KEY, date_value DATE NOT NULL ); `); const sampleDate = new Date('2000-06-03T05:40:10.123Z'); await db.query(sql` INSERT INTO dates_test_dates (id, a, b, c, d) VALUES (1, ${sampleDate}, ${sampleDate}, ${sampleDate}, ${2000}), (2, ${'2000-06-03 05:40:10'}, ${'2000-06-03 05:40:10'}, ${'05:40:10.123'}, ${2000}); `); await db.query(sql` INSERT INTO dates_test_pure_dates (id, date_value) VALUES (1, ${'2000-06-03'}), (2, ${new Date('2000-06-03T00:00:00.000Z')}), (3, ${new Date('2000-06-03T01:00:00.000Z')}), (4, ${new Date('2000-06-03T23:00:00.000Z')}); `); expect( (await (await rawConnection).query(`SELECT * from dates_test_dates`))[0], ).toEqual([ { a: '2000-06-03 05:40:10', b: '2000-06-03 05:40:10', c: '05:40:10', d: 2000, id: 1, }, { a: '2000-06-03 05:40:10', b: '2000-06-03 05:40:10', c: '05:40:10', d: 2000, id: 2, }, ]); expect( ( await (await rawConnection).query(`SELECT * from dates_test_pure_dates`) )[0], ).toEqual([ { date_value: '2000-06-03', id: 1, }, { date_value: '2000-06-03', id: 2, }, { date_value: '2000-06-03', id: 3, }, { date_value: '2000-06-03', id: 4, }, ]); const result = await db.query(sql` SELECT * from dates_test_dates; `); expect(result).toEqual([ { a: new Date('2000-06-03T05:40:10.000Z'), b: new Date('2000-06-03T05:40:10.000Z'), c: '05:40:10', d: 2000, id: 1, }, { a: new Date('2000-06-03T05:40:10.000Z'), b: new Date('2000-06-03T05:40:10.000Z'), c: '05:40:10', d: 2000, id: 2, }, ]); expect( await db.query(sql` SELECT * from dates_test_pure_dates; `), ).toEqual([ { date_value: new Date('2000-06-03T00:00:00.000Z'), id: 1, }, { date_value: new Date('2000-06-03T00:00:00.000Z'), id: 2, }, { date_value: new Date('2000-06-03T00:00:00.000Z'), id: 3, }, { date_value: new Date('2000-06-03T00:00:00.000Z'), id: 4, }, ]); }); await db.dispose(); }); test('DATE as string', async () => { const db = connect({dateMode: 'string'}); await db.query(sql` DROP TABLE IF EXISTS dates_test_pure_dates; CREATE TABLE dates_test_pure_dates ( id INT NOT NULL PRIMARY KEY, date_value DATE NOT NULL ); INSERT INTO dates_test_pure_dates (id, date_value) VALUES (1, ${'2000-06-03'}), (2, ${'2000-06-04'}); `); expect(await db.query(sql`SELECT * from dates_test_pure_dates`)).toEqual([ { date_value: '2000-06-03', id: 1, }, { date_value: '2000-06-04', id: 2, }, ]); await db.dispose(); }); test('DATE as utc', async () => { const db = connect({timeZone: {client: 'utc'}}); await db.query(sql` DROP TABLE IF EXISTS dates_test_pure_dates; CREATE TABLE dates_test_pure_dates ( id INT NOT NULL PRIMARY KEY, date_value DATE NOT NULL ); INSERT INTO dates_test_pure_dates (id, date_value) VALUES (1, ${'2000-06-03'}), (2, ${'2000-06-04'}); `); expect(await db.query(sql`SELECT * from dates_test_pure_dates`)).toEqual([ { date_value: new Date('2000-06-03T00:00:00.000Z'), id: 1, }, { date_value: new Date('2000-06-04T00:00:00.000Z'), id: 2, }, ]); await db.dispose(); });
the_stack
import { Injectable, Injector } from "@angular/core"; import { LocaleService, TelemetryService, TranslationsLoaderService } from "@batch-flask/core"; import { AutoUpdateService } from "@batch-flask/electron"; import { log } from "@batch-flask/utils"; import { AzureEnvironment } from "client/azure-environment"; import { parseArguments } from "client/cli"; import { BlIpcMain } from "client/core/bl-ipc-main"; import { BatchExplorerProperties } from "client/core/properties"; import { TelemetryManager } from "client/core/telemetry/telemetry-manager"; import { ManualProxyConfigurationWindow } from "client/proxy/manual-proxy-configuration-window"; import { ProxyCredentialsWindow } from "client/proxy/proxy-credentials-window"; import { ProxySettingsManager } from "client/proxy/proxy-settings"; import { BatchExplorerLink, Constants, Deferred } from "common"; import { IpcEvent } from "common/constants"; import { app, dialog, ipcMain, protocol, session } from "electron"; import { UpdateCheckResult } from "electron-updater"; import { ProxyCredentials, ProxySettings } from "get-proxy-settings"; import * as os from "os"; import { BehaviorSubject, Observable } from "rxjs"; import { Constants as ClientConstants } from "../client-constants"; import { MainWindow, WindowState } from "../main-window"; import { PythonRpcServerProcess } from "../python-process"; import { RecoverWindow } from "../recover-window"; import { AADService, AuthenticationState, AuthenticationWindow, LogoutError } from "./aad"; import { BatchExplorerInitializer } from "./batch-explorer-initializer"; import { MainWindowManager } from "./main-window-manager"; const osName = `${os.platform()}-${os.arch()}/${os.release()}`; const isDev = ClientConstants.isDev ? "-dev" : ""; const userAgentSuffix = `(${osName}) BatchExplorer/${ClientConstants.version}${isDev}`; export enum BatchExplorerState { Loading, Ready, } @Injectable() export class BatchExplorerApplication { public authenticationWindow = new AuthenticationWindow(this); public recoverWindow = new RecoverWindow(this); public windows: MainWindowManager; public pythonServer = new PythonRpcServerProcess(); public aadService: AADService; public state: Observable<BatchExplorerState>; public proxySettings: ProxySettingsManager; private _state = new BehaviorSubject<BatchExplorerState>(BatchExplorerState.Loading); private _initializer: BatchExplorerInitializer; private _currentlyAskingForCredentials: Promise<any> | null; constructor( public autoUpdater: AutoUpdateService, public translationLoader: TranslationsLoaderService, public localeService: LocaleService, public injector: Injector, public properties: BatchExplorerProperties, private telemetryService: TelemetryService, private telemetryManager: TelemetryManager, private ipcMain: BlIpcMain) { this.windows = new MainWindowManager(this, this.telemetryManager); this.state = this._state.asObservable(); ipcMain.on(IpcEvent.logoutAndLogin, () => { return this.logoutAndLogin(); }); } public async init() { await this.telemetryManager.init(); await this.properties.init(); this.telemetryService.trackEvent({ name: Constants.TelemetryEvents.applicationStart }); this._initializer = this.injector.get(BatchExplorerInitializer); this.aadService = this.injector.get(AADService); this.proxySettings = this.injector.get(ProxySettingsManager); this.ipcMain.init(); await this.aadService.init(); this._registerProtocol(); this._setupProcessEvents(); this._registerFileProtocol(); await this.proxySettings.init(); } /** * Start the app by showing the splash screen */ public async start() { const appReady = new Deferred(); const loggedIn = new Deferred(); this.pythonServer.start(); this._initializer.init(); const window = await this.openFromArguments(process.argv, false); if (!window) { return; } this._setCommonHeaders(window); const loginResponse = this.aadService.login(); loginResponse.done.catch((e) => { if (e instanceof LogoutError) { return; } log.error("Error while login", e); dialog.showMessageBox({ title: "Error during login", type: "error", message: e.toString(), }); this.logoutAndLogin(); }); await loginResponse.started; this._initializer.setTaskStatus("window", "Loading application"); const windowSub = window.state.subscribe((state) => { switch (state) { case WindowState.Loading: this._initializer.setTaskStatus("window", "Loading application"); break; case WindowState.Initializing: this._initializer.setTaskStatus("window", "Initializing application"); break; case WindowState.FailedLoad: this._initializer.setTaskStatus("window", "Fail to load! Make sure you built the app or are running the dev-server."); break; case WindowState.Ready: this._initializer.completeTask("window"); appReady.resolve(); } }); const authSub = this.aadService.authenticationState.subscribe((state) => { switch (state) { case AuthenticationState.None: this._initializer.setLoginStatus("Login to azure active directory"); break; case AuthenticationState.UserInput: this._initializer.setLoginStatus("Prompting for user input"); break; case AuthenticationState.Authenticated: this._initializer.completeLogin(); loggedIn.resolve(); break; } }); await Promise.all([appReady.promise, loggedIn.promise]); windowSub.unsubscribe(); authSub.unsubscribe(); window.show(); } /** * Update the current azure environemnt. * Warning: This will log the user out and redirect him the the loging page. */ public async updateAzureEnvironment(env: AzureEnvironment) { await this.aadService.logout(); this.windows.closeAll(); await this.properties.updateAzureEnvironment(env); await this.aadService.login().done; this.windows.openNewWindow(); } public async logoutAndLogin() { await this.aadService.logout(); await this.aadService.login().done; this.windows.openNewWindow(); } /** * Open a new link in the ms-batch-explorer format * If the link provide a session id which already exists it will change the window with that session id. * @param link ms-batch-explorer://... */ public openLink(link: string | BatchExplorerLink, show) { return this.windows.openLink(link); } /** * Open a new link in the ms-batch-explorer format * @param link ms-batch-explorer://... */ public openNewWindow(link?: string | BatchExplorerLink): MainWindow { return this.windows.openNewWindow(link); } public async openFromArguments(argv: string[], showWhenReady = true): Promise<MainWindow | null> { if (ClientConstants.isDev) { return this.windows.openNewWindow(undefined, showWhenReady); } const program = parseArguments(argv); const arg = program.args[0]; if (!arg || arg.startsWith("data:")) { return this.windows.openNewWindow(undefined, showWhenReady); } try { const link = new BatchExplorerLink(arg); return this.openLink(link, false); } catch (e) { await dialog.showMessageBox({ type: "error", title: "Cannot open given link in BatchExplorer", message: e.message, }); if (this.windows.size === 0) { this.quit(); } return null; } } public debugCrash() { this.windows.debugCrash(); } public quit() { this.pythonServer.stop(); app.quit(); } public checkForUpdates(): Promise<UpdateCheckResult> { return this.autoUpdater.checkForUpdates(); } public askUserForProxyCredentials(): Promise<ProxyCredentials> { log.warn("Asking for proxy credentials"); if (this._currentlyAskingForCredentials) { return this._currentlyAskingForCredentials; } const proxyCredentials = new ProxyCredentialsWindow(this); proxyCredentials.create(); this._currentlyAskingForCredentials = proxyCredentials.credentials; this._currentlyAskingForCredentials.then(() => { this._currentlyAskingForCredentials = null; }).catch(() => { this._currentlyAskingForCredentials = null; }); return this._currentlyAskingForCredentials; } public askUserForProxyConfiguration(current?: ProxySettings | null): Promise<ProxySettings | null> { const proxyCredentials = new ManualProxyConfigurationWindow(this, current); proxyCredentials.create(); return proxyCredentials.settings; } public get rootPath() { return ClientConstants.root; } public get resourcesFolder() { return ClientConstants.resourcesFolder; } public get version() { return app.getVersion(); } private _setupProcessEvents() { ipcMain.on("reload", () => { // Destroy window and error window if applicable this.windows.closeAll(); this.recoverWindow.destroy(); this.authenticationWindow.destroy(); // Show splash screen this.start(); }); app.on("activate", () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (this.windows.size === 0) { this.start(); } }); ipcMain.once("exit", () => { process.exit(1); }); // eslint-disable-next-line @typescript-eslint/ban-types process.on("uncaughtException" as any, (error: Error) => { log.error("There was a uncaught exception", error); this.recoverWindow.createWithError(error.message); this.telemetryService.trackError(error); this.telemetryService.flush(true); }); // eslint-disable-next-line @typescript-eslint/ban-types process.on("unhandledRejection", (r: Error) => { log.error("Unhandled promise error:", r); this.telemetryService.trackError(r); this.telemetryService.flush(true); }); app.on("window-all-closed", () => { // Required or electron will close when closing last open window before next one open }); app.on("login", async (event, webContents, request, authInfo, callback) => { event.preventDefault(); log.info("Electron chromium process need browser credentials."); try { const { username, password } = await this.proxySettings.credentials(); callback(username, password); } catch (e) { log.error("Unable to retrieve credentials for proxy settings", e); this.quit(); } }); } private _registerProtocol() { if (ClientConstants.isDev) { return; } if (app.setAsDefaultProtocolClient(Constants.customProtocolName)) { log.info(`Registered ${Constants.customProtocolName}:// as a protocol for Batch Explorer`); } else { log.error(`Failed to register ${Constants.customProtocolName}:// as a protocol for Batch Explorer`); } if (app.setAsDefaultProtocolClient(Constants.legacyProtocolName)) { log.info(`Registered ${Constants.legacyProtocolName}:// as a protocol for Batch Explorer`); } else { log.error(`Failed to register ${Constants.legacyProtocolName}:// as a protocol for Batch Explorer`); } } private _registerFileProtocol() { protocol.registerFileProtocol("file", (request, callback) => { const pathName = decodeURI(request.url.replace("file:///", "")); callback(pathName); }); } private _setCommonHeaders(window: MainWindow) { const requestFilter = { urls: ["*://*/*"] }; const userAgent = `${window.webContents.getUserAgent()} ${userAgentSuffix}`; session!.defaultSession!.webRequest.onBeforeSendHeaders(requestFilter, (details, callback) => { if (details.url.includes("batch.azure.com")) { details.requestHeaders["Origin"] = "http://localhost"; details.requestHeaders["Cache-Control"] = "no-cache"; } // Rate card api does some weird redirect which require removing the authorization header if (details.url.includes("ratecard.blob.core.windows.net")) { delete details.requestHeaders["Authorization"]; } details.requestHeaders["User-Agent"] = userAgent; callback({ cancel: false, requestHeaders: details.requestHeaders }); }); } }
the_stack
import { Layout } from "./layout"; import { Material, MaterialLibrary } from "./material"; export interface MeshOptions { enableWTextureCoord?: boolean; calcTangentsAndBitangents?: boolean; materials?: { [key: string]: Material }; } interface UnpackedAttrs { verts: number[]; norms: number[]; textures: number[]; hashindices: { [k: string]: number }; indices: number[][]; materialIndices: number[]; index: number; } export interface MaterialNameToIndex { [k: string]: number; } export interface IndexToMaterial { [k: number]: Material; } export interface ArrayBufferWithItemSize extends ArrayBuffer { numItems?: number; } export interface Uint16ArrayWithItemSize extends Uint16Array { numItems?: number; } /** * The main Mesh class. The constructor will parse through the OBJ file data * and collect the vertex, vertex normal, texture, and face information. This * information can then be used later on when creating your VBOs. See * OBJ.initMeshBuffers for an example of how to use the newly created Mesh */ export default class Mesh { public vertices: number[]; public vertexNormals: number[]; public textures: number[]; public indices: number[]; public name: string = ""; public vertexMaterialIndices: number[]; public indicesPerMaterial: number[][] = []; public materialNames: string[]; public materialIndices: MaterialNameToIndex; public materialsByIndex: IndexToMaterial = {}; public tangents: number[] = []; public bitangents: number[] = []; public textureStride: number; /** * Create a Mesh * @param {String} objectData - a string representation of an OBJ file with * newlines preserved. * @param {Object} options - a JS object containing valid options. See class * documentation for options. * @param {bool} options.enableWTextureCoord - Texture coordinates can have * an optional "w" coordinate after the u and v coordinates. This extra * value can be used in order to perform fancy transformations on the * textures themselves. Default is to truncate to only the u an v * coordinates. Passing true will provide a default value of 0 in the * event that any or all texture coordinates don't provide a w value. * Always use the textureStride attribute in order to determine the * stride length of the texture coordinates when rendering the element * array. * @param {bool} options.calcTangentsAndBitangents - Calculate the tangents * and bitangents when loading of the OBJ is completed. This adds two new * attributes to the Mesh instance: `tangents` and `bitangents`. */ constructor(objectData: string, options?: MeshOptions) { options = options || {}; options.materials = options.materials || {}; options.enableWTextureCoord = !!options.enableWTextureCoord; // the list of unique vertex, normal, texture, attributes this.vertexNormals = []; this.textures = []; // the indicies to draw the faces this.indices = []; this.textureStride = options.enableWTextureCoord ? 3 : 2; /* The OBJ file format does a sort of compression when saving a model in a program like Blender. There are at least 3 sections (4 including textures) within the file. Each line in a section begins with the same string: * 'v': indicates vertex section * 'vn': indicates vertex normal section * 'f': indicates the faces section * 'vt': indicates vertex texture section (if textures were used on the model) Each of the above sections (except for the faces section) is a list/set of unique vertices. Each line of the faces section contains a list of (vertex, [texture], normal) groups. **Note:** The following documentation will use a capital "V" Vertex to denote the above (vertex, [texture], normal) groups whereas a lowercase "v" vertex is used to denote an X, Y, Z coordinate. Some examples: // the texture index is optional, both formats are possible for models // without a texture applied f 1/25 18/46 12/31 f 1//25 18//46 12//31 // A 3 vertex face with texture indices f 16/92/11 14/101/22 1/69/1 // A 4 vertex face f 16/92/11 40/109/40 38/114/38 14/101/22 The first two lines are examples of a 3 vertex face without a texture applied. The second is an example of a 3 vertex face with a texture applied. The third is an example of a 4 vertex face. Note: a face can contain N number of vertices. Each number that appears in one of the groups is a 1-based index corresponding to an item from the other sections (meaning that indexing starts at one and *not* zero). For example: `f 16/92/11` is saying to - take the 16th element from the [v] vertex array - take the 92nd element from the [vt] texture array - take the 11th element from the [vn] normal array and together they make a unique vertex. Using all 3+ unique Vertices from the face line will produce a polygon. Now, you could just go through the OBJ file and create a new vertex for each face line and WebGL will draw what appears to be the same model. However, vertices will be overlapped and duplicated all over the place. Consider a cube in 3D space centered about the origin and each side is 2 units long. The front face (with the positive Z-axis pointing towards you) would have a Top Right vertex (looking orthogonal to its normal) mapped at (1,1,1) The right face would have a Top Left vertex (looking orthogonal to its normal) at (1,1,1) and the top face would have a Bottom Right vertex (looking orthogonal to its normal) at (1,1,1). Each face has a vertex at the same coordinates, however, three distinct vertices will be drawn at the same spot. To solve the issue of duplicate Vertices (the `(vertex, [texture], normal)` groups), while iterating through the face lines, when a group is encountered the whole group string ('16/92/11') is checked to see if it exists in the packed.hashindices object, and if it doesn't, the indices it specifies are used to look up each attribute in the corresponding attribute arrays already created. The values are then copied to the corresponding unpacked array (flattened to play nice with WebGL's ELEMENT_ARRAY_BUFFER indexing), the group string is added to the hashindices set and the current unpacked index is used as this hashindices value so that the group of elements can be reused. The unpacked index is incremented. If the group string already exists in the hashindices object, its corresponding value is the index of that group and is appended to the unpacked indices array. */ const verts = []; const vertNormals = []; const textures = []; const materialNamesByIndex = []; const materialIndicesByName: MaterialNameToIndex = {}; // keep track of what material we've seen last let currentMaterialIndex = -1; let currentObjectByMaterialIndex = 0; // unpacking stuff const unpacked: UnpackedAttrs = { verts: [], norms: [], textures: [], hashindices: {}, indices: [[]], materialIndices: [], index: 0, }; const VERTEX_RE = /^v\s/; const NORMAL_RE = /^vn\s/; const TEXTURE_RE = /^vt\s/; const FACE_RE = /^f\s/; const WHITESPACE_RE = /\s+/; const USE_MATERIAL_RE = /^usemtl/; // array of lines separated by the newline const lines = objectData.split("\n"); for (let line of lines) { line = line.trim(); if (!line || line.startsWith("#")) { continue; } const elements = line.split(WHITESPACE_RE); elements.shift(); if (VERTEX_RE.test(line)) { // if this is a vertex verts.push(...elements); } else if (NORMAL_RE.test(line)) { // if this is a vertex normal vertNormals.push(...elements); } else if (TEXTURE_RE.test(line)) { let coords = elements; // by default, the loader will only look at the U and V // coordinates of the vt declaration. So, this truncates the // elements to only those 2 values. If W texture coordinate // support is enabled, then the texture coordinate is // expected to have three values in it. if (elements.length > 2 && !options.enableWTextureCoord) { coords = elements.slice(0, 2); } else if (elements.length === 2 && options.enableWTextureCoord) { // If for some reason W texture coordinate support is enabled // and only the U and V coordinates are given, then we supply // the default value of 0 so that the stride length is correct // when the textures are unpacked below. coords.push("0"); } textures.push(...coords); } else if (USE_MATERIAL_RE.test(line)) { const materialName = elements[0]; // check to see if we've ever seen it before if (!(materialName in materialIndicesByName)) { // new material we've never seen materialNamesByIndex.push(materialName); materialIndicesByName[materialName] = materialNamesByIndex.length - 1; // push new array into indices // already contains an array at index zero, don't add if (materialIndicesByName[materialName] > 0) { unpacked.indices.push([]); } } // keep track of the current material index currentMaterialIndex = materialIndicesByName[materialName]; // update current index array currentObjectByMaterialIndex = currentMaterialIndex; } else if (FACE_RE.test(line)) { // if this is a face /* split this face into an array of Vertex groups for example: f 16/92/11 14/101/22 1/69/1 becomes: ['16/92/11', '14/101/22', '1/69/1']; */ const triangles = triangulate(elements); for (const triangle of triangles) { for (let j = 0, eleLen = triangle.length; j < eleLen; j++) { const hash = triangle[j] + "," + currentMaterialIndex; if (hash in unpacked.hashindices) { unpacked.indices[currentObjectByMaterialIndex].push(unpacked.hashindices[hash]); } else { /* Each element of the face line array is a Vertex which has its attributes delimited by a forward slash. This will separate each attribute into another array: '19/92/11' becomes: Vertex = ['19', '92', '11']; where Vertex[0] is the vertex index Vertex[1] is the texture index Vertex[2] is the normal index Think of faces having Vertices which are comprised of the attributes location (v), texture (vt), and normal (vn). */ const vertex = triangle[j].split("/"); // it's possible for faces to only specify the vertex // and the normal. In this case, vertex will only have // a length of 2 and not 3 and the normal will be the // second item in the list with an index of 1. const normalIndex = vertex.length - 1; /* The verts, textures, and vertNormals arrays each contain a flattend array of coordinates. Because it gets confusing by referring to Vertex and then vertex (both are different in my descriptions) I will explain what's going on using the vertexNormals array: vertex[2] will contain the one-based index of the vertexNormals section (vn). One is subtracted from this index number to play nice with javascript's zero-based array indexing. Because vertexNormal is a flattened array of x, y, z values, simple pointer arithmetic is used to skip to the start of the vertexNormal, then the offset is added to get the correct component: +0 is x, +1 is y, +2 is z. This same process is repeated for verts and textures. */ // Vertex position unpacked.verts.push(+verts[(+vertex[0] - 1) * 3 + 0]); unpacked.verts.push(+verts[(+vertex[0] - 1) * 3 + 1]); unpacked.verts.push(+verts[(+vertex[0] - 1) * 3 + 2]); // Vertex textures if (textures.length) { const stride = options.enableWTextureCoord ? 3 : 2; unpacked.textures.push(+textures[(+vertex[1] - 1) * stride + 0]); unpacked.textures.push(+textures[(+vertex[1] - 1) * stride + 1]); if (options.enableWTextureCoord) { unpacked.textures.push(+textures[(+vertex[1] - 1) * stride + 2]); } } // Vertex normals unpacked.norms.push(+vertNormals[(+vertex[normalIndex] - 1) * 3 + 0]); unpacked.norms.push(+vertNormals[(+vertex[normalIndex] - 1) * 3 + 1]); unpacked.norms.push(+vertNormals[(+vertex[normalIndex] - 1) * 3 + 2]); // Vertex material indices unpacked.materialIndices.push(currentMaterialIndex); // add the newly created Vertex to the list of indices unpacked.hashindices[hash] = unpacked.index; unpacked.indices[currentObjectByMaterialIndex].push(unpacked.hashindices[hash]); // increment the counter unpacked.index += 1; } } } } } this.vertices = unpacked.verts; this.vertexNormals = unpacked.norms; this.textures = unpacked.textures; this.vertexMaterialIndices = unpacked.materialIndices; this.indices = unpacked.indices[currentObjectByMaterialIndex]; this.indicesPerMaterial = unpacked.indices; this.materialNames = materialNamesByIndex; this.materialIndices = materialIndicesByName; this.materialsByIndex = {}; if (options.calcTangentsAndBitangents) { this.calculateTangentsAndBitangents(); } } /** * Calculates the tangents and bitangents of the mesh that forms an orthogonal basis together with the * normal in the direction of the texture coordinates. These are useful for setting up the TBN matrix * when distorting the normals through normal maps. * Method derived from: http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-13-normal-mapping/ * * This method requires the normals and texture coordinates to be parsed and set up correctly. * Adds the tangents and bitangents as members of the class instance. */ calculateTangentsAndBitangents() { console.assert( !!( this.vertices && this.vertices.length && this.vertexNormals && this.vertexNormals.length && this.textures && this.textures.length ), "Missing attributes for calculating tangents and bitangents", ); const unpacked = { tangents: [...new Array(this.vertices.length)].map(_ => 0), bitangents: [...new Array(this.vertices.length)].map(_ => 0), }; // Loop through all faces in the whole mesh const indices = this.indices; const vertices = this.vertices; const normals = this.vertexNormals; const uvs = this.textures; for (let i = 0; i < indices.length; i += 3) { const i0 = indices[i + 0]; const i1 = indices[i + 1]; const i2 = indices[i + 2]; const x_v0 = vertices[i0 * 3 + 0]; const y_v0 = vertices[i0 * 3 + 1]; const z_v0 = vertices[i0 * 3 + 2]; const x_uv0 = uvs[i0 * 2 + 0]; const y_uv0 = uvs[i0 * 2 + 1]; const x_v1 = vertices[i1 * 3 + 0]; const y_v1 = vertices[i1 * 3 + 1]; const z_v1 = vertices[i1 * 3 + 2]; const x_uv1 = uvs[i1 * 2 + 0]; const y_uv1 = uvs[i1 * 2 + 1]; const x_v2 = vertices[i2 * 3 + 0]; const y_v2 = vertices[i2 * 3 + 1]; const z_v2 = vertices[i2 * 3 + 2]; const x_uv2 = uvs[i2 * 2 + 0]; const y_uv2 = uvs[i2 * 2 + 1]; const x_deltaPos1 = x_v1 - x_v0; const y_deltaPos1 = y_v1 - y_v0; const z_deltaPos1 = z_v1 - z_v0; const x_deltaPos2 = x_v2 - x_v0; const y_deltaPos2 = y_v2 - y_v0; const z_deltaPos2 = z_v2 - z_v0; const x_uvDeltaPos1 = x_uv1 - x_uv0; const y_uvDeltaPos1 = y_uv1 - y_uv0; const x_uvDeltaPos2 = x_uv2 - x_uv0; const y_uvDeltaPos2 = y_uv2 - y_uv0; const rInv = x_uvDeltaPos1 * y_uvDeltaPos2 - y_uvDeltaPos1 * x_uvDeltaPos2; const r = 1.0 / Math.abs(rInv < 0.0001 ? 1.0 : rInv); // Tangent const x_tangent = (x_deltaPos1 * y_uvDeltaPos2 - x_deltaPos2 * y_uvDeltaPos1) * r; const y_tangent = (y_deltaPos1 * y_uvDeltaPos2 - y_deltaPos2 * y_uvDeltaPos1) * r; const z_tangent = (z_deltaPos1 * y_uvDeltaPos2 - z_deltaPos2 * y_uvDeltaPos1) * r; // Bitangent const x_bitangent = (x_deltaPos2 * x_uvDeltaPos1 - x_deltaPos1 * x_uvDeltaPos2) * r; const y_bitangent = (y_deltaPos2 * x_uvDeltaPos1 - y_deltaPos1 * x_uvDeltaPos2) * r; const z_bitangent = (z_deltaPos2 * x_uvDeltaPos1 - z_deltaPos1 * x_uvDeltaPos2) * r; // Gram-Schmidt orthogonalize //t = glm::normalize(t - n * glm:: dot(n, t)); const x_n0 = normals[i0 * 3 + 0]; const y_n0 = normals[i0 * 3 + 1]; const z_n0 = normals[i0 * 3 + 2]; const x_n1 = normals[i1 * 3 + 0]; const y_n1 = normals[i1 * 3 + 1]; const z_n1 = normals[i1 * 3 + 2]; const x_n2 = normals[i2 * 3 + 0]; const y_n2 = normals[i2 * 3 + 1]; const z_n2 = normals[i2 * 3 + 2]; // Tangent const n0_dot_t = x_tangent * x_n0 + y_tangent * y_n0 + z_tangent * z_n0; const n1_dot_t = x_tangent * x_n1 + y_tangent * y_n1 + z_tangent * z_n1; const n2_dot_t = x_tangent * x_n2 + y_tangent * y_n2 + z_tangent * z_n2; const x_resTangent0 = x_tangent - x_n0 * n0_dot_t; const y_resTangent0 = y_tangent - y_n0 * n0_dot_t; const z_resTangent0 = z_tangent - z_n0 * n0_dot_t; const x_resTangent1 = x_tangent - x_n1 * n1_dot_t; const y_resTangent1 = y_tangent - y_n1 * n1_dot_t; const z_resTangent1 = z_tangent - z_n1 * n1_dot_t; const x_resTangent2 = x_tangent - x_n2 * n2_dot_t; const y_resTangent2 = y_tangent - y_n2 * n2_dot_t; const z_resTangent2 = z_tangent - z_n2 * n2_dot_t; const magTangent0 = Math.sqrt( x_resTangent0 * x_resTangent0 + y_resTangent0 * y_resTangent0 + z_resTangent0 * z_resTangent0, ); const magTangent1 = Math.sqrt( x_resTangent1 * x_resTangent1 + y_resTangent1 * y_resTangent1 + z_resTangent1 * z_resTangent1, ); const magTangent2 = Math.sqrt( x_resTangent2 * x_resTangent2 + y_resTangent2 * y_resTangent2 + z_resTangent2 * z_resTangent2, ); // Bitangent const n0_dot_bt = x_bitangent * x_n0 + y_bitangent * y_n0 + z_bitangent * z_n0; const n1_dot_bt = x_bitangent * x_n1 + y_bitangent * y_n1 + z_bitangent * z_n1; const n2_dot_bt = x_bitangent * x_n2 + y_bitangent * y_n2 + z_bitangent * z_n2; const x_resBitangent0 = x_bitangent - x_n0 * n0_dot_bt; const y_resBitangent0 = y_bitangent - y_n0 * n0_dot_bt; const z_resBitangent0 = z_bitangent - z_n0 * n0_dot_bt; const x_resBitangent1 = x_bitangent - x_n1 * n1_dot_bt; const y_resBitangent1 = y_bitangent - y_n1 * n1_dot_bt; const z_resBitangent1 = z_bitangent - z_n1 * n1_dot_bt; const x_resBitangent2 = x_bitangent - x_n2 * n2_dot_bt; const y_resBitangent2 = y_bitangent - y_n2 * n2_dot_bt; const z_resBitangent2 = z_bitangent - z_n2 * n2_dot_bt; const magBitangent0 = Math.sqrt( x_resBitangent0 * x_resBitangent0 + y_resBitangent0 * y_resBitangent0 + z_resBitangent0 * z_resBitangent0, ); const magBitangent1 = Math.sqrt( x_resBitangent1 * x_resBitangent1 + y_resBitangent1 * y_resBitangent1 + z_resBitangent1 * z_resBitangent1, ); const magBitangent2 = Math.sqrt( x_resBitangent2 * x_resBitangent2 + y_resBitangent2 * y_resBitangent2 + z_resBitangent2 * z_resBitangent2, ); unpacked.tangents[i0 * 3 + 0] += x_resTangent0 / magTangent0; unpacked.tangents[i0 * 3 + 1] += y_resTangent0 / magTangent0; unpacked.tangents[i0 * 3 + 2] += z_resTangent0 / magTangent0; unpacked.tangents[i1 * 3 + 0] += x_resTangent1 / magTangent1; unpacked.tangents[i1 * 3 + 1] += y_resTangent1 / magTangent1; unpacked.tangents[i1 * 3 + 2] += z_resTangent1 / magTangent1; unpacked.tangents[i2 * 3 + 0] += x_resTangent2 / magTangent2; unpacked.tangents[i2 * 3 + 1] += y_resTangent2 / magTangent2; unpacked.tangents[i2 * 3 + 2] += z_resTangent2 / magTangent2; unpacked.bitangents[i0 * 3 + 0] += x_resBitangent0 / magBitangent0; unpacked.bitangents[i0 * 3 + 1] += y_resBitangent0 / magBitangent0; unpacked.bitangents[i0 * 3 + 2] += z_resBitangent0 / magBitangent0; unpacked.bitangents[i1 * 3 + 0] += x_resBitangent1 / magBitangent1; unpacked.bitangents[i1 * 3 + 1] += y_resBitangent1 / magBitangent1; unpacked.bitangents[i1 * 3 + 2] += z_resBitangent1 / magBitangent1; unpacked.bitangents[i2 * 3 + 0] += x_resBitangent2 / magBitangent2; unpacked.bitangents[i2 * 3 + 1] += y_resBitangent2 / magBitangent2; unpacked.bitangents[i2 * 3 + 2] += z_resBitangent2 / magBitangent2; // TODO: check handedness } this.tangents = unpacked.tangents; this.bitangents = unpacked.bitangents; } /** * @param layout - A {@link Layout} object that describes the * desired memory layout of the generated buffer * @return The packed array in the ... TODO */ makeBufferData(layout: Layout): ArrayBufferWithItemSize { const numItems = this.vertices.length / 3; const buffer: ArrayBufferWithItemSize = new ArrayBuffer(layout.stride * numItems); buffer.numItems = numItems; const dataView = new DataView(buffer); for (let i = 0, vertexOffset = 0; i < numItems; i++) { vertexOffset = i * layout.stride; // copy in the vertex data in the order and format given by the // layout param for (const attribute of layout.attributes) { const offset = vertexOffset + layout.attributeMap[attribute.key].offset; switch (attribute.key) { case Layout.POSITION.key: dataView.setFloat32(offset, this.vertices[i * 3], true); dataView.setFloat32(offset + 4, this.vertices[i * 3 + 1], true); dataView.setFloat32(offset + 8, this.vertices[i * 3 + 2], true); break; case Layout.UV.key: dataView.setFloat32(offset, this.textures[i * 2], true); dataView.setFloat32(offset + 4, this.textures[i * 2 + 1], true); break; case Layout.NORMAL.key: dataView.setFloat32(offset, this.vertexNormals[i * 3], true); dataView.setFloat32(offset + 4, this.vertexNormals[i * 3 + 1], true); dataView.setFloat32(offset + 8, this.vertexNormals[i * 3 + 2], true); break; case Layout.MATERIAL_INDEX.key: dataView.setInt16(offset, this.vertexMaterialIndices[i], true); break; case Layout.AMBIENT.key: { const materialIndex = this.vertexMaterialIndices[i]; const material = this.materialsByIndex[materialIndex]; if (!material) { console.warn( 'Material "' + this.materialNames[materialIndex] + '" not found in mesh. Did you forget to call addMaterialLibrary(...)?"', ); break; } dataView.setFloat32(offset, material.ambient[0], true); dataView.setFloat32(offset + 4, material.ambient[1], true); dataView.setFloat32(offset + 8, material.ambient[2], true); break; } case Layout.DIFFUSE.key: { const materialIndex = this.vertexMaterialIndices[i]; const material = this.materialsByIndex[materialIndex]; if (!material) { console.warn( 'Material "' + this.materialNames[materialIndex] + '" not found in mesh. Did you forget to call addMaterialLibrary(...)?"', ); break; } dataView.setFloat32(offset, material.diffuse[0], true); dataView.setFloat32(offset + 4, material.diffuse[1], true); dataView.setFloat32(offset + 8, material.diffuse[2], true); break; } case Layout.SPECULAR.key: { const materialIndex = this.vertexMaterialIndices[i]; const material = this.materialsByIndex[materialIndex]; if (!material) { console.warn( 'Material "' + this.materialNames[materialIndex] + '" not found in mesh. Did you forget to call addMaterialLibrary(...)?"', ); break; } dataView.setFloat32(offset, material.specular[0], true); dataView.setFloat32(offset + 4, material.specular[1], true); dataView.setFloat32(offset + 8, material.specular[2], true); break; } case Layout.SPECULAR_EXPONENT.key: { const materialIndex = this.vertexMaterialIndices[i]; const material = this.materialsByIndex[materialIndex]; if (!material) { console.warn( 'Material "' + this.materialNames[materialIndex] + '" not found in mesh. Did you forget to call addMaterialLibrary(...)?"', ); break; } dataView.setFloat32(offset, material.specularExponent, true); break; } case Layout.EMISSIVE.key: { const materialIndex = this.vertexMaterialIndices[i]; const material = this.materialsByIndex[materialIndex]; if (!material) { console.warn( 'Material "' + this.materialNames[materialIndex] + '" not found in mesh. Did you forget to call addMaterialLibrary(...)?"', ); break; } dataView.setFloat32(offset, material.emissive[0], true); dataView.setFloat32(offset + 4, material.emissive[1], true); dataView.setFloat32(offset + 8, material.emissive[2], true); break; } case Layout.TRANSMISSION_FILTER.key: { const materialIndex = this.vertexMaterialIndices[i]; const material = this.materialsByIndex[materialIndex]; if (!material) { console.warn( 'Material "' + this.materialNames[materialIndex] + '" not found in mesh. Did you forget to call addMaterialLibrary(...)?"', ); break; } dataView.setFloat32(offset, material.transmissionFilter[0], true); dataView.setFloat32(offset + 4, material.transmissionFilter[1], true); dataView.setFloat32(offset + 8, material.transmissionFilter[2], true); break; } case Layout.DISSOLVE.key: { const materialIndex = this.vertexMaterialIndices[i]; const material = this.materialsByIndex[materialIndex]; if (!material) { console.warn( 'Material "' + this.materialNames[materialIndex] + '" not found in mesh. Did you forget to call addMaterialLibrary(...)?"', ); break; } dataView.setFloat32(offset, material.dissolve, true); break; } case Layout.ILLUMINATION.key: { const materialIndex = this.vertexMaterialIndices[i]; const material = this.materialsByIndex[materialIndex]; if (!material) { console.warn( 'Material "' + this.materialNames[materialIndex] + '" not found in mesh. Did you forget to call addMaterialLibrary(...)?"', ); break; } dataView.setInt16(offset, material.illumination, true); break; } case Layout.REFRACTION_INDEX.key: { const materialIndex = this.vertexMaterialIndices[i]; const material = this.materialsByIndex[materialIndex]; if (!material) { console.warn( 'Material "' + this.materialNames[materialIndex] + '" not found in mesh. Did you forget to call addMaterialLibrary(...)?"', ); break; } dataView.setFloat32(offset, material.refractionIndex, true); break; } case Layout.SHARPNESS.key: { const materialIndex = this.vertexMaterialIndices[i]; const material = this.materialsByIndex[materialIndex]; if (!material) { console.warn( 'Material "' + this.materialNames[materialIndex] + '" not found in mesh. Did you forget to call addMaterialLibrary(...)?"', ); break; } dataView.setFloat32(offset, material.sharpness, true); break; } case Layout.ANTI_ALIASING.key: { const materialIndex = this.vertexMaterialIndices[i]; const material = this.materialsByIndex[materialIndex]; if (!material) { console.warn( 'Material "' + this.materialNames[materialIndex] + '" not found in mesh. Did you forget to call addMaterialLibrary(...)?"', ); break; } dataView.setInt16(offset, material.antiAliasing ? 1 : 0, true); break; } } } } return buffer; } makeIndexBufferData(): Uint16ArrayWithItemSize { const buffer: Uint16ArrayWithItemSize = new Uint16Array(this.indices); buffer.numItems = this.indices.length; return buffer; } makeIndexBufferDataForMaterials(...materialIndices: Array<number>): Uint16ArrayWithItemSize { const indices: number[] = new Array<number>().concat( ...materialIndices.map(mtlIdx => this.indicesPerMaterial[mtlIdx]), ); const buffer: Uint16ArrayWithItemSize = new Uint16Array(indices); buffer.numItems = indices.length; return buffer; } addMaterialLibrary(mtl: MaterialLibrary) { for (const name in mtl.materials) { if (!(name in this.materialIndices)) { // This material is not referenced by the mesh continue; } const material = mtl.materials[name]; // Find the material index for this material const materialIndex = this.materialIndices[material.name]; // Put the material into the materialsByIndex object at the right // spot as determined when the obj file was parsed this.materialsByIndex[materialIndex] = material; } } } function* triangulate(elements: string[]) { if (elements.length <= 3) { yield elements; } else if (elements.length === 4) { yield [elements[0], elements[1], elements[2]]; yield [elements[2], elements[3], elements[0]]; } else { for (let i = 1; i < elements.length - 1; i++) { yield [elements[0], elements[i], elements[i + 1]]; } } }
the_stack
import path from 'path' const log = require('debug')('bp:worker') import webpack, { Entry } from 'webpack' import MemoryFS from 'memory-fs' import isValidNPMName from 'is-valid-npm-name' import { gzipSync } from 'zlib' import fs from 'fs' import getDependencySizes from '../getDependencySizeTree' import getParseTime from '../getParseTime' import makeWebpackConfig from '../config/makeWebpackConfig' import { performance } from 'perf_hooks' import { BuildError, CLIBuildError, EntryPointError, MissingDependencyError, UnexpectedBuildError, } from '../errors/CustomError' import { Externals, WebpackError, BuildPackageOptions, CreateEntryPointOptions, } from '../common.types' import Telemetry from './telemetry.utils' type CompilePackageArgs = { name: string externals: Externals entry: Entry debug?: boolean minifier: 'terser' | 'esbuild' } type CompilePackageReturn = { stats: webpack.Stats error: WebpackError memoryFileSystem: MemoryFS } type BuildPackageArgs = { name: string installPath: string externals: Externals options: BuildPackageOptions } type WebpackStatsAsset = NonNullable<webpack.Stats.ToJsonOutput['assets']>[0] const BuildUtils = { createEntryPoint( packageName: string, installPath: string, options: CreateEntryPointOptions ) { const entryPath = path.join( installPath, options.entryFilename || 'index.js' ) let importStatement: string if (options.esm) { if (options.customImports) { importStatement = ` import { ${options.customImports.join(', ')} } from '${packageName}'; console.log(${options.customImports.join(', ')}) ` } else { importStatement = `import p from '${packageName}'; console.log(p)` } } else { if (options.customImports) { importStatement = ` const { ${options.customImports.join( ', ' )} } = require('${packageName}'); console.log(${options.customImports.join(', ')}) ` } else { importStatement = `const p = require('${packageName}'); console.log(p)` } } try { fs.writeFileSync(entryPath, importStatement, 'utf-8') return entryPath } catch (err) { throw new EntryPointError(err) } }, compilePackage({ name, entry, externals, debug, minifier, }: CompilePackageArgs) { const startTime = performance.now() const compiler = webpack( makeWebpackConfig({ packageName: name, entry, externals, debug, minifier, }) ) const memoryFileSystem = new MemoryFS() compiler.outputFileSystem = memoryFileSystem return new Promise<CompilePackageReturn>(resolve => { compiler.run((err, stats) => { const error = (err as unknown) as WebpackError // Webpack types incorrect // stats object can be empty if there are build errors resolve({ stats, error, memoryFileSystem }) if (error) { console.error(error) Telemetry.compilePackage(name, false, startTime, { minifier }, error) } else { Telemetry.compilePackage(name, true, startTime, { minifier }) } }) }) }, _parseMissingModules(errors: Array<WebpackError>) { const missingModuleErrors = errors.filter( error => error.name === 'ModuleNotFoundError' ) if (!missingModuleErrors.length) { return [] } // There's a better way to get the missing module's name, maybe ? const missingModuleRegex = /Can't resolve '(.+)' in/ const missingModules = missingModuleErrors.map(err => { const matches = err.error.toString().match(missingModuleRegex) if (!matches) { throw new UnexpectedBuildError( 'Expected to find a file path in the module not found error, but found none. Regex for this might be out of date.' ) } const missingFilePath = matches[1] let packageNameMatch if (missingFilePath.startsWith('@')) { packageNameMatch = missingFilePath.match(/@[^\/]+\/[^\/]+/) // @babel/runtime/object/create -> @babel/runtime } else { packageNameMatch = missingFilePath.match(/[^\/]+/) // babel-runtime/object/create -> babel-runtime } if (!packageNameMatch) { throw new UnexpectedBuildError( 'Failed to resolve the missing package name. Regex for this might be out of date.' ) } return packageNameMatch[0] }) let uniqueMissingModules = Array.from(new Set(missingModules)) uniqueMissingModules = uniqueMissingModules.filter( mod => !mod.startsWith(`${uniqueMissingModules[0]}/`) ) return uniqueMissingModules }, async buildPackage({ name, installPath, externals, options, }: BuildPackageArgs) { let entry: Entry = {} if (options.splitCustomImports) { if (!options.customImports || !options.customImports.length) { return { assets: [] } } options.customImports.forEach(importt => { entry[importt] = BuildUtils.createEntryPoint(name, installPath, { customImports: [importt], entryFilename: importt, esm: true, }) }) } else { entry['main'] = BuildUtils.createEntryPoint(name, installPath, { esm: false, customImports: options.customImports, }) } log('build start %s', name) const { stats, error, memoryFileSystem } = await BuildUtils.compilePackage({ name, entry, externals, debug: options.debug, minifier: options.minifier, }) log('build end %s', name) const jsonStatsStartTime = performance.now() let jsonStats = stats.toJson({ assets: true, children: false, chunks: false, chunkGroups: false, chunkModules: false, chunkOrigins: false, modules: true, errorDetails: false, entrypoints: false, reasons: false, maxModules: 500, performance: false, source: true, depth: true, providedExports: true, warnings: false, modulesSort: 'depth', }) if (!jsonStats) { Telemetry.parseWebpackStats(name, false, jsonStatsStartTime) throw new UnexpectedBuildError( 'Expected webpack json stats to be non-null, but was null' ) } else { Telemetry.parseWebpackStats(name, true, jsonStatsStartTime) } if (error && !stats) { throw new BuildError(error) } else if (stats.compilation.errors && stats.compilation.errors.length) { const missingModules = BuildUtils._parseMissingModules( stats.compilation.errors ) if (missingModules.length) { if (missingModules.length === 1 && missingModules[0] === name) { throw new EntryPointError( stats.compilation.errors.map(err => err.toString()) ) } else { throw new MissingDependencyError( stats.compilation.errors.map(err => err.toString()), { missingModules } ) } } else if (jsonStats.errors && jsonStats.errors.length > 0) { if ( jsonStats.errors.some(error => error.includes("Unexpected character '#'") ) ) { throw new CLIBuildError(jsonStats.errors) } else { throw new BuildError(jsonStats.errors) } } else { throw new UnexpectedBuildError( 'The webpack stats object was unexpectedly empty' ) } } else { const getAssetStats = (asset: WebpackStatsAsset) => { const bundle = path.join(process.cwd(), 'dist', asset.name) const bundleContents = memoryFileSystem.readFileSync(bundle) let parseTimes = null if (options.calcParse) { parseTimes = getParseTime(bundleContents) } const gzip = gzipSync(bundleContents, {}).length const matches = asset.name.match(/(.+?)\.bundle\.(.+)$/) if (!matches) { throw new UnexpectedBuildError( 'Found an asset without the `.bundle` suffix. ' + 'A loader customization might be needed to recognize this asset type' + asset.name ) } const [, entryName, extension] = matches return { name: entryName, type: extension, size: asset.size, gzip, parse: parseTimes, } } const assetsGzipStartTime = performance.now() const assetStats = jsonStats?.assets ?.filter(asset => !asset.chunkNames.includes('runtime')) .filter(asset => !asset.name.endsWith('LICENSE.txt')) .map(getAssetStats) Telemetry.assetsGZIPParseTime(name, assetsGzipStartTime) log('build result %O', assetStats) return { assets: assetStats || [], ...(options.includeDependencySizes && { dependencySizes: await getDependencySizes( name, jsonStats, options.minifier ), }), } } }, async buildPackageIgnoringMissingDeps({ name, externals, installPath, options, }: BuildPackageArgs) { const buildStartTime = performance.now() let buildIteration = 1 try { const buildResult = await BuildUtils.buildPackage({ name, externals, installPath, options, }) Telemetry.buildPackage(name, true, buildStartTime, { ...options, buildIteration, }) return buildResult } catch (e) { buildIteration++ if ( e instanceof MissingDependencyError && e.missingModules.length <= 6 && e.missingModules.every(mod => isValidNPMName(mod)) ) { const { missingModules } = e.extra const newExternals = { ...externals, externalPackages: externals.externalPackages.concat(missingModules), } log( '%s has missing dependencies, rebuilding without %o', name, missingModules ) const rebuiltResult = await BuildUtils.buildPackage({ name, externals: newExternals, installPath, options, }) Telemetry.buildPackage(name, true, buildStartTime, { ...options, buildIteration, missingModules, }) return { ignoredMissingDependencies: missingModules, ...rebuiltResult, } } else { Telemetry.buildPackage( name, false, buildStartTime, { ...options, buildIteration, }, e ) throw e } } }, } export default BuildUtils
the_stack
import "jest"; import * as SlackMock from "slack-mock-typed"; import * as slacker from "../slack-alert"; const base = process.env.PWD || "."; const vcsRoot: string = "github"; const ciProvider: string = "circleci"; const reportDir: string = base + "/src/slack/test/jsonTestPass"; const videoDir: string = base + "/src/slack/test/videosDirPopulated"; const screenshotDir: string = base + "/src/slack/test/screenshotDirPopulated"; const mock: SlackMock.Instance = SlackMock.SlackMocker({ logLevel: "debug" }); const mockedHooks = mock.incomingWebhooks; function setup() { beforeAll(async () => { jest.setTimeout(60000); await mockedHooks.start(); await mockedHooks.reset(); }); beforeEach(async () => { jest.resetModules(); await mockedHooks.reset(); expect(mockedHooks.calls).toHaveLength(0); }); afterEach(async () => { await mockedHooks.reset(); }); } describe("tester", () => { setup(); it("can call a mock slack instance vcs root bitbucket", async () => { await slacker.slackRunner({ ciProvider, vcsRoot: "bitbucket", reportDir, videoDir, screenshotDir, }); const body = await returnSlackWebhookCall(); expect(body).toContain("bitbucket"); expect(body).not.toContain("undefined"); }); }); describe("tester", () => { setup(); it("skips build logs with an unknown ci provider", async () => { await slacker.slackRunner({ ciProvider: "csdscscsc", vcsRoot, reportDir, videoDir, screenshotDir, }); const body = await returnSlackWebhookCall(); const buildNum = process.env.CI_BUILD_NUM; expect(body).toContain(`"text":"Build Logs","url":"undefined"`); }); }); describe("tester", () => { setup(); it("can set custom report link when a custom url is provided", async () => { const artifactUrl = "http://example.com"; // /report-data.html await slacker.slackRunner({ ciProvider, vcsRoot, reportDir: base + "/src/slack/test/jsonTestFail", videoDir, screenshotDir, customUrl: artifactUrl, }); const body = await returnSlackWebhookCall(); expect(body).toContain(`"url":"${artifactUrl}`); }); }); describe("tester", () => { setup(); it("can call a mock slack instance vcs root github", async () => { await slacker.slackRunner({ ciProvider, vcsRoot, reportDir, videoDir, screenshotDir, }); const body = await returnSlackWebhookCall(); checkStatus(body, "passed"); expect(body).toContain("github"); expect(body).not.toContain("undefined"); }); }); describe("tester", () => { setup(); it("can call a mock slack instance vcs root github with a failing test report", async () => { await slacker.slackRunner({ ciProvider, vcsRoot, reportDir: base + "/src/slack/test/jsonTestFail", videoDir, screenshotDir, }); const body = await returnSlackWebhookCall(); checkStatus(body, "failed"); expect(body).toContain("github"); expect(body).not.toContain("undefined"); }); }); describe("test custom webhooks per test status", () => { setup(); const errorUrl = "https://hooks.slack.com/services/TEA926DBJ/BEBB8FPCL/error"; const failedUrl = "https://hooks.slack.com/services/TEA926DBJ/BEBB8FPCL/failed"; const passedUrl = "https://hooks.slack.com/services/TEA926DBJ/BEBB8FPCL/passed"; const errorUrlMultiple = "https://hooks.slack.com/services/TEA926DBJ/BEBB8FPCL/error1,https://hooks.slack.com/services/TEA926DBJ/BEBB8FPCL/error2"; const failedUrlMultiple = "https://hooks.slack.com/services/TEA926DBJ/BEBB8FPCL/failed1,https://hooks.slack.com/services/TEA926DBJ/BEBB8FPCL/failed2"; const passedUrlMultiple = "https://hooks.slack.com/services/TEA926DBJ/BEBB8FPCL/passed1,https://hooks.slack.com/services/TEA926DBJ/BEBB8FPCL/passed2"; it("calls a mock slack instance with specific webhook for failed test runs", async () => { process.env.SLACK_WEBHOOK_FAILED_URL = failedUrl; await slacker.slackRunner({ ciProvider, vcsRoot, reportDir: base + "/src/slack/test/jsonTestFail", videoDir, screenshotDir, }); const body = await returnSlackWebhookCall(failedUrl); checkStatus(body, "failed"); expect(body).toContain("github"); expect(body).not.toContain("undefined"); process.env.SLACK_WEBHOOK_FAILED_URL = ""; }); it("calls a mock slack instance with specific webhook for passed test runs", async () => { process.env.SLACK_WEBHOOK_PASSED_URL = passedUrl; await slacker.slackRunner({ ciProvider, vcsRoot, reportDir: base + "/src/slack/test/jsonTestPass", videoDir, screenshotDir, }); const body = await returnSlackWebhookCall(passedUrl); checkStatus(body, "passed"); expect(body).toContain("github"); expect(body).not.toContain("undefined"); expect(mockedHooks.calls).toHaveLength(1); process.env.SLACK_WEBHOOK_PASSED_URL = ""; }); it("calls a mock slack instance with specific webhook for erroring test runs", async () => { process.env.SLACK_WEBHOOK_ERROR_URL = errorUrl; await slacker.slackRunner({ ciProvider, vcsRoot, reportDir: base + "/src/slack/test/jsonBuildFail", videoDir, screenshotDir, }); const body = await returnSlackWebhookCall(errorUrl); checkStatus(body, "build"); expect(body).toContain("github"); expect(body).not.toContain("undefined"); expect(mockedHooks.calls).toHaveLength(1); process.env.SLACK_WEBHOOK_ERROR_URL = ""; }); it("calls a mock slack instance multiple times if more than one webhook is provided", async () => { process.env.SLACK_WEBHOOK_PASSED_URL = passedUrlMultiple; await slacker.slackRunner({ ciProvider, vcsRoot, reportDir: base + "/src/slack/test/jsonTestPass", videoDir, screenshotDir, }); const body = await returnSlackWebhookCall(passedUrlMultiple, 2); checkStatus(body, "passed"); expect(body).toContain("github"); expect(body).not.toContain("undefined"); expect(mockedHooks.calls).toHaveLength(2); process.env.SLACK_WEBHOOK_PASSED_URL = ""; }); }); describe("test onlyFailed flag", () => { setup(); it("calls a mock slack instance with failing test report and onlyFailed flag set", async () => { await slacker.slackRunner({ ciProvider, vcsRoot, reportDir: base + "/src/slack/test/jsonTestFail", videoDir, screenshotDir, onlyFailed: true, }); const body = await returnSlackWebhookCall(); checkStatus(body, "failed"); expect(body).toContain("github"); expect(body).not.toContain("undefined"); }); it("does not call a mock slack instance with passing test report and onlyFailed flag set", async () => { const result = await slacker.slackRunner({ ciProvider, vcsRoot, reportDir: base + "/src/slack/test/jsonTestPass", videoDir, screenshotDir, onlyFailed: true, }); expect(mockedHooks.calls).toHaveLength(0); expect(result).toContain( "onlyFailed flag set, test run status was passed, so not sending message" ); }); }); describe("tester", () => { setup(); it("can call a mock slack instance vcs root github with a failing build report", async () => { await slacker.slackRunner({ ciProvider, vcsRoot, reportDir: base + "/src/slack/test/jsonBuildFail", videoDir, screenshotDir, }); const body = await returnSlackWebhookCall(); checkStatus(body, "build"); expect(body).toContain("github"); expect(body).not.toContain("undefined"); }); }); describe("Slack Reporter throws error if we cant find the test report", () => { it("Slack Reporter logs a warning and send an error slack message if we cant find the test report", async () => { process.env.SLACK_WEBHOOK_ERROR_URL = "https://hooks.slack.com/services/TEA926DBJ/BEBB8FPCL/error"; await slacker.slackRunner({ ciProvider, vcsRoot, reportDir: "/test", videoDir, screenshotDir, }); const body = await returnSlackWebhookCall( process.env.SLACK_WEBHOOK_ERROR_URL ); checkStatus(body, "build"); expect(body).toContain("github"); expect(body).not.toContain("undefined"); expect(mockedHooks.calls).toHaveLength(1); process.env.SLACK_WEBHOOK_ERROR_URL = ""; }); }); describe("tester", () => { setup(); it("can provide a simple report with an unknown vcsroot provider", async () => { await slacker.slackRunner({ ciProvider, vcsRoot: "none", reportDir, videoDir, screenshotDir, }); const body = await returnSlackWebhookCall(); expect(body).not.toContain("commits"); expect(body).not.toContain("artefacts"); }); }); function returnSlackWebhookCall(webhookUrl?: string, noOfCalls?: number) { // This checks the slack mock call counter expect(mockedHooks.calls).toHaveLength(noOfCalls ? noOfCalls : 1); // Load the response as json if (!webhookUrl) { webhookUrl = process.env.SLACK_WEBHOOK_URL; } if (webhookUrl) { let i = 0; webhookUrl.split(",").forEach((eachWebhookUrl) => { const firstCall = mockedHooks.calls[i]; // check our webhook url called in ENV var SLACK_WEBHOOK_URL expect(firstCall.url).toEqual(eachWebhookUrl); i++; }); } const body = mockedHooks.calls[0].params; return body; } function messageBuildURL(body: string) { // build a URL to check the message renders const mbTestUrlBase = "https://api.slack.com/docs/messages/builder?msg="; // encode our json message request into a URL encoded string const encodedBody = encodeURIComponent(body); const mbTestUrl = `${mbTestUrlBase}${encodedBody}`; return mbTestUrl; } function checkStatus(body: string, status: string) { expect(body).not.toContain("undefined"); switch (status) { case "passed": { expect(body).toContain("test run passed"); break; } case "failed": { expect(body).toContain("test run failed"); break; } case "build": { expect(body).toContain("build failed"); break; } default: { expect(body).toContain("test run passed"); } } }
the_stack
import { Injectable } from '@angular/core'; import { HttpHeaders } from '@angular/common/http'; import { Router } from '@angular/router'; import { Observable, of as observableOf, Subscription, timer as observableTimer } from 'rxjs'; import { catchError, concatMap, distinctUntilChanged, filter, find, map, startWith, take, tap } from 'rxjs/operators'; import { Store } from '@ngrx/store'; import { TranslateService } from '@ngx-translate/core'; import { submissionSelector, SubmissionState } from './submission.reducers'; import { hasValue, isEmpty, isNotUndefined } from '../shared/empty.util'; import { CancelSubmissionFormAction, ChangeSubmissionCollectionAction, DiscardSubmissionAction, InitSubmissionFormAction, ResetSubmissionFormAction, SaveAndDepositSubmissionAction, SaveForLaterSubmissionFormAction, SaveSubmissionFormAction, SaveSubmissionSectionFormAction, SetActiveSectionAction } from './objects/submission-objects.actions'; import { SubmissionError, SubmissionObjectEntry, SubmissionSectionEntry, SubmissionSectionObject } from './objects/submission-objects.reducer'; import { submissionObjectFromIdSelector } from './selectors'; import { HttpOptions } from '../core/dspace-rest/dspace-rest.service'; import { SubmissionRestService } from '../core/submission/submission-rest.service'; import { SectionDataObject } from './sections/models/section-data.model'; import { SubmissionScopeType } from '../core/submission/submission-scope-type'; import { SubmissionObject } from '../core/submission/models/submission-object.model'; import { RouteService } from '../core/services/route.service'; import { SectionsType } from './sections/sections-type'; import { NotificationsService } from '../shared/notifications/notifications.service'; import { SubmissionDefinitionsModel } from '../core/config/models/config-submission-definitions.model'; import { WorkspaceitemSectionsObject } from '../core/submission/models/workspaceitem-sections.model'; import { RemoteData } from '../core/data/remote-data'; import { ErrorResponse } from '../core/cache/response.models'; import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject } from '../shared/remote-data.utils'; import { RequestService } from '../core/data/request.service'; import { SearchService } from '../core/shared/search/search.service'; import { Item } from '../core/shared/item.model'; import { environment } from '../../environments/environment'; import { SubmissionJsonPatchOperationsService } from '../core/submission/submission-json-patch-operations.service'; /** * A service that provides methods used in submission process. */ @Injectable() export class SubmissionService { /** * Subscription */ protected autoSaveSub: Subscription; /** * Observable used as timer */ protected timer$: Observable<any>; private workspaceLinkPath = 'workspaceitems'; private workflowLinkPath = 'workflowitems'; /** * Initialize service variables * @param {NotificationsService} notificationsService * @param {SubmissionRestService} restService * @param {Router} router * @param {RouteService} routeService * @param {Store<SubmissionState>} store * @param {TranslateService} translate * @param {SearchService} searchService * @param {RequestService} requestService * @param {SubmissionJsonPatchOperationsService} jsonPatchOperationService */ constructor(protected notificationsService: NotificationsService, protected restService: SubmissionRestService, protected router: Router, protected routeService: RouteService, protected store: Store<SubmissionState>, protected translate: TranslateService, protected searchService: SearchService, protected requestService: RequestService, protected jsonPatchOperationService: SubmissionJsonPatchOperationsService) { } /** * Dispatch a new [ChangeSubmissionCollectionAction] * * @param submissionId * The submission id * @param collectionId * The collection id */ changeSubmissionCollection(submissionId, collectionId) { this.store.dispatch(new ChangeSubmissionCollectionAction(submissionId, collectionId)); } /** * Perform a REST call to create a new workspaceitem and return response * * @param collectionId * The owning collection id * @return Observable<SubmissionObject> * observable of SubmissionObject */ createSubmission(collectionId?: string): Observable<SubmissionObject> { return this.restService.postToEndpoint(this.workspaceLinkPath, {}, null, null, collectionId).pipe( map((workspaceitem: SubmissionObject[]) => workspaceitem[0] as SubmissionObject), catchError(() => observableOf({} as SubmissionObject))); } /** * Perform a REST call to deposit a workspaceitem and return response * * @param selfUrl * The workspaceitem self url * @param collectionId * Optional collection id * @return Observable<SubmissionObject> * observable of SubmissionObject */ createSubmissionFromExternalSource(selfUrl: string, collectionId?: string): Observable<SubmissionObject[]> { const options: HttpOptions = Object.create({}); let headers = new HttpHeaders(); headers = headers.append('Content-Type', 'text/uri-list'); options.headers = headers; return this.restService.postToEndpoint(this.workspaceLinkPath, selfUrl, null, options, collectionId) as Observable<SubmissionObject[]>; } /** * Perform a REST call to deposit a workspaceitem and return response * * @param selfUrl * The workspaceitem self url * @return Observable<SubmissionObject> * observable of SubmissionObject */ depositSubmission(selfUrl: string): Observable<SubmissionObject[]> { const options: HttpOptions = Object.create({}); let headers = new HttpHeaders(); headers = headers.append('Content-Type', 'text/uri-list'); options.headers = headers; return this.restService.postToEndpoint(this.workflowLinkPath, selfUrl, null, options) as Observable<SubmissionObject[]>; } /** * Perform a REST call to delete a workspaceitem and return response * * @param submissionId * The submission id * @return Observable<SubmissionObject> * observable of SubmissionObject */ discardSubmission(submissionId: string): Observable<SubmissionObject[]> { return this.restService.deleteById(submissionId) as Observable<SubmissionObject[]>; } /** * Dispatch a new [InitSubmissionFormAction] * * @param collectionId * The collection id * @param submissionId * The submission id * @param selfUrl * The workspaceitem self url * @param submissionDefinition * The [SubmissionDefinitionsModel] that define submission configuration * @param sections * The [WorkspaceitemSectionsObject] that define submission sections init data * @param errors * The [SubmissionSectionError] that define submission sections init errors */ dispatchInit( collectionId: string, submissionId: string, selfUrl: string, submissionDefinition: SubmissionDefinitionsModel, sections: WorkspaceitemSectionsObject, item: Item, errors: SubmissionError) { this.store.dispatch(new InitSubmissionFormAction(collectionId, submissionId, selfUrl, submissionDefinition, sections, item, errors)); } /** * Dispatch a new [SaveAndDepositSubmissionAction] * * @param submissionId * The submission id */ dispatchDeposit(submissionId) { this.store.dispatch(new SaveAndDepositSubmissionAction(submissionId)); } /** * Dispatch a new [DiscardSubmissionAction] * * @param submissionId * The submission id */ dispatchDiscard(submissionId) { this.store.dispatch(new DiscardSubmissionAction(submissionId)); } /** * Dispatch a new [SaveSubmissionFormAction] * * @param submissionId * The submission id * @param manual * whether is a manual save, default false */ dispatchSave(submissionId, manual?: boolean) { this.getSubmissionSaveProcessingStatus(submissionId).pipe( find((isPending: boolean) => !isPending) ).subscribe(() => { this.store.dispatch(new SaveSubmissionFormAction(submissionId, manual)); }); } /** * Dispatch a new [SaveForLaterSubmissionFormAction] * * @param submissionId * The submission id */ dispatchSaveForLater(submissionId) { this.store.dispatch(new SaveForLaterSubmissionFormAction(submissionId)); } /** * Dispatch a new [SaveSubmissionSectionFormAction] * * @param submissionId * The submission id * @param sectionId * The section id */ dispatchSaveSection(submissionId, sectionId) { this.store.dispatch(new SaveSubmissionSectionFormAction(submissionId, sectionId)); } /** * Return the id of the current focused section for the specified submission * * @param submissionId * The submission id * @return Observable<string> * observable of section id */ getActiveSectionId(submissionId: string): Observable<string> { return this.getSubmissionObject(submissionId).pipe( map((submission: SubmissionObjectEntry) => submission.activeSection)); } /** * Return the [SubmissionObjectEntry] for the specified submission * * @param submissionId * The submission id * @return Observable<SubmissionObjectEntry> * observable of SubmissionObjectEntry */ getSubmissionObject(submissionId: string): Observable<SubmissionObjectEntry> { return this.store.select(submissionObjectFromIdSelector(submissionId)).pipe( filter((submission: SubmissionObjectEntry) => isNotUndefined(submission))); } /** * Return a list of the active [SectionDataObject] belonging to the specified submission * * @param submissionId * The submission id * @return Observable<SubmissionObjectEntry> * observable with the list of active submission's sections */ getSubmissionSections(submissionId: string): Observable<SectionDataObject[]> { return this.getSubmissionObject(submissionId).pipe( find((submission: SubmissionObjectEntry) => isNotUndefined(submission.sections) && !submission.isLoading), map((submission: SubmissionObjectEntry) => submission.sections), map((sections: SubmissionSectionEntry) => { const availableSections: SectionDataObject[] = []; Object.keys(sections) .filter((sectionId) => !this.isSectionHidden(sections[sectionId] as SubmissionSectionObject)) .forEach((sectionId) => { const sectionObject: SectionDataObject = Object.create({}); sectionObject.config = sections[sectionId].config; sectionObject.mandatory = sections[sectionId].mandatory; sectionObject.data = sections[sectionId].data; sectionObject.errorsToShow = sections[sectionId].errorsToShow; sectionObject.serverValidationErrors = sections[sectionId].serverValidationErrors; sectionObject.header = sections[sectionId].header; sectionObject.id = sectionId; sectionObject.sectionType = sections[sectionId].sectionType; availableSections.push(sectionObject); }); return availableSections; }), startWith([]), distinctUntilChanged()); } /** * Return a list of the disabled [SectionDataObject] belonging to the specified submission * * @param submissionId * The submission id * @return Observable<SubmissionObjectEntry> * observable with the list of disabled submission's sections */ getDisabledSectionsList(submissionId: string): Observable<SectionDataObject[]> { return this.getSubmissionObject(submissionId).pipe( filter((submission: SubmissionObjectEntry) => isNotUndefined(submission.sections) && !submission.isLoading), map((submission: SubmissionObjectEntry) => submission.sections), map((sections: SubmissionSectionEntry) => { const disabledSections: SectionDataObject[] = []; Object.keys(sections) .filter((sectionId) => !this.isSectionHidden(sections[sectionId] as SubmissionSectionObject)) .filter((sectionId) => !sections[sectionId].enabled) .forEach((sectionId) => { const sectionObject: SectionDataObject = Object.create({}); sectionObject.header = sections[sectionId].header; sectionObject.id = sectionId; disabledSections.push(sectionObject); }); return disabledSections; }), startWith([]), distinctUntilChanged()); } /** * Return the correct REST endpoint link path depending on the page route * * @return string * link path */ getSubmissionObjectLinkName(): string { const url = this.router.routerState.snapshot.url; if (url.startsWith('/workspaceitems') || url.startsWith('/submit')) { return this.workspaceLinkPath; } else if (url.startsWith('/workflowitems')) { return this.workflowLinkPath; } else { return 'edititems'; } } /** * Return the submission scope * * @return SubmissionScopeType * the SubmissionScopeType */ getSubmissionScope(): SubmissionScopeType { let scope: SubmissionScopeType; switch (this.getSubmissionObjectLinkName()) { case this.workspaceLinkPath: scope = SubmissionScopeType.WorkspaceItem; break; case this.workflowLinkPath: scope = SubmissionScopeType.WorkflowItem; break; } return scope; } /** * Return the validity status of the submission * * @param submissionId * The submission id * @return Observable<boolean> * observable with submission validity status */ getSubmissionStatus(submissionId: string): Observable<boolean> { return this.store.select(submissionSelector).pipe( map((submissions: SubmissionState) => submissions.objects[submissionId]), filter((item) => isNotUndefined(item) && isNotUndefined(item.sections)), map((item) => item.sections), map((sections) => { const states = []; if (isNotUndefined(sections)) { Object.keys(sections) .filter((sectionId) => sections.hasOwnProperty(sectionId)) .filter((sectionId) => !this.isSectionHidden(sections[sectionId] as SubmissionSectionObject)) .filter((sectionId) => sections[sectionId].enabled) .filter((sectionId) => sections[sectionId].isValid === false) .forEach((sectionId) => { states.push(sections[sectionId].isValid); }); } return !isEmpty(sections) && isEmpty(states); }), distinctUntilChanged(), startWith(false)); } /** * Return the save processing status of the submission * * @param submissionId * The submission id * @return Observable<boolean> * observable with submission save processing status */ getSubmissionSaveProcessingStatus(submissionId: string): Observable<boolean> { return this.getSubmissionObject(submissionId).pipe( map((state: SubmissionObjectEntry) => state.savePending), distinctUntilChanged(), startWith(false)); } /** * Return the deposit processing status of the submission * * @param submissionId * The submission id * @return Observable<boolean> * observable with submission deposit processing status */ getSubmissionDepositProcessingStatus(submissionId: string): Observable<boolean> { return this.getSubmissionObject(submissionId).pipe( map((state: SubmissionObjectEntry) => state.depositPending), distinctUntilChanged(), startWith(false)); } /** * Return whether submission unsaved modification are present * * @return Observable<boolean> * observable with submission unsaved modification presence */ hasUnsavedModification(): Observable<boolean> { return this.jsonPatchOperationService.hasPendingOperations('sections'); } /** * Return the visibility status of the specified section * * @param sectionData * The section data * @return boolean * true if section is hidden, false otherwise */ isSectionHidden(sectionData: SubmissionSectionObject): boolean { return (isNotUndefined(sectionData.visibility) && sectionData.visibility.main === 'HIDDEN' && sectionData.visibility.other === 'HIDDEN'); } /** * Return the loading status of the submission * * @param submissionId * The submission id * @return Observable<boolean> * observable with submission loading status */ isSubmissionLoading(submissionId: string): Observable<boolean> { return this.getSubmissionObject(submissionId).pipe( map((submission: SubmissionObjectEntry) => submission.isLoading), distinctUntilChanged()); } /** * Show a notification when a new section is added to submission form * * @param submissionId * The submission id * @param sectionId * The section id * @param sectionType * The section type */ notifyNewSection(submissionId: string, sectionId: string, sectionType?: SectionsType) { const m = this.translate.instant('submission.sections.general.metadata-extracted-new-section', { sectionId }); this.notificationsService.info(null, m, null, true); } /** * Redirect to MyDspace page */ redirectToMyDSpace() { // This assures that the cache is empty before redirecting to mydspace. // See https://github.com/DSpace/dspace-angular/pull/468 this.searchService.getEndpoint().pipe( take(1), tap((url) => this.requestService.removeByHrefSubstring(url)), // Now, do redirect. concatMap( () => this.routeService.getPreviousUrl().pipe( take(1), tap((previousUrl) => { if (isEmpty(previousUrl) || !previousUrl.startsWith('/mydspace')) { this.router.navigate(['/mydspace']); } else { this.router.navigateByUrl(previousUrl); } }))) ).subscribe(); } /** * Dispatch a new [CancelSubmissionFormAction] */ resetAllSubmissionObjects() { this.store.dispatch(new CancelSubmissionFormAction()); } /** * Dispatch a new [ResetSubmissionFormAction] * * @param collectionId * The collection id * @param submissionId * The submission id * @param selfUrl * The workspaceitem self url * @param submissionDefinition * The [SubmissionDefinitionsModel] that define submission configuration * @param sections * The [WorkspaceitemSectionsObject] that define submission sections init data */ resetSubmissionObject( collectionId: string, submissionId: string, selfUrl: string, submissionDefinition: SubmissionDefinitionsModel, sections: WorkspaceitemSectionsObject, item: Item ) { this.store.dispatch(new ResetSubmissionFormAction(collectionId, submissionId, selfUrl, sections, submissionDefinition, item)); } /** * Perform a REST call to retrieve an existing workspaceitem/workflowitem and return response * * @return Observable<RemoteData<SubmissionObject>> * observable of RemoteData<SubmissionObject> */ retrieveSubmission(submissionId): Observable<RemoteData<SubmissionObject>> { return this.restService.getDataById(this.getSubmissionObjectLinkName(), submissionId).pipe( find((submissionObjects: SubmissionObject[]) => isNotUndefined(submissionObjects)), map((submissionObjects: SubmissionObject[]) => createSuccessfulRemoteDataObject( submissionObjects[0])), catchError((errorResponse: ErrorResponse) => { return createFailedRemoteDataObject$<SubmissionObject>(errorResponse.errorMessage, errorResponse.statusCode); }) ); } /** * Dispatch a new [SetActiveSectionAction] * * @param submissionId * The submission id * @param sectionId * The section id */ setActiveSection(submissionId, sectionId) { this.store.dispatch(new SetActiveSectionAction(submissionId, sectionId)); } /** * Allow to save automatically the submission * * @param submissionId * The submission id */ startAutoSave(submissionId) { this.stopAutoSave(); if (environment.submission.autosave.timer === 0) { return; } // AUTOSAVE submission const duration = environment.submission.autosave.timer; // Dispatch save action after given duration this.timer$ = observableTimer(duration, duration); this.autoSaveSub = this.timer$ .subscribe(() => this.store.dispatch(new SaveSubmissionFormAction(submissionId))); } /** * Unsubscribe subscription to timer */ stopAutoSave() { if (hasValue(this.autoSaveSub)) { this.autoSaveSub.unsubscribe(); this.autoSaveSub = null; } } }
the_stack
import React, { Component } from "react"; import ReactDOM from "react-dom"; import * as d3 from "d3"; import { bisect } from "./optimization.tsx"; import { InfoTooltip } from "./InfoTooltip.tsx"; import { VennLegend } from "./VennLegend.tsx"; import { DirectionalHint } from '@fluentui/react'; function calculateCircleRadiiAndDistance(a, b, ab, datasetSize) { let aProportion = a / datasetSize; let bProportion = b / datasetSize; let abProportion = ab / datasetSize; // We use the following reasoning: // aProportion = Area(circleA) / totalArea // bProportion = Area(circleB) / totalArea // We want the largest circle to have a radius of 50. // So we select the larget of the two circular regions and set // its area to be Pi * 50 * 50. // Thus if aProportion is the larger proportion, we have // that Ra must be 50 and aProportion = (Pi * 50 * 50) / totalArea // Thus totalArea = (Pi * 50 * 50) / aProportion. // Similarly if bProportion is the larger proportion: // We have that totalArea = (Pi * 50 * 50) / bProportion. let Ra; let Rb; let Aab; let totalArea = 1; if (a >= b) { totalArea = (50 * 50 * 3.14) / aProportion; Ra = 50; Rb = Math.sqrt(bProportion * totalArea / 3.14); Aab = abProportion * totalArea; } else { totalArea = (50 * 50 * 3.14) / bProportion; Rb = 50; Ra = Math.sqrt(aProportion * totalArea / 3.14); Aab = abProportion * totalArea; } // This function calcuates the area of overlap // of two circles of radii r1 and r2 whose // centers are separated by a distance d. function areaOverlap(r1, r2, dist) { var r = Math.min(r1, r2); var R = Math.max(r1, r2); if (dist == 0) { return (3.14 * Math.pow(r, 2)); } else if (dist >= (R + r)) { return 0; } var sectorAreas = Math.pow(r, 2) * Math.acos((Math.pow(dist, 2) + Math.pow(r, 2) - Math.pow(R, 2)) / (2 * dist * r)) + Math.pow(R, 2) * Math.acos((Math.pow(dist, 2) + Math.pow(R, 2) - Math.pow(r, 2)) / (2 * dist * R)); var triangleAreas = 1/2 * Math.sqrt((-dist + r + R) * (dist + r - R) * (dist - r + R) * (dist + r + R)); var overlapArea = sectorAreas - triangleAreas; return overlapArea; } // In order to decide the distance d that the circles // Need to be from each other, we use the bisection method // to search for the point at which the difference between // The area of overlap between the circles and the actual // are of the intersection is minimal. function aIntersection(dist) { return (areaOverlap(Ra, Rb, dist) - Aab); } var r = Math.min(Ra, Rb); var R = Math.max(Ra, Rb); let d; if ((ab > 0) && (ab < a) && (ab < b)) { // We perform the bisection search between the two extreme values d = bisect(aIntersection, (r + R - 0.00001), (R - r + 0.00001)); } else if (ab > 0) { d = R - r; } else { d = R + r + 10; } return [Ra, Rb, d]; } export function getRegionFill(regionName, regionSelected) { if (regionName == "intersection" && regionSelected != "intersection") { return "rgba(241, 241, 127, 0.8)"; } else if (regionName == "intersection" && regionSelected == "intersection") { return "rgba(141, 141, 27, 0.8)"; } else if(regionName == "progress" && regionSelected != "progress") { return "rgba(175, 227, 141, 0.8)"; } else if (regionName == "progress" && regionSelected == "progress") { return "rgba(75, 127, 41, 0.8)"; } else if (regionName == "regress" && regionSelected != "regress") { return "rgba(206, 160, 205, 0.8)"; } else if (regionName == "regress" && regionSelected == "regress") { return "rgba(106, 60, 105, 0.8)"; } } type IntersectionBetweenModelErrorsState = { selectedDataPoint: any, } type IntersectionBetweenModelErrorsProps = { selectedDataPoint: any, filterByInstanceIds: any, setSelectedRegion: any, selectedRegion: any } class IntersectionBetweenModelErrors extends Component<IntersectionBetweenModelErrorsProps, IntersectionBetweenModelErrorsState> { constructor(props) { super(props); this.state = { selectedDataPoint: this.props.selectedDataPoint, }; this.node = React.createRef<HTMLDivElement>(); this.createVennDiagramPlot = this.createVennDiagramPlot.bind(this); this.setSelectedRegion = this.setSelectedRegion.bind(this); } node: React.RefObject<HTMLDivElement> progress: any regress: any intersection: any componentDidMount() { this.createVennDiagramPlot(); } componentWillReceiveProps(nextProps) { this.setState({ selectedDataPoint: nextProps.selectedDataPoint, }); } componentDidUpdate() { this.createVennDiagramPlot(); } setSelectedRegion(regionName: string) { if (regionName == "intersection") { this.props.filterByInstanceIds(this.intersection); } else if (regionName == "progress") { this.props.filterByInstanceIds(this.progress); } else if (regionName == "regress") { this.props.filterByInstanceIds(this.regress); } else { console.log("invalid regionName " + (regionName ?? "null")); return; } this.props.setSelectedRegion(regionName); } createVennDiagramPlot() { var _this = this; var body = d3.select(this.node.current); var margin = { top: 5, right: 25, bottom: 50, left: 25 } var h = 270 - margin.top - margin.bottom var w = 470 - margin.left - margin.right var tooltip = d3.select("#venntooltip"); // SVG d3.select("#venndiagram").remove(); var svg = body.append('svg') .attr('id', "venndiagram") .attr('height',h + margin.top + margin.bottom) .attr('width',w + margin.left + margin.right) .append('g') .attr('transform',`translate(${margin.left},${margin.top})`) svg.append('text') .attr('id','xAxisLabel') .attr('y', -20) .attr('x', 200) .attr('dy','.71em') .style('text-anchor','end'); svg.append("rect") .attr("x", 0) .attr("y", 0) .attr("width", w) .attr("height", h) .attr("fill", "rgba(255, 255, 255, 0.8)") .attr("stroke", "black") .attr("stroke-width", 0.5); if (this.state.selectedDataPoint != null) { var errorPartition = this.state.selectedDataPoint.models_error_overlap; var a = errorPartition[0].length; var b = errorPartition[1].length; var ab = errorPartition[2].length; // Error instance ids of regress instances var regress = errorPartition[1].filter(instanceId => (errorPartition[2].indexOf(instanceId) == -1)); this.regress = regress; // Error instance ids of progress instances var progress = errorPartition[0].filter(instanceId => (errorPartition[2].indexOf(instanceId) == -1)); this.progress = progress; var regressSize = regress.length; var regressProportion = regressSize / this.state.selectedDataPoint.dataset_size; var progressSize = progress.length; var progressProportion = progressSize / this.state.selectedDataPoint.dataset_size; var intersection = errorPartition[2]; this.intersection = intersection; var intersectionSize = intersection.length; var intersectionProportion = intersectionSize / this.state.selectedDataPoint.dataset_size; var totalErrors = a + b - ab var aProportion = 0.0 var bProportion = 0.0 var abProportion = 0.0 var data = [ {"name": "intersectionRaRb", "area": ab}, {"name": "Ra", "area": a}, {"name": "Rb", "area": b} ]; if (totalErrors > 0) { aProportion = a / this.state.selectedDataPoint.dataset_size; bProportion = b / this.state.selectedDataPoint.dataset_size; abProportion = ab / this.state.selectedDataPoint.dataset_size; let Ra; let Rb; let Aab; var r = Math.min(Ra, Rb); var R = Math.max(Ra, Rb); // We perform the bisection search between the two extreme values //let d = bisect(aIntersection, (r + R - 0.00001), (R - r + 0.00001)); let d; [Ra, Rb, d] = calculateCircleRadiiAndDistance(a, b, ab, this.state.selectedDataPoint.dataset_size); var areas = svg.append("g").attr("id", "areas"); if ((Math.abs(Ra - Rb) < d) && (d < (Ra + Rb))) { // This is the case when the circles have some partial overlap. // That is when there is non-trivial overlap between the errors of h1 and h2. var circleRad = 50; var xCenter = w/2 - d/2; var yCenter = h/2 var xCenter2 = xCenter + d; // Draw the path that demarcates the boundary of the Intersection region var path = areas.append("path"); var intersectionPath = d3.path(); intersectionPath.arc(xCenter, yCenter, Ra, -Math.acos((Math.pow(d, 2) + Math.pow(Ra, 2) - Math.pow(Rb, 2))/(2 * d *Ra)), Math.acos((Math.pow(d, 2) + Math.pow(Ra, 2) - Math.pow(Rb, 2))/(2 * d *Ra))); intersectionPath.arc(xCenter2, yCenter, Rb, Math.PI - Math.acos((Math.pow(d, 2) + Math.pow(Rb, 2) - Math.pow(Ra, 2))/(2 * d *Rb)), Math.PI + Math.acos((Math.pow(d, 2) + Math.pow(Rb, 2) - Math.pow(Ra, 2))/(2 * d *Rb))); intersectionPath.closePath(); // Draw the path that demarcates the boundary of the Regress region var rPath = areas.append("path"); var progressPath = d3.path(); progressPath.arc(xCenter2, yCenter, Rb, Math.PI + Math.acos((Math.pow(d, 2) + Math.pow(Rb, 2) - Math.pow(Ra, 2))/(2 * d *Rb)), Math.PI - Math.acos((Math.pow(d, 2) + Math.pow(Rb, 2) - Math.pow(Ra, 2))/(2 * d *Rb)), true); progressPath.arc(xCenter, yCenter, Ra, Math.acos((Math.pow(d, 2) + Math.pow(Ra, 2) - Math.pow(Rb, 2))/(2 * d *Ra)), -Math.acos((Math.pow(d, 2) + Math.pow(Ra, 2) - Math.pow(Rb, 2))/(2 * d *Ra)), false); progressPath.closePath(); // Draw the path that demarcates the boundary of the Progress region var pPath = areas.append("path"); var regressPath = d3.path(); regressPath.arc(xCenter2, yCenter, Rb, Math.PI - Math.acos((Math.pow(d, 2) + Math.pow(Rb, 2) - Math.pow(Ra, 2))/(2 * d *Rb)), Math.PI + Math.acos((Math.pow(d, 2) + Math.pow(Rb, 2) - Math.pow(Ra, 2))/(2 * d *Rb)), true); regressPath.arc(xCenter, yCenter, Ra, -Math.acos((Math.pow(d, 2) + Math.pow(Ra, 2) - Math.pow(Rb, 2))/(2 * d *Ra)), Math.acos((Math.pow(d, 2) + Math.pow(Ra, 2) - Math.pow(Rb, 2))/(2 * d *Ra)), false); regressPath.closePath(); // Draw and style the Intersection region path.attr("d", intersectionPath) .attr("stroke", "black") .attr("stroke-width", "1px") .attr("fill", getRegionFill("intersection", _this.props.selectedRegion)) .on("mouseover", function() { tooltip.text(`${intersectionSize} (${(intersectionProportion * 100).toFixed(3)}%)`) .style("opacity", 0.8); d3.select(this).attr("stroke-width", "3px"); }) .on("mousemove", function() { var vennDiagramPlot = document.getElementById("venndiagramplot"); var coords = d3.mouse(vennDiagramPlot); tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2}px`) .style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`); }) .on("mouseout", function() { tooltip.style("opacity", 0); d3.select(this).attr("stroke-width", "1px"); }) .on("click", () => _this.setSelectedRegion("intersection")); // Draw and style the Regress region rPath.attr("d", regressPath) .attr("stroke", "black") .attr("stroke-width", "1px") .attr("fill", getRegionFill("regress", _this.props.selectedRegion)) .on("mouseover", function() { tooltip.text(`${regressSize} (${(regressProportion * 100).toFixed(3)}%)`) .style("opacity", 0.8); d3.select(this).attr("stroke-width", "2px"); }) .on("mousemove", function() { var vennDiagramPlot = document.getElementById("venndiagramplot"); var coords = d3.mouse(vennDiagramPlot); tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2}px`) .style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`); }) .on("mouseout", function() { tooltip.style("opacity", 0); d3.select(this).attr("stroke-width", "1px"); }) .on("click", () => _this.setSelectedRegion("regress")); // Draw and style the Progress region pPath.attr("d", progressPath) .attr("stroke", "black") .attr("stroke-width", "1px") .attr("fill", getRegionFill("progress", _this.props.selectedRegion)) .on("mouseover", function() { tooltip.text(`${progressSize} (${(progressProportion * 100).toFixed(3)}%)`) .style("opacity", 0.8); d3.select(this).attr("stroke-width", "2px"); }) .on("mousemove", function() { var vennDiagramPlot = document.getElementById("venndiagramplot"); var coords = d3.mouse(vennDiagramPlot); tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2}px`) .style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`); }) .on("mouseout", function() { tooltip.style("opacity", 0); d3.select(this).attr("stroke-width", "1px"); }) .on("click", () => _this.setSelectedRegion("progress")); areas.selectAll("g") .data(data); } else if (d <= Math.abs(Ra - Rb) && (Ra == Rb)) { // This is the case when one circle is completely contained within the other. // And when h1 and h2 errors are identical. var xCenter = w/2 - d/2; var yCenter = h/2 var xCenter2 = xCenter + d; areas.append("circle") .attr("r", Ra) .attr('transform', "translate(" + xCenter + "," + yCenter + ")") .attr("fill", getRegionFill("intersection", _this.props.selectedRegion)) .attr("stroke", "black") .attr("stroke-width", "1px") .on("mouseover", function() { tooltip.text(`${intersectionSize} (${(intersectionProportion * 100).toFixed(0)}%)`) .style("opacity", 0.8); d3.select(this).attr("stroke-width", "2px"); }) .on("mousemove", function() { var vennDiagramPlot = document.getElementById("venndiagramplot"); var coords = d3.mouse(vennDiagramPlot); tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2}px`) .style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`); }) .on("mouseout", function() { tooltip.style("opacity", 0); d3.select(this).attr("stroke-width", "1px"); }) .on("click", () => _this.setSelectedRegion("intersection")); } else if (d <= Math.abs(Ra - Rb) && (Ra > Rb)) { // This is the case when one circle is completely contained within the other. // And h1 errors fully contain h2 errors var xCenter = w/2 - d/2; var yCenter = h/2 var xCenter2 = xCenter + d; areas.append("circle") .attr("r", Rb) .attr('transform', "translate(" + xCenter2 + "," + yCenter + ")") .attr("fill", getRegionFill("intersection", _this.props.selectedRegion)) .attr("stroke", "black") .attr("stroke-width", "1px") .on("mouseover", function() { tooltip.text(`${intersectionSize} (${(intersectionProportion * 100).toFixed(0)}%)`) .style("opacity", 0.8); d3.select(this).attr("stroke-width", "2px"); }) .on("mousemove", function() { var vennDiagramPlot = document.getElementById("venndiagramplot"); var coords = d3.mouse(vennDiagramPlot); tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2}px`) .style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`); }) .on("mouseout", function() { tooltip.style("opacity", 0); d3.select(this).attr("stroke-width", "1px"); }) .on("click", () => _this.setSelectedRegion("intersection")); // Draw the path that demarcates the boundary of the Progress region var pPath = areas.append("path"); var progressPath = d3.path(); progressPath.arc(xCenter2, yCenter, Rb, 0, 2 * Math.PI, true); progressPath.arc(xCenter, yCenter, Ra, 0, 2 * Math.PI, false); progressPath.closePath(); // Draw and style the Regress region pPath.attr("d", progressPath) .attr("stroke", "black") .attr("stroke-width", "1px") .attr("fill", getRegionFill("progress", _this.props.selectedRegion)) .on("mouseover", function() { tooltip.text(`${progressSize} (${(progressProportion * 100).toFixed(3)}%)`) .style("opacity", 0.8); d3.select(this).attr("stroke-width", "2px"); }) .on("mousemove", function() { var vennDiagramPlot = document.getElementById("venndiagramplot"); var coords = d3.mouse(vennDiagramPlot); tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2}px`) .style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`); }) .on("mouseout", function() { tooltip.style("opacity", 0); d3.select(this).attr("stroke-width", "1px"); }) .on("click", () => _this.setSelectedRegion("progress")); } else if (d <= Math.abs(Ra - Rb) && (Ra < Rb)) { // This is the case when one circle is completely contained within the other. // And h2 errors filly contain h1 errors var xCenter = w/2 - d/2; var yCenter = h/2 var xCenter2 = xCenter + d; areas.append("circle") .attr("r", Ra) .attr('transform', "translate(" + xCenter2 + "," + yCenter + ")") .attr("fill", getRegionFill("intersection", _this.props.selectedRegion)) .attr("stroke", "black") .attr("stroke-width", "1px") .on("mouseover", function() { tooltip.text(`${intersectionSize} (${(intersectionProportion * 100).toFixed(0)}%)`) .style("opacity", 0.8); d3.select(this).attr("stroke-width", "2px"); }) .on("mousemove", function() { var vennDiagramPlot = document.getElementById("venndiagramplot"); var coords = d3.mouse(vennDiagramPlot); tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2}px`) .style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`); }) .on("mouseout", function() { tooltip.style("opacity", 0); d3.select(this).attr("stroke-width", "1px"); }) .on("click", () => _this.setSelectedRegion("intersection")); // Draw the path that demarcates the boundary of the Regress region var rPath = areas.append("path"); var regressPath = d3.path(); regressPath.arc(xCenter2, yCenter, Ra, 0, 2 * Math.PI, true); regressPath.arc(xCenter, yCenter, Rb, 0, 2 * Math.PI, false); regressPath.closePath(); // Draw and style the Regress region rPath.attr("d", regressPath) .attr("stroke", "black") .attr("stroke-width", "1px") .attr("fill", getRegionFill("regress", _this.props.selectedRegion)) .on("mouseover", function() { tooltip.text(`${regressSize} (${(regressProportion * 100).toFixed(3)}%)`) .style("opacity", 0.8); d3.select(this).attr("stroke-width", "2px"); }) .on("mousemove", function() { var vennDiagramPlot = document.getElementById("venndiagramplot"); var coords = d3.mouse(vennDiagramPlot); tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2}px`) .style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`); }) .on("mouseout", function() { tooltip.style("opacity", 0); d3.select(this).attr("stroke-width", "1px"); }) .on("click", () => _this.setSelectedRegion("regress")); } else if (d >= Math.abs(Ra + Rb)) { // This is the case when the circles are completely disjoint. // That is when there is no overlap between the errors of h1 and h2. var xCenter = w/2 - d/2; var yCenter = h/2 var xCenter2 = xCenter + d; areas.append("circle") .attr("r", Ra) .attr('transform', "translate(" + xCenter + "," + yCenter + ")") .attr("fill", getRegionFill("progress", _this.props.selectedRegion)) .attr("stroke", "black") .attr("stroke-width", "1px") .on("mouseover", function() { tooltip.text(`${progressSize} (${(progressProportion * 100).toFixed(0)}%)`) .style("opacity", 0.8); d3.select(this).attr("stroke-width", "2px"); }) .on("mousemove", function() { var vennDiagramPlot = document.getElementById("venndiagramplot"); var coords = d3.mouse(vennDiagramPlot); tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2}px`) .style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`); }) .on("mouseout", function() { tooltip.style("opacity", 0); d3.select(this).attr("stroke-width", "1px"); }) .on("click", () => _this.setSelectedRegion("progress")); areas.append("circle") .attr("r", Rb) .attr('transform', "translate(" + xCenter2 + "," + yCenter + ")") .attr("fill", getRegionFill("regress", _this.props.selectedRegion)) .attr("stroke", "black") .attr("stroke-width", "1px") .on("mouseover", function() { tooltip.text(`${regressSize} (${(regressProportion * 100).toFixed(0)}%)`) .style("opacity", 0.8); d3.select(this).attr("stroke-width", "2px"); }) .on("mousemove", function() { var vennDiagramPlot = document.getElementById("venndiagramplot"); var coords = d3.mouse(vennDiagramPlot); tooltip.style("left", `${coords[0] - (margin.left + margin.right)/2}px`) .style("top", `${coords[1] - (margin.top + margin.bottom)/2}px`); }) .on("mouseout", function() { tooltip.style("opacity", 0); d3.select(this).attr("stroke-width", "1px"); }) .on("click", () => _this.setSelectedRegion("regress")); } } } } render() { const diagramInfo = "Displays the newly trained model’s error counts and percentages in relation to those of the previous model."; return ( <div className="plot plot-venn" ref={this.node} id="venndiagramplot"> <div className="plot-title-row"> Intersection Between Model Errors <InfoTooltip direction={DirectionalHint.topCenter} message={diagramInfo}/> </div> <VennLegend selectedRegion={this.props.selectedRegion} setSelectedRegion={this.setSelectedRegion}/> <div className="tooltip" id="venntooltip" /> </div> ); } } export default IntersectionBetweenModelErrors;
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * An A record. */ export interface ARecord { /** * The IPv4 address of this A record. */ ipv4Address?: string; } /** * An AAAA record. */ export interface AaaaRecord { /** * The IPv6 address of this AAAA record. */ ipv6Address?: string; } /** * An MX record. */ export interface MxRecord { /** * The preference value for this MX record. */ preference?: number; /** * The domain name of the mail host for this MX record. */ exchange?: string; } /** * An NS record. */ export interface NsRecord { /** * The name server name for this NS record. */ nsdname?: string; } /** * A PTR record. */ export interface PtrRecord { /** * The PTR target domain name for this PTR record. */ ptrdname?: string; } /** * An SRV record. */ export interface SrvRecord { /** * The priority value for this SRV record. */ priority?: number; /** * The weight value for this SRV record. */ weight?: number; /** * The port value for this SRV record. */ port?: number; /** * The target domain name for this SRV record. */ target?: string; } /** * A TXT record. */ export interface TxtRecord { /** * The text value of this TXT record. */ value?: string[]; } /** * A CNAME record. */ export interface CnameRecord { /** * The canonical name for this CNAME record. */ cname?: string; } /** * An SOA record. */ export interface SoaRecord { /** * The domain name of the authoritative name server for this SOA record. */ host?: string; /** * The email contact for this SOA record. */ email?: string; /** * The serial number for this SOA record. */ serialNumber?: number; /** * The refresh value for this SOA record. */ refreshTime?: number; /** * The retry time for this SOA record. */ retryTime?: number; /** * The expire time for this SOA record. */ expireTime?: number; /** * The minimum value for this SOA record. By convention this is used to determine the negative * caching duration. */ minimumTtl?: number; } /** * Describes a DNS record set (a collection of DNS records with the same name and type). */ export interface RecordSet { /** * The ID of the record set. */ id?: string; /** * The name of the record set. */ name?: string; /** * The type of the record set. */ type?: string; /** * The etag of the record set. */ etag?: string; /** * The metadata attached to the record set. */ metadata?: { [propertyName: string]: string }; /** * The TTL (time-to-live) of the records in the record set. */ tTL?: number; /** * The list of A records in the record set. */ aRecords?: ARecord[]; /** * The list of AAAA records in the record set. */ aaaaRecords?: AaaaRecord[]; /** * The list of MX records in the record set. */ mxRecords?: MxRecord[]; /** * The list of NS records in the record set. */ nsRecords?: NsRecord[]; /** * The list of PTR records in the record set. */ ptrRecords?: PtrRecord[]; /** * The list of SRV records in the record set. */ srvRecords?: SrvRecord[]; /** * The list of TXT records in the record set. */ txtRecords?: TxtRecord[]; /** * The CNAME record in the record set. */ cnameRecord?: CnameRecord; /** * The SOA record in the record set. */ soaRecord?: SoaRecord; } /** * Parameters supplied to update a record set. */ export interface RecordSetUpdateParameters { /** * Specifies information about the record set being updated. */ recordSet?: RecordSet; } /** * An interface representing Resource. */ export interface Resource extends BaseResource { /** * Fully qualified resource Id for the resource. Ex - * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the resource * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The type of the resource. Ex- Microsoft.Compute/virtualMachines or * Microsoft.Storage/storageAccounts. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * The resource model definition for a ARM tracked top level resource */ export interface TrackedResource extends Resource { /** * Resource tags. */ tags?: { [propertyName: string]: string }; /** * The geo-location where the resource lives */ location: string; } /** * Describes a DNS zone. */ export interface Zone extends TrackedResource { /** * The etag of the zone. */ etag?: string; /** * The maximum number of record sets that can be created in this DNS zone. This is a read-only * property and any attempt to set this value will be ignored. */ maxNumberOfRecordSets?: number; /** * The current number of record sets in this DNS zone. This is a read-only property and any * attempt to set this value will be ignored. */ numberOfRecordSets?: number; /** * The name servers for this DNS zone. This is a read-only property and any attempt to set this * value will be ignored. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nameServers?: string[]; } /** * The response to a Zone Delete operation. */ export interface ZoneDeleteResult { /** * Users can perform a Get on Azure-AsyncOperation to get the status of their delete Zone * operations. */ azureAsyncOperation?: string; /** * Possible values include: 'InProgress', 'Succeeded', 'Failed' */ status?: OperationStatus; /** * Possible values include: 'Continue', 'SwitchingProtocols', 'OK', 'Created', 'Accepted', * 'NonAuthoritativeInformation', 'NoContent', 'ResetContent', 'PartialContent', * 'MultipleChoices', 'Ambiguous', 'MovedPermanently', 'Moved', 'Found', 'Redirect', 'SeeOther', * 'RedirectMethod', 'NotModified', 'UseProxy', 'Unused', 'TemporaryRedirect', * 'RedirectKeepVerb', 'BadRequest', 'Unauthorized', 'PaymentRequired', 'Forbidden', 'NotFound', * 'MethodNotAllowed', 'NotAcceptable', 'ProxyAuthenticationRequired', 'RequestTimeout', * 'Conflict', 'Gone', 'LengthRequired', 'PreconditionFailed', 'RequestEntityTooLarge', * 'RequestUriTooLong', 'UnsupportedMediaType', 'RequestedRangeNotSatisfiable', * 'ExpectationFailed', 'UpgradeRequired', 'InternalServerError', 'NotImplemented', 'BadGateway', * 'ServiceUnavailable', 'GatewayTimeout', 'HttpVersionNotSupported' */ statusCode?: HttpStatusCode; requestId?: string; } /** * The resource model definition for a ARM proxy resource. It will have everything other than * required location and tags */ export interface ProxyResource extends Resource { } /** * The resource model definition for a Azure Resource Manager resource with an etag. */ export interface AzureEntityResource extends Resource { /** * Resource Etag. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly etag?: string; } /** * Optional Parameters. */ export interface RecordSetsUpdateOptionalParams extends msRest.RequestOptionsBase { /** * The etag of the record set. Omit this value to always overwrite the current record set. * Specify the last-seen etag value to prevent accidentally overwriting concurrent changes. */ ifMatch?: string; } /** * Optional Parameters. */ export interface RecordSetsCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { /** * The etag of the record set. Omit this value to always overwrite the current record set. * Specify the last-seen etag value to prevent accidentally overwriting any concurrent changes. */ ifMatch?: string; /** * Set to '*' to allow a new record set to be created, but to prevent updating an existing record * set. Other values will be ignored. */ ifNoneMatch?: string; } /** * Optional Parameters. */ export interface RecordSetsDeleteMethodOptionalParams extends msRest.RequestOptionsBase { /** * The etag of the record set. Omit this value to always delete the current record set. Specify * the last-seen etag value to prevent accidentally deleting any concurrent changes. */ ifMatch?: string; } /** * Optional Parameters. */ export interface RecordSetsListByTypeOptionalParams extends msRest.RequestOptionsBase { /** * The maximum number of record sets to return. If not specified, returns up to 100 record sets. */ top?: number; /** * The suffix label of the record set name that has to be used to filter the record set * enumerations. If this parameter is specified, Enumeration will return only records that end * with .<recordSetNameSuffix> */ recordsetnamesuffix?: string; } /** * Optional Parameters. */ export interface RecordSetsListByDnsZoneOptionalParams extends msRest.RequestOptionsBase { /** * The maximum number of record sets to return. If not specified, returns up to 100 record sets. */ top?: number; /** * The suffix label of the record set name that has to be used to filter the record set * enumerations. If this parameter is specified, Enumeration will return only records that end * with .<recordSetNameSuffix> */ recordsetnamesuffix?: string; } /** * Optional Parameters. */ export interface ZonesCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { /** * The etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the * last-seen etag value to prevent accidentally overwriting any concurrent changes. */ ifMatch?: string; /** * Set to '*' to allow a new DNS zone to be created, but to prevent updating an existing zone. * Other values will be ignored. */ ifNoneMatch?: string; } /** * Optional Parameters. */ export interface ZonesDeleteMethodOptionalParams extends msRest.RequestOptionsBase { /** * The etag of the DNS zone. Omit this value to always delete the current zone. Specify the * last-seen etag value to prevent accidentally deleting any concurrent changes. */ ifMatch?: string; } /** * Optional Parameters. */ export interface ZonesListByResourceGroupOptionalParams extends msRest.RequestOptionsBase { /** * The maximum number of record sets to return. If not specified, returns up to 100 record sets. */ top?: number; } /** * Optional Parameters. */ export interface ZonesListOptionalParams extends msRest.RequestOptionsBase { /** * The maximum number of DNS zones to return. If not specified, returns up to 100 zones. */ top?: number; } /** * Optional Parameters. */ export interface ZonesBeginDeleteMethodOptionalParams extends msRest.RequestOptionsBase { /** * The etag of the DNS zone. Omit this value to always delete the current zone. Specify the * last-seen etag value to prevent accidentally deleting any concurrent changes. */ ifMatch?: string; } /** * An interface representing DnsManagementClientOptions. */ export interface DnsManagementClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * The response to a record set List operation. * @extends Array<RecordSet> */ export interface RecordSetListResult extends Array<RecordSet> { /** * The continuation token for the next page of results. */ nextLink?: string; } /** * @interface * The response to a Zone List or ListAll operation. * @extends Array<Zone> */ export interface ZoneListResult extends Array<Zone> { /** * The continuation token for the next page of results. */ nextLink?: string; } /** * Defines values for OperationStatus. * Possible values include: 'InProgress', 'Succeeded', 'Failed' * @readonly * @enum {string} */ export type OperationStatus = 'InProgress' | 'Succeeded' | 'Failed'; /** * Defines values for HttpStatusCode. * Possible values include: 'Continue', 'SwitchingProtocols', 'OK', 'Created', 'Accepted', * 'NonAuthoritativeInformation', 'NoContent', 'ResetContent', 'PartialContent', 'MultipleChoices', * 'Ambiguous', 'MovedPermanently', 'Moved', 'Found', 'Redirect', 'SeeOther', 'RedirectMethod', * 'NotModified', 'UseProxy', 'Unused', 'TemporaryRedirect', 'RedirectKeepVerb', 'BadRequest', * 'Unauthorized', 'PaymentRequired', 'Forbidden', 'NotFound', 'MethodNotAllowed', 'NotAcceptable', * 'ProxyAuthenticationRequired', 'RequestTimeout', 'Conflict', 'Gone', 'LengthRequired', * 'PreconditionFailed', 'RequestEntityTooLarge', 'RequestUriTooLong', 'UnsupportedMediaType', * 'RequestedRangeNotSatisfiable', 'ExpectationFailed', 'UpgradeRequired', 'InternalServerError', * 'NotImplemented', 'BadGateway', 'ServiceUnavailable', 'GatewayTimeout', * 'HttpVersionNotSupported' * @readonly * @enum {string} */ export type HttpStatusCode = 'Continue' | 'SwitchingProtocols' | 'OK' | 'Created' | 'Accepted' | 'NonAuthoritativeInformation' | 'NoContent' | 'ResetContent' | 'PartialContent' | 'MultipleChoices' | 'Ambiguous' | 'MovedPermanently' | 'Moved' | 'Found' | 'Redirect' | 'SeeOther' | 'RedirectMethod' | 'NotModified' | 'UseProxy' | 'Unused' | 'TemporaryRedirect' | 'RedirectKeepVerb' | 'BadRequest' | 'Unauthorized' | 'PaymentRequired' | 'Forbidden' | 'NotFound' | 'MethodNotAllowed' | 'NotAcceptable' | 'ProxyAuthenticationRequired' | 'RequestTimeout' | 'Conflict' | 'Gone' | 'LengthRequired' | 'PreconditionFailed' | 'RequestEntityTooLarge' | 'RequestUriTooLong' | 'UnsupportedMediaType' | 'RequestedRangeNotSatisfiable' | 'ExpectationFailed' | 'UpgradeRequired' | 'InternalServerError' | 'NotImplemented' | 'BadGateway' | 'ServiceUnavailable' | 'GatewayTimeout' | 'HttpVersionNotSupported'; /** * Defines values for RecordType. * Possible values include: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' * @readonly * @enum {string} */ export type RecordType = 'A' | 'AAAA' | 'CNAME' | 'MX' | 'NS' | 'PTR' | 'SOA' | 'SRV' | 'TXT'; /** * Contains response data for the update operation. */ export type RecordSetsUpdateResponse = RecordSet & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RecordSet; }; }; /** * Contains response data for the createOrUpdate operation. */ export type RecordSetsCreateOrUpdateResponse = RecordSet & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RecordSet; }; }; /** * Contains response data for the get operation. */ export type RecordSetsGetResponse = RecordSet & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RecordSet; }; }; /** * Contains response data for the listByType operation. */ export type RecordSetsListByTypeResponse = RecordSetListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RecordSetListResult; }; }; /** * Contains response data for the listByDnsZone operation. */ export type RecordSetsListByDnsZoneResponse = RecordSetListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RecordSetListResult; }; }; /** * Contains response data for the listByTypeNext operation. */ export type RecordSetsListByTypeNextResponse = RecordSetListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RecordSetListResult; }; }; /** * Contains response data for the listByDnsZoneNext operation. */ export type RecordSetsListByDnsZoneNextResponse = RecordSetListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RecordSetListResult; }; }; /** * Contains response data for the createOrUpdate operation. */ export type ZonesCreateOrUpdateResponse = Zone & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Zone; }; }; /** * Contains response data for the deleteMethod operation. */ export type ZonesDeleteMethodResponse = ZoneDeleteResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ZoneDeleteResult; }; }; /** * Contains response data for the get operation. */ export type ZonesGetResponse = Zone & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Zone; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type ZonesListByResourceGroupResponse = ZoneListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ZoneListResult; }; }; /** * Contains response data for the list operation. */ export type ZonesListResponse = ZoneListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ZoneListResult; }; }; /** * Contains response data for the beginDeleteMethod operation. */ export type ZonesBeginDeleteMethodResponse = ZoneDeleteResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ZoneDeleteResult; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type ZonesListByResourceGroupNextResponse = ZoneListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ZoneListResult; }; }; /** * Contains response data for the listNext operation. */ export type ZonesListNextResponse = ZoneListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ZoneListResult; }; };
the_stack
import { TreeMap } from '../../treemap/treemap'; import { BorderModel, FontModel } from '../model/base-model'; import { LegendShape, LegendPosition } from '../utils/enum'; import { Size } from '../utils/helper'; /** * Specifies the event argument for the treemap component. * * @private */ export interface ITreeMapEventArgs { /** Defines the name of the event. */ name: string; /** * Specifies the cancel state for the event. The default value is false. * If set as true, the event progress will be stopped. */ cancel: boolean; } /** * Specifies the event arguments for print event in treemap. */ export interface IPrintEventArgs extends ITreeMapEventArgs { /** * Specifies the html content that is printed. The html content returned is usually the id string of the treemap. */ htmlContent: Element; } /** * Specifies the event arguments for on load event in treemap. */ export interface ILoadEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; } /** * Specifies the event arguments for loaded event in treemap. */ export interface ILoadedEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** Defines isResized argument. */ isResized: boolean; } /** * Specifies the event arguments in item rendering event in treemap. */ export interface IItemRenderingEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance * * @deprecated */ treemap?: TreeMap; /** * Defines the current rendering item. */ // eslint-disable-next-line @typescript-eslint/ban-types currentItem: Object; /** * Defines all the items for rendering. */ // eslint-disable-next-line @typescript-eslint/ban-types RenderItems?: Object[]; /** * Defines the options for the treemap item rendering. */ // eslint-disable-next-line @typescript-eslint/ban-types options: Object; /** * Defines the header text of the treemap item. */ text: string; } /** * Specifies the event arguments for the drill down start event of treemap. */ export interface IDrillStartEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Defines the current drill-down. */ // eslint-disable-next-line @typescript-eslint/ban-types item: Object; /** * Defines the current element of drill-down. */ element: Element; /** * Defines the level of the treemap item. */ groupIndex: number; /** * Defines the parent name of the treemap item. */ groupName: string; /** * Returns a boolean value whether it is right click or not. */ rightClick: boolean; /** * Defines the child values of the item in the drill start event. */ // eslint-disable-next-line @typescript-eslint/ban-types childItems: Object; } /** * Specifies the event arguments for the drill down end event of the treemap. */ export interface IDrillEndEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Defines all the items for rendering. */ // eslint-disable-next-line @typescript-eslint/ban-types renderItems: Object[]; } /** * Defines the event arguments for treemap item click event. */ export interface IItemClickEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Defines the current item in the click event. * * @isGenericType true */ // eslint-disable-next-line @typescript-eslint/ban-types item: Object; /** * Defines the original mouse event arguments. */ mouseEvent: PointerEvent; /** * Defines the level of the current treemap item. */ groupIndex: number; /** * Defines the parent name of the current treemap item. */ groupName: string; /** * Defines the header name of the current treemap item. */ text: string; /** * Defines the template of the treemap item which is used to add it in the treemap control. */ contentItemTemplate : string; } /** * Defines the event argument of the treemap item data. */ export interface IItemDataEventArgs { /** * Defines the name of the treemap item. */ name: string; /** * Defines the level of the current treemap item. */ groupIndex: number; /** * Defines the parent name of the current treemap item. */ groupName: string; /** * Specifies whether the drill down is performed or not. */ isDrilled: boolean; /** * Specifies whether the item is leaf item or not. */ isLeafItem: boolean; /** * Defines the item area in the treemap. */ itemArea: number; /** * Defines the name of the parent level of the treemap item. */ levelOrderName: string; /** * Defines the options provided in the event arguments */ // eslint-disable-next-line @typescript-eslint/ban-types options?: Object; /** * Specifies the rect element in the event. */ // eslint-disable-next-line @typescript-eslint/ban-types rect?: Object; } /** * Specifies the event arguments available on performing mouse move on the treemap items. */ export interface IItemMoveEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Defines the current item move. * * @isGenericType true */ // eslint-disable-next-line @typescript-eslint/ban-types item: Object; /** * Defines the original mouse event arguments. */ mouseEvent: PointerEvent; } /** * Specifies the event arguments available on performing click event on the treemap items. */ export interface IClickEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Defines the original mouse event arguments. */ mouseEvent: PointerEvent; } /** * Specifies the event arguments available on performing double click event on the treemap items. */ export interface IDoubleClickEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Defines the original mouse event arguments. */ mouseEvent: PointerEvent; } /** * Specifies the event arguments available on performing right click event on the treemap items. */ export interface IRightClickEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Defines the original mouse event arguments. */ mouseEvent: PointerEvent; } /** * Specifies the event arguments available on performing mouse over on the treemap items. */ export interface IMouseMoveEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Defines the original mouse event arguments. */ mouseEvent: PointerEvent; } /** * Specifies the event arguments available when the item is selected in the treemap component. */ export interface IItemSelectedEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Specifies the current selected item. */ // eslint-disable-next-line @typescript-eslint/ban-types items: Object[]; /** * Specifies the current selected elements. */ elements: Element[]; /** * Defines the text used in the label contents. */ text: string; /** * Defines the template of the treemap item which is used to add it in the treemap control. */ contentItemTemplate : string; } /** * Specifies the event arguments available when the item is highlighted in the treemap component. */ export interface IItemHighlightEventArgs extends ITreeMapEventArgs { /** * Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Defines the current item which is highlighted. */ // eslint-disable-next-line @typescript-eslint/ban-types items: Object[]; /** * Defines the current highlighted elements. */ elements: Element[]; } /** * Specifies the event arguments available when the tooltip is rendered in the treemap component. */ export interface ITreeMapTooltipRenderEventArgs extends ITreeMapEventArgs { /** Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Defines the current treemap item in which the tooltip appears. */ // eslint-disable-next-line @typescript-eslint/ban-types item: Object; /** * Defines the options for customizing the tooltip. */ // eslint-disable-next-line @typescript-eslint/ban-types options: Object; /** * Defines the current tooltip element. */ element?: Element; /** * Defines the original mouse event arguments. */ eventArgs: PointerEvent; } /** * Specifies the event arguments available for the tooltip events in the treemap component. */ export interface ITreeMapTooltipArgs extends ITreeMapEventArgs { /** * Defines the location of the tooltip rendering event. */ // eslint-disable-next-line @typescript-eslint/ban-types location: Object; /** * Defines the text rendered in the tooltip. */ text: string[]; /** * Defines the data for rendering the tooltip. */ // eslint-disable-next-line @typescript-eslint/ban-types data: Object; /** * Defines the text style for customizing the tooltip text. */ textStyle: FontModel; /** * Defines the template for rendering the tooltip. */ template: string; } /** * Specifies the event arguments available when rendering each legend item in the treemap component. */ export interface ILegendItemRenderingEventArgs extends ITreeMapEventArgs { /** * Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Specifies the shape color of the legend. */ fill?: string; /** * Specifies the options for customizing the color and width of the shape border. */ shapeBorder?: BorderModel; /** * Defines the legend shape of the treemap. */ shape?: LegendShape; /** * Defines the URL of the legend if the shape is rendered as image. */ imageUrl?: string; } /** * Specifies the event arguments available when rendering the legend in the treemap component. */ export interface ILegendRenderingEventArgs extends ITreeMapEventArgs { /** * Defines the current treemap instance. * * @deprecated */ treemap?: TreeMap; /** * Specifies the position of the legend in the treemap component. */ position?: LegendPosition; /** * Specifies the position of the legend in the treemap component. */ _changePosition?: LegendPosition; } /** * Specifies the event arguments available for resize event of the treemap component. */ export interface IResizeEventArgs extends ITreeMapEventArgs { /** Defines the size of the treemap before resizing. */ previousSize: Size; /** Defines the size of the treemap after resizing. */ currentSize: Size; /** Defines the treemap instance. * * @deprecated */ treemap?: TreeMap; } /** * @private */ export interface IFontMapping { size?: string; color?: string; fontWeight?: string; fontStyle?: string; fontFamily?: string; } /** * @private */ export interface IShapes { // eslint-disable-next-line @typescript-eslint/ban-types renderOption?: Object; functionName?: string; } /** * Defines the theme supported for treemap component. */ export interface IThemeStyle { /** * Defines the background color of the treemap, supporting the theme. */ backgroundColor: string; /** * Defines the title text color of the treemap, supporting the theme. */ titleFontColor: string; /** * Defines the subtitle text color of the treemap, supporting the theme. */ subTitleFontColor: string; /** * Defines the tooltip fill color of the treemap, supporting the theme. */ tooltipFillColor: string; /** * Defines the tooltip text color of the treemap supporting the theme. */ tooltipFontColor: string; /** * Defines the opacity of tooltip in the treemap, supporting the theme. */ tooltipFillOpacity?: number; /** * Defines the opacity of tooltip text in the treemap, supporting the theme. */ tooltipTextOpacity?: number; /** * Defines the color of the legend title in the treemap, supporting the theme. */ legendTitleColor: string; /** * Defines the color of the legend text in the treemap, supporting the theme. */ legendTextColor: string; /** * Defines the font family of texts in the treemap, supporting the theme. */ fontFamily?: string; /** * Defines the font size of the texts in the treemap, supporting the theme. */ fontSize?: string; /** * Defines the font size of the legend texts in the treemap, supporting the theme. */ legendFontSize?: string; /** * Defines the font family of the label contents in the treemap, supporting the theme. */ labelFontFamily?: string; }
the_stack
import { assert } from "node-opcua-assert"; import { DataType, Variant, VariantArrayType } from "node-opcua-variant"; import { coerceInt32, coerceUInt64, Int64, isValidUInt64 } from "node-opcua-basic-types"; import { coerceLocalizedText, LocalizedText, QualifiedNameLike } from "node-opcua-data-model"; import { DataValue, DataValueT } from "node-opcua-data-value"; import { StatusCodes } from "node-opcua-status-code"; import { StatusCode } from "node-opcua-status-code"; import { NumericRange } from "node-opcua-numeric-range"; import { DTEnumValue } from "node-opcua-nodeset-ua"; import { BindVariableOptions, INamespace, UAVariable, UAProperty, ISessionContext } from "node-opcua-address-space-base"; import { VariableTypeIds } from "node-opcua-constants"; import { registerNodePromoter } from "../../source/loader/register_node_promoter"; import { coerceEnumValues } from "../../source/helpers/coerce_enum_value"; import { UAMultiStateValueDiscreteEx } from "../../source/interfaces/data_access/ua_multistate_value_discrete_ex"; import { AddMultiStateValueDiscreteOptions } from "../../source/address_space_ts"; import { UAVariableImpl } from "../ua_variable_impl"; import { add_dataItem_stuff } from "./add_dataItem_stuff"; function install_synchronization<T, DT extends DataType>(variable: UAMultiStateValueDiscreteEx<T, DT>) { const _variable = variable as UAMultiStateValueDiscreteEx<T, DT>; _variable.on("value_changed", (value: DataValue) => { const valueAsTextNode = variable.valueAsText || (_variable.getComponentByName("ValueAsText") as UAVariable); if (!valueAsTextNode) { return; } const valueAsText1 = _variable.findValueAsText(value.value.value); valueAsTextNode.setValueFromSource(valueAsText1); }); _variable.emit("value_changed", _variable.readValue()); } export interface UAMultiStateValueDiscreteImpl<T, DT extends DataType> { enumValues: UAProperty<DTEnumValue[], DataType.ExtensionObject>; valueAsText: UAProperty<LocalizedText, DataType.LocalizedText>; readValue( context?: ISessionContext | null, indexRange?: NumericRange, dataEncoding?: QualifiedNameLike | null ): DataValueT<T, DT>; readValueAsync(context: ISessionContext | null, callback?: any): any; } export class UAMultiStateValueDiscreteImpl<T, DT extends DataType> extends UAVariableImpl implements UAMultiStateValueDiscreteEx<T, DT> { public setValue(value: string | number | Int64): void { if (typeof value === "string") { const enumValues = this.enumValues.readValue().value.value; const selected = enumValues.filter((a: any) => a.displayName.text === value)[0]; if (selected) { this._setValue(selected.value); } else { throw new Error("cannot find enum string " + value + " in " + enumValues.toString()); } } else { this._setValue(coerceUInt64(value)); } } public getValueAsString(): string { return this.valueAsText.readValue().value.value.text || ""; } public getValueAsNumber(): number { return this.readValue().value.value as unknown as number; } public checkVariantCompatibility(value: Variant): StatusCode { if (this.enumValues) { if (!this._isValueInRange(coerceInt32(value.value))) { return StatusCodes.BadOutOfRange; } } return StatusCodes.Good; } public clone<T, DT extends DataType>(options1: any, optionalFilter: any, extraInfo: any): UAMultiStateValueDiscreteImpl<T, DT> { const variable1 = UAVariableImpl.prototype.clone.call(this, options1, optionalFilter, extraInfo); return promoteToMultiStateValueDiscrete(variable1); } /** * @private */ public _isValueInRange(value: number): boolean { // MultiStateValueDiscreteType const enumValues = this.enumValues.readValue().value.value as DTEnumValue[]; const e = enumValues.findIndex((x: DTEnumValue) => coerceInt32(x.value) === value); return !(e === -1); } /** * * @private */ public _enumValueIndex(): any { // construct an index to quickly find a EnumValue from a value const enumValues = this.enumValues.readValue().value.value; const enumValueIndex: any = {}; if (!enumValues || !enumValues.forEach) { return enumValueIndex; } enumValues.forEach((e: any) => { enumValueIndex[e.value[1]] = e; }); return enumValueIndex; } /** * * @private */ public _setValue(value: Int64): void { // check that value is in bound if (!this._isValueInRange(coerceInt32(value))) { throw new Error("UAMultiStateValueDiscrete#_setValue out of range " + value); } const dataType = this._getDataType(); if (dataType === DataType.Int64 || dataType === DataType.UInt64) { this.setValueFromSource({ dataType, value }); } else { const valueN = value[1]; this.setValueFromSource({ dataType, value: valueN }); } } /** * * @private */ public findValueAsText(value?: number | Int64): Variant { const enumValueIndex = this._enumValueIndex(); if (value === undefined) { throw new Error("Unexpected undefined value"); } if (value instanceof Array) { value = value[1]; } assert(!((value as any) instanceof Variant)); let valueAsText1 = "Invalid"; if (enumValueIndex[value]) { valueAsText1 = enumValueIndex[value].displayName; } const result = new Variant({ dataType: DataType.LocalizedText, value: coerceLocalizedText(valueAsText1) }); return result; } public _getDataType(): DataType { if (this.dataType.value === 26 /* Number */) { return DataType.UInt32; } const dataTypeStr = DataType[this.dataType.value as number] as string; return (DataType as any)[dataTypeStr] as DataType; } /** * * @private */ public _post_initialize(): void { // MultiStateValueDiscrete Variables can have any numeric Data Type; // this includes signed and unsigned integers from 8 to 64 Bit length. // istanbul ignore next if ( typeof this.dataType.value !== "number" || [ DataType.UInt64, DataType.Int64, DataType.UInt32, DataType.Int32, DataType.UInt16, DataType.Int16, DataType.Byte, DataType.Byte, DataType.SByte, 26 /*Number*/ ].indexOf(this.dataType.value as number) <= 0 ) { throw new Error("Invalid DataType in UAMultiStateValueDiscrete =>" + this.dataType.toString()); } // find the enum value type install_synchronization(this); } } export function promoteToMultiStateValueDiscrete<T, DT extends DataType>(node: UAVariable): UAMultiStateValueDiscreteImpl<T, DT> { if (node instanceof UAMultiStateValueDiscreteImpl) { return node; // already promoted } Object.setPrototypeOf(node, UAMultiStateValueDiscreteImpl.prototype); assert(node instanceof UAMultiStateValueDiscreteImpl, "should now be a State Machine"); (node as UAMultiStateValueDiscreteImpl<T, DT>)._post_initialize(); return node as UAMultiStateValueDiscreteImpl<T, DT>; } registerNodePromoter(VariableTypeIds.MultiStateValueDiscreteType, promoteToMultiStateValueDiscrete); export function _addMultiStateValueDiscrete<T, DT extends DataType>( namespace: INamespace, options: AddMultiStateValueDiscreteOptions ): UAMultiStateValueDiscreteEx<T, DT> { assert(Object.prototype.hasOwnProperty.call(options, "enumValues")); assert(!Object.prototype.hasOwnProperty.call(options, "ValuePrecision")); const addressSpace = namespace.addressSpace; const multiStateValueDiscreteType = addressSpace.findVariableType("MultiStateValueDiscreteType"); if (!multiStateValueDiscreteType) { throw new Error("expecting MultiStateValueDiscreteType to be defined , check nodeset xml file"); } // todo : if options.typeDefinition is specified, check that type is SubTypeOf MultiStateDiscreteType // EnumValueType // value: Int64, displayName: LocalizedText, Description: LocalizedText const enumValues = coerceEnumValues(options.enumValues); if (options.value === undefined && enumValues[0]) { options.value = enumValues[0].value; // Int64 } let value: undefined | BindVariableOptions; if (typeof options.value === "number" || isValidUInt64(options.value as number | number[])) { if (isValidUInt64(options.value as number | number[])) { value = new Variant({ dataType: DataType.UInt32, value: (options.value as Int64)[1] // Low word }); } else { value = new Variant({ dataType: DataType.UInt32, value: options.value }); } } else { value = options.value as any; } const cloned_options = { ...options, dataType: DataType.UInt32, typeDefinition: multiStateValueDiscreteType.nodeId, // valueRank: // note : OPCUA Spec 1.03 specifies -1:Scalar (part 8 page 8) but nodeset file specifies -2:Any value, valueRank: -1 // -1 : Scalar }; const variable = namespace.addVariable(cloned_options) as UAMultiStateValueDiscreteEx<T, DT>; add_dataItem_stuff(variable, options); namespace.addVariable({ accessLevel: "CurrentRead", browseName: { name: "EnumValues", namespaceIndex: 0 }, dataType: "EnumValueType", minimumSamplingInterval: 0, modellingRule: options.modellingRule ? "Mandatory" : undefined, propertyOf: variable, typeDefinition: "PropertyType", userAccessLevel: "CurrentRead", value: new Variant({ arrayType: VariantArrayType.Array, dataType: DataType.ExtensionObject, value: enumValues }) }); namespace.addVariable({ accessLevel: "CurrentRead", browseName: { name: "ValueAsText", namespaceIndex: 0 }, dataType: DataType.LocalizedText, minimumSamplingInterval: 0, modellingRule: options.modellingRule ? "Mandatory" : undefined, propertyOf: variable, typeDefinition: "PropertyType", userAccessLevel: "CurrentRead" // value: valueAsText }); // install additional helpers methods variable.install_extra_properties(); promoteToMultiStateValueDiscrete(variable); assert(variable.enumValues.browseName.toString() === "EnumValues"); assert(variable.valueAsText.browseName.toString() === "ValueAsText"); return variable; }
the_stack
* --------------------------------------------------------------- * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ## * ## ## * ## AUTHOR: acacode ## * ## SOURCE: https://github.com/acacode/swagger-typescript-api ## * --------------------------------------------------------------- */ /** * `Any` contains an arbitrary serialized protocol buffer message along with a URL that describes the type of the serialized message. Protobuf library provides support to pack/unpack Any values in the form of utility functions or additional generated methods of the Any type. Example 1: Pack and unpack a message in C++. Foo foo = ...; Any any; any.PackFrom(foo); ... if (any.UnpackTo(&foo)) { ... } Example 2: Pack and unpack a message in Java. Foo foo = ...; Any any = Any.pack(foo); ... if (any.is(Foo.class)) { foo = any.unpack(Foo.class); } Example 3: Pack and unpack a message in Python. foo = Foo(...) any = Any() any.Pack(foo) ... if any.Is(Foo.DESCRIPTOR): any.Unpack(foo) ... Example 4: Pack and unpack a message in Go foo := &pb.Foo{...} any, err := ptypes.MarshalAny(foo) ... foo := &pb.Foo{} if err := ptypes.UnmarshalAny(any, foo); err != nil { ... } The pack methods provided by protobuf library will by default use 'type.googleapis.com/full.type.name' as the type URL and the unpack methods only use the fully qualified type name after the last '/' in the type URL, for example "foo.bar.com/x/y.z" will yield type name "y.z". JSON ==== The JSON representation of an `Any` value uses the regular representation of the deserialized, embedded message, with an additional field `@type` which contains the type URL. Example: package google.profile; message Person { string first_name = 1; string last_name = 2; } { "@type": "type.googleapis.com/google.profile.Person", "firstName": <string>, "lastName": <string> } If the embedded message type is well-known and has a custom JSON representation, that representation will be embedded adding a field `value` which holds the custom JSON in addition to the `@type` field. Example (for message [google.protobuf.Duration][]): { "@type": "type.googleapis.com/google.protobuf.Duration", "value": "1.212s" } */ export interface ProtobufAny { /** * A URL/resource name that uniquely identifies the type of the serialized * protocol buffer message. This string must contain at least * one "/" character. The last segment of the URL's path must represent * the fully qualified name of the type (as in * `path/google.protobuf.Duration`). The name should be in a canonical form * (e.g., leading "." is not accepted). * * In practice, teams usually precompile into the binary all types that they * expect it to use in the context of Any. However, for URLs which use the * scheme `http`, `https`, or no scheme, one can optionally set up a type * server that maps type URLs to message definitions as follows: * * * If no scheme is provided, `https` is assumed. * * An HTTP GET on the URL must yield a [google.protobuf.Type][] * value in binary format, or produce an error. * * Applications are allowed to cache lookup results based on the * URL, or have them precompiled into a binary to avoid any * lookup. Therefore, binary compatibility needs to be preserved * on changes to types. (Use versioned type names to manage * breaking changes.) * * Note: this functionality is not currently available in the official * protobuf release, and it is not used for type URLs beginning with * type.googleapis.com. * * Schemes other than `http`, `https` (or the empty scheme) might be * used with implementation specific semantics. */ typeUrl?: string; /** * Must be a valid serialized protocol buffer of the above specified type. * @format byte */ value?: string; } export interface RpcStatus { /** @format int32 */ code?: number; message?: string; details?: ProtobufAny[]; } /** * Coin defines a token with a denomination and an amount. NOTE: The amount field is an Int which implements the custom method signatures required by gogoproto. */ export interface V1Beta1Coin { denom?: string; amount?: string; } /** * Deposit defines an amount deposited by an account address to an active proposal. */ export interface V1Beta1Deposit { /** @format uint64 */ proposalId?: string; depositor?: string; amount?: V1Beta1Coin[]; } /** * DepositParams defines the params for deposits on governance proposals. */ export interface V1Beta1DepositParams { /** Minimum deposit for a proposal to enter voting period. */ minDeposit?: V1Beta1Coin[]; /** * Maximum period for Atom holders to deposit on a proposal. Initial value: 2 * months. */ maxDepositPeriod?: string; } /** * MsgDepositResponse defines the Msg/Deposit response type. */ export type V1Beta1MsgDepositResponse = object; /** * MsgSubmitProposalResponse defines the Msg/SubmitProposal response type. */ export interface V1Beta1MsgSubmitProposalResponse { /** @format uint64 */ proposalId?: string; } /** * MsgVoteResponse defines the Msg/Vote response type. */ export type V1Beta1MsgVoteResponse = object; /** * message SomeRequest { Foo some_parameter = 1; PageRequest pagination = 2; } */ export interface V1Beta1PageRequest { /** * key is a value returned in PageResponse.next_key to begin * querying the next page most efficiently. Only one of offset or key * should be set. * @format byte */ key?: string; /** * offset is a numeric offset that can be used when key is unavailable. * It is less efficient than using key. Only one of offset or key should * be set. * @format uint64 */ offset?: string; /** * limit is the total number of results to be returned in the result page. * If left empty it will default to a value to be set by each app. * @format uint64 */ limit?: string; /** * count_total is set to true to indicate that the result set should include * a count of the total number of items available for pagination in UIs. * count_total is only respected when offset is used. It is ignored when key * is set. */ countTotal?: boolean; } /** * PageResponse is to be embedded in gRPC response messages where the corresponding request message has used PageRequest. message SomeResponse { repeated Bar results = 1; PageResponse page = 2; } */ export interface V1Beta1PageResponse { /** @format byte */ nextKey?: string; /** @format uint64 */ total?: string; } /** * Proposal defines the core field members of a governance proposal. */ export interface V1Beta1Proposal { /** @format uint64 */ proposalId?: string; /** * `Any` contains an arbitrary serialized protocol buffer message along with a * URL that describes the type of the serialized message. * * Protobuf library provides support to pack/unpack Any values in the form * of utility functions or additional generated methods of the Any type. * * Example 1: Pack and unpack a message in C++. * * Foo foo = ...; * Any any; * any.PackFrom(foo); * ... * if (any.UnpackTo(&foo)) { * ... * } * * Example 2: Pack and unpack a message in Java. * * Foo foo = ...; * Any any = Any.pack(foo); * ... * if (any.is(Foo.class)) { * foo = any.unpack(Foo.class); * } * * Example 3: Pack and unpack a message in Python. * * foo = Foo(...) * any = Any() * any.Pack(foo) * ... * if any.Is(Foo.DESCRIPTOR): * any.Unpack(foo) * ... * * Example 4: Pack and unpack a message in Go * * foo := &pb.Foo{...} * any, err := ptypes.MarshalAny(foo) * ... * foo := &pb.Foo{} * if err := ptypes.UnmarshalAny(any, foo); err != nil { * ... * } * * The pack methods provided by protobuf library will by default use * 'type.googleapis.com/full.type.name' as the type URL and the unpack * methods only use the fully qualified type name after the last '/' * in the type URL, for example "foo.bar.com/x/y.z" will yield type * name "y.z". * * * JSON * ==== * The JSON representation of an `Any` value uses the regular * representation of the deserialized, embedded message, with an * additional field `@type` which contains the type URL. Example: * * package google.profile; * message Person { * string first_name = 1; * string last_name = 2; * } * * { * "@type": "type.googleapis.com/google.profile.Person", * "firstName": <string>, * "lastName": <string> * } * * If the embedded message type is well-known and has a custom JSON * representation, that representation will be embedded adding a field * `value` which holds the custom JSON in addition to the `@type` * field. Example (for message [google.protobuf.Duration][]): * * { * "@type": "type.googleapis.com/google.protobuf.Duration", * "value": "1.212s" * } */ content?: ProtobufAny; /** * ProposalStatus enumerates the valid statuses of a proposal. * * - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. * - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit * period. * - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting * period. * - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has * passed. * - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has * been rejected. * - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has * failed. */ status?: V1Beta1ProposalStatus; /** TallyResult defines a standard tally for a governance proposal. */ finalTallyResult?: V1Beta1TallyResult; /** @format date-time */ submitTime?: string; /** @format date-time */ depositEndTime?: string; totalDeposit?: V1Beta1Coin[]; /** @format date-time */ votingStartTime?: string; /** @format date-time */ votingEndTime?: string; } /** * ProposalStatus enumerates the valid statuses of a proposal. - PROPOSAL_STATUS_UNSPECIFIED: PROPOSAL_STATUS_UNSPECIFIED defines the default propopsal status. - PROPOSAL_STATUS_DEPOSIT_PERIOD: PROPOSAL_STATUS_DEPOSIT_PERIOD defines a proposal status during the deposit period. - PROPOSAL_STATUS_VOTING_PERIOD: PROPOSAL_STATUS_VOTING_PERIOD defines a proposal status during the voting period. - PROPOSAL_STATUS_PASSED: PROPOSAL_STATUS_PASSED defines a proposal status of a proposal that has passed. - PROPOSAL_STATUS_REJECTED: PROPOSAL_STATUS_REJECTED defines a proposal status of a proposal that has been rejected. - PROPOSAL_STATUS_FAILED: PROPOSAL_STATUS_FAILED defines a proposal status of a proposal that has failed. */ export enum V1Beta1ProposalStatus { PROPOSAL_STATUS_UNSPECIFIED = "PROPOSAL_STATUS_UNSPECIFIED", PROPOSAL_STATUS_DEPOSIT_PERIOD = "PROPOSAL_STATUS_DEPOSIT_PERIOD", PROPOSAL_STATUS_VOTING_PERIOD = "PROPOSAL_STATUS_VOTING_PERIOD", PROPOSAL_STATUS_PASSED = "PROPOSAL_STATUS_PASSED", PROPOSAL_STATUS_REJECTED = "PROPOSAL_STATUS_REJECTED", PROPOSAL_STATUS_FAILED = "PROPOSAL_STATUS_FAILED", } /** * QueryDepositResponse is the response type for the Query/Deposit RPC method. */ export interface V1Beta1QueryDepositResponse { /** deposit defines the requested deposit. */ deposit?: V1Beta1Deposit; } /** * QueryDepositsResponse is the response type for the Query/Deposits RPC method. */ export interface V1Beta1QueryDepositsResponse { deposits?: V1Beta1Deposit[]; /** pagination defines the pagination in the response. */ pagination?: V1Beta1PageResponse; } /** * QueryParamsResponse is the response type for the Query/Params RPC method. */ export interface V1Beta1QueryParamsResponse { /** voting_params defines the parameters related to voting. */ votingParams?: V1Beta1VotingParams; /** deposit_params defines the parameters related to deposit. */ depositParams?: V1Beta1DepositParams; /** tally_params defines the parameters related to tally. */ tallyParams?: V1Beta1TallyParams; } /** * QueryProposalResponse is the response type for the Query/Proposal RPC method. */ export interface V1Beta1QueryProposalResponse { /** Proposal defines the core field members of a governance proposal. */ proposal?: V1Beta1Proposal; } /** * QueryProposalsResponse is the response type for the Query/Proposals RPC method. */ export interface V1Beta1QueryProposalsResponse { proposals?: V1Beta1Proposal[]; /** pagination defines the pagination in the response. */ pagination?: V1Beta1PageResponse; } /** * QueryTallyResultResponse is the response type for the Query/Tally RPC method. */ export interface V1Beta1QueryTallyResultResponse { /** tally defines the requested tally. */ tally?: V1Beta1TallyResult; } /** * QueryVoteResponse is the response type for the Query/Vote RPC method. */ export interface V1Beta1QueryVoteResponse { /** vote defined the queried vote. */ vote?: V1Beta1Vote; } /** * QueryVotesResponse is the response type for the Query/Votes RPC method. */ export interface V1Beta1QueryVotesResponse { /** votes defined the queried votes. */ votes?: V1Beta1Vote[]; /** pagination defines the pagination in the response. */ pagination?: V1Beta1PageResponse; } /** * TallyParams defines the params for tallying votes on governance proposals. */ export interface V1Beta1TallyParams { /** * Minimum percentage of total stake needed to vote for a result to be * considered valid. * @format byte */ quorum?: string; /** * Minimum proportion of Yes votes for proposal to pass. Default value: 0.5. * @format byte */ threshold?: string; /** * Minimum value of Veto votes to Total votes ratio for proposal to be * vetoed. Default value: 1/3. * @format byte */ vetoThreshold?: string; } /** * TallyResult defines a standard tally for a governance proposal. */ export interface V1Beta1TallyResult { yes?: string; abstain?: string; no?: string; noWithVeto?: string; } /** * Vote defines a vote on a governance proposal. A Vote consists of a proposal ID, the voter, and the vote option. */ export interface V1Beta1Vote { /** @format uint64 */ proposalId?: string; voter?: string; /** * VoteOption enumerates the valid vote options for a given governance proposal. * * - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. * - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. * - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. * - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. * - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. */ option?: V1Beta1VoteOption; } /** * VoteOption enumerates the valid vote options for a given governance proposal. - VOTE_OPTION_UNSPECIFIED: VOTE_OPTION_UNSPECIFIED defines a no-op vote option. - VOTE_OPTION_YES: VOTE_OPTION_YES defines a yes vote option. - VOTE_OPTION_ABSTAIN: VOTE_OPTION_ABSTAIN defines an abstain vote option. - VOTE_OPTION_NO: VOTE_OPTION_NO defines a no vote option. - VOTE_OPTION_NO_WITH_VETO: VOTE_OPTION_NO_WITH_VETO defines a no with veto vote option. */ export enum V1Beta1VoteOption { VOTE_OPTION_UNSPECIFIED = "VOTE_OPTION_UNSPECIFIED", VOTE_OPTION_YES = "VOTE_OPTION_YES", VOTE_OPTION_ABSTAIN = "VOTE_OPTION_ABSTAIN", VOTE_OPTION_NO = "VOTE_OPTION_NO", VOTE_OPTION_NO_WITH_VETO = "VOTE_OPTION_NO_WITH_VETO", } /** * VotingParams defines the params for voting on governance proposals. */ export interface V1Beta1VotingParams { /** Length of the voting period. */ votingPeriod?: string; } export type QueryParamsType = Record<string | number, any>; export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">; export interface FullRequestParams extends Omit<RequestInit, "body"> { /** set parameter to `true` for call `securityWorker` for this request */ secure?: boolean; /** request path */ path: string; /** content type of request body */ type?: ContentType; /** query params */ query?: QueryParamsType; /** format of response (i.e. response.json() -> format: "json") */ format?: keyof Omit<Body, "body" | "bodyUsed">; /** request body */ body?: unknown; /** base url */ baseUrl?: string; /** request cancellation token */ cancelToken?: CancelToken; } export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">; export interface ApiConfig<SecurityDataType = unknown> { baseUrl?: string; baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">; securityWorker?: (securityData: SecurityDataType) => RequestParams | void; } export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response { data: D; error: E; } type CancelToken = Symbol | string | number; export enum ContentType { Json = "application/json", FormData = "multipart/form-data", UrlEncoded = "application/x-www-form-urlencoded", } export class HttpClient<SecurityDataType = unknown> { public baseUrl: string = ""; private securityData: SecurityDataType = null as any; private securityWorker: null | ApiConfig<SecurityDataType>["securityWorker"] = null; private abortControllers = new Map<CancelToken, AbortController>(); private baseApiParams: RequestParams = { credentials: "same-origin", headers: {}, redirect: "follow", referrerPolicy: "no-referrer", }; constructor(apiConfig: ApiConfig<SecurityDataType> = {}) { Object.assign(this, apiConfig); } public setSecurityData = (data: SecurityDataType) => { this.securityData = data; }; private addQueryParam(query: QueryParamsType, key: string) { const value = query[key]; return ( encodeURIComponent(key) + "=" + encodeURIComponent(Array.isArray(value) ? value.join(",") : typeof value === "number" ? value : `${value}`) ); } protected toQueryString(rawQuery?: QueryParamsType): string { const query = rawQuery || {}; const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]); return keys .map((key) => typeof query[key] === "object" && !Array.isArray(query[key]) ? this.toQueryString(query[key] as QueryParamsType) : this.addQueryParam(query, key), ) .join("&"); } protected addQueryParams(rawQuery?: QueryParamsType): string { const queryString = this.toQueryString(rawQuery); return queryString ? `?${queryString}` : ""; } private contentFormatters: Record<ContentType, (input: any) => any> = { [ContentType.Json]: (input: any) => input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input, [ContentType.FormData]: (input: any) => Object.keys(input || {}).reduce((data, key) => { data.append(key, input[key]); return data; }, new FormData()), [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input), }; private mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams { return { ...this.baseApiParams, ...params1, ...(params2 || {}), headers: { ...(this.baseApiParams.headers || {}), ...(params1.headers || {}), ...((params2 && params2.headers) || {}), }, }; } private createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => { if (this.abortControllers.has(cancelToken)) { const abortController = this.abortControllers.get(cancelToken); if (abortController) { return abortController.signal; } return void 0; } const abortController = new AbortController(); this.abortControllers.set(cancelToken, abortController); return abortController.signal; }; public abortRequest = (cancelToken: CancelToken) => { const abortController = this.abortControllers.get(cancelToken); if (abortController) { abortController.abort(); this.abortControllers.delete(cancelToken); } }; public request = <T = any, E = any>({ body, secure, path, type, query, format = "json", baseUrl, cancelToken, ...params }: FullRequestParams): Promise<HttpResponse<T, E>> => { const secureParams = (secure && this.securityWorker && this.securityWorker(this.securityData)) || {}; const requestParams = this.mergeRequestParams(params, secureParams); const queryString = query && this.toQueryString(query); const payloadFormatter = this.contentFormatters[type || ContentType.Json]; return fetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, { ...requestParams, headers: { ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}), ...(requestParams.headers || {}), }, signal: cancelToken ? this.createAbortSignal(cancelToken) : void 0, body: typeof body === "undefined" || body === null ? null : payloadFormatter(body), }).then(async (response) => { const r = response as HttpResponse<T, E>; r.data = (null as unknown) as T; r.error = (null as unknown) as E; const data = await response[format]() .then((data) => { if (r.ok) { r.data = data; } else { r.error = data; } return r; }) .catch((e) => { r.error = e; return r; }); if (cancelToken) { this.abortControllers.delete(cancelToken); } if (!response.ok) throw data; return data; }); }; } /** * @title cosmos/gov/v1beta1/genesis.proto * @version version not set */ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> { /** * No description * * @tags Query * @name QueryParams * @summary Params queries all parameters of the gov module. * @request GET:/cosmos/gov/v1beta1/params/{paramsType} */ queryParams = (paramsType: string, params: RequestParams = {}) => this.request<V1Beta1QueryParamsResponse, RpcStatus>({ path: `/cosmos/gov/v1beta1/params/${paramsType}`, method: "GET", format: "json", ...params, }); /** * No description * * @tags Query * @name QueryProposals * @summary Proposals queries all proposals based on given status. * @request GET:/cosmos/gov/v1beta1/proposals */ queryProposals = ( query?: { proposalStatus?: | "PROPOSAL_STATUS_UNSPECIFIED" | "PROPOSAL_STATUS_DEPOSIT_PERIOD" | "PROPOSAL_STATUS_VOTING_PERIOD" | "PROPOSAL_STATUS_PASSED" | "PROPOSAL_STATUS_REJECTED" | "PROPOSAL_STATUS_FAILED"; voter?: string; depositor?: string; "pagination.key"?: string; "pagination.offset"?: string; "pagination.limit"?: string; "pagination.countTotal"?: boolean; }, params: RequestParams = {}, ) => this.request<V1Beta1QueryProposalsResponse, RpcStatus>({ path: `/cosmos/gov/v1beta1/proposals`, method: "GET", query: query, format: "json", ...params, }); /** * No description * * @tags Query * @name QueryProposal * @summary Proposal queries proposal details based on ProposalID. * @request GET:/cosmos/gov/v1beta1/proposals/{proposalId} */ queryProposal = (proposalId: string, params: RequestParams = {}) => this.request<V1Beta1QueryProposalResponse, RpcStatus>({ path: `/cosmos/gov/v1beta1/proposals/${proposalId}`, method: "GET", format: "json", ...params, }); /** * No description * * @tags Query * @name QueryDeposits * @summary Deposits queries all deposits of a single proposal. * @request GET:/cosmos/gov/v1beta1/proposals/{proposalId}/deposits */ queryDeposits = ( proposalId: string, query?: { "pagination.key"?: string; "pagination.offset"?: string; "pagination.limit"?: string; "pagination.countTotal"?: boolean; }, params: RequestParams = {}, ) => this.request<V1Beta1QueryDepositsResponse, RpcStatus>({ path: `/cosmos/gov/v1beta1/proposals/${proposalId}/deposits`, method: "GET", query: query, format: "json", ...params, }); /** * No description * * @tags Query * @name QueryDeposit * @summary Deposit queries single deposit information based proposalID, depositAddr. * @request GET:/cosmos/gov/v1beta1/proposals/{proposalId}/deposits/{depositor} */ queryDeposit = (proposalId: string, depositor: string, params: RequestParams = {}) => this.request<V1Beta1QueryDepositResponse, RpcStatus>({ path: `/cosmos/gov/v1beta1/proposals/${proposalId}/deposits/${depositor}`, method: "GET", format: "json", ...params, }); /** * No description * * @tags Query * @name QueryTallyResult * @summary TallyResult queries the tally of a proposal vote. * @request GET:/cosmos/gov/v1beta1/proposals/{proposalId}/tally */ queryTallyResult = (proposalId: string, params: RequestParams = {}) => this.request<V1Beta1QueryTallyResultResponse, RpcStatus>({ path: `/cosmos/gov/v1beta1/proposals/${proposalId}/tally`, method: "GET", format: "json", ...params, }); /** * No description * * @tags Query * @name QueryVotes * @summary Votes queries votes of a given proposal. * @request GET:/cosmos/gov/v1beta1/proposals/{proposalId}/votes */ queryVotes = ( proposalId: string, query?: { "pagination.key"?: string; "pagination.offset"?: string; "pagination.limit"?: string; "pagination.countTotal"?: boolean; }, params: RequestParams = {}, ) => this.request<V1Beta1QueryVotesResponse, RpcStatus>({ path: `/cosmos/gov/v1beta1/proposals/${proposalId}/votes`, method: "GET", query: query, format: "json", ...params, }); /** * No description * * @tags Query * @name QueryVote * @summary Vote queries voted information based on proposalID, voterAddr. * @request GET:/cosmos/gov/v1beta1/proposals/{proposalId}/votes/{voter} */ queryVote = (proposalId: string, voter: string, params: RequestParams = {}) => this.request<V1Beta1QueryVoteResponse, RpcStatus>({ path: `/cosmos/gov/v1beta1/proposals/${proposalId}/votes/${voter}`, method: "GET", format: "json", ...params, }); }
the_stack
import * as vscode from 'vscode'; import * as path from 'path'; import * as yaml from 'js-yaml'; import * as _ from 'lodash'; import { FS } from './fs'; import { Host } from './host'; import { isKubernetesExplorerResourceNode } from './components/clusterexplorer/explorer'; import { helmCreateCore } from './helm.exec'; import { failed, Errorable } from './errorable'; import { symbolAt, containmentChain, findKeyPath, FoundKeyPath, HelmDocumentSymbolProvider } from './helm.symbolProvider'; import { ClusterExplorerResourceNode } from './components/clusterexplorer/node'; import * as cancellation from './utils/cancellation'; interface Context { readonly fs: FS; readonly host: Host; readonly projectPath: string; } interface Chart { name: string; path: string; } export async function convertToTemplate(fs: FS, host: Host, projectPath: string, target: vscode.Uri | ClusterExplorerResourceNode | undefined): Promise<void> { const context = { fs, host, projectPath }; const activeDocument = host.activeDocument(); if (isKubernetesExplorerResourceNode(target)) { // it's a k8s explorer click const uri = target.uri('yaml'); const yaml = (await host.readDocument(uri)).getText(); addChart(context, yaml); } else if (target) { // it's a file explorer click addChartFrom(context, target.fsPath); } else if (activeDocument) { addChart(context, activeDocument.getText()); } else { host.showErrorMessage("This command requires a YAML file open or selected in the Explorer."); } } async function addChartFrom(context: Context, fsPath: string): Promise<void> { const yaml = context.fs.readFileSync(fsPath, 'utf-8'); await addChart(context, yaml); } async function addChart(context: Context, resourceYaml: string): Promise<void> { // TODO: check text is valid YAML const chart = await pickOrCreateChart(context); if (!chart) { return; } const template = yaml.safeLoad(resourceYaml); templatise(template); // TODO: offer a default const templateName = await context.host.showInputBox({ prompt: "Name for the new template" }); if (!templateName) { return; } const templateFile = path.join(chart.path, "templates", templateName + ".yaml"); // TODO: check if file already exists const templateYaml = yaml.safeDump(template); // the parse-dump cycle can change the indentation of collections - is this an issue? const templateText = fixYamlValueQuoting(templateYaml); context.fs.writeFileSync(templateFile, templateText); await context.host.showDocument(vscode.Uri.file(templateFile)); } enum QuoteMode { None, Double, } const NAME_EXPRESSION = '{{ template "fullname" . }}'; const CHART_LABEL_EXPRESSION = '{{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}'; const QUOTE_CONTROL_INFO = [ { text: NAME_EXPRESSION, mode: QuoteMode.None }, { text: CHART_LABEL_EXPRESSION, mode: QuoteMode.Double }, ]; function templatise(template: any): void { ensureMetadata(template); cleanseMetadata(template.metadata); template.metadata.name = NAME_EXPRESSION; template.metadata.labels.chart = CHART_LABEL_EXPRESSION; delete template.status; } function ensureMetadata(template: any): void { template.metadata = template.metadata || {}; template.metadata.labels = template.metadata.labels || {}; } const ANNOTATIONS_TO_STRIP = [ 'kubectl.kubernetes.io/last-applied-configuration' ]; function cleanseMetadata(metadata: any): void { delete metadata.clusterName; delete metadata.creationTimestamp; delete metadata.deletionTimestamp; delete metadata.generation; delete metadata.generateName; delete metadata.namespace; delete metadata.resourceVersion; delete metadata.selfLink; delete metadata.uid; if (metadata.annotations) { for (const annotation of ANNOTATIONS_TO_STRIP) { delete metadata.annotations[annotation]; } } } function chartsInProject(context: Context): Chart[] { const fs = context.fs; return subdirectories(fs, context.projectPath) .filter((d) => fs.existsSync(path.join(d, "Chart.yaml"))) .map((d) => ({ name: path.basename(d), path: d })); } function subdirectories(fs: FS, directory: string): string[] { const immediate = fs.dirSync(directory) .map((e) => path.join(directory, e)) .filter((e) => fs.statSync(e).isDirectory()); const indirect = immediate.map((d) => subdirectories(fs, d)); return immediate.concat(...indirect); } async function pickOrCreateChart(context: Context): Promise<Chart | undefined> { // TODO: refactor helmexec.pickChart so we can leverage it here const charts = chartsInProject(context); switch (charts.length) { case 0: return await createChart(context); case 1: return charts[0]; default: const chartPicks = charts.map((c) => ({ label: c.name, chart: c })); const pick = await context.host.showQuickPick(chartPicks, { placeHolder: 'Select chart to add the new template to' }); return pick ? pick.chart : undefined; } } function fixYamlValueQuoting(yamlText: string): string { let text = yamlText; for (const expr of QUOTE_CONTROL_INFO) { const q = expr.mode === QuoteMode.Double ? '"' : ''; text = text.replace(`'${expr.text}'`, `${q}${expr.text}${q}`); } return text; } async function createChart(context: Context): Promise<Chart | undefined> { const createResult = await helmCreateCore("No chart found. Enter name of the chart to create.", "mychart"); if (!createResult) { return undefined; } if (failed(createResult)) { context.host.showErrorMessage(createResult.error[0]); return undefined; } return createResult.result; } export interface ValueInsertion { readonly document: vscode.TextDocument; readonly keyPath: string[]; readonly edit: vscode.TextEdit; } export interface TextEdit { readonly document: vscode.TextDocument; readonly edits: vscode.TextEdit[]; } export async function convertToParameter(fs: FS, host: Host, document: vscode.TextDocument, selection: vscode.Selection): Promise<Errorable<ValueInsertion>> { const helmSymbols = await getHelmSymbols(document); if (helmSymbols.length === 0) { return { succeeded: false, error: ['Active document is not a Helm template'] }; } const property = symbolAt(selection.anchor, helmSymbols); if (!property || property.kind !== vscode.SymbolKind.Constant) { return { succeeded: false, error: ['Selection is not a YAML field'] }; } const templateName = path.parse(document.fileName).name; const valueLocation = property.location.range; const valueText = document.getText(valueLocation); const valueSymbolContainmentChain = containmentChain(property, helmSymbols); if (valueSymbolContainmentChain.length === 0) { return { succeeded: false, error: ['Cannot locate property name'] }; } const rawKeyPath = [templateName, valueSymbolContainmentChain[0].name]; const keyPath = rawKeyPath.map(sanitiseForGoTemplate); const insertParamEdit = await addEntryToValuesFile(fs, host, document, keyPath, valueText); if (failed(insertParamEdit)) { return { succeeded: false, error: insertParamEdit.error }; } const keyReference = keyPath.join('.'); const replaceValueWithParamRef = new vscode.TextEdit(valueLocation, `{{ .Values.${keyReference} }}`); const appliedEdits = await applyEdits( { document: document, edits: [replaceValueWithParamRef] }, { document: insertParamEdit.result.document, edits: [insertParamEdit.result.edit] } ); if (!appliedEdits) { return { succeeded: false, error: ['Unable to update the template and/or values file'] }; } return { succeeded: true, result: insertParamEdit.result }; } async function applyEdits(...edits: TextEdit[]): Promise<boolean> { const wsEdit = new vscode.WorkspaceEdit(); for (const e of edits) { wsEdit.set(e.document.uri, e.edits); } return await vscode.workspace.applyEdit(wsEdit); } async function getHelmSymbols(document: vscode.TextDocument): Promise<vscode.SymbolInformation[]> { const symbolProvider = new HelmDocumentSymbolProvider(); const symbols = await symbolProvider.provideDocumentSymbolsImpl(document, cancellation.dummyToken()); return symbols; } async function addEntryToValuesFile(fs: FS, host: Host, template: vscode.TextDocument, keyPath: string[], value: string): Promise<Errorable<ValueInsertion>> { const valuesYamlPath = path.normalize(path.join(path.dirname(template.fileName), '..', 'values.yaml')); if (!fs.existsSync(valuesYamlPath)) { fs.writeFileSync(valuesYamlPath, ''); } const valuesYamlDoc = await host.readDocument(vscode.Uri.file(valuesYamlPath)); const valuesYamlAst = await getHelmSymbols(valuesYamlDoc); const whatWeHave = findCreatableKeyPath(keyPath, valuesYamlAst); const insertion = addToYaml(valuesYamlDoc, valuesYamlAst, whatWeHave.found, whatWeHave.remaining, value); return { succeeded: true, result: insertion }; } function findCreatableKeyPath(keyPath: string[], ast: vscode.SymbolInformation[]): FoundKeyPath { const foundPath = findKeyPath(keyPath, ast); if (foundPath.remaining.length > 0) { return foundPath; } const disambiguatingPath = disambiguateKeyPath(keyPath); const foundDisambiguatingPath = findKeyPath(disambiguatingPath, ast); if (foundDisambiguatingPath.remaining.length > 0) { return foundDisambiguatingPath; } return findCreatableKeyPathBySuffixing(keyPath, ast, 1); } function disambiguateKeyPath(keyPath: string[]): string[] { const path = keyPath.slice(0, keyPath.length - 1); const disambiguatedFinal = keyPath.join('_'); path.push(disambiguatedFinal); return path; } function findCreatableKeyPathBySuffixing(keyPath: string[], ast: vscode.SymbolInformation[], suffix: number): FoundKeyPath { const path = keyPath.slice(0, keyPath.length - 1); const suffixedFinal = keyPath[keyPath.length - 1] + suffix.toString(); path.push(suffixedFinal); const foundPath = findKeyPath(path, ast); if (foundPath.remaining.length > 0) { return foundPath; } return findCreatableKeyPathBySuffixing(keyPath, ast, suffix + 1); } function addToYaml(document: vscode.TextDocument, ast: vscode.SymbolInformation[], parent: vscode.SymbolInformation | undefined, keys: string[], value: string): ValueInsertion { const eol = document.eol === vscode.EndOfLine.CRLF ? '\r\n' : '\n'; if (parent) { // TODO: do we need to handle the possibility of a parent node without any child nodes? const before = firstChild(document, parent, ast); return insertBefore(document, before, keys, value, eol); } else { // TODO: handle the case where the document is entirely empty const before = firstChild(document, undefined, ast); return insertBefore(document, before, keys, value, eol); } } function firstChild(document: vscode.TextDocument, parent: vscode.SymbolInformation | undefined, ast: vscode.SymbolInformation[]): vscode.SymbolInformation | undefined { const isDescendant = parent ? (n: vscode.SymbolInformation) => parent.location.range.contains(n.location.range) : (_n: vscode.SymbolInformation) => true; const linearPos = (p: vscode.Position) => document.offsetAt(p); return _.chain(ast) .filter(isDescendant) .filter((n) => n !== parent) .filter((n) => n.kind === vscode.SymbolKind.Field) .orderBy([(n) => linearPos(n.location.range.start), (n) => linearPos(n.location.range.end)]) .first() .value(); } function insertBefore(document: vscode.TextDocument, element: vscode.SymbolInformation | undefined, keys: string[], value: string, eol: string): ValueInsertion { const insertAt = element ? lineStart(element.location.range.start) : document.positionAt(0); const indent = indentLevel(element); const text = makeTree(indent, keys, value, eol); const edit = vscode.TextEdit.insert(insertAt, text); return { document: document, keyPath: keys, edit: edit }; } function lineStart(pos: vscode.Position): vscode.Position { return new vscode.Position(pos.line, 0); } function indentLevel(element: vscode.SymbolInformation | undefined): number { return element ? element.location.range.start.character : 0; } function makeTree(indentLevel: number, keys: string[], value: string, eol: string): string { if (keys.length < 1) { return ''; } const indent = ' '.repeat(indentLevel); if (keys.length === 1) { return `${indent}${keys[0]}: ${value}${eol}`; } const subtree = makeTree(indentLevel + 2, keys.slice(1), value, eol); return `${indent}${keys[0]}:${eol}${subtree}`; } function sanitiseForGoTemplate(s: string): string { return s.replace(/-./g, (h) => h.substring(1).toUpperCase()); }
the_stack
import {PolymerElement, html} from '@polymer/polymer'; import {customElement, observe, property} from '@polymer/decorators'; import '../../../components/polymer/irons_and_papers'; import '../tf_graph_info/tf-graph-info'; import '../tf_graph/tf-graph'; import * as tf_graph from '../tf_graph_common/graph'; import * as tf_graph_render from '../tf_graph_common/render'; import {LegacyElementMixin} from '../../../components/polymer/legacy_element_mixin'; import {ColorBy} from '../tf_graph_common/view_types'; import * as tf_graph_hierarchy from '../tf_graph_common/hierarchy'; /** * Some UX features, such as 'color by structure', rely on the 'template' * information of a graph. This can be very expensive to compute when the * graph is too large. This object's constants determine what constitutes * a 'large' graph. Graphs that exceed all these constraints should not * have templates computed by default. */ const maxGraphSizeToComputeTemplates = { MAX_NODE_COUNT: 10000, MAX_EDGE_COUNT: 10000, }; /** * Element for putting tf-graph and tf-graph-info side by side. * * Example * <tf-graph-board graph=[[graph]]></tf-graph-board> */ @customElement('tf-graph-board') class TfGraphBoard extends LegacyElementMixin(PolymerElement) { static readonly template = html` <style> ::host { display: block; } /deep/ .close { position: absolute; cursor: pointer; left: 15px; bottom: 15px; } .container { width: 100%; height: 100%; opacity: 1; } .container.loading { cursor: progress; opacity: 0.1; } .container.loading.error { cursor: auto; } #info { position: absolute; right: 5px; top: 5px; padding: 0px; max-width: 380px; min-width: 320px; background-color: rgba(255, 255, 255, 0.9); @apply --shadow-elevation-2dp; } #main { width: 100%; height: 100%; } #progress-bar { display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; position: absolute; top: 40px; left: 0; font-size: 13px; } #progress-msg { margin-bottom: 5px; white-space: pre-wrap; width: 400px; } paper-progress { width: 400px; --paper-progress-height: 6px; --paper-progress-active-color: #f3913e; } .context-menu { position: absolute; display: none; background-color: #e2e2e2; border-radius: 2px; font-size: 14px; min-width: 150px; border: 1px solid #d4d4d4; } /deep/ .context-menu ul { list-style-type: none; margin: 0; padding: 0; cursor: default; } /deep/ .context-menu ul li { padding: 4px 16px; } /deep/ .context-menu ul li:hover { background-color: #f3913e; color: white; } </style> <template is="dom-if" if="[[_isNotComplete(progress)]]"> <div id="progress-bar"> <div id="progress-msg">[[progress.msg]]</div> <paper-progress value="[[progress.value]]"></paper-progress> </div> </template> <div class$="[[_getContainerClass(progress)]]"> <div id="main"> <tf-graph id="graph" graph-hierarchy="{{graphHierarchy}}" basic-graph="[[graph]]" hierarchy-params="[[hierarchyParams]]" render-hierarchy="{{renderHierarchy}}" devices-for-stats="[[devicesForStats]]" stats="[[stats]]" selected-node="{{selectedNode}}" highlighted-node="{{_highlightedNode}}" color-by="[[colorBy]]" color-by-params="{{colorByParams}}" progress="{{progress}}" edge-label-function="[[edgeLabelFunction]]" edge-width-function="[[edgeWidthFunction]]" node-names-to-health-pills="[[nodeNamesToHealthPills]]" health-pill-step-index="[[healthPillStepIndex]]" handle-node-selected="[[handleNodeSelected]]" handle-edge-selected="[[handleEdgeSelected]]" trace-inputs="[[traceInputs]]" auto-extract-nodes="[[autoExtractNodes]]" ></tf-graph> </div> <div id="info"> <tf-graph-info id="graph-info" title="selected" graph-hierarchy="[[graphHierarchy]]" render-hierarchy="[[renderHierarchy]]" graph="[[graph]]" selected-node="{{selectedNode}}" selected-node-include="{{_selectedNodeInclude}}" highlighted-node="{{_highlightedNode}}" color-by="[[colorBy]]" color-by-params="[[colorByParams]]" debugger-data-enabled="[[debuggerDataEnabled]]" are-health-pills-loading="[[areHealthPillsLoading]]" debugger-numeric-alerts="[[debuggerNumericAlerts]]" node-names-to-health-pills="[[nodeNamesToHealthPills]]" all-steps-mode-enabled="{{allStepsModeEnabled}}" specific-health-pill-step="{{specificHealthPillStep}}" health-pill-step-index="{{healthPillStepIndex}}" compat-node-title="[[compatNodeTitle]]" on-node-toggle-inclusion="_onNodeInclusionToggled" on-node-toggle-seriesgroup="_onNodeSeriesGroupToggled" ></tf-graph-info> </div> </div> `; @property({type: Object}) graphHierarchy: tf_graph_hierarchy.Hierarchy; @property({type: Object}) graph: tf_graph.SlimGraph; // TODO(psybuzz): ideally, this would be a required property and the component // that owns <tf-graph-board> and the graph loader should create these params. @property({type: Object}) hierarchyParams: tf_graph_hierarchy.HierarchyParams = tf_graph_hierarchy.DefaultHierarchyParams; @property({type: Object}) stats: object; /** * A number between 0 and 100 denoting the % of progress * for the progress bar and the displayed message. * @type {{value: number, msg: string}} */ @property({type: Object}) progress: object; @property({type: Boolean}) traceInputs: boolean; @property({type: Boolean}) autoExtractNodes: boolean; @property({ type: String, notify: true, }) colorBy: ColorBy; @property({ type: Object, notify: true, }) colorByParams: object; @property({ type: Object, notify: true, }) renderHierarchy: tf_graph_render.RenderGraphInfo; // Whether debugger data is enabled for this instance of Tensorboard. @property({type: Boolean}) debuggerDataEnabled: boolean; // Whether health pills are currently being loaded. @property({type: Boolean}) areHealthPillsLoading: boolean; @property({ type: Array, notify: true, }) // An array of alerts (in chronological order) provided by debugging libraries on when bad // values (NaN, +/- Inf) appear. debuggerNumericAlerts: unknown[]; @property({type: Object}) // A mapping between node name to the tf.graph.scene.HealthPill to render. nodeNamesToHealthPills: object; // Whether the user can request health pills for individual steps from the server. This can be // slow compared the default of showing sampled health pills. @property({ type: Boolean, notify: true, }) allStepsModeEnabled: boolean = false; // Relevant if allStepsModeEnabled. The specific step for which to fetch health pills from the // server for. @property({ type: Number, notify: true, }) specificHealthPillStep: number = 0; // The step of health pills to show throughout the graph. @property({type: Number}) healthPillStepIndex: number; @property({ type: String, notify: true, }) selectedNode: string; @property({ type: String, }) compatNodeTitle: string = 'TPU Compatibility'; // A function with signature EdgeThicknessFunction that computes the // thickness of a given edge. @property({type: Object}) edgeWidthFunction: object; // The enum value of the include property of the selected node. @property({type: Number}) _selectedNodeInclude: number; @property({type: String}) _highlightedNode: string; // An optional function that takes a node selected event (whose `detail` // property is the selected node ... which could be null if a node is // deselected). Called whenever a node is selected or deselected. @property({type: Object}) handleNodeSelected: object; // An optional function that computes the label for an edge. Should // implement the EdgeLabelFunction signature. @property({type: Object}) edgeLabelFunction: object; // An optional callback that implements the tf.graph.edge.EdgeSelectionCallback signature. If // provided, edges are selectable, and this callback is run when an edge is selected. @property({type: Object}) handleEdgeSelected: object; fit() { (this.$.graph as any).fit(); } async downloadAsImage(filename: string) { const blob = await (this.$.graph as any).getImageBlob(); const element = document.createElement('a'); (element as any).href = (URL as any).createObjectURL(blob); element.download = filename; element.click(); URL.revokeObjectURL(element.href); } /** True if the progress is not complete yet (< 100 %). */ _isNotComplete(progress) { return progress.value < 100; } _getContainerClass(progress) { var result = 'container'; if (progress.error) { result += ' error'; } if (this._isNotComplete(progress)) { result += ' loading'; } return result; } _onNodeInclusionToggled(event) { (this.$.graph as any).nodeToggleExtract(event.detail.name); } _onNodeSeriesGroupToggled(event) { (this.$.graph as any).nodeToggleSeriesGroup(event.detail.name); } @observe('selectedNode', 'renderHierarchy') _updateNodeInclude() { const node = !this.renderHierarchy ? null : this.renderHierarchy.getNodeByName(this.selectedNode); this._selectedNodeInclude = node ? node.include : tf_graph.InclusionType.UNSPECIFIED; } @observe('graph') _slimGraphChanged() { // By default, avoid coloring by 'structure' for large graphs, since it may be very expensive. // Color by 'structure' is still available to users via explicit gesture. if (!this.graph) { return; } const {MAX_NODE_COUNT, MAX_EDGE_COUNT} = maxGraphSizeToComputeTemplates; const isGraphTooLarge = Object.keys(this.graph.nodes).length > MAX_NODE_COUNT && this.graph.edges.length > MAX_EDGE_COUNT; if (isGraphTooLarge && this.colorBy === ColorBy.STRUCTURE) { this.colorBy = ColorBy.NONE; } } @observe('colorBy', 'graphHierarchy') _ensureTemplates() { if (!this.graphHierarchy || this.colorBy !== ColorBy.STRUCTURE) { return; } if (this.graphHierarchy.getTemplateIndex()) { return; } this.graphHierarchy.updateTemplates(); } }
the_stack
import { TriangleDown } from "lib/Icons/TriangleDown" import { Autocomplete } from "lib/utils/Autocomplete" import { CloseIcon, Flex, Separator, Text, Touchable, useColor, useTextStyleForPalette } from "palette" import React, { useEffect, useMemo, useRef, useState } from "react" import { FlatList, TextInput, TouchableOpacity } from "react-native" import { FancyModal } from "../../../lib/Components/FancyModal/FancyModal" import { SearchInput } from "../../../lib/Components/SearchInput" import { INPUT_HEIGHT, InputTitle } from "../Input" export interface SelectOption<ValueType> { value: ValueType label: NonNullable<React.ReactNode> searchTerms?: string[] searchImportance?: number } export interface SelectProps<ValueType> { options: Array<SelectOption<ValueType>> value: ValueType | null placeholder?: string title: string showTitleLabel?: boolean optional?: boolean required?: boolean subTitle?: string enableSearch?: boolean maxModalHeight?: number hasError?: boolean testID?: string onSelectValue(value: ValueType, index: number): void renderButton?(args: { selectedValue: ValueType | null; onPress(): void }): JSX.Element renderItemLabel?(value: SelectOption<ValueType>): JSX.Element onModalFinishedClosing?(): void } export const Select = <ValueType,>({ options, value, placeholder, title, showTitleLabel = true, optional, required, subTitle, enableSearch, maxModalHeight, hasError, onSelectValue, renderButton, renderItemLabel, onModalFinishedClosing, testID, }: SelectProps<ValueType>) => { const [showingModal, setShowingModal] = useState(false) // tinkering with RN internals here to make sure that when this select is tapped we blur // any text input that was focuesd at the time. const blurAllOtherInputs = async () => { const inputRef = TextInput.State.currentlyFocusedInput() if (inputRef) { TextInput.State.blurTextInput(inputRef) await new Promise((r) => requestAnimationFrame(r)) } } const open = async () => { await blurAllOtherInputs() setShowingModal(true) } const close = () => { setShowingModal(false) } const selectedItem = options.find((o) => o.value === value) return ( <> {renderButton?.({ selectedValue: selectedItem?.value ?? null, onPress: open }) ?? ( <SelectButton testID={testID} title={title} showTitleLabel={showTitleLabel} subTitle={subTitle} placeholder={placeholder} value={selectedItem?.label} onPress={open} optional={optional} required={required} hasError={hasError} /> )} <SelectModal visible={showingModal} title={title} enableSearch={enableSearch} value={value} options={options} maxHeight={maxModalHeight} onDismiss={close} onSelectValue={onSelectValue} renderItemLabel={renderItemLabel} onModalFinishedClosing={onModalFinishedClosing} /> </> ) } const SelectButton: React.FC<{ value?: React.ReactNode title?: string showTitleLabel?: boolean subTitle?: string optional?: boolean required?: boolean placeholder?: string hasError?: boolean testID?: string onPress(): void }> = ({ value, placeholder, onPress, title, showTitleLabel, optional, required, subTitle, hasError, testID }) => { const color = useColor() const textStyle = useTextStyleForPalette("sm") return ( <Flex> {!!showTitleLabel && ( <InputTitle optional={optional} required={required}> {title} </InputTitle> )} {!!subTitle && ( <Text variant="xs" color="black60" mb={0.5}> {subTitle} </Text> )} <TouchableOpacity accessible accessibilityRole="button" onPress={onPress} testID={testID}> <Flex px="1" flexDirection="row" height={INPUT_HEIGHT} borderWidth={1} borderColor={hasError ? color("red100") : color("black10")} justifyContent="space-between" alignItems="center" > <Text style={textStyle} color={value ? "black100" : "black60"} mr={0.5}> {value ?? placeholder ?? "Pick an option"} </Text> <TriangleDown /> </Flex> </TouchableOpacity> </Flex> ) } const SelectModal: React.FC<{ options: Array<SelectOption<unknown>> value: unknown | null title: string enableSearch?: boolean visible: boolean maxHeight?: number onDismiss(): any onSelectValue(value: unknown, index: number): any renderItemLabel?(value: SelectOption<unknown>): JSX.Element onModalFinishedClosing?(): void }> = ({ options, value, title, enableSearch, visible, maxHeight, onDismiss, onSelectValue, renderItemLabel, onModalFinishedClosing, }) => { const color = useColor() // we need to be able to have a local version of the value state so we can show the updated // state between the moment the user taps a selection and the moment we automatically // close the modal. We don't want to tell the consuming component about the user's selection until the // animation is finished, so they don't have to worry about waiting for the animation to finish if they need // to trigger further actions as a result. const [localValue, setValue] = useState(value) useEffect(() => { setValue(value) }, [value]) const selectedItem = options.find((o) => o.value === localValue) const autocomplete = useMemo(() => { return enableSearch ? new Autocomplete<SelectOption<unknown>>( options.map((option) => { if (!option.searchTerms || option.searchTerms.length === 0) { console.error("Option with empty search terms: " + JSON.stringify(option)) return { searchTerms: [], importance: 0, key: option } } return { searchTerms: option.searchTerms, importance: option.searchImportance ?? 0, key: option } }) ) : null }, [enableSearch, options]) const [searchTerm, setSearchTerm] = useState("") // reset the search term whenever we show the modal useEffect(() => { if (visible) { setSearchTerm("") } }, [visible]) const autocompleteResults = useMemo(() => { return searchTerm && autocomplete ? autocomplete.getSuggestions(searchTerm) : options }, [autocomplete, searchTerm]) const flatListRef = useRef<FlatList>(null) const flatListHeight = useRef<number | null>(null) // scroll to show the selected value whenever we either clear the // search input, or show the modal. useEffect(() => { if (!visible) { return } if (!searchTerm.trim() && selectedItem) { const scrollToSelectedItem = async () => { let safety = 0 // wait for flat list to lay out while (flatListHeight.current == null && safety++ < 100) { await new Promise((r) => requestAnimationFrame(r)) } // search was cleared (or hasn't been touched yet) and the user has previously selected a value const initialScrollIndex = options.indexOf(selectedItem) // try to center the option on screen const initialScrollOffset = initialScrollIndex * INPUT_HEIGHT - (flatListHeight.current ?? 0) / 2 + INPUT_HEIGHT requestAnimationFrame(() => { flatListRef.current?.scrollToOffset({ offset: initialScrollOffset, animated: false }) }) } scrollToSelectedItem() } else { requestAnimationFrame(() => { flatListRef.current?.scrollToOffset({ offset: 0, animated: false }) }) } }, [searchTerm, visible]) return ( <FancyModal visible={visible} onBackgroundPressed={onDismiss} maxHeight={maxHeight} onModalFinishedClosing={onModalFinishedClosing} > <Flex p="2" pb={15} flexDirection="row" alignItems="center" flexGrow={0}> <Flex flex={1} /> <Flex flex={2} alignItems="center"> <Text>{title}</Text> </Flex> <TouchableOpacity onPress={onDismiss} hitSlop={{ top: 20, right: 20, bottom: 20, left: 20 }} style={{ flex: 1, alignItems: "flex-end" }} > <CloseIcon fill="black60" /> </TouchableOpacity> </Flex> {!!enableSearch && ( <Flex mb="1" mx="2"> <SearchInput placeholder="Type to search..." onChangeText={setSearchTerm} /> </Flex> )} <Separator /> <FlatList ref={flatListRef} keyboardDismissMode="on-drag" keyboardShouldPersistTaps="handled" data={autocompleteResults} extraData={{ value: localValue }} keyExtractor={(item) => String(item.value)} windowSize={4} contentContainerStyle={{ paddingTop: 10, paddingBottom: 60 }} // we handle scrolling to the selected value ourselves because FlatList has weird // rendering bugs when initialScrollIndex changes, at the time of writing initialScrollIndex={undefined} getItemLayout={(_item, index) => ({ index, length: INPUT_HEIGHT, offset: INPUT_HEIGHT * index })} style={{ flex: 1 }} onLayout={(e) => (flatListHeight.current = e.nativeEvent.layout.height)} renderItem={({ item, index }) => { const selected = localValue === item.value return ( <Touchable onPress={() => { setValue(item.value) onDismiss() onSelectValue(item.value, index) }} style={{ flexGrow: 0 }} testID="select-option" > <Flex flexDirection="row" pl="2" pr={15} justifyContent="space-between" height={INPUT_HEIGHT} alignItems="center" flexGrow={0} > {renderItemLabel?.(item) ?? ( <Text numberOfLines={1} ellipsizeMode="tail" color={selected ? color("blue100") : color("black100")} style={{ flexShrink: 1, textDecorationLine: selected ? "underline" : "none" }} > {item.label} </Text> )} </Flex> </Touchable> ) }} /> </FancyModal> ) }
the_stack
import * as t from '@/lib/io'; import { Extension, createExtensionContext, IExtensionContext, StateType, ExtensionData, ExtensionProps, FieldOptions, ReactiveDefinition, Setting, TypeOrOptions, } from '@/lib/framework/extensions'; import fs from '@/lib/fs'; import path from 'path'; import { GLOBAL_PATH, WORKSPACE_PATH, PROJECT_PATH } from '@/lib/framework/constants'; import { reverse, keys } from '@/lib/std'; import uuid from 'uuid'; import { ref } from '@vue/composition-api'; import { emitter } from '@/lib/events'; import { decodeItem } from '@/lib/io'; import { getLogger } from '@/lib/log'; const logger = getLogger('manager'); const events = emitter<{ setOpenedFile: [] }>(); // FIXME IF TWO instances of DAWG are opened at the same time // there will be an issue when writing to the fs because the // data is loaded on startup and written back at the end. Thus, // stuff can easily be overwritten export const PastProjectsType = t.partial({ projectPath: t.string, tempPath: t.string, }); // To try and parse the ID from the project file export const ProjectIdType = t.type({ id: t.string, }); type ProjectID = t.TypeOf<typeof ProjectIdType>; type PastProject = t.TypeOf<typeof PastProjectsType>; let pastProject: PastProject = {}; interface JSON { [k: string]: any; } const settings: Array<{ title: string, settings: Setting[] }> = []; const extensions: { [id: string]: any } = {}; const resolved: { [id: string]: boolean } = {}; const extensionsStack: Array< { extension: Extension, context: IExtensionContext } > = []; const makeAndRead = (file: string): JSON => { if (!fs.existsSync(file)) { logger.debug(`${file} does not exist and is being created`); const dir = path.dirname(file); fs.mkdirRecursiveSync(dir); fs.writeFileSync(file, JSON.stringify({})); } const contents = fs.readFileSync(file).toString(); return JSON.parse(contents); }; const write = async (file: string, contents: any) => { try { await fs.writeFile(file, JSON.stringify(contents, null, 4)); } catch (e) { logger.error(e.message); } }; const isState = (oo: TypeOrOptions): oo is StateType => { return (oo as any)._tag !== undefined; }; const isFieldOptions = (oo: TypeOrOptions): oo is FieldOptions<StateType> => { return (oo as any)._tag === undefined; }; const getPartialFromDefinition = (props: ExtensionProps) => { const partial: t.Props = {}; Object.keys(props).forEach((key) => { const fieldInformation = props[key]; partial[key] = isState(fieldInformation) ? fieldInformation : fieldInformation.type; }, {}); return t.partial(partial); }; const getDataFromExtensions = (key: 'workspace' | 'global'): { [k: string]: ExtensionData<ExtensionProps> } => { const data: { [k: string]: ExtensionData<ExtensionProps> } = {}; for (const { extension, context } of reverse(extensionsStack)) { try { const definition = extension[key]; if (!definition) { continue; } const state = context[key]; const toEncode: { [K in keyof typeof state]: t.TypeOf<StateType> | undefined } = {}; for (const k of keys(state)) { toEncode[k] = state[k].value; } const type = getPartialFromDefinition(definition); const encoded = type.encode(toEncode); data[extension.id] = encoded; } catch (e) { logger.warn('' + e); // If there is an error, don't write anything to the fs // This will basically invalidate the cache (for that particular extension) } } return data; }; const loadWorkspace = (projectId: string, file: string) => { const json = makeAndRead(file); if (!json[projectId]) { logger.debug(`${projectId} does not exist in the project cache`); return {}; } return json[projectId]; }; class Manager { public static fromFileSystem() { const result = t.read(PastProjectsType, { path: PROJECT_PATH }); if (result.type === 'error') { logger.error( `Unable to load previously opened project information. ` + `Opening blank project instead. Error message:` + result.message, ); } else if (result.type === 'not-found') { logger.info('Past project information not found. Opening a blank project!'); } else { pastProject = result.decoded; } const toOpen = pastProject.tempPath ? pastProject.tempPath : pastProject.projectPath; let projectContents: string | null = null; if (toOpen) { try { projectContents = fs.readFileSync(toOpen).toString(); } catch (e) { logger.error(`Unable to load project from ${toOpen}: ${e.message}`); } } const isTemp = !!pastProject.tempPath; // save this information for later if (pastProject.tempPath) { // Always remove temporary information once the file has been read // Even if there are errors we do this fs.unlink(pastProject.tempPath); // Make sure we don't overwrite the projectPath since tempPath takes priority pastProject.tempPath = undefined; // Btw no error handling here. If this fails there isn't much we can do anyway. t.write(PastProjectsType, { path: PROJECT_PATH, data: pastProject }); } let parsedProject: JSON | null = null; try { if (projectContents) { parsedProject = JSON.parse(projectContents); } } catch (e) { logger.error(`Unable to parse project ${toOpen}: ${e.message}`); } let info: ProjectInfo | null = null; if (parsedProject) { const r = decodeItem(ProjectIdType, parsedProject); if (r.type === 'success') { info = { // toOpen has to be defined at this point given that the project has been decoded path: toOpen!, id: r.decoded.id, }; } else { logger.error(`Unable to parse ID from project: ${toOpen}: ${r.message}`); } } if (!info) { info = { id: uuid.v4(), path: null }; } // We don't want to expose the path to the user when we open a tmp project. // We we some reason fail to load the temp project then this does nothing. // Since we this, when a user attempts to save, it will automatically open a save dialog. if (isTemp) { info.path = null; } let global: JSON = {}; let workspace: JSON = {}; try { global = makeAndRead(GLOBAL_PATH); } catch (e) { logger.error(`Unable to load global at ${GLOBAL_PATH}: ${e.message}`); } try { workspace = loadWorkspace(info.id, WORKSPACE_PATH); } catch (e) { logger.error(`Unable to load workspace at ${WORKSPACE_PATH}: ${e.message}`); } return new Manager(info, parsedProject, global, workspace); } constructor( public projectInfo: ProjectInfo, public readonly parsedProject: JSON | null, public readonly global: JSON, public readonly workspace: JSON, ) {} } export type ProjectInfo = { id: string, path: string } | { id: string, path: null }; const projectManager = Manager.fromFileSystem(); export const manager = { getOpenedFile() { return projectManager.projectInfo.path; }, getProjectJSON() { return projectManager.parsedProject; }, onDidSetOpenedFile(listener: () => void) { events.addListener('setOpenedFile', listener); return { dispose() { events.removeListener('setOpenedFile', listener); }, }; }, /** * Sets the path of the opened file and writes this information to the file system so that the next time the DAW is * opened, the correct file will open. Note that is NOT possible to change the ID of the currently opened project. * * @param projectPath The project path. * @param opts The options. */ setOpenedFile(projectPath?: string, opts: { isTemp?: boolean } = {}) { if (projectPath) { projectManager.projectInfo.path = projectPath; } else { projectManager.projectInfo = { id: projectManager.projectInfo.id, path: null, }; } if (opts.isTemp) { pastProject.tempPath = projectPath; } else { pastProject.projectPath = projectPath; } events.emit('setOpenedFile'); return t.write(PastProjectsType, { path: PROJECT_PATH, data: pastProject }); }, /** * To be called at the end right before the application closes. */ async dispose() { if (!projectManager) { return; } for (const e of reverse(extensionsStack)) { if (e.extension.deactivate) { try { await e.extension.deactivate(e.context); } catch (error) { logger.error(`Unable to deactivate ${e.extension.id}: ${error}`); } } e.context.subscriptions.forEach((subscription) => { try { subscription.dispose(); } catch (error) { logger.error(`Unable to deactivate subscription for ${e.extension.id}: ${error}`); } }); } const g = getDataFromExtensions('global'); const w = getDataFromExtensions('workspace'); // If there is no file set then do not write workspace to the fs because it is irrelevant if (projectManager.projectInfo.path) { projectManager.workspace[projectManager.projectInfo.id] = w; } await write(GLOBAL_PATH, g); await write(WORKSPACE_PATH, projectManager.workspace); }, activate<W extends ExtensionProps, G extends ExtensionProps, V>( extension: Extension<W, G, V>, ): V { logger.debug('Activating ' + extension.id); resolved[extension.id] = false; manager.activating.push(extension); const getOrEmptyObject = (o: JSON, key: string) => { return o[key] === undefined ? {} : o[key]; }; const makeReactive = < P extends ExtensionProps >(extensionProps: P | undefined, o: any) => { if (!extensionProps) { return {} as ReactiveDefinition<P>; } const type = getPartialFromDefinition(extensionProps); const result = t.decodeItem(type, o); let decoded: t.TypeOf<typeof type>; if (result.type === 'error') { logger.error(result.message); decoded = {}; } else { decoded = result.decoded; } const reactive = {} as ReactiveDefinition<P>; for (const key of keys(extensionProps)) { const props = extensionProps[key]; let decodedValue = decoded[key]; if (decodedValue === undefined && isFieldOptions(props)) { decodedValue = props.default; } // FIXME remove these weird casts reactive[key as keyof typeof reactive] = ref(decodedValue) as any; } return reactive; }; const w = getOrEmptyObject(projectManager.workspace, extension.id); const g = getOrEmptyObject(projectManager.global, extension.id); const reactiveWorkspace = makeReactive(extension.workspace, w); const reactiveGlobal = makeReactive(extension.global, g); const context = createExtensionContext<W, G>(reactiveWorkspace, reactiveGlobal); settings.push({ title: extension.name || extension.id, settings: context.settings, }); const api = extension.activate(context); extensions[extension.id] = api; manager.activating.pop(); resolved[extension.id] = true; extensionsStack.push({ extension: extension as Extension, context: context as IExtensionContext }); return api; }, get<T extends Extension<any, any, any>>(extension: T): ReturnType<T['activate']> { if (extensions.hasOwnProperty(extension.id)) { if (!resolved[extension.id]) { throw Error(`Circular dependency detected with ${extension.id}`); } } else { resolved[extension.id] = false; manager.activate(extension); } return extensions[extension.id] as ReturnType<T['activate']>; }, activating: [] as Array<Extension<any, any, any>>, settings, };
the_stack
import { customComponentPlugin, inlineTags, vueReservedTags, } from '@vuepress/markdown' import * as MarkdownIt from 'markdown-it' const md = MarkdownIt({ html: true }).use(customComponentPlugin) interface CustomComponentPluginTestCases { name: string cases: [string, string][] } // create test cases with specified component names const createTestCases = ( componentNames: string[] ): CustomComponentPluginTestCases[] => { const testCases: CustomComponentPluginTestCases[] = [] componentNames.forEach((comp) => { testCases.push( /** * self closed * * @example * <FooBar /> */ { name: `self closed <${comp} />`, cases: [ [`<${comp} />`, `<${comp} />`], [`<${comp} :prop-name="prop" />`, `<${comp} :prop-name="prop" />`], [`<${comp} @click="onClick" />`, `<${comp} @click="onClick" />`], [ `<${comp} :prop-name="prop" @click="onClick" />`, `<${comp} :prop-name="prop" @click="onClick" />`, ], [ `<${comp} :prop-name="prop"\nv-model="model" />`, `<${comp} :prop-name="prop"\nv-model="model" />`, ], [ `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick" />`, `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick" />`, ], [`# h1 <${comp} />`, `<h1>h1 <${comp} /></h1>\n`], [ `# h1 <${comp} :prop-name="prop" />`, `<h1>h1 <${comp} :prop-name="prop" /></h1>\n`, ], ], }, /** * empty * * @example * <FooBar></FooBar> */ { name: `empty <${comp}>`, cases: [ [`<${comp}></${comp}>`, `<${comp}></${comp}>`], [ `<${comp} :prop-name="prop"></${comp}>`, `<${comp} :prop-name="prop"></${comp}>`, ], [ `<${comp} @click="onClick"></${comp}>`, `<${comp} @click="onClick"></${comp}>`, ], [ `<${comp} :prop-name="prop" @click="onClick"></${comp}>`, `<${comp} :prop-name="prop" @click="onClick"></${comp}>`, ], [ `<${comp} :prop-name="prop"\nv-model="model"></${comp}>`, `<${comp} :prop-name="prop"\nv-model="model"></${comp}>`, ], [ `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"></${comp}>`, `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"></${comp}>`, ], [`# h1 <${comp}></${comp}>`, `<h1>h1 <${comp}></${comp}></h1>\n`], [ `# h1 <${comp} :prop-name="prop"></${comp}>`, `<h1>h1 <${comp} :prop-name="prop"></${comp}></h1>\n`, ], ], }, /** * text * * @example * <FooBar>foobar</FooBar> */ { name: `text <${comp}>`, cases: [ [`<${comp}>foobar</${comp}>`, `<${comp}>foobar</${comp}>`], [ `<${comp} :prop-name="prop">foobar</${comp}>`, `<${comp} :prop-name="prop">foobar</${comp}>`, ], [ `<${comp} @click="onClick">foobar</${comp}>`, `<${comp} @click="onClick">foobar</${comp}>`, ], [ `<${comp} :prop-name="prop" @click="onClick">foobar</${comp}>`, `<${comp} :prop-name="prop" @click="onClick">foobar</${comp}>`, ], [ `<${comp} :prop-name="prop"\nv-model="model">foobar</${comp}>`, `<${comp} :prop-name="prop"\nv-model="model">foobar</${comp}>`, ], [ `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick">foobar</${comp}>`, `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick">foobar</${comp}>`, ], [ `# h1 <${comp}>foobar</${comp}>`, `<h1>h1 <${comp}>foobar</${comp}></h1>\n`, ], [ `# h1 <${comp} :prop-name="prop">foobar</${comp}>`, `<h1>h1 <${comp} :prop-name="prop">foobar</${comp}></h1>\n`, ], ], }, /** * inline element * * @example * <FooBar><span>foobar</span></FooBar> */ { name: `inline element <${comp}>`, cases: [ [ `<${comp}><span>foobar</span></${comp}>`, `<${comp}><span>foobar</span></${comp}>`, ], [ `<${comp}>\n<span>foobar</span>\n</${comp}>`, `<${comp}>\n<span>foobar</span>\n</${comp}>`, ], [ `<${comp}>\n\n<span>foobar</span>\n\n</${comp}>`, `<${comp}>\n<p><span>foobar</span></p>\n</${comp}>`, ], [ `<${comp} :prop-name="prop"><span>foobar</span></${comp}>`, `<${comp} :prop-name="prop"><span>foobar</span></${comp}>`, ], [ `<${comp} @click="onClick"><span>foobar</span></${comp}>`, `<${comp} @click="onClick"><span>foobar</span></${comp}>`, ], [ `<${comp} :prop-name="prop" @click="onClick"><span>foobar</span></${comp}>`, `<${comp} :prop-name="prop" @click="onClick"><span>foobar</span></${comp}>`, ], [ `<${comp} :prop-name="prop"\nv-model="model"><span>foobar</span></${comp}>`, `<${comp} :prop-name="prop"\nv-model="model"><span>foobar</span></${comp}>`, ], [ `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"><span>foobar</span></${comp}>`, `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"><span>foobar</span></${comp}>`, ], [ `# h1 <${comp}><span>foobar</span></${comp}>`, `<h1>h1 <${comp}><span>foobar</span></${comp}></h1>\n`, ], [ `# h1 <${comp} :prop-name="prop"><span>foobar</span></${comp}>`, `<h1>h1 <${comp} :prop-name="prop"><span>foobar</span></${comp}></h1>\n`, ], ], }, /** * block element * * @example * <FooBar><div>foobar</div></FooBar> */ { name: `block element <${comp}>`, cases: [ [ `<${comp}><div>foobar</div></${comp}>`, `<${comp}><div>foobar</div></${comp}>`, ], [ `<${comp}>\n<div>foobar</div>\n</${comp}>`, `<${comp}>\n<div>foobar</div>\n</${comp}>`, ], [ `<${comp} :prop-name="prop"><div>foobar</div></${comp}>`, `<${comp} :prop-name="prop"><div>foobar</div></${comp}>`, ], [ `<${comp} @click="onClick"><div>foobar</div></${comp}>`, `<${comp} @click="onClick"><div>foobar</div></${comp}>`, ], [ `<${comp} :prop-name="prop" @click="onClick"><div>foobar</div></${comp}>`, `<${comp} :prop-name="prop" @click="onClick"><div>foobar</div></${comp}>`, ], [ `<${comp} :prop-name="prop"\nv-model="model"><div>foobar</div></${comp}>`, `<${comp} :prop-name="prop"\nv-model="model"><div>foobar</div></${comp}>`, ], [ `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"><div>foobar</div></${comp}>`, `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"><div>foobar</div></${comp}>`, ], [ `# h1 <${comp}><div>foobar</div></${comp}>`, `<h1>h1 <${comp}><div>foobar</div></${comp}></h1>\n`, ], [ `# h1 <${comp} :prop-name="prop"><div>foobar</div></${comp}>`, `<h1>h1 <${comp} :prop-name="prop"><div>foobar</div></${comp}></h1>\n`, ], ], }, /** * markdown syntax * * @example * <FooBar>*foobar*</FooBar> * * <FooBar> * - foo * - bar * </FooBar> */ { name: `markdown syntax <${comp}>`, cases: [ [`<${comp}>*foobar*</${comp}>`, `<${comp}>*foobar*</${comp}>`], [ `\ <${comp}> *foobar* </${comp}>`, `\ <${comp}> *foobar* </${comp}>`, ], [ `\ <${comp}> *foobar* </${comp}>`, `\ <${comp}> <p><em>foobar</em></p> </${comp}>`, ], [ `\ <${comp}> - foo - bar </${comp}>`, `\ <${comp}> - foo - bar </${comp}>`, ], [ `\ <${comp}> - foo - bar </${comp}>`, `\ <${comp}> <ul> <li>foo</li> <li>bar</li> </ul> </${comp}>`, ], // edge case // the blockquote should not be terminated // and the custom component should be treated as inline tag [ `\ > foo <${comp}>foobar</${comp}> `, `\ <blockquote> <p>foo <${comp}>foobar</${comp}></p> </blockquote> `, ], // edge case // if there is no matching end tag, the block will keep opening [ `\ - <${comp}> - foo `, `\ <ul> <li> <${comp}> </li> <li>foo</li> </ul> `, ], ], } ) }) return testCases } /** * Create test cases with inline tags * * Notice: if the starting tag and ending tag are in the same line, it will also * be treated as block */ const createInlineTestCases = ( tags: string[] ): CustomComponentPluginTestCases[] => { const testCases: CustomComponentPluginTestCases[] = [] tags.forEach((comp) => { testCases.push( /** * self closed * * @example * <span /> */ { name: `self closed <${comp} />`, cases: [ [`<${comp} />`, `<${comp} />`], [`<${comp} :prop-name="prop" />`, `<${comp} :prop-name="prop" />`], [`<${comp} @click="onClick" />`, `<${comp} @click="onClick" />`], [ `<${comp} :prop-name="prop" @click="onClick" />`, `<${comp} :prop-name="prop" @click="onClick" />`, ], [ `<${comp} :prop-name="prop"\nv-model="model" />`, `<p><${comp} :prop-name="prop"\nv-model="model" /></p>\n`, ], [ `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick" />`, `<p><${comp} :prop-name="prop"\nv-model="model"\n@click="onClick" /></p>\n`, ], [`# h1 <${comp} />`, `<h1>h1 <${comp} /></h1>\n`], [ `# h1 <${comp} :prop-name="prop" />`, `<h1>h1 <${comp} :prop-name="prop" /></h1>\n`, ], ], }, /** * empty * * @example * <span></span> */ { name: `empty <${comp}>`, cases: [ [`<${comp}></${comp}>`, `<p><${comp}></${comp}></p>\n`], [ `<${comp} :prop-name="prop"></${comp}>`, `<p><${comp} :prop-name="prop"></${comp}></p>\n`, ], [ `<${comp} @click="onClick"></${comp}>`, `<p><${comp} @click="onClick"></${comp}></p>\n`, ], [ `<${comp} :prop-name="prop" @click="onClick"></${comp}>`, `<p><${comp} :prop-name="prop" @click="onClick"></${comp}></p>\n`, ], [ `<${comp} :prop-name="prop"\nv-model="model"></${comp}>`, `<p><${comp} :prop-name="prop"\nv-model="model"></${comp}></p>\n`, ], [ `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"></${comp}>`, `<p><${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"></${comp}></p>\n`, ], [ `<${comp} :prop-name="prop" @click="onClick">\n</${comp}>`, `<${comp} :prop-name="prop" @click="onClick">\n</${comp}>`, ], [`# h1 <${comp}></${comp}>`, `<h1>h1 <${comp}></${comp}></h1>\n`], [ `# h1 <${comp} :prop-name="prop"></${comp}>`, `<h1>h1 <${comp} :prop-name="prop"></${comp}></h1>\n`, ], ], }, /** * text * * @example * <span>foobar</span> */ { name: `text <${comp}>`, cases: [ [`<${comp}>foobar</${comp}>`, `<p><${comp}>foobar</${comp}></p>\n`], [ `<${comp} :prop-name="prop">foobar</${comp}>`, `<p><${comp} :prop-name="prop">foobar</${comp}></p>\n`, ], [ `<${comp} @click="onClick">foobar</${comp}>`, `<p><${comp} @click="onClick">foobar</${comp}></p>\n`, ], [ `<${comp} :prop-name="prop" @click="onClick">foobar</${comp}>`, `<p><${comp} :prop-name="prop" @click="onClick">foobar</${comp}></p>\n`, ], [ `<${comp} :prop-name="prop"\nv-model="model">foobar</${comp}>`, `<p><${comp} :prop-name="prop"\nv-model="model">foobar</${comp}></p>\n`, ], [ `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick">foobar</${comp}>`, `<p><${comp} :prop-name="prop"\nv-model="model"\n@click="onClick">foobar</${comp}></p>\n`, ], [ `<${comp} :prop-name="prop" @click="onClick">\nfoobar\n</${comp}>`, `<${comp} :prop-name="prop" @click="onClick">\nfoobar\n</${comp}>`, ], [ `# h1 <${comp}>foobar</${comp}>`, `<h1>h1 <${comp}>foobar</${comp}></h1>\n`, ], [ `# h1 <${comp} :prop-name="prop">foobar</${comp}>`, `<h1>h1 <${comp} :prop-name="prop">foobar</${comp}></h1>\n`, ], ], }, /** * inline element * * @example * <span><span>foobar</span></span> */ { name: `inline element <${comp}>`, cases: [ [ `<${comp}><span>foobar</span></${comp}>`, `<p><${comp}><span>foobar</span></${comp}></p>\n`, ], [ `<${comp}>\n<span>foobar</span>\n</${comp}>`, `<${comp}>\n<span>foobar</span>\n</${comp}>`, ], [ `<${comp}>\n\n<span>foobar</span>\n\n</${comp}>`, `<${comp}>\n<p><span>foobar</span></p>\n</${comp}>`, ], [ `<${comp} :prop-name="prop"><span>foobar</span></${comp}>`, `<p><${comp} :prop-name="prop"><span>foobar</span></${comp}></p>\n`, ], [ `<${comp} @click="onClick"><span>foobar</span></${comp}>`, `<p><${comp} @click="onClick"><span>foobar</span></${comp}></p>\n`, ], [ `<${comp} :prop-name="prop" @click="onClick"><span>foobar</span></${comp}>`, `<p><${comp} :prop-name="prop" @click="onClick"><span>foobar</span></${comp}></p>\n`, ], [ `<${comp} :prop-name="prop"\nv-model="model"><span>foobar</span></${comp}>`, `<p><${comp} :prop-name="prop"\nv-model="model"><span>foobar</span></${comp}></p>\n`, ], [ `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"><span>foobar</span></${comp}>`, `<p><${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"><span>foobar</span></${comp}></p>\n`, ], [ `# h1 <${comp}><span>foobar</span></${comp}>`, `<h1>h1 <${comp}><span>foobar</span></${comp}></h1>\n`, ], [ `# h1 <${comp} :prop-name="prop"><span>foobar</span></${comp}>`, `<h1>h1 <${comp} :prop-name="prop"><span>foobar</span></${comp}></h1>\n`, ], ], }, /** * block element * * @example * <span><div>foobar</div></span> * * @remark * This is invalid HTML an should be avoided */ { name: `block element <${comp}>`, cases: [ [ `<${comp}><div>foobar</div></${comp}>`, `<p><${comp}><div>foobar</div></${comp}></p>\n`, ], [ `<${comp}>\n<div>foobar</div>\n</${comp}>`, `<${comp}>\n<div>foobar</div>\n</${comp}>`, ], [ `<${comp} :prop-name="prop"><div>foobar</div></${comp}>`, `<p><${comp} :prop-name="prop"><div>foobar</div></${comp}></p>\n`, ], [ `<${comp} @click="onClick"><div>foobar</div></${comp}>`, `<p><${comp} @click="onClick"><div>foobar</div></${comp}></p>\n`, ], [ `<${comp} :prop-name="prop" @click="onClick"><div>foobar</div></${comp}>`, `<p><${comp} :prop-name="prop" @click="onClick"><div>foobar</div></${comp}></p>\n`, ], [ `<${comp} :prop-name="prop"\nv-model="model"><div>foobar</div></${comp}>`, `<p><${comp} :prop-name="prop"\nv-model="model"><div>foobar</div></${comp}></p>\n`, ], [ `<${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"><div>foobar</div></${comp}>`, `<p><${comp} :prop-name="prop"\nv-model="model"\n@click="onClick"><div>foobar</div></${comp}></p>\n`, ], [ `# h1 <${comp}><div>foobar</div></${comp}>`, `<h1>h1 <${comp}><div>foobar</div></${comp}></h1>\n`, ], [ `# h1 <${comp} :prop-name="prop"><div>foobar</div></${comp}>`, `<h1>h1 <${comp} :prop-name="prop"><div>foobar</div></${comp}></h1>\n`, ], ], }, /** * markdown syntax * * @example * <FooBar>*foobar*</FooBar> * * <FooBar> * - foo * - bar * </FooBar> */ { name: `markdown syntax <${comp}>`, cases: [ [ `<${comp}>*foobar*</${comp}>`, `<p><${comp}><em>foobar</em></${comp}></p>\n`, ], [ `\ <${comp}> *foobar* </${comp}>`, `\ <${comp}> *foobar* </${comp}>`, ], [ `\ <${comp}> *foobar* </${comp}>`, `\ <${comp}> <p><em>foobar</em></p> </${comp}>`, ], [ `\ <${comp}> - foo - bar </${comp}>`, `\ <${comp}> - foo - bar </${comp}>`, ], [ `\ <${comp}> - foo - bar </${comp}>`, `\ <${comp}> <ul> <li>foo</li> <li>bar</li> </ul> </${comp}>`, ], ], } ) }) return testCases } describe('@vuepress/markdown > plugins > customComponentPlugin', () => { describe('should render custom components as normal html blocks', () => { describe('PascalCase components', () => { const testCases = createTestCases([ 'FooBar', 'V123', 'DivCustom', 'SpanCustom', ]) testCases.forEach(({ name, cases }) => { describe(name, () => { cases.forEach(([source, expected], index) => { it(`case ${index}`, () => { const rendered = md.render(source) expect(rendered).toBe(expected) }) }) }) }) }) describe('camelCase components', () => { const testCases = createTestCases([ 'fooBar', 'v123', 'divCustom', 'spanCustom', ]) testCases.forEach(({ name, cases }) => { describe(name, () => { cases.forEach(([source, expected], index) => { it(`case ${index}`, () => { const rendered = md.render(source) expect(rendered).toBe(expected) }) }) }) }) }) describe('kebab-case components', () => { const testCases = createTestCases([ 'foo-bar', 'v-123', 'div-custom', 'span-custom', ]) testCases.forEach(({ name, cases }) => { describe(name, () => { cases.forEach(([source, expected], index) => { it(`case ${index}`, () => { const rendered = md.render(source) expect(rendered).toBe(expected) }) }) }) }) }) describe('vue reserved tags', () => { const testCases = createTestCases(vueReservedTags) testCases.forEach(({ name, cases }) => { describe(name, () => { cases.forEach(([source, expected], index) => { it(`case ${index}`, () => { const rendered = md.render(source) expect(rendered).toBe(expected) }) }) }) }) }) }) it('should not treat custom components as html blocks if html option is disabled', () => { md.set({ html: false }) const source = '<foo-bar>foobar</foo-bar>' const expected = '<p>&lt;foo-bar&gt;foobar&lt;/foo-bar&gt;</p>\n' const rendered = md.render(source) expect(rendered).toBe(expected) md.set({ html: true }) }) describe('should make native inline tags work with vue template syntax', () => { const testCases = createInlineTestCases( inlineTags.filter( (item) => ![...vueReservedTags, 'script'].includes(item) ) ) testCases.forEach(({ name, cases }) => { describe(name, () => { cases.forEach(([source, expected], index) => { it(`case ${index}`, () => { const rendered = md.render(source) expect(rendered).toBe(expected) }) }) }) }) }) describe('some behaviors of original html block ruler (mainly for coverage purpose)', () => { describe('those html blocks whose ending tag is not required to be followed with an empty line', () => { it('ending tag in the same line as starting tag', () => { const source = '<pre>foobar</pre>' const expected = '<pre>foobar</pre>' const rendered = md.render(source) expect(rendered).toBe(expected) }) it('ending tag in different line from starting tag', () => { const source = '<pre>foobar\n</pre>' const expected = '<pre>foobar\n</pre>' const rendered = md.render(source) expect(rendered).toBe(expected) }) }) }) describe('compatibility with other markdown syntax', () => { it('should work with autolink', () => { const source = [ '<https://github.com>', '<localhost:5001/foo>', '<made-up-scheme://foo,bar>', '<foo@bar.example.com>', '<foo+special@Bar.baz-bar0.com>', '<a+b+c:d>', ].join('\n\n') const expected = [ '<a href="https://github.com">https://github.com</a>', '<a href="localhost:5001/foo">localhost:5001/foo</a>', '<a href="made-up-scheme://foo,bar">made-up-scheme://foo,bar</a>', '<a href="mailto:foo@bar.example.com">foo@bar.example.com</a>', '<a href="mailto:foo+special@Bar.baz-bar0.com">foo+special@Bar.baz-bar0.com</a>', '<a href="a+b+c:d">a+b+c:d</a>', ] .map((a) => `<p>${a}</p>`) .join('\n') + '\n' const rendered = md.render(source) expect(rendered).toBe(expected) }) }) })
the_stack
/* * Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info. */ namespace LiteMol.Core.Formats.Density.CCP4 { export function parse(buffer: ArrayBuffer) { return Parser.parse(buffer); } /** * Parses CCP4 files. */ namespace Parser { function getArray(r: (offset: number) => number, offset: number, count: number) { const ret:number[] = []; for (let i = 0; i < count; i++) { ret[i] = r(offset + i); } return ret; } /** * Parse CCP4 file according to spec at http://www.ccp4.ac.uk/html/maplib.html * Inspired by PyMOL implementation of the parser. */ export function parse(buffer: ArrayBuffer): ParserResult<Data> { const headerSize = 1024, headerView = new DataView(buffer, 0, headerSize), warnings: string[] = []; let endian = false; let mode = headerView.getInt32(3 * 4, false); if (mode !== 2) { endian = true; mode = headerView.getInt32(3 * 4, true); if (mode !== 2) { return ParserResult.error<Data>("Only CCP4 mode 2 is supported."); } } const readInt = (o: number) => headerView.getInt32(o * 4, endian), readFloat = (o: number) => headerView.getFloat32(o * 4, endian); const header = { extent: getArray(readInt, 0, 3), mode: mode, nxyzStart: getArray(readInt, 4, 3), grid: getArray(readInt, 7, 3), cellSize: getArray(readFloat, 10, 3), cellAngles: getArray(readFloat, 13, 3), crs2xyz: getArray(readInt, 16, 3), min: readFloat(19), max: readFloat(20), mean: readFloat(21), spacegroupNumber: readInt(22), symBytes: readInt(23), skewFlag: readInt(24), skewMatrix: getArray(readFloat, 25, 9), skewTranslation: getArray(readFloat, 34, 3), origin2k: getArray(readFloat, 49, 3) }; let dataOffset = buffer.byteLength - 4 * header.extent[0] * header.extent[1] * header.extent[2]; if (dataOffset !== headerSize + header.symBytes) { if (dataOffset === headerSize) { warnings.push("File contains bogus symmetry record."); } else if (dataOffset < headerSize) { return ParserResult.error<Data>("File appears truncated and doesn't match header."); } else if ((dataOffset > headerSize) && (dataOffset < (1024 * 1024))) { // Fix for loading SPIDER files which are larger than usual // In this specific case, we must absolutely trust the symBytes record dataOffset = headerSize + header.symBytes; warnings.push("File is larger than expected and doesn't match header. Continuing file load, good luck!"); } else { return ParserResult.error<Data>("File is MUCH larger than expected and doesn't match header."); } } //const mapp = readInt(52); //const mapStr = String.fromCharCode((mapp & 0xFF)) + String.fromCharCode(((mapp >> 8) & 0xFF)) + String.fromCharCode(((mapp >> 16) & 0xFF)) + String.fromCharCode(((mapp >> 24) & 0xFF)); // pretend we've checked the MAP string at offset 52 // pretend we've read the symmetry data if (header.grid[0] === 0 && header.extent[0] > 0) { header.grid[0] = header.extent[0] - 1; warnings.push("Fixed X interval count."); } if (header.grid[1] === 0 && header.extent[1] > 0) { header.grid[1] = header.extent[1] - 1; warnings.push("Fixed Y interval count."); } if (header.grid[2] === 0 && header.extent[2] > 0) { header.grid[2] = header.extent[2] - 1; warnings.push("Fixed Z interval count."); } if (header.crs2xyz[0] === 0 && header.crs2xyz[1] === 0 && header.crs2xyz[2] === 0) { warnings.push("All crs2xyz records are zero. Setting crs2xyz to 1, 2, 3."); header.crs2xyz = [1, 2, 3]; } if (header.cellSize[0] === 0.0 && header.cellSize[1] === 0.0 && header.cellSize[2] === 0.0) { warnings.push("Cell dimensions are all zero. Setting to 1.0, 1.0, 1.0. Map file will not align with other structures."); header.cellSize[0] = 1.0; header.cellSize[1] = 1.0; header.cellSize[2] = 1.0; } const indices = [0, 0, 0]; indices[header.crs2xyz[0] - 1] = 0; indices[header.crs2xyz[1] - 1] = 1; indices[header.crs2xyz[2] - 1] = 2; let originGrid: number[]; if (header.origin2k[0] === 0.0 && header.origin2k[1] === 0.0 && header.origin2k[2] === 0.0) { originGrid = [header.nxyzStart[indices[0]], header.nxyzStart[indices[1]], header.nxyzStart[indices[2]]]; } else { // Use ORIGIN records rather than old n[xyz]start records // http://www2.mrc-lmb.cam.ac.uk/image2000.html // XXX the ORIGIN field is only used by the EM community, and // has undefined meaning for non-orthogonal maps and/or // non-cubic voxels, etc. originGrid = [header.origin2k[indices[0]], header.origin2k[indices[1]], header.origin2k[indices[2]]] } const extent = [header.extent[indices[0]], header.extent[indices[1]], header.extent[indices[2]]]; const nativeEndian = new Uint16Array(new Uint8Array([0x12, 0x34]).buffer)[0] === 0x3412; const rawData = endian === nativeEndian ? readRawData1(new Float32Array(buffer, headerSize + header.symBytes, extent[0] * extent[1] * extent[2]), endian, extent, header.extent, indices, header.mean) : readRawData(new DataView(buffer, headerSize + header.symBytes), endian, extent, header.extent, indices, header.mean); const field = new Field3DZYX(<any>rawData.data, extent); const data: Data = { spacegroup: createSpacegroup(header.spacegroupNumber, header.cellSize, header.cellAngles), box: { origin: [originGrid[0] / header.grid[0], originGrid[1] / header.grid[1], originGrid[2] / header.grid[2]], dimensions: [extent[0] / header.grid[0], extent[1] / header.grid[1], extent[2] / header.grid[2]], sampleCount: extent }, data: field, valuesInfo: { min: header.min, max: header.max, mean: header.mean, sigma: rawData.sigma } }; return ParserResult.success(data, warnings); } function readRawData1(view: Float32Array, endian: boolean, extent: number[], headerExtent: number[], indices: number[], mean: number): { data: Float32Array, sigma: number } { let data = new Float32Array(extent[0] * extent[1] * extent[2]), coord = [0, 0, 0], mX: number, mY: number, mZ: number, cX: number, cY: number, cZ: number, xSize: number, xySize: number, offset = 0, v = 0.1, sigma = 0.0, t = 0.1, iX = indices[0], iY = indices[1], iZ = indices[2]; mX = headerExtent[0]; mY = headerExtent[1]; mZ = headerExtent[2]; xSize = extent[0]; xySize = extent[0] * extent[1]; for (cZ = 0; cZ < mZ; cZ++) { coord[2] = cZ; for (cY = 0; cY < mY; cY++) { coord[1] = cY; for (cX = 0; cX < mX; cX++) { coord[0] = cX; v = view[offset]; t = v - mean; sigma += t * t, data[coord[iX] + coord[iY] * xSize + coord[iZ] * xySize] = v; offset += 1; } } } sigma /= mX * mY * mZ; sigma = Math.sqrt(sigma); return { data: data, sigma: sigma }; } function readRawData(view: DataView, endian: boolean, extent: number[], headerExtent: number[], indices: number[], mean: number): { data: Float32Array, sigma: number } { let data = new Float32Array(extent[0] * extent[1] * extent[2]), coord = [0, 0, 0], mX: number, mY: number, mZ: number, cX: number, cY: number, cZ: number, xSize: number, xySize: number, offset = 0, v = 0.1, sigma = 0.0, t = 0.1, iX = indices[0], iY = indices[1], iZ = indices[2]; mX = headerExtent[0]; mY = headerExtent[1]; mZ = headerExtent[2]; xSize = extent[0]; xySize = extent[0] * extent[1]; for (cZ = 0; cZ < mZ; cZ++) { coord[2] = cZ; for (cY = 0; cY < mY; cY++) { coord[1] = cY; for (cX = 0; cX < mX; cX++) { coord[0] = cX; v = view.getFloat32(offset, endian); t = v - mean; sigma += t * t, data[coord[iX] + coord[iY] * xSize + coord[iZ] * xySize] = v; offset += 4; } } } sigma /= mX * mY * mZ; sigma = Math.sqrt(sigma); return { data: data, sigma: sigma }; } } }
the_stack
import type { MouseEvent as ReactMouseEvent, ReactNode } from 'react'; import { forwardRef, useEffect, useRef } from 'react'; import { Box } from 'reakit/Box'; import type { MenuBarStateReturn, MenuStateReturn } from 'reakit/Menu'; import { Menu as ReakitMenu, MenuBar as ReakitMenuBar, MenuButton as ReakitMenuButton, MenuGroup as ReakitMenuGroup, MenuItem as ReakitMenuItem, MenuSeparator, useMenuBarState, useMenuState, } from 'reakit/Menu'; import { Tooltip, TooltipReference, useTooltipState } from 'reakit/Tooltip'; import type { AnyExtension, CommandDecoratorMessageProps } from '@remirror/core'; import { cx, ErrorConstant, includes, invariant, isString } from '@remirror/core'; import { useActive, useChainedCommands, useCommands, useHelpers, useI18n, useRemirrorContext, } from '@remirror/react-core'; import { ComponentsTheme } from '@remirror/theme'; import { CommandIconComponent } from '../components'; import { useTheme } from '../providers'; import { ComponentItem, MenuBarGroupItem, MenuBarItem, MenuCommandPaneItem, MenuDropdownItem, MenuGroupItem, MenuPaneItem, MenuSeparatorItem, } from '../react-component-types'; import { getCommandOptionValue, getShortcutString, getUiShortcutString, } from '../react-component-utils'; interface MenuGroupProps extends BaseMenuProps { item: MenuGroupItem; } const MenuGroup = (props: MenuGroupProps) => { const { menuState, item: group } = props; const { items, label, role, separator } = group; const startSeparator = includes(['start', 'both'], separator) && <MenuSeparator {...menuState} />; const endSeparator = includes(['end', 'both'], separator) && <MenuSeparator {...menuState} />; return ( <> {startSeparator} <ReakitMenuGroup {...menuState} aria-label={label}> {items.map((item, index) => { switch (item.type) { case ComponentItem.MenuPane: return <MenuPane menuState={menuState} item={item} key={index} />; case ComponentItem.MenuCommandPane: return <MenuCommandPane menuState={menuState} item={item} role={role} key={index} />; case ComponentItem.MenuDropdown: return <MenuDropdown item={item} menuState={menuState} key={index} />; } })} </ReakitMenuGroup> {endSeparator} </> ); }; interface MenuPaneProps extends BaseMenuBarProps { item: MenuPaneItem; } const MenuPane = (props: MenuPaneProps): JSX.Element => { return <ReakitMenuItem {...props.menuState} />; }; interface MenuCommandPaneProps extends BaseMenuBarProps { item: MenuCommandPaneItem; autoFocus?: boolean; role?: 'radio' | 'checkbox'; } const MenuCommandPane = (props: MenuCommandPaneProps): JSX.Element => { // Gather all the hooks used for this component. const context = useRemirrorContext(); const { menuState, item, role } = props; const commands = useCommands(); const chain = useChainedCommands(); const { getCommandOptions } = useHelpers(); const { t } = useI18n(); const autoFocus = item.refocusEditor ?? props.autoFocus ?? false; // Will cause the editor to rerender for each state update. const active = useActive<AnyExtension>(); const { commandName, attrs, displayShortcut = true } = item; const options = getCommandOptions(commandName); if (!options) { return <span>Not found: {commandName}</span>; } const enabled = commands[commandName]?.isEnabled(attrs) ?? false; const isActive = active[options.name]?.(attrs) ?? false; const commandProps: CommandDecoratorMessageProps = { active: isActive, attrs, enabled, t }; const label = getCommandOptionValue(options.label, commandProps); const icon = getCommandOptionValue(options.icon, commandProps); const shortcutString = displayShortcut && options.shortcut ? `${getShortcutString(getUiShortcutString(options.shortcut, attrs ?? {}), { t })}` : undefined; const onClick = (event: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => { if (item.onClick) { item.onClick(event, context); return; } if (options.disableChaining) { commands[commandName]?.(attrs); return; } const command = chain[commandName]?.(attrs); if (autoFocus) { command?.focus?.(); } command?.run(); }; return ( <BaseMenuPane menuState={menuState} disabled={!enabled} focusable={enabled} onClick={onClick} active={isActive} role={role} > {icon && ( <Box as='span' className={ComponentsTheme.MENU_PANE_ICON}> <CommandIconComponent icon={icon} /> </Box> )} <Box as='span' className={ComponentsTheme.MENU_PANE_LABEL}> {label} </Box> {shortcutString && ( <Box as='span' className={ComponentsTheme.MENU_PANE_SHORTCUT}> {shortcutString} </Box> )} </BaseMenuPane> ); }; // type MenuDropdownProps = SubMenuDropdownProps | MenuBarDropdownProps; interface MenuDropdownProps extends BaseMenuBarProps { item: MenuDropdownItem; } const MenuDropdown = (props: MenuDropdownProps): JSX.Element => { const { menuState, item } = props; const { items, label, menuLabel } = item; return ( <ReakitMenuItem as={DropdownComponent} {...menuState} menuItems={items} label={label} menuLabel={menuLabel} /> ); }; interface DropdownComponentProps extends Omit<MenuDropdownItem, 'type' | 'items'>, Partial<MenuStateReturn> { menuItems: Array< MenuPaneItem | MenuSeparatorItem | MenuCommandPaneItem | MenuGroupItem | MenuDropdownItem >; } /** * A dropdown menu which can be composed together with other dropdown menus. */ export const DropdownComponent = forwardRef<HTMLButtonElement, DropdownComponentProps>( (props, ref) => { const menuState = useMenuState(); const { menuItems, label: Label, menuLabel, icon, ...rest } = props; let labelElement: ReactNode | undefined; let label: string | undefined = menuLabel; if (isString(Label)) { label ??= Label; } else if (Label != null) { labelElement = <Label menuState={menuState} />; } return ( <> <ReakitMenuButton {...menuState} {...rest} ref={ref} aria-label={label}> {labelElement && ( <Box as='span' className={ComponentsTheme.MENU_DROPDOWN_LABEL}> {labelElement} </Box> )} {icon && ( <Box as='span' className={ComponentsTheme.MENU_PANE_ICON}> <CommandIconComponent icon={icon} /> </Box> )} </ReakitMenuButton> <MenuComponent items={menuItems} menuState={menuState} label={label} /> </> ); }, ); DropdownComponent.displayName = 'Dropdown'; interface MenuComponentProps extends BaseMenuProps { /** * Whether the menu is open or not. */ open?: boolean | null; /** * The sub items to render */ items: Array< MenuPaneItem | MenuSeparatorItem | MenuCommandPaneItem | MenuGroupItem | MenuDropdownItem >; /** * The aria label for this menu. */ label?: string; } /** * A menu without the menu button trigger. The menu is opened and closed via the * `open` prop. */ export const MenuComponent = (props: MenuComponentProps): JSX.Element => { const { open, items, menuState, label } = props; const isControlled = useRef(open != null); useEffect(() => { invariant(isControlled.current === (open != null), { code: ErrorConstant.REACT_COMPONENTS, message: 'The controllable menu must either be controlled with a boolean value for `open` or uncontrolled (null | undefined value for `open`) for the lifetime of the component.', }); if (!isControlled.current) { return; } open ? menuState.show() : menuState.hide(); }, [open, menuState]); return ( <ReakitMenu {...menuState} aria-label={label}> {items.map((item, index) => { switch (item.type) { case ComponentItem.MenuSeparator: return <MenuSeparator {...menuState} key={index} />; case ComponentItem.MenuPane: return <MenuPane menuState={menuState} item={item} key={index} />; case ComponentItem.MenuCommandPane: return <MenuCommandPane menuState={menuState} item={item} key={index} />; case ComponentItem.MenuGroup: return <MenuGroup item={item} menuState={menuState} key={index} />; case ComponentItem.MenuDropdown: return <MenuDropdown item={item} menuState={menuState} key={index} />; default: return <></>; } })} </ReakitMenu> ); }; interface MenuBarProps { item: MenuBarItem; } export const MenuBar = (props: MenuBarProps): JSX.Element => { const menuState = useMenuBarState(); const { items } = props.item; return ( <ReakitMenuBar {...menuState}> {items.map((item) => { switch (item.type) { case ComponentItem.MenuSeparator: return <MenuSeparator {...menuState} />; case ComponentItem.MenuBarGroup: return <MenuBarGroup item={item} menuState={menuState} />; case ComponentItem.MenuDropdown: return <MenuDropdown item={item} menuState={menuState} />; } })} </ReakitMenuBar> ); }; interface MenuBarGroupProps extends BaseMenuBarProps { item: MenuBarGroupItem; } const MenuBarGroup = (props: MenuBarGroupProps) => { const { menuState, item } = props; return ( <ReakitMenuGroup {...menuState} aria-label={item.label}> {item.items.map((item) => { switch (item.type) { case ComponentItem.MenuDropdown: return <MenuDropdown item={item} menuState={menuState} />; } })} </ReakitMenuGroup> ); }; interface BaseMenuProps { menuState: MenuStateReturn; } interface BaseMenuBarProps { menuState: MenuBarStateReturn; } interface BaseMenuPaneProps extends BaseMenuBarProps { children: ReactNode; active: boolean; tooltip?: string; tooltipClass?: string; disabled?: boolean; focusable?: boolean; className?: string; role?: 'radio' | 'checkbox'; onClick: (event: ReactMouseEvent<HTMLButtonElement, MouseEvent>) => void; } const BaseMenuPane = (props: BaseMenuPaneProps) => { const { menuState: state, children, tooltip, disabled, focusable, onClick, tooltipClass, active, className, } = props; const tooltipState = useTooltipState({ gutter: 5 }); const themeProps = useTheme({ className: tooltipClass }); const checked = props.role ? (active ? 'true' : 'false') : undefined; const role = props.role === 'checkbox' ? 'menuitemcheckbox' : props.role === 'radio' ? 'menuitemradio' : undefined; return ( <> <TooltipReference {...tooltipState} as={Box}> <ReakitMenuItem {...state} role={role} aria-checked={checked} disabled={disabled} focusable={focusable} onClick={onClick} className={cx( className, ComponentsTheme.MENU_PANE, active && ComponentsTheme.MENU_PANE_ACTIVE, )} > {children} </ReakitMenuItem> </TooltipReference> {tooltip && ( <Tooltip {...tooltipState} style={themeProps.style} className={cx(themeProps.className)}> {tooltip} </Tooltip> )} </> ); };
the_stack
import { Store } from 'vuex'; import { readdirSync, readFileSync, rename, writeFile } from 'fs'; import * as os from 'os'; import * as path from 'path'; import { app, BrowserView, BrowserWindow, dialog, globalShortcut, ipcMain, Menu, MenuItem, nativeImage, protocol, shell, screen, systemPreferences, } from 'electron'; import collect from 'collect.js'; import { is } from 'electron-util'; import localshortcut from 'electron-localshortcut'; import autoUpdater from './lib/auto-updater'; import constants from './constants'; import menu from './lib/menu'; import promisify from './lib/promisify'; import fetch from './lib/fetch'; import View from './lib/view'; const { openProcessManager } = require('electron-process-manager'); const isTesting = process.env.NODE_ENV === 'test'; const startTime = new Date().getTime(); const globalObject = global as Lulumi.API.GlobalObject; /* * Set `__static` path to static files in production * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html */ if (process.env.NODE_ENV !== 'development') { globalObject.__static = path.resolve(__dirname, '../static'); } const gotTheLock = app.requestSingleInstanceLock(); if (!gotTheLock) { app.exit(); } let shuttingDown: boolean = isTesting; if (process.env.NODE_ENV === 'development') { app.setPath('userData', constants.devUserData); } else if (isTesting) { app.setPath('userData', constants.testUserData); } const storagePath: string = path.join(app.getPath('userData'), 'lulumi-state'); const langPath: string = path.join(app.getPath('userData'), 'lulumi-lang'); let lulumiStateSaveHandler: any = null; let setLanguage = false; const autoHideMenuBarSetting: boolean = is.macos; const swipeGesture: boolean = is.macos ? systemPreferences.isSwipeTrackingFromScrollEventsEnabled() : false; const winURL: string = process.env.NODE_ENV === 'development' ? `http://localhost:${require('../../.electron-vue/config').port}` : `file://${__dirname}/index.html`; const cpURL: string = process.env.NODE_ENV === 'development' ? `http://localhost:${require('../../.electron-vue/config').port}/cp.html` : `file://${__dirname}/cp.html`; // ./lib/session.ts const { default: session } = require('./lib/session'); // ../shared/store/mainStore.ts const { default: mainStore } = require('../shared/store/mainStore'); mainStore.register(storagePath, swipeGesture); const store: Store<any> = mainStore.getStore(); const windows: Electron.BrowserWindow[] = mainStore.getWindows(); const views: View[] = []; // ./api/lulumi-extension.ts const { default: lulumiExtension } = require('./api/lulumi-extension'); function lulumiStateSave(soft = true, windowCount = Object.keys(windows).length): void { if (!soft) { let count = 0; Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; window.once('closed', () => { count += 1; if (count === windowCount) { if (setLanguage) { // don't count in 'command-palette' mainStore.bumpWindowIds(windowCount - 1); } } }); window.close(); // https://github.com/electron/electron/issues/22290 (window as any).removeAllListeners('close'); }); } if (setLanguage) { return; } mainStore.saveLulumiState(soft) .then((state) => { if (state) { promisify(writeFile, storagePath, JSON.stringify(state)).then(() => { if (lulumiStateSaveHandler === null) { shuttingDown = true; app.quit(); } }); } }); } // eslint-disable-next-line max-len function createWindow(options?: Electron.BrowserWindowConstructorOptions, callback?: (eventName: string) => void): Electron.BrowserWindow { let mainWindow: Electron.BrowserWindow; const defaultOption: Record<string, any> = { autoHideMenuBar: autoHideMenuBarSetting, frame: !is.windows, fullscreenWindowTitle: true, minWidth: 320, minHeight: 500, titleBarStyle: 'hiddenInset', webPreferences: { worldSafeExecuteJavaScript: true, contextIsolation: false, nodeIntegration: true, webSecurity: false, webviewTag: true, }, }; if (options && Object.keys(options).length !== 0) { mainWindow = new BrowserWindow(Object.assign({}, defaultOption, options)); } else { /** * Initial window options */ mainWindow = new BrowserWindow(Object.assign({}, defaultOption, { width: 1080, height: 720, })); } mainWindow.loadURL(winURL); for (let index = 1; index < 9; index += 1) { localshortcut.register(mainWindow, `CmdOrCtrl+${index}`, () => { mainWindow.webContents.send('tab-click', index - 1); }); } if (!is.macos) { /* * On Windows and Linux, there're two shortcuts registered * to jump to the next and previous open tab. * However, it's not possible to add multiple accelerators in * Electron currently; therefore, we need to register another one here. * Ref: https://github.com/electron/electron/issues/5256 */ localshortcut.register(mainWindow, 'Ctrl+Tab', () => { mainWindow.webContents.send('tab-select', 'next'); }); localshortcut.register(mainWindow, 'Ctrl+Shift+Tab', () => { mainWindow.webContents.send('tab-select', 'previous'); }); } // register 'Escape' shortcut localshortcut.register(mainWindow, 'Escape', () => { mainWindow.webContents.send('escape-full-screen'); }); // special case: go to the last tab localshortcut.register(mainWindow, 'CmdOrCtrl+9', () => { mainWindow.webContents.send('tab-click', -1); }); // register the shortcut for opening the tab closed recently localshortcut.register(mainWindow, 'CmdOrCtrl+Shift+T', () => { mainWindow.webContents.send('restore-recently-closed-tab'); }); menu.init(); /* mainWindow.webContents.on('will-attach-webview', (event, webPreferences, params) => { webPreferences.nativeWindowOpen = false; webPreferences.enableBlinkFeatures = 'OverlayScrollbars'; webPreferences.nodeIntegrationInSubFrames = true; const backgroundRegExp = new RegExp(/^lulumi-extension:\/\/.+\/.*background.*\.html$/); if (params.src.startsWith('lulumi-extension://')) { if (params.src.match(backgroundRegExp)) { webPreferences.preload = path.join(constants.lulumiPreloadPath, 'extension-preload.js'); } else { webPreferences.preload = path.join(constants.lulumiPreloadPath, 'popup-preload.js'); } } }); */ mainWindow.on('close', () => { // https://github.com/electron/electron/issues/22290 (mainWindow as any).removeAllListeners('will-attach-webview'); }); mainWindow.on('closed', () => ((mainWindow as any) = null)); if (!isTesting) { // the first window if (lulumiStateSaveHandler === null) { // save app-state every 5 mins lulumiStateSaveHandler = setInterval(lulumiStateSave, 1000 * 60 * 5); // reset the setLanguage variable if (setLanguage) { setLanguage = false; } } } if (callback) { (mainWindow as any).callback = callback; } else { (mainWindow as any).callback = (eventName) => { ipcMain.once(eventName, (event: Electron.IpcMainEvent) => { event.sender.send(eventName.substr(4), { url: 'about:newtab', follow: true }); }); }; } return mainWindow; } // register the method to BrowserWindow (BrowserWindow as any).createWindow = createWindow; // register 'lulumi' and 'lulumi-extension' as standard protocols that are secure protocol.registerSchemesAsPrivileged([ { scheme: 'lulumi', privileges: { standard: true, secure: true } }, { scheme: 'lulumi-extension', privileges: { standard: true, secure: true } }, ]); app.whenReady().then(() => { // autoUpdater if (process.env.NODE_ENV !== 'development') { autoUpdater.init(); autoUpdater.listen(windows); } // session related operations session.onWillDownload(windows, constants.lulumiPDFJSPath); session.setPermissionRequestHandler(windows); session.registerScheme(constants.lulumiPagesCustomProtocol); session.registerCertificateVerifyProc(); session.registerWebRequestListeners(); // load persisted extensions lulumiExtension.loadExtensions(); // load lulumi-state let data: any = '""'; try { data = readFileSync(storagePath, 'utf8'); } catch (readError) { console.error(`(lulumi-browser) Could not read data from ${storagePath}, ${readError}`); } try { data = JSON.parse(data); } catch (parseError) { console.error(`(lulumi-browser) Could not parse data from ${storagePath}, ${parseError}`); } finally { if (data) { store.dispatch('setLulumiState', data); session.registerProxy(store.getters.proxyConfig); } try { const { width, height } = screen.getPrimaryDisplay().workAreaSize; globalObject.commandPalette = new BrowserWindow({ width: width / 2, height: height / 1.94, show: false, frame: false, alwaysOnTop: true, fullscreenable: false, resizable: false, webPreferences: { partition: 'command-palette', nodeIntegration: true, }, }); globalObject.commandPalette.setVisibleOnAllWorkspaces(false); globalObject.commandPalette.loadURL(cpURL); globalShortcut.register('CmdOrCtrl+Shift+K', () => { if (globalObject.commandPalette.isVisible()) { globalObject.commandPalette.hide(); } else { globalObject.commandPalette.show(); globalObject.commandPalette.webContents.send('send-focus'); } }); globalObject.commandPalette.on('blur', () => globalObject.commandPalette.hide()); createWindow(); } catch (createWindowError) { console.error(`(lulumi-browser) Could not create a window: ${createWindowError}`); app.exit(1); } } }); if (process.env.TEST_ENV !== 'e2e') { app.on('remote-require', (event, webContents) => { console.error( `(lulumi-browser) Invalid module to require at webContents ${webContents.id}` ); event.preventDefault(); }); app.on('remote-get-global', (event: Electron.IpcMainEvent, webContents, globalName) => { if (globalName === 'commandPalette') { event.returnValue = globalObject.commandPalette; } else { console.error( `(lulumi-browser) Invalid object to get at webContents ${webContents.id}` ); event.preventDefault(); } }); } app.on('login', (event, webContents, request, authInfo, callback) => { const { auth } = store.getters; if (auth.username && auth.password) { callback(auth.username, auth.password); } else { dialog.showMessageBox(null!, { type: 'warning', buttons: ['OK'], title: 'Require authentication', // eslint-disable-next-line max-len message: 'The server requires a username and password. You can set them in "Preferences / Auth".', detail: `Server: ${request.url}\nRealm: ${authInfo.realm}`, }); } }); app.on('window-all-closed', () => { if (isTesting || !is.macos) { app.quit(); } }); app.on('activate', () => { if (Object.keys(windows).length === 0) { createWindow(); } }); app.on('before-quit', (event: Electron.Event) => { if (shuttingDown) { return; } event.preventDefault(); mainStore.updateWindowStates(); if (lulumiStateSaveHandler !== null) { clearInterval(lulumiStateSaveHandler); lulumiStateSaveHandler = null; } lulumiStateSave(false); }); // https://github.com/electron/electron/pull/12782 app.on('second-instance', () => { // Someone tried to run a second instance, we should focus our window. for (let id = 0; id < Object.keys(windows).length; id += 1) { const window = windows[id] as Electron.BrowserWindow; if (window.getTitle() !== 'command-palette') { if (window.isMinimized()) { window.restore(); } window.focus(); return; } } }); // load windowProperties ipcMain.on('get-window-properties', (event: Electron.IpcMainEvent) => { const windowProperties: any = []; const baseDir = path.dirname(storagePath); const collection = collect(readdirSync(baseDir, 'utf8')); let windowPropertyFilenames = collection.filter(v => (v.match(/lulumi-state-window-\d+/) !== null)); if (windowPropertyFilenames.isNotEmpty()) { windowPropertyFilenames = windowPropertyFilenames.sort((a, b) => ( (b.split('-') as any).pop() - (a.split('-') as any).pop() )); windowPropertyFilenames.all().forEach((windowPropertyFilename) => { const windowPropertyFile = path.join(baseDir, windowPropertyFilename); const windowProperty = JSON.parse(readFileSync(windowPropertyFile, 'utf8')); windowProperty.path = windowPropertyFile; windowProperty.mtime = startTime; windowProperties.push(windowProperty); }); } event.returnValue = windowProperties; }); // restore windowProperties ipcMain.on('restore-window-property', (event: Electron.Event, windowProperty: any) => { const options: Electron.BrowserWindowConstructorOptions = {}; const { window } = windowProperty; const windowState: string = window.state; options.width = window.width; options.height = window.height; options.x = window.left; options.y = window.top; const tmpWindow = createWindow(options, (eventName) => { ipcMain.once(eventName, (event2: Electron.IpcMainEvent) => { event2.sender.send(eventName.substr(4), null); windowProperty.tabs.forEach((tab, index) => { tmpWindow.webContents.send( 'new-tab', { url: tab.url, follow: index === windowProperty.currentTabIndex } ); }); const windowPropertyFilename = path.basename(windowProperty.path); const windowPropertyTmp = path.resolve(app.getPath('temp'), windowPropertyFilename); rename(windowProperty.path, windowPropertyTmp, (renameError) => { if (renameError) { console.error(`(lulumi-browser) ${renameError}`); } }); }); }); if (window.focused) { tmpWindow.focus(); } if (windowState === 'minimized') { tmpWindow.minimize(); } else if (windowState === 'maximized') { tmpWindow.maximize(); } else if (windowState === 'fullscreen') { tmpWindow.setFullScreen(true); } }); // open ProcessManager ipcMain.on('open-process-manager', () => { openProcessManager(); }); // return the number of BrowserWindow ipcMain.on('get-window-count', (event: Electron.IpcMainEvent) => { event.returnValue = Object.keys(windows).length; }); // create a BrowserView ipcMain.on('create-browser-view', (event, data) => { const { tabId, tabIndex, url }: { tabId: number; tabIndex: number; url: string } = data; const window = windows[data.windowId] as Electron.BrowserWindow; if (window) { views.push(new View(window, tabIndex, tabId, url)); } }); // destroy a BrowserView ipcMain.on('destroy-browser-view', (event, browserViewId) => { const browserView = views.find(view => (view.id === browserViewId)); if (browserView) { browserView.destroy(); } }); // resize a BrowserView ipcMain.on('resize-browser-view', (event, browserViewId) => { const browserView = views.find(view => (view.id === browserViewId)); if (browserView) { browserView.fitWindow(); } }); // focus a BrowserView ipcMain.on('focus-browser-view', (event, data) => { const { browserViewId }: { browserViewId: number } = data; const window = windows[data.windowId] as Electron.BrowserWindow; if (window) { window.setBrowserView(BrowserView.fromId(browserViewId)); } }); // show the certificate ipcMain.on('show-certificate', (event: Electron.IpcMainEvent, certificate: Electron.Certificate, message: string) => { const browserWindow = BrowserWindow.fromWebContents(event.sender); if (browserWindow) { dialog.showCertificateTrustDialog(browserWindow, { certificate, message, }).then(); } }); // focus the window ipcMain.on('focus-window', (event, windowId) => { const window = windows[windowId] as Electron.BrowserWindow; if (window) { window.focus(); } }); // set the title for the focused BrowserWindow ipcMain.on('set-browser-window-title', (event, data) => { const window = windows[data.windowId] as Electron.BrowserWindow; if (window) { window.setTitle(data.title); } }); // show the item on host ipcMain.on('show-item-in-folder', (event, itemPath) => { if (itemPath) { shell.showItemInFolder(itemPath); } }); // open the item on host ipcMain.on('open-path', (event, itemPath) => { if (itemPath) { shell.openPath(itemPath); } }); // load preference things into global when users accessing 'lulumi' protocol ipcMain.on('lulumi-scheme-loaded', (event, val) => { let type: string = val.substr(`${constants.lulumiPagesCustomProtocol}://`.length).split('/')[0]; const data: Lulumi.Scheme.LulumiObject = {} as Lulumi.Scheme.LulumiObject; if (process.env.NODE_ENV === 'development' && val.startsWith('http://localhost:')) { if (require('url').parse(val).pathname === '/about.html') { type = 'about'; } } if (type === 'about') { const { versions } = process; data.lulumi = [ { key: 'Lulumi', value: app.getVersion(), }, { key: 'rev', value: constants.lulumiRev, }, { key: 'Electron', value: versions.electron, }, { key: 'Node', value: versions.node, }, { key: 'libchromiumcontent', value: versions.chrome, }, { key: 'V8', value: versions.v8, }, { key: 'os.platform', value: os.platform(), }, { key: 'os.release', value: os.release(), }, { key: 'os.arch', value: os.arch(), }, { key: 'userData', value: app.getPath('userData'), }, ]; data.preferences = [ ['Search Engine Provider', 'search'], ['Homepage', 'homepage'], ['PDFViewer', 'pdfViewer'], ['Tab', 'tab'], ['Language', 'language'], ['Proxy', 'proxy'], ['Auth', 'auth'], ]; data.about = [ [`${constants.lulumiPagesCustomProtocol}://about/#/about`, 'about'], [`${constants.lulumiPagesCustomProtocol}://about/#/lulumi`, 'lulumi'], [`${constants.lulumiPagesCustomProtocol}://about/#/preferences`, 'preferences'], [`${constants.lulumiPagesCustomProtocol}://about/#/downloads`, 'downloads'], [`${constants.lulumiPagesCustomProtocol}://about/#/history`, 'history'], [`${constants.lulumiPagesCustomProtocol}://about/#/extensions`, 'extensions'], ]; } event.returnValue = data; }); // about:* pages are eager to getting preference datas ipcMain.on('guest-want-data', (event: Electron.IpcMainEvent, type: string) => { const webContentsId: number = event.sender.id; Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; switch (type) { case 'searchEngineProvider': window.webContents.send('get-search-engine-provider', webContentsId); break; case 'homepage': window.webContents.send('get-homepage', webContentsId); break; case 'pdfViewer': window.webContents.send('get-pdf-viewer', webContentsId); break; case 'tabConfig': window.webContents.send('get-tab-config', webContentsId); break; case 'lang': window.webContents.send('get-lang', webContentsId); break; case 'proxyConfig': window.webContents.send('get-proxy-config', webContentsId); break; case 'auth': window.webContents.send('get-auth', webContentsId); break; case 'downloads': window.webContents.send('get-downloads', webContentsId); break; case 'history': window.webContents.send('get-history', webContentsId); break; case 'extensions': break; default: break; } }); }); ipcMain.on('set-current-search-engine-provider', (event: Electron.IpcMainEvent, val) => { store.dispatch('setCurrentSearchEngineProvider', val); Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; window.webContents.send('get-search-engine-provider', event.sender.id); }); }); ipcMain.on('set-homepage', (event: Electron.IpcMainEvent, val) => { store.dispatch('setHomepage', val); Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; window.webContents.send('get-homepage', event.sender.id); }); }); ipcMain.on('set-pdf-viewer', (event: Electron.IpcMainEvent, val) => { store.dispatch('setPDFViewer', val); Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; window.webContents.send('get-pdf-viewer', event.sender.id); }); }); ipcMain.on('set-tab-config', (event: Electron.IpcMainEvent, val) => { store.dispatch('setTabConfig', val); Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; window.webContents.send('get-tab-config', event.sender.id); }); }); ipcMain.on('set-lang', (eventOne: Electron.IpcMainEvent, val) => { const webContentsId: number = eventOne.sender.id; Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; window.webContents.send('request-permission', { webContentsId, permission: 'setLanguage', label: val.label, }); }); ipcMain.once(`response-permission-${eventOne.sender.id}`, (eventTwo, data) => { if (data.accept) { store.dispatch('setLang', val); promisify(writeFile, langPath, JSON.stringify(val.lang)) .then(() => { setLanguage = true; menu.setLocale(val.lang); app.quit(); }); } }); }); ipcMain.on('set-proxy-config', (event: Electron.IpcMainEvent, val) => { session.registerProxy(val); store.dispatch('setProxyConfig', val); Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; window.webContents.send('get-proxy-config', event.sender.id); }); }); ipcMain.on('set-auth', (event: Electron.IpcMainEvent, val) => { store.dispatch('setAuth', val); Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; window.webContents.send('get-auth', event.sender.id); }); }); ipcMain.on('set-downloads', (event: Electron.IpcMainEvent, val) => { store.dispatch('setDownloads', val); Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; window.webContents.send('get-downloads', event.sender.id); }); }); ipcMain.on('set-history', (event: Electron.IpcMainEvent, val) => { store.dispatch('setHistory', val); Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; window.webContents.send('get-history', event.sender.id); }); }); // listen to new-lulumi-window event ipcMain.on('new-lulumi-window', (event: Electron.IpcMainEvent, data) => { if (data.url) { event.returnValue = createWindow({ width: 800, height: 500, }, (eventName) => { ipcMain.once(eventName, (event2: Electron.IpcMainEvent) => { event2.sender.send(eventName.substr(4), { url: data.url, follow: data.follow }); }); }); } }); // load the lang file ipcMain.on('request-lang', (event: Electron.IpcMainEvent) => { let lang = ''; try { lang = readFileSync(langPath, 'utf8'); } catch (langError) { console.error(`(lulumi-browser) ${langError}`); lang = app.getLocaleCountryCode(); if (lang === 'TW') { lang = '"zh-TW"'; } else if (lang === 'CN') { lang = '"zh-CN"'; } else { lang = '"en-US"'; } } event.returnValue = JSON.parse(lang); }); // load extension objects for each BrowserWindow instance ipcMain.on('register-local-commands', (event: Electron.IpcMainEvent) => { Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; if (window.getTitle() !== 'command-palette') { Object.keys(lulumiExtension.getManifestMap()).forEach((manifest) => { lulumiExtension.registerLocalCommands(window, lulumiExtension.getManifestMap()[manifest]); }); } }); event.sender.send('registered-local-commands', lulumiExtension.getManifestMap()); }); ipcMain.on('fetch-search-suggestions', (event: Electron.IpcMainEvent, url: string, timestamp: number) => { fetch(url, (result) => { event.sender.send(`fetch-search-suggestions-${timestamp}`, result); }); }); ipcMain.on('popup', (event: Electron.IpcMainEvent, popupObject: any) => { const popupMenu = new Menu(); popupObject.menuItems.forEach((popupMenuItem) => { if (popupMenuItem.icon) { if (popupMenuItem.type === 'base64') { popupMenuItem.icon = nativeImage.createFromDataURL(popupMenuItem.icon).resize({ width: 14, height: 14, }); delete popupMenuItem.type; } } if (popupMenuItem.click) { if (popupMenuItem.click === 'open-history') { popupMenuItem.click = () => (event.sender.send('open-history')); } else if (popupMenuItem.click === 'go-to-index') { const { index } = popupMenuItem; delete popupMenuItem.index; popupMenuItem.click = () => { event.sender.send('go-to-index', index); }; } } popupMenu.append(new MenuItem(popupMenuItem)); }); popupMenu.popup({ window: BrowserWindow.fromId(popupObject.windowId), x: popupObject.x, y: popupObject.y, }); }); // reload each BrowserView when we plug in our cable globalObject.isOnline = true; ipcMain.on('online-status-changed', (event, status: boolean) => { if (status) { if (!globalObject.isOnline) { Object.keys(windows).forEach((key) => { const id = parseInt(key, 10); const window = windows[id]; window.webContents.send('reload'); }); globalObject.isOnline = true; } } else { globalObject.isOnline = false; } });
the_stack
import * as Path from "path"; import * as fs from "fs"; import {listFiles} from "../main/impl/FileUtils"; import {Log4TSProvider, LogLevel} from "typescript-logging"; import {NodeChannelFactory} from "../main/api"; import {NodeRawLogChannel} from "../main/impl/NodeRawLogChannel"; import {StreamCallBackImpl} from "./util/StreamCallBackImpl"; import {RollOverHelper} from "./util/RollOverHelper"; describe("Test node logging", () => { let testDir: string = ""; let provider: Log4TSProvider; let channel: NodeRawLogChannel; let streamCallBack: StreamCallBackImpl; let rollOverHelper: RollOverHelper; beforeEach(() => { /* * Clear any state, so we always start clean. */ Log4TSProvider.clear(); /* Sanity check */ const pathToNodeDir = getNodeDirectoryPath(); checkExistsAndIsDirectory(pathToNodeDir); testDir = getNodeTestDirectoryPath(); deleteDirectoryIfExists(testDir); fs.mkdirSync(testDir, {recursive: true}); streamCallBack = new StreamCallBackImpl(1); rollOverHelper = new RollOverHelper(streamCallBack, 1); const retention = NodeChannelFactory.createRetentionStrategyMaxFiles({directory: testDir, maxFiles: 3, maxFileSize: {value: 1, unit: "KiloBytes"}}); channel = NodeChannelFactory.createRawLogChannel(retention, msg => msg.message + "\n", {onRollOver: streamCallBack.onRollOver}) as NodeRawLogChannel; channel.setStreamCallBacks(streamCallBack); provider = Log4TSProvider.createProvider("test", {channel, groups: [{expression: new RegExp("model.+"), level: LogLevel.Debug}]}); }); afterEach(() => { if (testDir !== "") { deleteDirectoryIfExists(testDir); } testDir = ""; if (channel) { channel.close(); } }); test("Test node channel writes to file", async () => { const logger = provider.getLogger("model.Example"); logger.debug("hello world 1"); logger.debug("hello world 2"); logger.debug("hello world 3"); logger.debug("hello world 4"); channel.close(); await streamCallBack.isFinished(); streamCallBack.verifyStackValid(); const data = getFileContents(streamCallBack.getFile()); expect(data).toEqual("hello world 1\nhello world 2\nhello world 3\nhello world 4\n"); }); test("Test node channel does rollover to next file", async () => { /* The channel is configured to write max 1 KB in a file (1024 bytes) */ streamCallBack.setExpectedCount(1); const logger = provider.getLogger("model.Example"); /* We write as utf-8, both a and b fit a single byte, note that each debug has a \n added too (see above in setup), hence 511 for each line. */ const valueA = "a".repeat(511); const valueB = "b".repeat(511); logger.debug(valueA); logger.debug(valueB); channel.close(); // Just to assure flushing happens because we close the underlying stream. await streamCallBack.isFinished(); streamCallBack.verifyStackValid(); let files = streamCallBack.getFiles(); assertFile(files, "application1.log", `${valueA}\n${valueB}\n`); /* There is really only 1 file here */ const firstFile = files[0]; /* Write something else, this should end up in the next file */ streamCallBack = new StreamCallBackImpl(1); channel.setStreamCallBacks(streamCallBack); logger.debug("hello"); channel.close(); await streamCallBack.isFinished(); streamCallBack.verifyStackValid(); files = streamCallBack.getFiles(); assertFile(files, "application2.log", "hello\n"); /* First file should be valid too still of course */ assertFile([firstFile], "application1.log", `${valueA}\n${valueB}\n`); }); test("Test node channel rolls over multiple files", async () => { /* The channel is configured to write max 1 KB in a file (1024 bytes) */ streamCallBack.setExpectedCount(3); const logger = provider.getLogger("model.Example"); /* We write as utf-8, the letters fit a single byte, note that each debug has a \n added too (see above in setup), hence 1023 for each value. */ const valueA = "a".repeat(1023); const valueB = "b".repeat(1023); const valueC = "c".repeat(1023); logger.debug(valueA); logger.debug(valueB); // Rollover will happen, as this won't fit logger.debug(valueC); // Rollover will happen, as this won't fit channel.close(); // To make sure last file is written await streamCallBack.isFinished(); streamCallBack.verifyStackValid(); const files = streamCallBack.getFiles(); assertFile(files, "application1.log", valueA + "\n"); assertFile(files, "application2.log", valueB + "\n"); assertFile(files, "application3.log", valueC + "\n"); }); test("Test node channel finds existing file", async () => { const valueA = "a".repeat(511); const valueB = "b".repeat(511); const existingFile = getNodeTestDirectoryPath() + Path.sep + "application1.log"; fs.writeFileSync(existingFile, valueA + "\n", {encoding: "utf-8"}); streamCallBack.setExpectedCount(2); const logger = provider.getLogger("model.Example"); logger.debug(valueB); logger.debug("second file"); channel.close(); await streamCallBack.isFinished(); streamCallBack.verifyStackValid(); const files = streamCallBack.getFiles(); assertFile(files, "application1.log", `${valueA}\n${valueB}\n`); assertFile(files, "application2.log", "second file\n"); }); test("Test node channel finds last used file", async () => { const valueA = "a".repeat(511); const valueB = "b".repeat(511); const existingFile1 = getNodeTestDirectoryPath() + Path.sep + "application1.log"; const existingFile2 = getNodeTestDirectoryPath() + Path.sep + "application2.log"; const existingFile3 = getNodeTestDirectoryPath() + Path.sep + "application3.log"; fs.writeFileSync(existingFile2, "hello2", {encoding: "utf-8"}); await sleep(5); fs.writeFileSync(existingFile1, "hello1", {encoding: "utf-8"}); await sleep(5); fs.writeFileSync(existingFile3, valueA + "\n", {encoding: "utf-8"}); /* Last used file would be 3 so that should be appended to */ streamCallBack.setExpectedCount(2); const logger = provider.getLogger("model.Example"); logger.debug(valueB); logger.debug("should end up in file 1"); channel.close(); await streamCallBack.isFinished(); streamCallBack.verifyStackValid(); const files = streamCallBack.getFiles(); assertFile(files, "application1.log", "should end up in file 1\n"); assertFile(files, "application3.log", `${valueA}\n${valueB}\n`); /* application2.log was not touched so should be as it was before */ assertFile([existingFile2], "application2.log", "hello2"); }); test("Test node channel finds last used full file, should start with next", async () => { const valueA = "a".repeat(511); const valueB = "b".repeat(511); const existingFile1 = getNodeTestDirectoryPath() + Path.sep + "application1.log"; const existingFile2 = getNodeTestDirectoryPath() + Path.sep + "application2.log"; const existingFile3 = getNodeTestDirectoryPath() + Path.sep + "application3.log"; fs.writeFileSync(existingFile3, "hello 3", {encoding: "utf-8"}); await sleep(10); fs.writeFileSync(existingFile1, "hello 1", {encoding: "utf-8"}); await sleep(10); fs.writeFileSync(existingFile2, valueA + "\n" + valueB + "\n", {encoding: "utf-8"}); /* file 2 above is full, so it should find it but immediately roll over to 3, so 2 and 1 remain untouched when writing next */ streamCallBack.setExpectedCount(1); const logger = provider.getLogger("model.Example"); logger.debug("should end up in file 3"); channel.close(); await streamCallBack.isFinished(); streamCallBack.verifyStackValid(); const files = streamCallBack.getFiles(); assertFile(files, "application3.log", "should end up in file 3\n"); /* The other 2 files should remain untouched as they were */ assertFile([existingFile1], "application1.log", "hello 1"); assertFile([existingFile2], "application2.log", valueA + "\n" + valueB + "\n"); }); test("Test node channel rollover event occurs when file is flushed/written", async () => { streamCallBack.setExpectedCount(2); streamCallBack.setRollOver(rollOverHelper.onRollOver); const valueA = "a".repeat(1023); const logger = provider.getLogger("model.Example"); logger.debug(valueA); logger.debug("x"); channel.close(); await streamCallBack.isFinished(); streamCallBack.verifyStackValid(); /* Next wait that all files arrived as expected, they only get here if the streamCallBack verified ok, it will fail if rollover occurs before finish & close. */ await rollOverHelper.isFinished(); const files = rollOverHelper.getFiles(); assertFile(files, "application1.log", `${valueA}\n`); assertFile([getNodeTestDirectoryPath() + Path.sep + "application2.log"], "application2.log", `x\n`); }); test("Test node channel rollover events occur", async () => { /* We expect 4 rollovers, so 1, 2, 3 and 1 again */ rollOverHelper.setExpectedCount(4); streamCallBack.setExpectedCount(5); streamCallBack.setRollOver(rollOverHelper.onRollOver); const valueA = "a".repeat(1023); const valueB = "b".repeat(1023); const valueC = "c".repeat(1023); const valueD = "d".repeat(1023); const logger = provider.getLogger("model.Example"); logger.debug(valueA); logger.debug(valueB); logger.debug(valueC); logger.debug(valueD); logger.debug("last"); channel.close(); await streamCallBack.isFinished(); streamCallBack.verifyStackValid(); /* Next wait that all files arrived as expected, they only get here if the streamCallBack verified ok, it will fail if rollover occurs before finish & close. */ await rollOverHelper.isFinished(); const files = rollOverHelper.getFiles(); const dir = getNodeTestDirectoryPath(); const file1 = dir + Path.sep + "application1.log"; const file2 = dir + Path.sep + "application2.log"; const file3 = dir + Path.sep + "application3.log"; /* We expect 4 files rolled over, of which the first rolled over twice as max files is 3, also verify expected content */ expect(files).toEqual([file1, file2, file3, file1]); assertFile(files, "application1.log", `${valueD}\n`); assertFile(files, "application2.log", "last\n"); assertFile(files, "application3.log", `${valueC}\n`); }); function checkExistsAndIsDirectory(dir: string) { if (!fs.existsSync(dir)) { throw new Error(`Path '${dir}' does not exist.`); } try { const stats = fs.statSync(dir); if (!stats.isDirectory()) { // noinspection ExceptionCaughtLocallyJS throw new Error(`Path '${dir}' is not a directory.`); } } catch (e) { throw new Error(`Failed to stat directory '${dir}'`); } } function getNodeDirectoryPath() { let dir = process.env.INIT_CWD; if (!dir) { dir = process.cwd(); } if (!dir) { throw new Error("process.env.INIT_CWD is not set, is this not a node environment?"); } if (!dir.endsWith("node")) { dir += Path.sep + "node"; } return dir; } function getNodeTestDirectoryPath() { return getNodeDirectoryPath() + Path.sep + "dist" + Path.sep + "test"; } function deleteDirectoryIfExists(directory: string) { if (!fs.existsSync(directory)) { return; } listFiles(directory, "utf-8", () => true).forEach(dirEnt => { if (!dirEnt.isFile()) { throw new Error(`Did not expect anything but files in directory '${directory}', but found: ${dirEnt.name}`); } const path = directory + Path.sep + dirEnt.name; fs.unlinkSync(path); }); fs.rmdirSync(directory); } function getFileContents(path: fs.PathLike): string { return fs.readFileSync(path, {encoding: "utf-8"}); } function assertFile(paths: fs.PathLike[], name: string, expectedContent: string) { const foundFile = paths.find(path => path.toString().endsWith(name)); if (!foundFile) { throw new Error(`Failed to find file with name: ${name}`); } expect(getFileContents(foundFile)).toEqual(expectedContent); } function sleep(millis: number) { return new Promise((resolve) => { setTimeout(resolve, millis); }); } });
the_stack
import { Rule, RuleTester } from 'eslint' import { rule, name, Options } from 'rules/string-enum' import { SortingOrder } from 'common/options' import { typescript } from '../helpers/configs' import { InvalidTestCase, processInvalidTestCase, processValidTestCase, ValidTestCase, } from '../helpers/util' const valid: readonly ValidTestCase<Options>[] = [ /** * ignores */ { code: 'enum U {c, b, a}', optionsSet: [[]] }, { code: 'enum U {c=a(), b, a}', optionsSet: [[]] }, { code: 'enum U {c=0, b, a}', optionsSet: [[]] }, { code: 'enum U {c=3, b, a}', optionsSet: [[]] }, { code: 'enum U {c=1<<1, b, a}', optionsSet: [[]] }, { code: 'enum U {c=M|N, b, a}', optionsSet: [[]] }, { code: 'enum U {c="123".length, b, a}', optionsSet: [[]] }, { code: 'enum U {c=0, b="b", a}', optionsSet: [[]] }, { code: 'const enum U {A=1, B=A*2}', optionsSet: [[]] }, /** * default (asc) */ { code: 'enum U {_="a", a="b", b="c"}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {a="a", b="b", c="c"}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {a="a", b="b", b_="c"}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {C="a", b_="b", c="c"}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {$="a", A="b", _="c", a="d"}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: "enum U {'#'='a', 'Z'='b', À='c', è='d'}", optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {_="T", a="T", b="T"}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {a="T", b="T", c="T"}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {a="T", b="T", b_="T"}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {C="T", b_="T", c="T"}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {$="T", A="T", _="T", a="T"}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: "enum U {'#'='T', 'Z'='T', À='T', è='T'}", optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, /** * computed */ { code: '{a="T", ["aa"]="T", b="T", c="T"}', optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, /** * asc, insensitive */ { code: 'enum U {_="T", a="T", b="T"}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'enum U {a="T", b="T", c="T"}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'enum U {a="T", b="T", b_="T"}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'enum U {b_="T", C="T", c="T"}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'enum U {b_="T", c="T", C="T"}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'enum U {$="T", _="T", A="T", a="T"}', optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: "enum U {'#'='T', 'Z'='T', À='T', è='T'}", optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, /** * asc, natural, insensitive */ { code: 'enum U {_="T", a="T", b="T"}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {a="T", b="T", c="T"}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {a="T", b="T", b_="T"}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {b_="T", C="T", c="T"}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {b_="T", c="T", C="T"}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {$="T", _="T", A="T", a="T"}', optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: "enum U {'#'='T', 'Z'='T', À='T', è='T'}", optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, /** * desc */ { code: 'enum U {b="T", a="T", _="T"}', optionsSet: [[SortingOrder.Descending]] }, { code: 'enum U {c="T", b="T", a="T"}', optionsSet: [[SortingOrder.Descending]] }, { code: 'enum U {b_="T", b="T", a="T"}', optionsSet: [[SortingOrder.Descending]] }, { code: 'enum U {c="T", b_="T", C="T"}', optionsSet: [[SortingOrder.Descending]] }, { code: 'enum U {a="T", _="T", A="T", $="T"}', optionsSet: [[SortingOrder.Descending]] }, { code: "enum U {è='T', À='T', 'Z'='T', '#'='T'}", optionsSet: [[SortingOrder.Descending]] }, /** * desc, insensitive */ { code: 'enum U {b="T", a="T", _="T"}', optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'enum U {c="T", b="T", a="T"}', optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'enum U {b_="T", b="T", a="T"}', optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'enum U {c="T", C="T", b_="T"}', optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'enum U {C="T", c="T", b_="T"}', optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'enum U {a="T", A="T", _="T", $="T"}', optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: "enum U {è='T', À='T', 'Z'='T', '#'='T'}", optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, /** * desc, natural */ { code: 'enum U {b="T", a="T", _="T"}', optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'enum U {c="T", b="T", a="T"}', optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'enum U {b_="T", b="T", a="T"}', optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'enum U {c="T", b_="T", C="T"}', optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'enum U {a="T", A="T", _="T", $="T"}', optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: "enum U {è='T', À='T', 'Z'='T', '#'='T'}", optionsSet: [[SortingOrder.Descending, { natural: true }]], }, /** * desc, natural, insensitive */ { code: 'enum U {b="T", a="T", _="T"}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {c="T", b="T", a="T"}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {b_="T", b="T", a="T"}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {c="T", C="T", b_="T"}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {C="T", c="T", b_="T"}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {a="T", A="T", _="T", $="T"}', optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: "enum U {è='T', À='T', 'Z'='T', '#'='T'}", optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, ] const invalid: readonly InvalidTestCase<Options>[] = [ /** * default (asc) */ { code: 'enum U {a="a", _="b", b="c"}', output: 'enum U {_="b", a="a", b="c"}', errors: ["Expected string enum members to be in ascending order. '_' should be before 'a'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {a="T", c="T", b="T"}', output: 'enum U {a="T", b="T", c="T"}', errors: ["Expected string enum members to be in ascending order. 'b' should be before 'c'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {b_="T", a="T", b="T"}', output: 'enum U {a="T", b_="T", b="T"}', errors: ["Expected string enum members to be in ascending order. 'a' should be before 'b_'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {b_="T", c="T", C="T"}', output: 'enum U {C="T", c="T", b_="T",}', errors: ["Expected string enum members to be in ascending order. 'C' should be before 'c'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {$="T", _="T", A="T", a="T"}', output: 'enum U {$="T", A="T", _="T", a="T"}', errors: ["Expected string enum members to be in ascending order. 'A' should be before '_'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: "enum U {'#'='T', À='T', 'Z'='T', è='T'}", output: "enum U {'#'='T', 'Z'='T', À='T', è='T'}", errors: ["Expected string enum members to be in ascending order. 'Z' should be before 'À'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, /** * not ignore simple computed properties. */ { code: 'enum U {a="T", b="T", ["aa"]="T", c="T"}', output: 'enum U {a="T", ["aa"]="T", b="T", c="T"}', errors: ["Expected string enum members to be in ascending order. 'aa' should be before 'b'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, /** * asc */ { code: 'enum U {a="T", _="T", b="T"}', output: 'enum U {_="T", a="T", b="T"}', errors: ["Expected string enum members to be in ascending order. '_' should be before 'a'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {a="T", c="T", b="T"}', output: 'enum U {a="T", b="T", c="T"}', errors: ["Expected string enum members to be in ascending order. 'b' should be before 'c'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {b_="T", a="T", b="T"}', output: 'enum U {a="T", b_="T", b="T"}', errors: ["Expected string enum members to be in ascending order. 'a' should be before 'b_'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {b_="T", c="T", C="T"}', output: 'enum U {C="T", c="T", b_="T",}', errors: ["Expected string enum members to be in ascending order. 'C' should be before 'c'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: 'enum U {$="T", _="T", A="T", a="T"}', output: 'enum U {$="T", A="T", _="T", a="T"}', errors: ["Expected string enum members to be in ascending order. 'A' should be before '_'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, { code: "enum U {'#'='T', À='T', 'Z'='T', è='T'}", output: "enum U {'#'='T', 'Z'='T', À='T', è='T'}", errors: ["Expected string enum members to be in ascending order. 'Z' should be before 'À'."], optionsSet: [ [], [SortingOrder.Ascending], [SortingOrder.Ascending, { caseSensitive: true }], [SortingOrder.Ascending, { natural: false }], [SortingOrder.Ascending, { caseSensitive: true, natural: false }], ], }, /** * asc, insensitive */ { code: 'enum U {a="T", _="T", b="T"}', output: 'enum U {_="T", a="T", b="T"}', errors: [ "Expected string enum members to be in insensitive ascending order. '_' should be before 'a'.", ], optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'enum U {a="T", c="T", b="T"}', output: 'enum U {a="T", b="T", c="T"}', errors: [ "Expected string enum members to be in insensitive ascending order. 'b' should be before 'c'.", ], optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'enum U {b_="T", a="T", b="T"}', output: 'enum U {a="T", b_="T", b="T"}', errors: [ "Expected string enum members to be in insensitive ascending order. 'a' should be before 'b_'.", ], optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: 'enum U {$="T", A="T", _="T", a="T"}', output: 'enum U {$="T", _="T", A="T", a="T"}', errors: [ "Expected string enum members to be in insensitive ascending order. '_' should be before 'A'.", ], optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, { code: "enum U {'#'='T', À='T', 'Z'='T', è='T'}", output: "enum U {'#'='T', 'Z'='T', À='T', è='T'}", errors: [ "Expected string enum members to be in insensitive ascending order. 'Z' should be before 'À'.", ], optionsSet: [[SortingOrder.Ascending, { caseSensitive: false }]], }, /** * asc, natural */ { code: 'enum U {a="T", _="T", b="T"}', output: 'enum U {_="T", a="T", b="T"}', errors: [ "Expected string enum members to be in natural ascending order. '_' should be before 'a'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, { code: 'enum U {a="T", c="T", b="T"}', output: 'enum U {a="T", b="T", c="T"}', errors: [ "Expected string enum members to be in natural ascending order. 'b' should be before 'c'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, { code: 'enum U {b_="T", a="T", b="T"}', output: 'enum U {a="T", b_="T", b="T"}', errors: [ "Expected string enum members to be in natural ascending order. 'a' should be before 'b_'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, { code: 'enum U {b_="T", c="T", C="T"}', output: 'enum U {C="T", c="T", b_="T",}', errors: [ "Expected string enum members to be in natural ascending order. 'C' should be before 'c'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, { code: 'enum U {$="T", A="T", _="T", a="T"}', output: 'enum U {$="T", _="T", A="T", a="T"}', errors: [ "Expected string enum members to be in natural ascending order. '_' should be before 'A'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, { code: "enum U {'#'='T', À='T', 'Z'='T', è='T'}", output: "enum U {'#'='T', 'Z'='T', À='T', è='T'}", errors: [ "Expected string enum members to be in natural ascending order. 'Z' should be before 'À'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true }]], }, /** * asc, natural, insensitive */ { code: 'enum U {a="T", _="T", b="T"}', output: 'enum U {_="T", a="T", b="T"}', errors: [ "Expected string enum members to be in natural insensitive ascending order. '_' should be before 'a'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {a="T", c="T", b="T"}', output: 'enum U {a="T", b="T", c="T"}', errors: [ "Expected string enum members to be in natural insensitive ascending order. 'b' should be before 'c'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {b_="T", a="T", b="T"}', output: 'enum U {a="T", b_="T", b="T"}', errors: [ "Expected string enum members to be in natural insensitive ascending order. 'a' should be before 'b_'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {$="T", A="T", _="T", a="T"}', output: 'enum U {$="T", _="T", A="T", a="T"}', errors: [ "Expected string enum members to be in natural insensitive ascending order. '_' should be before 'A'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, { code: "enum U {'#'='T', À='T', 'Z'='T', è='T'}", output: "enum U {'#'='T', 'Z'='T', À='T', è='T'}", errors: [ "Expected string enum members to be in natural insensitive ascending order. 'Z' should be before 'À'.", ], optionsSet: [[SortingOrder.Ascending, { natural: true, caseSensitive: false }]], }, /** * desc */ { code: 'enum U {a="T", _="T", b="T"}', output: 'enum U {b="T", _="T", a="T",}', errors: ["Expected string enum members to be in descending order. 'b' should be before '_'."], optionsSet: [[SortingOrder.Descending]], }, { code: 'enum U {a="T", c="T", b="T"}', output: 'enum U {c="T", a="T", b="T"}', errors: ["Expected string enum members to be in descending order. 'c' should be before 'a'."], optionsSet: [[SortingOrder.Descending]], }, { code: 'enum U {b_="T", a="T", b="T"}', output: 'enum U {b_="T", b="T", a="T"}', errors: ["Expected string enum members to be in descending order. 'b' should be before 'a'."], optionsSet: [[SortingOrder.Descending]], }, { code: 'enum U {b_="T", c="T", C="T"}', output: 'enum U {c="T", b_="T", C="T"}', errors: ["Expected string enum members to be in descending order. 'c' should be before 'b_'."], optionsSet: [[SortingOrder.Descending]], }, { code: 'enum U {$="T", _="T", A="T", a="T"}', output: 'enum U {a="T", _="T", A="T", $="T"}', errors: [ "Expected string enum members to be in descending order. '_' should be before '$'.", "Expected string enum members to be in descending order. 'a' should be before 'A'.", ], optionsSet: [[SortingOrder.Descending]], }, { code: "enum U {'#'='T', À='T', 'Z'='T', è='T'}", output: "enum U {è='T', À='T', 'Z'='T', '#'='T'}", errors: [ "Expected string enum members to be in descending order. 'À' should be before '#'.", "Expected string enum members to be in descending order. 'è' should be before 'Z'.", ], optionsSet: [[SortingOrder.Descending]], }, /** * desc, insensitive */ { code: 'enum U {a="T", _="T", b="T"}', output: 'enum U {b="T", _="T", a="T",}', errors: [ "Expected string enum members to be in insensitive descending order. 'b' should be before '_'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'enum U {a="T", c="T", b="T"}', output: 'enum U {c="T", a="T", b="T"}', errors: [ "Expected string enum members to be in insensitive descending order. 'c' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'enum U {b_="T", a="T", b="T"}', output: 'enum U {b_="T", b="T", a="T"}', errors: [ "Expected string enum members to be in insensitive descending order. 'b' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'enum U {b_="T", c="T", C="T"}', output: 'enum U {c="T", b_="T", C="T"}', errors: [ "Expected string enum members to be in insensitive descending order. 'c' should be before 'b_'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: 'enum U {$="T", _="T", A="T", a="T"}', output: 'enum U {A="T", _="T", $="T", a="T"}', errors: [ "Expected string enum members to be in insensitive descending order. '_' should be before '$'.", "Expected string enum members to be in insensitive descending order. 'A' should be before '_'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, { code: "enum U {'#'='T', À='T', 'Z'='T', è='T'}", output: "enum U {è='T', À='T', 'Z'='T', '#'='T'}", errors: [ "Expected string enum members to be in insensitive descending order. 'À' should be before '#'.", "Expected string enum members to be in insensitive descending order. 'è' should be before 'Z'.", ], optionsSet: [[SortingOrder.Descending, { caseSensitive: false }]], }, /** * desc, natural */ { code: 'enum U {a="T", _="T", b="T"}', output: 'enum U {b="T", _="T", a="T",}', errors: [ "Expected string enum members to be in natural descending order. 'b' should be before '_'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'enum U {a="T", c="T", b="T"}', output: 'enum U {c="T", a="T", b="T"}', errors: [ "Expected string enum members to be in natural descending order. 'c' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'enum U {b_="T", a="T", b="T"}', output: 'enum U {b_="T", b="T", a="T"}', errors: [ "Expected string enum members to be in natural descending order. 'b' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'enum U {b_="T", c="T", C="T"}', output: 'enum U {c="T", b_="T", C="T"}', errors: [ "Expected string enum members to be in natural descending order. 'c' should be before 'b_'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: 'enum U {$="T", _="T", A="T", a="T"}', output: 'enum U {a="T", _="T", A="T", $="T"}', errors: [ "Expected string enum members to be in natural descending order. '_' should be before '$'.", "Expected string enum members to be in natural descending order. 'A' should be before '_'.", "Expected string enum members to be in natural descending order. 'a' should be before 'A'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, { code: "enum U {'#'='T', À='T', 'Z'='T', è='T'}", output: "enum U {è='T', À='T', 'Z'='T', '#'='T'}", errors: [ "Expected string enum members to be in natural descending order. 'À' should be before '#'.", "Expected string enum members to be in natural descending order. 'è' should be before 'Z'.", ], optionsSet: [[SortingOrder.Descending, { natural: true }]], }, /** * desc, natural, insensitive */ { code: 'enum U {a="T", _="T", b="T"}', output: 'enum U {b="T", _="T", a="T",}', errors: [ "Expected string enum members to be in natural insensitive descending order. 'b' should be before '_'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {a="T", c="T", b="T"}', output: 'enum U {c="T", a="T", b="T"}', errors: [ "Expected string enum members to be in natural insensitive descending order. 'c' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {b_="T", a="T", b="T"}', output: 'enum U {b_="T", b="T", a="T"}', errors: [ "Expected string enum members to be in natural insensitive descending order. 'b' should be before 'a'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {b_="T", c="T", C="T"}', output: 'enum U {c="T", b_="T", C="T"}', errors: [ "Expected string enum members to be in natural insensitive descending order. 'c' should be before 'b_'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: 'enum U {$="T", _="T", A="T", a="T"}', output: 'enum U {A="T", _="T", $="T", a="T"}', errors: [ "Expected string enum members to be in natural insensitive descending order. '_' should be before '$'.", "Expected string enum members to be in natural insensitive descending order. 'A' should be before '_'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, { code: "enum U {'#'='T', À='T', 'Z'='T', è='T'}", output: "enum U {è='T', À='T', 'Z'='T', '#'='T'}", errors: [ "Expected string enum members to be in natural insensitive descending order. 'À' should be before '#'.", "Expected string enum members to be in natural insensitive descending order. 'è' should be before 'Z'.", ], optionsSet: [[SortingOrder.Descending, { natural: true, caseSensitive: false }]], }, ] describe('TypeScript', () => { const ruleTester = new RuleTester(typescript) ruleTester.run(name, rule as unknown as Rule.RuleModule, { valid: processValidTestCase(valid), invalid: processInvalidTestCase(invalid), }) })
the_stack
import { Construct, Duration, IConstruct, aws_cloudwatch as cloudwatch, aws_codebuild as cbuild, aws_codepipeline as cpipeline, aws_codepipeline_actions as cpipeline_actions, aws_events as events, aws_events_targets as events_targets, aws_iam as iam, aws_s3 as s3, aws_sns as sns, aws_sns_subscriptions as sns_subs, } from 'monocdk'; import { AutoBuild, AutoBuildOptions } from './auto-build'; import { createBuildEnvironment } from './build-env'; import { Canary, CanaryProps } from './canary'; import { ChangeController } from './change-controller'; import { ChimeNotifier } from './chime-notifier'; import { PipelineWatcher } from './pipeline-watcher'; import * as publishing from './publishing'; import { AutoBump, AutoMergeBack, AutoBumpProps } from './pull-request'; import { AutoMergeBackPipelineOptions } from './pull-request/merge-back'; import { IRepo, WritableGitHubRepo } from './repo'; import { Shellable, ShellableProps } from './shellable'; import { determineRunOrder, flatMap } from './util'; const PUBLISH_STAGE_NAME = 'Publish'; const TEST_STAGE_NAME = 'Test'; const METRIC_NAMESPACE = 'CDK/Delivlib'; const FAILURE_METRIC_NAME = 'Failures'; export interface PipelineProps { /** * The source repository to build (e.g. GitHubRepo). */ readonly repo: IRepo; /** * A display name for this pipeline. */ readonly title?: string; /** * A physical name for this pipeline. * @default - a new name will be generated. */ readonly pipelineName?: string; /** * Branch to build. * @default master */ readonly branch?: string; /** * Email to send failure notifications. * @default - No email notifications */ readonly notificationEmail?: string; /** * The image used for the builds. * * @default jsii/superchain (see docs) */ readonly buildImage?: cbuild.IBuildImage; /** * The name of the CodeBuild project that will be part of this pipeline. * @default - `${pipelineName}-Build`, if `pipelineName` property is specified; automatically generated, otherwise. */ readonly buildProjectName?: string; /** * The type of compute to use for this build. * See the {@link ComputeType} enum for the possible values. * * @default taken from {@link #buildImage#defaultComputeType} */ readonly computeType?: cbuild.ComputeType; /** * Indicates how the project builds Docker images. Specify true to enable * running the Docker daemon inside a Docker container. This value must be * set to true only if this build project will be used to build Docker * images, and the specified build environment image is not one provided by * AWS CodeBuild with Docker support. Otherwise, all associated builds that * attempt to interact with the Docker daemon will fail. * * @default false */ readonly privileged?: boolean; /** * Environment variables to pass to build */ readonly environment?: { [key: string]: string }; /** * Optional buildspec, as an alternative to a buildspec.yml file */ readonly buildSpec?: cbuild.BuildSpec; /** * Indicates whether to re-run the pipeline after you've updated it. * @default true */ readonly restartExecutionOnUpdate?: boolean; /** * Indicates the concurrency limit test and publish stages. * * For example, if this value is 2, then only two actions will execute concurrently. * If this value is 1, the pipeline will not have any concurrent execution. * * @default - no limit */ readonly concurrency?: number; /** * Set the default dryRun for all publishing steps * * (Can still be changed when adding a step). * * @default false */ readonly dryRun?: boolean; /** * Automatically build commits that are pushed to this repository, including PR builds on github. * * @default false */ readonly autoBuild?: boolean; /** * Options for auto-build * * @default - 'autoBuildOptions.publicLogs' will be set to its default. 'autoBuildOptions.buildspec' will be configured to match with the * 'buildSpec' property. */ readonly autoBuildOptions?: AutoBuildOptions; /** * Post a notification to the given Chime webhooks if the pipeline fails * @default - no Chime notifications on pipeline failure * @deprecated - use `notifyOnFailure()` instead in combination with `PipelineNotification.chime()`. */ readonly chimeFailureWebhooks?: string[]; /** * The Chime message to post * * @default - A default message */ readonly chimeMessage?: string; /** * Build timeout * * How long the build can take at maximum (before failing with an error). * * @default - Duration.hours(8) */ readonly buildTimeout?: Duration; } export interface PipelineNotificationBindOptions { readonly pipeline: Pipeline; } export interface IPipelineNotification { bind(pipeline: PipelineNotificationBindOptions): void; } /** * Options for configuring an auto bump for this pipeline. */ export interface AutoBumpOptions extends Omit<AutoBumpProps, 'repo'> { } /** * Defines a delivlib CI/CD pipeline. */ export class Pipeline extends Construct { public buildRole?: iam.IRole; public readonly failureAlarm: cloudwatch.Alarm; public readonly buildOutput: cpipeline.Artifact; public readonly sourceArtifact: cpipeline.Artifact; /** * The primary CodeBuild project of this pipeline. */ public readonly buildProject: cbuild.IProject; /** * The auto build project. undefined if 'autoBuild' is disabled for this pipeline. */ public readonly autoBuildProject?: cbuild.Project; /* * The underlying CodePipeline Pipeline object that models this pipeline. */ public readonly pipeline: cpipeline.Pipeline; private readonly branch: string; private readonly notify?: sns.Topic; private stages: { [name: string]: cpipeline.IStage } = { }; private readonly concurrency?: number; private readonly repo: IRepo; private readonly dryRun: boolean; private readonly buildEnvironment: cbuild.BuildEnvironment; private readonly buildSpec?: cbuild.BuildSpec; private firstPublishStageName?: string; constructor(parent: Construct, name: string, props: PipelineProps) { super(parent, name); this.concurrency = props.concurrency; this.repo = props.repo; this.dryRun = !!props.dryRun; this.pipeline = new cpipeline.Pipeline(this, 'BuildPipeline', { pipelineName: props.pipelineName, restartExecutionOnUpdate: props.restartExecutionOnUpdate === undefined ? true : props.restartExecutionOnUpdate, }); this.branch = props.branch || 'master'; this.sourceArtifact = props.repo.createSourceStage(this.pipeline, this.branch); this.buildEnvironment = createBuildEnvironment(props); this.buildSpec = props.buildSpec; let buildProjectName = props.buildProjectName; if (buildProjectName === undefined && props.pipelineName !== undefined) { buildProjectName = `${props.pipelineName}-Build`; } this.buildProject = new cbuild.PipelineProject(this, 'BuildProject', { projectName: buildProjectName, environment: this.buildEnvironment, buildSpec: this.buildSpec, timeout: props.buildTimeout ?? Duration.hours(8), }); this.buildRole = this.buildProject.role; const buildStage = this.getOrCreateStage('Build'); const buildOutput = new cpipeline.Artifact(); buildStage.addAction(new cpipeline_actions.CodeBuildAction({ actionName: 'Build', project: this.buildProject, input: this.sourceArtifact, outputs: [buildOutput], })); this.buildOutput = buildOutput; if (props.notificationEmail) { this.notify = new sns.Topic(this, 'NotificationsTopic'); this.notify.addSubscription(new sns_subs.EmailSubscription(props.notificationEmail)); } // add a failure alarm for the entire pipeline. this.failureAlarm = this.addFailureAlarm(props.title); // emit an SNS notification every time build fails. this.addBuildFailureNotification(this.buildProject, `${props.title} build failed`); // Also emit to Chime webhooks if configured if (props.chimeFailureWebhooks) { new ChimeNotifier(this, 'ChimeNotifier', { pipeline: this.pipeline, message: props.chimeMessage, webhookUrls: props.chimeFailureWebhooks, }); } if (props.autoBuild) { this.autoBuildProject = this.autoBuild(props.autoBuildOptions).project; } } public notifyOnFailure(notification: IPipelineNotification) { notification.bind({ pipeline: this, }); } /** * Add an action to run a shell script to the pipeline * * @return The Shellable and the Action added to the pipeline. */ public addShellable(stageName: string, id: string, options: AddShellableOptions): { shellable: Shellable; action: cpipeline_actions.CodeBuildAction;} { const stage = this.getOrCreateStage(stageName); const sh = new Shellable(this, id, options); const action = sh.addToPipeline( stage, options.actionName || `Action${id}`, options.inputArtifact || this.buildOutput, this.determineRunOrderForNewAction(stage)); if (options.failureNotification) { this.addBuildFailureNotification(sh.project, options.failureNotification); } return { shellable: sh, action }; } public addTest(id: string, props: ShellableProps): {shellable: Shellable; action: cpipeline_actions.CodeBuildAction} { return this.addShellable(TEST_STAGE_NAME, id, { actionName: `Test${id}`, failureNotification: `Test ${id} failed`, ...props, }); } /** * Convenience/discovery method that defines a canary test in your account. * @param id the construct id * @param props canary options */ public addCanary(id: string, props: CanaryProps) { return new Canary(this, `Canary${id}`, props); } public addPublish(publisher: IPublisher, options: AddPublishOptions = {}) { const publishStageName = options.stageName ?? PUBLISH_STAGE_NAME; if (!this.firstPublishStageName) { this.firstPublishStageName = publishStageName; } const stage = this.getOrCreateStage(publishStageName); publisher.addToPipeline(stage, `${publisher.node.id}Publish`, { inputArtifact: options.inputArtifact || this.buildOutput, runOrder: this.determineRunOrderForNewAction(stage), }); } /** * Adds a change control policy to block transitions into the publish stage during certain time windows. * @param options the options to configure the change control policy. */ public addChangeControl(options: AddChangeControlOptions = { }): ChangeController { const publishStage = this.getStage(this.firstPublishStageName ?? PUBLISH_STAGE_NAME); if (!publishStage) { throw new Error(`This pipeline does not have a ${PUBLISH_STAGE_NAME} stage yet. Add one first.`); } return new ChangeController(this, 'ChangeController', { ...options, pipelineStage: publishStage, }); } public publishToNpm(options: publishing.PublishToNpmProjectProps & AddPublishOptions) { this.addPublish(new publishing.PublishToNpmProject(this, 'Npm', { dryRun: this.dryRun, ...options, }), options); } public publishToMaven(options: publishing.PublishToMavenProjectProps & AddPublishOptions) { this.addPublish(new publishing.PublishToMavenProject(this, 'Maven', { dryRun: this.dryRun, ...options, }), options); } public publishToNuGet(options: publishing.PublishToNuGetProjectProps & AddPublishOptions) { this.addPublish(new publishing.PublishToNuGetProject(this, 'NuGet', { dryRun: this.dryRun, ...options, }), options); } public publishToGitHubPages(options: publishing.PublishDocsToGitHubProjectProps & AddPublishOptions) { this.addPublish(new publishing.PublishDocsToGitHubProject(this, 'GitHubPages', { dryRun: this.dryRun, ...options, }), options); } public publishToGitHub(options: publishing.PublishToGitHubProps & AddPublishOptions) { this.addPublish(new publishing.PublishToGitHub(this, 'GitHub', { dryRun: this.dryRun, ...options, }), options); } public publishToPyPI(options: publishing.PublishToPyPiProps & AddPublishOptions) { this.addPublish(new publishing.PublishToPyPi(this, 'PyPI', { dryRun: this.dryRun, ...options, }), options); } public publishToS3(id: string, options: publishing.PublishToS3Props & AddPublishOptions) { this.addPublish(new publishing.PublishToS3(this, id, { dryRun: this.dryRun, ...options, }), options); } /** * Publish Golang code from `go` directory in build artifact to a GitHub repository. */ public publishToGolang(options: publishing.PublishToGolangProps) { this.addPublish(new publishing.PublishToGolang(this, 'Golang', { dryRun: this.dryRun, ...options, })); } /** * Enables automatic bumps for the source repo. * @param options Options for auto bump (see AutoBumpOptions for description of defaults) */ public autoBump(options?: AutoBumpOptions): AutoBump { if (!WritableGitHubRepo.isWritableGitHubRepo(this.repo)) { throw new Error('"repo" must be a WritableGitHubRepo in order to enable auto-bump'); } const autoBump = new AutoBump(this, 'AutoBump', { repo: this.repo, ...options, }); return autoBump; } /** * Enables automatic merge backs for the source repo. * @param options Options for auto bump (see AutoMergeBackPipelineOptions for description of defaults) */ public autoMergeBack(options?: AutoMergeBackPipelineOptions) { if (!WritableGitHubRepo.isWritableGitHubRepo(this.repo)) { throw new Error('"repo" must be a WritableGitHubRepo in order to enable auto-merge-back'); } const mergeBack = new AutoMergeBack(this, 'MergeBack', { repo: this.repo, ...options, }); if (options?.stage) { const afterStage = this.getStage(options.stage.after); if (!afterStage) { throw new Error(`'options.stage.after' must be configured to an existing stage: ${options.stage.after}`); } const stage = this.getOrCreateStage(options.stage.name ?? 'MergeBack', { justAfter: afterStage }); stage.addAction(new cpipeline_actions.CodeBuildAction({ actionName: 'CreateMergeBackPullRequest', project: mergeBack.pr.project, input: this.sourceArtifact, })); } } /** * Enables automatic builds of pull requests in the Github repository and posts the * results back as a comment with a public link to the build logs. */ public autoBuild(options: AutoBuildOptions = { }): AutoBuild { return new AutoBuild(this, 'AutoBuild', { environment: this.buildEnvironment, repo: this.repo, buildSpec: options.buildSpec || this.buildSpec, ...options, }); } /** * The metric that tracks pipeline failures. */ public metricFailures(options: cloudwatch.MetricOptions): cloudwatch.Metric { return new cloudwatch.Metric({ namespace: METRIC_NAMESPACE, metricName: FAILURE_METRIC_NAME, dimensions: { Pipeline: this.pipeline.pipelineName, }, statistic: 'Sum', ...options, }); } /** * The metrics that track failure of each action within the pipeline. */ public metricActionFailures(options: cloudwatch.MetricOptions): cloudwatch.Metric[] { return flatMap(this.pipeline.stages, stage => stage.actions.map(action => { return new cloudwatch.Metric({ namespace: METRIC_NAMESPACE, metricName: FAILURE_METRIC_NAME, dimensions: { Pipeline: this.pipeline.pipelineName, Action: action.actionProperties.actionName, }, statistic: 'Sum', ...options, }); })); } private addFailureAlarm(title?: string): cloudwatch.Alarm { return new PipelineWatcher(this, 'PipelineWatcher', { pipeline: this.pipeline, metricNamespace: METRIC_NAMESPACE, failureMetricName: FAILURE_METRIC_NAME, title, }).alarm; } private addBuildFailureNotification(buildProject: cbuild.IProject, message: string) { if (!this.notify) { return; } buildProject.onBuildFailed('OnBuildFailed').addTarget(new events_targets.SnsTopic(this.notify, { message: events.RuleTargetInput.fromText(message), })); } /** * @returns the stage or undefined if the stage doesn't exist */ private getStage(stageName: string): cpipeline.IStage | undefined { return this.stages[stageName]; } private getOrCreateStage(stageName: string, placement?: cpipeline.StagePlacement): cpipeline.IStage { // otherwise, group all actions so they run concurrently. let stage = this.getStage(stageName); if (!stage) { stage = this.pipeline.addStage({ stageName, placement, }); this.stages[stageName] = stage; } return stage; } private determineRunOrderForNewAction(stage: cpipeline.IStage): number | undefined { return determineRunOrder(stage.actions.length, this.concurrency); } } export interface IPublisher extends IConstruct { addToPipeline(stage: cpipeline.IStage, id: string, options: AddToPipelineOptions): void; } export interface AddToPipelineOptions { inputArtifact?: cpipeline.Artifact; runOrder?: number; } export interface AddChangeControlOptions { /** * The bucket in which the ChangeControl iCal document will be stored. * * @default a new bucket will be provisioned. */ changeControlBucket?: s3.IBucket; /** * The key in which the iCal fille will be stored. * * @default 'change-control.ical' */ changeControlObjectKey?: string; /** * Schedule to run the change controller on * * @default rate(15 minutes) */ scheduleExpression?: string; } export interface AddPublishOptions { /** * The input artifact to use * * @default Build output artifact */ inputArtifact?: cpipeline.Artifact; /** * Stage name to add publishing job to * * By default, this will be the stage name `'Publish'`, but if you want to * separate out the publishing actions into different stages (in order to * block/unblock them separately for example) you can change this. * * Stages appear in the pipeline in the order they are referenced for * the first time. * * @default "Publish" */ readonly stageName?: string; } export interface AddShellableOptions extends ShellableProps { /** * String to use as action name * * @default Id */ actionName?: string; /** * Message to use as failure notification * * @default No notification */ failureNotification?: string; /** * The input artifact to use * * @default Build output artifact */ inputArtifact?: cpipeline.Artifact; }
the_stack
import { html, TemplateResult } from '@spectrum-web-components/base'; import '../sp-slider.js'; import '../sp-slider-handle.js'; import { Slider, SliderHandle, variants } from '../'; import { spreadProps } from '@open-wc/lit-helpers'; export default { component: 'sp-slider', title: 'Slider', argTypes: { onInput: { action: 'input' }, onChange: { action: 'change' }, variant: { name: 'Variant', description: 'Determines the style of slider.', table: { type: { summary: 'string' }, defaultValue: { summary: undefined }, }, control: { type: 'inline-radio', options: [undefined, ...variants], }, }, tickStep: { name: 'Tick Step', description: 'Tick spacing on slider.', table: { type: { summary: 'number' }, defaultValue: { summary: 0.1 }, }, control: { type: 'number', }, }, labelVisibility: { name: 'Label Visibility', description: 'The labels visibily available in the UI', table: { type: { summary: '"text" | "value" | "none" | undefined' }, defaultValue: { summary: undefined }, }, control: { type: 'text', }, }, }, args: { variant: undefined, tickStep: 0.1, labelVisibility: undefined, }, }; export interface StoryArgs { variant?: string; tickStep?: number; labelVisibility?: string; onInput?: (val: string) => void; onChange?: (val: string) => void; } const handleEvent = ({ onInput, onChange }: StoryArgs) => (event: Event): void => { const { value } = event.target as Slider; if (onInput && event.type === 'input') { onInput(value.toString()); } else if (onChange && event.type === 'change') { onChange(value.toString()); } }; const handleHandleEvent = ({ onInput, onChange }: StoryArgs) => (event: Event): void => { const target = event.target as SliderHandle; if (target.value != null) { if (typeof target.value === 'object') { const value = JSON.stringify(target.value, null, 2); if (onInput && event.type === 'input') { onInput(value); } else if (onChange && event.type === 'change') { onChange(value); } } else { const value = `${target.name}: ${target.value}`; if (onInput && event.type === 'input') { onInput(value); } else if (onChange && event.type === 'change') { onChange(value); } } } }; export const Default = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider max="1" min="0" value=".5" step="0.01" @input=${handleEvent(args)} @change=${handleEvent(args)} .formatOptions=${{ style: 'percent' }} ...=${spreadProps(args)} > Opacity </sp-slider> </div> `; }; export const noVisibleTextLabel = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider max="1" min="0" value=".5" step="0.01" @input=${handleEvent(args)} @change=${handleEvent(args)} .formatOptions=${{ style: 'percent' }} ...=${spreadProps(args)} > Opacity </sp-slider> </div> `; }; noVisibleTextLabel.args = { labelVisibility: 'value', }; export const noVisibleValueLabel = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider max="1" min="0" value=".5" step="0.01" @input=${handleEvent(args)} @change=${handleEvent(args)} .formatOptions=${{ style: 'percent' }} ...=${spreadProps(args)} > Opacity </sp-slider> </div> `; }; noVisibleValueLabel.args = { labelVisibility: 'text', }; export const noVisibleLabels = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider max="1" min="0" value=".5" step="0.01" @input=${handleEvent(args)} @change=${handleEvent(args)} .formatOptions=${{ style: 'percent' }} ...=${spreadProps(args)} > Opacity </sp-slider> </div> `; }; noVisibleLabels.args = { labelVisibility: 'none', }; export const px = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider max="360" min="0" value="90" step="1" @input=${handleEvent(args)} @change=${handleEvent(args)} .formatOptions=${{ style: 'unit', unit: 'px', }} ...=${spreadProps(args)} > Angle </sp-slider> </div> `; }; class NumberFieldDefined extends HTMLElement { constructor() { super(); this.numberFieldLoaderPromise = new Promise((res) => { customElements.whenDefined('sp-number-field').then(() => { res(true); }); }); } private numberFieldLoaderPromise: Promise<boolean> = Promise.resolve(false); get updateComplete(): Promise<boolean> { return this.numberFieldLoaderPromise; } } customElements.define('number-field-defined', NumberFieldDefined); const editableDecorator = (story: () => TemplateResult): TemplateResult => { return html` ${story()} <number-field-defined></number-field-defined> `; }; export const editable = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider editable max="360" min="0" value="90" step="1" @input=${handleEvent(args)} @change=${handleEvent(args)} .formatOptions=${{ style: 'unit', unit: 'degree', unitDisplay: 'narrow', }} ...=${spreadProps(args)} > Angle </sp-slider> </div> `; }; editable.decorators = [editableDecorator]; export const editableDisabled = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider editable disabled max="360" min="0" value="90" step="1" @input=${handleEvent(args)} @change=${handleEvent(args)} .formatOptions=${{ style: 'unit', unit: 'degree', unitDisplay: 'narrow', }} ...=${spreadProps(args)} > Angle </sp-slider> </div> `; }; editable.decorators = [editableDecorator]; export const editableCustom = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px; --spectrum-slider-editable-number-field-width: 150px;" > <sp-slider editable max="24" min="0" value="12.75" step="0.25" @input=${handleEvent(args)} @change=${handleEvent(args)} .formatOptions=${{ style: 'unit', unit: 'hour' }} ...=${spreadProps(args)} > Hours </sp-slider> </div> `; }; editableCustom.decorators = [editableDecorator]; export const hideStepper = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider editable hide-stepper max="1" min="0" value=".5" step="0.01" @input=${handleEvent(args)} @change=${handleEvent(args)} .formatOptions=${{ style: 'percent' }} ...=${spreadProps(args)} > Opacity </sp-slider> </div> `; }; hideStepper.decorators = [editableDecorator]; export const Gradient = (args: StoryArgs = {}): TemplateResult => { return html` <div style=" width: 500px; margin: 12px 20px; --spectrum-slider-track-color:linear-gradient(to right, red, green 100%); --spectrum-slider-track-color-rtl:linear-gradient(to left, red, green 100%); " > <sp-slider label="Opacity" max="100" min="0" value="50" id="opacity-slider" @input=${handleEvent(args)} @change=${handleEvent(args)} ...=${spreadProps(args)} ></sp-slider> </div> `; }; Gradient.args = { variant: undefined, }; export const tick = (args: StoryArgs = {}): TemplateResult => { return html` <sp-slider label="Slider Label" variant="tick" min="0" max="92" ...=${spreadProps(args)} ></sp-slider> `; }; tick.args = { variant: 'tick', tickStep: 5, }; export const Disabled = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider disabled value="5" step="0.5" min="0" max="20" label="Intensity" ...=${spreadProps(args)} ></sp-slider> </div> `; }; export const ExplicitHandle = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider step="0.5" min="0" max="20" @input=${handleHandleEvent(args)} @change=${handleHandleEvent(args)} ...=${spreadProps(args)} > Intensity <sp-slider-handle slot="handle" value="5"></sp-slider-handle> </sp-slider> </div> `; }; export const TwoHandles = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider value="5" step="1" min="0" max="255" @input=${handleHandleEvent(args)} @change=${handleHandleEvent(args)} ...=${spreadProps(args)} > Output Levels <sp-slider-handle slot="handle" name="min" value="5" ></sp-slider-handle> <sp-slider-handle slot="handle" name="max" value="250" ></sp-slider-handle> </sp-slider> </div> `; }; TwoHandles.args = { variant: 'range', tickStep: 10, }; export const TwoHandlesPt = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider value="5" step="1" min="0" max="255" @input=${handleHandleEvent(args)} @change=${handleHandleEvent(args)} .formatOptions=${{ style: 'unit', unit: 'pt', }} ...=${spreadProps(args)} > Output Levels <sp-slider-handle slot="handle" name="min" value="5" ></sp-slider-handle> <sp-slider-handle slot="handle" name="max" value="250" ></sp-slider-handle> </sp-slider> </div> `; }; TwoHandlesPt.args = { variant: 'range', tickStep: 10, }; export const ThreeHandlesPc = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider value="5" step="1" min="0" max="255" @input=${handleHandleEvent(args)} @change=${handleHandleEvent(args)} .formatOptions=${{ style: 'unit', unit: 'pc', }} ...=${spreadProps(args)} > Output Levels <sp-slider-handle slot="handle" value="5"></sp-slider-handle> <sp-slider-handle slot="handle" value="133"></sp-slider-handle> <sp-slider-handle slot="handle" value="250"></sp-slider-handle> </sp-slider> </div> `; }; export const ThreeHandlesOrdered = (args: StoryArgs = {}): TemplateResult => { return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider step="1" min="0" max="255" @input=${handleHandleEvent(args)} @change=${handleHandleEvent(args)} ...=${spreadProps(args)} > Output Levels <sp-slider-handle slot="handle" name="low" value="5" max="next" ></sp-slider-handle> <sp-slider-handle slot="handle" name="mid" value="100" min="previous" max="next" ></sp-slider-handle> <sp-slider-handle slot="handle" name="high" value="250" min="previous" ></sp-slider-handle> </sp-slider> </div> `; }; ThreeHandlesOrdered.args = { tickStep: 10, }; // This is a very complex example from an actual application. // // The first and last handles go from 0 to 255 in a linear fashion. // The last and first handles are ordered so that the last handle // must be greater than or equal to the first handle. // // The middle handle's range goes from 9.99 to 0.01, counting down. // the middle handle's limits are set by the outer handles such that // the position of the left handle is the staring value (9.99) for the // middle handle. And the position of the right handle is the end // value (0.01). That means that the middle handle will move // proportionally as you move the outer handles. // // The two other interesting features of the middle handle are that // it counts down, and that it does so exponentially for the first // half of its range. // // Because the specification for the <input> tag in HTML says that the // min should be less than the max, we do a double normalization to make // this work. The middle handle is considered to go between 0 and 1, // where 0 is the left handle's position and 1 is the right handle's // position. We then do the appropriate calculation to convert that // value into one between 9.99 and 0.01 for display to the user. // // One iteresting thing to note is that the normalization function // can also be used to enforce clamping. // export const ThreeHandlesComplex = (args: StoryArgs = {}): TemplateResult => { const values: { [key: string]: number } = { black: 50, gray: 4.98, white: 225, }; const handleEvent = ({ onInput, onChange }: StoryArgs) => (event: Event): void => { const target = event.target as SliderHandle; if (target.value != null) { if (typeof target.value === 'object') { const value = JSON.stringify(target.value, null, 2); if (onInput && event.type === 'input') { onInput(value); } else if (onChange && event.type === 'change') { onChange(value); } } else { const value = `${target.name}: ${target.value}`; if (onInput && event.type === 'input') { onInput(value); } else if (onChange && event.type === 'change') { onChange(value); } } values[target.name] = target.value; } }; const grayNormalization = { toNormalized(value: number) { const normalizedBlack = values.black / 255; const normalizedWhite = values.white / 255; const clamped = Math.max(Math.min(value, 1), 0); return ( clamped * (normalizedWhite - normalizedBlack) + normalizedBlack ); }, fromNormalized(value: number) { const normalizedBlack = values.black / 255; const normalizedWhite = values.white / 255; const clamped = Math.max( Math.min(value, normalizedWhite), normalizedBlack ); return ( (clamped - normalizedBlack) / (normalizedWhite - normalizedBlack) ); }, }; const blackNormalization = { toNormalized(value: number) { const clamped = Math.min(value, values.white); return clamped / 255; }, fromNormalized(value: number) { const denormalized = value * 255; return Math.min(denormalized, values.white); }, }; const whiteNormalization = { toNormalized(value: number) { const clamped = Math.max(value, values.black); return clamped / 255; }, fromNormalized(value: number) { const denormalized = value * 255; return Math.max(denormalized, values.black); }, }; const computeGray = (value: number): string => { let result = 1.0; if (value > 0.5) { result = Math.max(2 * (1 - value), 0.01); } else if (value < 0.5) { result = ((1 - 2 * value) * (Math.sqrt(9.99) - 1) + 1) ** 2; } const formatOptions = { maximumFractionDigits: 2, minimumFractionDigits: 2, }; return new Intl.NumberFormat(navigator.language, formatOptions).format( result ); }; return html` <div style="width: 500px; margin: 12px 20px;"> <sp-slider step="1" min="0" max="255" @input=${handleEvent} @change=${handleEvent} ...=${spreadProps(args)} > Output Levels <sp-slider-handle slot="handle" name="black" value=${values.black} .normalization=${blackNormalization} ></sp-slider-handle> <sp-slider-handle slot="handle" name="gray" value="0.215" min="0" max="1" step="0.005" .normalization=${grayNormalization} .getAriaHandleText=${computeGray} ></sp-slider-handle> <sp-slider-handle slot="handle" name="white" value=${values.white} .normalization=${whiteNormalization} ></sp-slider-handle> </sp-slider> </div> `; }; ThreeHandlesOrdered.args = { tickStep: 10, }; export const focusTabDemo = (args: StoryArgs = {}): TemplateResult => { const value = 50; const min = 0; const max = 100; const step = 1; return html` <div style="width: 500px; margin: 12px 20px 20px;"> <sp-slider value="${value}" step="${step}" min="${min}" max="${max}" label="Opacity" id="opacity-slider-opacity" ...=${spreadProps(args)} ></sp-slider> </div> <div style="width: 500px; margin: 20px;"> <sp-slider value="${value}" step="${step}" min="${min}" max="${max}" label="Lightness" id="opacity-slider-lightness" ...=${spreadProps(args)} ></sp-slider> </div> <div style="width: 500px; margin: 20px 20px 12px;"> <sp-slider value="${value}" step="${step}" min="${min}" max="${max}" label="Saturation" id="opacity-slider-saturation" ...=${spreadProps(args)} ></sp-slider> </div> `; };
the_stack
// IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://www.googleapis.com/discovery/v1/apis/gamesConfiguration/v1configuration/rest /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Google Play Game Services Publishing API v1configuration */ function load(name: "gamesconfiguration", version: "v1configuration"): PromiseLike<void>; function load(name: "gamesconfiguration", version: "v1configuration", callback: () => any): void; const achievementConfigurations: gamesconfiguration.AchievementConfigurationsResource; const imageConfigurations: gamesconfiguration.ImageConfigurationsResource; const leaderboardConfigurations: gamesconfiguration.LeaderboardConfigurationsResource; namespace gamesconfiguration { interface AchievementConfiguration { /** * The type of the achievement. * Possible values are: * - "STANDARD" - Achievement is either locked or unlocked. * - "INCREMENTAL" - Achievement is incremental. */ achievementType?: string; /** The draft data of the achievement. */ draft?: AchievementConfigurationDetail; /** The ID of the achievement. */ id?: string; /** * The initial state of the achievement. * Possible values are: * - "HIDDEN" - Achievement is hidden. * - "REVEALED" - Achievement is revealed. * - "UNLOCKED" - Achievement is unlocked. */ initialState?: string; /** Uniquely identifies the type of this resource. Value is always the fixed string gamesConfiguration#achievementConfiguration. */ kind?: string; /** The read-only published data of the achievement. */ published?: AchievementConfigurationDetail; /** Steps to unlock. Only applicable to incremental achievements. */ stepsToUnlock?: number; /** The token for this resource. */ token?: string; } interface AchievementConfigurationDetail { /** Localized strings for the achievement description. */ description?: LocalizedStringBundle; /** The icon url of this achievement. Writes to this field are ignored. */ iconUrl?: string; /** Uniquely identifies the type of this resource. Value is always the fixed string gamesConfiguration#achievementConfigurationDetail. */ kind?: string; /** Localized strings for the achievement name. */ name?: LocalizedStringBundle; /** Point value for the achievement. */ pointValue?: number; /** The sort rank of this achievement. Writes to this field are ignored. */ sortRank?: number; } interface AchievementConfigurationListResponse { /** The achievement configurations. */ items?: AchievementConfiguration[]; /** Uniquely identifies the type of this resource. Value is always the fixed string games#achievementConfigurationListResponse. */ kind?: string; /** The pagination token for the next page of results. */ nextPageToken?: string; } interface GamesNumberAffixConfiguration { /** * When the language requires special treatment of "small" numbers (as with 2, 3, and 4 in Czech; or numbers ending 2, 3, or 4 but not 12, 13, or 14 in * Polish). */ few?: LocalizedStringBundle; /** When the language requires special treatment of "large" numbers (as with numbers ending 11-99 in Maltese). */ many?: LocalizedStringBundle; /** * When the language requires special treatment of numbers like one (as with the number 1 in English and most other languages; in Russian, any number * ending in 1 but not ending in 11 is in this class). */ one?: LocalizedStringBundle; /** When the language does not require special treatment of the given quantity (as with all numbers in Chinese, or 42 in English). */ other?: LocalizedStringBundle; /** When the language requires special treatment of numbers like two (as with 2 in Welsh, or 102 in Slovenian). */ two?: LocalizedStringBundle; /** When the language requires special treatment of the number 0 (as in Arabic). */ zero?: LocalizedStringBundle; } interface GamesNumberFormatConfiguration { /** The curreny code string. Only used for CURRENCY format type. */ currencyCode?: string; /** The number of decimal places for number. Only used for NUMERIC format type. */ numDecimalPlaces?: number; /** * The formatting for the number. * Possible values are: * - "NUMERIC" - Numbers are formatted to have no digits or a fixed number of digits after the decimal point according to locale. An optional custom unit * can be added. * - "TIME_DURATION" - Numbers are formatted to hours, minutes and seconds. * - "CURRENCY" - Numbers are formatted to currency according to locale. */ numberFormatType?: string; /** An optional suffix for the NUMERIC format type. These strings follow the same plural rules as all Android string resources. */ suffix?: GamesNumberAffixConfiguration; } interface ImageConfiguration { /** The image type for the image. */ imageType?: string; /** Uniquely identifies the type of this resource. Value is always the fixed string gamesConfiguration#imageConfiguration. */ kind?: string; /** The resource ID of resource which the image belongs to. */ resourceId?: string; /** The url for this image. */ url?: string; } interface LeaderboardConfiguration { /** The draft data of the leaderboard. */ draft?: LeaderboardConfigurationDetail; /** The ID of the leaderboard. */ id?: string; /** Uniquely identifies the type of this resource. Value is always the fixed string gamesConfiguration#leaderboardConfiguration. */ kind?: string; /** The read-only published data of the leaderboard. */ published?: LeaderboardConfigurationDetail; /** Maximum score that can be posted to this leaderboard. */ scoreMax?: string; /** Minimum score that can be posted to this leaderboard. */ scoreMin?: string; /** * The type of the leaderboard. * Possible values are: * - "LARGER_IS_BETTER" - Larger scores posted are ranked higher. * - "SMALLER_IS_BETTER" - Smaller scores posted are ranked higher. */ scoreOrder?: string; /** The token for this resource. */ token?: string; } interface LeaderboardConfigurationDetail { /** The icon url of this leaderboard. Writes to this field are ignored. */ iconUrl?: string; /** Uniquely identifies the type of this resource. Value is always the fixed string gamesConfiguration#leaderboardConfigurationDetail. */ kind?: string; /** Localized strings for the leaderboard name. */ name?: LocalizedStringBundle; /** The score formatting for the leaderboard. */ scoreFormat?: GamesNumberFormatConfiguration; /** The sort rank of this leaderboard. Writes to this field are ignored. */ sortRank?: number; } interface LeaderboardConfigurationListResponse { /** The leaderboard configurations. */ items?: LeaderboardConfiguration[]; /** Uniquely identifies the type of this resource. Value is always the fixed string games#leaderboardConfigurationListResponse. */ kind?: string; /** The pagination token for the next page of results. */ nextPageToken?: string; } interface LocalizedString { /** Uniquely identifies the type of this resource. Value is always the fixed string gamesConfiguration#localizedString. */ kind?: string; /** The locale string. */ locale?: string; /** The string value. */ value?: string; } interface LocalizedStringBundle { /** Uniquely identifies the type of this resource. Value is always the fixed string gamesConfiguration#localizedStringBundle. */ kind?: string; /** The locale strings. */ translations?: LocalizedString[]; } interface AchievementConfigurationsResource { /** Delete the achievement configuration with the given ID. */ delete(request: { /** The ID of the achievement used by this method. */ achievementId: string; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Retrieves the metadata of the achievement configuration with the given ID. */ get(request: { /** The ID of the achievement used by this method. */ achievementId: string; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<AchievementConfiguration>; /** Insert a new achievement configuration in this application. */ insert(request: { /** Data format for the response. */ alt?: string; /** The application ID from the Google Play developer console. */ applicationId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<AchievementConfiguration>; /** Returns a list of the achievement configurations in this application. */ list(request: { /** Data format for the response. */ alt?: string; /** The application ID from the Google Play developer console. */ applicationId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The maximum number of resource configurations to return in the response, used for paging. For any response, the actual number of resources returned may * be less than the specified maxResults. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The token returned by the previous request. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<AchievementConfigurationListResponse>; /** Update the metadata of the achievement configuration with the given ID. This method supports patch semantics. */ patch(request: { /** The ID of the achievement used by this method. */ achievementId: string; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<AchievementConfiguration>; /** Update the metadata of the achievement configuration with the given ID. */ update(request: { /** The ID of the achievement used by this method. */ achievementId: string; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<AchievementConfiguration>; } interface ImageConfigurationsResource { /** Uploads an image for a resource with the given ID and image type. */ upload(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** Selects which image in a resource for this method. */ imageType: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the resource used by this method. */ resourceId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<ImageConfiguration>; } interface LeaderboardConfigurationsResource { /** Delete the leaderboard configuration with the given ID. */ delete(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The ID of the leaderboard. */ leaderboardId: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Retrieves the metadata of the leaderboard configuration with the given ID. */ get(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The ID of the leaderboard. */ leaderboardId: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<LeaderboardConfiguration>; /** Insert a new leaderboard configuration in this application. */ insert(request: { /** Data format for the response. */ alt?: string; /** The application ID from the Google Play developer console. */ applicationId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<LeaderboardConfiguration>; /** Returns a list of the leaderboard configurations in this application. */ list(request: { /** Data format for the response. */ alt?: string; /** The application ID from the Google Play developer console. */ applicationId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The maximum number of resource configurations to return in the response, used for paging. For any response, the actual number of resources returned may * be less than the specified maxResults. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The token returned by the previous request. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<LeaderboardConfigurationListResponse>; /** Update the metadata of the leaderboard configuration with the given ID. This method supports patch semantics. */ patch(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The ID of the leaderboard. */ leaderboardId: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<LeaderboardConfiguration>; /** Update the metadata of the leaderboard configuration with the given ID. */ update(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The ID of the leaderboard. */ leaderboardId: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<LeaderboardConfiguration>; } } }
the_stack
* @file Conversion from independent triangles to triangle strips. * * http://www.codercorner.com/Strips.htm */ import {hashCombine} from 'neuroglancer/gpu_hash/hash_function'; import {MeshVertexIndices} from 'neuroglancer/mesh/base'; const DEBUG_TIMING = false; /** * Sorts the vertex indices for each triangle in ascending order. * * This ensures later edge comparisons can be done more efficiently. This can reverse face * orientations, which would normally be a problem, but since we render all faces as double-sided it * isn't an issue. */ function normalizeTriangleVertexOrder(indices: MeshVertexIndices) { let maxVertex = 0; for (let i = 0, length = indices.length; i < length; i += 3) { let a = indices[i], b = indices[i + 1], c = indices[i + 2]; let t: number; if (a > b) { t = a; a = b; b = t; } if (b > c) { t = b; b = c; c = t; } if (a > b) { t = a; a = b; b = t; } indices[i] = a; indices[i + 1] = b; indices[i + 2] = c; if (c > maxVertex) maxVertex = c; } return maxVertex; } let collisions = 0; function hashTableInsert( table: Uint32Array, numBuckets: number, value: number, emptyValue: number, hashCode: number, equals: (x: number) => boolean) { const mask = (numBuckets - 1) >>> 0; let bucket = (hashCode & mask) >>> 0; for (let probe = 0; true; ++probe) { const x = table[bucket]; if (x === emptyValue) { table[bucket] = value; return value; } if (equals(x)) { return x; } ++collisions; bucket = ((bucket + probe + 1) & mask) >>> 0; } } function hashEdge(a: number, b: number) { return hashCombine(hashCombine(0, a), b); } // edgeIndex: 0, 1, 2 // vertexA: 0 0 1 <- bit 1 // vertexB: 1 2 2 <- 1 + bit 1 of (edgeIndex + 1) // vertexC: 2 1 0 <- 2 - edgeIndex // BC 2 2 1 // BC flipped 0 1 1 // AC 1 0 0 // AC flipped 0 0 1 // Lookup table, where the 3 bits starting at (edgeIndex * 3 + flipped * 12) specify the new value // of `edgeIndexAndFlipped`. const nextEdgeTable = 0b1_00_0_00_0_01_000_1_01_1_10_0_10; /** * Computes the edge index and flipped state in a triangle strip for the next edge after the given * edge. * * @param edgeIndexAndFlipped Bits 0,1 specify the `edgeIndex` in the range `[0, 2]` corresponding * to the last edge that was traversed. Bit 2 specifies the `flipped` state. If `flipped` is * equal to 0, the last two emitted vertices are B and C relative to `edgeIndex`. If `flipped` * is equal to 1, the last two emitted vertices are A and C relative to `edgeIndex`. * @returns The next `edgeIndexAndFlipped` value specifying `nextEdgeIndex` and `nextFlipped`. If * `flipped == 0`, `nextEdgeIndex` corresponds to the B-C edge relative to `edgeIndex`; if * `flipped == 1`, `nextEdgeIndex` correspond to the A-C edge relative to `edgeIndex`. The * `nextFlipped` value is equal to 1 iff `vertexCIndex(edgeIndex) == * vertexAIndex(nextEdgeIndex)`. */ export function getNextEdge(edgeIndexAndFlipped: number) { return (nextEdgeTable >>> (edgeIndexAndFlipped * 3)) & 7; } export function getBaseIndex(entry: number) { return (entry >>> 2) * 3; } export function getEdgeIndex(entry: number) { return entry & 3; } /** * Computes the first vertex offset for the given edge. * * @returns `[0, 0, 1][edgeIndex]` */ export function vertexAIndex(edgeIndex: number) { return edgeIndex >>> 1; } /** * Computes the second vertex offset for the given edge. * * @returns `[1, 2, 2][edgeIndex]` */ export function vertexBIndex(edgeIndex: number) { return 1 + ((edgeIndex + 1) >>> 1); } /** * Computes the opposite vertex offset for the given edge. * * @returns `[2, 1, 0][edgeIndex]` */ export function vertexCIndex(edgeIndex: number) { return 2 - edgeIndex; } export function getEdgeMapSize(numIndices: number) { const numEdges = numIndices; // Choose quadratic probing hash table size to be the smallest power of 2 greater than `numEdges`. const edgeMapSize = 2 ** Math.ceil(Math.log2(numEdges)); return edgeMapSize * 4; } function computeTriangleAdjacencies( triangleAdjacencies: Uint32Array, indices: MeshVertexIndices, edgeMap: Uint32Array): Uint32Array { const numTriangles = indices.length / 3; // Row-major array of shape `[numTriangles, 3]` specifying the triangles adjacent to each // triangle. The triangle index `i` corresponds to elements `[i * 3, (i + 1) * 3)` of the // `indices` array. For each triangle, columns 0 to 2 are the indices of the triangles adjacent // to edge 0-1, edge 0-2, and edge 1-2, respectively. const edgeMapSize = edgeMap.length; const emptyEntry = 0xFFFFFFFF; triangleAdjacencies.fill(emptyEntry); edgeMap.fill(emptyEntry); // Insert edges for (let triangle = 0; triangle < numTriangles; ++triangle) { const baseIndex = triangle * 3; for (let edgeIndex = 0; edgeIndex < 3; ++edgeIndex) { const vertexA0 = indices[baseIndex + vertexAIndex(edgeIndex)]; const vertexB0 = indices[baseIndex + vertexBIndex(edgeIndex)]; const newEntry = (triangle << 2) | edgeIndex; const existingEntry = hashTableInsert( edgeMap, edgeMapSize, newEntry, emptyEntry, hashEdge(vertexA0, vertexB0), x => { const otherBaseIndex = getBaseIndex(x); const otherEdgeIndex = getEdgeIndex(x); const vertexA1 = indices[otherBaseIndex + vertexAIndex(otherEdgeIndex)]; const vertexB1 = indices[otherBaseIndex + vertexBIndex(otherEdgeIndex)]; // console.log('checking equality', vertexA0, vertexA1, vertexB0, vertexB1); return vertexA0 === vertexA1 && vertexB0 === vertexB1; }); if (existingEntry !== newEntry) { const otherBaseIndex = getBaseIndex(existingEntry); const otherEdgeIndex = getEdgeIndex(existingEntry); triangleAdjacencies[otherBaseIndex + otherEdgeIndex] = newEntry; triangleAdjacencies[baseIndex + edgeIndex] = existingEntry; } } } return triangleAdjacencies; } function emitTriangleStrips( indices: MeshVertexIndices, triangleAdjacencies: Uint32Array, output: MeshVertexIndices, outputIndex: number): number { const invalidVertex = ~0 >>> (32 - 8 * output.BYTES_PER_ELEMENT); const numIndices = indices.length; const numTriangles = numIndices / 3; const emptyEntry = 0xFFFFFFFF; // Extract strips startNewStrip: for (let triangle = 0; triangle < numTriangles; ++triangle) { let baseIndex = triangle * 3; if (indices[baseIndex] === invalidVertex) { // Triangle was already emitted. continue; } for (let edgeIndex = 0; edgeIndex < 3; ++edgeIndex) { let entry = triangleAdjacencies[baseIndex + edgeIndex]; if (entry === emptyEntry) continue; let otherBaseIndex = getBaseIndex(entry); if (indices[otherBaseIndex] === invalidVertex) continue; let otherEdgeIndex = getEdgeIndex(entry); output[outputIndex++] = indices[baseIndex + vertexCIndex(edgeIndex)]; output[outputIndex++] = indices[baseIndex + vertexAIndex(edgeIndex)]; output[outputIndex++] = indices[baseIndex + vertexBIndex(edgeIndex)]; let edgeIndexAndFlipped = otherEdgeIndex; while (true) { indices[baseIndex] = invalidVertex; baseIndex = otherBaseIndex; output[outputIndex++] = indices[baseIndex + vertexCIndex(edgeIndexAndFlipped & 3)]; edgeIndexAndFlipped = getNextEdge(edgeIndexAndFlipped); entry = triangleAdjacencies[baseIndex + (edgeIndexAndFlipped & 3)]; if (entry === emptyEntry || indices[(otherBaseIndex = getBaseIndex(entry))] === invalidVertex) { // console.log(stripLength); // End of strip. Emit restart index. output[outputIndex++] = invalidVertex; indices[baseIndex] = invalidVertex; continue startNewStrip; } edgeIndexAndFlipped = getEdgeIndex(entry) | (edgeIndexAndFlipped & 4); } } // Emit isolated triangle. output[outputIndex++] = indices[baseIndex]; output[outputIndex++] = indices[baseIndex + 1]; output[outputIndex++] = indices[baseIndex + 2]; indices[baseIndex] = invalidVertex; output[outputIndex++] = invalidVertex; } return outputIndex; } export function computeTriangleStrips<T extends MeshVertexIndices>( indices: T, subChunkOffsets?: Uint32Array): MeshVertexIndices { if (indices.length === 0) return indices; collisions = 0; if (subChunkOffsets === undefined) { subChunkOffsets = Uint32Array.of(0, indices.length); } let adjacenciesElapsed = 0; let emitElapsed = 0; let startTime = 0, midTime = 0, endTime = 0; const maxVertexIndex = normalizeTriangleVertexOrder(indices); const outputBufferSize = indices.length / 3 * 4; const output = maxVertexIndex >= 65535 ? new Uint32Array(outputBufferSize) : new Uint16Array(outputBufferSize); let outputIndex = 0; let maxSubChunkIndices = 0; const numSubChunks = subChunkOffsets.length - 1; for (let subChunk = 0; subChunk < numSubChunks; ++subChunk) { maxSubChunkIndices = Math.max(maxSubChunkIndices, subChunkOffsets[subChunk + 1] - subChunkOffsets[subChunk]); } const triangleAdjacencies = new Uint32Array(maxSubChunkIndices); const edgeMap = new Uint32Array(getEdgeMapSize(maxSubChunkIndices)); let subChunkOffset = subChunkOffsets[0]; for (let subChunk = 0; subChunk < numSubChunks; ++subChunk) { subChunkOffsets[subChunk] = outputIndex; const subChunkEnd = subChunkOffsets[subChunk + 1]; const subIndices = indices.subarray(subChunkOffset, subChunkEnd); if (DEBUG_TIMING) startTime = Date.now(); computeTriangleAdjacencies(triangleAdjacencies, subIndices, edgeMap); if (DEBUG_TIMING) midTime = Date.now(); outputIndex = emitTriangleStrips(subIndices, triangleAdjacencies, output, outputIndex); if (DEBUG_TIMING) { endTime = Date.now(); adjacenciesElapsed += (midTime - startTime); emitElapsed += (endTime - midTime); } subChunkOffset = subChunkEnd; } --outputIndex; subChunkOffsets[numSubChunks] = outputIndex; const shrunkOutput: T = new (output.constructor as any)(outputIndex); shrunkOutput.set(output.subarray(0, outputIndex)); if (DEBUG_TIMING) { console.log(`reduced from ${indices.byteLength}(${indices.BYTES_PER_ELEMENT}) -> ${ shrunkOutput.byteLength}(${shrunkOutput.BYTES_PER_ELEMENT}): adj=${ adjacenciesElapsed}, emit=${emitElapsed}, ${collisions}/${indices.length} collisions`); } return shrunkOutput; }
the_stack
import type { EnhancedStore } from '@reduxjs/toolkit' import { configureStore, createSlice } from '@reduxjs/toolkit' import type { PayloadAction } from '@reduxjs/toolkit' import type { ForkedTaskExecutor, TaskResult } from '../types' import { createActionListenerMiddleware, TaskAbortError } from '../index' function delay(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)) } // @see https://deno.land/std@0.95.0/async/deferred.ts (MIT) export interface Deferred<T> extends Promise<T> { resolve(value?: T | PromiseLike<T>): void reject(reason?: any): void } /** Creates a Promise with the `reject` and `resolve` functions * placed as methods on the promise object itself. It allows you to do: * * const p = deferred<number>(); * // ... * p.resolve(42); */ export function deferred<T>(): Deferred<T> { let methods const promise = new Promise<T>((resolve, reject): void => { methods = { resolve, reject } }) return Object.assign(promise, methods) as Deferred<T> } interface CounterSlice { value: number } describe('fork', () => { const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 } as CounterSlice, reducers: { increment(state) { state.value += 1 }, decrement(state) { state.value -= 1 }, // Use the PayloadAction type to declare the contents of `action.payload` incrementByAmount: (state, action: PayloadAction<number>) => { state.value += action.payload }, }, }) const { increment, decrement, incrementByAmount } = counterSlice.actions let middleware: ReturnType<typeof createActionListenerMiddleware> let store: EnhancedStore<CounterSlice> beforeEach(() => { middleware = createActionListenerMiddleware() store = configureStore({ reducer: counterSlice.reducer, middleware: (gDM) => gDM().prepend(middleware), }) }) it('runs executors in the next microtask', async () => { let hasRunSyncExector = false let hasRunAsyncExecutor = false middleware.addListener({ actionCreator: increment, listener: async (_, listenerApi) => { listenerApi.fork(() => { hasRunSyncExector = true }) listenerApi.fork(async () => { hasRunAsyncExecutor = true }) }, }) store.dispatch(increment()) expect(hasRunSyncExector).toBe(false) expect(hasRunAsyncExecutor).toBe(false) await Promise.resolve() expect(hasRunSyncExector).toBe(true) expect(hasRunAsyncExecutor).toBe(true) }) it('runs forked tasks that are cancelled if parent listener is cancelled', async () => { const deferredForkedTaskError = deferred() middleware.addListener({ actionCreator: increment, listener: async (_, listenerApi) => { listenerApi.cancelActiveListeners() const result = await listenerApi.fork(async () => { await delay(20) throw new Error('unreachable code') }).result if (result.status !== 'ok') { deferredForkedTaskError.resolve(result.error) } else { deferredForkedTaskError.reject(new Error('unreachable code')) } }, }) store.dispatch(increment()) store.dispatch(increment()) expect(await deferredForkedTaskError).toEqual(new TaskAbortError()) }) it('synchronously throws TypeError error if the provided executor is not a function', () => { const invalidExecutors = [null, {}, undefined, 1] middleware.addListener({ predicate: () => true, listener: async (_, listenerApi) => { invalidExecutors.forEach((invalidExecutor) => { let caughtError try { listenerApi.fork(invalidExecutor as any) } catch (err) { caughtError = err } expect(caughtError).toBeInstanceOf(TypeError) }) }, }) store.dispatch(increment()) expect.assertions(invalidExecutors.length) }) it('does not run an executor if the task is synchronously cancelled', async () => { const storeStateAfter = deferred() middleware.addListener({ actionCreator: increment, listener: async (action, listenerApi) => { const forkedTask = listenerApi.fork(() => { listenerApi.dispatch(decrement()) listenerApi.dispatch(decrement()) listenerApi.dispatch(decrement()) }) forkedTask.cancel() const result = await forkedTask.result storeStateAfter.resolve(listenerApi.getState()) }, }) store.dispatch(increment()) expect(storeStateAfter).resolves.toEqual({ value: 1 }) }) it.each<{ desc: string executor: ForkedTaskExecutor<any> cancelAfterMs?: number expected: TaskResult<any> }>([ { desc: 'sync exec - success', executor: () => 42, expected: { status: 'ok', value: 42 }, }, { desc: 'sync exec - error', executor: () => { throw new Error('2020') }, expected: { status: 'rejected', error: new Error('2020') }, }, { desc: 'sync exec - sync cancel', executor: () => 42, cancelAfterMs: -1, expected: { status: 'cancelled', error: new TaskAbortError() }, }, { desc: 'sync exec - async cancel', executor: () => 42, cancelAfterMs: 0, expected: { status: 'ok', value: 42 }, }, { desc: 'async exec - async cancel', executor: async (forkApi) => { await forkApi.delay(100) throw new Error('2020') }, cancelAfterMs: 10, expected: { status: 'cancelled', error: new TaskAbortError() }, }, { desc: 'async exec - success', executor: async () => { await delay(20) return Promise.resolve(21) }, expected: { status: 'ok', value: 21 }, }, { desc: 'async exec - error', executor: async () => { await Promise.resolve() throw new Error('2020') }, expected: { status: 'rejected', error: new Error('2020') }, }, { desc: 'async exec - success with forkApi.pause', executor: async (forkApi) => { return forkApi.pause(Promise.resolve(2)) }, expected: { status: 'ok', value: 2 }, }, { desc: 'async exec - error with forkApi.pause', executor: async (forkApi) => { return forkApi.pause(Promise.reject(22)) }, expected: { status: 'rejected', error: 22 }, }, { desc: 'async exec - success with forkApi.delay', executor: async (forkApi) => { await forkApi.delay(10) return 5 }, expected: { status: 'ok', value: 5 }, }, ])('%# - %j', async ({ executor, expected, cancelAfterMs }) => { let deferredResult = deferred() let forkedTask: any = {} middleware.addListener({ predicate: () => true, listener: async (_, listenerApi) => { forkedTask = listenerApi.fork(executor) deferredResult.resolve(await forkedTask.result) }, }) store.dispatch({ type: '' }) if (typeof cancelAfterMs === 'number') { if (cancelAfterMs < 0) { forkedTask.cancel() } else { await delay(cancelAfterMs) forkedTask.cancel() } } const result = await deferredResult expect(result).toEqual(expected) }) describe('forkAPI', () => { test('forkApi.delay rejects as soon as the task is cancelled', async () => { let deferredResult = deferred() middleware.addListener({ actionCreator: increment, listener: async (_, listenerApi) => { const forkedTask = listenerApi.fork(async (forkApi) => { await forkApi.delay(100) return 4 }) await listenerApi.delay(10) forkedTask.cancel() deferredResult.resolve(await forkedTask.result) }, }) store.dispatch(increment()) expect(await deferredResult).toEqual({ status: 'cancelled', error: new TaskAbortError(), }) }) test('fork.delay does not trigger unhandledRejections for completed or cancelled tasks', async () => { let deferredCompletedEvt = deferred() let deferredCancelledEvt = deferred() // Unfortunately we cannot test declaratively unhandleRejections in jest: https://github.com/facebook/jest/issues/5620 // This test just fails if an `unhandledRejection` occurs. middleware.addListener({ actionCreator: increment, listener: async (_, listenerApi) => { const completedTask = listenerApi.fork(async (forkApi) => { forkApi.signal.addEventListener( 'abort', deferredCompletedEvt.resolve, { once: true } ) forkApi.delay(100) // missing await return 4 }) deferredCompletedEvt.resolve(await completedTask.result) const godotPauseTrigger = deferred() const cancelledTask = listenerApi.fork(async (forkApi) => { forkApi.signal.addEventListener( 'abort', deferredCompletedEvt.resolve, { once: true } ) forkApi.delay(1_000) // missing await await forkApi.pause(godotPauseTrigger) return 4 }) await Promise.resolve() cancelledTask.cancel() deferredCancelledEvt.resolve(await cancelledTask.result) }, }) store.dispatch(increment()) expect(await deferredCompletedEvt).toBeDefined() expect(await deferredCancelledEvt).toBeDefined() }) }) test('forkApi.pause rejects if task is cancelled', async () => { let deferredResult = deferred() middleware.addListener({ actionCreator: increment, listener: async (_, listenerApi) => { const forkedTask = listenerApi.fork(async (forkApi) => { await forkApi.pause(delay(30)) return 4 }) await listenerApi.delay(10) forkedTask.cancel() deferredResult.resolve(await forkedTask.result) }, }) store.dispatch(increment()) expect(await deferredResult).toEqual({ status: 'cancelled', error: new TaskAbortError(), }) }) test('forkApi.pause rejects if listener is cancelled', async () => { let deferredResult = deferred() middleware.addListener({ actionCreator: increment, listener: async (_, listenerApi) => { listenerApi.cancelActiveListeners() const forkedTask = listenerApi.fork(async (forkApi) => { await forkApi.pause(delay(30)) return 4 }) deferredResult.resolve(await forkedTask.result) }, }) store.dispatch(increment()) store.dispatch(increment()) expect(await deferredResult).toEqual({ status: 'cancelled', error: new TaskAbortError(), }) }) })
the_stack